Skip to content

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

DEV: Support topic template category and tag options (#41197)

Natalie Tay500ca0bdb3ee
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/connectors/topic-above-posts/discourse-templates-button.gjs b/plugins/discourse-templates/assets/javascripts/discourse/connectors/topic-above-posts/discourse-templates-button.gjs
index 133cb1fab37..4ee93a87471 100644
--- a/plugins/discourse-templates/assets/javascripts/discourse/connectors/topic-above-posts/discourse-templates-button.gjs
+++ b/plugins/discourse-templates/assets/javascripts/discourse/connectors/topic-above-posts/discourse-templates-button.gjs
@@ -4,9 +4,14 @@ import { action } from "@ember/object";
import { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
import discourseDebounce from "discourse/lib/debounce";
+import Category from "discourse/models/category";
import DButton from "discourse/ui-kit/d-button";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+const TEMPLATE_OPTIONS_START_REGEX = /^\s*<!--\s*discourse-template\s*/i;
+const TEMPLATE_OPTIONS_BODY_SEPARATOR_REGEX = /^([ \t]*\r?\n){1,2}/;
+const TEMPLATE_OPTIONS_MAX_LENGTH = 500;
+
export default class DiscourseTemplatesButton extends Component {
static shouldRender(outletArgs, helper) {
return outletArgs.model.is_template && helper.currentUser?.can_create_topic;
@@ -21,11 +26,68 @@ export default class DiscourseTemplatesButton extends Component {
return await ajax(`/raw/${topic.id}/1`, { dataType: "text" });
}
+ parseTemplateOptions(raw) {
+ const header = raw.slice(0, TEMPLATE_OPTIONS_MAX_LENGTH);
+ const startMatch = header.match(TEMPLATE_OPTIONS_START_REGEX);
+
+ if (!startMatch) {
+ return { body: raw };
+ }
+
+ const headerEnd = header.indexOf("-->", startMatch[0].length);
+
+ if (headerEnd === -1) {
+ return { body: raw };
+ }
+
+ const options = {};
+ raw
+ .slice(startMatch[0].length, headerEnd)
+ .split("\n")
+ .forEach((line) => {
+ const [, key, value] = line.match(/^\s*([\w-]+)\s*:\s*(.*?)\s*$/) || [];
+
+ if (key && value) {
+ options[key] = value;
+ }
+ });
+
+ return {
+ body: raw
+ .slice(headerEnd + 3)
+ .replace(TEMPLATE_OPTIONS_BODY_SEPARATOR_REGEX, ""),
+ categorySlug: options.category,
+ tags: options.tags
+ ?.split(",")
+ .map((tag) => tag.trim())
+ .filter(Boolean)
+ .join(","),
+ };
+ }
+
+ async findCategory(categorySlug) {
+ if (!categorySlug) {
+ return null;
+ }
+
+ const slugPath = categorySlug.split(/[/:]/).filter(Boolean);
+
+ const category =
+ Category.findBySlugPath(slugPath) ||
+ (await Category.asyncFindBySlugPath(slugPath).catch(() => null));
+
+ return category?.canCreateTopic ? category : null;
+ }
+
@action
async createNewTopic() {
- const text = await this.fetchRaw();
+ const template = this.parseTemplateOptions(await this.fetchRaw());
+ const category = await this.findCategory(template.categorySlug);
+
this.composer.openNewTopic({
- body: text,
+ body: template.body,
+ category,
+ tags: template.tags,
});
}
diff --git a/plugins/discourse-templates/test/javascripts/acceptance/templates-test.js b/plugins/discourse-templates/test/javascripts/acceptance/templates-test.js
index da033c9adcb..ab0592e9155 100644
--- a/plugins/discourse-templates/test/javascripts/acceptance/templates-test.js
+++ b/plugins/discourse-templates/test/javascripts/acceptance/templates-test.js
@@ -8,6 +8,8 @@ import {
} from "@ember/test-helpers";
import { test } from "qunit";
import { cloneJSON } from "discourse/lib/object";
+import Category from "discourse/models/category";
+import PermissionType from "discourse/models/permission-type";
import { PLATFORM_KEY_MODIFIER } from "discourse/services/keyboard-shortcuts";
import topicFixtures from "discourse/tests/fixtures/topic";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
@@ -427,9 +429,18 @@ acceptance("keyboard shortcut", function (needs) {
});
acceptance("buttons on topics", function (needs) {
+ let templateBody;
+ let templateCategory;
+
needs.user();
+ needs.site({ can_tag_topics: true });
needs.settings({
allow_uncategorized_topics: true,
+ tagging_enabled: true,
+ });
+ needs.hooks.beforeEach(() => {
+ templateBody = "post raw content";
+ templateCategory = "dev";
});
needs.pretender((server, helper) => {
@@ -437,13 +448,101 @@ acceptance("buttons on topics", function (needs) {
topicResponse.is_template = true;
server.get("/t/280.json", () => helper.response(topicResponse));
- server.get("/raw/280/1", () => [200, {}, "post raw content"]);
+ server.get("/raw/280/1", () => [
+ 200,
+ {},
+ `<!-- discourse-template
+category: ${templateCategory}
+tags: security, minor-security-fix
+-->
+
+${templateBody}`,
+ ]);
});
test("Can open composer using button on topic", async function (assert) {
await visit("/t/280");
await click(".template-new-topic");
- assert.dom("textarea.d-editor-input").hasValue("post raw content");
+ assert
+ .dom("textarea.d-editor-input")
+ .hasValue("post raw content", "uses the raw template content");
+
+ const categoryChooser = selectKit(".category-chooser");
+ assert.strictEqual(
+ categoryChooser.header().value(),
+ "7",
+ "selects the category from the template options"
+ );
+
+ const tags = selectKit(".mini-tag-chooser");
+ assert.strictEqual(
+ tags.header().value(),
+ "security,minor-security-fix",
+ "selects the tags from the template options"
+ );
+ });
+
+ test("Does not select a category the user cannot create topics in", async function (assert) {
+ Category.findById(7).set("permission", PermissionType.READONLY);
+
+ await visit("/t/280");
+
+ await click(".template-new-topic");
+
+ const categoryChooser = selectKit(".category-chooser");
+ assert.notStrictEqual(
+ categoryChooser.header().value(),
+ "7",
+ "does not select the category from the template options"
+ );
+
+ const tags = selectKit(".mini-tag-chooser");
+ assert.strictEqual(
+ tags.header().value(),
+ "security,minor-security-fix",
+ "still selects allowed tags from the template options"
+ );
+ });
+
+ test("Ignores an invalid category in template options", async function (assert) {
+ templateCategory = "not-a-real-category";
+
+ await visit("/t/280");
+
+ await click(".template-new-topic");
+
+ assert
+ .dom("textarea.d-editor-input")
+ .hasValue("post raw content", "still opens the composer");
+
+ const categoryChooser = selectKit(".category-chooser");
+ assert.notStrictEqual(
+ categoryChooser.header().value(),
+ "7",
+ "does not select the invalid category"
+ );
+
+ const tags = selectKit(".mini-tag-chooser");
+ assert.strictEqual(
+ tags.header().value(),
+ "security,minor-security-fix",
+ "still selects tags from the template options"
+ );
+ });
+
+ test("Preserves body indentation after template options", async function (assert) {
+ templateBody = " indented raw content";
+
+ await visit("/t/280");
+
+ await click(".template-new-topic");
+
+ assert
+ .dom("textarea.d-editor-input")
+ .hasValue(
+ " indented raw content",
+ "preserves intentional leading indentation"
+ );
});
});