Skip to content

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

UX: display active state on rich editor toolbar (#33296)

Renato Atilioc74366c595c6
diff --git a/app/assets/javascripts/discourse/app/components/composer/toolbar-buttons.gjs b/app/assets/javascripts/discourse/app/components/composer/toolbar-buttons.gjs
index ed8c5c7b06b..07b8f412b96 100644
--- a/app/assets/javascripts/discourse/app/components/composer/toolbar-buttons.gjs
+++ b/app/assets/javascripts/discourse/app/components/composer/toolbar-buttons.gjs
@@ -25,6 +25,12 @@ export default class ComposerToolbarButtons extends Component {
return this.args.rovingButtonBar || this.args.data.rovingButtonBar;
}
+ @action
+ isButtonActive(button) {
+ const state = this.args.data.context?.textManipulation?.state || {};
+ return button.active?.({ state });
+ }
+
<template>
{{#each @data.groups key="group" as |group|}}
{{#each group.buttons key="id" as |button|}}
@@ -53,7 +59,11 @@ export default class ComposerToolbarButtons extends Component {
@preventFocus={{button.preventFocus}}
@onKeyDown={{this.rovingButtonBar}}
tabindex={{this.tabIndex button}}
- class={{concatClass "toolbar-link" button.className}}
+ class={{concatClass
+ "toolbar__button"
+ button.className
+ (if (this.isButtonActive button) "--active")
+ }}
rel={{if button.href "noopener noreferrer"}}
target={{if button.href "_blank"}}
/>
diff --git a/app/assets/javascripts/discourse/app/components/d-editor.gjs b/app/assets/javascripts/discourse/app/components/d-editor.gjs
index 27d8da2f371..dcc9014bde5 100644
--- a/app/assets/javascripts/discourse/app/components/d-editor.gjs
+++ b/app/assets/javascripts/discourse/app/components/d-editor.gjs
@@ -91,6 +91,8 @@ export default class DEditor extends Component {
this.register = getRegister(this);
+ this.setupToolbar();
+
if (
this.siteSettings.rich_editor &&
this.keyValueStore.get("d-editor-prefers-rich-editor") === "true"
@@ -101,6 +103,19 @@ export default class DEditor extends Component {
}
}
+ setupToolbar() {
+ this.toolbar = new Toolbar(
+ this.getProperties("siteSettings", "showLink", "capabilities")
+ );
+ this.toolbar.context = this;
+
+ _createCallbacks.forEach((cb) => cb(this.toolbar));
+
+ if (this.extraButtons) {
+ this.extraButtons(this.toolbar);
+ }
+ }
+
@discourseComputed("placeholder")
placeholderTranslated(placeholder) {
if (placeholder) {
@@ -179,22 +194,6 @@ export default class DEditor extends Component {
this._cachedCookFunction = null;
}
- @discourseComputed()
- toolbar() {
- const toolbar = new Toolbar(
- this.getProperties("siteSettings", "showLink", "capabilities")
- );
- toolbar.context = this;
-
- _createCallbacks.forEach((cb) => cb(toolbar));
-
- if (this.extraButtons) {
- this.extraButtons(toolbar);
- }
-
- return toolbar;
- }
-
async cachedCookAsync(text, options) {
this._cachedCookFunction ||= await generateCookFunction(options || {});
return await this._cachedCookFunction(text);
diff --git a/app/assets/javascripts/discourse/app/lib/composer/text-manipulation.js b/app/assets/javascripts/discourse/app/lib/composer/text-manipulation.js
index 4a81c39f7c9..3b494b64df2 100644
--- a/app/assets/javascripts/discourse/app/lib/composer/text-manipulation.js
+++ b/app/assets/javascripts/discourse/app/lib/composer/text-manipulation.js
@@ -7,6 +7,25 @@
*/
export const TextManipulation = {};
+/**
+ * @typedef ToolbarState
+ * @property {boolean} [inBold]
+ * @property {boolean} [inItalic]
+ * @property {boolean} [inLink]
+ * @property {boolean} [inBulletList]
+ * @property {boolean} [inOrderedList]
+ * @property {boolean} [inCode]
+ * @property {boolean} [inCodeBlock]
+ * @property {boolean} [inBlockquote]
+ */
+
+/**
+ * The current state of the editor for toolbar button active states
+ * @name TextManipulation#state
+ * @type {ToolbarState | undefined}
+ * @readonly
+ */
+
/**
* Whether the editor allows a preview being shown
* @name TextManipulation#allowPreview
diff --git a/app/assets/javascripts/discourse/app/lib/composer/toolbar.js b/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
index 5474c8bad7a..08e022d68b1 100644
--- a/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
+++ b/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
@@ -1,7 +1,30 @@
+// @ts-check
import { PLATFORM_KEY_MODIFIER } from "discourse/lib/keyboard-shortcuts";
import { translateModKey } from "discourse/lib/utilities";
import { i18n } from "discourse-i18n";
+/**
+ * @typedef ToolbarButton
+ * @property {string} id
+ * @property {string} [group]
+ * @property {string} [tabindex]
+ * @property {string} [className]
+ * @property {string} [label]
+ * @property {string} [icon]
+ * @property {string} [href]
+ * @property {Function} action
+ * @property {Function} [perform]
+ * @property {Function} [sendAction]
+ * @property {boolean} [trimLeading]
+ * @property {boolean} [preventFocus]
+ * @property {Function} condition
+ * @property {boolean} [hideShortcutInTitle]
+ * @property {string} title
+ * @property {string} [shortcut]
+ * @property {boolean} [unshift]
+ * @property {Function} [active]
+ */
+
function getButtonLabel(labelKey, defaultLabel) {
// use the Font Awesome icon if the label matches the default
return i18n(labelKey) === defaultLabel ? null : labelKey;
@@ -40,13 +63,15 @@ export class ToolbarBase {
* @param {string=} buttonAttrs.shortcut
* @param {boolean=} buttonAttrs.unshift
* @param {boolean=} buttonAttrs.disabled
+ * @param {Function=} buttonAttrs.active callback function that receives state and returns boolean
*/
addButton(buttonAttrs) {
- const g = this.groups.findBy("group", buttonAttrs.group || DEFAULT_GROUP);
+ const group = this.groups.find(
+ (item) => item.group === (buttonAttrs.group || DEFAULT_GROUP)
+ );
- const createdButton = Object.defineProperties(
- {},
- Object.getOwnPropertyDescriptors(buttonAttrs)
+ const createdButton = /** @type {ToolbarButton} */ (
+ Object.defineProperties({}, Object.getOwnPropertyDescriptors(buttonAttrs))
);
createdButton.tabindex ||= "-1";
@@ -89,19 +114,23 @@ export class ToolbarBase {
}
if (buttonAttrs.unshift) {
- g.buttons.unshift(createdButton);
+ group.buttons.unshift(createdButton);
} else {
- g.buttons.push(createdButton);
+ group.buttons.push(createdButton);
}
}
- addSeparator({ group = DEFAULT_GROUP, condition }) {
- const g = this.groups.findBy("group", group);
- if (!g) {
- throw new Error(`Couldn't find toolbar group ${group}`);
+ addSeparator({ group: groupName = DEFAULT_GROUP, condition }) {
+ const group = this.groups.find((item) => item.group === groupName);
+
+ if (!group) {
+ throw new Error(`Couldn't find toolbar group ${groupName}`);
}
- g.buttons.push({ type: "separator", condition: condition || (() => true) });
+ group.buttons.push({
+ type: "separator",
+ condition: condition || (() => true),
+ });
}
}
@@ -129,6 +158,7 @@ export default class Toolbar extends ToolbarBase {
preventFocus: true,
trimLeading: true,
perform: (e) => e.applySurround("**", "**", "bold_text"),
+ active: ({ state }) => state.inBold,
});
const italicLabel = getButtonLabel("composer.italic_label", "I");
@@ -142,6 +172,7 @@ export default class Toolbar extends ToolbarBase {
preventFocus: true,
trimLeading: true,
perform: (e) => e.applySurround("*", "*", "italic_text"),
+ active: ({ state }) => state.inItalic,
});
if (opts.showLink) {
@@ -153,6 +184,7 @@ export default class Toolbar extends ToolbarBase {
preventFocus: true,
trimLeading: true,
sendAction: (event) => this.context.send("showLinkModal", event),
+ active: ({ state }) => state.inLink,
});
}
@@ -167,6 +199,7 @@ export default class Toolbar extends ToolbarBase {
applyEmptyLines: true,
multiline: true,
}),
+ active: ({ state }) => state.inBlockquote,
});
if (!this.capabilities.touch) {
@@ -178,6 +211,7 @@ export default class Toolbar extends ToolbarBase {
preventFocus: true,
trimLeading: true,
perform: (e) => e.formatCode(),
+ active: ({ state }) => state.inCode || state.inCodeBlock,
});
this.addButton({
@@ -188,6 +222,7 @@ export default class Toolbar extends ToolbarBase {
title: "composer.ulist_title",
preventFocus: true,
perform: (e) => e.applyList("* ", "list_item"),
+ active: ({ state }) => state.inBulletList,
});
this.addButton({
@@ -202,6 +237,7 @@ export default class Toolbar extends ToolbarBase {
(i) => (!i ? "1. " : `${parseInt(i, 10) + 1}. `),
"list_item"
),
+ active: ({ state }) => state.inOrderedList,
});
}
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/components/prosemirror-editor.gjs b/app/assets/javascripts/discourse/app/static/prosemirror/components/prosemirror-editor.gjs
index 3b7371d4971..c0c2b6a056c 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/components/prosemirror-editor.gjs
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/components/prosemirror-editor.gjs
@@ -183,6 +183,8 @@ export default class ProsemirrorEditor extends Component {
this.#lastSerialized = value;
this.args.change?.({ target: { value } });
}
+
+ this.textManipulation.updateState();
},
handleDOMEvents: {
focus: () => {
@@ -213,6 +215,8 @@ export default class ProsemirrorEditor extends Component {
this.#destructor = this.args.onSetup?.(this.textManipulation);
this.convertFromValue();
+
+ this.textManipulation.updateState();
}
@bind
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.js b/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.js
index 0de2f9642cc..4ae5fa4dbec 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.js
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.js
@@ -189,3 +189,37 @@ export function findMarkOfType(marks, type, attrs = {}) {
Object.keys(attrs).every((key) => item.attrs[key] === attrs[key])
);
}
+
+export function hasMark(state, markType, attrs = {}) {
+ const { from, to, empty } = state.selection;
+
+ // For empty selection, check stored marks or marks at position
+ if (empty) {
+ const storedMarks = state.storedMarks || state.selection.$from.marks();
+ return !!findMarkOfType(storedMarks, markType, attrs);
+ }
+
+ // For range selections, check if mark exists in the range
+ return (
+ state.doc.rangeHasMark(from, to, markType) &&
+ (!Object.keys(attrs).length ||
+ state.doc.rangeHasMark(from, to, markType.create(attrs)))
+ );
+}
+
+export function inNode(state, nodeType, attrs = {}) {
+ const { $from } = state.selection;
+
+ for (let d = $from.depth; d >= 0; d--) {
+ const node = $from.node(d);
+ if (node.type === nodeType) {
+ if (!Object.keys(attrs).length) {
+ return true;
+ }
+
+ return Object.keys(attrs).every((key) => node.attrs[key] === attrs[key]);
+ }
+ }
+
+ return false;
+}
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.js b/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.js
index 5010f3fae95..5e2a0588148 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.js
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.js
@@ -1,6 +1,7 @@
// @ts-check
import { setOwner } from "@ember/owner";
import { next } from "@ember/runloop";
+import { TrackedObject } from "@ember-compat/tracked-built-ins";
import $ from "jquery";
import { lift, setBlockType, toggleMark, wrapIn } from "prosemirror-commands";
import { Slice } from "prosemirror-model";
@@ -9,11 +10,13 @@ import { TextSelection } from "prosemirror-state";
import { bind } from "discourse/lib/decorators";
import escapeRegExp from "discourse/lib/escape-regexp";
import { i18n } from "discourse-i18n";
+import { hasMark, inNode } from "./plugin-utils";
/**
* @typedef {import("discourse/lib/composer/text-manipulation").TextManipulation} TextManipulation
* @typedef {import("discourse/lib/composer/text-manipulation").AutocompleteHandler} AutocompleteHandler
* @typedef {import("discourse/lib/composer/text-manipulation").PlaceholderHandler} PlaceholderHandler
+ * @typedef {import("discourse/lib/composer/text-manipulation").ToolbarState} ToolbarState
*/
/** @implements {TextManipulation} */
@@ -28,6 +31,8 @@ export default class ProsemirrorTextManipulation {
placeholder;
/** @type {AutocompleteHandler} */
autocompleteHandler;
+ /** @type {ToolbarState} */
+ state = new TrackedObject({});
convertFromMarkdown;
convertToMarkdown;
@@ -335,6 +340,22 @@ export default class ProsemirrorTextManipulation {
toggleDirection() {
this.view.dom.dir = this.view.dom.dir === "rtl" ? "ltr" : "rtl";
}
+
+ /**
+ * Updates the toolbar state object based on the current editor active states
+ */
+ updateState() {
+ Object.assign(this.state, {
+ inBold: hasMark(this.view.state, this.schema.marks.strong),
+ inItalic: hasMark(this.view.state, this.schema.marks.em),
+ inLink: hasMark(this.view.state, this.schema.marks.link),
+ inCode: hasMark(this.view.state, this.schema.marks.code),
+ inBulletList: inNode(this.view.state, this.schema.nodes.bullet_list),
+ inOrderedList: inNode(this.view.state, this.schema.nodes.ordered_list),
+ inCodeBlock: inNode(this.view.state, this.schema.nodes.code_block),
+ inBlockquote: inNode(this.view.state, this.schema.nodes.blockquote),
+ });
+ }
}
/** @implements {AutocompleteHandler} */
diff --git a/app/assets/stylesheets/common/d-editor.scss b/app/assets/stylesheets/common/d-editor.scss
index 95b6a47ee58..34f3edec62d 100644
--- a/app/assets/stylesheets/common/d-editor.scss
+++ b/app/assets/stylesheets/common/d-editor.scss
@@ -317,6 +317,7 @@
display: flex;
flex-direction: row;
flex-wrap: wrap;
+ gap: var(--space-2);
align-items: center;
margin: 0.25rem 0;
@@ -335,7 +336,7 @@
.btn {
margin: 0;
background-color: transparent;
- color: var(--primary-medium);
+ color: var(--primary-high);
border-radius: var(--d-border-radius);
.d-icon {
@@ -382,6 +383,22 @@
height: 1.25rem;
}
+.toolbar__button {
+ .d-editor-button-bar & {
+ @include viewport.from(sm) {
+ padding: 0.3em 0.45em;
+ }
+ }
+
+ &.--active {
+ background: var(--d-selected);
+
+ &.btn:hover .d-icon {
+ color: var(--primary-high);
+ }
+ }
+}
+
.d-editor #form-template-form {
overflow: auto;
background: var(--primary-very-low);
diff --git a/spec/system/composer/prosemirror_editor_spec.rb b/spec/system/composer/prosemirror_editor_spec.rb
index 2ece2cb5f43..8ced4216f10 100644
--- a/spec/system/composer/prosemirror_editor_spec.rb
+++ b/spec/system/composer/prosemirror_editor_spec.rb
@@ -644,6 +644,37 @@ describe "Composer - ProseMirror editor", type: :system do
end
end
+ describe "toolbar state updates" do
+ it "updates the toolbar state following the cursor position" do
+ open_composer_and_toggle_rich_editor
+
+ expect(page).to have_css(".toolbar__button.bold.--active", count: 0)
+ expect(page).to have_css(".toolbar__button.italic.--active", count: 0)
+ expect(page).to have_css(".toolbar__button.link.--active", count: 0)
+ expect(page).to have_css(".toolbar__button.bullet.--active", count: 0)
+ expect(page).to have_css(".toolbar__button.list.--active", count: 0)
+ expect(page).to have_css(".toolbar__button.code.--active", count: 0)
+ expect(page).to have_css(".toolbar__button.blockquote.--active", count: 0)
+
+ composer.type_content("> - ` [***many styles***](https://example.com)`")
+ composer.send_keys(:left, :left)
+
+ expect(page).to have_css(".toolbar__button.bold.--active", count: 1)
+ expect(page).to have_css(".toolbar__button.italic.--active", count: 1)
+ expect(page).to have_css(".toolbar__button.link.--active", count: 1)
+ expect(page).to have_css(".toolbar__button.bullet.--active", count: 1)
+ expect(page).to have_css(".toolbar__button.list.--active", count: 0)
+ expect(page).to have_css(".toolbar__button.code.--active", count: 1)
+ expect(page).to have_css(".toolbar__button.blockquote.--active", count: 1)
+
+ page.find(".toolbar__button.bullet").click
+ page.find(".toolbar__button.list").click
+
+ expect(page).to have_css(".toolbar__button.list.--active", count: 1)
+ expect(page).to have_css(".toolbar__button.bullet.--active", count: 0)
+ end
+ end
+
describe "trailing paragraph" do
it "ensures there is always a trailing paragraph" do
open_composer_and_toggle_rich_editor