Skip to content

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

DEV: extract composer toolbar class for future reuse (#32897)

Renato Atilio1ee51f2e3b9c
diff --git a/app/assets/javascripts/discourse/app/components/composer-editor.gjs b/app/assets/javascripts/discourse/app/components/composer-editor.gjs
index c2cf1d77d59..84a163976e9 100644
--- a/app/assets/javascripts/discourse/app/components/composer-editor.gjs
+++ b/app/assets/javascripts/discourse/app/components/composer-editor.gjs
@@ -927,7 +927,10 @@ export default class ComposerEditor extends Component {
icon: "gear",
title: "composer.options",
sendAction: this.onExpandPopupMenuOptions.bind(this),
- popupMenu: true,
+ popupMenu: {
+ options: () => this.composer.popupMenuOptions,
+ action: this.composer.onPopupMenuAction,
+ },
});
}
diff --git a/app/assets/javascripts/discourse/app/components/composer/toolbar-buttons.gjs b/app/assets/javascripts/discourse/app/components/composer/toolbar-buttons.gjs
new file mode 100644
index 00000000000..8ad9cc62b05
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/composer/toolbar-buttons.gjs
@@ -0,0 +1,67 @@
+import Component from "@glimmer/component";
+import { fn, hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { eq } from "truth-helpers";
+import DButton from "discourse/components/d-button";
+import concatClass from "discourse/helpers/concat-class";
+import icon from "discourse/helpers/d-icon";
+import ToolbarPopupMenuOptions from "select-kit/components/toolbar-popup-menu-options";
+
+export default class ComposerToolbarButtons extends Component {
+ @action
+ tabIndex(button) {
+ return button === this.firstButton ? 0 : button.tabindex;
+ }
+
+ get firstButton() {
+ return (
+ this.args.isFirst &&
+ this.args.data.groups.find((group) => group.buttons?.length > 0)
+ ?.buttons[0]
+ );
+ }
+
+ <template>
+ {{#each @data.groups key="group" as |group|}}
+ {{#each group.buttons key="id" as |button|}}
+ {{#if (button.condition @data.context)}}
+ {{#if button.href}}
+ <a
+ href={{button.href}}
+ target="_blank"
+ rel="noopener noreferrer"
+ class={{concatClass "btn no-text btn-icon" button.className}}
+ title={{button.title}}
+ tabindex={{this.tabIndex button}}
+ >
+ {{icon button.icon}}
+ </a>
+ {{else if button.popupMenu}}
+ <ToolbarPopupMenuOptions
+ @content={{(button.popupMenu.options)}}
+ @onChange={{button.popupMenu.action}}
+ @onOpen={{fn button.action button}}
+ @tabindex={{this.tabIndex button}}
+ @onKeydown={{@rovingButtonBar}}
+ @options={{hash icon=button.icon focusAfterOnChange=false}}
+ class={{button.className}}
+ />
+ {{else if (eq button.type "separator")}}
+ <div class="toolbar-separator"></div>
+ {{else}}
+ <DButton
+ @action={{fn button.action button}}
+ @translatedTitle={{button.title}}
+ @label={{button.label}}
+ @icon={{button.icon}}
+ @preventFocus={{button.preventFocus}}
+ @onKeyDown={{@rovingButtonBar}}
+ tabindex={{this.tabIndex button}}
+ class={{button.className}}
+ />
+ {{/if}}
+ {{/if}}
+ {{/each}}
+ {{/each}}
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/d-editor.gjs b/app/assets/javascripts/discourse/app/components/d-editor.gjs
index 4dbc6a80f67..8ba4e0c2d03 100644
--- a/app/assets/javascripts/discourse/app/components/d-editor.gjs
+++ b/app/assets/javascripts/discourse/app/components/d-editor.gjs
@@ -1,6 +1,5 @@
import { tracked } from "@glimmer/tracking";
import Component from "@ember/component";
-import { fn, hash } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { getOwner } from "@ember/owner";
@@ -11,8 +10,10 @@ import { observes, on as onEvent } from "@ember-decorators/object";
import { emojiSearch, isSkinTonableEmoji } from "pretty-text/emoji";
import { translations } from "pretty-text/emoji/data";
import { Promise } from "rsvp";
+import { not } from "truth-helpers";
import TextareaEditor from "discourse/components/composer/textarea-editor";
import ToggleSwitch from "discourse/components/composer/toggle-switch";
+import ToolbarButtons from "discourse/components/composer/toolbar-buttons";
import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
import DButton from "discourse/components/d-button";
import DEditorPreview from "discourse/components/d-editor-preview";
@@ -41,7 +42,6 @@ import {
renderUserStatusHtml,
} from "discourse/lib/user-status-on-autocomplete";
import { i18n } from "discourse-i18n";
-import ToolbarPopupMenuOptions from "select-kit/components/toolbar-popup-menu-options";
let _createCallbacks = [];
@@ -68,6 +68,7 @@ export default class DEditor extends Component {
@tracked editorComponent;
/** @type {TextManipulation} */
@tracked textManipulation;
+ @tracked replacedToolbarInstance;
@tracked preview;
@@ -171,7 +172,7 @@ export default class DEditor extends Component {
@discourseComputed()
toolbar() {
const toolbar = new Toolbar(
- this.getProperties("site", "siteSettings", "showLink", "capabilities")
+ this.getProperties("siteSettings", "showLink", "capabilities")
);
toolbar.context = this;
@@ -181,11 +182,6 @@ export default class DEditor extends Component {
this.extraButtons(toolbar);
}
- const firstButton = toolbar.groups.mapBy("buttons").flat().firstObject;
- if (firstButton) {
- firstButton.tabindex = 0;
- }
-
return toolbar;
}
@@ -616,6 +612,16 @@ export default class DEditor extends Component {
});
}
+ @action
+ replaceToolbar(toolbarInstance) {
+ this.replacedToolbarInstance = toolbarInstance;
+ }
+
+ @action
+ resetToolbar() {
+ this.replacedToolbarInstance = null;
+ }
+
@action
onChange(event) {
this.set("value", event?.target?.value);
@@ -715,45 +721,40 @@ export default class DEditor extends Component {
{{if this.disabled 'disabled'}}
{{if this.isEditorFocused 'in-focus'}}"
>
- <div class="d-editor-button-bar" role="toolbar">
- {{#if this.siteSettings.rich_editor}}
- <ToggleSwitch
+
+ {{#if this.replacedToolbarInstance}}
+ <div class="d-editor-button-bar --replaced-toolbar" role="toolbar">
+ <DButton
+ @action={{this.resetToolbar}}
+ @icon="angle-left"
@preventFocus={{true}}
- @disabled={{@disableSubmit}}
- @state={{this.isRichEditorEnabled}}
- {{on "click" this.toggleRichEditor}}
+ @onKeyDown={{this.rovingButtonBar}}
+ class="btn-flat d-editor-button-bar__back"
+ />
+ <ToolbarButtons
+ @data={{this.replacedToolbarInstance}}
+ @rovingButtonBar={{this.rovingButtonBar}}
+ />
+ </div>
+ {{else}}
+ <div class="d-editor-button-bar" role="toolbar">
+ {{#if this.siteSettings.rich_editor}}
+ <ToggleSwitch
+ @preventFocus={{true}}
+ @disabled={{@disableSubmit}}
+ @state={{this.isRichEditorEnabled}}
+ {{on "click" this.toggleRichEditor}}
+ {{on "keydown" this.rovingButtonBar}}
+ />
+ {{/if}}
+
+ <ToolbarButtons
+ @data={{this.toolbar}}
+ @rovingButtonBar={{this.rovingButtonBar}}
+ @isFirst={{not this.siteSettings.rich_editor}}
/>
- {{/if}}
-
- {{#each this.toolbar.groups as |group|}}
- {{#each group.buttons as |b|}}
- {{#if (b.condition this)}}
- {{#if b.popupMenu}}
- <ToolbarPopupMenuOptions
- @content={{this.popupMenuOptions}}
- @onChange={{this.onPopupMenuAction}}
- @onOpen={{fn b.action b}}
- @tabindex={{-1}}
- @onKeydown={{this.rovingButtonBar}}
- @options={{hash icon=b.icon focusAfterOnChange=false}}
- class={{b.className}}
- />
- {{else}}
- <DButton
- @action={{fn b.action b}}
- @translatedTitle={{b.title}}
- @label={{b.label}}
- @icon={{b.icon}}
- @preventFocus={{b.preventFocus}}
- @onKeyDown={{this.rovingButtonBar}}
- tabindex={{b.tabindex}}
- class={{b.className}}
- />
- {{/if}}
- {{/if}}
- {{/each}}
- {{/each}}
- </div>
+ </div>
+ {{/if}}
<ConditionalLoadingSpinner @condition={{this.loading}} />
<this.editorComponent
@@ -770,6 +771,7 @@ export default class DEditor extends Component {
@categoryId={{@categoryId}}
@topicId={{@topicId}}
@id={{this.textAreaId}}
+ @replaceToolbar={{this.replaceToolbar}}
/>
<PopupInputTip @validation={{this.validation}} />
<PluginOutlet
diff --git a/app/assets/javascripts/discourse/app/lib/composer/toolbar.js b/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
index 034cf2aae09..b5966bbf696 100644
--- a/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
+++ b/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
@@ -7,11 +7,90 @@ function getButtonLabel(labelKey, defaultLabel) {
return i18n(labelKey) === defaultLabel ? null : labelKey;
}
-export default class Toolbar {
- constructor(opts) {
- const { siteSettings, capabilities } = opts;
+const DEFAULT_GROUP = "main";
+
+export class ToolbarBase {
+ constructor(opts = {}) {
this.shortcuts = {};
this.context = null;
+ this.groups = [{ group: DEFAULT_GROUP, buttons: [] }];
+ this.siteSettings = opts.siteSettings || {};
+ this.capabilities = opts.capabilities || {};
+ }
+
+ addButton(buttonAttrs) {
+ const g = this.groups.findBy("group", buttonAttrs.group || DEFAULT_GROUP);
+
+ const createdButton = {
+ id: buttonAttrs.id,
+ tabindex: buttonAttrs.tabindex || "-1",
+ className: buttonAttrs.className || buttonAttrs.id,
+ label: buttonAttrs.label,
+ icon: buttonAttrs.icon,
+ href: buttonAttrs.href,
+ action: (button) => {
+ buttonAttrs.action
+ ? buttonAttrs.action(button)
+ : this.context.send("toolbarButton", button);
+
+ // appEvents is only available on the main toolbar
+ // only custom plugins listen to this event
+ this.context.appEvents?.trigger(
+ "d-editor:toolbar-button-clicked",
+ button
+ );
+ },
+ perform: buttonAttrs.perform || function () {},
+ trimLeading: buttonAttrs.trimLeading,
+ popupMenu: buttonAttrs.popupMenu,
+ preventFocus: buttonAttrs.preventFocus || false,
+ condition: buttonAttrs.condition || (() => true),
+ sendAction: buttonAttrs.sendAction,
+ shortcutAction: buttonAttrs.shortcutAction, // (optional) custom shortcut action
+ hideShortcutInTitle: buttonAttrs.hideShortcutInTitle || false, // (optional) hide shortcut in title
+ };
+
+ const title = i18n(buttonAttrs.title || `composer.${buttonAttrs.id}_title`);
+ if (buttonAttrs.shortcut) {
+ const shortcutTitle = `${translateModKey(
+ PLATFORM_KEY_MODIFIER + "+"
+ )}${translateModKey(buttonAttrs.shortcut)}`;
+
+ if (buttonAttrs.hideShortcutInTitle) {
+ createdButton.title = title;
+ } else {
+ createdButton.title = `${title} (${shortcutTitle})`;
+ }
+ this.shortcuts[
+ `${PLATFORM_KEY_MODIFIER}+${buttonAttrs.shortcut}`.toLowerCase()
+ ] = createdButton;
+ } else {
+ createdButton.title = title;
+ }
+
+ if (buttonAttrs.unshift) {
+ g.buttons.unshift(createdButton);
+ } else {
+ g.buttons.push(createdButton);
+ }
+ }
+
+ addSeparator(group = DEFAULT_GROUP) {
+ const g = this.groups.findBy("group", group);
+ if (!g) {
+ throw new Error(`Couldn't find toolbar group ${group}`);
+ }
+
+ g.buttons.push({ type: "separator" });
+ }
+}
+
+/**
+ * Standard editor toolbar with default buttons
+ */
+export default class Toolbar extends ToolbarBase {
+ constructor(opts) {
+ super(opts);
this.groups = [
{ group: "fontStyles", buttons: [] },
@@ -70,7 +149,7 @@ export default class Toolbar {
}),
});
- if (!capabilities.touch) {
+ if (!this.capabilities.touch) {
this.addButton({
id: "code",
group: "insertions",
@@ -106,7 +185,7 @@ export default class Toolbar {
});
}
- if (siteSettings.support_mixed_text_direction) {
+ if (this.siteSettings.support_mixed_text_direction) {
this.addButton({
id: "toggle-direction",
group: "extras",
@@ -117,67 +196,5 @@ export default class Toolbar {
perform: (e) => e.toggleDirection(),
});
}
-
- this.groups[this.groups.length - 1].lastGroup = true;
- }
-
- addButton(buttonAttrs) {
- const g = this.groups.findBy("group", buttonAttrs.group);
- if (!g) {
- throw new Error(`Couldn't find toolbar group ${buttonAttrs.group}`);
- }
-
- const createdButton = {
- id: buttonAttrs.id,
- tabindex: buttonAttrs.tabindex || "-1",
- className: buttonAttrs.className || buttonAttrs.id,
- label: buttonAttrs.label,
- icon: buttonAttrs.icon,
- action: (button) => {
- buttonAttrs.action
- ? buttonAttrs.action(button)
- : this.context.send("toolbarButton", button);
- this.context.appEvents.trigger(
- "d-editor:toolbar-button-clicked",
- button
- );
- },
- perform: buttonAttrs.perform || function () {},
- trimLeading: buttonAttrs.trimLeading,
- popupMenu: buttonAttrs.popupMenu || false,
- preventFocus: buttonAttrs.preventFocus || false,
- condition: buttonAttrs.condition || (() => true),
- shortcutAction: buttonAttrs.shortcutAction, // (optional) custom shortcut action
- hideShortcutInTitle: buttonAttrs.hideShortcutInTitle || false, // (optional) hide shortcut in title
- };
-
- if (buttonAttrs.sendAction) {
- createdButton.sendAction = buttonAttrs.sendAction;
- }
-
- const title = i18n(buttonAttrs.title || `composer.${buttonAttrs.id}_title`);
- if (buttonAttrs.shortcut) {
- const shortcutTitle = `${translateModKey(
- PLATFORM_KEY_MODIFIER + "+"
- )}${translateModKey(buttonAttrs.shortcut)}`;
-
- if (buttonAttrs.hideShortcutInTitle) {
- createdButton.title = title;
- } else {
- createdButton.title = `${title} (${shortcutTitle})`;
- }
-
- this.shortcuts[
- `${PLATFORM_KEY_MODIFIER}+${buttonAttrs.shortcut}`.toLowerCase()
- ] = createdButton;
- } else {
- createdButton.title = title;
- }
-
- if (buttonAttrs.unshift) {
- g.buttons.unshift(createdButton);
- } else {
- g.buttons.push(createdButton);
- }
}
}
diff --git a/app/assets/javascripts/discourse/tests/integration/components/d-editor-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/d-editor-test.gjs
index 95ca658857b..18473df15fe 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/d-editor-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/d-editor-test.gjs
@@ -11,6 +11,7 @@ import {
} from "@ember/test-helpers";
import { module, test } from "qunit";
import DEditor from "discourse/components/d-editor";
+import { ToolbarBase } from "discourse/lib/composer/toolbar";
import { withPluginApi } from "discourse/lib/plugin-api";
import { setCaretPosition } from "discourse/lib/utilities";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
@@ -1313,6 +1314,56 @@ third line`
});
}
})();
+
+ test("toolbar instance replacement", async function (assert) {
+ const self = this;
+
+ const customToolbar = new ToolbarBase({
+ siteSettings: this.siteSettings,
+ capabilities: this.capabilities,
+ showLink: true,
+ });
+ customToolbar.addButton({
+ id: "custom-toolbar-button",
+ icon: "plus",
+ title: "Custom Toolbar Button",
+ });
+
+ withPluginApi((api) => {
+ api.onToolbarCreate((toolbar) => {
+ toolbar.addButton({
+ id: "replace-toolbar",
+ icon: "xmark",
+ group: "extras",
+ action: () => {
+ toolbar.context.replaceToolbar(customToolbar);
+ },
+ condition: () => true,
+ });
+ });
+ });
+
+ this.value = "hello";
+
+ await render(<template><DEditor @value={{self.value}} /></template>);
+
+ assert.dom(".d-editor-button-bar").exists();
+ assert.dom(".d-editor-button-bar.--replaced-toolbar").doesNotExist();
+
+ await click("button.replace-toolbar");
+
+ assert
+ .dom(
+ ".d-editor-button-bar.--replaced-toolbar button.custom-toolbar-button"
+ )
+ .exists("It should show the custom toolbar button");
+
+ // Back button
+ await click(".d-editor-button-bar__back");
+
+ assert.dom(".d-editor-button-bar").exists();
+ assert.dom(".d-editor-button-bar.--replaced-toolbar").doesNotExist();
+ });
});
module("Integration | Component | d-editor | rich editor", function (hooks) {