Skip to content

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

FEATURE: rich editor image toolbar for scale/alt text/delete (#33381)

Renato Atiliod07443a72122
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 d9805ffac13..1dde9c2bf57 100644
--- a/app/assets/javascripts/discourse/app/components/composer/toolbar-buttons.gjs
+++ b/app/assets/javascripts/discourse/app/components/composer/toolbar-buttons.gjs
@@ -16,11 +16,16 @@ export default class ComposerToolbarButtons extends Component {
const { isFirst = true } = this.args;
return (
isFirst &&
- this.args.data.groups.find((group) => group.buttons?.length > 0)
- ?.buttons[0]
+ this.args.data.groups
+ .find((group) => group.buttons?.length > 0)
+ ?.buttons.filter(this.isActionable)[0]
);
}
+ isActionable(button) {
+ return button.type !== "separator" && !button.disabled;
+ }
+
get rovingButtonBar() {
return this.args.rovingButtonBar || this.args.data.rovingButtonBar;
}
diff --git a/app/assets/javascripts/discourse/app/lib/composer/rich-editor-extensions.js b/app/assets/javascripts/discourse/app/lib/composer/rich-editor-extensions.js
index 1cad1658456..2761ad1fee4 100644
--- a/app/assets/javascripts/discourse/app/lib/composer/rich-editor-extensions.js
+++ b/app/assets/javascripts/discourse/app/lib/composer/rich-editor-extensions.js
@@ -6,11 +6,25 @@
* @property {number} topicId
* @property {number} categoryId
* @property {import("discourse/models/session").default} session
+ * @property {import("float-kit/services/menu").default} menu
+ * @property {import("discourse/services/capabilities").default} capabilities
+ * @property {import("discourse/services/modal").default} modal
+ * @property {import("float-kit/services/toasts").default} toasts
+ * @property {import("discourse/models/site").default} site
+ * @property {(toolbar: import("discourse/lib/composer/toolbar").ToolbarBase) => void} replaceToolbar
+ * @property {(nodeView: import("discourse/static/prosemirror/lib/glimmer-node-view").default) => void} addGlimmerNodeView
+ * @property {(nodeView: import("discourse/static/prosemirror/lib/glimmer-node-view").default) => void} removeGlimmerNodeView
+ */
+
+/**
+ * @typedef {Object} MarkdownConversionHelpers
+ * @property {(markdown: string) => import("prosemirror-model").Node} convertFromMarkdown
+ * @property {(doc: import("prosemirror-model").Node) => string} convertToMarkdown
*/
/**
* @typedef PluginParams
- * @property {typeof import("discourse/static/prosemirror/lib/plugin-utils")} utils
+ * @property {typeof import("discourse/static/prosemirror/lib/plugin-utils") & MarkdownConversionHelpers} utils
* @property {typeof import('prosemirror-model')} pmModel
* @property {typeof import('prosemirror-view')} pmView
* @property {typeof import('prosemirror-state')} pmState
diff --git a/app/assets/javascripts/discourse/app/lib/composer/toolbar.js b/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
index 08e022d68b1..369cefe5f6b 100644
--- a/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
+++ b/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
@@ -74,7 +74,8 @@ export class ToolbarBase {
Object.defineProperties({}, Object.getOwnPropertyDescriptors(buttonAttrs))
);
- createdButton.tabindex ||= "-1";
+ createdButton.preventFocus ??= true;
+ createdButton.tabindex ??= "-1";
createdButton.className ||= buttonAttrs.id;
createdButton.condition ||= () => true;
@@ -155,7 +156,6 @@ export default class Toolbar extends ToolbarBase {
icon: boldIcon,
label: boldLabel,
shortcut: "B",
- preventFocus: true,
trimLeading: true,
perform: (e) => e.applySurround("**", "**", "bold_text"),
active: ({ state }) => state.inBold,
@@ -169,7 +169,6 @@ export default class Toolbar extends ToolbarBase {
icon: italicIcon,
label: italicLabel,
shortcut: "I",
- preventFocus: true,
trimLeading: true,
perform: (e) => e.applySurround("*", "*", "italic_text"),
active: ({ state }) => state.inItalic,
@@ -181,7 +180,6 @@ export default class Toolbar extends ToolbarBase {
icon: "link",
group: "insertions",
shortcut: "K",
- preventFocus: true,
trimLeading: true,
sendAction: (event) => this.context.send("showLinkModal", event),
active: ({ state }) => state.inLink,
@@ -193,7 +191,6 @@ export default class Toolbar extends ToolbarBase {
group: "insertions",
icon: "quote-right",
shortcut: "Shift+9",
- preventFocus: true,
perform: (e) =>
e.applyList("> ", "blockquote_text", {
applyEmptyLines: true,
@@ -208,7 +205,6 @@ export default class Toolbar extends ToolbarBase {
group: "insertions",
shortcut: "E",
icon: "code",
- preventFocus: true,
trimLeading: true,
perform: (e) => e.formatCode(),
active: ({ state }) => state.inCode || state.inCodeBlock,
@@ -220,7 +216,6 @@ export default class Toolbar extends ToolbarBase {
icon: "list-ul",
shortcut: "Shift+8",
title: "composer.ulist_title",
- preventFocus: true,
perform: (e) => e.applyList("* ", "list_item"),
active: ({ state }) => state.inBulletList,
});
@@ -231,7 +226,6 @@ export default class Toolbar extends ToolbarBase {
icon: "list-ol",
shortcut: "Shift+7",
title: "composer.olist_title",
- preventFocus: true,
perform: (e) =>
e.applyList(
(i) => (!i ? "1. " : `${parseInt(i, 10) + 1}. `),
@@ -248,7 +242,6 @@ export default class Toolbar extends ToolbarBase {
icon: "right-left",
shortcut: "Shift+6",
title: "composer.toggle_direction",
- preventFocus: true,
perform: (e) => e.toggleDirection(),
});
}
diff --git a/app/assets/javascripts/discourse/app/lib/roving-button-bar.js b/app/assets/javascripts/discourse/app/lib/roving-button-bar.js
index 87c2240d3b8..587d292b41b 100644
--- a/app/assets/javascripts/discourse/app/lib/roving-button-bar.js
+++ b/app/assets/javascripts/discourse/app/lib/roving-button-bar.js
@@ -7,7 +7,7 @@ export function rovingButtonBar(event, containerClass = null) {
} else if (event.code === "ArrowLeft") {
siblingFinder = "previousElementSibling";
} else {
- return true;
+ return false;
}
if (containerClass) {
@@ -20,22 +20,28 @@ export function rovingButtonBar(event, containerClass = null) {
}
let focusable = target[siblingFinder];
- if (focusable) {
- while (
- focusable.tagName !== "BUTTON" &&
- focusable.tagName !== "A" &&
- !focusable.classList.contains("select-kit") &&
- !focusable.classList.contains("hidden")
- ) {
- focusable = focusable[siblingFinder];
- }
+ while (focusable && !isActionable(focusable)) {
+ focusable = focusable[siblingFinder];
if (focusable?.tagName === "DETAILS") {
focusable = focusable.querySelector("summary");
}
+ }
- focusable?.focus();
+ if (!focusable) {
+ return false;
}
+ focusable.focus();
+
return true;
}
+
+function isActionable(element) {
+ return (
+ element.disabled !== true &&
+ (element.tagName === "BUTTON" || element.tagName === "A") &&
+ !element.classList.contains("select-kit") &&
+ !element.classList.contains("hidden")
+ );
+}
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/components/image-alt-text-input.gjs b/app/assets/javascripts/discourse/app/static/prosemirror/components/image-alt-text-input.gjs
new file mode 100644
index 00000000000..9bc618304a3
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/components/image-alt-text-input.gjs
@@ -0,0 +1,86 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { next } from "@ember/runloop";
+import { or } from "truth-helpers";
+import concatClass from "discourse/helpers/concat-class";
+import { i18n } from "discourse-i18n";
+
+export default class ImageAltTextInput extends Component {
+ @tracked isExpanded = false;
+
+ @tracked initialAltText = this.args.data.alt || "";
+ @tracked transientAltText = this.initialAltText;
+
+ @action
+ expandInput() {
+ this.isExpanded = true;
+
+ next(() => this.textarea.select());
+ }
+
+ @action
+ setupTextarea(element) {
+ this.textarea = element;
+ }
+
+ @action
+ onInputChange(event) {
+ this.transientAltText = event.target.value;
+ }
+
+ @action
+ onBlur(event) {
+ // helps avoid a shift of the composer window on mobile
+ const forceFocus = event.relatedTarget === this.args.data.view.dom;
+
+ this.isExpanded = false;
+ this.initialAltText = this.transientAltText;
+ this.args.data.onSave?.(this.transientAltText.trim(), forceFocus);
+ }
+
+ @action
+ onKeyDown(event) {
+ event.stopPropagation();
+ if (event.key === "Enter") {
+ event.preventDefault();
+ this.args.data.onClose?.();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ this.transientAltText = this.initialAltText;
+ this.args.data.onClose?.();
+ }
+ }
+
+ <template>
+ <div
+ class={{concatClass
+ "image-alt-text-input"
+ (if this.isExpanded "--expanded")
+ }}
+ >
+ {{#if this.isExpanded}}
+ <textarea
+ value={{this.transientAltText}}
+ placeholder={{i18n "composer.image_alt_text.title"}}
+ class="image-alt-text-input__field"
+ {{on "input" this.onInputChange}}
+ {{on "blur" this.onBlur}}
+ {{on "keydown" this.onKeyDown}}
+ {{didInsert this.setupTextarea}}
+ />
+ {{else}}
+ <div
+ tabindex="0"
+ class="image-alt-text-input__display"
+ {{on "focus" this.expandInput}}
+ {{on "click" this.expandInput}}
+ >
+ {{or this.transientAltText (i18n "composer.image_alt_text.title")}}
+ </div>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/components/image-node-view.gjs b/app/assets/javascripts/discourse/app/static/prosemirror/components/image-node-view.gjs
new file mode 100644
index 00000000000..5133030c090
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/components/image-node-view.gjs
@@ -0,0 +1,276 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import { htmlSafe } from "@ember/template";
+import { NodeSelection } from "prosemirror-state";
+import { eq } from "truth-helpers";
+import ToolbarButtons from "discourse/components/composer/toolbar-buttons";
+import { ToolbarBase } from "discourse/lib/composer/toolbar";
+import ImageAltTextInput from "./image-alt-text-input";
+
+const MIN_SCALE = 50;
+const MAX_SCALE = 100;
+const SCALE_STEP = 25;
+
+const MENU_PADDING = 8;
+
+class ImageToolbar extends ToolbarBase {
+ constructor(opts = {}) {
+ super(opts);
+
+ this.addButton({
+ id: "image-scale-down",
+ icon: "magnifying-glass-minus",
+ title: "composer.image_toolbar.zoom_out",
+ className: "composer-image-toolbar__zoom-out",
+ get disabled() {
+ return !opts.canScaleDown();
+ },
+ action: opts.scaleDown,
+ tabindex: 0,
+ });
+
+ this.addButton({
+ id: "image-scale-up",
+ icon: "magnifying-glass-plus",
+ title: "composer.image_toolbar.zoom_in",
+ className: "composer-image-toolbar__zoom-in",
+ get disabled() {
+ return !opts.canScaleUp();
+ },
+ action: opts.scaleUp,
+ tabindex: 0,
+ });
+
+ this.addButton({
+ id: "image-remove",
+ icon: "trash-can",
+ title: "composer.image_toolbar.remove",
+ className: "composer-image-toolbar__trash",
+ action: opts.removeImage,
+ tabindex: 0,
+ });
+ }
+}
+
+export default class ImageNodeView extends Component {
+ @service menu;
+
+ @tracked imageToolbar;
+ @tracked menuInstance;
+ @tracked altMenuInstance;
+
+ constructor() {
+ super(...arguments);
+
+ this.args.onSetup?.(this);
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.closeMenus();
+ }
+
+ stopEvent(event) {
+ if (["dragover", "dragend", "drop", "dragleave"].includes(event.type)) {
+ return false;
+ }
+
+ return (
+ this.menuInstance?.content?.contains(event.target) ||
+ this.altMenuInstance?.content?.contains(event.target)
+ );
+ }
+
+ @action
+ async showToolbar() {
+ this.imageToolbar ??= new ImageToolbar({
+ scaleDown: this.scaleDown.bind(this),
+ scaleUp: this.scaleUp.bind(this),
+ removeImage: this.removeImage.bind(this),
+ canScaleDown: () =>
+ !this.args.node.attrs.scale || this.args.node.attrs.scale > MIN_SCALE,
+ canScaleUp: () =>
+ this.args.node.attrs.scale && this.args.node.attrs.scale < MAX_SCALE,
+ isAltTextMenuOpen: () => this.altMenuInstance?.expanded,
+ });
+
+ this.menuInstance = await this.menu.newInstance(this.args.dom, {
+ identifier: "composer-image-toolbar",
+ component: ToolbarButtons,
+ placement: "top-start",
+ fallbackPlacements: ["top-start"],
+ padding: MENU_PADDING,
+ data: this.imageToolbar,
+ portalOutletElement: this.args.dom,
+ closeOnClickOutside: false,
+ closeOnEscape: false,
+ closeOnScroll: false,
+ trapTab: false,
+ offset({ rects }) {
+ return {
+ mainAxis: -MENU_PADDING - rects.floating.height,
+ crossAxis: MENU_PADDING,
+ };
+ },
+ limitShift: {
+ offset: ({ rects }) => {
+ const inputHeight = this.altMenuInstance?.content?.offsetHeight || 0;
+
+ return {
+ crossAxis: Math.min(
+ rects.floating.height + 2 * MENU_PADDING + inputHeight,
+ rects.reference.height - MENU_PADDING
+ ),
+ };
+ },
+ },
+ });
+
+ await this.menuInstance.show();
+ }
+
+ @action
+ removeImage() {
+ const pos = this.args.getPos();
+ this.args.view.dispatch(this.args.view.state.tr.delete(pos, pos + 1));
+ }
+
+ @action
+ async showAltText() {
+ this.altMenuInstance = await this.menu.newInstance(this.args.dom, {
+ identifier: "composer-image-alt-text",
+ component: ImageAltTextInput,
+ placement: "bottom-start",
+ fallbackPlacements: ["bottom-start"],
+ padding: MENU_PADDING,
+ data: {
+ alt: this.args.node.attrs.alt,
+ onSave: this.saveAltText,
+ onClose: () => this.args.view.focus(),
+ view: this.args.view,
+ },
+ portalOutletElement: this.args.dom,
+ closeOnClickOutside: false,
+ closeOnEscape: false,
+ closeOnScroll: false,
+ trapTab: false,
+ offset: ({ rects }) => ({
+ mainAxis: -MENU_PADDING - rects.floating.height,
+ crossAxis: MENU_PADDING,
+ }),
+ limitShift: {
+ offset: ({ rects }) => {
+ const toolbarHeight = this.menuInstance?.content?.offsetHeight || 0;
+ return {
+ crossAxis: toolbarHeight + 2 * MENU_PADDING + rects.floating.height,
+ };
+ },
+ },
+ });
+
+ await this.altMenuInstance.show();
+ }
+
+ @action
+ saveAltText(altText, forceFocus) {
+ const pos = this.args.getPos();
+ const tr = this.args.view.state.tr;
+ const newAttrs = {
+ ...this.args.node.attrs,
+ alt: altText || null,
+ };
+
+ tr.setNodeMarkup(pos, null, newAttrs);
+ tr.setSelection(NodeSelection.create(tr.doc, pos));
+ this.args.view.dispatch(tr);
+
+ if (forceFocus) {
+ this.args.view.focus();
+ }
+ }
+
+ @action
+ setupImage(element) {
+ this.image = element;
+ }
+
+ @action
+ scaleDown() {
+ const currentScale = this.args.node.attrs.scale || 100;
+ const newScale = Math.max(MIN_SCALE, currentScale - SCALE_STEP);
+ this.scaleImage(newScale);
+ }
+
+ @action
+ scaleUp() {
+ const currentScale = this.args.node.attrs.scale || 100;
+ const newScale = Math.min(MAX_SCALE, currentScale + SCALE_STEP);
+ this.scaleImage(newScale);
+ }
+
+ @action
+ scaleImage(scale) {
+ const pos = this.args.getPos();
+ const tr = this.args.view.state.tr;
+ this.args.view.dispatch(
+ tr
+ .setNodeMarkup(pos, null, {
+ ...this.args.node.attrs,
+ scale,
+ })
+ .setSelection(NodeSelection.create(tr.doc, pos))
+ );
+ }
+
+ selectNode() {
+ this.image.classList.add("ProseMirror-selectednode");
+
+ this.showToolbar();
+ this.showAltText();
+ }
+
+ deselectNode() {
+ this.image.classList.remove("ProseMirror-selectednode");
+
+ this.closeMenus();
+ }
+
+ closeMenus() {
+ this.menuInstance?.close();
+ this.menuInstance = null;
+ this.altMenuInstance?.close();
+ this.altMenuInstance = null;
+ }
+
+ get imageStyle() {
+ if (!this.args.node.attrs.width || !this.args.node.attrs.height) {
+ return null;
+ }
+
+ const scale = (this.args.node.attrs.scale || 100) / 100;
+
+ return htmlSafe(
+ `width: ${this.args.node.attrs.width * scale}px; height: ${
+ this.args.node.attrs.height * scale
+ }px;`
+ );
+ }
+
+ <template>
+ <img
+ src={{@node.attrs.src}}
+ alt={{@node.attrs.alt}}
+ title={{@node.attrs.title}}
+ width={{@node.attrs.width}}
+ height={{@node.attrs.height}}
+ data-orig-src={{@node.attrs.originalSrc}}
+ data-scale={{@node.attrs.scale}}
+ data-thumbnail={{if (eq @node.attrs.extras "thumbnail") "true"}}
+ style={{this.imageStyle}}
+ {{didInsert this.setupImage}}
+ />
+ </template>
+}
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 8d27d641db5..e0fdea50cc2 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
@@ -8,6 +8,7 @@ import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";
import { next } from "@ember/runloop";
import { service } from "@ember/service";
import "../extensions/register-default";
+import { TrackedArray } from "@ember-compat/tracked-built-ins";
import { baseKeymap } from "prosemirror-commands";
import * as ProsemirrorCommands from "prosemirror-commands";
import { dropCursor } from "prosemirror-dropcursor";
@@ -58,6 +59,8 @@ const AUTOCOMPLETE_KEY_DOWN_SUPPRESS = ["Enter", "Tab"];
* @property {ProsemirrorEditorArgs} Args
*/
+/** @typedef {import("../lib/glimmer-node-view").default} GlimmerNodeView */
+
/**
* @extends {Component<ProsemirrorEditorSignature>}
*/
@@ -73,10 +76,13 @@ export default class ProsemirrorEditor extends Component {
schema = createSchema(this.extensions, this.args.includeDefault);
view;
+ /** @type {TrackedArray<GlimmerNodeView>} */
+ glimmerNodeViews = new TrackedArray();
#lastSerialized;
/** @type {undefined | (() => void)} */
#destructor;
+ /** @type {import("discourse/lib/composer/rich-editor-extensions").PluginParams} */
get pluginParams() {
return {
utils: {
@@ -102,6 +108,12 @@ export default class ProsemirrorEditor extends Component {
toasts: this.toasts,
site: this.site,
replaceToolbar: this.args.replaceToolbar,
+ addGlimmerNodeView: (nodeView) => this.glimmerNodeViews.push(nodeView),
+ removeGlimmerNodeView: (nodeView) =>
+ this.glimmerNodeViews.splice(
+ this.glimmerNodeViews.indexOf(nodeView),
+ 1
+ ),
}),
};
}
@@ -277,7 +289,17 @@ export default class ProsemirrorEditor extends Component {
{{didUpdate this.convertFromValue @value}}
{{didUpdate this.updateContext "placeholder" @placeholder}}
{{willDestroy this.teardown}}
- >
- </div>
+ ></div>
+ {{#each this.glimmerNodeViews key="dom" as |nodeView|}}
+ {{#in-element nodeView.dom insertBefore=null}}
+ <nodeView.component
+ @node={{nodeView.node}}
+ @view={{nodeView.view}}
+ @getPos={{nodeView.getPos}}
+ @dom={{nodeView.dom}}
+ @onSetup={{nodeView.setComponentInstance}}
+ />
+ {{/in-element}}
+ {{/each}}
</template>
}
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/core/plugin.js b/app/assets/javascripts/discourse/app/static/prosemirror/core/plugin.js
index 753d47c6574..3a9dfc01ced 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/core/plugin.js
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/core/plugin.js
@@ -1,15 +1,34 @@
import { Plugin } from "prosemirror-state";
+/*
+ There are 3 ways to define a node view:
+
+ Setting a node view class directly (e.g. code-block)
+ `nodeViews: { nodeName: NodeViewClass }`
+
+ Setting a node view class as returned by a function, when plugin params are needed (e.g. footnote)
+ `nodeViews: { nodeName: (pluginParams) => NodeViewClass }`
+
+ Setting a node view instance as returned by a function, when plugin params are needed (e.g. image)
+ `nodeViews: { nodeName: (pluginParams) => (...args) => nodeViewInstance }`
+*/
export function extractNodeViews(extensions, pluginParams) {
/** @type {Record<string, import('prosemirror-view').NodeViewConstructor>} */
const allNodeViews = {};
for (const { nodeViews } of extensions) {
if (nodeViews) {
- for (let [name, NodeViewClass] of Object.entries(nodeViews)) {
- if (!NodeViewClass.toString().startsWith("class")) {
- NodeViewClass = NodeViewClass(pluginParams);
+ for (let [name, nodeView] of Object.entries(nodeViews)) {
+ // node view can be a function, to which we pass pluginParams
+ if (!nodeView.toString().startsWith("class")) {
+ nodeView = nodeView(pluginParams);
+ }
+
+ // directly or returned by the function, we may have a class
+ if (nodeView.toString().startsWith("class")) {
+ allNodeViews[name] = (...args) => new nodeView(...args);
+ } else {
+ allNodeViews[name] = nodeView;
}
- allNodeViews[name] = (...args) => new NodeViewClass(...args);
}
}
}
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/image.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/image.js
index f171dd938a0..596a91c08d1 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/image.js
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/image.js
@@ -4,28 +4,52 @@ import {
} from "pretty-text/upload-short-url";
import { ajax } from "discourse/lib/ajax";
import { isNumeric } from "discourse/lib/utilities";
+import ImageNodeView from "../components/image-node-view";
+import GlimmerNodeView from "../lib/glimmer-node-view";
const PLACEHOLDER_IMG = "/images/transparent.png";
const ALT_TEXT_REGEX =
/^(.*?)(?:\|(\d{1,4}x\d{1,4}))?(?:,\s*(\d{1,3})%)?(?:\|(.*))?$/;
+const createImageNodeView =
+ ({ getContext }) =>
+ (node, view, getPos) => {
+ if (
+ node.attrs.placeholder ||
+ node.attrs.extras === "audio" ||
+ node.attrs.extras === "video"
+ ) {
+ return null;
+ }
+
+ return new GlimmerNodeView({
+ node,
+ view,
+ getPos,
+ getContext,
+ component: ImageNodeView,
+ name: "image",
+ });
+ };
+
/** @type {RichEditorExtension} */
const extension = {
+ nodeViews: { image: createImageNodeView },
+
nodeSpec: {
image: {
inline: true,
attrs: {
- src: {},
+ src: { default: "" },
alt: { default: null },
title: { default: null },
- // Overriding ProseMirror's default node to support these attrs
width: { default: null },
height: { default: null },
originalSrc: { default: null },
extras: { default: null },
- "data-scale": { default: null },
- "data-placeholder": { default: null },
+ scale: { default: null },
+ placeholder: { default: null },
},
group: "inline",
draggable: true,
@@ -33,36 +57,43 @@ const extension = {
{
tag: "img[src]",
getAttrs(dom) {
+ const originalSrc =
+ dom.dataset.origSrc ??
+ (dom.dataset.base62Sha1
+ ? `upload://${dom.dataset.base62Sha1}`
+ : undefined);
+
+ const extras = dom.hasAttribute("data-thumbnail")
+ ? "thumbnail"
+ : undefined;
+
return {
src: dom.getAttribute("src"),
title: dom.getAttribute("title")?.replace(/\n/g, " "),
alt: dom.getAttribute("alt")?.replace(/\n/g, " "),
width: dom.getAttribute("width"),
height: dom.getAttribute("height"),
- originalSrc:
- dom.dataset.origSrc ??
- (dom.dataset.base62Sha1
- ? `upload://${dom.dataset.base62Sha1}`
- : undefined),
- extras: dom.hasAttribute("data-thumbnail")
- ? "thumbnail"
- : undefined,
+ originalSrc,
+ extras,
+ scale: dom.getAttribute("data-scale"),
+ };
+ },
+ },
+ {
+ tag: "audio source[data-orig-src]",
+ getAttrs(dom) {
+ return {
+ originalSrc: dom.getAttribute("data-orig-src"),
+ extras: "audio",
};
},
},
],
toDOM(node) {
- const width = node.attrs.width
- ? (node.attrs.width * (node.attrs["data-scale"] || 100)) / 100
- : undefined;
- const height = node.attrs.height
- ? (node.attrs.height * (node.attrs["data-scale"] || 100)) / 100
- : undefined;
-
if (node.attrs.extras === "audio") {
return [
"audio",
- { preload: "metadata", controls: false },
+ { preload: "metadata", controls: false, tabindex: -1 },
["source", { "data-orig-src": node.attrs.originalSrc }],
];
}
@@ -78,13 +109,23 @@ const extension = {
];
}
- const { originalSrc, extras, ...attrs } = node.attrs;
+ const { originalSrc, extras, scale, placeholder, ...attrs } =
+ node.attrs;
attrs["data-orig-src"] = originalSrc;
+
if (extras === "thumbnail") {
attrs["data-thumbnail"] = true;
}
- return ["img", { ...attrs, width, height }];
+ if (scale !== null) {
+ attrs["data-scale"] = scale;
+ }
+
+ if (placeholder !== null) {
+ attrs["data-placeholder"] = placeholder;
+ }
+
+ return ["img", attrs];
},
},
},
@@ -105,7 +146,7 @@ const extension = {
originalSrc: token.attrGet("data-orig-src"),
width,
height,
- "data-scale":
+ scale:
percent && isNumeric(percent) ? parseInt(percent, 10) : undefined,
extras,
};
@@ -115,14 +156,12 @@ const extension = {
serializeNode: {
image(state, node) {
- if (node.attrs["data-placeholder"]) {
+ if (node.attrs.placeholder) {
return;
}
const alt = (node.attrs.alt || "").replace(/([\\[\]`])/g, "\\$1");
- const scale = node.attrs["data-scale"]
- ? `, ${node.attrs["data-scale"]}%`
- : "";
+ const scale = node.attrs.scale ? `, ${node.attrs.scale}%` : "";
const dimensions =
node.attrs.width && node.attrs.height
? `|${node.attrs.width}x${node.attrs.height}${scale}`
@@ -138,7 +177,7 @@ const extension = {
},
},
- plugins({ pmState: { Plugin } }) {
+ plugins({ pmState: { Plugin, NodeSelection, TextSelection } }) {
const shortUrlResolver = new Plugin({
state: {
init() {
@@ -197,7 +236,31 @@ const extension = {
},
});
- return shortUrlResolver;
+ const avoidTextInputRemoval = new Plugin({
+ props: {
+ handleTextInput(view, from, to, text) {
+ const { state } = view;
+ const { selection } = state;
+
+ if (
+ selection instanceof NodeSelection &&
+ selection.node.type.name === "image"
+ ) {
+ view.dispatch(
+ state.tr
+ .setSelection(TextSelection.create(state.doc, selection.to - 1))
+ .insertText(text)
+ );
+
+ return true;
+ }
+
+ return false;
+ },
+ },
+ });
+
+ return [shortUrlResolver, avoidTextInputRemoval];
},
};
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/link-toolbar.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/link-toolbar.js
index 2acbd2ebaac..ccda1f04577 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/link-toolbar.js
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/link-toolbar.js
@@ -1,5 +1,5 @@
import { TrackedObject } from "@ember-compat/tracked-built-ins";
-import { TextSelection } from "prosemirror-state";
+import { NodeSelection, TextSelection } from "prosemirror-state";
import ToolbarButtons from "discourse/components/composer/toolbar-buttons";
import InsertHyperlink from "discourse/components/modal/insert-hyperlink";
import { ToolbarBase } from "discourse/lib/composer/toolbar";
@@ -21,7 +21,6 @@ class LinkToolbar extends ToolbarBase {
icon: "pen",
title: "composer.link_toolbar.edit",
className: "composer-link-toolbar__edit",
- preventFocus: true,
action: opts.editLink,
});
@@ -30,7 +29,6 @@ class LinkToolbar extends ToolbarBase {
icon: "copy",
title: "composer.link_toolbar.copy",
className: "composer-link-toolbar__copy",
- preventFocus: true,
action: opts.copyLink,
});
@@ -39,7 +37,6 @@ class LinkToolbar extends ToolbarBase {
icon: "link-slash",
title: "composer.link_toolbar.remove",
className: "composer-link-toolbar__unlink",
- preventFocus: true,
condition: opts.canUnlink,
action: opts.unlinkText,
});
@@ -55,7 +52,6 @@ class LinkToolbar extends ToolbarBase {
},
title: "composer.link_toolbar.visit",
className: "composer-link-toolbar__visit",
- preventFocus: true,
condition: () => opts.canVisit() || opts.canUnlink(),
get href() {
return opts.canVisit() ? opts.getHref() : null;
@@ -105,6 +101,11 @@ class LinkToolbarPluginView {
update(view) {
this.#view = view;
+ if (view.state.selection instanceof NodeSelection) {
+ this.#resetToolbar();
+ return;
+ }
+
const markRange = this.#utils.getMarkRange(
view.state.selection.$head,
view.state.schema.marks.link
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/lib/glimmer-node-view.js b/app/assets/javascripts/discourse/app/static/prosemirror/lib/glimmer-node-view.js
new file mode 100644
index 00000000000..9a7a2c144a5
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/lib/glimmer-node-view.js
@@ -0,0 +1,71 @@
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+
+/**
+ * @typedef {Object} GlimmerNodeViewArgs
+ * @property {import("prosemirror-model").Node} node
+ * @property {import("prosemirror-view").EditorView} view
+ * @property {() => number} getPos
+ * @property {() => import("discourse/lib/composer/rich-editor-extensions").PluginContext} getContext
+ * @property {any} component
+ * @property {string} name
+ */
+export default class GlimmerNodeView {
+ @tracked node;
+
+ #componentInstance;
+
+ /**
+ * @param {GlimmerNodeViewArgs} args
+ */
+ constructor({ node, view, getPos, getContext, component, name }) {
+ this.node = node;
+ this.view = view;
+ this.getPos = getPos;
+ this.getContext = getContext;
+ this.component = component;
+
+ getContext().addGlimmerNodeView(this);
+
+ this.dom = document.createElement("div");
+ this.dom.classList.add(`composer-${name}-node`);
+ }
+
+ @action
+ setComponentInstance(instance) {
+ this.#componentInstance = instance;
+ }
+
+ update(node) {
+ this.node = node;
+
+ return true;
+ }
+
+ selectNode() {
+ this.#componentInstance?.selectNode?.();
+ }
+
+ deselectNode() {
+ this.#componentInstance?.deselectNode?.();
+ }
+
+ setSelection() {
+ this.#componentInstance?.setSelection?.(...arguments);
+ }
+
+ stopEvent(event) {
+ return this.#componentInstance?.stopEvent?.(event) ?? false;
+ }
+
+ ignoreMutation() {
+ return this.#componentInstance?.ignoreMutation?.() ?? true;
+ }
+
+ destroy() {
+ this.#componentInstance?.destroy?.();
+ this.#componentInstance = null;
+
+ this.getContext().removeGlimmerNodeView(this);
+ }
+}
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 5e2a0588148..286de9b1e09 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
@@ -472,7 +472,7 @@ class ProsemirrorPlaceholderHandler {
alt: i18n("uploading_filename", { filename: file.name }),
title: file.id,
width: 120,
- "data-placeholder": true,
+ placeholder: true,
});
this.view.dispatch(
@@ -490,10 +490,7 @@ class ProsemirrorPlaceholderHandler {
cancelAll() {
this.view.state.doc.descendants((node, pos) => {
- if (
- node.type === this.schema.nodes.image &&
- node.attrs["data-placeholder"]
- ) {
+ if (node.type === this.schema.nodes.image && node.attrs.placeholder) {
this.view.dispatch(this.view.state.tr.delete(pos, pos + node.nodeSize));
}
});
@@ -503,8 +500,8 @@ class ProsemirrorPlaceholderHandler {
this.view.state.doc.descendants((node, pos) => {
if (
node.type === this.schema.nodes.image &&
- node.attrs["data-placeholder"] &&
- node.attrs?.title === file.id
+ node.attrs.placeholder &&
+ node.attrs.title === file.id
) {
this.view.dispatch(this.view.state.tr.delete(pos, pos + node.nodeSize));
}
@@ -517,8 +514,8 @@ class ProsemirrorPlaceholderHandler {
this.view.state.doc.descendants((node, pos) => {
if (
node.type === this.schema.nodes.image &&
- node.attrs["data-placeholder"] &&
- node.attrs?.title === file.id
+ node.attrs.placeholder &&
+ node.attrs.title === file.id
) {
nodeToReplace = { node, pos };
return false;
diff --git a/app/assets/javascripts/discourse/tests/helpers/rich-editor-helper.gjs b/app/assets/javascripts/discourse/tests/helpers/rich-editor-helper.gjs
index 2b27b5d7dde..2c155a00c6a 100644
--- a/app/assets/javascripts/discourse/tests/helpers/rich-editor-helper.gjs
+++ b/app/assets/javascripts/discourse/tests/helpers/rich-editor-helper.gjs
@@ -91,3 +91,26 @@ export async function testMarkdown(
`Markdown should match for "${markdown}"`
);
}
+
+/**
+ * Helper to test rendered markdown with DOM assertions
+ * @param {string} markdown - The markdown to render
+ * @param {Function} assertions - Function to run assertions on the rendered HTML
+ * @returns {Function} - A test function that can be passed to QUnit's test()
+ */
+export function testRenderedMarkdown(markdown, assertions) {
+ return async function (assert) {
+ this.siteSettings.rich_editor = true;
+
+ const [editorClass] = await setupRichEditor(assert, markdown);
+
+ // The editor is already in the DOM, so we can use assert.dom directly
+ assertions(assert, editorClass);
+
+ assert.strictEqual(
+ editorClass.value,
+ markdown,
+ `Markdown should match for "${markdown}"`
+ );
+ };
+}
diff --git a/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/image-test.js b/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/image-test.js
index b047ff961a3..d2fbfcfa87a 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/image-test.js
+++ b/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/image-test.js
@@ -1,65 +1,158 @@
import { module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import { testMarkdown } from "discourse/tests/helpers/rich-editor-helper";
+import { testRenderedMarkdown } from "discourse/tests/helpers/rich-editor-helper";
module(
"Integration | Component | prosemirror-editor - image extension",
function (hooks) {
setupRenderingTest(hooks);
- const testCases = {
- image: [
- [
- "![alt text](https://example.com/image.jpg)",
- '<p><img src="https://example.com/image.jpg" alt="alt text" contenteditable="false" draggable="true"></p>',
- "![alt text](https://example.com/image.jpg)",
- ],
- [
- "![alt text](https://example.com/image.jpg 'title')",
- '<p><img src="https://example.com/image.jpg" alt="alt text" title="title" contenteditable="false" draggable="true"></p>',
- '![alt text](https://example.com/image.jpg "title")',
- ],
- [
- '![alt text|100x200](https://example.com/image.jpg "title")',
- '<p><img src="https://example.com/image.jpg" alt="alt text" title="title" width="100" height="200" contenteditable="false" draggable="true"></p>',
- '![alt text|100x200](https://example.com/image.jpg "title")',
- ],
- [
- "![alt text|100x200, 50%](https://example.com/image.jpg)",
- '<p><img src="https://example.com/image.jpg" alt="alt text" width="50" height="100" data-scale="50" contenteditable="false" draggable="true"></p>',
- "![alt text|100x200, 50%](https://example.com/image.jpg)",
- ],
- [
- "![alt text|100x200, 50%|thumbnail](https://example.com/image.jpg)",
- '<p><img src="https://example.com/image.jpg" alt="alt text" width="50" height="100" data-scale="50" data-thumbnail="true" contenteditable="false" draggable="true"></p>',
- "![alt text|100x200, 50%|thumbnail](https://example.com/image.jpg)",
- ],
- [
- "![alt text](https://example.com/image(1).jpg)",
- '<p><img src="https://example.com/image(1).jpg" alt="alt text" contenteditable="false" draggable="true"></p>',
- "![alt text](https://example.com/image\\(1\\).jpg)",
- ],
- [
- "![alt text|video](uploads://hash)",
- '<p><div class="onebox-placeholder-container" contenteditable="false" draggable="true"><span class="placeholder-icon video"></span></div></p>',
- "![alt text|video](uploads://hash)",
- ],
- [
- "![alt text|audio](upload://hash)",
- '<p><audio preload="metadata" controls="false" contenteditable="false" draggable="true"><source data-orig-src="upload://hash"></audio></p>',
- "![alt text|audio](upload://hash)",
- ],
- ],
- };
+ test(
+ "basic image",
+ testRenderedMarkdown(
+ "![alt text](https://example.com/image.jpg)",
+ (assert) => {
+ assert.dom("img").exists("Image should exist");
+ assert
+ .dom("img")
+ .hasAttribute("src", "https://example.com/image.jpg");
+ assert.dom("img").hasAttribute("alt", "alt text");
+ }
+ )
+ );
- Object.entries(testCases).forEach(([name, tests]) => {
- tests.forEach(([markdown, expectedHtml, expectedMarkdown]) => {
- test(name, async function (assert) {
- this.siteSettings.rich_editor = true;
+ test(
+ "image with title",
+ testRenderedMarkdown(
+ '![alt text](https://example.com/image.jpg "title")',
+ (assert) => {
+ assert.dom("img").exists("Image should exist");
+ assert
+ .dom("img")
+ .hasAttribute("src", "https://example.com/image.jpg");
+ assert.dom("img").hasAttribute("alt", "alt text");
+ assert.dom("img").hasAttribute("title", "title");
+ }
+ )
+ );
- await testMarkdown(assert, markdown, expectedHtml, expectedMarkdown);
- });
- });
- });
+ test(
+ "image with dimensions and title",
+ testRenderedMarkdown(
+ '![alt text|100x200](https://example.com/image.jpg "title")',
+ (assert) => {
+ assert.dom("img").exists("Image should exist");
+ assert
+ .dom("img")
+ .hasAttribute("src", "https://example.com/image.jpg");
+ assert.dom("img").hasAttribute("alt", "alt text");
+ assert.dom("img").hasAttribute("title", "title");
+ assert.dom("img").hasAttribute("width", "100");
+ assert.dom("img").hasAttribute("height", "200");
+ }
+ )
+ );
+
+ test(
+ "image with dimensions and scale",
+ testRenderedMarkdown(
+ "![alt text|100x200, 50%](https://example.com/image.jpg)",
+ (assert) => {
+ assert.dom("img").exists("Image should exist");
+ assert
+ .dom("img")
+ .hasAttribute("src", "https://example.com/image.jpg");
+ assert.dom("img").hasAttribute("alt", "alt text");
+ assert.dom("img").hasAttribute("width", "100");
+ assert.dom("img").hasAttribute("height", "200");
+ assert.dom("img").hasAttribute("data-scale", "50");
+
+ // Check style attribute directly
+ const img = document.querySelector("img");
+ assert.strictEqual(
+ img.style.width,
+ "50px",
+ "Image width style should be 50px"
+ );
+ assert.strictEqual(
+ img.style.height,
+ "100px",
+ "Image height style should be 100px"
+ );
+ }
+ )
+ );
+
+ test(
+ "image with dimensions, scale and thumbnail",
+ testRenderedMarkdown(
+ "![alt text|100x200, 50%|thumbnail](https://example.com/image.jpg)",
+ (assert) => {
+ assert.dom("img").exists("Image should exist");
+ assert
+ .dom("img")
+ .hasAttribute("src", "https://example.com/image.jpg");
+ assert.dom("img").hasAttribute("alt", "alt text");
+ assert.dom("img").hasAttribute("width", "100");
+ assert.dom("img").hasAttribute("height", "200");
+ assert.dom("img").hasAttribute("data-scale", "50");
+ assert.dom("img").hasAttribute("data-thumbnail", "true");
+
+ // Check style attribute directly
+ const img = document.querySelector("img");
+ assert.strictEqual(
+ img.style.width,
+ "50px",
+ "Image width style should be 50px"
+ );
+ assert.strictEqual(
+ img.style.height,
+ "100px",
+ "Image height style should be 100px"
+ );
+ }
+ )
+ );
+
+ test(
+ "image with parentheses in URL",
+ testRenderedMarkdown(
+ "![alt text](https://example.com/image\\(1\\).jpg)",
+ (assert) => {
+ assert.dom("img").exists("Image should exist");
+ assert
+ .dom("img")
+ .hasAttribute("src", "https://example.com/image(1).jpg");
+ assert.dom("img").hasAttribute("alt", "alt text");
+ }
+ )
+ );
+
+ test(
+ "video placeholder",
+ testRenderedMarkdown("![alt text|video](upload://hash)", (assert) => {
+ assert
+ .dom(".onebox-placeholder-container")
+ .exists("Video placeholder should exist");
+ assert
+ .dom(".onebox-placeholder-container")
+ .hasAttribute("data-orig-src", "upload://hash");
+ assert
+ .dom(".placeholder-icon.video")
+ .exists("Video placeholder icon should exist");
+ })
+ );
+
+ test(
+ "audio element",
+ testRenderedMarkdown("![alt text|audio](upload://hash)", (assert) => {
+ assert.dom("audio").exists("Audio element should exist");
+ assert.dom("audio").hasAttribute("preload", "metadata");
+ assert.dom("audio source").exists("Audio source should exist");
+ assert
+ .dom("audio source")
+ .hasAttribute("data-orig-src", "upload://hash");
+ })
+ );
}
);
diff --git a/app/assets/javascripts/float-kit/addon/lib/update-position.js b/app/assets/javascripts/float-kit/addon/lib/update-position.js
index 79eed829025..233b3df4f80 100644
--- a/app/assets/javascripts/float-kit/addon/lib/update-position.js
+++ b/app/assets/javascripts/float-kit/addon/lib/update-position.js
@@ -4,6 +4,7 @@ import {
flip,
hide,
inline,
+ limitShift,
offset,
shift,
} from "@floating-ui/dom";
@@ -40,14 +41,19 @@ export async function updatePosition(trigger, content, options) {
if (isCentered) {
middleware.push(centerOffset);
} else {
- middleware.push(offset(options.offset ? parseInt(options.offset, 10) : 10));
+ middleware.push(offset(options.offset ?? 10));
if (options.inline) {
middleware.push(inline());
}
middleware.push(flip(flipOptions));
- middleware.push(shift({ padding }));
+
+ let limiter;
+ if (options.limitShift) {
+ limiter = limitShift(options.limitShift);
+ }
+ middleware.push(shift({ padding, limiter, crossAxis: true }));
}
let arrowElement;
diff --git a/app/assets/javascripts/float-kit/addon/services/menu.js b/app/assets/javascripts/float-kit/addon/services/menu.js
index ae90f7eee24..72a256450c1 100644
--- a/app/assets/javascripts/float-kit/addon/services/menu.js
+++ b/app/assets/javascripts/float-kit/addon/services/menu.js
@@ -42,11 +42,7 @@ export default class Menu extends Service {
(registeredMenu) => registeredMenu.trigger === arguments[0]
);
- if (!instance) {
- instance = new DMenuInstance(getOwner(this), arguments[1]);
- instance.trigger = arguments[0];
- instance.detachedTrigger = true;
- }
+ instance ??= this.newInstance(arguments[0], arguments[1]);
}
if (instance.options.identifier || instance.options.groupIdentifier) {
@@ -81,6 +77,14 @@ export default class Menu extends Service {
return instance;
}
+ newInstance(trigger, options) {
+ const instance = new DMenuInstance(getOwner(this), options);
+ instance.trigger = trigger;
+ instance.detachedTrigger = true;
+
+ return instance;
+ }
+
/**
* Returns an existing menu by its identifier if found
*
diff --git a/app/assets/stylesheets/common/rich-editor/rich-editor.scss b/app/assets/stylesheets/common/rich-editor/rich-editor.scss
index a7f0c43fb60..4643ad3afc8 100644
--- a/app/assets/stylesheets/common/rich-editor/rich-editor.scss
+++ b/app/assets/stylesheets/common/rich-editor/rich-editor.scss
@@ -53,6 +53,7 @@
display: inline-block;
height: auto;
max-width: 100%;
+ border-radius: var(--d-border-radius);
&[data-placeholder="true"] {
animation: placeholder 1.5s infinite;
@@ -195,17 +196,21 @@
}
}
-.fk-d-menu[data-identifier="composer-link-toolbar"] {
- z-index: z("composer", "dropdown") + 1;
- animation: fade-in ease 0.25s 1 forwards;
+.fk-d-menu[data-identifier="composer-link-toolbar"],
+.fk-d-menu[data-identifier="composer-image-toolbar"],
+.fk-d-menu[data-identifier="composer-image-alt-text"] {
+ user-select: none;
+ z-index: z("composer", "dropdown");
+ animation: fade-in ease 0.25s 1 forwards !important;
.fk-d-menu__inner-content {
overflow: visible;
}
- .btn {
+ .toolbar__button {
background-color: var(--secondary);
color: var(--primary-medium);
+ border-radius: var(--d-border-radius);
.d-icon {
color: var(--primary-medium);
@@ -226,6 +231,10 @@
&:focus-visible {
@include default-focus;
}
+
+ &.--active {
+ background: var(--d-selected);
+ }
}
.composer-link-toolbar__visit {
@@ -259,6 +268,110 @@
}
}
+.fk-d-menu[data-identifier="composer-image-alt-text"] {
+ width: calc(100% - 1rem);
+ min-width: calc(max(100% - 1rem, 7.25rem));
+ background-color: rgb(var(--secondary-rgb), 0.65);
+ backdrop-filter: blur(4px);
+ color: var(--primary);
+ isolation: auto;
+ border-radius: var(--d-border-radius);
+ font-size: var(--font-down-1);
+ box-shadow: var(--shadow-dropdown);
+
+ .fk-d-menu__inner-content {
+ width: 100%;
+ box-sizing: border-box;
+ border: none;
+ box-shadow: none;
+ background-color: transparent;
+ min-width: 100%;
+ padding: 0.25rem 0.5rem;
+ }
+
+ &:focus-within {
+ box-shadow: 0 0 0 2px var(--tertiary-high);
+ }
+
+ &:has(.image-alt-text-input.--expanded) {
+ min-width: calc(max(100% - 1rem, 15rem));
+ }
+ transition: min-width 0.15s ease;
+}
+
+.composer-image-node {
+ display: inline-block;
+ white-space: normal;
+ position: relative;
+
+ // This makes the editor less pixel perfect with cooked, but it helps with some
+ // hard positions (like between images), and makes the blinking cursor more visible
+ // The vertical offset increases the drop area between image paragraphs
+ margin: -2px 1px;
+ padding: 2px 1px;
+
+ img {
+ transition:
+ width 0.2s ease,
+ height 0.2s ease;
+
+ &:not(.ProseMirror-selectednode):hover {
+ cursor: pointer;
+ }
+
+ &.ProseMirror-selectednode {
+ user-select: none;
+ }
+ }
+}
+
+.image-alt-text-input {
+ min-width: 100%;
+ display: flex;
+ position: relative;
+ transition: height 0.15s ease;
+ height: 1.5em;
+
+ @media (prefers-reduced-motion: reduce) {
+ transition: none;
+ }
+
+ &.--expanded {
+ height: 4.25em;
+ }
+
+ &__field {
+ flex: 1;
+ border: none;
+ outline: none;
+ padding: 0;
+ background: transparent;
+ resize: none;
+ margin: 0;
+ scrollbar-color: rgb(var(--primary-rgb), 0.3) transparent;
+ scrollbar-width: thin;
+ overflow-y: auto;
+ scrollbar-gutter: stable;
+ line-height: var(--line-height-large);
+
+ &::placeholder {
+ color: var(--primary);
+ }
+
+ &:focus {
+ outline: none;
+ }
+ }
+
+ &__display {
+ cursor: pointer;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ flex: 1;
+ }
+}
+
/*********************************************************
Section below from prosemirror-view/style/prosemirror.css
********************************************************/
@@ -292,7 +405,7 @@
}
.ProseMirror-selectednode {
- outline: 2px solid #8cf;
+ outline: 2px solid var(--tertiary-high);
border-radius: var(--d-border-radius);
}
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index b7e155b0f89..8bd833cbf09 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -2941,6 +2941,12 @@ en:
aria_label: Alt text for image
title: "Add image description"
+ image_toolbar:
+ alt_text: "Add image description"
+ zoom_out: "Decrease image size"
+ zoom_in: "Increase image size"
+ remove: "Remove image"
+
image_scale_button: "Scale image to %{percent}%"
delete_image_button: Delete Image
toggle_image_grid: Toggle image grid
@@ -3370,7 +3376,7 @@ en:
hot: "There are no hot topics."
filter: "There are no topics."
education:
- topic_tracking_preferences: "You can view and change your new topic tracking settings in <a href=\"%{basePath}/my/preferences/tracking\">your preferences</a>."
+ topic_tracking_preferences: 'You can view and change your new topic tracking settings in <a href="%{basePath}/my/preferences/tracking">your preferences</a>.'
unread: "Nothing left unread...impressive!"
new_new: "Nothing new at the moment...check back soon!"
new: "Nothing new at the moment...check back soon!"
diff --git a/spec/system/composer/prosemirror_editor_spec.rb b/spec/system/composer/prosemirror_editor_spec.rb
index 8ced4216f10..cb098ded85d 100644
--- a/spec/system/composer/prosemirror_editor_spec.rb
+++ b/spec/system/composer/prosemirror_editor_spec.rb
@@ -20,6 +20,13 @@ describe "Composer - ProseMirror editor", type: :system do
composer.focus
end
+ def paste_and_click_image
+ cdp.allow_clipboard
+ cdp.copy_test_image
+ cdp.paste
+ rich.find(".composer-image-node img").click
+ end
+
it "hides the Composer container's preview button" do
page.visit "/new-topic"
@@ -602,7 +609,7 @@ describe "Composer - ProseMirror editor", type: :system do
lines">
HTML
- img = rich.find("img:nth-of-type(1)")
+ img = rich.find(".composer-image-node img")
expect(img["src"]).to eq("https://example.com/image.png")
expect(img["alt"]).to eq("alt with new lines")
@@ -616,10 +623,8 @@ describe "Composer - ProseMirror editor", type: :system do
end
it "ignores text/html content if Files are present" do
- cdp.allow_clipboard
open_composer_and_toggle_rich_editor
- cdp.copy_test_image
- cdp.paste
+ paste_and_click_image
expect(rich).to have_css("img[data-orig-src]", count: 1)
@@ -1140,4 +1145,102 @@ describe "Composer - ProseMirror editor", type: :system do
)
end
end
+
+ describe "image toolbar" do
+ it "allows scaling image down and up via toolbar" do
+ open_composer_and_toggle_rich_editor
+ paste_and_click_image
+
+ find(".composer-image-toolbar__zoom-out").click
+
+ expect(rich.find(".composer-image-node img")["data-scale"]).to eq("75")
+
+ find(".composer-image-toolbar__zoom-out").click
+
+ expect(rich.find(".composer-image-node img")["data-scale"]).to eq("50")
+
+ find(".composer-image-toolbar__zoom-in").click
+
+ expect(rich.find(".composer-image-node img")["data-scale"]).to eq("75")
+
+ find(".composer-image-toolbar__zoom-in").click
+
+ expect(rich.find(".composer-image-node img")["data-scale"]).to eq("100")
+ end
+
+ it "allows removing image via toolbar" do
+ open_composer_and_toggle_rich_editor
+ composer.type_content("Before")
+ paste_and_click_image
+
+ find(".composer-image-toolbar__trash").click
+
+ expect(rich).to have_no_css(".composer-image-node img")
+ expect(rich).to have_content("Before")
+ end
+
+ it "hides toolbar when clicking outside image" do
+ open_composer_and_toggle_rich_editor
+ paste_and_click_image
+
+ expect(page).to have_css("[data-identifier='composer-image-toolbar']")
+
+ rich.find("p").click
+
+ expect(page).to have_no_css("[data-identifier='composer-image-toolbar']")
+ end
+ end
+
+ describe "image alt text display and editing" do
+ it "shows alt text input when image is selected" do
+ open_composer_and_toggle_rich_editor
+ paste_and_click_image
+
+ expect(page).to have_css("[data-identifier='composer-image-alt-text']")
+ expect(page).to have_css(".image-alt-text-input__display")
+ end
+
+ it "allows editing alt text by clicking on display" do
+ open_composer_and_toggle_rich_editor
+ paste_and_click_image
+
+ find(".image-alt-text-input__display").click
+
+ expect(page).to have_css(".image-alt-text-input.--expanded")
+ expect(page).to have_css(".image-alt-text-input__field")
+
+ find(".image-alt-text-input__field").fill_in(with: "updated alt text")
+ find(".image-alt-text-input__field").send_keys(:enter)
+
+ expect(rich.find(".composer-image-node img")["alt"]).to eq("updated alt text")
+ end
+
+ it "saves alt text when leaving the input field" do
+ open_composer_and_toggle_rich_editor
+ paste_and_click_image
+
+ find(".image-alt-text-input__display").click
+ find(".image-alt-text-input__field").fill_in(with: "new alt text")
+
+ rich.find("p").click
+
+ expect(rich.find(".composer-image-node img")["alt"]).to eq("new alt text")
+ end
+
+ it "displays the placeholder if alt text is empty" do
+ open_composer_and_toggle_rich_editor
+ paste_and_click_image
+
+ expect(page).to have_css(".image-alt-text-input__display", text: "image")
+
+ find(".image-alt-text-input__display").click
+ find(".image-alt-text-input__field").fill_in(with: "")
+ find(".image-alt-text-input__field").send_keys(:enter)
+
+ expect(page).to have_css(
+ ".image-alt-text-input__display",
+ text: I18n.t("js.composer.image_alt_text.title"),
+ )
+ end
+ end
end