Skip to content

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

FEATURE: add API for custom composer actions, new "event" composer action (#40203)

Krisad87713821e9
diff --git a/app/serializers/category_serializer.rb b/app/serializers/category_serializer.rb
index 2c055433291..c57717288d6 100644
--- a/app/serializers/category_serializer.rb
+++ b/app/serializers/category_serializer.rb
@@ -43,7 +43,6 @@ class CategorySerializer < SiteCategorySerializer
:style_type,
:emoji,
:icon,
- :category_types,
:category_type_settings,
:available_category_types
@@ -162,14 +161,6 @@ class CategorySerializer < SiteCategorySerializer
category_description
end
- def include_category_types?
- can_edit_category?
- end
-
- def category_types
- object.category_types
- end
-
def include_category_type_settings?
can_edit_category?
end
diff --git a/app/serializers/site_category_serializer.rb b/app/serializers/site_category_serializer.rb
index b9ed6e093b2..77dbcce878e 100644
--- a/app/serializers/site_category_serializer.rb
+++ b/app/serializers/site_category_serializer.rb
@@ -5,7 +5,8 @@ class SiteCategorySerializer < BasicCategorySerializer
:allowed_tag_groups,
:allow_global_tags,
:read_only_banner,
- :form_template_ids
+ :form_template_ids,
+ :category_types
has_many :category_required_tag_groups, key: :required_tag_groups, embed: :objects
@@ -13,6 +14,11 @@ class SiteCategorySerializer < BasicCategorySerializer
object.form_template_ids.sort
end
+ def category_types
+ return {} if !SiteSetting.enable_simplified_category_creation
+ object.category_types
+ end
+
def include_allowed_tags?
SiteSetting.tagging_enabled
end
diff --git a/app/services/categories/configure.rb b/app/services/categories/configure.rb
index 5a792c98f03..d4a7218cc07 100644
--- a/app/services/categories/configure.rb
+++ b/app/services/categories/configure.rb
@@ -35,6 +35,7 @@ module Categories
step :log_action
step :clear_category_type_counts_cache
+ step :clear_site_cache
private
@@ -84,5 +85,11 @@ module Categories
def clear_category_type_counts_cache
Discourse.cache.delete(Categories::TypeRegistry::COUNTS_CACHE_KEY)
end
+
+ # The cached `site.json` carries `category_types`
+ # clearing cache makes type changes apply immediately on change
+ def clear_site_cache
+ Site.clear_cache
+ end
end
end
diff --git a/app/services/categories/unconfigure.rb b/app/services/categories/unconfigure.rb
index ab3e992d1bd..ed9407c3e03 100644
--- a/app/services/categories/unconfigure.rb
+++ b/app/services/categories/unconfigure.rb
@@ -27,6 +27,7 @@ module Categories
step :unconfigure_category
step :log_action
step :clear_category_type_counts_cache
+ step :clear_site_cache
private
@@ -56,5 +57,9 @@ module Categories
def clear_category_type_counts_cache
Discourse.cache.delete(Categories::TypeRegistry::COUNTS_CACHE_KEY)
end
+
+ def clear_site_cache
+ Site.clear_cache
+ end
end
end
diff --git a/frontend/discourse/app/components/composer-editor.gjs b/frontend/discourse/app/components/composer-editor.gjs
index 39f3e3db501..299bb53770a 100644
--- a/frontend/discourse/app/components/composer-editor.gjs
+++ b/frontend/discourse/app/components/composer-editor.gjs
@@ -959,6 +959,11 @@ export default class ComposerEditor extends Component {
});
}
+ @action
+ replyChanged() {
+ this.appEvents.trigger("composer:reply-changed", this.composer.model);
+ }
+
@action
previewUpdated(preview, helper) {
this._renderMentions(preview);
@@ -1141,6 +1146,7 @@ export default class ComposerEditor extends Component {
{{else}}
<DEditor
@value={{this.composer.model.reply}}
+ @change={{this.replyChanged}}
@placeholder={{this.replyPlaceholder}}
@previewUpdated={{this.previewUpdated}}
@markdownOptions={{this.markdownOptions}}
diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjs
index 11580208537..bc3e57a6fe5 100644
--- a/frontend/discourse/app/lib/plugin-api.gjs
+++ b/frontend/discourse/app/lib/plugin-api.gjs
@@ -128,6 +128,7 @@ import {
} from "discourse/models/user";
import { preventCloaking } from "discourse/modifiers/post-stream-viewport-tracker";
import { setNotificationsLimit } from "discourse/routes/user-notifications";
+import { registerComposerAction } from "discourse/select-kit/components/composer-actions";
import { CUSTOM_USER_SEARCH_OPTIONS } from "discourse/select-kit/components/user-chooser";
import { modifySelectKit } from "discourse/select-kit/lib/plugin-api";
import { addComposerSaveErrorCallback } from "discourse/services/composer";
@@ -909,6 +910,33 @@ class _PluginApi {
this.addComposerToolbarPopupMenuOption(opts);
}
+ /**
+ * Register a custom item in the composer-actions dropdown (the menu next
+ * to the composer title that switches between Reply, Create Topic, etc.).
+ *
+ * @param {Object} opts
+ * @param {string} opts.id - Unique identifier for the item.
+ * @param {string} opts.label - I18n key for the item's display name.
+ * @param {string} [opts.description] - Optional I18n key for the item's description text.
+ * @param {string} [opts.icon] - Optional icon name.
+ * @param {Function} [opts.condition] - `(composerActionsComponent) => boolean`. Item is shown when this returns truthy, or when omitted.
+ * @param {Function} opts.action - `(composerModel, composerActionsComponent) => void`. Called when the user picks the item.
+ *
+ * @example
+ * api.addComposerAction({
+ * id: "create_event",
+ * label: "discourse_post_event.composer_actions.create_event.label",
+ * description: "discourse_post_event.composer_actions.create_event.desc",
+ * icon: "calendar-days",
+ * condition: (component) =>
+ * component.composerModel?.category?.isType("events"),
+ * action: (composerModel) => composerModel.set("creatingEvent", true),
+ * });
+ */
+ addComposerAction(opts) {
+ registerComposerAction(opts);
+ }
+
/**
* Called whenever the "page" changes. This allows us to set up analytics
* and other tracking.
@@ -2435,6 +2463,12 @@ class _PluginApi {
* Support for customizing the composer text. By providing a callback. Callbacks should
* return `null` or `undefined` if you don't need a customization based on the current state.
*
+ * Supported callback keys: `actionTitle`, `saveLabel`, `saveIcon`,
+ * `titlePlaceholder`. Each callback receives the composer model and
+ * returns an i18n key (or a translated string for `actionTitle`, or an
+ * icon name for `saveIcon`). Return `null` or `undefined` to fall
+ * through to the default.
+ *
* ```
* api.customizeComposerText({
* actionTitle(model) {
@@ -2445,6 +2479,12 @@ class _PluginApi {
*
* saveLabel(model) {
* return "my.custom_save_label_key";
+ * },
+ *
+ * titlePlaceholder(model) {
+ * if (model.creatingEvent) {
+ * return "my.event_title_placeholder";
+ * }
* }
* })
*
diff --git a/frontend/discourse/app/models/composer.js b/frontend/discourse/app/models/composer.js
index 5fc195033eb..7ad9c9ebcf3 100644
--- a/frontend/discourse/app/models/composer.js
+++ b/frontend/discourse/app/models/composer.js
@@ -370,12 +370,15 @@ export default class Composer extends RestModel {
this._categoryId = categoryId;
if (oldCategoryId !== categoryId) {
+ const applyTemplate = () => {
+ this.applyTopicTemplate(oldCategoryId, categoryId);
+ this.appEvents?.trigger("composer:category-changed", this);
+ };
+
if (this.site.lazy_load_categories) {
- Category.asyncFindById(categoryId).then(() => {
- this.applyTopicTemplate(oldCategoryId, categoryId);
- });
+ Category.asyncFindById(categoryId).then(applyTemplate);
} else {
- this.applyTopicTemplate(oldCategoryId, categoryId);
+ applyTemplate();
}
}
}
@@ -525,8 +528,12 @@ export default class Composer extends RestModel {
);
}
- @computed("canEditTopicFeaturedLink")
+ @computed("canEditTopicFeaturedLink", "category")
get titlePlaceholder() {
+ const custom = this.customizationFor("titlePlaceholder");
+ if (custom) {
+ return custom;
+ }
return this.canEditTopicFeaturedLink
? "composer.title_or_link_placeholder"
: "composer.title_placeholder";
diff --git a/frontend/discourse/app/services/composer.js b/frontend/discourse/app/services/composer.js
index d64fe70c634..14a67185f25 100644
--- a/frontend/discourse/app/services/composer.js
+++ b/frontend/discourse/app/services/composer.js
@@ -440,7 +440,12 @@ export default class ComposerService extends Service {
);
}
- @computed("model.action", "isWhispering", "model.privateMessage")
+ @computed(
+ "model.action",
+ "isWhispering",
+ "model.privateMessage",
+ "model.category"
+ )
get saveIcon() {
if (this.isWhispering) {
return "far-eye-slash";
@@ -449,6 +454,11 @@ export default class ComposerService extends Service {
return "envelope";
}
+ const custom = this.model?.customizationFor("saveIcon");
+ if (custom) {
+ return custom;
+ }
+
return SAVE_ICONS[this.model?.action];
}
diff --git a/frontend/discourse/select-kit/components/composer-actions.js b/frontend/discourse/select-kit/components/composer-actions.js
index 892a638c030..a9ddccf9a75 100644
--- a/frontend/discourse/select-kit/components/composer-actions.js
+++ b/frontend/discourse/select-kit/components/composer-actions.js
@@ -27,6 +27,18 @@ export function _clearSnapshots() {
_actionSnapshot = null;
}
+let _registeredActions = [];
+let _warnedConditionIds = new Set();
+
+export function registerComposerAction(opts) {
+ _registeredActions.push(opts);
+}
+
+export function _clearRegisteredActions() {
+ _registeredActions = [];
+ _warnedConditionIds = new Set();
+}
+
@classNames("composer-actions")
@pluginApiIdentifiers(["composer-actions"])
@selectKitOptions({
@@ -114,7 +126,7 @@ export default class ComposerActions extends DropdownSelectBoxComponent {
return {};
}
- @computed("seq")
+ @computed("seq", "composerModel.categoryId", "composerModel.category")
get content() {
let items = [];
@@ -269,6 +281,34 @@ export default class ComposerActions extends DropdownSelectBoxComponent {
});
}
+ _registeredActions.forEach((opts) => {
+ let visible = true;
+ if (opts.condition) {
+ try {
+ visible = !!opts.condition(this);
+ } catch (e) {
+ if (!_warnedConditionIds.has(opts.id)) {
+ _warnedConditionIds.add(opts.id);
+ // eslint-disable-next-line no-console
+ console.error(
+ `composer-actions: condition for "${opts.id}" threw`,
+ e
+ );
+ }
+ visible = false;
+ }
+ }
+ if (!visible) {
+ return;
+ }
+ items.push({
+ id: opts.id,
+ name: i18n(opts.label),
+ description: opts.description ? i18n(opts.description) : undefined,
+ icon: opts.icon,
+ });
+ });
+
return items;
}
@@ -410,6 +450,13 @@ export default class ComposerActions extends DropdownSelectBoxComponent {
@action
onChange(value) {
+ const registered = _registeredActions.find((a) => a.id === value);
+ if (registered) {
+ registered.action(this.composerModel, this);
+ this.contentChanged();
+ return;
+ }
+
const composerAction = `${camelize(value)}Selected`;
if (this[composerAction]) {
this[composerAction](
diff --git a/frontend/discourse/tests/acceptance/composer-actions-test.js b/frontend/discourse/tests/acceptance/composer-actions-test.js
index 27f5b964962..bb1607fc4a3 100644
--- a/frontend/discourse/tests/acceptance/composer-actions-test.js
+++ b/frontend/discourse/tests/acceptance/composer-actions-test.js
@@ -3,6 +3,10 @@ import { test } from "qunit";
import sinon from "sinon";
import { cloneJSON } from "discourse/lib/object";
import Draft from "discourse/models/draft";
+import {
+ _clearRegisteredActions,
+ registerComposerAction,
+} from "discourse/select-kit/components/composer-actions";
import discoveryFixtures from "discourse/tests/fixtures/discovery-fixtures";
import userFixtures from "discourse/tests/fixtures/user-fixtures";
import {
@@ -559,3 +563,108 @@ acceptance(`Prioritizing Name fall back`, function (needs) {
);
});
});
+
+acceptance(`Composer Actions - plugin registration`, function (needs) {
+ needs.user();
+
+ let lastInvocation;
+ let showCustomAction;
+
+ needs.hooks.beforeEach(function () {
+ lastInvocation = null;
+ showCustomAction = true;
+ registerComposerAction({
+ id: "my_plugin_action",
+ label: "composer.composer_actions.create_topic.label",
+ description: "composer.composer_actions.create_topic.desc",
+ icon: "wand-magic-sparkles",
+ condition: () => showCustomAction,
+ action: (composer, component) => {
+ lastInvocation = { composer, component };
+ },
+ });
+ });
+
+ needs.hooks.afterEach(function () {
+ _clearRegisteredActions();
+ });
+
+ test("registered action appears in dropdown when condition is true", 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
+ .dom(`.composer-actions li[data-value="my_plugin_action"]`)
+ .exists("the registered action is rendered");
+ });
+
+ test("registered action is hidden when condition is false", async function (assert) {
+ showCustomAction = false;
+ const composerActions = selectKit(".composer-actions");
+
+ await visit("/t/internationalization-localization/280");
+ await click("article#post_3 button.reply");
+ await composerActions.expand();
+
+ assert
+ .dom(`.composer-actions li[data-value="my_plugin_action"]`)
+ .doesNotExist("the registered action is not rendered");
+ });
+
+ test("selecting the registered action invokes its callback", async function (assert) {
+ const composerActions = selectKit(".composer-actions");
+
+ await visit("/t/internationalization-localization/280");
+ await click("article#post_3 button.reply");
+ await composerActions.expand();
+ await composerActions.selectRowByValue("my_plugin_action");
+
+ assert.true(!!lastInvocation, "the registered action callback was invoked");
+ assert.strictEqual(
+ lastInvocation.composer.constructor.name,
+ "Composer",
+ "the callback receives the composer model"
+ );
+ });
+
+ test("a throwing condition logs an error once and hides the item", async function (assert) {
+ registerComposerAction({
+ id: "broken_action",
+ label: "composer.composer_actions.create_topic.label",
+ condition: () => {
+ throw new Error("boom");
+ },
+ action: () => {},
+ });
+
+ const errorStub = sinon.stub(console, "error");
+ try {
+ const composerActions = selectKit(".composer-actions");
+
+ await visit("/t/internationalization-localization/280");
+ await click("article#post_3 button.reply");
+ await composerActions.expand();
+ await composerActions.collapse();
+ await composerActions.expand();
+ await composerActions.collapse();
+ await composerActions.expand();
+
+ assert
+ .dom(`.composer-actions .select-kit-row[data-value="broken_action"]`)
+ .doesNotExist("broken action is hidden");
+ const calls = errorStub
+ .getCalls()
+ .filter((c) => String(c.args[0]).includes("broken_action"));
+ assert.strictEqual(
+ calls.length,
+ 1,
+ "console.error fired exactly once across multiple dropdown opens"
+ );
+ } finally {
+ errorStub.restore();
+ }
+ });
+});
diff --git a/frontend/discourse/tests/integration/components/composer-editor-test.gjs b/frontend/discourse/tests/integration/components/composer-editor-test.gjs
index 14f0da31cf4..962504ac2f7 100644
--- a/frontend/discourse/tests/integration/components/composer-editor-test.gjs
+++ b/frontend/discourse/tests/integration/components/composer-editor-test.gjs
@@ -49,6 +49,17 @@ module("Integration | Component | ComposerEditor", function (hooks) {
await fillIn("textarea", "@user-no @user-ok @user-nope");
});
+ test("fires composer:reply-changed on user input", async function (assert) {
+ const appEvents = this.owner.lookup("service:app-events");
+ let fired = false;
+ appEvents.on("composer:reply-changed", () => (fired = true));
+
+ await render(<template><ComposerEditor /></template>);
+ await fillIn(".d-editor-input", "hello");
+
+ assert.true(fired, "fires when the reply text changes");
+ });
+
test("preview sanitizes HTML", async function (assert) {
await render(<template><ComposerEditor /></template>);
diff --git a/frontend/discourse/tests/unit/models/composer-test.js b/frontend/discourse/tests/unit/models/composer-test.js
index 1895d2ad1b6..41102abb663 100644
--- a/frontend/discourse/tests/unit/models/composer-test.js
+++ b/frontend/discourse/tests/unit/models/composer-test.js
@@ -135,6 +135,25 @@ module("Unit | Model | composer", function (hooks) {
);
});
+ test("fires composer:category-changed when the category changes", function (assert) {
+ const composer = createComposer.call(this, { action: CREATE_TOPIC });
+ const appEvents = getOwner(this).lookup("service:app-events");
+
+ let firedWith;
+ appEvents.on("composer:category-changed", (model) => (firedWith = model));
+
+ composer.set("categoryId", 12345);
+ assert.strictEqual(firedWith, composer, "fires with the composer model");
+
+ firedWith = undefined;
+ composer.set("categoryId", 12345);
+ assert.strictEqual(
+ firedWith,
+ undefined,
+ "does not fire when the category is unchanged"
+ );
+ });
+
test("missingTitleCharacters", function (assert) {
const missingTitleCharacters = (val, isPM, expected, message) => {
const composer = createComposer.call(this, {
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/initializers/add-create-event-composer-action.js b/plugins/discourse-calendar/assets/javascripts/discourse/initializers/add-create-event-composer-action.js
new file mode 100644
index 00000000000..0aad5de8016
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/initializers/add-create-event-composer-action.js
@@ -0,0 +1,71 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+import I18n, { i18n } from "discourse-i18n";
+
+const EVENT_ICON = "calendar-day";
+
+function initializeCreateEventComposerAction(api, eventComposer) {
+ api.addComposerAction({
+ id: "create_event",
+ label: "discourse_post_event.composer_actions.create_event.label",
+ description: "discourse_post_event.composer_actions.create_event.desc",
+ icon: EVENT_ICON,
+ condition: (component) => {
+ const composer = component.composerModel;
+ return eventComposer.eligible(composer) && !composer.creatingEvent;
+ },
+ action: (composer) => eventComposer.enterEventMode(composer),
+ });
+
+ api.addComposerAction({
+ id: "create_regular_topic",
+ label: "discourse_post_event.composer_actions.create_topic.label",
+ description: "discourse_post_event.composer_actions.create_topic.desc",
+ icon: "plus",
+ condition: (component) => {
+ const composer = component.composerModel;
+ return eventComposer.eligible(composer) && composer.creatingEvent;
+ },
+ action: (composer) => eventComposer.exitEventMode(composer),
+ });
+
+ api.customizeComposerText({
+ actionTitle(model) {
+ if (!model.creatingEvent) {
+ return;
+ }
+ const key = "discourse_post_event.composer.action_title";
+ if (I18n.lookup(key) !== undefined) {
+ return i18n(key);
+ }
+ },
+ saveLabel(model) {
+ if (model.creatingEvent) {
+ return "discourse_post_event.composer.create_event_button";
+ }
+ },
+ saveIcon(model) {
+ if (model.creatingEvent) {
+ return EVENT_ICON;
+ }
+ },
+ titlePlaceholder(model) {
+ if (model.creatingEvent) {
+ return "discourse_post_event.composer.event_title_placeholder";
+ }
+ },
+ });
+}
+
+export default {
+ name: "add-create-event-composer-action",
+ initialize(container) {
+ const siteSettings = container.lookup("service:site-settings");
+ if (!siteSettings.discourse_post_event_enabled) {
+ return;
+ }
+ const eventComposer = container.lookup("service:create-event-composer");
+ withPluginApi((api) =>
+ initializeCreateEventComposerAction(api, eventComposer)
+ );
+ },
+};
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js b/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js
index a3c9e1373d9..2c9c896adf6 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js
@@ -381,3 +381,12 @@ export function camelCase(input) {
export function removeEvent(raw) {
return raw.replace(/\[event (.*?)\](.*?)\[\/event\]/s, "");
}
+
+export function buildEventSkeleton(currentUser) {
+ const timezone = currentUser?.user_option?.timezone || moment.tz.guess();
+ const startsAt = moment.tz(moment(), timezone).startOf("hour").add(1, "hour");
+ const endsAt = startsAt.clone().add(1, "hour");
+ const reminder = defaultReminderFor({ startsAt, endsAt, allDay: false });
+ const defaults = `start="${startsAt.format("YYYY-MM-DD HH:mm")}" end="${endsAt.format("YYYY-MM-DD HH:mm")}" status="public" timezone="${timezone}" reminders="${reminderToBBCode(reminder)}"`;
+ return `[event ${defaults}]\n[/event]`;
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js b/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js
index 65aaa9497cb..100641f2335 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js
@@ -3,7 +3,7 @@ import { withPluginApi } from "discourse/lib/plugin-api";
import { buildBBCodeAttrs } from "discourse/lib/text";
import EventNodeView from "../components/event-node-view";
import { buildEventPreview } from "../lib/event-preview";
-import { defaultReminderFor, reminderToBBCode } from "../lib/raw-event-helper";
+import { buildEventSkeleton } from "../lib/raw-event-helper";
export const EVENT_ATTRIBUTES = {
name: { default: null },
@@ -106,28 +106,10 @@ const extension = {
inputRules: ({ utils: { convertFromMarkdown }, getContext }) => ({
match: /^\[event([^\]]*)]$/,
handler: (state, match, start, end) => {
- const currentUser = getContext().currentUser;
- const timezone = currentUser?.user_option?.timezone || moment.tz.guess();
-
const userInput = match[1].trim();
- let eventMarkdown;
-
- if (userInput) {
- eventMarkdown = `[event ${userInput}]\n[/event]`;
- } else {
- const now = moment
- .tz(moment(), timezone)
- .startOf("hour")
- .add(1, "hour");
- const endsAt = now.clone().add(1, "hour");
- const reminder = defaultReminderFor({
- startsAt: now,
- endsAt,
- allDay: false,
- });
- const defaults = `start="${now.format("YYYY-MM-DD HH:mm")}" end="${endsAt.format("YYYY-MM-DD HH:mm")}" status="public" timezone="${timezone}" reminders="${reminderToBBCode(reminder)}"`;
- eventMarkdown = `[event ${defaults}]\n[/event]`;
- }
+ const eventMarkdown = userInput
+ ? `[event ${userInput}]\n[/event]`
+ : buildEventSkeleton(getContext().currentUser);
const doc = convertFromMarkdown(eventMarkdown);
return doc.content.firstChild
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/services/create-event-composer.js b/plugins/discourse-calendar/assets/javascripts/discourse/services/create-event-composer.js
new file mode 100644
index 00000000000..5212596210f
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/services/create-event-composer.js
@@ -0,0 +1,125 @@
+import Service, { service } from "@ember/service";
+import { CREATE_TOPIC } from "discourse/models/composer";
+import { buildEventSkeleton } from "../lib/raw-event-helper";
+
+// Matches an opening `[event` BBCode tag — `[event ` (with attributes) or
+// `[event]` (bare). Used to detect when the user has added/removed the block.
+const EVENT_OPEN_TAG = /\[event(\s|\])/;
+
+// Drives the composer's "event mode" from composer appEvents.
+// State lives on the composer model. This only decides when it triggers.
+export default class CreateEventComposer extends Service {
+ @service appEvents;
+
+ constructor() {
+ super(...arguments);
+ this.appEvents.on(
+ "composer:category-changed",
+ this,
+ this.onCategoryChanged
+ );
+ this.appEvents.on("composer:reply-changed", this, this.syncEventMode);
+ this.appEvents.on("composer:reply-reloaded", this, this.syncEventMode);
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.appEvents.off(
+ "composer:category-changed",
+ this,
+ this.onCategoryChanged
+ );
+ this.appEvents.off("composer:reply-changed", this, this.syncEventMode);
+ this.appEvents.off("composer:reply-reloaded", this, this.syncEventMode);
+ }
+
+ eligible(composer) {
+ return (
+ composer?.action === CREATE_TOPIC &&
+ composer?.user?.can_create_discourse_post_event &&
+ composer?.category?.isType?.("events")
+ );
+ }
+
+ enterEventMode(composer) {
+ if (composer.creatingEvent) {
+ return;
+ }
+ composer.set("creatingEvent", true);
+ // `actionTitle`, `saveLabel`, `saveIcon` are @computed on `model.category`
+ // and don't re-fire when only `creatingEvent` changes.
+ composer.notifyPropertyChange("category");
+
+ if (EVENT_OPEN_TAG.test(composer.reply || "")) {
+ return;
+ }
+
+ const reply = (composer.reply || "").trim();
+ const template = (composer.category?.topic_template || "").trim();
+ const skeleton = buildEventSkeleton(composer.user);
+
+ if (!reply || reply === template) {
+ composer.set("reply", skeleton);
+ } else {
+ composer.appendText(skeleton, null, { new_line: true });
+ }
+ // Snapshot the exact reply we just produced so we can recognise it as
+ // "untouched" on exit. Any edit (attribute change, surrounding text)
+ // makes this comparison fail and changes are preserved.
+ composer._insertedEventReply = composer.reply;
+ }
+
+ exitEventMode(composer) {
+ if (!composer.creatingEvent) {
+ return;
+ }
+ composer.set("creatingEvent", false);
+ composer.notifyPropertyChange("category");
+
+ if (composer.reply === composer._insertedEventReply) {
+ composer.set("reply", "");
+ }
+ composer._insertedEventReply = null;
+ }
+
+ // Guards auto-enter so a restored draft without an [event] block is left alone
+ maybeAutoEnterEventMode(composer) {
+ if (composer.creatingEvent || !this.eligible(composer)) {
+ return;
+ }
+ const reply = (composer.reply || "").trim();
+ const template = (composer.category?.topic_template || "").trim();
+ const hasEventTag = EVENT_OPEN_TAG.test(composer.reply || "");
+ if (!hasEventTag && reply && reply !== template) {
+ return;
+ }
+ this.enterEventMode(composer);
+ }
+
+ onCategoryChanged(composer) {
+ if (composer.creatingEvent && !this.eligible(composer)) {
+ this.exitEventMode(composer);
+ // The unedited skeleton blocked `applyTopicTemplate` from populating the
+ // destination category's template; now that exit has cleared it, apply
+ // the template the user would have seen had they never been in event mode.
+ composer.applyTopicTemplate(null, composer.categoryId);
+ }
+ this.maybeAutoEnterEventMode(composer);
+ }
+
+ syncEventMode(composer) {
+ const hasEventTag = EVENT_OPEN_TAG.test(composer.reply || "");
+ // Exit if the block is gone or the composer is no longer eligible — the
+ // eligibility check also clears a stale flag left on a reused model, which
+ // core's `clearState` no longer resets.
+ if (composer.creatingEvent && (!hasEventTag || !this.eligible(composer))) {
+ this.exitEventMode(composer);
+ } else if (
+ !composer.creatingEvent &&
+ hasEventTag &&
+ this.eligible(composer)
+ ) {
+ this.enterEventMode(composer);
+ }
+ }
+}
diff --git a/plugins/discourse-calendar/config/locales/client.en.yml b/plugins/discourse-calendar/config/locales/client.en.yml
index 836d03a696c..209c42b7d64 100644
--- a/plugins/discourse-calendar/config/locales/client.en.yml
+++ b/plugins/discourse-calendar/config/locales/client.en.yml
@@ -450,6 +450,9 @@ en:
other: "Max %{count} attendees"
no_rsvps_label: "Not collecting attendance"
description_placeholder: "Add event description"
+ event_title_placeholder: "Event name"
+ create_event_button: "Create event"
+ action_title: "Create a new event"
all_day: "All day"
reminder:
units:
@@ -470,6 +473,13 @@ en:
notification_title: "Notify attendees"
bump_topic_title: "Auto-bump topic"
remove: "Remove reminder"
+ composer_actions:
+ create_event:
+ label: "Create event"
+ desc: "Create a new event in this category"
+ create_topic:
+ label: "Create topic"
+ desc: "Create a regular topic instead of an event"
builder_modal:
custom_fields:
diff --git a/plugins/discourse-calendar/spec/system/composer/create_event_action_spec.rb b/plugins/discourse-calendar/spec/system/composer/create_event_action_spec.rb
new file mode 100644
index 00000000000..85c754bf06a
--- /dev/null
+++ b/plugins/discourse-calendar/spec/system/composer/create_event_action_spec.rb
@@ -0,0 +1,69 @@
+# frozen_string_literal: true
+
+describe "Composer - Create event action" do
+ fab!(:admin)
+ fab!(:events_category) { Fabricate(:category, name: "Events") }
+ fab!(:regular_category) { Fabricate(:category, name: "General") }
+
+ let(:composer) { PageObjects::Components::Composer.new }
+
+ before do
+ SiteSetting.calendar_enabled = true
+ SiteSetting.discourse_post_event_enabled = true
+ SiteSetting.enable_events_category_type_setup = true
+ DiscourseCalendar::Categories::Types::Events.configure_category(
+ events_category,
+ guardian: admin.guardian,
+ )
+ sign_in(admin)
+ end
+
+ it "opens the composer in event mode for events-type categories" do
+ visit("/new-topic?category_id=#{events_category.id}")
+
+ expect(composer).to have_value(
+ %r{\A\[event start="[^"]+" end="[^"]+" status="public" timezone="[^"]+" reminders="[^"]+"\]\n\[/event\]\z},
+ )
+ expect(composer.button_label.text).to eq(
+ I18n.t("js.discourse_post_event.composer.create_event_button"),
+ )
+ expect(page).to have_css(
+ "#reply-title[placeholder='#{I18n.t("js.discourse_post_event.composer.event_title_placeholder")}']",
+ )
+ end
+
+ it "creates a topic with a parsed public event post when submitted" do
+ visit("/new-topic?category_id=#{events_category.id}")
+ composer.fill_title("Team offsite kickoff")
+ composer.create
+
+ expect(page).to have_current_path(%r{/t/team-offsite-kickoff/})
+ topic = Topic.find_by(title: "Team offsite kickoff")
+ expect(topic).to be_present
+ event = DiscoursePostEvent::Event.find_by(id: topic.first_post.id)
+ expect(event).to be_present
+ expect(event.status).to eq(DiscoursePostEvent::Event.statuses[:public])
+ expect(event.starts_at).to be_present
+ end
+
+ it "does not enter event mode for non-events categories" do
+ visit("/new-topic?category_id=#{regular_category.id}")
+
+ expect(composer).to have_value("")
+ expect(composer.button_label.text).to eq(I18n.t("js.composer.create_topic"))
+ end
+
+ it "lets the user switch back to a regular topic via the dropdown" do
+ visit("/new-topic?category_id=#{events_category.id}")
+
+ expect(composer.button_label.text).to eq(
+ I18n.t("js.discourse_post_event.composer.create_event_button"),
+ )
+
+ composer.open_composer_actions
+ composer.select_action(I18n.t("js.discourse_post_event.composer_actions.create_topic.label"))
+
+ expect(composer.button_label.text).to eq(I18n.t("js.composer.create_topic"))
+ expect(composer).to have_value("")
+ end
+end
diff --git a/plugins/discourse-calendar/test/javascripts/acceptance/create-event-composer-action-test.js b/plugins/discourse-calendar/test/javascripts/acceptance/create-event-composer-action-test.js
new file mode 100644
index 00000000000..3b2c4ec922a
--- /dev/null
+++ b/plugins/discourse-calendar/test/javascripts/acceptance/create-event-composer-action-test.js
@@ -0,0 +1,337 @@
+import { click, fillIn, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import Site from "discourse/models/site";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+import { i18n } from "discourse-i18n";
+
+const _mutatedCategoryIds = new Set();
+
+function markCategoryAsEvents(categoryId) {
+ const category = Site.current().categories.find((c) => c.id === categoryId);
+ category.categoryTypes = {
+ events: { id: "events", name: "Events", configuration_schema: {} },
+ };
+ _mutatedCategoryIds.add(categoryId);
+}
+
+acceptance("Create event composer action", function (needs) {
+ needs.user({ can_create_discourse_post_event: true });
+ needs.settings({
+ calendar_enabled: true,
+ discourse_post_event_enabled: true,
+ discourse_post_event_allowed_on_groups: "",
+ discourse_post_event_allowed_custom_fields: "",
+ });
+
+ needs.hooks.afterEach(function () {
+ _mutatedCategoryIds.forEach((id) => {
+ const category = Site.current().categories.find((c) => c.id === id);
+ if (category) {
+ category.categoryTypes = {};
+ }
+ });
+ _mutatedCategoryIds.clear();
+ });
+
+ test("entering an events-type category puts the composer in event mode", async function (assert) {
+ markCategoryAsEvents(2);
+
+ await visit("/");
+ await click("#create-topic");
+ const categoryChooser = selectKit(".category-chooser");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(2);
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ /^\[event start="[^"]+" end="[^"]+" status="public" timezone="[^"]+" reminders="[^"]+"\]\n\[\/event\]$/,
+ "event bbcode skeleton is inserted"
+ );
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("discourse_post_event.composer.create_event_button"));
+ assert
+ .dom(".save-or-cancel button.create .d-icon-calendar-day")
+ .exists("submit button shows the calendar icon in event mode");
+ assert
+ .dom("#reply-title")
+ .hasAttribute(
+ "placeholder",
+ i18n("discourse_post_event.composer.event_title_placeholder")
+ );
+ });
+
+ test("non-events categories leave the composer in topic mode", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ const categoryChooser = selectKit(".category-chooser");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(1);
+
+ assert.dom(".d-editor-input").hasNoValue();
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.create_topic"));
+ });
+
+ test("dropdown shows Create topic in event mode and Create event in topic mode (events-type only)", async function (assert) {
+ markCategoryAsEvents(2);
+
+ await visit("/");
+ await click("#create-topic");
+ const categoryChooser = selectKit(".category-chooser");
+ const composerActions = selectKit(".composer-actions");
+
+ // Non-events category — neither plugin option appears
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(1);
+ await composerActions.expand();
+ assert
+ .dom(`.composer-actions .select-kit-row[data-value="create_event"]`)
+ .doesNotExist();
+ assert
+ .dom(
+ `.composer-actions .select-kit-row[data-value="create_regular_topic"]`
+ )
+ .doesNotExist();
+ await composerActions.collapse();
+
+ // Events-type category — auto-enters event mode; Create topic switch-back appears
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(2);
+ await composerActions.expand();
+ assert
+ .dom(`.composer-actions .select-kit-row[data-value="create_event"]`)
+ .doesNotExist();
+ assert
+ .dom(
+ `.composer-actions .select-kit-row[data-value="create_regular_topic"]`
+ )
+ .exists();
+
+ // Picking Create topic exits event mode and surfaces Create event
+ await composerActions.selectRowByValue("create_regular_topic");
+ assert.dom(".d-editor-input").hasNoValue("skeleton is cleared on exit");
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.create_topic"));
+
+ await composerActions.expand();
+ assert
+ .dom(`.composer-actions .select-kit-row[data-value="create_event"]`)
+ .exists();
+ assert
+ .dom(
+ `.composer-actions .select-kit-row[data-value="create_regular_topic"]`
+ )
+ .doesNotExist();
+ });
+
+ test("switching from events-type to a regular category clears the unedited skeleton", async function (assert) {
+ markCategoryAsEvents(2);
+
+ await visit("/");
+ await click("#create-topic");
+ const categoryChooser = selectKit(".category-chooser");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(2);
+
+ assert.dom(".d-editor-input").hasValue(/^\[event /);
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("discourse_post_event.composer.create_event_button"));
+
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(1);
+
+ assert
+ .dom(".d-editor-input")
+ .hasNoValue("unedited event skeleton is cleared");
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.create_topic"));
+ });
+
+ test("manually removing the event bbcode exits event mode", async function (assert) {
+ markCategoryAsEvents(2);
+
+ await visit("/");
+ await click("#create-topic");
+ const categoryChooser = selectKit(".category-chooser");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(2);
+
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("discourse_post_event.composer.create_event_button"));
+
+ await fillIn(".d-editor-input", "just a regular topic body");
+
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.create_topic"));
+ assert.notStrictEqual(
+ document.querySelector("#reply-title").getAttribute("placeholder"),
+ i18n("discourse_post_event.composer.event_title_placeholder"),
+ "title placeholder is no longer the event one"
+ );
+ });
+
+ test("manually adding an event block back re-enters event mode", async function (assert) {
+ markCategoryAsEvents(2);
+
+ await visit("/");
+ await click("#create-topic");
+ const categoryChooser = selectKit(".category-chooser");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(2);
+
+ // Exit by deleting the auto-inserted skeleton
+ await fillIn(".d-editor-input", "");
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.create_topic"));
+
+ // Now paste in an event block by hand
+ await fillIn(
+ ".d-editor-input",
+ '[event start="2026-05-21 10:00" status="public" timezone="UTC"]\n[/event]'
+ );
+
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("discourse_post_event.composer.create_event_button"));
+ });
+
+ test("pasting an event block into a topic-mode reply enters event mode", async function (assert) {
+ markCategoryAsEvents(2);
+
+ await visit("/");
+ await click("#create-topic");
+ const categoryChooser = selectKit(".category-chooser");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(2);
+
+ await fillIn(".d-editor-input", "");
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.create_topic"), "starts in topic mode");
+
+ await fillIn(
+ ".d-editor-input",
+ '[event start="2026-06-15 10:00" status="public" timezone="UTC"]\n[/event]'
+ );
+
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(
+ i18n("discourse_post_event.composer.create_event_button"),
+ "auto-enters event mode"
+ );
+ });
+
+ test("switching to an events category with existing content does not auto-enter event mode", async function (assert) {
+ markCategoryAsEvents(2);
+
+ await visit("/");
+ await click("#create-topic");
+
+ const categoryChooser = selectKit(".category-chooser");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(1);
+ await fillIn(".d-editor-input", "draft I started in a regular category");
+
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(2);
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(
+ "draft I started in a regular category",
+ "existing reply is left untouched"
+ );
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.create_topic"), "stays in topic mode");
+
+ const composerActions = selectKit(".composer-actions");
+ await composerActions.expand();
+ assert
+ .dom(`.composer-actions .select-kit-row[data-value="create_event"]`)
+ .exists("Create event is still offered as an explicit opt-in");
+ });
+
+ test("an edited event block is preserved on category switch", async function (assert) {
+ markCategoryAsEvents(2);
+
+ await visit("/");
+ await click("#create-topic");
+ const categoryChooser = selectKit(".category-chooser");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(2);
+
+ const original = document.querySelector(".d-editor-input").value;
+ const edited = original.replace(`status="public"`, `status="private"`);
+ await fillIn(".d-editor-input", edited);
+
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(1);
+
+ assert
+ .dom(".d-editor-input")
+ .hasValue(edited, "user-edited content survives the switch");
+ });
+});
+
+acceptance(
+ "Create event composer action — user without create-event permission",
+ function (needs) {
+ needs.user({ can_create_discourse_post_event: false });
+ needs.settings({
+ calendar_enabled: true,
+ discourse_post_event_enabled: true,
+ discourse_post_event_allowed_on_groups: "",
+ discourse_post_event_allowed_custom_fields: "",
+ });
+
+ needs.hooks.afterEach(function () {
+ _mutatedCategoryIds.forEach((id) => {
+ const category = Site.current().categories.find((c) => c.id === id);
+ if (category) {
+ category.categoryTypes = {};
+ }
+ });
+ _mutatedCategoryIds.clear();
+ });
+
+ test("events-type category stays in regular topic mode", async function (assert) {
+ markCategoryAsEvents(2);
+
+ await visit("/");
+ await click("#create-topic");
+ const categoryChooser = selectKit(".category-chooser");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(2);
+
+ assert
+ .dom(".d-editor-input")
+ .hasNoValue("event skeleton is not inserted");
+ assert
+ .dom(".save-or-cancel button.create")
+ .hasText(i18n("composer.create_topic"));
+
+ const composerActions = selectKit(".composer-actions");
+ await composerActions.expand();
+ assert
+ .dom(`.composer-actions .select-kit-row[data-value="create_event"]`)
+ .doesNotExist("Create event option is not offered");
+ assert
+ .dom(
+ `.composer-actions .select-kit-row[data-value="create_regular_topic"]`
+ )
+ .doesNotExist();
+ });
+ }
+);
diff --git a/spec/requests/api/schemas/json/site_response.json b/spec/requests/api/schemas/json/site_response.json
index c44e3aeab3b..def64d0f75d 100644
--- a/spec/requests/api/schemas/json/site_response.json
+++ b/spec/requests/api/schemas/json/site_response.json
@@ -855,6 +855,10 @@
"form_template_ids": {
"type": "array",
"items": {}
+ },
+ "category_types": {
+ "type": "object",
+ "additionalProperties": true
}
},
"required": [
diff --git a/spec/serializers/site_serializer_spec.rb b/spec/serializers/site_serializer_spec.rb
index 478538335d9..19bc280fc97 100644
--- a/spec/serializers/site_serializer_spec.rb
+++ b/spec/serializers/site_serializer_spec.rb
@@ -6,6 +6,16 @@ RSpec.describe SiteSerializer do
after { Site.clear_cache }
+ describe "category_types" do
+ it "is included on each serialized category in the site payload" do
+ category
+ Site.clear_cache
+ serialized = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json
+ c = serialized[:categories].find { |entry| entry[:id] == category.id }
+ expect(c).to have_key(:category_types)
+ end
+ end
+
describe "#user_tips" do
it "is included if enable_user_tips" do
SiteSetting.enable_user_tips = true
diff --git a/spec/services/categories/configure_spec.rb b/spec/services/categories/configure_spec.rb
index ecc5f37ce71..949ff83b1d2 100644
--- a/spec/services/categories/configure_spec.rb
+++ b/spec/services/categories/configure_spec.rb
@@ -79,6 +79,11 @@ RSpec.describe Categories::Configure do
result
expect(Discourse.cache.read(Categories::TypeRegistry::COUNTS_CACHE_KEY)).to be_nil
end
+
+ it "clears the site categories cache so `category_types` propagates" do
+ Site.expects(:clear_cache).at_least_once
+ result
+ end
end
end
end
diff --git a/spec/services/categories/unconfigure_spec.rb b/spec/services/categories/unconfigure_spec.rb
index 0aa23ebbded..bc06cfa139a 100644
--- a/spec/services/categories/unconfigure_spec.rb
+++ b/spec/services/categories/unconfigure_spec.rb
@@ -63,6 +63,11 @@ RSpec.describe Categories::Unconfigure do
result
expect(Discourse.cache.read(Categories::TypeRegistry::COUNTS_CACHE_KEY)).to be_nil
end
+
+ it "clears the site categories cache so `category_types` propagates" do
+ Site.expects(:clear_cache).at_least_once
+ result
+ end
end
end
end