Skip to content

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

DEV: Purge the widget rendering system (#36109)

Sérgio Saquetimc2c1cd978eb3
diff --git a/app/assets/stylesheets/common/base/topic-post.scss b/app/assets/stylesheets/common/base/topic-post.scss
index ccad39b3b54..9a1ed786d43 100644
--- a/app/assets/stylesheets/common/base/topic-post.scss
+++ b/app/assets/stylesheets/common/base/topic-post.scss
@@ -527,7 +527,6 @@ nav.post-controls {
}
}
- .widget-button, // TODO (glimmer-post-stream): Remove this when glimmer-post-stream is enabled
.btn {
&:hover {
color: currentcolor;
@@ -983,7 +982,6 @@ aside.quote {
}
&.edits {
- .widget-button, // TODO (glimmer-post-stream): Remove this when glimmer-post-stream is enabled
.btn {
display: flex;
align-items: center;
diff --git a/app/serializers/current_user_serializer.rb b/app/serializers/current_user_serializer.rb
index 8834a35bf15..68e071eef37 100644
--- a/app/serializers/current_user_serializer.rb
+++ b/app/serializers/current_user_serializer.rb
@@ -77,7 +77,6 @@ class CurrentUserSerializer < BasicUserSerializer
:login_method,
:has_unseen_features,
:can_see_emails,
- :use_glimmer_post_stream_mode_auto_mode,
:can_localize_content?,
:effective_locale,
:use_reviewable_ui_refresh,
@@ -332,14 +331,6 @@ class CurrentUserSerializer < BasicUserSerializer
object.staff?
end
- def use_glimmer_post_stream_mode_auto_mode
- true
- end
-
- def include_use_glimmer_post_stream_mode_auto_mode?
- scope.user.in_any_groups?(SiteSetting.glimmer_post_stream_mode_auto_groups_map)
- end
-
def can_localize_content?
scope.can_localize_content?
end
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index db93a347fd8..31385448947 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -2745,9 +2745,6 @@ en:
default_navigation_menu_categories: "Selected categories will be displayed under Navigation Menu's Categories section by default."
default_navigation_menu_tags: "Selected tags will be displayed under Navigation Menu's Tags section by default."
experimental_new_new_view_groups: 'Enable a new topics list that combines unread and new topics and make the "Everything" link in the sidebar link to it.'
- glimmer_post_stream_mode: "Control whether the new 'glimmer' post stream implementation is used. 'auto' will enable automatically once all your themes and plugins are ready."
- glimmer_post_stream_mode_auto_groups: "Enable the new 'glimmer' post stream implementation in 'auto' mode for the specified user groups."
- deactivate_widgets_rendering: "Disable the legacy widgets rendering engine. This will disable all widgets that have not been updated to Glimmer components, it will also force the Glimmer Post Stream to be enabled unconditionally regardless of the value of the `glimmer_post_stream_mode` setting."
experimental_form_templates: "Enable the form templates feature. Manage the templates at <a href='%{base_path}/admin/customize/form-templates'>Customize / Templates</a>."
show_preview_for_form_templates: "Enable the preview for form templates feature"
lazy_load_categories_groups: "Lazy load category information only for users of these groups. This improves performance on sites with many categories."
diff --git a/config/site_settings.yml b/config/site_settings.yml
index 7f9650e8418..889d18eca5e 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -4254,27 +4254,6 @@ experimental:
allow_any: false
refresh: true
area: "group_permissions|navigation|experimental"
- glimmer_post_stream_mode_auto_groups:
- client: true
- type: group_list
- list_type: compact
- default: ""
- allow_any: false
- refresh: true
- area: "experimental"
- glimmer_post_stream_mode:
- client: true
- type: enum
- choices:
- - disabled
- - auto
- - enabled
- default: "enabled"
- area: "experimental"
- deactivate_widgets_rendering:
- client: true
- default: true
- area: "experimental"
enable_rich_text_paste:
client: true
default: true
diff --git a/db/migrate/20251119033712_remove_widget_poststream_settings.rb b/db/migrate/20251119033712_remove_widget_poststream_settings.rb
new file mode 100644
index 00000000000..7a40ca38b06
--- /dev/null
+++ b/db/migrate/20251119033712_remove_widget_poststream_settings.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+class RemoveWidgetPoststreamSettings < ActiveRecord::Migration[8.0]
+ def up
+ execute <<~SQL
+ DELETE FROM site_settings
+ WHERE name IN (
+ 'deactivate_widgets_rendering',
+ 'glimmer_post_stream_mode',
+ 'glimmer_post_stream_mode_auto_groups'
+ )
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/frontend/asset-processor/package.json b/frontend/asset-processor/package.json
index 7f3aaba0077..e72b0f2bdc1 100644
--- a/frontend/asset-processor/package.json
+++ b/frontend/asset-processor/package.json
@@ -24,7 +24,6 @@
"decorator-transforms": "^2.3.0",
"discourse": "workspace:0.0.0",
"discourse-plugins": "workspace:1.0.0",
- "discourse-widget-hbs": "workspace:1.0.0",
"ember-cli-htmlbars": "^6.3.0",
"ember-source": "~6.6.0",
"ember-this-fallback": "^0.4.0",
diff --git a/frontend/asset-processor/theme-rollup.js b/frontend/asset-processor/theme-rollup.js
index eed4f69748b..0baf08cec9a 100644
--- a/frontend/asset-processor/theme-rollup.js
+++ b/frontend/asset-processor/theme-rollup.js
@@ -7,7 +7,6 @@ import colocatedBabelPlugin from "ember-cli-htmlbars/lib/colocated-babel-plugin"
import EmberThisFallback from "ember-this-fallback";
import { memfs } from "memfs";
import transformActionSyntax from "discourse-plugins/transform-action-syntax";
-import { WidgetHbsCompiler } from "discourse-widget-hbs/lib/widget-hbs-compiler";
import { browsers } from "../discourse/config/targets";
import babelTransformModuleRenames from "../discourse/lib/babel-transform-module-renames";
import AddThemeGlobals from "./add-theme-globals";
@@ -61,7 +60,6 @@ globalThis.rollup = function (modules, opts) {
babelTransformModuleRenames,
AddThemeGlobals,
colocatedBabelPlugin,
- WidgetHbsCompiler,
[
HTMLBarsInlinePrecompile,
{
diff --git a/frontend/discourse-plugins/package.json b/frontend/discourse-plugins/package.json
index 01a7babb967..72d262bb7ea 100644
--- a/frontend/discourse-plugins/package.json
+++ b/frontend/discourse-plugins/package.json
@@ -10,7 +10,6 @@
"dependencies": {
"@babel/core": "^7.28.5",
"deprecation-silencer": "workspace:1.0.0",
- "discourse-widget-hbs": "workspace:1.0.0",
"ember-cli-babel": "^8.2.0",
"ember-cli-htmlbars": "^6.3.0",
"ember-template-imports": "^4.3.0",
diff --git a/frontend/discourse-widget-hbs/.npmrc b/frontend/discourse-widget-hbs/.npmrc
deleted file mode 100644
index c42da845b44..00000000000
--- a/frontend/discourse-widget-hbs/.npmrc
+++ /dev/null
@@ -1 +0,0 @@
-engine-strict = true
diff --git a/frontend/discourse-widget-hbs/addon/.gitkeep b/frontend/discourse-widget-hbs/addon/.gitkeep
deleted file mode 100644
index e69de29bb2d..00000000000
diff --git a/frontend/discourse-widget-hbs/addon/helpers.js b/frontend/discourse-widget-hbs/addon/helpers.js
deleted file mode 100644
index 7bfa8a98ff5..00000000000
--- a/frontend/discourse-widget-hbs/addon/helpers.js
+++ /dev/null
@@ -1,11 +0,0 @@
-import { dateNode } from "discourse/helpers/node";
-import { iconNode } from "discourse/lib/icon-library";
-import { avatarFor as avatar } from "discourse/widgets/post";
-import rawHtml from "discourse/widgets/raw-html";
-
-export default {
- avatar,
- dateNode,
- iconNode,
- rawHtml,
-};
diff --git a/frontend/discourse-widget-hbs/app/.gitkeep b/frontend/discourse-widget-hbs/app/.gitkeep
deleted file mode 100644
index e69de29bb2d..00000000000
diff --git a/frontend/discourse-widget-hbs/ember-cli-build.js b/frontend/discourse-widget-hbs/ember-cli-build.js
deleted file mode 100644
index d4c73d7e6ff..00000000000
--- a/frontend/discourse-widget-hbs/ember-cli-build.js
+++ /dev/null
@@ -1,13 +0,0 @@
-"use strict";
-
-const EmberAddon = require("ember-cli/lib/broccoli/ember-addon");
-
-module.exports = function (defaults) {
- const app = new EmberAddon(defaults, {
- autoImport: {
- publicAssetURL: "",
- },
- });
-
- return app.toTree();
-};
diff --git a/frontend/discourse-widget-hbs/index.js b/frontend/discourse-widget-hbs/index.js
deleted file mode 100644
index d76f936f732..00000000000
--- a/frontend/discourse-widget-hbs/index.js
+++ /dev/null
@@ -1,30 +0,0 @@
-"use strict";
-
-const widgetHbsCompilerPath = require.resolve("./lib/widget-hbs-compiler");
-
-module.exports = {
- name: require("./package").name,
-
- included() {
- this._super.included.apply(this, arguments);
- let addonOptions = this._getAddonOptions();
- addonOptions.babel = addonOptions.babel || {};
- addonOptions.babel.plugins = addonOptions.babel.plugins || [];
- let babelPlugins = addonOptions.babel.plugins;
-
- babelPlugins.push({
- _parallelBabel: {
- requireFile: widgetHbsCompilerPath,
- useMethod: "WidgetHbsCompiler",
- },
- });
- },
-
- _getAddonOptions() {
- return (
- (this.parent && this.parent.options) ||
- (this.app && this.app.options) ||
- {}
- );
- },
-};
diff --git a/frontend/discourse-widget-hbs/lib/widget-hbs-compiler.js b/frontend/discourse-widget-hbs/lib/widget-hbs-compiler.js
deleted file mode 100644
index 641220f9765..00000000000
--- a/frontend/discourse-widget-hbs/lib/widget-hbs-compiler.js
+++ /dev/null
@@ -1,373 +0,0 @@
-function resolve(path) {
- if (path.startsWith("settings") || path.startsWith("transformed")) {
- return `this.${path}`;
- }
- return path;
-}
-
-function sexpValue(value) {
- if (!value) {
- return;
- }
-
- if (value.type === "PathExpression") {
- return resolve(value.original);
- } else if (value.type === "StringLiteral") {
- return JSON.stringify(value.value);
- } else if (value.type === "SubExpression") {
- return sexp(value);
- } else {
- return resolve(value.value);
- }
-}
-
-function pairsToObj(pairs) {
- let result = [];
-
- pairs.forEach((p) => {
- result.push(`"${p.key}": ${sexpValue(p.value)}`);
- });
-
- return `{ ${result.join(", ")} }`;
-}
-
-function i18n(node) {
- let key = sexpValue(node.params[0]);
-
- let hash = node.hash;
- if (hash.pairs.length) {
- return `I18n.t(${key}, ${pairsToObj(hash.pairs)})`;
- }
-
- return `I18n.t(${key})`;
-}
-
-function sexp(value) {
- if (value.path.original === "hash") {
- return pairsToObj(value.hash.pairs);
- }
-
- if (value.path.original === "concat") {
- let result = [];
- value.params.forEach((p) => {
- result.push(sexpValue(p));
- });
- return result.join(" + ");
- }
-
- if (value.path.original === "i18n") {
- return i18n(value);
- }
-}
-
-function valueOf(value) {
- if (value.type === "SubExpression") {
- return sexp(value);
- } else if (value.type === "PathExpression") {
- return value.original;
- } else if (value.type === "StringLiteral") {
- return JSON.stringify(value.value);
- }
-}
-
-function argValue(arg) {
- return valueOf(arg.value);
-}
-
-function useHelper(state, name) {
- let id = state.helpersUsed[name];
- if (!id) {
- id = ++state.helperNumber;
- state.helpersUsed[name] = id;
- }
- return `__h${id}`;
-}
-
-function mustacheValue(node, state) {
- let path = node.path.original;
-
- switch (path) {
- case "attach":
- let widgetName = argValue(
- node.hash.pairs.find((p) => p.key === "widget")
- );
-
- const attrs = node.hash.pairs.find((p) => p.key === "attrs");
- const opts = node.hash.pairs.find((p) => p.key === "opts");
- const otherOpts = node.hash.pairs.find((p) => p.key === "otherOpts");
-
- return `this.attach(${widgetName}, ${attrs ? argValue(attrs) : attrs}, ${
- opts ? argValue(opts) : opts
- }, ${otherOpts ? argValue(otherOpts) : otherOpts})`;
-
- case "yield":
- return `this.attrs.contents()`;
- case "i18n":
- return i18n(node);
- case "avatar":
- let template = argValue(
- node.hash.pairs.find((p) => p.key === "template")
- );
- let username = argValue(
- node.hash.pairs.find((p) => p.key === "username")
- );
- let size = argValue(node.hash.pairs.find((p) => p.key === "size"));
- return `${useHelper(
- state,
- "avatar"
- )}(${size}, { template: ${template}, username: ${username} })`;
- case "date":
- return `${useHelper(state, "dateNode")}(${valueOf(node.params[0])})`;
- case "d-icon":
- return `${useHelper(state, "iconNode")}(${valueOf(node.params[0])})`;
- default:
- // Shortcut: If our mustache has hash arguments, we can assume it's attaching.
- // For example `{{home-logo count=123}}` can become `this.attach('home-logo, { "count": 123 });`
- let hash = node.hash;
- if (hash.pairs.length) {
- let widgetString = JSON.stringify(path);
- // magic: support applying of attrs. This is commonly done like `{{home-logo attrs=attrs}}`
- let firstPair = hash.pairs[0];
- if (firstPair.key === "attrs") {
- return `this.attach(${widgetString}, ${firstPair.value.original})`;
- }
-
- return `this.attach(${widgetString}, ${pairsToObj(hash.pairs)})`;
- }
-
- if (node.trusting) {
- return `new ${useHelper(state, "rawHtml")}({ html: '<span>' + ${resolve(
- path
- )} + '</span>'})`;
- } else {
- return `${resolve(path)}`;
- }
- }
-}
-
-class Compiler {
- constructor(ast) {
- this.idx = 0;
- this.ast = ast;
-
- this.state = {
- helpersUsed: {},
- helperNumber: 0,
- };
- }
-
- newAcc() {
- return `_a${this.idx++}`;
- }
-
- processNode(parentAcc, node) {
- let instructions = [];
- let innerAcc;
-
- switch (node.type) {
- case "Program":
- case "Template":
- node.body.forEach((bodyNode) => {
- instructions = instructions.concat(
- this.processNode(parentAcc, bodyNode)
- );
- });
- break;
- case "ElementNode":
- innerAcc = this.newAcc();
- instructions.push(`var ${innerAcc} = [];`);
- node.children.forEach((child) => {
- instructions = instructions.concat(this.processNode(innerAcc, child));
- });
-
- if (node.attributes.length) {
- let attributes = [];
- let properties = [];
-
- node.attributes.forEach((a) => {
- const name = a.name;
- const value =
- a.value.type === "MustacheStatement"
- ? mustacheValue(a.value, this.state)
- : `"${a.value.chars}"`;
-
- if (a.name === "class") {
- properties.push(`"className":${value}`);
- } else {
- attributes.push(`"${name}":${value}`);
- }
- });
-
- properties.push(`"attributes":{${attributes.join(", ")}}`);
- const propertiesString = `{${properties.join(", ")}}`;
-
- instructions.push(
- `${parentAcc}.push(virtualDom.h('${node.tag}', ${propertiesString}, ${innerAcc}));`
- );
- } else {
- instructions.push(
- `${parentAcc}.push(virtualDom.h('${node.tag}', ${innerAcc}));`
- );
- }
-
- break;
-
- case "TextNode":
- return `${parentAcc}.push(${JSON.stringify(node.chars)});`;
-
- case "MustacheStatement":
- const value = mustacheValue(node, this.state);
- if (value) {
- instructions.push(`${parentAcc}.push(${value});`);
- }
- break;
- case "BlockStatement":
- let negate = "";
-
- switch (node.path.original) {
- case "unless":
- negate = "!";
- // eslint-disable-next-line no-fallthrough
- case "if":
- instructions.push(
- `if (${negate}${resolve(node.params[0].original)}) {`
- );
- node.program.body.forEach((child) => {
- instructions = instructions.concat(
- this.processNode(parentAcc, child)
- );
- });
-
- if (node.inverse) {
- instructions.push(`} else {`);
- node.inverse.body.forEach((child) => {
- instructions = instructions.concat(
- this.processNode(parentAcc, child)
- );
- });
- }
- instructions.push(`}`);
- break;
- case "each":
- const collection = resolve(node.params[0].original);
- instructions.push(`if (${collection} && ${collection}.length) {`);
- instructions.push(
- ` ${collection}.forEach(${node.program.blockParams[0]} => {`
- );
- node.program.body.forEach((child) => {
- instructions = instructions.concat(
- this.processNode(parentAcc, child)
- );
- });
- instructions.push(` });`);
- instructions.push("}");
-
- break;
- }
- break;
- default:
- break;
- }
-
- return instructions.join("\n");
- }
-
- compile() {
- return this.processNode("_r", this.ast);
- }
-}
-
-const defaultGlimmer = require("@glimmer/syntax");
-
-function compile(template, glimmer) {
- if (!glimmer) {
- glimmer = defaultGlimmer;
- }
- const compiled = glimmer.preprocess(template);
- const compiler = new Compiler(compiled);
-
- let code = compiler.compile();
-
- let imports = "";
-
- Object.keys(compiler.state.helpersUsed).forEach((h) => {
- let id = compiler.state.helpersUsed[h];
- imports += `var __h${id} = __widget_helpers.${h}; `;
- });
-
- return `function(attrs, state) { ${imports}var _r = [];\n${code}\nreturn _r; }`;
-}
-
-exports.compile = compile;
-
-function error(path, state, msg) {
- const filename = state.file.opts.filename;
- return path.replaceWithSourceString(
- `function() { console.error("${filename}: ${msg}"); }`
- );
-}
-
-const WidgetHbsCompiler = function (babel) {
- let t = babel.types;
- return {
- visitor: {
- ImportDeclaration(path, state) {
- let node = path.node;
- if (
- t.isLiteral(node.source, { value: "discourse/widgets/hbs-compiler" })
- ) {
- let first = node.specifiers && node.specifiers[0];
- if (!t.isImportDefaultSpecifier(first)) {
- let input = state.file.code;
- let usedImportStatement = input.slice(node.start, node.end);
- let msg = `Only \`import hbs from 'discourse/widgets/hbs-compiler'\` is supported. You used: \`${usedImportStatement}\``;
- throw path.buildCodeFrameError(msg);
- }
-
- state.importId =
- state.importId ||
- path.scope.generateUidIdentifierBasedOnNode(path.node.id);
- path.scope.rename(first.local.name, state.importId.name);
- path.remove();
- }
- },
-
- TaggedTemplateExpression(path, state) {
- if (!state.importId) {
- return;
- }
-
- let tagPath = path.get("tag");
- if (tagPath.node.name !== state.importId.name) {
- return;
- }
-
- if (path.node.quasi.expressions.length) {
- return error(
- path,
- state,
- "placeholders inside a tagged template string are not supported"
- );
- }
-
- let template = path.node.quasi.quasis
- .map((quasi) => quasi.value.cooked)
- .join("");
-
- try {
- path.replaceWithSourceString(
- compile(template, WidgetHbsCompiler.glimmer)
- );
- } catch (e) {
- // eslint-disable-next-line no-console
- console.error("widget hbs error", e.toString());
- return error(path, state, e.toString());
- }
- },
- },
- };
-};
-
-WidgetHbsCompiler.cacheKey = () => "discourse-widget-hbs";
-
-exports.WidgetHbsCompiler = WidgetHbsCompiler;
diff --git a/frontend/discourse-widget-hbs/package.json b/frontend/discourse-widget-hbs/package.json
deleted file mode 100644
index 5c8b25aae10..00000000000
--- a/frontend/discourse-widget-hbs/package.json
+++ /dev/null
@@ -1,49 +0,0 @@
-{
- "name": "discourse-widget-hbs",
- "version": "1.0.0",
- "description": "Support for Discourse's inline `hbs` compiler for widgets",
- "author": "Discourse",
- "license": "GPL-2.0-only",
- "keywords": [
- "ember-addon"
- ],
- "scripts": {
- "build": "ember build",
- "lint:hbs": "ember-template-lint .",
- "lint:js": "eslint .",
- "start": "ember serve"
- },
- "dependencies": {
- "@babel/core": "^7.28.5",
- "ember-auto-import": "^2.12.0",
- "ember-cli-babel": "^8.2.0",
- "ember-cli-htmlbars": "^6.3.0"
- },
- "devDependencies": {
- "@ember/optional-features": "^2.2.0",
- "@embroider/test-setup": "^4.0.0",
- "@glimmer/component": "^2.0.0",
- "@glimmer/syntax": "0.93.1",
- "broccoli-asset-rev": "^3.0.0",
- "ember-cli": "~6.8.0",
- "ember-cli-inject-live-reload": "^2.1.0",
- "ember-cli-sri": "^2.1.1",
- "ember-cli-terser": "^4.0.2",
- "ember-disable-prototype-extensions": "^1.1.3",
- "ember-load-initializers": "^3.0.1",
- "ember-resolver": "^13.1.1",
- "ember-source": "~6.6.0",
- "ember-source-channel-url": "^3.0.0",
- "loader.js": "^4.7.0",
- "webpack": "5.99.9"
- },
- "engines": {
- "node": ">= 18",
- "npm": "please-use-pnpm",
- "yarn": "please-use-pnpm",
- "pnpm": "^9"
- },
- "ember": {
- "edition": "default"
- }
-}
diff --git a/frontend/discourse/app/components/composer-editor.gjs b/frontend/discourse/app/components/composer-editor.gjs
index 9997d7731c8..e1bea4bd5a3 100644
--- a/frontend/discourse/app/components/composer-editor.gjs
+++ b/frontend/discourse/app/components/composer-editor.gjs
@@ -15,6 +15,7 @@ import $ from "jquery";
import { resolveAllShortUrls } from "pretty-text/upload-short-url";
import DEditor from "discourse/components/d-editor";
import DEditorPreview from "discourse/components/d-editor-preview";
+import { applyHtmlDecorators } from "discourse/components/decorated-html";
import Wrapper from "discourse/components/form-template-field/wrapper";
import PickFilesButton from "discourse/components/pick-files-button";
import PostTranslationEditor from "discourse/components/post-translation-editor";
@@ -609,11 +610,7 @@ export default class ComposerEditor extends Component {
}
_decorateCookedElement(preview, helper) {
- this.appEvents.trigger(
- "decorate-non-stream-cooked-element",
- preview,
- helper
- );
+ applyHtmlDecorators(preview, helper);
}
@debounce(DEBOUNCE_JIT_MS)
diff --git a/frontend/discourse/app/components/decorated-html.gjs b/frontend/discourse/app/components/decorated-html.gjs
index 09991c66b20..78b0b725cc1 100644
--- a/frontend/discourse/app/components/decorated-html.gjs
+++ b/frontend/discourse/app/components/decorated-html.gjs
@@ -9,10 +9,89 @@ import {
isRailsTesting,
isTesting,
} from "discourse/lib/environment";
-import { POST_STREAM_DEPRECATION_OPTIONS } from "discourse/widgets/widget";
+import { WIDGET_DECOMMISSION_OPTIONS } from "discourse/widgets/widget";
const detachedDocument = document.implementation.createHTMLDocument("detached");
+/** @type {Symbol} Default decorator type used when no specific type is provided */
+export const NON_STREAM_HTML_DECORATOR = Symbol("non-stream");
+
+/** @type {Object.<Symbol|string, Function[]>} Storage for HTML decorators organized by type */
+let htmlDecorators = {};
+
+/**
+ * Gets or initializes an array of HTML decorators for a specific type
+ *
+ * @param {Symbol|string} [type] - The decorator type to get decorators for. If not provided,
+ * defaults to NON_STREAM_HTML_DECORATOR
+ * @returns {Function[]} An array of decorator functions for the specified type
+ * @example
+ * const decorators = getHtmlDecoratorsForType(myDecoratorType);
+ * // Returns existing decorators array or initializes a new one
+ */
+function getHtmlDecoratorsForType(type) {
+ return (htmlDecorators[type ?? NON_STREAM_HTML_DECORATOR] ||= []);
+}
+
+/**
+ * Registers a new HTML decorator function for a specific type of decoration.
+ *
+ * @param {Function} decorator - The decorator function to register. It receives two parameters:
+ * 1. element: HTMLElement to be decorated
+ * 2. options: Object containing decoration options
+ * The decorator can optionally return a cleanup function.
+ * @param {Symbol|string} [type=NON_STREAM_HTML_DECORATOR] - The type of decorator to register.
+ * When not provided, defaults to NON_STREAM_HTML_DECORATOR (non-stream).
+ * @returns {void}
+ * @example
+ * registerHtmlDecorator((element, options) => {
+ * element.classList.add('decorated');
+ * return () => element.classList.remove('decorated'); // Cleanup function
+ * });
+ */
+export function registerHtmlDecorator(decorator, type) {
+ getHtmlDecoratorsForType(type).push(decorator);
+}
+
+/**
+ * Applies registered HTML decorators to a DOM element and returns their cleanup functions.
+ *
+ * @param {HTMLElement} element - The DOM element to apply decorators to
+ * @param {Object} options - Options object passed to each decorator function
+ * @param {Symbol|string} [type=NON_STREAM_HTML_DECORATOR] - The type of decorators to apply.
+ * When not provided, defaults to NON_STREAM_HTML_DECORATOR (non-stream).
+ * @returns {Function[]} Array of cleanup functions from decorators that returned them.
+ * Each function, when called, will undo the decorator's effects.
+ * @example
+ * const cleanupFunctions = applyHtmlDecorators(
+ * document.querySelector('.content'),
+ * { highlight: true }
+ * );
+ *
+ * // To clean up all decorations:
+ * cleanupFunctions.forEach(cleanup => cleanup());
+ */
+export function applyHtmlDecorators(element, options, type) {
+ return getHtmlDecoratorsForType(type)
+ .map((decorator) => {
+ return decorator(element, options);
+ })
+ .filter((fn) => typeof fn === "function");
+}
+
+/**
+ * Clears all registered HTML decorators
+ *
+ * USE ONLY FOR TESTING PURPOSES
+ *
+ * @returns {void}
+ */
+export function resetHtmlDecorators() {
+ if (isTesting()) {
+ htmlDecorators = {};
+ }
+}
+
/**
* Reactively renders cooked HTML with decorations applied.
*/
@@ -128,11 +207,21 @@ class DecorateHtmlHelper {
this.#context = context;
}
+ /**
+ * Renders a Glimmer component into a specified target HTML element with provided data.
+ * Handles deprecation warnings if invalid parameters are passed.
+ *
+ * @param {Element} targetElement The HTML element where the Glimmer component should be rendered. Must be a valid DOM element.
+ * @param {Object} component The Glimmer component object to render. Should not have a name of "factory" to avoid deprecation warnings.
+ * @param {Object} data The data to be passed to the Glimmer component for rendering.
+ * @param {Object} [opts={}] Additional options for rendering. Supports an `append` boolean property that defaults to `true` to determine if the content should be appended to the target element.
+ * @return {void}
+ */
renderGlimmer(targetElement, component, data, opts = {}) {
if (!(targetElement instanceof Element)) {
deprecated(
"Invalid `targetElement` passed to `helper.renderGlimmer` while using `api.decorateCookedElement` with the Glimmer Post Stream. `targetElement` must be a valid HTML element. This call has been ignored to prevent errors.",
- POST_STREAM_DEPRECATION_OPTIONS
+ WIDGET_DECOMMISSION_OPTIONS
);
return;
@@ -141,7 +230,7 @@ class DecorateHtmlHelper {
if (component.name === "factory") {
deprecated(
"Invalid `component` passed to `helper.renderGlimmer` while using `api.decorateCookedElement` with the Glimmer Post Stream. `component` must be a valid Glimmer component. If using a template compiled via ember-cli-htmlbars, replace it with the `<template>...</template>` syntax. This call has been ignored to prevent errors.",
- POST_STREAM_DEPRECATION_OPTIONS
+ WIDGET_DECOMMISSION_OPTIONS
);
return;
@@ -168,24 +257,11 @@ class DecorateHtmlHelper {
return this.model;
}
- // TODO (glimmer-post-stream): remove this when we remove the legacy post stream code
get widget() {
deprecated(
- "Accessing `helper.widget` is not supported when using `api.decorateCookedElement` with the Glimmer Post Stream and can yield unexpected results.",
- POST_STREAM_DEPRECATION_OPTIONS
+ "Using `helper.widget` has been decommissioned. See https://meta.discourse.org/t/372063/1",
+ WIDGET_DECOMMISSION_OPTIONS
);
-
- const attrs = this.model;
-
- return {
- get attrs() {
- return attrs;
- },
- scheduleRerender() {
- // This is a no-op when using the new glimmer components.
- // The component will rerender automatically when the model changes.
- },
- };
}
teardown() {
diff --git a/frontend/discourse/app/components/discourse-banner.gjs b/frontend/discourse/app/components/discourse-banner.gjs
index 1fea3f3100e..ade9b13124e 100644
--- a/frontend/discourse/app/components/discourse-banner.gjs
+++ b/frontend/discourse/app/components/discourse-banner.gjs
@@ -7,10 +7,9 @@ import DButton from "discourse/components/d-button";
import icon from "discourse/helpers/d-icon";
import { bind } from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
-import DecoratedHtml from "./decorated-html";
+import DecoratedHtml, { applyHtmlDecorators } from "./decorated-html";
export default class DiscourseBanner extends Component {
- @service appEvents;
@service currentUser;
@service keyValueStore;
@service site;
@@ -50,11 +49,7 @@ export default class DiscourseBanner extends Component {
@bind
decorateContent(element, helper) {
- this.appEvents.trigger(
- "decorate-non-stream-cooked-element",
- element,
- helper
- );
+ applyHtmlDecorators(element, helper);
}
@action
diff --git a/frontend/discourse/app/components/invite-panel.gjs b/frontend/discourse/app/components/invite-panel.gjs
index f36d930996d..4b15e37d32c 100644
--- a/frontend/discourse/app/components/invite-panel.gjs
+++ b/frontend/discourse/app/components/invite-panel.gjs
@@ -349,9 +349,6 @@ export default class InvitePanel extends Component {
.then(() => {
model.setProperties({ saving: false, finished: true });
this.inviteModel.reload().then(() => {
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh");
-
this.toasts.success({
data: { message: this.successMessage(this.invitee) },
});
@@ -368,9 +365,6 @@ export default class InvitePanel extends Component {
this.get("inviteModel.details.allowed_users").pushObject(
EmberObject.create(result.user)
);
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { force: true });
-
this.toasts.success({
data: { message: this.successMessage(result) },
});
diff --git a/frontend/discourse/app/components/modal/history.gjs b/frontend/discourse/app/components/modal/history.gjs
index 5b2ad5d8cbf..3707fc2a47a 100644
--- a/frontend/discourse/app/components/modal/history.gjs
+++ b/frontend/discourse/app/components/modal/history.gjs
@@ -31,7 +31,6 @@ export default class History extends Component {
@service site;
@service currentUser;
@service siteSettings;
- @service appEvents;
@tracked loading;
@tracked postRevision;
@@ -193,10 +192,7 @@ export default class History extends Component {
return;
}
- postStream.triggerChangedPost(postId, this.args.model).then(() =>
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { id: postId })
- );
+ postStream.triggerChangedPost(postId, this.args.model);
} finally {
this.loading = false;
this.initialLoad = false;
diff --git a/frontend/discourse/app/components/modal/json-schema-editor.gjs b/frontend/discourse/app/components/modal/json-schema-editor.gjs
index 86599a73c0b..5344108d4c8 100644
--- a/frontend/discourse/app/components/modal/json-schema-editor.gjs
+++ b/frontend/discourse/app/components/modal/json-schema-editor.gjs
@@ -4,10 +4,9 @@ import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";
import { waitForPromise } from "@ember/test-waiters";
-import { create } from "virtual-dom";
import DButton from "discourse/components/d-button";
import DModal from "discourse/components/d-modal";
-import { iconNode } from "discourse/lib/icon-library";
+import { iconElement } from "discourse/lib/icon-library";
import { i18n } from "discourse-i18n";
export default class JsonSchemaEditorModal extends Component {
@@ -116,6 +115,6 @@ class DiscourseJsonSchemaEditorIconlib {
if (!this.mapping[key]) {
return;
}
- return create(iconNode(this.mapping[key]));
+ return iconElement(this.mapping[key]);
}
}
diff --git a/frontend/discourse/app/components/mount-widget.gjs b/frontend/discourse/app/components/mount-widget.gjs
index 8928ee1c6a3..8521dbbf70b 100644
--- a/frontend/discourse/app/components/mount-widget.gjs
+++ b/frontend/discourse/app/components/mount-widget.gjs
@@ -1,282 +1,27 @@
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
/* eslint-disable ember/no-classic-components */
-import ArrayProxy from "@ember/array/proxy";
import Component from "@ember/component";
-import { cancel, scheduleOnce } from "@ember/runloop";
-import { service } from "@ember/service";
-import { camelize } from "@ember/string";
-import { diff, patch } from "virtual-dom";
-import DirtyKeys from "discourse/lib/dirty-keys";
-import { getRegister } from "discourse/lib/get-owner";
-import { WidgetClickHook } from "discourse/widgets/hooks";
-import {
- queryRegistry,
- traverseCustomWidgets,
- warnWidgetsDeprecation,
-} from "discourse/widgets/widget";
-
-let _cleanCallbacks = {};
-
-export function addWidgetCleanCallback(widgetName, fn) {
- _cleanCallbacks[widgetName] = _cleanCallbacks[widgetName] || [];
- _cleanCallbacks[widgetName].push(fn);
-}
-
-export function removeWidgetCleanCallback(widgetName, fn) {
- const callbacks = _cleanCallbacks[widgetName];
- if (!callbacks) {
- return;
- }
-
- const index = callbacks.indexOf(fn);
- if (index === -1) {
- return;
- }
+import { warnWidgetsDecommissioned } from "discourse/widgets/widget";
- callbacks.splice(index, 1);
-}
-
-export function resetWidgetCleanCallbacks() {
- _cleanCallbacks = {};
-}
+export {
+ warnWidgetsDecommissioned as addWidgetCleanCallback,
+ warnWidgetsDecommissioned as removeWidgetCleanCallback,
+ warnWidgetsDecommissioned as resetWidgetCleanCallbacks,
+} from "discourse/widgets/widget";
export default class MountWidget extends Component {
- @service siteSettings;
-
- dirtyKeys = null;
- _tree = null;
- _rootNode = null;
- _timeout = null;
- _widgetClass = null;
- _renderCallback = null;
- _childEvents = null;
- _dispatched = null;
-
init() {
super.init(...arguments);
- const name = this.widget;
-
- if (this.isDeactivated) {
- warnWidgetsDeprecation(
- `Widgets are deactivated and won't be rendered. Your site may not work properly. Affected widget: ${name}.`,
- true
- );
- return;
- } else {
- warnWidgetsDeprecation(
- `The \`MountWidget\` component is deprecated and will soon stop working. Use Glimmer components instead. Affected widget: ${name}.`
- );
- }
-
- if (name === "post-cooked") {
- throw [
- "Cannot use <MountWidget /> with `post-cooked`.",
- "It's a special-case that needs to be wrapped in another widget.",
- "For example:",
- " createWidget('test-widget', {",
- " html(attrs) {",
- " return [",
- " new PostCooked(attrs, new DecoratorHelper(this), this.currentUser),",
- " ];",
- " },",
- " });",
- ].join("\n");
- }
-
- this.register = getRegister(this);
-
- this._widgetClass =
- queryRegistry(name) || this.register.lookupFactory(`widget:${name}`);
-
- if (this._widgetClass?.class) {
- this._widgetClass = this._widgetClass.class;
- }
-
- if (!this._widgetClass) {
- // eslint-disable-next-line no-console
- console.error(`Error: Could not find widget: ${name}`);
- }
-
- this._childEvents = [];
- this._connected = [];
- this._childComponents = ArrayProxy.create({ content: [] });
- this._dispatched = [];
- this.dirtyKeys = new DirtyKeys(name);
- }
-
- get isDeactivated() {
- return this.siteSettings.deactivate_widgets_rendering;
- }
-
- didInsertElement() {
- super.didInsertElement(...arguments);
- if (this.isDeactivated) {
- return;
- }
-
- WidgetClickHook.setupDocumentCallback();
-
- this._rootNode = document.createElement("div");
- this.element.appendChild(this._rootNode);
- this._timeout = scheduleOnce("render", this, this.rerenderWidget);
- }
-
- willClearRender() {
- if (this.isDeactivated) {
- return;
- }
-
- super.willClearRender(...arguments);
- const callbacks = _cleanCallbacks[this.widget];
- if (callbacks) {
- callbacks.forEach((cb) => cb(this._tree));
- }
-
- this._connected.forEach((v) => v.destroy());
- this._connected.length = 0;
-
- traverseCustomWidgets(this._tree, (w) => w.destroy());
- this._rootNode = patch(this._rootNode, diff(this._tree, null));
- this._tree = null;
- }
-
- willDestroyElement() {
- super.willDestroyElement(...arguments);
- if (this.isDeactivated) {
- return;
- }
-
- this._dispatched.forEach((evt) => {
- const [eventName, caller] = evt;
- this.appEvents.off(eventName, this, caller);
- });
- cancel(this._timeout);
- }
-
- afterRender() {}
- beforePatch() {}
- afterPatch() {}
-
- eventDispatched(eventName, key, refreshArg) {
- if (this.isDeactivated) {
- return;
- }
-
- key = typeof key === "function" ? key(refreshArg) : key;
- const onRefresh = camelize(eventName.replace(/:/, "-"));
- this.dirtyKeys.keyDirty(key, { onRefresh, refreshArg });
- this.queueRerender();
- }
-
- dispatch(eventName, key) {
- if (this.isDeactivated) {
- return;
- }
-
- this._childEvents.push(eventName);
-
- const caller = (refreshArg) =>
- this.eventDispatched(eventName, key, refreshArg);
- this._dispatched.push([eventName, caller]);
- this.appEvents.on(eventName, this, caller);
- }
-
- queueRerender(callback) {
- if (this.isDeactivated) {
- return;
- }
-
- if (callback && !this._renderCallback) {
- this._renderCallback = callback;
- }
-
- scheduleOnce("render", this, this.rerenderWidget);
- }
-
- buildArgs() {}
-
- rerenderWidget() {
- if (this.isDeactivated) {
- return;
- }
-
- cancel(this._timeout);
-
- if (this._rootNode) {
- if (!this._widgetClass) {
- return;
- }
-
- const t0 = Date.now();
- const args = this.args || this.buildArgs();
- const opts = {
- model: this.model,
- dirtyKeys: this.dirtyKeys,
- };
- const newTree = new this._widgetClass(args, this.register, opts);
-
- newTree._rerenderable = this;
- newTree._emberView = this;
- const patches = diff(this._tree || this._rootNode, newTree);
-
- traverseCustomWidgets(this._tree, (w) => w.willRerenderWidget());
-
- this.beforePatch();
- this._rootNode = patch(this._rootNode, patches);
- this.afterPatch();
-
- this._tree = newTree;
-
- traverseCustomWidgets(newTree, (w) => w.didRenderWidget());
-
- if (this._renderCallback) {
- this._renderCallback();
- this._renderCallback = null;
- }
- this.afterRender();
- this.dirtyKeys.renderedKey("*");
-
- if (this.profileWidget) {
- // eslint-disable-next-line no-console
- console.log(Date.now() - t0);
- }
- }
- }
-
- mountChildComponent(info) {
- if (this.isDeactivated) {
- return;
- }
-
- this._childComponents.pushObject(info);
- }
-
- unmountChildComponent(info) {
- if (this.isDeactivated) {
- return;
- }
-
- this._childComponents.removeObject(info);
- }
-
- didUpdateAttrs() {
- super.didUpdateAttrs(...arguments);
- if (this.isDeactivated) {
- return;
- }
-
- this.queueRerender();
+ warnWidgetsDecommissioned();
}
<template>
- {{#unless this.isDeactivated}}
- {{#each this._childComponents as |info|}}
- {{#in-element info.element insertBefore=null}}
- <info.component
- @data={{info.data}}
- @setWrapperElementAttrs={{info.setWrapperElementAttrs}}
- />
- {{/in-element}}
- {{/each}}
- {{/unless}}
+ {{! No-op. The widget rendering system was decommissioned }}
</template>
}
diff --git a/frontend/discourse/app/components/post-action-description.gjs b/frontend/discourse/app/components/post-action-description.gjs
index 94eabbe6479..8bde6c60444 100644
--- a/frontend/discourse/app/components/post-action-description.gjs
+++ b/frontend/discourse/app/components/post-action-description.gjs
@@ -1,5 +1,33 @@
import Component from "@glimmer/component";
-import { actionDescriptionHtml } from "discourse/widgets/post-small-action";
+import { htmlSafe } from "@ember/template";
+import {
+ customGroupActionCodes,
+ GROUP_ACTION_CODES,
+} from "discourse/components/post/small-action";
+import { autoUpdatingRelativeAge } from "discourse/lib/formatter";
+import { userPath } from "discourse/lib/url";
+import { i18n } from "discourse-i18n";
+
+export function actionDescriptionHtml(actionCode, createdAt, username, path) {
+ const when = createdAt
+ ? autoUpdatingRelativeAge(new Date(createdAt), {
+ format: "medium-with-ago-and-on",
+ })
+ : "";
+
+ let who = "";
+ if (username) {
+ if (
+ GROUP_ACTION_CODES.includes(actionCode) ||
+ customGroupActionCodes.includes(actionCode)
+ ) {
+ who = `<a class="mention-group" href="/g/${username}">@${username}</a>`;
+ } else {
+ who = `<a class="mention" href="${userPath(username)}">@${username}</a>`;
+ }
+ }
+ return htmlSafe(i18n(`action_codes.${actionCode}`, { who, when, path }));
+}
export default class PostActionDescription extends Component {
get description() {
diff --git a/frontend/discourse/app/components/post-list/item/index.gjs b/frontend/discourse/app/components/post-list/item/index.gjs
index 6e43aab4173..ff25a05905d 100644
--- a/frontend/discourse/app/components/post-list/item/index.gjs
+++ b/frontend/discourse/app/components/post-list/item/index.gjs
@@ -5,7 +5,9 @@ import { action } from "@ember/object";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import DButton from "discourse/components/d-button";
-import DecoratedHtml from "discourse/components/decorated-html";
+import DecoratedHtml, {
+ applyHtmlDecorators,
+} from "discourse/components/decorated-html";
import ExpandPost from "discourse/components/expand-post";
import PostListItemDetails from "discourse/components/post-list/item/details";
import avatar from "discourse/helpers/avatar";
@@ -18,7 +20,6 @@ import { or } from "discourse/truth-helpers";
export default class PostListItem extends Component {
@service site;
@service currentUser;
- @service appEvents;
get moderatorActionClass() {
return this.args.post.post_type === this.site.post_types.moderator_action
@@ -104,11 +105,7 @@ export default class PostListItem extends Component {
@bind
decoratePostContent(element, helper) {
- this.appEvents.trigger(
- "decorate-non-stream-cooked-element",
- element,
- helper
- );
+ applyHtmlDecorators(element, helper);
}
<template>
diff --git a/frontend/discourse/app/components/post/cooked-html.gjs b/frontend/discourse/app/components/post/cooked-html.gjs
index 60e71e5586a..e784fb96ca9 100644
--- a/frontend/discourse/app/components/post/cooked-html.gjs
+++ b/frontend/discourse/app/components/post/cooked-html.gjs
@@ -4,7 +4,10 @@ import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import { TrackedMap } from "@ember-compat/tracked-built-ins";
import curryComponent from "ember-curry-component";
-import DecoratedHtml from "discourse/components/decorated-html";
+import DecoratedHtml, {
+ applyHtmlDecorators,
+ NON_STREAM_HTML_DECORATOR,
+} from "discourse/components/decorated-html";
import lazyHash from "discourse/helpers/lazy-hash";
import { bind } from "discourse/lib/decorators";
import { isRailsTesting, isTesting } from "discourse/lib/environment";
@@ -27,8 +30,9 @@ const POST_COOKED_DECORATORS = [
decorateMentions,
];
+export const STREAM_HTML_DECORATOR = Symbol("stream-html-decorator");
+
export default class PostCookedHtml extends Component {
- @service appEvents;
@service currentUser;
#pendingDecoratorCleanup = [];
@@ -131,13 +135,12 @@ export default class PostCookedHtml extends Component {
}
});
- this.appEvents.trigger(
- this.isStreamElement
- ? "decorate-post-cooked-element"
- : "decorate-non-stream-cooked-element",
- element,
- helper
- );
+ const cleanUpFns = [
+ ...applyHtmlDecorators(element, helper, NON_STREAM_HTML_DECORATOR),
+ ...applyHtmlDecorators(element, helper, STREAM_HTML_DECORATOR),
+ ];
+
+ this.#pendingDecoratorCleanup.push(...cleanUpFns);
}
get className() {
diff --git a/frontend/discourse/app/components/post/meta-data/language.gjs b/frontend/discourse/app/components/post/meta-data/language.gjs
index 5c49c9c7b28..7bf5bed6e7c 100644
--- a/frontend/discourse/app/components/post/meta-data/language.gjs
+++ b/frontend/discourse/app/components/post/meta-data/language.gjs
@@ -4,20 +4,15 @@ import DTooltip from "discourse/float-kit/components/d-tooltip";
import { i18n } from "discourse-i18n";
export default class PostMetaDataLanguage extends Component {
- // TODO (glimmer-post-stream) once we switch to glimmer, we can remove `this.args.data.x` from the following 2 getters
-
@service languageNameLookup;
get language() {
- const lang = this.args.data?.language || this.args.post?.language;
+ const lang = this.args.post?.language;
return this.languageNameLookup.getLanguageName(lang);
}
get outdated() {
- return (
- this.args.data?.localization_outdated ||
- this.args.post?.localization_outdated
- );
+ return this.args.post?.localization_outdated;
}
get tooltip() {
diff --git a/frontend/discourse/app/components/post/notice/custom.gjs b/frontend/discourse/app/components/post/notice/custom.gjs
index 03da8924f78..eb8a2b79fac 100644
--- a/frontend/discourse/app/components/post/notice/custom.gjs
+++ b/frontend/discourse/app/components/post/notice/custom.gjs
@@ -8,7 +8,6 @@ import icon from "discourse/helpers/d-icon";
import { prioritizeNameInUx } from "discourse/lib/settings";
import { i18n } from "discourse-i18n";
-// TODO (glimmer-post-stream) needs tests
export default class PostNoticeCustom extends Component {
@tracked createdByAnchorElement;
diff --git a/frontend/discourse/app/components/post/notice/new-user.gjs b/frontend/discourse/app/components/post/notice/new-user.gjs
index bb6e5350300..5bff64bd30e 100644
--- a/frontend/discourse/app/components/post/notice/new-user.gjs
+++ b/frontend/discourse/app/components/post/notice/new-user.gjs
@@ -4,7 +4,6 @@ import emoji from "discourse/helpers/emoji";
import { prioritizeNameInUx } from "discourse/lib/settings";
import { i18n } from "discourse-i18n";
-// TODO (glimmer-post-stream) needs tests
export default class PostNoticeNewUser extends Component {
@service siteSettings;
diff --git a/frontend/discourse/app/components/post/small-action.gjs b/frontend/discourse/app/components/post/small-action.gjs
index e07f554c462..eccdb8f8e0a 100644
--- a/frontend/discourse/app/components/post/small-action.gjs
+++ b/frontend/discourse/app/components/post/small-action.gjs
@@ -16,7 +16,6 @@ import { userPath } from "discourse/lib/url";
import { i18n } from "discourse-i18n";
import PostA11yHeading from "./a11y-heading";
-// TODO (glimmer-post-stream) remove the export after removing the legacy widget code
export const GROUP_ACTION_CODES = ["invited_group", "removed_group"];
export const customGroupActionCodes = [];
diff --git a/frontend/discourse/app/components/reviewable-refresh/post.gjs b/frontend/discourse/app/components/reviewable-refresh/post.gjs
index d6634265917..d042191c4d2 100644
--- a/frontend/discourse/app/components/reviewable-refresh/post.gjs
+++ b/frontend/discourse/app/components/reviewable-refresh/post.gjs
@@ -1,7 +1,8 @@
import Component from "@glimmer/component";
-import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
-import DecoratedHtml from "discourse/components/decorated-html";
+import DecoratedHtml, {
+ applyHtmlDecorators,
+} from "discourse/components/decorated-html";
import PluginOutlet from "discourse/components/plugin-outlet";
import ReviewablePostEdits from "discourse/components/reviewable-post-edits";
import ReviewableCreatedBy from "discourse/components/reviewable-refresh/created-by";
@@ -12,8 +13,6 @@ import highlightHTML from "discourse/lib/highlight-html";
import { i18n } from "discourse-i18n";
export default class ReviewablePost extends Component {
- @service appEvents;
-
get metaLabel() {
return this.args.metaLabel || i18n("review.posted_in");
}
@@ -46,11 +45,7 @@ export default class ReviewablePost extends Component {
}
}
- this.appEvents.trigger(
- "decorate-non-stream-cooked-element",
- element,
- helper
- );
+ applyHtmlDecorators(element, helper);
}
<template>
diff --git a/frontend/discourse/app/components/reviewable-refresh/timeline.gjs b/frontend/discourse/app/components/reviewable-refresh/timeline.gjs
index 7bb2583cbfd..46d0bb401aa 100644
--- a/frontend/discourse/app/components/reviewable-refresh/timeline.gjs
+++ b/frontend/discourse/app/components/reviewable-refresh/timeline.gjs
@@ -5,7 +5,9 @@ import { action } from "@ember/object";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import DButton from "discourse/components/d-button";
-import DecoratedHtml from "discourse/components/decorated-html";
+import DecoratedHtml, {
+ applyHtmlDecorators,
+} from "discourse/components/decorated-html";
import InterpolatedTranslation from "discourse/components/interpolated-translation";
import ReviewableFlagReason from "discourse/components/reviewable-refresh/flag-reason";
import ReviewableNoteForm from "discourse/components/reviewable-refresh/note-form";
@@ -27,7 +29,6 @@ import { i18n } from "discourse-i18n";
* @component ReviewableTimeline
*/
export default class ReviewableTimeline extends Component {
- @service appEvents;
@service currentUser;
@service store;
@@ -219,11 +220,7 @@ export default class ReviewableTimeline extends Component {
@bind
decorate(element, helper) {
- this.appEvents.trigger(
- "decorate-non-stream-cooked-element",
- element,
- helper
- );
+ applyHtmlDecorators(element, helper);
}
<template>
diff --git a/frontend/discourse/app/components/scrolling-post-stream.js b/frontend/discourse/app/components/scrolling-post-stream.js
deleted file mode 100644
index d1285e76221..00000000000
--- a/frontend/discourse/app/components/scrolling-post-stream.js
+++ /dev/null
@@ -1,395 +0,0 @@
-import { next, schedule, scheduleOnce } from "@ember/runloop";
-import { service } from "@ember/service";
-import MountWidget from "discourse/components/mount-widget";
-import discourseDebounce from "discourse/lib/debounce";
-import { bind } from "discourse/lib/decorators";
-import domUtils from "discourse/lib/dom-utils";
-import offsetCalculator from "discourse/lib/offset-calculator";
-import DiscourseURL from "discourse/lib/url";
-import { cloak, uncloak } from "discourse/widgets/post-stream";
-
-const DEBOUNCE_DELAY = 50;
-
-function findTopView(posts, viewportTop, postsWrapperTop, min, max) {
- if (max < min) {
- return min;
- }
-
- while (max > min) {
- const mid = Math.floor((min + max) / 2);
- const post = posts.item(mid);
- const viewBottom =
- domUtils.offset(post).top - postsWrapperTop + post.clientHeight;
-
- if (viewBottom > viewportTop) {
- max = mid - 1;
- } else {
- min = mid + 1;
- }
- }
-
- return min;
-}
-
-export default class ScrollingPostStream extends MountWidget {
- @service screenTrack;
- @service site;
-
- widget = "post-stream";
- _topVisible = null;
- _bottomVisible = null;
- _currentPostObj = null;
- _currentVisible = null;
- _currentPercent = null;
-
- buildArgs() {
- return this.getProperties(
- "posts",
- "canCreatePost",
- "filteredPostsCount",
- "filteringRepliesToPostNumber",
- "multiSelect",
- "gaps",
- "selectedQuery",
- "selectedPostsCount",
- "searchService",
- "showReadIndicator",
- "streamFilters",
- "lastReadPostNumber",
- "highestPostNumber",
- "topicPageQueryParams"
- );
- }
-
- scrolled() {
- if (this.isDestroyed || this.isDestroying) {
- return;
- }
-
- if (document.webkitFullscreenElement || document.fullscreenElement) {
- return;
- }
-
- const windowHeight = window.innerHeight;
- const slack = Math.round(windowHeight * 5);
- const onscreen = [];
- const nearby = [];
- const windowTop = document.scrollingElement.scrollTop;
- const postsWrapperTop = domUtils.offset(
- document.querySelector(".posts-wrapper")
- ).top;
- const postsNodes = this.element.querySelectorAll(
- ".onscreen-post, .cloaked-post"
- );
-
- const viewportTop = windowTop - slack;
- const topView = findTopView(
- postsNodes,
- viewportTop,
- postsWrapperTop,
- 0,
- postsNodes.length - 1
- );
-
- let windowBottom = windowTop + windowHeight;
- let viewportBottom = windowBottom + slack;
- const bodyHeight = document.body.clientHeight;
- if (windowBottom > bodyHeight) {
- windowBottom = bodyHeight;
- }
- if (viewportBottom > bodyHeight) {
- viewportBottom = bodyHeight;
- }
-
- let currentPost = null;
- let percent = null;
-
- const offset = offsetCalculator();
- const topCheck = Math.ceil(windowTop + offset + 5);
-
- // uncomment to debug the eyeline
- /*
- let $eyeline = $('.debug-eyeline');
- if ($eyeline.length === 0) {
- $('body').prepend('<div class="debug-eyeline"></div>');
- $eyeline = $('.debug-eyeline');
- }
- $eyeline.css({ height: '5px', width: '100%', backgroundColor: 'blue', position: 'absolute', top: `${topCheck}px`, zIndex: 999999 });
- */
-
- let allAbove = true;
- let bottomView = topView;
- let lastBottom = 0;
- while (bottomView < postsNodes.length) {
- const post = postsNodes.item(bottomView);
-
- if (!post) {
- break;
- }
-
- const viewTop = domUtils.offset(post).top;
- const postHeight = post.clientHeight;
- const viewBottom = Math.ceil(viewTop + postHeight);
-
- allAbove = allAbove && viewTop < topCheck;
-
- if (viewTop > viewportBottom) {
- break;
- }
-
- if (viewBottom >= windowTop && viewTop <= windowBottom) {
- onscreen.push(bottomView);
- }
-
- if (
- currentPost === null &&
- ((viewTop <= topCheck && viewBottom >= topCheck) ||
- (lastBottom <= topCheck && viewTop >= topCheck))
- ) {
- percent = (topCheck - viewTop) / postHeight;
- currentPost = bottomView;
- }
-
- lastBottom = viewBottom;
- nearby.push(bottomView);
- bottomView++;
- }
-
- if (allAbove) {
- if (percent === null) {
- percent = 1.0;
- }
- if (currentPost === null) {
- currentPost = bottomView - 1;
- }
- }
-
- const posts = this.posts;
- const refresh = (cb) => this.queueRerender(cb);
- if (onscreen.length) {
- const first = posts.objectAt(onscreen[0]);
- if (this._topVisible !== first) {
- this._topVisible = first;
- const elemId = postsNodes.item(onscreen[0]).id;
-
- const topRefresh = () => {
- refresh(() => {
- const refreshedElem = document.getElementById(elemId);
-
- if (!refreshedElem) {
- return;
- }
-
- // The getOffsetTop function calculates the total offset distance of
- // an element from the top of the document. Unlike element.offsetTop
- // which only returns the offset relative to its nearest positioned
- // ancestor, this function recursively accumulates the offsetTop
- // of an element and all of its offset parents (ancestors).
- // This ensures the total distance is measured from the very top of
- // the document, accounting for any nested elements and their
- // respective offsets.
- const getOffsetTop = (element) => {
- if (!element) {
- return 0;
- }
- return element.offsetTop + getOffsetTop(element.offsetParent);
- };
-
- window.scrollTo({
- top: getOffsetTop(refreshedElem) - offsetCalculator(),
- });
-
- // This seems weird, but somewhat infrequently a rerender
- // will cause the browser to scroll to the top of the document
- // in Chrome. This makes sure the scroll works correctly if that
- // happens.
- schedule("afterRender", () => {
- window.scrollTo({
- top: getOffsetTop(refreshedElem) - offsetCalculator(),
- });
- });
- });
- };
- this.topVisibleChanged({
- post: first,
- refresh: topRefresh,
- });
- }
-
- const last = posts.objectAt(onscreen[onscreen.length - 1]);
- if (this._bottomVisible !== last) {
- this._bottomVisible = last;
- this.bottomVisibleChanged({ post: last, refresh });
- }
-
- const currentPostObj = posts.objectAt(currentPost);
- const changedPost = this._currentPostObj !== currentPostObj;
- if (changedPost) {
- this._currentPostObj = currentPostObj;
- this.currentPostChanged({ post: currentPostObj });
- }
-
- if (percent !== null) {
- percent = Math.max(0.0, Math.min(1.0, percent));
-
- if (changedPost || this._currentPercent !== percent) {
- this._currentPercent = percent;
- this.currentPostScrolled({ percent });
- }
- }
- } else {
- this._topVisible = null;
- this._bottomVisible = null;
- this._currentPostObj = null;
- this._currentPercent = null;
- }
-
- const onscreenPostNumbers = new Set();
- const readPostNumbers = new Set();
-
- const newPrev = new Set();
- nearby.forEach((idx) => {
- const post = posts.objectAt(idx);
-
- this._previouslyNearby.delete(post.post_number);
-
- if (onscreen.includes(idx)) {
- onscreenPostNumbers.add(post.post_number);
- if (post.read) {
- readPostNumbers.add(post.post_number);
- }
- }
-
- newPrev.add(post.post_number, post);
- uncloak(post, this);
- });
-
- Object.values(this._previouslyNearby).forEach((node) => cloak(node, this));
-
- this._previouslyNearby = newPrev;
- this.screenTrack.setOnscreen(onscreenPostNumbers, readPostNumbers);
- }
-
- _scrollTriggered() {
- scheduleOnce("afterRender", this, this.scrolled);
- }
-
- _posted(staged) {
- this.queueRerender(() => {
- if (staged) {
- const postNumber = staged.post_number;
- DiscourseURL.jumpToPost(postNumber, { skipIfOnScreen: true });
- }
- });
- }
-
- _refresh(args) {
- if (args) {
- if (args.id) {
- this.dirtyKeys.keyDirty(`post-${args.id}`);
-
- if (args.refreshLikes) {
- this.dirtyKeys.keyDirty(`post-menu-${args.id}`, {
- onRefresh: "refreshLikes",
- });
- }
-
- if (args.refreshReaders) {
- this.dirtyKeys.keyDirty(`post-menu-${args.id}`, {
- onRefresh: "refreshReaders",
- });
- }
- } else if (args.force) {
- this.dirtyKeys.forceAll();
- }
- }
- this.queueRerender();
- this._scrollTriggered();
- }
-
- @bind
- _debouncedScroll() {
- discourseDebounce(this, this._scrollTriggered, DEBOUNCE_DELAY);
- }
-
- didInsertElement() {
- super.didInsertElement(...arguments);
- this._previouslyNearby = new Set();
-
- this.appEvents.on("post-stream:refresh", this, "_debouncedScroll");
- const opts = {
- passive: true,
- };
- document.addEventListener("touchmove", this._debouncedScroll, opts);
- window.addEventListener("scroll", this._debouncedScroll, opts);
-
- if (this.site.useGlimmerPostStream) {
- next(() => this._scrollTriggered());
- } else {
- this._scrollTriggered();
- }
-
- this.appEvents.on("post-stream:posted", this, "_posted");
-
- this.element.addEventListener(
- "mouseenter",
- this._handleWidgetButtonHoverState,
- true
- );
-
- this.element.addEventListener(
- "mouseleave",
- this._removeWidgetButtonHoverState,
- true
- );
-
- this.appEvents.on("post-stream:refresh", this, "_refresh");
-
- // restore scroll position on browsers with aggressive BFCaches (like Safari)
- window.onpageshow = function (event) {
- if (event.persisted) {
- DiscourseURL.routeTo(this.location.pathname);
- }
- };
- }
-
- willDestroyElement() {
- super.willDestroyElement(...arguments);
-
- document.removeEventListener("touchmove", this._debouncedScroll);
- window.removeEventListener("scroll", this._debouncedScroll);
- this.appEvents.off("post-stream:refresh", this, "_debouncedScroll");
- this.element.removeEventListener(
- "mouseenter",
- this._handleWidgetButtonHoverState
- );
- this.element.removeEventListener(
- "mouseleave",
- this._removeWidgetButtonHoverState
- );
- this.appEvents.off("post-stream:refresh", this, "_refresh");
- this.appEvents.off("post-stream:posted", this, "_posted");
- }
-
- didUpdateAttrs() {
- super.didUpdateAttrs(...arguments);
- this._refresh({ force: true });
- }
-
- _handleWidgetButtonHoverState(event) {
- if (event.target.classList.contains("widget-button")) {
- document
- .querySelectorAll("button.widget-button")
- .forEach((widgetButton) => {
- widgetButton.classList.remove("d-hover");
- });
- event.target.classList.add("d-hover");
- }
- }
-
- _removeWidgetButtonHoverState() {
- document.querySelectorAll("button.widget-button").forEach((button) => {
- button.classList.remove("d-hover");
- });
- }
-}
diff --git a/frontend/discourse/app/components/search-menu.gjs b/frontend/discourse/app/components/search-menu.gjs
index 64e681bd7c5..1f4067ce988 100644
--- a/frontend/discourse/app/components/search-menu.gjs
+++ b/frontend/discourse/app/components/search-menu.gjs
@@ -334,13 +334,6 @@ export default class SearchMenu extends Component {
// we ensure the current search term is the one used
// when starting the query
if (results) {
- if (this.searchContext) {
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", {
- force: true,
- });
- }
-
this.search.noResults = results.resultTypes.length === 0;
this.search.results = results;
}
diff --git a/frontend/discourse/app/components/topic-timeline/container.gjs b/frontend/discourse/app/components/topic-timeline/container.gjs
index aad6efd2865..9101747f9cd 100644
--- a/frontend/discourse/app/components/topic-timeline/container.gjs
+++ b/frontend/discourse/app/components/topic-timeline/container.gjs
@@ -8,6 +8,7 @@ import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import DButton from "discourse/components/d-button";
import PluginOutlet from "discourse/components/plugin-outlet";
+import { actionDescriptionHtml } from "discourse/components/post-action-description";
import TopicAdminMenu from "discourse/components/topic-admin-menu";
import UserTip from "discourse/components/user-tip";
import ageWithTooltip from "discourse/helpers/age-with-tooltip";
@@ -21,7 +22,6 @@ import domUtils from "discourse/lib/dom-utils";
import { headerOffset } from "discourse/lib/offset-calculator";
import TopicNotificationsButton from "discourse/select-kit/components/topic-notifications-button";
import { and, not, or } from "discourse/truth-helpers";
-import { actionDescriptionHtml } from "discourse/widgets/post-small-action";
import { i18n } from "discourse-i18n";
import BackButton from "./back-button";
import Scroller from "./scroller";
@@ -92,8 +92,6 @@ export default class TopicTimelineScrollArea extends Component {
this.appEvents.on("composer:resized", this.calculatePosition);
this.appEvents.on("composer:closed", this.calculatePosition);
this.appEvents.on("composer:preview-toggled", this.calculatePosition);
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.on("post-stream:posted", this.calculatePosition);
}
this.intersectionObserver = new IntersectionObserver((entries) => {
@@ -133,8 +131,6 @@ export default class TopicTimelineScrollArea extends Component {
this.appEvents.off("composer:closed", this.calculatePosition);
this.appEvents.off("composer:preview-toggled", this.calculatePosition);
this.appEvents.off("topic:current-post-scrolled", this.postScrolled);
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.off("post-stream:posted", this.calculatePosition);
}
}
diff --git a/frontend/discourse/app/components/user-stream-item.gjs b/frontend/discourse/app/components/user-stream-item.gjs
index 6d6edb3d551..598a5e9a122 100644
--- a/frontend/discourse/app/components/user-stream-item.gjs
+++ b/frontend/discourse/app/components/user-stream-item.gjs
@@ -7,6 +7,7 @@ import { classNameBindings, tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
import ExpandPost from "discourse/components/expand-post";
import PluginOutlet from "discourse/components/plugin-outlet";
+import { actionDescriptionHtml } from "discourse/components/post-action-description";
import TopicStatus from "discourse/components/topic-status";
import avatar from "discourse/helpers/avatar";
import categoryLink from "discourse/helpers/category-link";
@@ -19,7 +20,20 @@ import discourseComputed from "discourse/lib/decorators";
import deprecated from "discourse/lib/deprecated";
import { userPath } from "discourse/lib/url";
import { or } from "discourse/truth-helpers";
-import { actionDescription } from "discourse/widgets/post-small-action";
+
+function actionDescription(actionCode, createdAt, username, path = null) {
+ return computed(actionCode, createdAt, function () {
+ const ac = this.get(actionCode);
+ if (ac) {
+ return actionDescriptionHtml(
+ ac,
+ this.get(createdAt),
+ this.get(username),
+ path ? this.get(path) : null
+ );
+ }
+ });
+}
@tagName("li")
@classNameBindings(
diff --git a/frontend/discourse/app/controllers/topic.js b/frontend/discourse/app/controllers/topic.js
index 9b06008a642..0729e698ba3 100644
--- a/frontend/discourse/app/controllers/topic.js
+++ b/frontend/discourse/app/controllers/topic.js
@@ -10,10 +10,6 @@ import { observes } from "@ember-decorators/object";
import BufferedProxy from "ember-buffered-proxy/proxy";
import { Promise } from "rsvp";
import DEditorOriginalTranslationPreview from "discourse/components/d-editor-original-translation-preview";
-import {
- CLOSE_INITIATED_BY_BUTTON,
- CLOSE_INITIATED_BY_ESC,
-} from "discourse/components/d-modal";
import BookmarkModal from "discourse/components/modal/bookmark";
import ChangePostNoticeModal from "discourse/components/modal/change-post-notice";
import ConvertToPublicTopicModal from "discourse/components/modal/convert-to-public-topic";
@@ -118,11 +114,9 @@ export default class TopicController extends Controller {
super.init(...arguments);
this.appEvents.on("post:show-revision", this, "_showRevision");
- this.appEvents.on("post:created", this, () => {
- this._removeDeleteOnOwnerReplyBookmarks();
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { force: true });
- });
+ this.appEvents.on("post:created", this, () =>
+ this._removeDeleteOnOwnerReplyBookmarks()
+ );
}
willDestroy() {
@@ -175,21 +169,6 @@ export default class TopicController extends Controller {
return mobileView && postsCount > 3;
}
- // TODO (glimmer-post-stream) this method is not used in the Glimmer Post Stream
- @discourseComputed(
- "model.postStream.posts",
- "model.postStream.postsWithPlaceholders"
- )
- postsToRender(posts, postsWithPlaceholders) {
- return this.capabilities.isAndroid ? posts : postsWithPlaceholders;
- }
-
- // TODO (glimmer-post-stream) is this still used?
- @discourseComputed("model.postStream.loadingFilter")
- androidLoading(loading) {
- return this.capabilities.isAndroid && loading;
- }
-
@discourseComputed("model")
pmPath(topic) {
return this.currentUser && this.currentUser.pmPath(topic);
@@ -317,11 +296,6 @@ export default class TopicController extends Controller {
}
}
- _forceRefreshPostStream() {
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { force: true });
- }
-
_updateSelectedPostIds(postIds) {
const smallActionsPostIds = this._smallActionPostIds();
this.selectedPostIds = Array.from(
@@ -330,7 +304,6 @@ export default class TopicController extends Controller {
...postIds.filter((postId) => !smallActionsPostIds.has(postId)),
])
);
- this._forceRefreshPostStream();
}
_smallActionPostIds() {
@@ -468,21 +441,18 @@ export default class TopicController extends Controller {
(postId) => !smallActionsPostIds.has(postId)
),
];
- this._forceRefreshPostStream();
}
@action
deselectAll(event) {
event?.preventDefault();
this.selectedPostIds = [];
- this._forceRefreshPostStream();
}
@action
toggleMultiSelect(event) {
event?.preventDefault();
this.toggleProperty("multiSelect");
- this._forceRefreshPostStream();
}
@action
@@ -650,7 +620,6 @@ export default class TopicController extends Controller {
postStream.get("canAppendMore")
) {
await postStream.appendMore();
- // TODO (glimmer-post-stream) the Glimmer Post stream doesn't pass a refresh function
refresh?.();
}
}
@@ -847,22 +816,16 @@ export default class TopicController extends Controller {
}
const user = this.currentUser;
- const refresh = () =>
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh");
const hasReplies = post.get("reply_count") > 0;
const loadedPosts = this.get("model.postStream.posts");
if (user.get("staff") && hasReplies) {
ajax(`/posts/${post.id}/reply-ids.json`).then((replies) => {
if (replies.length === 0) {
- return post
- .destroy(user, opts)
- .then(refresh)
- .catch((error) => {
- popupAjaxError(error);
- post.undoDeleteState();
- });
+ return post.destroy(user, opts).catch((error) => {
+ popupAjaxError(error);
+ post.undoDeleteState();
+ });
}
const buttons = [];
@@ -882,9 +845,7 @@ export default class TopicController extends Controller {
(p === post || directReplyIds.includes(p.id)) &&
p.setDeletedState(user)
);
- Post.deleteMany([post.id, ...directReplyIds])
- .then(refresh)
- .catch(popupAjaxError);
+ Post.deleteMany([post.id, ...directReplyIds]).catch(popupAjaxError);
},
});
@@ -899,9 +860,9 @@ export default class TopicController extends Controller {
(p === post || replies.some((r) => r.id === p.id)) &&
p.setDeletedState(user)
);
- Post.deleteMany([post.id, ...replies.map((r) => r.id)])
- .then(refresh)
- .catch(popupAjaxError);
+ Post.deleteMany([post.id, ...replies.map((r) => r.id)]).catch(
+ popupAjaxError
+ );
},
});
}
@@ -909,13 +870,10 @@ export default class TopicController extends Controller {
buttons.push({
label: i18n("post.controls.delete_replies.just_the_post"),
action: () => {
- post
- .destroy(user, opts)
- .then(refresh)
- .catch((error) => {
- popupAjaxError(error);
- post.undoDeleteState();
- });
+ post.destroy(user, opts).catch((error) => {
+ popupAjaxError(error);
+ post.undoDeleteState();
+ });
},
});
@@ -930,13 +888,10 @@ export default class TopicController extends Controller {
});
});
} else {
- return post
- .destroy(user, opts)
- .then(refresh)
- .catch((error) => {
- popupAjaxError(error);
- post.undoDeleteState();
- });
+ return post.destroy(user, opts).catch((error) => {
+ popupAjaxError(error);
+ post.undoDeleteState();
+ });
}
}
@@ -1069,15 +1024,7 @@ export default class TopicController extends Controller {
post
);
} else {
- return this._toggleTopicLevelBookmark().then((changedIds) => {
- if (!changedIds) {
- return;
- }
- changedIds.forEach((id) =>
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { id })
- );
- });
+ return this._toggleTopicLevelBookmark();
}
}
@@ -1163,7 +1110,6 @@ export default class TopicController extends Controller {
post.id,
...replyIds,
]);
- this._forceRefreshPostStream();
});
}
@@ -1563,38 +1509,22 @@ export default class TopicController extends Controller {
}
_modifyPostBookmark(bookmark, post) {
- this.modal
- .show(BookmarkModal, {
- model: {
- bookmark: new BookmarkFormData(bookmark),
- afterSave: (savedData) => {
- this._syncBookmarks(savedData);
- this.model.set("bookmarking", false);
- post.createBookmark(savedData);
- this.model.afterPostBookmarked(post, savedData);
- return [post.id];
- },
- afterDelete: (topicBookmarked, bookmarkId) => {
- this.model.removeBookmark(bookmarkId);
- post.deleteBookmark(topicBookmarked);
- },
+ this.modal.show(BookmarkModal, {
+ model: {
+ bookmark: new BookmarkFormData(bookmark),
+ afterSave: (savedData) => {
+ this._syncBookmarks(savedData);
+ this.model.set("bookmarking", false);
+ post.createBookmark(savedData);
+ this.model.afterPostBookmarked(post, savedData);
+ return [post.id];
},
- })
- .then((closeData) => {
- if (!closeData) {
- return;
- }
-
- if (
- closeData.closeWithoutSaving ||
- closeData.initiatedBy === CLOSE_INITIATED_BY_ESC ||
- closeData.initiatedBy === CLOSE_INITIATED_BY_BUTTON
- ) {
- post.appEvents.trigger("post-stream:refresh", {
- id: bookmark.bookmarkable_id,
- });
- }
- });
+ afterDelete: (topicBookmarked, bookmarkId) => {
+ this.model.removeBookmark(bookmarkId);
+ post.deleteBookmark(topicBookmarked);
+ },
+ },
+ });
}
_syncBookmarks(data) {
@@ -1891,9 +1821,6 @@ export default class TopicController extends Controller {
@bind
onMessage(data) {
const topic = this.model;
- const refresh = (args) =>
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", args);
if (isPresent(data.notification_level_change)) {
topic.set("details.notification_level", data.notification_level_change);
@@ -1923,48 +1850,39 @@ export default class TopicController extends Controller {
switch (data.type) {
case "acted":
- postStream
- .triggerChangedPost(data.id, data.updated_at, {
- preserveCooked: true,
- })
- .then(() => refresh({ id: data.id, refreshLikes: true }));
+ postStream.triggerChangedPost(data.id, data.updated_at, {
+ preserveCooked: true,
+ });
break;
case "read": {
- postStream
- .triggerReadPost(data.id, data.readers_count)
- .then(() => refresh({ id: data.id, refreshLikes: true }));
+ postStream.triggerReadPost(data.id, data.readers_count);
break;
}
case "liked":
case "unliked": {
- postStream
- .triggerLikedPost(data.id, data.likes_count, data.user_id, data.type)
- .then(() => refresh({ id: data.id, refreshLikes: true }));
+ postStream.triggerLikedPost(
+ data.id,
+ data.likes_count,
+ data.user_id,
+ data.type
+ );
break;
}
case "revised":
case "rebaked": {
- postStream
- .triggerChangedPost(data.id, data.updated_at)
- .then(() => refresh({ id: data.id }));
+ postStream.triggerChangedPost(data.id, data.updated_at);
break;
}
case "deleted": {
- postStream
- .triggerDeletedPost(data.id)
- .then(() => refresh({ id: data.id }));
+ postStream.triggerDeletedPost(data.id);
break;
}
case "destroyed": {
- postStream
- .triggerDestroyedPost(data.id)
- .then(() => refresh({ id: data.id }));
+ postStream.triggerDestroyedPost(data.id);
break;
}
case "recovered": {
- postStream
- .triggerRecoveredPost(data.id)
- .then(() => refresh({ id: data.id }));
+ postStream.triggerRecoveredPost(data.id);
break;
}
case "created": {
@@ -1976,7 +1894,6 @@ export default class TopicController extends Controller {
return postStream
.triggerNewPostsInStream(postIds, { background: true })
- .then(() => refresh())
.catch((e) => {
this._newPostsInStream = postIds.concat(this._newPostsInStream);
throw e;
@@ -2012,9 +1929,7 @@ export default class TopicController extends Controller {
}
if (updateStream) {
- postStream
- .triggerChangedTopicStats()
- .then((firstPostId) => refresh({ id: firstPostId }));
+ postStream.triggerChangedTopicStats();
}
break;
}
@@ -2046,8 +1961,6 @@ export default class TopicController extends Controller {
postStream.get("posts").forEach((post) => {
if (!post.read && postNumbers.includes(post.post_number)) {
post.set("read", true);
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { id: post.get("id") });
}
});
diff --git a/frontend/discourse/app/global-compat.js b/frontend/discourse/app/global-compat.js
index 7e3ec1b853a..f26cafe2a74 100644
--- a/frontend/discourse/app/global-compat.js
+++ b/frontend/discourse/app/global-compat.js
@@ -1,9 +1,6 @@
import "discourse/lib/load-moment";
import jQuery from "jquery";
-import virtualDom from "virtual-dom";
-import widgetHelpers from "discourse-widget-hbs/helpers";
-
-window.__widget_helpers = widgetHelpers;
+import * as virtualDom from "discourse/widgets/virtual-dom";
// TODO: Eliminate this global
window.virtualDom = virtualDom;
diff --git a/frontend/discourse/app/helpers/fa-icon-node.js b/frontend/discourse/app/helpers/fa-icon-node.js
index 6a6c6eed4f8..d7d26bb4f28 100644
--- a/frontend/discourse/app/helpers/fa-icon-node.js
+++ b/frontend/discourse/app/helpers/fa-icon-node.js
@@ -1,5 +1,8 @@
-import { renderIcon } from "discourse/lib/icon-library";
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
-export function iconNode(id, params) {
- return renderIcon("node", id, params);
-}
+export { iconNode } from "discourse/lib/icon-library";
diff --git a/frontend/discourse/app/helpers/node.js b/frontend/discourse/app/helpers/node.js
index 8d014c3fba9..f0f1f175012 100644
--- a/frontend/discourse/app/helpers/node.js
+++ b/frontend/discourse/app/helpers/node.js
@@ -1,34 +1,4 @@
-import { h } from "virtual-dom";
-import { longDate, number, relativeAge } from "discourse/lib/formatter";
-
-export function dateNode(dt) {
- if (typeof dt === "string") {
- dt = new Date(dt);
- }
- if (dt) {
- const attributes = {
- title: longDate(dt),
- "data-time": dt.getTime(),
- "data-format": "tiny",
- };
-
- return h("span.relative-date", { attributes }, relativeAge(dt));
- }
-}
-
-export function numberNode(num, opts) {
- opts = opts || {};
- num = parseInt(num, 10);
- if (isNaN(num)) {
- num = 0;
- }
-
- const numString = num.toString();
- const attributes = {};
- const formatted = number(num);
- if (formatted !== numString) {
- attributes.title = numString;
- }
-
- return h("span.number", { className: opts.className, attributes }, formatted);
-}
+export {
+ warnWidgetsDecommissioned as dateNode,
+ warnWidgetsDecommissioned as numberNode,
+} from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/instance-initializers/animated-images-pause-on-click.js b/frontend/discourse/app/instance-initializers/animated-images-pause-on-click.js
index de2089b59e2..9532437af25 100644
--- a/frontend/discourse/app/instance-initializers/animated-images-pause-on-click.js
+++ b/frontend/discourse/app/instance-initializers/animated-images-pause-on-click.js
@@ -2,7 +2,7 @@ import { iconHTML } from "discourse/lib/icon-library";
import { withPluginApi } from "discourse/lib/plugin-api";
import { prefersReducedMotion } from "discourse/lib/utilities";
-let _gifClickHandlers = {};
+const eventedImageElements = new WeakSet();
function _pauseAnimation(img, opts = {}) {
let canvas = document.createElement("canvas");
@@ -35,15 +35,6 @@ function animatedImgs() {
export default {
initialize() {
withPluginApi((api) => {
- function _cleanUp() {
- Object.values(_gifClickHandlers || {}).forEach((handler) => {
- handler.removeEventListener("click", _handleEvent);
- handler.removeEventListener("load", _handleEvent);
- });
-
- _gifClickHandlers = {};
- }
-
function _handleEvent(event) {
const img = event.target;
if (img && !img.previousSibling) {
@@ -58,39 +49,35 @@ export default {
return;
}
- let images = post.querySelectorAll("img.animated:not(.onebox-avatar)");
+ let imageElements = post.querySelectorAll(
+ "img.animated:not(.onebox-avatar)"
+ );
- images.forEach((img) => {
+ imageElements.forEach((imageElement) => {
// skip for edge case of multiple animated images in same block
- if (img.parentNode.querySelectorAll("img").length > 1) {
+ if (imageElement.parentNode.querySelectorAll("img").length > 1) {
return;
}
- if (_gifClickHandlers[img.src]) {
- _gifClickHandlers[img.src].removeEventListener(
- "click",
- _handleEvent
- );
- _gifClickHandlers[img.src].removeEventListener(
- "load",
- _handleEvent
- );
- delete _gifClickHandlers[img.src];
+ if (eventedImageElements.has(imageElement)) {
+ imageElement.removeEventListener("click", _handleEvent);
+ imageElement.removeEventListener("load", _handleEvent);
+ eventedImageElements.delete(imageElement);
}
- _gifClickHandlers[img.src] = img;
- img.addEventListener("click", _handleEvent, false);
+ eventedImageElements.add(imageElement);
+ imageElement.addEventListener("click", _handleEvent, false);
if (prefersReducedMotion()) {
- img.addEventListener("load", _handleEvent, false);
+ imageElement.addEventListener("load", _handleEvent, false);
}
const wrapper = document.createElement("div"),
overlay = document.createElement("div");
- img.parentNode.insertBefore(wrapper, img);
+ imageElement.parentNode.insertBefore(wrapper, imageElement);
wrapper.classList.add("pausable-animated-image");
- wrapper.appendChild(img);
+ wrapper.appendChild(imageElement);
overlay.classList.add("animated-image-overlay");
overlay.setAttribute("aria-hidden", "true");
@@ -104,8 +91,6 @@ export default {
onlyStream: true,
});
- api.cleanupStream(_cleanUp);
-
// paused on load when prefers-reduced-motion is active, no need for blur/focus events
if (!prefersReducedMotion()) {
window.addEventListener("blur", this.blurEvent);
diff --git a/frontend/discourse/app/instance-initializers/codeblock-buttons.js b/frontend/discourse/app/instance-initializers/codeblock-buttons.js
index 32f34480e88..b1f65148d5b 100644
--- a/frontend/discourse/app/instance-initializers/codeblock-buttons.js
+++ b/frontend/discourse/app/instance-initializers/codeblock-buttons.js
@@ -2,53 +2,38 @@ import { schedule } from "@ember/runloop";
import CodeblockButtons from "discourse/lib/codeblock-buttons";
import { withPluginApi } from "discourse/lib/plugin-api";
-let _codeblockButtons = [];
-
export default {
initialize(owner) {
const site = owner.lookup("service:site");
const siteSettings = owner.lookup("service:site-settings");
withPluginApi((api) => {
- function _cleanUp() {
- _codeblockButtons.forEach((cb) => cb.cleanup());
- _codeblockButtons.length = 0;
- }
-
function _attachCommands(postElement, helper) {
if (!helper) {
return;
}
- if (!siteSettings.show_copy_button_on_codeblocks) {
- return;
- }
-
const post = helper.getModel();
const cb = new CodeblockButtons({
site,
showFullscreen: true,
showCopy: true,
});
- cb.attachToPost(post, postElement);
- _codeblockButtons.push(cb);
+ // must be done after render so we can check the scroll width
+ // of the code blocks
+ schedule("afterRender", () => {
+ cb.attachToPost(post, postElement);
+ });
+
+ return cb.cleanup;
}
- api.decorateCookedElement(
- (postElement, helper) => {
- // must be done after render so we can check the scroll width
- // of the code blocks
- schedule("afterRender", () => {
- _attachCommands(postElement, helper);
- });
- },
- {
+ if (siteSettings.show_copy_button_on_codeblocks) {
+ api.decorateCookedElement(_attachCommands, {
onlyStream: true,
- }
- );
-
- api.cleanupStream(_cleanUp);
+ });
+ }
});
},
};
diff --git a/frontend/discourse/app/instance-initializers/onebox-decorators.js b/frontend/discourse/app/instance-initializers/onebox-decorators.js
index 099ff3555d5..36317a37c6f 100644
--- a/frontend/discourse/app/instance-initializers/onebox-decorators.js
+++ b/frontend/discourse/app/instance-initializers/onebox-decorators.js
@@ -1,15 +1,15 @@
import { withPluginApi } from "discourse/lib/plugin-api";
-let _showMoreClickPostsElements = [];
-
export function decorateGithubOneboxBody(element) {
const containers = element.querySelectorAll(
".onebox.githubcommit .show-more-container, .onebox.githubpullrequest .show-more-container, .onebox.githubissue .show-more-container"
);
if (containers.length) {
- _showMoreClickPostsElements.push(element);
element.addEventListener("click", _handleClick, false);
+
+ // cleanup function to remove the event listener while cleaning up the decorations
+ return () => element.removeEventListener("click", _handleClick);
}
}
@@ -29,22 +29,10 @@ function _handleClick(event) {
return false;
}
-function _cleanUp() {
- (_showMoreClickPostsElements || []).forEach((element) => {
- element.removeEventListener("click", _handleClick);
- });
-
- _showMoreClickPostsElements = [];
-}
-
export default {
initialize() {
withPluginApi((api) => {
- api.decorateCookedElement((element) => {
- decorateGithubOneboxBody(element);
- });
-
- api.cleanupStream(_cleanUp);
+ api.decorateCookedElement(decorateGithubOneboxBody);
});
},
};
diff --git a/frontend/discourse/app/instance-initializers/post-decorations.js b/frontend/discourse/app/instance-initializers/post-decorations.js
index 0b6adaddc7a..f54de44d8f3 100644
--- a/frontend/discourse/app/instance-initializers/post-decorations.js
+++ b/frontend/discourse/app/instance-initializers/post-decorations.js
@@ -1,12 +1,11 @@
import { schedule } from "@ember/runloop";
-import { create } from "virtual-dom";
import FullscreenTableModal from "discourse/components/modal/fullscreen-table";
import SpreadsheetEditor from "discourse/components/modal/spreadsheet-editor";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import Columns from "discourse/lib/columns";
import highlightSyntax from "discourse/lib/highlight-syntax";
-import { iconHTML, iconNode } from "discourse/lib/icon-library";
+import { iconElement, iconHTML } from "discourse/lib/icon-library";
import { nativeLazyLoading } from "discourse/lib/lazy-load-images";
import lightbox from "discourse/lib/lightbox";
import { withPluginApi } from "discourse/lib/plugin-api";
@@ -119,9 +118,9 @@ export default {
}
if (props.icon) {
- const icon = create(
- iconNode(props.icon.name, { class: props.icon?.class })
- );
+ const icon = iconElement(props.icon.name, {
+ class: props.icon?.class,
+ });
openPopupBtn.prepend(icon);
}
@@ -187,8 +186,7 @@ export default {
table.parentNode.setAttribute("data-table-index", index);
table.parentNode.classList.add("fullscreen-table-wrapper");
- // TODO (glimmer-post-stream) in the Glimmer post stream we can check for post.can_edit instead
- if (post.canEdit) {
+ if (post.can_edit) {
table.parentNode.classList.add("--editable");
buttonWrapper.append(tableEditorBtn);
tableEditorBtn.addEventListener(
@@ -224,21 +222,6 @@ export default {
});
}
- function cleanupPopupBtns() {
- const editTableBtn = document.querySelector(
- ".open-popup-link.btn-edit-table"
- );
- const expandTableBtn = document.querySelector(
- ".open-popup-link.btn-expand-table"
- );
-
- expandTableBtn?.removeEventListener(
- "click",
- generateFullScreenTableModal
- );
- editTableBtn?.removeEventListener("click", generateSpreadsheetModal);
- }
-
api.decorateCookedElement(
(element, helper) => {
schedule("afterRender", () => {
@@ -251,8 +234,6 @@ export default {
id: "table-wrapper",
}
);
-
- api.cleanupStream(cleanupPopupBtns);
});
},
};
diff --git a/frontend/discourse/app/lib/attribute-hook.js b/frontend/discourse/app/lib/attribute-hook.js
index b66172c73b5..6b0366581a6 100644
--- a/frontend/discourse/app/lib/attribute-hook.js
+++ b/frontend/discourse/app/lib/attribute-hook.js
@@ -1,42 +1,8 @@
-// FROM: https://github.com/Matt-Esch/virtual-dom
-// License: MIT
-
-function AttributeHook(namespace, value) {
- if (!(this instanceof AttributeHook)) {
- return new AttributeHook(namespace, value);
- }
-
- this.namespace = namespace;
- this.value = value;
-}
-
-AttributeHook.prototype.hook = function (node, prop, prev) {
- if (
- prev &&
- prev.type === "AttributeHook" &&
- prev.value === this.value &&
- prev.namespace === this.namespace
- ) {
- return;
- }
-
- node.setAttributeNS(this.namespace, prop, this.value);
-};
-
-AttributeHook.prototype.unhook = function (node, prop, next) {
- if (
- next &&
- next.type === "AttributeHook" &&
- next.namespace === this.namespace
- ) {
- return;
- }
-
- let colonPosition = prop.indexOf(":");
- let localName = colonPosition > -1 ? prop.slice(colonPosition + 1) : prop;
- node.removeAttributeNS(this.namespace, localName);
-};
-
-AttributeHook.prototype.type = "AttributeHook";
-
-export default AttributeHook;
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export { warnWidgetsDecommissioned as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/lib/codeblock-buttons.js b/frontend/discourse/app/lib/codeblock-buttons.js
index 0d6cb013be8..08dfc2d8dff 100644
--- a/frontend/discourse/app/lib/codeblock-buttons.js
+++ b/frontend/discourse/app/lib/codeblock-buttons.js
@@ -73,6 +73,7 @@ export default class CodeblockButtons {
this._addClickEvent(element);
}
+ @bind
cleanup() {
Object.values(this._codeblockButtonClickHandlers || {}).forEach((handler) =>
handler.removeEventListener("click", this._handleClick)
diff --git a/frontend/discourse/app/lib/flag-targets/flag.js b/frontend/discourse/app/lib/flag-targets/flag.js
index e712d7149ec..5833f077edc 100644
--- a/frontend/discourse/app/lib/flag-targets/flag.js
+++ b/frontend/discourse/app/lib/flag-targets/flag.js
@@ -22,11 +22,6 @@ export default class Flag {
flagModal.args.closeModal();
postAction
.act(flagModal.args.model.flagModel, opts)
- .then(() => {
- flagModal.appEvents.trigger("post-stream:refresh", {
- id: flagModal.args.model.flagModel.id,
- });
- })
.catch((error) => popupAjaxError(error));
}
}
diff --git a/frontend/discourse/app/lib/icon-library.js b/frontend/discourse/app/lib/icon-library.js
index 1b7a9ad356e..b3fd37b5023 100644
--- a/frontend/discourse/app/lib/icon-library.js
+++ b/frontend/discourse/app/lib/icon-library.js
@@ -1,8 +1,7 @@
-import { h } from "virtual-dom";
-import attributeHook from "discourse/lib/attribute-hook";
import deprecated from "discourse/lib/deprecated";
import { isDevelopment } from "discourse/lib/environment";
import escape from "discourse/lib/escape";
+import { warnWidgetsDecommissioned } from "discourse/widgets/widget";
import { i18n } from "discourse-i18n";
export const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
@@ -94,8 +93,17 @@ export function iconHTML(id, params) {
return renderIcon("string", id, params);
}
-export function iconNode(id, params) {
- return renderIcon("node", id, params);
+/**
+ * @deprecated The widget rendering system has been decommissioned.
+ * - If you need to create DOM nodes directly, use `iconElement` instead.
+ * - If you need to render icons in a template, use the `{{icon}}` helper.
+ */
+export function iconNode() {
+ warnWidgetsDecommissioned();
+}
+
+export function iconElement(id, params) {
+ return renderIcon("element", id, params);
}
export function convertIconClass(icon) {
@@ -191,35 +199,28 @@ registerIconRenderer({
return html;
},
- node(icon, params) {
- const id = handleIconId(icon);
+ element(icon, params) {
+ const id = escape(handleIconId(icon));
const classes = iconClasses(icon, params) + " svg-node";
- const svg = h(
- "svg",
- {
- attributes: { class: classes, "aria-hidden": true },
- namespace: SVG_NAMESPACE,
- },
- [
- h("use", {
- href: attributeHook("http://www.w3.org/1999/xlink", `#${escape(id)}`),
- namespace: SVG_NAMESPACE,
- }),
- ]
- );
+ const svgElement = document.createElementNS(SVG_NAMESPACE, "svg");
+ svgElement.setAttribute("class", classes);
+ svgElement.setAttribute("aria-hidden", true);
+
+ const useElement = document.createElementNS(SVG_NAMESPACE, "use");
+ useElement.setAttribute("href", `#${id}`);
+
+ svgElement.appendChild(useElement);
if (params.title) {
- return h(
- "span",
- {
- title: params.title,
- attributes: { class: "svg-icon-title" },
- },
- [svg]
- );
+ const spanElement = document.createElement("span");
+ spanElement.setAttribute("class", "svg-icon-title");
+ spanElement.setAttribute("title", params.title);
+ spanElement.appendChild(svgElement);
+
+ return spanElement;
} else {
- return svg;
+ return svgElement;
}
},
});
diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjs
index a95376de7bc..19b602e05a9 100644
--- a/frontend/discourse/app/lib/plugin-api.gjs
+++ b/frontend/discourse/app/lib/plugin-api.gjs
@@ -1,5 +1,4 @@
import $ from "jquery";
-import { h } from "virtual-dom";
import { addAboutPageActivity } from "discourse/components/about-page";
import { addBulkDropdownButton } from "discourse/components/bulk-select-topics-dropdown";
import { addCardClickListenerSelector } from "discourse/components/card-contents-base";
@@ -11,13 +10,17 @@ import {
} from "discourse/components/composer-editor";
import { addPluginDocumentTitleCounter } from "discourse/components/d-document";
import { addToolbarCallback } from "discourse/components/d-editor";
+import {
+ NON_STREAM_HTML_DECORATOR,
+ registerHtmlDecorator,
+} from "discourse/components/decorated-html";
import { forceDropdownForMenuPanels as glimmerForceDropdownForMenuPanels } from "discourse/components/glimmer-site-header";
import { addGlobalNotice } from "discourse/components/global-notice";
import { headerButtonsDAG } from "discourse/components/header";
import { headerIconsDAG } from "discourse/components/header/icons";
import { registeredTabs } from "discourse/components/more-topics";
-import { addWidgetCleanCallback } from "discourse/components/mount-widget";
import { addPluginOutletDecorator } from "discourse/components/plugin-connector";
+import { STREAM_HTML_DECORATOR } from "discourse/components/post/cooked-html";
import { addGroupPostSmallActionCode } from "discourse/components/post/small-action";
import {
addPluginReviewableParam,
@@ -56,7 +59,7 @@ import classPrepend, {
} from "discourse/lib/class-prepend";
import { addPopupMenuOption } from "discourse/lib/composer/custom-popup-menu-options";
import { registerRichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";
-import deprecated, { withSilencedDeprecations } from "discourse/lib/deprecated";
+import deprecated from "discourse/lib/deprecated";
import { registerDesktopNotificationHandler } from "discourse/lib/desktop-notifications";
import { downloadCalendar } from "discourse/lib/download-calendar";
import { isTesting } from "discourse/lib/environment";
@@ -67,11 +70,7 @@ import {
registerHighlightJSLanguage,
registerHighlightJSPlugin,
} from "discourse/lib/highlight-syntax";
-import {
- iconNode,
- registerIconRenderer,
- replaceIcon,
-} from "discourse/lib/icon-library";
+import { registerIconRenderer, replaceIcon } from "discourse/lib/icon-library";
import { registerModelTransformer } from "discourse/lib/model-transformers";
import { registerNotificationTypeRenderer } from "discourse/lib/notification-types-manager";
import { addGTMPageChangedCallback } from "discourse/lib/page-tracker";
@@ -102,7 +101,6 @@ import {
} from "discourse/lib/sidebar/user/categories-section/category-section-link";
import { registerCustomTagSectionLinkPrefixIcon } from "discourse/lib/sidebar/user/tags-section/base-tag-section-link";
import { consolePrefix } from "discourse/lib/source-identifier";
-import { includeAttributes } from "discourse/lib/transform-post";
import {
_addTransformerName,
_registerTransformer,
@@ -128,64 +126,9 @@ import { CUSTOM_USER_SEARCH_OPTIONS } from "discourse/select-kit/components/user
import { modifySelectKit } from "discourse/select-kit/lib/plugin-api";
import { addComposerSaveErrorCallback } from "discourse/services/composer";
import { disableDefaultKeyboardShortcuts } from "discourse/services/keyboard-shortcuts";
-import { addPostClassesCallback } from "discourse/widgets/post";
-import { addDecorator } from "discourse/widgets/post-cooked";
-import {
- addPostSmallActionClassesCallback,
- addPostSmallActionIcon,
-} from "discourse/widgets/post-small-action";
-import {
- addPostTransformCallback,
- preventCloak,
-} from "discourse/widgets/post-stream";
-import { disableNameSuppression } from "discourse/widgets/poster-name";
-import {
- changeSetting,
- createWidget,
- decorateWidget,
- POST_STREAM_DEPRECATION_OPTIONS,
- queryRegistry,
- reopenWidget,
- warnWidgetsDeprecation,
-} from "discourse/widgets/widget";
+import { warnWidgetsDecommissioned } from "discourse/widgets/widget";
import { addImageWrapperButton } from "discourse-markdown-it/features/image-controls";
-const DEPRECATED_POST_STREAM_CLASSES = ["component:scrolling-post-stream"];
-
-const DEPRECATED_POST_STREAM_WIDGETS = [
- "actions-summary",
- "avatar-flair",
- "embedded-post",
- "expand-hidden",
- "expand-post-button",
- "filter-jump-to-post",
- "filter-show-all",
- "post-article",
- "post-article",
- "post-avatar-user-info",
- "post-avatar",
- "post-body",
- "post-contents",
- "post-date",
- "post-edits-indicator",
- "post-email-indicator",
- "post-gap",
- "post-group-request",
- "post-links",
- "post-locked-indicator",
- "post-meta-data",
- "post-notice",
- "post-placeholder",
- "post-stream",
- "post",
- "poster-name",
- "poster-name-title",
- "posts-filtered-notice",
- "reply-to-tab",
- "select-post",
- "topic-post-visited-line",
-];
-
const blockedModifications = ["component:topic-list"];
const appliedModificationIds = new WeakMap();
@@ -241,7 +184,7 @@ function wrapWithErrorHandler(func, messageKey) {
class _PluginApi {
constructor(container) {
this.container = container;
- this.h = h;
+ this.h = warnWidgetsDecommissioned;
}
/**
@@ -545,16 +488,17 @@ class _PluginApi {
* },
*
* // for the places in code that render virtual dom elements
- * node() {
- * return h("svg", {
- * attributes: { class: "fa d-icon d-icon-far-face-smile", "aria-hidden": true },
- * namespace: "http://www.w3.org/2000/svg"
- * },[
- * h("use", {
- * "href": attributeHook("http://www.w3.org/1999/xlink", `#far-face-smile`),
- * namespace: "http://www.w3.org/2000/svg"
- * })]
- * );
+ * element() {
+ * const svgElement = document.createElementNS(SVG_NAMESPACE, "svg");
+ * svgElement.setAttribute("class", "fa d-icon d-icon-far-face-smile");
+ * svgElement.setAttribute("aria-hidden", true);
+ *
+ * const useElement = document.createElementNS(SVG_NAMESPACE, "use");
+ * useElement.setAttribute("href", `#far-face-smile`);
+ *
+ * svgElement.appendChild(useElement);
+ *
+ * return svgElement;
* }
* });
**/
@@ -589,29 +533,59 @@ class _PluginApi {
}
/**
- * Used for decorating the `cooked` content of a post after it is rendered
+ * Used for decorating the `cooked` content of a post after it is rendered.
*
- * `callback` will be called when it is time to decorate with an DOM node.
+ * @param {Function} callback - Function called to decorate a DOM node.
+ * For stream-only decorators, this callback can return
+ * a cleanup function that will be executed when decorated content is rerendered/removed.
+ * The callback receives two parameters:
*
- * Use `options.onlyStream` if you only want to decorate posts within a topic,
- * and not in other places like the user stream.
+ * 1. element: HTMLElement to be decorated
+ * 2. decoratorHelper: Object containing helper methods for the decorator
*
- * For example, to add a yellow background to all posts you could do this:
+ * @param {Object} [opts] - Optional configuration object
+ * @param {boolean} [opts.onlyStream=false] - If true, only decorate posts within a post stream.
*
- * ```
+ * @example
+ * // Add a yellow background to the decorated element
* api.decorateCookedElement(
- * elem => { elem.style.backgroundColor = 'yellow' }
+ * elem => {
+ * elem.style.backgroundColor = 'yellow';
+ * // Optionally return a cleanup function
+ * return () => elem.style.backgroundColor = '';
+ * }
* );
- * ```
- **/
+ *
+ * @example
+ * // Only decorate posts in the post-stream
+ * api.decorateCookedElement(
+ * elem => { elem.classList.add('topic-post'); },
+ * { onlyStream: true }
+ * );
+ *
+ * @example
+ * // Using the decorator helper
+ * api.decorateCookedElement(
+ * (elem, helper) => {
+ * const post = helper.model; // Get associated post model
+ * if (post.firstPost) {
+ * elem.classList.add('first-post');
+ * }
+ * }
+ * );
+ */
decorateCookedElement(callback, opts) {
opts = opts || {};
callback = wrapWithErrorHandler(callback, "broken_decorator_alert");
- addDecorator(callback);
+ registerHtmlDecorator(
+ callback,
+ opts.onlyStream ? STREAM_HTML_DECORATOR : NON_STREAM_HTML_DECORATOR
+ );
- this.onAppEvent("decorate-post-cooked-element", callback);
+ // for backwards compatibility with plugins/themes decorating cooked elements
+ // using the app events
if (!opts.onlyStream) {
this.onAppEvent("decorate-non-stream-cooked-element", callback);
}
@@ -704,133 +678,20 @@ class _PluginApi {
return makeArray(value).concat(definitions).filter(Boolean);
}
);
-
- // TODO (glimmer-post-stream): remove the fallback when removing the legacy post stream code
- withSilencedDeprecations(POST_STREAM_DEPRECATION_OPTIONS.id, () => {
- const decoratorFor = (view) => (dec) => {
- const currentView = this.container.lookup("service:site").mobileView
- ? "mobile"
- : "desktop";
-
- if (view !== currentView) {
- return;
- }
-
- const attrs = dec.attrs;
- let results = cb(attrs.userCustomFields || {}, attrs);
-
- if (results) {
- if (!Array.isArray(results)) {
- results = [results];
- }
-
- return results.map((result) => {
- let iconBody;
-
- if (result.icon) {
- iconBody = iconNode(result.icon);
- } else if (result.emoji) {
- iconBody = result.emoji.split("|").map((name) => {
- let widgetAttrs = { name };
- if (result.emojiTitle) {
- widgetAttrs.title = true;
- }
- return dec.attach("emoji", widgetAttrs);
- });
- }
-
- if (result.text) {
- iconBody = [iconBody, result.text];
- }
-
- if (result.url) {
- iconBody = dec.h(
- "a",
- { attributes: { href: result.url } },
- iconBody
- );
- }
-
- return dec.h(
- "span.poster-icon",
- {
- className: result.className,
- attributes: { title: result.title },
- },
- iconBody
- );
- });
- }
- };
-
- decorateWidget(`poster-name:before`, decoratorFor("mobile"));
- decorateWidget(`poster-name:after`, decoratorFor("desktop"));
- });
}
/**
- * The main interface for extending widgets with additional HTML.
- *
- * The `name` you pass it should be the name of the widget and a type
- * for the decorator. All widgets support `before` and `after` types.
- *
- * Example:
- *
- * ```
- * api.decorateWidget('post:after', () => {
- * return "I am displayed after every post!";
- * });
- * ```
- *
- * Your decorator will be called with an instance of a `DecoratorHelper`
- * object, which provides methods you can use to build more interesting
- * formatting.
- *
- * ```
- * api.decorateWidget('post:after', helper => {
- * return helper.h('p.fancy', `I'm an HTML paragraph on post with id ${helper.attrs.id}`);
- * });
- *
- * (View the source for `DecoratorHelper` for more helper methods you
- * can use in your plugin decorators.)
- *
- **/
- decorateWidget(name, fn) {
- const widgetName = name.split(":")[0];
- this.#deprecatedWidgetOverride(widgetName, "decorateWidget");
-
- decorateWidget(name, fn);
+ * @deprecated the widget rendering system was decommissioned
+ */
+ decorateWidget() {
+ warnWidgetsDecommissioned();
}
/**
- * Adds a new action to a widget that already exists. You can use this to
- * add additional functionality from your plugin.
- *
- * Example:
- *
- * ```
- * api.attachWidgetAction('post', 'annoyMe', () => {
- * alert('ANNOYED!');
- * });
- * ```
- **/
- attachWidgetAction(widget, actionName, fn) {
- const widgetClass =
- queryRegistry(widget) ||
- this.container.factoryFor(`widget:${widget}`)?.class;
-
- if (!widgetClass) {
- // eslint-disable-next-line no-console
- console.error(
- consolePrefix(),
- `attachWidgetAction: Could not find widget ${widget} in registry`
- );
- return;
- }
-
- this.#deprecatedWidgetOverride(widget, "attachWidgetAction");
-
- widgetClass.prototype[actionName] = fn;
+ * @deprecated the widget rendering system was decommissioned
+ */
+ attachWidgetAction() {
+ warnWidgetsDecommissioned();
}
/**
@@ -839,10 +700,6 @@ class _PluginApi {
* This function is now an alias to `api.addTrackedPostProperties`.
* Use that function instead.
*
- * Add more attributes to the Post's `attrs` object passed through to widgets.
- * You'll need to do this if you've added attributes to the serializer for a
- * Post and want to use them when you're rendering.
- *
* Example:
*
* ```
@@ -852,12 +709,12 @@ class _PluginApi {
*
**/
includePostAttributes(...attributes) {
- // TODO (glimmer-post-stream): we can keep this function as an alias to addTrackedPostProperties but it is useful to
- // deprecate it for now to get warnings for code that is incompatible with the Glimmer Post Stream because if an
- // extension is using it, then it is very likely that there is other code that is incompatible
deprecated(
"`api.includePostAttributes` has been deprecated. Use `api.addTrackedPostProperties` instead.",
- POST_STREAM_DEPRECATION_OPTIONS
+ {
+ since: "v3.5.0.beta1-dev",
+ url: "https://meta.discourse.org/t/372063/1",
+ }
);
this.addTrackedPostProperties(...attributes);
@@ -868,17 +725,13 @@ class _PluginApi {
*
* This method is used to mark properties as tracked for post updates.
*
- * It will also add the properties to the list of Post's attributes passed to
- * widgets.
- *
- * You'll need to do this if you've added properties to a Post and want to use
- * them when you're rendering.
+ * You'll need to do this if you've added properties to a Post and need them to be
+ * automatically updated in the UI when there are changes in the model.
*
* @param {...string} names - The names of the properties to be tracked.
*/
addTrackedPostProperties(...names) {
names.forEach((name) => _addTrackedPostProperty(name));
- includeAttributes(...names); // compatibility with widget's attributes
}
/**
@@ -1030,13 +883,10 @@ class _PluginApi {
}
/**
- * A hook that is called when the post stream is removed from the DOM.
- * This advanced hook should be used if you end up wiring up any
- * events that need to be torn down when the user leaves the topic
- * page.
- **/
- cleanupStream(fn) {
- addWidgetCleanCallback("post-stream", fn);
+ * @deprecated the widget rendering system was decommissioned
+ */
+ cleanupStream() {
+ warnWidgetsDecommissioned();
}
/**
@@ -1095,7 +945,6 @@ class _PluginApi {
* This allows you to override core behavior
**/
disableNameSuppressionOnPosts() {
- disableNameSuppression();
this.registerValueTransformer(
"post-meta-data-poster-name-suppress-similar-name",
() => true
@@ -1137,17 +986,10 @@ class _PluginApi {
}
/**
- * Changes a setting associated with a widget. For example, if
- * you wanted small avatars in the post stream:
- *
- * ```javascript
- * api.changeWidgetSetting('post-avatar', 'size', 'small');
- * ```
- *
- **/
- changeWidgetSetting(widgetName, settingName, newValue) {
- this.#deprecatedWidgetOverride(widgetName, "changeWidgetSetting");
- changeSetting(widgetName, settingName, newValue);
+ * @deprecated the widget rendering system was decommissioned
+ */
+ changeWidgetSetting() {
+ warnWidgetsDecommissioned();
}
/**
@@ -1168,29 +1010,21 @@ class _PluginApi {
* ```
**/
preventCloak(postId, prevent = true) {
- // TODO (glimmer-post-stream) remove the call to the widget version of preventCloak below
- preventCloak(postId); // widgets
- preventCloaking(postId, prevent); // glimmer-post-stream
+ preventCloaking(postId, prevent);
}
/**
- * Exposes the widget creating ability to plugins. Plugins can
- * register their own widgets and attach them with decorators.
- * See `createWidget` in `discourse/widgets/widget` for more info.
- **/
- createWidget(name, args) {
- return createWidget(name, args);
+ * @deprecated the widget rendering system was decommissioned
+ */
+ createWidget() {
+ warnWidgetsDecommissioned();
}
/**
- * Exposes the widget update ability to plugins. Updates the widget
- * registry for the given widget name to include the properties on args
- * See `reopenWidget` in `discourse/widgets/widget` from more info.
- **/
-
- reopenWidget(name, args) {
- this.#deprecatedWidgetOverride(name, "reopenWidget");
- return reopenWidget(name, args);
+ * @deprecated the widget rendering system was decommissioned
+ */
+ reopenWidget() {
+ warnWidgetsDecommissioned();
}
addFlagProperty() {
@@ -1201,21 +1035,8 @@ class _PluginApi {
}
/**
- * Adds a panel to the header
- *
- * takes a widget name, a value to toggle on, and a function which returns the attrs for the widget
- * Example:
- * ```javascript
- * api.addHeaderPanel('widget-name', 'widgetVisible', function(attrs, state) {
- * return { name: attrs.name, description: state.description };
- * });
- * ```
- * 'toggle' is an attribute on the state of the header widget,
- *
- * 'transformAttrs' is a function which is passed the current attrs and state of the widget,
- * and returns a hash of values to pass to attach
- *
- **/
+ * @deprecated Use `api.headerIcons` instead.
+ */
addHeaderPanel() {
// eslint-disable-next-line no-console
console.error(
@@ -1416,9 +1237,6 @@ class _PluginApi {
"post-small-action-icon",
({ value, context: { code } }) => (key === code ? icon : value)
);
-
- // TODO (glimmer-post-stream): remove the fallback when removing the legacy post stream code
- addPostSmallActionIcon(key, icon);
}
/**
@@ -1452,9 +1270,6 @@ class _PluginApi {
...makeArray(callback(post)),
]
);
-
- // TODO (glimmer-post-stream): remove the fallback when removing the legacy post stream code
- addPostSmallActionClassesCallback(callback);
}
/**
@@ -1522,9 +1337,6 @@ class _PluginApi {
...makeArray(callback(post)),
]
);
-
- // TODO (glimmer-post-stream): remove the fallback when removing the legacy post stream code
- addPostClassesCallback(callback);
}
/**
@@ -1567,26 +1379,10 @@ class _PluginApi {
}
/**
- *
- * Adds a callback to be executed on the "transformed" post that is passed to the post
- * widget.
- *
- * This allows you to apply transformations on the actual post that is about to be rendered.
- *
- * Example:
- *
- * addPostTransformCallback((t)=>{
- * // post number 7 is overrated, don't show it ever
- * if (t.post_number === 7) { t.cooked = ""; }
- * })
+ * @deprecated the widget rendering system was decommissioned
*/
- addPostTransformCallback(callback) {
- deprecated(
- "`api.addPostTransformCallback` has been deprecated.",
- POST_STREAM_DEPRECATION_OPTIONS
- );
-
- addPostTransformCallback(callback);
+ addPostTransformCallback() {
+ warnWidgetsDecommissioned();
}
/**
@@ -2182,15 +1978,8 @@ class _PluginApi {
}
/**
- * Adds a widget to the header-icon ul. The widget must already be created. You can create new widgets
- * in a theme or plugin via an initializer prior to calling this function.
- *
- * ```
- * api.addToHeaderIcons(
- * createWidget("some-widget")
- * ```
- *
- **/
+ * @deprecated Use `api.headerIcons` instead
+ */
// eslint-disable-next-line no-unused-vars
addToHeaderIcons(icon) {
// eslint-disable-next-line no-console
@@ -2466,7 +2255,7 @@ class _PluginApi {
}
/**
- * Add a function to be called when there is a keyDown even on the search-menu widget.
+ * Add a function to be called when there is a keyDown even on the search-menu.
* This function runs before the default logic, and if one callback returns a falsey value
* the logic chain will stop, to prevent the core behavior from occurring.
*
@@ -2541,31 +2330,10 @@ class _PluginApi {
}
/**
- * Calls a method on a mounted widget whenever an app event happens.
- *
- * For example, if you have a widget with a `key` of `cool-widget` that lives inside the
- * `site-header` component, and you wanted it to respond to `thing:happened`, you could do this:
- *
- * ```
- * api.dispatchWidgetAppEvent('site-header', 'cool-widget', 'thing:happened');
- * ```
- *
- * In this case, the `cool-widget` must have a method called `thingHappened`. The event name
- * is converted to camelCase and used as the method name for you.
+ * @deprecated the widget rendering system was decommissioned
*/
- dispatchWidgetAppEvent(mountedComponent, widgetKey, appEvent) {
- this.modifyClass(
- `component:${mountedComponent}`,
- {
- pluginId: `${mountedComponent}/${widgetKey}/${appEvent}`,
-
- didInsertElement() {
- this._super();
- this.dispatch(appEvent, widgetKey);
- },
- },
- { ignoreMissing: true }
- );
+ dispatchWidgetAppEvent() {
+ warnWidgetsDecommissioned();
}
/**
@@ -3421,39 +3189,17 @@ class _PluginApi {
_addCategoryPropertyForSave(property);
}
+ // eslint-disable-next-line no-unused-vars
#deprecateModifyClass(className) {
- if (DEPRECATED_POST_STREAM_CLASSES.includes(className)) {
- deprecated(
- `Using api.modifyClass for \`${className}\` has been deprecated and is no longer a supported override.`,
- POST_STREAM_DEPRECATION_OPTIONS
- );
- }
- }
-
- #deprecatedWidgetOverride(widgetName, override) {
- // insert here the code to handle widget deprecations, e.g. for the header widgets we used:
- // if (DEPRECATED_HEADER_WIDGETS.includes(widgetName)) {
- // this.container.lookup("service:header").anyWidgetHeaderOverrides = true;
+ // display notification messages for deprecated classes
+ // e.g:
+ //
+ // if (DEPRECATED_CLASSES.includes(className)) {
// deprecated(
- // `The ${widgetName} widget has been deprecated and ${override} is no longer a supported override.`,
- // {
- // since: "v3.3.0.beta1-dev",
- // id: "discourse.header-widget-overrides",
- // url: "https://meta.discourse.org/t/316549",
- // }
+ // `Using api.modifyClass for \`${className}\` has been deprecated and is no longer a supported override.`,
+ // DEPRECATION_OPTIONS
// );
// }
-
- if (DEPRECATED_POST_STREAM_WIDGETS.includes(widgetName)) {
- deprecated(
- `The \`${widgetName}\` widget has been deprecated and \`api.${override}\` is no longer a supported override.`,
- POST_STREAM_DEPRECATION_OPTIONS
- );
- } else {
- warnWidgetsDeprecation(
- `Using \`api.${override}\` is deprecated and will soon stop working. Affected widget: ${widgetName}.`
- );
- }
}
}
diff --git a/frontend/discourse/app/lib/post-bookmark-manager.js b/frontend/discourse/app/lib/post-bookmark-manager.js
index 5ae76104b89..057666952eb 100644
--- a/frontend/discourse/app/lib/post-bookmark-manager.js
+++ b/frontend/discourse/app/lib/post-bookmark-manager.js
@@ -2,10 +2,6 @@ import { tracked } from "@glimmer/tracking";
import { inject as controller } from "@ember/controller";
import { setOwner } from "@ember/owner";
import { service } from "@ember/service";
-import {
- CLOSE_INITIATED_BY_BUTTON,
- CLOSE_INITIATED_BY_ESC,
-} from "discourse/components/d-modal";
import { BookmarkFormData } from "discourse/lib/bookmark-form-data";
import Bookmark from "discourse/models/bookmark";
@@ -47,20 +43,8 @@ export default class PostBookmarkManager {
return this.bookmarkApi.update(this.trackedBookmark);
}
- afterModalClose(closeData) {
- if (!closeData) {
- return;
- }
-
- if (
- closeData.closeWithoutSaving ||
- closeData.initiatedBy === CLOSE_INITIATED_BY_ESC ||
- closeData.initiatedBy === CLOSE_INITIATED_BY_BUTTON
- ) {
- this.model.appEvents.trigger("post-stream:refresh", {
- id: this.model.id,
- });
- }
+ afterModalClose() {
+ // no-op
}
afterSave(bookmarkFormData) {
diff --git a/frontend/discourse/app/lib/render-topic-featured-link.js b/frontend/discourse/app/lib/render-topic-featured-link.js
index 008092d7f27..9db3b2f4221 100644
--- a/frontend/discourse/app/lib/render-topic-featured-link.js
+++ b/frontend/discourse/app/lib/render-topic-featured-link.js
@@ -1,4 +1,3 @@
-import { h } from "virtual-dom";
import { renderIcon } from "discourse/lib/icon-library";
import User from "discourse/models/user";
@@ -54,16 +53,3 @@ export default function renderTopicFeaturedLink(topic) {
return "";
}
}
-// deprecated per components/header/topic/featured-link.gjs
-export function topicFeaturedLinkNode(topic) {
- const meta = extractLinkMeta(topic);
- if (meta) {
- return h(
- "a.topic-featured-link",
- {
- attributes: { href: meta.href, rel: meta.rel, target: meta.target },
- },
- [renderIcon("node", "up-right-from-square"), meta.domain]
- );
- }
-}
diff --git a/frontend/discourse/app/lib/transform-post.js b/frontend/discourse/app/lib/transform-post.js
index 82d5a1f7f55..6d8233e666d 100644
--- a/frontend/discourse/app/lib/transform-post.js
+++ b/frontend/discourse/app/lib/transform-post.js
@@ -1,255 +1,12 @@
-import { isEmpty } from "@ember/utils";
-import getURL from "discourse/lib/get-url";
-import { userPath } from "discourse/lib/url";
-import Badge from "discourse/models/badge";
-
-const _additionalAttributes = new Set();
-
-export function includeAttributes(...attributes) {
- attributes.forEach((a) => _additionalAttributes.add(a));
-}
-
-export function transformBasicPost(post) {
- // Note: it can be dangerous to not use `get` in Ember code, but this is significantly
- // faster and has tests to confirm it works. We only call `get` when the property is a CP
- const postAtts = {
- id: post.id,
- hidden: post.hidden,
- deleted: post.get("deleted"),
- deleted_at: post.deleted_at,
- user_deleted: post.user_deleted,
- isDeleted: post.deleted,
- deletedByAvatarTemplate: null,
- deletedByUsername: null,
- primary_group_name: post.primary_group_name,
- flair_name: post.flair_name,
- flair_url: post.flair_url,
- flair_bg_color: post.flair_bg_color,
- flair_color: post.flair_color,
- flair_group_id: post.flair_group_id,
- wiki: post.wiki,
- lastWikiEdit: post.last_wiki_edit,
- firstPost: post.post_number === 1,
- post_number: post.post_number,
- cooked: post.cooked,
- via_email: post.via_email,
- isAutoGenerated: post.is_auto_generated,
- user_id: post.user_id,
- usernameUrl: userPath(post.username),
- username: post.username,
- badgesGranted: post.badges_granted?.map(
- (badge) => Badge.createFromJson(badge)[0]
- ),
- avatar_template: post.avatar_template,
- bookmarked: post.bookmarked,
- bookmarkReminderAt: post.bookmark_reminder_at,
- bookmarkName: post.bookmark_name,
- yours: post.yours,
- shareUrl: post.get("shareUrl"),
- staff: post.staff,
- admin: post.admin,
- moderator: post.moderator,
- groupModerator: post.group_moderator,
- new_user: post.trust_level === 0,
- name: post.name,
- user_title: post.user_title,
- title_is_group: post.title_is_group,
- created_at: post.created_at,
- updated_at: post.updated_at,
- canDelete: post.can_delete,
- canPermanentlyDelete: false,
- showFlagDelete: false,
- canRecover: post.can_recover,
- canSeeHiddenPost: post.can_see_hidden_post,
- canEdit: post.can_edit,
- canFlag: !post.get("topic.deleted") && !isEmpty(post.get("flagsAvailable")),
- canReviewTopic: false,
- reviewableId: post.reviewable_id,
- reviewableScoreCount: post.reviewable_score_count,
- reviewableScorePendingCount: post.reviewable_score_pending_count,
- version: post.version,
- canRecoverTopic: false,
- canDeleteTopic: false,
- canViewEditHistory: post.can_view_edit_history,
- canWiki: post.can_wiki,
- showLike: false,
- liked: false,
- canToggleLike: false,
- likeCount: false,
- actionsSummary: null,
- read: post.read,
- replyToUsername: null,
- replyToName: null,
- replyToAvatarTemplate: null,
- reply_to_post_number: post.reply_to_post_number,
- cooked_hidden: !!post.cooked_hidden,
- expandablePost: false,
- replyCount: post.reply_count,
- locked: post.locked,
- userCustomFields: post.user_custom_fields,
- readCount: post.readers_count,
- canPublishPage: false,
- trustLevel: post.trust_level,
- userSuspended: post.user_suspended,
- locale: post.locale,
- is_localized: post.is_localized,
- language: post.language,
- localization_outdated: post.localization_outdated,
- };
-
- _additionalAttributes.forEach((a) => (postAtts[a] = post[a]));
-
- return postAtts;
-}
-
-export default function transformPost(
- currentUser,
- site,
- post,
- prevPost,
- nextPost
-) {
- // Note: it can be dangerous to not use `get` in Ember code, but this is significantly
- // faster and has tests to confirm it works. We only call `get` when the property is a CP
- const postType = post.post_type;
- const postTypes = site.post_types;
- const topic = post.topic;
- const details = topic.get("details");
- const filteredUpwardsPostID = topic.get("postStream.filterUpwardsPostID");
- const filteredRepliesPostNumber = topic.get(
- "postStream.filterRepliesToPostNumber"
- );
-
- const postAtts = transformBasicPost(post);
-
- const createdBy = details.created_by || {};
-
- postAtts.topic = topic;
- postAtts.topicId = topic.id;
- postAtts.topicOwner = createdBy.id === post.user_id;
- postAtts.topicCreatedById = createdBy.id;
- postAtts.post_type = postType;
- postAtts.via_email = post.via_email;
- postAtts.isAutoGenerated = post.is_auto_generated;
- postAtts.isModeratorAction = post.isModeratorAction;
- postAtts.isWhisper = post.isWhisper;
- postAtts.isSmallAction =
- postType === postTypes.small_action || post.action_code === "split_topic";
- postAtts.canBookmark = !!currentUser;
- postAtts.canManage = post.canManage;
- postAtts.canViewRawEmail = currentUser && currentUser.can_view_raw_email;
- postAtts.canArchiveTopic = !!details.can_archive_topic;
- postAtts.canCloseTopic = !!details.can_close_topic;
- postAtts.canSplitMergeTopic = !!details.can_split_merge_topic;
- postAtts.canEditStaffNotes = post.canEditStaffNotes;
- postAtts.canReplyAsNewTopic = !!details.can_reply_as_new_topic;
- postAtts.canReviewTopic = !!details.can_review_topic;
- postAtts.canPublishPage = post.canPublishPage;
- postAtts.isWarning = topic.is_warning;
- postAtts.links = post.get("internalLinks");
-
- // on the glimmer post menu this logic was implemented on the PostMenu component as it depends on
- // two post object instances
- // if you change the logic replyDirectlyBelow here, while the widget post menu is still around, please
- // be sure to also update the logic on the Glimmer PostMenu component
- postAtts.replyDirectlyBelow =
- nextPost &&
- nextPost.reply_to_post_number === post.post_number &&
- post.post_number !== filteredRepliesPostNumber;
-
- postAtts.replyDirectlyAbove =
- prevPost &&
- post.id !== filteredUpwardsPostID &&
- post.reply_to_post_number === prevPost.post_number;
- postAtts.linkCounts = post.link_counts;
- postAtts.actionCode = post.action_code;
- postAtts.actionCodeWho = post.action_code_who;
- postAtts.actionCodePath = getURL(post.action_code_path || `/t/${topic.id}`);
- postAtts.topicUrl = topic.get("url");
- postAtts.isSaving = post.isSaving;
- postAtts.staged = post.staged;
- postAtts.user = post.user;
-
- if (post.notice) {
- postAtts.notice = post.notice;
- postAtts.noticeCreatedByUser = post.notice_created_by_user;
- if (postAtts.notice.type === "returning_user") {
- postAtts.notice.lastPostedAt = new Date(post.notice.last_posted_at);
- }
- }
-
- if (post.post_number === 1 && topic.requested_group_name) {
- postAtts.requestedGroupName = topic.requested_group_name;
- }
-
- if (postAtts.isDeleted) {
- postAtts.deletedByAvatarTemplate = post.get("deletedBy.avatar_template");
- postAtts.deletedByUsername = post.get("deletedBy.username");
- }
-
- const replyToUser = post.get("reply_to_user");
- if (replyToUser) {
- postAtts.replyToUsername = replyToUser.username;
- postAtts.replyToName = replyToUser.name;
- postAtts.replyToAvatarTemplate = replyToUser.avatar_template;
- }
-
- if (post.actions_summary) {
- postAtts.actionsSummary = post.actions_summary
- .filter((a) => {
- return a.actionType.name_key !== "like" && a.acted;
- })
- .map((a) => {
- return {
- id: a.id,
- postId: post.id,
- action: a.actionType.name_key,
- canUndo: a.can_undo,
- description: a.actionType.translatedDescription,
- };
- });
- }
-
- postAtts.liked = post.liked;
-
- const likeAction = post.likeAction;
- if (likeAction) {
- postAtts.canToggleLike = likeAction.get("canToggle");
- postAtts.showLike = postAtts.liked || postAtts.canToggleLike;
- postAtts.likeCount = likeAction.count;
- } else if (
- !currentUser ||
- (topic.archived && topic.user_id !== currentUser.id)
- ) {
- postAtts.showLike = true;
- }
-
- postAtts.canDelete = post.canDelete;
- postAtts.canDeleteTopic = post.canDeleteTopic;
- postAtts.canPermanentlyDelete = post.canPermanentlyDelete;
- postAtts.canRecover = post.canRecover;
- postAtts.canRecoverTopic = post.canRecoverTopic;
-
- if (postAtts.post_number === 1) {
- postAtts.expandablePost = topic.expandable_first_post;
-
- // Show a "Flag to delete" message if not staff and you can't
- // otherwise delete it.
- postAtts.showFlagDelete =
- !postAtts.canDelete &&
- postAtts.yours &&
- postAtts.canFlag &&
- currentUser &&
- !currentUser.staff;
- } else {
- postAtts.canDelete =
- postAtts.canDelete &&
- !post.deleted_at &&
- currentUser &&
- (currentUser.staff || !post.user_deleted);
- }
-
- _additionalAttributes.forEach((a) => (postAtts[a] = post[a]));
-
- return postAtts;
-}
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export {
+ warnWidgetsDecommissioned as includeAttributes,
+ warnWidgetsDecommissioned as transformBasicPost,
+ warnWidgetsDecommissioned as transformPost,
+} from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/loader-shims.js b/frontend/discourse/app/loader-shims.js
index f172d17c981..d1c0040e791 100644
--- a/frontend/discourse/app/loader-shims.js
+++ b/frontend/discourse/app/loader-shims.js
@@ -124,5 +124,5 @@ loaderShim("truth-helpers/helpers/not", () =>
loaderShim("truth-helpers/helpers/or", () =>
importSync("truth-helpers/helpers/or")
);
-loaderShim("virtual-dom", () => importSync("virtual-dom"));
+loaderShim("virtual-dom", () => importSync("discourse/widgets/virtual-dom"));
loaderShim("xss", () => importSync("xss"));
diff --git a/frontend/discourse/app/models/action-summary.js b/frontend/discourse/app/models/action-summary.js
index 21904ac115d..3b8ce55cbb6 100644
--- a/frontend/discourse/app/models/action-summary.js
+++ b/frontend/discourse/app/models/action-summary.js
@@ -3,7 +3,6 @@ import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import RestModel from "discourse/models/rest";
-// TODO (glimmer-post-stream) is this model still used?
export default class ActionSummary extends RestModel {
@or("can_undo", "can_act") canToggle;
diff --git a/frontend/discourse/app/models/composer.js b/frontend/discourse/app/models/composer.js
index cc3759ab5fa..a7bde2beca3 100644
--- a/frontend/discourse/app/models/composer.js
+++ b/frontend/discourse/app/models/composer.js
@@ -1137,8 +1137,6 @@ export default class Composer extends RestModel {
const cooked = this.getCookedHtml();
post.setProperties({ cooked, staged: true });
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { id: post.id });
return promise
.then(() => {
@@ -1150,8 +1148,6 @@ export default class Composer extends RestModel {
.catch(rollback)
.finally(() => {
post.set("staged", false);
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { id: post.id });
});
}
diff --git a/frontend/discourse/app/models/post-stream.js b/frontend/discourse/app/models/post-stream.js
index c6467604486..dd953a6050f 100644
--- a/frontend/discourse/app/models/post-stream.js
+++ b/frontend/discourse/app/models/post-stream.js
@@ -289,9 +289,6 @@ export default class PostStream extends RestModel {
? element.getBoundingClientRect().top
: null;
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh");
-
DiscourseURL.jumpToPost(postNumber, {
originalTopOffset,
});
@@ -310,9 +307,6 @@ export default class PostStream extends RestModel {
post_id: postID,
});
return this.refresh({ refreshInPlace: true }).then(() => {
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh");
-
if (this.posts && this.posts.length > 1) {
const postNumber = this.posts[1].post_number;
DiscourseURL.jumpToPost(postNumber, { skipIfOnScreen: true });
@@ -448,9 +442,6 @@ export default class PostStream extends RestModel {
}
gapExpanded() {
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh");
-
// resets the reply count in posts-filtered-notice
// because once a gap has been expanded that count is no longer exact
if (this.streamFilters && this.streamFilters.replies_to_post_number) {
diff --git a/frontend/discourse/app/models/post.js b/frontend/discourse/app/models/post.js
index 1ab1a1c9262..71545da5515 100644
--- a/frontend/discourse/app/models/post.js
+++ b/frontend/discourse/app/models/post.js
@@ -226,8 +226,6 @@ export default class Post extends RestModel {
@or("deleted_at", "user_deleted") recoverable; // post or content still can be recovered
@propertyEqual("topic.details.created_by.id", "user_id") topicOwner;
@alias("topic.details.created_by.id") topicCreatedById;
- @alias("deletedBy") postDeletedBy; // TODO (glimmer-post-stream): check if this alias can be removed after removing the widget code
- @alias("deletedAt") postDeletedAt; // TODO (glimmer-post-stream): check if this alias can be removed after removing the widget code
constructor() {
super(...arguments);
@@ -691,8 +689,6 @@ export default class Post extends RestModel {
target: "post",
targetId: this.id,
});
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { id: this.id });
}
deleteBookmark(bookmarked) {
diff --git a/frontend/discourse/app/models/site.js b/frontend/discourse/app/models/site.js
index fefdfd7c3fc..dce81475b65 100644
--- a/frontend/discourse/app/models/site.js
+++ b/frontend/discourse/app/models/site.js
@@ -18,7 +18,6 @@ import Category from "discourse/models/category";
import PostActionType from "discourse/models/post-action-type";
import RestModel from "discourse/models/rest";
import TrustLevel from "discourse/models/trust-level";
-import { havePostStreamWidgetExtensions } from "discourse/widgets/post-stream";
@singleton
export default class Site extends RestModel {
@@ -83,7 +82,6 @@ export default class Site extends RestModel {
}
@service siteSettings;
- @service currentUser;
@service capabilities;
@trackedArray categories;
@@ -92,7 +90,6 @@ export default class Site extends RestModel {
@sort("categories", "topicCountDesc") categoriesByCount;
- #glimmerPostStreamEnabled;
#siteInitialized = false;
init() {
@@ -163,71 +160,6 @@ export default class Site extends RestModel {
return this.mobileView;
}
- get useGlimmerPostStream() {
- if (this.#glimmerPostStreamEnabled !== undefined) {
- // Use cached value after the first call to prevent duplicate messages in the console
- return this.#glimmerPostStreamEnabled;
- }
-
- let enabled;
-
- /* eslint-disable no-console */
- let settingValue = this.siteSettings.deactivate_widgets_rendering
- ? "enabled" // if widgets rendering is deactivated, we always use the glimmer post stream
- : this.siteSettings.glimmer_post_stream_mode;
- if (
- settingValue === "disabled" &&
- this.currentUser?.use_glimmer_post_stream_mode_auto_mode
- ) {
- settingValue = "auto";
- }
-
- if (settingValue === "disabled") {
- enabled = false;
- } else {
- if (settingValue === "enabled") {
- if (havePostStreamWidgetExtensions) {
- console.log(
- [
- "⚠️ Using the new 'glimmer' post stream, even though some themes/plugins are not ready.\n" +
- "The following plugins and/or themes are using deprecated APIs and may have broken customizations: \n",
- ...Array.from(havePostStreamWidgetExtensions).sort(),
- ].join("\n- ")
- );
- } else {
- if (!isTesting() && !isRailsTesting()) {
- console.log("✅ Using the new 'glimmer' post stream!");
- }
- }
-
- enabled = true;
- } else {
- // auto
- if (havePostStreamWidgetExtensions) {
- console.warn(
- [
- "⚠️ Detected themes/plugins which are incompatible with the new 'glimmer' post stream. Falling back to the old implementation.\n" +
- "The following plugins and/or themes are using deprecated APIs: \n",
- ...Array.from(havePostStreamWidgetExtensions).sort(),
- ].join("\n- ")
- );
- enabled = false;
- } else {
- if (!isTesting() && !isRailsTesting()) {
- console.log("✅ Using the new 'glimmer' post stream!");
- }
-
- enabled = true;
- }
- }
- }
- /* eslint-enable no-console */
-
- this.#glimmerPostStreamEnabled = enabled;
-
- return enabled;
- }
-
@computed("categories.[]")
get categoriesById() {
const map = new Map();
diff --git a/frontend/discourse/app/services/composer.js b/frontend/discourse/app/services/composer.js
index 24de4495652..033af61a82b 100644
--- a/frontend/discourse/app/services/composer.js
+++ b/frontend/discourse/app/services/composer.js
@@ -1193,24 +1193,15 @@ export default class ComposerService extends Service {
return this.destroyDraft().then(() => {
this.close();
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh");
return result;
});
}
if (this.get("model.editingPost")) {
this.appEvents.trigger("composer:edited-post");
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", {
- id: parseInt(result.responseJson.id, 10),
- });
if (result.responseJson.post.post_number === 1) {
this.appEvents.trigger("header:update-topic", composer.topic);
}
- } else {
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh");
}
if (result.responseJson.action === "create_post") {
@@ -1278,9 +1269,6 @@ export default class ComposerService extends Service {
staged = composer.get("stagedPost");
}
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:posted", staged);
-
this.messageBus.pause();
promise.finally(() => this.messageBus.resume());
diff --git a/frontend/discourse/app/services/deprecation-warning-handler.js b/frontend/discourse/app/services/deprecation-warning-handler.js
index b6f119a9554..339b37e6d78 100644
--- a/frontend/discourse/app/services/deprecation-warning-handler.js
+++ b/frontend/discourse/app/services/deprecation-warning-handler.js
@@ -35,6 +35,7 @@ export const CRITICAL_DEPRECATIONS = [
"discourse.script-tag-discourse-plugin",
"discourse.post-stream-widget-overrides",
"discourse.widgets-end-of-life",
+ "discourse.widgets-decommissioned",
];
const REPLACEMENT_URLS = {};
diff --git a/frontend/discourse/app/services/keyboard-shortcuts.js b/frontend/discourse/app/services/keyboard-shortcuts.js
index ff7a2c980c7..2896229a387 100644
--- a/frontend/discourse/app/services/keyboard-shortcuts.js
+++ b/frontend/discourse/app/services/keyboard-shortcuts.js
@@ -628,11 +628,7 @@ export default class KeyboardShortcutLib extends Service {
actionMethod = topicRoute.actions[action];
}
- const result = actionMethod.call(topicController, post);
- if (result && result.then) {
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { id: selectedPostId });
- }
+ actionMethod.call(topicController, post);
}
}
diff --git a/frontend/discourse/app/templates/topic.gjs b/frontend/discourse/app/templates/topic.gjs
index f82e10a4a97..a2a4f5c65a1 100644
--- a/frontend/discourse/app/templates/topic.gjs
+++ b/frontend/discourse/app/templates/topic.gjs
@@ -18,7 +18,6 @@ import PostTextSelection from "discourse/components/post-text-selection";
import PrivateMessageGlyph from "discourse/components/private-message-glyph";
import ReviewableCreatedBy from "discourse/components/reviewable-created-by";
import ReviewableCreatedByName from "discourse/components/reviewable-created-by-name";
-import ScrollingPostStream from "discourse/components/scrolling-post-stream";
import SelectedPosts from "discourse/components/selected-posts";
import SharedDraftControls from "discourse/components/shared-draft-controls";
import SignupCta from "discourse/components/signup-cta";
@@ -425,153 +424,74 @@ export default <template>
id="topic"
data-topic-id={{@controller.model.id}}
>
-
- {{#if @controller.site.useGlimmerPostStream}}
- <div class="posts-wrapper">
- <span>
- <PluginOutlet
- @name="topic-above-posts"
- @connectorTagName="div"
- @outletArgs={{lazyHash [email protected]}}
- />
- </span>
-
- {{#unless @controller.model.postStream.loadingFilter}}
- <PostStream
- @postStream={{@controller.model.postStream}}
- @posts={{@controller.postsToRender}}
- @canCreatePost={{@controller.model.details.can_create_post}}
- @multiSelect={{@controller.multiSelect}}
- @selectedPostsCount={{@controller.selectedPostsCount}}
- @filteredPostsCount={{@controller.model.postStream.filteredPostsCount}}
- @selectedQuery={{@controller.selectedQuery}}
- @gaps={{@controller.model.postStream.gaps}}
- @showReadIndicator={{@controller.model.show_read_indicator}}
- @streamFilters={{@controller.model.postStream.streamFilters}}
- @lastReadPostNumber={{@controller.userLastReadPostNumber}}
- @highestPostNumber={{@controller.highestPostNumber}}
- @showFlags={{@controller.showPostFlags}}
- @editPost={{@controller.editPost}}
- @showHistory={{routeAction "showHistory"}}
- @showLogin={{routeAction "showLogin"}}
- @showRawEmail={{routeAction "showRawEmail"}}
- @deletePost={{@controller.deletePost}}
- @permanentlyDeletePost={{@controller.permanentlyDeletePost}}
- @recoverPost={{@controller.recoverPost}}
- @expandHidden={{@controller.expandHidden}}
- @toggleBookmark={{@controller.toggleBookmark}}
- @togglePostType={{@controller.togglePostType}}
- @rebakePost={{@controller.rebakePost}}
- @changePostOwner={{@controller.changePostOwner}}
- @grantBadge={{@controller.grantBadge}}
- @changeNotice={{@controller.changeNotice}}
- @lockPost={{@controller.lockPost}}
- @unlockPost={{@controller.unlockPost}}
- @unhidePost={{@controller.unhidePost}}
- @replyToPost={{@controller.replyToPost}}
- @toggleWiki={{@controller.toggleWiki}}
- @showTopReplies={{@controller.showTopReplies}}
- @cancelFilter={{@controller.cancelFilter}}
- @removeAllowedUser={{@controller.removeAllowedUser}}
- @removeAllowedGroup={{@controller.removeAllowedGroup}}
- @topVisibleChanged={{@controller.topVisibleChanged}}
- @currentPostChanged={{@controller.currentPostChanged}}
- @currentPostScrolled={{@controller.currentPostScrolled}}
- @bottomVisibleChanged={{@controller.bottomVisibleChanged}}
- @togglePostSelection={{@controller.togglePostSelection}}
- @selectReplies={{@controller.selectReplies}}
- @selectBelow={{@controller.selectBelow}}
- @fillGapBefore={{@controller.fillGapBefore}}
- @fillGapAfter={{@controller.fillGapAfter}}
- @showInvite={{routeAction "showInvite"}}
- @showPagePublish={{routeAction "showPagePublish"}}
- @filteringRepliesToPostNumber={{@controller.replies_to_post_number}}
- @updateTopicPageQueryParams={{@controller.updateTopicPageQueryParams}}
- @postSelected={{@controller.postSelected}}
- @topicPageQueryParams={{getProperties
- @controller
- @controller.queryParams
- }}
- @topic={{@controller.model}}
- />
- {{/unless}}
- </div>
- {{else}}
- <div class="posts-wrapper">
- <ConditionalLoadingSpinner
- @condition={{@controller.model.postStream.loadingAbove}}
+ <div class="posts-wrapper">
+ <span>
+ <PluginOutlet
+ @name="topic-above-posts"
+ @connectorTagName="div"
+ @outletArgs={{lazyHash [email protected]}}
/>
+ </span>
- <span>
- <PluginOutlet
- @name="topic-above-posts"
- @connectorTagName="div"
- @outletArgs={{lazyHash [email protected]}}
- />
- </span>
-
- {{#unless @controller.model.postStream.loadingFilter}}
- <ScrollingPostStream
- @posts={{@controller.postsToRender}}
- @canCreatePost={{@controller.model.details.can_create_post}}
- @multiSelect={{@controller.multiSelect}}
- @selectedPostsCount={{@controller.selectedPostsCount}}
- @filteredPostsCount={{@controller.model.postStream.filteredPostsCount}}
- @selectedQuery={{@controller.selectedQuery}}
- @gaps={{@controller.model.postStream.gaps}}
- @showReadIndicator={{@controller.model.show_read_indicator}}
- @streamFilters={{@controller.model.postStream.streamFilters}}
- @lastReadPostNumber={{@controller.userLastReadPostNumber}}
- @highestPostNumber={{@controller.highestPostNumber}}
- @showFlags={{@controller.showPostFlags}}
- @editPost={{@controller.editPost}}
- @showHistory={{routeAction "showHistory"}}
- @showLogin={{routeAction "showLogin"}}
- @showRawEmail={{routeAction "showRawEmail"}}
- @deletePost={{@controller.deletePost}}
- @permanentlyDeletePost={{@controller.permanentlyDeletePost}}
- @recoverPost={{@controller.recoverPost}}
- @expandHidden={{@controller.expandHidden}}
- @toggleBookmark={{@controller.toggleBookmark}}
- @togglePostType={{@controller.togglePostType}}
- @rebakePost={{@controller.rebakePost}}
- @changePostOwner={{@controller.changePostOwner}}
- @grantBadge={{@controller.grantBadge}}
- @changeNotice={{@controller.changeNotice}}
- @lockPost={{@controller.lockPost}}
- @unlockPost={{@controller.unlockPost}}
- @unhidePost={{@controller.unhidePost}}
- @replyToPost={{@controller.replyToPost}}
- @toggleWiki={{@controller.toggleWiki}}
- @showTopReplies={{@controller.showTopReplies}}
- @cancelFilter={{@controller.cancelFilter}}
- @removeAllowedUser={{@controller.removeAllowedUser}}
- @removeAllowedGroup={{@controller.removeAllowedGroup}}
- @topVisibleChanged={{@controller.topVisibleChanged}}
- @currentPostChanged={{@controller.currentPostChanged}}
- @currentPostScrolled={{@controller.currentPostScrolled}}
- @bottomVisibleChanged={{@controller.bottomVisibleChanged}}
- @togglePostSelection={{@controller.togglePostSelection}}
- @selectReplies={{@controller.selectReplies}}
- @selectBelow={{@controller.selectBelow}}
- @fillGapBefore={{@controller.fillGapBefore}}
- @fillGapAfter={{@controller.fillGapAfter}}
- @showInvite={{routeAction "showInvite"}}
- @showPagePublish={{routeAction "showPagePublish"}}
- @filteringRepliesToPostNumber={{@controller.replies_to_post_number}}
- @updateTopicPageQueryParams={{@controller.updateTopicPageQueryParams}}
- @topicPageQueryParams={{getProperties
- @controller
- @controller.queryParams
- }}
- />
- {{/unless}}
-
- <ConditionalLoadingSpinner
- @condition={{@controller.model.postStream.loadingBelow}}
+ {{#unless @controller.model.postStream.loadingFilter}}
+ <PostStream
+ @postStream={{@controller.model.postStream}}
+ @canCreatePost={{@controller.model.details.can_create_post}}
+ @multiSelect={{@controller.multiSelect}}
+ @selectedPostsCount={{@controller.selectedPostsCount}}
+ @filteredPostsCount={{@controller.model.postStream.filteredPostsCount}}
+ @selectedQuery={{@controller.selectedQuery}}
+ @gaps={{@controller.model.postStream.gaps}}
+ @showReadIndicator={{@controller.model.show_read_indicator}}
+ @streamFilters={{@controller.model.postStream.streamFilters}}
+ @lastReadPostNumber={{@controller.userLastReadPostNumber}}
+ @highestPostNumber={{@controller.highestPostNumber}}
+ @showFlags={{@controller.showPostFlags}}
+ @editPost={{@controller.editPost}}
+ @showHistory={{routeAction "showHistory"}}
+ @showLogin={{routeAction "showLogin"}}
+ @showRawEmail={{routeAction "showRawEmail"}}
+ @deletePost={{@controller.deletePost}}
+ @permanentlyDeletePost={{@controller.permanentlyDeletePost}}
+ @recoverPost={{@controller.recoverPost}}
+ @expandHidden={{@controller.expandHidden}}
+ @toggleBookmark={{@controller.toggleBookmark}}
+ @togglePostType={{@controller.togglePostType}}
+ @rebakePost={{@controller.rebakePost}}
+ @changePostOwner={{@controller.changePostOwner}}
+ @grantBadge={{@controller.grantBadge}}
+ @changeNotice={{@controller.changeNotice}}
+ @lockPost={{@controller.lockPost}}
+ @unlockPost={{@controller.unlockPost}}
+ @unhidePost={{@controller.unhidePost}}
+ @replyToPost={{@controller.replyToPost}}
+ @toggleWiki={{@controller.toggleWiki}}
+ @showTopReplies={{@controller.showTopReplies}}
+ @cancelFilter={{@controller.cancelFilter}}
+ @removeAllowedUser={{@controller.removeAllowedUser}}
+ @removeAllowedGroup={{@controller.removeAllowedGroup}}
+ @topVisibleChanged={{@controller.topVisibleChanged}}
+ @currentPostChanged={{@controller.currentPostChanged}}
+ @currentPostScrolled={{@controller.currentPostScrolled}}
+ @bottomVisibleChanged={{@controller.bottomVisibleChanged}}
+ @togglePostSelection={{@controller.togglePostSelection}}
+ @selectReplies={{@controller.selectReplies}}
+ @selectBelow={{@controller.selectBelow}}
+ @fillGapBefore={{@controller.fillGapBefore}}
+ @fillGapAfter={{@controller.fillGapAfter}}
+ @showInvite={{routeAction "showInvite"}}
+ @showPagePublish={{routeAction "showPagePublish"}}
+ @filteringRepliesToPostNumber={{@controller.replies_to_post_number}}
+ @updateTopicPageQueryParams={{@controller.updateTopicPageQueryParams}}
+ @postSelected={{@controller.postSelected}}
+ @topicPageQueryParams={{getProperties
+ @controller
+ @controller.queryParams
+ }}
+ @topic={{@controller.model}}
/>
- </div>
- {{/if}}
+ {{/unless}}
+ </div>
<div id="topic-bottom"></div>
<ConditionalLoadingSpinner
diff --git a/frontend/discourse/app/widgets/actions-summary.js b/frontend/discourse/app/widgets/actions-summary.js
deleted file mode 100644
index a4b811445c3..00000000000
--- a/frontend/discourse/app/widgets/actions-summary.js
+++ /dev/null
@@ -1,23 +0,0 @@
-import { hbs } from "ember-cli-htmlbars";
-import { registerWidgetShim } from "discourse/widgets/render-glimmer";
-
-// This shim is nesting everything into a DIV and changing the HTML but only thw two voting plugins
-// are using this widget outside of core.
-registerWidgetShim(
- "small-user-list",
- "div",
- hbs`
- <SmallUserList class={{@data.listClassName}}
- @ariaLabel={{@data.ariaLabel}}
- @users={{@data.users}}
- @addSelf={{@data.addSelf}}
- @count={{@data.count}}
- @description={{@data.description}}
- @isVisible={{@data.isVisible}}/>`
-);
-
-registerWidgetShim(
- "actions-summary",
- "section.post-actions",
- hbs`<Post::ActionsSummary @post={{@data.post}} />`
-);
diff --git a/frontend/discourse/app/widgets/avatar-flair.js b/frontend/discourse/app/widgets/avatar-flair.js
index 339d40d0602..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/avatar-flair.js
+++ b/frontend/discourse/app/widgets/avatar-flair.js
@@ -1,52 +1,8 @@
-import { convertIconClass, iconNode } from "discourse/lib/icon-library";
-import { escapeExpression } from "discourse/lib/utilities";
-import { createWidget } from "discourse/widgets/widget";
-
-createWidget("avatar-flair", {
- tagName: "div.avatar-flair",
-
- isIcon(attrs) {
- return attrs.flair_url && !attrs.flair_url.includes("/");
- },
-
- title(attrs) {
- return attrs.flair_name;
- },
-
- buildClasses(attrs) {
- let defaultClass = `avatar-flair-${attrs.flair_name} ${
- attrs.flair_bg_color ? "rounded" : ""
- }`;
-
- if (!this.isIcon(attrs)) {
- defaultClass += " avatar-flair-image";
- }
-
- return defaultClass;
- },
-
- buildAttributes(attrs) {
- let style = "";
- if (!this.isIcon(attrs)) {
- style +=
- "background-image: url(" + escapeExpression(attrs.flair_url) + "); ";
- }
- if (attrs.flair_bg_color) {
- style +=
- "background-color: #" + escapeExpression(attrs.flair_bg_color) + "; ";
- }
- if (attrs.flair_color) {
- style += "color: #" + escapeExpression(attrs.flair_color) + "; ";
- }
- return { style };
- },
-
- html(attrs) {
- if (this.isIcon(attrs)) {
- const icon = convertIconClass(attrs.flair_url);
- return [iconNode(icon)];
- } else {
- return [];
- }
- },
-});
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/bookmark-menu.js b/frontend/discourse/app/widgets/bookmark-menu.js
deleted file mode 100644
index 49e2b3c97c1..00000000000
--- a/frontend/discourse/app/widgets/bookmark-menu.js
+++ /dev/null
@@ -1,8 +0,0 @@
-import { hbs } from "ember-cli-htmlbars";
-import { registerWidgetShim } from "discourse/widgets/render-glimmer";
-
-registerWidgetShim(
- "bookmark-menu-shim",
- "div.bookmark-menu-shim",
- hbs`<BookmarkMenu @bookmarkManager={{@data.bookmarkManager}} @buttonClasses="btn-flat" />`
-);
diff --git a/frontend/discourse/app/widgets/button.js b/frontend/discourse/app/widgets/button.js
index ef0177ca6c9..838fe632e99 100644
--- a/frontend/discourse/app/widgets/button.js
+++ b/frontend/discourse/app/widgets/button.js
@@ -1,165 +1,40 @@
-import $ from "jquery";
-import { h } from "virtual-dom";
-import { iconNode } from "discourse/lib/icon-library";
-import DiscourseURL from "discourse/lib/url";
-import { createWidget } from "discourse/widgets/widget";
-import { i18n } from "discourse-i18n";
-
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */
export const ButtonClass = {
- tagName: "button.widget-button.btn",
-
- buildClasses(attrs) {
- let className = this.attrs.className || "";
-
- let hasText = attrs.translatedLabel || attrs.label || attrs.contents;
-
- if (!hasText) {
- className += " no-text";
- }
-
- if (attrs.icon) {
- className += " btn-icon";
- if (hasText) {
- className += "-text";
- }
- } else if (hasText) {
- className += " btn-text";
- }
-
- return className;
- },
-
- buildAttributes() {
- const attrs = this.attrs;
- const attributes = {};
- let title = attrs.translatedTitle;
-
- if (!title && attrs.title) {
- title = i18n(attrs.title, attrs.titleOptions);
- }
-
- if (title) {
- attributes.title = title;
- }
-
- if (attrs.role) {
- attributes["role"] = attrs.role;
- }
-
- if (attrs.translatedAriaLabel) {
- attributes["aria-label"] = attrs.translatedAriaLabel;
- }
-
- if (attrs.ariaExpanded) {
- attributes["aria-expanded"] = attrs.ariaExpanded;
- }
-
- if (attrs.ariaControls) {
- attributes["aria-controls"] = attrs.ariaControls;
- }
-
- if (attrs.ariaPressed) {
- attributes["aria-pressed"] = attrs.ariaPressed;
- }
-
- if (attrs.ariaLive) {
- attributes["aria-live"] = attrs.ariaLive;
- }
-
- if (attrs.tabAttrs) {
- const tab = attrs.tabAttrs;
- attributes["aria-selected"] = tab["aria-selected"];
- attributes["tabindex"] = tab["tabindex"];
- attributes["aria-controls"] = tab["aria-controls"];
- attributes["id"] = attrs.id;
- }
-
- if (attrs.disabled) {
- attributes.disabled = "true";
- }
-
- if (attrs.data) {
- Object.keys(attrs.data).forEach(
- (k) => (attributes[`data-${k}`] = attrs.data[k])
- );
- }
-
- return attributes;
- },
-
- _buildIcon(attrs) {
- const icon = iconNode(attrs.icon, { class: attrs.iconClass });
- if (attrs["aria-label"]) {
- icon.properties.attributes["role"] = "img";
- icon.properties.attributes["aria-hidden"] = false;
- }
- return icon;
- },
-
- html(attrs) {
- const contents = [];
- const left = !attrs.iconRight;
-
- if (attrs.icon && left) {
- contents.push(this._buildIcon(attrs));
- }
- if (attrs.emoji && left) {
- contents.push(this.attach("emoji", { name: attrs.emoji }));
- }
- if (attrs.label) {
- contents.push(
- h("span.d-button-label", i18n(attrs.label, attrs.labelOptions))
- );
- }
- if (attrs.translatedLabel) {
- contents.push(
- h(
- "span.d-button-label",
- attrs.translatedLabel.toString(),
- attrs.translatedLabelOptions
- )
- );
- }
- if (attrs.contents) {
- contents.push(attrs.contents);
- }
- if (attrs.emoji && !left) {
- contents.push(this.attach("emoji", { name: attrs.emoji }));
- }
- if (attrs.icon && !left) {
- contents.push(this._buildIcon(attrs));
- }
-
- return contents;
- },
-
- click(e) {
- const attrs = this.attrs;
- if (attrs.disabled) {
- return;
- }
-
- $(`button.widget-button`).removeClass("d-hover").blur();
- if (attrs.secondaryAction) {
- this.sendWidgetAction(attrs.secondaryAction);
- }
-
- if (attrs.url) {
- return DiscourseURL.routeTo(attrs.url);
- }
-
- if (attrs.sendActionEvent) {
- return this.sendWidgetAction(attrs.action, e);
- }
- return this.sendWidgetAction(attrs.action, attrs.actionParam);
- },
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ buildClasses() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ buildAttributes() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _buildIcon() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ html() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ click() {},
};
-export default createWidget("button", ButtonClass);
-
-createWidget(
- "flat-button",
- Object.assign(ButtonClass, {
- tagName: "button.widget-button.btn-flat",
- })
-);
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/category-link.js b/frontend/discourse/app/widgets/category-link.js
index 22b947f0884..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/category-link.js
+++ b/frontend/discourse/app/widgets/category-link.js
@@ -1,10 +1,8 @@
-import { categoryBadgeHTML } from "discourse/helpers/category-link";
-import RawHtml from "discourse/widgets/raw-html";
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
-// Right now it's RawHTML. Eventually it should emit nodes
-export default class CategoryLink extends RawHtml {
- constructor(attrs) {
- attrs.html = `<span>${categoryBadgeHTML(attrs.category, attrs)}</span>`;
- super(attrs);
- }
-}
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/component-connector.js b/frontend/discourse/app/widgets/component-connector.js
index 676def89f75..a5219673647 100644
--- a/frontend/discourse/app/widgets/component-connector.js
+++ b/frontend/discourse/app/widgets/component-connector.js
@@ -1,75 +1,39 @@
-import { getOwner } from "@ember/owner";
-import { scheduleOnce } from "@ember/runloop";
-
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+import { warnWidgetsDecommissioned } from "discourse/widgets/widget";
+
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */
export default class ComponentConnector {
- constructor(
- widget,
- componentName,
- opts,
- trackedProperties,
- { applyStyle = true } = {}
- ) {
- this.widget = widget;
- this.opts = opts;
- this.componentName = componentName;
- this.trackedProperties = trackedProperties || [];
- this.applyStyle = applyStyle;
- this._component = null;
- }
-
- init() {
- const elem = document.createElement("div");
- if (this.applyStyle) {
- elem.style.display = "inline-flex";
- }
- elem.className = "widget-component-connector";
- this.elem = elem;
- scheduleOnce("afterRender", this, this.connectComponent);
-
- return this.elem;
+ constructor() {
+ warnWidgetsDecommissioned();
}
- destroy() {
- this._component?.destroy();
- }
-
- update(prev) {
- // mutated external properties might not correctly update the underlying component
- // in this case we can define trackedProperties, if different from previous
- // state we will re-init the whole component, be careful when using this
- // to not track a property which would be updated too often (on scroll for example)
- let shouldInit = false;
- this.trackedProperties.forEach((prop) => {
- if (prev.opts[prop] !== this.opts[prop]) {
- shouldInit = true;
- }
- });
-
- if (shouldInit) {
- return this.init();
- }
-
- return null;
- }
-
- connectComponent() {
- const { elem, opts, widget, componentName } = this;
-
- const mounted = widget._findView();
- const component = getOwner(mounted)
- .factoryFor(`component:${componentName}`)
- .create(opts);
-
- // component connector is not triggering didReceiveAttrs
- // we force it for selectKit components
- if (component.selectKit) {
- component.didReceiveAttrs();
- }
-
- mounted._connected.push(component);
- component.renderer.appendTo(component, elem);
- this._component = component;
- }
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ init() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ destroy() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ update() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ connectComponent() {}
}
-
-ComponentConnector.prototype.type = "Widget";
diff --git a/frontend/discourse/app/widgets/connector.js b/frontend/discourse/app/widgets/connector.js
index 715712620c1..d2ee56482aa 100644
--- a/frontend/discourse/app/widgets/connector.js
+++ b/frontend/discourse/app/widgets/connector.js
@@ -1,37 +1,29 @@
-import { getOwner } from "@ember/owner";
-import { next } from "@ember/runloop";
-
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+import { warnWidgetsDecommissioned } from "discourse/widgets/widget";
+
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */
export default class Connector {
- constructor(widget, opts) {
- this.widget = widget;
- this.opts = opts;
+ constructor() {
+ warnWidgetsDecommissioned();
}
- init() {
- const elem = document.createElement("div");
- elem.classList.add("widget-connector");
-
- const { opts, widget } = this;
- next(() => {
- const mounted = widget._findView();
-
- if (opts.component) {
- const component = getOwner(mounted)
- .factoryFor("component:connector-container")
- .create({
- layoutName: `components/${opts.component}`,
- model: widget.findAncestorModel(),
- });
-
- mounted._connected.push(component);
- component.renderer.appendTo(component, elem);
- }
- });
-
- return elem;
- }
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ init() {}
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
update() {}
}
-
-Connector.prototype.type = "Widget";
diff --git a/frontend/discourse/app/widgets/decorator-helper.js b/frontend/discourse/app/widgets/decorator-helper.js
index f896243666e..6bdd1cce860 100644
--- a/frontend/discourse/app/widgets/decorator-helper.js
+++ b/frontend/discourse/app/widgets/decorator-helper.js
@@ -1,179 +1,54 @@
-import { hasInternalComponentManager } from "@glimmer/manager";
-import { h } from "virtual-dom";
-import deprecated from "discourse/lib/deprecated";
-import Connector from "discourse/widgets/connector";
-import PostCooked from "discourse/widgets/post-cooked";
-import RawHtml from "discourse/widgets/raw-html";
-import RenderGlimmer from "discourse/widgets/render-glimmer";
-import { POST_STREAM_DEPRECATION_OPTIONS } from "discourse/widgets/widget";
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
-class DecoratorHelper {
- constructor(widget, attrs, state) {
- this.widget = widget;
- this.attrs = attrs;
- this.canConnectComponent = true;
- this.state = state;
- this.register = widget.register;
- this.register.deprecateContainer(this);
+import { warnWidgetsDecommissioned } from "discourse/widgets/widget";
+
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */
+export default class DecoratorHelper {
+ constructor() {
+ warnWidgetsDecommissioned();
}
/**
- * The `h` helper allows you to build up a virtual dom easily.
- *
- * Example:
- *
- * ```
- * // renders `<div class='some-class'><p>paragraph</p></div>`
- * return helper.h('div.some-class', helper.h('p', 'paragraph'));
- * ```
- * Check out https://github.com/Matt-Esch/virtual-dom/blob/master/virtual-hyperscript/README.md
- * for more details on how to construct markup with h.
- **/
- // h() is attached via `prototype` below
+ * @deprecated the widget rendering system was decommissioned
+ */
+ attach() {}
/**
- * Attach another widget inside this one.
- *
- * ```
- * return helper.attach('widget-name');
- * ```
+ * @deprecated the widget rendering system was decommissioned
*/
- attach(name, attrs, state) {
- attrs = attrs || this.widget.attrs;
- state = state || this.widget.state;
-
- return this.widget.attach(name, attrs, state);
- }
-
- get model() {
- return this.widget.findAncestorModel();
- }
+ get model() {}
/**
- * Returns the model associated with this widget. When decorating
- * posts this will normally be the post.
- *
- * Example:
- *
- * ```
- * const post = helper.getModel();
- * console.log(post.get('id'));
- * ```
- **/
- getModel() {
- return this.model;
- }
+ * @deprecated the widget rendering system was decommissioned
+ */
+ getModel() {}
/**
- * If your decorator must produce raw HTML, you can use this helper
- * to display it. It is preferred to use the `h` helper and create
- * the HTML yourself whenever possible.
- *
- * Example:
- *
- * ```
- * return helper.rawHtml(`<p>I will be displayed</p`);
- * ```
- **/
- rawHtml(html) {
- return new RawHtml({ html });
- }
+ * @deprecated the widget rendering system was decommissioned
+ */
+ rawHtml() {}
/**
- * Renders `cooked` content using all the helpers and decorators that
- * are attached to that. This is useful if you want to render a post's
- * content or a different version of it.
- *
- * Example:
- *
- * ```
- * return helper.cooked(`<p>Cook me</p>`);
- * ```
- **/
- cooked(cooked) {
- return new PostCooked({ cooked }, this);
- }
+ * @deprecated the widget rendering system was decommissioned
+ */
+ cooked() {}
/**
- * You can use this bridge to mount an Ember Component inside the virtual
- * DOM post stream. Note that this is a bit bizarre, as our core app
- * is rendered in Ember, then we switch to a virtual dom, and this
- * allows part of that virtual dom to use Ember again!
- *
- * It really only exists as backwards compatibility for some old
- * plugins that would be difficult to update otherwise. There are
- * performance reasons not to use this, so be careful and avoid
- * using it whenever possible.
- *
- * Example:
- *
- * ```
- * helper.connect({ component: 'my-component-name' });
- * ```
- **/
- connect(details) {
- return new Connector(this.widget, details);
- }
+ * @deprecated the widget rendering system was decommissioned
+ */
+ connect() {}
/**
- * Returns an element containing a rendered glimmer template. For full usage instructions,
- * see `widgets/render-glimmer.js`.
- *
- * DEPRECATION NOTICES:
- * - using a string describing a new wrapper element as the `targetElement` parameter is deprecated.
- * Use an existing HTML element instead.
- * - using a template compiled via `ember-cli-htmlbars` as the `component` parameter is deprecated.
- * You should provide a component instead.
- *
- * Example usage in a `.gjs` file:
- *
- * ```
- * api.decorateCookedElement((cooked, helper) => {
- * // Or append to an existing element
- * helper.renderGlimmer(
- * cooked.querySelector(".some-container"),
- * <template>I will be appended to some-container</template>
- * );
- * }, { onlyStream: true });
- * ```
- *
+ * @deprecated the widget rendering system was decommissioned
*/
- renderGlimmer(targetElement, component, data) {
- // Ideally we should throw an error here, but we can't for now to prevent existing incompatible customizations from
- // crashing the app. Instead, we will log a deprecation warning while we're in the process of migrating to the new
- // Glimmer Post Stream API.
- if (!(targetElement instanceof Element)) {
- deprecated(
- "The `targetElement` parameter provided to `helper.renderGlimmer` is invalid. It must be an existing HTML element. Using a string to describe a new wrapper element is deprecated.",
- POST_STREAM_DEPRECATION_OPTIONS
- );
- }
-
- if (!hasInternalComponentManager(component)) {
- deprecated(
- "The `component` parameter provided to `helper.renderGlimmer` is invalid. It must be a valid Glimmer component. Using a template compiled via `ember-cli-htmlbars` is deprecated. Use the <template>...</template> syntax or replace it with a proper component.",
- POST_STREAM_DEPRECATION_OPTIONS
- );
- }
-
- if (!this.widget.postContentsDestroyCallbacks) {
- throw "renderGlimmer can only be used in the context of a post";
- }
-
- const renderGlimmer = new RenderGlimmer(
- this.widget,
- targetElement,
- component,
- data
- );
- renderGlimmer.init();
- this.widget.postContentsDestroyCallbacks.push(
- renderGlimmer.destroy.bind(renderGlimmer)
- );
- return renderGlimmer.element;
- }
+ renderGlimmer() {}
}
-
-DecoratorHelper.prototype.h = h;
-
-export default DecoratorHelper;
diff --git a/frontend/discourse/app/widgets/discourse-tags.js b/frontend/discourse/app/widgets/discourse-tags.js
index ad5e70449fa..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/discourse-tags.js
+++ b/frontend/discourse/app/widgets/discourse-tags.js
@@ -1,10 +1,8 @@
-import renderTags from "discourse/lib/render-tags";
-import RawHtml from "discourse/widgets/raw-html";
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
-// Right now it's RawHTML. Eventually it should emit nodes
-export default class DiscourseTags extends RawHtml {
- constructor(attrs) {
- attrs.html = renderTags(attrs.topic, attrs);
- super(attrs);
- }
-}
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/embedded-post.js b/frontend/discourse/app/widgets/embedded-post.js
index 9fb3c1a233b..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/embedded-post.js
+++ b/frontend/discourse/app/widgets/embedded-post.js
@@ -1,69 +1,8 @@
-import { h } from "virtual-dom";
-import DecoratorHelper from "discourse/widgets/decorator-helper";
-import hbs from "discourse/widgets/hbs-compiler";
-import PostCooked from "discourse/widgets/post-cooked";
-import { createWidget } from "discourse/widgets/widget";
-
-// glimmer-post-stream: has glimmer version
-createWidget("post-link-arrow", {
- tagName: "div.post-link-arrow",
-
- template: hbs`
- <a href={{attrs.shareUrl}} class="post-info arrow" title={{i18n "topic.jump_reply"}} aria-label={{i18n
- "topic.jump_reply_aria" username=attrs.name
- }}>
- {{#if attrs.above}}
- {{d-icon "arrow-up"}}
- {{else}}
- {{d-icon "arrow-down"}}
- {{/if}}
- {{i18n "topic.jump_reply_button"}}
- </a>
- `,
-});
-
-// glimmer-post-stream: has glimmer version
-export default createWidget("embedded-post", {
- tagName: "div.reply",
- buildKey: (attrs) => `embedded-post-${attrs.id}`,
-
- buildAttributes(attrs) {
- const attributes = { "data-post-id": attrs.id };
- if (this.state.role) {
- attributes.role = this.state.role;
- }
- if (this.state["aria-label"]) {
- attributes["aria-label"] = this.state["aria-label"];
- }
- return attributes;
- },
-
- html(attrs, state) {
- attrs.embeddedPost = true;
- return [
- h("div.row", [
- this.attach("post-avatar", attrs),
- h("div.topic-body", [
- h("div.topic-meta-data.embedded-reply", [
- this.attach("poster-name", attrs),
- this.attach("post-link-arrow", {
- name: attrs.username,
- above: state.above,
- shareUrl: attrs.customShare,
- }),
- ]),
- new PostCooked(attrs, new DecoratorHelper(this), this.currentUser),
- ]),
- ]),
- ];
- },
-
- init() {
- // TODO (glimmer-post-stream): How does this fit into the Glimmer lifecycle?
- this.postContentsDestroyCallbacks = [];
- },
-
- destroy() {
- this.postContentsDestroyCallbacks.forEach((c) => c());
- },
-});
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/emoji.js b/frontend/discourse/app/widgets/emoji.js
index 537402d7ec3..7536bcc02b0 100644
--- a/frontend/discourse/app/widgets/emoji.js
+++ b/frontend/discourse/app/widgets/emoji.js
@@ -1,24 +1,11 @@
-import { emojiUnescape, emojiUrlFor } from "discourse/lib/text";
-import { escapeExpression } from "discourse/lib/utilities";
-import RawHtml from "discourse/widgets/raw-html";
-import { createWidget } from "discourse/widgets/widget";
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
-export function replaceEmoji(str) {
- const escaped = emojiUnescape(escapeExpression(str));
- return [new RawHtml({ html: `<span>${escaped}</span>` })];
-}
-
-export default createWidget("emoji", {
- tagName: "img.emoji",
-
- buildAttributes(attrs) {
- let result = {
- src: emojiUrlFor(attrs.name),
- alt: `:${attrs.alt || attrs.name}:`,
- };
- if (attrs.title) {
- result.title = typeof attrs.title === "string" ? attrs.title : attrs.name;
- }
- return result;
- },
-});
+export {
+ warnWidgetsDecommissioned as replaceEmoji,
+ DummyWidget as default,
+} from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/glue.js b/frontend/discourse/app/widgets/glue.js
index a6881743cf1..577ab6dde82 100644
--- a/frontend/discourse/app/widgets/glue.js
+++ b/frontend/discourse/app/widgets/glue.js
@@ -1,67 +1,37 @@
-import { cancel, scheduleOnce } from "@ember/runloop";
-import { diff, patch } from "virtual-dom";
-import DirtyKeys from "discourse/lib/dirty-keys";
-import { isTesting } from "discourse/lib/environment";
-import { queryRegistry, traverseCustomWidgets } from "discourse/widgets/widget";
-
-export default class WidgetGlue {
- constructor(name, register, attrs) {
- this._tree = null;
- this._rootNode = null;
- this.register = register;
- this.attrs = attrs;
- this._timeout = null;
- this.dirtyKeys = new DirtyKeys(name);
-
- this._widgetClass =
- queryRegistry(name) || this.register.lookupFactory(`widget:${name}`);
- if (!this._widgetClass) {
- // eslint-disable-next-line no-console
- console.error(`Error: Could not find widget: ${name}`);
- }
- }
-
- appendTo(elem) {
- this._rootNode = elem;
- this.queueRerender();
- }
-
- queueRerender() {
- this._timeout = scheduleOnce("render", this, this.rerenderWidget);
- }
-
- rerenderWidget() {
- cancel(this._timeout);
-
- // in test mode return early if store cannot be found
- if (isTesting()) {
- try {
- this.register.lookup("service:store");
- } catch {
- return;
- }
- }
-
- const newTree = new this._widgetClass(this.attrs, this.register, {
- dirtyKeys: this.dirtyKeys,
- });
- const patches = diff(this._tree || this._rootNode, newTree);
-
- traverseCustomWidgets(this._tree, (w) => w.willRerenderWidget());
-
- newTree._rerenderable = this;
- this._rootNode = patch(this._rootNode, patches);
- this._tree = newTree;
-
- traverseCustomWidgets(newTree, (w) => w.didRenderWidget());
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+import { warnWidgetsDecommissioned } from "discourse/widgets/widget";
+
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */ export default class WidgetGlue {
+ constructor() {
+ warnWidgetsDecommissioned();
}
- cleanUp() {
- traverseCustomWidgets(this._tree, (w) => w.destroy());
-
- cancel(this._timeout);
-
- this._rootNode = patch(this._rootNode, diff(this._tree, null));
- this._tree = null;
- }
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ appendTo() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ queueRerender() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ rerenderWidget() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ cleanUp() {}
}
diff --git a/frontend/discourse/app/widgets/hbs-compiler.js b/frontend/discourse/app/widgets/hbs-compiler.js
index 71bd31e6f1f..6b0366581a6 100644
--- a/frontend/discourse/app/widgets/hbs-compiler.js
+++ b/frontend/discourse/app/widgets/hbs-compiler.js
@@ -1,4 +1,8 @@
-export default function hbs() {
- // eslint-disable-next-line no-console
- console.log("Templates should be precompiled server side");
-}
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export { warnWidgetsDecommissioned as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/hooks.js b/frontend/discourse/app/widgets/hooks.js
index e607f8f9236..02bdac96a88 100644
--- a/frontend/discourse/app/widgets/hooks.js
+++ b/frontend/discourse/app/widgets/hooks.js
@@ -1,381 +1,51 @@
-import { bind } from "@ember/runloop";
-import $ from "jquery";
-
-const CLICK_ATTRIBUTE_NAME = "_discourse_click_widget";
-const DOUBLE_CLICK_ATTRIBUTE_NAME = "_discourse_double_click_widget";
-const CLICK_OUTSIDE_ATTRIBUTE_NAME = "_discourse_click_outside_widget";
-const MOUSE_DOWN_OUTSIDE_ATTRIBUTE_NAME =
- "_discourse_mouse_down_outside_widget";
-const KEY_UP_ATTRIBUTE_NAME = "_discourse_key_up_widget";
-const KEY_DOWN_ATTRIBUTE_NAME = "_discourse_key_down_widget";
-const DRAG_ATTRIBUTE_NAME = "_discourse_drag_widget";
-const INPUT_ATTRIBUTE_NAME = "_discourse_input_widget";
-const CHANGE_ATTRIBUTE_NAME = "_discourse_change_widget";
-const MOUSE_DOWN_ATTRIBUTE_NAME = "_discourse_mouse_down_widget";
-const MOUSE_UP_ATTRIBUTE_NAME = "_discourse_mouse_up_widget";
-const MOUSE_MOVE_ATTRIBUTE_NAME = "_discourse_mouse_move_widget";
-const MOUSE_OVER_ATTRIBUTE_NAME = "_discourse_mouse_over_widget";
-const MOUSE_OUT_ATTRIBUTE_NAME = "_discourse_mouse_out_widget";
-const TOUCH_START_ATTRIBUTE_NAME = "_discourse_touch_start_widget";
-const TOUCH_END_ATTRIBUTE_NAME = "_discourse_touch_end_widget";
-const TOUCH_MOVE_ATTRIBUTE_NAME = "_discourse_touch_move_widget";
-const POINTER_OVER_ATTRIBUTE_NAME = "_discourse_pointer_over_widget";
-const POINTER_OUT_ATTRIBUTE_NAME = "_discourse_pointer_out_widget";
-
-class WidgetBaseHook {
- constructor(widget) {
- this.widget = widget;
- }
-}
-
-function buildHook(attributeName, setAttr) {
- return class extends WidgetBaseHook {
- hook(node) {
- if (setAttr) {
- node.setAttribute(setAttr, true);
- }
- node[attributeName] = this.widget;
- }
-
- unhook(node) {
- if (setAttr) {
- node.removeAttribute(setAttr, true);
- }
- node[attributeName] = null;
- }
- };
-}
-
-// For the majority of events, we register a single listener on the `<body>`, and then
-// notify the relevant widget (if any) when the event fires (see setupDocumentCallback() below)
-export const WidgetClickHook = buildHook(CLICK_ATTRIBUTE_NAME);
-export const WidgetDoubleClickHook = buildHook(DOUBLE_CLICK_ATTRIBUTE_NAME);
-export const WidgetClickOutsideHook = buildHook(
- CLICK_OUTSIDE_ATTRIBUTE_NAME,
- "data-click-outside"
-);
-export const WidgetMouseDownOutsideHook = buildHook(
- MOUSE_DOWN_OUTSIDE_ATTRIBUTE_NAME,
- "data-mouse-down-outside"
-);
-export const WidgetKeyUpHook = buildHook(KEY_UP_ATTRIBUTE_NAME);
-export const WidgetKeyDownHook = buildHook(KEY_DOWN_ATTRIBUTE_NAME);
-export const WidgetInputHook = buildHook(INPUT_ATTRIBUTE_NAME);
-export const WidgetChangeHook = buildHook(CHANGE_ATTRIBUTE_NAME);
-export const WidgetMouseUpHook = buildHook(MOUSE_UP_ATTRIBUTE_NAME);
-export const WidgetMouseDownHook = buildHook(MOUSE_DOWN_ATTRIBUTE_NAME);
-export const WidgetMouseMoveHook = buildHook(MOUSE_MOVE_ATTRIBUTE_NAME);
-export const WidgetMouseOverHook = buildHook(MOUSE_OVER_ATTRIBUTE_NAME);
-export const WidgetPointerOverHook = buildHook(POINTER_OVER_ATTRIBUTE_NAME);
-export const WidgetPointerOutHook = buildHook(POINTER_OUT_ATTRIBUTE_NAME);
-export const WidgetMouseOutHook = buildHook(MOUSE_OUT_ATTRIBUTE_NAME);
-export const WidgetTouchEndHook = buildHook(TOUCH_END_ATTRIBUTE_NAME);
-
-// `touchstart` and `touchmove` events are particularly performance sensitive because
-// they block scrolling on mobile. Therefore we want to avoid registering global non-passive
-// listeners for these events.
-// Instead, the WidgetTouchStartHook and WidgetDragHook automatically register listeners on
-// the specific widget DOM elements when required.
-function touchStartHandler(e) {
- return e.currentTarget[TOUCH_START_ATTRIBUTE_NAME].touchStart(e);
-}
-function touchMoveHandler(e) {
- return e.currentTarget[TOUCH_MOVE_ATTRIBUTE_NAME].touchMove(e);
-}
-
-export class WidgetTouchStartHook extends WidgetBaseHook {
- hook(node, propertyName, previousValue) {
- node[TOUCH_START_ATTRIBUTE_NAME] = this.widget;
- if (!previousValue) {
- // Element added to DOM
- node.addEventListener("touchstart", touchStartHandler, {
- passive: false,
- });
- }
- }
-
- unhook(node, propertyName, newValue) {
- if (!newValue) {
- // Element removed from DOM
- node.removeEventListener("touchstart", touchStartHandler);
- }
- }
-}
-export class WidgetTouchMoveHook extends WidgetBaseHook {
- hook(node, propertyName, previousValue) {
- node[TOUCH_MOVE_ATTRIBUTE_NAME] = this.widget;
- if (!previousValue) {
- // Element added to DOM
- node.addEventListener("touchmove", touchMoveHandler, {
- passive: false,
- });
- }
- }
-
- unhook(node, propertyName, newValue) {
- if (!newValue) {
- // Element removed from DOM
- node.removeEventListener("touchmove", touchMoveHandler);
- }
- }
-}
-
-let _currentlyDraggingElement;
-
-function dragStart(e) {
- e.preventDefault();
- e.stopPropagation();
- if (_currentlyDraggingElement) {
- dragEnd();
- }
- _currentlyDraggingElement = e.currentTarget;
- document.body.classList.add("widget-dragging");
- document.addEventListener("touchmove", drag, { passive: false });
- document.addEventListener("mousemove", drag, { passive: false });
- document.addEventListener("touchend", dragEnd);
- document.addEventListener("mouseup", dragEnd);
-}
-
-function drag(e) {
- const widget = _currentlyDraggingElement[DRAG_ATTRIBUTE_NAME];
- if (e.type === "mousemove") {
- widget.drag(e);
- } else {
- const tt = e.targetTouches[0];
- e.preventDefault();
- e.stopPropagation();
- widget.drag(tt);
- }
-}
-
-function dragEnd(e) {
- document.body.classList.remove("widget-dragging");
- document.removeEventListener("touchmove", drag);
- document.removeEventListener("mousemove", drag);
- document.removeEventListener("touchend", dragEnd);
- document.removeEventListener("mouseup", dragEnd);
- const widget = _currentlyDraggingElement[DRAG_ATTRIBUTE_NAME];
- widget.dragEnd(e);
- _currentlyDraggingElement = null;
-}
-
-export class WidgetDragHook extends WidgetBaseHook {
- hook(node, propertyName, previousValue) {
- node[DRAG_ATTRIBUTE_NAME] = this.widget;
- if (!previousValue) {
- // Adding to DOM
- node.addEventListener("touchstart", dragStart, { passive: false });
- node.addEventListener("mousedown", dragStart, { passive: false });
- }
- }
-
- unhook(node, propertyName, newValue) {
- if (!newValue) {
- // Removing from DOM
- if (_currentlyDraggingElement === node) {
- dragEnd();
- }
- node.removeEventListener("touchstart", dragStart);
- node.removeEventListener("mousedown", dragStart);
- }
- }
-}
-
-function nodeCallback(node, attrName, cb, options = { rerender: true }) {
- const { rerender } = options;
- const widget = findWidget(node, attrName);
-
- if (widget) {
- if (rerender) {
- widget.rerenderResult(() => cb(widget));
- } else {
- cb(widget);
- }
- }
-}
-
-function findWidget(node, attrName) {
- while (node) {
- const widget = node[attrName];
- if (widget) {
- return widget;
- }
- node = node.parentNode;
- }
-}
-
-let _watchingDocument = false;
-
-WidgetClickHook.setupDocumentCallback = function () {
- if (_watchingDocument) {
- return;
- }
-
- $(document).on(
- "mouseover.discourse-widget",
- bind(this, (e) => {
- nodeCallback(e.target, MOUSE_OVER_ATTRIBUTE_NAME, (w) => w.mouseOver(e), {
- rerender: false,
- });
- })
- );
-
- $(document).on(
- "pointerover.discourse-widget",
- bind(this, (e) => {
- nodeCallback(
- e.target,
- POINTER_OVER_ATTRIBUTE_NAME,
- (w) => w.pointerOver(e),
- {
- rerender: false,
- }
- );
- })
- );
-
- $(document).on(
- "mouseout.discourse-widget",
- bind(this, (e) => {
- nodeCallback(e.target, MOUSE_OUT_ATTRIBUTE_NAME, (w) => w.mouseOut(e), {
- rerender: false,
- });
- })
- );
-
- $(document).on(
- "pointerout.discourse-widget",
- bind(this, (e) => {
- nodeCallback(
- e.target,
- POINTER_OUT_ATTRIBUTE_NAME,
- (w) => w.pointerOut(e),
- {
- rerender: false,
- }
- );
- })
- );
-
- $(document).on(
- "dblclick.discourse-widget",
- bind(this, (e) => {
- nodeCallback(e.target, DOUBLE_CLICK_ATTRIBUTE_NAME, (w) =>
- w.doubleClick(e)
- );
- })
- );
-
- $(document).on(
- "click.discourse-widget",
- bind(this, (e) => {
- nodeCallback(e.target, CLICK_ATTRIBUTE_NAME, (w) => w.click(e));
-
- let node = e.target;
- const $outside = $("[data-click-outside]");
- $outside.each((i, outNode) => {
- if (
- outNode.contains(node) ||
- (outNode === node && outNode.style.position === "absolute")
- ) {
- return;
- }
-
- const widget2 = outNode[CLICK_OUTSIDE_ATTRIBUTE_NAME];
- if (widget2) {
- widget2.clickOutside(e);
- }
- });
- })
- );
-
- $(document).on(
- "mousedown.discourse-widget",
- bind(this, (e) => {
- let node = e.target;
- const $outside = $("[data-mouse-down-outside]");
- $outside.each((i, outNode) => {
- if (outNode.contains(node)) {
- return;
- }
- const widget2 = outNode[MOUSE_DOWN_OUTSIDE_ATTRIBUTE_NAME];
- if (widget2) {
- widget2.mouseDownOutside(e);
- }
- });
- })
- );
-
- $(document).on(
- "keyup.discourse-widget",
- bind(this, (e) => {
- nodeCallback(e.target, KEY_UP_ATTRIBUTE_NAME, (w) => w.keyUp(e));
- })
- );
-
- $(document).on(
- "keydown.discourse-widget",
- bind(this, (e) => {
- nodeCallback(e.target, KEY_DOWN_ATTRIBUTE_NAME, (w) => w.keyDown(e));
- })
- );
-
- $(document).on(
- "input.discourse-widget",
- bind(this, (e) => {
- nodeCallback(e.target, INPUT_ATTRIBUTE_NAME, (w) => w.input(e), {
- rerender: false,
- });
- })
- );
-
- $(document).on(
- "change.discourse-widget",
- bind(this, (e) => {
- nodeCallback(e.target, CHANGE_ATTRIBUTE_NAME, (w) => w.change(e), {
- rerender: false,
- });
- })
- );
-
- $(document).on(
- "touchend.discourse-widget",
- bind(this, (e) => {
- nodeCallback(e.target, TOUCH_END_ATTRIBUTE_NAME, (w) => w.touchEnd(e), {
- rerender: false,
- });
- })
- );
-
- $(document).on(
- "mousedown.discourse-widget",
- bind(this, (e) => {
- nodeCallback(
- e.target,
- MOUSE_DOWN_ATTRIBUTE_NAME,
- (w) => {
- w.mouseDown(e);
- },
- { rerender: false }
- );
- })
- );
-
- $(document).on(
- "mouseup.discourse-widget",
- bind(this, (e) => {
- nodeCallback(e.target, MOUSE_UP_ATTRIBUTE_NAME, (w) => w.mouseUp(e), {
- rerender: false,
- });
- })
- );
-
- $(document).on(
- "mousemove.discourse-widget",
- bind(this, (e) => {
- nodeCallback(e.target, MOUSE_MOVE_ATTRIBUTE_NAME, (w) => w.mouseMove(e));
- })
- );
-
- _watchingDocument = true;
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+import { warnWidgetsDecommissioned } from "discourse/widgets/widget";
+
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */
+class DummyHook {
+ constructor() {
+ warnWidgetsDecommissioned();
+ }
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ hook() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ unhook() {}
+}
+
+export {
+ DummyHook as WidgetClickHook,
+ DummyHook as WidgetDoubleClickHook,
+ DummyHook as WidgetClickOutsideHook,
+ DummyHook as WidgetMouseDownOutsideHook,
+ DummyHook as WidgetKeyUpHook,
+ DummyHook as WidgetKeyDownHook,
+ DummyHook as WidgetInputHook,
+ DummyHook as WidgetChangeHook,
+ DummyHook as WidgetMouseUpHook,
+ DummyHook as WidgetMouseDownHook,
+ DummyHook as WidgetMouseMoveHook,
+ DummyHook as WidgetMouseOverHook,
+ DummyHook as WidgetPointerOverHook,
+ DummyHook as WidgetPointerOutHook,
+ DummyHook as WidgetMouseOutHook,
+ DummyHook as WidgetTouchEndHook,
+ DummyHook as WidgetTouchStartHook,
+ DummyHook as WidgetTouchMoveHook,
+ DummyHook as WidgetDragHook,
};
diff --git a/frontend/discourse/app/widgets/link.js b/frontend/discourse/app/widgets/link.js
index b7e23750238..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/link.js
+++ b/frontend/discourse/app/widgets/link.js
@@ -1,132 +1,8 @@
-import { h } from "virtual-dom";
-import getURL from "discourse/lib/get-url";
-import { iconNode } from "discourse/lib/icon-library";
-import { wantsNewWindow } from "discourse/lib/intercept-click";
-import DiscourseURL from "discourse/lib/url";
-import { createWidget } from "discourse/widgets/widget";
-import { i18n } from "discourse-i18n";
-
-export default createWidget("link", {
- tagName: "a",
-
- href(attrs) {
- if (attrs.route) {
- const router = this.register.lookup("service:router");
-
- if (attrs.model) {
- return router.urlFor(attrs.route, attrs.model);
- } else {
- return router.urlFor(attrs.route);
- }
- } else {
- return getURL(attrs.href);
- }
- },
-
- buildClasses(attrs) {
- const result = [];
- result.push("widget-link");
- if (attrs.className) {
- result.push(attrs.className);
- }
- return result;
- },
-
- buildAttributes(attrs) {
- const ret = {
- href: this.href(attrs),
- title: attrs.title
- ? i18n(attrs.title, attrs.titleOptions)
- : this.label(attrs),
- };
- if (attrs.attributes) {
- Object.keys(attrs.attributes).forEach(
- (k) => (ret[k] = attrs.attributes[k])
- );
- }
- return ret;
- },
-
- label(attrs) {
- if (attrs.labelCount && attrs.count) {
- return i18n(attrs.labelCount, { count: attrs.count });
- }
- return attrs.rawLabel || (attrs.label ? i18n(attrs.label) : "");
- },
-
- html(attrs) {
- if (attrs.contents) {
- return attrs.contents();
- }
-
- const result = [];
- if (attrs.icon) {
- if (attrs["aria-label"]) {
- let icon = iconNode(attrs.icon);
-
- icon.properties.attributes["aria-label"] = i18n(
- attrs["aria-label"],
- attrs.ariaLabelOptions
- );
-
- icon.properties.attributes["role"] = "img";
- icon.properties.attributes["aria-hidden"] = false;
- result.push(icon);
- } else {
- result.push(iconNode(attrs.icon));
- }
- result.push(" ");
- }
-
- if (!attrs.hideLabel) {
- let label = this.label(attrs);
-
- if (attrs.omitSpan) {
- result.push(label);
- } else {
- result.push(h("span.d-label", label));
- }
- }
-
- const currentUser = this.currentUser;
- if (currentUser && attrs.badgeCount) {
- const val = parseInt(currentUser.get(attrs.badgeCount), 10);
- if (val > 0) {
- const title = attrs.badgeTitle ? i18n(attrs.badgeTitle) : "";
- result.push(" ");
- result.push(
- h(
- "span.badge-notification",
- {
- className: attrs.badgeClass,
- attributes: { title },
- },
- val
- )
- );
- }
- }
- return result;
- },
-
- click(e) {
- if (this.attrs.attributes && this.attrs.attributes.target === "_blank") {
- return;
- }
-
- if (wantsNewWindow(e)) {
- return;
- }
-
- e.preventDefault();
-
- if (this.attrs.action) {
- e.preventDefault();
- return this.sendWidgetAction(this.attrs.action, this.attrs.actionParam);
- } else {
- this.sendWidgetEvent("linkClicked", this.attrs);
- }
-
- return DiscourseURL.routeToTag(e.target.closest("a"));
- },
-});
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/menu-panel.js b/frontend/discourse/app/widgets/menu-panel.js
index 5d6f13858ec..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/menu-panel.js
+++ b/frontend/discourse/app/widgets/menu-panel.js
@@ -1,19 +1,8 @@
-import hbs from "discourse/widgets/hbs-compiler";
-import { createWidget } from "discourse/widgets/widget";
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
-createWidget("menu-panel", {
- tagName: "div.menu-panel",
- template: hbs`
- <div class='panel-body'>
- <div class='panel-body-contents'>
- {{yield}}
- </div>
- </div>
- `,
-
- buildAttributes(attrs) {
- if (attrs.maxWidth) {
- return { "data-max-width": attrs.maxWidth };
- }
- },
-});
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/post-cooked.js b/frontend/discourse/app/widgets/post-cooked.js
index a65e28b3d74..c2b35505b02 100644
--- a/frontend/discourse/app/widgets/post-cooked.js
+++ b/frontend/discourse/app/widgets/post-cooked.js
@@ -1,448 +1,115 @@
-import { spinnerHTML } from "discourse/helpers/loading-spinner";
-import { ajax } from "discourse/lib/ajax";
-import { isValidLink } from "discourse/lib/click-track";
-import escape from "discourse/lib/escape";
-import { number } from "discourse/lib/formatter";
-import { getOwnerWithFallback } from "discourse/lib/get-owner";
-import getURL from "discourse/lib/get-url";
-import highlightHTML, { unhighlightHTML } from "discourse/lib/highlight-html";
-import highlightSearch from "discourse/lib/highlight-search";
-import { iconHTML } from "discourse/lib/icon-library";
-import { applyValueTransformer } from "discourse/lib/transformer";
-import {
- destroyUserStatusOnMentions,
- updateUserStatusOnMention,
-} from "discourse/lib/update-user-status-on-mention";
-import { i18n } from "discourse-i18n";
-
-let _decorators = [];
-
-// Don't call this directly: use `plugin-api/decorateCookedElement`
-export function addDecorator(callback) {
- _decorators.push(callback);
-}
-
-export function resetDecorators() {
- _decorators = [];
-}
-
-let detachedDocument = document.implementation.createHTMLDocument("detached");
-
-function createDetachedElement(nodeName) {
- return detachedDocument.createElement(nodeName);
-}
-
-export default class PostCooked {
- originalQuoteContents = null;
-
- constructor(attrs, decoratorHelper, currentUser) {
- this.attrs = attrs;
- this.expanding = false;
- this._highlighted = false;
- this.decoratorHelper = decoratorHelper;
- this.currentUser = currentUser;
- this.ignoredUsers = this.currentUser
- ? this.currentUser.ignored_users
- : null;
- }
-
- init() {
- this.originalQuoteContents = null;
- // todo should be a better way of detecting if it is composer preview
- this._isInComposerPreview = !this.decoratorHelper;
-
- this.cookedDiv = this._computeCooked();
-
- this._insertQuoteControls(this.cookedDiv);
- this._showLinkCounts(this.cookedDiv);
- this._applySearchHighlight(this.cookedDiv);
- this._decorateMentions();
- this._decorateAndAdopt(this.cookedDiv);
-
- return this.cookedDiv;
- }
-
- update(prev) {
- if (
- prev.attrs.cooked !== this.attrs.cooked ||
- prev.attrs.highlightTerm !== this.attrs.highlightTerm
- ) {
- return this.init();
- }
- }
-
- destroy() {
- this._stopTrackingMentionedUsersStatus();
- destroyUserStatusOnMentions();
- }
-
- _decorateAndAdopt(cooked) {
- _decorators.forEach((d) => d(cooked, this.decoratorHelper));
- document.adoptNode(cooked);
- }
-
- _applySearchHighlight(html) {
- const highlight = this.attrs.highlightTerm;
-
- if (highlight && highlight.length > 2) {
- if (this._highlighted) {
- unhighlightHTML(html);
- }
-
- highlightSearch(html, highlight, { defaultClassName: true });
- this._highlighted = true;
- } else if (this._highlighted) {
- unhighlightHTML(html);
- this._highlighted = false;
- }
- }
-
- _showLinkCounts(html) {
- const linkCounts = this.attrs.linkCounts;
- if (!linkCounts) {
- return;
- }
-
- // find the best <a> element in each onebox and display link counts only
- // for that one (the best element is the most significant one to the
- // viewer)
- const bestElements = new Map();
- html.querySelectorAll("aside.onebox").forEach((onebox) => {
- // look in headings first
- for (let i = 1; i <= 6; ++i) {
- const hLinks = onebox.querySelectorAll(`h${i} a[href]`);
- if (hLinks.length > 0) {
- bestElements.set(onebox, hLinks[0]);
- return;
- }
- }
-
- // use the header otherwise
- const hLinks = onebox.querySelectorAll("header a[href]");
- if (hLinks.length > 0) {
- bestElements.set(onebox, hLinks[0]);
- }
- });
-
- linkCounts.forEach((lc) => {
- if (!lc.clicks || lc.clicks < 1) {
- return;
- }
-
- html.querySelectorAll("a[href]").forEach((link) => {
- const href = link.getAttribute("href");
- let valid = href === lc.url;
-
- // this might be an attachment
- if (lc.internal && /^\/uploads\//.test(lc.url)) {
- valid = href.includes(lc.url);
- }
-
- // match server-side behavior for internal links with query params
- if (lc.internal && /\?/.test(href)) {
- valid = href.split("?")[0] === lc.url;
- }
-
- // don't display badge counts on category badge & oneboxes (unless when explicitly stated)
- if (valid && isValidLink(link)) {
- const onebox = link.closest(".onebox");
-
- if (
- !onebox ||
- !bestElements.has(onebox) ||
- bestElements.get(onebox) === link
- ) {
- link.setAttribute("data-clicks", number(lc.clicks));
- const ariaLabel = `${link.textContent.trim()} ${i18n(
- "post.link_clicked",
- {
- count: lc.clicks,
- }
- )}`;
- link.setAttribute("aria-label", ariaLabel);
- }
- }
- });
- });
- }
-
- async _toggleQuote(aside) {
- if (this.expanding) {
- return;
- }
-
- this.expanding = true;
- const blockQuote = aside.querySelector("blockquote");
-
- if (!blockQuote) {
- return;
- }
-
- if (aside.dataset.expanded) {
- delete aside.dataset.expanded;
- } else {
- aside.dataset.expanded = true;
- }
-
- const quoteId = blockQuote.id;
-
- if (aside.dataset.expanded) {
- this._updateQuoteElements(aside, "chevron-up");
-
- // Show expanded quote
- this.originalQuoteContents.set(quoteId, blockQuote.innerHTML);
-
- const originalText =
- blockQuote.textContent.trim() ||
- this.attrs.cooked.querySelector("blockquote").textContent.trim();
-
- blockQuote.innerHTML = spinnerHTML;
-
- const topicId = parseInt(aside.dataset.topic || this.attrs.topicId, 10);
- const postId = parseInt(aside.dataset.post, 10);
-
- try {
- const result = await ajax(`/posts/by_number/${topicId}/${postId}`);
-
- const post = this._post();
- const quotedPosts = post.quoted || {};
- quotedPosts[result.id] = result;
- post.set("quoted", quotedPosts);
-
- const div = createDetachedElement("div");
- div.classList.add("expanded-quote");
- div.dataset.postId = result.id;
- div.innerHTML = result.cooked;
-
- this._decorateAndAdopt(div);
-
- highlightHTML(div, originalText, {
- matchCase: true,
- });
-
- blockQuote.innerHTML = "";
- blockQuote.appendChild(div);
- } catch (e) {
- if ([403, 404].includes(e.jqXHR.status)) {
- const icon = e.jqXHR.status === 403 ? "lock" : "trash-can";
- blockQuote.innerHTML = `<div class='expanded-quote icon-only'>${iconHTML(
- icon
- )}</div>`;
- }
- }
- } else {
- // Hide expanded quote
- this._updateQuoteElements(aside, "chevron-down");
- blockQuote.innerHTML = this.originalQuoteContents.get(blockQuote.id);
- }
-
- this.expanding = false;
- }
-
- _urlForPostNumber(postNumber) {
- return postNumber > 0
- ? `${this.attrs.topicUrl}/${postNumber}`
- : this.attrs.topicUrl;
- }
-
- _updateQuoteElements(aside, desc) {
- const quoteTitle = i18n("post.follow_quote");
- const postNumber = aside.dataset.post;
- const topicNumber = aside.dataset.topic;
-
- // If we have a post reference
- let navLink = "";
- if (
- topicNumber &&
- postNumber &&
- topicNumber === this.attrs.topicId?.toString()
- ) {
- const icon = iconHTML("arrow-up");
- navLink = `<a href='${this._urlForPostNumber(
- postNumber
- )}' title='${quoteTitle}' aria-label='${quoteTitle}' class='btn-flat back'>${icon}</a>`;
- }
-
- // Only add the expand/contract control if it's not a full post
- const titleElement = aside.querySelector(".title");
- let expandContract = "";
-
- if (!aside.dataset.full) {
- const icon = iconHTML(desc);
- const quoteId = aside.querySelector("blockquote")?.id;
-
- if (quoteId) {
- const isExpanded = aside.dataset.expanded === "true";
- const toggleLabel = isExpanded ? i18n("post.collapse") : i18n("expand");
- expandContract = `<button aria-controls="${quoteId}" aria-expanded="${isExpanded}" aria-label="${toggleLabel}" title="${toggleLabel}" class="quote-toggle btn-flat">${icon}</button>`;
-
- if (titleElement) {
- titleElement.style.cursor = "pointer";
- }
- }
- }
-
- if (this.ignoredUsers?.length && titleElement) {
- const username = titleElement.innerText.trim().slice(0, -1);
-
- if (username.length > 0 && this.ignoredUsers.includes(username)) {
- aside.querySelectorAll("p").forEach((el) => el.remove());
- aside.classList.add("ignored-user");
- }
- }
-
- const quoteControls = aside.querySelector(".quote-controls");
- if (quoteControls) {
- quoteControls.innerHTML = expandContract + navLink;
- }
- }
-
- _insertQuoteControls(html) {
- const quotes = html.querySelectorAll("aside.quote");
- if (quotes.length === 0) {
- return;
- }
-
- this.originalQuoteContents = new Map();
-
- quotes.forEach((aside, index) => {
- if (aside.dataset.post) {
- const quoteId = `quote-id-${aside.dataset.topic}-${aside.dataset.post}-${index}`;
-
- const blockquote = aside.querySelector("blockquote");
- if (blockquote) {
- blockquote.id = quoteId;
- }
-
- this._updateQuoteElements(aside, "chevron-down");
- const title = aside.querySelector(".title");
-
- if (!title) {
- return;
- }
-
- // If post/topic is not found then display username, skip controls
- if (aside.classList.contains("quote-post-not-found")) {
- if (aside.dataset.username) {
- title.innerHTML = escape(aside.dataset.username);
- } else {
- title.remove();
- }
-
- return;
- }
-
- // Unless it's a full quote, allow click to expand
- if (!aside.dataset.full && !title.dataset.hasQuoteControls) {
- title.addEventListener("click", (e) => {
- if (e.target.closest("a")) {
- return true;
- }
-
- this._toggleQuote(aside);
- });
-
- title.dataset.hasQuoteControls = true;
- }
- }
- });
- }
-
- _computeCooked() {
- const cookedDiv = createDetachedElement("div");
- cookedDiv.classList.add("cooked");
-
- if (
- (this.attrs.firstPost || this.attrs.embeddedPost) &&
- this.ignoredUsers?.includes?.(this.attrs.username)
- ) {
- cookedDiv.classList.add("post-ignored");
- cookedDiv.innerHTML = i18n("post.ignored");
- } else {
- cookedDiv.innerHTML = this.attrs.cooked;
- }
-
- // On WebKit-based browsers, triple clicking on the last paragraph of a post won't stop at the end of the paragraph.
- // It looks like the browser is selecting EOL characters, and that causes the selection to leak into the following
- // nodes until it finds a non-empty node. This is a workaround to prevent that from happening.
- // We insert a div after the last paragraph at the end of the cooked content, containing a <br> element.
- // The line break works as a barrier, causing the selection to stop at the correct place.
- // To prevent layout shifts this div is styled to be invisible with height 0 and overflow hidden and set aria-hidden
- // to true to prevent screen readers from reading it.
- const selectionBarrier = document.createElement("div");
- selectionBarrier.classList.add("cooked-selection-barrier");
- selectionBarrier.ariaHidden = "true";
- selectionBarrier.appendChild(document.createElement("br"));
- cookedDiv.appendChild(selectionBarrier);
-
- return cookedDiv;
- }
-
- _decorateMentions() {
- if (!this._isInComposerPreview) {
- destroyUserStatusOnMentions();
- }
-
- this._extractMentions().forEach(({ mentions, user }) => {
- if (!this._isInComposerPreview) {
- this._trackMentionedUserStatus(user);
- this._rerenderUserStatusOnMentions(mentions, user);
- }
-
- const classes = applyValueTransformer("mentions-class", [], {
- user,
- });
-
- mentions.forEach((mention) => {
- mention.classList.add(...classes);
- });
- });
- }
-
- _rerenderUserStatusOnMentions(mentions, user) {
- mentions.forEach((mention) => {
- updateUserStatusOnMention(
- getOwnerWithFallback(this),
- mention,
- user.status
- );
- });
- }
-
- _rerenderUsersStatusOnMentions() {
- this._extractMentions().forEach(({ mentions, user }) => {
- this._rerenderUserStatusOnMentions(mentions, user);
- });
- }
-
- _extractMentions() {
- return (
- this._post()?.mentioned_users?.map((user) => {
- const href = getURL(`/u/${user.username.toLowerCase()}`);
- const mentions = this.cookedDiv.querySelectorAll(
- `a.mention[href="${href}"]`
- );
-
- return { user, mentions };
- }) || []
- );
- }
-
- _trackMentionedUserStatus(user) {
- user.statusManager?.trackStatus?.();
- user.on?.("status-changed", this, "_rerenderUsersStatusOnMentions");
- }
-
- _stopTrackingMentionedUsersStatus() {
- this._post()?.mentioned_users?.forEach((user) => {
- user.statusManager?.stopTrackingStatus?.();
- user.off?.("status-changed", this, "_rerenderUsersStatusOnMentions");
- });
- }
-
- _post() {
- return this.decoratorHelper?.getModel?.();
- }
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+import { warnWidgetsDecommissioned } from "discourse/widgets/widget";
+
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */
+class PostCooked {
+ constructor() {
+ warnWidgetsDecommissioned();
+ }
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ init() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ update() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ destroy() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _decorateAndAdopt() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _applySearchHighlight() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _showLinkCounts() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ async _toggleQuote() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _urlForPostNumber() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _updateQuoteElements() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _insertQuoteControls() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _computeCooked() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _decorateMentions() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _rerenderUserStatusOnMentions() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _rerenderUsersStatusOnMentions() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _extractMentions() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _trackMentionedUserStatus() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _stopTrackingMentionedUsersStatus() {}
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _post() {}
}
-PostCooked.prototype.type = "Widget";
+export {
+ warnWidgetsDecommissioned as addDecorator,
+ warnWidgetsDecommissioned as resetDecorators,
+ PostCooked as default,
+};
diff --git a/frontend/discourse/app/widgets/post-edits-indicator.js b/frontend/discourse/app/widgets/post-edits-indicator.js
index 34ab7054656..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/post-edits-indicator.js
+++ b/frontend/discourse/app/widgets/post-edits-indicator.js
@@ -1,47 +1,8 @@
-import { historyHeat } from "discourse/components/post/meta-data/edits-indicator";
-import { longDate } from "discourse/lib/formatter";
-import { createWidget } from "discourse/widgets/widget";
-import { i18n } from "discourse-i18n";
-
-// glimmer-post-stream: has glimmer version
-export default createWidget("post-edits-indicator", {
- tagName: "div.post-info.edits",
-
- html(attrs) {
- let icon = "pencil";
- const updatedAt = new Date(attrs.updated_at);
- let className = historyHeat(this.siteSettings, updatedAt);
- const date = longDate(updatedAt);
- let title;
-
- if (attrs.wiki) {
- icon = "far-pen-to-square";
- className = `${className || ""} wiki`.trim();
-
- if (attrs.version > 1) {
- title = i18n("post.wiki_last_edited_on", { dateTime: date });
- } else {
- title = i18n("post.wiki.about");
- }
- } else {
- title = i18n("post.last_edited_on", { dateTime: date });
- }
-
- return this.attach("flat-button", {
- icon,
- translatedTitle: title,
- className,
- action: "onPostEditsIndicatorClick",
- translatedAriaLabel: i18n("post.edit_history"),
- translatedLabel: attrs.version > 1 ? attrs.version - 1 : "",
- });
- },
-
- onPostEditsIndicatorClick() {
- if (this.attrs.wiki && this.attrs.version === 1) {
- this.sendWidgetAction("editPost");
- } else if (this.attrs.canViewEditHistory) {
- this.sendWidgetAction("showHistory");
- }
- },
-});
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/post-gap.js b/frontend/discourse/app/widgets/post-gap.js
index 1e3a6ade96e..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/post-gap.js
+++ b/frontend/discourse/app/widgets/post-gap.js
@@ -1,37 +1,8 @@
-import { createWidget } from "discourse/widgets/widget";
-import { i18n } from "discourse-i18n";
-
-export default createWidget("post-gap", {
- tagName: "div.gap",
- buildKey: (attrs) => `post-gap-${attrs.pos}-${attrs.postId}`,
-
- defaultState() {
- return { loading: false };
- },
-
- html(attrs, state) {
- return state.loading
- ? i18n("loading")
- : i18n("post.gap", { count: attrs.gap.length });
- },
-
- click() {
- const { attrs, state } = this;
-
- if (state.loading) {
- return;
- }
- state.loading = true;
-
- const args = { gap: attrs.gap, post: this.model };
- return this.sendWidgetAction(
- attrs.pos === "before" ? "fillGapBefore" : "fillGapAfter",
- args
- ).then(() => {
- state.loading = false;
- this.appEvents.trigger("post-stream:gap-expanded", {
- post_id: this.model.id,
- });
- });
- },
-});
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/post-links.js b/frontend/discourse/app/widgets/post-links.js
index 6dfedd77b52..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/post-links.js
+++ b/frontend/discourse/app/widgets/post-links.js
@@ -1,89 +1,8 @@
-import { h } from "virtual-dom";
-import { uniqueItemsFromArray } from "discourse/lib/array-tools";
-import { iconNode } from "discourse/lib/icon-library";
-import { replaceEmoji } from "discourse/widgets/emoji";
-import { createWidget } from "discourse/widgets/widget";
-
-export default createWidget("post-links", {
- tagName: "div.post-links-container",
- buildKey: (attrs) => `post-links-${attrs.id}`,
-
- defaultState() {
- return { collapsed: true };
- },
-
- linkHtml(link) {
- const linkBody = replaceEmoji(link.title);
- const attributes = {
- href: link.url,
- };
-
- if (link.clicks) {
- attributes["data-clicks"] = link.clicks.toString();
- }
-
- return h(
- "li",
- h(
- "a.track-link",
- {
- className: "inbound",
- attributes,
- },
- [iconNode("link"), linkBody]
- )
- );
- },
-
- html(attrs, state) {
- if (!this.attrs.links || this.attrs.links.length === 0) {
- // shortcut all work
- return;
- }
-
- // only show incoming
- const links = uniqueItemsFromArray(
- this.attrs.links.filter((l) => l.reflection),
- "title"
- );
-
- if (links.length === 0) {
- return;
- }
-
- const result = [];
-
- // show all links
- if (links.length <= 5 || !state.collapsed) {
- links.forEach((l) => result.push(this.linkHtml(l)));
- } else {
- const max = Math.min(5, links.length);
- for (let i = 0; i < max; i++) {
- result.push(this.linkHtml(links[i]));
- }
- // 'show more' link
- if (links.length > max) {
- result.push(
- h(
- "li",
- this.attach("link", {
- labelCount: "post_links.title",
- title: "post_links.about",
- count: links.length - max,
- action: "expandLinks",
- className: "expand-links",
- })
- )
- );
- }
- }
-
- if (result.length) {
- return h("ul.post-links", result);
- }
- },
-
- expandLinks() {
- this.state.collapsed = false;
- },
-});
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/post-placeholder.js b/frontend/discourse/app/widgets/post-placeholder.js
index f66e097ec16..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/post-placeholder.js
+++ b/frontend/discourse/app/widgets/post-placeholder.js
@@ -1,19 +1,8 @@
-import hbs from "discourse/widgets/hbs-compiler";
-import { createWidget } from "discourse/widgets/widget";
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
-// glimmer-post-stream: has glimmer version
-export default createWidget("post-placeholder", {
- tagName: "article.placeholder",
- template: hbs`
- <div class='row'>
- <div class='topic-avatar'>
- <div class='placeholder-avatar placeholder-animation'></div>
- </div>
- <div class='topic-body'>
- <div class='placeholder-text placeholder-animation'></div>
- <div class='placeholder-text placeholder-animation'></div>
- <div class='placeholder-text placeholder-animation'></div>
- </div>
- </div>
- `,
-});
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/post-small-action.js b/frontend/discourse/app/widgets/post-small-action.js
index 08fe7c07dd8..57b6fd6fcb1 100644
--- a/frontend/discourse/app/widgets/post-small-action.js
+++ b/frontend/discourse/app/widgets/post-small-action.js
@@ -1,187 +1,15 @@
-import { computed } from "@ember/object";
-import { htmlSafe } from "@ember/template";
-import { h } from "virtual-dom";
-import {
- customGroupActionCodes,
- GROUP_ACTION_CODES,
- ICONS,
-} from "discourse/components/post/small-action";
-import { autoUpdatingRelativeAge } from "discourse/lib/formatter";
-import { iconNode } from "discourse/lib/icon-library";
-import { userPath } from "discourse/lib/url";
-import DecoratorHelper from "discourse/widgets/decorator-helper";
-import { avatarFor } from "discourse/widgets/post";
-import PostCooked from "discourse/widgets/post-cooked";
-import RawHtml from "discourse/widgets/raw-html";
-import { createWidget } from "discourse/widgets/widget";
-import { i18n } from "discourse-i18n";
-
-export function actionDescriptionHtml(actionCode, createdAt, username, path) {
- const when = createdAt
- ? autoUpdatingRelativeAge(new Date(createdAt), {
- format: "medium-with-ago-and-on",
- })
- : "";
-
- let who = "";
- if (username) {
- if (
- GROUP_ACTION_CODES.includes(actionCode) ||
- customGroupActionCodes.includes(actionCode)
- ) {
- who = `<a class="mention-group" href="/g/${username}">@${username}</a>`;
- } else {
- who = `<a class="mention" href="${userPath(username)}">@${username}</a>`;
- }
- }
- return htmlSafe(i18n(`action_codes.${actionCode}`, { who, when, path }));
-}
-
-export function actionDescription(
- actionCode,
- createdAt,
- username,
- path = null
-) {
- return computed(actionCode, createdAt, function () {
- const ac = this.get(actionCode);
- if (ac) {
- return actionDescriptionHtml(
- ac,
- this.get(createdAt),
- this.get(username),
- path ? this.get(path) : null
- );
- }
- });
-}
-
-const addPostSmallActionClassesCallbacks = [];
-
-export function addPostSmallActionIcon(key, icon) {
- ICONS[key] = icon;
-}
-
-export function addPostSmallActionClassesCallback(callback) {
- addPostSmallActionClassesCallbacks.push(callback);
-}
-
-export function resetPostSmallActionClassesCallbacks() {
- addPostSmallActionClassesCallbacks.length = 0;
-}
-
-// glimmer-post-stream: has glimmer version
-export default createWidget("post-small-action", {
- buildKey: (attrs) => `post-small-act-${attrs.id}`,
- tagName: "article.small-action.onscreen-post",
-
- buildAttributes(attrs) {
- return {
- "aria-label": i18n("share.post", {
- postNumber: attrs.post_number,
- username: attrs.username,
- }),
- role: "region",
- };
- },
-
- buildId(attrs) {
- return `post_${attrs.post_number}`;
- },
-
- buildClasses(attrs) {
- let classNames = [];
-
- if (attrs.deleted) {
- classNames.push("deleted");
- }
-
- if (addPostSmallActionClassesCallbacks.length > 0) {
- addPostSmallActionClassesCallbacks.forEach((callback) => {
- const additionalClasses = callback.call(this, attrs);
-
- if (additionalClasses) {
- classNames.push(...additionalClasses);
- }
- });
- }
-
- return classNames;
- },
-
- html(attrs) {
- const contents = [];
- const buttons = [];
-
- contents.push(
- avatarFor.call(this, "small", {
- template: attrs.avatar_template,
- username: attrs.username,
- url: attrs.usernameUrl,
- ariaHidden: false,
- })
- );
-
- if (attrs.actionDescriptionWidget) {
- contents.push(this.attach(attrs.actionDescriptionWidget, attrs));
- } else {
- const description = actionDescriptionHtml(
- attrs.actionCode,
- new Date(attrs.created_at),
- attrs.actionCodeWho,
- attrs.actionCodePath
- );
- contents.push(new RawHtml({ html: `<p>${description}</p>` }));
- }
-
- if (attrs.canRecover) {
- buttons.push(
- this.attach("button", {
- className: "btn-flat small-action-recover",
- icon: "arrow-rotate-left",
- action: "recoverPost",
- title: "post.controls.undelete",
- })
- );
- }
-
- if (attrs.canEdit && !attrs.canRecover) {
- buttons.push(
- this.attach("button", {
- className: "btn-flat small-action-edit",
- icon: "pencil",
- action: "editPost",
- title: "post.controls.edit",
- })
- );
- }
-
- if (attrs.canDelete) {
- buttons.push(
- this.attach("button", {
- className: "btn-flat btn-danger small-action-delete",
- icon: "trash-can",
- action: "deletePost",
- title: "post.controls.delete",
- })
- );
- }
-
- return [
- h("div.topic-avatar", iconNode(ICONS[attrs.actionCode] || "exclamation")),
- h("div.small-action-desc", [
- h("div.small-action-contents", contents),
- h("div.small-action-buttons", buttons),
- !attrs.actionDescriptionWidget && attrs.cooked
- ? h("div.small-action-custom-message", [
- new PostCooked(
- attrs,
- new DecoratorHelper(this),
- this.currentUser
- ),
- ])
- : null,
- ]),
- ];
- },
-});
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export {
+ warnWidgetsDecommissioned as actionDescriptionHtml,
+ warnWidgetsDecommissioned as actionDescription,
+ warnWidgetsDecommissioned as addPostSmallActionIcon,
+ warnWidgetsDecommissioned as addPostSmallActionClassesCallback,
+ warnWidgetsDecommissioned as resetPostSmallActionClassesCallbacks,
+ DummyWidget as default,
+} from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/post-stream.js b/frontend/discourse/app/widgets/post-stream.js
index 9b47b1405b5..9c5243ea703 100644
--- a/frontend/discourse/app/widgets/post-stream.js
+++ b/frontend/discourse/app/widgets/post-stream.js
@@ -1,348 +1,16 @@
-import { hbs } from "ember-cli-htmlbars";
-import $ from "jquery";
-import { h } from "virtual-dom";
-import { addWidgetCleanCallback } from "discourse/components/mount-widget";
-import discourseDebounce from "discourse/lib/debounce";
-import { registerDeprecationHandler } from "discourse/lib/deprecated";
-import { iconNode } from "discourse/lib/icon-library";
-import { consolePrefix } from "discourse/lib/source-identifier";
-import transformPost from "discourse/lib/transform-post";
-import DiscourseURL from "discourse/lib/url";
-import { Placeholder } from "discourse/models/post-stream";
-import { avatarFor } from "discourse/widgets/post";
-import RenderGlimmer from "discourse/widgets/render-glimmer";
-import {
- createWidget,
- POST_STREAM_DEPRECATION_OPTIONS,
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export {
+ warnWidgetsDecommissioned as postTransformCallbacks,
+ warnWidgetsDecommissioned as addPostTransformCallback,
+ warnWidgetsDecommissioned as disableCloaking,
+ warnWidgetsDecommissioned as preventCloak,
+ warnWidgetsDecommissioned as cloak,
+ warnWidgetsDecommissioned as uncloak,
+ DummyWidget as default,
} from "discourse/widgets/widget";
-import { i18n } from "discourse-i18n";
-
-export let havePostStreamWidgetExtensions = null;
-
-registerDeprecationHandler((_, opts) => {
- if (opts?.id === POST_STREAM_DEPRECATION_OPTIONS.id) {
- if (!havePostStreamWidgetExtensions) {
- havePostStreamWidgetExtensions = new Set();
- }
-
- havePostStreamWidgetExtensions.add(consolePrefix().slice(1, -1));
- }
-});
-
-let transformCallbacks = null;
-
-export function postTransformCallbacks(transformed) {
- if (transformCallbacks === null) {
- return;
- }
-
- for (let i = 0; i < transformCallbacks.length; i++) {
- transformCallbacks[i].call(this, transformed);
- }
-}
-
-export function addPostTransformCallback(callback) {
- transformCallbacks = transformCallbacks || [];
- transformCallbacks.push(callback);
-}
-
-let _enabled = true;
-const DAY = 1000 * 60 * 60 * 24;
-
-const _dontCloak = {};
-let _cloaked = {};
-let _heights = {};
-
-export function disableCloaking() {
- _enabled = false;
-}
-
-export function preventCloak(postId) {
- _dontCloak[postId] = true;
-}
-
-export function cloak(post, component) {
- if (!_enabled || _cloaked[post.id] || _dontCloak[post.id]) {
- return;
- }
-
- const $post = $(`#post_${post.post_number}`).parent();
- _cloaked[post.id] = true;
- _heights[post.id] = $post.outerHeight();
-
- component.dirtyKeys.keyDirty(`post-${post.id}`);
- discourseDebounce(component, "queueRerender", 1000);
-}
-
-export function uncloak(post, component) {
- if (!_enabled || !_cloaked[post.id]) {
- return;
- }
- _cloaked[post.id] = null;
- component.dirtyKeys.keyDirty(`post-${post.id}`);
- component.queueRerender();
-}
-
-addWidgetCleanCallback("post-stream", () => {
- _cloaked = {};
- _heights = {};
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("posts-filtered-notice", {
- buildKey: (attrs) => `posts-filtered-notice-${attrs.id}`,
-
- buildClasses() {
- return ["posts-filtered-notice"];
- },
-
- html(attrs) {
- const filters = attrs.streamFilters;
-
- if (filters.filter_upwards_post_id || filters.mixedHiddenPosts) {
- return [
- h(
- "span.filtered-replies-viewing",
- i18n("post.filtered_replies.viewing_subset")
- ),
- this.attach("filter-show-all", attrs),
- ];
- } else if (filters.replies_to_post_number) {
- const sourcePost = attrs.posts.find(
- (item) => item.post_number === filters.replies_to_post_number
- );
-
- return [
- h(
- "span.filtered-replies-viewing",
- i18n("post.filtered_replies_viewing", {
- count: sourcePost.reply_count,
- })
- ),
- h("span.filtered-user-row", [
- h(
- "span.filtered-avatar",
- avatarFor.call(this, "small", {
- template: sourcePost.avatar_template,
- username: sourcePost.username,
- url: sourcePost.usernameUrl,
- })
- ),
- this.attach("filter-jump-to-post", {
- username: sourcePost.username,
- postNumber: filters.replies_to_post_number,
- }),
- ]),
- this.attach("filter-show-all", attrs),
- ];
- } else if (filters.filter && filters.filter === "summary") {
- return [
- h(
- "span.filtered-replies-viewing",
- i18n("post.filtered_replies.viewing_summary")
- ),
- this.attach("filter-show-all", attrs),
- ];
- } else if (filters.username_filters) {
- const firstUserPost = attrs.posts[1],
- userPostsCount = parseInt(attrs.filteredPostsCount, 10) - 1;
- return [
- h(
- "span.filtered-replies-viewing",
- i18n("post.filtered_replies.viewing_posts_by", {
- post_count: userPostsCount,
- })
- ),
- h(
- "span.filtered-avatar",
- avatarFor.call(this, "small", {
- template: firstUserPost.avatar_template,
- username: firstUserPost.username,
- url: firstUserPost.usernameUrl,
- })
- ),
- this.attach("poster-name", firstUserPost),
- this.attach("filter-show-all", attrs),
- ];
- }
-
- return [];
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("filter-jump-to-post", {
- tagName: "a.filtered-jump-to-post",
- buildKey: (attrs) => `jump-to-post-${attrs.id}`,
-
- html(attrs) {
- return i18n("post.filtered_replies.post_number", {
- username: attrs.username,
- post_number: attrs.postNumber,
- });
- },
-
- click() {
- DiscourseURL.jumpToPost(this.attrs.postNumber);
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("filter-show-all", {
- tagName: "button.filtered-replies-show-all",
- buildKey: (attrs) => `filtered-show-all-${attrs.id}`,
-
- buildClasses() {
- return ["btn", "btn-primary"];
- },
-
- html() {
- return [iconNode("up-down"), i18n("post.filtered_replies.show_all")];
- },
-
- click() {
- this.sendWidgetAction("cancelFilter");
- this.appEvents.trigger(
- "post-stream:filter-show-all",
- this.attrs.streamFilters
- );
- },
-});
-
-export default createWidget("post-stream", {
- tagName: "div.post-stream.widget-post-stream",
-
- html(attrs) {
- const postArray = attrs.posts || [];
- const postArrayLength = postArray.length;
- const maxPostNumber =
- postArrayLength > 0 ? postArray[postArrayLength - 1].post_number : 0;
- const result = [];
- const before = attrs.gaps && attrs.gaps.before ? attrs.gaps.before : {};
- const after = attrs.gaps && attrs.gaps.after ? attrs.gaps.after : {};
- const mobileView = this.site.mobileView;
-
- let prevPost;
- let prevDate;
-
- for (let i = 0; i < postArrayLength; i++) {
- const post = postArray[i];
-
- if (post instanceof Placeholder) {
- result.push(this.attach("post-placeholder"));
- continue;
- }
-
- const nextPost = i < postArray.length - 1 ? postArray[i + 1] : null;
-
- const transformed = transformPost(
- this.currentUser,
- this.site,
- post,
- prevPost,
- nextPost
- );
- transformed.canCreatePost = attrs.canCreatePost;
- transformed.prevPost = prevPost;
- transformed.nextPost = nextPost;
- transformed.mobileView = mobileView;
-
- if (transformed.canManage || transformed.canSplitMergeTopic) {
- transformed.multiSelect = attrs.multiSelect;
-
- if (attrs.multiSelect) {
- transformed.selected = attrs.selectedQuery(post);
- }
- }
-
- if (attrs.searchService) {
- transformed.highlightTerm = attrs.searchService.highlightTerm;
- }
-
- // Post gap - before
- const beforeGap = before[post.id];
- if (beforeGap) {
- result.push(
- this.attach(
- "post-gap",
- { pos: "before", postId: post.id, gap: beforeGap },
- { model: post }
- )
- );
- }
-
- // Handle time gaps
- const curTime = new Date(transformed.created_at).getTime();
- if (prevDate) {
- const daysSince = Math.floor((curTime - prevDate) / DAY);
- if (daysSince > this.siteSettings.show_time_gap_days) {
- result.push(
- new RenderGlimmer(
- this,
- "div.time-gap",
- hbs`<Post::TimeGap @daysSince={{@data.daysSince}} />`,
- { daysSince }
- )
- );
- }
- }
- prevDate = curTime;
-
- transformed.height = _heights[post.id];
- transformed.cloaked = _cloaked[post.id];
-
- postTransformCallbacks(transformed);
-
- if (transformed.isSmallAction) {
- result.push(
- this.attach("post-small-action", transformed, { model: post })
- );
- } else {
- transformed.showReadIndicator = attrs.showReadIndicator;
- result.push(this.attach("post", transformed, { model: post }));
- }
-
- // Post gap - after
- const afterGap = after[post.id];
- if (afterGap) {
- result.push(
- this.attach(
- "post-gap",
- { pos: "after", postId: post.id, gap: afterGap },
- { model: post }
- )
- );
- }
-
- if (
- i !== postArrayLength - 1 &&
- maxPostNumber <= attrs.highestPostNumber &&
- attrs.lastReadPostNumber === post.post_number
- ) {
- result.push(
- this.attach("topic-post-visited-line", {
- post_number: post.post_number,
- })
- );
- }
-
- prevPost = post;
- }
-
- if (
- attrs.streamFilters &&
- Object.keys(attrs.streamFilters).length &&
- (Object.keys(before).length > 0 || Object.keys(after).length > 0)
- ) {
- result.push(
- this.attach("posts-filtered-notice", {
- posts: postArray,
- streamFilters: attrs.streamFilters,
- filteredPostsCount: attrs.filteredPostsCount,
- })
- );
- }
-
- return result;
- },
-});
diff --git a/frontend/discourse/app/widgets/post-user-status.js b/frontend/discourse/app/widgets/post-user-status.js
index c8328a94339..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/post-user-status.js
+++ b/frontend/discourse/app/widgets/post-user-status.js
@@ -1,20 +1,8 @@
-import { hbs } from "ember-cli-htmlbars";
-import RenderGlimmer from "discourse/widgets/render-glimmer";
-import { createWidget } from "discourse/widgets/widget";
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
-createWidget("post-user-status", {
- tagName: "span.user-status-message-wrap",
-
- html(attrs) {
- return [
- new RenderGlimmer(
- this,
- "span",
- hbs`<UserStatusMessage @status={{@data.attrs}} />`,
- {
- attrs,
- }
- ),
- ];
- },
-});
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/post-user-tip-shim.js b/frontend/discourse/app/widgets/post-user-tip-shim.js
deleted file mode 100644
index 5527859079c..00000000000
--- a/frontend/discourse/app/widgets/post-user-tip-shim.js
+++ /dev/null
@@ -1,15 +0,0 @@
-import { hbs } from "ember-cli-htmlbars";
-import { registerWidgetShim } from "discourse/widgets/render-glimmer";
-
-registerWidgetShim(
- "post-user-tip-shim",
- "div.post-user-tip-shim",
- hbs`<UserTip
- @id="post_menu"
- @triggerSelector=".post-controls .actions .show-more-actions"
- @placement="top"
- @titleText={{i18n "user_tips.post_menu.title"}}
- @contentText={{i18n "user_tips.post_menu.content"}}
- @priority={{600}}
- />`
-);
diff --git a/frontend/discourse/app/widgets/post.js b/frontend/discourse/app/widgets/post.js
index 243652548b7..35d56391075 100644
--- a/frontend/discourse/app/widgets/post.js
+++ b/frontend/discourse/app/widgets/post.js
@@ -1,1251 +1,14 @@
-import { getOwner } from "@ember/owner";
-import { hbs } from "ember-cli-htmlbars";
-import { Promise } from "rsvp";
-import { h } from "virtual-dom";
-import ShareTopicModal from "discourse/components/modal/share-topic";
-import PostMetaDataLanguage from "discourse/components/post/meta-data/language";
-import { dateNode } from "discourse/helpers/node";
-import autoGroupFlairForUser from "discourse/lib/avatar-flair";
-import { avatarUrl, translateSize } from "discourse/lib/avatar-utils";
-import { isTesting } from "discourse/lib/environment";
-import { relativeAgeMediumSpan } from "discourse/lib/formatter";
-import getURL, { getAbsoluteURL, getURLWithCDN } from "discourse/lib/get-url";
-import { iconNode } from "discourse/lib/icon-library";
-import postActionFeedback from "discourse/lib/post-action-feedback";
-import { nativeShare } from "discourse/lib/pwa-utils";
-import {
- prioritizeNameFallback,
- prioritizeNameInUx,
-} from "discourse/lib/settings";
-import { transformBasicPost } from "discourse/lib/transform-post";
-import DiscourseURL from "discourse/lib/url";
-import {
- clipboardCopy,
- escapeExpression,
- formatUsername,
-} from "discourse/lib/utilities";
-import DecoratorHelper from "discourse/widgets/decorator-helper";
-import widgetHbs from "discourse/widgets/hbs-compiler";
-import PostCooked from "discourse/widgets/post-cooked";
-import { postTransformCallbacks } from "discourse/widgets/post-stream";
-import RawHtml from "discourse/widgets/raw-html";
-import RenderGlimmer, {
- registerWidgetShim,
-} from "discourse/widgets/render-glimmer";
-import { applyDecorators, createWidget } from "discourse/widgets/widget";
-import { i18n } from "discourse-i18n";
-
-function transformWithCallbacks(post, topicUrl, store) {
- let transformed = transformBasicPost(post);
- postTransformCallbacks(transformed);
-
- transformed.customShare = `${topicUrl}/${post.post_number}`;
- transformed.asPost = store.createRecord("post", post);
-
- return transformed;
-}
-
-export function avatarImg(wanted, attrs) {
- const size = translateSize(wanted);
- const url = avatarUrl(attrs.template, size);
-
- // We won't render an invalid url
- if (!url || url.length === 0) {
- return;
- }
-
- let title;
- if (!attrs.hideTitle) {
- title = attrs.name || formatUsername(attrs.username);
- }
-
- let alt = "";
- if (attrs.alt) {
- alt = i18n(attrs.alt);
- }
-
- let className =
- "avatar" + (attrs.extraClasses ? " " + attrs.extraClasses : "");
-
- const properties = {
- attributes: {
- alt,
- width: size,
- height: size,
- src: getURLWithCDN(url),
- title,
- "aria-hidden": true,
- loading: "lazy",
- tabindex: "-1",
- },
- className,
- };
-
- return h("img", properties);
-}
-
-// glimmer-post-stream: has glimmer version
-export function avatarFor(wanted, attrs, linkAttrs) {
- const attributes = {
- href: attrs.url,
- "data-user-card": attrs.username,
- };
-
- // often avatars are paired with usernames,
- // making them redundant for screen readers
- // so we hide the avatar from screen readers by default
- if (attrs.ariaHidden === false) {
- attributes["aria-label"] = i18n("user.profile_possessive", {
- username: attrs.username,
- });
- } else {
- attributes["aria-hidden"] = true;
- }
-
- if (linkAttrs) {
- Object.assign(attributes, linkAttrs);
- }
- return h(
- "a",
- {
- className: `trigger-user-card ${attrs.className || ""}`,
- attributes,
- },
- avatarImg(wanted, attrs)
- );
-}
-
-// glimmer-post-stream: has glimmer version
-createWidget("select-post", {
- tagName: "div.select-posts",
-
- html(attrs) {
- const buttons = [];
-
- if (!attrs.selected && attrs.post_number > 1) {
- if (attrs.replyCount > 0) {
- buttons.push(
- this.attach("button", {
- label: "topic.multi_select.select_replies.label",
- title: "topic.multi_select.select_replies.title",
- action: "selectReplies",
- className: "select-replies",
- })
- );
- }
- buttons.push(
- this.attach("button", {
- label: "topic.multi_select.select_below.label",
- title: "topic.multi_select.select_below.title",
- action: "selectBelow",
- className: "select-below",
- })
- );
- }
-
- const key = `topic.multi_select.${
- attrs.selected ? "selected" : "select"
- }_post`;
- buttons.push(
- this.attach("button", {
- label: key + ".label",
- title: key + ".title",
- action: "togglePostSelection",
- className: "select-post",
- })
- );
-
- return buttons;
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("reply-to-tab", {
- tagName: "a.reply-to-tab",
- buildKey: (attrs) => `reply-to-tab-${attrs.id}`,
- title: "post.in_reply_to",
- defaultState() {
- return { loading: false };
- },
-
- buildAttributes(attrs) {
- let result = {
- href: "",
- };
-
- if (!attrs.mobileView) {
- result["role"] = "button";
- result["aria-controls"] = `embedded-posts__top--${attrs.post_number}`;
- result["aria-expanded"] = (attrs.repliesAbove.length > 0).toString();
- }
-
- return result;
- },
-
- html(attrs, state) {
- const icon = state.loading ? h("div.spinner.small") : iconNode("share");
- const name = prioritizeNameFallback(
- attrs.replyToName,
- attrs.replyToUsername
- );
-
- return [
- icon,
- " ",
- avatarImg("small", {
- template: attrs.replyToAvatarTemplate,
- username: name,
- }),
- " ",
- h("span", formatUsername(name)),
- ];
- },
-
- click(event) {
- event.preventDefault();
- this.state.loading = true;
- this.sendWidgetAction("toggleReplyAbove").then(
- () => (this.state.loading = false)
- );
- },
-});
-
-createWidget("post-avatar-user-info", {
- tagName: "div.post-avatar-user-info",
-
- html(attrs) {
- return this.attach("poster-name", attrs);
- },
-});
-
-createWidget("post-avatar", {
- tagName: "div.topic-avatar",
-
- settings: {
- size: "large",
- displayPosterName: false,
- },
-
- html(attrs) {
- let body;
- let hideFromAnonUser =
- this.siteSettings.hide_user_profiles_from_public && !this.currentUser;
- if (!attrs.user_id) {
- body = iconNode("trash-can", { class: "deleted-user-avatar" });
- } else {
- body = avatarFor.call(
- this,
- this.settings.size,
- {
- template: attrs.avatar_template,
- username: attrs.username,
- name: attrs.name,
- url: attrs.usernameUrl,
- className: `main-avatar ${hideFromAnonUser ? "non-clickable" : ""}`,
- hideTitle: true,
- },
- {
- tabindex: "-1",
- }
- );
- }
-
- const postAvatarBody = [body];
-
- if (attrs.flair_group_id) {
- if (attrs.flair_url || attrs.flair_bg_color) {
- postAvatarBody.push(this.attach("avatar-flair", attrs));
- } else {
- const autoFlairAttrs = autoGroupFlairForUser(this.site, attrs);
-
- if (autoFlairAttrs) {
- postAvatarBody.push(this.attach("avatar-flair", autoFlairAttrs));
- }
- }
- }
-
- const result = [h("div.post-avatar", postAvatarBody)];
-
- if (this.settings.displayPosterName) {
- result.push(this.attach("post-avatar-user-info", attrs));
- }
-
- return result;
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("post-locked-indicator", {
- tagName: "div.post-info.post-locked",
- template: widgetHbs`{{d-icon "lock"}}`,
- title: () => i18n("post.locked"),
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("post-email-indicator", {
- tagName: "div.post-info.via-email",
-
- title(attrs) {
- return attrs.isAutoGenerated
- ? i18n("post.via_auto_generated_email")
- : i18n("post.via_email");
- },
-
- buildClasses(attrs) {
- return attrs.canViewRawEmail ? "raw-email" : null;
- },
-
- html(attrs) {
- return attrs.isAutoGenerated
- ? iconNode("envelope")
- : iconNode("far-envelope");
- },
-
- click() {
- if (this.attrs.canViewRawEmail) {
- this.sendWidgetAction("showRawEmail");
- }
- },
-});
-
-function showReplyTab(attrs, siteSettings) {
- return (
- attrs.replyToUsername &&
- (!attrs.replyDirectlyAbove || !siteSettings.suppress_reply_directly_above)
- );
-}
-
-// glimmer-post-stream: has glimmer version
-createWidget("post-meta-data", {
- tagName: "div.topic-meta-data",
-
- buildAttributes() {
- return {
- role: "heading",
- "aria-level": "2",
- };
- },
-
- settings: {
- displayPosterName: true,
- },
-
- html(attrs) {
- let postInfo = [];
-
- if (attrs.isWhisper) {
- const groups = this.site.get("whispers_allowed_groups_names");
- let title = "";
-
- if (groups?.length > 0) {
- title = i18n("post.whisper_groups", {
- groupNames: groups.join(", "),
- });
- } else {
- title = i18n("post.whisper");
- }
-
- postInfo.push(
- h(
- "div.post-info.whisper",
- {
- attributes: { title },
- },
- iconNode("far-eye-slash")
- )
- );
- }
-
- if (attrs.via_email) {
- postInfo.push(this.attach("post-email-indicator", attrs));
- }
-
- if (attrs.locked) {
- postInfo.push(this.attach("post-locked-indicator", attrs));
- }
-
- if (attrs.version > 1 || attrs.wiki) {
- postInfo.push(this.attach("post-edits-indicator", attrs));
- }
-
- if (attrs.multiSelect) {
- postInfo.push(this.attach("select-post", attrs));
- }
-
- if (showReplyTab(attrs, this.siteSettings)) {
- postInfo.push(this.attach("reply-to-tab", attrs));
- }
-
- if (attrs.language && attrs.is_localized) {
- postInfo.push(this.attach("post-language", attrs));
- }
-
- postInfo.push(this.attach("post-date", attrs));
-
- postInfo.push(
- h(
- "div.read-state",
- {
- className: attrs.read ? "read" : null,
- attributes: {
- title: i18n("post.unread"),
- },
- },
- iconNode("circle")
- )
- );
-
- let result = [];
- if (this.settings.displayPosterName) {
- result.push(this.attach("poster-name", attrs));
- }
- result.push(h("div.post-infos", postInfo));
-
- return result;
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("expand-hidden", {
- tagName: "a.expand-hidden",
-
- html() {
- return i18n("post.show_hidden");
- },
-
- click() {
- this.sendWidgetAction("expandHidden");
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("post-date", {
- tagName: "div.post-info.post-date",
-
- html(attrs) {
- let date,
- linkClassName = "post-date";
-
- if (attrs.wiki && attrs.lastWikiEdit) {
- linkClassName += " last-wiki-edit";
- date = new Date(attrs.lastWikiEdit);
- } else {
- date = new Date(attrs.created_at);
- }
- return this.attach("link", {
- rawLabel: dateNode(date),
- className: linkClassName,
- omitSpan: true,
- title: "post.sr_date",
- href: attrs.shareUrl,
- action: "showShareModal",
- });
- },
-
- showShareModal() {
- const post = this.findAncestorModel();
- const topic = post.topic;
- getOwner(this)
- .lookup("service:modal")
- .show(ShareTopicModal, {
- model: { category: topic.category, topic, post },
- });
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("post-language", {
- html(attrs) {
- return [
- new RenderGlimmer(this, "div", PostMetaDataLanguage, {
- language: attrs.language,
- localization_outdated: attrs.localization_outdated,
- }),
- ];
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("expand-post-button", {
- tagName: "button.btn.expand-post",
- buildKey: (attrs) => `expand-post-button-${attrs.id}`,
-
- defaultState() {
- return { loadingExpanded: false };
- },
-
- html(attrs, state) {
- if (state.loadingExpanded) {
- return i18n("loading");
- } else {
- return [i18n("post.show_full"), "..."];
- }
- },
-
- click() {
- this.state.loadingExpanded = true;
- this.sendWidgetAction("expandFirstPost");
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("post-group-request", {
- buildKey: (attrs) => `post-group-request-${attrs.id}`,
-
- buildClasses() {
- return ["group-request"];
- },
-
- html(attrs) {
- const href = getURL(
- "/g/" + attrs.requestedGroupName + "/requests?filter=" + attrs.username
- );
-
- return h("a", { attributes: { href } }, i18n("groups.requests.handle"));
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("post-contents", {
- buildKey: (attrs) => `post-contents-${attrs.id}`,
-
- defaultState(attrs) {
- const defaultState = {
- expandedFirstPost: false,
- repliesBelow: [],
- };
-
- if (this.siteSettings.enable_filtered_replies_view) {
- const topicController = this.register.lookup("controller:topic");
-
- if (attrs.post_number) {
- defaultState.filteredRepliesShown =
- topicController.replies_to_post_number ===
- attrs.post_number.toString();
- }
- }
-
- return defaultState;
- },
-
- buildClasses(attrs) {
- const classes = ["regular"];
- if (!this.state.repliesShown) {
- classes.push("contents");
- }
- if (showReplyTab(attrs, this.siteSettings)) {
- classes.push("avoid-tab");
- }
- return classes;
- },
-
- html(attrs, state) {
- let result = [
- new PostCooked(attrs, new DecoratorHelper(this), this.currentUser),
- ];
-
- if (attrs.requestedGroupName) {
- result.push(this.attach("post-group-request", attrs));
- }
-
- result = result.concat(applyDecorators(this, "after-cooked", attrs, state));
-
- if (attrs.cooked_hidden && attrs.canSeeHiddenPost) {
- result.push(this.attach("expand-hidden", attrs));
- }
-
- if (!state.expandedFirstPost && attrs.expandablePost) {
- result.push(this.attach("expand-post-button", attrs));
- }
-
- const extraState = {
- state: {
- repliesShown: state.repliesBelow.length > 0,
- filteredRepliesShown: state.filteredRepliesShown,
- },
- };
-
- const filteredRepliesView = this.siteSettings.enable_filtered_replies_view;
- result.push(
- // TODO (glimmer-post-stream):
- // Once this widget shim is removed the `<section>...</section>` tag needs to be added to the PostMenu component
- new RenderGlimmer(
- this,
- "section.post-menu-area.clearfix",
- hbs`
- <Post::Menu
- @canCreatePost={{@data.canCreatePost}}
- @filteredRepliesView={{@data.filteredRepliesView}}
- @nextPost={{@data.nextPost}}
- @post={{@data.post}}
- @prevPost={{@data.prevPost}}
- @repliesShown={{@data.repliesShown}}
- @showReadIndicator={{@data.showReadIndicator}}
- @changeNotice={{@data.changeNotice}}
- @changePostOwner={{@data.changePostOwner}}
- @copyLink={{@data.copyLink}}
- @deletePost={{@data.deletePost}}
- @editPost={{@data.editPost}}
- @grantBadge={{@data.grantBadge}}
- @lockPost={{@data.lockPost}}
- @permanentlyDeletePost={{@data.permanentlyDeletePost}}
- @rebakePost={{@data.rebakePost}}
- @recoverPost={{@data.recoverPost}}
- @replyToPost={{@data.replyToPost}}
- @share={{@data.share}}
- @showFlags={{@data.showFlags}}
- @showLogin={{@data.showLogin}}
- @showPagePublish={{@data.showPagePublish}}
- @toggleLike={{@data.toggleLike}}
- @togglePostType={{@data.togglePostType}}
- @toggleReplies={{@data.toggleReplies}}
- @toggleWiki={{@data.toggleWiki}}
- @unhidePost={{@data.unhidePost}}
- @unlockPost={{@data.unlockPost}}
- />`,
- {
- canCreatePost: attrs.canCreatePost,
- filteredRepliesView,
- nextPost: attrs.nextPost,
- post: this.findAncestorModel(),
- prevPost: attrs.prevPost,
- repliesShown: filteredRepliesView
- ? extraState.state.filteredRepliesShown
- : extraState.state.repliesShown,
- showReadIndicator: attrs.showReadIndicator,
- changeNotice: () => this.sendWidgetAction("changeNotice"), // this action comes from the post stream
- changePostOwner: () => this.sendWidgetAction("changePostOwner"), // this action comes from the post stream
- copyLink: () => this.sendWidgetAction("copyLink"),
- deletePost: () => this.sendWidgetAction("deletePost"), // this action comes from the post stream
- editPost: () => this.sendWidgetAction("editPost"), // this action comes from the post stream
- expandHidden: () => this.sendWidgetAction("editPost"), // this action comes from the post stream
- grantBadge: () => this.sendWidgetAction("grantBadge"), // this action comes from the post stream
- lockPost: () => this.sendWidgetAction("lockPost"), // this action comes from the post stream
- permanentlyDeletePost: () =>
- this.sendWidgetAction("permanentlyDeletePost"),
- rebakePost: () => this.sendWidgetAction("rebakePost"), // this action comes from the post stream
- recoverPost: () => this.sendWidgetAction("recoverPost"), // this action comes from the post stream
- replyToPost: () => this.sendWidgetAction("replyToPost"), // this action comes from the post stream
- share: () => this.sendWidgetAction("share"),
- showFlags: () => this.sendWidgetAction("showFlags"), // this action comes from the post stream
- showLogin: () => this.sendWidgetAction("showLogin"), // this action comes from application route
- showPagePublish: () => this.sendWidgetAction("showPagePublish"), // this action comes from the post stream
- toggleLike: () => this.sendWidgetAction("toggleLike"),
- togglePostType: () => this.sendWidgetAction("togglePostType"), // this action comes from the post stream
- toggleReplies: filteredRepliesView
- ? () => this.sendWidgetAction("toggleFilteredRepliesView")
- : () => this.sendWidgetAction("toggleRepliesBelow"),
- toggleWiki: () => this.sendWidgetAction("toggleWiki"), // this action comes from the post stream
- unhidePost: () => this.sendWidgetAction("unhidePost"), // this action comes from the post stream
- unlockPost: () => this.sendWidgetAction("unlockPost"), // this action comes from the post stream
- }
- )
- );
-
- const repliesBelow = state.repliesBelow;
- if (repliesBelow.length) {
- let children = [];
-
- repliesBelow.forEach((p) => {
- children.push(
- this.attach("embedded-post", p, {
- model: p.asPost,
- state: {
- role: "region",
- "aria-label": i18n("post.sr_embedded_reply_description", {
- post_number: attrs.post_number,
- username: p.username,
- }),
- },
- })
- );
- });
-
- children.push(
- this.attach("button", {
- title: "post.collapse",
- icon: "chevron-up",
- action: "toggleRepliesBelow",
- actionParam: true,
- className: "btn collapse-up",
- translatedAriaLabel: i18n("post.sr_collapse_replies"),
- })
- );
-
- if (repliesBelow.length < this.attrs.replyCount) {
- children.push(
- this.attach("button", {
- label: "post.load_more_replies",
- action: "loadMoreReplies",
- actionParam: repliesBelow[repliesBelow.length - 1]?.post_number,
- className: "btn load-more-replies",
- })
- );
- }
-
- result.push(
- h(
- `section.embedded-posts.bottom#embedded-posts__bottom--${this.attrs.post_number}`,
- children
- )
- );
- }
-
- return result;
- },
-
- _date(attrs) {
- const lastWikiEdit =
- attrs.wiki && attrs.lastWikiEdit && new Date(attrs.lastWikiEdit);
- const createdAt = new Date(attrs.created_at);
- return lastWikiEdit ? lastWikiEdit : createdAt;
- },
-
- toggleFilteredRepliesView() {
- const post = this.findAncestorModel(),
- controller = this.register.lookup("controller:topic"),
- currentFilterPostNumber = post.get(
- "topic.postStream.filterRepliesToPostNumber"
- );
-
- if (
- currentFilterPostNumber &&
- currentFilterPostNumber === post.post_number
- ) {
- controller.send("cancelFilter", currentFilterPostNumber);
- this.state.filteredRepliesShown = false;
- return Promise.resolve();
- } else {
- this.state.filteredRepliesShown = true;
-
- return post
- .get("topic.postStream")
- .filterReplies(post.post_number, post.id)
- .then(() => {
- controller.updateQueryParams();
- });
- }
- },
-
- loadMoreReplies(after = 1) {
- return this.store
- .find("post-reply", { postId: this.attrs.id, after })
- .then((replies) => {
- replies.forEach((reply) => {
- this.state.repliesBelow.push(
- transformWithCallbacks(reply, this.attrs.topicUrl, this.store)
- );
- });
- });
- },
-
- toggleRepliesBelow(goToPost = false) {
- if (this.state.repliesBelow.length) {
- this.state.repliesBelow = [];
- if (goToPost === true) {
- const { topicUrl, post_number } = this.attrs;
- DiscourseURL.routeTo(`${topicUrl}/${post_number}`);
- }
- } else {
- return this.loadMoreReplies();
- }
- },
-
- expandFirstPost() {
- const post = this.findAncestorModel();
- return post.expand().then(() => (this.state.expandedFirstPost = true));
- },
-
- share() {
- const post = this.findAncestorModel();
- nativeShare(this.capabilities, { url: post.shareUrl }).catch(() => {
- const topic = post.topic;
- getOwner(this)
- .lookup("service:modal")
- .show(ShareTopicModal, {
- model: { category: topic.category, topic, post },
- });
- });
- },
-
- copyLink() {
- // Copying the link to clipboard on mobile doesn't make sense.
- if (this.site.mobileView) {
- return this.share();
- }
-
- const post = this.findAncestorModel();
- const postId = post.id;
-
- let actionCallback = () => clipboardCopy(getAbsoluteURL(post.shareUrl));
-
- // Can't use clipboard in JS tests.
- if (isTesting()) {
- actionCallback = () => {};
- }
-
- postActionFeedback({
- postId,
- actionClass: "post-action-menu__copy-link",
- messageKey: "post.controls.link_copied",
- actionCallback,
- errorCallback: () => this.share(),
- });
- },
-
- init() {
- // TODO (glimmer-post-stream): How does this fit into the Glimmer lifecycle?
- this.postContentsDestroyCallbacks = [];
- },
-
- destroy() {
- this.postContentsDestroyCallbacks.forEach((c) => c());
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("post-notice", {
- tagName: "div.post-notice",
-
- buildClasses(attrs) {
- const classes = [attrs.notice.type.replace(/_/g, "-")];
-
- if (
- new Date() - new Date(attrs.created_at) >
- this.siteSettings.old_post_notice_days * 86400000
- ) {
- classes.push("old");
- }
-
- return classes;
- },
-
- html(attrs) {
- if (attrs.notice.type === "custom") {
- let createdByHTML = "";
- if (attrs.noticeCreatedByUser) {
- const createdByName = escapeExpression(
- prioritizeNameInUx(attrs.noticeCreatedByUser.name)
- ? attrs.noticeCreatedByUser.name
- : attrs.noticeCreatedByUser.username
- );
- createdByHTML = i18n("post.notice.custom_created_by", {
- userLinkHTML: `<a
- class="trigger-user-card"
- data-user-card="${attrs.noticeCreatedByUser.username}"
- title="${createdByName}"
- aria-hidden="false"
- role="listitem"
- >${createdByName}</a>`,
- });
- }
- return [
- iconNode("user-shield"),
- new RawHtml({
- html: `<div class="post-notice-message">${attrs.notice.cooked} ${createdByHTML}</div>`,
- }),
- ];
- }
-
- const user =
- this.siteSettings.display_name_on_posts && prioritizeNameInUx(attrs.name)
- ? attrs.name
- : attrs.username;
-
- if (attrs.notice.type === "new_user") {
- return [
- iconNode("handshake-angle"),
- h("p", i18n("post.notice.new_user", { user })),
- ];
- }
-
- if (attrs.notice.type === "returning_user") {
- const timeAgo = (new Date() - new Date(attrs.notice.lastPostedAt)) / 1000;
- const time = relativeAgeMediumSpan(timeAgo, true);
- return [
- iconNode("far-face-smile"),
- h("p", i18n("post.notice.returning_user", { user, time })),
- ];
- }
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("post-body", {
- tagName: "div.topic-body.clearfix",
-
- html(attrs, state) {
- const post = this.findAncestorModel();
- const postContents = this.attach("post-contents", attrs);
- let result = [this.attach("post-meta-data", attrs)];
- result = result.concat(
- applyDecorators(this, "after-meta-data", attrs, state)
- );
- result.push(postContents);
- result.push(this.attach("actions-summary", { post }));
- result.push(this.attach("post-links", attrs));
-
- return result;
- },
-});
-
-// glimmer-post-stream: has glimmer version
-createWidget("post-article", {
- tagName: "article.boxed.onscreen-post",
- buildKey: (attrs) => `post-article-${attrs.id}`,
-
- defaultState() {
- return { repliesAbove: [] };
- },
-
- buildId(attrs) {
- return `post_${attrs.post_number}`;
- },
-
- buildClasses(attrs, state) {
- let classNames = [];
- if (state.repliesAbove.length) {
- classNames.push("replies-above");
- }
- if (attrs.via_email) {
- classNames.push("via-email");
- }
- if (attrs.isAutoGenerated) {
- classNames.push("is-auto-generated");
- }
- return classNames;
- },
-
- buildAttributes(attrs) {
- return {
- "aria-label": i18n("share.post", {
- postNumber: attrs.post_number,
- username: attrs.username,
- }),
- role: "region",
- "data-post-id": attrs.id,
- "data-topic-id": attrs.topicId,
- "data-user-id": attrs.user_id,
- };
- },
-
- html(attrs, state) {
- const rows = [];
- if (state.repliesAbove.length) {
- const replies = state.repliesAbove.map((p) => {
- return this.attach("embedded-post", p, {
- model: p.asPost,
- state: { above: true },
- });
- });
-
- rows.push(
- h(
- "div.row",
- h(
- `section.embedded-posts.top.topic-body#embedded-posts__top--${attrs.post_number}`,
- [
- this.attach("button", {
- title: "post.collapse",
- icon: "chevron-down",
- action: "toggleReplyAbove",
- actionParam: true,
- className: "btn collapse-down",
- }),
- replies,
- ]
- )
- )
- );
- }
-
- if (!attrs.deleted_at && attrs.notice) {
- rows.push(h("div.row", [this.attach("post-notice", attrs)]));
- }
-
- rows.push(
- h("div.row", [
- this.attach("post-avatar", attrs),
- this.attach("post-body", {
- ...attrs,
- repliesAbove: state.repliesAbove,
- }),
- ])
- );
-
- if (this.shouldShowTopicMap(attrs)) {
- rows.push(this.buildTopicMap(attrs));
- }
-
- return rows;
- },
-
- _getTopicUrl() {
- const post = this.findAncestorModel();
- return post ? post.get("topic.url") : null;
- },
-
- toggleReplyAbove(goToPost = false) {
- const replyPostNumber = this.attrs.reply_to_post_number;
-
- if (this.siteSettings.enable_filtered_replies_view) {
- const post = this.findAncestorModel();
- const controller = this.register.lookup("controller:topic");
- return post
- .get("topic.postStream")
- .filterUpwards(this.attrs.id)
- .then(() => {
- controller.updateQueryParams();
- });
- }
-
- // jump directly on mobile
- if (this.attrs.mobileView) {
- const topicUrl = this._getTopicUrl();
- if (topicUrl) {
- DiscourseURL.routeTo(`${topicUrl}/${replyPostNumber}`);
- }
- return Promise.resolve();
- }
-
- if (this.state.repliesAbove.length) {
- this.state.repliesAbove = [];
- if (goToPost === true) {
- const { topicUrl, post_number } = this.attrs;
- DiscourseURL.routeTo(`${topicUrl}/${post_number}`);
- }
- return Promise.resolve();
- } else {
- const topicUrl = this._getTopicUrl();
- return this.store
- .find("post-reply-history", { postId: this.attrs.id })
- .then((posts) => {
- posts.content.forEach((post) => {
- this.state.repliesAbove.push(
- transformWithCallbacks(post, topicUrl, this.store)
- );
- });
- });
- }
- },
-
- shouldShowTopicMap(attrs) {
- if (attrs.post_number !== 1) {
- return false;
- }
- const isPM = attrs.topic.archetype === "private_message";
- const isRegular = attrs.topic.archetype === "regular";
- const showWithoutReplies =
- this.siteSettings.show_topic_map_in_topics_without_replies;
-
- return (
- attrs.topicMap ||
- isPM ||
- (isRegular && (attrs.topic.posts_count > 1 || showWithoutReplies))
- );
- },
-
- buildTopicMap(attrs) {
- return new RenderGlimmer(
- this,
- "div.topic-map.--op",
- hbs`
- <TopicMap
- @model={{@data.model}}
- @topicDetails={{@data.topicDetails}}
- @postStream={{@data.postStream}}
- @showPMMap={{@data.showPMMap}}
- @showInvite={{@data.showInvite}}
- @removeAllowedGroup={{@data.removeAllowedGroup}}
- @removeAllowedUser={{@data.removeAllowedUser}}
- />`,
- {
- model: attrs.topic,
- topicDetails: attrs.topic.get("details"),
- postStream: attrs.topic.postStream,
- showPMMap: attrs.topic.archetype === "private_message",
- showInvite: () => this.sendWidgetAction("showInvite"),
- removeAllowedGroup: (group) =>
- this.sendWidgetAction("removeAllowedGroup", group),
- removeAllowedUser: (user) =>
- this.sendWidgetAction("removeAllowedUser", user),
- }
- );
- },
-});
-
-const addPostClassesCallbacks = [];
-
-export function addPostClassesCallback(callback) {
- addPostClassesCallbacks.push(callback);
-}
-
-// only for testing purposes
-export function resetPostClassesCallback() {
- addPostClassesCallbacks.length = 0;
-}
-
-// glimmer-post-stream: has glimmer version
-export default createWidget("post", {
- buildKey: (attrs) => `post-${attrs.id}`,
- services: ["dialog", "user-tips"],
- shadowTree: true,
-
- buildAttributes(attrs) {
- const heightStyle = attrs.height
- ? { style: `min-height: ${attrs.height}px` }
- : undefined;
-
- return { "data-post-number": attrs.post_number, ...heightStyle };
- },
-
- buildId(attrs) {
- return attrs.cloaked ? `post_${attrs.post_number}` : undefined;
- },
-
- buildClasses(attrs) {
- if (attrs.cloaked) {
- return "cloaked-post";
- }
- const classNames = ["topic-post", "clearfix"];
-
- if (!attrs.mobileView) {
- classNames.push("sticky-avatar");
- }
- if (attrs.id === -1 || attrs.isSaving || attrs.staged) {
- classNames.push("staged");
- }
- if (attrs.selected) {
- classNames.push("selected");
- }
- if (attrs.topicOwner) {
- classNames.push("topic-owner");
- }
- if (this.currentUser && attrs.user_id === this.currentUser.id) {
- classNames.push("current-user-post");
- }
- if (attrs.groupModerator) {
- classNames.push("category-moderator");
- }
- if (attrs.hidden) {
- classNames.push("post-hidden");
- }
- if (attrs.deleted) {
- classNames.push("deleted");
- }
- if (attrs.primary_group_name) {
- classNames.push(`group-${attrs.primary_group_name}`);
- }
- if (attrs.wiki) {
- classNames.push(`wiki`);
- }
- if (attrs.isWhisper) {
- classNames.push("whisper");
- }
- if (attrs.isModeratorAction || (attrs.isWarning && attrs.firstPost)) {
- classNames.push("moderator");
- } else {
- classNames.push("regular");
- }
- if (attrs.userSuspended) {
- classNames.push("user-suspended");
- }
- if (addPostClassesCallbacks) {
- for (let i = 0; i < addPostClassesCallbacks.length; i++) {
- let pluginClasses = addPostClassesCallbacks[i].call(this, attrs);
- if (pluginClasses) {
- classNames.push.apply(classNames, pluginClasses);
- }
- }
- }
- return classNames;
- },
-
- html(attrs) {
- if (attrs.cloaked) {
- return "";
- }
-
- return [this.attach("post-article", attrs)];
- },
-
- async toggleLike() {
- const post = this.model;
- const likeAction = post.get("likeAction");
-
- if (likeAction && likeAction.get("canToggle")) {
- const result = await likeAction.togglePromise(post);
-
- this.appEvents.trigger("page:like-toggled", post, likeAction);
- return this._warnIfClose(result);
- }
- },
-
- _warnIfClose(result) {
- if (!result || !result.acted) {
- return;
- }
-
- const kvs = this.keyValueStore;
- const lastWarnedLikes = kvs.get("lastWarnedLikes");
-
- // only warn once per day
- const yesterday = Date.now() - 1000 * 60 * 60 * 24;
- if (lastWarnedLikes && parseInt(lastWarnedLikes, 10) > yesterday) {
- return;
- }
-
- const { remaining, max } = result;
- const threshold = Math.ceil(max * 0.1);
- if (remaining === threshold) {
- this.dialog.alert(i18n("post.few_likes_left"));
- kvs.set({ key: "lastWarnedLikes", value: Date.now() });
- }
- },
-});
-
-// TODO (glimmer-post-stream): Once this widget is removed the `<section>...</section>` tag needs to be added to the PostMenu component
-registerWidgetShim(
- "glimmer-post",
- "div",
- hbs`
- <Post
- @canCreatePost={{@data.canCreatePost}}
- @cancelFilter={{@data.cancelFilter}}
- @changeNotice={{@data.changeNotice}}
- @changePostOwner={{@data.changePostOwner}}
- @deletePost={{@data.deletePost}}
- @editPost={{@data.editPost}}
- @expandHidden={{@expandHidden}}
- @filteringRepliesToPostNumber={{@data.filteringRepliesToPostNumber}}
- @grantBadge={{@data.grantBadge}}
- @lockPost={{@data.lockPost}}
- @multiSelect={{@data.multiSelect}}
- @nextPost={{@data.nextPost}}
- @permanentlyDeletePost={{@data.permanentlyDeletePost}}
- @post={{@data.post}}
- @prevPost={{@data.prevPost}}
- @rebakePost={{@data.rebakePost}}
- @recoverPost={{@data.recoverPost}}
- @replyToPost={{@data.replyToPost}}
- @selectBelow={{@data.selectBelow}}
- @selectReplies={{@data.selectReplies}}
- @selected={{@data.selected}}
- @showFlags={{@data.showFlags}}
- @showHistory={{@data.showHistory}}
- @showInvite={{@data.showInvite}}
- @showLogin={{@data.showLogin}}
- @showPagePublish={{@data.showPagePublish}}
- @showRawEmail={{@data.showRawEmail}}
- @showReadIndicator={{@data.showReadIndicator}}
- @togglePostSelection={{@data.togglePostSelection}}
- @togglePostType={{@data.togglePostType}}
- @toggleReplies={{@toggleReplies}}
- @toggleReplyAbove={{@data.toggleReplyAbove}}
- @toggleWiki={{@data.toggleWiki}}
- @topicPageQueryParams={{@data.topicPageQueryParams}}
- @unhidePost={{@data.unhidePost}}
- @unlockPost={{@data.unlockPost}}
- @updateTopicPageQueryParams={{@data.updateTopicPageQueryParams}}
- />`
-);
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export {
+ warnWidgetsDecommissioned as avatarImg,
+ warnWidgetsDecommissioned as avatarFor,
+ warnWidgetsDecommissioned as addPostClassesCallback,
+ warnWidgetsDecommissioned as resetPostClassesCallback,
+ DummyWidget as default,
+} from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/poster-name.js b/frontend/discourse/app/widgets/poster-name.js
index 3b47ec996d0..7ccd8e05d88 100644
--- a/frontend/discourse/app/widgets/poster-name.js
+++ b/frontend/discourse/app/widgets/poster-name.js
@@ -1,235 +1,11 @@
-import { hbs } from "ember-cli-htmlbars";
-import { h } from "virtual-dom";
-import getURL from "discourse/lib/get-url";
-import { iconNode } from "discourse/lib/icon-library";
-import { prioritizeNameInUx } from "discourse/lib/settings";
-import { applyValueTransformer } from "discourse/lib/transformer";
-import { formatUsername } from "discourse/lib/utilities";
-import RenderGlimmer from "discourse/widgets/render-glimmer";
-import { applyDecorators, createWidget } from "discourse/widgets/widget";
-import { i18n } from "discourse-i18n";
-
-let sanitizeName = function (name) {
- return name.toLowerCase().replace(/[\s\._-]/g, "");
-};
-
-export function disableNameSuppression() {
- sanitizeName = (name) => name;
-}
-
-// glimmer-post-stream: has glimmer version
-createWidget("poster-name-title", {
- tagName: "span.user-title",
-
- buildClasses(attrs) {
- let classNames = [];
-
- classNames.push(attrs.title);
-
- if (attrs.titleIsGroup) {
- classNames.push(attrs.primaryGroupName);
- }
-
- classNames = classNames.map(
- (className) =>
- `user-title--${className.replace(/\s+/g, "-").toLowerCase()}`
- );
-
- return classNames;
- },
-
- html(attrs) {
- let titleContents = attrs.title;
- if (attrs.primaryGroupName && attrs.titleIsGroup) {
- const href = getURL(`/g/${attrs.primaryGroupName}`);
- titleContents = h(
- "a.user-group",
- {
- className: attrs.extraClasses,
- attributes: { href, "data-group-card": attrs.primaryGroupName },
- },
- attrs.title
- );
- }
- return titleContents;
- },
-});
-
-// glimmer-post-stream: has glimmer version
-export default createWidget("poster-name", {
- tagName: "div.names.trigger-user-card",
-
- settings: {
- showNameAndGroup: true,
- showGlyph: true,
- },
-
- didRenderWidget() {
- if (this.attrs.user) {
- this.attrs.user.statusManager.trackStatus();
- this.attrs.user.on("status-changed", this, "scheduleRerender");
- }
- },
-
- willRerenderWidget() {
- if (this.attrs.user) {
- this.attrs.user.off("status-changed", this, "scheduleRerender");
- this.attrs.user.statusManager.stopTrackingStatus();
- }
- },
-
- // TODO: Allow extensibility
- posterGlyph(attrs) {
- if (attrs.moderator || attrs.groupModerator) {
- return iconNode("shield-halved", {
- title: i18n("user.moderator_tooltip"),
- });
- }
- },
-
- userLink(attrs, text) {
- return h(
- "a",
- {
- attributes: {
- href: attrs.usernameUrl,
- "data-user-card": attrs.username,
- class: `${
- this.siteSettings.hide_user_profiles_from_public &&
- !this.currentUser
- ? "non-clickable"
- : ""
- }`,
- },
- },
- formatUsername(text)
- );
- },
-
- additionalClasses(attrs) {
- return applyValueTransformer("poster-name-class", [], {
- user: attrs.user,
- });
- },
-
- html(attrs) {
- const username = attrs.username;
- const name = attrs.name;
- const nameFirst =
- this.siteSettings.display_name_on_posts && prioritizeNameInUx(name);
- const classNames = nameFirst
- ? ["first", "full-name"]
- : ["first", "username"];
-
- if (attrs.staff) {
- classNames.push("staff");
- }
- if (attrs.admin) {
- classNames.push("admin");
- }
- if (attrs.moderator) {
- classNames.push("moderator");
- }
- if (attrs.groupModerator) {
- classNames.push("category-moderator");
- }
- if (attrs.new_user) {
- classNames.push("new-user");
- }
- classNames.push(...this.additionalClasses(attrs));
-
- const primaryGroupName = attrs.primary_group_name;
- if (primaryGroupName && primaryGroupName.length) {
- classNames.push(`group--${primaryGroupName}`);
- }
- let nameContents = [this.userLink(attrs, nameFirst ? name : username)];
-
- if (this.settings.showGlyph) {
- const glyph = this.posterGlyph(attrs);
- if (glyph) {
- nameContents.push(glyph);
- }
- }
-
- const afterNameContents =
- applyDecorators(this, "after-name", attrs, this.state) || [];
-
- nameContents = nameContents.concat(afterNameContents);
-
- const contents = [
- h("span", { className: classNames.join(" ") }, nameContents),
- ];
-
- if (this.settings.showNameAndGroup) {
- if (
- name &&
- this.siteSettings.display_name_on_posts &&
- sanitizeName(name) !== sanitizeName(username)
- ) {
- contents.push(
- h(
- "span.second." + (nameFirst ? "username" : "full-name"),
- [this.userLink(attrs, nameFirst ? username : name)].concat(
- afterNameContents
- )
- )
- );
- }
-
- this.buildTitleObject(attrs, contents);
-
- if (this.siteSettings.enable_user_status) {
- this.addUserStatus(contents, attrs);
- }
- }
-
- if (attrs.badgesGranted?.length) {
- const badges = [];
-
- attrs.badgesGranted.forEach((badge) => {
- // Alter the badge description to show that the badge was granted for this post.
- badge.description = i18n("post.badge_granted_tooltip", {
- username: attrs.username,
- badge_name: badge.name,
- });
-
- const badgeIcon = new RenderGlimmer(
- this,
- `span.user-badge-button-${badge.slug}`,
- hbs`<UserBadge @badge={{@data.badge}} @user={{@data.user}} @showName={{false}} />`,
- {
- badge,
- user: attrs.user,
- }
- );
- badges.push(badgeIcon);
- });
-
- contents.push(h("span.user-badge-buttons", badges));
- }
-
- return contents;
- },
-
- buildTitleObject(attrs, contents) {
- const primaryGroupName = attrs.primary_group_name;
- const title = attrs.user_title,
- titleIsGroup = attrs.title_is_group;
-
- if (title && title.length) {
- contents.push(
- this.attach("poster-name-title", {
- title,
- primaryGroupName,
- titleIsGroup,
- })
- );
- }
- },
-
- addUserStatus(contents, attrs) {
- if (attrs.user && attrs.user.status) {
- contents.push(this.attach("post-user-status", attrs.user.status));
- }
- },
-});
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+export {
+ warnWidgetsDecommissioned as disableNameSuppression,
+ DummyWidget as default,
+} from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/raw-html.js b/frontend/discourse/app/widgets/raw-html.js
index c9b7539c907..2b54b5d4b67 100644
--- a/frontend/discourse/app/widgets/raw-html.js
+++ b/frontend/discourse/app/widgets/raw-html.js
@@ -1,26 +1,39 @@
-import $ from "jquery";
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+import { warnWidgetsDecommissioned } from "discourse/widgets/widget";
+
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */
export default class RawHtml {
- constructor(attrs) {
- this.html = attrs.html;
+ constructor() {
+ warnWidgetsDecommissioned();
}
- init() {
- const $html = $(this.html);
- this.decorate($html);
- return $html[0];
- }
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ init() {}
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
decorate() {}
- update(prev) {
- if (prev.html === this.html) {
- return;
- }
- return this.init();
- }
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ update() {}
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
destroy() {}
}
-
-RawHtml.prototype.type = "Widget";
diff --git a/frontend/discourse/app/widgets/render-glimmer.js b/frontend/discourse/app/widgets/render-glimmer.js
index 9f5852e885f..a9b5d83270b 100644
--- a/frontend/discourse/app/widgets/render-glimmer.js
+++ b/frontend/discourse/app/widgets/render-glimmer.js
@@ -1,260 +1,51 @@
-import { hasInternalComponentManager } from "@glimmer/manager";
-import { tracked } from "@glimmer/tracking";
-import { setComponentTemplate } from "@ember/component";
-import templateOnly from "@ember/component/template-only";
-import { assert } from "@ember/debug";
-import { getOwnerWithFallback } from "discourse/lib/get-owner";
-import {
- createWidgetFrom,
- warnWidgetsDeprecation,
-} from "discourse/widgets/widget";
-
-const INITIAL_CLASSES = Symbol("RENDER_GLIMMER_INITIAL_CLASSES");
-
-/*
-
-This class allows you to render arbitrary Glimmer templates inside widgets.
-That glimmer template can include Classic and/or Glimmer components.
-
-Example usage:
-
-```
-import { hbs } from "ember-cli-htmlbars";
-
-// NOTE: If your file is already importing the `hbs` helper from "discourse/widgets/hbs-compiler"
-// you'll need to rename that import to `import widgetHbs from "discourse/widgets/hbs-compiler"`
-// before adding the `ember-cli-htmlbars` import.
-
-...
-
-// (inside an existing widget)
-html(){
- return [
- new RenderGlimmer(
- this,
- "div.my-wrapper-class",
- hbs`<MyComponent @arg1={{@data.arg1}} />`,
- {
- arg1: "some argument value"
- }
- ),
- ]
-}
-```
-
-You can also include function references in the `data` object, and use them as actions within the Ember component.
-You will need to `bind` the function to ensure it maintains a reference to the widget, and you'll need to manually
-call `this.scheduleRerender()` after making any changes to widget state (the normal widget auto-rerendering does not apply).
-
-Note that the @bind decorator will only work if you're using class-based Widget syntax. When using createWidget, you'll need to
-call `.bind(this)` manually when passing the function to RenderGlimmer.
-
-For example:
-```
-createWidget("my-widget", {
- tagName: "div",
- buildKey: () => `my-widget`,
-
- defaultState() {
- return { counter: 0 };
- },
-
- html(args, state){
- return [
- new RenderGlimmer(
- this,
- "div.my-wrapper-class",
- hbs`<MyComponent @counter={{@data.counter}} @incrementCounter={{@data.incrementCounter}} />`,
- {
- counter: state.counter,
- incrementCounter: this.incrementCounter.bind(this),
- }
- ),
- ]
- },
-
- incrementCounter() {
- this.state.counter++;
- this.scheduleRerender();
- },
-});
-
-To dynamically control the attributes of the wrapper element, a helper function is provided as an argument to your hbs template.
-To use this via a template, you can do something like this:
-```
-hbs`{{@setWrapperElementAttrs class="some class value" title="title value"}}`
-```
-If you prefer, you can pass this function down into your own components, and call it from there. Invoked as a helper, this can
-be passed (auto-)tracked values, and will update the wrapper element attributes whenever the inputs.
-*/
-
-export default class RenderGlimmer {
- /**
- * Create a RenderGlimmer instance
- * @param widget - the widget instance which is rendering this content
- * @param renderInto - a string describing a new wrapper element (e.g. `div.my-class`),
- * or an existing HTML element to append content into.
- * @param template - a glimmer template compiled via ember-cli-htmlbars
- * @param data - will be made available at `@data` in your template
- */
- constructor(widget, renderInto, template, data) {
- assert(
- "`template` should be a template compiled via `ember-cli-htmlbars`, or a component",
- template.name === "factory" || hasInternalComponentManager(template)
- );
- this.renderInto = renderInto;
- if (widget) {
- this.widget = widget;
- }
- this.template = template;
- this.data = data;
- }
-
- init() {
- if (this.renderInto instanceof Element) {
- this.element = this.renderInto;
- } else {
- const [type, ...classNames] = this.renderInto.split(".");
- this.element = document.createElement(type);
- this.element.classList.add(...classNames);
- this.element[INITIAL_CLASSES] = classNames;
- }
- this.connectComponent();
- return this.element;
- }
-
- destroy() {
- if (this._componentInfo) {
- this.parentMountWidgetComponent.unmountChildComponent(
- this._componentInfo
- );
- }
- }
-
- update(prev) {
- if (
- prev.template.__id !== this.template.__id ||
- prev.renderInto !== this.renderInto
- ) {
- // Totally different component, but the widget framework guessed it was the
- // same widget. Destroy old component and re-init the new one.
- prev.destroy();
- return this.init();
- }
-
- this._componentInfo = prev._componentInfo;
- if (prev.data !== this.data) {
- this._componentInfo.data = this.data;
- }
-
- return null;
- }
-
- connectComponent() {
- const { element, template } = this;
-
- let component;
- if (hasInternalComponentManager(template)) {
- component = template;
- } else {
- component = templateOnly();
- component.name = "Widgets/RenderGlimmer";
- setComponentTemplate(template, component);
- }
-
- this._componentInfo = new ComponentInfo({
- element,
- component,
- data: this.data,
- setWrapperElementAttrs: (attrs) =>
- this.updateElementAttrs(element, attrs),
- });
-
- this.parentMountWidgetComponent.mountChildComponent(this._componentInfo);
- }
-
- updateElementAttrs(element, attrs) {
- for (let [key, value] of Object.entries(attrs)) {
- if (key === "class") {
- value = [element[INITIAL_CLASSES], value].filter(Boolean).join(" ");
- }
-
- if ([null, undefined].includes(value)) {
- element.removeAttribute(key);
- } else {
- element.setAttribute(key, value);
- }
- }
- }
-
- get parentMountWidgetComponent() {
- if (this._emberView) {
- return this._emberView;
- }
- // Work up parent widgets until we find one with a _emberView
- // attribute. `.parentWidget` is the normal way to work up the tree,
- // but we use `attrs._postCookedWidget` to handle the special case
- // of widgets rendered inside post-cooked.
- let widget = this.widget;
- while (widget) {
- const component = widget._emberView;
- if (component) {
- return component;
- }
- widget = widget.parentWidget || widget.attrs._postCookedWidget;
- }
- }
-}
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
-RenderGlimmer.prototype.type = "Widget";
+import { warnWidgetsDecommissioned } from "discourse/widgets/widget";
/**
- * Define a widget shim which renders a Glimmer template. Designed for incrementally migrating
- * a widget-based UI to Glimmer. Widget attrs will be made available to your template at `@data`.
- * For more details, see documentation for the RenderGlimmer class.
- * @param name - the widget's name (which can then be used in `.attach` elsewhere)
- * @param tagName - a string describing a new wrapper element (e.g. `div.my-class`)
- * @param template - a glimmer template compiled via ember-cli-htmlbars
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
*/
-export function registerWidgetShim(name, tagName, template) {
- if (
- getOwnerWithFallback(this)?.lookup(`service:site-settings`)
- ?.deactivate_widgets_rendering
- ) {
- warnWidgetsDeprecation(
- `Widgets are deactivated. Your site may not work properly. Affected widget: ${name}.`
- );
- } else {
- warnWidgetsDeprecation(
- `Using \`registerWidgetShim\` is deprecated and will soon stop working. Affected widgetShim: ${name}.`
- );
+export default class RenderGlimmer {
+ constructor() {
+ warnWidgetsDecommissioned();
}
- const RenderGlimmerShim = class MyClass extends RenderGlimmer {
- constructor(attrs) {
- super(null, tagName, template, attrs);
- return this;
- }
-
- get widget() {
- return this.parentWidget;
- }
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ init() {}
- didRenderWidget() {}
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ destroy() {}
- willRerenderWidget() {}
- };
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ update() {}
- createWidgetFrom(RenderGlimmerShim, name, {});
-}
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ connectComponent() {}
-class ComponentInfo {
- @tracked data;
- element;
- component;
- setWrapperElementAttrs;
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ updateElementAttrs() {}
- constructor(params) {
- Object.assign(this, params);
- }
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ get parentMountWidgetComponent() {}
}
+
+export { createWidgetFrom as registerWidgetShim } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/topic-post-visited-line.js b/frontend/discourse/app/widgets/topic-post-visited-line.js
index 5011b23855f..9d410856b6e 100644
--- a/frontend/discourse/app/widgets/topic-post-visited-line.js
+++ b/frontend/discourse/app/widgets/topic-post-visited-line.js
@@ -1,14 +1,8 @@
-import { h } from "virtual-dom";
-import { createWidget } from "discourse/widgets/widget";
-import { i18n } from "discourse-i18n";
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
-export default createWidget("topic-post-visited-line", {
- tagName: "div.small-action.topic-post-visited",
-
- html(attrs) {
- return h(
- `div.topic-post-visited-line.post-${attrs.post_number}}`,
- h("span.topic-post-visited-message", i18n("topics.new_messages_marker"))
- );
- },
-});
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/topic-status.js b/frontend/discourse/app/widgets/topic-status.js
deleted file mode 100644
index 5ccc916fcc8..00000000000
--- a/frontend/discourse/app/widgets/topic-status.js
+++ /dev/null
@@ -1,12 +0,0 @@
-import { hbs } from "ember-cli-htmlbars";
-import { registerWidgetShim } from "discourse/widgets/render-glimmer";
-
-registerWidgetShim(
- "topic-status",
- "span.topic-statuses",
- hbs`<TopicStatus
- @topic={{@data.topic}}
- @disableActions={{@data.disableActions}}
- @tagName=""
- />`
-);
diff --git a/frontend/discourse/app/widgets/virtual-dom.js b/frontend/discourse/app/widgets/virtual-dom.js
new file mode 100644
index 00000000000..c916e7ce3cd
--- /dev/null
+++ b/frontend/discourse/app/widgets/virtual-dom.js
@@ -0,0 +1,14 @@
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+/**
+ * This is a shim used to prevent breaking imports from "virtual-dom"
+ */
+export {
+ warnWidgetsDecommissioned as create,
+ warnWidgetsDecommissioned as h,
+} from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/widget-dropdown.js b/frontend/discourse/app/widgets/widget-dropdown.js
index 611edfb896e..e9c9d5ef76f 100644
--- a/frontend/discourse/app/widgets/widget-dropdown.js
+++ b/frontend/discourse/app/widgets/widget-dropdown.js
@@ -1,325 +1,156 @@
-import { schedule } from "@ember/runloop";
-import { createPopper } from "@popperjs/core";
-import hbs from "discourse/widgets/hbs-compiler";
-import { createWidget } from "discourse/widgets/widget";
-import { i18n } from "discourse-i18n";
-
-/*
-
- widget-dropdown
-
- Usage
- -----
-
- {{attach
- widget="widget-dropdown"
- attrs=(hash
- id=id
- label=label
- content=content
- onChange=onChange
- options=(hash)
- )
- }}
-
- Mandatory attributes:
-
- - id: must be unique in the application
-
- - label or translatedLabel:
- - label: an i18n key to be translated and displayed on the header
- - translatedLabel: an already translated label to display on the header
-
- - onChange: action called when a click happens on a row, content[rowIndex] will be passed as params
-
- Optional attributes:
-
- - class: adds css class to the dropdown
- - content: list of items to display, if undefined or empty dropdown won't display
- Example content:
-
- ```
- [
- { id: 1, label: "foo.bar" },
- "separator",
- { id: 2, translatedLabel: "FooBar" },
- { id: 3 label: "foo.baz", icon: "xmark" },
- { id: 4, html: "<b>foo</b>" }
- ]
- ```
-
- - options: accepts a hash of optional attributes
- - headerClass: adds css class to the dropdown header
- - bodyClass: adds css class to the dropdown header
- - caret: adds a caret to visually enforce this is a dropdown
- - disabled: adds disabled css class and lock dropdown
-*/
-
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */
export const WidgetDropdownHeaderClass = {
- tagName: "button",
-
- transform(attrs) {
- return { label: this._buildLabel(attrs) };
- },
-
- buildAttributes(attrs) {
- return { title: this._buildLabel(attrs) };
- },
-
- buildClasses(attrs) {
- let classes = ["widget-dropdown-header", "btn", "btn-default"];
- if (attrs.class) {
- classes = classes.concat(attrs.class.split(" "));
- }
- return classes.filter(Boolean).join(" ");
- },
-
- click(event) {
- event.preventDefault();
-
- this.sendWidgetAction("_onTrigger");
- },
-
- template: hbs`
- {{#if attrs.icon}}
- {{d-icon attrs.icon}}
- {{/if}}
- <span class="label">
- {{transformed.label}}
- </span>
- {{#if attrs.caret}}
- {{d-icon "caret-down"}}
- {{/if}}
- `,
-
- _buildLabel(attrs) {
- return attrs.translatedLabel ? attrs.translatedLabel : i18n(attrs.label);
- },
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ transform() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ buildAttributes() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ buildClasses() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ click() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _buildLabel() {},
};
-createWidget("widget-dropdown-header", WidgetDropdownHeaderClass);
-
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */
export const WidgetDropdownItemClass = {
- tagName: "div",
-
- transform(attrs) {
- return {
- content:
- attrs.item === "separator"
- ? "<hr>"
- : attrs.item.html
- ? attrs.item.html
- : attrs.item.translatedLabel
- ? attrs.item.translatedLabel
- : i18n(attrs.item.label),
- };
- },
-
- buildAttributes(attrs) {
- return {
- "data-id": attrs.item.id,
- tabindex: attrs.item === "separator" ? -1 : 0,
- };
- },
-
- buildClasses(attrs) {
- const classes = [
- "widget-dropdown-item",
- attrs.item === "separator" ? "separator" : `item-${attrs.item.id}`,
- ];
- classes.push(attrs.item.disabled ? "disabled" : "");
- return classes.join(" ");
- },
-
- keyDown(event) {
- if (event.key === "Enter") {
- event.preventDefault();
- this.sendWidgetAction("_onChange", this.attrs.item);
- }
- },
-
- click(event) {
- event.preventDefault();
-
- this.sendWidgetAction("_onChange", this.attrs.item);
- },
-
- template: hbs`
- {{#if attrs.item.icon}}
- {{d-icon attrs.item.icon}}
- {{/if}}
- {{{transformed.content}}}
- `,
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ transform() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ buildAttributes() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ buildClasses() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ keyDown() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ click() {},
};
-createWidget("widget-dropdown-item", WidgetDropdownItemClass);
-
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */
export const WidgetDropdownBodyClass = {
- tagName: "div",
-
- buildClasses(attrs) {
- return `widget-dropdown-body ${attrs.class || ""}`;
- },
-
- clickOutside() {
- this.sendWidgetAction("hideBody");
- },
-
- template: hbs`
- {{#each attrs.content as |item|}}
- {{attach
- widget="widget-dropdown-item"
- attrs=(hash item=item)
- }}
- {{/each}}
- `,
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ buildClasses() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ clickOutside() {},
};
-createWidget("widget-dropdown-body", WidgetDropdownBodyClass);
-
+/**
+ * This class is kept only for backward compatibility.
+ *
+ * @deprecated This class is part of the decommissioned widget system and should not be used anymore.
+ */
export const WidgetDropdownClass = {
- tagName: "div",
-
- init(attrs) {
- if (!attrs) {
- throw "A widget-dropdown expects attributes.";
- }
-
- if (!attrs.id) {
- throw "A widget-dropdown expects a unique `id` attribute.";
- }
-
- if (!attrs.label && !attrs.translatedLabel) {
- throw "A widget-dropdown expects at least a `label` or `translatedLabel`";
- }
- },
-
- buildKey: (attrs) => {
- return attrs.id;
- },
-
- buildAttributes(attrs) {
- return { id: attrs.id };
- },
-
- defaultState(attrs) {
- return {
- opened: false,
- disabled: (attrs.options && attrs.options.disabled) || false,
- };
- },
-
- buildClasses(attrs) {
- const classes = ["widget-dropdown"];
- classes.push(this.state.opened ? "opened" : "closed");
- classes.push(this.state.disabled ? "disabled" : "");
- return classes.join(" ") + " " + (attrs.class || "");
- },
-
- transform(attrs) {
- return {
- options: attrs.options || {},
- isDropdownVisible: !this.state.disabled && this.state.opened,
- };
- },
-
- hideBody() {
- this.state.opened = false;
- },
-
- _onChange(params) {
- if (params.disabled) {
- return;
- }
- this.state.opened = false;
-
- if (this.attrs.onChange) {
- if (typeof this.attrs.onChange === "string") {
- this.sendWidgetAction(this.attrs.onChange, params);
- } else {
- this.attrs.onChange(params);
- }
- }
- },
-
- destroy() {
- if (this._popper) {
- this._popper.destroy();
- this._popper = null;
- }
- },
-
- willRerenderWidget() {
- this._popper && this._popper.destroy();
- },
-
- didRenderWidget() {
- if (this.state.opened) {
- schedule("afterRender", () => {
- const dropdownHeader = document.querySelector(
- `#${this.attrs.id} .widget-dropdown-header`
- );
-
- if (!dropdownHeader) {
- return;
- }
-
- const dropdownBody = document.querySelector(
- `#${this.attrs.id} .widget-dropdown-body`
- );
-
- if (!dropdownBody) {
- return;
- }
-
- this._popper = createPopper(dropdownHeader, dropdownBody, {
- strategy: "absolute",
- placement: "bottom-start",
- modifiers: [
- {
- name: "preventOverflow",
- },
- {
- name: "offset",
- options: {
- offset: [0, 5],
- },
- },
- ],
- });
- });
- }
- },
-
- _onTrigger() {
- this.state.opened = !this.state.opened;
- },
-
- template: hbs`
- {{#if attrs.content}}
- {{attach
- widget="widget-dropdown-header"
- attrs=(hash
- icon=attrs.icon
- label=attrs.label
- translatedLabel=attrs.translatedLabel
- class=this.transformed.options.headerClass
- caret=this.transformed.options.caret
- )
- }}
-
- {{#if this.transformed.isDropdownVisible}}
- {{attach
- widget="widget-dropdown-body"
- attrs=(hash
- id=attrs.id
- class=this.transformed.options.bodyClass
- content=attrs.content
- )
- }}
- {{/if}}
- {{/if}}
- `,
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ init() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ buildKey() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ buildAttributes() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ defaultState() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ buildClasses() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ transform() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ hideBody() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _onChange() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ destroy() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ willRerenderWidget() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ didRenderWidget() {},
+
+ /**
+ * @deprecated the widget rendering system was decommissioned
+ */
+ _onTrigger() {},
};
-export default createWidget("widget-dropdown", WidgetDropdownClass);
+export { DummyWidget as default } from "discourse/widgets/widget";
diff --git a/frontend/discourse/app/widgets/widget.js b/frontend/discourse/app/widgets/widget.js
index 7f2f2bb662b..ceec58fff3b 100644
--- a/frontend/discourse/app/widgets/widget.js
+++ b/frontend/discourse/app/widgets/widget.js
@@ -1,36 +1,12 @@
-import { get } from "@ember/object";
-import { getOwner, setOwner } from "@ember/owner";
-import { camelize } from "@ember/string";
-import { Promise } from "rsvp";
-import { h } from "virtual-dom";
-import deprecated, { isDeprecationSilenced } from "discourse/lib/deprecated";
-import { isProduction } from "discourse/lib/environment";
-import { getOwnerWithFallback } from "discourse/lib/get-owner";
-import { deepMerge } from "discourse/lib/object";
+/**
+ * IMPORTANT: The widget rendering system has been decommissioned.
+ *
+ * This file is maintained only to prevent breaking imports in existing third-party customizations.
+ * New code should not use this component or the widget system.
+ */
+
+import deprecated from "discourse/lib/deprecated";
import { consolePrefix } from "discourse/lib/source-identifier";
-import DecoratorHelper from "discourse/widgets/decorator-helper";
-import {
- WidgetChangeHook,
- WidgetClickHook,
- WidgetClickOutsideHook,
- WidgetDoubleClickHook,
- WidgetDragHook,
- WidgetInputHook,
- WidgetKeyDownHook,
- WidgetKeyUpHook,
- WidgetMouseDownHook,
- WidgetMouseDownOutsideHook,
- WidgetMouseMoveHook,
- WidgetMouseOutHook,
- WidgetMouseOverHook,
- WidgetMouseUpHook,
- WidgetPointerOutHook,
- WidgetPointerOverHook,
- WidgetTouchEndHook,
- WidgetTouchMoveHook,
- WidgetTouchStartHook,
-} from "discourse/widgets/hooks";
-import { i18n } from "discourse-i18n";
export const WIDGET_DEPRECATION_OPTIONS = {
since: "v3.5.0.beta8-dev",
@@ -44,533 +20,46 @@ export const POST_STREAM_DEPRECATION_OPTIONS = {
url: "https://meta.discourse.org/t/372063/1",
};
-export function warnWidgetsDeprecation(message, dontSkipCore = false) {
- if (
- (dontSkipCore || consolePrefix()) &&
- !isDeprecationSilenced(POST_STREAM_DEPRECATION_OPTIONS.id)
- ) {
- deprecated(message, WIDGET_DEPRECATION_OPTIONS);
- }
-}
-
-const _registry = {};
-
-export function queryRegistry(name) {
- return _registry[name];
-}
-
-export function deleteFromRegistry(name) {
- return delete _registry[name];
-}
-
-const _decorators = {};
-
-export function decorateWidget(decorateIdentifier, cb) {
- const widgetName = decorateIdentifier.split(":")[0];
- if (!_registry[widgetName]) {
- // eslint-disable-next-line no-console
- console.error(
- consolePrefix(),
- `decorateWidget: Could not find widget '${widgetName}' in registry`
- );
- }
- _decorators[decorateIdentifier] ??= [];
- _decorators[decorateIdentifier].push(cb);
-}
-
-export function traverseCustomWidgets(tree, callback) {
- if (!tree) {
- return;
- }
-
- if (tree.__type === "CustomWidget") {
- callback(tree);
- }
-
- (tree.children || (tree.vnode ? tree.vnode.children : [])).forEach((node) => {
- traverseCustomWidgets(node, callback);
- });
-}
-
-export function applyDecorators(widget, type, attrs, state) {
- const decorators = _decorators[`${widget.name}:${type}`] || [];
-
- if (decorators.length) {
- const helper = new DecoratorHelper(widget, attrs, state);
- return decorators.map((d) => d(helper));
- }
-
- return [];
-}
-
-export function resetDecorators() {
- Object.keys(_decorators).forEach((key) => delete _decorators[key]);
-}
-
-const _customSettings = {};
-
-export function changeSetting(widgetName, settingName, newValue) {
- _customSettings[widgetName] = _customSettings[widgetName] || {};
- _customSettings[widgetName][settingName] = newValue;
-}
-
-export function createWidgetFrom(base, name, opts) {
- const result = class CustomWidget extends base {};
-
- // todo this shouldn't been needed anymore once we don't transpile for IE anymore
- // see: https://discuss.emberjs.com/t/constructor-name-behaves-differently-in-dev-and-prod-builds-for-models-defined-with-the-es6-class-syntax/15572/6
- // once done, we can just check on constructor.name
- result.prototype.__type = "CustomWidget";
-
- if (name) {
- _registry[name] = result;
- }
-
- opts.name = name;
-
- if (opts.template) {
- opts.html = opts.template;
- }
-
- Object.keys(opts).forEach((k) => (result.prototype[k] = opts[k]));
- return result;
-}
-
-export function createWidget(name, opts) {
- if (
- getOwnerWithFallback(this)?.lookup(`service:site-settings`)
- ?.deactivate_widgets_rendering
- ) {
- warnWidgetsDeprecation(
- `Widgets are deactivated. Your site may not work properly. Affected widget: ${name}.`
- );
- } else {
- warnWidgetsDeprecation(
- `Using \`api.createWidget\` is deprecated and will soon stop working. Use Glimmer components instead. Affected widget: ${name}.`
- );
- }
-
- return createWidgetFrom(Widget, name, opts);
-}
-
-export function reopenWidget(name, opts) {
- let existing = _registry[name];
- if (!existing) {
- // eslint-disable-next-line no-console
- console.error(
- consolePrefix(),
- `reopenWidget: Could not find widget ${name} in registry`
- );
- return;
- }
-
- if (opts.template) {
- opts.html = opts.template;
- }
-
- Object.keys(opts).forEach((k) => {
- let old = existing.prototype[k];
+export const WIDGET_DECOMMISSION_OPTIONS = {
+ since: "v3.6.0.beta3-latest",
+ id: "discourse.widgets-decommissioned",
+ url: "https://meta.discourse.org/t/375332/1",
+};
- if (old instanceof Function) {
- // Add support for `this._super()` to reopened widgets if the prototype exists in the
- // base object
- existing.prototype[k] = function (...args) {
- let ctx = Object.create(this);
- ctx._super = (...superArgs) => old.apply(this, superArgs);
- return opts[k].apply(ctx, args);
- };
- } else {
- existing.prototype[k] = opts[k];
- }
- });
- return existing;
+function warnWidgetsDecommissioned() {
+ deprecated(
+ `"The widget rendering system has been decommissioned and all related components and APIs are no-longer operational.`,
+ WIDGET_DECOMMISSION_OPTIONS
+ );
}
-export default class Widget {
- constructor(attrs, register, opts) {
- opts = opts || {};
- this.attrs = attrs || {};
- this.mergeState = opts.state;
- this.model = opts.model;
- this.register = register;
- this.dirtyKeys = opts.dirtyKeys;
-
- register.deprecateContainer(this);
- setOwner(this, getOwner(register));
-
- this.key = this.buildKey ? this.buildKey(attrs) : null;
- this.site = register.lookup("service:site");
- this.siteSettings = register.lookup("service:site-settings");
- this.currentUser = register.lookup("service:current-user");
- this.capabilities = register.lookup("service:capabilities");
- this.store = register.lookup("service:store");
- this.appEvents = register.lookup("service:app-events");
- this.keyValueStore = register.lookup("service:key-value-store");
-
- // We can inject services into widgets by passing a `services` parameter on creation
- (this.services || []).forEach((s) => {
- this[camelize(s)] = register.lookup(`service:${s}`);
- });
-
- this.init(this.attrs);
-
- if (this.name) {
- const custom = _customSettings[this.name];
- if (custom) {
- Object.keys(custom).forEach((k) => (this.settings[k] = custom[k]));
- }
- }
- }
-
- init() {}
-
- transform() {
- return {};
- }
-
- defaultState() {
- return {};
- }
-
- destroy() {}
-
- get(propertyPath) {
- return get(this, propertyPath);
- }
-
- render(prev) {
- const { dirtyKeys } = this;
-
- if (prev && prev.key && prev.key === this.key) {
- this.state = prev.state;
- } else {
- // Helps debug widgets
- this.state = this.defaultState(this.attrs, this.state);
- if (!isProduction()) {
- if (typeof this.state !== "object") {
- throw new Error(`defaultState must return an object`);
- } else if (Object.keys(this.state).length > 0 && !this.key) {
- throw new Error(`you need a key when using state in ${this.name}`);
- }
- }
- }
-
- // Sometimes we pass state down from the parent
- if (this.mergeState) {
- this.state = deepMerge(this.state, this.mergeState);
- }
-
- if (prev) {
- const dirtyOpts = dirtyKeys.optionsFor(prev.key);
-
- if (prev.shadowTree) {
- this.shadowTree = true;
- if (!dirtyOpts.dirty && !dirtyKeys.allDirty()) {
- return prev.vnode;
- }
- }
- if (prev.key) {
- dirtyKeys.renderedKey(prev.key);
- }
-
- const refreshAction = dirtyOpts.onRefresh;
- if (refreshAction) {
- this.sendWidgetAction(refreshAction, dirtyOpts.refreshArg);
- }
- }
-
- return this.draw(h, this.attrs, this.state);
- }
-
- _findAncestorWithProperty(property) {
- let widget = this;
- while (widget) {
- const value = widget[property];
- if (value) {
- return widget;
- }
- widget = widget.parentWidget;
- }
- }
-
- _findView() {
- const widget = this._findAncestorWithProperty("_emberView");
- if (widget) {
- return widget._emberView;
- }
- }
-
- lookupWidgetClass(widgetName) {
- let WidgetClass = _registry[widgetName];
- if (WidgetClass) {
- return WidgetClass;
- }
-
- if (!this.register) {
- // eslint-disable-next-line no-console
- console.error("couldn't find register");
- return null;
- }
-
- WidgetClass = this.register.lookupFactory(`widget:${widgetName}`);
- if (WidgetClass && WidgetClass.class) {
- return WidgetClass.class;
- }
-
- return null;
- }
-
- attach(widgetName, attrs, opts, otherOpts = {}) {
- let WidgetClass = this.lookupWidgetClass(widgetName);
-
- if (!WidgetClass && otherOpts.fallbackWidgetName) {
- WidgetClass = this.lookupWidgetClass(otherOpts.fallbackWidgetName);
- }
-
- if (WidgetClass) {
- const result = new WidgetClass(attrs, this.register, opts);
- result.parentWidget = this;
- result.dirtyKeys = this.dirtyKeys;
-
- if (otherOpts.tagName) {
- result.tagName = otherOpts.tagName;
- }
-
- return result;
- } else {
- throw new Error(
- `Couldn't find ${widgetName} or fallback ${otherOpts.fallbackWidgetName}`
- );
- }
- }
-
- didRenderWidget() {}
-
- willRerenderWidget() {}
-
- scheduleRerender() {
- let widget = this;
- while (widget) {
- if (widget.shadowTree) {
- this.dirtyKeys.keyDirty(widget.key);
- }
-
- const rerenderable = widget._rerenderable;
- if (rerenderable) {
- return rerenderable.queueRerender();
- }
-
- widget = widget.parentWidget;
+class DummyWidget {
+ constructor() {
+ // skip if the constructor is run in core code
+ // some fake widgets are still instantiated to prevent breaking imports
+ if (consolePrefix()) {
+ warnWidgetsDecommissioned();
}
}
+}
- _sendComponentAction(name, param) {
- let promise;
-
- const view = this._findView();
- if (view) {
- let method;
-
- if (typeof name === "function") {
- method = name;
- } else {
- method = view.get(name);
- if (!method) {
- // eslint-disable-next-line no-console
- console.warn(`${name} not found`);
- return;
- }
- }
-
- if (typeof method === "string") {
- view[method](param);
- promise = Promise.resolve();
- } else {
- const target = view.get("target") || view;
- promise = method.call(target, param);
- if (!promise || !promise.then) {
- promise = Promise.resolve(promise);
- }
- }
- }
-
- return this.rerenderResult(() => promise);
- }
-
- findAncestorModel() {
- const modelWidget = this._findAncestorWithProperty("model");
- if (modelWidget) {
- return modelWidget.model;
- }
- }
-
- rerenderResult(fn) {
- this.scheduleRerender();
- const result = fn();
- // re-render after any promises complete, too!
- if (result && result.then) {
- return result.then(() => this.scheduleRerender());
- }
- return result;
- }
-
- sendWidgetEvent(name, attrs) {
- const methodName = `${name}Event`;
- return this.rerenderResult(() => {
- const widget = this._findAncestorWithProperty(methodName);
- if (widget) {
- return widget[methodName](attrs);
- }
- });
- }
-
- callWidgetFunction(name, param) {
- const widget = this._findAncestorWithProperty(name);
- if (widget) {
- return widget[name].call(widget, param);
- }
- }
-
- sendWidgetAction(name, param) {
- return this.rerenderResult(() => {
- const widget = this._findAncestorWithProperty(name);
- if (widget) {
- return widget[name].call(widget, param);
- }
-
- return this._sendComponentAction(name, param || this.findAncestorModel());
- });
- }
-
- html() {}
-
- draw(builder, attrs, state) {
- const properties = {};
-
- if (this.buildClasses) {
- let classes = this.buildClasses(attrs, state) || [];
- if (!Array.isArray(classes)) {
- classes = [classes];
- }
-
- const customClasses = applyDecorators(this, "classNames", attrs, state);
- if (customClasses && customClasses.length) {
- classes = classes.concat(customClasses);
- }
-
- if (classes.length) {
- properties.className = classes.join(" ");
- }
- }
- if (this.buildId) {
- properties.id = this.buildId(attrs);
- }
-
- if (this.buildAttributes) {
- properties.attributes = this.buildAttributes(attrs);
- }
-
- if (this.keyUp) {
- properties["widget-key-up"] = new WidgetKeyUpHook(this);
- }
-
- if (this.keyDown) {
- properties["widget-key-down"] = new WidgetKeyDownHook(this);
- }
-
- if (this.clickOutside) {
- properties["widget-click-outside"] = new WidgetClickOutsideHook(this);
- }
-
- if (this.click) {
- properties["widget-click"] = new WidgetClickHook(this);
- }
-
- if (this.doubleClick) {
- properties["widget-double-click"] = new WidgetDoubleClickHook(this);
- }
-
- if (this.mouseDownOutside) {
- properties["widget-mouse-down-outside"] = new WidgetMouseDownOutsideHook(
- this
- );
- }
-
- if (this.drag) {
- properties["widget-drag"] = new WidgetDragHook(this);
- }
-
- if (this.input) {
- properties["widget-input"] = new WidgetInputHook(this);
- }
-
- if (this.change) {
- properties["widget-change"] = new WidgetChangeHook(this);
- }
-
- if (this.mouseDown) {
- properties["widget-mouse-down"] = new WidgetMouseDownHook(this);
- }
-
- if (this.mouseUp) {
- properties["widget-mouse-up"] = new WidgetMouseUpHook(this);
- }
-
- if (this.mouseMove) {
- properties["widget-mouse-move"] = new WidgetMouseMoveHook(this);
- }
-
- if (this.mouseOver) {
- properties["widget-mouse-over"] = new WidgetMouseOverHook(this);
- }
-
- if (this.pointerOver) {
- properties["widget-pointer-over"] = new WidgetPointerOverHook(this);
- }
-
- if (this.pointerOut) {
- properties["widget-pointer-out"] = new WidgetPointerOutHook(this);
- }
-
- if (this.mouseOut) {
- properties["widget-mouse-out"] = new WidgetMouseOutHook(this);
- }
-
- if (this.touchStart) {
- properties["widget-touch-start"] = new WidgetTouchStartHook(this);
- }
-
- if (this.touchEnd) {
- properties["widget-touch-end"] = new WidgetTouchEndHook(this);
- }
-
- if (this.touchMove) {
- properties["widget-touch-move"] = new WidgetTouchMoveHook(this);
- }
-
- const attributes = properties["attributes"] || {};
- properties.attributes = attributes;
-
- if (this.title) {
- if (typeof this.title === "function") {
- attributes.title = this.title(attrs, state);
- } else {
- attributes.title = i18n(this.title);
- }
- }
-
- this.transformed = this.transform(this.attrs, this.state);
-
- let contents = this.html(attrs, state);
- if (this.name) {
- const beforeContents =
- applyDecorators(this, "before", attrs, state) || [];
- const afterContents = applyDecorators(this, "after", attrs, state) || [];
- contents = beforeContents.concat(contents).concat(afterContents);
- }
-
- return h(this.tagName || "div", properties, contents);
- }
+function dummyCreateWidgetFrom() {
+ return DummyWidget;
}
-Widget.prototype.type = "Thunk";
+export {
+ warnWidgetsDecommissioned,
+ warnWidgetsDecommissioned as warnWidgetsDeprecation,
+ warnWidgetsDecommissioned as queryRegistry,
+ warnWidgetsDecommissioned as deleteFromRegistry,
+ warnWidgetsDecommissioned as decorateWidget,
+ warnWidgetsDecommissioned as traverseCustomWidgets,
+ warnWidgetsDecommissioned as applyDecorators,
+ warnWidgetsDecommissioned as resetDecorators,
+ warnWidgetsDecommissioned as changeSetting,
+ dummyCreateWidgetFrom as createWidgetFrom,
+ dummyCreateWidgetFrom as createWidget,
+ warnWidgetsDecommissioned as reopenWidget,
+ DummyWidget,
+ DummyWidget as default,
+};
diff --git a/frontend/discourse/package.json b/frontend/discourse/package.json
index ea75a802340..2695c132635 100644
--- a/frontend/discourse/package.json
+++ b/frontend/discourse/package.json
@@ -47,7 +47,6 @@
"chartjs-plugin-datalabels": "2.2.0",
"decorator-transforms": "^2.3.0",
"diff": "^8.0.2",
- "discourse-widget-hbs": "workspace:1.0.0",
"ember-curry-component": "^0.3.1",
"ember-resolver": "^13.1.1",
"ember-route-template": "^1.0.3",
@@ -157,7 +156,6 @@
"testem": "^3.16.0",
"typescript": "^5.9.3",
"util": "^0.12.5",
- "virtual-dom": "^2.1.1",
"webpack": "5.99.9",
"webpack-retry-chunk-load-plugin": "^3.1.1",
"webpack-stats-plugin": "^1.1.3",
diff --git a/frontend/discourse/tests/acceptance/composer-actions-test.js b/frontend/discourse/tests/acceptance/composer-actions-test.js
index 1f48b3c884e..264f7ce3728 100644
--- a/frontend/discourse/tests/acceptance/composer-actions-test.js
+++ b/frontend/discourse/tests/acceptance/composer-actions-test.js
@@ -12,588 +12,521 @@ import {
import selectKit from "discourse/tests/helpers/select-kit-helper";
import { i18n } from "discourse-i18n";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Composer Actions (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({
- id: 5,
- username: "kris",
- whisperer: true,
- });
- needs.settings({
- prioritize_username_in_ux: true,
- display_name_on_posts: false,
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.site({ can_tag_topics: true });
- needs.pretender((server, helper) => {
- server.put("/u/kris.json", () => helper.response({ user: {} }));
- const cardResponse = cloneJSON(userFixtures["/u/shade/card.json"]);
- server.get("/u/shade/card.json", () => helper.response(cardResponse));
- });
-
- test("replying to post", async function (assert) {
- const composerActions = selectKit(".composer-actions");
-
- await visit("/t/internationalization-localization/280");
- await click("article#post_3 button.reply");
- await composerActions.expand();
-
- assert.strictEqual(
- composerActions.rowByIndex(0).value(),
- "reply_as_new_topic"
- );
- assert.strictEqual(
- composerActions.rowByIndex(1).value(),
- "reply_to_topic"
- );
- assert.strictEqual(
- composerActions.rowByIndex(2).value(),
- "toggle_whisper"
- );
- assert.strictEqual(
- composerActions.rowByIndex(3).value(),
- "toggle_topic_bump"
- );
- assert.strictEqual(composerActions.rowByIndex(4).value(), null);
- });
-
- test("replying to post - reply_to_topic", async function (assert) {
- const composerActions = selectKit(".composer-actions");
-
- await visit("/t/internationalization-localization/280");
- await click("article#post_3 button.reply");
- await fillIn(
- ".d-editor-input",
- "test replying to topic when initially replied to post"
- );
-
- await composerActions.expand();
- await composerActions.selectRowByValue("reply_to_topic");
-
- assert
- .dom(".action-title .topic-link")
- .hasText("Internationalization / localization");
- assert
- .dom(".action-title .topic-link")
- .hasAttribute("href", "/t/internationalization-localization/280");
- assert
- .dom(".d-editor-input")
- .hasValue("test replying to topic when initially replied to post");
- });
-
- test("replying to post - toggle_whisper for whisperers", async function (assert) {
- updateCurrentUser({ admin: false, moderator: false });
- const composerActions = selectKit(".composer-actions");
-
- await visit("/t/internationalization-localization/280");
- await click("article#post_3 button.reply");
- await fillIn(
- ".d-editor-input",
- "test replying as whisper to topic when initially not a whisper"
- );
-
- assert
- .dom(".composer-actions svg.d-icon-far-eye-slash")
- .doesNotExist("whisper icon is not visible");
- assert
- .dom(".composer-actions svg.d-icon-share")
- .exists("reply icon is visible");
-
- await composerActions.expand();
- await composerActions.selectRowByValue("toggle_whisper");
-
- assert
- .dom(".composer-actions svg.d-icon-far-eye-slash")
- .exists("whisper icon is visible");
- assert
- .dom(".composer-actions svg.d-icon-share")
- .doesNotExist("reply icon is not visible");
- });
-
- test("replying to post - reply_as_new_topic", async function (assert) {
- sinon.stub(Draft, "get").resolves({ draft: "", draft_sequence: 0 });
-
- const composerActions = selectKit(".composer-actions");
- const categoryChooser = selectKit(".title-wrapper .category-chooser");
- const categoryChooserReplyArea = selectKit(
- ".reply-area .category-chooser"
- );
- const quote =
- "test replying as new topic when initially replied to post";
-
- await visit("/t/internationalization-localization/280");
-
- await click("#topic-title .d-icon-pencil");
- await categoryChooser.expand();
- await categoryChooser.selectRowByValue(4);
- await click("#topic-title .submit-edit");
-
- await click("article#post_3 button.reply");
- await fillIn(".d-editor-input", quote);
-
- await composerActions.expand();
- await composerActions.selectRowByValue("reply_as_new_topic");
-
- assert.strictEqual(categoryChooserReplyArea.header().name(), "faq");
- assert.dom(".action-title").hasText(i18n("topic.create_long"));
- assert.dom(".d-editor-input").includesValue(quote);
- });
-
- test("reply_as_new_topic without a new_topic draft", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".create.reply");
- const composerActions = selectKit(".composer-actions");
- await composerActions.expand();
- await composerActions.selectRowByValue("reply_as_new_topic");
- assert.dom(".dialog-body").doesNotExist();
- });
-
- test("reply_as_new_topic without a permission to create topic", async function (assert) {
- updateCurrentUser({ can_create_topic: false });
- await visit("/t/internationalization-localization/280");
- await click(".create.reply");
- const composerActions = selectKit(".composer-actions");
- await composerActions.expand();
- assert
- .dom(".composer-actions svg.d-icon-plus")
- .doesNotExist("reply as new topic icon is not visible");
- });
-
- test("reply_as_new_group_message", async function (assert) {
- await visit("/t/lorem-ipsum-dolor-sit-amet/130");
- await click(".create.reply");
- const composerActions = selectKit(".composer-actions");
- await composerActions.expand();
- await composerActions.selectRowByValue("reply_as_new_group_message");
-
- const privateMessageUsers = selectKit("#private-message-users");
- assert.deepEqual(privateMessageUsers.header().value(), "foo,foo_group");
- });
-
- test("interactions", async function (assert) {
- const composerActions = selectKit(".composer-actions");
- const quote = "Life is like riding a bicycle.";
-
- await visit("/t/short-topic-with-two-posts/54077");
- await click("article#post_2 button.reply");
- await fillIn(".d-editor-input", quote);
- await composerActions.expand();
- await composerActions.selectRowByValue("reply_to_topic");
-
- assert.dom(".action-title").hasText("Short topic with two posts");
- assert.dom(".d-editor-input").hasValue(quote);
-
- await composerActions.expand();
-
- assert.strictEqual(
- composerActions.rowByIndex(0).value(),
- "reply_as_new_topic"
- );
- assert.strictEqual(
- composerActions.rowByIndex(1).value(),
- "reply_to_post"
- );
- assert.strictEqual(
- composerActions.rowByIndex(2).value(),
- "toggle_whisper"
- );
- assert.strictEqual(
- composerActions.rowByIndex(3).value(),
- "toggle_topic_bump"
- );
- assert.strictEqual(composerActions.rows().length, 4);
-
- await composerActions.selectRowByValue("reply_to_post");
- await composerActions.expand();
-
- assert.dom(".action-title img.avatar").exists();
- assert.dom(".action-title .user-link").hasText("tms");
- assert.dom(".d-editor-input").hasValue(quote);
- assert.strictEqual(
- composerActions.rowByIndex(0).value(),
- "reply_as_new_topic"
- );
- assert.strictEqual(
- composerActions.rowByIndex(1).value(),
- "reply_to_topic"
- );
- assert.strictEqual(
- composerActions.rowByIndex(2).value(),
- "toggle_whisper"
- );
- assert.strictEqual(
- composerActions.rowByIndex(3).value(),
- "toggle_topic_bump"
- );
- assert.strictEqual(composerActions.rows().length, 4);
-
- await composerActions.selectRowByValue("reply_as_new_topic");
- await composerActions.expand();
-
- assert.dom(".action-title").hasText(i18n("topic.create_long"));
- assert.dom(".d-editor-input").includesValue(quote);
- assert.strictEqual(
- composerActions.rowByIndex(0).value(),
- "reply_to_post"
- );
- assert.strictEqual(
- composerActions.rowByIndex(1).value(),
- "reply_to_topic"
- );
- assert.strictEqual(
- composerActions.rowByIndex(2).value(),
- "toggle_unlisted"
- );
- assert.strictEqual(
- composerActions.rowByIndex(3).value(),
- "shared_draft"
- );
- assert.strictEqual(
- composerActions.rowByIndex(4).value(),
- "create_private_message"
- );
- assert.strictEqual(composerActions.rows().length, 5);
- });
-
- test("interactions - private message", async function (assert) {
- const composerActions = selectKit(".composer-actions");
-
- await visit("/t/internationalization-localization/280");
- await click('#post_4 a[data-user-card="shade"]');
- await click(".usercard-controls .compose-pm .btn-primary");
- await composerActions.expand();
-
- assert.dom(".action-title").hasText(i18n("topic.private_message"));
- assert.strictEqual(
- composerActions.rowByIndex(0).value(),
- "create_topic"
- );
- assert.strictEqual(composerActions.rows().length, 1);
- });
-
- test("replying to post - toggle_topic_bump", async function (assert) {
- const composerActions = selectKit(".composer-actions");
-
- await visit("/t/short-topic-with-two-posts/54077");
- await click("article#post_2 button.reply");
-
- assert
- .dom(".composer-actions svg.d-icon-anchor")
- .doesNotExist("no-bump icon is not visible");
- assert
- .dom(".composer-actions svg.d-icon-share")
- .exists("reply icon is visible");
-
- await composerActions.expand();
- await composerActions.selectRowByValue("toggle_topic_bump");
-
- assert
- .dom(".composer-actions svg.d-icon-anchor")
- .exists("no-bump icon is visible");
- assert
- .dom(".composer-actions svg.d-icon-share")
- .doesNotExist("reply icon is not visible");
-
- await composerActions.expand();
- await composerActions.selectRowByValue("toggle_topic_bump");
-
- assert
- .dom(".composer-actions svg.d-icon-anchor")
- .doesNotExist("no-bump icon is not visible");
- assert
- .dom(".composer-actions svg.d-icon-share")
- .exists("reply icon is visible");
- });
-
- test("replying to post - whisper and no bump", async function (assert) {
- const composerActions = selectKit(".composer-actions");
-
- await visit("/t/short-topic-with-two-posts/54077");
- await click("article#post_2 button.reply");
-
- assert
- .dom(".composer-actions svg.d-icon-far-eye-slash")
- .doesNotExist("whisper icon is not visible");
- assert
- .dom(".reply-details .whisper .d-icon-anchor")
- .doesNotExist("no-bump icon is not visible");
- assert
- .dom(".composer-actions svg.d-icon-share")
- .exists("reply icon is visible");
-
- await composerActions.expand();
- await composerActions.selectRowByValue("toggle_topic_bump");
- await composerActions.expand();
- await composerActions.selectRowByValue("toggle_whisper");
-
- assert
- .dom(".composer-actions svg.d-icon-far-eye-slash")
- .exists("whisper icon is visible");
- assert
- .dom(".reply-details .no-bump .d-icon-anchor")
- .exists("no-bump icon is visible");
- assert
- .dom(".composer-actions svg.d-icon-share")
- .doesNotExist("reply icon is not visible");
- });
-
- test("replying to post as staff", async function (assert) {
- const composerActions = selectKit(".composer-actions");
-
- updateCurrentUser({ admin: true });
- await visit("/t/internationalization-localization/280");
- await click("article#post_3 button.reply");
- await composerActions.expand();
-
- assert.strictEqual(composerActions.rows().length, 4);
- assert.strictEqual(
- composerActions.rowByIndex(3).value(),
- "toggle_topic_bump"
- );
- });
-
- test("replying to post as TL3 user", async function (assert) {
- const composerActions = selectKit(".composer-actions");
-
- updateCurrentUser({
- moderator: false,
- admin: false,
- trust_level: 3,
- whisperer: false,
- groups: [{ id: 13, name: "tl3_group" }],
- });
- await visit("/t/internationalization-localization/280");
- await click("article#post_3 button.reply");
- await composerActions.expand();
-
- assert.strictEqual(composerActions.rows().length, 2);
- Array.from(composerActions.rows()).forEach((row) => {
- assert.notStrictEqual(
- row.value,
- "toggle_topic_bump",
- "toggle button is not visible"
- );
- });
- });
-
- test("replying to post as TL4 user", async function (assert) {
- const composerActions = selectKit(".composer-actions");
-
- updateCurrentUser({
- moderator: false,
- admin: false,
- trust_level: 4,
- whisperer: false,
- groups: [{ id: 13, name: "tl4_group" }],
- });
- await visit("/t/internationalization-localization/280");
- await click("article#post_3 button.reply");
- await composerActions.expand();
-
- assert.strictEqual(composerActions.rows().length, 3);
- assert.strictEqual(
- composerActions.rowByIndex(2).value(),
- "toggle_topic_bump"
- );
- });
-
- test("editing post", async function (assert) {
- const composerActions = selectKit(".composer-actions");
-
- await visit("/t/internationalization-localization/280");
- await click("article#post_1 button.show-more-actions");
- await click("article#post_1 button.edit");
- await composerActions.expand();
-
- assert.strictEqual(composerActions.rows().length, 1);
- assert.strictEqual(
- composerActions.rowByIndex(0).value(),
- "reply_to_post"
- );
- });
- }
- );
-
- function stubDraftResponse() {
- sinon.stub(Draft, "get").resolves({
- draft:
- '{"reply":"dum de dum da ba.","action":"createTopic","title":"dum da ba dum dum","categoryId":null,"archetypeId":"regular","metaData":null,"composerTime":540879,"typingTime":3400}',
- draft_sequence: 0,
+acceptance(`Composer Actions`, function (needs) {
+ needs.user({
+ id: 5,
+ username: "kris",
+ whisperer: true,
+ });
+ needs.settings({
+ prioritize_username_in_ux: true,
+ display_name_on_posts: false,
+ });
+ needs.site({ can_tag_topics: true });
+ needs.pretender((server, helper) => {
+ server.put("/u/kris.json", () => helper.response({ user: {} }));
+ const cardResponse = cloneJSON(userFixtures["/u/shade/card.json"]);
+ server.get("/u/shade/card.json", () => helper.response(cardResponse));
+ });
+
+ test("replying to post", async function (assert) {
+ const composerActions = selectKit(".composer-actions");
+
+ await visit("/t/internationalization-localization/280");
+ await click("article#post_3 button.reply");
+ await composerActions.expand();
+
+ assert.strictEqual(
+ composerActions.rowByIndex(0).value(),
+ "reply_as_new_topic"
+ );
+ assert.strictEqual(composerActions.rowByIndex(1).value(), "reply_to_topic");
+ assert.strictEqual(composerActions.rowByIndex(2).value(), "toggle_whisper");
+ assert.strictEqual(
+ composerActions.rowByIndex(3).value(),
+ "toggle_topic_bump"
+ );
+ assert.strictEqual(composerActions.rowByIndex(4).value(), null);
+ });
+
+ test("replying to post - reply_to_topic", async function (assert) {
+ const composerActions = selectKit(".composer-actions");
+
+ await visit("/t/internationalization-localization/280");
+ await click("article#post_3 button.reply");
+ await fillIn(
+ ".d-editor-input",
+ "test replying to topic when initially replied to post"
+ );
+
+ await composerActions.expand();
+ await composerActions.selectRowByValue("reply_to_topic");
+
+ assert
+ .dom(".action-title .topic-link")
+ .hasText("Internationalization / localization");
+ assert
+ .dom(".action-title .topic-link")
+ .hasAttribute("href", "/t/internationalization-localization/280");
+ assert
+ .dom(".d-editor-input")
+ .hasValue("test replying to topic when initially replied to post");
+ });
+
+ test("replying to post - toggle_whisper for whisperers", async function (assert) {
+ updateCurrentUser({ admin: false, moderator: false });
+ const composerActions = selectKit(".composer-actions");
+
+ await visit("/t/internationalization-localization/280");
+ await click("article#post_3 button.reply");
+ await fillIn(
+ ".d-editor-input",
+ "test replying as whisper to topic when initially not a whisper"
+ );
+
+ assert
+ .dom(".composer-actions svg.d-icon-far-eye-slash")
+ .doesNotExist("whisper icon is not visible");
+ assert
+ .dom(".composer-actions svg.d-icon-share")
+ .exists("reply icon is visible");
+
+ await composerActions.expand();
+ await composerActions.selectRowByValue("toggle_whisper");
+
+ assert
+ .dom(".composer-actions svg.d-icon-far-eye-slash")
+ .exists("whisper icon is visible");
+ assert
+ .dom(".composer-actions svg.d-icon-share")
+ .doesNotExist("reply icon is not visible");
+ });
+
+ test("replying to post - reply_as_new_topic", async function (assert) {
+ sinon.stub(Draft, "get").resolves({ draft: "", draft_sequence: 0 });
+
+ const composerActions = selectKit(".composer-actions");
+ const categoryChooser = selectKit(".title-wrapper .category-chooser");
+ const categoryChooserReplyArea = selectKit(".reply-area .category-chooser");
+ const quote = "test replying as new topic when initially replied to post";
+
+ await visit("/t/internationalization-localization/280");
+
+ await click("#topic-title .d-icon-pencil");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(4);
+ await click("#topic-title .submit-edit");
+
+ await click("article#post_3 button.reply");
+ await fillIn(".d-editor-input", quote);
+
+ await composerActions.expand();
+ await composerActions.selectRowByValue("reply_as_new_topic");
+
+ assert.strictEqual(categoryChooserReplyArea.header().name(), "faq");
+ assert.dom(".action-title").hasText(i18n("topic.create_long"));
+ assert.dom(".d-editor-input").includesValue(quote);
+ });
+
+ test("reply_as_new_topic without a new_topic draft", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".create.reply");
+ const composerActions = selectKit(".composer-actions");
+ await composerActions.expand();
+ await composerActions.selectRowByValue("reply_as_new_topic");
+ assert.dom(".dialog-body").doesNotExist();
+ });
+
+ test("reply_as_new_topic without a permission to create topic", async function (assert) {
+ updateCurrentUser({ can_create_topic: false });
+ await visit("/t/internationalization-localization/280");
+ await click(".create.reply");
+ const composerActions = selectKit(".composer-actions");
+ await composerActions.expand();
+ assert
+ .dom(".composer-actions svg.d-icon-plus")
+ .doesNotExist("reply as new topic icon is not visible");
+ });
+
+ test("reply_as_new_group_message", async function (assert) {
+ await visit("/t/lorem-ipsum-dolor-sit-amet/130");
+ await click(".create.reply");
+ const composerActions = selectKit(".composer-actions");
+ await composerActions.expand();
+ await composerActions.selectRowByValue("reply_as_new_group_message");
+
+ const privateMessageUsers = selectKit("#private-message-users");
+ assert.deepEqual(privateMessageUsers.header().value(), "foo,foo_group");
+ });
+
+ test("interactions", async function (assert) {
+ const composerActions = selectKit(".composer-actions");
+ const quote = "Life is like riding a bicycle.";
+
+ await visit("/t/short-topic-with-two-posts/54077");
+ await click("article#post_2 button.reply");
+ await fillIn(".d-editor-input", quote);
+ await composerActions.expand();
+ await composerActions.selectRowByValue("reply_to_topic");
+
+ assert.dom(".action-title").hasText("Short topic with two posts");
+ assert.dom(".d-editor-input").hasValue(quote);
+
+ await composerActions.expand();
+
+ assert.strictEqual(
+ composerActions.rowByIndex(0).value(),
+ "reply_as_new_topic"
+ );
+ assert.strictEqual(composerActions.rowByIndex(1).value(), "reply_to_post");
+ assert.strictEqual(composerActions.rowByIndex(2).value(), "toggle_whisper");
+ assert.strictEqual(
+ composerActions.rowByIndex(3).value(),
+ "toggle_topic_bump"
+ );
+ assert.strictEqual(composerActions.rows().length, 4);
+
+ await composerActions.selectRowByValue("reply_to_post");
+ await composerActions.expand();
+
+ assert.dom(".action-title img.avatar").exists();
+ assert.dom(".action-title .user-link").hasText("tms");
+ assert.dom(".d-editor-input").hasValue(quote);
+ assert.strictEqual(
+ composerActions.rowByIndex(0).value(),
+ "reply_as_new_topic"
+ );
+ assert.strictEqual(composerActions.rowByIndex(1).value(), "reply_to_topic");
+ assert.strictEqual(composerActions.rowByIndex(2).value(), "toggle_whisper");
+ assert.strictEqual(
+ composerActions.rowByIndex(3).value(),
+ "toggle_topic_bump"
+ );
+ assert.strictEqual(composerActions.rows().length, 4);
+
+ await composerActions.selectRowByValue("reply_as_new_topic");
+ await composerActions.expand();
+
+ assert.dom(".action-title").hasText(i18n("topic.create_long"));
+ assert.dom(".d-editor-input").includesValue(quote);
+ assert.strictEqual(composerActions.rowByIndex(0).value(), "reply_to_post");
+ assert.strictEqual(composerActions.rowByIndex(1).value(), "reply_to_topic");
+ assert.strictEqual(
+ composerActions.rowByIndex(2).value(),
+ "toggle_unlisted"
+ );
+ assert.strictEqual(composerActions.rowByIndex(3).value(), "shared_draft");
+ assert.strictEqual(
+ composerActions.rowByIndex(4).value(),
+ "create_private_message"
+ );
+ assert.strictEqual(composerActions.rows().length, 5);
+ });
+
+ test("interactions - private message", async function (assert) {
+ const composerActions = selectKit(".composer-actions");
+
+ await visit("/t/internationalization-localization/280");
+ await click('#post_4 a[data-user-card="shade"]');
+ await click(".usercard-controls .compose-pm .btn-primary");
+ await composerActions.expand();
+
+ assert.dom(".action-title").hasText(i18n("topic.private_message"));
+ assert.strictEqual(composerActions.rowByIndex(0).value(), "create_topic");
+ assert.strictEqual(composerActions.rows().length, 1);
+ });
+
+ test("replying to post - toggle_topic_bump", async function (assert) {
+ const composerActions = selectKit(".composer-actions");
+
+ await visit("/t/short-topic-with-two-posts/54077");
+ await click("article#post_2 button.reply");
+
+ assert
+ .dom(".composer-actions svg.d-icon-anchor")
+ .doesNotExist("no-bump icon is not visible");
+ assert
+ .dom(".composer-actions svg.d-icon-share")
+ .exists("reply icon is visible");
+
+ await composerActions.expand();
+ await composerActions.selectRowByValue("toggle_topic_bump");
+
+ assert
+ .dom(".composer-actions svg.d-icon-anchor")
+ .exists("no-bump icon is visible");
+ assert
+ .dom(".composer-actions svg.d-icon-share")
+ .doesNotExist("reply icon is not visible");
+
+ await composerActions.expand();
+ await composerActions.selectRowByValue("toggle_topic_bump");
+
+ assert
+ .dom(".composer-actions svg.d-icon-anchor")
+ .doesNotExist("no-bump icon is not visible");
+ assert
+ .dom(".composer-actions svg.d-icon-share")
+ .exists("reply icon is visible");
+ });
+
+ test("replying to post - whisper and no bump", async function (assert) {
+ const composerActions = selectKit(".composer-actions");
+
+ await visit("/t/short-topic-with-two-posts/54077");
+ await click("article#post_2 button.reply");
+
+ assert
+ .dom(".composer-actions svg.d-icon-far-eye-slash")
+ .doesNotExist("whisper icon is not visible");
+ assert
+ .dom(".reply-details .whisper .d-icon-anchor")
+ .doesNotExist("no-bump icon is not visible");
+ assert
+ .dom(".composer-actions svg.d-icon-share")
+ .exists("reply icon is visible");
+
+ await composerActions.expand();
+ await composerActions.selectRowByValue("toggle_topic_bump");
+ await composerActions.expand();
+ await composerActions.selectRowByValue("toggle_whisper");
+
+ assert
+ .dom(".composer-actions svg.d-icon-far-eye-slash")
+ .exists("whisper icon is visible");
+ assert
+ .dom(".reply-details .no-bump .d-icon-anchor")
+ .exists("no-bump icon is visible");
+ assert
+ .dom(".composer-actions svg.d-icon-share")
+ .doesNotExist("reply icon is not visible");
+ });
+
+ test("replying to post as staff", async function (assert) {
+ const composerActions = selectKit(".composer-actions");
+
+ updateCurrentUser({ admin: true });
+ await visit("/t/internationalization-localization/280");
+ await click("article#post_3 button.reply");
+ await composerActions.expand();
+
+ assert.strictEqual(composerActions.rows().length, 4);
+ assert.strictEqual(
+ composerActions.rowByIndex(3).value(),
+ "toggle_topic_bump"
+ );
+ });
+
+ test("replying to post as TL3 user", async function (assert) {
+ const composerActions = selectKit(".composer-actions");
+
+ updateCurrentUser({
+ moderator: false,
+ admin: false,
+ trust_level: 3,
+ whisperer: false,
+ groups: [{ id: 13, name: "tl3_group" }],
});
- }
-
- acceptance(
- `Composer Actions With New Topic Draft (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({ whisperer: true });
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.site({
- can_tag_topics: true,
- });
-
- test("shared draft", async function (assert) {
- updateCurrentUser({ draft_count: 1 });
- stubDraftResponse();
-
- await visit("/");
- await click("button.topic-drafts-menu-trigger");
- await click(
- ".topic-drafts-menu-content .topic-drafts-item:first-child button"
- );
-
- await fillIn(
- "#reply-title",
- "This is the new text for the title using 'quotes'"
- );
- await fillIn(".d-editor-input", "This is the new text for the post");
-
- const tags = selectKit(".mini-tag-chooser");
- await tags.expand();
- await tags.selectRowByValue("monkey");
-
- const composerActions = selectKit(".composer-actions");
- await composerActions.expand();
- await composerActions.selectRowByValue("shared_draft");
-
- assert.strictEqual(
- tags.header().value(),
- "monkey",
- "tags are not reset"
- );
- assert
- .dom("#reply-title")
- .hasValue("This is the new text for the title using 'quotes'");
-
- assert
- .dom("#reply-control .btn-primary.create .d-button-label")
- .hasText(i18n("composer.create_shared_draft"));
- assert
- .dom(".composer-actions svg.d-icon-far-clipboard")
- .exists("shared draft icon is visible");
- });
-
- test("reply_as_new_topic with new_topic draft", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".create.reply");
-
- stubDraftResponse();
-
- const composerActions = selectKit(".composer-actions");
- await composerActions.expand();
- await composerActions.selectRowByValue("reply_as_new_topic");
-
- assert
- .dom(".dialog-body")
- .hasText(
- i18n("composer.composer_actions.reply_as_new_topic.confirm")
- );
- await click(".dialog-footer .btn-primary");
-
- assert
- .dom(".d-editor-input")
- .hasValue(/^Continuing the discussion from/);
- });
- }
- );
-
- acceptance(
- `Prioritize Username (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- prioritize_username_in_ux: true,
- display_name_on_posts: false,
- glimmer_post_stream_mode: postStreamMode,
- });
-
- test("Reply to post use username", async function (assert) {
- await visit("/t/short-topic-with-two-posts/54079");
- await click("article#post_2 button.reply");
-
- assert.dom(".action-title .user-link").hasText("james_john");
- });
-
- test("Quotes use username", async function (assert) {
- await visit("/t/short-topic-with-two-posts/54079");
- await selectText("#post_2 p");
- await click(".insert-quote");
- assert
- .dom(".d-editor-input")
- .hasValue(
- '[quote="james_john, post:2, topic:54079, full:true"]\nThis is a short topic.\n[/quote]\n\n'
- );
- });
- }
- );
-
- acceptance(
- `Prioritize Full Name (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- prioritize_username_in_ux: false,
- display_name_on_posts: true,
- glimmer_post_stream_mode: postStreamMode,
- });
-
- test("Reply to post use full name", async function (assert) {
- await visit("/t/short-topic-with-two-posts/54079");
- await click("article#post_3 button.reply");
-
- assert
- .dom(".action-title .user-link")
- .hasHtml("&lt;h1&gt;Tim Stone&lt;/h1&gt;");
- });
-
- test("Quotes use full name", async function (assert) {
- await visit("/t/short-topic-with-two-posts/54079");
- await selectText("#post_2 p");
- await click(".insert-quote");
- assert
- .dom(".d-editor-input")
- .hasValue(
- '[quote="james, john, the third, post:2, topic:54079, full:true, username:james_john"]\nThis is a short topic.\n[/quote]\n\n'
- );
- });
-
- test("Quoting a nested quote returns the correct username", async function (assert) {
- await visit("/t/short-topic-with-two-posts/54079");
- await selectText("#post_4 p");
- await click(".insert-quote");
- assert
- .dom(".d-editor-input")
- .hasValue(
- '[quote="james_john, post:2, topic:54079"]\nThis is a short topic.\n[/quote]\n\n'
- );
- });
- }
- );
-
- acceptance(
- `Prioritizing Name fall back (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- prioritize_username_in_ux: false,
- display_name_on_posts: true,
- glimmer_post_stream_mode: postStreamMode,
- });
-
- test("Quotes fall back to username if name is not present", async function (assert) {
- await visit("/t/internationalization-localization/130");
- // select a user with no name
- await selectText("#post_1 p");
- await click(".insert-quote");
- assert
- .dom(".d-editor-input")
- .hasValue(
- '[quote="bianca, post:1, topic:130, full:true"]\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas a varius ipsum. Nunc euismod, metus non vulputate malesuada, ligula metus pharetra tortor, vel sodales arcu lacus sed mauris. Nam semper, orci vitae fringilla placerat, dui tellus convallis felis, ultricies laoreet sapien mi et metus. Mauris facilisis, mi fermentum rhoncus feugiat, dolor est vehicula leo, id porta leo ex non enim. In a ligula vel tellus commodo scelerisque non in ex. Pellentesque semper leo quam, nec varius est viverra eget. Donec vehicula sem et massa faucibus tempus.\n[/quote]\n\n'
- );
- });
- }
- );
+ await visit("/t/internationalization-localization/280");
+ await click("article#post_3 button.reply");
+ await composerActions.expand();
+
+ assert.strictEqual(composerActions.rows().length, 2);
+ Array.from(composerActions.rows()).forEach((row) => {
+ assert.notStrictEqual(
+ row.value,
+ "toggle_topic_bump",
+ "toggle button is not visible"
+ );
+ });
+ });
+
+ test("replying to post as TL4 user", async function (assert) {
+ const composerActions = selectKit(".composer-actions");
+
+ updateCurrentUser({
+ moderator: false,
+ admin: false,
+ trust_level: 4,
+ whisperer: false,
+ groups: [{ id: 13, name: "tl4_group" }],
+ });
+ await visit("/t/internationalization-localization/280");
+ await click("article#post_3 button.reply");
+ await composerActions.expand();
+
+ assert.strictEqual(composerActions.rows().length, 3);
+ assert.strictEqual(
+ composerActions.rowByIndex(2).value(),
+ "toggle_topic_bump"
+ );
+ });
+
+ test("editing post", async function (assert) {
+ const composerActions = selectKit(".composer-actions");
+
+ await visit("/t/internationalization-localization/280");
+ await click("article#post_1 button.show-more-actions");
+ await click("article#post_1 button.edit");
+ await composerActions.expand();
+
+ assert.strictEqual(composerActions.rows().length, 1);
+ assert.strictEqual(composerActions.rowByIndex(0).value(), "reply_to_post");
+ });
+});
+
+function stubDraftResponse() {
+ sinon.stub(Draft, "get").resolves({
+ draft:
+ '{"reply":"dum de dum da ba.","action":"createTopic","title":"dum da ba dum dum","categoryId":null,"archetypeId":"regular","metaData":null,"composerTime":540879,"typingTime":3400}',
+ draft_sequence: 0,
+ });
+}
+
+acceptance(`Composer Actions With New Topic Draft`, function (needs) {
+ needs.user({ whisperer: true });
+
+ needs.site({
+ can_tag_topics: true,
+ });
+
+ test("shared draft", async function (assert) {
+ updateCurrentUser({ draft_count: 1 });
+ stubDraftResponse();
+
+ await visit("/");
+ await click("button.topic-drafts-menu-trigger");
+ await click(
+ ".topic-drafts-menu-content .topic-drafts-item:first-child button"
+ );
+
+ await fillIn(
+ "#reply-title",
+ "This is the new text for the title using 'quotes'"
+ );
+ await fillIn(".d-editor-input", "This is the new text for the post");
+
+ const tags = selectKit(".mini-tag-chooser");
+ await tags.expand();
+ await tags.selectRowByValue("monkey");
+
+ const composerActions = selectKit(".composer-actions");
+ await composerActions.expand();
+ await composerActions.selectRowByValue("shared_draft");
+
+ assert.strictEqual(tags.header().value(), "monkey", "tags are not reset");
+ assert
+ .dom("#reply-title")
+ .hasValue("This is the new text for the title using 'quotes'");
+
+ assert
+ .dom("#reply-control .btn-primary.create .d-button-label")
+ .hasText(i18n("composer.create_shared_draft"));
+ assert
+ .dom(".composer-actions svg.d-icon-far-clipboard")
+ .exists("shared draft icon is visible");
+ });
+
+ test("reply_as_new_topic with new_topic draft", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".create.reply");
+
+ stubDraftResponse();
+
+ const composerActions = selectKit(".composer-actions");
+ await composerActions.expand();
+ await composerActions.selectRowByValue("reply_as_new_topic");
+
+ assert
+ .dom(".dialog-body")
+ .hasText(i18n("composer.composer_actions.reply_as_new_topic.confirm"));
+ await click(".dialog-footer .btn-primary");
+
+ assert.dom(".d-editor-input").hasValue(/^Continuing the discussion from/);
+ });
+});
+
+acceptance(`Prioritize Username`, function (needs) {
+ needs.user();
+ needs.settings({
+ prioritize_username_in_ux: true,
+ display_name_on_posts: false,
+ });
+
+ test("Reply to post use username", async function (assert) {
+ await visit("/t/short-topic-with-two-posts/54079");
+ await click("article#post_2 button.reply");
+
+ assert.dom(".action-title .user-link").hasText("james_john");
+ });
+
+ test("Quotes use username", async function (assert) {
+ await visit("/t/short-topic-with-two-posts/54079");
+ await selectText("#post_2 p");
+ await click(".insert-quote");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ '[quote="james_john, post:2, topic:54079, full:true"]\nThis is a short topic.\n[/quote]\n\n'
+ );
+ });
+});
+
+acceptance(`Prioritize Full Name`, function (needs) {
+ needs.user();
+ needs.settings({
+ prioritize_username_in_ux: false,
+ display_name_on_posts: true,
+ });
+
+ test("Reply to post use full name", async function (assert) {
+ await visit("/t/short-topic-with-two-posts/54079");
+ await click("article#post_3 button.reply");
+
+ assert
+ .dom(".action-title .user-link")
+ .hasHtml("&lt;h1&gt;Tim Stone&lt;/h1&gt;");
+ });
+
+ test("Quotes use full name", async function (assert) {
+ await visit("/t/short-topic-with-two-posts/54079");
+ await selectText("#post_2 p");
+ await click(".insert-quote");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ '[quote="james, john, the third, post:2, topic:54079, full:true, username:james_john"]\nThis is a short topic.\n[/quote]\n\n'
+ );
+ });
+
+ test("Quoting a nested quote returns the correct username", async function (assert) {
+ await visit("/t/short-topic-with-two-posts/54079");
+ await selectText("#post_4 p");
+ await click(".insert-quote");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ '[quote="james_john, post:2, topic:54079"]\nThis is a short topic.\n[/quote]\n\n'
+ );
+ });
+});
+
+acceptance(`Prioritizing Name fall back`, function (needs) {
+ needs.user();
+ needs.settings({
+ prioritize_username_in_ux: false,
+ display_name_on_posts: true,
+ });
+
+ test("Quotes fall back to username if name is not present", async function (assert) {
+ await visit("/t/internationalization-localization/130");
+ // select a user with no name
+ await selectText("#post_1 p");
+ await click(".insert-quote");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ '[quote="bianca, post:1, topic:130, full:true"]\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas a varius ipsum. Nunc euismod, metus non vulputate malesuada, ligula metus pharetra tortor, vel sodales arcu lacus sed mauris. Nam semper, orci vitae fringilla placerat, dui tellus convallis felis, ultricies laoreet sapien mi et metus. Mauris facilisis, mi fermentum rhoncus feugiat, dolor est vehicula leo, id porta leo ex non enim. In a ligula vel tellus commodo scelerisque non in ex. Pellentesque semper leo quam, nec varius est viverra eget. Donec vehicula sem et massa faucibus tempus.\n[/quote]\n\n'
+ );
+ });
});
diff --git a/frontend/discourse/tests/acceptance/composer-draft-saving-test.js b/frontend/discourse/tests/acceptance/composer-draft-saving-test.js
index a11e42acdac..45a05485769 100644
--- a/frontend/discourse/tests/acceptance/composer-draft-saving-test.js
+++ b/frontend/discourse/tests/acceptance/composer-draft-saving-test.js
@@ -3,57 +3,45 @@ import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import { i18n } from "discourse-i18n";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Composer - Draft saving (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.user();
-
- const draftThatWillBeSaved = "This_will_be_saved_successfully";
-
- needs.pretender((server, helper) => {
- server.post("/drafts.json", (request) => {
- const success = request.requestBody.includes(draftThatWillBeSaved);
- return success
- ? helper.response({ success: true })
- : helper.response(500, {});
- });
- });
-
- test("Shows a warning if a draft wasn't saved", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(
- ".topic-post[data-post-number='1'] button.show-more-actions"
- );
- await click(".topic-post[data-post-number='1'] button.edit");
-
- await fillIn(".d-editor-input", draftThatWillBeSaved);
-
- assert
- .dom("div#draft-status span")
- .doesNotExist("the draft was saved, there's no warning");
-
- await fillIn(".d-editor-input", "This won't be saved because of error");
- assert
- .dom("div#draft-status span")
- .hasText(
- i18n("composer.drafts_offline"),
- "the draft wasn't saved, a warning is rendered"
- );
- assert
- .dom("div#draft-status svg.d-icon-triangle-exclamation")
- .exists("an exclamation icon is rendered");
-
- await fillIn(".d-editor-input", draftThatWillBeSaved);
- assert
- .dom("div#draft-status span")
- .doesNotExist(
- "the draft was saved again, the warning has disappeared"
- );
- });
- }
- );
+acceptance(`Composer - Draft saving`, function (needs) {
+ needs.user();
+
+ const draftThatWillBeSaved = "This_will_be_saved_successfully";
+
+ needs.pretender((server, helper) => {
+ server.post("/drafts.json", (request) => {
+ const success = request.requestBody.includes(draftThatWillBeSaved);
+ return success
+ ? helper.response({ success: true })
+ : helper.response(500, {});
+ });
+ });
+
+ test("Shows a warning if a draft wasn't saved", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.show-more-actions");
+ await click(".topic-post[data-post-number='1'] button.edit");
+
+ await fillIn(".d-editor-input", draftThatWillBeSaved);
+
+ assert
+ .dom("div#draft-status span")
+ .doesNotExist("the draft was saved, there's no warning");
+
+ await fillIn(".d-editor-input", "This won't be saved because of error");
+ assert
+ .dom("div#draft-status span")
+ .hasText(
+ i18n("composer.drafts_offline"),
+ "the draft wasn't saved, a warning is rendered"
+ );
+ assert
+ .dom("div#draft-status svg.d-icon-triangle-exclamation")
+ .exists("an exclamation icon is rendered");
+
+ await fillIn(".d-editor-input", draftThatWillBeSaved);
+ assert
+ .dom("div#draft-status span")
+ .doesNotExist("the draft was saved again, the warning has disappeared");
+ });
});
diff --git a/frontend/discourse/tests/acceptance/composer-edit-conflict-test.js b/frontend/discourse/tests/acceptance/composer-edit-conflict-test.js
index 3e5043671cf..381e6af09db 100644
--- a/frontend/discourse/tests/acceptance/composer-edit-conflict-test.js
+++ b/frontend/discourse/tests/acceptance/composer-edit-conflict-test.js
@@ -2,46 +2,35 @@ import { click, fillIn, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Composer - Edit conflict (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
+acceptance(`Composer - Edit conflict`, function (needs) {
+ needs.user();
- needs.user();
+ let lastBody;
+ needs.pretender((server, helper) => {
+ server.post("/drafts.json", (request) => {
+ lastBody = request.requestBody;
+ return helper.response({ success: true });
+ });
+ });
- let lastBody;
- needs.pretender((server, helper) => {
- server.post("/drafts.json", (request) => {
- lastBody = request.requestBody;
- return helper.response({ success: true });
- });
- });
+ test("Should not send 'original_text' when posting a new reply", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.reply");
+ await fillIn(
+ ".d-editor-input",
+ "hello world hello world hello world hello world hello world"
+ );
+ assert.false(lastBody.includes("original_text"));
+ });
- test("Should not send 'original_text' when posting a new reply", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".topic-post[data-post-number='1'] button.reply");
- await fillIn(
- ".d-editor-input",
- "hello world hello world hello world hello world hello world"
- );
- assert.false(lastBody.includes("original_text"));
- });
-
- test("Should send 'original_text' when editing a reply", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(
- ".topic-post[data-post-number='1'] button.show-more-actions"
- );
- await click(".topic-post[data-post-number='1'] button.edit");
- await fillIn(
- ".d-editor-input",
- "hello world hello world hello world hello world hello world"
- );
- assert.true(lastBody.includes("original_text"));
- });
- }
- );
+ test("Should send 'original_text' when editing a reply", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.show-more-actions");
+ await click(".topic-post[data-post-number='1'] button.edit");
+ await fillIn(
+ ".d-editor-input",
+ "hello world hello world hello world hello world hello world"
+ );
+ assert.true(lastBody.includes("original_text"));
+ });
});
diff --git a/frontend/discourse/tests/acceptance/composer-hyperlink-test.js b/frontend/discourse/tests/acceptance/composer-hyperlink-test.js
index eff1bc4c1d2..79e58a9bb0b 100644
--- a/frontend/discourse/tests/acceptance/composer-hyperlink-test.js
+++ b/frontend/discourse/tests/acceptance/composer-hyperlink-test.js
@@ -2,119 +2,105 @@ import { click, fillIn, triggerKeyEvent, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Composer - Hyperlink (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.user();
-
- test("add a hyperlink to a reply", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".topic-post[data-post-number='1'] button.reply");
- await fillIn(".d-editor-input", "This is a link to ");
-
- assert
- .dom(".insert-link.d-modal__body")
- .doesNotExist("no hyperlink modal by default");
-
- await click(".d-editor button.link");
- assert
- .dom(".insert-link.d-modal__body")
- .exists("hyperlink modal visible");
-
- await fillIn(".d-modal__body .link-url", "google.com");
- await fillIn(".d-modal__body .link-text", "Google");
- await click(".d-modal__footer button.btn-primary");
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- "This is a link to [Google](https://google.com)",
- "adds link with url and text, prepends 'https://'"
- );
-
- assert
- .dom(".insert-link.d-modal__body")
- .doesNotExist("modal dismissed after submitting link");
-
- await fillIn(".d-editor-input", "Reset textarea contents.");
-
- await click(".d-editor button.link");
- await fillIn(".d-modal__body .link-url", "google.com");
- await fillIn(".d-modal__body .link-text", "Google");
- await click(".d-modal__footer button.btn-transparent");
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- "Reset textarea contents.",
- "doesn’t insert anything after cancelling"
- );
-
- assert
- .dom(".insert-link.d-modal__body")
- .doesNotExist("modal dismissed after cancelling");
-
- const textarea = document.querySelector(
- "#reply-control .d-editor-input"
- );
- textarea.selectionStart = 0;
- textarea.selectionEnd = 6;
- await click(".d-editor button.link");
-
- await fillIn(".d-modal__body .link-url", "somelink.com");
- await click(".d-modal__footer button.btn-primary");
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- "[Reset](https://somelink.com) textarea contents.",
- "adds link to a selected text"
- );
-
- await fillIn(".d-editor-input", "");
-
- await click(".d-editor button.link");
- await fillIn(".d-modal__body .link-url", "http://google.com");
- await triggerKeyEvent(".d-modal__body .link-url", "keyup", "Space");
- assert
- .dom(".internal-link-results")
- .doesNotExist(
- "does not show internal links search dropdown when inputting a url"
- );
-
- await fillIn(".d-modal__body .link-url", "local");
- await triggerKeyEvent(".d-modal__body .link-url", "keyup", "Space");
- assert
- .dom(".internal-link-results")
- .exists(
- "shows internal links search dropdown when entering keywords"
- );
-
- await triggerKeyEvent(".insert-link", "keydown", "ArrowDown");
- await triggerKeyEvent(".insert-link", "keydown", "Enter");
-
- assert
- .dom(".internal-link-results")
- .doesNotExist(
- "search dropdown dismissed after selecting an internal link"
- );
-
- assert
- .dom(".link-url")
- .hasValue(/http/, "replaces link url field with internal link");
-
- await triggerKeyEvent(".insert-link", "keydown", "Escape");
-
- assert
- .dom(".d-editor-input")
- .isFocused(
- "focus stays on composer after dismissing modal using Esc key"
- );
- });
- }
- );
+acceptance(`Composer - Hyperlink`, function (needs) {
+ needs.user();
+
+ test("add a hyperlink to a reply", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.reply");
+ await fillIn(".d-editor-input", "This is a link to ");
+
+ assert
+ .dom(".insert-link.d-modal__body")
+ .doesNotExist("no hyperlink modal by default");
+
+ await click(".d-editor button.link");
+ assert.dom(".insert-link.d-modal__body").exists("hyperlink modal visible");
+
+ await fillIn(".d-modal__body .link-url", "google.com");
+ await fillIn(".d-modal__body .link-text", "Google");
+ await click(".d-modal__footer button.btn-primary");
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "This is a link to [Google](https://google.com)",
+ "adds link with url and text, prepends 'https://'"
+ );
+
+ assert
+ .dom(".insert-link.d-modal__body")
+ .doesNotExist("modal dismissed after submitting link");
+
+ await fillIn(".d-editor-input", "Reset textarea contents.");
+
+ await click(".d-editor button.link");
+ await fillIn(".d-modal__body .link-url", "google.com");
+ await fillIn(".d-modal__body .link-text", "Google");
+ await click(".d-modal__footer button.btn-transparent");
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "Reset textarea contents.",
+ "doesn’t insert anything after cancelling"
+ );
+
+ assert
+ .dom(".insert-link.d-modal__body")
+ .doesNotExist("modal dismissed after cancelling");
+
+ const textarea = document.querySelector("#reply-control .d-editor-input");
+ textarea.selectionStart = 0;
+ textarea.selectionEnd = 6;
+ await click(".d-editor button.link");
+
+ await fillIn(".d-modal__body .link-url", "somelink.com");
+ await click(".d-modal__footer button.btn-primary");
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "[Reset](https://somelink.com) textarea contents.",
+ "adds link to a selected text"
+ );
+
+ await fillIn(".d-editor-input", "");
+
+ await click(".d-editor button.link");
+ await fillIn(".d-modal__body .link-url", "http://google.com");
+ await triggerKeyEvent(".d-modal__body .link-url", "keyup", "Space");
+ assert
+ .dom(".internal-link-results")
+ .doesNotExist(
+ "does not show internal links search dropdown when inputting a url"
+ );
+
+ await fillIn(".d-modal__body .link-url", "local");
+ await triggerKeyEvent(".d-modal__body .link-url", "keyup", "Space");
+ assert
+ .dom(".internal-link-results")
+ .exists("shows internal links search dropdown when entering keywords");
+
+ await triggerKeyEvent(".insert-link", "keydown", "ArrowDown");
+ await triggerKeyEvent(".insert-link", "keydown", "Enter");
+
+ assert
+ .dom(".internal-link-results")
+ .doesNotExist(
+ "search dropdown dismissed after selecting an internal link"
+ );
+
+ assert
+ .dom(".link-url")
+ .hasValue(/http/, "replaces link url field with internal link");
+
+ await triggerKeyEvent(".insert-link", "keydown", "Escape");
+
+ assert
+ .dom(".d-editor-input")
+ .isFocused(
+ "focus stays on composer after dismissing modal using Esc key"
+ );
+ });
});
diff --git a/frontend/discourse/tests/acceptance/composer-test.js b/frontend/discourse/tests/acceptance/composer-test.js
index 47dfd6794ef..5fd4ae2c99a 100644
--- a/frontend/discourse/tests/acceptance/composer-test.js
+++ b/frontend/discourse/tests/acceptance/composer-test.js
@@ -28,1769 +28,1675 @@ import {
import selectKit from "discourse/tests/helpers/select-kit-helper";
import { i18n } from "discourse-i18n";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Composer (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({
- id: 5,
- username: "kris",
- whisperer: true,
- });
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- general_category_id: 1,
- default_composer_category: 1,
- });
- needs.site({
- can_tag_topics: true,
- categories: [
- {
- id: 1,
- name: "General",
- slug: "general",
- permission: 1,
- topic_template: null,
- },
- {
- id: 2,
- name: "test too",
- slug: "test-too",
- permission: 1,
- topic_template: "",
- },
- ],
- });
- needs.pretender((server, helper) => {
- server.put("/u/kris.json", () => helper.response({ user: {} }));
- server.post("/uploads/lookup-urls", () => {
- return helper.response([]);
- });
- server.get("/posts/419", () => {
- return helper.response({ id: 419 });
- });
- server.get("/composer/mentions", () => {
- return helper.response({
- users: [],
- user_reasons: {},
- groups: { staff: { user_count: 30 } },
- group_reasons: {},
- max_users_notified_per_group_mention: 100,
- });
- });
- server.get("/t/960.json", () => {
- const topicList = cloneJSON(TopicFixtures["/t/9/1.json"]);
- topicList.post_stream.posts[2].post_type = 4;
- return helper.response(topicList);
- });
- });
-
- test("Composer is opened", async function (assert) {
- await visit("/");
- await click("#create-topic");
- // Check that the default category is selected
- assert.strictEqual(
- selectKit(".category-chooser").header().value(),
- "1"
- );
-
- assert.strictEqual(
- document.documentElement.style.getPropertyValue("--composer-height"),
- "var(--new-topic-composer-height, 400px)",
- "sets --composer-height to 400px when creating topic"
- );
-
- await click(".toggle-minimize");
- assert.strictEqual(
- document.documentElement.style.getPropertyValue("--composer-height"),
- "40px",
- "sets --composer-height to 40px when composer is minimized without content"
- );
-
- await click(".toggle-fullscreen");
- await fillIn(
- ".d-editor-input",
- "this is the *content* of a new topic post"
- );
- await click(".toggle-minimize");
- assert.strictEqual(
- document.documentElement.style.getPropertyValue("--composer-height"),
- "40px",
- "sets --composer-height to 40px when composer is minimized to draft mode"
- );
-
- await click(".toggle-fullscreen");
- assert.strictEqual(
- document.documentElement.style.getPropertyValue("--composer-height"),
- "var(--new-topic-composer-height, 400px)",
- "sets --composer-height back to 400px when composer is opened from draft mode"
- );
-
- await fillIn(".d-editor-input", "");
- await click("#reply-control .discard-button");
- assert.strictEqual(
- document.documentElement.style.getPropertyValue("--composer-height"),
- "",
- "removes --composer-height property when composer is closed"
- );
- });
-
- test("Composer height adjustment", async function (assert) {
- await visit("/");
- await click("#create-topic");
- await triggerEvent(".grippie", "mousedown");
- await triggerEvent(".grippie", "mousemove");
- await triggerEvent(".grippie", "mouseup");
- await visit("/"); // reload page
- await click("#create-topic");
-
- const expectedHeight = localStorage.getItem(
- "__test_discourse_composerHeight"
- );
- const actualHeight =
- document.documentElement.style.getPropertyValue("--composer-height");
-
- assert.strictEqual(
- expectedHeight,
- actualHeight,
- "Updated height is persistent"
- );
- });
-
- test("composer controls", async function (assert) {
- await visit("/");
- assert.dom("#create-topic").exists("the create button is visible");
-
- await click("#create-topic");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- await focus(".title-input input");
- assert
- .dom(".title-input .popup-tip.good.hide")
- .exists("title errors are hidden by default");
- assert
- .dom(".d-editor-textarea-wrapper .popup-tip.bad.hide")
- .exists("body errors are hidden by default");
-
- await click(".toggle-preview");
- assert
- .dom(".d-editor-preview")
- .isNotVisible("clicking the toggle hides the preview");
-
- await click(".toggle-preview");
- assert
- .dom(".d-editor-preview")
- .isVisible("clicking the toggle shows the preview again");
-
- await click("#reply-control button.create");
- assert
- .dom(".title-input .popup-tip.bad")
- .exists("shows the empty title error");
- assert
- .dom(".d-editor-textarea-wrapper .popup-tip.bad")
- .exists("shows the empty body error");
-
- await fillIn("#reply-title", "this is my new topic title");
- assert
- .dom(".title-input .popup-tip.good.hide")
- .exists("the title is now good");
-
- await triggerKeyEvent(
- ".d-editor-textarea-wrapper .popup-tip.bad",
- "keydown",
- "Enter"
- );
- assert
- .dom(".d-editor-textarea-wrapper .popup-tip.bad.hide")
- .exists("body error is dismissed via keyboard");
-
- await fillIn(".d-editor-input", "this is the *content* of a post");
- assert
- .dom(".d-editor-preview")
- .hasHtml(
- "<p>this is the <em>content</em> of a post</p>",
- "previews content"
- );
- assert
- .dom(".d-editor-textarea-wrapper .popup-tip.good")
- .exists("the body is now good");
-
- const textarea = find("#reply-control .d-editor-input");
- textarea.selectionStart = textarea.value.length;
- textarea.selectionEnd = textarea.value.length;
-
- await triggerKeyEvent(textarea, "keydown", "B", metaModifier);
-
- assert
- .dom("#reply-control .d-editor-input")
- .hasValue(
- `this is the *content* of a post**${i18n("composer.bold_text")}**`,
- "supports keyboard shortcuts"
- );
-
- await click("#reply-control .discard-button");
- assert.dom(".d-modal").exists("pops up a confirmation dialog");
-
- await click(".d-modal__footer .discard-draft-modal__discard-btn");
- assert
- .dom(".d-modal__body")
- .doesNotExist("the confirmation can be cancelled");
- });
-
- test("Create a topic with server side errors", async function (assert) {
- pretender.post("/posts", function () {
- return response(422, {
- errors: ["That title has already been taken"],
- });
- });
-
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "this title triggers an error");
- await fillIn(".d-editor-input", "this is the *content* of a post");
- await click("#reply-control button.create");
- assert.dom(".dialog-body").exists("pops up an error message");
-
- await click(".dialog-footer .btn-primary");
- assert.dom(".dialog-body").doesNotExist("dismisses the error");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- });
-
- test("Create a Topic", async function (assert) {
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "Internationalization Localization");
- await fillIn(
- ".d-editor-input",
- "this is the *content* of a new topic post"
- );
- await click("#reply-control button.create");
- assert.strictEqual(
- currentURL(),
- "/t/internationalization-localization/280",
- "transitions to the newly created topic URL"
- );
- });
-
- test("Create an enqueued Topic", async function (assert) {
- pretender.post("/posts", function () {
- return response(200, {
- success: true,
- action: "enqueued",
- pending_post: {
- id: 1234,
- raw: "enqueue this content please",
- },
- });
- });
-
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "Internationalization Localization");
- await fillIn(".d-editor-input", "enqueue this content please");
- await click("#reply-control button.create");
- assert.dom(".d-modal").exists("pops up a modal");
- assert.strictEqual(currentURL(), "/", "doesn't change routes");
-
- await click(".d-modal__footer button");
- assert.dom(".d-modal").doesNotExist("the modal can be dismissed");
- });
-
- test("Can display a message and route to a URL", async function (assert) {
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "This title doesn't matter");
- await fillIn(".d-editor-input", "custom message that is a good length");
- await click("#reply-control button.create");
-
- assert
- .dom("#dialog-holder .dialog-body")
- .hasText("This is a custom response");
- assert.strictEqual(currentURL(), "/", "doesn't change routes");
-
- await click(".dialog-footer .btn-primary");
- assert.strictEqual(
- currentURL(),
- "/faq",
- "can navigate to a `route_to` destination"
- );
- });
-
- test("Create a Reply", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- assert
- .dom('article[data-post-id="12345"]')
- .doesNotExist("the post is not in the DOM");
-
- await click("#topic-footer-buttons .btn.create");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- assert
- .dom("#reply-title")
- .doesNotExist("there is no title since this is a reply");
-
- await fillIn(".d-editor-input", "this is the content of my reply");
- await click("#reply-control button.create");
- assert
- .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p")
- .hasText("this is the content of my reply");
- });
-
- test("Replying to the first post in a topic is a topic reply", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- await click("#post_1 .reply.create");
- assert
- .dom(".reply-details a.topic-link")
- .hasText("Internationalization / localization");
-
- await click("#post_1 .reply.create");
- assert
- .dom(".reply-details a.topic-link")
- .hasText("Internationalization / localization");
- });
-
- test("Can edit a post after starting a reply", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- await click("#topic-footer-buttons .create");
- await fillIn(".d-editor-input", "this is the content of my reply");
-
- await click(
- ".topic-post[data-post-number='1'] button.show-more-actions"
- );
- await click(".topic-post[data-post-number='1'] button.edit");
-
- await click(".d-modal__footer .discard-draft-modal__cancel-btn");
- assert.dom(".discard-draft-modal.modal").doesNotExist();
- assert
- .dom(".d-editor-input")
- .hasValue(
- "this is the content of my reply",
- "composer does not switch on dismissed Discard draft confirmation modal"
- );
-
- await click(".topic-post[data-post-number='1'] button.edit");
- await click(".d-modal__footer .discard-draft-modal__discard-btn");
- assert.dom(".discard-draft-modal.modal").doesNotExist();
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- find(".topic-post[data-post-number='1'] .cooked > p").innerText,
- "composer has contents of post to be edited"
- );
- });
-
- test("Can dismiss Discard draft confirmation modal when replying on a different topic", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- await click("#topic-footer-buttons .create");
- await fillIn(".d-editor-input", "this is the content of my reply");
-
- await visit("/t/this-is-a-test-topic/9");
- await click("#topic-footer-buttons .create");
- assert.dom(".discard-draft-modal.modal").exists();
-
- await click(".d-modal__footer .discard-draft-modal__cancel-btn");
- assert.dom(".discard-draft-modal.modal").doesNotExist();
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- "this is the content of my reply",
- "composer does not switch on dismissed Discard draft confirmation modal"
- );
- });
-
- test("Posting on a different topic", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .btn.create");
- await fillIn(
- ".d-editor-input",
- "this is the content for a different topic"
- );
- await visit("/t/1-3-0beta9-no-rate-limit-popups/28830");
-
- assert.strictEqual(
- currentURL(),
- "/t/1-3-0beta9-no-rate-limit-popups/28830"
- );
-
- await click("#reply-control button.create");
-
- assert.dom(".reply-where-modal").exists("pops up a modal");
- assert
- .dom(".topic-title")
- .exists({ count: 2 }, "it renders the two topics");
- assert
- .dom(".btn-reply-where:nth-of-type(1) .badge-category__name")
- .hasText("test too", "it renders the category name");
- assert
- .dom(".btn-reply-where:nth-of-type(2) .discourse-tags")
- .hasText("foo", "it renders the tags");
-
- await click(".btn-reply-here");
-
- assert
- .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p")
- .hasText(
- "If you use gettext format you could leverage Launchpad translations and the community behind it."
- );
- });
-
- test("Discard draft modal works when switching topics", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .btn.create");
- await fillIn(
- ".d-editor-input",
- "this is the content of the first reply"
- );
-
- await visit("/t/this-is-a-test-topic/9");
- assert.true(
- currentURL().startsWith("/t/this-is-a-test-topic/9"),
- "moves to second topic"
- );
- await click("#topic-footer-buttons .btn.create");
- assert
- .dom(".discard-draft-modal.modal")
- .exists("pops up the discard drafts modal");
-
- await click(".d-modal__footer .discard-draft-modal__cancel-btn");
-
- assert.dom(".discard-draft-modal.modal").doesNotExist("hides modal");
- await click("#topic-footer-buttons .btn.create");
- assert
- .dom(".discard-draft-modal.modal")
- .exists("pops up the modal again");
-
- await click(".d-modal__footer .discard-draft-modal__discard-btn");
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- "This is a draft of the first post",
- "loads the existing draft"
- );
- });
-
- test("Loads draft in composer when clicking reply on a topic with existing draft", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- await click("#topic-footer-buttons .btn.create");
-
- assert
- .dom(".d-editor-input")
- .hasValue("This is a draft of the first post");
- });
-
- test("Autosaves drafts after cancelling Discard draft confirmation modal", async function (assert) {
- pretender.post("/drafts.json", function () {
- assert.step("saveDraft");
- return response(200, {});
- });
- pretender.get("/drafts/topic_280.json", function () {
- return response(200, { draft: null });
- });
-
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .btn.create");
- await fillIn(".d-editor-input", "this is draft content of the reply");
- assert.verifySteps(["saveDraft"], "first draft is auto saved");
-
- await click("#reply-control .discard-button");
- assert
- .dom(".discard-draft-modal.modal")
- .exists("shows Discard draft confirmation modal");
-
- await click(".d-modal__footer .discard-draft-modal__cancel-btn");
- assert
- .dom(".discard-draft-modal.modal")
- .doesNotExist("hides modal on Cancel button click");
- assert
- .dom(".d-editor-input")
- .hasValue(
- "this is draft content of the reply",
- "composer has the content of the first draft"
- );
-
- await fillIn(
- ".d-editor-input",
- "this is the first update to the draft content",
- "update content in the composer"
- );
- assert.verifySteps(["saveDraft"], "second draft is saved");
-
- await click("#reply-control .discard-button");
- assert
- .dom(".discard-draft-modal.modal")
- .exists("pops up the discard drafts modal");
-
- await triggerKeyEvent(".discard-draft-modal", "keydown", "Escape");
- assert
- .dom(".discard-draft-modal.modal")
- .doesNotExist("hides modal on Esc key stroke");
+acceptance(`Composer`, function (needs) {
+ needs.user({
+ id: 5,
+ username: "kris",
+ whisperer: true,
+ });
+ needs.settings({
+ general_category_id: 1,
+ default_composer_category: 1,
+ });
+ needs.site({
+ can_tag_topics: true,
+ categories: [
+ {
+ id: 1,
+ name: "General",
+ slug: "general",
+ permission: 1,
+ topic_template: null,
+ },
+ {
+ id: 2,
+ name: "test too",
+ slug: "test-too",
+ permission: 1,
+ topic_template: "",
+ },
+ ],
+ });
+ needs.pretender((server, helper) => {
+ server.put("/u/kris.json", () => helper.response({ user: {} }));
+ server.post("/uploads/lookup-urls", () => {
+ return helper.response([]);
+ });
+ server.get("/posts/419", () => {
+ return helper.response({ id: 419 });
+ });
+ server.get("/composer/mentions", () => {
+ return helper.response({
+ users: [],
+ user_reasons: {},
+ groups: { staff: { user_count: 30 } },
+ group_reasons: {},
+ max_users_notified_per_group_mention: 100,
+ });
+ });
+ server.get("/t/960.json", () => {
+ const topicList = cloneJSON(TopicFixtures["/t/9/1.json"]);
+ topicList.post_stream.posts[2].post_type = 4;
+ return helper.response(topicList);
+ });
+ });
+
+ test("Composer is opened", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ // Check that the default category is selected
+ assert.strictEqual(selectKit(".category-chooser").header().value(), "1");
+
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ "var(--new-topic-composer-height, 400px)",
+ "sets --composer-height to 400px when creating topic"
+ );
+
+ await click(".toggle-minimize");
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ "40px",
+ "sets --composer-height to 40px when composer is minimized without content"
+ );
+
+ await click(".toggle-fullscreen");
+ await fillIn(
+ ".d-editor-input",
+ "this is the *content* of a new topic post"
+ );
+ await click(".toggle-minimize");
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ "40px",
+ "sets --composer-height to 40px when composer is minimized to draft mode"
+ );
+
+ await click(".toggle-fullscreen");
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ "var(--new-topic-composer-height, 400px)",
+ "sets --composer-height back to 400px when composer is opened from draft mode"
+ );
+
+ await fillIn(".d-editor-input", "");
+ await click("#reply-control .discard-button");
+ assert.strictEqual(
+ document.documentElement.style.getPropertyValue("--composer-height"),
+ "",
+ "removes --composer-height property when composer is closed"
+ );
+ });
+
+ test("Composer height adjustment", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await triggerEvent(".grippie", "mousedown");
+ await triggerEvent(".grippie", "mousemove");
+ await triggerEvent(".grippie", "mouseup");
+ await visit("/"); // reload page
+ await click("#create-topic");
+
+ const expectedHeight = localStorage.getItem(
+ "__test_discourse_composerHeight"
+ );
+ const actualHeight =
+ document.documentElement.style.getPropertyValue("--composer-height");
+
+ assert.strictEqual(
+ expectedHeight,
+ actualHeight,
+ "Updated height is persistent"
+ );
+ });
+
+ test("composer controls", async function (assert) {
+ await visit("/");
+ assert.dom("#create-topic").exists("the create button is visible");
+
+ await click("#create-topic");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ await focus(".title-input input");
+ assert
+ .dom(".title-input .popup-tip.good.hide")
+ .exists("title errors are hidden by default");
+ assert
+ .dom(".d-editor-textarea-wrapper .popup-tip.bad.hide")
+ .exists("body errors are hidden by default");
+
+ await click(".toggle-preview");
+ assert
+ .dom(".d-editor-preview")
+ .isNotVisible("clicking the toggle hides the preview");
+
+ await click(".toggle-preview");
+ assert
+ .dom(".d-editor-preview")
+ .isVisible("clicking the toggle shows the preview again");
+
+ await click("#reply-control button.create");
+ assert
+ .dom(".title-input .popup-tip.bad")
+ .exists("shows the empty title error");
+ assert
+ .dom(".d-editor-textarea-wrapper .popup-tip.bad")
+ .exists("shows the empty body error");
+
+ await fillIn("#reply-title", "this is my new topic title");
+ assert
+ .dom(".title-input .popup-tip.good.hide")
+ .exists("the title is now good");
+
+ await triggerKeyEvent(
+ ".d-editor-textarea-wrapper .popup-tip.bad",
+ "keydown",
+ "Enter"
+ );
+ assert
+ .dom(".d-editor-textarea-wrapper .popup-tip.bad.hide")
+ .exists("body error is dismissed via keyboard");
+
+ await fillIn(".d-editor-input", "this is the *content* of a post");
+ assert
+ .dom(".d-editor-preview")
+ .hasHtml(
+ "<p>this is the <em>content</em> of a post</p>",
+ "previews content"
+ );
+ assert
+ .dom(".d-editor-textarea-wrapper .popup-tip.good")
+ .exists("the body is now good");
- await fillIn(
- ".d-editor-input",
- "this is the second update to the draft content",
- "update content in the composer"
- );
- assert.verifySteps(["saveDraft"], "third draft is saved");
+ const textarea = find("#reply-control .d-editor-input");
+ textarea.selectionStart = textarea.value.length;
+ textarea.selectionEnd = textarea.value.length;
- await click("#reply-control button.create");
- assert
- .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p")
- .hasText("this is the second update to the draft content");
- });
+ await triggerKeyEvent(textarea, "keydown", "B", metaModifier);
- test("Create an enqueued Reply", async function (assert) {
- pretender.post("/posts", function () {
- return response(200, {
- success: true,
- action: "enqueued",
- pending_post: {
- id: 1234,
- raw: "enqueue this content please",
- },
- });
- });
+ assert
+ .dom("#reply-control .d-editor-input")
+ .hasValue(
+ `this is the *content* of a post**${i18n("composer.bold_text")}**`,
+ "supports keyboard shortcuts"
+ );
- await visit("/t/internationalization-localization/280");
- assert.dom(".pending-posts .reviewable-item").doesNotExist();
+ await click("#reply-control .discard-button");
+ assert.dom(".d-modal").exists("pops up a confirmation dialog");
+
+ await click(".d-modal__footer .discard-draft-modal__discard-btn");
+ assert
+ .dom(".d-modal__body")
+ .doesNotExist("the confirmation can be cancelled");
+ });
+
+ test("Create a topic with server side errors", async function (assert) {
+ pretender.post("/posts", function () {
+ return response(422, {
+ errors: ["That title has already been taken"],
+ });
+ });
+
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "this title triggers an error");
+ await fillIn(".d-editor-input", "this is the *content* of a post");
+ await click("#reply-control button.create");
+ assert.dom(".dialog-body").exists("pops up an error message");
+
+ await click(".dialog-footer .btn-primary");
+ assert.dom(".dialog-body").doesNotExist("dismisses the error");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ });
+
+ test("Create a Topic", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "Internationalization Localization");
+ await fillIn(
+ ".d-editor-input",
+ "this is the *content* of a new topic post"
+ );
+ await click("#reply-control button.create");
+ assert.strictEqual(
+ currentURL(),
+ "/t/internationalization-localization/280",
+ "transitions to the newly created topic URL"
+ );
+ });
+
+ test("Create an enqueued Topic", async function (assert) {
+ pretender.post("/posts", function () {
+ return response(200, {
+ success: true,
+ action: "enqueued",
+ pending_post: {
+ id: 1234,
+ raw: "enqueue this content please",
+ },
+ });
+ });
+
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "Internationalization Localization");
+ await fillIn(".d-editor-input", "enqueue this content please");
+ await click("#reply-control button.create");
+ assert.dom(".d-modal").exists("pops up a modal");
+ assert.strictEqual(currentURL(), "/", "doesn't change routes");
+
+ await click(".d-modal__footer button");
+ assert.dom(".d-modal").doesNotExist("the modal can be dismissed");
+ });
+
+ test("Can display a message and route to a URL", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "This title doesn't matter");
+ await fillIn(".d-editor-input", "custom message that is a good length");
+ await click("#reply-control button.create");
+
+ assert
+ .dom("#dialog-holder .dialog-body")
+ .hasText("This is a custom response");
+ assert.strictEqual(currentURL(), "/", "doesn't change routes");
+
+ await click(".dialog-footer .btn-primary");
+ assert.strictEqual(
+ currentURL(),
+ "/faq",
+ "can navigate to a `route_to` destination"
+ );
+ });
+
+ test("Create a Reply", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ assert
+ .dom('article[data-post-id="12345"]')
+ .doesNotExist("the post is not in the DOM");
+
+ await click("#topic-footer-buttons .btn.create");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ assert
+ .dom("#reply-title")
+ .doesNotExist("there is no title since this is a reply");
+
+ await fillIn(".d-editor-input", "this is the content of my reply");
+ await click("#reply-control button.create");
+ assert
+ .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p")
+ .hasText("this is the content of my reply");
+ });
+
+ test("Replying to the first post in a topic is a topic reply", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ await click("#post_1 .reply.create");
+ assert
+ .dom(".reply-details a.topic-link")
+ .hasText("Internationalization / localization");
+
+ await click("#post_1 .reply.create");
+ assert
+ .dom(".reply-details a.topic-link")
+ .hasText("Internationalization / localization");
+ });
+
+ test("Can edit a post after starting a reply", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ await click("#topic-footer-buttons .create");
+ await fillIn(".d-editor-input", "this is the content of my reply");
+
+ await click(".topic-post[data-post-number='1'] button.show-more-actions");
+ await click(".topic-post[data-post-number='1'] button.edit");
+
+ await click(".d-modal__footer .discard-draft-modal__cancel-btn");
+ assert.dom(".discard-draft-modal.modal").doesNotExist();
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "this is the content of my reply",
+ "composer does not switch on dismissed Discard draft confirmation modal"
+ );
- await click("#topic-footer-buttons .btn.create");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- assert
- .dom("#reply-title")
- .doesNotExist("there is no title since this is a reply");
+ await click(".topic-post[data-post-number='1'] button.edit");
+ await click(".d-modal__footer .discard-draft-modal__discard-btn");
+ assert.dom(".discard-draft-modal.modal").doesNotExist();
- await fillIn(".d-editor-input", "enqueue this content please");
- await click("#reply-control button.create");
- assert
- .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p")
- .doesNotIncludeText(
- "enqueue this content please",
- "doesn't insert the post"
- );
- assert.dom(".d-modal").exists("pops up a modal");
-
- await click(".d-modal__footer button");
- assert.dom(".d-modal").doesNotExist("the modal can be dismissed");
- assert.dom(".pending-posts .reviewable-item").exists();
- });
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ find(".topic-post[data-post-number='1'] .cooked > p").innerText,
+ "composer has contents of post to be edited"
+ );
+ });
- test("Edit the first post", async function (assert) {
- await visit("/t/internationalization-localization/280");
+ test("Can dismiss Discard draft confirmation modal when replying on a different topic", async function (assert) {
+ await visit("/t/internationalization-localization/280");
- assert
- .dom(".topic-post[data-post-number='1'] .post-info.edits")
- .doesNotExist("has no edits icon at first");
+ await click("#topic-footer-buttons .create");
+ await fillIn(".d-editor-input", "this is the content of my reply");
- await click(
- ".topic-post[data-post-number='1'] button.show-more-actions"
- );
- await click(".topic-post[data-post-number='1'] button.edit");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^Any plans to support/,
- "populates the input with the post text"
- );
-
- await fillIn(".d-editor-input", "This is the new text for the post");
- await fillIn("#reply-title", "This is the new text for the title");
- await click("#reply-control button.create");
- assert.dom(".d-editor-input").doesNotExist("closes the composer");
- assert
- .dom(".topic-post[data-post-number='1'] .post-info.edits")
- .exists("has the edits icon");
- assert
- .dom("#topic-title h1")
- .includesText(
- "This is the new text for the title",
- "shows the new title"
- );
- assert
- .dom(".topic-post[data-post-number='1'] .cooked")
- .includesText(
- "This is the new text for the post",
- "updates the post"
- );
- });
+ await visit("/t/this-is-a-test-topic/9");
+ await click("#topic-footer-buttons .create");
+ assert.dom(".discard-draft-modal.modal").exists();
- test("Editing a post stages new content", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".topic-post button.show-more-actions");
- await click(".topic-post button.edit");
+ await click(".d-modal__footer .discard-draft-modal__cancel-btn");
+ assert.dom(".discard-draft-modal.modal").doesNotExist();
- await fillIn(".d-editor-input", "will return empty json");
- await fillIn("#reply-title", "This is the new text for the title");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "this is the content of my reply",
+ "composer does not switch on dismissed Discard draft confirmation modal"
+ );
+ });
+
+ test("Posting on a different topic", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .btn.create");
+ await fillIn(
+ ".d-editor-input",
+ "this is the content for a different topic"
+ );
+ await visit("/t/1-3-0beta9-no-rate-limit-popups/28830");
+
+ assert.strictEqual(
+ currentURL(),
+ "/t/1-3-0beta9-no-rate-limit-popups/28830"
+ );
+
+ await click("#reply-control button.create");
+
+ assert.dom(".reply-where-modal").exists("pops up a modal");
+ assert
+ .dom(".topic-title")
+ .exists({ count: 2 }, "it renders the two topics");
+ assert
+ .dom(".btn-reply-where:nth-of-type(1) .badge-category__name")
+ .hasText("test too", "it renders the category name");
+ assert
+ .dom(".btn-reply-where:nth-of-type(2) .discourse-tags")
+ .hasText("foo", "it renders the tags");
+
+ await click(".btn-reply-here");
+
+ assert
+ .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p")
+ .hasText(
+ "If you use gettext format you could leverage Launchpad translations and the community behind it."
+ );
+ });
+
+ test("Discard draft modal works when switching topics", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .btn.create");
+ await fillIn(".d-editor-input", "this is the content of the first reply");
+
+ await visit("/t/this-is-a-test-topic/9");
+ assert.true(
+ currentURL().startsWith("/t/this-is-a-test-topic/9"),
+ "moves to second topic"
+ );
+ await click("#topic-footer-buttons .btn.create");
+ assert
+ .dom(".discard-draft-modal.modal")
+ .exists("pops up the discard drafts modal");
+
+ await click(".d-modal__footer .discard-draft-modal__cancel-btn");
+
+ assert.dom(".discard-draft-modal.modal").doesNotExist("hides modal");
+ await click("#topic-footer-buttons .btn.create");
+ assert.dom(".discard-draft-modal.modal").exists("pops up the modal again");
+
+ await click(".d-modal__footer .discard-draft-modal__discard-btn");
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "This is a draft of the first post",
+ "loads the existing draft"
+ );
+ });
+
+ test("Loads draft in composer when clicking reply on a topic with existing draft", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ await click("#topic-footer-buttons .btn.create");
+
+ assert.dom(".d-editor-input").hasValue("This is a draft of the first post");
+ });
+
+ test("Autosaves drafts after cancelling Discard draft confirmation modal", async function (assert) {
+ pretender.post("/drafts.json", function () {
+ assert.step("saveDraft");
+ return response(200, {});
+ });
+ pretender.get("/drafts/topic_280.json", function () {
+ return response(200, { draft: null });
+ });
+
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .btn.create");
+ await fillIn(".d-editor-input", "this is draft content of the reply");
+ assert.verifySteps(["saveDraft"], "first draft is auto saved");
+
+ await click("#reply-control .discard-button");
+ assert
+ .dom(".discard-draft-modal.modal")
+ .exists("shows Discard draft confirmation modal");
+
+ await click(".d-modal__footer .discard-draft-modal__cancel-btn");
+ assert
+ .dom(".discard-draft-modal.modal")
+ .doesNotExist("hides modal on Cancel button click");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "this is draft content of the reply",
+ "composer has the content of the first draft"
+ );
- const done = assert.async();
+ await fillIn(
+ ".d-editor-input",
+ "this is the first update to the draft content",
+ "update content in the composer"
+ );
+ assert.verifySteps(["saveDraft"], "second draft is saved");
+
+ await click("#reply-control .discard-button");
+ assert
+ .dom(".discard-draft-modal.modal")
+ .exists("pops up the discard drafts modal");
+
+ await triggerKeyEvent(".discard-draft-modal", "keydown", "Escape");
+ assert
+ .dom(".discard-draft-modal.modal")
+ .doesNotExist("hides modal on Esc key stroke");
+
+ await fillIn(
+ ".d-editor-input",
+ "this is the second update to the draft content",
+ "update content in the composer"
+ );
+ assert.verifySteps(["saveDraft"], "third draft is saved");
+
+ await click("#reply-control button.create");
+ assert
+ .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p")
+ .hasText("this is the second update to the draft content");
+ });
+
+ test("Create an enqueued Reply", async function (assert) {
+ pretender.post("/posts", function () {
+ return response(200, {
+ success: true,
+ action: "enqueued",
+ pending_post: {
+ id: 1234,
+ raw: "enqueue this content please",
+ },
+ });
+ });
+
+ await visit("/t/internationalization-localization/280");
+ assert.dom(".pending-posts .reviewable-item").doesNotExist();
+
+ await click("#topic-footer-buttons .btn.create");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ assert
+ .dom("#reply-title")
+ .doesNotExist("there is no title since this is a reply");
+
+ await fillIn(".d-editor-input", "enqueue this content please");
+ await click("#reply-control button.create");
+ assert
+ .dom(".topic-post:nth-last-child(1 of .topic-post) .cooked p")
+ .doesNotIncludeText(
+ "enqueue this content please",
+ "doesn't insert the post"
+ );
+ assert.dom(".d-modal").exists("pops up a modal");
+
+ await click(".d-modal__footer button");
+ assert.dom(".d-modal").doesNotExist("the modal can be dismissed");
+ assert.dom(".pending-posts .reviewable-item").exists();
+ });
+
+ test("Edit the first post", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ assert
+ .dom(".topic-post[data-post-number='1'] .post-info.edits")
+ .doesNotExist("has no edits icon at first");
+
+ await click(".topic-post[data-post-number='1'] button.show-more-actions");
+ await click(".topic-post[data-post-number='1'] button.edit");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^Any plans to support/,
+ "populates the input with the post text"
+ );
- pretender.put("/posts/:post_id", async () => {
- // at this point, request is in flight, so post is staged
- await waitFor(".topic-post.staged");
+ await fillIn(".d-editor-input", "This is the new text for the post");
+ await fillIn("#reply-title", "This is the new text for the title");
+ await click("#reply-control button.create");
+ assert.dom(".d-editor-input").doesNotExist("closes the composer");
+ assert
+ .dom(".topic-post[data-post-number='1'] .post-info.edits")
+ .exists("has the edits icon");
+ assert
+ .dom("#topic-title h1")
+ .includesText(
+ "This is the new text for the title",
+ "shows the new title"
+ );
+ assert
+ .dom(".topic-post[data-post-number='1'] .cooked")
+ .includesText("This is the new text for the post", "updates the post");
+ });
- assert.dom(".topic-post.staged").exists();
- assert
- .dom(".topic-post.staged .cooked")
- .hasText("will return empty json");
+ test("Editing a post stages new content", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post button.show-more-actions");
+ await click(".topic-post button.edit");
- done();
+ await fillIn(".d-editor-input", "will return empty json");
+ await fillIn("#reply-title", "This is the new text for the title");
- return response(200, {});
- });
+ const done = assert.async();
- await click("#reply-control button.create");
+ pretender.put("/posts/:post_id", async () => {
+ // at this point, request is in flight, so post is staged
+ await waitFor(".topic-post.staged");
- await visit("/t/internationalization-localization/280");
- assert.dom(".topic-post.staged").doesNotExist();
- });
+ assert.dom(".topic-post.staged").exists();
+ assert
+ .dom(".topic-post.staged .cooked")
+ .hasText("will return empty json");
- test("Composer can switch between edits", async function (assert) {
- await visit("/t/this-is-a-test-topic/9");
+ done();
- await click(".topic-post[data-post-number='1'] button.edit");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the first post\./,
- "populates the input with the post text"
- );
- await click(".topic-post[data-post-number='2'] button.edit");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the second post\./,
- "populates the input with the post text"
- );
- });
+ return response(200, {});
+ });
- test("Composer with dirty edit can toggle to another edit", async function (assert) {
- await visit("/t/this-is-a-test-topic/9");
+ await click("#reply-control button.create");
- await click(".topic-post[data-post-number='1'] button.edit");
- await fillIn(".d-editor-input", "This is a dirty reply");
- await click(".topic-post[data-post-number='2'] button.edit");
- assert
- .dom(".discard-draft-modal.modal")
- .exists("pops up a confirmation dialog");
+ await visit("/t/internationalization-localization/280");
+ assert.dom(".topic-post.staged").doesNotExist();
+ });
- await click(".d-modal__footer .discard-draft-modal__discard-btn");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the second post\./,
- "populates the input with the post text"
- );
- });
+ test("Composer can switch between edits", async function (assert) {
+ await visit("/t/this-is-a-test-topic/9");
- test("Composer can toggle between edit and reply on the OP", async function (assert) {
- await visit("/t/this-is-a-test-topic/54081");
+ await click(".topic-post[data-post-number='1'] button.edit");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the first post\./,
+ "populates the input with the post text"
+ );
+ await click(".topic-post[data-post-number='2'] button.edit");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the second post\./,
+ "populates the input with the post text"
+ );
+ });
+
+ test("Composer with dirty edit can toggle to another edit", async function (assert) {
+ await visit("/t/this-is-a-test-topic/9");
+
+ await click(".topic-post[data-post-number='1'] button.edit");
+ await fillIn(".d-editor-input", "This is a dirty reply");
+ await click(".topic-post[data-post-number='2'] button.edit");
+ assert
+ .dom(".discard-draft-modal.modal")
+ .exists("pops up a confirmation dialog");
+
+ await click(".d-modal__footer .discard-draft-modal__discard-btn");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the second post\./,
+ "populates the input with the post text"
+ );
+ });
- await click(".topic-post[data-post-number='1'] button.edit");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the first post\./,
- "populates the input with the post text"
- );
+ test("Composer can toggle between edit and reply on the OP", async function (assert) {
+ await visit("/t/this-is-a-test-topic/54081");
- await click(".topic-post[data-post-number='1'] button.reply");
- assert.dom(".d-editor-input").hasNoValue("clears the composer input");
+ await click(".topic-post[data-post-number='1'] button.edit");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the first post\./,
+ "populates the input with the post text"
+ );
- await click(".topic-post[data-post-number='1'] button.edit");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the first post\./,
- "populates the input with the post text"
- );
- });
+ await click(".topic-post[data-post-number='1'] button.reply");
+ assert.dom(".d-editor-input").hasNoValue("clears the composer input");
- test("Composer can toggle between edit and reply on a reply", async function (assert) {
- await visit("/t/this-is-a-test-topic/54081");
+ await click(".topic-post[data-post-number='1'] button.edit");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the first post\./,
+ "populates the input with the post text"
+ );
+ });
- await click(".topic-post[data-post-number='2'] button.edit");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the second post\./,
- "populates the input with the post text"
- );
+ test("Composer can toggle between edit and reply on a reply", async function (assert) {
+ await visit("/t/this-is-a-test-topic/54081");
- await click(".topic-post[data-post-number='2'] button.reply");
- assert.dom(".d-editor-input").hasNoValue("clears the composer input");
+ await click(".topic-post[data-post-number='2'] button.edit");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the second post\./,
+ "populates the input with the post text"
+ );
- await click(".topic-post[data-post-number='2'] button.edit");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the second post\./,
- "populates the input with the post text"
- );
- });
+ await click(".topic-post[data-post-number='2'] button.reply");
+ assert.dom(".d-editor-input").hasNoValue("clears the composer input");
- test("Composer can toggle whispers when whisperer user", async function (assert) {
- const menu = selectKit(".composer-actions");
+ await click(".topic-post[data-post-number='2'] button.edit");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the second post\./,
+ "populates the input with the post text"
+ );
+ });
- await visit("/t/this-is-a-test-topic/9");
- await click(".topic-post[data-post-number='1'] button.reply");
+ test("Composer can toggle whispers when whisperer user", async function (assert) {
+ const menu = selectKit(".composer-actions");
- await menu.expand();
- await menu.selectRowByValue("toggle_whisper");
+ await visit("/t/this-is-a-test-topic/9");
+ await click(".topic-post[data-post-number='1'] button.reply");
- assert
- .dom(".composer-actions svg.d-icon-far-eye-slash")
- .exists("sets the post type to whisper");
+ await menu.expand();
+ await menu.selectRowByValue("toggle_whisper");
- await menu.expand();
- await menu.selectRowByValue("toggle_whisper");
+ assert
+ .dom(".composer-actions svg.d-icon-far-eye-slash")
+ .exists("sets the post type to whisper");
- assert
- .dom(".composer-actions svg.d-icon-far-eye-slash")
- .doesNotExist("removes the whisper mode");
- });
+ await menu.expand();
+ await menu.selectRowByValue("toggle_whisper");
- test("Composer can toggle layouts (open, fullscreen and draft)", async function (assert) {
- await visit("/t/this-is-a-test-topic/9");
- await click(".topic-post[data-post-number='1'] button.reply");
+ assert
+ .dom(".composer-actions svg.d-icon-far-eye-slash")
+ .doesNotExist("removes the whisper mode");
+ });
- assert
- .dom("#reply-control.open")
- .isVisible("starts in open state by default");
+ test("Composer can toggle layouts (open, fullscreen and draft)", async function (assert) {
+ await visit("/t/this-is-a-test-topic/9");
+ await click(".topic-post[data-post-number='1'] button.reply");
- await click(".toggle-fullscreen");
+ assert
+ .dom("#reply-control.open")
+ .isVisible("starts in open state by default");
- assert
- .dom("#reply-control.fullscreen")
- .isVisible("expands composer to full screen");
+ await click(".toggle-fullscreen");
- assert
- .dom(".composer-fullscreen-prompt")
- .isVisible("the fullscreen prompt is visible");
+ assert
+ .dom("#reply-control.fullscreen")
+ .isVisible("expands composer to full screen");
- await click(".toggle-fullscreen");
+ assert
+ .dom(".composer-fullscreen-prompt")
+ .isVisible("the fullscreen prompt is visible");
- assert
- .dom("#reply-control.open")
- .isVisible("collapses composer to regular size");
+ await click(".toggle-fullscreen");
- await fillIn(".d-editor-input", "This is a dirty reply");
- await click(".toggler");
+ assert
+ .dom("#reply-control.open")
+ .isVisible("collapses composer to regular size");
- assert
- .dom("#reply-control.draft")
- .isVisible("collapses composer to draft bar");
+ await fillIn(".d-editor-input", "This is a dirty reply");
+ await click(".toggler");
- await click(".toggle-fullscreen");
+ assert
+ .dom("#reply-control.draft")
+ .isVisible("collapses composer to draft bar");
- assert
- .dom("#reply-control.open")
- .isVisible("from draft, it expands composer back to open state");
- });
+ await click(".toggle-fullscreen");
- test("Composer fullscreen submit button", async function (assert) {
- await visit("/t/this-is-a-test-topic/9");
- await click(".topic-post[data-post-number='1'] button.reply");
+ assert
+ .dom("#reply-control.open")
+ .isVisible("from draft, it expands composer back to open state");
+ });
- assert
- .dom("#reply-control.open")
- .exists("starts in open state by default");
+ test("Composer fullscreen submit button", async function (assert) {
+ await visit("/t/this-is-a-test-topic/9");
+ await click(".topic-post[data-post-number='1'] button.reply");
- await click(".toggle-fullscreen");
+ assert.dom("#reply-control.open").exists("starts in open state by default");
- assert
- .dom("#reply-control button.create")
- .exists("shows composer submit button in fullscreen");
+ await click(".toggle-fullscreen");
- await fillIn(".d-editor-input", "too short");
- await click("#reply-control button.create");
+ assert
+ .dom("#reply-control button.create")
+ .exists("shows composer submit button in fullscreen");
- assert
- .dom("#reply-control.open")
- .exists("goes back to open state if there's errors");
- });
+ await fillIn(".d-editor-input", "too short");
+ await click("#reply-control button.create");
- module(
- "Composer can switch between new topic and new PM in different contexts",
- function () {
- test("within post/topic context", async function (assert) {
- await visit("/t/this-is-a-test-topic/54081");
- await click(".topic-post[data-post-number='1'] button.reply");
- await selectKit(".composer-actions").expand();
- assert.notStrictEqual(
- selectKit(".composer-actions")
- .rowByValue("create_private_message")
- .exists(),
- "New message option is not present when in reply mode"
- );
-
- await click("#reply-control .discard-button");
- await visit("/");
- await click("#create-topic");
- await selectKit(".composer-actions").expand();
- assert.true(
- selectKit(".composer-actions")
- .rowByValue("reply_to_topic")
- .exists(),
- "composer topic context is preserved when reopened"
- );
-
- await selectKit(".composer-actions").selectRowByValue(
- "create_private_message"
- );
- assert.dom(".action-title").hasText(i18n("topic.private_message"));
- assert
- .dom(".save-or-cancel button")
- .hasText(i18n("composer.create_pm"));
-
- await selectKit(".composer-actions").expand();
- await selectKit(".composer-actions").selectRowByValue(
- "create_topic"
- );
- assert.dom(".action-title").hasText(i18n("topic.create_long"));
- assert
- .dom(".save-or-cancel button")
- .hasText(i18n("composer.create_topic"));
- });
- }
- );
+ assert
+ .dom("#reply-control.open")
+ .exists("goes back to open state if there's errors");
+ });
- test("Composer can toggle between reply and createTopic", async function (assert) {
+ module(
+ "Composer can switch between new topic and new PM in different contexts",
+ function () {
+ test("within post/topic context", async function (assert) {
await visit("/t/this-is-a-test-topic/54081");
await click(".topic-post[data-post-number='1'] button.reply");
-
await selectKit(".composer-actions").expand();
-
- await selectKit(".composer-actions").selectRowByValue("toggle_whisper");
-
- assert
- .dom(".composer-actions svg.d-icon-far-eye-slash")
- .exists("sets the post type to whisper");
-
- await visit("/");
- assert
- .dom("#create-topic")
- .exists("the create topic button is visible");
-
- await click("#create-topic");
- assert
- .dom(".reply-details .whisper .d-icon-far-eye-slash")
- .doesNotExist("should reset the state of the composer's model");
-
- await selectKit(".composer-actions").expand();
- await selectKit(".composer-actions").selectRowByValue(
- "toggle_unlisted"
- );
-
- assert
- .dom(".reply-details .unlist")
- .includesText(i18n("composer.unlist"), "sets the topic to unlisted");
-
- await visit("/t/this-is-a-test-topic/9");
-
- await click(".topic-post[data-post-number='1'] button.reply");
- assert
- .dom(".reply-details .whisper")
- .doesNotExist("should reset the state of the composer's model");
- });
-
- test("Composer can toggle whisper when switching from reply to whisper to reply to topic", async function (assert) {
- await visit("/t/topic-with-whisper/960");
-
- await click(".topic-post[data-post-number='3'] button.reply");
- await click(".reply-details summary div");
- assert
- .dom('.reply-details li[data-value="toggle_whisper"]')
- .doesNotExist(
- "toggle whisper is not available when reply to whisper"
- );
- await click('.reply-details li[data-value="reply_to_topic"]');
- await click(".reply-details summary div");
- assert
- .dom('.reply-details li[data-value="toggle_whisper"]')
- .exists("toggle whisper is available when reply to topic");
- });
-
- test("Composer can toggle whisper when clicking reply to topic after reply to whisper", async function (assert) {
- await visit("/t/topic-with-whisper/54081");
-
- await click(".topic-post[data-post-number='3'] button.reply");
- await click("#reply-control .discard-button");
- await click(".timeline-footer-controls button.create");
- await click(".reply-details summary div");
- assert
- .dom('.reply-details li[data-value="toggle_whisper"]')
- .exists("toggle whisper is available when reply to topic");
- });
-
- test("Composer draft with dirty reply can toggle to edit", async function (assert) {
- await visit("/t/this-is-a-test-topic/9");
-
- await click(".topic-post[data-post-number='1'] button.reply");
- await fillIn(".d-editor-input", "This is a dirty reply");
- await click(".toggler");
- await click(".topic-post[data-post-number='2'] button.edit");
- assert
- .dom(".discard-draft-modal.modal")
- .exists("pops up a confirmation dialog");
- assert
- .dom(".d-modal__footer .discard-draft-modal__cancel-btn")
- .hasText(i18n("cancel_value"), "has Cancel button");
- await click(".d-modal__footer .discard-draft-modal__discard-btn");
- assert
- .dom(".d-editor-input")
- .hasValue(
- /^This is the second post\./,
- "populates the input with the post text"
- );
- });
-
- test("Composer shows Discard draft confirmation dialog in new context (when creating a new topic)", async function (assert) {
- await visit("/t/this-is-a-test-topic/9");
-
- await click(".topic-post[data-post-number='1'] button.reply");
- await fillIn(".d-editor-input", "This is a dirty reply");
-
- await click("#site-logo");
- await click("#create-topic");
-
- assert
- .dom(".discard-draft-modal.modal")
- .exists("pops up a confirmation dialog");
- assert
- .dom(".d-modal__footer .discard-draft-modal__discard-btn")
- .hasText(i18n("post.cancel_composer.discard"), "has Discard button");
- assert
- .dom(".d-modal__footer .discard-draft-modal__cancel-btn")
- .hasText(i18n("cancel_value"), "has Cancel button");
- });
-
- test("Does not check for existing draft", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- await click(
- ".topic-post[data-post-number='1'] button.show-more-actions"
+ assert.notStrictEqual(
+ selectKit(".composer-actions")
+ .rowByValue("create_private_message")
+ .exists(),
+ "New message option is not present when in reply mode"
);
- await click(".topic-post[data-post-number='1'] button.edit");
-
- assert.dom(".dialog-body").doesNotExist("does not open the dialog");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- assert.dom(".d-editor-input").hasValue(/^Any plans to support/);
- });
-
- test("Can switch states without abandon popup", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- const longText = "a".repeat(256);
-
- sinon.stub(Draft, "get").resolves({
- draft: null,
- draft_sequence: 0,
- });
-
- await click(".btn-primary.create.btn");
-
- await fillIn(".d-editor-input", longText);
-
- assert
- .dom(
- '.action-title a[href="/t/internationalization-localization/280"]'
- )
- .exists("the mode should be: reply to post");
-
- await click("article#post_3 button.reply");
-
- const composerActions = selectKit(".composer-actions");
- await composerActions.expand();
- await composerActions.selectRowByValue("reply_as_new_topic");
-
- assert
- .dom(".d-modal__body")
- .doesNotExist("abandon popup shouldn't come");
-
- assert
- .dom(".d-editor-input")
- .includesValue(longText, "entered text should still be there");
-
- assert
- .dom(
- '.action-title a[href="/t/internationalization-localization/280"]'
- )
- .doesNotExist("mode should have changed");
- });
-
- test("Does not replace recipient when another draft exists", async function (assert) {
- sinon.stub(Draft, "get").resolves({
- draft:
- '{"reply":"hello","action":"privateMessage","title":"hello","categoryId":null,"archetypeId":"private_message","metaData":null,"recipients":"codinghorror","composerTime":9159,"typingTime":2500}',
- draft_sequence: 0,
- });
-
- await visit("/u/charlie");
- await click("button.compose-pm");
-
- const privateMessageUsers = selectKit("#private-message-users");
- assert.strictEqual(privateMessageUsers.header().value(), "charlie");
await click("#reply-control .discard-button");
- assert.dom(".d-editor-input").doesNotExist();
- });
-
- test("Deleting the text content of the first post in a private message", async function (assert) {
- await visit("/t/34");
-
- await click("#post_1 .d-icon-ellipsis");
- await click("#post_1 .d-icon-pencil");
- await fillIn(".d-editor-input", "");
-
- assert
- .dom(".d-editor-container textarea")
- .hasAttribute(
- "placeholder",
- i18n("composer.reply_placeholder"),
- "should not block because of missing category"
- );
- });
-
- test("modified placeholder with composer-editor-reply-placeholder is rendered", async function (assert) {
- withPluginApi((api) => {
- api.registerValueTransformer(
- "composer-editor-reply-placeholder",
- () => {
- return "modified_value";
- }
- );
- });
-
- await visit("/t/34");
- await click("article#post_3 button.reply");
-
- assert
- .dom(".d-editor-container textarea")
- .hasAttribute("placeholder", i18n("modified_value"));
- });
-
- test("reply button has envelope icon when replying to private message", async function (assert) {
- await visit("/t/34");
- await click("article#post_3 button.reply");
- assert
- .dom(".save-or-cancel button.create")
- .hasText(i18n("composer.create_pm"), "reply button says Message");
- assert
- .dom(".save-or-cancel button.create svg.d-icon-envelope")
- .exists("reply button has envelope icon");
- });
-
- test("edit button when editing a post in a PM", async function (assert) {
- await visit("/t/34");
- await click("article#post_3 button.show-more-actions");
- await click("article#post_3 button.edit");
-
- assert
- .dom(".save-or-cancel button.create")
- .hasText(i18n("composer.save_edit"), "save button says Save Edit");
- assert
- .dom(".save-or-cancel button.create svg.d-icon-pencil")
- .exists("save button has pencil icon");
- });
-
- test("Shows duplicate_link notice", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .create");
-
- this.container.lookup("service:composer").set(
- "linkLookup",
- new LinkLookup({
- "github.com": {
- domain: "github.com",
- username: "system",
- posted_at: "2021-01-01T12:00:00.000Z",
- post_number: 1,
- },
- })
- );
-
- await fillIn(".d-editor-input", "[](https://discourse.org)");
- assert.dom(".composer-popup").doesNotExist();
-
- await fillIn(
- ".d-editor-input",
- "[quote][](https://github.com)[/quote]"
- );
- assert.dom(".composer-popup").doesNotExist();
-
- await fillIn(".d-editor-input", "[](https://github.com)");
- assert.dom(".composer-popup").exists();
- });
-
- test("Shows the 'group_mentioned' notice", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .create");
-
- await fillIn(".d-editor-input", "[quote]\n@staff\n[/quote]");
- assert
- .dom(".composer-popup")
- .doesNotExist("Doesn't show the 'group_mentioned' notice in a quote");
-
- await fillIn(".d-editor-input", "@staff");
- assert
- .dom(".composer-popup")
- .exists("shows the 'group_mentioned' notice");
- });
-
- test("Does not save invalid draft", async function (assert) {
- this.siteSettings.min_first_post_length = 20;
-
await visit("/");
await click("#create-topic");
- await fillIn("#reply-title", "Something");
- await fillIn(".d-editor-input", "Something");
- await click("button.create");
- assert.dom(".d-editor-textarea-wrapper .popup-tip.bad").hasText(
- i18n("composer.error.post_length.other", {
- count: this.siteSettings.min_first_post_length,
- }),
- "shows error"
+ await selectKit(".composer-actions").expand();
+ assert.true(
+ selectKit(".composer-actions").rowByValue("reply_to_topic").exists(),
+ "composer topic context is preserved when reopened"
);
- });
-
- test("Saves drafts that only contain quotes", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .create");
-
- await fillIn(".d-editor-input", "[quote]some quote[/quote]");
- await click(".discard-button");
- assert.dom(".discard-draft-modal").exists();
- });
-
- test("Discard drafts modal can be dismissed via keyboard", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-buttons .create");
-
- await fillIn(".d-editor-input", "[quote]some quote[/quote]");
-
- await click(".discard-button");
- assert.dom(".discard-draft-modal").exists();
-
- await triggerKeyEvent(".discard-draft-modal", "keydown", "Escape");
-
- assert.dom(".discard-draft-modal").doesNotExist();
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- "[quote]some quote[/quote]",
- "composer textarea is not cleared"
- );
- });
- }
- );
-
- acceptance(
- `Composer - Customizations (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.user();
- needs.site({ can_tag_topics: true });
-
- function customComposerAction(composer) {
- return (
- (composer.tags || []).includes("monkey") &&
- composer.action === CREATE_TOPIC
+ await selectKit(".composer-actions").selectRowByValue(
+ "create_private_message"
);
- }
-
- needs.hooks.beforeEach(() => {
- withPluginApi((api) => {
- api.customizeComposerText({
- actionTitle(model) {
- if (customComposerAction(model)) {
- return "custom text";
- }
- },
-
- saveLabel(model) {
- if (customComposerAction(model)) {
- return "composer.emoji";
- }
- },
- });
- });
- });
+ assert.dom(".action-title").hasText(i18n("topic.private_message"));
+ assert
+ .dom(".save-or-cancel button")
+ .hasText(i18n("composer.create_pm"));
- test("Supports text customization", async function (assert) {
- await visit("/");
- await click("#create-topic");
+ await selectKit(".composer-actions").expand();
+ await selectKit(".composer-actions").selectRowByValue("create_topic");
assert.dom(".action-title").hasText(i18n("topic.create_long"));
assert
.dom(".save-or-cancel button")
.hasText(i18n("composer.create_topic"));
- const tags = selectKit(".mini-tag-chooser");
- await tags.expand();
- await tags.selectRowByValue("monkey");
- assert.dom(".action-title").hasText("custom text");
- assert.dom(".save-or-cancel button").hasText(i18n("composer.emoji"));
});
}
);
- acceptance(
- `Composer - Error Extensibility (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- general_category_id: 1,
- default_composer_category: 1,
- });
-
- needs.hooks.beforeEach(() => {
- withPluginApi((api) => {
- api.addComposerSaveErrorCallback((error) => {
- if (error.match(/PLUGIN_XYZ ERROR/)) {
- // handle error
- return true;
- }
- return false;
- });
- });
- });
-
- test("Create a topic with server side errors handled by a plugin", async function (assert) {
- pretender.post("/posts", function () {
- return response(422, { errors: ["PLUGIN_XYZ ERROR"] });
- });
-
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "this title triggers an error");
- await fillIn(".d-editor-input", "this is the *content* of a post");
- await click("#reply-control button.create");
- assert
- .dom(".dialog-body")
- .doesNotExist("does not pop up an error message");
- });
-
- test("Create a topic with server side errors not handled by a plugin", async function (assert) {
- pretender.post("/posts", function () {
- return response(422, { errors: ["PLUGIN_ABC ERROR"] });
- });
-
- await visit("/");
- await click("#create-topic");
- await fillIn("#reply-title", "this title triggers an error");
- await fillIn(".d-editor-input", "this is the *content* of a post");
- await click("#reply-control button.create");
- assert.dom(".dialog-body").exists("pops up an error message");
- assert
- .dom(".dialog-body")
- .hasText(/PLUGIN_ABC ERROR/, "contains the server side error text");
- await click(".dialog-footer .btn-primary");
- assert.dom(".dialog-body").doesNotExist("dismisses the error");
- assert.dom(".d-editor-input").exists("the composer input is visible");
- });
- }
- );
+ test("Composer can toggle between reply and createTopic", async function (assert) {
+ await visit("/t/this-is-a-test-topic/54081");
+ await click(".topic-post[data-post-number='1'] button.reply");
+
+ await selectKit(".composer-actions").expand();
+
+ await selectKit(".composer-actions").selectRowByValue("toggle_whisper");
+
+ assert
+ .dom(".composer-actions svg.d-icon-far-eye-slash")
+ .exists("sets the post type to whisper");
+
+ await visit("/");
+ assert.dom("#create-topic").exists("the create topic button is visible");
+
+ await click("#create-topic");
+ assert
+ .dom(".reply-details .whisper .d-icon-far-eye-slash")
+ .doesNotExist("should reset the state of the composer's model");
+
+ await selectKit(".composer-actions").expand();
+ await selectKit(".composer-actions").selectRowByValue("toggle_unlisted");
+
+ assert
+ .dom(".reply-details .unlist")
+ .includesText(i18n("composer.unlist"), "sets the topic to unlisted");
+
+ await visit("/t/this-is-a-test-topic/9");
+
+ await click(".topic-post[data-post-number='1'] button.reply");
+ assert
+ .dom(".reply-details .whisper")
+ .doesNotExist("should reset the state of the composer's model");
+ });
+
+ test("Composer can toggle whisper when switching from reply to whisper to reply to topic", async function (assert) {
+ await visit("/t/topic-with-whisper/960");
+
+ await click(".topic-post[data-post-number='3'] button.reply");
+ await click(".reply-details summary div");
+ assert
+ .dom('.reply-details li[data-value="toggle_whisper"]')
+ .doesNotExist("toggle whisper is not available when reply to whisper");
+ await click('.reply-details li[data-value="reply_to_topic"]');
+ await click(".reply-details summary div");
+ assert
+ .dom('.reply-details li[data-value="toggle_whisper"]')
+ .exists("toggle whisper is available when reply to topic");
+ });
+
+ test("Composer can toggle whisper when clicking reply to topic after reply to whisper", async function (assert) {
+ await visit("/t/topic-with-whisper/54081");
+
+ await click(".topic-post[data-post-number='3'] button.reply");
+ await click("#reply-control .discard-button");
+ await click(".timeline-footer-controls button.create");
+ await click(".reply-details summary div");
+ assert
+ .dom('.reply-details li[data-value="toggle_whisper"]')
+ .exists("toggle whisper is available when reply to topic");
+ });
+
+ test("Composer draft with dirty reply can toggle to edit", async function (assert) {
+ await visit("/t/this-is-a-test-topic/9");
+
+ await click(".topic-post[data-post-number='1'] button.reply");
+ await fillIn(".d-editor-input", "This is a dirty reply");
+ await click(".toggler");
+ await click(".topic-post[data-post-number='2'] button.edit");
+ assert
+ .dom(".discard-draft-modal.modal")
+ .exists("pops up a confirmation dialog");
+ assert
+ .dom(".d-modal__footer .discard-draft-modal__cancel-btn")
+ .hasText(i18n("cancel_value"), "has Cancel button");
+ await click(".d-modal__footer .discard-draft-modal__discard-btn");
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^This is the second post\./,
+ "populates the input with the post text"
+ );
+ });
- acceptance(
- `Composer - Focus Open and Closed (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- allow_uncategorized_topics: true,
- });
+ test("Composer shows Discard draft confirmation dialog in new context (when creating a new topic)", async function (assert) {
+ await visit("/t/this-is-a-test-topic/9");
- test("Focusing a composer which is not open with create topic", async function (assert) {
- await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.reply");
+ await fillIn(".d-editor-input", "This is a dirty reply");
- const composer = this.container.lookup("service:composer");
- await composer.focusComposer({ fallbackToNewTopic: true });
+ await click("#site-logo");
+ await click("#create-topic");
- await settled();
- assert.dom(".d-editor-input").isFocused("composer is open and focused");
- assert.strictEqual(composer.model.action, Composer.CREATE_TOPIC);
- });
+ assert
+ .dom(".discard-draft-modal.modal")
+ .exists("pops up a confirmation dialog");
+ assert
+ .dom(".d-modal__footer .discard-draft-modal__discard-btn")
+ .hasText(i18n("post.cancel_composer.discard"), "has Discard button");
+ assert
+ .dom(".d-modal__footer .discard-draft-modal__cancel-btn")
+ .hasText(i18n("cancel_value"), "has Cancel button");
+ });
- test("Focusing a composer which is not open with create topic and append text", async function (assert) {
- await visit("/t/internationalization-localization/280");
+ test("Does not check for existing draft", async function (assert) {
+ await visit("/t/internationalization-localization/280");
- const composer = this.container.lookup("service:composer");
- await composer.focusComposer({
- fallbackToNewTopic: true,
- insertText: "this is appended",
- });
+ await click(".topic-post[data-post-number='1'] button.show-more-actions");
+ await click(".topic-post[data-post-number='1'] button.edit");
- await settled();
- assert.dom(".d-editor-input").isFocused("composer is open and focused");
- assert.dom("textarea.d-editor-input").hasValue("this is appended");
- });
+ assert.dom(".dialog-body").doesNotExist("does not open the dialog");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ assert.dom(".d-editor-input").hasValue(/^Any plans to support/);
+ });
- test("Focusing a composer which is already open", async function (assert) {
- await visit("/");
- await click("#create-topic");
+ test("Can switch states without abandon popup", async function (assert) {
+ await visit("/t/internationalization-localization/280");
- const composer = this.container.lookup("service:composer");
- await composer.focusComposer();
+ const longText = "a".repeat(256);
- await settled();
- assert.dom(".d-editor-input").isFocused("composer is open and focused");
- });
+ sinon.stub(Draft, "get").resolves({
+ draft: null,
+ draft_sequence: 0,
+ });
- test("Focusing a composer which is already open and append text", async function (assert) {
- await visit("/");
- await click("#create-topic");
+ await click(".btn-primary.create.btn");
- const composer = this.container.lookup("service:composer");
- await composer.focusComposer({
- insertText: "this is some appended text",
- });
+ await fillIn(".d-editor-input", longText);
- await settled();
- assert.dom(".d-editor-input").isFocused("composer is open and focused");
- assert
- .dom("textarea.d-editor-input")
- .hasValue("this is some appended text");
- });
+ assert
+ .dom('.action-title a[href="/t/internationalization-localization/280"]')
+ .exists("the mode should be: reply to post");
- test("Focusing a composer which is not open that has a draft", async function (assert) {
- await visit("/t/this-is-a-test-topic/9");
+ await click("article#post_3 button.reply");
- await click(".topic-post[data-post-number='1'] button.edit");
- await fillIn(".d-editor-input", "This is a dirty reply");
- await click(".toggle-minimize");
+ const composerActions = selectKit(".composer-actions");
+ await composerActions.expand();
+ await composerActions.selectRowByValue("reply_as_new_topic");
- const composer = this.container.lookup("service:composer");
- await composer.focusComposer({
- insertText: "this is some appended text",
- });
+ assert.dom(".d-modal__body").doesNotExist("abandon popup shouldn't come");
- await settled();
- assert.dom(".d-editor-input").isFocused("composer is open and focused");
- assert
- .dom("textarea.d-editor-input")
- .hasValue("This is a dirty reply\n\nthis is some appended text");
- });
- }
- );
+ assert
+ .dom(".d-editor-input")
+ .includesValue(longText, "entered text should still be there");
- // Default Composer Category tests
- acceptance(
- `Composer - Default category (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- general_category_id: 1,
- default_composer_category: 2,
- });
- needs.site({
- categories: [
- {
- id: 1,
- name: "General",
- slug: "general",
- permission: 1,
- topic_template: null,
- },
- {
- id: 2,
- name: "test too",
- slug: "test-too",
- permission: 1,
- topic_template: null,
- },
- ],
- });
+ assert
+ .dom('.action-title a[href="/t/internationalization-localization/280"]')
+ .doesNotExist("mode should have changed");
+ });
- test("Default category is selected over general category", async function (assert) {
- await visit("/");
- await click("#create-topic");
- assert.strictEqual(
- selectKit(".category-chooser").header().value(),
- "2"
- );
- assert.strictEqual(
- selectKit(".category-chooser").header().name(),
- "test too"
- );
- });
- }
- );
+ test("Does not replace recipient when another draft exists", async function (assert) {
+ sinon.stub(Draft, "get").resolves({
+ draft:
+ '{"reply":"hello","action":"privateMessage","title":"hello","categoryId":null,"archetypeId":"private_message","metaData":null,"recipients":"codinghorror","composerTime":9159,"typingTime":2500}',
+ draft_sequence: 0,
+ });
- acceptance(
- `Composer - Uncategorized category (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- general_category_id: -1, // For sites that never had this seeded
- default_composer_category: -1, // For sites that never had this seeded
- allow_uncategorized_topics: true,
- });
- needs.site({
- categories: [
- {
- id: 1,
- name: "General",
- slug: "general",
- permission: 1,
- topic_template: null,
- },
- {
- id: 2,
- name: "test too",
- slug: "test-too",
- permission: 1,
- topic_template: null,
- },
- ],
- });
+ await visit("/u/charlie");
+ await click("button.compose-pm");
- test("Uncategorized category is selected", async function (assert) {
- await visit("/");
- await click("#create-topic");
- assert.strictEqual(
- selectKit(".category-chooser").header().value(),
- null
- );
- });
- }
- );
+ const privateMessageUsers = selectKit("#private-message-users");
+ assert.strictEqual(privateMessageUsers.header().value(), "charlie");
- acceptance(
- `Composer - default category not set (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- default_composer_category: "",
- });
- needs.site({
- categories: [
- {
- id: 1,
- name: "General",
- slug: "general",
- permission: 1,
- topic_template: null,
- },
- {
- id: 2,
- name: "test too",
- slug: "test-too",
- permission: 1,
- topic_template: null,
- },
- ],
- });
+ await click("#reply-control .discard-button");
+ assert.dom(".d-editor-input").doesNotExist();
+ });
- test("Nothing is selected", async function (assert) {
- await visit("/");
- await click("#create-topic");
- assert.strictEqual(
- selectKit(".category-chooser").header().value(),
- null
- );
- assert.strictEqual(
- selectKit(".category-chooser").header().name(),
- "category&hellip;"
- );
- });
- }
- );
- // END: Default Composer Category tests
-
- acceptance(
- `composer buttons API (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- allow_uncategorized_topics: true,
- });
- needs.pretender((server, helper) => {
- server.get("/drafts/topic_280.json", function () {
- return helper.response(200, { draft: null });
- });
- });
+ test("Deleting the text content of the first post in a private message", async function (assert) {
+ await visit("/t/34");
- test("buttons can support a shortcut", async function (assert) {
- withPluginApi((api) => {
- api.addComposerToolbarPopupMenuOption({
- action: (toolbarEvent) => {
- toolbarEvent.applySurround("**", "**");
- },
- shortcut: "alt+b",
- icon: "far-bold",
- name: "bold",
- title: "some_title",
- label: "some_label",
-
- condition: () => {
- return true;
- },
- });
- });
+ await click("#post_1 .d-icon-ellipsis");
+ await click("#post_1 .d-icon-pencil");
+ await fillIn(".d-editor-input", "");
- await visit("/t/internationalization-localization/280");
- await click(".post-controls button.reply");
- await fillIn(".d-editor-input", "hello the world");
+ assert
+ .dom(".d-editor-container textarea")
+ .hasAttribute(
+ "placeholder",
+ i18n("composer.reply_placeholder"),
+ "should not block because of missing category"
+ );
+ });
+
+ test("modified placeholder with composer-editor-reply-placeholder is rendered", async function (assert) {
+ withPluginApi((api) => {
+ api.registerValueTransformer("composer-editor-reply-placeholder", () => {
+ return "modified_value";
+ });
+ });
+
+ await visit("/t/34");
+ await click("article#post_3 button.reply");
+
+ assert
+ .dom(".d-editor-container textarea")
+ .hasAttribute("placeholder", i18n("modified_value"));
+ });
+
+ test("reply button has envelope icon when replying to private message", async function (assert) {
+ await visit("/t/34");
+ await click("article#post_3 button.reply");
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.create_pm"), "reply button says Message");
+ assert
+ .dom(".save-or-cancel button.create svg.d-icon-envelope")
+ .exists("reply button has envelope icon");
+ });
+
+ test("edit button when editing a post in a PM", async function (assert) {
+ await visit("/t/34");
+ await click("article#post_3 button.show-more-actions");
+ await click("article#post_3 button.edit");
+
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.save_edit"), "save button says Save Edit");
+ assert
+ .dom(".save-or-cancel button.create svg.d-icon-pencil")
+ .exists("save button has pencil icon");
+ });
+
+ test("Shows duplicate_link notice", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .create");
+
+ this.container.lookup("service:composer").set(
+ "linkLookup",
+ new LinkLookup({
+ "github.com": {
+ domain: "github.com",
+ username: "system",
+ posted_at: "2021-01-01T12:00:00.000Z",
+ post_number: 1,
+ },
+ })
+ );
+
+ await fillIn(".d-editor-input", "[](https://discourse.org)");
+ assert.dom(".composer-popup").doesNotExist();
+
+ await fillIn(".d-editor-input", "[quote][](https://github.com)[/quote]");
+ assert.dom(".composer-popup").doesNotExist();
+
+ await fillIn(".d-editor-input", "[](https://github.com)");
+ assert.dom(".composer-popup").exists();
+ });
+
+ test("Shows the 'group_mentioned' notice", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .create");
+
+ await fillIn(".d-editor-input", "[quote]\n@staff\n[/quote]");
+ assert
+ .dom(".composer-popup")
+ .doesNotExist("Doesn't show the 'group_mentioned' notice in a quote");
+
+ await fillIn(".d-editor-input", "@staff");
+ assert.dom(".composer-popup").exists("shows the 'group_mentioned' notice");
+ });
+
+ test("Does not save invalid draft", async function (assert) {
+ this.siteSettings.min_first_post_length = 20;
+
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "Something");
+ await fillIn(".d-editor-input", "Something");
+ await click("button.create");
+ assert.dom(".d-editor-textarea-wrapper .popup-tip.bad").hasText(
+ i18n("composer.error.post_length.other", {
+ count: this.siteSettings.min_first_post_length,
+ }),
+ "shows error"
+ );
+ });
+
+ test("Saves drafts that only contain quotes", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .create");
+
+ await fillIn(".d-editor-input", "[quote]some quote[/quote]");
+
+ await click(".discard-button");
+ assert.dom(".discard-draft-modal").exists();
+ });
+
+ test("Discard drafts modal can be dismissed via keyboard", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-buttons .create");
+
+ await fillIn(".d-editor-input", "[quote]some quote[/quote]");
+
+ await click(".discard-button");
+ assert.dom(".discard-draft-modal").exists();
+
+ await triggerKeyEvent(".discard-draft-modal", "keydown", "Escape");
+
+ assert.dom(".discard-draft-modal").doesNotExist();
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "[quote]some quote[/quote]",
+ "composer textarea is not cleared"
+ );
+ });
+});
- const editor = find(".d-editor-input");
- editor.setSelectionRange(6, 9); // select the text input in the composer
+acceptance(`Composer - Customizations`, function (needs) {
+ needs.user();
+ needs.site({ can_tag_topics: true });
+
+ function customComposerAction(composer) {
+ return (
+ (composer.tags || []).includes("monkey") &&
+ composer.action === CREATE_TOPIC
+ );
+ }
+
+ needs.hooks.beforeEach(() => {
+ withPluginApi((api) => {
+ api.customizeComposerText({
+ actionTitle(model) {
+ if (customComposerAction(model)) {
+ return "custom text";
+ }
+ },
+
+ saveLabel(model) {
+ if (customComposerAction(model)) {
+ return "composer.emoji";
+ }
+ },
+ });
+ });
+ });
+
+ test("Supports text customization", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ assert.dom(".action-title").hasText(i18n("topic.create_long"));
+ assert.dom(".save-or-cancel button").hasText(i18n("composer.create_topic"));
+ const tags = selectKit(".mini-tag-chooser");
+ await tags.expand();
+ await tags.selectRowByValue("monkey");
+ assert.dom(".action-title").hasText("custom text");
+ assert.dom(".save-or-cancel button").hasText(i18n("composer.emoji"));
+ });
+});
- await triggerKeyEvent(".d-editor-input", "keydown", "B", {
- altKey: true,
- ...metaModifier,
- });
+acceptance(`Composer - Error Extensibility`, function (needs) {
+ needs.user();
+ needs.settings({
+ general_category_id: 1,
+ default_composer_category: 1,
+ });
+
+ needs.hooks.beforeEach(() => {
+ withPluginApi((api) => {
+ api.addComposerSaveErrorCallback((error) => {
+ if (error.match(/PLUGIN_XYZ ERROR/)) {
+ // handle error
+ return true;
+ }
+ return false;
+ });
+ });
+ });
+
+ test("Create a topic with server side errors handled by a plugin", async function (assert) {
+ pretender.post("/posts", function () {
+ return response(422, { errors: ["PLUGIN_XYZ ERROR"] });
+ });
+
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "this title triggers an error");
+ await fillIn(".d-editor-input", "this is the *content* of a post");
+ await click("#reply-control button.create");
+ assert.dom(".dialog-body").doesNotExist("does not pop up an error message");
+ });
+
+ test("Create a topic with server side errors not handled by a plugin", async function (assert) {
+ pretender.post("/posts", function () {
+ return response(422, { errors: ["PLUGIN_ABC ERROR"] });
+ });
+
+ await visit("/");
+ await click("#create-topic");
+ await fillIn("#reply-title", "this title triggers an error");
+ await fillIn(".d-editor-input", "this is the *content* of a post");
+ await click("#reply-control button.create");
+ assert.dom(".dialog-body").exists("pops up an error message");
+ assert
+ .dom(".dialog-body")
+ .hasText(/PLUGIN_ABC ERROR/, "contains the server side error text");
+ await click(".dialog-footer .btn-primary");
+ assert.dom(".dialog-body").doesNotExist("dismisses the error");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+ });
+});
- assert
- .dom(".d-editor-input")
- .hasValue("hello **the** world", "adds the bold");
+acceptance(`Composer - Focus Open and Closed`, function (needs) {
+ needs.user();
+ needs.settings({
+ allow_uncategorized_topics: true,
+ });
+
+ test("Focusing a composer which is not open with create topic", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ const composer = this.container.lookup("service:composer");
+ await composer.focusComposer({ fallbackToNewTopic: true });
+
+ await settled();
+ assert.dom(".d-editor-input").isFocused("composer is open and focused");
+ assert.strictEqual(composer.model.action, Composer.CREATE_TOPIC);
+ });
+
+ test("Focusing a composer which is not open with create topic and append text", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ const composer = this.container.lookup("service:composer");
+ await composer.focusComposer({
+ fallbackToNewTopic: true,
+ insertText: "this is appended",
+ });
+
+ await settled();
+ assert.dom(".d-editor-input").isFocused("composer is open and focused");
+ assert.dom("textarea.d-editor-input").hasValue("this is appended");
+ });
+
+ test("Focusing a composer which is already open", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+
+ const composer = this.container.lookup("service:composer");
+ await composer.focusComposer();
+
+ await settled();
+ assert.dom(".d-editor-input").isFocused("composer is open and focused");
+ });
+
+ test("Focusing a composer which is already open and append text", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+
+ const composer = this.container.lookup("service:composer");
+ await composer.focusComposer({
+ insertText: "this is some appended text",
+ });
+
+ await settled();
+ assert.dom(".d-editor-input").isFocused("composer is open and focused");
+ assert
+ .dom("textarea.d-editor-input")
+ .hasValue("this is some appended text");
+ });
+
+ test("Focusing a composer which is not open that has a draft", async function (assert) {
+ await visit("/t/this-is-a-test-topic/9");
+
+ await click(".topic-post[data-post-number='1'] button.edit");
+ await fillIn(".d-editor-input", "This is a dirty reply");
+ await click(".toggle-minimize");
+
+ const composer = this.container.lookup("service:composer");
+ await composer.focusComposer({
+ insertText: "this is some appended text",
+ });
+
+ await settled();
+ assert.dom(".d-editor-input").isFocused("composer is open and focused");
+ assert
+ .dom("textarea.d-editor-input")
+ .hasValue("This is a dirty reply\n\nthis is some appended text");
+ });
+});
- await click(".toolbar-menu__options-trigger");
+// Default Composer Category tests
+acceptance(`Composer - Default category`, function (needs) {
+ needs.user();
+ needs.settings({
+ general_category_id: 1,
+ default_composer_category: 2,
+ });
+ needs.site({
+ categories: [
+ {
+ id: 1,
+ name: "General",
+ slug: "general",
+ permission: 1,
+ topic_template: null,
+ },
+ {
+ id: 2,
+ name: "test too",
+ slug: "test-too",
+ permission: 1,
+ topic_template: null,
+ },
+ ],
+ });
+
+ test("Default category is selected over general category", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ assert.strictEqual(selectKit(".category-chooser").header().value(), "2");
+ assert.strictEqual(
+ selectKit(".category-chooser").header().name(),
+ "test too"
+ );
+ });
+});
- const row = find("[data-name='bold']");
- assert
- .dom(row)
- .hasAttribute(
- "title",
- i18n("some_title") +
- ` (${translateModKey(PLATFORM_KEY_MODIFIER + " alt b")})`,
- "shows the title with shortcut"
- );
- assert
- .dom(row)
- .hasText(
- i18n("some_label") +
- ` ${translateModKey(PLATFORM_KEY_MODIFIER + " alt b")}`,
- "shows the label with shortcut"
- );
- });
+acceptance(`Composer - Uncategorized category`, function (needs) {
+ needs.user();
+ needs.settings({
+ general_category_id: -1, // For sites that never had this seeded
+ default_composer_category: -1, // For sites that never had this seeded
+ allow_uncategorized_topics: true,
+ });
+ needs.site({
+ categories: [
+ {
+ id: 1,
+ name: "General",
+ slug: "general",
+ permission: 1,
+ topic_template: null,
+ },
+ {
+ id: 2,
+ name: "test too",
+ slug: "test-too",
+ permission: 1,
+ topic_template: null,
+ },
+ ],
+ });
+
+ test("Uncategorized category is selected", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ assert.strictEqual(selectKit(".category-chooser").header().value(), null);
+ });
+});
- test("buttons with shortcuts can have their shortcut in title conditionally hidden", async function (assert) {
- withPluginApi((api) => {
- api.onToolbarCreate((toolbar) => {
- toolbar.addButton({
- id: "smile",
- group: "extras",
- name: "smile",
- icon: "far-face-smile",
- title: "cheese",
- shortcut: "ALT+S",
- hideShortcutInTitle: true,
- });
- });
+acceptance(`Composer - default category not set`, function (needs) {
+ needs.user();
+ needs.settings({
+ default_composer_category: "",
+ });
+ needs.site({
+ categories: [
+ {
+ id: 1,
+ name: "General",
+ slug: "general",
+ permission: 1,
+ topic_template: null,
+ },
+ {
+ id: 2,
+ name: "test too",
+ slug: "test-too",
+ permission: 1,
+ topic_template: null,
+ },
+ ],
+ });
+
+ test("Nothing is selected", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ assert.strictEqual(selectKit(".category-chooser").header().value(), null);
+ assert.strictEqual(
+ selectKit(".category-chooser").header().name(),
+ "category&hellip;"
+ );
+ });
+});
+// END: Default Composer Category tests
+
+acceptance(`composer buttons API`, function (needs) {
+ needs.user();
+ needs.settings({
+ allow_uncategorized_topics: true,
+ });
+ needs.pretender((server, helper) => {
+ server.get("/drafts/topic_280.json", function () {
+ return helper.response(200, { draft: null });
+ });
+ });
+
+ test("buttons can support a shortcut", async function (assert) {
+ withPluginApi((api) => {
+ api.addComposerToolbarPopupMenuOption({
+ action: (toolbarEvent) => {
+ toolbarEvent.applySurround("**", "**");
+ },
+ shortcut: "alt+b",
+ icon: "far-bold",
+ name: "bold",
+ title: "some_title",
+ label: "some_label",
+
+ condition: () => {
+ return true;
+ },
+ });
+ });
+
+ await visit("/t/internationalization-localization/280");
+ await click(".post-controls button.reply");
+ await fillIn(".d-editor-input", "hello the world");
+
+ const editor = find(".d-editor-input");
+ editor.setSelectionRange(6, 9); // select the text input in the composer
+
+ await triggerKeyEvent(".d-editor-input", "keydown", "B", {
+ altKey: true,
+ ...metaModifier,
+ });
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue("hello **the** world", "adds the bold");
+
+ await click(".toolbar-menu__options-trigger");
+
+ const row = find("[data-name='bold']");
+ assert
+ .dom(row)
+ .hasAttribute(
+ "title",
+ i18n("some_title") +
+ ` (${translateModKey(PLATFORM_KEY_MODIFIER + " alt b")})`,
+ "shows the title with shortcut"
+ );
+ assert
+ .dom(row)
+ .hasText(
+ i18n("some_label") +
+ ` ${translateModKey(PLATFORM_KEY_MODIFIER + " alt b")}`,
+ "shows the label with shortcut"
+ );
+ });
+
+ test("buttons with shortcuts can have their shortcut in title conditionally hidden", async function (assert) {
+ withPluginApi((api) => {
+ api.onToolbarCreate((toolbar) => {
+ toolbar.addButton({
+ id: "smile",
+ group: "extras",
+ name: "smile",
+ icon: "far-face-smile",
+ title: "cheese",
+ shortcut: "ALT+S",
+ hideShortcutInTitle: true,
});
-
- await visit("/t/internationalization-localization/280");
- await click(".post-controls button.reply");
- await fillIn(".d-editor-input", "hello the world");
-
- assert
- .dom(".d-editor-button-bar .smile")
- .hasAttribute(
- "title",
- i18n("cheese"),
- "shows the title without the shortcut"
- );
});
+ });
- test("buttons can support a shortcut that triggers a custom action", async function (assert) {
- withPluginApi((api) => {
- api.onToolbarCreate((toolbar) => {
- toolbar.addButton({
- id: "smile",
- group: "extras",
- icon: "far-face-smile",
- shortcut: "ALT+S",
- shortcutAction: (toolbarEvent) => {
- toolbarEvent.addText(":smile: from keyboard");
- },
- sendAction: (event) => {
- event.addText(":smile: from click");
- },
- });
- });
- });
-
- await visit("/t/internationalization-localization/280");
- await click(".post-controls button.reply");
+ await visit("/t/internationalization-localization/280");
+ await click(".post-controls button.reply");
+ await fillIn(".d-editor-input", "hello the world");
- const editor = find(".d-editor-input");
- await triggerKeyEvent(".d-editor-input", "keydown", "S", {
- altKey: true,
- ...metaModifier,
+ assert
+ .dom(".d-editor-button-bar .smile")
+ .hasAttribute(
+ "title",
+ i18n("cheese"),
+ "shows the title without the shortcut"
+ );
+ });
+
+ test("buttons can support a shortcut that triggers a custom action", async function (assert) {
+ withPluginApi((api) => {
+ api.onToolbarCreate((toolbar) => {
+ toolbar.addButton({
+ id: "smile",
+ group: "extras",
+ icon: "far-face-smile",
+ shortcut: "ALT+S",
+ shortcutAction: (toolbarEvent) => {
+ toolbarEvent.addText(":smile: from keyboard");
+ },
+ sendAction: (event) => {
+ event.addText(":smile: from click");
+ },
});
-
- assert.dom(editor).hasValue(":smile: from keyboard");
});
-
- test("buttons with conditions should not trigger shortcut actions when condition is false", async function (assert) {
- withPluginApi((api) => {
- api.onToolbarCreate((toolbar) => {
- toolbar.addButton({
- id: "smile",
- group: "extras",
- icon: "far-face-smile",
- shortcut: "ALT+S",
- shortcutAction: (toolbarEvent) => {
- toolbarEvent.addText(":smile: from keyboard");
- },
- condition: () => false,
- });
- });
- });
-
- await visit("/t/internationalization-localization/280");
- await click(".post-controls button.reply");
-
- const editor = find(".d-editor-input");
- await triggerKeyEvent(".d-editor-input", "keydown", "S", {
- altKey: true,
- ...metaModifier,
+ });
+
+ await visit("/t/internationalization-localization/280");
+ await click(".post-controls button.reply");
+
+ const editor = find(".d-editor-input");
+ await triggerKeyEvent(".d-editor-input", "keydown", "S", {
+ altKey: true,
+ ...metaModifier,
+ });
+
+ assert.dom(editor).hasValue(":smile: from keyboard");
+ });
+
+ test("buttons with conditions should not trigger shortcut actions when condition is false", async function (assert) {
+ withPluginApi((api) => {
+ api.onToolbarCreate((toolbar) => {
+ toolbar.addButton({
+ id: "smile",
+ group: "extras",
+ icon: "far-face-smile",
+ shortcut: "ALT+S",
+ shortcutAction: (toolbarEvent) => {
+ toolbarEvent.addText(":smile: from keyboard");
+ },
+ condition: () => false,
});
-
- assert.dom(editor).hasValue("");
});
-
- test("buttons with conditions should trigger shortcut actions when condition is true", async function (assert) {
- withPluginApi((api) => {
- api.onToolbarCreate((toolbar) => {
- toolbar.addButton({
- id: "smile",
- group: "extras",
- icon: "far-face-smile",
- shortcut: "ALT+S",
- shortcutAction: (toolbarEvent) => {
- toolbarEvent.addText(":smile: from keyboard");
- },
- condition: () => true,
- });
- });
- });
-
- await visit("/t/internationalization-localization/280");
- await click(".post-controls button.reply");
-
- const editor = find(".d-editor-input");
- await triggerKeyEvent(".d-editor-input", "keydown", "S", {
- altKey: true,
- ...metaModifier,
+ });
+
+ await visit("/t/internationalization-localization/280");
+ await click(".post-controls button.reply");
+
+ const editor = find(".d-editor-input");
+ await triggerKeyEvent(".d-editor-input", "keydown", "S", {
+ altKey: true,
+ ...metaModifier,
+ });
+
+ assert.dom(editor).hasValue("");
+ });
+
+ test("buttons with conditions should trigger shortcut actions when condition is true", async function (assert) {
+ withPluginApi((api) => {
+ api.onToolbarCreate((toolbar) => {
+ toolbar.addButton({
+ id: "smile",
+ group: "extras",
+ icon: "far-face-smile",
+ shortcut: "ALT+S",
+ shortcutAction: (toolbarEvent) => {
+ toolbarEvent.addText(":smile: from keyboard");
+ },
+ condition: () => true,
});
-
- assert.dom(editor).hasValue(":smile: from keyboard");
});
+ });
- test("buttons can be added conditionally", async function (assert) {
- withPluginApi((api) => {
- api.addComposerToolbarPopupMenuOption({
- action: (toolbarEvent) => {
- toolbarEvent.applySurround("**", "**");
- },
- icon: "far-bold",
- label: "some_label",
- condition: (composer) => {
- return composer.model.creatingTopic;
- },
- });
- });
+ await visit("/t/internationalization-localization/280");
+ await click(".post-controls button.reply");
- await visit("/t/internationalization-localization/280");
+ const editor = find(".d-editor-input");
+ await triggerKeyEvent(".d-editor-input", "keydown", "S", {
+ altKey: true,
+ ...metaModifier,
+ });
- await click(".post-controls button.reply");
- assert.dom(".d-editor-input").exists("the composer input is visible");
+ assert.dom(editor).hasValue(":smile: from keyboard");
+ });
- const expectedName = "[en.some_label]";
- await click(".toolbar-menu__options-trigger");
+ test("buttons can be added conditionally", async function (assert) {
+ withPluginApi((api) => {
+ api.addComposerToolbarPopupMenuOption({
+ action: (toolbarEvent) => {
+ toolbarEvent.applySurround("**", "**");
+ },
+ icon: "far-bold",
+ label: "some_label",
+ condition: (composer) => {
+ return composer.model.creatingTopic;
+ },
+ });
+ });
- assert
- .dom(`button[title="${expectedName}"]`)
- .doesNotExist("custom button is not displayed for reply");
+ await visit("/t/internationalization-localization/280");
- await click(".toolbar-menu__options-trigger");
+ await click(".post-controls button.reply");
+ assert.dom(".d-editor-input").exists("the composer input is visible");
- await visit("/latest");
- await click("#create-topic");
+ const expectedName = "[en.some_label]";
+ await click(".toolbar-menu__options-trigger");
- await click(".toolbar-menu__options-trigger");
+ assert
+ .dom(`button[title="${expectedName}"]`)
+ .doesNotExist("custom button is not displayed for reply");
- assert
- .dom(`button[title="${expectedName}"]`)
- .exists("custom button is displayed for new topic");
- });
+ await click(".toolbar-menu__options-trigger");
- test("modified name when replying to a post", async function (assert) {
- withPluginApi((api) => {
- api.registerValueTransformer(
- "composer-reply-options-user-link-name",
- () => {
- return "NewNameHere";
- }
- );
- });
+ await visit("/latest");
+ await click("#create-topic");
- await visit("/t/34");
- await click("article#post_3 button.reply");
+ await click(".toolbar-menu__options-trigger");
- assert.dom(".reply-details .user-link").hasText("NewNameHere");
- });
+ assert
+ .dom(`button[title="${expectedName}"]`)
+ .exists("custom button is displayed for new topic");
+ });
- test("modified avatar when replying to a post", async function (assert) {
- withPluginApi((api) => {
- api.registerValueTransformer(
- "composer-reply-options-user-avatar-template",
- () => {
- return "/images/avatar.png?size={size}";
- }
- );
- });
+ test("modified name when replying to a post", async function (assert) {
+ withPluginApi((api) => {
+ api.registerValueTransformer(
+ "composer-reply-options-user-link-name",
+ () => {
+ return "NewNameHere";
+ }
+ );
+ });
- await visit("/t/34");
- await click("article#post_3 button.reply");
+ await visit("/t/34");
+ await click("article#post_3 button.reply");
- assert
- .dom(".reply-details .action-title img")
- .hasAttribute(
- "src",
- /\/images\/avatar\.png/,
- "Reply avatar can be customized"
- );
- });
+ assert.dom(".reply-details .user-link").hasText("NewNameHere");
+ });
- test("modified avatar in quote", async function (assert) {
- withPluginApi((api) => {
- api.registerValueTransformer(
- "composer-editor-quoted-post-avatar-template",
- () => {
- return "/images/custom-quote-avatar.png?size={size}";
- }
- );
- });
+ test("modified avatar when replying to a post", async function (assert) {
+ withPluginApi((api) => {
+ api.registerValueTransformer(
+ "composer-reply-options-user-avatar-template",
+ () => {
+ return "/images/avatar.png?size={size}";
+ }
+ );
+ });
- await visit("/t/34");
- await click("article#post_3 button.reply");
- await fillIn(
- ".d-editor-input",
- '[quote="charlie, post:1, topic:34"]\noriginal post content\n[/quote]'
- );
+ await visit("/t/34");
+ await click("article#post_3 button.reply");
- assert
- .dom(".d-editor-preview .quote .title img")
- .hasAttribute(
- "src",
- /\/images\/custom-quote-avatar\.png/,
- "Quote avatar can be customized"
- );
- });
- }
- );
+ assert
+ .dom(".reply-details .action-title img")
+ .hasAttribute(
+ "src",
+ /\/images\/avatar\.png/,
+ "Reply avatar can be customized"
+ );
+ });
+
+ test("modified avatar in quote", async function (assert) {
+ withPluginApi((api) => {
+ api.registerValueTransformer(
+ "composer-editor-quoted-post-avatar-template",
+ () => {
+ return "/images/custom-quote-avatar.png?size={size}";
+ }
+ );
+ });
+
+ await visit("/t/34");
+ await click("article#post_3 button.reply");
+ await fillIn(
+ ".d-editor-input",
+ '[quote="charlie, post:1, topic:34"]\noriginal post content\n[/quote]'
+ );
+
+ assert
+ .dom(".d-editor-preview .quote .title img")
+ .hasAttribute(
+ "src",
+ /\/images\/custom-quote-avatar\.png/,
+ "Quote avatar can be customized"
+ );
+ });
});
diff --git a/frontend/discourse/tests/acceptance/flag-post-test.js b/frontend/discourse/tests/acceptance/flag-post-test.js
index 0ab3c659f6d..448aebb0878 100644
--- a/frontend/discourse/tests/acceptance/flag-post-test.js
+++ b/frontend/discourse/tests/acceptance/flag-post-test.js
@@ -25,206 +25,194 @@ async function pressEnter(selector, modifier) {
});
}
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `flagging (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
+acceptance(`flagging`, function (needs) {
+ needs.user({ admin: true });
+ needs.pretender((server, helper) => {
+ server.get("/u/uwe_keim.json", () => {
+ return helper.response(userFixtures["/u/charlie.json"]);
+ });
+ server.get("/admin/users/255.json", () => {
+ return helper.response({
+ id: 255,
+ automatic: false,
+ name: "admin",
+ username: "admin",
+ user_count: 0,
+ alias_level: 99,
+ visible: true,
+ automatic_membership_email_domains: "",
+ primary_group: false,
+ title: null,
+ grant_trust_level: null,
+ has_messages: false,
+ flair_url: null,
+ flair_bg_color: null,
+ flair_color: null,
+ bio_raw: null,
+ bio_cooked: null,
+ public_admission: false,
+ allow_membership_requests: true,
+ membership_request_template: "Please add me",
+ can_be_deleted: true,
+ can_delete_all_posts: true,
});
- needs.user({ admin: true });
- needs.pretender((server, helper) => {
- server.get("/u/uwe_keim.json", () => {
- return helper.response(userFixtures["/u/charlie.json"]);
- });
- server.get("/admin/users/255.json", () => {
- return helper.response({
- id: 255,
- automatic: false,
- name: "admin",
- username: "admin",
- user_count: 0,
- alias_level: 99,
- visible: true,
- automatic_membership_email_domains: "",
- primary_group: false,
- title: null,
- grant_trust_level: null,
- has_messages: false,
- flair_url: null,
- flair_bg_color: null,
- flair_color: null,
- bio_raw: null,
- bio_cooked: null,
- public_admission: false,
- allow_membership_requests: true,
- membership_request_template: "Please add me",
- can_be_deleted: true,
- can_delete_all_posts: true,
- });
- });
- server.get("/admin/users/5.json", () => {
- return helper.response({
- id: 5,
- automatic: false,
- name: "user",
- username: "user",
- user_count: 0,
- alias_level: 99,
- visible: true,
- automatic_membership_email_domains: "",
- primary_group: false,
- title: null,
- grant_trust_level: null,
- has_messages: false,
- flair_url: null,
- flair_bg_color: null,
- flair_color: null,
- bio_raw: null,
- bio_cooked: null,
- public_admission: false,
- allow_membership_requests: true,
- membership_request_template: "Please add me",
- full_name: null,
- });
- });
- server.put("/admin/users/5/silence", () => {
- return helper.response({
- silence: {
- silence_reason: "spamming",
- silenced_at: "",
- silenced_till: "",
- silenced_by: "",
- },
- });
- });
- server.post("/post_actions", () => {
- return helper.response({
- response: true,
- });
- });
+ });
+ server.get("/admin/users/5.json", () => {
+ return helper.response({
+ id: 5,
+ automatic: false,
+ name: "user",
+ username: "user",
+ user_count: 0,
+ alias_level: 99,
+ visible: true,
+ automatic_membership_email_domains: "",
+ primary_group: false,
+ title: null,
+ grant_trust_level: null,
+ has_messages: false,
+ flair_url: null,
+ flair_bg_color: null,
+ flair_color: null,
+ bio_raw: null,
+ bio_cooked: null,
+ public_admission: false,
+ allow_membership_requests: true,
+ membership_request_template: "Please add me",
+ full_name: null,
});
-
- test("Flag modal opening", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- assert.dom(".flag-modal-body").exists("shows the flag modal");
+ });
+ server.put("/admin/users/5/silence", () => {
+ return helper.response({
+ silence: {
+ silence_reason: "spamming",
+ silenced_at: "",
+ silenced_till: "",
+ silenced_by: "",
+ },
});
-
- test("Flag take action dropdown exists", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- await click("#radio_inappropriate");
- await selectKit(".reviewable-action-dropdown").expand();
- assert
- .dom("[data-value='agree_and_silence']")
- .exists("it shows the silence action option");
- assert
- .dom("[data-value='agree_and_suspend']")
- .exists("it shows the suspend action option");
- assert
- .dom("[data-value='agree_and_hide']")
- .exists("it shows the hide action option");
+ });
+ server.post("/post_actions", () => {
+ return helper.response({
+ response: true,
});
+ });
+ });
- test("Can silence from take action", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- await click("#radio_inappropriate");
- await selectKit(".reviewable-action-dropdown").expand();
- await click("[data-value='agree_and_silence']");
- assert.dom(".silence-user-modal").exists("shows the silence modal");
- assert.dom(".suspend-message").hasValue("", "penalty message is empty");
- const silenceUntilCombobox = selectKit(".silence-until .combobox");
- await silenceUntilCombobox.expand();
- await silenceUntilCombobox.selectRowByValue("tomorrow");
- assert.dom(".d-modal__body").exists();
- await fillIn("input.silence-reason", "for breaking the rules");
-
- await click(".perform-penalize");
- assert.dom(".d-modal__body").doesNotExist();
- });
+ test("Flag modal opening", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ assert.dom(".flag-modal-body").exists("shows the flag modal");
+ });
- test("Message appears in penalty modal", async function (assert) {
- this.siteSettings.penalty_include_post_message = true;
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- await click("#radio_inappropriate");
- await selectKit(".reviewable-action-dropdown").expand();
- await click("[data-value='agree_and_silence']");
- assert.dom(".silence-user-modal").exists("shows the silence modal");
- assert
- .dom(".suspend-message")
- .hasValue(
- "-------------------\n<p>Any plans to support localization of UI elements, so that I (for example) could set up a completely German speaking forum?</p>\n-------------------",
- "penalty message is prefilled with post text"
- );
- });
+ test("Flag take action dropdown exists", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ await click("#radio_inappropriate");
+ await selectKit(".reviewable-action-dropdown").expand();
+ assert
+ .dom("[data-value='agree_and_silence']")
+ .exists("it shows the silence action option");
+ assert
+ .dom("[data-value='agree_and_suspend']")
+ .exists("it shows the suspend action option");
+ assert
+ .dom("[data-value='agree_and_hide']")
+ .exists("it shows the hide action option");
+ });
- test("Can delete spammer from spam", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- await click("#radio_spam");
+ test("Can silence from take action", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ await click("#radio_inappropriate");
+ await selectKit(".reviewable-action-dropdown").expand();
+ await click("[data-value='agree_and_silence']");
+ assert.dom(".silence-user-modal").exists("shows the silence modal");
+ assert.dom(".suspend-message").hasValue("", "penalty message is empty");
+ const silenceUntilCombobox = selectKit(".silence-until .combobox");
+ await silenceUntilCombobox.expand();
+ await silenceUntilCombobox.selectRowByValue("tomorrow");
+ assert.dom(".d-modal__body").exists();
+ await fillIn("input.silence-reason", "for breaking the rules");
+
+ await click(".perform-penalize");
+ assert.dom(".d-modal__body").doesNotExist();
+ });
- assert.dom(".delete-spammer").exists();
- });
+ test("Message appears in penalty modal", async function (assert) {
+ this.siteSettings.penalty_include_post_message = true;
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ await click("#radio_inappropriate");
+ await selectKit(".reviewable-action-dropdown").expand();
+ await click("[data-value='agree_and_silence']");
+ assert.dom(".silence-user-modal").exists("shows the silence modal");
+ assert
+ .dom(".suspend-message")
+ .hasValue(
+ "-------------------\n<p>Any plans to support localization of UI elements, so that I (for example) could set up a completely German speaking forum?</p>\n-------------------",
+ "penalty message is prefilled with post text"
+ );
+ });
- test("Gets dismissable warning from canceling incomplete silence from take action", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
- await click("#radio_inappropriate");
- await selectKit(".reviewable-action-dropdown").expand();
- await click("[data-value='agree_and_silence']");
-
- const silenceUntilCombobox = selectKit(".silence-until .combobox");
- await silenceUntilCombobox.expand();
- await silenceUntilCombobox.selectRowByValue("tomorrow");
- await fillIn("input.silence-reason", "for breaking the rules");
- await click(".d-modal-cancel");
- assert.dom(".dialog-body").exists();
-
- await click(".dialog-footer .btn-default");
- assert.dom(".dialog-body").doesNotExist();
- assert.dom(".silence-user-modal").exists("shows the silence modal");
-
- await click(".d-modal-cancel");
- assert.dom(".dialog-body").exists();
-
- await click(".dialog-footer .btn-primary");
- assert.dom(".dialog-body").doesNotExist();
- });
+ test("Can delete spammer from spam", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ await click("#radio_spam");
- test("CTRL + ENTER accepts the modal", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
+ assert.dom(".delete-spammer").exists();
+ });
- await pressEnter(".d-modal", "ctrlKey");
- assert
- .dom(".d-modal")
- .exists(
- "The modal wasn't closed because the accept button was disabled"
- );
+ test("Gets dismissable warning from canceling incomplete silence from take action", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+ await click("#radio_inappropriate");
+ await selectKit(".reviewable-action-dropdown").expand();
+ await click("[data-value='agree_and_silence']");
+
+ const silenceUntilCombobox = selectKit(".silence-until .combobox");
+ await silenceUntilCombobox.expand();
+ await silenceUntilCombobox.selectRowByValue("tomorrow");
+ await fillIn("input.silence-reason", "for breaking the rules");
+ await click(".d-modal-cancel");
+ assert.dom(".dialog-body").exists();
+
+ await click(".dialog-footer .btn-default");
+ assert.dom(".dialog-body").doesNotExist();
+ assert.dom(".silence-user-modal").exists("shows the silence modal");
+
+ await click(".d-modal-cancel");
+ assert.dom(".dialog-body").exists();
+
+ await click(".dialog-footer .btn-primary");
+ assert.dom(".dialog-body").doesNotExist();
+ });
- await click("#radio_inappropriate"); // this enables the accept button
- await pressEnter(".d-modal", "ctrlKey");
- assert.dom(".d-modal").doesNotExist("The modal was closed");
- });
+ test("CTRL + ENTER accepts the modal", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
- test("CMD or WINDOWS-KEY + ENTER accepts the modal", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await openFlagModal();
+ await pressEnter(".d-modal", "ctrlKey");
+ assert
+ .dom(".d-modal")
+ .exists("The modal wasn't closed because the accept button was disabled");
- await pressEnter(".d-modal", "metaKey");
- assert
- .dom(".d-modal")
- .exists(
- "The modal wasn't closed because the accept button was disabled"
- );
+ await click("#radio_inappropriate"); // this enables the accept button
+ await pressEnter(".d-modal", "ctrlKey");
+ assert.dom(".d-modal").doesNotExist("The modal was closed");
+ });
- await click("#radio_inappropriate"); // this enables the accept button
- await pressEnter(".d-modal", "ctrlKey");
- assert.dom(".d-modal").doesNotExist("The modal was closed");
- });
- }
- );
+ test("CMD or WINDOWS-KEY + ENTER accepts the modal", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await openFlagModal();
+
+ await pressEnter(".d-modal", "metaKey");
+ assert
+ .dom(".d-modal")
+ .exists("The modal wasn't closed because the accept button was disabled");
+
+ await click("#radio_inappropriate"); // this enables the accept button
+ await pressEnter(".d-modal", "ctrlKey");
+ assert.dom(".d-modal").doesNotExist("The modal was closed");
+ });
});
diff --git a/frontend/discourse/tests/acceptance/page-publishing-test.js b/frontend/discourse/tests/acceptance/page-publishing-test.js
index dc61a984a68..5e07e47aeb9 100644
--- a/frontend/discourse/tests/acceptance/page-publishing-test.js
+++ b/frontend/discourse/tests/acceptance/page-publishing-test.js
@@ -2,55 +2,44 @@ import { click, fillIn, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Page Publishing (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
-
- needs.user();
- needs.pretender((server, helper) => {
- const validSlug = helper.response({ valid_slug: true });
+acceptance(`Page Publishing`, function (needs) {
+ needs.user();
+ needs.pretender((server, helper) => {
+ const validSlug = helper.response({ valid_slug: true });
- server.put("/pub/by-topic/280", () => {
- return helper.response({});
- });
- server.get("/pub/by-topic/280", () => {
- return helper.response({});
- });
- server.get("/pub/check-slug", (req) => {
- if (req.queryParams.slug === "internationalization-localization") {
- return validSlug;
- }
- return helper.response({
- valid_slug: false,
- reason: "i don't need a reason",
- });
- });
+ server.put("/pub/by-topic/280", () => {
+ return helper.response({});
+ });
+ server.get("/pub/by-topic/280", () => {
+ return helper.response({});
+ });
+ server.get("/pub/check-slug", (req) => {
+ if (req.queryParams.slug === "internationalization-localization") {
+ return validSlug;
+ }
+ return helper.response({
+ valid_slug: false,
+ reason: "i don't need a reason",
});
+ });
+ });
- test("can publish a page via modal", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(
- ".topic-post[data-post-number='1'] button.show-more-actions"
- );
- await click(
- ".topic-post[data-post-number='1'] button.show-post-admin-menu"
- );
- await click(".publish-page");
+ test("can publish a page via modal", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.show-more-actions");
+ await click(
+ ".topic-post[data-post-number='1'] button.show-post-admin-menu"
+ );
+ await click(".publish-page");
- await fillIn(".publish-slug", "bad-slug");
- assert.dom(".valid-slug").doesNotExist();
- assert.dom(".invalid-slug").exists();
- await fillIn(".publish-slug", "internationalization-localization");
- assert.dom(".valid-slug").exists();
- assert.dom(".invalid-slug").doesNotExist();
+ await fillIn(".publish-slug", "bad-slug");
+ assert.dom(".valid-slug").doesNotExist();
+ assert.dom(".invalid-slug").exists();
+ await fillIn(".publish-slug", "internationalization-localization");
+ assert.dom(".valid-slug").exists();
+ assert.dom(".invalid-slug").doesNotExist();
- await click(".publish-page");
- assert.dom(".current-url").exists();
- });
- }
- );
+ await click(".publish-page");
+ assert.dom(".current-url").exists();
+ });
});
diff --git a/frontend/discourse/tests/acceptance/post-inline-mentions-test.js b/frontend/discourse/tests/acceptance/post-inline-mentions-test.js
index c3ca5b1b35a..0ce58143c4d 100644
--- a/frontend/discourse/tests/acceptance/post-inline-mentions-test.js
+++ b/frontend/discourse/tests/acceptance/post-inline-mentions-test.js
@@ -30,245 +30,217 @@ function topicWithUserStatus(topicId, mentionedUserId, status) {
return topic;
}
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Post inline mentions (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- enable_user_status: true,
- });
-
- const topicId = 130;
- const mentionedUserId = 1;
- const status = {
- description: "Surfing",
- emoji: "surfing_man",
- ends_at: null,
- };
-
- test("shows user status on inline mentions", async function (assert) {
- pretender.get(`/t/${topicId}.json`, () => {
- return response(
- topicWithUserStatus(topicId, mentionedUserId, status)
- );
- });
-
- await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
-
- assert
- .dom(".topic-post .cooked .mention .user-status-message")
- .exists("user status is shown");
- assert
- .dom(".topic-post .cooked .mention .user-status-message img")
- .hasAttribute("src", /surfing_man/, "status emoji is correct");
- });
-
- test("do not show status in inline mentions if the user status is empty ", async function (assert) {
- pretender.get(`/t/${topicId}.json`, () => {
- return response(topicWithUserStatus(topicId, mentionedUserId));
- });
-
- await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
-
- assert
- .dom(".topic-post .cooked .mention .user-status-message-wrapper")
- .doesNotExist("the wrapper is not present in the DOM");
-
- assert
- .dom(".topic-post .cooked .mention .user-status-message")
- .doesNotExist("the user status is not shown");
- });
-
- test("inserts user status on message bus message", async function (assert) {
- pretender.get(`/t/${topicId}.json`, () => {
- return response(topicWithoutUserStatus(topicId, mentionedUserId));
- });
- await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
-
- assert
- .dom(".topic-post .cooked .mention .user-status-message")
- .doesNotExist("user status isn't shown");
-
- await publishToMessageBus("/user-status", {
- [mentionedUserId]: {
- description: status.description,
- emoji: status.emoji,
- },
- });
-
- assert
- .dom(".topic-post .cooked .mention .user-status-message")
- .exists("user status is shown");
- assert
- .dom(".topic-post .cooked .mention .user-status-message img")
- .hasAttribute("src", /surfing_man/, "status emoji is correct");
- });
-
- test("updates user status on message bus message", async function (assert) {
- pretender.get(`/t/${topicId}.json`, () => {
- return response(
- topicWithUserStatus(topicId, mentionedUserId, status)
- );
- });
- await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
-
- assert
- .dom(".topic-post .cooked .mention .user-status-message")
- .exists("initial user status is shown");
-
- const newStatus = {
- description: "off to dentist",
- emoji: "tooth",
- };
- await publishToMessageBus("/user-status", {
- [mentionedUserId]: {
- description: newStatus.description,
- emoji: newStatus.emoji,
- },
- });
-
- assert
- .dom(".topic-post .cooked .mention .user-status-message")
- .exists("updated user status is shown");
- assert
- .dom(".topic-post .cooked .mention .user-status-message img")
- .hasAttribute("src", /tooth/, "updated status emoji is correct");
- });
-
- test("removes user status on message bus message", async function (assert) {
- pretender.get(`/t/${topicId}.json`, () => {
- return response(
- topicWithUserStatus(topicId, mentionedUserId, status)
- );
- });
- await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
-
- // TODO (glimmer-post-stream-mode) remove the `if` surrounding the assertion when removing the legacy code
- if (this.siteSettings.glimmer_post_stream_mode === "enabled") {
- assert
- .dom(".topic-post .cooked .mention .user-status-message-wrapper")
- .exists("the wrapper is present in the DOM");
- }
- assert
- .dom(".topic-post .cooked .mention .user-status-message")
- .exists("initial user status is shown");
-
- await publishToMessageBus("/user-status", {
- [mentionedUserId]: null,
- });
-
- // TODO (glimmer-post-stream-mode) remove the `if` surrounding the assertion when removing the legacy code
- if (this.siteSettings.glimmer_post_stream_mode === "enabled") {
- assert
- .dom(".topic-post .cooked .mention .user-status-message-wrapper")
- .doesNotExist("the wrapper was removed from the DOM");
- }
- assert
- .dom(".topic-post .cooked .mention .user-status-message")
- .doesNotExist("updated user has disappeared");
- });
- }
- );
-
- acceptance(
- `Post inline mentions – user status tooltip (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- enable_user_status: true,
- });
-
- const topicId = 130;
- const mentionedUserId = 1;
- const status = {
- description: "Surfing",
- emoji: "surfing_man",
- ends_at: null,
- };
-
- async function mouseMove(selector) {
- await triggerEvent(selector, "pointermove");
- }
-
- test("shows user status tooltip", async function (assert) {
- pretender.get(`/t/${topicId}.json`, () => {
- return response(
- topicWithUserStatus(topicId, mentionedUserId, status)
- );
- });
-
- await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
- assert
- .dom(".topic-post .cooked .mention .user-status-message")
- .exists("user status is shown");
-
- await mouseMove(".topic-post .cooked .mention .user-status-message");
-
- assert
- .dom(".user-status-message-tooltip-content")
- .exists("status tooltip is shown");
- assert.true(
- document
- .querySelector(".user-status-message-tooltip-content img")
- .src.includes(status.emoji),
- "emoji is correct"
- );
- assert
- .dom(".user-status-tooltip-description")
- .hasText(status.description, "status description is correct");
- });
- }
- );
-
- acceptance(
- `Post inline mentions as an anonymous user (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- enable_user_status: true,
- });
+acceptance(`Post inline mentions`, function (needs) {
+ needs.user();
+ needs.settings({
+ enable_user_status: true,
+ });
+
+ const topicId = 130;
+ const mentionedUserId = 1;
+ const status = {
+ description: "Surfing",
+ emoji: "surfing_man",
+ ends_at: null,
+ };
+
+ test("shows user status on inline mentions", async function (assert) {
+ pretender.get(`/t/${topicId}.json`, () => {
+ return response(topicWithUserStatus(topicId, mentionedUserId, status));
+ });
+
+ await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
+
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message")
+ .exists("user status is shown");
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message img")
+ .hasAttribute("src", /surfing_man/, "status emoji is correct");
+ });
+
+ test("do not show status in inline mentions if the user status is empty ", async function (assert) {
+ pretender.get(`/t/${topicId}.json`, () => {
+ return response(topicWithUserStatus(topicId, mentionedUserId));
+ });
+
+ await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
+
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message-wrapper")
+ .doesNotExist("the wrapper is not present in the DOM");
+
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message")
+ .doesNotExist("the user status is not shown");
+ });
+
+ test("inserts user status on message bus message", async function (assert) {
+ pretender.get(`/t/${topicId}.json`, () => {
+ return response(topicWithoutUserStatus(topicId, mentionedUserId));
+ });
+ await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
+
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message")
+ .doesNotExist("user status isn't shown");
+
+ await publishToMessageBus("/user-status", {
+ [mentionedUserId]: {
+ description: status.description,
+ emoji: status.emoji,
+ },
+ });
+
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message")
+ .exists("user status is shown");
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message img")
+ .hasAttribute("src", /surfing_man/, "status emoji is correct");
+ });
+
+ test("updates user status on message bus message", async function (assert) {
+ pretender.get(`/t/${topicId}.json`, () => {
+ return response(topicWithUserStatus(topicId, mentionedUserId, status));
+ });
+ await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
+
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message")
+ .exists("initial user status is shown");
+
+ const newStatus = {
+ description: "off to dentist",
+ emoji: "tooth",
+ };
+ await publishToMessageBus("/user-status", {
+ [mentionedUserId]: {
+ description: newStatus.description,
+ emoji: newStatus.emoji,
+ },
+ });
+
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message")
+ .exists("updated user status is shown");
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message img")
+ .hasAttribute("src", /tooth/, "updated status emoji is correct");
+ });
+
+ test("removes user status on message bus message", async function (assert) {
+ pretender.get(`/t/${topicId}.json`, () => {
+ return response(topicWithUserStatus(topicId, mentionedUserId, status));
+ });
+ await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
+
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message-wrapper")
+ .exists("the wrapper is present in the DOM");
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message")
+ .exists("initial user status is shown");
+
+ await publishToMessageBus("/user-status", {
+ [mentionedUserId]: null,
+ });
+
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message-wrapper")
+ .doesNotExist("the wrapper was removed from the DOM");
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message")
+ .doesNotExist("updated user has disappeared");
+ });
+});
- const topicId = 130;
- const mentionedUserId = 1;
- const status = {
- description: "Surfing",
- emoji: "surfing_man",
- ends_at: null,
- };
-
- test("an anonymous user can see user status on mentions", async function (assert) {
- pretender.get(`/t/${topicId}.json`, () => {
- const topic = topicWithUserStatus(topicId, mentionedUserId, status);
- return response(topic);
- });
- await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
-
- assert
- .dom(".topic-post .cooked .mention .user-status-message")
- .exists("user status is shown");
- });
+acceptance(`Post inline mentions – user status tooltip`, function (needs) {
+ needs.user();
+ needs.settings({
+ enable_user_status: true,
+ });
+
+ const topicId = 130;
+ const mentionedUserId = 1;
+ const status = {
+ description: "Surfing",
+ emoji: "surfing_man",
+ ends_at: null,
+ };
+
+ async function mouseMove(selector) {
+ await triggerEvent(selector, "pointermove");
+ }
+
+ test("shows user status tooltip", async function (assert) {
+ pretender.get(`/t/${topicId}.json`, () => {
+ return response(topicWithUserStatus(topicId, mentionedUserId, status));
+ });
+
+ await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message")
+ .exists("user status is shown");
+
+ await mouseMove(".topic-post .cooked .mention .user-status-message");
+
+ assert
+ .dom(".user-status-message-tooltip-content")
+ .exists("status tooltip is shown");
+ assert.true(
+ document
+ .querySelector(".user-status-message-tooltip-content img")
+ .src.includes(status.emoji),
+ "emoji is correct"
+ );
+ assert
+ .dom(".user-status-tooltip-description")
+ .hasText(status.description, "status description is correct");
+ });
+});
- test("an anonymous user can see user status with an end date on mentions", async function (assert) {
- pretender.get(`/t/${topicId}.json`, () => {
- const statusWithEndDate = Object.assign(status, {
- ends_at: "2100-02-01T09:00:00.000Z",
- });
- const topic = topicWithUserStatus(
- topicId,
- mentionedUserId,
- statusWithEndDate
- );
- return response(topic);
- });
- await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
-
- assert
- .dom(".topic-post .cooked .mention .user-status-message")
- .exists("user status is shown");
+acceptance(`Post inline mentions as an anonymous user`, function (needs) {
+ needs.settings({
+ enable_user_status: true,
+ });
+
+ const topicId = 130;
+ const mentionedUserId = 1;
+ const status = {
+ description: "Surfing",
+ emoji: "surfing_man",
+ ends_at: null,
+ };
+
+ test("an anonymous user can see user status on mentions", async function (assert) {
+ pretender.get(`/t/${topicId}.json`, () => {
+ const topic = topicWithUserStatus(topicId, mentionedUserId, status);
+ return response(topic);
+ });
+ await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
+
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message")
+ .exists("user status is shown");
+ });
+
+ test("an anonymous user can see user status with an end date on mentions", async function (assert) {
+ pretender.get(`/t/${topicId}.json`, () => {
+ const statusWithEndDate = Object.assign(status, {
+ ends_at: "2100-02-01T09:00:00.000Z",
});
- }
- );
+ const topic = topicWithUserStatus(
+ topicId,
+ mentionedUserId,
+ statusWithEndDate
+ );
+ return response(topic);
+ });
+ await visit(`/t/lorem-ipsum-dolor-sit-amet/${topicId}`);
+
+ assert
+ .dom(".topic-post .cooked .mention .user-status-message")
+ .exists("user status is shown");
+ });
});
diff --git a/frontend/discourse/tests/acceptance/post-stream-test.gjs b/frontend/discourse/tests/acceptance/post-stream-test.gjs
index f81e7576e24..50958fca49d 100644
--- a/frontend/discourse/tests/acceptance/post-stream-test.gjs
+++ b/frontend/discourse/tests/acceptance/post-stream-test.gjs
@@ -7,7 +7,6 @@ acceptance("Post-Stream | @topicPageQueryParams reactivity", function (needs) {
needs.user();
needs.settings({
enable_filtered_replies_view: true,
- glimmer_post_stream_mode: "enabled",
});
needs.hooks.beforeEach(function () {
diff --git a/frontend/discourse/tests/acceptance/post-table-wrapper-test.js b/frontend/discourse/tests/acceptance/post-table-wrapper-test.js
index f32d6d7e0c8..f993b5a8d1d 100644
--- a/frontend/discourse/tests/acceptance/post-table-wrapper-test.js
+++ b/frontend/discourse/tests/acceptance/post-table-wrapper-test.js
@@ -2,61 +2,55 @@ import { click, find, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Post Table Wrapper Test (glimmer_post_stream_mode = ${postStreamMode})`,
-
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
-
- test("fullscreen table wrapper appears on post with large table", async function (assert) {
- await visit("/t/54081");
- const postWithLargeTable =
- ".post-stream .topic-post[data-post-number='1']";
- assert
- .dom(`${postWithLargeTable} .fullscreen-table-wrapper`)
- .exists("The wrapper is present on the post with the large table");
-
- assert
- .dom(
- `${postWithLargeTable} .fullscreen-table-wrapper .fullscreen-table-wrapper__buttons .open-popup-link`
- )
- .exists("buttons for the table wrapper appear inside a separate div");
-
- const fullscreenButtonWrapper = find(
- `${postWithLargeTable} .fullscreen-table-wrapper .fullscreen-table-wrapper__buttons`
- );
-
- assert.strictEqual(
- window
- .getComputedStyle(fullscreenButtonWrapper)
- .getPropertyValue("position"),
- "absolute",
- "the wrapper buttons should not be in the cooked post's flow"
- );
-
- await click(
- `${postWithLargeTable} .fullscreen-table-wrapper .btn-expand-table`
- );
-
- assert
- .dom(".fullscreen-table-modal")
- .exists("The fullscreen table modal appears");
- assert
- .dom(".fullscreen-table-modal table")
- .exists("The table is present inside the modal");
-
- await click(".fullscreen-table-modal .modal-close");
- await click(
- `${postWithLargeTable} .fullscreen-table-wrapper .btn-expand-table svg`
- );
-
- assert
- .dom(".fullscreen-table-modal")
- .exists("Fullscreen table modal appears on clicking svg icon");
- });
- }
- );
-});
+acceptance(
+ `Post Table Wrapper Test`,
+
+ function () {
+ test("fullscreen table wrapper appears on post with large table", async function (assert) {
+ await visit("/t/54081");
+ const postWithLargeTable =
+ ".post-stream .topic-post[data-post-number='1']";
+ assert
+ .dom(`${postWithLargeTable} .fullscreen-table-wrapper`)
+ .exists("The wrapper is present on the post with the large table");
+
+ assert
+ .dom(
+ `${postWithLargeTable} .fullscreen-table-wrapper .fullscreen-table-wrapper__buttons .open-popup-link`
+ )
+ .exists("buttons for the table wrapper appear inside a separate div");
+
+ const fullscreenButtonWrapper = find(
+ `${postWithLargeTable} .fullscreen-table-wrapper .fullscreen-table-wrapper__buttons`
+ );
+
+ assert.strictEqual(
+ window
+ .getComputedStyle(fullscreenButtonWrapper)
+ .getPropertyValue("position"),
+ "absolute",
+ "the wrapper buttons should not be in the cooked post's flow"
+ );
+
+ await click(
+ `${postWithLargeTable} .fullscreen-table-wrapper .btn-expand-table`
+ );
+
+ assert
+ .dom(".fullscreen-table-modal")
+ .exists("The fullscreen table modal appears");
+ assert
+ .dom(".fullscreen-table-modal table")
+ .exists("The table is present inside the modal");
+
+ await click(".fullscreen-table-modal .modal-close");
+ await click(
+ `${postWithLargeTable} .fullscreen-table-wrapper .btn-expand-table svg`
+ );
+
+ assert
+ .dom(".fullscreen-table-modal")
+ .exists("Fullscreen table modal appears on clicking svg icon");
+ });
+ }
+);
diff --git a/frontend/discourse/tests/acceptance/table-builder-test.js b/frontend/discourse/tests/acceptance/table-builder-test.js
index a4911f4ebad..5b7c875d0d4 100644
--- a/frontend/discourse/tests/acceptance/table-builder-test.js
+++ b/frontend/discourse/tests/acceptance/table-builder-test.js
@@ -2,36 +2,28 @@ import { click, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Table Builder (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.user();
+acceptance(`Table Builder`, function (needs) {
+ needs.user();
- test("Can see table builder button when creating a topic", async function (assert) {
- await visit("/");
- await click("#create-topic");
- await click(".toolbar-menu__options-trigger");
+ test("Can see table builder button when creating a topic", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await click(".toolbar-menu__options-trigger");
- assert
- .dom("button[data-name='toggle-spreadsheet']")
- .exists("it shows the builder button");
- });
+ assert
+ .dom("button[data-name='toggle-spreadsheet']")
+ .exists("it shows the builder button");
+ });
- test("Can see table builder button when editing post", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#post_1 .show-more-actions");
- await click("#post_1 .edit");
- assert.dom("#reply-control").exists();
- await click(".toolbar-menu__options-trigger");
+ test("Can see table builder button when editing post", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#post_1 .show-more-actions");
+ await click("#post_1 .edit");
+ assert.dom("#reply-control").exists();
+ await click(".toolbar-menu__options-trigger");
- assert
- .dom("button[data-name='toggle-spreadsheet']")
- .exists("it shows the builder button");
- });
- }
- );
+ assert
+ .dom("button[data-name='toggle-spreadsheet']")
+ .exists("it shows the builder button");
+ });
});
diff --git a/frontend/discourse/tests/acceptance/topic-post-decorate-cooked-test.gjs b/frontend/discourse/tests/acceptance/topic-post-decorate-cooked-test.gjs
index a937ea9d94e..222f218f82a 100644
--- a/frontend/discourse/tests/acceptance/topic-post-decorate-cooked-test.gjs
+++ b/frontend/discourse/tests/acceptance/topic-post-decorate-cooked-test.gjs
@@ -6,79 +6,70 @@ import { test } from "qunit";
import { withPluginApi } from "discourse/lib/plugin-api";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Acceptance | decorateCookedElement (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
+acceptance(`Acceptance | decorateCookedElement`, function () {
+ test("decorator with renderGlimmer works", async function (assert) {
+ class DemoComponent extends Component {
+ static eventLog = [];
- test("decorator with renderGlimmer works", async function (assert) {
- class DemoComponent extends Component {
- static eventLog = [];
+ constructor() {
+ DemoComponent.eventLog.push("created");
+ super(...arguments);
+ }
- constructor() {
- DemoComponent.eventLog.push("created");
- super(...arguments);
- }
-
- willDestroy() {
- super.willDestroy(...arguments);
- DemoComponent.eventLog.push("willDestroy");
- }
- }
+ willDestroy() {
+ super.willDestroy(...arguments);
+ DemoComponent.eventLog.push("willDestroy");
+ }
+ }
- setComponentTemplate(
- hbs`<span class='glimmer-component-content'>Hello world</span>`,
- DemoComponent
- );
+ setComponentTemplate(
+ hbs`<span class='glimmer-component-content'>Hello world</span>`,
+ DemoComponent
+ );
- withPluginApi((api) => {
- api.decorateCookedElement(
- (cooked, helper) => {
- if (helper.getModel().post_number !== 1) {
- return;
- }
+ withPluginApi((api) => {
+ api.decorateCookedElement(
+ (cooked, helper) => {
+ if (helper.getModel().post_number !== 1) {
+ return;
+ }
- cooked.innerHTML =
- "<div class='existing-wrapper'>Some existing content</div>";
+ cooked.innerHTML =
+ "<div class='existing-wrapper'>Some existing content</div>";
- helper.renderGlimmer(
- cooked,
- <template><@data.component /></template>,
- {
- component: DemoComponent,
- }
- );
+ helper.renderGlimmer(
+ cooked,
+ <template><@data.component /></template>,
+ {
+ component: DemoComponent,
+ }
+ );
- // Append to existing element
- helper.renderGlimmer(
- cooked.querySelector(".existing-wrapper"),
- <template>
- <span>with more content from glimmer</span>
- </template>
- );
- },
- { onlyStream: true }
+ // Append to existing element
+ helper.renderGlimmer(
+ cooked.querySelector(".existing-wrapper"),
+ <template>
+ <span>with more content from glimmer</span>
+ </template>
);
- });
+ },
+ { onlyStream: true }
+ );
+ });
- await visit("/t/internationalization-localization/280");
+ await visit("/t/internationalization-localization/280");
- assert.dom("span.glimmer-component-content").exists();
+ assert.dom("span.glimmer-component-content").exists();
- assert.dom("div.existing-wrapper").exists();
- assert
- .dom("div.existing-wrapper span")
- .hasText("with more content from glimmer");
+ assert.dom("div.existing-wrapper").exists();
+ assert
+ .dom("div.existing-wrapper span")
+ .hasText("with more content from glimmer");
- assert.deepEqual(DemoComponent.eventLog, ["created"]);
+ assert.deepEqual(DemoComponent.eventLog, ["created"]);
- await visit("/");
+ await visit("/");
- assert.deepEqual(DemoComponent.eventLog, ["created", "willDestroy"]);
- });
- }
- );
+ assert.deepEqual(DemoComponent.eventLog, ["created", "willDestroy"]);
+ });
});
diff --git a/frontend/discourse/tests/acceptance/topic-test.js b/frontend/discourse/tests/acceptance/topic-test.js
index 731f2bae868..beea82f501e 100644
--- a/frontend/discourse/tests/acceptance/topic-test.js
+++ b/frontend/discourse/tests/acceptance/topic-test.js
@@ -18,832 +18,740 @@ import {
import selectKit from "discourse/tests/helpers/select-kit-helper";
import { i18n } from "discourse-i18n";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Topic (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- post_menu:
- "read|like|share|flag|edit|bookmark|delete|admin|reply|copyLink",
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.pretender((server, helper) => {
- server.get("/c/2/visible_groups.json", () =>
- helper.response(200, {
- groups: [],
- })
- );
-
- server.get("/c/feature/find_by_slug.json", () => {
- return helper.response(200, CategoryFixtures["/c/1/show.json"]);
- });
- server.put("/posts/398/wiki", () => {
- return helper.response({});
- });
- });
-
- test("Reply as new topic", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("button.share:nth-of-type(1)");
- await click("button.new-topic");
-
- assert.dom(".d-editor-input").exists("the composer input is visible");
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- `Continuing the discussion from [Internationalization / localization](${window.location.origin}/t/internationalization-localization/280):\n\n`,
- "fills composer with the ring string"
- );
- assert.strictEqual(
- selectKit(".category-chooser").header().value(),
- "2",
- "fills category selector with the right category"
- );
- });
-
- test("Reply as new message", async function (assert) {
- await visit("/t/pm-for-testing/12");
- await click("button.share:nth-of-type(1)");
- await click("button.new-topic");
-
- assert.dom(".d-editor-input").exists("the composer input is visible");
-
- assert
- .dom(".d-editor-input")
- .hasValue(
- `Continuing the discussion from [PM for testing](${window.location.origin}/t/pm-for-testing/12):\n\n`,
- "fills composer with the ring string"
- );
-
- const privateMessageUsers = selectKit("#private-message-users");
- assert.strictEqual(
- privateMessageUsers.header().value(),
- "someguy,test,Group",
- "fills up the composer correctly"
- );
- });
-
- test("Share Modal", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".topic-post[data-post-number='1'] button.share");
-
- assert.dom(".share-topic-modal").exists("shows the share modal");
- });
-
- test("Copy Link Button", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(
- ".topic-post[data-post-number='1'] button.post-action-menu__copy-link"
- );
-
- assert
- .dom(".post-action-menu__copy-link-checkmark")
- .exists("shows the Link Copied! message");
- });
-
- test("Showing and hiding the edit controls", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- await click("#topic-title .d-icon-pencil");
-
- assert.dom("#edit-title").exists("shows the editing controls");
- assert
- .dom(".title-wrapper .remove-featured-link")
- .doesNotExist("link to remove featured link is not shown");
-
- await fillIn("#edit-title", "this is the new title");
- await click("#topic-title .cancel-edit");
- assert.dom("#edit-title").doesNotExist("hides the editing controls");
- });
-
- test("Updating the topic title and category", async function (assert) {
- const categoryChooser = selectKit(".title-wrapper .category-chooser");
-
- await visit("/t/internationalization-localization/280");
-
- await click("#topic-title .d-icon-pencil");
- await fillIn("#edit-title", "this is the new title");
- await categoryChooser.expand();
- await categoryChooser.selectRowByValue(4);
- await click("#topic-title .submit-edit");
-
- assert
- .dom("#topic-title .badge-category")
- .hasText("faq", "displays the new category");
- assert
- .dom(".fancy-title")
- .hasText("this is the new title", "displays the new title");
- });
-
- test("Marking a topic as wiki", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- assert.dom("a.wiki").doesNotExist("does not show the wiki icon");
-
- await click(
- ".topic-post[data-post-number='1'] button.show-more-actions"
- );
- await click(
- ".topic-post[data-post-number='1'] button.show-post-admin-menu"
- );
- await click(".btn.wiki");
-
- assert.dom("button.wiki").exists("shows the wiki icon");
- });
-
- test("Visit topic routes", async function (assert) {
- await visit("/t/12");
-
- assert
- .dom(".fancy-title")
- .hasText("PM for testing", "routes to the right topic");
-
- await visit("/t/280/20");
-
- assert
- .dom(".fancy-title")
- .hasText(
- "Internationalization / localization",
- "routes to the right topic"
- );
- });
-
- test("Updating the topic title with emojis", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-title .d-icon-pencil");
-
- await fillIn("#edit-title", "emojis title :bike: :blonde_woman:t6:");
-
- await click("#topic-title .submit-edit");
-
- assert
- .dom(".fancy-title")
- .includesHtml("bike.png", "displays the new title with emojis");
- });
-
- test("Updating the topic title with unicode emojis", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-title .d-icon-pencil");
-
- await fillIn("#edit-title", "emojis title 👨‍🌾🙏");
-
- await click("#topic-title .submit-edit");
-
- assert
- .dom(".fancy-title")
- .includesHtml("man_farmer.png", "displays the new title with emojis");
- });
-
- test("Updating the topic title with unicode emojis without whitespace", async function (assert) {
- this.siteSettings.enable_inline_emoji_translation = true;
- await visit("/t/internationalization-localization/280");
- await click("#topic-title .d-icon-pencil");
-
- await fillIn("#edit-title", "Test🙂Title");
-
- await click("#topic-title .submit-edit");
-
- assert
- .dom(".fancy-title")
- .includesHtml(
- "slightly_smiling_face.png",
- "displays the new title with emojis"
- );
- });
-
- test("Suggested topics", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- assert
- .dom("#suggested-topics-title")
- .hasText(i18n("suggested_topics.title"));
- });
-
- test("Deleting a topic", async function (assert) {
- this.siteSettings.min_topic_views_for_delete_confirm = 10000;
- await visit("/t/internationalization-localization/280");
- await click(
- ".topic-post[data-post-number='1'] button.show-more-actions"
- );
- await click(".topic-post[data-post-number='1'] button.delete");
- await click(".toggle-admin-menu");
- assert.dom(".topic-admin-recover").exists("shows the recover button");
- });
-
- test("Deleting a popular topic displays confirmation modal", async function (assert) {
- this.siteSettings.min_topic_views_for_delete_confirm = 10;
- await visit("/t/internationalization-localization/280");
- await click(
- ".topic-post[data-post-number='1'] button.show-more-actions"
- );
- await click(".topic-post[data-post-number='1'] button.delete");
- assert
- .dom(".delete-topic-confirm-modal")
- .exists("shows the delete confirmation modal");
-
- await click(".delete-topic-confirm-modal .btn-primary");
- assert
- .dom(".delete-topic-confirm-modal")
- .doesNotExist("hides the delete confirmation modal");
- await click(".topic-post[data-post-number='1'] button.delete");
- await click(".delete-topic-confirm-modal .btn-danger");
- await click(".toggle-admin-menu");
- assert.dom(".topic-admin-recover").exists("shows the recover button");
- });
-
- test("Group category moderator posts", async function (assert) {
- await visit("/t/topic-for-group-moderators/2480");
-
- assert.dom(".category-moderator").exists("has a class applied");
- assert.dom(".d-icon-shield-halved").exists("shows an icon");
- });
-
- test("Suspended user posts", async function (assert) {
- await visit("/t/topic-from-suspended-user/54077");
-
- assert
- .dom(".topic-post.user-suspended > #post_1")
- .exists("has a class applied");
- });
- }
- );
+acceptance(`Topic`, function (needs) {
+ needs.user();
+ needs.settings({
+ post_menu: "read|like|share|flag|edit|bookmark|delete|admin|reply|copyLink",
+ });
+ needs.pretender((server, helper) => {
+ server.get("/c/2/visible_groups.json", () =>
+ helper.response(200, {
+ groups: [],
+ })
+ );
+
+ server.get("/c/feature/find_by_slug.json", () => {
+ return helper.response(200, CategoryFixtures["/c/1/show.json"]);
+ });
+ server.put("/posts/398/wiki", () => {
+ return helper.response({});
+ });
+ });
+
+ test("Reply as new topic", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("button.share:nth-of-type(1)");
+ await click("button.new-topic");
+
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ `Continuing the discussion from [Internationalization / localization](${window.location.origin}/t/internationalization-localization/280):\n\n`,
+ "fills composer with the ring string"
+ );
+ assert.strictEqual(
+ selectKit(".category-chooser").header().value(),
+ "2",
+ "fills category selector with the right category"
+ );
+ });
+
+ test("Reply as new message", async function (assert) {
+ await visit("/t/pm-for-testing/12");
+ await click("button.share:nth-of-type(1)");
+ await click("button.new-topic");
+
+ assert.dom(".d-editor-input").exists("the composer input is visible");
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ `Continuing the discussion from [PM for testing](${window.location.origin}/t/pm-for-testing/12):\n\n`,
+ "fills composer with the ring string"
+ );
- acceptance(
- `Topic featured links (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- topic_featured_link_enabled: true,
- max_topic_title_length: 80,
- exclude_rel_nofollow_domains: "example.com",
- display_name_on_posts: false,
- prioritize_username_in_ux: true,
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.pretender((server, helper) => {
- server.get("/inline-onebox", () => {
- return helper.response({ "inline-oneboxes": [] });
- });
- });
-
- test("remove nofollow attribute", async function (assert) {
- await visit("/t/-/299/1");
-
- assert
- .dom(".title-wrapper .topic-featured-link")
- .hasText("example.com");
- assert
- .dom(".title-wrapper .topic-featured-link")
- .hasAttribute("rel", "ugc");
- });
-
- test("remove featured link", async function (assert) {
- await visit("/t/-/299/1");
- assert
- .dom(".title-wrapper .topic-featured-link")
- .exists("link is shown with topic title");
-
- await click(".title-wrapper .edit-topic");
- assert
- .dom(".title-wrapper .remove-featured-link")
- .exists("link to remove featured link");
- });
-
- test("Converting to a public topic", async function (assert) {
- await visit("/t/test-pm/34");
- assert.dom(".private_message").exists();
- await click(".toggle-admin-menu");
- await click(".topic-admin-convert button");
-
- let categoryChooser = selectKit(
- ".convert-to-public-topic .category-chooser"
- );
- await categoryChooser.expand();
- await categoryChooser.selectRowByValue(21);
-
- await click(".convert-to-public-topic .btn-primary");
- assert.dom(".private_message").doesNotExist();
- });
-
- test("Unpinning unlisted topic", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- await click(".toggle-admin-menu");
- await click(".topic-admin-pin .btn");
- await click(".make-banner");
-
- await click(".toggle-admin-menu");
- await click(".topic-admin-visible .btn");
-
- await click(".toggle-admin-menu");
- assert
- .dom(".topic-admin-pin")
- .exists("should show the multi select menu");
- });
-
- test("selecting posts", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".toggle-admin-menu");
- await click(".topic-admin-multi-select .btn");
-
- assert
- .dom(".selected-posts:not(.hidden)")
- .exists("should show the multi select menu");
-
- assert
- .dom(".select-all")
- .exists("should allow users to select all the posts");
- });
-
- test("select below", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".toggle-admin-menu");
- await click(".topic-admin-multi-select .btn");
- await click("#post_3 .select-below");
-
- assert
- .dom(".selected-posts")
- .includesHtml(
- i18n("topic.multi_select.description", { count: 18 }),
- "selects the right number of posts"
- );
-
- await click("#post_2 .select-below");
-
- assert
- .dom(".selected-posts")
- .includesHtml(
- i18n("topic.multi_select.description", { count: 19 }),
- "selects the right number of posts"
- );
- });
-
- test("View Hidden Replies", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click(".gap");
-
- assert.dom(".gap").doesNotExist("hides gap");
- });
-
- test("Quoting a quote keeps the original poster name", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await selectText("#post_5 blockquote");
- await click(".quote-button .insert-quote");
-
- assert
- .dom(".d-editor-input")
- .includesValue('quote="codinghorror said, post:3, topic:280"');
- });
-
- test("Quoting a quote of a different topic keeps the original topic title", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await selectText("#post_9 blockquote");
- await click(".quote-button .insert-quote");
-
- assert
- .dom(".d-editor-input")
- .includesValue(
- 'quote="A new topic with a link to another topic, post:3, topic:62"'
- );
- });
-
- test("Quoting a quote with the Reply button keeps the original poster name", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await selectText("#post_5 blockquote");
- await click(".reply");
-
- assert
- .dom(".d-editor-input")
- .includesValue('quote="codinghorror said, post:3, topic:280"');
- });
-
- // Using J/K on Firefox clean the text selection, so this won't work there
- chromeTest(
- "Quoting a quote with replyAsNewTopic keeps the original poster name",
- async function (assert) {
- await visit("/t/internationalization-localization/280");
- await selectText("#post_5 blockquote");
- await triggerKeyEvent(document, "keypress", "J");
- await triggerKeyEvent(document, "keypress", "T");
-
- assert
- .dom(".d-editor-input")
- .includesValue('quote="codinghorror said, post:3, topic:280"');
- }
+ const privateMessageUsers = selectKit("#private-message-users");
+ assert.strictEqual(
+ privateMessageUsers.header().value(),
+ "someguy,test,Group",
+ "fills up the composer correctly"
+ );
+ });
+
+ test("Share Modal", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.share");
+
+ assert.dom(".share-topic-modal").exists("shows the share modal");
+ });
+
+ test("Copy Link Button", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(
+ ".topic-post[data-post-number='1'] button.post-action-menu__copy-link"
+ );
+
+ assert
+ .dom(".post-action-menu__copy-link-checkmark")
+ .exists("shows the Link Copied! message");
+ });
+
+ test("Showing and hiding the edit controls", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ await click("#topic-title .d-icon-pencil");
+
+ assert.dom("#edit-title").exists("shows the editing controls");
+ assert
+ .dom(".title-wrapper .remove-featured-link")
+ .doesNotExist("link to remove featured link is not shown");
+
+ await fillIn("#edit-title", "this is the new title");
+ await click("#topic-title .cancel-edit");
+ assert.dom("#edit-title").doesNotExist("hides the editing controls");
+ });
+
+ test("Updating the topic title and category", async function (assert) {
+ const categoryChooser = selectKit(".title-wrapper .category-chooser");
+
+ await visit("/t/internationalization-localization/280");
+
+ await click("#topic-title .d-icon-pencil");
+ await fillIn("#edit-title", "this is the new title");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(4);
+ await click("#topic-title .submit-edit");
+
+ assert
+ .dom("#topic-title .badge-category")
+ .hasText("faq", "displays the new category");
+ assert
+ .dom(".fancy-title")
+ .hasText("this is the new title", "displays the new title");
+ });
+
+ test("Marking a topic as wiki", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ assert.dom("a.wiki").doesNotExist("does not show the wiki icon");
+
+ await click(".topic-post[data-post-number='1'] button.show-more-actions");
+ await click(
+ ".topic-post[data-post-number='1'] button.show-post-admin-menu"
+ );
+ await click(".btn.wiki");
+
+ assert.dom("button.wiki").exists("shows the wiki icon");
+ });
+
+ test("Visit topic routes", async function (assert) {
+ await visit("/t/12");
+
+ assert
+ .dom(".fancy-title")
+ .hasText("PM for testing", "routes to the right topic");
+
+ await visit("/t/280/20");
+
+ assert
+ .dom(".fancy-title")
+ .hasText(
+ "Internationalization / localization",
+ "routes to the right topic"
);
+ });
- test("Quoting by selecting text can mark the quote as full", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await selectText("#post_5 .cooked");
- await click(".quote-button .insert-quote");
- assert
- .dom(".d-editor-input")
- .includesValue('quote="pekka, post:5, topic:280, full:true"');
- });
- }
- );
+ test("Updating the topic title with emojis", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-title .d-icon-pencil");
- acceptance(
- `Topic featured links (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- topic_featured_link_enabled: true,
- max_topic_title_length: 80,
- glimmer_post_stream_mode: postStreamMode,
- });
-
- test("remove featured link", async function (assert) {
- await visit("/t/-/299/1");
- assert
- .dom(".title-wrapper .topic-featured-link")
- .exists("link is shown with topic title");
-
- await click(".title-wrapper .edit-topic");
- assert
- .dom(".title-wrapper .remove-featured-link")
- .exists("link to remove featured link");
- });
- }
- );
+ await fillIn("#edit-title", "emojis title :bike: :blonde_woman:t6:");
- acceptance(
- `Topic pinning/unpinning as an admin (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({ admin: true });
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
+ await click("#topic-title .submit-edit");
- test("Admin pinning topic", async function (assert) {
- await visit("/t/topic-for-group-moderators/2480");
+ assert
+ .dom(".fancy-title")
+ .includesHtml("bike.png", "displays the new title with emojis");
+ });
- await click(".toggle-admin-menu");
- await click(".topic-admin-pin .btn");
+ test("Updating the topic title with unicode emojis", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-title .d-icon-pencil");
- assert
- .dom(".feature-topic .btn-primary")
- .exists("should show the 'Pin Topic' button");
+ await fillIn("#edit-title", "emojis title 👨‍🌾🙏");
- assert
- .dom(".make-banner")
- .exists("should show the 'Banner Topic' button");
- });
- }
- );
+ await click("#topic-title .submit-edit");
+
+ assert
+ .dom(".fancy-title")
+ .includesHtml("man_farmer.png", "displays the new title with emojis");
+ });
+
+ test("Updating the topic title with unicode emojis without whitespace", async function (assert) {
+ this.siteSettings.enable_inline_emoji_translation = true;
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-title .d-icon-pencil");
+
+ await fillIn("#edit-title", "Test🙂Title");
- acceptance(
- `Topic pinning/unpinning as a staff member (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({ moderator: true, admin: false, trust_level: 2 });
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
+ await click("#topic-title .submit-edit");
- test("Staff pinning topic", async function (assert) {
- await visit("/t/topic-for-group-moderators/2480");
+ assert
+ .dom(".fancy-title")
+ .includesHtml(
+ "slightly_smiling_face.png",
+ "displays the new title with emojis"
+ );
+ });
+
+ test("Suggested topics", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ assert
+ .dom("#suggested-topics-title")
+ .hasText(i18n("suggested_topics.title"));
+ });
+
+ test("Deleting a topic", async function (assert) {
+ this.siteSettings.min_topic_views_for_delete_confirm = 10000;
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.show-more-actions");
+ await click(".topic-post[data-post-number='1'] button.delete");
+ await click(".toggle-admin-menu");
+ assert.dom(".topic-admin-recover").exists("shows the recover button");
+ });
+
+ test("Deleting a popular topic displays confirmation modal", async function (assert) {
+ this.siteSettings.min_topic_views_for_delete_confirm = 10;
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-post[data-post-number='1'] button.show-more-actions");
+ await click(".topic-post[data-post-number='1'] button.delete");
+ assert
+ .dom(".delete-topic-confirm-modal")
+ .exists("shows the delete confirmation modal");
+
+ await click(".delete-topic-confirm-modal .btn-primary");
+ assert
+ .dom(".delete-topic-confirm-modal")
+ .doesNotExist("hides the delete confirmation modal");
+ await click(".topic-post[data-post-number='1'] button.delete");
+ await click(".delete-topic-confirm-modal .btn-danger");
+ await click(".toggle-admin-menu");
+ assert.dom(".topic-admin-recover").exists("shows the recover button");
+ });
+
+ test("Group category moderator posts", async function (assert) {
+ await visit("/t/topic-for-group-moderators/2480");
+
+ assert.dom(".category-moderator").exists("has a class applied");
+ assert.dom(".d-icon-shield-halved").exists("shows an icon");
+ });
+
+ test("Suspended user posts", async function (assert) {
+ await visit("/t/topic-from-suspended-user/54077");
+
+ assert
+ .dom(".topic-post.user-suspended > #post_1")
+ .exists("has a class applied");
+ });
+});
- await click(".toggle-admin-menu");
- await click(".topic-admin-pin .btn");
+acceptance(`Topic featured links`, function (needs) {
+ needs.user();
+ needs.settings({
+ topic_featured_link_enabled: true,
+ max_topic_title_length: 80,
+ exclude_rel_nofollow_domains: "example.com",
+ display_name_on_posts: false,
+ prioritize_username_in_ux: true,
+ });
+ needs.pretender((server, helper) => {
+ server.get("/inline-onebox", () => {
+ return helper.response({ "inline-oneboxes": [] });
+ });
+ });
+
+ test("remove nofollow attribute", async function (assert) {
+ await visit("/t/-/299/1");
+
+ assert.dom(".title-wrapper .topic-featured-link").hasText("example.com");
+ assert
+ .dom(".title-wrapper .topic-featured-link")
+ .hasAttribute("rel", "ugc");
+ });
+
+ test("remove featured link", async function (assert) {
+ await visit("/t/-/299/1");
+ assert
+ .dom(".title-wrapper .topic-featured-link")
+ .exists("link is shown with topic title");
+
+ await click(".title-wrapper .edit-topic");
+ assert
+ .dom(".title-wrapper .remove-featured-link")
+ .exists("link to remove featured link");
+ });
+
+ test("Converting to a public topic", async function (assert) {
+ await visit("/t/test-pm/34");
+ assert.dom(".private_message").exists();
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-convert button");
+
+ let categoryChooser = selectKit(
+ ".convert-to-public-topic .category-chooser"
+ );
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(21);
+
+ await click(".convert-to-public-topic .btn-primary");
+ assert.dom(".private_message").doesNotExist();
+ });
+
+ test("Unpinning unlisted topic", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-pin .btn");
+ await click(".make-banner");
+
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-visible .btn");
+
+ await click(".toggle-admin-menu");
+ assert.dom(".topic-admin-pin").exists("should show the multi select menu");
+ });
+
+ test("selecting posts", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-multi-select .btn");
+
+ assert
+ .dom(".selected-posts:not(.hidden)")
+ .exists("should show the multi select menu");
+
+ assert
+ .dom(".select-all")
+ .exists("should allow users to select all the posts");
+ });
+
+ test("select below", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-multi-select .btn");
+ await click("#post_3 .select-below");
+
+ assert
+ .dom(".selected-posts")
+ .includesHtml(
+ i18n("topic.multi_select.description", { count: 18 }),
+ "selects the right number of posts"
+ );
- assert
- .dom(".feature-topic .btn-primary")
- .exists("should show the 'Pin Topic' button");
+ await click("#post_2 .select-below");
- assert
- .dom(".make-banner")
- .exists("should show the 'Banner Topic' button");
- });
+ assert
+ .dom(".selected-posts")
+ .includesHtml(
+ i18n("topic.multi_select.description", { count: 19 }),
+ "selects the right number of posts"
+ );
+ });
+
+ test("View Hidden Replies", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".gap");
+
+ assert.dom(".gap").doesNotExist("hides gap");
+ });
+
+ test("Quoting a quote keeps the original poster name", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_5 blockquote");
+ await click(".quote-button .insert-quote");
+
+ assert
+ .dom(".d-editor-input")
+ .includesValue('quote="codinghorror said, post:3, topic:280"');
+ });
+
+ test("Quoting a quote of a different topic keeps the original topic title", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_9 blockquote");
+ await click(".quote-button .insert-quote");
+
+ assert
+ .dom(".d-editor-input")
+ .includesValue(
+ 'quote="A new topic with a link to another topic, post:3, topic:62"'
+ );
+ });
+
+ test("Quoting a quote with the Reply button keeps the original poster name", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_5 blockquote");
+ await click(".reply");
+
+ assert
+ .dom(".d-editor-input")
+ .includesValue('quote="codinghorror said, post:3, topic:280"');
+ });
+
+ // Using J/K on Firefox clean the text selection, so this won't work there
+ chromeTest(
+ "Quoting a quote with replyAsNewTopic keeps the original poster name",
+ async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_5 blockquote");
+ await triggerKeyEvent(document, "keypress", "J");
+ await triggerKeyEvent(document, "keypress", "T");
+
+ assert
+ .dom(".d-editor-input")
+ .includesValue('quote="codinghorror said, post:3, topic:280"');
}
);
- acceptance(
- `Topic pinning/unpinning as a group moderator (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({ moderator: false, admin: false, trust_level: 1 });
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
+ test("Quoting by selecting text can mark the quote as full", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await selectText("#post_5 .cooked");
+ await click(".quote-button .insert-quote");
+ assert
+ .dom(".d-editor-input")
+ .includesValue('quote="pekka, post:5, topic:280, full:true"');
+ });
+});
- test("Group category moderator pinning topic", async function (assert) {
- await visit("/t/topic-for-group-moderators/2480");
+acceptance(`Topic featured links`, function (needs) {
+ needs.user();
+ needs.settings({
+ topic_featured_link_enabled: true,
+ max_topic_title_length: 80,
+ });
+
+ test("remove featured link", async function (assert) {
+ await visit("/t/-/299/1");
+ assert
+ .dom(".title-wrapper .topic-featured-link")
+ .exists("link is shown with topic title");
+
+ await click(".title-wrapper .edit-topic");
+ assert
+ .dom(".title-wrapper .remove-featured-link")
+ .exists("link to remove featured link");
+ });
+});
- await click(".toggle-admin-menu");
- await click(".topic-admin-pin .btn");
+acceptance(`Topic pinning/unpinning as an admin`, function (needs) {
+ needs.user({ admin: true });
- assert
- .dom(".feature-topic .btn-primary")
- .exists("should show the 'Pin Topic' button");
+ test("Admin pinning topic", async function (assert) {
+ await visit("/t/topic-for-group-moderators/2480");
- assert
- .dom(".make-banner")
- .doesNotExist("should not show the 'Banner Topic' button");
- });
- }
- );
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-pin .btn");
- acceptance(
- `Topic last visit line (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({ moderator: false, admin: false, trust_level: 1 });
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
-
- test("visit topic", async function (assert) {
- await visit("/t/-/280");
-
- assert
- .dom(".topic-post-visited-line.post-10")
- .exists("shows the last visited line on the right post");
-
- await visit("/t/-/9");
-
- assert
- .dom(".topic-post-visited-line")
- .doesNotExist(
- "does not show last visited line if post is the last post"
- );
- });
- }
- );
+ assert
+ .dom(".feature-topic .btn-primary")
+ .exists("should show the 'Pin Topic' button");
- acceptance(
- `Topic filter replies to post number (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- enable_filtered_replies_view: true,
- glimmer_post_stream_mode: postStreamMode,
- });
-
- test("visit topic", async function (assert) {
- await visit("/t/-/280");
-
- assert
- .dom("#post_3 .show-replies")
- .hasAttribute(
- "title",
- i18n("post.filtered_replies_hint", { count: 3 }),
- "displays the right title for filtering by replies"
- );
-
- await visit("/");
- await visit("/t/-/280?replies_to_post_number=3");
-
- assert
- .dom("#post_3 .show-replies")
- .hasAttribute(
- "title",
- i18n("post.view_all_posts"),
- "displays the right title when filtered by replies"
- );
- });
- }
- );
+ assert.dom(".make-banner").exists("should show the 'Banner Topic' button");
+ });
+});
- acceptance(
- `Navigating between topics (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
-
- needs.pretender((server, helper) => {
- const topicResponse = cloneJSON(topicFixtures["/t/280/1.json"]);
- const firstPost = topicResponse.post_stream.posts[0];
- firstPost.cooked += `\n<a class='same-topic-slugless' href='/t/280'>Link 1</a>`;
- firstPost.cooked += `\n<a class='same-topic-slugless-post' href='/t/280/3'>Link 2</a>`;
- firstPost.cooked += `\n<a class='diff-topic-slugless' href='/t/28830'>Link 3</a>`;
- firstPost.cooked += `\n<a class='diff-topic-slugless-post' href='/t/28830/1'>Link 4</a>`;
- firstPost.cooked += `\n<a class='by-post-id' href='/p/${firstPost.id}'>Link to Post</a>`;
-
- server.get("/t/280.json", () => helper.response(topicResponse));
- server.get("/t/280/:post_number.json", () =>
- helper.response(topicResponse)
- );
- });
-
- test("clicking slug-less URLs within the same topic", async function (assert) {
- await visit("/t/-/280");
- await click("a.same-topic-slugless");
- assert.true(currentURL().includes("/280"));
-
- await click("a.same-topic-slugless-post");
- assert.true(currentURL().includes("/280"));
- });
-
- test("clicking slug-less URLs to a different topic", async function (assert) {
- await visit("/t/-/280");
- await click("a.diff-topic-slugless");
- assert.true(currentURL().includes("/28830"));
-
- await visit("/t/-/280");
- await click("a.diff-topic-slugless-post");
- assert.true(currentURL().includes("/28830"));
- });
-
- test("clicking post URLs", async function (assert) {
- await visit("/t/-/280");
- await click("a.by-post-id");
- assert.true(currentURL().includes("/280"));
- });
- }
- );
+acceptance(`Topic pinning/unpinning as a staff member`, function (needs) {
+ needs.user({ moderator: true, admin: false, trust_level: 2 });
- acceptance(
- `Cooked quoted content (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
-
- needs.pretender((server, helper) => {
- server.get("/posts/by_number/280/3", () =>
- helper.response(
- 200,
- topicFixtures["/t/280/1.json"].post_stream.posts[2]
- )
- );
- server.get("/posts/by_number/280/5", () =>
- helper.response(
- 200,
- topicFixtures["/t/280/1.json"].post_stream.posts[4]
- )
- );
- });
-
- test("The quoted content is toggled correclty", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- assert
- .dom(
- "#post_5 .cooked .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
- )
- .hasAttribute("aria-expanded", "false");
- assert
- .dom("#post_5 .quote[data-topic='280'][data-post='3']")
- .includesText(
- 'So you could replace that lookup table with the "de" one to get German.'
- )
- .doesNotIncludeText(
- "Yep, all strings are going through a lookup table.*"
- );
-
- await click(
- "#post_5 .cooked .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
- );
-
- assert
- .dom(
- "#post_5 .cooked .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
- )
- .hasAttribute("aria-expanded", "true");
- assert
- .dom("#post_5 .quote[data-topic='280'][data-post='3']")
- .includesText(
- 'So you could replace that lookup table with the "de" one to get German.'
- )
- .includesText("Yep, all strings are going through a lookup table.*");
-
- await click(
- "#post_5 .cooked .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
- );
-
- assert
- .dom(
- "#post_5 .cooked .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
- )
- .hasAttribute("aria-expanded", "false");
- });
-
- // TODO (glimmer-post-stream): this test only works with the Glimmer Post Stream.
- // When the removing the legacy code we should remove the `if` and run it unconditionally.
- if (postStreamMode === "enabled") {
- test("Nesting quoted content works", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- // outer quote
- assert
- .dom(
- "#post_7 .cooked .quote[data-topic='280'][data-post='5'] > .title .quote-controls .quote-toggle"
- )
- .hasAttribute("aria-expanded", "false");
-
- assert
- .dom("#post_7 .quote[data-topic='280'][data-post='5']")
- .includesText("The problem I see here")
- .doesNotIncludeText("So you could replace that lookup table");
-
- await click(
- "#post_7 .cooked .quote[data-topic='280'][data-post='5'] > .title .quote-controls .quote-toggle"
- );
-
- assert
- .dom(
- "#post_7 .cooked .quote[data-topic='280'][data-post='5'] > .title .quote-controls .quote-toggle"
- )
- .hasAttribute("aria-expanded", "true");
- assert
- .dom("#post_7 .quote[data-topic='280'][data-post='5']")
- .includesText("The problem I see here")
- .includesText("So you could replace that lookup table");
-
- // nested quote
- assert
- .dom(
- "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
- )
- .hasAttribute("aria-expanded", "false");
- assert
- .dom(
- "#post_7 .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3']"
- )
- .includesText(
- 'So you could replace that lookup table with the "de" one to get German.'
- )
- .doesNotIncludeText(
- "Yep, all strings are going through a lookup table.*"
- );
-
- await click(
- "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
- );
-
- assert
- .dom(
- "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
- )
- .hasAttribute("aria-expanded", "true");
- assert
- .dom(
- "#post_7 .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3']"
- )
- .includesText(
- 'So you could replace that lookup table with the "de" one to get German.'
- )
- .includesText(
- "Yep, all strings are going through a lookup table.*"
- );
-
- await click(
- "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
- );
-
- assert
- .dom(
- "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
- )
- .hasAttribute("aria-expanded", "false");
-
- // outer quote
- await click(
- "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote-controls .quote-toggle"
- );
-
- assert
- .dom(
- "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote-controls .quote-toggle"
- )
- .hasAttribute("aria-expanded", "false");
- });
- }
- }
- );
+ test("Staff pinning topic", async function (assert) {
+ await visit("/t/topic-for-group-moderators/2480");
- acceptance(
- `Topic stats update automatically (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
-
- test("Likes count updates automatically", async function (assert) {
- await visit("/t/internationalization-localization/280");
-
- const oldLikesCount = document.querySelector(
- "#post_1 .topic-map .topic-map__likes-trigger .number"
- ).textContent;
- const likesChangedFixture = {
- id: 280,
- type: "stats",
- like_count: parseInt(oldLikesCount, 10) + 42,
- };
- const expectedLikesCount = likesChangedFixture.like_count.toString();
-
- // simulate the topic like_count being changed
- await publishToMessageBus("/topic/280", likesChangedFixture);
-
- assert
- .dom("#post_1 .topic-map .topic-map__likes-trigger .number")
- .hasText(expectedLikesCount);
- assert.notStrictEqual(
- oldLikesCount,
- expectedLikesCount,
- "updates the likes count on the topic stats"
- );
- });
- }
- );
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-pin .btn");
+
+ assert
+ .dom(".feature-topic .btn-primary")
+ .exists("should show the 'Pin Topic' button");
+
+ assert.dom(".make-banner").exists("should show the 'Banner Topic' button");
+ });
+});
+
+acceptance(`Topic pinning/unpinning as a group moderator`, function (needs) {
+ needs.user({ moderator: false, admin: false, trust_level: 1 });
+
+ test("Group category moderator pinning topic", async function (assert) {
+ await visit("/t/topic-for-group-moderators/2480");
+
+ await click(".toggle-admin-menu");
+ await click(".topic-admin-pin .btn");
+
+ assert
+ .dom(".feature-topic .btn-primary")
+ .exists("should show the 'Pin Topic' button");
+
+ assert
+ .dom(".make-banner")
+ .doesNotExist("should not show the 'Banner Topic' button");
+ });
+});
+
+acceptance(`Topic last visit line`, function (needs) {
+ needs.user({ moderator: false, admin: false, trust_level: 1 });
+
+ test("visit topic", async function (assert) {
+ await visit("/t/-/280");
+
+ assert
+ .dom(".topic-post-visited-line.post-10")
+ .exists("shows the last visited line on the right post");
+
+ await visit("/t/-/9");
+
+ assert
+ .dom(".topic-post-visited-line")
+ .doesNotExist("does not show last visited line if post is the last post");
+ });
+});
+
+acceptance(`Topic filter replies to post number`, function (needs) {
+ needs.settings({
+ enable_filtered_replies_view: true,
+ });
+
+ test("visit topic", async function (assert) {
+ await visit("/t/-/280");
+
+ assert
+ .dom("#post_3 .show-replies")
+ .hasAttribute(
+ "title",
+ i18n("post.filtered_replies_hint", { count: 3 }),
+ "displays the right title for filtering by replies"
+ );
+
+ await visit("/");
+ await visit("/t/-/280?replies_to_post_number=3");
+
+ assert
+ .dom("#post_3 .show-replies")
+ .hasAttribute(
+ "title",
+ i18n("post.view_all_posts"),
+ "displays the right title when filtered by replies"
+ );
+ });
+});
+
+acceptance(`Navigating between topics`, function (needs) {
+ needs.pretender((server, helper) => {
+ const topicResponse = cloneJSON(topicFixtures["/t/280/1.json"]);
+ const firstPost = topicResponse.post_stream.posts[0];
+ firstPost.cooked += `\n<a class='same-topic-slugless' href='/t/280'>Link 1</a>`;
+ firstPost.cooked += `\n<a class='same-topic-slugless-post' href='/t/280/3'>Link 2</a>`;
+ firstPost.cooked += `\n<a class='diff-topic-slugless' href='/t/28830'>Link 3</a>`;
+ firstPost.cooked += `\n<a class='diff-topic-slugless-post' href='/t/28830/1'>Link 4</a>`;
+ firstPost.cooked += `\n<a class='by-post-id' href='/p/${firstPost.id}'>Link to Post</a>`;
+
+ server.get("/t/280.json", () => helper.response(topicResponse));
+ server.get("/t/280/:post_number.json", () =>
+ helper.response(topicResponse)
+ );
+ });
+
+ test("clicking slug-less URLs within the same topic", async function (assert) {
+ await visit("/t/-/280");
+ await click("a.same-topic-slugless");
+ assert.true(currentURL().includes("/280"));
+
+ await click("a.same-topic-slugless-post");
+ assert.true(currentURL().includes("/280"));
+ });
+
+ test("clicking slug-less URLs to a different topic", async function (assert) {
+ await visit("/t/-/280");
+ await click("a.diff-topic-slugless");
+ assert.true(currentURL().includes("/28830"));
+
+ await visit("/t/-/280");
+ await click("a.diff-topic-slugless-post");
+ assert.true(currentURL().includes("/28830"));
+ });
+
+ test("clicking post URLs", async function (assert) {
+ await visit("/t/-/280");
+ await click("a.by-post-id");
+ assert.true(currentURL().includes("/280"));
+ });
+});
+
+acceptance(`Cooked quoted content`, function (needs) {
+ needs.pretender((server, helper) => {
+ server.get("/posts/by_number/280/3", () =>
+ helper.response(200, topicFixtures["/t/280/1.json"].post_stream.posts[2])
+ );
+ server.get("/posts/by_number/280/5", () =>
+ helper.response(200, topicFixtures["/t/280/1.json"].post_stream.posts[4])
+ );
+ });
+
+ test("The quoted content is toggled correclty", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ assert
+ .dom(
+ "#post_5 .cooked .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "false");
+ assert
+ .dom("#post_5 .quote[data-topic='280'][data-post='3']")
+ .includesText(
+ 'So you could replace that lookup table with the "de" one to get German.'
+ )
+ .doesNotIncludeText(
+ "Yep, all strings are going through a lookup table.*"
+ );
+
+ await click(
+ "#post_5 .cooked .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ );
+
+ assert
+ .dom(
+ "#post_5 .cooked .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "true");
+ assert
+ .dom("#post_5 .quote[data-topic='280'][data-post='3']")
+ .includesText(
+ 'So you could replace that lookup table with the "de" one to get German.'
+ )
+ .includesText("Yep, all strings are going through a lookup table.*");
+
+ await click(
+ "#post_5 .cooked .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ );
+
+ assert
+ .dom(
+ "#post_5 .cooked .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "false");
+ });
+
+ test("Nesting quoted content works", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ // outer quote
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] > .title .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "false");
+
+ assert
+ .dom("#post_7 .quote[data-topic='280'][data-post='5']")
+ .includesText("The problem I see here")
+ .doesNotIncludeText("So you could replace that lookup table");
+
+ await click(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] > .title .quote-controls .quote-toggle"
+ );
+
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] > .title .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "true");
+ assert
+ .dom("#post_7 .quote[data-topic='280'][data-post='5']")
+ .includesText("The problem I see here")
+ .includesText("So you could replace that lookup table");
+
+ // nested quote
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "false");
+ assert
+ .dom(
+ "#post_7 .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3']"
+ )
+ .includesText(
+ 'So you could replace that lookup table with the "de" one to get German.'
+ )
+ .doesNotIncludeText(
+ "Yep, all strings are going through a lookup table.*"
+ );
+
+ await click(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ );
+
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "true");
+ assert
+ .dom(
+ "#post_7 .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3']"
+ )
+ .includesText(
+ 'So you could replace that lookup table with the "de" one to get German.'
+ )
+ .includesText("Yep, all strings are going through a lookup table.*");
+
+ await click(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ );
+
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "false");
+
+ // outer quote
+ await click(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote-controls .quote-toggle"
+ );
+
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "false");
+ });
+});
+
+acceptance(`Topic stats update automatically`, function () {
+ test("Likes count updates automatically", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ const oldLikesCount = document.querySelector(
+ "#post_1 .topic-map .topic-map__likes-trigger .number"
+ ).textContent;
+ const likesChangedFixture = {
+ id: 280,
+ type: "stats",
+ like_count: parseInt(oldLikesCount, 10) + 42,
+ };
+ const expectedLikesCount = likesChangedFixture.like_count.toString();
+
+ // simulate the topic like_count being changed
+ await publishToMessageBus("/topic/280", likesChangedFixture);
+
+ assert
+ .dom("#post_1 .topic-map .topic-map__likes-trigger .number")
+ .hasText(expectedLikesCount);
+ assert.notStrictEqual(
+ oldLikesCount,
+ expectedLikesCount,
+ "updates the likes count on the topic stats"
+ );
+ });
});
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index bc030e2b6fe..56525e45d37 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -21,10 +21,10 @@ import {
cleanUpComposerUploadPreProcessor,
} from "discourse/components/composer-editor";
import { clearToolbarCallbacks } from "discourse/components/d-editor";
+import { resetHtmlDecorators } from "discourse/components/decorated-html";
import { clearExtraHeaderButtons as clearExtraGlimmerHeaderButtons } from "discourse/components/header";
import { clearExtraHeaderIcons as clearExtraGlimmerHeaderIcons } from "discourse/components/header/icons";
import { clearRegisteredTabs } from "discourse/components/more-topics";
-import { resetWidgetCleanCallbacks } from "discourse/components/mount-widget";
import { resetDecorators as resetPluginOutletDecorators } from "discourse/components/plugin-connector";
import { resetGroupPostSmallActionCodes } from "discourse/components/post/small-action";
import { resetItemSelectCallbacks } from "discourse/components/search-menu/results/assistant-item";
@@ -101,10 +101,6 @@ import {
currentSettings,
mergeSettings,
} from "discourse/tests/helpers/site-settings";
-import { resetPostClassesCallback } from "discourse/widgets/post";
-import { resetDecorators as resetPostCookedDecorators } from "discourse/widgets/post-cooked";
-import { resetPostSmallActionClassesCallbacks } from "discourse/widgets/post-small-action";
-import { resetDecorators } from "discourse/widgets/widget";
import I18n from "discourse-i18n";
import { setupDSelectAssertions } from "./d-select-assertions";
import { setupFormKitAssertions } from "./form-kit-assertions";
@@ -209,8 +205,6 @@ export function testCleanup(container, app) {
clearOutletCache();
clearHTMLCache();
clearRewrites();
- resetDecorators();
- resetPostCookedDecorators();
resetPluginOutletDecorators();
resetUsernameDecorators();
resetOneboxCache();
@@ -265,14 +259,12 @@ export function testCleanup(container, app) {
resetTransformers();
rollbackAllPrepends();
clearAboutPageActivities();
- resetWidgetCleanCallbacks();
clearPluginHeaderActionComponents();
clearRegisteredTabs();
clearAddedTrackedPostProperties();
resetGroupPostSmallActionCodes();
- resetPostSmallActionClassesCallbacks();
- resetPostClassesCallback();
enableClearA11yAnnouncementsInTests();
+ resetHtmlDecorators();
}
function cleanupCssGeneratorTags() {
diff --git a/frontend/discourse/tests/integration/components/decorated-html-test.gjs b/frontend/discourse/tests/integration/components/decorated-html-test.gjs
index 247e1884d08..a0c089d8e55 100644
--- a/frontend/discourse/tests/integration/components/decorated-html-test.gjs
+++ b/frontend/discourse/tests/integration/components/decorated-html-test.gjs
@@ -8,7 +8,7 @@ import { module, test } from "qunit";
import DecoratedHtml from "discourse/components/decorated-html";
import { withSilencedDeprecations } from "discourse/lib/deprecated";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import { POST_STREAM_DEPRECATION_OPTIONS } from "discourse/widgets/widget";
+import { WIDGET_DECOMMISSION_OPTIONS } from "discourse/widgets/widget";
module("Integration | Component | <DecoratedHtml />", function (hooks) {
setupRenderingTest(hooks);
@@ -92,7 +92,7 @@ module("Integration | Component | <DecoratedHtml />", function (hooks) {
const decorateWithStringTarget = (element, helper) => {
element.innerHTML += "<div id='appended'>Appended</div>";
- withSilencedDeprecations(POST_STREAM_DEPRECATION_OPTIONS.id, () => {
+ withSilencedDeprecations(WIDGET_DECOMMISSION_OPTIONS.id, () => {
helper.renderGlimmer(
"div",
<template>
@@ -132,7 +132,7 @@ module("Integration | Component | <DecoratedHtml />", function (hooks) {
const decorateWithHbsTemplate = (element, helper) => {
element.innerHTML += "<div id='appended'>Appended</div>";
- withSilencedDeprecations(POST_STREAM_DEPRECATION_OPTIONS.id, () => {
+ withSilencedDeprecations(WIDGET_DECOMMISSION_OPTIONS.id, () => {
helper.renderGlimmer(
element,
hbs("<div id='render-glimmer'>Hello from Glimmer Component</div>")
diff --git a/frontend/discourse/tests/integration/components/post/actions-summary-test.gjs b/frontend/discourse/tests/integration/components/post/actions-summary-test.gjs
index 039bbca9587..109a61af55f 100644
--- a/frontend/discourse/tests/integration/components/post/actions-summary-test.gjs
+++ b/frontend/discourse/tests/integration/components/post/actions-summary-test.gjs
@@ -12,8 +12,6 @@ module("Integration | Component | Post | PostActionsSummary", function (hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_stream_mode = "enabled";
-
const store = getOwner(this).lookup("service:store");
const topic = store.createRecord("topic", { id: 1 });
const post = store.createRecord("post", {
diff --git a/frontend/discourse/tests/integration/components/post/avatar-test.gjs b/frontend/discourse/tests/integration/components/post/avatar-test.gjs
index 76343a3789f..067e6afd9bc 100644
--- a/frontend/discourse/tests/integration/components/post/avatar-test.gjs
+++ b/frontend/discourse/tests/integration/components/post/avatar-test.gjs
@@ -13,8 +13,6 @@ module("Integration | Component | Post | PostAvatar", function (hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_stream_mode = "enabled";
-
const store = getOwner(this).lookup("service:store");
const topic = store.createRecord("topic", { id: 1 });
const post = store.createRecord("post", {
diff --git a/frontend/discourse/tests/integration/components/post/cooked-html-test.gjs b/frontend/discourse/tests/integration/components/post/cooked-html-test.gjs
index f9d909eea6e..e6c393deee2 100644
--- a/frontend/discourse/tests/integration/components/post/cooked-html-test.gjs
+++ b/frontend/discourse/tests/integration/components/post/cooked-html-test.gjs
@@ -16,8 +16,6 @@ module("Integration | Component | Post | PostCookedHtml", function (hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_stream_mode = "enabled";
-
const store = getOwner(this).lookup("service:store");
const topic = store.createRecord("topic", { id: 1 });
const post = store.createRecord("post", {
diff --git a/frontend/discourse/tests/integration/components/post/meta-data-test.gjs b/frontend/discourse/tests/integration/components/post/meta-data-test.gjs
index 2a3f0faebd1..2fce3969641 100644
--- a/frontend/discourse/tests/integration/components/post/meta-data-test.gjs
+++ b/frontend/discourse/tests/integration/components/post/meta-data-test.gjs
@@ -13,8 +13,6 @@ module("Integration | Component | Post | PostMetaData", function (hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_stream_mode = "enabled";
-
this.store = getOwner(this).lookup("service:store");
const topic = this.store.createRecord("topic", { id: 1 });
const post = this.store.createRecord("post", {
diff --git a/frontend/discourse/tests/integration/components/post/meta-data/edits-indicator-test.gjs b/frontend/discourse/tests/integration/components/post/meta-data/edits-indicator-test.gjs
index 74e89fb8c2a..355760f7e74 100644
--- a/frontend/discourse/tests/integration/components/post/meta-data/edits-indicator-test.gjs
+++ b/frontend/discourse/tests/integration/components/post/meta-data/edits-indicator-test.gjs
@@ -17,8 +17,6 @@ module(
setupRenderingTest(hooks);
hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_stream_mode = "enabled";
-
this.store = getOwner(this).lookup("service:store");
const topic = this.store.createRecord("topic", { id: 1 });
const post = this.store.createRecord("post", {
diff --git a/frontend/discourse/tests/integration/components/post/meta-data/poster-name-test.gjs b/frontend/discourse/tests/integration/components/post/meta-data/poster-name-test.gjs
index e5b9fdc1390..359e103ffbc 100644
--- a/frontend/discourse/tests/integration/components/post/meta-data/poster-name-test.gjs
+++ b/frontend/discourse/tests/integration/components/post/meta-data/poster-name-test.gjs
@@ -15,8 +15,6 @@ module(
setupRenderingTest(hooks);
hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_stream_mode = "enabled";
-
this.store = getOwner(this).lookup("service:store");
const topic = this.store.createRecord("topic", { id: 1 });
const post = this.store.createRecord("post", {
diff --git a/frontend/discourse/tests/integration/components/post/post-links-test.gjs b/frontend/discourse/tests/integration/components/post/post-links-test.gjs
index 19e1a0d13fd..8f36d9c1760 100644
--- a/frontend/discourse/tests/integration/components/post/post-links-test.gjs
+++ b/frontend/discourse/tests/integration/components/post/post-links-test.gjs
@@ -12,8 +12,6 @@ module("Integration | Component | Post | PostLinks", function (hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_stream_mode = "enabled";
-
const store = getOwner(this).lookup("service:store");
const topic = store.createRecord("topic", { id: 1 });
const post = store.createRecord("post", {
diff --git a/frontend/discourse/tests/integration/components/post/post-test.gjs b/frontend/discourse/tests/integration/components/post/post-test.gjs
index 422a2df4328..65827cc1b9b 100644
--- a/frontend/discourse/tests/integration/components/post/post-test.gjs
+++ b/frontend/discourse/tests/integration/components/post/post-test.gjs
@@ -23,24 +23,21 @@ function renderComponent(
unhidePost,
} = {}
) {
- // TODO (glimmer-post-stream) remove the outer div when the post-stream widget is converted to a Glimmer component
return render(
<template>
- <div class="topic-post glimmer-post-stream">
- <Post
- @post={{post}}
- @prevPost={{prevPost}}
- @changePostOwner={{changePostOwner}}
- @editPost={{editPost}}
- @expandHidden={{expandHidden}}
- @permanentlyDeletePost={{permanentlyDeletePost}}
- @rebakePost={{rebakePost}}
- @showHistory={{showHistory}}
- @showRawEmail={{showRawEmail}}
- @togglePostType={{togglePostType}}
- @unhidePost={{unhidePost}}
- />
- </div>
+ <Post
+ @post={{post}}
+ @prevPost={{prevPost}}
+ @changePostOwner={{changePostOwner}}
+ @editPost={{editPost}}
+ @expandHidden={{expandHidden}}
+ @permanentlyDeletePost={{permanentlyDeletePost}}
+ @rebakePost={{rebakePost}}
+ @showHistory={{showHistory}}
+ @showRawEmail={{showRawEmail}}
+ @togglePostType={{togglePostType}}
+ @unhidePost={{unhidePost}}
+ />
<DMenus />
</template>
);
@@ -50,7 +47,6 @@ module("Integration | Component | Post", function (hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_stream_mode = "enabled";
this.siteSettings.post_menu_hidden_items = "";
this.store = getOwner(this).lookup("service:store");
@@ -811,12 +807,9 @@ module("Integration | Component | Post", function (hooks) {
});
test("a11y heading is rendered when post is cloaked", async function (assert) {
- // TODO (glimmer-post-stream) remove the outer div when the post-stream widget is converted to a Glimmer component
await render(
<template>
- <div class="topic-post glimmer-post-stream">
- <Post @post={{this.post}} @cloaked={{true}} />
- </div>
+ <Post @post={{this.post}} @cloaked={{true}} />
<DMenus />
</template>
);
@@ -865,13 +858,10 @@ module("Integration | Component | Post", function (hooks) {
});
// Render both posts
- // TODO (glimmer-post-stream) remove the outer div when the post-stream widget is converted to a Glimmer component
await render(
<template>
- <div class="topic-post glimmer-post-stream">
- <Post @post={{post1}} />
- <Post @post={{post2}} />
- </div>
+ <Post @post={{post1}} />
+ <Post @post={{post2}} />
<DMenus />
</template>
);
diff --git a/frontend/discourse/tests/integration/components/post/small-action-test.gjs b/frontend/discourse/tests/integration/components/post/small-action-test.gjs
index b2222781f94..8b3e87f2dcf 100644
--- a/frontend/discourse/tests/integration/components/post/small-action-test.gjs
+++ b/frontend/discourse/tests/integration/components/post/small-action-test.gjs
@@ -15,8 +15,6 @@ module("Integration | Component | Post | PostSmallAction", function (hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_stream_mode = "enabled";
-
const store = getOwner(this).lookup("service:store");
const topic = store.createRecord("topic", { id: 1 });
const post = store.createRecord("post", {
diff --git a/frontend/discourse/tests/integration/components/widgets/actions-summary-test.gjs b/frontend/discourse/tests/integration/components/widgets/actions-summary-test.gjs
deleted file mode 100644
index 2ba3cc389cb..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/actions-summary-test.gjs
+++ /dev/null
@@ -1,41 +0,0 @@
-import { getOwner } from "@ember/owner";
-import { render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import MountWidget from "discourse/components/mount-widget";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-
-// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
-module("Integration | Component | Widget | actions-summary", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
-
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", { id: 123 });
- const post = store.createRecord("post", {
- id: 1,
- post_number: 2,
- topic,
- deleted_at: "2016-01-01",
- deleted_by: {
- username: "eviltrout",
- avatar_template: "/images/avatar.png",
- },
- });
-
- this.set("post", post);
- });
-
- test("post deleted", async function (assert) {
- const data = { post: this.post };
- await render(
- <template>
- <MountWidget @widget="actions-summary" @args={{data}} />
- </template>
- );
-
- assert.dom(".post-action .d-icon-trash-can").exists("has the deleted icon");
- assert.dom(".avatar[title=eviltrout]").exists("has the deleted by avatar");
- });
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/avatar-flair-test.gjs b/frontend/discourse/tests/integration/components/widgets/avatar-flair-test.gjs
deleted file mode 100644
index 6836cd807f7..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/avatar-flair-test.gjs
+++ /dev/null
@@ -1,44 +0,0 @@
-import { render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import MountWidget from "discourse/components/mount-widget";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-
-module("Integration | Component | Widget | avatar-flair", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
- });
-
- test("avatar flair with an icon", async function (assert) {
- const args = {
- flair_url: "bars",
- flair_bg_color: "CC0000",
- flair_color: "FFFFFF",
- };
-
- await render(
- <template><MountWidget @widget="avatar-flair" @args={{args}} /></template>
- );
-
- assert.dom(".avatar-flair").exists("has the tag");
- assert.dom("svg.d-icon-bars").exists("has the svg icon");
- assert.dom(".avatar-flair").hasStyle({
- backgroundColor: "rgb(204, 0, 0)",
- color: "rgb(255, 255, 255)",
- });
- });
-
- test("avatar flair with an image", async function (assert) {
- const args = {
- flair_url: "/images/avatar.png",
- };
-
- await render(
- <template><MountWidget @widget="avatar-flair" @args={{args}} /></template>
- );
-
- assert.dom(".avatar-flair").exists("has the tag");
- assert.dom("svg").doesNotExist("does not have an svg icon");
- });
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/button-test.gjs b/frontend/discourse/tests/integration/components/widgets/button-test.gjs
deleted file mode 100644
index 97e7a5a96f7..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/button-test.gjs
+++ /dev/null
@@ -1,79 +0,0 @@
-import { render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import MountWidget from "discourse/components/mount-widget";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-
-module("Integration | Component | Widget | button", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
- });
-
- test("icon only button", async function (assert) {
- this.set("args", { icon: "far-face-smile" });
-
- await render(
- <template><MountWidget @widget="button" @args={{this.args}} /></template>
- );
-
- assert.dom("button.btn.btn-icon.no-text").exists("has all the classes");
- assert.dom("button .d-icon.d-icon-far-face-smile").exists("has the icon");
- });
-
- test("icon and text button", async function (assert) {
- this.set("args", { icon: "plus", label: "topic.create" });
-
- await render(
- <template><MountWidget @widget="button" @args={{this.args}} /></template>
- );
-
- assert.dom("button.btn.btn-icon-text").exists("has all the classes");
- assert.dom("button .d-icon.d-icon-plus").exists("has the icon");
- assert.dom("button span.d-button-label").exists("has the label");
- });
-
- test("emoji and text button", async function (assert) {
- this.set("args", { emoji: "mega", label: "topic.create" });
-
- await render(
- <template><MountWidget @widget="button" @args={{this.args}} /></template>
- );
-
- assert.dom("button.widget-button").exists("renders the widget");
- assert.dom("button img.emoji").exists("it renders the emoji");
- assert.dom("button span.d-button-label").exists("it renders the label");
- });
-
- test("translatedLabel", async function (assert) {
- this.set("args", { translatedLabel: "foo bar" });
-
- await render(
- <template><MountWidget @widget="button" @args={{this.args}} /></template>
- );
-
- assert.dom("button span.d-button-label").hasText("foo bar");
- });
-
- test("translatedTitle", async function (assert) {
- this.set("args", { label: "topic.create", translatedTitle: "foo bar" });
-
- await render(
- <template><MountWidget @widget="button" @args={{this.args}} /></template>
- );
-
- assert.dom("button").hasAttribute("title", "foo bar");
- });
-
- test("translatedLabel skips no-text class in icon", async function (assert) {
- this.set("args", { icon: "plus", translatedLabel: "foo bar" });
-
- await render(
- <template><MountWidget @widget="button" @args={{this.args}} /></template>
- );
-
- assert
- .dom("button.btn.btn-icon-text")
- .doesNotHaveClass("no-text", "skips no-text class");
- });
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/post-cooked-test.gjs b/frontend/discourse/tests/integration/components/widgets/post-cooked-test.gjs
deleted file mode 100644
index 69e1997d7c2..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/post-cooked-test.gjs
+++ /dev/null
@@ -1,36 +0,0 @@
-import { render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import MountWidget from "discourse/components/mount-widget";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import DecoratorHelper from "discourse/widgets/decorator-helper";
-import PostCooked from "discourse/widgets/post-cooked";
-import { createWidget } from "discourse/widgets/widget";
-
-// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
-module("Integration | Component | Widget | post-cooked", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
- });
-
- test("quotes with no username and no valid topic", async function (assert) {
- const args = {
- cooked: `<aside class=\"quote no-group quote-post-not-found\" data-post=\"1\" data-topic=\"123456\">\n<blockquote>\n<p>abcd</p>\n</blockquote>\n</aside>\n<p>Testing the issue</p>`,
- };
-
- createWidget("test-widget", {
- html(attrs) {
- return [
- new PostCooked(attrs, new DecoratorHelper(this), this.currentUser),
- ];
- },
- });
-
- await render(
- <template><MountWidget @widget="test-widget" @args={{args}} /></template>
- );
-
- assert.dom("blockquote").hasText("abcd");
- });
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/post-links-test.gjs b/frontend/discourse/tests/integration/components/widgets/post-links-test.gjs
deleted file mode 100644
index 2e4f82f0b6d..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/post-links-test.gjs
+++ /dev/null
@@ -1,91 +0,0 @@
-import { click, render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import MountWidget from "discourse/components/mount-widget";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-
-// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
-module("Integration | Component | Widget | post-links", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
- });
-
- test("duplicate links", async function (assert) {
- const args = {
- id: 2,
- links: [
- {
- title: "Evil Trout Link",
- url: "http://eviltrout.com",
- reflection: true,
- },
- {
- title: "Evil Trout Link",
- url: "http://dupe.eviltrout.com",
- reflection: true,
- },
- ],
- };
-
- await render(
- <template><MountWidget @widget="post-links" @args={{args}} /></template>
- );
-
- assert
- .dom(".post-links a.track-link")
- .exists({ count: 1 }, "hides the dupe link");
- });
-
- test("collapsed links", async function (assert) {
- const args = {
- id: 1,
- links: [
- {
- title: "Link 1",
- url: "http://eviltrout.com?1",
- reflection: true,
- },
- {
- title: "Link 2",
- url: "http://eviltrout.com?2",
- reflection: true,
- },
- {
- title: "Link 3",
- url: "http://eviltrout.com?3",
- reflection: true,
- },
- {
- title: "Link 4",
- url: "http://eviltrout.com?4",
- reflection: true,
- },
- {
- title: "Link 5",
- url: "http://eviltrout.com?5",
- reflection: true,
- },
- {
- title: "Link 6",
- url: "http://eviltrout.com?6",
- reflection: true,
- },
- {
- title: "Link 7",
- url: "http://eviltrout.com?7",
- reflection: true,
- },
- ],
- };
-
- await render(
- <template><MountWidget @widget="post-links" @args={{args}} /></template>
- );
-
- assert.dom(".expand-links").exists({ count: 1 }, "collapsed by default");
-
- await click("a.expand-links");
- assert.dom(".post-links a.track-link").exists({ count: 7 });
- });
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/post-small-action-test.gjs b/frontend/discourse/tests/integration/components/widgets/post-small-action-test.gjs
deleted file mode 100644
index 99b4fb1e480..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/post-small-action-test.gjs
+++ /dev/null
@@ -1,180 +0,0 @@
-import { render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import MountWidget from "discourse/components/mount-widget";
-import { withSilencedDeprecations } from "discourse/lib/deprecated";
-import { withPluginApi } from "discourse/lib/plugin-api";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import { POST_STREAM_DEPRECATION_OPTIONS } from "discourse/widgets/widget";
-import I18n from "discourse-i18n";
-
-// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
-module(
- "Integration | Component | Widget | post-small-action",
- function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_stream_mode = "disabled";
- this.siteSettings.deactivate_widgets_rendering = false;
- });
-
- test("does not have delete/edit/recover buttons by default", async function (assert) {
- this.set("args", { id: 123 });
-
- await render(
- <template>
- <MountWidget @widget="post-small-action" @args={{this.args}} />
- </template>
- );
-
- assert.dom(".small-action-desc .small-action-delete").doesNotExist();
- assert.dom(".small-action-desc .small-action-recover").doesNotExist();
- assert.dom(".small-action-desc .small-action-edit").doesNotExist();
- });
-
- test("shows edit button if canEdit", async function (assert) {
- this.set("args", { id: 123, canEdit: true });
-
- await render(
- <template>
- <MountWidget @widget="post-small-action" @args={{this.args}} />
- </template>
- );
-
- assert
- .dom(".small-action-desc .small-action-edit")
- .exists("adds the edit small action button");
- });
-
- test("uses custom widget if actionDescriptionWidget", async function (assert) {
- this.set("args", { id: 123, actionDescriptionWidget: "button" });
-
- await render(
- <template>
- <MountWidget @widget="post-small-action" @args={{this.args}} />
- </template>
- );
-
- assert
- .dom(".small-action .widget-button")
- .exists("adds the custom widget");
- });
-
- test("does not show edit button if canRecover even if canEdit", async function (assert) {
- this.set("args", { id: 123, canEdit: true, canRecover: true });
-
- await render(
- <template>
- <MountWidget @widget="post-small-action" @args={{this.args}} />
- </template>
- );
-
- assert
- .dom(".small-action-desc .small-action-edit")
- .doesNotExist("does not add the edit small action button");
- assert
- .dom(".small-action-desc .small-action-recover")
- .exists("adds the recover small action button");
- });
-
- test("shows delete button if canDelete", async function (assert) {
- this.set("args", { id: 123, canDelete: true });
-
- await render(
- <template>
- <MountWidget @widget="post-small-action" @args={{this.args}} />
- </template>
- );
-
- assert
- .dom(".small-action-desc .small-action-delete")
- .exists("adds the delete small action button");
- });
-
- test("shows undo button if canRecover", async function (assert) {
- this.set("args", { id: 123, canRecover: true });
-
- await render(
- <template>
- <MountWidget @widget="post-small-action" @args={{this.args}} />
- </template>
- );
-
- assert
- .dom(".small-action-desc .small-action-recover")
- .exists("adds the recover small action button");
- });
-
- test("`addGroupPostSmallActionCode` plugin api", async function (assert) {
- withPluginApi((api) => {
- api.addGroupPostSmallActionCode("some_code");
- });
-
- this.set("args", {
- id: 123,
- actionCode: "some_code",
- actionCodeWho: "somegroup",
- });
-
- I18n.translations[I18n.locale].js.action_codes = {
- some_code: "Some %{who} Code Action",
- };
- await render(
- <template>
- <MountWidget @widget="post-small-action" @args={{this.args}} />
- </template>
- );
- assert
- .dom(".small-action")
- .hasText(
- "Some @somegroup Code Action",
- "the action code text was rendered correctly"
- );
- assert
- .dom("a.mention-group")
- .hasAttribute(
- "href",
- "/g/somegroup",
- "the group mention link has the correct href"
- );
- });
-
- test("`addPostSmallActionClassesCallback` plugin api", async function (assert) {
- withSilencedDeprecations(POST_STREAM_DEPRECATION_OPTIONS.id, () => {
- withPluginApi((api) => {
- api.addPostSmallActionClassesCallback((postAttrs) => {
- if (postAttrs.canRecover) {
- return ["abcde"];
- }
- });
- });
- });
-
- this.set("args", { id: 123, canRecover: false });
-
- await render(
- <template>
- <MountWidget @widget="post-small-action" @args={{this.args}} />
- </template>
- );
-
- assert
- .dom(".abcde")
- .doesNotExist(
- "custom CSS class is not added when condition is not met"
- );
-
- this.set("args", { id: 123, canRecover: true });
-
- await render(
- <template>
- <MountWidget @widget="post-small-action" @args={{this.args}} />
- </template>
- );
-
- assert
- .dom(".abcde")
- .exists("adds custom CSS class as registered from the plugin API");
- });
- }
-);
diff --git a/frontend/discourse/tests/integration/components/widgets/post-stream-test.gjs b/frontend/discourse/tests/integration/components/widgets/post-stream-test.gjs
deleted file mode 100644
index 498bd761c02..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/post-stream-test.gjs
+++ /dev/null
@@ -1,231 +0,0 @@
-import { getOwner } from "@ember/owner";
-import { render } from "@ember/test-helpers";
-import { hbs } from "ember-cli-htmlbars";
-import { module, test } from "qunit";
-import DButton from "discourse/components/d-button";
-import { withSilencedDeprecations } from "discourse/lib/deprecated";
-import { withPluginApi } from "discourse/lib/plugin-api";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-
-function postStreamTest(name, attrs) {
- test(name, async function (assert) {
- this.set("posts", attrs.posts.call(this));
-
- await render(
- hbs`<MountWidget @widget="post-stream" @args={{hash posts=this.posts}} />`
- );
-
- attrs.test.call(this, assert);
- });
-}
-
-["enabled", "disabled"].forEach((postStreamMode) => {
- let lastTransformedPost = null;
-
- module(
- `Integration | Component | Widget | post-stream (glimmer_post_stream_mode = ${postStreamMode})`,
- function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.glimmer_post_stream_mode = postStreamMode;
- this.siteSettings.deactivate_widgets_rendering = false;
- });
-
- const CustomPostMenuButton = <template>
- <DButton
- class="hot-coffee"
- ...attributes
- @icon="mug-saucer"
- @title="coffee.title"
- />
- </template>;
-
- postStreamTest("extensibility", {
- posts() {
- withPluginApi((api) => {
- api.registerValueTransformer(
- "post-menu-buttons",
- ({ value: dag, context: { post, firstButtonKey } }) => {
- dag.add("coffee", CustomPostMenuButton, {
- before: firstButtonKey,
- });
-
- // value transformers shouldn't have side effects
- // we are only doing it below for testing purposes. Do not use strategies like this in the app code
- lastTransformedPost = post;
- }
- );
-
- withSilencedDeprecations(
- "discourse.post-menu-widget-overrides",
- () => {
- api.addPostMenuButton("coffee", (transformedPost) => {
- lastTransformedPost = transformedPost;
-
- return {
- action: "drinkCoffee",
- icon: "mug-saucer",
- className: "hot-coffee",
- title: "coffee.title",
- position: "first",
- };
- });
- }
- );
- });
-
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic");
- topic.set("details.created_by", { id: 123 });
- topic.set("id", 1234);
-
- return [
- store.createRecord("post", {
- topic,
- id: 1,
- post_number: 1,
- user_id: 123,
- primary_group_name: "trout",
- avatar_template: "/images/avatar.png",
- }),
- ];
- },
-
- test(assert) {
- assert.dom(".post-stream").exists({ count: 1 });
- assert.dom(".topic-post").exists({ count: 1 }, "renders all posts");
- assert
- .dom(".topic-post[data-post-number='1'] button.hot-coffee")
- .exists("it transforms posts");
- assert.strictEqual(
- lastTransformedPost.topic.id,
- 1234,
- "it also transforms the topic"
- );
- assert
- .dom(".actions .hot-coffee")
- .exists({ count: 1 }, "has the extended button");
- },
- });
-
- postStreamTest("basics", {
- posts() {
- const site = getOwner(this).lookup("service:site");
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic");
- topic.set("details.created_by", { id: 123 });
-
- return [
- store.createRecord("post", {
- topic,
- id: 1,
- post_number: 1,
- username: "eviltrout",
- user_id: 123,
- primary_group_name: "trout",
- avatar_template: "/images/avatar.png",
- }),
- store.createRecord("post", {
- topic,
- id: 2,
- post_number: 2,
- post_type: site.get("post_types.moderator_action"),
- }),
- store.createRecord("post", {
- topic,
- id: 3,
- post_number: 3,
- hidden: true,
- }),
- store.createRecord("post", {
- topic,
- id: 4,
- post_number: 4,
- post_type: site.get("post_types.whisper"),
- }),
- store.createRecord("post", {
- topic,
- id: 5,
- post_number: 5,
- wiki: true,
- via_email: true,
- }),
- store.createRecord("post", {
- topic,
- id: 6,
- post_number: 6,
- via_email: true,
- is_auto_generated: true,
- }),
- ];
- },
-
- async test(assert) {
- assert.dom(".post-stream").exists({ count: 1 });
- assert.dom(".topic-post").exists({ count: 6 }, "renders all posts");
-
- // look for special class bindings
- assert
- .dom(".topic-post[data-post-number='1'].topic-owner")
- .exists({ count: 1 }, "applies the topic owner class");
- assert
- .dom(".topic-post[data-post-number='1'].group-trout")
- .exists({ count: 1 }, "applies the primary group class");
- assert
- .dom(".topic-post[data-post-number='1'].regular")
- .exists({ count: 1 }, "applies the regular class");
- assert
- .dom(".topic-post[data-post-number='2'].moderator")
- .exists({ count: 1 }, "applies the moderator class");
- assert
- .dom(".topic-post[data-post-number='3'].post-hidden")
- .exists({ count: 1 }, "applies the hidden class");
- assert
- .dom(".topic-post[data-post-number='4'].whisper")
- .exists({ count: 1 }, "applies the whisper class");
- assert
- .dom(".topic-post[data-post-number='5'].wiki")
- .exists({ count: 1 }, "applies the wiki class");
-
- // it renders an article for the body with appropriate attributes
- assert.dom("article#post_2").exists({ count: 1 });
- assert.dom('article[data-user-id="123"]').exists({ count: 1 });
- assert.dom('article[data-post-id="3"]').exists({ count: 1 });
- assert.dom("article#post_5.via-email").exists({ count: 1 });
- assert.dom("article#post_6.is-auto-generated").exists({ count: 1 });
-
- assert
- .dom("article:nth-of-type(1) .main-avatar")
- .exists({ count: 1 }, "renders the main avatar");
- },
- });
-
- postStreamTest("deleted posts", {
- posts() {
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic");
- topic.set("details.created_by", { id: 123 });
-
- return [
- store.createRecord("post", {
- topic,
- id: 1,
- post_number: 1,
- deleted_at: new Date().toString(),
- }),
- ];
- },
-
- test(assert) {
- assert
- .dom(".topic-post.deleted")
- .exists({ count: 1 }, "applies the deleted class");
- assert
- .dom(".deleted-user-avatar")
- .exists({ count: 1 }, "has the trash avatar");
- },
- });
- }
- );
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/post-test.gjs b/frontend/discourse/tests/integration/components/widgets/post-test.gjs
deleted file mode 100644
index 5460a06b92b..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/post-test.gjs
+++ /dev/null
@@ -1,1009 +0,0 @@
-import EmberObject from "@ember/object";
-import { getOwner } from "@ember/owner";
-import { click, render, triggerEvent } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import MountWidget from "discourse/components/mount-widget";
-import DMenus from "discourse/float-kit/components/d-menus";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import { i18n } from "discourse-i18n";
-
-// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
-module("Integration | Component | Widget | post", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
- this.siteSettings.post_menu_hidden_items = "";
-
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", { id: 123 });
- const post = store.createRecord("post", {
- id: 1,
- post_number: 1,
- topic,
- like_count: 3,
- actions_summary: [{ id: 2, count: 1, hidden: false, can_act: true }],
- });
-
- this.set("post", post);
- this.set("args", {});
- });
-
- test("basic elements", async function (assert) {
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", {
- id: 123,
- archetype: "regular",
- });
-
- this.set("args", { shareUrl: "/example", post_number: 1, topic });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".names").exists("includes poster name");
- assert.dom("a.post-date").exists("includes post date");
- });
-
- test("post - links", async function (assert) {
- this.set("args", {
- cooked:
- "<a href='http://link1.example.com/'>first link</a> and <a href='http://link2.example.com/?some=query'>second link</a>",
- linkCounts: [
- { url: "http://link1.example.com/", clicks: 1, internal: true },
- { url: "http://link2.example.com/", clicks: 2, internal: true },
- ],
- });
-
- await render(
- <template>
- <MountWidget
- @widget="post-contents"
- @model={{this.post}}
- @args={{this.args}}
- />
- </template>
- );
-
- assert.dom("a[data-clicks='1']").hasAttribute("data-clicks", "1");
- assert.dom("a[data-clicks='2']").hasAttribute("data-clicks", "2");
- });
-
- test("post - onebox links", async function (assert) {
- this.set("args", {
- cooked: `
- <p><a href="https://example.com">Other URL</a></p>
-
- <aside class="onebox twitterstatus" data-onebox-src="https://twitter.com/codinghorror">
- <header class="source">
- <a href="https://twitter.com/codinghorror" target="_blank" rel="noopener">twitter.com</a>
- </header>
- <article class="onebox-body">
- <h4><a href="https://twitter.com/codinghorror" target="_blank" rel="noopener">Jeff Atwood</a></h4>
- <div class="twitter-screen-name"><a href="https://twitter.com/codinghorror" target="_blank" rel="noopener">@codinghorror</a></div>
- </article>
- </aside>`,
- linkCounts: [
- { url: "https://example.com", clicks: 1 },
- { url: "https://twitter.com/codinghorror", clicks: 2 },
- ],
- });
-
- await render(
- <template>
- <MountWidget
- @widget="post-contents"
- @model={{this.post}}
- @args={{this.args}}
- />
- </template>
- );
-
- assert
- .dom("a[data-clicks='1']")
- .hasAttribute(
- "data-clicks",
- "1",
- "First link has correct data attribute and content"
- );
- assert
- .dom("a[data-clicks='2']")
- .hasAttribute(
- "data-clicks",
- "2",
- "Second link has correct data attribute and content"
- );
- });
-
- test("wiki", async function (assert) {
- this.set("args", { wiki: true, version: 2, canViewEditHistory: true });
- this.set("showHistory", () => (this.historyShown = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @showHistory={{this.showHistory}}
- />
- </template>
- );
-
- await click(".post-info .wiki");
- assert.true(
- this.historyShown,
- "clicking the wiki icon displays the post history"
- );
- });
-
- test("wiki without revision", async function (assert) {
- this.set("args", { wiki: true, version: 1, canViewEditHistory: true });
- this.set("editPost", () => (this.editPostCalled = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @editPost={{this.editPost}}
- />
- </template>
- );
-
- await click(".post-info .wiki");
- assert.true(this.editPostCalled, "clicking wiki icon edits the post");
- });
-
- test("via-email", async function (assert) {
- this.set("args", { via_email: true, canViewRawEmail: true });
- this.set("showRawEmail", () => (this.rawEmailShown = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @showRawEmail={{this.showRawEmail}}
- />
- </template>
- );
-
- await click(".post-info.via-email");
- assert.true(
- this.rawEmailShown,
- "clicking the envelope shows the raw email"
- );
- });
-
- test("via-email without permission", async function (assert) {
- this.rawEmailShown = false;
- this.set("args", { via_email: true, canViewRawEmail: false });
- this.set("showRawEmail", () => (this.rawEmailShown = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @showRawEmail={{this.showRawEmail}}
- />
- </template>
- );
-
- await click(".post-info.via-email");
- assert.false(
- this.rawEmailShown,
- "clicking the envelope doesn't show the raw email"
- );
- });
-
- test("history", async function (assert) {
- this.set("args", { version: 3, canViewEditHistory: true });
- this.set("showHistory", () => (this.historyShown = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @showHistory={{this.showHistory}}
- />
- </template>
- );
-
- await click(".post-info.edits button");
- assert.true(this.historyShown, "clicking the pencil shows the history");
- });
-
- test("history without view permission", async function (assert) {
- this.historyShown = false;
- this.set("args", { version: 3, canViewEditHistory: false });
- this.set("showHistory", () => (this.historyShown = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @showHistory={{this.showHistory}}
- />
- </template>
- );
-
- await click(".post-info.edits");
- assert.false(
- this.historyShown,
- `clicking the pencil doesn't show the history`
- );
- });
-
- test("whisper", async function (assert) {
- this.set("args", { isWhisper: true });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".topic-post.whisper").exists();
- assert.dom(".post-info.whisper").exists();
- });
-
- test(`read indicator`, async function (assert) {
- this.set("args", { read: true });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".read-state.read").exists();
- });
-
- test(`unread indicator`, async function (assert) {
- this.set("args", { read: false });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".read-state").exists();
- });
-
- test("reply directly above (suppressed)", async function (assert) {
- this.set("args", {
- replyToUsername: "eviltrout",
- replyToAvatarTemplate: "/images/avatar.png",
- replyDirectlyAbove: true,
- });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom("a.reply-to-tab").doesNotExist("hides the tab");
- assert.dom(".avoid-tab").doesNotExist("doesn't have the avoid tab class");
- });
-
- test("reply a few posts above (suppressed)", async function (assert) {
- this.set("args", {
- replyToUsername: "eviltrout",
- replyToAvatarTemplate: "/images/avatar.png",
- replyDirectlyAbove: false,
- });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom("a.reply-to-tab").exists("shows the tab");
- assert.dom(".avoid-tab").exists("has the avoid tab class");
- });
-
- test("reply directly above", async function (assert) {
- this.set("args", {
- replyToUsername: "eviltrout",
- replyToAvatarTemplate: "/images/avatar.png",
- replyDirectlyAbove: true,
- });
- this.siteSettings.suppress_reply_directly_above = false;
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".avoid-tab").exists("has the avoid tab class");
- await click("a.reply-to-tab");
- assert.dom("section.embedded-posts.top .cooked").exists();
- assert.dom("section.embedded-posts .d-icon-arrow-up").exists();
- });
-
- test("cooked content hidden", async function (assert) {
- this.set("args", { cooked_hidden: true, canSeeHiddenPost: true });
- this.set("expandHidden", () => (this.unhidden = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @expandHidden={{this.expandHidden}}
- />
- </template>
- );
-
- await click(".topic-body .expand-hidden");
- assert.true(this.unhidden, "triggers the action");
- });
-
- test(`cooked content hidden - can't view hidden post`, async function (assert) {
- this.set("args", { cooked_hidden: true, canSeeHiddenPost: false });
- this.set("expandHidden", () => (this.unhidden = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @expandHidden={{this.expandHidden}}
- />
- </template>
- );
-
- assert
- .dom(".topic-body .expand-hidden")
- .doesNotExist("button is not displayed");
- });
-
- test("expand first post", async function (assert) {
- this.set("args", { expandablePost: true });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- await click(".topic-body .expand-post");
- assert.dom(".expand-post").doesNotExist("button is gone");
- });
-
- test("can't show admin menu when you can't manage", async function (assert) {
- this.set("args", { canManage: false });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".post-menu-area .show-post-admin-menu").doesNotExist();
- });
-
- test("show admin menu", async function (assert) {
- this.currentUser.admin = true;
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- <DMenus />
- </template>
- );
-
- assert
- .dom("[data-content][data-identifier='admin-post-menu']")
- .doesNotExist();
-
- await click(".post-menu-area .show-post-admin-menu");
- assert.dom("[data-content][data-identifier='admin-post-menu']").exists();
-
- await triggerEvent(".post-menu-area", "pointerdown");
- assert
- .dom("[data-content][data-identifier='admin-post-menu']")
- .doesNotExist("clicking outside clears the popup");
- });
-
- test("permanently delete topic", async function (assert) {
- this.currentUser.set("admin", true);
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", {
- id: 123,
- details: { can_permanently_delete: true },
- });
- const post = store.createRecord("post", {
- id: 1,
- post_number: 1,
- deleted_at: new Date().toISOString(),
- topic,
- });
-
- this.set("args", { canManage: true });
- this.set("post", post);
- this.set("permanentlyDeletePost", () => (this.deleted = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @permanentlyDeletePost={{this.permanentlyDeletePost}}
- />
- <DMenus />
- </template>
- );
-
- await click(".post-menu-area .show-post-admin-menu");
- await click(
- "[data-content][data-identifier='admin-post-menu'] .permanently-delete"
- );
- assert.true(this.deleted);
- assert
- .dom("[data-content][data-identifier='admin-post-menu']")
- .doesNotExist("also hides the menu");
- });
-
- test("permanently delete post", async function (assert) {
- this.currentUser.set("admin", true);
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", {
- id: 123,
- });
- const post = store.createRecord("post", {
- id: 1,
- post_number: 2,
- deleted_at: new Date().toISOString(),
- can_permanently_delete: true,
- topic,
- });
-
- this.set("args", { canManage: true });
- this.set("post", post);
- this.set("permanentlyDeletePost", () => (this.deleted = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @permanentlyDeletePost={{this.permanentlyDeletePost}}
- />
- <DMenus />
- </template>
- );
-
- await click(".post-menu-area .show-post-admin-menu");
-
- await click(
- "[data-content][data-identifier='admin-post-menu'] .permanently-delete"
- );
- assert.true(this.deleted);
- assert
- .dom("[data-content][data-identifier='admin-post-menu']")
- .doesNotExist("also hides the menu");
- });
-
- test("toggle moderator post", async function (assert) {
- this.currentUser.set("moderator", true);
-
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", {
- id: 123,
- });
- const post = store.createRecord("post", {
- id: 1,
- post_number: 2,
- deleted_at: new Date().toISOString(),
- can_permanently_delete: true,
- topic,
- });
-
- this.set("args", { canManage: true });
- this.set("post", post);
- this.set("togglePostType", () => (this.toggled = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @togglePostType={{this.togglePostType}}
- />
- <DMenus />
- </template>
- );
-
- await click(".post-menu-area .show-post-admin-menu");
- await click(
- "[data-content][data-identifier='admin-post-menu'] .toggle-post-type"
- );
-
- assert.true(this.toggled);
- assert
- .dom("[data-content][data-identifier='admin-post-menu']")
- .doesNotExist("also hides the menu");
- });
-
- test("rebake post", async function (assert) {
- this.currentUser.moderator = true;
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", { id: 123 });
- const post = store.createRecord("post", {
- id: 1,
- post_number: 1,
- topic,
- });
-
- this.set("args", { canManage: true });
- this.set("post", post);
- this.set("rebakePost", () => (this.baked = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @rebakePost={{this.rebakePost}}
- />
- <DMenus />
- </template>
- );
-
- await click(".post-menu-area .show-post-admin-menu");
- await click(
- "[data-content][data-identifier='admin-post-menu'] .rebuild-html"
- );
- assert.true(this.baked);
- assert
- .dom("[data-content][data-identifier='admin-post-menu']")
- .doesNotExist("also hides the menu");
- });
-
- test("unhide post", async function (assert) {
- let unhidden;
-
- this.currentUser.admin = true;
- this.post.hidden = true;
- this.set("args", { canManage: true });
- this.set("unhidePost", () => (unhidden = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @unhidePost={{this.unhidePost}}
- />
- <DMenus />
- </template>
- );
-
- await click(".post-menu-area .show-post-admin-menu");
-
- await click(
- "[data-content][data-identifier='admin-post-menu'] .unhide-post"
- );
-
- assert.true(unhidden);
-
- assert
- .dom("[data-content][data-identifier='admin-post-menu']")
- .doesNotExist("also hides the menu");
- });
-
- test("change owner", async function (assert) {
- this.currentUser.admin = true;
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", { id: 123 });
- const post = store.createRecord("post", {
- id: 1,
- post_number: 1,
- hidden: true,
- topic,
- });
-
- this.set("args", { canManage: true });
- this.set("post", post);
- this.set("changePostOwner", () => (this.owned = true));
-
- await render(
- <template>
- <MountWidget
- @widget="post"
- @model={{this.post}}
- @args={{this.args}}
- @changePostOwner={{this.changePostOwner}}
- />
- <DMenus />
- </template>
- );
-
- await click(".post-menu-area .show-post-admin-menu");
- await click(
- "[data-content][data-identifier='admin-post-menu'] .change-owner"
- );
- assert.true(this.owned);
- assert
- .dom("[data-content][data-identifier='admin-post-menu']")
- .doesNotExist("also hides the menu");
- });
-
- test("shows the topic map when setting the 'topicMap' attribute", async function (assert) {
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", { id: 123 });
- this.set("args", { topic, post_number: 1, topicMap: true });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".topic-map").exists();
- });
-
- test("shows the topic map when no replies", async function (assert) {
- this.siteSettings.show_topic_map_in_topics_without_replies = true;
-
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", {
- id: 123,
- archetype: "regular",
- });
- this.set("args", { topic, post_number: 1 });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".topic-map").exists();
- });
-
- test("topic map - few participants", async function (assert) {
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", {
- id: 123,
- posts_count: 10,
- participant_count: 2,
- archetype: "regular",
- });
- topic.details.set("participants", [
- { username: "eviltrout" },
- { username: "codinghorror" },
- ]);
- this.set("args", {
- topic,
- post_number: 1,
- });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
- assert.dom(".topic-map__users-trigger").doesNotExist();
- assert.dom(".topic-map__users-list a.poster").exists({ count: 2 });
- });
-
- test("topic map - participants", async function (assert) {
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", {
- id: 123,
- posts_count: 10,
- participant_count: 6,
- archetype: "regular",
- });
- topic.postStream.setProperties({ userFilters: ["sam", "codinghorror"] });
- topic.details.set("participants", [
- { username: "eviltrout" },
- { username: "codinghorror" },
- { username: "sam" },
- { username: "zogstrip" },
- { username: "joffreyjaffeux" },
- { username: "david" },
- ]);
-
- this.set("args", {
- topic,
- post_number: 1,
- });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
- assert.dom(".topic-map__users-list a.poster").exists({ count: 5 });
-
- await click(".topic-map__users-trigger");
- assert
- .dom(".topic-map__users-content .topic-map__users-list a.poster")
- .exists({ count: 6 });
- });
-
- test("topic map - links", async function (assert) {
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", {
- id: 123,
- posts_count: 2,
- archetype: "regular",
- });
- topic.details.set("links", [
- { url: "http://link1.example.com", clicks: 0 },
- { url: "http://link2.example.com", clicks: 0 },
- { url: "http://link3.example.com", clicks: 0 },
- { url: "http://link4.example.com", clicks: 0 },
- { url: "http://link5.example.com", clicks: 0 },
- { url: "http://link6.example.com", clicks: 0 },
- ]);
- this.set("args", { topic, post_number: 1 });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".topic-map").exists({ count: 1 });
- assert.dom(".topic-map__links-content").doesNotExist();
- await click(".topic-map__links-trigger");
- assert.dom(".topic-map__links-content").exists({ count: 1 });
- assert.dom(".topic-map__links-content .topic-link").exists({ count: 5 });
- await click(".link-summary");
- assert.dom(".topic-map__links-content .topic-link").exists({ count: 6 });
- });
-
- test("topic map - has top replies summary", async function (assert) {
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", {
- id: 123,
- archetype: "regular",
- posts_count: 2,
- has_summary: true,
- });
- this.set("args", { topic, post_number: 1 });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".summarization-button .top-replies").exists({ count: 1 });
- });
-
- test("topic map - no top reply summary", async function (assert) {
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", {
- id: 123,
- archetype: "regular",
- posts_count: 2,
- });
- this.set("args", { topic, post_number: 1 });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".topic-map").exists();
- assert.dom(".summarization-button .top-replies").doesNotExist();
- });
-
- test("pm map", async function (assert) {
- const store = getOwner(this).lookup("service:store");
- const topic = store.createRecord("topic", {
- id: 123,
- archetype: "private_message",
- });
- topic.details.set("allowed_users", [
- EmberObject.create({ username: "eviltrout" }),
- ]);
- this.set("args", {
- topic,
- post_number: 1,
- });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".topic-map__private-message-map").exists({ count: 1 });
- assert.dom(".topic-map__private-message-map .user").exists({ count: 1 });
- });
-
- test("post notice - with username", async function (assert) {
- const twoDaysAgo = new Date();
- twoDaysAgo.setDate(twoDaysAgo.getDate() - 2);
- this.siteSettings.display_name_on_posts = false;
- this.siteSettings.prioritize_username_in_ux = true;
- this.siteSettings.old_post_notice_days = 14;
- this.set("args", {
- username: "codinghorror",
- name: "Jeff",
- created_at: new Date(),
- notice: {
- type: "returning_user",
- lastPostedAt: twoDaysAgo,
- },
- });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".post-notice.returning-user:not(.old)").hasText(
- i18n("post.notice.returning_user", {
- user: "codinghorror",
- time: "2 days ago",
- })
- );
- });
-
- test("post notice - custom official notice with created by username", async function (assert) {
- this.siteSettings.display_name_on_posts = false;
- this.siteSettings.prioritize_username_in_ux = true;
- this.set("args", {
- notice: {
- type: "custom",
- cooked: "<p>This is an official notice</p>",
- },
- noticeCreatedByUser: {
- username: "codinghorror",
- name: "Jeff",
- id: 1,
- },
- });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".post-notice.custom").hasText(
- "This is an official notice " +
- i18n("post.notice.custom_created_by", {
- userLinkHTML: "codinghorror",
- })
- );
-
- assert
- .dom(
- ".post-notice.custom .post-notice-message a.trigger-user-card[data-user-card='codinghorror']"
- )
- .exists();
- });
-
- test("post notice - with name", async function (assert) {
- this.siteSettings.display_name_on_posts = true;
- this.siteSettings.prioritize_username_in_ux = false;
- this.siteSettings.old_post_notice_days = 14;
- this.set("args", {
- username: "codinghorror",
- name: "Jeff",
- created_at: new Date(2019, 0, 1),
- notice: { type: "new_user" },
- });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert
- .dom(".post-notice.old.new-user")
- .hasText(i18n("post.notice.new_user", { user: "Jeff", time: "Jan '10" }));
- });
-
- test("show group request in post", async function (assert) {
- this.set("args", {
- username: "foo",
- requestedGroupName: "testGroup",
- });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".group-request a").hasText(i18n("groups.requests.handle"));
- assert
- .dom(".group-request a")
- .hasAttribute("href", "/g/testGroup/requests?filter=foo");
- });
-
- test("shows user status if enabled in site settings", async function (assert) {
- this.siteSettings.enable_user_status = true;
- const status = {
- emoji: "tooth",
- description: "off to dentist",
- };
- const store = getOwner(this).lookup("service:store");
- const user = store.createRecord("user", { status });
- this.set("args", { user });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".user-status-message").exists();
- });
-
- test("doesn't show user status if disabled in site settings", async function (assert) {
- this.siteSettings.enable_user_status = false;
- const status = {
- emoji: "tooth",
- description: "off to dentist",
- };
- const store = getOwner(this).lookup("service:store");
- const user = store.createRecord("user", { status });
- this.set("args", { user });
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
-
- assert.dom(".user-status-message").doesNotExist();
- });
-
- test("more actions button is displayed when multiple hidden items are configured", async function (assert) {
- this.siteSettings.post_menu_hidden_items = "bookmark|edit|copyLink";
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
- assert.dom(".show-more-actions").exists();
- });
-
- test("hidden menu expands automatically when only one hidden item is configured", async function (assert) {
- this.siteSettings.post_menu_hidden_items = "bookmark|edit";
-
- await render(
- <template>
- <MountWidget @widget="post" @model={{this.post}} @args={{this.args}} />
- </template>
- );
- assert.dom(".show-more-actions").doesNotExist();
- });
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/poster-name-test.gjs b/frontend/discourse/tests/integration/components/widgets/poster-name-test.gjs
deleted file mode 100644
index 3974e40f8ad..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/poster-name-test.gjs
+++ /dev/null
@@ -1,115 +0,0 @@
-import { render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import MountWidget from "discourse/components/mount-widget";
-import Badge from "discourse/models/badge";
-import User from "discourse/models/user";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-
-// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
-module("Integration | Component | Widget | poster-name", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
- this.siteSettings.glimmer_post_stream_mode = "disabled";
- });
-
- test("basic rendering", async function (assert) {
- const args = {
- username: "eviltrout",
- usernameUrl: "/u/eviltrout",
- name: "Robin Ward",
- user_title: "Trout Master",
- };
-
- await render(
- <template><MountWidget @widget="poster-name" @args={{args}} /></template>
- );
-
- assert.dom(".names").exists();
- assert.dom("span.username").exists();
- assert.dom('a[data-user-card="eviltrout"]').exists();
- assert.dom(".username a").hasText("eviltrout");
- assert.dom(".user-title").hasText("Trout Master");
- });
-
- test("extra classes and glyphs", async function (assert) {
- const args = {
- username: "eviltrout",
- usernameUrl: "/u/eviltrout",
- staff: true,
- admin: true,
- moderator: true,
- new_user: true,
- primary_group_name: "fish",
- };
-
- await render(
- <template><MountWidget @widget="poster-name" @args={{args}} /></template>
- );
-
- assert.dom("span.staff").exists();
- assert.dom("span.admin").exists();
- assert.dom("span.moderator").exists();
- assert.dom(".d-icon-shield-halved").exists();
- assert.dom("span.new-user").exists();
- assert.dom("span.group--fish").exists();
- });
-
- test("disable display name on posts", async function (assert) {
- this.siteSettings.display_name_on_posts = false;
- const args = { username: "eviltrout", name: "Robin Ward" };
-
- await render(
- <template><MountWidget @widget="poster-name" @args={{args}} /></template>
- );
-
- assert.dom(".full-name").doesNotExist();
- });
-
- test("doesn't render a name if it's similar to the username", async function (assert) {
- this.siteSettings.prioritize_username_in_ux = true;
- this.siteSettings.display_name_on_posts = true;
- const args = { username: "eviltrout", name: "evil-trout" };
-
- await render(
- <template><MountWidget @widget="poster-name" @args={{args}} /></template>
- );
-
- assert.dom(".second").doesNotExist();
- });
-
- test("renders badges that are passed in", async function (assert) {
- const args = {
- username: "eviltrout",
- usernameUrl: "/u/eviltrout",
- user: User.create({
- username: "eviltrout",
- }),
- badgesGranted: [
- { id: 1, icon: "heart", slug: "badge1", name: "Badge One" },
- { id: 2, icon: "target", slug: "badge2", name: "Badge Two" },
- ].map((badge) => Badge.createFromJson({ badges: [badge] })[0]),
- };
-
- await render(
- <template><MountWidget @widget="poster-name" @args={{args}} /></template>
- );
-
- // Check that the custom CSS classes are set
- assert.dom("span.user-badge-button-badge1").exists();
- assert.dom("span.user-badge-button-badge2").exists();
-
- // Check that the custom titles are set
- assert.dom("span.user-badge[title*='Badge One']").exists();
- assert.dom("span.user-badge[title*='Badge Two']").exists();
-
- // Check that the badges link to the correct badge page
- assert
- .dom("a.user-card-badge-link[href='/badges/1/badge1?username=eviltrout']")
- .exists();
- assert
- .dom("a.user-card-badge-link[href='/badges/2/badge2?username=eviltrout']")
- .exists();
- });
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/render-glimmer-test.js b/frontend/discourse/tests/integration/components/widgets/render-glimmer-test.js
deleted file mode 100644
index 43358b249b7..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/render-glimmer-test.js
+++ /dev/null
@@ -1,369 +0,0 @@
-/* eslint-disable ember/no-classic-components */
-import ClassicComponent, { setComponentTemplate } from "@ember/component";
-import templateOnly from "@ember/component/template-only";
-import { click, fillIn, render } from "@ember/test-helpers";
-import { hbs } from "ember-cli-htmlbars";
-import { module, test } from "qunit";
-import { bind } from "discourse/lib/decorators";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import widgetHbs from "discourse/widgets/hbs-compiler";
-import RenderGlimmer, {
- registerWidgetShim,
-} from "discourse/widgets/render-glimmer";
-import Widget, { deleteFromRegistry } from "discourse/widgets/widget";
-
-class DemoWidget extends Widget {
- static actionTriggered = false;
- tagName = "div.my-widget";
-
- buildKey() {
- return "abc";
- }
-
- defaultState() {
- return {
- actionTriggered: false,
- };
- }
-
- html(attrs, state) {
- return [
- this.attach("button", {
- label: "rerender",
- className: "triggerRerender",
- action: "dummyAction",
- }),
- new RenderGlimmer(
- this,
- "div.glimmer-wrapper",
- hbs`<div class='glimmer-content'>
- arg1={{@data.arg1}} dynamicArg={{@data.dynamicArg}}
- </div>
- <DemoComponent @arg1={{@data.arg1}} @dynamicArg={{@data.dynamicArg}} @action={{@data.actionForComponentToTrigger}} @widgetActionTriggered={{@data.widgetActionTriggered}}/>`,
- {
- ...attrs,
- actionForComponentToTrigger: this.actionForComponentToTrigger,
- widgetActionTriggered: state.actionTriggered,
- }
- ),
- ];
- }
-
- dummyAction() {}
-
- @bind
- actionForComponentToTrigger() {
- this.state.actionTriggered = true;
- DemoWidget.actionTriggered = true;
- this.scheduleRerender();
- }
-}
-
-class DemoComponent extends ClassicComponent {
- static eventLog = [];
- classNames = ["demo-component"];
- layout = hbs`<DButton class="component-action-button" @label="component_action" @action={{@action}} /><p class='action-state'>{{@widgetActionTriggered}}</p>`;
-
- init() {
- DemoComponent.eventLog.push("init");
- super.init(...arguments);
- }
-
- willDestroy() {
- super.willDestroy(...arguments);
- DemoComponent.eventLog.push("willDestroy");
- }
-
- didInsertElement() {
- super.didInsertElement(...arguments);
- DemoComponent.eventLog.push("didInsertElement");
- }
-
- willDestroyElement() {
- super.willDestroyElement(...arguments);
- DemoComponent.eventLog.push("willDestroyElement");
- }
-
- didReceiveAttrs() {
- super.didReceiveAttrs(...arguments);
- DemoComponent.eventLog.push("didReceiveAttrs");
- }
-}
-
-class ToggleDemoWidget extends Widget {
- static actionTriggered = false;
- tagName = "div.my-widget";
-
- buildKey() {
- return "abc";
- }
-
- defaultState() {
- return {
- showOne: true,
- };
- }
-
- html(attrs, state) {
- const output = [
- this.attach("button", {
- label: "toggle",
- className: "toggleButton",
- action: "toggleComponent",
- }),
- ];
- if (state.showOne) {
- output.push(new RenderGlimmer(this, "div.glimmer-wrapper", hbs`One`, {}));
- } else {
- output.push(new RenderGlimmer(this, "div.glimmer-wrapper", hbs`Two`, {}));
- }
- return output;
- }
-
- toggleComponent() {
- this.state.showOne = !this.state.showOne;
- }
-}
-
-const SimpleComponent = templateOnly();
-setComponentTemplate(hbs`<div class="component-shim"></div>`, SimpleComponent);
-
-module("Integration | Component | Widget | render-glimmer", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
-
- DemoComponent.eventLog = [];
- DemoWidget.actionTriggered = false;
- this.registry.register("widget:demo-widget", DemoWidget);
- this.registry.register("widget:toggle-demo-widget", ToggleDemoWidget);
- this.registry.register("component:demo-component", DemoComponent);
- registerWidgetShim(
- "render-glimmer-test-shim",
- "div.my-wrapper",
- hbs`<span class='shim-content'>{{@data.attr1}}</span>`
- );
- registerWidgetShim(
- "render-glimmer-test-wrapper-attrs",
- "div.initial-wrapper-class",
- hbs`{{@setWrapperElementAttrs class=(concat-class "static-extra-class" @data.extraClass) [email protected]}}`
- );
- registerWidgetShim(
- "render-glimmer-test-component-shim",
- "div.initial-wrapper-class",
- SimpleComponent
- );
- });
-
- hooks.afterEach(function () {
- this.registry.unregister("widget:demo-widget");
- this.registry.unregister("widget:toggle-demo-widget");
- this.registry.unregister("component:demo-component");
- deleteFromRegistry("render-glimmer-test-shim");
- deleteFromRegistry("render-glimmer-test-wrapper-attrs");
- deleteFromRegistry("render-glimmer-test-component-shim");
- });
-
- test("argument handling", async function (assert) {
- await render(
- hbs`
- <Input class='dynamic-value-input' @type="text" @value={{this.dynamicValue}} />
- <MountWidget @widget="demo-widget" @args={{hash arg1="val1" dynamicArg=this.dynamicValue}} />`
- );
-
- assert.dom("div.my-widget").exists("widget is rendered");
- assert.dom("div.glimmer-content").exists("glimmer content is rendered");
- assert
- .dom("div.glimmer-content")
- .hasText("arg1=val1 dynamicArg=", "arguments are passed through");
-
- await fillIn("input.dynamic-value-input", "somedynamicvalue");
- await click(".my-widget button");
- assert
- .dom("div.glimmer-content")
- .hasText(
- "arg1=val1 dynamicArg=somedynamicvalue",
- "changed arguments are applied after rerender"
- );
- });
-
- test("child component lifecycle", async function (assert) {
- assert.deepEqual(
- DemoComponent.eventLog,
- [],
- "component event log starts empty"
- );
-
- await render(
- hbs`
- <Input class='dynamic-value-input' @type="text" @value={{this.dynamicValue}} />
- {{#unless (eq this.dynamicValue 'hidden')}}
- <MountWidget @widget="demo-widget" @args={{hash arg1="val1" dynamicArg=this.dynamicValue}} />
- {{/unless}}`
- );
-
- assert.dom("div.my-widget").exists("widget is rendered");
- assert.dom("div.glimmer-content").exists("glimmer content is rendered");
- assert.dom("div.demo-component").exists("demo component is rendered");
-
- assert.deepEqual(
- DemoComponent.eventLog,
- ["init", "didReceiveAttrs", "didInsertElement"],
- "component is initialized correctly"
- );
-
- DemoComponent.eventLog = [];
-
- await fillIn("input.dynamic-value-input", "somedynamicvalue");
- await click(".my-widget button");
- assert.deepEqual(
- DemoComponent.eventLog,
- ["didReceiveAttrs", "didReceiveAttrs"], // once for input, once for event
- "component is notified of attr change during widget rerender"
- );
-
- DemoComponent.eventLog = [];
-
- await fillIn("input.dynamic-value-input", "hidden");
- assert.deepEqual(
- DemoComponent.eventLog,
- ["willDestroyElement", "willDestroy"],
- "destroy hooks are run correctly"
- );
-
- DemoComponent.eventLog = [];
-
- await fillIn("input.dynamic-value-input", "visibleAgain");
- assert.deepEqual(
- DemoComponent.eventLog,
- ["init", "didReceiveAttrs", "didInsertElement"],
- "component can be reinitialized"
- );
- });
-
- test("rendering component directly", async function (assert) {
- await render(hbs`
- <MountWidget @widget="render-glimmer-test-component-shim" />
- `);
-
- assert.dom("div.component-shim").exists();
- });
-
- test("trigger widget actions from component", async function (assert) {
- assert.false(
- DemoWidget.actionTriggered,
- "widget event has not been triggered yet"
- );
-
- await render(
- hbs`
- <Input class='dynamic-value-input' @type="text" @value={{this.dynamicValue}} />
- {{#unless (eq this.dynamicValue 'hidden')}}
- <MountWidget @widget="demo-widget" @args={{hash arg1="val1" dynamicArg=this.dynamicValue}} />
- {{/unless}}`
- );
-
- assert
- .dom("div.demo-component button")
- .exists("component button is rendered");
-
- await click("div.demo-component button");
- assert.true(DemoWidget.actionTriggered, "widget event is triggered");
- });
-
- test("modify widget state with component action", async function (assert) {
- await render(
- hbs`<MountWidget @widget="demo-widget" @args={{hash arg1="val1"}} />`
- );
-
- assert.false(
- DemoWidget.actionTriggered,
- "widget event has not been triggered yet"
- );
-
- assert
- .dom(".action-state")
- .hasText("false", "eventTriggered is false in nested component");
-
- assert
- .dom("div.demo-component button")
- .exists("component button is rendered");
-
- await click("div.demo-component button");
- assert.true(DemoWidget.actionTriggered, "widget event is triggered");
-
- assert
- .dom(".action-state")
- .hasText("true", "eventTriggered is true in nested component");
- });
-
- test("developer ergonomics", function (assert) {
- assert.throws(
- () => {
- // eslint-disable-next-line no-new
- new RenderGlimmer(this, "div", `<NotActuallyATemplate />`);
- },
- /`template` should be a template compiled via `ember-cli-htmlbars`/,
- "it raises a useful error when passed a string instead of a template"
- );
-
- assert.throws(
- () => {
- // eslint-disable-next-line no-new
- new RenderGlimmer(this, "div", widgetHbs`{{using-the-wrong-compiler}}`);
- },
- /`template` should be a template compiled via `ember-cli-htmlbars`/,
- "it raises a useful error when passed a widget-hbs-compiler template"
- );
-
- // eslint-disable-next-line no-new
- new RenderGlimmer(this, "div", hbs`<TheCorrectCompiler />`);
- assert.true(true, "it doesn't raise an error for correct params");
- });
-
- test("multiple adjacent components", async function (assert) {
- await render(hbs`<MountWidget @widget="toggle-demo-widget" />`);
- assert.dom("div.glimmer-wrapper").hasText("One");
- await click(".toggleButton");
- assert.dom("div.glimmer-wrapper").hasText("Two");
- await click(".toggleButton");
- assert.dom("div.glimmer-wrapper").hasText("One");
- });
-
- test("registerWidgetShim can register a fake widget", async function (assert) {
- await render(
- hbs`<MountWidget @widget="render-glimmer-test-shim" @args={{hash attr1="val1"}} />`
- );
-
- assert.dom("div.my-wrapper span.shim-content").exists();
- assert.dom("div.my-wrapper span.shim-content").hasText("val1");
- });
-
- test("setWrapperElementAttrs API", async function (assert) {
- await render(
- hbs`<MountWidget @widget="render-glimmer-test-wrapper-attrs" @args={{hash extraClass=this.extraClass dataAttrValue=this.dataAttrValue}} />`
- );
-
- assert.dom("div.initial-wrapper-class").exists();
- assert
- .dom("div.initial-wrapper-class")
- .hasAttribute("class", "initial-wrapper-class static-extra-class");
- assert
- .dom("div.initial-wrapper-class")
- .doesNotHaveAttribute("data-some-attr");
-
- this.set("extraClass", "dynamic-extra-class");
- this.set("dataAttrValue", "hello world");
-
- assert
- .dom("div.initial-wrapper-class")
- .hasAttribute(
- "class",
- "initial-wrapper-class static-extra-class dynamic-extra-class"
- );
- assert
- .dom("div.initial-wrapper-class")
- .hasAttribute("data-some-attr", "hello world");
- });
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/small-user-list-test.gjs b/frontend/discourse/tests/integration/components/widgets/small-user-list-test.gjs
deleted file mode 100644
index 703cdc52a93..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/small-user-list-test.gjs
+++ /dev/null
@@ -1,33 +0,0 @@
-import { render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import MountWidget from "discourse/components/mount-widget";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-
-// TODO (glimmer-post-stream) remove this test when removing the widget post stream code
-module("Integration | Component | Widget | small-user-list", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
- });
-
- test("renders avatars and support for unknown", async function (assert) {
- const args = {
- users: [
- { id: 456, username: "eviltrout" },
- { id: 457, username: "someone", unknown: true },
- ],
- isVisible: true,
- };
-
- await render(
- <template>
- <MountWidget @widget="small-user-list" @args={{args}} />
- </template>
- );
-
- assert.dom('[data-user-card="eviltrout"]').exists({ count: 1 });
- assert.dom('[data-user-card="someone"]').doesNotExist();
- assert.dom(".unknown").exists("includes unknown user");
- });
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/topic-status-test.gjs b/frontend/discourse/tests/integration/components/widgets/topic-status-test.gjs
deleted file mode 100644
index ee87998f209..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/topic-status-test.gjs
+++ /dev/null
@@ -1,57 +0,0 @@
-import { getOwner } from "@ember/owner";
-import { click, render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import MountWidget from "discourse/components/mount-widget";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-
-module("Integration | Component | Widget | topic-status", function (hooks) {
- setupRenderingTest(hooks);
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
- });
-
- test("basics", async function (assert) {
- const store = getOwner(this).lookup("service:store");
- const args = {
- topic: store.createRecord("topic", { closed: true }),
- disableActions: true,
- };
-
- await render(
- <template><MountWidget @widget="topic-status" @args={{args}} /></template>
- );
-
- assert.dom(".topic-status [class*='d-icon-topic.closed']").exists();
- });
-
- test("toggling pin status", async function (assert) {
- const store = getOwner(this).lookup("service:store");
- const args = {
- topic: store.createRecord("topic", { closed: true, pinned: true }),
- };
-
- await render(
- <template><MountWidget @widget="topic-status" @args={{args}} /></template>
- );
-
- assert.dom(".topic-statuses .pinned").exists("pinned icon is shown");
- assert
- .dom(".topic-statuses .unpinned")
- .doesNotExist("unpinned icon is not shown");
-
- await click(".topic-statuses a.pin-toggle-button");
-
- assert
- .dom(".topic-statuses .pinned")
- .doesNotExist("pinned icon is not shown");
- assert.dom(".topic-statuses .unpinned").exists("unpinned icon is shown");
-
- await click(".topic-statuses a.pin-toggle-button");
-
- assert.dom(".topic-statuses .pinned").exists("pinned icon is shown");
- assert
- .dom(".topic-statuses .unpinned")
- .doesNotExist("unpinned icon is not shown");
- });
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/widget-dropdown-test.gjs b/frontend/discourse/tests/integration/components/widgets/widget-dropdown-test.gjs
deleted file mode 100644
index f666d68945b..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/widget-dropdown-test.gjs
+++ /dev/null
@@ -1,519 +0,0 @@
-import { hash } from "@ember/helper";
-import { click, render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import MountWidget from "discourse/components/mount-widget";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import I18n from "discourse-i18n";
-
-const DEFAULT_CONTENT = {
- content: [
- { id: 1, label: "foo" },
- { id: 2, translatedLabel: "FooBar" },
- "separator",
- { id: 3, translatedLabel: "With icon", icon: "xmark" },
- { id: 4, html: "<b>baz</b>" },
- { id: 5, translatedLabel: "Disabled", disabled: true },
- ],
- label: "foo",
-};
-
-module("Integration | Component | Widget | widget-dropdown", function (hooks) {
- setupRenderingTest(hooks);
-
- let _translations = I18n.translations;
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
- });
-
- hooks.afterEach(function () {
- I18n.translations = _translations;
- });
-
- test("dropdown id", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- assert.dom("#my-dropdown").exists();
- });
-
- test("label", async function (assert) {
- I18n.translations = { en: { js: { foo: "FooBaz" } } };
- this.setProperties(DEFAULT_CONTENT);
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- assert.dom("#my-dropdown .widget-dropdown-header .label").hasText("FooBaz");
- });
-
- test("translatedLabel", async function (assert) {
- I18n.translations = { en: { js: { foo: "FooBaz" } } };
- this.setProperties(DEFAULT_CONTENT);
- this.set("translatedLabel", "BazFoo");
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- assert.dom("#my-dropdown .widget-dropdown-header .label").hasText("BazFoo");
- });
-
- test("content", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- await click("#my-dropdown .widget-dropdown-header");
- assert
- .dom("#my-dropdown .widget-dropdown-item.item-1")
- .hasAttribute("data-id", "1", "creates rows");
- assert
- .dom("#my-dropdown .widget-dropdown-item.item-2")
- .hasAttribute("data-id", "2", "creates rows");
- assert
- .dom("#my-dropdown .widget-dropdown-item.item-3")
- .hasAttribute("data-id", "3", "creates rows");
- });
-
- test("onChange action", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
- this.set("onChange", (item) => assert.step(`${item.id}`));
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- label=this.label
- content=this.content
- onChange=this.onChange
- }}
- />
- </template>
- );
-
- await click("#my-dropdown .widget-dropdown-header");
- await click("#my-dropdown .widget-dropdown-item.item-2");
- assert.verifySteps(["2"], "calls the onChange actions");
- });
-
- test("can be opened and closed", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- assert.dom("#my-dropdown.closed").exists();
- assert.dom("#my-dropdown .widget-dropdown-body").doesNotExist();
- await click("#my-dropdown .widget-dropdown-header");
- assert.dom("#my-dropdown .widget-dropdown-item.item-2").hasText("FooBar");
- assert.dom("#my-dropdown.opened").exists();
- assert.dom("#my-dropdown .widget-dropdown-body").exists();
- await click("#my-dropdown .widget-dropdown-header");
- assert.dom("#my-dropdown.closed").exists();
- assert.dom("#my-dropdown .widget-dropdown-body").doesNotExist();
- });
-
- test("icon", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
- this.set("icon", "xmark");
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- assert.dom("#my-dropdown .widget-dropdown-header .d-icon-xmark").exists();
- });
-
- test("class", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
- this.set("class", "activated");
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- assert.dom("#my-dropdown.activated").exists();
- });
-
- test("content with translatedLabel", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- await click("#my-dropdown .widget-dropdown-header");
- assert.dom("#my-dropdown .widget-dropdown-item.item-2").hasText("FooBar");
- });
-
- test("content with label", async function (assert) {
- I18n.translations = { en: { js: { foo: "FooBaz" } } };
- this.setProperties(DEFAULT_CONTENT);
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- await click("#my-dropdown .widget-dropdown-header");
- assert.dom("#my-dropdown .widget-dropdown-item.item-1").hasText("FooBaz");
- });
-
- test("content with icon", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- await click("#my-dropdown .widget-dropdown-header");
- assert
- .dom("#my-dropdown .widget-dropdown-item.item-3 .d-icon-xmark")
- .exists();
- });
-
- test("content with html", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
- await click("#my-dropdown .widget-dropdown-header");
-
- assert
- .dom("#my-dropdown .widget-dropdown-item.item-4")
- .hasHtml("<span><b>baz</b></span>");
- });
-
- test("separator", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- await click("#my-dropdown .widget-dropdown-header");
- assert
- .dom("#my-dropdown .widget-dropdown-item:nth-child(3)")
- .hasClass("separator");
- });
-
- test("hides widget if no content", async function (assert) {
- this.setProperties({ content: null, label: "foo" });
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- assert.dom("#my-dropdown .widget-dropdown-header").doesNotExist();
- assert.dom("#my-dropdown .widget-dropdown-body").doesNotExist();
- });
-
- test("headerClass option", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
- this.set("options", { headerClass: "btn-small and-text" });
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- assert.dom("#my-dropdown .widget-dropdown-header").hasClass("btn-small");
- assert.dom("#my-dropdown .widget-dropdown-header").hasClass("and-text");
- });
-
- test("bodyClass option", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
- this.set("options", { bodyClass: "gigantic and-yet-small" });
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- await click("#my-dropdown .widget-dropdown-header");
- assert.dom("#my-dropdown .widget-dropdown-body").hasClass("gigantic");
- assert.dom("#my-dropdown .widget-dropdown-body").hasClass("and-yet-small");
- });
-
- test("caret option", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
- this.set("options", { caret: true });
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- assert
- .dom("#my-dropdown .widget-dropdown-header .d-icon-caret-down")
- .exists();
- });
-
- test("disabled widget", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
- this.set("options", { disabled: true });
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- assert.dom("#my-dropdown.disabled").exists();
-
- await click("#my-dropdown .widget-dropdown-header");
- assert
- .dom("#my-dropdown .widget-dropdown-item.item-1")
- .doesNotExist("does not display options");
- });
-
- test("disabled item", async function (assert) {
- this.setProperties(DEFAULT_CONTENT);
-
- await render(
- <template>
- <MountWidget
- @widget="widget-dropdown"
- @args={{hash
- id="my-dropdown"
- icon=this.icon
- label=this.label
- class=this.class
- translatedLabel=this.translatedLabel
- content=this.content
- options=this.options
- }}
- />
- </template>
- );
-
- await click("#my-dropdown .widget-dropdown-header");
- assert.dom(".widget-dropdown-item.item-5.disabled").exists();
- });
-});
diff --git a/frontend/discourse/tests/integration/components/widgets/widget-test.gjs b/frontend/discourse/tests/integration/components/widgets/widget-test.gjs
deleted file mode 100644
index e54790194d7..00000000000
--- a/frontend/discourse/tests/integration/components/widgets/widget-test.gjs
+++ /dev/null
@@ -1,529 +0,0 @@
-import { next } from "@ember/runloop";
-import { click, render, settled } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import { Promise } from "rsvp";
-import { h } from "virtual-dom";
-import MountWidget from "discourse/components/mount-widget";
-import { withPluginApi } from "discourse/lib/plugin-api";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import widgetHbs from "discourse/widgets/hbs-compiler";
-import { createWidget } from "discourse/widgets/widget";
-import I18n from "discourse-i18n";
-
-module("Integration | Component | Widget | base", function (hooks) {
- setupRenderingTest(hooks);
-
- let _translations = I18n.translations;
-
- hooks.beforeEach(function () {
- this.siteSettings.deactivate_widgets_rendering = false;
- });
-
- hooks.afterEach(function () {
- I18n.translations = _translations;
- });
-
- test("widget attributes are passed in via args", async function (assert) {
- createWidget("hello-test", {
- tagName: "div.test",
- template: widgetHbs`Hello {{attrs.name}}`,
- });
-
- this.set("args", { name: "Robin" });
-
- await render(
- <template>
- <MountWidget @widget="hello-test" @args={{this.args}} />
- </template>
- );
-
- assert.dom(".test").hasText("Hello Robin");
- });
-
- test("widget rerenders when args change", async function (assert) {
- createWidget("hello-test", {
- tagName: "div.test",
- template: widgetHbs`Hello {{attrs.name}}`,
- });
-
- this.set("args", { name: "Robin" });
-
- await render(
- <template>
- <MountWidget @widget="hello-test" @args={{this.args}} />
- </template>
- );
-
- assert.dom(".test").hasText("Hello Robin");
-
- this.set("args", { name: "David" });
- await settled();
-
- assert.dom(".test").hasText("Hello David");
- });
-
- test("widget services", async function (assert) {
- createWidget("service-test", {
- tagName: "div.base-url-test",
- services: ["router"],
- html() {
- return this.router.rootURL;
- },
- });
-
- await render(<template><MountWidget @widget="service-test" /></template>);
-
- assert.dom(".base-url-test").hasText("/");
- });
-
- test("hbs template - no tagName", async function (assert) {
- createWidget("hbs-test", {
- template: widgetHbs`<div class='test'>Hello {{attrs.name}}</div>`,
- });
-
- this.set("args", { name: "Robin" });
-
- await render(
- <template>
- <MountWidget @widget="hbs-test" @args={{this.args}} />
- </template>
- );
-
- assert.dom("div.test").hasText("Hello Robin");
- });
-
- test("hbs template - with tagName", async function (assert) {
- createWidget("hbs-test", {
- tagName: "div.test",
- template: widgetHbs`Hello {{attrs.name}}`,
- });
-
- this.set("args", { name: "Robin" });
-
- await render(
- <template>
- <MountWidget @widget="hbs-test" @args={{this.args}} />
- </template>
- );
-
- assert.dom("div.test").hasText("Hello Robin");
- });
-
- test("hbs template - with data attributes", async function (assert) {
- createWidget("hbs-test", {
- template: widgetHbs`<div class='my-div' data-my-test='hello world'></div>`,
- });
-
- await render(
- <template>
- <MountWidget @widget="hbs-test" @args={{this.args}} />
- </template>
- );
-
- assert.dom("div.my-div").hasAttribute("data-my-test", "hello world");
- });
-
- test("buildClasses", async function (assert) {
- createWidget("classname-test", {
- tagName: "div.test",
-
- buildClasses(attrs) {
- return ["static", attrs.dynamic];
- },
- });
-
- this.set("args", { dynamic: "cool-class" });
-
- await render(
- <template>
- <MountWidget @widget="classname-test" @args={{this.args}} />
- </template>
- );
-
- assert.dom(".test.static.cool-class").exists("has all the classes");
- });
-
- test("buildAttributes", async function (assert) {
- createWidget("attributes-test", {
- tagName: "div.test",
-
- buildAttributes(attrs) {
- return { "data-evil": "trout", "aria-label": attrs.label };
- },
- });
-
- this.set("args", { label: "accessibility" });
-
- await render(
- <template>
- <MountWidget @widget="attributes-test" @args={{this.args}} />
- </template>
- );
-
- assert.dom('.test[data-evil="trout"]').exists();
- assert.dom('.test[aria-label="accessibility"]').exists();
- });
-
- test("buildId", async function (assert) {
- createWidget("id-test", {
- buildId(attrs) {
- return `test-${attrs.id}`;
- },
- });
-
- this.set("args", { id: 1234 });
-
- await render(
- <template><MountWidget @widget="id-test" @args={{this.args}} /></template>
- );
-
- assert.dom("#test-1234").exists();
- });
-
- test("widget state", async function (assert) {
- createWidget("state-test", {
- tagName: "button.test",
- buildKey: () => `button-test`,
- template: widgetHbs`{{state.clicks}} clicks`,
-
- defaultState() {
- return { clicks: 0 };
- },
-
- click() {
- this.state.clicks++;
- },
- });
-
- await render(<template><MountWidget @widget="state-test" /></template>);
-
- assert.dom("button.test").exists("renders the button");
- assert.dom("button.test").hasText("0 clicks");
-
- await click("button");
- assert.dom("button.test").hasText("1 clicks");
- });
-
- test("widget update with promise", async function (assert) {
- createWidget("promise-test", {
- tagName: "button.test",
- buildKey: () => "promise-test",
- template: widgetHbs`
- {{#if state.name}}
- {{state.name}}
- {{else}}
- No name
- {{/if}}
- `,
-
- click() {
- return new Promise((resolve) => {
- next(() => {
- this.state.name = "Robin";
- resolve();
- });
- });
- },
- });
-
- await render(<template><MountWidget @widget="promise-test" /></template>);
-
- assert.dom("button.test").hasText("No name");
-
- await click("button");
- assert.dom("button.test").hasText("Robin");
- });
-
- test("widget attaching", async function (assert) {
- createWidget("test-embedded", { tagName: "div.embedded" });
-
- createWidget("attach-test", {
- tagName: "div.container",
- template: widgetHbs`{{attach widget="test-embedded" attrs=attrs}}`,
- });
-
- await render(<template><MountWidget @widget="attach-test" /></template>);
-
- assert.dom(".container").exists("renders container");
- assert.dom(".container .embedded").exists("renders attached");
- });
-
- test("magic attaching by name", async function (assert) {
- createWidget("test-embedded", { tagName: "div.embedded" });
-
- createWidget("attach-test", {
- tagName: "div.container",
- template: widgetHbs`{{test-embedded attrs=attrs}}`,
- });
-
- await render(<template><MountWidget @widget="attach-test" /></template>);
-
- assert.dom(".container").exists("renders container");
- assert.dom(".container .embedded").exists("renders attached");
- });
-
- test("custom attrs to a magic attached widget", async function (assert) {
- createWidget("testing", {
- tagName: "span.value",
- template: widgetHbs`{{attrs.value}}`,
- });
-
- createWidget("attach-test", {
- tagName: "div.container",
- template: widgetHbs`{{testing value=(concat "hello" " " "world")}}`,
- });
-
- await render(<template><MountWidget @widget="attach-test" /></template>);
-
- assert.dom(".container").exists("renders container");
- assert.dom(".container .value").hasText("hello world");
- });
-
- test("using transformed values in a sub-expression", async function (assert) {
- createWidget("testing", {
- tagName: "span.value",
- template: widgetHbs`{{attrs.value}}`,
- });
-
- createWidget("attach-test", {
- transform() {
- return { someValue: "world" };
- },
- tagName: "div.container",
- template: widgetHbs`{{testing value=(concat "hello" " " transformed.someValue)}}`,
- });
-
- await render(<template><MountWidget @widget="attach-test" /></template>);
-
- assert.dom(".container").exists("renders container");
- assert.dom(".container .value").hasText("hello world");
- });
-
- test("handlebars d-icon", async function (assert) {
- createWidget("hbs-icon-test", {
- template: widgetHbs`{{d-icon "arrow-down"}}`,
- });
-
- await render(
- <template>
- <MountWidget @widget="hbs-icon-test" @args={{this.args}} />
- </template>
- );
-
- assert.dom(".d-icon-arrow-down").exists();
- });
-
- test("handlebars i18n", async function (assert) {
- createWidget("hbs-i18n-test", {
- template: widgetHbs`
- <span class='string'>{{i18n "hbs_test0"}}</span>
- <span class='var'>{{i18n attrs.key}}</span>
- <a href title={{i18n "hbs_test0"}}>test</a>
- `,
- });
- I18n.translations = {
- en: {
- js: {
- hbs_test0: "evil",
- hbs_test1: "trout",
- },
- },
- };
- this.set("args", { key: "hbs_test1" });
-
- await render(
- <template>
- <MountWidget @widget="hbs-i18n-test" @args={{this.args}} />
- </template>
- );
-
- // coming up
- assert.dom("span.string").hasText("evil");
- assert.dom("span.var").hasText("trout");
- assert.dom("a").hasAttribute("title", "evil");
- });
-
- test("handlebars #each", async function (assert) {
- createWidget("hbs-each-test", {
- tagName: "ul",
- template: widgetHbs`
- {{#each attrs.items as |item|}}
- <li>{{item}}</li>
- {{/each}}
- `,
- });
-
- this.set("args", {
- items: ["one", "two", "three"],
- });
-
- await render(
- <template>
- <MountWidget @widget="hbs-each-test" @args={{this.args}} />
- </template>
- );
-
- assert.dom("ul li").exists({ count: 3 });
- assert.dom("ul li:nth-of-type(1)").hasText("one");
- });
-
- test("widget decorating", async function (assert) {
- createWidget("decorate-test", {
- tagName: "div.decorate",
- template: widgetHbs`main content`,
- });
-
- withPluginApi((api) => {
- api.decorateWidget("decorate-test:before", (dec) => {
- return dec.h("b", "before");
- });
-
- api.decorateWidget("decorate-test:after", (dec) => {
- return dec.h("i", "after");
- });
- });
-
- await render(<template><MountWidget @widget="decorate-test" /></template>);
-
- assert.dom(".decorate").exists();
- assert.dom(".decorate b").hasText("before");
- assert.dom(".decorate i").hasText("after");
- });
-
- test("widget settings", async function (assert) {
- createWidget("settings-test", {
- tagName: "div.settings",
- template: widgetHbs`age is {{settings.age}}`,
- settings: { age: 36 },
- });
-
- await render(<template><MountWidget @widget="settings-test" /></template>);
-
- assert.dom(".settings").hasText("age is 36");
- });
-
- test("override settings", async function (assert) {
- createWidget("ov-settings-test", {
- tagName: "div.settings",
- template: widgetHbs`age is {{settings.age}}`,
- settings: { age: 36 },
- });
-
- withPluginApi((api) => {
- api.changeWidgetSetting("ov-settings-test", "age", 37);
- });
-
- await render(
- <template><MountWidget @widget="ov-settings-test" /></template>
- );
-
- assert.dom(".settings").hasText("age is 37");
- });
-
- test("get accessor", async function (assert) {
- createWidget("get-accessor-test", {
- tagName: "div.test",
- template: widgetHbs`Hello {{transformed.name}}`,
- transform() {
- return {
- name: this.get("currentUser.username"),
- };
- },
- });
-
- await render(
- <template><MountWidget @widget="get-accessor-test" /></template>
- );
-
- assert.dom("div.test").hasText("Hello eviltrout");
- });
-
- test("tagName", async function (assert) {
- createWidget("test-override", { tagName: "div.not-override" });
-
- createWidget("tag-name-override-test", {
- template: widgetHbs`{{attach widget="test-override" attrs=attrs otherOpts=(hash tagName="section.override")}}`,
- });
-
- await render(
- <template><MountWidget @widget="tag-name-override-test" /></template>
- );
-
- assert
- .dom("section.override")
- .exists("renders container with overridden tagName");
- });
-
- test("avoids rerendering on prepend", async function (assert) {
- createWidget("prepend-test", {
- tagName: "div.test",
- html(attrs) {
- const result = [];
- result.push(
- this.attach("button", {
- label: "rerender",
- className: "rerender",
- action: "dummyAction",
- })
- );
- result.push(
- h(
- "div",
- attrs.array.map((val) => h(`span.val.${val}`, { key: val }, val))
- )
- );
- return result;
- },
- dummyAction() {},
- });
-
- const array = ["ElementOne", "ElementTwo"];
- this.set("args", { array });
-
- await render(
- <template>
- <MountWidget @widget="prepend-test" @args={{this.args}} />
- </template>
- );
-
- const startElements = Array.from(document.querySelectorAll("span.val"));
- assert.deepEqual(
- startElements.map((e) => e.innerText),
- ["ElementOne", "ElementTwo"]
- );
- const elementOneBefore = startElements[0];
-
- const parent = elementOneBefore.parentNode;
- const observer = new MutationObserver(function (mutations) {
- assert.false(
- mutations.some((m) =>
- Array.from(m.addedNodes).includes(elementOneBefore)
- )
- );
- });
- observer.observe(parent, { childList: true });
-
- array.unshift(
- "PrependedElementOne",
- "PrependedElementTwo",
- "PrependedElementThree"
- );
-
- await click(".rerender");
-
- const endElements = Array.from(document.querySelectorAll("span.val"));
- assert.deepEqual(
- endElements.map((e) => e.innerText),
- [
- "PrependedElementOne",
- "PrependedElementTwo",
- "PrependedElementThree",
- "ElementOne",
- "ElementTwo",
- ]
- );
- const elementOneAfter = endElements[3];
-
- assert.strictEqual(elementOneBefore, elementOneAfter);
- });
-});
diff --git a/frontend/discourse/tests/unit/lib/icon-library-test.js b/frontend/discourse/tests/unit/lib/icon-library-test.js
index 76d15f390cb..6addfaac0ad 100644
--- a/frontend/discourse/tests/unit/lib/icon-library-test.js
+++ b/frontend/discourse/tests/unit/lib/icon-library-test.js
@@ -2,20 +2,18 @@ import { setupTest } from "ember-qunit";
import { module, test } from "qunit";
import {
convertIconClass,
+ iconElement,
iconHTML,
- iconNode,
} from "discourse/lib/icon-library";
module("Unit | Utility | icon-library", function (hooks) {
setupTest(hooks);
- test("return icon markup", function (assert) {
- assert.true(iconHTML("bars").includes('use href="#bars"'));
-
- const nodeIcon = iconNode("bars");
- assert.strictEqual(nodeIcon.tagName, "svg");
+ test("creates icon element", function (assert) {
+ const icon = iconElement("bars");
+ assert.strictEqual(icon.tagName, "svg");
assert.strictEqual(
- nodeIcon.properties.attributes.class,
+ icon.className.baseVal,
"fa d-icon d-icon-bars svg-icon svg-node"
);
});
diff --git a/package.json b/package.json
index 2b4a6cceed6..87dd03df2e8 100644
--- a/package.json
+++ b/package.json
@@ -61,7 +61,6 @@
"patchedDependencies": {
"@ember-compat/[email protected]": "patches/@[email protected]",
diff --git a/patches/[email protected] b/patches/[email protected]
deleted file mode 100644
index aa162b8d311..00000000000
--- a/patches/[email protected]
+++ /dev/null
@@ -1,43 +0,0 @@
-diff --git a/vtree/diff.js b/vtree/diff.js
-index b5bccbd..058d6b3 100644
---- a/vtree/diff.js
-+++ b/vtree/diff.js
-@@ -311,6 +311,38 @@ function reorder(aChildren, bChildren) {
- var inserts = []
- var simulateItem
-
-+ // handle prepends without reordering old elements
-+ var shift = bChildren.length - aChildren.length
-+ if (shift > 0 && simulate.length === bChildren.length) {
-+ var prepend = true
-+ for (var i = 0; prepend && i < simulate.length; i++) {
-+ prepend = simulate[i] && simulate[i].key
-+ }
-+ for (var i = 0; prepend && i < aChildren.length; i++) {
-+ prepend = aChildren[i].key === bChildren[i + shift].key
-+ }
-+
-+ if (prepend) {
-+ for (var i = 0; i < shift; i++) {
-+ removes.push({
-+ from: aChildren.length,
-+ key: bChildren[i].key
-+ })
-+ inserts.push({
-+ to: i,
-+ key: bChildren[i].key
-+ })
-+ }
-+ return {
-+ children: newChildren,
-+ moves: {
-+ removes: removes,
-+ inserts: inserts
-+ }
-+ }
-+ }
-+ }
-+
- for (var k = 0; k < bChildren.length;) {
- var wantedItem = bChildren[k]
- simulateItem = simulate[simulateIndex]
diff --git a/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js b/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js
index 84f09af3dcd..78c249e4d3e 100644
--- a/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js
+++ b/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js
@@ -1,7 +1,5 @@
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import { withSilencedDeprecations } from "discourse/lib/deprecated";
-import { getOwnerWithFallback } from "discourse/lib/get-owner";
import { iconHTML } from "discourse/lib/icon-library";
import { withPluginApi } from "discourse/lib/plugin-api";
import richEditorExtension from "../../lib/rich-editor-extension";
@@ -60,15 +58,6 @@ export function checklistSyntax(elem, postDecorator) {
const postModel = postDecorator?.getModel();
- // TODO (glimmer-post-stream): remove this when we remove the legacy post stream code
- const postWidget = withSilencedDeprecations(
- "discourse.post-stream-widget-overrides",
- () =>
- getOwnerWithFallback(this).lookup("service:site").useGlimmerPostStream
- ? null
- : postDecorator?.widget
- );
-
if (!postModel?.can_edit) {
return;
}
@@ -156,12 +145,6 @@ export function checklistSyntax(elem, postDecorator) {
);
await postModel.save({ raw: newRaw });
-
- // TODO (glimmer-post-stream): remove the following code when removing the legacy post stream code
- if (postWidget) {
- postWidget.attrs.isSaving = false;
- postWidget.scheduleRerender();
- }
} catch (e) {
popupAjaxError(e);
} finally {
diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/initializers/initialize-ad-plugin.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/initializers/initialize-ad-plugin.gjs
index 1d357bb7121..31da3025061 100644
--- a/plugins/discourse-adplugin/assets/javascripts/discourse/initializers/initialize-ad-plugin.gjs
+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/initializers/initialize-ad-plugin.gjs
@@ -1,7 +1,5 @@
-import { withSilencedDeprecations } from "discourse/lib/deprecated";
import { withPluginApi } from "discourse/lib/plugin-api";
import Site from "discourse/models/site";
-import { registerWidgetShim } from "discourse/widgets/render-glimmer";
import PostBottomAd from "../components/post-bottom-ad";
export default {
@@ -33,20 +31,4 @@ function customizePost(api) {
</div>
</template>
);
-
- withSilencedDeprecations("discourse.post-stream-widget-overrides", () =>
- customizeWidgetPost(api)
- );
-}
-
-function customizeWidgetPost(api) {
- registerWidgetShim(
- "after-post-ad",
- "div.ad-connector",
- <template><PostBottomAd @model={{@data}} /></template>
- );
-
- api.decorateWidget("post:after", (helper) => {
- return helper.attach("after-post-ad", helper.widget.model);
- });
}
diff --git a/plugins/discourse-adplugin/test/javascripts/acceptance/adsense-test.js b/plugins/discourse-adplugin/test/javascripts/acceptance/adsense-test.js
index 108decb173c..b8437ff308c 100644
--- a/plugins/discourse-adplugin/test/javascripts/acceptance/adsense-test.js
+++ b/plugins/discourse-adplugin/test/javascripts/acceptance/adsense-test.js
@@ -7,107 +7,101 @@ import {
updateCurrentUser,
} from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `AdSense (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- no_ads_for_groups: "47",
- no_ads_for_categories: "1",
- adsense_publisher_code: "MYADSENSEID",
- adsense_display_groups: [
- AUTO_GROUPS.trust_level_1,
- AUTO_GROUPS.trust_level_2,
- ],
- adsense_topic_list_top_code: "list_top_ad_unit",
- adsense_topic_list_top_ad_sizes: "728*90 - leaderboard",
- adsense_mobile_topic_list_top_code: "mobile_list_top_ad_unit",
- adsense_mobile_topic_list_top_ad_size: "300*250 - medium rectangle",
- adsense_post_bottom_code: "post_bottom_ad_unit",
- adsense_post_bottom_ad_sizes: "728*90 - leaderboard",
- adsense_mobile_post_bottom_code: "mobile_post_bottom_ad_unit",
- adsense_mobile_post_bottom_ad_size: "300*250 - medium rectangle",
- adsense_nth_post_code: 6,
- adsense_topic_above_post_stream_code: "above_post_stream_ad_unit",
- adsense_topic_above_post_stream_ad_sizes: "728*90 - leaderboard",
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.site({
- house_creatives: {
- settings: {
- topic_list_top: "",
- topic_above_post_stream: "",
- topic_above_suggested: "",
- post_bottom: "",
- after_nth_post: 20,
- },
- creatives: {},
- },
- });
+acceptance(`AdSense`, function (needs) {
+ needs.user();
+ needs.settings({
+ no_ads_for_groups: "47",
+ no_ads_for_categories: "1",
+ adsense_publisher_code: "MYADSENSEID",
+ adsense_display_groups: [
+ AUTO_GROUPS.trust_level_1,
+ AUTO_GROUPS.trust_level_2,
+ ],
+ adsense_topic_list_top_code: "list_top_ad_unit",
+ adsense_topic_list_top_ad_sizes: "728*90 - leaderboard",
+ adsense_mobile_topic_list_top_code: "mobile_list_top_ad_unit",
+ adsense_mobile_topic_list_top_ad_size: "300*250 - medium rectangle",
+ adsense_post_bottom_code: "post_bottom_ad_unit",
+ adsense_post_bottom_ad_sizes: "728*90 - leaderboard",
+ adsense_mobile_post_bottom_code: "mobile_post_bottom_ad_unit",
+ adsense_mobile_post_bottom_ad_size: "300*250 - medium rectangle",
+ adsense_nth_post_code: 6,
+ adsense_topic_above_post_stream_code: "above_post_stream_ad_unit",
+ adsense_topic_above_post_stream_ad_sizes: "728*90 - leaderboard",
+ });
+ needs.site({
+ house_creatives: {
+ settings: {
+ topic_list_top: "",
+ topic_above_post_stream: "",
+ topic_above_suggested: "",
+ post_bottom: "",
+ after_nth_post: 20,
+ },
+ creatives: {},
+ },
+ });
- test("correct number of ads should show", async (assert) => {
- updateCurrentUser({
- staff: false,
- trust_level: 1,
- groups: [AUTO_GROUPS.trust_level_1],
- show_adsense_ads: true,
- show_to_groups: true,
- });
- await visit("/t/280"); // 20 posts
+ test("correct number of ads should show", async (assert) => {
+ updateCurrentUser({
+ staff: false,
+ trust_level: 1,
+ groups: [AUTO_GROUPS.trust_level_1],
+ show_adsense_ads: true,
+ show_to_groups: true,
+ });
+ await visit("/t/280"); // 20 posts
- assert
- .dom(".google-adsense.adsense-topic-above-post-stream")
- .exists({ count: 1 }, "it should render 1 ad above post stream");
+ assert
+ .dom(".google-adsense.adsense-topic-above-post-stream")
+ .exists({ count: 1 }, "it should render 1 ad above post stream");
- assert
- .dom(".google-adsense.adsense-post-bottom")
- .exists({ count: 3 }, "it should render 3 ads");
+ assert
+ .dom(".google-adsense.adsense-post-bottom")
+ .exists({ count: 3 }, "it should render 3 ads");
- assert
- .dom("#post_6 + .ad-connector .google-adsense.adsense-post-bottom")
- .exists({ count: 1 }, "ad after 6th post");
+ assert
+ .dom("#post_6 + .ad-connector .google-adsense.adsense-post-bottom")
+ .exists({ count: 1 }, "ad after 6th post");
- assert
- .dom("#post_12 + .ad-connector .google-adsense.adsense-post-bottom")
- .exists({ count: 1 }, "ad after 12th post");
+ assert
+ .dom("#post_12 + .ad-connector .google-adsense.adsense-post-bottom")
+ .exists({ count: 1 }, "ad after 12th post");
- assert
- .dom("#post_18 + .ad-connector .google-adsense.adsense-post-bottom")
- .exists({ count: 1 }, "ad after 18th post");
- });
+ assert
+ .dom("#post_18 + .ad-connector .google-adsense.adsense-post-bottom")
+ .exists({ count: 1 }, "ad after 18th post");
+ });
- test("no ads for trust level 3", async (assert) => {
- updateCurrentUser({
- staff: false,
- trust_level: 3,
- groups: [AUTO_GROUPS.trust_level_3],
- });
- await visit("/t/280");
- assert
- .dom(".google-adsense.adsense-post-bottom")
- .doesNotExist("it should render 0 ads");
- });
+ test("no ads for trust level 3", async (assert) => {
+ updateCurrentUser({
+ staff: false,
+ trust_level: 3,
+ groups: [AUTO_GROUPS.trust_level_3],
+ });
+ await visit("/t/280");
+ assert
+ .dom(".google-adsense.adsense-post-bottom")
+ .doesNotExist("it should render 0 ads");
+ });
- test("can omit ads based on groups", async (assert) => {
- updateCurrentUser({
- staff: false,
- trust_level: 1,
- groups: [groupFixtures["/groups/discourse.json"].group],
- });
- await visit("/t/280");
- assert
- .dom(".google-adsense.adsense-post-bottom")
- .doesNotExist("it should render 0 ads");
- });
+ test("can omit ads based on groups", async (assert) => {
+ updateCurrentUser({
+ staff: false,
+ trust_level: 1,
+ groups: [groupFixtures["/groups/discourse.json"].group],
+ });
+ await visit("/t/280");
+ assert
+ .dom(".google-adsense.adsense-post-bottom")
+ .doesNotExist("it should render 0 ads");
+ });
- test("can omit ads based on category", async (assert) => {
- updateCurrentUser({ staff: false, trust_level: 1 });
- await visit("/t/28830");
- assert
- .dom(".google-adsense.adsense-topic-above-post-stream")
- .doesNotExist("it should render 0 ads");
- });
- }
- );
+ test("can omit ads based on category", async (assert) => {
+ updateCurrentUser({ staff: false, trust_level: 1 });
+ await visit("/t/28830");
+ assert
+ .dom(".google-adsense.adsense-topic-above-post-stream")
+ .doesNotExist("it should render 0 ads");
+ });
});
diff --git a/plugins/discourse-adplugin/test/javascripts/acceptance/dfp-test.js b/plugins/discourse-adplugin/test/javascripts/acceptance/dfp-test.js
index 1973614fc0e..b3c2adf07d5 100644
--- a/plugins/discourse-adplugin/test/javascripts/acceptance/dfp-test.js
+++ b/plugins/discourse-adplugin/test/javascripts/acceptance/dfp-test.js
@@ -7,107 +7,98 @@ import {
updateCurrentUser,
} from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `DFP Ads (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- no_ads_for_groups: "47",
- no_ads_for_categories: "1",
- dfp_publisher_id: "MYdfpID",
- dfp_through_trust_level: 2,
- dfp_display_groups: [
- AUTO_GROUPS.trust_level_1,
- AUTO_GROUPS.trust_level_2,
- ],
- dfp_topic_list_top_code: "list_top_ad_unit",
- dfp_topic_list_top_ad_sizes: "728*90 - leaderboard",
- dfp_mobile_topic_list_top_code: "mobile_list_top_ad_unit",
- dfp_mobile_topic_list_top_ad_size: "300*250 - medium rectangle",
- dfp_post_bottom_code: "post_bottom_ad_unit",
- dfp_post_bottom_ad_sizes: "728*90 - leaderboard",
- dfp_mobile_post_bottom_code: "mobile_post_bottom_ad_unit",
- dfp_mobile_post_bottom_ad_size: "300*250 - medium rectangle",
- dfp_nth_post_code: 6,
- dfp_topic_above_post_stream_code: "list_top_ad_unit",
- dfp_topic_above_post_stream_ad_sizes: "728*90 - leaderboard",
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.site({
- house_creatives: {
- settings: {
- topic_list_top: "",
- topic_above_post_stream: "",
- topic_above_suggested: "",
- post_bottom: "",
- after_nth_post: 20,
- },
- creatives: {},
- },
- });
+acceptance(`DFP Ads`, function (needs) {
+ needs.user();
+ needs.settings({
+ no_ads_for_groups: "47",
+ no_ads_for_categories: "1",
+ dfp_publisher_id: "MYdfpID",
+ dfp_through_trust_level: 2,
+ dfp_display_groups: [AUTO_GROUPS.trust_level_1, AUTO_GROUPS.trust_level_2],
+ dfp_topic_list_top_code: "list_top_ad_unit",
+ dfp_topic_list_top_ad_sizes: "728*90 - leaderboard",
+ dfp_mobile_topic_list_top_code: "mobile_list_top_ad_unit",
+ dfp_mobile_topic_list_top_ad_size: "300*250 - medium rectangle",
+ dfp_post_bottom_code: "post_bottom_ad_unit",
+ dfp_post_bottom_ad_sizes: "728*90 - leaderboard",
+ dfp_mobile_post_bottom_code: "mobile_post_bottom_ad_unit",
+ dfp_mobile_post_bottom_ad_size: "300*250 - medium rectangle",
+ dfp_nth_post_code: 6,
+ dfp_topic_above_post_stream_code: "list_top_ad_unit",
+ dfp_topic_above_post_stream_ad_sizes: "728*90 - leaderboard",
+ });
+ needs.site({
+ house_creatives: {
+ settings: {
+ topic_list_top: "",
+ topic_above_post_stream: "",
+ topic_above_suggested: "",
+ post_bottom: "",
+ after_nth_post: 20,
+ },
+ creatives: {},
+ },
+ });
- test("correct number of ads should show", async (assert) => {
- updateCurrentUser({
- staff: false,
- trust_level: 1,
- show_dfp_ads: true,
- show_to_groups: true,
- });
- await visit("/t/280"); // 20 posts
+ test("correct number of ads should show", async (assert) => {
+ updateCurrentUser({
+ staff: false,
+ trust_level: 1,
+ show_dfp_ads: true,
+ show_to_groups: true,
+ });
+ await visit("/t/280"); // 20 posts
- assert
- .dom(".google-dfp-ad.dfp-ad-post-bottom")
- .exists({ count: 3 }, "it should render 3 ads");
+ assert
+ .dom(".google-dfp-ad.dfp-ad-post-bottom")
+ .exists({ count: 3 }, "it should render 3 ads");
- assert
- .dom("#post_6 + .ad-connector .google-dfp-ad.dfp-ad-post-bottom")
- .exists({ count: 1 }, "ad after 6th post");
+ assert
+ .dom("#post_6 + .ad-connector .google-dfp-ad.dfp-ad-post-bottom")
+ .exists({ count: 1 }, "ad after 6th post");
- assert
- .dom("#post_12 + .ad-connector .google-dfp-ad.dfp-ad-post-bottom")
- .exists({ count: 1 }, "ad after 12th post");
+ assert
+ .dom("#post_12 + .ad-connector .google-dfp-ad.dfp-ad-post-bottom")
+ .exists({ count: 1 }, "ad after 12th post");
- assert
- .dom("#post_18 + .ad-connector .google-dfp-ad.dfp-ad-post-bottom")
- .exists({ count: 1 }, "ad after 18th post");
- });
+ assert
+ .dom("#post_18 + .ad-connector .google-dfp-ad.dfp-ad-post-bottom")
+ .exists({ count: 1 }, "ad after 18th post");
+ });
- test("no ads for trust level 3", async (assert) => {
- updateCurrentUser({
- staff: false,
- trust_level: 3,
- groups: [
- AUTO_GROUPS.trust_level_1,
- AUTO_GROUPS.trust_level_2,
- AUTO_GROUPS.trust_level_3,
- ],
- });
- await visit("/t/280");
- assert
- .dom(".google-dfp-ad.dfp-ad-post-bottom")
- .doesNotExist("it should render 0 ads");
- });
+ test("no ads for trust level 3", async (assert) => {
+ updateCurrentUser({
+ staff: false,
+ trust_level: 3,
+ groups: [
+ AUTO_GROUPS.trust_level_1,
+ AUTO_GROUPS.trust_level_2,
+ AUTO_GROUPS.trust_level_3,
+ ],
+ });
+ await visit("/t/280");
+ assert
+ .dom(".google-dfp-ad.dfp-ad-post-bottom")
+ .doesNotExist("it should render 0 ads");
+ });
- test("can omit ads based on groups", async (assert) => {
- updateCurrentUser({
- staff: false,
- trust_level: 1,
- groups: [groupFixtures["/groups/discourse.json"].group],
- });
- await visit("/t/280");
- assert
- .dom(".google-dfp-ad.dfp-ad-post-bottom")
- .doesNotExist("it should render 0 ads");
- });
+ test("can omit ads based on groups", async (assert) => {
+ updateCurrentUser({
+ staff: false,
+ trust_level: 1,
+ groups: [groupFixtures["/groups/discourse.json"].group],
+ });
+ await visit("/t/280");
+ assert
+ .dom(".google-dfp-ad.dfp-ad-post-bottom")
+ .doesNotExist("it should render 0 ads");
+ });
- test("can omit ads based on category", async (assert) => {
- updateCurrentUser({ staff: false, trust_level: 1 });
- await visit("/t/28830");
- assert
- .dom(".google-dfp-ad.dfp-ad-topic-above-post-stream")
- .doesNotExist("it should render 0 ads");
- });
- }
- );
+ test("can omit ads based on category", async (assert) => {
+ updateCurrentUser({ staff: false, trust_level: 1 });
+ await visit("/t/28830");
+ assert
+ .dom(".google-dfp-ad.dfp-ad-topic-above-post-stream")
+ .doesNotExist("it should render 0 ads");
+ });
});
diff --git a/plugins/discourse-adplugin/test/javascripts/acceptance/house-ad-test.js b/plugins/discourse-adplugin/test/javascripts/acceptance/house-ad-test.js
index 169277cd9a8..5289d6eac17 100644
--- a/plugins/discourse-adplugin/test/javascripts/acceptance/house-ad-test.js
+++ b/plugins/discourse-adplugin/test/javascripts/acceptance/house-ad-test.js
@@ -5,344 +5,328 @@ import {
updateCurrentUser,
} from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `House Ads (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- no_ads_for_categories: "1",
- house_ads_after_nth_post: 6,
- house_ads_after_nth_topic: 3,
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.site({
- house_creatives: {
- settings: {
- topic_list_top: "Topic List Top",
- topic_above_post_stream: "Above Post Stream",
- topic_above_suggested: "Above Suggested",
- post_bottom: "Post",
- topic_list_between: "Between Topic List",
- after_nth_post: 6,
- after_nth_topic: 6,
- },
- creatives: {
- "Topic List Top": {
- html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
- category_ids: [],
- },
- "Above Post Stream": {
- html: "<div class='h-above-post-stream'>ABOVE POST STREAM</div>",
- category_ids: [],
- },
- "Above Suggested": {
- html: "<div class='h-above-suggested'>ABOVE SUGGESTED</div>",
- category_ids: [],
- },
- Post: {
- html: "<div class='h-post'>BELOW POST</div>",
- category_ids: [],
- },
- "Between Topic List": {
- html: "<div class='h-between-topic-list'>BETWEEN TOPIC LIST</div>",
- category_ids: [],
- },
- },
+acceptance(`House Ads`, function (needs) {
+ needs.user();
+ needs.settings({
+ no_ads_for_categories: "1",
+ house_ads_after_nth_post: 6,
+ house_ads_after_nth_topic: 3,
+ });
+ needs.site({
+ house_creatives: {
+ settings: {
+ topic_list_top: "Topic List Top",
+ topic_above_post_stream: "Above Post Stream",
+ topic_above_suggested: "Above Suggested",
+ post_bottom: "Post",
+ topic_list_between: "Between Topic List",
+ after_nth_post: 6,
+ after_nth_topic: 6,
+ },
+ creatives: {
+ "Topic List Top": {
+ html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
+ category_ids: [],
},
- });
+ "Above Post Stream": {
+ html: "<div class='h-above-post-stream'>ABOVE POST STREAM</div>",
+ category_ids: [],
+ },
+ "Above Suggested": {
+ html: "<div class='h-above-suggested'>ABOVE SUGGESTED</div>",
+ category_ids: [],
+ },
+ Post: {
+ html: "<div class='h-post'>BELOW POST</div>",
+ category_ids: [],
+ },
+ "Between Topic List": {
+ html: "<div class='h-between-topic-list'>BETWEEN TOPIC LIST</div>",
+ category_ids: [],
+ },
+ },
+ },
+ });
- test("correct ads show", async function (assert) {
- updateCurrentUser({
- staff: false,
- trust_level: 1,
- show_to_groups: true,
- });
- await visit("/t/280"); // 20 posts
+ test("correct ads show", async function (assert) {
+ updateCurrentUser({
+ staff: false,
+ trust_level: 1,
+ show_to_groups: true,
+ });
+ await visit("/t/280"); // 20 posts
- assert
- .dom(".h-above-post-stream")
- .exists({ count: 1 }, "renders ad at top of topic");
+ assert
+ .dom(".h-above-post-stream")
+ .exists({ count: 1 }, "renders ad at top of topic");
- assert
- .dom(".h-above-suggested")
- .exists({ count: 1 }, "renders ad above suggested topics");
+ assert
+ .dom(".h-above-suggested")
+ .exists({ count: 1 }, "renders ad above suggested topics");
- assert
- .dom(".h-post")
- .exists({ count: 3 }, "renders 3 ads between posts");
+ assert.dom(".h-post").exists({ count: 3 }, "renders 3 ads between posts");
- assert
- .dom("#post_6 + .ad-connector .h-post")
- .exists({ count: 1 }, "ad after 6th post");
+ assert
+ .dom("#post_6 + .ad-connector .h-post")
+ .exists({ count: 1 }, "ad after 6th post");
- assert
- .dom("#post_12 + .ad-connector .h-post")
- .exists({ count: 1 }, "ad after 12th post");
+ assert
+ .dom("#post_12 + .ad-connector .h-post")
+ .exists({ count: 1 }, "ad after 12th post");
- assert
- .dom("#post_18 + .ad-connector .h-post")
- .exists({ count: 1 }, "ad after 18th post");
+ assert
+ .dom("#post_18 + .ad-connector .h-post")
+ .exists({ count: 1 }, "ad after 18th post");
- await visit("/latest");
+ await visit("/latest");
- assert
- .dom(".h-topic-list")
- .exists({ count: 1 }, "renders ad above topic list");
- const originalTopAdElement = document.querySelector(".h-topic-list");
+ assert
+ .dom(".h-topic-list")
+ .exists({ count: 1 }, "renders ad above topic list");
+ const originalTopAdElement = document.querySelector(".h-topic-list");
- assert
- .dom(".h-between-topic-list")
- .exists({ count: 5 }, "renders 5 ads between topics");
+ assert
+ .dom(".h-between-topic-list")
+ .exists({ count: 5 }, "renders 5 ads between topics");
- await visit("/top");
- const newTopAdElement = document.querySelector(".h-topic-list");
+ await visit("/top");
+ const newTopAdElement = document.querySelector(".h-topic-list");
- assert.notStrictEqual(
- originalTopAdElement,
- newTopAdElement,
- "ad is fully re-rendered when changing pages"
- );
+ assert.notStrictEqual(
+ originalTopAdElement,
+ newTopAdElement,
+ "ad is fully re-rendered when changing pages"
+ );
- await visit("/t/28830");
+ await visit("/t/28830");
- assert
- .dom(".h-above-post-stream")
- .doesNotExist(
- "no ad above post stream because category is in no_ads_for_categories"
- );
+ assert
+ .dom(".h-above-post-stream")
+ .doesNotExist(
+ "no ad above post stream because category is in no_ads_for_categories"
+ );
- assert
- .dom(".h-post")
- .doesNotExist(
- "no ad between posts because category is in no_ads_for_categories"
- );
+ assert
+ .dom(".h-post")
+ .doesNotExist(
+ "no ad between posts because category is in no_ads_for_categories"
+ );
- assert
- .dom(".h-above-suggested")
- .doesNotExist(
- "no ad above suggested because category is in no_ads_for_categories"
- );
+ assert
+ .dom(".h-above-suggested")
+ .doesNotExist(
+ "no ad above suggested because category is in no_ads_for_categories"
+ );
- await visit("/c/bug");
+ await visit("/c/bug");
- assert
- .dom(".h-topic-list")
- .doesNotExist(
- "no ad above category topic list because category is in no_ads_for_categories"
- );
- });
- }
- );
+ assert
+ .dom(".h-topic-list")
+ .doesNotExist(
+ "no ad above category topic list because category is in no_ads_for_categories"
+ );
+ });
+});
- acceptance(
- `House Ads | Category and Group Permissions | Authenticated | Display Ad (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- no_ads_for_categories: "",
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.site({
- house_creatives: {
- settings: {
- topic_list_top: "Topic List Top",
- },
- creatives: {
- "Topic List Top": {
- html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
- // match /c/bug/1
- category_ids: [1],
- },
+acceptance(
+ `House Ads | Category and Group Permissions | Authenticated | Display Ad`,
+ function (needs) {
+ needs.user();
+ needs.settings({
+ no_ads_for_categories: "",
+ });
+ needs.site({
+ house_creatives: {
+ settings: {
+ topic_list_top: "Topic List Top",
+ },
+ creatives: {
+ "Topic List Top": {
+ html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
+ // match /c/bug/1
+ category_ids: [1],
},
},
- });
+ },
+ });
- test("displays ad to users when current category id is included in ad category_ids", async function (assert) {
- updateCurrentUser({
- staff: false,
- trust_level: 1,
- show_to_groups: true,
- });
- await visit("/c/bug/1");
- assert
- .dom(".h-topic-list")
- .exists(
- "ad is displayed above the topic list because the current category id is included in the ad category_ids"
- );
+ test("displays ad to users when current category id is included in ad category_ids", async function (assert) {
+ updateCurrentUser({
+ staff: false,
+ trust_level: 1,
+ show_to_groups: true,
});
- }
- );
+ await visit("/c/bug/1");
+ assert
+ .dom(".h-topic-list")
+ .exists(
+ "ad is displayed above the topic list because the current category id is included in the ad category_ids"
+ );
+ });
+ }
+);
- acceptance(
- `House Ads | Category and Group Permissions | Authenticated | Hide Ad (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- no_ads_for_categories: "",
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.site({
- house_creatives: {
- settings: {
- topic_list_top: "Topic List Top",
- },
- creatives: {
- "Topic List Top": {
- html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
- // restrict ad to a different category than /c/bug/1
- category_ids: [2],
- },
+acceptance(
+ `House Ads | Category and Group Permissions | Authenticated | Hide Ad`,
+ function (needs) {
+ needs.user();
+ needs.settings({
+ no_ads_for_categories: "",
+ });
+ needs.site({
+ house_creatives: {
+ settings: {
+ topic_list_top: "Topic List Top",
+ },
+ creatives: {
+ "Topic List Top": {
+ html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
+ // restrict ad to a different category than /c/bug/1
+ category_ids: [2],
},
},
- });
+ },
+ });
- test("hides ad to users when current category id is not included in ad category_ids", async function (assert) {
- updateCurrentUser({
- staff: false,
- trust_level: 1,
- show_to_groups: true,
- });
- await visit("/c/bug/1");
- assert
- .dom(".h-topic-list")
- .doesNotExist(
- "ad is not displayed because the current category id is not included in the ad category_ids"
- );
+ test("hides ad to users when current category id is not included in ad category_ids", async function (assert) {
+ updateCurrentUser({
+ staff: false,
+ trust_level: 1,
+ show_to_groups: true,
});
- }
- );
+ await visit("/c/bug/1");
+ assert
+ .dom(".h-topic-list")
+ .doesNotExist(
+ "ad is not displayed because the current category id is not included in the ad category_ids"
+ );
+ });
+ }
+);
- acceptance(
- `House Ads | Category and Group Permissions | Anonymous | Hide Ad (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- no_ads_for_categories: "",
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.site({
- house_creatives: {
- settings: {
- topic_list_top: "Topic List Top",
- },
- creatives: {
- "Topic List Top": {
- html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
- // restrict ad to a different category than /c/bug/1
- category_ids: [2],
- },
+acceptance(
+ `House Ads | Category and Group Permissions | Anonymous | Hide Ad`,
+ function (needs) {
+ needs.settings({
+ no_ads_for_categories: "",
+ });
+ needs.site({
+ house_creatives: {
+ settings: {
+ topic_list_top: "Topic List Top",
+ },
+ creatives: {
+ "Topic List Top": {
+ html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
+ // restrict ad to a different category than /c/bug/1
+ category_ids: [2],
},
},
- });
+ },
+ });
- test("hides ad to anon users when current category id is not included in ad category_ids", async function (assert) {
- await visit("/c/bug/1");
- assert
- .dom(".h-topic-list")
- .doesNotExist(
- "ad is not displayed because the current category id is not included in the ad category_ids"
- );
- });
- }
- );
+ test("hides ad to anon users when current category id is not included in ad category_ids", async function (assert) {
+ await visit("/c/bug/1");
+ assert
+ .dom(".h-topic-list")
+ .doesNotExist(
+ "ad is not displayed because the current category id is not included in the ad category_ids"
+ );
+ });
+ }
+);
- acceptance(
- `House Ads | Category and Group Permissions | Anonymous | Hide Ad (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- no_ads_for_categories: "",
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.site({
- house_creatives: {
- settings: {
- topic_list_top: "Topic List Top",
- },
- creatives: {
- "Topic List Top": {
- html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
- // restrict ad to a different category than /c/bug/1
- category_ids: [2],
- },
+acceptance(
+ `House Ads | Category and Group Permissions | Anonymous | Hide Ad`,
+ function (needs) {
+ needs.settings({
+ no_ads_for_categories: "",
+ });
+ needs.site({
+ house_creatives: {
+ settings: {
+ topic_list_top: "Topic List Top",
+ },
+ creatives: {
+ "Topic List Top": {
+ html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
+ // restrict ad to a different category than /c/bug/1
+ category_ids: [2],
},
},
- });
+ },
+ });
- test("hides ad to anon users when current category id is not included in ad category_ids", async function (assert) {
- await visit("/c/bug/1");
- assert
- .dom(".h-topic-list")
- .doesNotExist(
- "ad is not displayed because the current category id is not included in the ad category_ids"
- );
- });
- }
- );
+ test("hides ad to anon users when current category id is not included in ad category_ids", async function (assert) {
+ await visit("/c/bug/1");
+ assert
+ .dom(".h-topic-list")
+ .doesNotExist(
+ "ad is not displayed because the current category id is not included in the ad category_ids"
+ );
+ });
+ }
+);
- acceptance(
- `House Ads | Category and Group Permissions | Anonymous | Show Ad (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- no_ads_for_categories: "",
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.site({
- house_creatives: {
- settings: {
- topic_list_top: "Topic List Top",
- },
- creatives: {
- "Topic List Top": {
- html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
- // match /c/bug/1
- category_ids: [1],
- },
+acceptance(
+ `House Ads | Category and Group Permissions | Anonymous | Show Ad`,
+ function (needs) {
+ needs.settings({
+ no_ads_for_categories: "",
+ });
+ needs.site({
+ house_creatives: {
+ settings: {
+ topic_list_top: "Topic List Top",
+ },
+ creatives: {
+ "Topic List Top": {
+ html: "<div class='h-topic-list'>TOPIC LIST TOP</div>",
+ // match /c/bug/1
+ category_ids: [1],
},
},
- });
+ },
+ });
- test("shows ad to anon users when current category id is included in ad category_ids", async function (assert) {
- await visit("/c/bug/1");
- assert
- .dom(".h-topic-list")
- .exists(
- "ad is displayed because the current category id is included in the ad category_ids"
- );
- });
- }
- );
+ test("shows ad to anon users when current category id is included in ad category_ids", async function (assert) {
+ await visit("/c/bug/1");
+ assert
+ .dom(".h-topic-list")
+ .exists(
+ "ad is displayed because the current category id is included in the ad category_ids"
+ );
+ });
+ }
+);
- acceptance(
- `House Ads | Category and Group Permissions | Anonymous | Show non-restricted ads (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- no_ads_for_categories: "",
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.site({
- house_creatives: {
- settings: {
- topic_list_top: "Topic List Top One|Topic List Top Two",
+acceptance(
+ `House Ads | Category and Group Permissions | Anonymous | Show non-restricted ads`,
+ function (needs) {
+ needs.settings({
+ no_ads_for_categories: "",
+ });
+ needs.site({
+ house_creatives: {
+ settings: {
+ topic_list_top: "Topic List Top One|Topic List Top Two",
+ },
+ creatives: {
+ "Topic List Top One": {
+ html: "<div class='h-topic-list-one'>TOPIC LIST TOP ONE</div>",
+ category_ids: [2],
},
- creatives: {
- "Topic List Top One": {
- html: "<div class='h-topic-list-one'>TOPIC LIST TOP ONE</div>",
- category_ids: [2],
- },
- "Topic List Top Two": {
- html: "<div class='h-topic-list-two'>TOPIC LIST TOP TWO</div>",
- category_ids: [],
- },
+ "Topic List Top Two": {
+ html: "<div class='h-topic-list-two'>TOPIC LIST TOP TWO</div>",
+ category_ids: [],
},
},
- });
+ },
+ });
- test("shows non-restricted ad to anon users", async function (assert) {
- await visit("/c/bug/1");
- assert
- .dom(".h-topic-list-two")
- .exists("non-restricted ad is displayed");
- });
- }
- );
-});
+ test("shows non-restricted ad to anon users", async function (assert) {
+ await visit("/c/bug/1");
+ assert.dom(".h-topic-list-two").exists("non-restricted ad is displayed");
+ });
+ }
+);
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact.gjs
index fc7a0e0b874..3d91001586b 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-artifact.gjs
@@ -8,11 +8,6 @@ import DButton from "discourse/components/d-button";
import htmlClass from "discourse/helpers/html-class";
import getURL from "discourse/lib/get-url";
-// note the panel for artifact full screen can not be at position 0,0
-// otherwise this hack will not activate.
-// https://github.com/discourse/discourse/blob/b8325f2190a8c0a9022405c219faeac6f0f98ca5/app/assets/javascripts/discourse/app/components/scrolling-post-stream.js#L77-L77
-// this will cause post stream to navigate to a different post
-
export default class AiArtifactComponent extends Component {
@service siteSettings;
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.js
index c74650d663e..a3972270661 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.js
@@ -1,17 +1,10 @@
-import { hbs } from "ember-cli-htmlbars";
-import { withSilencedDeprecations } from "discourse/lib/deprecated";
import { withPluginApi } from "discourse/lib/plugin-api";
-import { registerWidgetShim } from "discourse/widgets/render-glimmer";
import AiBotHeaderIcon from "../components/ai-bot-header-icon";
import AiPersonaFlair from "../components/post/ai-persona-flair";
import AiCancelStreamingButton from "../components/post-menu/ai-cancel-streaming-button";
import AiDebugButton from "../components/post-menu/ai-debug-button";
import AiShareButton from "../components/post-menu/ai-share-button";
-import {
- getBotType,
- isGPTBot,
- showShareConversationModal,
-} from "../lib/ai-bot-helper";
+import { isGPTBot, showShareConversationModal } from "../lib/ai-bot-helper";
import { streamPostText } from "../lib/ai-streamer/progress-handlers";
let allowDebug = false;
@@ -55,34 +48,6 @@ function initializeAIBotReplies(api) {
function initializePersonaDecorator(api) {
api.renderAfterWrapperOutlet("post-meta-data-poster-name", AiPersonaFlair);
-
- withSilencedDeprecations("discourse.post-stream-widget-overrides", () =>
- initializeWidgetPersonaDecorator(api)
- );
-}
-
-function initializeWidgetPersonaDecorator(api) {
- api.decorateWidget(`poster-name:after`, (dec) => {
- const botType = getBotType(dec.attrs.user);
- // we have 2 ways of decorating
- // 1. if a bot is a LLM we decorate with persona name
- // 2. if bot is a persona we decorate with LLM name
- if (botType === "llm") {
- return dec.widget.attach("persona-flair", {
- personaName: dec.model?.topic?.ai_persona_name,
- });
- } else if (botType === "persona") {
- return dec.widget.attach("persona-flair", {
- personaName: dec.model?.llm_name,
- });
- }
- });
-
- registerWidgetShim(
- "persona-flair",
- "span.persona-flair",
- hbs`{{@data.personaName}}`
- );
}
function initializePauseButton(api) {
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/translation.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/translation.js
index d327ff6833d..4405d36e747 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/translation.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/translation.js
@@ -13,11 +13,7 @@ export default apiInitializer((api) => {
(topicController, data) => {
if (!cookie("content-localization-show-original")) {
const postStream = topicController.get("model.postStream");
- postStream.triggerChangedPost(data.id, data.updated_at).then(() => {
- topicController.appEvents.trigger("post-stream:refresh", {
- id: data.id,
- });
- });
+ postStream.triggerChangedPost(data.id, data.updated_at);
}
}
);
diff --git a/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb
index 5553fed123f..36b1957f2c4 100644
--- a/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb
+++ b/plugins/discourse-ai/spec/system/ai_bot/homepage_spec.rb
@@ -108,350 +108,342 @@ RSpec.describe "AI Bot - Homepage", type: :system do
sign_in(user)
end
- %w[enabled disabled].each do |value|
- before { SiteSetting.glimmer_post_stream_mode = value }
-
- context "when glimmer_post_stream_mode=#{value}" do
- context "when mobile", mobile: true do
- it "allows navigating from AI conversation to regular topic, and loads new post stream" do
- regular_topic = Fabricate(:topic)
- regular_post = Fabricate(:post, topic: regular_topic)
-
- post_url = Topic.relative_url(regular_topic.id, regular_topic.slug)
- post_with_link =
- Fabricate(
- :post,
- topic: pm,
- user: user,
- post_number: 4,
- raw: "This is a second reply by the user [link](#{post_url})",
- )
-
- topic_page.visit_topic(pm)
- page.find(
- "article[data-post-id='#{post_with_link.id}'] .cooked a[href='#{post_url}']",
- ).click
-
- expect(topic_page.current_topic).to eq(regular_topic)
- expect(page).to have_css("article[data-post-id='#{regular_post.id}']")
- end
+ context "when mobile", mobile: true do
+ it "allows navigating from AI conversation to regular topic, and loads new post stream" do
+ regular_topic = Fabricate(:topic)
+ regular_post = Fabricate(:post, topic: regular_topic)
+
+ post_url = Topic.relative_url(regular_topic.id, regular_topic.slug)
+ post_with_link =
+ Fabricate(
+ :post,
+ topic: pm,
+ user: user,
+ post_number: 4,
+ raw: "This is a second reply by the user [link](#{post_url})",
+ )
+
+ topic_page.visit_topic(pm)
+ page.find("article[data-post-id='#{post_with_link.id}'] .cooked a[href='#{post_url}']").click
+
+ expect(topic_page.current_topic).to eq(regular_topic)
+ expect(page).to have_css("article[data-post-id='#{regular_post.id}']")
+ end
+ end
+
+ context "when `ai_bot_enable_dedicated_ux` is enabled" do
+ before { SiteSetting.ai_bot_add_to_header = true }
+
+ it "allows uploading files to a new conversation" do
+ ai_pm_homepage.visit
+ expect(ai_pm_homepage).to have_homepage
+
+ file_path_1 = file_from_fixtures("logo.png", "images").path
+ file_path_2 = file_from_fixtures("logo.jpg", "images").path
+ attach_file("ai-bot-file-uploader", [file_path_1, file_path_2], make_visible: true)
+
+ expect(page).to have_css(".ai-bot-upload", count: 2)
+
+ ai_pm_homepage.input.fill_in(with: "Here are two image attachments")
+
+ expect(page).to have_no_css(".ai-bot-upload--in-progress")
+
+ responses = ["hello user", "topic title"]
+ DiscourseAi::Completions::Llm.with_prepared_responses(responses) do
+ ai_pm_homepage.submit
+ expect(topic_page).to have_content("Here are two image attachments")
+ expect(page).to have_css(".cooked img", count: 2)
+ end
+
+ find(".ai-new-question-button").click
+ expect(ai_pm_homepage).to have_homepage
+ expect(page).to have_no_css(".ai-bot-upload")
+ end
+
+ it "shows an error when trying to submit while uploads are in progress" do
+ ai_pm_homepage.visit
+ expect(ai_pm_homepage).to have_homepage
+
+ file_path_1 = file_from_fixtures("logo.png", "images").path
+ file_path_2 = file_from_fixtures("logo.jpg", "images").path
+
+ ai_pm_homepage.input.fill_in(with: "Some message to send to AI with uploads")
+
+ cdp.with_slow_upload do
+ attach_file("ai-bot-file-uploader", [file_path_1, file_path_2], make_visible: true)
+ expect(page).to have_css(".ai-bot-upload--in-progress", count: 2)
+
+ ai_pm_homepage.submit
+ expect(page).to have_content(
+ I18n.t("js.discourse_ai.ai_bot.conversations.uploads_in_progress"),
+ )
end
+ end
- context "when `ai_bot_enable_dedicated_ux` is enabled" do
- before { SiteSetting.ai_bot_add_to_header = true }
-
- it "allows uploading files to a new conversation" do
- ai_pm_homepage.visit
- expect(ai_pm_homepage).to have_homepage
-
- file_path_1 = file_from_fixtures("logo.png", "images").path
- file_path_2 = file_from_fixtures("logo.jpg", "images").path
- attach_file("ai-bot-file-uploader", [file_path_1, file_path_2], make_visible: true)
-
- expect(page).to have_css(".ai-bot-upload", count: 2)
-
- ai_pm_homepage.input.fill_in(with: "Here are two image attachments")
-
- expect(page).to have_no_css(".ai-bot-upload--in-progress")
-
- responses = ["hello user", "topic title"]
- DiscourseAi::Completions::Llm.with_prepared_responses(responses) do
- ai_pm_homepage.submit
- expect(topic_page).to have_content("Here are two image attachments")
- expect(page).to have_css(".cooked img", count: 2)
- end
-
- find(".ai-new-question-button").click
- expect(ai_pm_homepage).to have_homepage
- expect(page).to have_no_css(".ai-bot-upload")
- end
-
- it "shows an error when trying to submit while uploads are in progress" do
- ai_pm_homepage.visit
- expect(ai_pm_homepage).to have_homepage
-
- file_path_1 = file_from_fixtures("logo.png", "images").path
- file_path_2 = file_from_fixtures("logo.jpg", "images").path
-
- ai_pm_homepage.input.fill_in(with: "Some message to send to AI with uploads")
-
- cdp.with_slow_upload do
- attach_file("ai-bot-file-uploader", [file_path_1, file_path_2], make_visible: true)
- expect(page).to have_css(".ai-bot-upload--in-progress", count: 2)
-
- ai_pm_homepage.submit
- expect(page).to have_content(
- I18n.t("js.discourse_ai.ai_bot.conversations.uploads_in_progress"),
- )
- end
- end
-
- it "allows removing an upload before submission" do
- ai_pm_homepage.visit
- expect(ai_pm_homepage).to have_homepage
-
- file_path = file_from_fixtures("logo.png", "images").path
- attach_file("ai-bot-file-uploader", file_path, make_visible: true)
- expect(page).to have_css(".ai-bot-upload", count: 1)
-
- find(".ai-bot-upload__remove").click
-
- expect(page).to have_no_css(".ai-bot-upload")
-
- ai_pm_homepage.input.fill_in(with: "Message without attachments")
-
- responses = ["hello user", "topic title"]
- DiscourseAi::Completions::Llm.with_prepared_responses(responses) do
- ai_pm_homepage.submit
- expect(topic_page).to have_content("Message without attachments")
- expect(page).to have_no_css(".cooked img")
- end
- end
-
- it "renders landing page on bot click" do
- visit "/"
- header.click_bot_button
- expect(ai_pm_homepage).to have_homepage
- expect(sidebar).to be_visible
- end
-
- it "displays error when message is too short" do
- visit "/"
- header.click_bot_button
-
- ai_pm_homepage.input.fill_in(with: "a")
- ai_pm_homepage.submit
- expect(ai_pm_homepage).to have_too_short_dialog
- dialog.click_yes
- expect(composer).to be_closed
- end
-
- it "hides default content in the sidebar" do
- visit "/"
- header.click_bot_button
-
- expect(ai_pm_homepage).to have_homepage
- expect(sidebar).to have_no_tags_section
- expect(sidebar).to have_no_section("categories")
- expect(sidebar).to have_no_section("chat-dms")
- expect(sidebar).to have_no_section("chat-channels")
- expect(sidebar).to have_no_section("user-threads")
- end
-
- it "shows the bot conversation in the sidebar" do
- visit "/"
- header.click_bot_button
-
- expect(ai_pm_homepage).to have_homepage
- expect(sidebar).to have_section("Today")
- expect(sidebar).to have_section_link(pm.title)
- end
-
- it "allows navigating to a specific LLM and persona" do
- # url encode name
- persona_name = CGI.escape(persona.name)
- llm_name = CGI.escape(claude_2_dup.display_name)
- visit "/discourse-ai/ai-bot/conversations?persona=#{persona_name}&llm=#{llm_name}"
-
- ai_pm_homepage.persona_selector.expand # not needed, but helps to see what the list has
- expect(ai_pm_homepage.persona_selector).to have_selected_name(persona.name)
- expect(ai_pm_homepage.llm_selector).to have_selected_name(claude_2_dup.display_name)
- end
-
- it "removes persona from selector when allow_personal_messages is disabled" do
- begin
- persona.update!(allow_personal_messages: false)
- ai_pm_homepage.visit
- ai_pm_homepage.persona_selector.expand
- expect(ai_pm_homepage.persona_selector).to have_no_option_name(persona.name)
- ensure
- persona.update!(allow_personal_messages: true)
- end
- end
-
- it "includes persona in selector when allow_personal_messages is enabled" do
- # default is true
- ai_pm_homepage.visit
- ai_pm_homepage.persona_selector.expand
- expect(ai_pm_homepage.persona_selector).to have_option_name(persona.name)
- end
-
- it "shows empty state when no PMs exist" do
- pm.destroy!
-
- visit "/"
- header.click_bot_button
-
- expect(page).to have_css(".sidebar-section .ai-bot-sidebar-empty-state", visible: true)
- end
-
- it "doesn't show empty state when a PM exists" do
- visit "/"
- header.click_bot_button
-
- expect(page).to have_no_css(".sidebar-section .ai-bot-sidebar-empty-state")
- end
-
- it "displays last_7_days label in the sidebar" do
- pm.update!(last_posted_at: 5.days.ago)
- visit "/"
- header.click_bot_button
-
- expect(ai_pm_homepage).to have_homepage
- expect(sidebar).to have_section("Last 7 days")
- end
-
- it "displays last_30_days label in the sidebar" do
- pm.update!(last_posted_at: 28.days.ago)
- visit "/"
- header.click_bot_button
-
- expect(ai_pm_homepage).to have_homepage
- expect(sidebar).to have_section("Last 30 days")
- end
-
- it "displays month and year label in the sidebar for older conversations" do
- pm.update!(last_posted_at: "2024-04-10 15:39:11.406192000 +00:00")
- visit "/"
- header.click_bot_button
-
- expect(ai_pm_homepage).to have_homepage
- expect(sidebar).to have_section("2024-3")
- end
-
- it "navigates to the bot conversation when clicked" do
- visit "/"
- header.click_bot_button
-
- expect(ai_pm_homepage).to have_homepage
- ai_pm_homepage.click_fist_sidebar_conversation
- expect(topic_page).to have_topic_title(pm.title)
- end
-
- it "displays the shuffle icon when on homepage or bot PM" do
- visit "/"
- expect(header).to have_icon_in_bot_button(icon: "robot")
- header.click_bot_button
-
- expect(header).to have_icon_in_bot_button(icon: "shuffle")
-
- # Go to a PM and assert that the icon is still shuffle
- ai_pm_homepage.click_fist_sidebar_conversation
- expect(header).to have_icon_in_bot_button(icon: "shuffle")
-
- # Go back home and assert that the icon is now robot again
- header.click_bot_button
- expect(header).to have_icon_in_bot_button(icon: "robot")
- end
-
- it "displays 'new question' button on homepage and topic page" do
- topic_page.visit_topic(pm)
- expect(ai_pm_homepage).to have_new_question_button
-
- ai_pm_homepage.visit
- expect(ai_pm_homepage).to have_new_question_button
- end
-
- it "redirect to the homepage when 'new question' is clicked" do
- topic_page.visit_topic(pm)
- expect(sidebar).to be_visible
- ai_pm_homepage.click_new_question_button
- expect(ai_pm_homepage).to have_homepage
- end
-
- it "can send a new message to the bot" do
- topic_page.visit_topic(pm)
- topic_page.click_reply_button
- expect(composer).to be_opened
-
- composer.fill_in(with: "Hello bot replying to you")
- composer.submit
- expect(page).to have_content("Hello bot replying to you")
- end
-
- it "does not render custom sidebar on non-authored bot pms" do
- # Include user_2 in the PM by creating a new post and topic_allowed_user association
- Fabricate(:post, topic: pm, user: user_2, post_number: 4)
- Fabricate(:topic_allowed_user, topic: pm, user: user_2)
- sign_in(user_2)
-
- topic_page.visit_topic(pm)
-
- expect(sidebar).to be_visible
- expect(sidebar).to have_no_section("ai-conversations-history")
- expect(sidebar).to have_no_css("button.ai-new-question-button")
- end
-
- it "does not include non-authored bot pms in sidebar" do
- # Include user_2 in the PM by creating a new post and topic_allowed_user association
- Fabricate(:post, topic: pm, user: user_2, post_number: 4)
- Fabricate(:topic_allowed_user, topic: pm, user: user_2)
- sign_in(user_2)
- visit "/"
- header.click_bot_button
- expect(ai_pm_homepage).to have_homepage
- expect(sidebar).to have_no_section_link(pm.title)
- end
-
- it "Allows choosing persona and LLM" do
- ai_pm_homepage.visit
-
- ai_pm_homepage.llm_selector.expand
- ai_pm_homepage.llm_selector.select_row_by_name(claude_2_dup.display_name)
- ai_pm_homepage.llm_selector.collapse
-
- # confirm memory works for llm selection
- ai_pm_homepage.visit
- expect(ai_pm_homepage.llm_selector).to have_selected_name(claude_2_dup.display_name)
- end
-
- it "renders back to forum link when header button is disabled" do
- SiteSetting.ai_bot_add_to_header = false
- ai_pm_homepage.visit
- expect(ai_pm_homepage).to have_sidebar_back_link
- end
-
- context "with hamburger menu" do
- before do
- SiteSetting.navigation_menu = "header dropdown"
- SiteSetting.ai_bot_add_to_header = true
- end
-
- it "keeps robot icon in the header and doesn't display sidebar back link" do
- visit "/"
- expect(header).to have_icon_in_bot_button(icon: "robot")
- header.click_bot_button
- expect(ai_pm_homepage).to have_homepage
- expect(header).to have_icon_in_bot_button(icon: "robot")
- expect(ai_pm_homepage).to have_no_sidebar_back_link
- end
-
- it "still renders the sidebar" do
- visit "/"
- header.click_bot_button
- expect(ai_pm_homepage).to have_homepage
- expect(sidebar).to be_visible
- expect(header_dropdown).to be_visible
- end
- end
+ it "allows removing an upload before submission" do
+ ai_pm_homepage.visit
+ expect(ai_pm_homepage).to have_homepage
+
+ file_path = file_from_fixtures("logo.png", "images").path
+ attach_file("ai-bot-file-uploader", file_path, make_visible: true)
+ expect(page).to have_css(".ai-bot-upload", count: 1)
+
+ find(".ai-bot-upload__remove").click
+
+ expect(page).to have_no_css(".ai-bot-upload")
+
+ ai_pm_homepage.input.fill_in(with: "Message without attachments")
+
+ responses = ["hello user", "topic title"]
+ DiscourseAi::Completions::Llm.with_prepared_responses(responses) do
+ ai_pm_homepage.submit
+ expect(topic_page).to have_content("Message without attachments")
+ expect(page).to have_no_css(".cooked img")
end
+ end
+
+ it "renders landing page on bot click" do
+ visit "/"
+ header.click_bot_button
+ expect(ai_pm_homepage).to have_homepage
+ expect(sidebar).to be_visible
+ end
+
+ it "displays error when message is too short" do
+ visit "/"
+ header.click_bot_button
+
+ ai_pm_homepage.input.fill_in(with: "a")
+ ai_pm_homepage.submit
+ expect(ai_pm_homepage).to have_too_short_dialog
+ dialog.click_yes
+ expect(composer).to be_closed
+ end
+
+ it "hides default content in the sidebar" do
+ visit "/"
+ header.click_bot_button
+
+ expect(ai_pm_homepage).to have_homepage
+ expect(sidebar).to have_no_tags_section
+ expect(sidebar).to have_no_section("categories")
+ expect(sidebar).to have_no_section("chat-dms")
+ expect(sidebar).to have_no_section("chat-channels")
+ expect(sidebar).to have_no_section("user-threads")
+ end
+
+ it "shows the bot conversation in the sidebar" do
+ visit "/"
+ header.click_bot_button
+
+ expect(ai_pm_homepage).to have_homepage
+ expect(sidebar).to have_section("Today")
+ expect(sidebar).to have_section_link(pm.title)
+ end
+
+ it "allows navigating to a specific LLM and persona" do
+ # url encode name
+ persona_name = CGI.escape(persona.name)
+ llm_name = CGI.escape(claude_2_dup.display_name)
+ visit "/discourse-ai/ai-bot/conversations?persona=#{persona_name}&llm=#{llm_name}"
+
+ ai_pm_homepage.persona_selector.expand # not needed, but helps to see what the list has
+ expect(ai_pm_homepage.persona_selector).to have_selected_name(persona.name)
+ expect(ai_pm_homepage.llm_selector).to have_selected_name(claude_2_dup.display_name)
+ end
+
+ it "removes persona from selector when allow_personal_messages is disabled" do
+ begin
+ persona.update!(allow_personal_messages: false)
+ ai_pm_homepage.visit
+ ai_pm_homepage.persona_selector.expand
+ expect(ai_pm_homepage.persona_selector).to have_no_option_name(persona.name)
+ ensure
+ persona.update!(allow_personal_messages: true)
+ end
+ end
+
+ it "includes persona in selector when allow_personal_messages is enabled" do
+ # default is true
+ ai_pm_homepage.visit
+ ai_pm_homepage.persona_selector.expand
+ expect(ai_pm_homepage.persona_selector).to have_option_name(persona.name)
+ end
+
+ it "shows empty state when no PMs exist" do
+ pm.destroy!
+
+ visit "/"
+ header.click_bot_button
+
+ expect(page).to have_css(".sidebar-section .ai-bot-sidebar-empty-state", visible: true)
+ end
- context "with header dropdown on mobile", mobile: true do
- before { SiteSetting.navigation_menu = "header dropdown" }
+ it "doesn't show empty state when a PM exists" do
+ visit "/"
+ header.click_bot_button
- it "displays the new question button in the menu when viewing a PM" do
- ai_pm_homepage.visit
- header_dropdown.open
- expect(ai_pm_homepage).to have_new_question_button
+ expect(page).to have_no_css(".sidebar-section .ai-bot-sidebar-empty-state")
+ end
+
+ it "displays last_7_days label in the sidebar" do
+ pm.update!(last_posted_at: 5.days.ago)
+ visit "/"
+ header.click_bot_button
+
+ expect(ai_pm_homepage).to have_homepage
+ expect(sidebar).to have_section("Last 7 days")
+ end
+
+ it "displays last_30_days label in the sidebar" do
+ pm.update!(last_posted_at: 28.days.ago)
+ visit "/"
+ header.click_bot_button
+
+ expect(ai_pm_homepage).to have_homepage
+ expect(sidebar).to have_section("Last 30 days")
+ end
+
+ it "displays month and year label in the sidebar for older conversations" do
+ pm.update!(last_posted_at: "2024-04-10 15:39:11.406192000 +00:00")
+ visit "/"
+ header.click_bot_button
+
+ expect(ai_pm_homepage).to have_homepage
+ expect(sidebar).to have_section("2024-3")
+ end
+
+ it "navigates to the bot conversation when clicked" do
+ visit "/"
+ header.click_bot_button
+
+ expect(ai_pm_homepage).to have_homepage
+ ai_pm_homepage.click_fist_sidebar_conversation
+ expect(topic_page).to have_topic_title(pm.title)
+ end
+
+ it "displays the shuffle icon when on homepage or bot PM" do
+ visit "/"
+ expect(header).to have_icon_in_bot_button(icon: "robot")
+ header.click_bot_button
+
+ expect(header).to have_icon_in_bot_button(icon: "shuffle")
+
+ # Go to a PM and assert that the icon is still shuffle
+ ai_pm_homepage.click_fist_sidebar_conversation
+ expect(header).to have_icon_in_bot_button(icon: "shuffle")
+
+ # Go back home and assert that the icon is now robot again
+ header.click_bot_button
+ expect(header).to have_icon_in_bot_button(icon: "robot")
+ end
- topic_page.visit_topic(pm)
- header_dropdown.open
- ai_pm_homepage.click_new_question_button
+ it "displays 'new question' button on homepage and topic page" do
+ topic_page.visit_topic(pm)
+ expect(ai_pm_homepage).to have_new_question_button
- # Hamburger sidebar is closed
- expect(header_dropdown).to have_no_dropdown_visible
- end
+ ai_pm_homepage.visit
+ expect(ai_pm_homepage).to have_new_question_button
+ end
+
+ it "redirect to the homepage when 'new question' is clicked" do
+ topic_page.visit_topic(pm)
+ expect(sidebar).to be_visible
+ ai_pm_homepage.click_new_question_button
+ expect(ai_pm_homepage).to have_homepage
+ end
+
+ it "can send a new message to the bot" do
+ topic_page.visit_topic(pm)
+ topic_page.click_reply_button
+ expect(composer).to be_opened
+
+ composer.fill_in(with: "Hello bot replying to you")
+ composer.submit
+ expect(page).to have_content("Hello bot replying to you")
+ end
+
+ it "does not render custom sidebar on non-authored bot pms" do
+ # Include user_2 in the PM by creating a new post and topic_allowed_user association
+ Fabricate(:post, topic: pm, user: user_2, post_number: 4)
+ Fabricate(:topic_allowed_user, topic: pm, user: user_2)
+ sign_in(user_2)
+
+ topic_page.visit_topic(pm)
+
+ expect(sidebar).to be_visible
+ expect(sidebar).to have_no_section("ai-conversations-history")
+ expect(sidebar).to have_no_css("button.ai-new-question-button")
+ end
+
+ it "does not include non-authored bot pms in sidebar" do
+ # Include user_2 in the PM by creating a new post and topic_allowed_user association
+ Fabricate(:post, topic: pm, user: user_2, post_number: 4)
+ Fabricate(:topic_allowed_user, topic: pm, user: user_2)
+ sign_in(user_2)
+ visit "/"
+ header.click_bot_button
+ expect(ai_pm_homepage).to have_homepage
+ expect(sidebar).to have_no_section_link(pm.title)
+ end
+
+ it "Allows choosing persona and LLM" do
+ ai_pm_homepage.visit
+
+ ai_pm_homepage.llm_selector.expand
+ ai_pm_homepage.llm_selector.select_row_by_name(claude_2_dup.display_name)
+ ai_pm_homepage.llm_selector.collapse
+
+ # confirm memory works for llm selection
+ ai_pm_homepage.visit
+ expect(ai_pm_homepage.llm_selector).to have_selected_name(claude_2_dup.display_name)
+ end
+
+ it "renders back to forum link when header button is disabled" do
+ SiteSetting.ai_bot_add_to_header = false
+ ai_pm_homepage.visit
+ expect(ai_pm_homepage).to have_sidebar_back_link
+ end
+
+ context "with hamburger menu" do
+ before do
+ SiteSetting.navigation_menu = "header dropdown"
+ SiteSetting.ai_bot_add_to_header = true
+ end
+
+ it "keeps robot icon in the header and doesn't display sidebar back link" do
+ visit "/"
+ expect(header).to have_icon_in_bot_button(icon: "robot")
+ header.click_bot_button
+ expect(ai_pm_homepage).to have_homepage
+ expect(header).to have_icon_in_bot_button(icon: "robot")
+ expect(ai_pm_homepage).to have_no_sidebar_back_link
end
+
+ it "still renders the sidebar" do
+ visit "/"
+ header.click_bot_button
+ expect(ai_pm_homepage).to have_homepage
+ expect(sidebar).to be_visible
+ expect(header_dropdown).to be_visible
+ end
+ end
+ end
+
+ context "with header dropdown on mobile", mobile: true do
+ before { SiteSetting.navigation_menu = "header dropdown" }
+
+ it "displays the new question button in the menu when viewing a PM" do
+ ai_pm_homepage.visit
+ header_dropdown.open
+ expect(ai_pm_homepage).to have_new_question_button
+
+ topic_page.visit_topic(pm)
+ header_dropdown.open
+ ai_pm_homepage.click_new_question_button
+
+ # Hamburger sidebar is closed
+ expect(header_dropdown).to have_no_dropdown_visible
end
end
end
diff --git a/plugins/discourse-assign/assets/javascripts/discourse/components/topic-level-assign-menu.js b/plugins/discourse-assign/assets/javascripts/discourse/components/topic-level-assign-menu.js
index 76c0dc22a21..b702a94cee6 100644
--- a/plugins/discourse-assign/assets/javascripts/discourse/components/topic-level-assign-menu.js
+++ b/plugins/discourse-assign/assets/javascripts/discourse/components/topic-level-assign-menu.js
@@ -24,7 +24,6 @@ export default {
const taskActions = getOwner(this).lookup("service:task-actions");
const modal = getOwner(this).lookup("service:modal");
- const firstPostId = this.topic.postStream.firstPostId;
switch (id) {
case "unassign": {
@@ -32,8 +31,6 @@ export default {
this.topic.assigned_to_group = null;
await taskActions.unassign(this.topic.id);
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { id: firstPostId });
break;
}
case "reassign-self": {
@@ -41,8 +38,6 @@ export default {
this.topic.assigned_to_group = null;
await taskActions.reassignUserToTopic(this.currentUser, this.topic);
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { id: firstPostId });
break;
}
case "reassign": {
@@ -50,9 +45,6 @@ export default {
model: {
topic: this.topic,
},
- onSuccess: () =>
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { id: firstPostId }),
});
break;
}
@@ -66,8 +58,6 @@ export default {
// force the components tracking `topic.indirectly_assigned_to` to update
// eslint-disable-next-line no-self-assign
this.topic.indirectly_assigned_to = this.topic.indirectly_assigned_to;
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", { id: firstPostId });
}
}
}
diff --git a/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js b/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js
index 7b194cf1b77..da046192591 100644
--- a/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js
+++ b/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js
@@ -1,20 +1,14 @@
import { action } from "@ember/object";
import { getOwner } from "@ember/owner";
import { htmlSafe } from "@ember/template";
-import { isEmpty } from "@ember/utils";
-import { hbs } from "ember-cli-htmlbars";
-import { h } from "virtual-dom";
import { renderAvatar } from "discourse/helpers/user-avatar";
import discourseComputed from "discourse/lib/decorators";
-import { withSilencedDeprecations } from "discourse/lib/deprecated";
import getURL from "discourse/lib/get-url";
-import { iconHTML, iconNode } from "discourse/lib/icon-library";
+import { iconHTML } from "discourse/lib/icon-library";
import { withPluginApi } from "discourse/lib/plugin-api";
import { registerTopicFooterDropdown } from "discourse/lib/register-topic-footer-dropdown";
import { applyValueTransformer } from "discourse/lib/transformer";
import { escapeExpression } from "discourse/lib/utilities";
-import RawHtml from "discourse/widgets/raw-html";
-import RenderGlimmer from "discourse/widgets/render-glimmer";
import { i18n } from "discourse-i18n";
import AssignButton from "../components/assign-button";
import BulkActionsAssignUser from "../components/bulk-actions/bulk-assign-user";
@@ -78,21 +72,11 @@ function registerTopicFooterButtons(api) {
this.topic.assigned_to_group = null;
await taskActions.unassign(this.topic.id, "Topic");
-
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", {
- id: this.topic.postStream.firstPostId,
- });
} else {
await modal.show(EditTopicAssignments, {
model: {
topic: this.topic,
},
- onSuccess: () =>
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", {
- id: this.topic.postStream.firstPostId,
- }),
});
}
},
@@ -176,12 +160,7 @@ function registerTopicFooterButtons(api) {
this.topic.assigned_to_user = null;
this.topic.assigned_to_group = null;
- taskActions.unassign(this.topic.id).then(() => {
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", {
- id: this.topic.postStream.firstPostId,
- });
- });
+ taskActions.unassign(this.topic.id);
},
dropdown() {
return this.currentUser?.can_assign && this.topic.isAssigned();
@@ -227,11 +206,6 @@ function registerTopicFooterButtons(api) {
this.topic.assigned_to_group = null;
await taskActions.reassignUserToTopic(this.currentUser, this.topic);
-
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", {
- id: this.topic.postStream.firstPostId,
- });
},
dropdown() {
return this.currentUser?.can_assign && this.topic.isAssigned();
@@ -277,11 +251,6 @@ function registerTopicFooterButtons(api) {
await taskActions.showAssignModal(this.topic, {
targetType: "Topic",
isAssigned: this.topic.isAssigned(),
- onSuccess: () =>
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", {
- id: this.topic.postStream.firstPostId,
- }),
});
},
dropdown() {
@@ -524,21 +493,6 @@ function initialize(api) {
} else if (data.type === "unassigned") {
delete topic.indirectly_assigned_to[data.post_id];
}
-
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", {
- id: topic.postStream.posts[0].id,
- });
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", {
- id: data.post_id,
- });
- }
- if (topic.closed) {
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", {
- id: topic.postStream.posts[0].id,
- });
}
}
// force the components tracking `topic.indirectly_assigned_to` to update
@@ -546,10 +500,6 @@ function initialize(api) {
topic.indirectly_assigned_to = topic.indirectly_assigned_to;
this.appEvents.trigger("header:update-topic", topic);
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- this.appEvents.trigger("post-stream:refresh", {
- id: topic.postStream.posts[0].id,
- });
});
}
@@ -627,8 +577,7 @@ function customizePost(api, siteSettings) {
);
api.addPostSmallActionClassesCallback((post) => {
- // TODO (glimmer-post-stream): only check for .action_code once the widget code is removed
- const actionCode = post.action_code || post.actionCode;
+ const actionCode = post.action_code;
if (actionCode.includes("assigned") && !siteSettings.assigns_public) {
return ["private-assign"];
@@ -645,170 +594,6 @@ function customizePost(api, siteSettings) {
api.addPostSmallActionIcon("unassigned_group_from_post", "group-times");
api.addPostSmallActionIcon("reassigned", "user-plus");
api.addPostSmallActionIcon("reassigned_group", "group-plus");
-
- withSilencedDeprecations("discourse.post-stream-widget-overrides", () =>
- customizeWidgetPost(api)
- );
-}
-
-function customizeWidgetPost(api) {
- api.decorateWidget("post-contents:after-cooked", (dec) => {
- const postModel = dec.getModel();
- if (postModel) {
- let assignedToUser, assignedToGroup, postAssignment, href;
- if (dec.attrs.post_number === 1) {
- return dec.widget.attach("assigned-to-first-post", {
- topic: postModel.topic,
- });
- } else {
- postAssignment =
- postModel.topic.indirectly_assigned_to?.[postModel.id]?.assigned_to;
- if (postAssignment?.username) {
- assignedToUser = postAssignment;
- }
- if (postAssignment?.name) {
- assignedToGroup = postAssignment;
- }
- }
- if (assignedToUser || assignedToGroup) {
- href = assignedToUser
- ? assignedToUserPath(assignedToUser)
- : assignedToGroupPath(assignedToGroup);
- }
-
- if (href) {
- return dec.widget.attach("assigned-to-post", {
- assignedToUser,
- assignedToGroup,
- href,
- post: postModel,
- });
- }
- }
- });
-
- api.createWidget("assigned-to-post", {
- html(attrs) {
- return new RenderGlimmer(
- this,
- "p.assigned-to",
- hbs`
- <AssignedToPost @assignedToUser={{@data.assignedToUser}} @assignedToGroup={{@data.assignedToGroup}}
- @href={{@data.href}} @post={{@data.post}} />`,
- {
- assignedToUser: attrs.post.assigned_to_user,
- assignedToGroup: attrs.post.assigned_to_group,
- href: attrs.href,
- post: attrs.post,
- }
- );
- },
- });
-
- api.createWidget("assigned-to-first-post", {
- html(attrs) {
- const topic = attrs.topic;
- const [assignedToUser, assignedToGroup, indirectlyAssignedTo] = [
- topic.assigned_to_user,
- topic.assigned_to_group,
- topic.indirectly_assigned_to,
- ];
- const assigneeElements = [];
-
- const assignedHtml = (username, path, type) => {
- return `<span class="assigned-to--${type}">${htmlSafe(
- i18n("discourse_assign.assigned_topic_to", {
- username,
- path,
- })
- )}</span>`;
- };
-
- let displayedName = "";
- if (assignedToUser) {
- displayedName = this.siteSettings.prioritize_full_name_in_ux
- ? assignedToUser.name || assignedToUser.username
- : assignedToUser.username;
-
- assigneeElements.push(
- h(
- "span.assignee",
- new RawHtml({
- html: assignedHtml(
- displayedName,
- assignedToUserPath(assignedToUser),
- "user"
- ),
- })
- )
- );
- }
-
- if (assignedToGroup) {
- assigneeElements.push(
- h(
- "span.assignee",
- new RawHtml({
- html: assignedHtml(
- assignedToGroup.name,
- assignedToGroupPath(assignedToGroup),
- "group"
- ),
- })
- )
- );
- }
-
- if (indirectlyAssignedTo) {
- Object.keys(indirectlyAssignedTo).map((postId) => {
- const assignee = indirectlyAssignedTo[postId].assigned_to;
- const postNumber = indirectlyAssignedTo[postId].post_number;
-
- displayedName =
- !this.siteSettings.prioritize_username_in_ux || !assignee.username
- ? assignee.name || assignee.username
- : assignee.username;
-
- assigneeElements.push(
- h("span.assignee", [
- h(
- "a",
- {
- attributes: {
- class: "assigned-indirectly",
- href: `${topic.url}/${postNumber}`,
- },
- },
- i18n("discourse_assign.assign_post_to_multiple", {
- post_number: postNumber,
- username: displayedName,
- })
- ),
- ])
- );
- });
- }
-
- if (!isEmpty(assigneeElements)) {
- return h("p.assigned-to", [
- assignedToUser ? iconNode("user-plus") : iconNode("group-plus"),
- assignedToUser || assignedToGroup
- ? ""
- : h("span.assign-text", i18n("discourse_assign.assigned")),
- assigneeElements,
- ]);
- }
- },
- });
-
- // `addPostTransformCallback` doesn't have a direct translation in the new Glimmer API.
- // We need to use a modify class in the post model instead
- api.addPostTransformCallback((transformed) => {
- if (isAssignSmallAction(transformed.actionCode)) {
- transformed.isSmallAction = true;
- transformed.canEdit = true;
- }
- });
}
function isAssignSmallAction(actionCode) {
diff --git a/plugins/discourse-assign/spec/system/assign_topic_spec.rb b/plugins/discourse-assign/spec/system/assign_topic_spec.rb
index e7bc7fcb992..0ecac549f5a 100644
--- a/plugins/discourse-assign/spec/system/assign_topic_spec.rb
+++ b/plugins/discourse-assign/spec/system/assign_topic_spec.rb
@@ -17,174 +17,168 @@ describe "Assign | Assigning topics", type: :system do
sign_in(admin1)
end
- %w[enabled disabled].each do |value|
- before { SiteSetting.glimmer_post_stream_mode = value }
+ describe "with open topic" do
+ it "can assign and unassign" do
+ visit "/t/#{topic.id}"
- context "when glimmer_post_stream_mode=#{value}" do
- describe "with open topic" do
- it "can assign and unassign" do
- visit "/t/#{topic.id}"
+ topic_page.click_assign_topic
+ assign_modal.assignee = admin2
+ assign_modal.confirm
- topic_page.click_assign_topic
- assign_modal.assignee = admin2
- assign_modal.confirm
+ expect(assign_modal).to be_closed
- expect(assign_modal).to be_closed
+ expect(topic_page).to have_assigned(user: admin2, at_post: 2)
+ expect(find("#topic .assigned-to")).to have_content(admin2.username)
- expect(topic_page).to have_assigned(user: admin2, at_post: 2)
- expect(find("#topic .assigned-to")).to have_content(admin2.username)
+ topic_page.click_unassign_topic
- topic_page.click_unassign_topic
+ expect(topic_page).to have_unassigned(user: admin2, at_post: 3)
+ expect(page).to have_no_css("#topic .assigned-to")
+ end
- expect(topic_page).to have_unassigned(user: admin2, at_post: 3)
- expect(page).to have_no_css("#topic .assigned-to")
- end
+ it "can submit form with shortcut from texatea" do
+ visit "/t/#{topic.id}"
- it "can submit form with shortcut from texatea" do
- visit "/t/#{topic.id}"
+ topic_page.click_assign_topic
+ assign_modal.assignee = admin2
- topic_page.click_assign_topic
- assign_modal.assignee = admin2
-
- find("body").send_keys(:tab)
- find("body").send_keys(:control, :enter)
+ find("body").send_keys(:tab)
+ find("body").send_keys(:control, :enter)
- expect(assign_modal).to be_closed
+ expect(assign_modal).to be_closed
- expect(topic_page).to have_assigned(user: admin2, at_post: 2)
- expect(find("#topic .assigned-to")).to have_content(admin2.username)
- end
+ expect(topic_page).to have_assigned(user: admin2, at_post: 2)
+ expect(find("#topic .assigned-to")).to have_content(admin2.username)
+ end
- context "when prioritize_full_name_in_ux setting is enabled" do
- before { SiteSetting.prioritize_full_name_in_ux = true }
+ context "when prioritize_full_name_in_ux setting is enabled" do
+ before { SiteSetting.prioritize_full_name_in_ux = true }
- it "shows the user's name after assign" do
- visit "/t/#{topic.id}"
+ it "shows the user's name after assign" do
+ visit "/t/#{topic.id}"
- topic_page.click_assign_topic
- assign_modal.assignee = admin2
- assign_modal.confirm
- expect(find("#topic .assigned-to")).to have_content(admin2.name)
- end
+ topic_page.click_assign_topic
+ assign_modal.assignee = admin2
+ assign_modal.confirm
+ expect(find("#topic .assigned-to")).to have_content(admin2.name)
+ end
- it "show the user's username if there is no name" do
- visit "/t/#{topic.id}"
- admin2.name = nil
- admin2.save!
- admin2.reload
+ it "show the user's username if there is no name" do
+ visit "/t/#{topic.id}"
+ admin2.name = nil
+ admin2.save!
+ admin2.reload
- topic_page.click_assign_topic
- assign_modal.assignee = admin2
- assign_modal.confirm
- expect(find("#topic .assigned-to")).to have_content(admin2.username)
- end
- end
+ topic_page.click_assign_topic
+ assign_modal.assignee = admin2
+ assign_modal.confirm
+ expect(find("#topic .assigned-to")).to have_content(admin2.username)
+ end
+ end
- context "when assigns are not public" do
- before { SiteSetting.assigns_public = false }
+ context "when assigns are not public" do
+ before { SiteSetting.assigns_public = false }
- it "assigned small action post has 'private-assign' in class attribute" do
- visit "/t/#{topic.id}"
+ it "assigned small action post has 'private-assign' in class attribute" do
+ visit "/t/#{topic.id}"
- topic_page.click_assign_topic
- assign_modal.assignee = admin2
- assign_modal.confirm
+ topic_page.click_assign_topic
+ assign_modal.assignee = admin2
+ assign_modal.confirm
- expect(assign_modal).to be_closed
- expect(topic_page).to have_assigned(
- user: admin2,
- at_post: 2,
- class_attribute: ".private-assign",
- )
- end
- end
+ expect(assign_modal).to be_closed
+ expect(topic_page).to have_assigned(
+ user: admin2,
+ at_post: 2,
+ class_attribute: ".private-assign",
+ )
+ end
+ end
- context "when unassign_on_close is set to true" do
- before { SiteSetting.unassign_on_close = true }
+ context "when unassign_on_close is set to true" do
+ before { SiteSetting.unassign_on_close = true }
- it "unassigns the topic on close" do
- visit "/t/#{topic.id}"
+ it "unassigns the topic on close" do
+ visit "/t/#{topic.id}"
- topic_page.click_assign_topic
- assign_modal.assignee = admin2
- assign_modal.confirm
+ topic_page.click_assign_topic
+ assign_modal.assignee = admin2
+ assign_modal.confirm
- expect(assign_modal).to be_closed
- expect(topic_page).to have_assigned(user: admin2, at_post: 2)
+ expect(assign_modal).to be_closed
+ expect(topic_page).to have_assigned(user: admin2, at_post: 2)
- find(".timeline-controls .toggle-admin-menu").click
- find(".topic-admin-close").click
+ find(".timeline-controls .toggle-admin-menu").click
+ find(".topic-admin-close").click
- expect(find("#post_3")).to have_content(
- I18n.t("js.action_codes.closed.enabled", when: "just now"),
- )
- expect(page).to have_no_css("#post_4")
- expect(page).to have_no_css("#topic .assigned-to")
- end
+ expect(find("#post_3")).to have_content(
+ I18n.t("js.action_codes.closed.enabled", when: "just now"),
+ )
+ expect(page).to have_no_css("#post_4")
+ expect(page).to have_no_css("#topic .assigned-to")
+ end
- it "can assign the previous assignee" do
- visit "/t/#{topic.id}"
+ it "can assign the previous assignee" do
+ visit "/t/#{topic.id}"
- topic_page.click_assign_topic
- assign_modal.assignee = admin2
- assign_modal.confirm
+ topic_page.click_assign_topic
+ assign_modal.assignee = admin2
+ assign_modal.confirm
- expect(assign_modal).to be_closed
- expect(topic_page).to have_assigned(user: admin2, at_post: 2)
+ expect(assign_modal).to be_closed
+ expect(topic_page).to have_assigned(user: admin2, at_post: 2)
- find(".timeline-controls .toggle-admin-menu").click
- find(".topic-admin-close").click
+ find(".timeline-controls .toggle-admin-menu").click
+ find(".topic-admin-close").click
- expect(find("#post_3")).to have_content(
- I18n.t("js.action_codes.closed.enabled", when: "just now"),
- )
- expect(page).to have_no_css("#post_4")
- expect(page).to have_no_css("#topic .assigned-to")
+ expect(find("#post_3")).to have_content(
+ I18n.t("js.action_codes.closed.enabled", when: "just now"),
+ )
+ expect(page).to have_no_css("#post_4")
+ expect(page).to have_no_css("#topic .assigned-to")
- topic_page.click_assign_topic
- assign_modal.assignee = admin2
- assign_modal.confirm
+ topic_page.click_assign_topic
+ assign_modal.assignee = admin2
+ assign_modal.confirm
- expect(page).to have_no_css("#post_4")
+ expect(page).to have_no_css("#post_4")
- expect(find("#topic .assigned-to")).to have_content(admin2.username)
- end
+ expect(find("#topic .assigned-to")).to have_content(admin2.username)
+ end
- context "when reassign_on_open is set to true" do
- before { SiteSetting.reassign_on_open = true }
+ context "when reassign_on_open is set to true" do
+ before { SiteSetting.reassign_on_open = true }
- it "reassigns the topic on open" do
- skip_on_ci!("Flaky test - reassigning topic on open")
- visit "/t/#{topic.id}"
+ it "reassigns the topic on open" do
+ skip_on_ci!("Flaky test - reassigning topic on open")
+ visit "/t/#{topic.id}"
- topic_page.click_assign_topic
- assign_modal.assignee = admin2
- assign_modal.confirm
+ topic_page.click_assign_topic
+ assign_modal.assignee = admin2
+ assign_modal.confirm
- expect(assign_modal).to be_closed
- expect(topic_page).to have_assigned(user: admin2)
+ expect(assign_modal).to be_closed
+ expect(topic_page).to have_assigned(user: admin2)
- find(".timeline-controls .toggle-admin-menu").click
- find(".topic-admin-close").click
+ find(".timeline-controls .toggle-admin-menu").click
+ find(".topic-admin-close").click
- expect(find("#post_3")).to have_content(
- I18n.t("js.action_codes.closed.enabled", when: "just now"),
- )
- expect(page).to have_no_css("#post_4")
- expect(page).to have_no_css("#topic .assigned-to")
+ expect(find("#post_3")).to have_content(
+ I18n.t("js.action_codes.closed.enabled", when: "just now"),
+ )
+ expect(page).to have_no_css("#post_4")
+ expect(page).to have_no_css("#topic .assigned-to")
- find(".timeline-controls .toggle-admin-menu").click
- find(".topic-admin-open").click
+ find(".timeline-controls .toggle-admin-menu").click
+ find(".topic-admin-open").click
- expect(find("#post_4")).to have_content(
- I18n.t("js.action_codes.closed.disabled", when: "just now"),
- )
- expect(page).to have_no_css("#post_5")
+ expect(find("#post_4")).to have_content(
+ I18n.t("js.action_codes.closed.disabled", when: "just now"),
+ )
+ expect(page).to have_no_css("#post_5")
- try_until_success(reason: "Relies on MessageBus updates") do
- expect(find("#topic .assigned-to")).to have_content(admin2.username)
- end
- end
+ try_until_success(reason: "Relies on MessageBus updates") do
+ expect(find("#topic .assigned-to")).to have_content(admin2.username)
end
end
end
diff --git a/plugins/discourse-assign/test/javascripts/acceptance/assign-disabled-test.js b/plugins/discourse-assign/test/javascripts/acceptance/assign-disabled-test.js
index 95a033531b7..92520050733 100644
--- a/plugins/discourse-assign/test/javascripts/acceptance/assign-disabled-test.js
+++ b/plugins/discourse-assign/test/javascripts/acceptance/assign-disabled-test.js
@@ -2,21 +2,15 @@ import { visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Assign | Assign disabled mobile (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({ can_assign: true });
- needs.mobileView();
- needs.settings({
- assign_enabled: false,
- glimmer_post_stream_mode: postStreamMode,
- });
+acceptance(`Discourse Assign | Assign disabled mobile`, function (needs) {
+ needs.user({ can_assign: true });
+ needs.mobileView();
+ needs.settings({
+ assign_enabled: false,
+ });
- test("Footer dropdown does not contain button", async function (assert) {
- await visit("/t/internationalization-localization/280");
- assert.dom(".assign").doesNotExist();
- });
- }
- );
+ test("Footer dropdown does not contain button", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ assert.dom(".assign").doesNotExist();
+ });
});
diff --git a/plugins/discourse-assign/test/javascripts/acceptance/assign-enabled-test.js b/plugins/discourse-assign/test/javascripts/acceptance/assign-enabled-test.js
index c8e6e901355..eb71ad585b8 100644
--- a/plugins/discourse-assign/test/javascripts/acceptance/assign-enabled-test.js
+++ b/plugins/discourse-assign/test/javascripts/acceptance/assign-enabled-test.js
@@ -12,230 +12,212 @@ import {
} from "discourse/tests/helpers/qunit-helpers";
import selectKit from "discourse/tests/helpers/select-kit-helper";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Assign | Assign mobile (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.mobileView();
- needs.settings({
- assign_enabled: true,
- glimmer_post_stream_mode: postStreamMode,
- });
+acceptance(`Discourse Assign | Assign mobile`, function (needs) {
+ needs.user();
+ needs.mobileView();
+ needs.settings({
+ assign_enabled: true,
+ });
- needs.pretender((server, helper) => {
- server.get("/assign/suggestions", () => {
- return helper.response({
- success: true,
- assign_allowed_groups: false,
- assign_allowed_for_groups: [],
- suggestions: [
- {
- id: 19,
- username: "eviltrout",
- name: "Robin Ward",
- avatar_template:
- "/user_avatar/meta.discourse.org/eviltrout/{size}/5275_2.png",
- },
- ],
- });
- });
+ needs.pretender((server, helper) => {
+ server.get("/assign/suggestions", () => {
+ return helper.response({
+ success: true,
+ assign_allowed_groups: false,
+ assign_allowed_for_groups: [],
+ suggestions: [
+ {
+ id: 19,
+ username: "eviltrout",
+ name: "Robin Ward",
+ avatar_template:
+ "/user_avatar/meta.discourse.org/eviltrout/{size}/5275_2.png",
+ },
+ ],
});
+ });
+ });
- test("Footer dropdown contains button", async function (assert) {
- updateCurrentUser({ can_assign: true });
- await visit("/t/internationalization-localization/280");
- await click(".topic-footer-mobile-dropdown-trigger");
- await click(".assign");
- assert.dom(".assign.d-modal").exists("assign modal opens");
- });
- }
- );
-
- acceptance(
- `Discourse Assign | Assign desktop (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({ can_assign: true });
- needs.settings({
- assign_enabled: true,
- glimmer_post_stream_mode: postStreamMode,
- });
+ test("Footer dropdown contains button", async function (assert) {
+ updateCurrentUser({ can_assign: true });
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-footer-mobile-dropdown-trigger");
+ await click(".assign");
+ assert.dom(".assign.d-modal").exists("assign modal opens");
+ });
+});
- needs.pretender((server, helper) => {
- server.get("/assign/suggestions", () => {
- return helper.response({
- success: true,
- assign_allowed_groups: false,
- assign_allowed_for_groups: [],
- suggestions: [
- {
- id: 19,
- username: "eviltrout",
- name: "Robin Ward",
- avatar_template:
- "/user_avatar/meta.discourse.org/eviltrout/{size}/5275_2.png",
- },
- ],
- });
- });
+acceptance(`Discourse Assign | Assign desktop`, function (needs) {
+ needs.user({ can_assign: true });
+ needs.settings({
+ assign_enabled: true,
+ });
+
+ needs.pretender((server, helper) => {
+ server.get("/assign/suggestions", () => {
+ return helper.response({
+ success: true,
+ assign_allowed_groups: false,
+ assign_allowed_for_groups: [],
+ suggestions: [
+ {
+ id: 19,
+ username: "eviltrout",
+ name: "Robin Ward",
+ avatar_template:
+ "/user_avatar/meta.discourse.org/eviltrout/{size}/5275_2.png",
+ },
+ ],
});
+ });
+ });
- test("Assigning user to a post", async function (assert) {
- await visit("/t/internationalization-localization/280");
+ test("Assigning user to a post", async function (assert) {
+ await visit("/t/internationalization-localization/280");
- assert
- .dom("#post_2 .post-action-menu__assign-post")
- .doesNotExist("assign to post button is hidden");
+ assert
+ .dom("#post_2 .post-action-menu__assign-post")
+ .doesNotExist("assign to post button is hidden");
- await click("#post_2 button.show-more-actions");
- assert
- .dom("#post_2 .post-action-menu__assign-post")
- .exists("assign to post button exists");
+ await click("#post_2 button.show-more-actions");
+ assert
+ .dom("#post_2 .post-action-menu__assign-post")
+ .exists("assign to post button exists");
- await click("#post_2 .post-action-menu__assign-post");
- assert.dom(".assign.d-modal").exists("assign modal opens");
+ await click("#post_2 .post-action-menu__assign-post");
+ assert.dom(".assign.d-modal").exists("assign modal opens");
- const menu = selectKit(".assign.d-modal .user-chooser");
- assert.true(menu.isExpanded(), "user selector is expanded");
+ const menu = selectKit(".assign.d-modal .user-chooser");
+ assert.true(menu.isExpanded(), "user selector is expanded");
- await click(".assign.d-modal .btn-primary");
- assert.dom(".error-label").includesText("Choose a user to assign");
+ await click(".assign.d-modal .btn-primary");
+ assert.dom(".error-label").includesText("Choose a user to assign");
- await menu.expand();
- await menu.selectRowByIndex(0);
- assert.strictEqual(menu.header().value(), "eviltrout");
- assert.dom(".error-label").doesNotExist();
+ await menu.expand();
+ await menu.selectRowByIndex(0);
+ assert.strictEqual(menu.header().value(), "eviltrout");
+ assert.dom(".error-label").doesNotExist();
- pretender.put("/assign/assign", ({ requestBody }) => {
- const body = parsePostData(requestBody);
- assert.strictEqual(body.target_type, "Post");
- assert.strictEqual(body.username, "eviltrout");
- assert.strictEqual(body.note, "a note!");
- return response({ success: true });
- });
+ pretender.put("/assign/assign", ({ requestBody }) => {
+ const body = parsePostData(requestBody);
+ assert.strictEqual(body.target_type, "Post");
+ assert.strictEqual(body.username, "eviltrout");
+ assert.strictEqual(body.note, "a note!");
+ return response({ success: true });
+ });
- await fillIn("#assign-modal-note", "a note!");
- await click(".assign.d-modal .btn-primary");
+ await fillIn("#assign-modal-note", "a note!");
+ await click(".assign.d-modal .btn-primary");
- assert.dom(".assign.d-modal").doesNotExist("assign modal closes");
- });
+ assert.dom(".assign.d-modal").doesNotExist("assign modal closes");
+ });
- test("Footer dropdown contains button", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-button-assign");
+ test("Footer dropdown contains button", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-button-assign");
- assert.dom(".assign.d-modal").exists("assign modal opens");
- });
- }
- );
-
- acceptance(
- `Discourse Assign | Assign Status enabled (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({
- can_assign: true,
- });
- needs.settings({
- assign_enabled: true,
- enable_assign_status: true,
- assign_statuses: "New|In Progress|Done",
- glimmer_post_stream_mode: postStreamMode,
- });
+ assert.dom(".assign.d-modal").exists("assign modal opens");
+ });
+});
+
+acceptance(`Discourse Assign | Assign Status enabled`, function (needs) {
+ needs.user({
+ can_assign: true,
+ });
+ needs.settings({
+ assign_enabled: true,
+ enable_assign_status: true,
+ assign_statuses: "New|In Progress|Done",
+ });
- needs.pretender((server, helper) => {
- server.get("/assign/suggestions", () => {
- return helper.response({
- success: true,
- assign_allowed_groups: false,
- assign_allowed_for_groups: [],
- suggestions: [
- {
- id: 19,
- username: "eviltrout",
- name: "Robin Ward",
- avatar_template:
- "/user_avatar/meta.discourse.org/eviltrout/{size}/5275_2.png",
- },
- ],
- });
- });
+ needs.pretender((server, helper) => {
+ server.get("/assign/suggestions", () => {
+ return helper.response({
+ success: true,
+ assign_allowed_groups: false,
+ assign_allowed_for_groups: [],
+ suggestions: [
+ {
+ id: 19,
+ username: "eviltrout",
+ name: "Robin Ward",
+ avatar_template:
+ "/user_avatar/meta.discourse.org/eviltrout/{size}/5275_2.png",
+ },
+ ],
});
+ });
+ });
- test("Modal contains status dropdown", async function (assert) {
- pretender.put("/assign/assign", ({ requestBody }) => {
- const body = parsePostData(requestBody);
- assert.strictEqual(body.target_type, "Topic");
- assert.strictEqual(body.target_id, "280");
- assert.strictEqual(body.username, "eviltrout");
- assert.strictEqual(body.status, "In Progress");
+ test("Modal contains status dropdown", async function (assert) {
+ pretender.put("/assign/assign", ({ requestBody }) => {
+ const body = parsePostData(requestBody);
+ assert.strictEqual(body.target_type, "Topic");
+ assert.strictEqual(body.target_id, "280");
+ assert.strictEqual(body.username, "eviltrout");
+ assert.strictEqual(body.status, "In Progress");
- return response({ success: true });
- });
+ return response({ success: true });
+ });
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-button-assign");
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-button-assign");
- assert
- .dom(".assign.d-modal #assign-status")
- .exists("assign status dropdown exists");
+ assert
+ .dom(".assign.d-modal #assign-status")
+ .exists("assign status dropdown exists");
- const statusDropdown = selectKit("#assign-status");
- assert.strictEqual(statusDropdown.header().value(), "New");
+ const statusDropdown = selectKit("#assign-status");
+ assert.strictEqual(statusDropdown.header().value(), "New");
- await statusDropdown.expand();
- await statusDropdown.selectRowByValue("In Progress");
- assert.strictEqual(statusDropdown.header().value(), "In Progress");
+ await statusDropdown.expand();
+ await statusDropdown.selectRowByValue("In Progress");
+ assert.strictEqual(statusDropdown.header().value(), "In Progress");
- const menu = selectKit(".assign.d-modal .user-chooser");
- await menu.expand();
- await menu.selectRowByIndex(0);
+ const menu = selectKit(".assign.d-modal .user-chooser");
+ await menu.expand();
+ await menu.selectRowByIndex(0);
- await click(".assign.d-modal .btn-primary");
- });
- }
- );
-
- acceptance(
- `Discourse Assign | Assign Status disabled (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({
- can_assign: true,
- });
- needs.settings({
- assign_enabled: true,
- enable_assign_status: false,
- glimmer_post_stream_mode: postStreamMode,
- });
+ await click(".assign.d-modal .btn-primary");
+ });
+});
- needs.pretender((server, helper) => {
- server.get("/assign/suggestions", () => {
- return helper.response({
- success: true,
- assign_allowed_groups: false,
- assign_allowed_for_groups: [],
- suggestions: [
- {
- id: 19,
- username: "eviltrout",
- name: "Robin Ward",
- avatar_template:
- "/user_avatar/meta.discourse.org/eviltrout/{size}/5275_2.png",
- },
- ],
- });
- });
+acceptance(`Discourse Assign | Assign Status disabled`, function (needs) {
+ needs.user({
+ can_assign: true,
+ });
+ needs.settings({
+ assign_enabled: true,
+ enable_assign_status: false,
+ });
+
+ needs.pretender((server, helper) => {
+ server.get("/assign/suggestions", () => {
+ return helper.response({
+ success: true,
+ assign_allowed_groups: false,
+ assign_allowed_for_groups: [],
+ suggestions: [
+ {
+ id: 19,
+ username: "eviltrout",
+ name: "Robin Ward",
+ avatar_template:
+ "/user_avatar/meta.discourse.org/eviltrout/{size}/5275_2.png",
+ },
+ ],
});
+ });
+ });
- test("Modal contains status dropdown", async function (assert) {
- await visit("/t/internationalization-localization/280");
- await click("#topic-footer-button-assign");
+ test("Modal contains status dropdown", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("#topic-footer-button-assign");
- assert
- .dom(".assign.d-modal #assign-status")
- .doesNotExist("assign status dropdown doesn't exists");
- });
- }
- );
+ assert
+ .dom(".assign.d-modal #assign-status")
+ .doesNotExist("assign status dropdown doesn't exists");
+ });
});
// See RemindAssignsFrequencySiteSettings
diff --git a/plugins/discourse-assign/test/javascripts/acceptance/assigned-topic-test.js b/plugins/discourse-assign/test/javascripts/acceptance/assigned-topic-test.js
index e535cee4d52..cf91d2145f5 100644
--- a/plugins/discourse-assign/test/javascripts/acceptance/assigned-topic-test.js
+++ b/plugins/discourse-assign/test/javascripts/acceptance/assigned-topic-test.js
@@ -81,196 +81,176 @@ function assignNewUserToTopic(needs) {
});
}
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Assign | Assigned topic (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- assign_enabled: true,
- tagging_enabled: true,
- assigns_user_url_path: "/",
- assigns_public: true,
- enable_assign_status: true,
- glimmer_post_stream_mode: postStreamMode,
- });
-
- assignCurrentUserToTopic(needs);
-
- test("Shows user assignment info", async function (assert) {
- updateCurrentUser({ can_assign: true });
- await visit("/t/assignment-topic/44");
-
- assert
- .dom("#topic-title .assigned-to")
- .hasText("eviltrout", "shows assignment in the header");
-
- assert
- .dom("#post_1 .assigned-to")
- .includesText(
- "Assigned topic to eviltrout",
- "shows assignment in the first post"
- );
- assert
- .dom("#post_1 .assigned-to")
- .includesText("#2 to Developers", "Also shows indirect assignments");
- assert.dom("#post_1 .assigned-to svg.d-icon-user-plus").exists();
- assert.dom("#post_1 .assigned-to a[href='/']").exists();
- assert
- .dom(".discourse-tags .assigned-to[href='/t/28830'] span")
- .hasAttribute("title", "Shark Doododooo", "shows topic assign notes");
- assert
- .dom(".discourse-tags .assigned-to[href='/p/2'] span")
- .hasAttribute(
- "title",
- '<script>alert("xss")</script>',
- "shows indirect assign notes"
- );
- assert
- .dom("#topic-footer-dropdown-reassign")
- .exists("shows reassign dropdown at the bottom of the topic");
- });
-
- test("Shows group assignment info", async function (assert) {
- updateCurrentUser({ can_assign: true });
- await visit("/t/assignment-topic/45");
-
- assert
- .dom("#topic-title .assigned-to")
- .hasText("Developers", "shows assignment in the header");
- assert
- .dom("#post_1 .assigned-to--group")
- .hasText(
- "Assigned topic to Developers",
- "shows assignment in the first post"
- );
- assert.dom("#post_1 .assigned-to svg.d-icon-group-plus").exists();
- assert
- .dom("#post_1 .assigned-to a[href='/g/Developers/assigned/everyone']")
- .exists();
- assert
- .dom("#topic-footer-dropdown-reassign")
- .exists("shows reassign dropdown at the bottom of the topic");
- });
-
- test("User without assign ability cannot see footer button", async function (assert) {
- updateCurrentUser({
- can_assign: false,
- admin: false,
- moderator: false,
- });
- await visit("/t/assignment-topic/45");
-
- assert
- .dom("#topic-footer-dropdown-reassign")
- .doesNotExist(
- "does not show reassign dropdown at the bottom of the topic"
- );
- });
-
- test("Shows assignment notification", async function (assert) {
- updateCurrentUser({ can_assign: true });
-
- await visit("/u/eviltrout/notifications");
-
- assert
- .dom("section.user-content .user-notifications-list li.notification")
- .hasClass("assigned", "with correct assigned class");
-
- assert
- .dom(
- "section.user-content .user-notifications-list li.notification a"
- )
- .hasAttribute(
- "title",
- i18n("notifications.titles.assigned"),
- "with correct title"
- );
- assert
- .dom(
- "section.user-content .user-notifications-list li.notification svg use"
- )
- .hasAttribute("href", "#user-plus", "with correct icon");
- });
- }
- );
-
- acceptance(
- `Discourse Assign | Reassign topic (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- assign_enabled: true,
- tagging_enabled: true,
- assigns_user_url_path: "/",
- glimmer_post_stream_mode: postStreamMode,
- });
-
- assignNewUserToTopic(needs);
-
- test("Reassign Footer dropdown contains reassign buttons", async function (assert) {
- updateCurrentUser({ can_assign: true });
- const menu = selectKit("#topic-footer-dropdown-reassign");
-
- await visit("/t/assignment-topic/44");
- await menu.expand();
-
- assert.true(menu.rowByValue("unassign").exists());
- assert.true(menu.rowByValue("reassign").exists());
- assert.true(menu.rowByValue("reassign-self").exists());
- });
- }
- );
-
- acceptance(
- `Discourse Assign | Reassign topic | mobile (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.mobileView();
- needs.settings({
- assign_enabled: true,
- tagging_enabled: true,
- assigns_user_url_path: "/",
- glimmer_post_stream_mode: postStreamMode,
- });
-
- assignNewUserToTopic(needs);
-
- test("Mobile Footer dropdown contains reassign buttons", async function (assert) {
- updateCurrentUser({ can_assign: true });
-
- await visit("/t/assignment-topic/44");
- await click(".topic-footer-mobile-dropdown-trigger");
-
- assert.dom("#topic-footer-button-unassign-mobile").exists();
- assert.dom("#topic-footer-button-reassign-self-mobile").exists();
- assert.dom("#topic-footer-button-reassign-mobile").exists();
- });
- }
- );
-
- acceptance(
- `Discourse Assign | Reassign topic conditionals (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- assign_enabled: true,
- tagging_enabled: true,
- assigns_user_url_path: "/",
- glimmer_post_stream_mode: postStreamMode,
- });
-
- assignCurrentUserToTopic(needs);
-
- test("Reassign Footer dropdown won't display reassign-to-self button when already assigned to current user", async function (assert) {
- updateCurrentUser({ can_assign: true });
- const menu = selectKit("#topic-footer-dropdown-reassign");
-
- await visit("/t/assignment-topic/44");
- await menu.expand();
-
- assert.false(menu.rowByValue("reassign-self").exists());
- });
- }
- );
+acceptance(`Discourse Assign | Assigned topic`, function (needs) {
+ needs.user();
+ needs.settings({
+ assign_enabled: true,
+ tagging_enabled: true,
+ assigns_user_url_path: "/",
+ assigns_public: true,
+ enable_assign_status: true,
+ });
+
+ assignCurrentUserToTopic(needs);
+
+ test("Shows user assignment info", async function (assert) {
+ updateCurrentUser({ can_assign: true });
+ await visit("/t/assignment-topic/44");
+
+ assert
+ .dom("#topic-title .assigned-to")
+ .hasText("eviltrout", "shows assignment in the header");
+
+ assert
+ .dom("#post_1 .assigned-to")
+ .includesText(
+ "Assigned topic to eviltrout",
+ "shows assignment in the first post"
+ );
+ assert
+ .dom("#post_1 .assigned-to")
+ .includesText("#2 to Developers", "Also shows indirect assignments");
+ assert.dom("#post_1 .assigned-to svg.d-icon-user-plus").exists();
+ assert.dom("#post_1 .assigned-to a[href='/']").exists();
+ assert
+ .dom(".discourse-tags .assigned-to[href='/t/28830'] span")
+ .hasAttribute("title", "Shark Doododooo", "shows topic assign notes");
+ assert
+ .dom(".discourse-tags .assigned-to[href='/p/2'] span")
+ .hasAttribute(
+ "title",
+ '<script>alert("xss")</script>',
+ "shows indirect assign notes"
+ );
+ assert
+ .dom("#topic-footer-dropdown-reassign")
+ .exists("shows reassign dropdown at the bottom of the topic");
+ });
+
+ test("Shows group assignment info", async function (assert) {
+ updateCurrentUser({ can_assign: true });
+ await visit("/t/assignment-topic/45");
+
+ assert
+ .dom("#topic-title .assigned-to")
+ .hasText("Developers", "shows assignment in the header");
+ assert
+ .dom("#post_1 .assigned-to--group")
+ .hasText(
+ "Assigned topic to Developers",
+ "shows assignment in the first post"
+ );
+ assert.dom("#post_1 .assigned-to svg.d-icon-group-plus").exists();
+ assert
+ .dom("#post_1 .assigned-to a[href='/g/Developers/assigned/everyone']")
+ .exists();
+ assert
+ .dom("#topic-footer-dropdown-reassign")
+ .exists("shows reassign dropdown at the bottom of the topic");
+ });
+
+ test("User without assign ability cannot see footer button", async function (assert) {
+ updateCurrentUser({
+ can_assign: false,
+ admin: false,
+ moderator: false,
+ });
+ await visit("/t/assignment-topic/45");
+
+ assert
+ .dom("#topic-footer-dropdown-reassign")
+ .doesNotExist(
+ "does not show reassign dropdown at the bottom of the topic"
+ );
+ });
+
+ test("Shows assignment notification", async function (assert) {
+ updateCurrentUser({ can_assign: true });
+
+ await visit("/u/eviltrout/notifications");
+
+ assert
+ .dom("section.user-content .user-notifications-list li.notification")
+ .hasClass("assigned", "with correct assigned class");
+
+ assert
+ .dom("section.user-content .user-notifications-list li.notification a")
+ .hasAttribute(
+ "title",
+ i18n("notifications.titles.assigned"),
+ "with correct title"
+ );
+ assert
+ .dom(
+ "section.user-content .user-notifications-list li.notification svg use"
+ )
+ .hasAttribute("href", "#user-plus", "with correct icon");
+ });
+});
+
+acceptance(`Discourse Assign | Reassign topic`, function (needs) {
+ needs.user();
+ needs.settings({
+ assign_enabled: true,
+ tagging_enabled: true,
+ assigns_user_url_path: "/",
+ });
+
+ assignNewUserToTopic(needs);
+
+ test("Reassign Footer dropdown contains reassign buttons", async function (assert) {
+ updateCurrentUser({ can_assign: true });
+ const menu = selectKit("#topic-footer-dropdown-reassign");
+
+ await visit("/t/assignment-topic/44");
+ await menu.expand();
+
+ assert.true(menu.rowByValue("unassign").exists());
+ assert.true(menu.rowByValue("reassign").exists());
+ assert.true(menu.rowByValue("reassign-self").exists());
+ });
+});
+
+acceptance(`Discourse Assign | Reassign topic | mobile`, function (needs) {
+ needs.user();
+ needs.mobileView();
+ needs.settings({
+ assign_enabled: true,
+ tagging_enabled: true,
+ assigns_user_url_path: "/",
+ });
+
+ assignNewUserToTopic(needs);
+
+ test("Mobile Footer dropdown contains reassign buttons", async function (assert) {
+ updateCurrentUser({ can_assign: true });
+
+ await visit("/t/assignment-topic/44");
+ await click(".topic-footer-mobile-dropdown-trigger");
+
+ assert.dom("#topic-footer-button-unassign-mobile").exists();
+ assert.dom("#topic-footer-button-reassign-self-mobile").exists();
+ assert.dom("#topic-footer-button-reassign-mobile").exists();
+ });
+});
+
+acceptance(`Discourse Assign | Reassign topic conditionals`, function (needs) {
+ needs.user();
+ needs.settings({
+ assign_enabled: true,
+ tagging_enabled: true,
+ assigns_user_url_path: "/",
+ });
+
+ assignCurrentUserToTopic(needs);
+
+ test("Reassign Footer dropdown won't display reassign-to-self button when already assigned to current user", async function (assert) {
+ updateCurrentUser({ can_assign: true });
+ const menu = selectKit("#topic-footer-dropdown-reassign");
+
+ await visit("/t/assignment-topic/44");
+ await menu.expand();
+
+ assert.false(menu.rowByValue("reassign-self").exists());
+ });
});
diff --git a/plugins/discourse-assign/test/javascripts/acceptance/edit-assignments-modal-test.js b/plugins/discourse-assign/test/javascripts/acceptance/edit-assignments-modal-test.js
index 881b4b0c9d5..3e63790ccec 100644
--- a/plugins/discourse-assign/test/javascripts/acceptance/edit-assignments-modal-test.js
+++ b/plugins/discourse-assign/test/javascripts/acceptance/edit-assignments-modal-test.js
@@ -12,170 +12,158 @@ const secondReply = topic.post_stream.posts[2];
const new_assignee_1 = "user_1";
const new_assignee_2 = "user_2";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Assign | Edit assignments modal (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user({ can_assign: true });
- needs.settings({
- assign_enabled: true,
- glimmer_post_stream_mode: postStreamMode,
- });
-
- needs.pretender((server, helper) => {
- server.get("/t/44.json", () => helper.response(topic));
- server.put("/assign/assign", () => {
- return helper.response({ success: true });
- });
-
- const suggestions = [
- { username: new_assignee_1 },
- { username: new_assignee_2 },
- ];
- server.get("/assign/suggestions", () =>
- helper.response({
- assign_allowed_for_groups: [],
- suggestions,
- })
- );
- server.get("/u/search/users", () =>
- helper.response({
- users: suggestions,
- })
- );
- });
-
- test("reassigning topic", async function (assert) {
- await visit("/t/assignment-topic/44");
- await openModal();
- await selectAssignee(new_assignee_1);
-
- await submitModal();
- await receiveAssignedMessage(topic, new_assignee_1);
-
- assert
- .dom(".post-stream article#post_1 .assigned-to .assigned-to--user a")
- .hasText(new_assignee_1, "The topic is assigned to a new assignee");
- });
-
- test("reassigning posts", async function (assert) {
- await visit("/t/assignment-topic/44");
- await openModal();
-
- await selectPost(1);
- await expandAssigneeChooser();
- await selectAssignee(new_assignee_1);
-
- await selectPost(2);
- await expandAssigneeChooser();
- await selectAssignee(new_assignee_2);
-
- await submitModal();
- await receiveAssignedMessage(firstReply, new_assignee_1);
- await receiveAssignedMessage(secondReply, new_assignee_2);
-
- assert
- .dom(".post-stream article#post_2 .assigned-to .assigned-to-username")
- .hasText(
- new_assignee_1,
- "The first reply is assigned to a new assignee"
- );
-
- assert
- .dom(".post-stream article#post_3 .assigned-to .assigned-to-username")
- .hasText(
- new_assignee_2,
- "The second reply is assigned to a new assignee"
- );
- });
-
- test("reassigning topic and posts in one go", async function (assert) {
- await visit("/t/assignment-topic/44");
- await openModal();
- await selectAssignee(new_assignee_1);
-
- await selectPost(1);
- await expandAssigneeChooser();
- await selectAssignee(new_assignee_2);
-
- await selectPost(2);
- await expandAssigneeChooser();
- await selectAssignee(new_assignee_2);
-
- await submitModal();
- await receiveAssignedMessage(topic, new_assignee_1);
- await receiveAssignedMessage(firstReply, new_assignee_2);
- await receiveAssignedMessage(secondReply, new_assignee_2);
-
- assert
- .dom(".post-stream article#post_1 .assigned-to .assigned-to--user a")
- .hasText(new_assignee_1, "The topic is assigned to a new assignee");
-
- assert
- .dom(".post-stream article#post_2 .assigned-to .assigned-to-username")
- .hasText(
- new_assignee_2,
- "The first reply is assigned to a new assignee"
- );
-
- assert
- .dom(".post-stream article#post_3 .assigned-to .assigned-to-username")
- .hasText(
- new_assignee_2,
- "The second reply is assigned to a new assignee"
- );
- });
-
- async function expandAssigneeChooser() {
- await click(
- ".modal-container #assignee-chooser-header .select-kit-header-wrapper"
- );
- }
-
- async function openModal() {
- await click("#topic-footer-dropdown-reassign .btn");
- await click(`li[data-value='reassign']`);
- }
-
- // todo remove this function and all calls to it after we start updating UI right away
- // (there is no need to wait for a message bus message in the browser of a user
- // who did reassignment, but we do that at the moment)
- async function receiveAssignedMessage(target, newAssignee) {
- const targetIsAPost = !!target.topic_id;
-
- let topicId, postId;
- if (targetIsAPost) {
- topicId = target.topic_id;
- postId = target.id;
- } else {
- topicId = target.id;
- postId = false;
- }
-
- await publishToMessageBus("/staff/topic-assignment", {
- type: "assigned",
- topic_id: topicId,
- post_id: postId,
- assigned_type: "User",
- assigned_to: {
- username: newAssignee,
- },
- });
- await settled();
- }
-
- async function selectPost(number) {
- await click(".target .single-select .select-kit-header-wrapper");
- await click(`li[title='Post #${number}']`);
- }
-
- async function selectAssignee(username) {
- await click(`.email-group-user-chooser-row[data-value='${username}']`);
- }
-
- async function submitModal() {
- await click(".d-modal__footer .btn-primary");
- }
+acceptance(`Discourse Assign | Edit assignments modal`, function (needs) {
+ needs.user({ can_assign: true });
+ needs.settings({
+ assign_enabled: true,
+ });
+
+ needs.pretender((server, helper) => {
+ server.get("/t/44.json", () => helper.response(topic));
+ server.put("/assign/assign", () => {
+ return helper.response({ success: true });
+ });
+
+ const suggestions = [
+ { username: new_assignee_1 },
+ { username: new_assignee_2 },
+ ];
+ server.get("/assign/suggestions", () =>
+ helper.response({
+ assign_allowed_for_groups: [],
+ suggestions,
+ })
+ );
+ server.get("/u/search/users", () =>
+ helper.response({
+ users: suggestions,
+ })
+ );
+ });
+
+ test("reassigning topic", async function (assert) {
+ await visit("/t/assignment-topic/44");
+ await openModal();
+ await selectAssignee(new_assignee_1);
+
+ await submitModal();
+ await receiveAssignedMessage(topic, new_assignee_1);
+
+ assert
+ .dom(".post-stream article#post_1 .assigned-to .assigned-to--user a")
+ .hasText(new_assignee_1, "The topic is assigned to a new assignee");
+ });
+
+ test("reassigning posts", async function (assert) {
+ await visit("/t/assignment-topic/44");
+ await openModal();
+
+ await selectPost(1);
+ await expandAssigneeChooser();
+ await selectAssignee(new_assignee_1);
+
+ await selectPost(2);
+ await expandAssigneeChooser();
+ await selectAssignee(new_assignee_2);
+
+ await submitModal();
+ await receiveAssignedMessage(firstReply, new_assignee_1);
+ await receiveAssignedMessage(secondReply, new_assignee_2);
+
+ assert
+ .dom(".post-stream article#post_2 .assigned-to .assigned-to-username")
+ .hasText(new_assignee_1, "The first reply is assigned to a new assignee");
+
+ assert
+ .dom(".post-stream article#post_3 .assigned-to .assigned-to-username")
+ .hasText(
+ new_assignee_2,
+ "The second reply is assigned to a new assignee"
+ );
+ });
+
+ test("reassigning topic and posts in one go", async function (assert) {
+ await visit("/t/assignment-topic/44");
+ await openModal();
+ await selectAssignee(new_assignee_1);
+
+ await selectPost(1);
+ await expandAssigneeChooser();
+ await selectAssignee(new_assignee_2);
+
+ await selectPost(2);
+ await expandAssigneeChooser();
+ await selectAssignee(new_assignee_2);
+
+ await submitModal();
+ await receiveAssignedMessage(topic, new_assignee_1);
+ await receiveAssignedMessage(firstReply, new_assignee_2);
+ await receiveAssignedMessage(secondReply, new_assignee_2);
+
+ assert
+ .dom(".post-stream article#post_1 .assigned-to .assigned-to--user a")
+ .hasText(new_assignee_1, "The topic is assigned to a new assignee");
+
+ assert
+ .dom(".post-stream article#post_2 .assigned-to .assigned-to-username")
+ .hasText(new_assignee_2, "The first reply is assigned to a new assignee");
+
+ assert
+ .dom(".post-stream article#post_3 .assigned-to .assigned-to-username")
+ .hasText(
+ new_assignee_2,
+ "The second reply is assigned to a new assignee"
+ );
+ });
+
+ async function expandAssigneeChooser() {
+ await click(
+ ".modal-container #assignee-chooser-header .select-kit-header-wrapper"
+ );
+ }
+
+ async function openModal() {
+ await click("#topic-footer-dropdown-reassign .btn");
+ await click(`li[data-value='reassign']`);
+ }
+
+ // todo remove this function and all calls to it after we start updating UI right away
+ // (there is no need to wait for a message bus message in the browser of a user
+ // who did reassignment, but we do that at the moment)
+ async function receiveAssignedMessage(target, newAssignee) {
+ const targetIsAPost = !!target.topic_id;
+
+ let topicId, postId;
+ if (targetIsAPost) {
+ topicId = target.topic_id;
+ postId = target.id;
+ } else {
+ topicId = target.id;
+ postId = false;
}
- );
+
+ await publishToMessageBus("/staff/topic-assignment", {
+ type: "assigned",
+ topic_id: topicId,
+ post_id: postId,
+ assigned_type: "User",
+ assigned_to: {
+ username: newAssignee,
+ },
+ });
+ await settled();
+ }
+
+ async function selectPost(number) {
+ await click(".target .single-select .select-kit-header-wrapper");
+ await click(`li[title='Post #${number}']`);
+ }
+
+ async function selectAssignee(username) {
+ await click(`.email-group-user-chooser-row[data-value='${username}']`);
+ }
+
+ async function submitModal() {
+ await click(".d-modal__footer .btn-primary");
+ }
});
diff --git a/plugins/discourse-assign/test/javascripts/acceptance/post-popup-menu-test.js b/plugins/discourse-assign/test/javascripts/acceptance/post-popup-menu-test.js
index b036f6bb898..c8800e3deeb 100644
--- a/plugins/discourse-assign/test/javascripts/acceptance/post-popup-menu-test.js
+++ b/plugins/discourse-assign/test/javascripts/acceptance/post-popup-menu-test.js
@@ -26,86 +26,80 @@ const selectors = {
const topic = topicWithAssignedPosts();
const post = topic.post_stream.posts[1];
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Assign | Post popup menu (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- assign_enabled: true,
- glimmer_post_stream_mode: postStreamMode,
- });
-
- needs.pretender((server, helper) => {
- server.get("/t/44.json", () => helper.response(topic));
-
- server.put("/assign/assign", () => {
- return helper.response({ success: true });
- });
-
- server.put("/assign/unassign", () => {
- return helper.response({ success: true });
- });
-
- server.get("/assign/suggestions", () =>
- helper.response({
- assign_allowed_for_groups: [],
- suggestions: [{ username: new_assignee_username }],
- })
- );
-
- server.get("/u/search/users", () =>
- helper.response({ users: [{ username: new_assignee_username }] })
- );
- });
-
- needs.hooks.beforeEach(() => {
- updateCurrentUser({ can_assign: true });
- });
-
- test("Unassigns the post", async function (assert) {
- await visit("/t/assignment-topic/44");
- await click(selectors.moreButton);
- await click(selectors.popupMenu.unassign);
- await publishToMessageBus("/staff/topic-assignment", {
- type: "unassigned",
- topic_id: topic.id,
- post_id: post.id,
- assigned_type: "User",
- });
-
- assert.dom(".popup-menu").doesNotExist("The popup menu is closed");
- assert.dom(selectors.assignedTo).doesNotExist("The post is unassigned");
- });
-
- test("Reassigns the post", async function (assert) {
- await visit("/t/assignment-topic/44");
- await click(selectors.moreButton);
- await click(selectors.popupMenu.editAssignment);
- await click(selectors.modal.assignee);
- await fillIn(selectors.modal.assigneeInput, new_assignee_username);
- await click(selectors.modal.assignButton);
-
- await publishToMessageBus("/staff/topic-assignment", {
- type: "assigned",
- topic_id: topic.id,
- post_id: post.id,
- assigned_type: "User",
- assigned_to: {
- username: new_assignee_username,
- },
- });
-
- // todo: we can skip this one for now, It will be fixed it in a core PR
- // assert.dom(".popup-menu").doesNotExist("The popup menu is closed");
-
- assert
- .dom(`${selectors.assignedTo} .assigned-to-username`)
- .hasText(
- new_assignee_username,
- "The post is assigned to the new assignee"
- );
- });
- }
- );
+acceptance(`Discourse Assign | Post popup menu`, function (needs) {
+ needs.user();
+ needs.settings({
+ assign_enabled: true,
+ });
+
+ needs.pretender((server, helper) => {
+ server.get("/t/44.json", () => helper.response(topic));
+
+ server.put("/assign/assign", () => {
+ return helper.response({ success: true });
+ });
+
+ server.put("/assign/unassign", () => {
+ return helper.response({ success: true });
+ });
+
+ server.get("/assign/suggestions", () =>
+ helper.response({
+ assign_allowed_for_groups: [],
+ suggestions: [{ username: new_assignee_username }],
+ })
+ );
+
+ server.get("/u/search/users", () =>
+ helper.response({ users: [{ username: new_assignee_username }] })
+ );
+ });
+
+ needs.hooks.beforeEach(() => {
+ updateCurrentUser({ can_assign: true });
+ });
+
+ test("Unassigns the post", async function (assert) {
+ await visit("/t/assignment-topic/44");
+ await click(selectors.moreButton);
+ await click(selectors.popupMenu.unassign);
+ await publishToMessageBus("/staff/topic-assignment", {
+ type: "unassigned",
+ topic_id: topic.id,
+ post_id: post.id,
+ assigned_type: "User",
+ });
+
+ assert.dom(".popup-menu").doesNotExist("The popup menu is closed");
+ assert.dom(selectors.assignedTo).doesNotExist("The post is unassigned");
+ });
+
+ test("Reassigns the post", async function (assert) {
+ await visit("/t/assignment-topic/44");
+ await click(selectors.moreButton);
+ await click(selectors.popupMenu.editAssignment);
+ await click(selectors.modal.assignee);
+ await fillIn(selectors.modal.assigneeInput, new_assignee_username);
+ await click(selectors.modal.assignButton);
+
+ await publishToMessageBus("/staff/topic-assignment", {
+ type: "assigned",
+ topic_id: topic.id,
+ post_id: post.id,
+ assigned_type: "User",
+ assigned_to: {
+ username: new_assignee_username,
+ },
+ });
+
+ // todo: we can skip this one for now, It will be fixed it in a core PR
+ // assert.dom(".popup-menu").doesNotExist("The popup menu is closed");
+
+ assert
+ .dom(`${selectors.assignedTo} .assigned-to-username`)
+ .hasText(
+ new_assignee_username,
+ "The post is assigned to the new assignee"
+ );
+ });
});
diff --git a/plugins/discourse-assign/test/javascripts/acceptance/topic-level-assign-menu-test.js b/plugins/discourse-assign/test/javascripts/acceptance/topic-level-assign-menu-test.js
index a50ce5fd83f..dd0954e8c42 100644
--- a/plugins/discourse-assign/test/javascripts/acceptance/topic-level-assign-menu-test.js
+++ b/plugins/discourse-assign/test/javascripts/acceptance/topic-level-assign-menu-test.js
@@ -10,46 +10,40 @@ import topicWithAssignedPosts from "../fixtures/topic-with-assigned-posts";
const topic = topicWithAssignedPosts();
const post = topic.post_stream.posts[1];
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Assign | Topic level assign menu (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- assign_enabled: true,
- glimmer_post_stream_mode: postStreamMode,
- });
+acceptance(`Discourse Assign | Topic level assign menu`, function (needs) {
+ needs.user();
+ needs.settings({
+ assign_enabled: true,
+ });
- needs.pretender((server, helper) => {
- server.get("/t/44.json", () => helper.response(topic));
- server.put("/assign/unassign", () => {
- return helper.response({ success: true });
- });
- });
+ needs.pretender((server, helper) => {
+ server.get("/t/44.json", () => helper.response(topic));
+ server.put("/assign/unassign", () => {
+ return helper.response({ success: true });
+ });
+ });
- needs.hooks.beforeEach(() => {
- updateCurrentUser({ can_assign: true });
- });
+ needs.hooks.beforeEach(() => {
+ updateCurrentUser({ can_assign: true });
+ });
- test("Unassign button unassigns the post", async function (assert) {
- await visit("/t/assignment-topic/44");
+ test("Unassign button unassigns the post", async function (assert) {
+ await visit("/t/assignment-topic/44");
- await click("#topic-footer-dropdown-reassign .btn");
- await click(`li[data-value='unassign-from-post-${post.id}']`);
- await publishToMessageBus("/staff/topic-assignment", {
- type: "unassigned",
- topic_id: topic.id,
- post_id: post.id,
- assigned_type: "User",
- });
+ await click("#topic-footer-dropdown-reassign .btn");
+ await click(`li[data-value='unassign-from-post-${post.id}']`);
+ await publishToMessageBus("/staff/topic-assignment", {
+ type: "unassigned",
+ topic_id: topic.id,
+ post_id: post.id,
+ assigned_type: "User",
+ });
- assert
- .dom("#topic-footer-dropdown-reassign-body ul[role='menu']")
- .doesNotExist("The menu is closed");
- assert
- .dom(".post-stream article#post_2 .assigned-to")
- .doesNotExist("The post is unassigned");
- });
- }
- );
+ assert
+ .dom("#topic-footer-dropdown-reassign-body ul[role='menu']")
+ .doesNotExist("The menu is closed");
+ assert
+ .dom(".post-stream article#post_2 .assigned-to")
+ .doesNotExist("The post is unassigned");
+ });
});
diff --git a/plugins/discourse-cakeday/test/javascripts/acceptance/cakeday-test.js b/plugins/discourse-cakeday/test/javascripts/acceptance/cakeday-test.js
index d6d56bb70bb..b5a4196d43b 100644
--- a/plugins/discourse-cakeday/test/javascripts/acceptance/cakeday-test.js
+++ b/plugins/discourse-cakeday/test/javascripts/acceptance/cakeday-test.js
@@ -3,255 +3,246 @@ import { test } from "qunit";
import { acceptance, queryAll } from "discourse/tests/helpers/qunit-helpers";
import { i18n } from "discourse-i18n";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Cakeday (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- cakeday_enabled: true,
- cakeday_emoji: "cake",
- cakeday_birthday_enabled: true,
- cakeday_birthday_emoji: "birthday",
- });
+acceptance(`Cakeday`, function (needs) {
+ needs.user();
+ needs.settings({
+ cakeday_enabled: true,
+ cakeday_emoji: "cake",
+ cakeday_birthday_enabled: true,
+ cakeday_birthday_emoji: "birthday",
+ });
- needs.pretender((server, { response }) => {
- server.get("/t/11.json", () =>
- response({
- post_stream: {
- posts: [
- {
- id: 14,
- name: null,
- username: "tgx",
- avatar_template:
- "/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png",
- created_at: "2016-11-21T06:55:17.892Z",
- cooked:
- "<p>This is a topic written for an acceptance test</p>",
- post_number: 1,
- post_type: 1,
- updated_at: "2016-11-21T06:55:17.892Z",
- reply_count: 0,
- reply_to_post_number: null,
- quote_count: 0,
- avg_time: null,
- incoming_link_count: 0,
- reads: 1,
- score: 0,
- yours: true,
- topic_id: 11,
- topic_slug: "some-really-interesting-topic",
- display_username: null,
- primary_group_name: null,
- primary_group_flair_url: null,
- primary_group_flair_bg_color: null,
- primary_group_flair_color: null,
- version: 1,
- can_edit: true,
- can_delete: false,
- can_recover: true,
- can_wiki: true,
- read: true,
- user_title: null,
- actions_summary: [
- { id: 3, can_act: true },
- { id: 4, can_act: true },
- { id: 5, hidden: true, can_act: true },
- { id: 7, can_act: true },
- { id: 8, can_act: true },
- ],
- moderator: false,
- admin: true,
- staff: true,
- user_id: 1,
- hidden: false,
- hidden_reason_id: null,
- trust_level: 4,
- deleted_at: null,
- user_deleted: false,
- edit_reason: null,
- can_view_edit_history: true,
- wiki: false,
- user_cakedate: moment()
- .subtract(4, "year")
- .format("YYYY-MM-DD"),
- user_birthdate: moment().format("YYYY-MM-DD"),
- },
+ needs.pretender((server, { response }) => {
+ server.get("/t/11.json", () =>
+ response({
+ post_stream: {
+ posts: [
+ {
+ id: 14,
+ name: null,
+ username: "tgx",
+ avatar_template:
+ "/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png",
+ created_at: "2016-11-21T06:55:17.892Z",
+ cooked: "<p>This is a topic written for an acceptance test</p>",
+ post_number: 1,
+ post_type: 1,
+ updated_at: "2016-11-21T06:55:17.892Z",
+ reply_count: 0,
+ reply_to_post_number: null,
+ quote_count: 0,
+ avg_time: null,
+ incoming_link_count: 0,
+ reads: 1,
+ score: 0,
+ yours: true,
+ topic_id: 11,
+ topic_slug: "some-really-interesting-topic",
+ display_username: null,
+ primary_group_name: null,
+ primary_group_flair_url: null,
+ primary_group_flair_bg_color: null,
+ primary_group_flair_color: null,
+ version: 1,
+ can_edit: true,
+ can_delete: false,
+ can_recover: true,
+ can_wiki: true,
+ read: true,
+ user_title: null,
+ actions_summary: [
+ { id: 3, can_act: true },
+ { id: 4, can_act: true },
+ { id: 5, hidden: true, can_act: true },
+ { id: 7, can_act: true },
+ { id: 8, can_act: true },
],
- stream: [14],
+ moderator: false,
+ admin: true,
+ staff: true,
+ user_id: 1,
+ hidden: false,
+ hidden_reason_id: null,
+ trust_level: 4,
+ deleted_at: null,
+ user_deleted: false,
+ edit_reason: null,
+ can_view_edit_history: true,
+ wiki: false,
+ user_cakedate: moment().subtract(4, "year").format("YYYY-MM-DD"),
+ user_birthdate: moment().format("YYYY-MM-DD"),
},
- timeline_lookup: [[1, 0]],
- id: 11,
- title: "Some really interesting topic",
- fancy_title: "Some really interesting topic",
- posts_count: 1,
- created_at: "2016-11-21T06:55:17.771Z",
- views: 1,
- reply_count: 0,
- participant_count: 1,
- like_count: 0,
- last_posted_at: "2016-11-21T06:55:17.892Z",
- visible: true,
- closed: false,
- archived: false,
- has_summary: false,
- archetype: "regular",
- slug: "some-really-interesting-topic",
- category_id: 1,
- word_count: 9,
- deleted_at: null,
- user_id: 1,
- draft: null,
- draft_key: "topic_11",
- draft_sequence: 1,
- posted: true,
- unpinned: null,
- pinned_globally: false,
- pinned: false,
- pinned_at: null,
- pinned_until: null,
- details: {
- auto_close_at: null,
- auto_close_hours: null,
- auto_close_based_on_last_post: false,
- created_by: {
- id: 1,
- username: "tgx",
- avatar_template:
- "/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png",
- },
- last_poster: {
- id: 1,
- username: "tgx",
- avatar_template:
- "/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png",
- },
- participants: [
- {
- id: 1,
- username: "tgx",
- avatar_template:
- "/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png",
- post_count: 1,
- },
- ],
- suggested_topics: [
+ ],
+ stream: [14],
+ },
+ timeline_lookup: [[1, 0]],
+ id: 11,
+ title: "Some really interesting topic",
+ fancy_title: "Some really interesting topic",
+ posts_count: 1,
+ created_at: "2016-11-21T06:55:17.771Z",
+ views: 1,
+ reply_count: 0,
+ participant_count: 1,
+ like_count: 0,
+ last_posted_at: "2016-11-21T06:55:17.892Z",
+ visible: true,
+ closed: false,
+ archived: false,
+ has_summary: false,
+ archetype: "regular",
+ slug: "some-really-interesting-topic",
+ category_id: 1,
+ word_count: 9,
+ deleted_at: null,
+ user_id: 1,
+ draft: null,
+ draft_key: "topic_11",
+ draft_sequence: 1,
+ posted: true,
+ unpinned: null,
+ pinned_globally: false,
+ pinned: false,
+ pinned_at: null,
+ pinned_until: null,
+ details: {
+ auto_close_at: null,
+ auto_close_hours: null,
+ auto_close_based_on_last_post: false,
+ created_by: {
+ id: 1,
+ username: "tgx",
+ avatar_template:
+ "/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png",
+ },
+ last_poster: {
+ id: 1,
+ username: "tgx",
+ avatar_template:
+ "/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png",
+ },
+ participants: [
+ {
+ id: 1,
+ username: "tgx",
+ avatar_template:
+ "/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png",
+ post_count: 1,
+ },
+ ],
+ suggested_topics: [
+ {
+ id: 8,
+ title: "Welcome to Discourse",
+ fancy_title: "Welcome to Discourse",
+ slug: "welcome-to-discourse",
+ posts_count: 1,
+ reply_count: 0,
+ highest_post_number: 1,
+ image_url: null,
+ created_at: "2016-11-21T06:53:31.836Z",
+ last_posted_at: "2016-11-21T06:53:31.877Z",
+ bumped: true,
+ bumped_at: "2016-11-21T06:53:31.877Z",
+ unseen: false,
+ pinned: true,
+ unpinned: null,
+ excerpt:
+ "The first paragraph of this pinned topic will be visible as a welcome message to all new visitors on your homepage. It&#39;s important! \n\nEdit this into a brief description of your community: \n\n\nWho is it for?\nWhat can they &hellip;",
+ visible: true,
+ closed: false,
+ archived: false,
+ bookmarked: null,
+ liked: null,
+ archetype: "regular",
+ like_count: 0,
+ views: 0,
+ category_id: 1,
+ posters: [
{
- id: 8,
- title: "Welcome to Discourse",
- fancy_title: "Welcome to Discourse",
- slug: "welcome-to-discourse",
- posts_count: 1,
- reply_count: 0,
- highest_post_number: 1,
- image_url: null,
- created_at: "2016-11-21T06:53:31.836Z",
- last_posted_at: "2016-11-21T06:53:31.877Z",
- bumped: true,
- bumped_at: "2016-11-21T06:53:31.877Z",
- unseen: false,
- pinned: true,
- unpinned: null,
- excerpt:
- "The first paragraph of this pinned topic will be visible as a welcome message to all new visitors on your homepage. It&#39;s important! \n\nEdit this into a brief description of your community: \n\n\nWho is it for?\nWhat can they &hellip;",
- visible: true,
- closed: false,
- archived: false,
- bookmarked: null,
- liked: null,
- archetype: "regular",
- like_count: 0,
- views: 0,
- category_id: 1,
- posters: [
- {
- extras: "latest single",
- description: "Original Poster, Most Recent Poster",
- user: {
- id: -1,
- username: "system",
- avatar_template:
- "/letter_avatar_proxy/v2/letter/s/bcef8e/{size}.png",
- },
- },
- ],
+ extras: "latest single",
+ description: "Original Poster, Most Recent Poster",
+ user: {
+ id: -1,
+ username: "system",
+ avatar_template:
+ "/letter_avatar_proxy/v2/letter/s/bcef8e/{size}.png",
+ },
},
],
- notification_level: 3,
- notifications_reason_id: 1,
- can_move_posts: true,
- can_edit: true,
- can_delete: true,
- can_recover: true,
- can_remove_allowed_users: true,
- can_invite_to: true,
- can_create_post: true,
- can_reply_as_new_topic: true,
- can_flag_topic: true,
},
- highest_post_number: 1,
- last_read_post_number: 1,
- last_read_post_id: 14,
- deleted_by: null,
- has_deleted: false,
- actions_summary: [
- { id: 4, count: 0, hidden: false, can_act: true },
- { id: 7, count: 0, hidden: false, can_act: true },
- { id: 8, count: 0, hidden: false, can_act: true },
- ],
- chunk_size: 20,
- bookmarked: false,
- })
- );
+ ],
+ notification_level: 3,
+ notifications_reason_id: 1,
+ can_move_posts: true,
+ can_edit: true,
+ can_delete: true,
+ can_recover: true,
+ can_remove_allowed_users: true,
+ can_invite_to: true,
+ can_create_post: true,
+ can_reply_as_new_topic: true,
+ can_flag_topic: true,
+ },
+ highest_post_number: 1,
+ last_read_post_number: 1,
+ last_read_post_id: 14,
+ deleted_by: null,
+ has_deleted: false,
+ actions_summary: [
+ { id: 4, count: 0, hidden: false, can_act: true },
+ { id: 7, count: 0, hidden: false, can_act: true },
+ { id: 8, count: 0, hidden: false, can_act: true },
+ ],
+ chunk_size: 20,
+ bookmarked: false,
+ })
+ );
- server.get("/u/tgx.json", () =>
- response({
- user: {
- birthdate: moment().format("YYYY-MM-DD"),
- cakedate: moment().subtract(4, "year").format("YYYY-MM-DD"),
- },
- })
- );
+ server.get("/u/tgx.json", () =>
+ response({
+ user: {
+ birthdate: moment().format("YYYY-MM-DD"),
+ cakedate: moment().subtract(4, "year").format("YYYY-MM-DD"),
+ },
+ })
+ );
- server.get("/u/tgx/card.json", () =>
- response({
- user: {
- birthdate: moment().format("YYYY-MM-DD"),
- cakedate: moment().subtract(4, "year").format("YYYY-MM-DD"),
- },
- })
- );
- });
+ server.get("/u/tgx/card.json", () =>
+ response({
+ user: {
+ birthdate: moment().format("YYYY-MM-DD"),
+ cakedate: moment().subtract(4, "year").format("YYYY-MM-DD"),
+ },
+ })
+ );
+ });
- test("Anniversary emoji", async function (assert) {
- await visit("/t/some-really-interesting-topic/11");
+ test("Anniversary emoji", async function (assert) {
+ await visit("/t/some-really-interesting-topic/11");
- const posterIcons = queryAll(".poster-icon");
+ const posterIcons = queryAll(".poster-icon");
- assert
- .dom(posterIcons[0])
- .hasAttribute("title", i18n("user.anniversary.title"));
- assert
- .dom(posterIcons[1])
- .hasAttribute("title", i18n("user.date_of_birth.title"));
- assert.dom("img.emoji", posterIcons[0]).exists({ count: 1 });
- assert.dom("img.emoji", posterIcons[1]).exists({ count: 1 });
+ assert
+ .dom(posterIcons[0])
+ .hasAttribute("title", i18n("user.anniversary.title"));
+ assert
+ .dom(posterIcons[1])
+ .hasAttribute("title", i18n("user.date_of_birth.title"));
+ assert.dom("img.emoji", posterIcons[0]).exists({ count: 1 });
+ assert.dom("img.emoji", posterIcons[1]).exists({ count: 1 });
- await click(".trigger-user-card a[data-user-card]");
+ await click(".trigger-user-card a[data-user-card]");
- const emojiImages = queryAll(".emoji-images div");
+ const emojiImages = queryAll(".emoji-images div");
- assert
- .dom(emojiImages[1])
- .hasAttribute("title", i18n("user.anniversary.title"));
- assert
- .dom(emojiImages[0])
- .hasAttribute("title", i18n("user.date_of_birth.title"));
- assert.strictEqual(emojiImages[0].children.length, 1);
- assert.strictEqual(emojiImages[1].children.length, 1);
- });
- }
- );
+ assert
+ .dom(emojiImages[1])
+ .hasAttribute("title", i18n("user.anniversary.title"));
+ assert
+ .dom(emojiImages[0])
+ .hasAttribute("title", i18n("user.date_of_birth.title"));
+ assert.strictEqual(emojiImages[0].children.length, 1);
+ assert.strictEqual(emojiImages[1].children.length, 1);
+ });
});
diff --git a/plugins/discourse-post-voting/assets/javascripts/discourse/initializers/custom-post-message-callbacks.js b/plugins/discourse-post-voting/assets/javascripts/discourse/initializers/custom-post-message-callbacks.js
index a95d2eff85c..75c170b87d8 100644
--- a/plugins/discourse-post-voting/assets/javascripts/discourse/initializers/custom-post-message-callbacks.js
+++ b/plugins/discourse-post-voting/assets/javascripts/discourse/initializers/custom-post-message-callbacks.js
@@ -30,10 +30,6 @@ export default {
cooked: message.comment_cooked,
};
post.comments.splice(indexToUpdate, 1, updatedComment);
-
- topicController.appEvents.trigger("post-stream:refresh", {
- id: post.id,
- });
}
}
}
@@ -59,10 +55,6 @@ export default {
}
post.set("comments_count", message.comments_count);
-
- topicController.appEvents.trigger("post-stream:refresh", {
- id: post.id,
- });
}
}
);
@@ -87,10 +79,6 @@ export default {
) {
post.comments.push(message.comment);
}
-
- topicController.appEvents.trigger("post-stream:refresh", {
- id: post.id,
- });
}
}
);
@@ -116,10 +104,6 @@ export default {
}
post.setProperties(props);
-
- topicController.appEvents.trigger("post-stream:refresh", {
- id: post.id,
- });
}
}
);
diff --git a/plugins/discourse-post-voting/assets/javascripts/discourse/initializers/post-voting-edits.gjs b/plugins/discourse-post-voting/assets/javascripts/discourse/initializers/post-voting-edits.gjs
index 42f7f752317..7c95bd8bec8 100644
--- a/plugins/discourse-post-voting/assets/javascripts/discourse/initializers/post-voting-edits.gjs
+++ b/plugins/discourse-post-voting/assets/javascripts/discourse/initializers/post-voting-edits.gjs
@@ -1,10 +1,7 @@
import Component from "@glimmer/component";
import routeAction from "discourse/helpers/route-action";
-import { withSilencedDeprecations } from "discourse/lib/deprecated";
import { withPluginApi } from "discourse/lib/plugin-api";
import { trackedArray } from "discourse/lib/tracked-tools";
-import { registerWidgetShim } from "discourse/widgets/render-glimmer";
-import { i18n } from "discourse-i18n";
import PostVotingAnswerButton from "../components/post-voting-answer-button";
import PostVotingAnswerHeader, {
ORDER_BY_ACTIVITY_FILTER,
@@ -86,130 +83,7 @@ function customizePost(api) {
}
);
api.renderBeforeWrapperOutlet("post-article", PostVotingAnswerHeader);
-
- withSilencedDeprecations("discourse.post-stream-widget-overrides", () =>
- customizeWidgetPost(api)
- );
-}
-
-function customizeWidgetPost(api) {
- api.reopenWidget("post", {
- orderByVotes() {
- this._topicController()
- .model.postStream.orderStreamByVotes()
- .then(() => {
- this._refreshController();
- });
- },
-
- orderByActivity() {
- this._topicController()
- .model.postStream.orderStreamByActivity()
- .then(() => {
- this._refreshController();
- });
- },
-
- _refreshController() {
- this._topicController().updateQueryParams();
- },
-
- _topicController() {
- return this.register.lookup("controller:topic");
- },
- });
-
- api.decorateWidget("post-article:before", (helper) => {
- const result = [];
- const post = helper.getModel();
-
- if (!post.topic.is_post_voting) {
- return result;
- }
-
- const topicController = helper.widget.register.lookup("controller:topic");
- let positionInStream;
-
- if (
- topicController.replies_to_post_number &&
- parseInt(topicController.replies_to_post_number, 10) !== 1
- ) {
- positionInStream = 2;
- } else {
- positionInStream = 1;
- }
-
- const answersCount = post.topic.posts_count - 1;
-
- if (
- answersCount <= 0 ||
- post.id !== post.topic.postStream.stream[positionInStream]
- ) {
- return result;
- }
-
- result.push(
- helper.h("div.post-voting-answers-header.small-action", [
- helper.h(
- "span.post-voting-answers-headers-count",
- i18n("post_voting.topic.answer_count", { count: answersCount })
- ),
- helper.h("span.post-voting-answers-headers-sort", [
- helper.h("span", i18n("post_voting.topic.sort_by")),
- helper.attach("button", {
- action: "orderByVotes",
- contents: i18n("post_voting.topic.votes"),
- disabled: topicController.filter !== ORDER_BY_ACTIVITY_FILTER,
- className: `post-voting-answers-headers-sort-votes ${
- topicController.filter === ORDER_BY_ACTIVITY_FILTER
- ? ""
- : "active"
- }`,
- }),
- helper.attach("button", {
- action: "orderByActivity",
- contents: i18n("post_voting.topic.activity"),
- disabled: topicController.filter === ORDER_BY_ACTIVITY_FILTER,
- className: `post-voting-answers-headers-sort-activity ${
- topicController.filter === ORDER_BY_ACTIVITY_FILTER
- ? "active"
- : ""
- }`,
- }),
- ]),
- ])
- );
-
- return result;
- });
-
- registerWidgetShim(
- "post-voting-vote-controls",
- "div.post-voting-post-shim",
- <template>
- <PostVotingVoteControls
- @post={{@data.post}}
- @showLogin={{routeAction "showLogin"}}
- />
- </template>
- );
-
- api.decorateWidget("post-avatar:after", function (helper) {
- const result = [];
- const model = helper.getModel();
-
- if (model.topic?.is_post_voting) {
- const postVotingPost = helper.attach("post-voting-vote-controls", {
- post: model,
- });
-
- result.push(postVotingPost);
- }
-
- return result;
- });
}
-
function customizePostMenu(api, container) {
const siteSettings = container.lookup("service:site-settings");
diff --git a/plugins/discourse-post-voting/spec/system/post_voting_spec.rb b/plugins/discourse-post-voting/spec/system/post_voting_spec.rb
index 7079d78369e..3914e695e5c 100644
--- a/plugins/discourse-post-voting/spec/system/post_voting_spec.rb
+++ b/plugins/discourse-post-voting/spec/system/post_voting_spec.rb
@@ -7,49 +7,38 @@ RSpec.describe "Post voting", type: :system do
let(:topic_page) { PageObjects::Pages::PostVotingTopic.new }
- %w[enabled disabled].each do |value|
- before { SiteSetting.glimmer_post_stream_mode = value }
-
- context "when glimmer_post_stream_mode=#{value}" do
- it "does not display button to add a comment and does not show comments when `post_voting_comment_enabled` site setting is false" do
- SiteSetting.post_voting_comment_enabled = false
- SiteSetting.post_voting_enabled = true
-
- topic = Fabricate(:topic, subtype: Topic::POST_VOTING_SUBTYPE, user: user2)
- post_1 = Fabricate(:post, topic: topic)
- post_2 = Fabricate(:post, topic: topic)
-
- sign_in(user1)
-
- topic_page.visit_topic(topic)
-
- expect(topic_page).to have_no_comment_menu
- end
-
- it "disallows voting on archived or closed topics" do
- SiteSetting.post_voting_enabled = true
- topic = Fabricate(:topic, subtype: Topic::POST_VOTING_SUBTYPE, user: user2, archived: true)
- Fabricate(:post, topic: topic, post_number: 2)
- post = Fabricate(:post, topic: topic, post_number: 3)
- Fabricate(:post_voting_comment, post: post, user: user1)
-
- sign_in(user1)
-
- topic_page.visit_topic(topic)
-
- expect(page).to have_css(PageObjects::Pages::PostVotingTopic::POST_VOTE_BUTTON, count: 4)
- expect(page).to have_css(
- "#{PageObjects::Pages::PostVotingTopic::POST_VOTE_BUTTON}:disabled",
- count: 4,
- )
- expect(page).to have_css(
- "#{PageObjects::Pages::PostVotingTopic::COMMENT_VOTE_BUTTON}:disabled",
- )
- expect(page).to have_no_css(
- PageObjects::Pages::PostVotingTopic::COMMENT_ACTIONS,
- visible: :all,
- )
- end
- end
+ it "does not display button to add a comment and does not show comments when `post_voting_comment_enabled` site setting is false" do
+ SiteSetting.post_voting_comment_enabled = false
+ SiteSetting.post_voting_enabled = true
+
+ topic = Fabricate(:topic, subtype: Topic::POST_VOTING_SUBTYPE, user: user2)
+ post_1 = Fabricate(:post, topic: topic)
+ post_2 = Fabricate(:post, topic: topic)
+
+ sign_in(user1)
+
+ topic_page.visit_topic(topic)
+
+ expect(topic_page).to have_no_comment_menu
+ end
+
+ it "disallows voting on archived or closed topics" do
+ SiteSetting.post_voting_enabled = true
+ topic = Fabricate(:topic, subtype: Topic::POST_VOTING_SUBTYPE, user: user2, archived: true)
+ Fabricate(:post, topic: topic, post_number: 2)
+ post = Fabricate(:post, topic: topic, post_number: 3)
+ Fabricate(:post_voting_comment, post: post, user: user1)
+
+ sign_in(user1)
+
+ topic_page.visit_topic(topic)
+
+ expect(page).to have_css(PageObjects::Pages::PostVotingTopic::POST_VOTE_BUTTON, count: 4)
+ expect(page).to have_css(
+ "#{PageObjects::Pages::PostVotingTopic::POST_VOTE_BUTTON}:disabled",
+ count: 4,
+ )
+ expect(page).to have_css("#{PageObjects::Pages::PostVotingTopic::COMMENT_VOTE_BUTTON}:disabled")
+ expect(page).to have_no_css(PageObjects::Pages::PostVotingTopic::COMMENT_ACTIONS, visible: :all)
end
end
diff --git a/plugins/discourse-post-voting/test/javascripts/acceptance/post-voting-test.js b/plugins/discourse-post-voting/test/javascripts/acceptance/post-voting-test.js
index fabddf151bc..7165f7c4afb 100644
--- a/plugins/discourse-post-voting/test/javascripts/acceptance/post-voting-test.js
+++ b/plugins/discourse-post-voting/test/javascripts/acceptance/post-voting-test.js
@@ -123,13 +123,12 @@ function postVotingTopicListResponse() {
let filteredByActivity = false;
-function setupPostVoting(needs, postStreamMode) {
+function setupPostVoting(needs) {
needs.settings({
post_voting_enabled: true,
min_post_length: 5,
post_voting_comment_max_raw_length: 50,
post_voting_enable_likes_on_answers: false,
- glimmer_post_stream_mode: postStreamMode,
});
needs.hooks.afterEach(function () {
@@ -208,787 +207,762 @@ function setupPostVoting(needs, postStreamMode) {
});
}
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Post Voting - anon user (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- setupPostVoting(needs, postStreamMode);
-
- test("Viewing comments", async function (assert) {
- await visit("/t/280");
-
- assert
- .dom("#post_1 .post-voting-comment")
- .exists(
- { count: 1 },
- "displays the right number of comments for the first post"
- );
-
- assert
- .dom("#post_2 .post-voting-comment")
- .exists(
- { count: 5 },
- "displays the right number of comments for the second post"
- );
-
- assert
- .dom("#post_2 .post-voting-comment-action")
- .doesNotExist("does not display comment action to anon users");
-
- await click(".post-voting-comments-menu-show-more-link");
-
- assert
- .dom("#post_2 .post-voting-comment")
- .exists(
- { count: 6 },
- "displays the right number of comments after loading more"
- );
-
- assert
- .dom(
- "#post_2 .post-voting-comments #post-voting-comment-6 .post-voting-comment-info-username"
- )
- .hasText(i18n("post_voting.post.post_voting_comment.user.deleted"));
- });
+acceptance(`Discourse Post Voting - anon user`, function (needs) {
+ setupPostVoting(needs);
+
+ test("Viewing comments", async function (assert) {
+ await visit("/t/280");
+
+ assert
+ .dom("#post_1 .post-voting-comment")
+ .exists(
+ { count: 1 },
+ "displays the right number of comments for the first post"
+ );
+
+ assert
+ .dom("#post_2 .post-voting-comment")
+ .exists(
+ { count: 5 },
+ "displays the right number of comments for the second post"
+ );
+
+ assert
+ .dom("#post_2 .post-voting-comment-action")
+ .doesNotExist("does not display comment action to anon users");
+
+ await click(".post-voting-comments-menu-show-more-link");
+
+ assert
+ .dom("#post_2 .post-voting-comment")
+ .exists(
+ { count: 6 },
+ "displays the right number of comments after loading more"
+ );
+
+ assert
+ .dom(
+ "#post_2 .post-voting-comments #post-voting-comment-6 .post-voting-comment-info-username"
+ )
+ .hasText(i18n("post_voting.post.post_voting_comment.user.deleted"));
+ });
- test("adding a comment", async function (assert) {
- await visit("/t/280");
- await click(".post-voting-comment-add-link");
+ test("adding a comment", async function (assert) {
+ await visit("/t/280");
+ await click(".post-voting-comment-add-link");
- assert.dom("#login-form").exists("displays the login screen");
- });
+ assert.dom("#login-form").exists("displays the login screen");
+ });
- test("voting a comment", async function (assert) {
- await visit("/t/280");
- await click(
- "#post_2 #post-voting-comment-2 .post-voting-button-upvote"
- );
+ test("voting a comment", async function (assert) {
+ await visit("/t/280");
+ await click("#post_2 #post-voting-comment-2 .post-voting-button-upvote");
- assert.dom("#login-form").exists("displays the login screen");
- });
- }
- );
+ assert.dom("#login-form").exists("displays the login screen");
+ });
+});
- acceptance(
- `Discourse Post Voting - logged in user (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- setupPostVoting(needs, postStreamMode);
- needs.user();
+acceptance(`Discourse Post Voting - logged in user`, function (needs) {
+ setupPostVoting(needs);
+ needs.user();
- test("Post Voting features do not leak into non-Post Voting topics", async function (assert) {
- await visit("/t/130");
+ test("Post Voting features do not leak into non-Post Voting topics", async function (assert) {
+ await visit("/t/130");
- assert.dom("#post_1 button.reply").exists("displays the reply button");
+ assert.dom("#post_1 button.reply").exists("displays the reply button");
- assert
- .dom(".post-voting-answers-header")
- .doesNotExist("does not display the Post Voting answers header");
- });
+ assert
+ .dom(".post-voting-answers-header")
+ .doesNotExist("does not display the Post Voting answers header");
+ });
- test("non Post Voting topics do not have Post Voting specific class on body tag", async function (assert) {
- await visit("/t/130");
-
- assert
- .dom(document.body)
- .doesNotHaveClass(
- "post-voting-topic",
- "does not append Post Voting specific class on body tag"
- );
-
- await visit("/t/280");
-
- assert
- .dom(document.body)
- .hasClass(
- "post-voting-topic",
- "appends Post Voting specific class on body tag"
- );
-
- await visit("/t/130");
-
- assert
- .dom(document.body)
- .doesNotHaveClass(
- "post-voting-topic",
- "does not append Post Voting specific class on body tag"
- );
- });
+ test("non Post Voting topics do not have Post Voting specific class on body tag", async function (assert) {
+ await visit("/t/130");
+
+ assert
+ .dom(document.body)
+ .doesNotHaveClass(
+ "post-voting-topic",
+ "does not append Post Voting specific class on body tag"
+ );
+
+ await visit("/t/280");
+
+ assert
+ .dom(document.body)
+ .hasClass(
+ "post-voting-topic",
+ "appends Post Voting specific class on body tag"
+ );
+
+ await visit("/t/130");
+
+ assert
+ .dom(document.body)
+ .doesNotHaveClass(
+ "post-voting-topic",
+ "does not append Post Voting specific class on body tag"
+ );
+ });
- test("Post Voting topics has relevant copy on reply button", async function (assert) {
- await visit("/t/280");
+ test("Post Voting topics has relevant copy on reply button", async function (assert) {
+ await visit("/t/280");
- assert
- .dom(".reply.create .d-button-label")
- .hasText(
- i18n("post_voting.topic.answer.label"),
- "displays the correct reply label"
- );
- });
+ assert
+ .dom(".reply.create .d-button-label")
+ .hasText(
+ i18n("post_voting.topic.answer.label"),
+ "displays the correct reply label"
+ );
+ });
- test("sorting post stream by activity and votes", async function (assert) {
- await visit("/t/280");
-
- assert
- .dom(".post-voting-answers-headers-sort-votes")
- .isDisabled("sort by votes button is disabled by default");
-
- assert
- .dom(document.body)
- .hasClass(
- "post-voting-topic",
- "appends the right class to body when loading Post Voting topic"
- );
-
- await click(".post-voting-answers-headers-sort-activity");
-
- assert.true(
- filteredByActivity,
- "refreshes post stream with the right filter"
- );
-
- assert
- .dom(document.body)
- .hasClass(
- "post-voting-topic-sort-by-activity",
- "appends the right class to body when topic is filtered by activity"
- );
-
- assert
- .dom(".post-voting-answers-headers-sort-activity")
- .isDisabled("disabled sort by activity button");
-
- await click(".post-voting-answers-headers-sort-votes");
-
- assert
- .dom(".post-voting-answers-headers-sort-votes")
- .isDisabled("disables sort by votes button");
-
- assert
- .dom(document.body)
- .hasClass(
- "post-voting-topic",
- "appends the right class to body when topic is filtered by votes"
- );
-
- assert.false(
- filteredByActivity,
- "removes activity filter from post stream"
- );
- });
+ test("sorting post stream by activity and votes", async function (assert) {
+ await visit("/t/280");
+
+ assert
+ .dom(".post-voting-answers-headers-sort-votes")
+ .isDisabled("sort by votes button is disabled by default");
+
+ assert
+ .dom(document.body)
+ .hasClass(
+ "post-voting-topic",
+ "appends the right class to body when loading Post Voting topic"
+ );
+
+ await click(".post-voting-answers-headers-sort-activity");
+
+ assert.true(
+ filteredByActivity,
+ "refreshes post stream with the right filter"
+ );
+
+ assert
+ .dom(document.body)
+ .hasClass(
+ "post-voting-topic-sort-by-activity",
+ "appends the right class to body when topic is filtered by activity"
+ );
+
+ assert
+ .dom(".post-voting-answers-headers-sort-activity")
+ .isDisabled("disabled sort by activity button");
+
+ await click(".post-voting-answers-headers-sort-votes");
+
+ assert
+ .dom(".post-voting-answers-headers-sort-votes")
+ .isDisabled("disables sort by votes button");
+
+ assert
+ .dom(document.body)
+ .hasClass(
+ "post-voting-topic",
+ "appends the right class to body when topic is filtered by votes"
+ );
+
+ assert.false(
+ filteredByActivity,
+ "removes activity filter from post stream"
+ );
+ });
- test("reply buttons are hidden in post stream except for the first post", async function (assert) {
- await visit("/t/280");
+ test("reply buttons are hidden in post stream except for the first post", async function (assert) {
+ await visit("/t/280");
- assert
- .dom("#post_1 .reply")
- .exists("reply button is shown for the first post");
+ assert
+ .dom("#post_1 .reply")
+ .exists("reply button is shown for the first post");
- assert
- .dom("#post_2 .reply")
- .doesNotExist("reply button is only shown for the first post");
- });
+ assert
+ .dom("#post_2 .reply")
+ .doesNotExist("reply button is only shown for the first post");
+ });
- test("like buttons are hidden in post stream except for the first post", async function (assert) {
- await visit("/t/280");
+ test("like buttons are hidden in post stream except for the first post", async function (assert) {
+ await visit("/t/280");
- assert
- .dom("#post_1 .like")
- .exists("like button is shown for the first post");
+ assert
+ .dom("#post_1 .like")
+ .exists("like button is shown for the first post");
- assert
- .dom("#post_2 .like")
- .doesNotExist("like button is only shown for the first post");
- });
+ assert
+ .dom("#post_2 .like")
+ .doesNotExist("like button is only shown for the first post");
+ });
- test("validations for comment length", async function (assert) {
- await visit("/t/280");
- await click("#post_1 .post-voting-comment-add-link");
+ test("validations for comment length", async function (assert) {
+ await visit("/t/280");
+ await click("#post_1 .post-voting-comment-add-link");
- await fillIn(".post-voting-comment-composer-textarea", "a".repeat(4));
+ await fillIn(".post-voting-comment-composer-textarea", "a".repeat(4));
- assert.dom(".post-voting-comment-composer-flash").hasText(
- i18n("post_voting.post.post_voting_comment.composer.too_short", {
- count: 5,
- }),
- "displays the right message about raw length when it is too short"
- );
+ assert.dom(".post-voting-comment-composer-flash").hasText(
+ i18n("post_voting.post.post_voting_comment.composer.too_short", {
+ count: 5,
+ }),
+ "displays the right message about raw length when it is too short"
+ );
- assert
- .dom(".post-voting-comments-menu-composer-submit")
- .isDisabled("submit comment button is disabled");
+ assert
+ .dom(".post-voting-comments-menu-composer-submit")
+ .isDisabled("submit comment button is disabled");
- await fillIn(".post-voting-comment-composer-textarea", "a".repeat(6));
+ await fillIn(".post-voting-comment-composer-textarea", "a".repeat(6));
- assert.dom(".post-voting-comment-composer-flash").hasText(
- i18n("post_voting.post.post_voting_comment.composer.length_ok", {
- count: 44,
- }),
- "displays the right message about raw length when it is OK"
- );
+ assert.dom(".post-voting-comment-composer-flash").hasText(
+ i18n("post_voting.post.post_voting_comment.composer.length_ok", {
+ count: 44,
+ }),
+ "displays the right message about raw length when it is OK"
+ );
- assert
- .dom(".post-voting-comments-menu-composer-submit")
- .isEnabled("submit comment button is enabled");
+ assert
+ .dom(".post-voting-comments-menu-composer-submit")
+ .isEnabled("submit comment button is enabled");
- await fillIn(".post-voting-comment-composer-textarea", "a".repeat(51));
+ await fillIn(".post-voting-comment-composer-textarea", "a".repeat(51));
- assert.dom(".post-voting-comment-composer-flash").hasText(
- i18n("post_voting.post.post_voting_comment.composer.too_long", {
- count: 50,
- }),
- "displays the right message about raw length when it is too long"
- );
+ assert.dom(".post-voting-comment-composer-flash").hasText(
+ i18n("post_voting.post.post_voting_comment.composer.too_long", {
+ count: 50,
+ }),
+ "displays the right message about raw length when it is too long"
+ );
- assert
- .dom(".post-voting-comments-menu-composer-submit")
- .isDisabled("submit comment button is disabled");
- });
+ assert
+ .dom(".post-voting-comments-menu-composer-submit")
+ .isDisabled("submit comment button is disabled");
+ });
- test("adding a comment", async function (assert) {
- await visit("/t/280");
+ test("adding a comment", async function (assert) {
+ await visit("/t/280");
- assert
- .dom("#post_1 .post-voting-comment")
- .exists(
- { count: 1 },
- "displays the right number of comments for the first post"
- );
+ assert
+ .dom("#post_1 .post-voting-comment")
+ .exists(
+ { count: 1 },
+ "displays the right number of comments for the first post"
+ );
- await click("#post_1 .post-voting-comment-add-link");
+ await click("#post_1 .post-voting-comment-add-link");
- assert
- .dom("#post_1 .post-voting-comment")
- .exists({ count: 2 }, "loads all comments when composer is expanded");
+ assert
+ .dom("#post_1 .post-voting-comment")
+ .exists({ count: 2 }, "loads all comments when composer is expanded");
- await fillIn(
- ".post-voting-comment-composer-textarea",
- "this is some comment"
- );
- await click(".post-voting-comments-menu-composer-submit");
+ await fillIn(
+ ".post-voting-comment-composer-textarea",
+ "this is some comment"
+ );
+ await click(".post-voting-comments-menu-composer-submit");
- assert
- .dom("#post_1 .post-voting-comment")
- .exists({ count: 3 }, "should add the new comment");
- });
+ assert
+ .dom("#post_1 .post-voting-comment")
+ .exists({ count: 3 }, "should add the new comment");
+ });
- test("adding a comment with keyboard shortcut", async function (assert) {
- await visit("/t/280");
- await click("#post_1 .post-voting-comment-add-link");
+ test("adding a comment with keyboard shortcut", async function (assert) {
+ await visit("/t/280");
+ await click("#post_1 .post-voting-comment-add-link");
- assert
- .dom("#post_1 .post-voting-comment")
- .exists({ count: 2 }, "loads all comments when composer is expanded");
+ assert
+ .dom("#post_1 .post-voting-comment")
+ .exists({ count: 2 }, "loads all comments when composer is expanded");
- await fillIn(
- ".post-voting-comment-composer-textarea",
- "this is a new test comment"
- );
+ await fillIn(
+ ".post-voting-comment-composer-textarea",
+ "this is a new test comment"
+ );
- await triggerEvent(
- ".post-voting-comments-menu-composer-submit",
- "keydown",
- {
- key: "Enter",
- ctrlKey: true,
- }
- );
-
- assert
- .dom("#post_1 .post-voting-comment")
- .exists({ count: 3 }, "should add the new comment");
- });
+ await triggerEvent(
+ ".post-voting-comments-menu-composer-submit",
+ "keydown",
+ {
+ key: "Enter",
+ ctrlKey: true,
+ }
+ );
- test("regular user can't edit other people's comments", async function (assert) {
- updateCurrentUser({ id: 9876, admin: false, moderator: false }); // hasn't commented
+ assert
+ .dom("#post_1 .post-voting-comment")
+ .exists({ count: 3 }, "should add the new comment");
+ });
- await visit("/t/280");
+ test("regular user can't edit other people's comments", async function (assert) {
+ updateCurrentUser({ id: 9876, admin: false, moderator: false }); // hasn't commented
- assert
- .dom("#post_2 .post-voting-comment-actions")
- .doesNotExist(
- "does not display edit link on other people's comments"
- );
- });
+ await visit("/t/280");
- test("moderator can edit other people's comments", async function (assert) {
- updateCurrentUser({ id: 9876, admin: false, moderator: true }); // hasn't commented
+ assert
+ .dom("#post_2 .post-voting-comment-actions")
+ .doesNotExist("does not display edit link on other people's comments");
+ });
- await visit("/t/280");
+ test("moderator can edit other people's comments", async function (assert) {
+ updateCurrentUser({ id: 9876, admin: false, moderator: true }); // hasn't commented
- assert
- .dom("#post_2 .post-voting-comment-actions")
- .exists(
- { count: 5 },
- "displays edit link on other people's comments"
- );
- });
+ await visit("/t/280");
- test("admin can edit other people's comments", async function (assert) {
- updateCurrentUser({ id: 9876, admin: true, moderator: false }); // hasn't commented
+ assert
+ .dom("#post_2 .post-voting-comment-actions")
+ .exists({ count: 5 }, "displays edit link on other people's comments");
+ });
- await visit("/t/280");
+ test("admin can edit other people's comments", async function (assert) {
+ updateCurrentUser({ id: 9876, admin: true, moderator: false }); // hasn't commented
- assert
- .dom("#post_2 .post-voting-comment-actions")
- .exists(
- { count: 5 },
- "displays edit link on other people's comments"
- );
- });
+ await visit("/t/280");
- test("editing a comment", async function (assert) {
- updateCurrentUser({ id: 12345 }); // userId of comments in fixtures
-
- await visit("/t/280");
-
- assert
- .dom("#post_1 .post-voting-comment-cooked")
- .hasText(
- "Test comment 1",
- "displays the right content for the given comment"
- );
-
- await click("#post_1 .post-voting-comment-actions-edit-link");
-
- await fillIn(".post-voting-comment-composer-textarea", "a".repeat(4));
-
- assert.dom(".post-voting-comment-composer-flash").hasText(
- i18n("post_voting.post.post_voting_comment.composer.too_short", {
- count: 5,
- }),
- "displays the right message about raw length when it is too short"
- );
-
- assert
- .dom(".post-voting-comment-editor-submit")
- .isDisabled("submit comment button is disabled");
-
- await fillIn(
- "#post_1 .post-voting-comment-editor-1 textarea",
- "editing this"
- );
-
- assert.dom(".post-voting-comment-composer-flash").hasText(
- i18n("post_voting.post.post_voting_comment.composer.length_ok", {
- count: 38,
- }),
- "displays the right message when comment length is OK"
- );
-
- assert
- .dom(".post-voting-comment-editor-submit")
- .isEnabled("submit comment button is enabled");
-
- await click(
- "#post_1 .post-voting-comment-editor-1 .post-voting-comment-editor-submit"
- );
-
- assert
- .dom("#post_1 .post-voting-comment-cooked")
- .hasText(
- "editing this",
- "displays the right content after comment has been edited"
- );
-
- assert
- .dom("#post_1 .post-voting-comment-editor-1")
- .doesNotExist("hides editor after comment has been edited");
- });
+ assert
+ .dom("#post_2 .post-voting-comment-actions")
+ .exists({ count: 5 }, "displays edit link on other people's comments");
+ });
- test("deleting a comment", async function (assert) {
- updateCurrentUser({ id: 12345 }); // userId of comments in fixtures
+ test("editing a comment", async function (assert) {
+ updateCurrentUser({ id: 12345 }); // userId of comments in fixtures
+
+ await visit("/t/280");
+
+ assert
+ .dom("#post_1 .post-voting-comment-cooked")
+ .hasText(
+ "Test comment 1",
+ "displays the right content for the given comment"
+ );
+
+ await click("#post_1 .post-voting-comment-actions-edit-link");
+
+ await fillIn(".post-voting-comment-composer-textarea", "a".repeat(4));
+
+ assert.dom(".post-voting-comment-composer-flash").hasText(
+ i18n("post_voting.post.post_voting_comment.composer.too_short", {
+ count: 5,
+ }),
+ "displays the right message about raw length when it is too short"
+ );
+
+ assert
+ .dom(".post-voting-comment-editor-submit")
+ .isDisabled("submit comment button is disabled");
+
+ await fillIn(
+ "#post_1 .post-voting-comment-editor-1 textarea",
+ "editing this"
+ );
+
+ assert.dom(".post-voting-comment-composer-flash").hasText(
+ i18n("post_voting.post.post_voting_comment.composer.length_ok", {
+ count: 38,
+ }),
+ "displays the right message when comment length is OK"
+ );
+
+ assert
+ .dom(".post-voting-comment-editor-submit")
+ .isEnabled("submit comment button is enabled");
+
+ await click(
+ "#post_1 .post-voting-comment-editor-1 .post-voting-comment-editor-submit"
+ );
+
+ assert
+ .dom("#post_1 .post-voting-comment-cooked")
+ .hasText(
+ "editing this",
+ "displays the right content after comment has been edited"
+ );
+
+ assert
+ .dom("#post_1 .post-voting-comment-editor-1")
+ .doesNotExist("hides editor after comment has been edited");
+ });
- await visit("/t/280");
+ test("deleting a comment", async function (assert) {
+ updateCurrentUser({ id: 12345 }); // userId of comments in fixtures
- assert
- .dom("#post_1 .post-voting-comment")
- .exists(
- { count: 1 },
- "displays the right number of comments for the first post"
- );
+ await visit("/t/280");
- await click("#post_1 .post-voting-comment-actions-delete-link");
- await click("button.btn-danger");
+ assert
+ .dom("#post_1 .post-voting-comment")
+ .exists(
+ { count: 1 },
+ "displays the right number of comments for the first post"
+ );
- assert
- .dom("#post_1 #post-voting-comment-1")
- .hasClass(
- "post-voting-comment-deleted",
- "adds the right class to deleted comment"
- );
- });
+ await click("#post_1 .post-voting-comment-actions-delete-link");
+ await click("button.btn-danger");
- test("deleting a comment after more comments have been loaded", async function (assert) {
- updateCurrentUser({ admin: true });
+ assert
+ .dom("#post_1 #post-voting-comment-1")
+ .hasClass(
+ "post-voting-comment-deleted",
+ "adds the right class to deleted comment"
+ );
+ });
- await visit("/t/280");
+ test("deleting a comment after more comments have been loaded", async function (assert) {
+ updateCurrentUser({ admin: true });
- assert
- .dom("#post_2 .post-voting-comment")
- .exists(
- { count: 5 },
- "displays the right number of comments for the second post"
- );
+ await visit("/t/280");
- await click("#post_2 .post-voting-comments-menu-show-more-link");
+ assert
+ .dom("#post_2 .post-voting-comment")
+ .exists(
+ { count: 5 },
+ "displays the right number of comments for the second post"
+ );
- assert
- .dom("#post_2 .post-voting-comment")
- .exists({ count: 6 }, "appends the loaded comments");
+ await click("#post_2 .post-voting-comments-menu-show-more-link");
- const comments = document.querySelectorAll(
- "#post_2 .post-voting-comment-actions-delete-link"
- );
+ assert
+ .dom("#post_2 .post-voting-comment")
+ .exists({ count: 6 }, "appends the loaded comments");
- await click(comments[comments.length - 1]);
- await click("button.btn-danger");
+ const comments = document.querySelectorAll(
+ "#post_2 .post-voting-comment-actions-delete-link"
+ );
- assert
- .dom("#post_2 .post-voting-comments-menu-show-more-link")
- .doesNotExist(
- "updates the comment count such that show more link is not displayed"
- );
+ await click(comments[comments.length - 1]);
+ await click("button.btn-danger");
- assert
- .dom("#post_2 #post-voting-comment-7")
- .hasClass(
- "post-voting-comment-deleted",
- "adds the right class to deleted comment"
- );
- });
+ assert
+ .dom("#post_2 .post-voting-comments-menu-show-more-link")
+ .doesNotExist(
+ "updates the comment count such that show more link is not displayed"
+ );
- test("vote count display", async function (assert) {
- await visit("/t/280");
+ assert
+ .dom("#post_2 #post-voting-comment-7")
+ .hasClass(
+ "post-voting-comment-deleted",
+ "adds the right class to deleted comment"
+ );
+ });
- assert
- .dom(
- "#post_2 #post-voting-comment-2 .post-voting-comment-actions-vote-count"
- )
- .doesNotExist("does not display element if vote count is zero");
+ test("vote count display", async function (assert) {
+ await visit("/t/280");
- assert
- .dom(
- "#post_2 #post-voting-comment-3 .post-voting-comment-actions-vote-count"
- )
- .hasText("3", "displays the right vote count");
- });
+ assert
+ .dom(
+ "#post_2 #post-voting-comment-2 .post-voting-comment-actions-vote-count"
+ )
+ .doesNotExist("does not display element if vote count is zero");
- test("voting on a comment and removing vote", async function (assert) {
- await visit("/t/280");
+ assert
+ .dom(
+ "#post_2 #post-voting-comment-3 .post-voting-comment-actions-vote-count"
+ )
+ .hasText("3", "displays the right vote count");
+ });
- await click(
- "#post_2 #post-voting-comment-2 .post-voting-button-upvote"
- );
+ test("voting on a comment and removing vote", async function (assert) {
+ await visit("/t/280");
- assert
- .dom(
- "#post_2 #post-voting-comment-2 .post-voting-comment-actions-vote-count"
- )
- .hasText("1", "updates the comment vote count correctly");
+ await click("#post_2 #post-voting-comment-2 .post-voting-button-upvote");
- await click(
- "#post_2 #post-voting-comment-2 .post-voting-button-upvote"
- );
+ assert
+ .dom(
+ "#post_2 #post-voting-comment-2 .post-voting-comment-actions-vote-count"
+ )
+ .hasText("1", "updates the comment vote count correctly");
- assert
- .dom(
- "#post_2 #post-voting-comment-2 .post-voting-comment-actions-vote-count"
- )
- .doesNotExist("updates the comment vote count correctly");
- });
+ await click("#post_2 #post-voting-comment-2 .post-voting-button-upvote");
- test("topic list link overrides work", async function (assert) {
- await visit("/");
+ assert
+ .dom(
+ "#post_2 #post-voting-comment-2 .post-voting-comment-actions-vote-count"
+ )
+ .doesNotExist("updates the comment vote count correctly");
+ });
- assert
- .dom(".topic-list-item:first-child .raw-topic-link")
- .hasAttribute("href", /\/1$/);
+ test("topic list link overrides work", async function (assert) {
+ await visit("/");
- assert
- .dom(".topic-list-item:nth-child(2) .raw-topic-link")
- .hasAttribute("href", /\?filter=activity$/);
+ assert
+ .dom(".topic-list-item:first-child .raw-topic-link")
+ .hasAttribute("href", /\/1$/);
- assert
- .dom(".topic-list-item:nth-child(4) .raw-topic-link")
- .hasAttribute("href", /\/2$/);
- });
+ assert
+ .dom(".topic-list-item:nth-child(2) .raw-topic-link")
+ .hasAttribute("href", /\?filter=activity$/);
- test("receiving user post voted message where current user removed their vote", async function (assert) {
- await visit("/t/280");
-
- publishToMessageBus("/topic/280", {
- type: "post_voting_post_voted",
- id: topicResponse.post_stream.posts[1].id,
- post_voting_vote_count: 0,
- post_voting_has_votes: false,
- post_voting_user_voted_id: 19,
- post_voting_user_voted_direction: null,
- });
-
- await settled();
-
- assert
- .dom("#post_2 span.post-voting-post-toggle-voters")
- .hasText("0", "displays the right count");
-
- assert
- .dom("#post_2 .post-voting-button-upvote")
- .doesNotHaveClass(
- "post-voting-button-voted",
- "does not highlight the upvote button"
- );
- });
+ assert
+ .dom(".topic-list-item:nth-child(4) .raw-topic-link")
+ .hasAttribute("href", /\/2$/);
+ });
- test("receiving user post voted message where post no longer has votes", async function (assert) {
- await visit("/t/280");
+ test("receiving user post voted message where current user removed their vote", async function (assert) {
+ await visit("/t/280");
- publishToMessageBus("/topic/280", {
- type: "post_voting_post_voted",
- id: topicResponse.post_stream.posts[1].id,
- post_voting_vote_count: 0,
- post_voting_has_votes: false,
- post_voting_user_voted_id: 280,
- post_voting_user_voted_direction: "down",
- });
+ publishToMessageBus("/topic/280", {
+ type: "post_voting_post_voted",
+ id: topicResponse.post_stream.posts[1].id,
+ post_voting_vote_count: 0,
+ post_voting_has_votes: false,
+ post_voting_user_voted_id: 19,
+ post_voting_user_voted_direction: null,
+ });
- await settled();
+ await settled();
- assert
- .dom("#post_2 span.post-voting-post-toggle-voters")
- .hasText("0", "does not render a button to show post voters");
- });
+ assert
+ .dom("#post_2 span.post-voting-post-toggle-voters")
+ .hasText("0", "displays the right count");
- test("receiving user post voted message where current user is not the one that voted", async function (assert) {
- await visit("/t/280");
-
- publishToMessageBus("/topic/280", {
- type: "post_voting_post_voted",
- id: topicResponse.post_stream.posts[1].id,
- post_voting_vote_count: 5,
- post_voting_has_votes: true,
- post_voting_user_voted_id: 123456,
- post_voting_user_voted_direction: "down",
- });
-
- await settled();
-
- assert
- .dom("#post_2 .post-voting-post-toggle-voters")
- .hasText("5", "displays the right post vote count");
-
- assert
- .dom("#post_2 .post-voting-button-upvote")
- .hasClass(
- "post-voting-button-voted",
- "highlights the upvote button for the current user"
- );
-
- assert
- .dom("#post_2 .post-voting-button-downvote")
- .doesNotHaveClass(
- "post-voting-button-voted",
- "does not highlight the downvote button for the current user"
- );
- });
+ assert
+ .dom("#post_2 .post-voting-button-upvote")
+ .doesNotHaveClass(
+ "post-voting-button-voted",
+ "does not highlight the upvote button"
+ );
+ });
- test("receiving user post voted message where current user is the one that voted", async function (assert) {
- await visit("/t/280");
-
- publishToMessageBus("/topic/280", {
- type: "post_voting_post_voted",
- id: topicResponse.post_stream.posts[1].id,
- post_voting_vote_count: 5,
- post_voting_has_votes: true,
- post_voting_user_voted_id: 19,
- post_voting_user_voted_direction: "up",
- });
-
- await settled();
-
- assert
- .dom("#post_2 .post-voting-post-toggle-voters")
- .hasText("5", "displays the right post vote count");
-
- assert
- .dom("#post_2 .post-voting-button-upvote")
- .hasClass(
- "post-voting-button-voted",
- "highlights the upvote button for the current user"
- );
- });
+ test("receiving user post voted message where post no longer has votes", async function (assert) {
+ await visit("/t/280");
- test("receiving post commented message when comment has already been loaded", async function (assert) {
- await visit("/t/280");
+ publishToMessageBus("/topic/280", {
+ type: "post_voting_post_voted",
+ id: topicResponse.post_stream.posts[1].id,
+ post_voting_vote_count: 0,
+ post_voting_has_votes: false,
+ post_voting_user_voted_id: 280,
+ post_voting_user_voted_direction: "down",
+ });
- publishToMessageBus("/topic/280", {
- type: "post_voting_post_commented",
- id: topicResponse.post_stream.posts[0].id,
- comments_count: 1,
- comment: topicResponse.post_stream.posts[0]["comments"][0],
- });
+ await settled();
- await settled();
+ assert
+ .dom("#post_2 span.post-voting-post-toggle-voters")
+ .hasText("0", "does not render a button to show post voters");
+ });
- assert
- .dom("#post_1 #post-voting-comment-5678")
- .doesNotExist(
- "does not append comment when comment has already been loaded"
- );
- });
+ test("receiving user post voted message where current user is not the one that voted", async function (assert) {
+ await visit("/t/280");
- test("receiving post commented message for a comment created by the current user", async function (assert) {
- updateCurrentUser({ id: 12345 });
+ publishToMessageBus("/topic/280", {
+ type: "post_voting_post_voted",
+ id: topicResponse.post_stream.posts[1].id,
+ post_voting_vote_count: 5,
+ post_voting_has_votes: true,
+ post_voting_user_voted_id: 123456,
+ post_voting_user_voted_direction: "down",
+ });
- await visit("/t/280");
+ await settled();
+
+ assert
+ .dom("#post_2 .post-voting-post-toggle-voters")
+ .hasText("5", "displays the right post vote count");
+
+ assert
+ .dom("#post_2 .post-voting-button-upvote")
+ .hasClass(
+ "post-voting-button-voted",
+ "highlights the upvote button for the current user"
+ );
+
+ assert
+ .dom("#post_2 .post-voting-button-downvote")
+ .doesNotHaveClass(
+ "post-voting-button-voted",
+ "does not highlight the downvote button for the current user"
+ );
+ });
- publishToMessageBus("/topic/280", {
- type: "post_voting_post_commented",
- id: topicResponse.post_stream.posts[0].id,
- comments_count: 2,
- comment: {
- id: 5678,
- user_id: 12345,
- name: "Some Commenter",
- username: "some_commenter",
- created_at: "2022-01-12T08:21:54.175Z",
- cooked: "<p>Test comment ABC</p>",
- },
- });
+ test("receiving user post voted message where current user is the one that voted", async function (assert) {
+ await visit("/t/280");
- await settled();
+ publishToMessageBus("/topic/280", {
+ type: "post_voting_post_voted",
+ id: topicResponse.post_stream.posts[1].id,
+ post_voting_vote_count: 5,
+ post_voting_has_votes: true,
+ post_voting_user_voted_id: 19,
+ post_voting_user_voted_direction: "up",
+ });
- assert
- .dom("#post_1 #post-voting-comment-5678")
- .doesNotExist("does not append comment");
- });
+ await settled();
- test("receiving post commented message when there are no more comments to load ", async function (assert) {
- await visit("/t/280");
-
- publishToMessageBus("/topic/280", {
- type: "post_voting_post_commented",
- id: topicResponse.post_stream.posts[0].id,
- comments_count: 2,
- comment: {
- id: 5678,
- user_id: 12345,
- name: "Some Commenter",
- username: "some_commenter",
- created_at: "2022-01-12T08:21:54.175Z",
- cooked: "<p>Test comment ABC</p>",
- },
- });
+ assert
+ .dom("#post_2 .post-voting-post-toggle-voters")
+ .hasText("5", "displays the right post vote count");
- await settled();
+ assert
+ .dom("#post_2 .post-voting-button-upvote")
+ .hasClass(
+ "post-voting-button-voted",
+ "highlights the upvote button for the current user"
+ );
+ });
- assert
- .dom("#post_1 #post-voting-comment-5678")
- .includesText(
- "Test comment ABC",
- "appends comment to comments stream"
- );
- });
+ test("receiving post commented message when comment has already been loaded", async function (assert) {
+ await visit("/t/280");
- test("receiving post commented message when there are more comments to load", async function (assert) {
- await visit("/t/280");
-
- publishToMessageBus("/topic/280", {
- type: "post_voting_post_commented",
- id: topicResponse.post_stream.posts[1].id,
- comments_count: 7,
- comment: {
- id: 5678,
- user_id: 12345,
- name: "Some Commenter",
- username: "some_commenter",
- created_at: "2022-01-12T08:21:54.175Z",
- cooked: "<p>Test comment ABC</p>",
- },
- });
+ publishToMessageBus("/topic/280", {
+ type: "post_voting_post_commented",
+ id: topicResponse.post_stream.posts[0].id,
+ comments_count: 1,
+ comment: topicResponse.post_stream.posts[0]["comments"][0],
+ });
- await settled();
+ await settled();
- assert
- .dom("#post_2 #post-voting-comment-5678")
- .doesNotExist(
- "does not append comment when there are more comments to load"
- );
+ assert
+ .dom("#post_1 #post-voting-comment-5678")
+ .doesNotExist(
+ "does not append comment when comment has already been loaded"
+ );
+ });
- assert
- .dom("#post_2 .post-voting-comments-menu-show-more-link")
- .exists("updates the comments count to reflect the new comment");
- });
+ test("receiving post commented message for a comment created by the current user", async function (assert) {
+ updateCurrentUser({ id: 12345 });
- test("receiving post comment trashed message for a comment that has not been loaded ", async function (assert) {
- await visit("/t/280");
+ await visit("/t/280");
- publishToMessageBus("/topic/280", {
- type: "post_voting_post_comment_trashed",
- id: topicResponse.post_stream.posts[1].id,
- comments_count: 5,
- comment_id: 12345,
- });
+ publishToMessageBus("/topic/280", {
+ type: "post_voting_post_commented",
+ id: topicResponse.post_stream.posts[0].id,
+ comments_count: 2,
+ comment: {
+ id: 5678,
+ user_id: 12345,
+ name: "Some Commenter",
+ username: "some_commenter",
+ created_at: "2022-01-12T08:21:54.175Z",
+ cooked: "<p>Test comment ABC</p>",
+ },
+ });
- await settled();
+ await settled();
- assert
- .dom("#post_2 .post-voting-comments-menu-show-more-link")
- .doesNotExist("removes the show more comments link");
- });
+ assert
+ .dom("#post_1 #post-voting-comment-5678")
+ .doesNotExist("does not append comment");
+ });
- test("receiving post comment trashed message for a comment that has been loaded", async function (assert) {
- await visit("/t/280");
+ test("receiving post commented message when there are no more comments to load ", async function (assert) {
+ await visit("/t/280");
- publishToMessageBus("/topic/280", {
- type: "post_voting_post_comment_trashed",
- id: topicResponse.post_stream.posts[1].id,
- comments_count: 5,
- comment_id: topicResponse.post_stream.posts[1].comments[0].id,
- });
+ publishToMessageBus("/topic/280", {
+ type: "post_voting_post_commented",
+ id: topicResponse.post_stream.posts[0].id,
+ comments_count: 2,
+ comment: {
+ id: 5678,
+ user_id: 12345,
+ name: "Some Commenter",
+ username: "some_commenter",
+ created_at: "2022-01-12T08:21:54.175Z",
+ cooked: "<p>Test comment ABC</p>",
+ },
+ });
- await settled();
+ await settled();
- assert
- .dom("#post_2 #post-voting-comment-2")
- .hasClass(
- "post-voting-comment-deleted",
- "adds the right class to the comment"
- );
- });
+ assert
+ .dom("#post_1 #post-voting-comment-5678")
+ .includesText("Test comment ABC", "appends comment to comments stream");
+ });
- test("receiving post comment edited message for a comment that has been loaded", async function (assert) {
- await visit("/t/280");
-
- publishToMessageBus("/topic/280", {
- type: "post_voting_post_comment_edited",
- id: topicResponse.post_stream.posts[0].id,
- comment_id: topicResponse.post_stream.posts[0].comments[0].id,
- comment_raw: "this is a new comment raw",
- comment_cooked: "<p>this is a new comment cooked</p>",
- });
-
- await settled();
-
- assert
- .dom("#post_1 #post-voting-comment-1 .post-voting-comment-cooked")
- .hasText(
- "this is a new comment cooked",
- "updates the content of the comment"
- );
-
- await click(
- "#post_1 #post-voting-comment-1 .post-voting-comment-actions-edit-link"
- );
-
- assert
- .dom(
- "#post_1 #post-voting-comment-1 .post-voting-comment-composer textarea"
- )
- .hasValue(
- "this is a new comment raw",
- "updates the content of the comment editor"
- );
- });
- }
- );
+ test("receiving post commented message when there are more comments to load", async function (assert) {
+ await visit("/t/280");
+
+ publishToMessageBus("/topic/280", {
+ type: "post_voting_post_commented",
+ id: topicResponse.post_stream.posts[1].id,
+ comments_count: 7,
+ comment: {
+ id: 5678,
+ user_id: 12345,
+ name: "Some Commenter",
+ username: "some_commenter",
+ created_at: "2022-01-12T08:21:54.175Z",
+ cooked: "<p>Test comment ABC</p>",
+ },
+ });
+
+ await settled();
+
+ assert
+ .dom("#post_2 #post-voting-comment-5678")
+ .doesNotExist(
+ "does not append comment when there are more comments to load"
+ );
+
+ assert
+ .dom("#post_2 .post-voting-comments-menu-show-more-link")
+ .exists("updates the comments count to reflect the new comment");
+ });
+
+ test("receiving post comment trashed message for a comment that has not been loaded ", async function (assert) {
+ await visit("/t/280");
+
+ publishToMessageBus("/topic/280", {
+ type: "post_voting_post_comment_trashed",
+ id: topicResponse.post_stream.posts[1].id,
+ comments_count: 5,
+ comment_id: 12345,
+ });
+
+ await settled();
+
+ assert
+ .dom("#post_2 .post-voting-comments-menu-show-more-link")
+ .doesNotExist("removes the show more comments link");
+ });
+
+ test("receiving post comment trashed message for a comment that has been loaded", async function (assert) {
+ await visit("/t/280");
+
+ publishToMessageBus("/topic/280", {
+ type: "post_voting_post_comment_trashed",
+ id: topicResponse.post_stream.posts[1].id,
+ comments_count: 5,
+ comment_id: topicResponse.post_stream.posts[1].comments[0].id,
+ });
+
+ await settled();
+
+ assert
+ .dom("#post_2 #post-voting-comment-2")
+ .hasClass(
+ "post-voting-comment-deleted",
+ "adds the right class to the comment"
+ );
+ });
+
+ test("receiving post comment edited message for a comment that has been loaded", async function (assert) {
+ await visit("/t/280");
+
+ publishToMessageBus("/topic/280", {
+ type: "post_voting_post_comment_edited",
+ id: topicResponse.post_stream.posts[0].id,
+ comment_id: topicResponse.post_stream.posts[0].comments[0].id,
+ comment_raw: "this is a new comment raw",
+ comment_cooked: "<p>this is a new comment cooked</p>",
+ });
+
+ await settled();
+
+ assert
+ .dom("#post_1 #post-voting-comment-1 .post-voting-comment-cooked")
+ .hasText(
+ "this is a new comment cooked",
+ "updates the content of the comment"
+ );
+
+ await click(
+ "#post_1 #post-voting-comment-1 .post-voting-comment-actions-edit-link"
+ );
+
+ assert
+ .dom(
+ "#post_1 #post-voting-comment-1 .post-voting-comment-composer textarea"
+ )
+ .hasValue(
+ "this is a new comment raw",
+ "updates the content of the comment editor"
+ );
+ });
});
diff --git a/plugins/discourse-reactions/assets/javascripts/discourse/initializers/discourse-reactions.gjs b/plugins/discourse-reactions/assets/javascripts/discourse/initializers/discourse-reactions.gjs
index 059c6e5b49b..7d03cffdc0b 100644
--- a/plugins/discourse-reactions/assets/javascripts/discourse/initializers/discourse-reactions.gjs
+++ b/plugins/discourse-reactions/assets/javascripts/discourse/initializers/discourse-reactions.gjs
@@ -1,4 +1,3 @@
-import { withSilencedDeprecations } from "discourse/lib/deprecated";
import { replaceIcon } from "discourse/lib/icon-library";
import { withPluginApi } from "discourse/lib/plugin-api";
import { emojiUrlFor } from "discourse/lib/text";
@@ -15,7 +14,6 @@ replaceIcon("notification.reaction", "bell");
function initializeDiscourseReactions(api) {
customizePostMenu(api);
- customizeWidgetPost(api);
api.addKeyboardShortcut("l", null, {
click: ".topic-post.selected .discourse-reactions-reaction-button",
@@ -154,43 +152,6 @@ function initializeDiscourseReactions(api) {
}
}
-function customizeWidgetPost(api) {
- withSilencedDeprecations("discourse.post-stream-widget-overrides", () => {
- api.modifyClass("component:scrolling-post-stream", {
- pluginId: PLUGIN_ID,
-
- didInsertElement() {
- this._super(...arguments);
-
- const topicId = this?.posts?.firstObject?.topic_id;
- if (topicId) {
- this.messageBus.subscribe(`/topic/${topicId}/reactions`, (data) => {
- this.dirtyKeys.keyDirty(
- `discourse-reactions-counter-${data.post_id}`,
- {
- onRefresh: "reactionsChanged",
- refreshArg: data,
- }
- );
- this._refresh({ id: data.post_id });
- });
- }
- },
- });
-
- api.modifyClass("controller:topic", {
- pluginId: PLUGIN_ID,
-
- unsubscribe() {
- this._super(...arguments);
-
- const topicId = this.model.id;
- topicId && this.messageBus.unsubscribe(`/topic/${topicId}/reactions`);
- },
- });
- });
-}
-
function customizePostMenu(api) {
api.registerValueTransformer(
"post-menu-buttons",
diff --git a/plugins/discourse-reactions/spec/system/reactions_post_list_spec.rb b/plugins/discourse-reactions/spec/system/reactions_post_list_spec.rb
index a60430db258..318e182c7b1 100644
--- a/plugins/discourse-reactions/spec/system/reactions_post_list_spec.rb
+++ b/plugins/discourse-reactions/spec/system/reactions_post_list_spec.rb
@@ -25,64 +25,58 @@ describe "Reactions | Post reaction user list", type: :system do
).toggle!
end
- %w[enabled disabled].each do |value|
- before { SiteSetting.glimmer_post_stream_mode = value }
+ it "shows a list of users who have reacted to a post on hover for likes and each reaction" do
+ sign_in(current_user)
+ visit(post.url)
- context "when glimmer_post_stream_mode=#{value}" do
- it "shows a list of users who have reacted to a post on hover for likes and each reaction" do
- sign_in(current_user)
- visit(post.url)
+ expect(reactions_list).to have_reaction("heart")
+ expect(reactions_list).to have_reaction("clap")
- expect(reactions_list).to have_reaction("heart")
- expect(reactions_list).to have_reaction("clap")
+ reactions_list.hover_over_reaction("heart")
+ expect(reactions_list).to have_users_for_reaction("heart", [user_2.username])
- reactions_list.hover_over_reaction("heart")
- expect(reactions_list).to have_users_for_reaction("heart", [user_2.username])
+ # hover on something else to clear the current hover
+ page.find("#site-logo").hover
- # hover on something else to clear the current hover
- page.find("#site-logo").hover
-
- reactions_list.hover_over_reaction("clap")
- expect(reactions_list).to have_users_for_reaction("clap", [user_3.username])
- end
+ reactions_list.hover_over_reaction("clap")
+ expect(reactions_list).to have_users_for_reaction("clap", [user_3.username])
+ end
- it "shows more info about reactions when clicking" do
- visit(post.url)
- expect(reactions_list).to have_reaction("heart")
- reactions_list.click_reaction("heart")
+ it "shows more info about reactions when clicking" do
+ visit(post.url)
+ expect(reactions_list).to have_reaction("heart")
+ reactions_list.click_reaction("heart")
- expect(page).to have_css(".discourse-reactions-state-panel")
- find(".discourse-reactions-state-panel [data-user-card=#{user_2.username}]").click
+ expect(page).to have_css(".discourse-reactions-state-panel")
+ find(".discourse-reactions-state-panel [data-user-card=#{user_2.username}]").click
- expect(page).to have_css(".user-card.user-card-#{user_2.username}")
- end
+ expect(page).to have_css(".user-card.user-card-#{user_2.username}")
+ end
- context "when the site allows anonymous users to like posts" do
- before do
- SiteSetting.allow_anonymous_mode = true
- SiteSetting.allow_likes_in_anonymous_mode = true
- end
+ context "when the site allows anonymous users to like posts" do
+ before do
+ SiteSetting.allow_anonymous_mode = true
+ SiteSetting.allow_likes_in_anonymous_mode = true
+ end
- it "shows a list of users who have liked a post on hover for unauthenticated users" do
- visit(post.url)
+ it "shows a list of users who have liked a post on hover for unauthenticated users" do
+ visit(post.url)
- expect(reactions_list).to have_reaction("heart")
+ expect(reactions_list).to have_reaction("heart")
- reactions_list.hover_over_reaction("heart")
- expect(reactions_list).to have_users_for_reaction("heart", [user_2.username])
- end
+ reactions_list.hover_over_reaction("heart")
+ expect(reactions_list).to have_users_for_reaction("heart", [user_2.username])
+ end
- it "shows a list of users who have liked a post on hover for authenticated users posting anonymously" do
- anonymous_user = Fabricate(:anonymous)
- sign_in(anonymous_user)
- visit(post.url)
+ it "shows a list of users who have liked a post on hover for authenticated users posting anonymously" do
+ anonymous_user = Fabricate(:anonymous)
+ sign_in(anonymous_user)
+ visit(post.url)
- expect(reactions_list).to have_reaction("heart")
+ expect(reactions_list).to have_reaction("heart")
- reactions_list.hover_over_reaction("heart")
- expect(reactions_list).to have_users_for_reaction("heart", [user_2.username])
- end
- end
+ reactions_list.hover_over_reaction("heart")
+ expect(reactions_list).to have_users_for_reaction("heart", [user_2.username])
end
end
end
diff --git a/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-custom-emoji-test.js b/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-custom-emoji-test.js
index 9eef981063a..acca2338668 100644
--- a/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-custom-emoji-test.js
+++ b/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-custom-emoji-test.js
@@ -3,156 +3,145 @@ import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import ReactionsTopics from "../fixtures/reactions-topic-fixtures";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Reactions - Custom Emoji Picker (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
-
- needs.settings({
- discourse_reactions_enabled: true,
- discourse_reactions_enabled_reactions: "otter|open_mouth|heart",
- discourse_reactions_reaction_for_like: "heart",
- discourse_reactions_like_icon: "heart",
- discourse_reactions_allow_any_emoji: true,
- glimmer_post_stream_mode: postStreamMode,
- });
-
- needs.pretender((server, helper) => {
- const topicPath = "/t/374.json";
- server.get(topicPath, () =>
- helper.response(ReactionsTopics[topicPath])
- );
-
- server.put(
- "/discourse-reactions/posts/:post_id/custom-reaction/:reaction",
- () => helper.response({ success: true })
- );
-
- server.put(
- "/discourse-reactions/posts/:post_id/custom-reactions/:reaction/toggle.json",
- () => helper.response({ success: "OK" })
- );
- });
-
- test("Shows EmojiPicker button when discourse_reactions_allow_any_emoji is enabled", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
- await triggerEvent(
- "#post_2 button.btn-toggle-reaction-like",
- "pointerover",
- { pointerType: "mouse" }
- );
-
- assert
- .dom(".emoji-picker-trigger")
- .exists("EmojiPicker button exists in reactions picker");
- });
-
- test("Clicking EmojiPicker prevents reactions picker from collapsing", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
- await triggerEvent(
- "#post_2 button.btn-toggle-reaction-like",
- "pointerover",
- { pointerType: "mouse" }
- );
-
- await click(".emoji-picker-trigger");
-
- await triggerEvent("#site-logo", "pointerover", {
- pointerType: "mouse",
- });
- await new Promise((resolve) => setTimeout(resolve, 1000));
- assert
- .dom(".discourse-reactions-picker.is-expanded")
- .exists(
- "Reactions picker remains expanded even if mouse moving outside when EmojiPicker is open"
- );
-
- await click("#post_4 .post-avatar");
-
- assert
- .dom(".discourse-reactions-picker.is-expanded")
- .exists(
- "Reactions picker remains expanded even if mouse clicking outside when EmojiPicker is open"
- );
- });
-
- test("Selected custom emoji is added to reactions when discourse_reactions_allow_any_emoji is enabled", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
- await triggerEvent(
- "#post_2 button.btn-toggle-reaction-like",
- "pointerover",
- { pointerType: "mouse" }
- );
- await click(".emoji-picker-trigger");
- await click('img.emoji[alt="grinning"]');
- // Assert the reactions list emoji on the left
- assert
- .dom('#post_2 .discourse-reactions-list-emoji img[alt="grinning"]')
- .exists("Grinning emoji exists in reactions list");
-
- // Assert the reaction button emoji
- assert
- .dom('#post_2 .btn.reaction-button img[alt=":grinning"]')
- .exists("Grinning emoji exists in reaction button");
- });
- }
- );
-
- acceptance(
- `Discourse Reactions - Custom Emoji Picker Disabled (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
-
- needs.settings({
- discourse_reactions_enabled: true,
- discourse_reactions_enabled_reactions: "otter|open_mouth|heart",
- discourse_reactions_reaction_for_like: "heart",
- discourse_reactions_like_icon: "heart",
- discourse_reactions_allow_any_emoji: false,
- glimmer_post_stream_mode: postStreamMode,
- });
-
- needs.pretender((server, helper) => {
- const topicPath = "/t/374.json";
- server.get(topicPath, () =>
- helper.response(ReactionsTopics[topicPath])
- );
-
- server.put(
- "/discourse-reactions/posts/:post_id/custom-reactions/:reaction/toggle.json",
- () => helper.response({ success: "OK" })
- );
- });
-
- test("Does not show EmojiPicker button when discourse_reactions_allow_any_emoji is disabled", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
- await triggerEvent(
- "#post_2 button.btn-toggle-reaction-like",
- "pointerover",
- { pointerType: "mouse" }
- );
+acceptance(`Discourse Reactions - Custom Emoji Picker`, function (needs) {
+ needs.user();
+
+ needs.settings({
+ discourse_reactions_enabled: true,
+ discourse_reactions_enabled_reactions: "otter|open_mouth|heart",
+ discourse_reactions_reaction_for_like: "heart",
+ discourse_reactions_like_icon: "heart",
+ discourse_reactions_allow_any_emoji: true,
+ });
+
+ needs.pretender((server, helper) => {
+ const topicPath = "/t/374.json";
+ server.get(topicPath, () => helper.response(ReactionsTopics[topicPath]));
+
+ server.put(
+ "/discourse-reactions/posts/:post_id/custom-reaction/:reaction",
+ () => helper.response({ success: true })
+ );
+
+ server.put(
+ "/discourse-reactions/posts/:post_id/custom-reactions/:reaction/toggle.json",
+ () => helper.response({ success: "OK" })
+ );
+ });
+
+ test("Shows EmojiPicker button when discourse_reactions_allow_any_emoji is enabled", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+ await triggerEvent(
+ "#post_2 button.btn-toggle-reaction-like",
+ "pointerover",
+ { pointerType: "mouse" }
+ );
+
+ assert
+ .dom(".emoji-picker-trigger")
+ .exists("EmojiPicker button exists in reactions picker");
+ });
+
+ test("Clicking EmojiPicker prevents reactions picker from collapsing", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+ await triggerEvent(
+ "#post_2 button.btn-toggle-reaction-like",
+ "pointerover",
+ { pointerType: "mouse" }
+ );
+
+ await click(".emoji-picker-trigger");
+
+ await triggerEvent("#site-logo", "pointerover", {
+ pointerType: "mouse",
+ });
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ assert
+ .dom(".discourse-reactions-picker.is-expanded")
+ .exists(
+ "Reactions picker remains expanded even if mouse moving outside when EmojiPicker is open"
+ );
+
+ await click("#post_4 .post-avatar");
+
+ assert
+ .dom(".discourse-reactions-picker.is-expanded")
+ .exists(
+ "Reactions picker remains expanded even if mouse clicking outside when EmojiPicker is open"
+ );
+ });
+
+ test("Selected custom emoji is added to reactions when discourse_reactions_allow_any_emoji is enabled", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+ await triggerEvent(
+ "#post_2 button.btn-toggle-reaction-like",
+ "pointerover",
+ { pointerType: "mouse" }
+ );
+ await click(".emoji-picker-trigger");
+ await click('img.emoji[alt="grinning"]');
+ // Assert the reactions list emoji on the left
+ assert
+ .dom('#post_2 .discourse-reactions-list-emoji img[alt="grinning"]')
+ .exists("Grinning emoji exists in reactions list");
+
+ // Assert the reaction button emoji
+ assert
+ .dom('#post_2 .btn.reaction-button img[alt=":grinning"]')
+ .exists("Grinning emoji exists in reaction button");
+ });
+});
- assert
- .dom(".emoji-picker-trigger")
- .doesNotExist(
- "EmojiPicker button does not exist when setting is disabled"
- );
- });
-
- test("Reactions picker grid only counts enabled reactions when EmojiPicker is disabled", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
- await triggerEvent(
- "#post_2 button.btn-toggle-reaction-like",
- "pointerover",
- { pointerType: "mouse" }
+acceptance(
+ `Discourse Reactions - Custom Emoji Picker Disabled`,
+ function (needs) {
+ needs.user();
+
+ needs.settings({
+ discourse_reactions_enabled: true,
+ discourse_reactions_enabled_reactions: "otter|open_mouth|heart",
+ discourse_reactions_reaction_for_like: "heart",
+ discourse_reactions_like_icon: "heart",
+ discourse_reactions_allow_any_emoji: false,
+ });
+
+ needs.pretender((server, helper) => {
+ const topicPath = "/t/374.json";
+ server.get(topicPath, () => helper.response(ReactionsTopics[topicPath]));
+
+ server.put(
+ "/discourse-reactions/posts/:post_id/custom-reactions/:reaction/toggle.json",
+ () => helper.response({ success: "OK" })
+ );
+ });
+
+ test("Does not show EmojiPicker button when discourse_reactions_allow_any_emoji is disabled", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+ await triggerEvent(
+ "#post_2 button.btn-toggle-reaction-like",
+ "pointerover",
+ { pointerType: "mouse" }
+ );
+
+ assert
+ .dom(".emoji-picker-trigger")
+ .doesNotExist(
+ "EmojiPicker button does not exist when setting is disabled"
);
-
- // With 3 enabled reactions and no emoji picker button = 3 total
- assert
- .dom(".discourse-reactions-picker-container")
- .hasClass("col-3", "Grid has 3 columns without EmojiPicker button");
- });
- }
- );
-});
+ });
+
+ test("Reactions picker grid only counts enabled reactions when EmojiPicker is disabled", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+ await triggerEvent(
+ "#post_2 button.btn-toggle-reaction-like",
+ "pointerover",
+ { pointerType: "mouse" }
+ );
+
+ // With 3 enabled reactions and no emoji picker button = 3 total
+ assert
+ .dom(".discourse-reactions-picker-container")
+ .hasClass("col-3", "Grid has 3 columns without EmojiPicker button");
+ });
+ }
+);
diff --git a/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-disabled-test.js b/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-disabled-test.js
index 471b5134e73..ad6efa3958f 100644
--- a/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-disabled-test.js
+++ b/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-disabled-test.js
@@ -3,31 +3,23 @@ import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import ReactionsTopics from "../fixtures/reactions-topic-fixtures";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Reactions - Disabled (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
+acceptance(`Discourse Reactions - Disabled`, function (needs) {
+ needs.user();
- needs.settings({
- discourse_reactions_enabled: false,
- glimmer_post_stream_mode: postStreamMode,
- });
+ needs.settings({
+ discourse_reactions_enabled: false,
+ });
- needs.pretender((server, helper) => {
- const topicPath = "/t/374.json";
- server.get(topicPath, () =>
- helper.response(ReactionsTopics[topicPath])
- );
- });
+ needs.pretender((server, helper) => {
+ const topicPath = "/t/374.json";
+ server.get(topicPath, () => helper.response(ReactionsTopics[topicPath]));
+ });
- test("Does not show reactions controls", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
+ test("Does not show reactions controls", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
- assert
- .dom(".discourse-reactions-actions")
- .doesNotExist("reactions controls are not shown");
- });
- }
- );
+ assert
+ .dom(".discourse-reactions-actions")
+ .doesNotExist("reactions controls are not shown");
+ });
});
diff --git a/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-enabled-test.js b/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-enabled-test.js
index e794dbc6b0c..a85e62764a2 100644
--- a/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-enabled-test.js
+++ b/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-enabled-test.js
@@ -3,61 +3,47 @@ import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import ReactionsTopics from "../fixtures/reactions-topic-fixtures";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Reactions - Enabled (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
-
- needs.settings({
- discourse_reactions_enabled: true,
- discourse_reactions_enabled_reactions: "otter|open_mouth",
- discourse_reactions_reaction_for_like: "heart",
- discourse_reactions_like_icon: "heart",
- glimmer_post_stream_mode: postStreamMode,
- });
-
- needs.pretender((server, helper) => {
- const topicPath = "/t/374.json";
- server.get(topicPath, () =>
- helper.response(ReactionsTopics[topicPath])
- );
- });
-
- test("It shows reactions controls", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
-
- assert
- .dom(".discourse-reactions-actions")
- .exists("reaction controls are available");
- });
- }
- );
-
- acceptance(
- `Discourse Reactions - Enabled | Anonymous user (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- discourse_reactions_enabled: true,
- discourse_reactions_enabled_reactions: "otter|open_mouth",
- discourse_reactions_reaction_for_like: "heart",
- discourse_reactions_like_icon: "heart",
- glimmer_post_stream_mode: postStreamMode,
- });
-
- needs.pretender((server, helper) => {
- const topicPath = "/t/374.json";
- server.get(topicPath, () =>
- helper.response(ReactionsTopics[topicPath])
- );
- });
-
- test("It shows reactions controls", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
- await click(".actions button.btn-toggle-reaction-like");
-
- assert.dom("#login-form").exists("login form was displayed");
- });
- }
- );
+acceptance(`Discourse Reactions - Enabled`, function (needs) {
+ needs.user();
+
+ needs.settings({
+ discourse_reactions_enabled: true,
+ discourse_reactions_enabled_reactions: "otter|open_mouth",
+ discourse_reactions_reaction_for_like: "heart",
+ discourse_reactions_like_icon: "heart",
+ });
+
+ needs.pretender((server, helper) => {
+ const topicPath = "/t/374.json";
+ server.get(topicPath, () => helper.response(ReactionsTopics[topicPath]));
+ });
+
+ test("It shows reactions controls", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+
+ assert
+ .dom(".discourse-reactions-actions")
+ .exists("reaction controls are available");
+ });
+});
+
+acceptance(`Discourse Reactions - Enabled | Anonymous user`, function (needs) {
+ needs.settings({
+ discourse_reactions_enabled: true,
+ discourse_reactions_enabled_reactions: "otter|open_mouth",
+ discourse_reactions_reaction_for_like: "heart",
+ discourse_reactions_like_icon: "heart",
+ });
+
+ needs.pretender((server, helper) => {
+ const topicPath = "/t/374.json";
+ server.get(topicPath, () => helper.response(ReactionsTopics[topicPath]));
+ });
+
+ test("It shows reactions controls", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+ await click(".actions button.btn-toggle-reaction-like");
+
+ assert.dom("#login-form").exists("login form was displayed");
+ });
});
diff --git a/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-post-test.js b/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-post-test.js
index 4a26976988f..7d0f498113b 100644
--- a/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-post-test.js
+++ b/plugins/discourse-reactions/test/javascripts/acceptance/discourse-reactions-post-test.js
@@ -3,100 +3,92 @@ import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import ReactionsTopics from "../fixtures/reactions-topic-fixtures";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Reactions - Post (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
-
- needs.settings({
- discourse_reactions_enabled: true,
- discourse_reactions_enabled_reactions: "otter|open_mouth",
- discourse_reactions_reaction_for_like: "heart",
- discourse_reactions_like_icon: "heart",
- glimmer_post_stream_mode: postStreamMode,
- });
-
- needs.pretender((server, helper) => {
- const topicPath = "/t/374.json";
- server.get(topicPath, () =>
- helper.response(ReactionsTopics[topicPath])
- );
- });
-
- test("Reactions count", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
-
- assert
- .dom("#post_1 .discourse-reactions-counter .reactions-counter")
- .hasText("209", "displays the correct count");
- });
-
- test("Other user post", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
-
- assert
- .dom("#post_2 .discourse-reactions-reaction-button")
- .exists("displays the reaction button");
- });
-
- test("Post is yours", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
-
- assert
- .dom("#post_1 .discourse-reactions-reaction-button")
- .doesNotExist("does not display the reaction button");
- });
-
- test("Post has only likes (no reactions)", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
-
- assert
- .dom("#post_3 .discourse-reactions-double-button")
- .exists("displays the reaction count beside the reaction button");
- });
-
- test("Post has likes and reactions", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
-
- assert
- .dom("#post_1 .discourse-reactions-double-button")
- .doesNotExist(
- "does not display the reaction count beside the reaction button"
- );
- });
-
- test("Current user has no reaction on post and can toggle", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
-
- assert
- .dom("#post_2 .discourse-reactions-actions.can-toggle-reaction")
- .exists("allows to toggle the reaction");
- });
-
- test("Current user has no reaction on post and can toggle", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
-
- assert
- .dom("#post_2 .discourse-reactions-actions.can-toggle-reaction")
- .exists("allows to toggle the reaction");
- });
-
- test("Current user can undo on post and can toggle", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
-
- assert
- .dom("#post_3 .discourse-reactions-actions.can-toggle-reaction")
- .exists("allows to toggle the reaction");
- });
-
- test("Current user can't toggle", async function (assert) {
- await visit("/t/topic_with_reactions_and_likes/374");
-
- assert
- .dom("#post_1 .discourse-reactions-actions.can-toggle-reaction")
- .doesNotExist("doesn’t allow to toggle the reaction");
- });
- }
- );
+acceptance(`Discourse Reactions - Post`, function (needs) {
+ needs.user();
+
+ needs.settings({
+ discourse_reactions_enabled: true,
+ discourse_reactions_enabled_reactions: "otter|open_mouth",
+ discourse_reactions_reaction_for_like: "heart",
+ discourse_reactions_like_icon: "heart",
+ });
+
+ needs.pretender((server, helper) => {
+ const topicPath = "/t/374.json";
+ server.get(topicPath, () => helper.response(ReactionsTopics[topicPath]));
+ });
+
+ test("Reactions count", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+
+ assert
+ .dom("#post_1 .discourse-reactions-counter .reactions-counter")
+ .hasText("209", "displays the correct count");
+ });
+
+ test("Other user post", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+
+ assert
+ .dom("#post_2 .discourse-reactions-reaction-button")
+ .exists("displays the reaction button");
+ });
+
+ test("Post is yours", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+
+ assert
+ .dom("#post_1 .discourse-reactions-reaction-button")
+ .doesNotExist("does not display the reaction button");
+ });
+
+ test("Post has only likes (no reactions)", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+
+ assert
+ .dom("#post_3 .discourse-reactions-double-button")
+ .exists("displays the reaction count beside the reaction button");
+ });
+
+ test("Post has likes and reactions", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+
+ assert
+ .dom("#post_1 .discourse-reactions-double-button")
+ .doesNotExist(
+ "does not display the reaction count beside the reaction button"
+ );
+ });
+
+ test("Current user has no reaction on post and can toggle", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+
+ assert
+ .dom("#post_2 .discourse-reactions-actions.can-toggle-reaction")
+ .exists("allows to toggle the reaction");
+ });
+
+ test("Current user has no reaction on post and can toggle", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+
+ assert
+ .dom("#post_2 .discourse-reactions-actions.can-toggle-reaction")
+ .exists("allows to toggle the reaction");
+ });
+
+ test("Current user can undo on post and can toggle", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+
+ assert
+ .dom("#post_3 .discourse-reactions-actions.can-toggle-reaction")
+ .exists("allows to toggle the reaction");
+ });
+
+ test("Current user can't toggle", async function (assert) {
+ await visit("/t/topic_with_reactions_and_likes/374");
+
+ assert
+ .dom("#post_1 .discourse-reactions-actions.can-toggle-reaction")
+ .doesNotExist("doesn’t allow to toggle the reaction");
+ });
});
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjs
index e5d02131242..782cd1006dc 100644
--- a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjs
+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjs
@@ -29,11 +29,6 @@ export default class SolvedAcceptAnswerButton extends Component {
await acceptPost(post, this.currentUser);
this.appEvents.trigger("discourse-solved:solution-toggled", post);
-
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- post.get("topic.postStream.posts").forEach((p) => {
- this.appEvents.trigger("post-stream:refresh", { id: p.id });
- });
} catch (e) {
popupAjaxError(e);
} finally {
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjs
index 8b2a3de55ad..219bb5af48d 100644
--- a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjs
+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjs
@@ -27,11 +27,6 @@ export default class SolvedUnacceptAnswerButton extends Component {
await unacceptPost(post);
this.appEvents.trigger("discourse-solved:solution-toggled", post);
-
- // TODO (glimmer-post-stream) the Glimmer Post Stream does not listen to this event
- post.get("topic.postStream.posts").forEach((p) => {
- this.appEvents.trigger("post-stream:refresh", { id: p.id });
- });
} catch (e) {
popupAjaxError(e);
} finally {
diff --git a/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjs b/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjs
index d144dc107bd..be566b168ed 100644
--- a/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjs
+++ b/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjs
@@ -1,8 +1,6 @@
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
-import { withSilencedDeprecations } from "discourse/lib/deprecated";
import { withPluginApi } from "discourse/lib/plugin-api";
-import RenderGlimmer from "discourse/widgets/render-glimmer";
import { i18n } from "discourse-i18n";
import SolvedAcceptAnswerButton from "../components/solved-accept-answer-button";
import SolvedAcceptedAnswer from "../components/solved-accepted-answer";
@@ -77,25 +75,6 @@ function customizePost(api) {
</template>
}
);
-
- withSilencedDeprecations("discourse.post-stream-widget-overrides", () =>
- customizeWidgetPost(api)
- );
-}
-
-function customizeWidgetPost(api) {
- api.decorateWidget("post-contents:after-cooked", (helper) => {
- let post = helper.getModel();
-
- if (helper.attrs.post_number === 1 && post?.topic?.accepted_answer) {
- return new RenderGlimmer(
- helper.widget,
- "div",
- <template><SolvedAcceptedAnswer @post={{@data.post}} /></template>,
- { post }
- );
- }
- });
}
function customizePostMenu(api) {
diff --git a/plugins/discourse-solved/spec/system/solved_spec.rb b/plugins/discourse-solved/spec/system/solved_spec.rb
index 27ad5bcecee..a7be0d739a5 100644
--- a/plugins/discourse-solved/spec/system/solved_spec.rb
+++ b/plugins/discourse-solved/spec/system/solved_spec.rb
@@ -24,36 +24,30 @@ describe "Solved", type: :system do
SiteSetting.display_name_on_posts = true
end
- %w[enabled disabled].each do |value|
- context "when glimmer_post_stream_mode=#{value}" do
- before { SiteSetting.glimmer_post_stream_mode = value }
-
- it "accepts post as solution and shows in OP" do
- sign_in(accepter)
- visit_solver_post
-
- verify_solution_unaccepted_state
- accept_solution
- verify_solution_accepted_state
- verify_solution_quote_content
- verify_solver_and_accepter_info
- expand_solution_quote
- end
-
- it "accepts and unaccepts post as solution" do
- sign_in(accepter)
- visit_solver_post
-
- verify_solution_unaccepted_state
- accept_solution
- verify_solution_accepted_state
- verify_solution_info_present
-
- unaccept_solution
- verify_solution_unaccepted_state
- verify_solution_info_absent
- end
- end
+ it "accepts post as solution and shows in OP" do
+ sign_in(accepter)
+ visit_solver_post
+
+ verify_solution_unaccepted_state
+ accept_solution
+ verify_solution_accepted_state
+ verify_solution_quote_content
+ verify_solver_and_accepter_info
+ expand_solution_quote
+ end
+
+ it "accepts and unaccepts post as solution" do
+ sign_in(accepter)
+ visit_solver_post
+
+ verify_solution_unaccepted_state
+ accept_solution
+ verify_solution_accepted_state
+ verify_solution_info_present
+
+ unaccept_solution
+ verify_solution_unaccepted_state
+ verify_solution_info_absent
end
it "shows the solved post in user activity at /my/activity/solved" do
diff --git a/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-test.js b/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-test.js
index 41e2239e9d2..f0b359f7d8e 100644
--- a/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-test.js
+++ b/plugins/discourse-solved/test/javascripts/acceptance/discourse-solved-test.js
@@ -8,47 +8,39 @@ import pretender, {
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import { postStreamWithAcceptedAnswerExcerpt } from "../helpers/discourse-solved-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Discourse Solved Plugin (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.settings({
- glimmer_post_stream_mode: postStreamMode,
- });
- needs.user();
-
- test("A topic with an accepted answer shows an excerpt of the answer, if provided", async function (assert) {
- pretender.get("/t/11.json", () =>
- response(postStreamWithAcceptedAnswerExcerpt("this is an excerpt"))
- );
-
- pretender.get("/t/12.json", () =>
- response(postStreamWithAcceptedAnswerExcerpt(null))
- );
-
- await visit("/t/with-excerpt/11");
- assert.dom(".quote blockquote").hasText("this is an excerpt");
-
- await visit("/t/without-excerpt/12");
-
- assert.dom(".quote blockquote").hasNoText();
- assert.dom(".quote.title-only .title").exists();
- });
-
- test("Full page search displays solved status", async function (assert) {
- pretender.get("/search", () => {
- const fixtures = cloneJSON(fixturesByUrl["/search.json"]);
- fixtures.topics[0].has_accepted_answer = true;
- return response(fixtures);
- });
-
- await visit("/search");
- await fillIn(".search-query", "discourse");
- await click(".search-cta");
-
- assert.dom(".fps-topic").exists({ count: 1 }, "has one post");
- assert.dom(".topic-statuses .solved").exists("shows the right icon");
- });
- }
- );
+acceptance(`Discourse Solved Plugin`, function (needs) {
+ needs.user();
+
+ test("A topic with an accepted answer shows an excerpt of the answer, if provided", async function (assert) {
+ pretender.get("/t/11.json", () =>
+ response(postStreamWithAcceptedAnswerExcerpt("this is an excerpt"))
+ );
+
+ pretender.get("/t/12.json", () =>
+ response(postStreamWithAcceptedAnswerExcerpt(null))
+ );
+
+ await visit("/t/with-excerpt/11");
+ assert.dom(".quote blockquote").hasText("this is an excerpt");
+
+ await visit("/t/without-excerpt/12");
+
+ assert.dom(".quote blockquote").hasNoText();
+ assert.dom(".quote.title-only .title").exists();
+ });
+
+ test("Full page search displays solved status", async function (assert) {
+ pretender.get("/search", () => {
+ const fixtures = cloneJSON(fixturesByUrl["/search.json"]);
+ fixtures.topics[0].has_accepted_answer = true;
+ return response(fixtures);
+ });
+
+ await visit("/search");
+ await fillIn(".search-query", "discourse");
+ await click(".search-cta");
+
+ assert.dom(".fps-topic").exists({ count: 1 }, "has one post");
+ assert.dom(".topic-statuses .solved").exists("shows the right icon");
+ });
});
diff --git a/plugins/discourse-user-notes/assets/javascripts/discourse/initializers/enable-user-notes.gjs b/plugins/discourse-user-notes/assets/javascripts/discourse/initializers/enable-user-notes.gjs
index 09b437be99c..793ad359845 100644
--- a/plugins/discourse-user-notes/assets/javascripts/discourse/initializers/enable-user-notes.gjs
+++ b/plugins/discourse-user-notes/assets/javascripts/discourse/initializers/enable-user-notes.gjs
@@ -1,8 +1,6 @@
import Component from "@glimmer/component";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import { withSilencedDeprecations } from "discourse/lib/deprecated";
-import { iconNode } from "discourse/lib/icon-library";
import { withPluginApi } from "discourse/lib/plugin-api";
import { applyValueTransformer } from "discourse/lib/transformer";
import PostMetadataUserNotes from "../components/post-metadata-user-notes";
@@ -81,97 +79,6 @@ function customizePost(api, container) {
DesktopUserNotesIcon
);
}
-
- withSilencedDeprecations("discourse.post-stream-widget-overrides", () =>
- customizeWidgetPost(api)
- );
-}
-
-/**
- * Customizes the post widget to display user notes
- *
- * @param {Object} api - Plugin API instance
- */
-function customizeWidgetPost(api) {
- // Handler for showing user notes modal
- function widgetShowUserNotes() {
- showUserNotes(
- this.store,
- this.attrs.user_id,
- (count) => {
- this.sendWidgetAction("refreshUserNotes", count);
- },
- {
- postId: this.attrs.id,
- }
- );
- }
-
- // Update post when notes are changed
- api.attachWidgetAction("post", "refreshUserNotes", function (count) {
- updatePostUserNotesCount(this.model, count);
- });
-
- // Helper to attach notes icon if user has notes
- const attachUserNotesIconIfPresent = (dec) => {
- const post = dec.getModel();
- if (post?.user_custom_fields?.user_notes_count > 0) {
- return dec.attach("user-notes-icon");
- }
- };
-
- // Add notes icon to poster name
-
- // place the icon before the poster name on mobile
- api.decorateWidget(`poster-name:before`, (dec) => {
- if (
- api.container.lookup("service:site").desktopView ||
- dec.widget.settings.hideNotes
- ) {
- return;
- }
-
- return attachUserNotesIconIfPresent(dec);
- });
-
- // place the icon after the poster name on desktop
- api.decorateWidget(`poster-name:after`, (dec) => {
- if (
- api.container.lookup("service:site").mobileView ||
- dec.widget.settings.hideNotes
- ) {
- return;
- }
-
- return attachUserNotesIconIfPresent(dec);
- });
-
- // Add notes icon after avatar
- api.decorateWidget(`post-avatar:after`, (dec) => {
- if (!dec.widget.settings.showNotes) {
- return;
- }
-
- return attachUserNotesIconIfPresent(dec);
- });
-
- api.attachWidgetAction("post", "showUserNotes", widgetShowUserNotes);
-
- // Create the user notes icon widget
- api.createWidget("user-notes-icon", {
- services: ["site-settings"],
-
- tagName: "span.user-notes-icon",
- click: widgetShowUserNotes,
-
- html() {
- if (this.siteSettings.enable_emoji) {
- return this.attach("emoji", { name: "memo" });
- } else {
- return iconNode("pen-to-square");
- }
- },
- });
}
/**
@@ -181,7 +88,6 @@ function customizeWidgetPost(api) {
* @param {Object} container - Container instance
*/
function customizePostMenu(api, container) {
- const appEvents = container.lookup("service:app-events");
const store = container.lookup("service:store");
api.addPostAdminMenuButton((attrs) => {
@@ -194,9 +100,6 @@ function customizePostMenu(api, container) {
attrs.user_id,
(count) => {
updatePostUserNotesCount(post, count);
- appEvents.trigger("post-stream:refresh", {
- id: post.id,
- });
},
{ postId: attrs.id }
);
diff --git a/plugins/poll/assets/javascripts/discourse/initializers/extend-for-poll.gjs b/plugins/poll/assets/javascripts/discourse/initializers/extend-for-poll.gjs
index 36c72009a86..40388c1666d 100644
--- a/plugins/poll/assets/javascripts/discourse/initializers/extend-for-poll.gjs
+++ b/plugins/poll/assets/javascripts/discourse/initializers/extend-for-poll.gjs
@@ -25,7 +25,6 @@ function attachPolls(elem, helper) {
const quotedId = pollNode.closest(".expanded-quote")?.dataset.postId;
- // TODO (glimmer-post-stream) the condition below is probably not needed after the widget are gone
if (quotedId && post.quoted[quotedId]) {
pollPost = EmberObject.create(post.quoted[quotedId]);
poll = new TrackedObject(pollPost.polls.find((p) => p.name === pollName));
diff --git a/plugins/poll/test/javascripts/acceptance/poll-in-reply-history-test.js b/plugins/poll/test/javascripts/acceptance/poll-in-reply-history-test.js
index 04085303c81..72d2e51ab21 100644
--- a/plugins/poll/test/javascripts/acceptance/poll-in-reply-history-test.js
+++ b/plugins/poll/test/javascripts/acceptance/poll-in-reply-history-test.js
@@ -2,392 +2,36 @@ import { click, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Poll in a post reply history (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- poll_enabled: true,
- glimmer_post_stream_mode: postStreamMode,
- });
+acceptance(`Poll in a post reply history`, function (needs) {
+ needs.user();
+ needs.settings({
+ poll_enabled: true,
+ });
- needs.pretender((server, helper) => {
- server.get("/t/topic_with_poll_in_post_reply_history.json", () => {
- return helper.response({
- post_stream: {
- posts: [
- {
- id: 82,
- name: null,
- username: "admin1",
- avatar_template:
- "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
- created_at: "2021-01-25T13:08:27.385Z",
- cooked: "<p>A reply to the poll.</p>",
- post_number: 4,
- post_type: 1,
- updated_at: "2021-01-25T13:08:27.385Z",
- reply_count: 0,
- reply_to_post_number: 2,
- quote_count: 0,
- incoming_link_count: 0,
- reads: 1,
- readers_count: 0,
- score: 0.2,
- yours: true,
- topic_id: 25,
- topic_slug: "topic-with-a-poll-in-a-post-reply-history",
- display_username: null,
- primary_group_name: null,
- flair_url: null,
- flair_bg_color: null,
- flair_color: null,
- version: 1,
- can_edit: true,
- can_delete: true,
- can_recover: false,
- can_wiki: true,
- read: true,
- user_title: null,
- reply_to_user: {
- username: "admin1",
- avatar_template:
- "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
- },
- bookmarked: false,
- bookmarks: [],
- actions_summary: [
- {
- id: 3,
- can_act: true,
- },
- {
- id: 4,
- can_act: true,
- },
- {
- id: 8,
- can_act: true,
- },
- {
- id: 7,
- can_act: true,
- },
- ],
- moderator: false,
- admin: true,
- staff: true,
- user_id: 3,
- hidden: false,
- trust_level: 1,
- deleted_at: null,
- user_deleted: false,
- edit_reason: null,
- can_view_edit_history: true,
- wiki: false,
- reviewable_id: 0,
- reviewable_score_count: 0,
- reviewable_score_pending_count: 0,
- },
- ],
- stream: [82],
- },
- timeline_lookup: [[1, 0]],
- suggested_topics: [
- {
- id: 7,
- title: "Welcome to Discourse",
- fancy_title: "Welcome to Discourse",
- slug: "welcome-to-discourse",
- posts_count: 1,
- reply_count: 0,
- highest_post_number: 1,
- image_url: null,
- created_at: "2021-01-07T15:36:44.707Z",
- last_posted_at: "2021-01-07T15:36:44.750Z",
- bumped: true,
- bumped_at: "2021-01-07T15:36:44.750Z",
- archetype: "regular",
- unseen: false,
- pinned: true,
- unpinned: null,
- excerpt:
- "The first paragraph of this pinned topic will be visible as a welcome message to all new visitors on your homepage. It’s important! Edit this into a brief description of your community: Who is it for? What can they fi&hellip;",
- visible: true,
- closed: false,
- archived: false,
- bookmarked: null,
- liked: null,
- like_count: 0,
- views: 1,
- category_id: 1,
- featured_link: null,
- posters: [
- {
- extras: "latest single",
- description: "Original Poster, Most Recent Poster",
- user: {
- id: -1,
- username: "system",
- name: "system",
- avatar_template:
- "http://localhost:3000/images/discourse-logo-sketch-small.png",
- },
- },
- ],
- },
- {
- id: 20,
- title: "Polls testing. Just one poll in the comment",
- fancy_title: "Polls testing. Just one poll in the comment",
- slug: "polls-testing-just-one-poll-in-the-comment",
- posts_count: 3,
- reply_count: 1,
- highest_post_number: 3,
- image_url: null,
- created_at: "2021-01-21T09:21:35.102Z",
- last_posted_at: "2021-01-22T09:35:33.543Z",
- bumped: true,
- bumped_at: "2021-01-22T09:35:33.543Z",
- archetype: "regular",
- unseen: false,
- last_read_post_number: 3,
- unread_posts: 0,
- pinned: false,
- unpinned: null,
- visible: true,
- closed: false,
- archived: false,
- notification_level: 2,
- bookmarked: false,
- bookmarks: [],
- liked: false,
- like_count: 0,
- views: 3,
- category_id: 1,
- featured_link: null,
- posters: [
- {
- extras: null,
- description: "Original Poster",
- user: {
- id: 2,
- username: "andrey1",
- name: "andrey1",
- avatar_template:
- "/letter_avatar_proxy/v4/letter/a/c0e974/{size}.png",
- },
- },
- {
- extras: "latest",
- description: "Most Recent Poster",
- user: {
- id: 3,
- username: "admin1",
- name: null,
- avatar_template:
- "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
- },
- },
- ],
- },
- {
- id: 22,
- title: "Polls testing. The whole test",
- fancy_title: "Polls testing. The whole test",
- slug: "polls-testing-the-whole-test",
- posts_count: 12,
- reply_count: 8,
- highest_post_number: 12,
- image_url: null,
- created_at: "2021-01-21T09:55:20.135Z",
- last_posted_at: "2021-01-22T11:59:31.561Z",
- bumped: true,
- bumped_at: "2021-01-22T11:59:31.561Z",
- archetype: "regular",
- unseen: false,
- last_read_post_number: 12,
- unread_posts: 0,
- pinned: false,
- unpinned: null,
- visible: true,
- closed: false,
- archived: false,
- notification_level: 2,
- bookmarked: false,
- bookmarks: [],
- liked: false,
- like_count: 0,
- views: 4,
- category_id: 1,
- featured_link: null,
- posters: [
- {
- extras: null,
- description: "Original Poster",
- user: {
- id: 2,
- username: "andrey1",
- name: "andrey1",
- avatar_template:
- "/letter_avatar_proxy/v4/letter/a/c0e974/{size}.png",
- },
- },
- {
- extras: "latest",
- description: "Most Recent Poster",
- user: {
- id: 3,
- username: "admin1",
- name: null,
- avatar_template:
- "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
- },
- },
- ],
- },
- ],
- id: 25,
- title: "Topic with a poll in a post reply history",
- fancy_title: "Topic with a poll in a post reply history",
- posts_count: 4,
- created_at: "2021-01-25T13:07:31.670Z",
- views: 2,
- reply_count: 2,
- like_count: 0,
- last_posted_at: "2021-01-25T13:08:27.385Z",
- visible: true,
- closed: false,
- archived: false,
- has_summary: false,
- archetype: "regular",
- slug: "topic-with-a-poll-in-a-post-reply-history",
- category_id: 1,
- word_count: 25,
- deleted_at: null,
- user_id: 3,
- featured_link: null,
- pinned_globally: false,
- pinned_at: null,
- pinned_until: null,
- image_url: null,
- slow_mode_seconds: 0,
- draft: null,
- draft_key: "topic_25",
- draft_sequence: 4,
- posted: true,
- unpinned: null,
- pinned: false,
- current_post_number: 4,
- highest_post_number: 4,
- last_read_post_number: 4,
- last_read_post_id: 82,
- deleted_by: null,
- has_deleted: false,
- actions_summary: [
- {
- id: 4,
- count: 0,
- hidden: false,
- can_act: true,
- },
- {
- id: 8,
- count: 0,
- hidden: false,
- can_act: true,
- },
- {
- id: 7,
- count: 0,
- hidden: false,
- can_act: true,
- },
- ],
- chunk_size: 20,
- bookmarked: false,
- bookmarks: [],
- topic_timer: null,
- message_bus_last_id: 4,
- participant_count: 1,
- show_read_indicator: false,
- thumbnails: null,
- details: {
- can_edit: true,
- notification_level: 3,
- notifications_reason_id: 1,
- can_move_posts: true,
- can_delete: true,
- can_remove_allowed_users: true,
- can_invite_to: true,
- can_invite_via_email: true,
- can_create_post: true,
- can_reply_as_new_topic: true,
- can_flag_topic: true,
- can_convert_topic: true,
- can_review_topic: true,
- can_close_topic: true,
- can_archive_topic: true,
- can_split_merge_topic: true,
- can_edit_staff_notes: true,
- can_toggle_topic_visibility: true,
- can_moderate_category: true,
- can_remove_self_id: 3,
- participants: [
- {
- id: 3,
- username: "admin1",
- name: null,
- avatar_template:
- "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
- post_count: 4,
- primary_group_name: null,
- flair_url: null,
- flair_color: null,
- flair_bg_color: null,
- },
- ],
- created_by: {
- id: 3,
- username: "admin1",
- name: null,
- avatar_template:
- "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
- },
- last_poster: {
- id: 3,
- username: "admin1",
- name: null,
- avatar_template:
- "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
- },
- },
- });
- });
-
- server.get("/posts/82/reply-history", () => {
- return helper.response([
+ needs.pretender((server, helper) => {
+ server.get("/t/topic_with_poll_in_post_reply_history.json", () => {
+ return helper.response({
+ post_stream: {
+ posts: [
{
- id: 80,
+ id: 82,
name: null,
username: "admin1",
avatar_template:
"/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
- created_at: "2021-01-25T13:07:58.995Z",
- cooked:
- '<p>The poll:</p>\n<div class="poll" data-poll-status="open" data-poll-name="poll">\n<div>\n<div class="poll-container">\n<ul>\n<li data-poll-option-id="5b8ee5ba2a43e258f93dbef9264bf1ad">Option A</li>\n<li data-poll-option-id="6872645f5d8ef2311883617a3a7d381b">Option B</li>\n</ul>\n</div>\n<div class="poll-info">\n<p>\n<span class="info-number">0</span>\n<span class="info-label">voters</span>\n</p>\n</div>\n</div>\n</div>',
- post_number: 2,
+ created_at: "2021-01-25T13:08:27.385Z",
+ cooked: "<p>A reply to the poll.</p>",
+ post_number: 4,
post_type: 1,
- updated_at: "2021-01-25T13:07:58.995Z",
- reply_count: 2,
- reply_to_post_number: null,
+ updated_at: "2021-01-25T13:08:27.385Z",
+ reply_count: 0,
+ reply_to_post_number: 2,
quote_count: 0,
incoming_link_count: 0,
reads: 1,
readers_count: 0,
- score: 10.2,
- yours: false,
+ score: 0.2,
+ yours: true,
topic_id: 25,
topic_slug: "topic-with-a-poll-in-a-post-reply-history",
display_username: null,
@@ -396,14 +40,37 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";
flair_bg_color: null,
flair_color: null,
version: 1,
- can_edit: false,
- can_delete: false,
+ can_edit: true,
+ can_delete: true,
can_recover: false,
- can_wiki: false,
+ can_wiki: true,
+ read: true,
user_title: null,
+ reply_to_user: {
+ username: "admin1",
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
+ },
bookmarked: false,
bookmarks: [],
- actions_summary: [],
+ actions_summary: [
+ {
+ id: 3,
+ can_act: true,
+ },
+ {
+ id: 4,
+ can_act: true,
+ },
+ {
+ id: 8,
+ can_act: true,
+ },
+ {
+ id: 7,
+ can_act: true,
+ },
+ ],
moderator: false,
admin: true,
staff: true,
@@ -415,40 +82,366 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";
edit_reason: null,
can_view_edit_history: true,
wiki: false,
- polls: [
+ reviewable_id: 0,
+ reviewable_score_count: 0,
+ reviewable_score_pending_count: 0,
+ },
+ ],
+ stream: [82],
+ },
+ timeline_lookup: [[1, 0]],
+ suggested_topics: [
+ {
+ id: 7,
+ title: "Welcome to Discourse",
+ fancy_title: "Welcome to Discourse",
+ slug: "welcome-to-discourse",
+ posts_count: 1,
+ reply_count: 0,
+ highest_post_number: 1,
+ image_url: null,
+ created_at: "2021-01-07T15:36:44.707Z",
+ last_posted_at: "2021-01-07T15:36:44.750Z",
+ bumped: true,
+ bumped_at: "2021-01-07T15:36:44.750Z",
+ archetype: "regular",
+ unseen: false,
+ pinned: true,
+ unpinned: null,
+ excerpt:
+ "The first paragraph of this pinned topic will be visible as a welcome message to all new visitors on your homepage. It’s important! Edit this into a brief description of your community: Who is it for? What can they fi&hellip;",
+ visible: true,
+ closed: false,
+ archived: false,
+ bookmarked: null,
+ liked: null,
+ like_count: 0,
+ views: 1,
+ category_id: 1,
+ featured_link: null,
+ posters: [
+ {
+ extras: "latest single",
+ description: "Original Poster, Most Recent Poster",
+ user: {
+ id: -1,
+ username: "system",
+ name: "system",
+ avatar_template:
+ "http://localhost:3000/images/discourse-logo-sketch-small.png",
+ },
+ },
+ ],
+ },
+ {
+ id: 20,
+ title: "Polls testing. Just one poll in the comment",
+ fancy_title: "Polls testing. Just one poll in the comment",
+ slug: "polls-testing-just-one-poll-in-the-comment",
+ posts_count: 3,
+ reply_count: 1,
+ highest_post_number: 3,
+ image_url: null,
+ created_at: "2021-01-21T09:21:35.102Z",
+ last_posted_at: "2021-01-22T09:35:33.543Z",
+ bumped: true,
+ bumped_at: "2021-01-22T09:35:33.543Z",
+ archetype: "regular",
+ unseen: false,
+ last_read_post_number: 3,
+ unread_posts: 0,
+ pinned: false,
+ unpinned: null,
+ visible: true,
+ closed: false,
+ archived: false,
+ notification_level: 2,
+ bookmarked: false,
+ bookmarks: [],
+ liked: false,
+ like_count: 0,
+ views: 3,
+ category_id: 1,
+ featured_link: null,
+ posters: [
+ {
+ extras: null,
+ description: "Original Poster",
+ user: {
+ id: 2,
+ username: "andrey1",
+ name: "andrey1",
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/c0e974/{size}.png",
+ },
+ },
+ {
+ extras: "latest",
+ description: "Most Recent Poster",
+ user: {
+ id: 3,
+ username: "admin1",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
+ },
+ },
+ ],
+ },
+ {
+ id: 22,
+ title: "Polls testing. The whole test",
+ fancy_title: "Polls testing. The whole test",
+ slug: "polls-testing-the-whole-test",
+ posts_count: 12,
+ reply_count: 8,
+ highest_post_number: 12,
+ image_url: null,
+ created_at: "2021-01-21T09:55:20.135Z",
+ last_posted_at: "2021-01-22T11:59:31.561Z",
+ bumped: true,
+ bumped_at: "2021-01-22T11:59:31.561Z",
+ archetype: "regular",
+ unseen: false,
+ last_read_post_number: 12,
+ unread_posts: 0,
+ pinned: false,
+ unpinned: null,
+ visible: true,
+ closed: false,
+ archived: false,
+ notification_level: 2,
+ bookmarked: false,
+ bookmarks: [],
+ liked: false,
+ like_count: 0,
+ views: 4,
+ category_id: 1,
+ featured_link: null,
+ posters: [
+ {
+ extras: null,
+ description: "Original Poster",
+ user: {
+ id: 2,
+ username: "andrey1",
+ name: "andrey1",
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/c0e974/{size}.png",
+ },
+ },
+ {
+ extras: "latest",
+ description: "Most Recent Poster",
+ user: {
+ id: 3,
+ username: "admin1",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
+ },
+ },
+ ],
+ },
+ ],
+ id: 25,
+ title: "Topic with a poll in a post reply history",
+ fancy_title: "Topic with a poll in a post reply history",
+ posts_count: 4,
+ created_at: "2021-01-25T13:07:31.670Z",
+ views: 2,
+ reply_count: 2,
+ like_count: 0,
+ last_posted_at: "2021-01-25T13:08:27.385Z",
+ visible: true,
+ closed: false,
+ archived: false,
+ has_summary: false,
+ archetype: "regular",
+ slug: "topic-with-a-poll-in-a-post-reply-history",
+ category_id: 1,
+ word_count: 25,
+ deleted_at: null,
+ user_id: 3,
+ featured_link: null,
+ pinned_globally: false,
+ pinned_at: null,
+ pinned_until: null,
+ image_url: null,
+ slow_mode_seconds: 0,
+ draft: null,
+ draft_key: "topic_25",
+ draft_sequence: 4,
+ posted: true,
+ unpinned: null,
+ pinned: false,
+ current_post_number: 4,
+ highest_post_number: 4,
+ last_read_post_number: 4,
+ last_read_post_id: 82,
+ deleted_by: null,
+ has_deleted: false,
+ actions_summary: [
+ {
+ id: 4,
+ count: 0,
+ hidden: false,
+ can_act: true,
+ },
+ {
+ id: 8,
+ count: 0,
+ hidden: false,
+ can_act: true,
+ },
+ {
+ id: 7,
+ count: 0,
+ hidden: false,
+ can_act: true,
+ },
+ ],
+ chunk_size: 20,
+ bookmarked: false,
+ bookmarks: [],
+ topic_timer: null,
+ message_bus_last_id: 4,
+ participant_count: 1,
+ show_read_indicator: false,
+ thumbnails: null,
+ details: {
+ can_edit: true,
+ notification_level: 3,
+ notifications_reason_id: 1,
+ can_move_posts: true,
+ can_delete: true,
+ can_remove_allowed_users: true,
+ can_invite_to: true,
+ can_invite_via_email: true,
+ can_create_post: true,
+ can_reply_as_new_topic: true,
+ can_flag_topic: true,
+ can_convert_topic: true,
+ can_review_topic: true,
+ can_close_topic: true,
+ can_archive_topic: true,
+ can_split_merge_topic: true,
+ can_edit_staff_notes: true,
+ can_toggle_topic_visibility: true,
+ can_moderate_category: true,
+ can_remove_self_id: 3,
+ participants: [
+ {
+ id: 3,
+ username: "admin1",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
+ post_count: 4,
+ primary_group_name: null,
+ flair_url: null,
+ flair_color: null,
+ flair_bg_color: null,
+ },
+ ],
+ created_by: {
+ id: 3,
+ username: "admin1",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
+ },
+ last_poster: {
+ id: 3,
+ username: "admin1",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
+ },
+ },
+ });
+ });
+
+ server.get("/posts/82/reply-history", () => {
+ return helper.response([
+ {
+ id: 80,
+ name: null,
+ username: "admin1",
+ avatar_template: "/letter_avatar_proxy/v4/letter/a/bbce88/{size}.png",
+ created_at: "2021-01-25T13:07:58.995Z",
+ cooked:
+ '<p>The poll:</p>\n<div class="poll" data-poll-status="open" data-poll-name="poll">\n<div>\n<div class="poll-container">\n<ul>\n<li data-poll-option-id="5b8ee5ba2a43e258f93dbef9264bf1ad">Option A</li>\n<li data-poll-option-id="6872645f5d8ef2311883617a3a7d381b">Option B</li>\n</ul>\n</div>\n<div class="poll-info">\n<p>\n<span class="info-number">0</span>\n<span class="info-label">voters</span>\n</p>\n</div>\n</div>\n</div>',
+ post_number: 2,
+ post_type: 1,
+ updated_at: "2021-01-25T13:07:58.995Z",
+ reply_count: 2,
+ reply_to_post_number: null,
+ quote_count: 0,
+ incoming_link_count: 0,
+ reads: 1,
+ readers_count: 0,
+ score: 10.2,
+ yours: false,
+ topic_id: 25,
+ topic_slug: "topic-with-a-poll-in-a-post-reply-history",
+ display_username: null,
+ primary_group_name: null,
+ flair_url: null,
+ flair_bg_color: null,
+ flair_color: null,
+ version: 1,
+ can_edit: false,
+ can_delete: false,
+ can_recover: false,
+ can_wiki: false,
+ user_title: null,
+ bookmarked: false,
+ bookmarks: [],
+ actions_summary: [],
+ moderator: false,
+ admin: true,
+ staff: true,
+ user_id: 3,
+ hidden: false,
+ trust_level: 1,
+ deleted_at: null,
+ user_deleted: false,
+ edit_reason: null,
+ can_view_edit_history: true,
+ wiki: false,
+ polls: [
+ {
+ name: "poll",
+ type: "regular",
+ status: "open",
+ results: "always",
+ options: [
{
- name: "poll",
- type: "regular",
- status: "open",
- results: "always",
- options: [
- {
- id: "5b8ee5ba2a43e258f93dbef9264bf1ad",
- html: "Option A",
- votes: 0,
- },
- {
- id: "6872645f5d8ef2311883617a3a7d381b",
- html: "Option B",
- votes: 0,
- },
- ],
- voters: 0,
- chart_type: "bar",
- title: null,
+ id: "5b8ee5ba2a43e258f93dbef9264bf1ad",
+ html: "Option A",
+ votes: 0,
+ },
+ {
+ id: "6872645f5d8ef2311883617a3a7d381b",
+ html: "Option B",
+ votes: 0,
},
],
+ voters: 0,
+ chart_type: "bar",
+ title: null,
},
- ]);
- });
- });
+ ],
+ },
+ ]);
+ });
+ });
- test("renders and extends", async function (assert) {
- await visit("/t/-/topic_with_poll_in_post_reply_history");
- await click(".reply-to-tab");
- assert.dom(".poll").exists("poll is rendered");
- assert.dom(".poll-buttons").exists("poll is extended");
- });
- }
- );
+ test("renders and extends", async function (assert) {
+ await visit("/t/-/topic_with_poll_in_post_reply_history");
+ await click(".reply-to-tab");
+ assert.dom(".poll").exists("poll is rendered");
+ assert.dom(".poll-buttons").exists("poll is extended");
+ });
});
diff --git a/plugins/poll/test/javascripts/acceptance/poll-quote-test.js b/plugins/poll/test/javascripts/acceptance/poll-quote-test.js
index 6a1f74bc90e..248b33cd5f8 100644
--- a/plugins/poll/test/javascripts/acceptance/poll-quote-test.js
+++ b/plugins/poll/test/javascripts/acceptance/poll-quote-test.js
@@ -2,441 +2,434 @@ import { click, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
-["enabled", "disabled"].forEach((postStreamMode) => {
- acceptance(
- `Poll quote (glimmer_post_stream_mode = ${postStreamMode})`,
- function (needs) {
- needs.user();
- needs.settings({
- poll_enabled: true,
- glimmer_post_stream_mode: postStreamMode,
- });
+acceptance(`Poll quote`, function (needs) {
+ needs.user();
+ needs.settings({
+ poll_enabled: true,
+ });
- needs.pretender((server, helper) => {
- server.get("/posts/by_number/130/1", () => {
- return helper.response({
- id: 133,
- name: null,
- username: "bianca",
- avatar_template:
- "/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",
- created_at: "2020-08-17T12:05:24.577Z",
- cooked:
- '<div class="poll" data-poll-status="open" data-poll-name="poll1" data-poll-results="always" data-poll-charttype="bar" data-poll-type="regular">\n<div>\n<div class="poll-container">\n<ul>\n<li data-poll-option-id="bf48cd4958a17180e2a298e246988f94">Alpha</li>\n<li data-poll-option-id="c19aa835729ab0413a84a2c9850c4005">Beta</li>\n</ul>\n</div>\n<div class="poll-info">\n<p>\n<span class="info-number">0</span>\n<span class="info-label">voters</span>\n</p>\n</div>\n</div>\n</div>\n<div class="poll" data-poll-status="open" data-poll-name="poll2" data-poll-results="always" data-poll-charttype="bar" data-poll-type="regular">\n<div>\n<div class="poll-container">\n<ul>\n<li data-poll-option-id="def034c6770c6fd3754c054ef9ec4721">First</li>\n<li data-poll-option-id="e0f55d1a981683789bec2a0b05eb70ef">Second</li>\n</ul>\n</div>\n<div class="poll-info">\n<p>\n<span class="info-number">0</span>\n<span class="info-label">voters</span>\n</p>\n</div>\n</div>\n</div>',
- post_number: 1,
- post_type: 1,
- updated_at: "2020-08-17T12:05:24.577Z",
- reply_count: 0,
- reply_to_post_number: null,
- quote_count: 0,
- incoming_link_count: 0,
- reads: 1,
- readers_count: 0,
- score: 0.2,
- yours: true,
- topic_id: 130,
- topic_slug: "topic-with-two-polls",
- display_username: null,
- primary_group_name: null,
- flair_url: null,
- flair_bg_color: null,
- flair_color: null,
- version: 1,
- can_edit: true,
- can_delete: false,
- can_recover: false,
- can_wiki: true,
- user_title: "Tester",
- title_is_group: false,
- bookmarked: false,
- bookmarks: [],
- raw: "[poll name=poll1 type=regular results=always chartType=bar]\n* Alpha\n* Beta\n[/poll]\n\n[poll name=poll2 type=regular results=always chartType=bar]\n* First\n* Second\n[/poll]",
- actions_summary: [
- {
- id: 3,
- can_act: true,
- },
- {
- id: 4,
- can_act: true,
- },
+ needs.pretender((server, helper) => {
+ server.get("/posts/by_number/130/1", () => {
+ return helper.response({
+ id: 133,
+ name: null,
+ username: "bianca",
+ avatar_template: "/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",
+ created_at: "2020-08-17T12:05:24.577Z",
+ cooked:
+ '<div class="poll" data-poll-status="open" data-poll-name="poll1" data-poll-results="always" data-poll-charttype="bar" data-poll-type="regular">\n<div>\n<div class="poll-container">\n<ul>\n<li data-poll-option-id="bf48cd4958a17180e2a298e246988f94">Alpha</li>\n<li data-poll-option-id="c19aa835729ab0413a84a2c9850c4005">Beta</li>\n</ul>\n</div>\n<div class="poll-info">\n<p>\n<span class="info-number">0</span>\n<span class="info-label">voters</span>\n</p>\n</div>\n</div>\n</div>\n<div class="poll" data-poll-status="open" data-poll-name="poll2" data-poll-results="always" data-poll-charttype="bar" data-poll-type="regular">\n<div>\n<div class="poll-container">\n<ul>\n<li data-poll-option-id="def034c6770c6fd3754c054ef9ec4721">First</li>\n<li data-poll-option-id="e0f55d1a981683789bec2a0b05eb70ef">Second</li>\n</ul>\n</div>\n<div class="poll-info">\n<p>\n<span class="info-number">0</span>\n<span class="info-label">voters</span>\n</p>\n</div>\n</div>\n</div>',
+ post_number: 1,
+ post_type: 1,
+ updated_at: "2020-08-17T12:05:24.577Z",
+ reply_count: 0,
+ reply_to_post_number: null,
+ quote_count: 0,
+ incoming_link_count: 0,
+ reads: 1,
+ readers_count: 0,
+ score: 0.2,
+ yours: true,
+ topic_id: 130,
+ topic_slug: "topic-with-two-polls",
+ display_username: null,
+ primary_group_name: null,
+ flair_url: null,
+ flair_bg_color: null,
+ flair_color: null,
+ version: 1,
+ can_edit: true,
+ can_delete: false,
+ can_recover: false,
+ can_wiki: true,
+ user_title: "Tester",
+ title_is_group: false,
+ bookmarked: false,
+ bookmarks: [],
+ raw: "[poll name=poll1 type=regular results=always chartType=bar]\n* Alpha\n* Beta\n[/poll]\n\n[poll name=poll2 type=regular results=always chartType=bar]\n* First\n* Second\n[/poll]",
+ actions_summary: [
+ {
+ id: 3,
+ can_act: true,
+ },
+ {
+ id: 4,
+ can_act: true,
+ },
+ {
+ id: 8,
+ can_act: true,
+ },
+ {
+ id: 7,
+ can_act: true,
+ },
+ ],
+ moderator: false,
+ admin: true,
+ staff: true,
+ user_id: 1,
+ hidden: false,
+ trust_level: 0,
+ deleted_at: null,
+ user_deleted: false,
+ edit_reason: null,
+ can_view_edit_history: true,
+ wiki: false,
+ reviewable_id: null,
+ reviewable_score_count: 0,
+ reviewable_score_pending_count: 0,
+ calendar_details: [],
+ polls: [
+ {
+ name: "poll1",
+ type: "regular",
+ status: "open",
+ results: "always",
+ options: [
{
- id: 8,
- can_act: true,
+ id: "bf48cd4958a17180e2a298e246988f94",
+ html: "Alpha",
+ votes: 0,
},
{
- id: 7,
- can_act: true,
+ id: "c19aa835729ab0413a84a2c9850c4005",
+ html: "Beta",
+ votes: 0,
},
],
- moderator: false,
- admin: true,
- staff: true,
- user_id: 1,
- hidden: false,
- trust_level: 0,
- deleted_at: null,
- user_deleted: false,
- edit_reason: null,
- can_view_edit_history: true,
- wiki: false,
- reviewable_id: null,
- reviewable_score_count: 0,
- reviewable_score_pending_count: 0,
- calendar_details: [],
- polls: [
+ voters: 0,
+ chart_type: "bar",
+ },
+ {
+ name: "poll2",
+ type: "regular",
+ status: "open",
+ results: "always",
+ options: [
{
- name: "poll1",
- type: "regular",
- status: "open",
- results: "always",
- options: [
- {
- id: "bf48cd4958a17180e2a298e246988f94",
- html: "Alpha",
- votes: 0,
- },
- {
- id: "c19aa835729ab0413a84a2c9850c4005",
- html: "Beta",
- votes: 0,
- },
- ],
- voters: 0,
- chart_type: "bar",
+ id: "def034c6770c6fd3754c054ef9ec4721",
+ html: "First",
+ votes: 0,
},
{
- name: "poll2",
- type: "regular",
- status: "open",
- results: "always",
- options: [
- {
- id: "def034c6770c6fd3754c054ef9ec4721",
- html: "First",
- votes: 0,
- },
- {
- id: "e0f55d1a981683789bec2a0b05eb70ef",
- html: "Second",
- votes: 0,
- },
- ],
- voters: 0,
- chart_type: "bar",
+ id: "e0f55d1a981683789bec2a0b05eb70ef",
+ html: "Second",
+ votes: 0,
},
],
- });
- });
+ voters: 0,
+ chart_type: "bar",
+ },
+ ],
+ });
+ });
- server.get("/t/topic_with_two_quoted_polls.json", () => {
- return helper.response({
- post_stream: {
- posts: [
+ server.get("/t/topic_with_two_quoted_polls.json", () => {
+ return helper.response({
+ post_stream: {
+ posts: [
+ {
+ id: 134,
+ name: null,
+ username: "bianca",
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",
+ created_at: "2020-08-17T12:08:24.043Z",
+ cooked:
+ '<aside class="quote quote-modified" data-post="1" data-topic="130">\n <div class="title">\n <div class="quote-controls"></div>\n <img alt="" width="20" height="20" src="/letter_avatar_proxy/v4/letter/b/3be4f8/40.png" class="avatar">\n <a href="//forum.example.com/t/topic-with-two-polls/130">Topic with two polls</a> \n </div>\n <blockquote>\n <a href="/t/topic-with-two-polls/130/1">poll</a>\n<a href="/t/topic-with-two-polls/130/1">poll</a>\n </blockquote>\n</aside>\n',
+ post_number: 1,
+ post_type: 1,
+ updated_at: "2020-08-17T12:08:24.043Z",
+ reply_count: 0,
+ reply_to_post_number: null,
+ quote_count: 0,
+ incoming_link_count: 0,
+ reads: 1,
+ readers_count: 0,
+ score: 0,
+ yours: true,
+ topic_id: 131,
+ topic_slug: "topic-with-two-quoted-polls",
+ display_username: null,
+ primary_group_name: null,
+ flair_url: null,
+ flair_bg_color: null,
+ flair_color: null,
+ version: 1,
+ can_edit: true,
+ can_delete: false,
+ can_recover: false,
+ can_wiki: true,
+ link_counts: [
{
- id: 134,
- name: null,
- username: "bianca",
- avatar_template:
- "/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",
- created_at: "2020-08-17T12:08:24.043Z",
- cooked:
- '<aside class="quote quote-modified" data-post="1" data-topic="130">\n <div class="title">\n <div class="quote-controls"></div>\n <img alt="" width="20" height="20" src="/letter_avatar_proxy/v4/letter/b/3be4f8/40.png" class="avatar">\n <a href="//forum.example.com/t/topic-with-two-polls/130">Topic with two polls</a> \n </div>\n <blockquote>\n <a href="/t/topic-with-two-polls/130/1">poll</a>\n<a href="/t/topic-with-two-polls/130/1">poll</a>\n </blockquote>\n</aside>\n',
- post_number: 1,
- post_type: 1,
- updated_at: "2020-08-17T12:08:24.043Z",
- reply_count: 0,
- reply_to_post_number: null,
- quote_count: 0,
- incoming_link_count: 0,
- reads: 1,
- readers_count: 0,
- score: 0,
- yours: true,
- topic_id: 131,
- topic_slug: "topic-with-two-quoted-polls",
- display_username: null,
- primary_group_name: null,
- flair_url: null,
- flair_bg_color: null,
- flair_color: null,
- version: 1,
- can_edit: true,
- can_delete: false,
- can_recover: false,
- can_wiki: true,
- link_counts: [
- {
- url: "http://forum.example.com/t/topic-with-two-polls/130",
- internal: true,
- reflection: false,
- title: "Topic with two polls",
- clicks: 0,
- },
- ],
- read: true,
- user_title: "Tester",
- title_is_group: false,
- bookmarked: false,
- bookmarks: [],
- actions_summary: [
- {
- id: 3,
- can_act: true,
- },
- {
- id: 4,
- can_act: true,
- },
- {
- id: 8,
- can_act: true,
- },
- {
- id: 7,
- can_act: true,
- },
- ],
- moderator: false,
- admin: true,
- staff: true,
- user_id: 1,
- hidden: false,
- trust_level: 0,
- deleted_at: null,
- user_deleted: false,
- edit_reason: null,
- can_view_edit_history: true,
- wiki: false,
- reviewable_id: 0,
- reviewable_score_count: 0,
- reviewable_score_pending_count: 0,
- calendar_details: [],
+ url: "http://forum.example.com/t/topic-with-two-polls/130",
+ internal: true,
+ reflection: false,
+ title: "Topic with two polls",
+ clicks: 0,
},
],
- stream: [134],
+ read: true,
+ user_title: "Tester",
+ title_is_group: false,
+ bookmarked: false,
+ bookmarks: [],
+ actions_summary: [
+ {
+ id: 3,
+ can_act: true,
+ },
+ {
+ id: 4,
+ can_act: true,
+ },
+ {
+ id: 8,
+ can_act: true,
+ },
+ {
+ id: 7,
+ can_act: true,
+ },
+ ],
+ moderator: false,
+ admin: true,
+ staff: true,
+ user_id: 1,
+ hidden: false,
+ trust_level: 0,
+ deleted_at: null,
+ user_deleted: false,
+ edit_reason: null,
+ can_view_edit_history: true,
+ wiki: false,
+ reviewable_id: 0,
+ reviewable_score_count: 0,
+ reviewable_score_pending_count: 0,
+ calendar_details: [],
},
- timeline_lookup: [[1, 0]],
- suggested_topics: [
- {
- id: 7,
- title: "Welcome to Discourse",
- fancy_title: "Welcome to Discourse",
- slug: "welcome-to-discourse",
- posts_count: 1,
- reply_count: 0,
- highest_post_number: 1,
- image_url: null,
- created_at: "2020-08-11T12:43:04.894Z",
- last_posted_at: "2020-08-11T12:43:04.959Z",
- bumped: true,
- bumped_at: "2020-08-11T12:43:04.959Z",
- archetype: "regular",
- unseen: false,
- last_read_post_number: 1,
- unread_posts: 0,
- pinned: false,
- unpinned: true,
- visible: true,
- closed: false,
- archived: false,
- notification_level: 1,
- bookmarked: false,
- bookmarks: [],
- liked: false,
- tags: [],
- like_count: 0,
- views: 1,
- category_id: 1,
- featured_link: null,
- posters: [
- {
- extras: "latest single",
- description: "Original Poster, Most Recent Poster",
- user: {
- id: 5,
- username: "foo2",
- name: null,
- avatar_template:
- "/letter_avatar_proxy/v4/letter/f/8edcca/{size}.png",
- },
- },
- ],
- },
- {
- id: 130,
- title: "Topic with two polls",
- fancy_title: "Topic with two polls",
- slug: "topic-with-two-polls",
- posts_count: 1,
- reply_count: 0,
- highest_post_number: 1,
- image_url: null,
- created_at: "2020-08-17T12:05:24.500Z",
- last_posted_at: "2020-08-17T12:05:24.577Z",
- bumped: true,
- bumped_at: "2020-08-17T12:05:24.577Z",
- archetype: "regular",
- unseen: false,
- last_read_post_number: 1,
- unread_posts: 0,
- pinned: false,
- unpinned: null,
- visible: true,
- closed: false,
- archived: false,
- notification_level: 3,
- bookmarked: false,
- bookmarks: [],
- liked: false,
- tags: [],
- like_count: 0,
- views: 1,
- category_id: 1,
- featured_link: null,
- posters: [
- {
- extras: "latest single",
- description: "Original Poster, Most Recent Poster",
- user: {
- id: 1,
- username: "bianca",
- name: null,
- avatar_template:
- "/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",
- },
- },
- ],
- },
- ],
- tags: [],
- id: 131,
- title: "Topic with two quoted polls",
- fancy_title: "Topic with two quoted polls",
+ ],
+ stream: [134],
+ },
+ timeline_lookup: [[1, 0]],
+ suggested_topics: [
+ {
+ id: 7,
+ title: "Welcome to Discourse",
+ fancy_title: "Welcome to Discourse",
+ slug: "welcome-to-discourse",
posts_count: 1,
- created_at: "2020-08-17T12:08:23.918Z",
- views: 1,
reply_count: 0,
- like_count: 0,
- last_posted_at: "2020-08-17T12:08:24.043Z",
+ highest_post_number: 1,
+ image_url: null,
+ created_at: "2020-08-11T12:43:04.894Z",
+ last_posted_at: "2020-08-11T12:43:04.959Z",
+ bumped: true,
+ bumped_at: "2020-08-11T12:43:04.959Z",
+ archetype: "regular",
+ unseen: false,
+ last_read_post_number: 1,
+ unread_posts: 0,
+ pinned: false,
+ unpinned: true,
visible: true,
closed: false,
archived: false,
- has_summary: false,
- archetype: "regular",
- slug: "topic-with-two-quoted-polls",
+ notification_level: 1,
+ bookmarked: false,
+ bookmarks: [],
+ liked: false,
+ tags: [],
+ like_count: 0,
+ views: 1,
category_id: 1,
- word_count: 9,
- deleted_at: null,
- user_id: 1,
featured_link: null,
- pinned_globally: false,
- pinned_at: null,
- pinned_until: null,
- image_url: null,
- draft: null,
- draft_key: "topic_131",
- draft_sequence: 0,
- posted: true,
- unpinned: null,
- pinned: false,
- current_post_number: 1,
- highest_post_number: 1,
- last_read_post_number: 1,
- last_read_post_id: 134,
- deleted_by: null,
- has_deleted: false,
- actions_summary: [
- {
- id: 4,
- count: 0,
- hidden: false,
- can_act: true,
- },
- {
- id: 8,
- count: 0,
- hidden: false,
- can_act: true,
- },
+ posters: [
{
- id: 7,
- count: 0,
- hidden: false,
- can_act: true,
+ extras: "latest single",
+ description: "Original Poster, Most Recent Poster",
+ user: {
+ id: 5,
+ username: "foo2",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/f/8edcca/{size}.png",
+ },
},
],
- chunk_size: 20,
+ },
+ {
+ id: 130,
+ title: "Topic with two polls",
+ fancy_title: "Topic with two polls",
+ slug: "topic-with-two-polls",
+ posts_count: 1,
+ reply_count: 0,
+ highest_post_number: 1,
+ image_url: null,
+ created_at: "2020-08-17T12:05:24.500Z",
+ last_posted_at: "2020-08-17T12:05:24.577Z",
+ bumped: true,
+ bumped_at: "2020-08-17T12:05:24.577Z",
+ archetype: "regular",
+ unseen: false,
+ last_read_post_number: 1,
+ unread_posts: 0,
+ pinned: false,
+ unpinned: null,
+ visible: true,
+ closed: false,
+ archived: false,
+ notification_level: 3,
bookmarked: false,
bookmarks: [],
- topic_timer: null,
- message_bus_last_id: 2,
- participant_count: 1,
- queued_posts_count: 0,
- show_read_indicator: false,
- thumbnails: null,
- can_vote: false,
- vote_count: null,
- user_voted: false,
- details: {
- notification_level: 3,
- notifications_reason_id: 1,
- can_move_posts: true,
- can_edit: true,
- can_delete: true,
- can_remove_allowed_users: true,
- can_invite_to: true,
- can_invite_via_email: true,
- can_create_post: true,
- can_reply_as_new_topic: true,
- can_flag_topic: true,
- can_convert_topic: true,
- can_review_topic: true,
- can_close_topic: true,
- can_archive_topic: true,
- can_split_merge_topic: true,
- can_edit_staff_notes: true,
- can_remove_self_id: 1,
- participants: [
- {
+ liked: false,
+ tags: [],
+ like_count: 0,
+ views: 1,
+ category_id: 1,
+ featured_link: null,
+ posters: [
+ {
+ extras: "latest single",
+ description: "Original Poster, Most Recent Poster",
+ user: {
id: 1,
username: "bianca",
name: null,
avatar_template:
"/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",
- post_count: 1,
- primary_group_name: null,
- flair_url: null,
- flair_color: null,
- flair_bg_color: null,
},
- ],
- created_by: {
- id: 1,
- username: "bianca",
- name: null,
- avatar_template:
- "/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",
- },
- last_poster: {
- id: 1,
- username: "bianca",
- name: null,
- avatar_template:
- "/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",
},
+ ],
+ },
+ ],
+ tags: [],
+ id: 131,
+ title: "Topic with two quoted polls",
+ fancy_title: "Topic with two quoted polls",
+ posts_count: 1,
+ created_at: "2020-08-17T12:08:23.918Z",
+ views: 1,
+ reply_count: 0,
+ like_count: 0,
+ last_posted_at: "2020-08-17T12:08:24.043Z",
+ visible: true,
+ closed: false,
+ archived: false,
+ has_summary: false,
+ archetype: "regular",
+ slug: "topic-with-two-quoted-polls",
+ category_id: 1,
+ word_count: 9,
+ deleted_at: null,
+ user_id: 1,
+ featured_link: null,
+ pinned_globally: false,
+ pinned_at: null,
+ pinned_until: null,
+ image_url: null,
+ draft: null,
+ draft_key: "topic_131",
+ draft_sequence: 0,
+ posted: true,
+ unpinned: null,
+ pinned: false,
+ current_post_number: 1,
+ highest_post_number: 1,
+ last_read_post_number: 1,
+ last_read_post_id: 134,
+ deleted_by: null,
+ has_deleted: false,
+ actions_summary: [
+ {
+ id: 4,
+ count: 0,
+ hidden: false,
+ can_act: true,
+ },
+ {
+ id: 8,
+ count: 0,
+ hidden: false,
+ can_act: true,
+ },
+ {
+ id: 7,
+ count: 0,
+ hidden: false,
+ can_act: true,
+ },
+ ],
+ chunk_size: 20,
+ bookmarked: false,
+ bookmarks: [],
+ topic_timer: null,
+ message_bus_last_id: 2,
+ participant_count: 1,
+ queued_posts_count: 0,
+ show_read_indicator: false,
+ thumbnails: null,
+ can_vote: false,
+ vote_count: null,
+ user_voted: false,
+ details: {
+ notification_level: 3,
+ notifications_reason_id: 1,
+ can_move_posts: true,
+ can_edit: true,
+ can_delete: true,
+ can_remove_allowed_users: true,
+ can_invite_to: true,
+ can_invite_via_email: true,
+ can_create_post: true,
+ can_reply_as_new_topic: true,
+ can_flag_topic: true,
+ can_convert_topic: true,
+ can_review_topic: true,
+ can_close_topic: true,
+ can_archive_topic: true,
+ can_split_merge_topic: true,
+ can_edit_staff_notes: true,
+ can_remove_self_id: 1,
+ participants: [
+ {
+ id: 1,
+ username: "bianca",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",
+ post_count: 1,
+ primary_group_name: null,
+ flair_url: null,
+ flair_color: null,
+ flair_bg_color: null,
},
- pending_posts: [],
- });
- });
+ ],
+ created_by: {
+ id: 1,
+ username: "bianca",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",
+ },
+ last_poster: {
+ id: 1,
+ username: "bianca",
+ name: null,
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/b/3be4f8/{size}.png",
+ },
+ },
+ pending_posts: [],
});
+ });
+ });
- test("renders and extends", async function (assert) {
- await visit("/t/-/topic_with_two_quoted_polls");
- await click(".quote-controls .quote-toggle");
- assert.dom(".poll").exists({ count: 2 }, "polls are rendered");
- assert.dom(".poll-buttons").exists({ count: 2 }, "polls are extended");
- });
- }
- );
+ test("renders and extends", async function (assert) {
+ await visit("/t/-/topic_with_two_quoted_polls");
+ await click(".quote-controls .quote-toggle");
+ assert.dom(".poll").exists({ count: 2 }, "polls are rendered");
+ assert.dom(".poll-buttons").exists({ count: 2 }, "polls are extended");
+ });
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c8bb5cdd659..a443aff5c96 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -26,9 +26,6 @@ patchedDependencies:
hash: 55h346kvblvnigtrwrsh4hpona
path: patches/[email protected]
- hash: ng672yys7q7cl7vz44xn3y54uq
- path: patches/[email protected]
importers:
@@ -157,9 +154,6 @@ importers:
discourse-plugins:
specifier: workspace:1.0.0
version: link:../discourse-plugins
- discourse-widget-hbs:
- specifier: workspace:1.0.0
- version: link:../discourse-widget-hbs
ember-cli-htmlbars:
specifier: ^6.3.0
version: 6.3.0
@@ -301,9 +295,6 @@ importers:
diff:
specifier: ^8.0.2
version: 8.0.2
- discourse-widget-hbs:
- specifier: workspace:1.0.0
- version: link:../discourse-widget-hbs
ember-curry-component:
specifier: ^0.3.1
version: 0.3.1(@babel/[email protected])
@@ -626,9 +617,6 @@ importers:
util:
specifier: ^0.12.5
version: 0.12.5
- virtual-dom:
- specifier: ^2.1.1
- version: 2.1.1(patch_hash=ng672yys7q7cl7vz44xn3y54uq)
webpack:
specifier: 5.99.9
version: 5.99.9(@swc/[email protected])([email protected])
@@ -680,9 +668,6 @@ importers:
deprecation-silencer:
specifier: workspace:1.0.0
version: link:../deprecation-silencer
- discourse-widget-hbs:
- specifier: workspace:1.0.0
- version: link:../discourse-widget-hbs
ember-cli-babel:
specifier: ^8.2.0
version: 8.2.0(@babel/[email protected])
@@ -718,70 +703,6 @@ importers:
specifier: ~6.6.0
version: 6.6.0(patch_hash=nsmtwj6thcg4lxkztr5oqzscwe)(@glimmer/[email protected])([email protected])
- frontend/discourse-widget-hbs:
- dependencies:
- '@babel/core':
- specifier: ^7.28.5
- version: 7.28.5([email protected])
- ember-auto-import:
- specifier: ^2.12.0
- ember-cli-babel:
- specifier: ^8.2.0
- version: 8.2.0(@babel/[email protected])
- ember-cli-htmlbars:
- specifier: ^6.3.0
- version: 6.3.0
- devDependencies:
- '@ember/optional-features':
- specifier: ^2.2.0
- version: 2.2.0
- '@embroider/test-setup':
- specifier: ^4.0.0
- '@glimmer/component':
- specifier: ^2.0.0
- version: 2.0.0
- '@glimmer/syntax':
- specifier: 0.93.1
- version: 0.93.1
- broccoli-asset-rev:
- specifier: ^3.0.0
- version: 3.0.0
- ember-cli:
- specifier: ~6.8.0
- ember-cli-inject-live-reload:
- specifier: ^2.1.0
- version: 2.1.0
- ember-cli-sri:
- specifier: ^2.1.1
- version: 2.1.1
- ember-cli-terser:
- specifier: ^4.0.2
- version: 4.0.2
- ember-disable-prototype-extensions:
- specifier: ^1.1.3
- version: 1.1.3
- ember-load-initializers:
- specifier: ^3.0.1
- version: 3.0.1([email protected](patch_hash=nsmtwj6thcg4lxkztr5oqzscwe)(@glimmer/[email protected])([email protected]))
- ember-resolver:
- specifier: ^13.1.1
- version: 13.1.1
- ember-source:
- specifier: ~6.6.0
- version: 6.6.0(patch_hash=nsmtwj6thcg4lxkztr5oqzscwe)(@glimmer/[email protected])([email protected])
- ember-source-channel-url:
- specifier: ^3.0.0
- version: 3.0.0([email protected])
- loader.js:
- specifier: ^4.7.0
- version: 4.7.0
- webpack:
- specifier: 5.99.9
- version: 5.99.9(@swc/[email protected])([email protected])
-
frontend/ember-cli-progress-ci: {}
frontend/pretty-text:
@@ -3750,9 +3671,6 @@ packages:
resolution: {integrity: sha512-sWi3b3fTUSVPDsz5KsQ5eCQNVAtLgkIE/HYFkEZXR/07clqmd4E/gFiuwSaqa9b+QTXc1Uemfb7TVWbEIURWDg==}
engines: {node: 8.* || >= 10.*}
- resolution: {integrity: sha512-JhvgRb2ihQhsljNda3BI8/UcRHVzrVwo3Q+P8vDtSiyobXuFpuZ9mq+MbRGMnC22CjW3RrfXdg6j6ITX8M+7Ow==}
-
resolution: {integrity: sha512-tbydkR/CxfMwelN0vwdP/pLkDwyAASZ+VfWm4EOwlB6SWhx1sYnWLqo8N5j0rAzPfzfRaxt0mM/4wPU/Su84RQ==}
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
@@ -3818,9 +3736,6 @@ packages:
resolution: {integrity: sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==}
engines: {node: '>= 6'}
- resolution: {integrity: sha512-dU+Tx2fsypxTgtLoE36npi3UqcjSSMNYfkqgmoEhtZrraP5VWq0K7FkWVTYa8eMPtnU/G2txVsfdCJTn9uzpuQ==}
-
resolution: {integrity: sha512-RbsNrFyhwkx+6psk/0fK/Q9orOUr9VMxohGd8vTa4djf4TGLfblBgUfqZChrZuW0Q+mz2eBPFLusw9Jfukzmhg==}
hasBin: true
@@ -4525,9 +4440,6 @@ packages:
resolution: {integrity: sha512-DLayMRQ+yJaziF4JJX1FMjwjdr7wdTr1y9XvZ+NfHELfOMcYDnCHneAYXAS4FT1gLILh4V0juMZohhH1N5FsoQ==}
- resolution: {integrity: sha512-6QvTW9mrGeIegrFXdtQi9pk7O/nSK6lSdXW2eqUspN5LWD7UTji2Fqw5V2YLjBpHEoU9Xl/eUWNpDeZvoyOv2w==}
-
resolution: {integrity: sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==}
@@ -4841,9 +4753,6 @@ packages:
resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==}
- resolution: {integrity: sha512-SNDKualLUtT4StGFP7xNfuFybL2f6iJujFtrWuvJqGbVQGaN+adE23veqzPz1hjUjTunLi2EnJ+0SJxtbJreKw==}
-
resolution: {integrity: sha512-fo9HBvWnx3NGUKMvMwB/CBCMMrfEJgbDTVDEkPygA3Bdd3lM1OyCd+rbQ8BwnpF6GdVeOLDNmyL4N5Bg80ZvdA==}
@@ -5064,9 +4973,6 @@ packages:
resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}
engines: {node: '>= 0.6'}
- resolution: {integrity: sha512-otazchNRnGzp2YarBJ+GXKVGvhxVATB1zmaStxJBYet0Dyq7A9VhH8IUEB/gRcL6Ch52lfpgPTRJ2m49epyMsQ==}
-
resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}
engines: {node: '>=6'}
@@ -5605,9 +5511,6 @@ packages:
resolution: {integrity: sha512-awConJSVCHVGND6x3tmMaKcQvwXLhjdkmomy2W+Goaui8YPgYgXJZewhg3fWC+DlfqqQuWg8AwqjGTD2nAPVWg==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-wv/LAoHdRE3BeTGz53FAamhGlPLhlssK45usmGFThIi4XqnBmjKQ16u+RNbP7WvigRZDxUsM0J3gcQ5yicaL0w==}
-
resolution: {integrity: sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==}
engines: {node: '>=18'}
@@ -5869,9 +5772,6 @@ packages:
resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-rUY5vtT748NMRbEMrTNiFfy29BgGZwGXUi2NFUVMWQrogSLzlJvQV9eeMWi+g1aVaQ53tpyLAQtd5x/JH0Nh1g==}
-
resolution: {integrity: sha512-wzkZHqpb4eGrOKBl34xy3umnYHx8Si5R1U4fwmdxLo5gdH6mEK8gclckTj/qWqy4Je0bsDYe/qazZYuO7xe3XQ==}
engines: {node: '>=14.0.0'}
@@ -6073,9 +5973,6 @@ packages:
resolution: {integrity: sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-2rRIahhZr2UWb45fIOuvZGpFtz0TyOZLf32KxBbSoUCeZR495zCKlWUKKUByk3geS2eAs7ZAABt0Y/Rx0GiQGA==}
-
resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}
engines: {node: '>=12'}
@@ -6765,9 +6662,6 @@ packages:
resolution: {integrity: sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-9Wy1B3m3f66bPPmU5hdA4DR4PB2OfDU/+GS3yAB7IQozE3tqXaVv2zOjgla7MEGSRv95+ILmOuvhLkOK6wJtCQ==}
-
resolution: {integrity: sha512-ZWYT7ln73Hptxqxk2DxPU9MmapXRhxkJD6tkSR04dnQxm8BGu2hzgKLugK5yySD97u/8yy7Ma7E76k9ZdvtjkQ==}
engines: {node: '>= 12.13.0'}
@@ -6943,9 +6837,6 @@ packages:
resolution: {integrity: sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg==}
engines: {node: '>= 0.4.0'}
- resolution: {integrity: sha512-f7h4svPtl+QidoBv4taKXUjJ70G2asaZ8G28nS0OkqaalX8dwwrtWtyxEDPK62AC00ur/+/E0pUwBwY5EPn15Q==}
-
resolution: {integrity: sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==}
@@ -8947,9 +8838,6 @@ packages:
resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}
engines: {node: '>= 0.8'}
- resolution: {integrity: sha512-wb6Qc9Lbqug0kRqo/iuApfBpJJAq14Sk1faAnSmtqXiwahg7PVTvWMs9L02Z8nNIMqbwsxzBAA90bbtRLbw0zg==}
-
resolution: {integrity: sha512-NL8jTlbo0Tn4dUEXEsUg8KeyG/Lkmc4Fnzb8JXN/Ykm9G4HNImjtABMJgkQoVjOBN/j2WAwDTRytdqJbZsah7w==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -9292,12 +9180,6 @@ packages:
utf-8-validate:
optional: true
- resolution: {integrity: sha512-goHPif61oNrr0jJgsXRfc8oqtYzvfiMJpTqwE7Z4y9uH+T3UozkGqQ4d2nX9mB9khvA8U2o/UbPOFjgC7hLWIA==}
-
- resolution: {integrity: sha512-GojqklwG8gpzOVEVki5KudKNoq7MbbjYZCbyWzEz7tyPA7eleiE0+ePwOWQQRb5fm86rD3S8Tc0tSFf3AOv50w==}
-
resolution: {integrity: sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==}
engines: {node: '>=8'}
@@ -12847,8 +12729,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
-
dependencies:
baseline-browser-mapping: 2.8.26
@@ -12941,8 +12821,6 @@ snapshots:
-
dependencies:
tmp: 0.0.28
@@ -13449,8 +13327,6 @@ snapshots:
-
dependencies:
no-case: 3.0.4
@@ -14213,12 +14089,6 @@ snapshots:
dependencies:
is-arrayish: 0.2.1
- dependencies:
- camelize: 1.0.1
- string-template: 0.2.1
- xtend: 4.0.2
-
dependencies:
string-template: 0.2.1
@@ -14544,10 +14414,6 @@ snapshots:
- dependencies:
- individual: 3.0.0
-
@@ -15337,11 +15203,6 @@ snapshots:
kind-of: 6.0.3
which: 1.3.1
- dependencies:
- min-document: 2.19.0
- process: 0.11.10
-
@@ -15607,8 +15468,6 @@ snapshots:
-
@@ -15824,8 +15683,6 @@ snapshots:
-
@@ -16536,10 +16393,6 @@ snapshots:
- dependencies:
- dom-walk: 0.1.2
-
dependencies:
schema-utils: 4.3.3
@@ -16699,8 +16552,6 @@ snapshots:
-
@@ -19076,17 +18927,6 @@ snapshots:
- [email protected](patch_hash=ng672yys7q7cl7vz44xn3y54uq):
- dependencies:
- browser-split: 0.0.1
- error: 4.4.0
- ev-store: 7.0.0
- global: 4.4.0
- is-object: 1.0.2
- next-tick: 0.2.2
- x-is-array: 0.1.0
- x-is-string: 0.1.0
-
dependencies:
esbuild: 0.25.12
@@ -19454,10 +19294,6 @@ snapshots:
-
-
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index a9a1e85f6af..73274f68721 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -5,7 +5,6 @@ packages:
- "frontend/discourse-i18n"
- "frontend/discourse-markdown-it"
- "frontend/discourse-plugins"
-- "frontend/discourse-widget-hbs"
- "frontend/ember-cli-progress-ci"
- "frontend/pretty-text"
- "frontend/asset-processor"
diff --git a/spec/system/pm_user_removal_spec.rb b/spec/system/pm_user_removal_spec.rb
index 6cb28fbd6e9..88478bba509 100644
--- a/spec/system/pm_user_removal_spec.rb
+++ b/spec/system/pm_user_removal_spec.rb
@@ -9,64 +9,55 @@ describe "PM user removal", type: :system do
before { sign_in(current_user) }
- %w[enabled disabled].each do |setting|
- context "when the setting is #{setting}" do
- before { SiteSetting.glimmer_post_stream_mode = setting }
-
- it "removes a user from the PM list" do
- pm =
- create_post(
- user: current_user,
- target_usernames: [other_user.username],
- archetype: Archetype.private_message,
- ).topic
-
- topic_page.visit_topic(pm)
-
- find(".user[data-id='#{other_user.id}'] .remove-invited").click
-
- expect(page).to have_selector(
- ".small-action-contents",
- text: "Removed @#{other_user.username} just now",
- )
- end
+ it "removes a user from the PM list" do
+ pm =
+ create_post(
+ user: current_user,
+ target_usernames: [other_user.username],
+ archetype: Archetype.private_message,
+ ).topic
+
+ topic_page.visit_topic(pm)
+
+ find(".user[data-id='#{other_user.id}'] .remove-invited").click
+
+ expect(page).to have_selector(
+ ".small-action-contents",
+ text: "Removed @#{other_user.username} just now",
+ )
+ end
- it "removes yourself from the PM list" do
- pm =
- create_post(
- user: current_user,
- target_usernames: [other_user.username],
- archetype: Archetype.private_message,
- ).topic
- topic_page.visit_topic(pm)
- find(".user[data-id='#{current_user.id}'] .remove-invited").click
- dialog.click_yes
+ it "removes yourself from the PM list" do
+ pm =
+ create_post(
+ user: current_user,
+ target_usernames: [other_user.username],
+ archetype: Archetype.private_message,
+ ).topic
+ topic_page.visit_topic(pm)
+ find(".user[data-id='#{current_user.id}'] .remove-invited").click
+ dialog.click_yes
+
+ expect(page).to have_current_path("/u/#{current_user.username}/messages")
+ end
- expect(page).to have_current_path("/u/#{current_user.username}/messages")
+ it "removes a group from the PM list" do
+ group =
+ Fabricate(:group, messageable_level: Group::ALIAS_LEVELS[:everyone]).tap do |g|
+ g.add(other_user)
end
- it "removes a group from the PM list" do
- group =
- Fabricate(:group, messageable_level: Group::ALIAS_LEVELS[:everyone]).tap do |g|
- g.add(other_user)
- end
+ pm =
+ create_post(
+ user: current_user,
+ target_group_names: [group.name],
+ archetype: Archetype.private_message,
+ ).topic
- pm =
- create_post(
- user: current_user,
- target_group_names: [group.name],
- archetype: Archetype.private_message,
- ).topic
+ topic_page.visit_topic(pm)
- topic_page.visit_topic(pm)
+ find(".group[data-id='#{group.id}'] .remove-invited").click
- find(".group[data-id='#{group.id}'] .remove-invited").click
-
- expect(page).to have_selector(
- ".small-action-contents",
- text: "Removed @#{group.name} just now",
- )
- end
- end
+ expect(page).to have_selector(".small-action-contents", text: "Removed @#{group.name} just now")
end
end
diff --git a/spec/system/post_stream_spec.rb b/spec/system/post_stream_spec.rb
index f96ed99e257..1d0291d03ce 100644
--- a/spec/system/post_stream_spec.rb
+++ b/spec/system/post_stream_spec.rb
@@ -4,57 +4,51 @@ describe "Post stream", type: :system do
fab!(:user)
fab!(:admin)
- %w[enabled disabled].each do |value|
- before { SiteSetting.glimmer_post_stream_mode = value }
-
- context "when glimmer_post_stream_mode=#{value}" do
- context "when posting" do
- let(:topic) { Fabricate(:topic, user: user) }
- let(:post) { Fabricate(:post, topic: topic, user: user) }
-
- let(:topic_page) { PageObjects::Pages::Topic.new }
- let(:composer) { PageObjects::Components::Composer.new }
-
- before do
- SiteSetting.post_menu_hidden_items = ""
-
- sign_in(admin)
- end
-
- it "can reply to a post and edit the reply" do
- # Visit topic and initiate reply
- topic_page.visit_topic(post.topic)
- topic_page.click_post_action_button(post, :reply)
- expect(composer).to be_opened
-
- # Create initial reply
- composer.type_content("This is a reply")
- composer.submit
- expect(composer).to be_closed
-
- # Verify initial reply
- reply = Post.last
- expect(topic_page).to have_post_number(reply.post_number)
- expect(topic_page).to have_post_content(
- post_number: reply.post_number,
- content: "This is a reply",
- )
-
- # Edit the reply
- expect(topic_page).to have_post_action_button(reply, :edit)
- topic_page.click_post_action_button(reply, :edit)
- expect(composer).to be_opened
- composer.type_content("This is an edited reply")
- composer.submit
-
- # Verify edited reply
- expect(topic_page).to have_post_action_button(reply, :edit)
- expect(topic_page).to have_post_content(
- post_number: reply.post_number,
- content: "This is an edited reply",
- )
- end
- end
+ context "when posting" do
+ let(:topic) { Fabricate(:topic, user: user) }
+ let(:post) { Fabricate(:post, topic: topic, user: user) }
+
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+ let(:composer) { PageObjects::Components::Composer.new }
+
+ before do
+ SiteSetting.post_menu_hidden_items = ""
+
+ sign_in(admin)
+ end
+
+ it "can reply to a post and edit the reply" do
+ # Visit topic and initiate reply
+ topic_page.visit_topic(post.topic)
+ topic_page.click_post_action_button(post, :reply)
+ expect(composer).to be_opened
+
+ # Create initial reply
+ composer.type_content("This is a reply")
+ composer.submit
+ expect(composer).to be_closed
+
+ # Verify initial reply
+ reply = Post.last
+ expect(topic_page).to have_post_number(reply.post_number)
+ expect(topic_page).to have_post_content(
+ post_number: reply.post_number,
+ content: "This is a reply",
+ )
+
+ # Edit the reply
+ expect(topic_page).to have_post_action_button(reply, :edit)
+ topic_page.click_post_action_button(reply, :edit)
+ expect(composer).to be_opened
+ composer.type_content("This is an edited reply")
+ composer.submit
+
+ # Verify edited reply
+ expect(topic_page).to have_post_action_button(reply, :edit)
+ expect(topic_page).to have_post_content(
+ post_number: reply.post_number,
+ content: "This is an edited reply",
+ )
end
end
@@ -62,10 +56,7 @@ describe "Post stream", type: :system do
let!(:topic) { Fabricate(:topic) }
let!(:posts) { Fabricate.times(20, :post, topic: topic) }
- before do
- sign_in(user)
- SiteSetting.glimmer_post_stream_mode = "enabled"
- end
+ before { sign_in(user) }
it "cloaks posts that are far from the viewport" do
# Visit the topic page
diff --git a/spec/system/table_builder_spec.rb b/spec/system/table_builder_spec.rb
index 9d6de82120a..09172d0874f 100644
--- a/spec/system/table_builder_spec.rb
+++ b/spec/system/table_builder_spec.rb
@@ -28,23 +28,19 @@ describe "Table Builder", type: :system do
content.strip.gsub(/\s+/, " ").gsub(/\r\n/, "\n")
end
- %w[enabled disabled].each do |value|
- before { SiteSetting.glimmer_post_stream_mode = value }
-
- context "when glimmer_post_stream_mode=#{value}" do
- context "when creating a new table" do
- it "should add table items created in spreadsheet to composer input" do
- visit("/latest")
- page.find("#create-topic").click
- find(".toolbar-menu__options-trigger").click
- page.find("button[data-name='toggle-spreadsheet']").click
- insert_table_modal.type_in_cell(0, 0, "Item 1")
- insert_table_modal.type_in_cell(0, 1, "Item 2")
- insert_table_modal.type_in_cell(0, 2, "Item 3")
- insert_table_modal.type_in_cell(0, 3, "Item 4")
- insert_table_modal.click_insert_table
-
- created_table = <<~TABLE
+ context "when creating a new table" do
+ it "should add table items created in spreadsheet to composer input" do
+ visit("/latest")
+ page.find("#create-topic").click
+ find(".toolbar-menu__options-trigger").click
+ page.find("button[data-name='toggle-spreadsheet']").click
+ insert_table_modal.type_in_cell(0, 0, "Item 1")
+ insert_table_modal.type_in_cell(0, 1, "Item 2")
+ insert_table_modal.type_in_cell(0, 2, "Item 3")
+ insert_table_modal.type_in_cell(0, 3, "Item 4")
+ insert_table_modal.click_insert_table
+
+ created_table = <<~TABLE
|Column 1 | Column 2 | Column 3 | Column 4|
|--- | --- | --- | ---|
|Item 1 | Item 2 | Item 3 | Item 4|
@@ -55,60 +51,58 @@ describe "Table Builder", type: :system do
| | | | |
TABLE
- expect(normalize_value(composer.composer_input.value)).to eq(
- normalize_value(created_table),
- )
- end
+ expect(normalize_value(composer.composer_input.value)).to eq(normalize_value(created_table))
+ end
- context "when cancelling table creation" do
- it "should close the modal if there are no changes made" do
- visit("/latest")
- page.find("#create-topic").click
- find(".toolbar-menu__options-trigger").click
- page.find("button[data-name='toggle-spreadsheet']").click
- insert_table_modal.cancel
- expect(page).to have_no_css(".insert-table-modal")
- end
-
- it "should show a warning popup if there are unsaved changes" do
- visit("/latest")
- page.find("#create-topic").click
- find(".toolbar-menu__options-trigger").click
- page.find("button[data-name='toggle-spreadsheet']").click
- insert_table_modal.type_in_cell(0, 0, "Item 1")
- insert_table_modal.cancel
- expect(page).to have_css(".dialog-container .dialog-content")
- end
- end
+ context "when cancelling table creation" do
+ it "should close the modal if there are no changes made" do
+ visit("/latest")
+ page.find("#create-topic").click
+ find(".toolbar-menu__options-trigger").click
+ page.find("button[data-name='toggle-spreadsheet']").click
+ insert_table_modal.cancel
+ expect(page).to have_no_css(".insert-table-modal")
end
- context "when editing a table" do
- it "should prefill the spreadsheet with the markdown table items from the post" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
-
- expected_table_content = [
- %w[Toyota Supra 1998],
- %w[Nissan Skyline 1999],
- %w[Honda S2000 2001],
- ]
-
- expected_table_content.each_with_index do |row, row_index|
- row.each_with_index do |content, col_index|
- expect(insert_table_modal).to have_content_in_cell(row_index, col_index, content)
- end
- end
+ it "should show a warning popup if there are unsaved changes" do
+ visit("/latest")
+ page.find("#create-topic").click
+ find(".toolbar-menu__options-trigger").click
+ page.find("button[data-name='toggle-spreadsheet']").click
+ insert_table_modal.type_in_cell(0, 0, "Item 1")
+ insert_table_modal.cancel
+ expect(page).to have_css(".dialog-container .dialog-content")
+ end
+ end
+ end
+
+ context "when editing a table" do
+ it "should prefill the spreadsheet with the markdown table items from the post" do
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+
+ expected_table_content = [
+ %w[Toyota Supra 1998],
+ %w[Nissan Skyline 1999],
+ %w[Honda S2000 2001],
+ ]
+
+ expected_table_content.each_with_index do |row, row_index|
+ row.each_with_index do |content, col_index|
+ expect(insert_table_modal).to have_content_in_cell(row_index, col_index, content)
end
+ end
+ end
- it "should update the post with the new table content" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(1, 1, " GTR")
- insert_table_modal.click_insert_table
+ it "should update the post with the new table content" do
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+ insert_table_modal.type_in_cell(1, 1, " GTR")
+ insert_table_modal.click_insert_table
- updated_post = <<~RAW
+ updated_post = <<~RAW
|Make | Model | Year|
|--- | --- | ---|
|Toyota | Supra | 1998|
@@ -116,73 +110,71 @@ describe "Table Builder", type: :system do
|Honda | S2000 | 2001|
RAW
- expect(normalize_value(post1.reload.raw)).to eq(normalize_value(updated_post))
- end
+ expect(normalize_value(post1.reload.raw)).to eq(normalize_value(updated_post))
+ end
- it "should respect the original empty header" do
- topic_page.visit_topic(topic2)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(0, 0, " updated")
- insert_table_modal.click_insert_table
+ it "should respect the original empty header" do
+ topic_page.visit_topic(topic2)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+ insert_table_modal.type_in_cell(0, 0, " updated")
+ insert_table_modal.click_insert_table
- updated_post = <<~RAW
+ updated_post = <<~RAW
| | | |
|--- | --- | ---|
|Some updated | content | here|
|1 | 2 | 3|
RAW
- expect(normalize_value(post2.reload.raw)).to eq(normalize_value(updated_post))
- end
-
- context "when adding an edit reason" do
- it "should add the edit reason to the edit history" do
- edit_reason = "Updated Nissan model"
-
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(1, 1, " GTR")
- insert_table_modal.click_edit_reason
- insert_table_modal.type_edit_reason(edit_reason)
- insert_table_modal.click_insert_table
- wait_for { post1.reload.edit_reason == edit_reason }
- expect(post1.reload.edit_reason).to eq(edit_reason)
- end
- end
+ expect(normalize_value(post2.reload.raw)).to eq(normalize_value(updated_post))
+ end
- context "when cancelling table creation" do
- it "should close the modal if there are no changes made" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.cancel
- expect(page).to have_no_css(".insert-table-modal")
- end
-
- it "should show a warning popup if there are unsaved changes" do
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- expect(page).to have_selector(".insert-table-modal")
- insert_table_modal.type_in_cell(1, 1, " GTR")
- insert_table_modal.cancel
- expect(page).to have_css(".dialog-container .dialog-content")
- end
- end
+ context "when adding an edit reason" do
+ it "should add the edit reason to the edit history" do
+ edit_reason = "Updated Nissan model"
+
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+ insert_table_modal.type_in_cell(1, 1, " GTR")
+ insert_table_modal.click_edit_reason
+ insert_table_modal.type_edit_reason(edit_reason)
+ insert_table_modal.click_insert_table
+ wait_for { post1.reload.edit_reason == edit_reason }
+ expect(post1.reload.edit_reason).to eq(edit_reason)
+ end
+ end
- it "should not accept default Discourse keyboard shortcuts" do
- # Some default keyboard shortcuts like Shift + S bring up a modal overriding
- # the table builder modal and therefore should not be accepted
+ context "when cancelling table creation" do
+ it "should close the modal if there are no changes made" do
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+ insert_table_modal.cancel
+ expect(page).to have_no_css(".insert-table-modal")
+ end
- topic_page.visit_topic(topic)
- topic_page.find(".btn-edit-table", visible: :all).click
- insert_table_modal.find_cell(0, 0)
- insert_table_modal.send_keys(:shift, "s")
- expect(page).to have_css(".insert-table-modal")
- expect(page).to have_no_css(".share-topic-modal")
- end
+ it "should show a warning popup if there are unsaved changes" do
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ expect(page).to have_selector(".insert-table-modal")
+ insert_table_modal.type_in_cell(1, 1, " GTR")
+ insert_table_modal.cancel
+ expect(page).to have_css(".dialog-container .dialog-content")
end
end
+
+ it "should not accept default Discourse keyboard shortcuts" do
+ # Some default keyboard shortcuts like Shift + S bring up a modal overriding
+ # the table builder modal and therefore should not be accepted
+
+ topic_page.visit_topic(topic)
+ topic_page.find(".btn-edit-table", visible: :all).click
+ insert_table_modal.find_cell(0, 0)
+ insert_table_modal.send_keys(:shift, "s")
+ expect(page).to have_css(".insert-table-modal")
+ expect(page).to have_no_css(".share-topic-modal")
+ end
end
end