Skip to content

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

DEV: Build composer image controls in a decorator (#44261)

David Taylorcf9af5961acb
diff --git a/frontend/discourse-markdown-it/src/features/image-controls.js b/frontend/discourse-markdown-it/src/features/image-controls.js
index 6103eee19e5..0b8ee4a5729 100644
--- a/frontend/discourse-markdown-it/src/features/image-controls.js
+++ b/frontend/discourse-markdown-it/src/features/image-controls.js
@@ -1,39 +1,5 @@
-import { i18n } from "discourse-i18n";
-
const SCALES = ["100", "75", "50"];
-let apiExtraButton = [];
-let apiExtraButtonAllowList = [];
-
-export function addImageWrapperButton(
- label,
- btnClass,
- icon = null,
- includeCondition = null
-) {
- const markup = [];
- markup.push(`<span class="${btnClass}">`);
- if (icon) {
- markup.push(`
- <svg class="fa d-icon d-icon-${icon} svg-icon svg-string" xmlns="http://www.w3.org/2000/svg">
- <use href="#${icon}"></use>
- </svg>
- `);
- }
- markup.push(label);
- markup.push("</span>");
-
- apiExtraButton.push({
- markup: markup.join(""),
- condition: includeCondition,
- });
- apiExtraButtonAllowList.push(`span.${btnClass}`);
- apiExtraButtonAllowList.push(
- `svg[class=fa d-icon d-icon-${icon} svg-icon svg-string]`
- );
- apiExtraButtonAllowList.push(`use[href=#${icon}]`);
-}
-
function isUpload(token) {
return token.content.includes("upload://");
}
@@ -56,8 +22,20 @@ function appendMetaData(index, token) {
selectedScale = "100";
}
- token.attrs.push(["index-image", index]);
- token.attrs.push(["scale", selectedScale]);
+ token.attrs.push(["data-image-index", index]);
+ token.attrs.push(["data-scale", selectedScale]);
+}
+
+// Count here, as the preview can drop images and can't show which were grouped.
+function appendRunLength(tokens) {
+ const first = tokens[0];
+
+ if (first?.tag === "img" && first.attrIndex("data-image-index") !== -1) {
+ first.attrs.push([
+ "data-image-run",
+ tokens.filter((token) => token.type === "image").length,
+ ]);
+ }
}
function rule(state) {
@@ -85,180 +63,26 @@ function rule(state) {
currentIndex++;
}
}
- }
-}
-
-function buildScaleButton(selectedScale, scale) {
- const activeScaleClass = selectedScale === scale ? " active" : "";
- return `<span title="
- ${i18n("composer.image_scale_button", { percent: scale })}"
- class='scale-btn${activeScaleClass}' data-scale='${scale}'
- >
- ${scale}%
- </span>`;
-}
-function buildImageShowAltTextControls(altText) {
- return `
- <span class="alt-text-readonly-container">
- <span class="alt-text-edit-btn"
- title="${i18n("composer.image_alt_text.title")}"
- >
- <svg aria-hidden="true" class="fa d-icon d-icon-pencil svg-icon svg-string"><use href="#pencil"></use></svg>
- </span>
- <span class="alt-text"
- aria-label="${i18n("composer.image_alt_text.aria_label")}"
- >${altText}</span>
- </span>
- `;
-}
-
-function buildImageEditAltTextControls(altText) {
- return `
- <span class="alt-text-edit-container" hidden="true">
- <input class="alt-text-input" type="text" value="${altText}" />
- <button class="alt-text-edit-ok btn btn-primary">
- <svg class="fa d-icon d-icon-check svg-icon svg-string"><use href="#check"></use></svg>
- </button>
- <button class="alt-text-edit-cancel btn btn-default">
- <svg class="fa d-icon d-icon-xmark svg-icon svg-string"><use href="#xmark"></use></svg>
- </button>
- </span>
- `;
-}
-
-function buildImageDeleteButton() {
- return `
- <span class="delete-image-button"
- title="${i18n("composer.delete_image_button")}"
- aria-label="${i18n("composer.delete_image_button")}"
- >
- <svg class="fa d-icon d-icon-trash-can svg-icon svg-string" xmlns="http://www.w3.org/2000/svg">
- <use href="#trash-can"></use>
- </svg>
- </span>
- `;
-}
+ appendRunLength(blockToken.children);
+ }
-function buildImageGalleryControl(imageCount) {
- return `
- <span class="wrap-image-grid-button" title="${i18n(
- "composer.toggle_image_grid"
- )}" data-image-count="${imageCount}">
- <svg class="fa d-icon d-icon-table-cells svg-icon svg-string" xmlns="http://www.w3.org/2000/svg">
- <use href="#table-cells"></use>
- </svg>
- </span>
- `;
+ appendRunLength(state.tokens);
}
// We need this to load after `upload-protocol` which is priority 0
export const priority = 1;
-function ruleWithImageControls(oldRule) {
- return function (tokens, idx, options, env, slf) {
- const token = tokens[idx];
- const scaleIndex = token.attrIndex("scale");
- const imageIndex = token.attrIndex("index-image");
-
- if (scaleIndex !== -1) {
- let selectedScale = token.attrs[scaleIndex][1];
- let index = token.attrs[imageIndex][1];
-
- let result = `<span class="image-wrapper">`;
-
- result += oldRule(tokens, idx, options, env, slf);
-
- result += `<span class="button-wrapper" data-image-index="${index}">`;
- if (idx === 0) {
- const imageCount = tokens.filter((x) => x.type === "image").length;
- if (imageCount > 1) {
- result += buildImageGalleryControl(imageCount);
- }
- }
- result += buildImageShowAltTextControls(
- token.attrs[token.attrIndex("alt")][1]
- );
- result += buildImageEditAltTextControls(
- token.attrs[token.attrIndex("alt")][1]
- );
-
- result += `<span class="scale-btn-container">`;
- result += SCALES.map((scale) =>
- buildScaleButton(selectedScale, scale)
- ).join("");
- result += `</span>`;
- result += buildImageDeleteButton();
-
- // Get upload URL from token for conditional button rendering
- const origSrcIndex = token.attrIndex("data-orig-src");
- const uploadUrl =
- origSrcIndex !== -1 ? token.attrs[origSrcIndex][1] : null;
-
- // Add API extra buttons with optional conditions
- apiExtraButton.forEach((button) => {
- if (!button.condition || button.condition(uploadUrl)) {
- result += button.markup;
- }
- });
-
- result += "</span></span>";
-
- return result;
- } else {
- return oldRule(tokens, idx, options, env, slf);
- }
- };
-}
-
export function setup(helper) {
const opts = helper.getOptions();
if (opts.previewing) {
helper.allowList([
- "span.image-wrapper",
- "span.button-wrapper",
- "span[class=scale-btn-container]",
- "span[class=scale-btn]",
- "span[class=scale-btn active]",
- "span.separator",
- "span.scale-btn[data-scale]",
- "span.button-wrapper[data-image-index]",
- "span[aria-label]",
- "span[class=delete-image-button]",
- "span.alt-text-container",
- "span.alt-text-readonly-container",
- "span.alt-text-readonly-container.alt-text",
- "span.alt-text-readonly-container.alt-text-edit-btn",
- "svg[class=fa d-icon d-icon-pencil svg-icon svg-string]",
- "use[href=#pencil]",
- "use[href=#trash-can]",
-
- "span.alt-text-edit-container",
- "span.delete-image-button",
- "span[hidden=true]",
- "input[type=text]",
- "input[class=alt-text-input]",
- "button[class=alt-text-edit-ok btn btn-primary]",
- "svg[class=fa d-icon d-icon-check svg-icon svg-string]",
- "use[href=#check]",
- "button[class=alt-text-edit-cancel btn btn-default]",
- "svg[class=fa d-icon d-icon-xmark svg-icon svg-string]",
- "svg[class=fa d-icon d-icon-trash-can svg-icon svg-string]",
- "use[href=#xmark]",
-
- "span.wrap-image-grid-button",
- "span.wrap-image-grid-button[data-image-count]",
- "svg[class=fa d-icon d-icon-table-cells svg-icon svg-string]",
- "use[href=#table-cells]",
-
- ...apiExtraButtonAllowList,
+ "img[data-image-index]",
+ "img[data-image-run]",
+ "img[data-scale]",
]);
helper.registerPlugin((md) => {
- const oldRule = md.renderer.rules.image;
-
- md.renderer.rules.image = ruleWithImageControls(oldRule);
-
md.core.ruler.after("upload-protocol", "resize-controls", rule);
});
}
diff --git a/frontend/discourse/app/components/composer-editor.gjs b/frontend/discourse/app/components/composer-editor.gjs
index ac0f53669f6..bb0375a23bb 100644
--- a/frontend/discourse/app/components/composer-editor.gjs
+++ b/frontend/discourse/app/components/composer-editor.gjs
@@ -19,6 +19,7 @@ import lazyHash from "discourse/helpers/lazy-hash";
import { ajax } from "discourse/lib/ajax";
import { tinyAvatar } from "discourse/lib/avatar-utils";
import { setupComposerPosition } from "discourse/lib/composer/composer-position";
+import { decorateImageControls } from "discourse/lib/composer/image-controls";
import { bind, debounce } from "discourse/lib/decorators";
import prepareFormTemplateData from "discourse/lib/form-template-validation";
import {
@@ -408,7 +409,13 @@ export default class ComposerEditor extends Component {
const matchingPlaceholder = this.get("composer.model.reply").match(
IMAGE_MARKDOWN_REGEX
);
- const match = matchingPlaceholder[index];
+ const match = matchingPlaceholder?.[index];
+
+ if (!match) {
+ this.resetImageControls(buttonWrapper);
+ return;
+ }
+
const input = buttonWrapper.querySelector("input.alt-text-input");
const replacement = match.replace(
IMAGE_MARKDOWN_REGEX,
@@ -475,6 +482,8 @@ export default class ComposerEditor extends Component {
@action
previewUpdated(preview, helper) {
+ decorateImageControls(preview);
+
this._renderMentions(preview);
this._renderHashtags(preview);
this._refreshOneboxes(preview);
@@ -869,6 +878,11 @@ export default class ComposerEditor extends Component {
const matchingPlaceholder = this.get("composer.model.reply").match(
IMAGE_MARKDOWN_REGEX
);
+
+ if (!matchingPlaceholder?.[index]) {
+ return;
+ }
+
this.appEvents.trigger(
`${this.composerEventPrefix}:replace-text`,
matchingPlaceholder[index],
@@ -892,6 +906,10 @@ export default class ComposerEditor extends Component {
const closingIndex =
index + parseInt(event.target.dataset.imageCount, 10) - 1;
+ if (!matches?.[index] || !matches[closingIndex]) {
+ return;
+ }
+
const textArea = this.element.querySelector(".d-editor-input");
textArea.selectionStart = reply.indexOf(matches[index]);
textArea.selectionEnd =
diff --git a/frontend/discourse/app/components/d-editor-original-translation-preview.gjs b/frontend/discourse/app/components/d-editor-original-translation-preview.gjs
index fce944eb050..d2ec4e75312 100644
--- a/frontend/discourse/app/components/d-editor-original-translation-preview.gjs
+++ b/frontend/discourse/app/components/d-editor-original-translation-preview.gjs
@@ -9,6 +9,7 @@ import { trustHTML } from "@ember/template";
import { waitForPromise } from "@ember/test-waiters";
import { resolveAllShortUrls } from "pretty-text/upload-short-url";
import { ajax } from "discourse/lib/ajax";
+import { decorateImageControls } from "discourse/lib/composer/image-controls";
import { cook } from "discourse/lib/text";
import DCookText from "discourse/ui-kit/d-cook-text";
import DDecoratedHtml, {
@@ -45,6 +46,7 @@ class DecoratedPreviewCookText extends Component {
@action
decoratePreview(preview, helper) {
+ decorateImageControls(preview);
applyHtmlDecorators(preview, helper);
resolveAllShortUrls(ajax, this.siteSettings, preview);
}
diff --git a/frontend/discourse/app/lib/composer/image-controls.js b/frontend/discourse/app/lib/composer/image-controls.js
new file mode 100644
index 00000000000..8fa46a7b532
--- /dev/null
+++ b/frontend/discourse/app/lib/composer/image-controls.js
@@ -0,0 +1,163 @@
+import { iconElement } from "discourse/lib/icon-library";
+import { i18n } from "discourse-i18n";
+
+const SCALES = ["100", "75", "50"];
+
+const extraButtons = [];
+
+export function addImageWrapperButton(
+ label,
+ btnClass,
+ icon = null,
+ includeCondition = null
+) {
+ extraButtons.push({ label, btnClass, icon, condition: includeCondition });
+}
+
+function element(tag, attributes, ...children) {
+ const el = document.createElement(tag);
+
+ for (const [name, value] of Object.entries(attributes)) {
+ el.setAttribute(name, value);
+ }
+
+ el.append(...children.filter(Boolean));
+ return el;
+}
+
+function buildScaleButton(selectedScale, scale) {
+ return element(
+ "span",
+ {
+ class: selectedScale === scale ? "scale-btn active" : "scale-btn",
+ title: i18n("composer.image_scale_button", { percent: scale }),
+ "data-scale": scale,
+ },
+ `${scale}%`
+ );
+}
+
+function buildShowAltTextControls(altText) {
+ return element(
+ "span",
+ { class: "alt-text-readonly-container" },
+ element(
+ "span",
+ {
+ class: "alt-text-edit-btn",
+ title: i18n("composer.image_alt_text.title"),
+ },
+ iconElement("pencil")
+ ),
+ element(
+ "span",
+ {
+ class: "alt-text",
+ "aria-label": i18n("composer.image_alt_text.aria_label"),
+ },
+ altText
+ )
+ );
+}
+
+function buildEditAltTextControls(altText) {
+ const input = element("input", {
+ class: "alt-text-input",
+ type: "text",
+ });
+ input.value = altText;
+
+ return element(
+ "span",
+ { class: "alt-text-edit-container", hidden: "true" },
+ input,
+ element(
+ "button",
+ { class: "alt-text-edit-ok btn btn-primary" },
+ iconElement("check")
+ ),
+ element(
+ "button",
+ { class: "alt-text-edit-cancel btn btn-default" },
+ iconElement("xmark")
+ )
+ );
+}
+
+function buildDeleteButton() {
+ return element(
+ "span",
+ {
+ class: "delete-image-button",
+ title: i18n("composer.delete_image_button"),
+ "aria-label": i18n("composer.delete_image_button"),
+ },
+ iconElement("trash-can")
+ );
+}
+
+function buildGalleryButton(imageCount) {
+ return element(
+ "span",
+ {
+ class: "wrap-image-grid-button",
+ title: i18n("composer.toggle_image_grid"),
+ "data-image-count": imageCount,
+ },
+ iconElement("table-cells")
+ );
+}
+
+function buildExtraButton({ label, btnClass, icon }) {
+ return element(
+ "span",
+ { class: btnClass },
+ icon ? iconElement(icon) : null,
+ label
+ );
+}
+
+function buildButtonWrapper(image) {
+ const altText = image.getAttribute("alt") || "";
+ const imageCount = parseInt(image.dataset.imageRun, 10);
+
+ const wrapper = element("span", {
+ class: "button-wrapper",
+ "data-image-index": image.dataset.imageIndex,
+ });
+
+ if (imageCount > 1) {
+ wrapper.append(buildGalleryButton(imageCount));
+ }
+
+ wrapper.append(
+ buildShowAltTextControls(altText),
+ buildEditAltTextControls(altText),
+ element(
+ "span",
+ { class: "scale-btn-container" },
+ ...SCALES.map((scale) => buildScaleButton(image.dataset.scale, scale))
+ ),
+ buildDeleteButton()
+ );
+
+ const uploadUrl = image.getAttribute("data-orig-src");
+ for (const button of extraButtons) {
+ if (!button.condition || button.condition(uploadUrl)) {
+ wrapper.append(buildExtraButton(button));
+ }
+ }
+
+ return wrapper;
+}
+
+export function decorateImageControls(preview) {
+ preview
+ .querySelectorAll("img[data-image-index][data-scale]")
+ .forEach((image) => {
+ const wrapper = element("span", { class: "image-wrapper" });
+
+ image.replaceWith(wrapper);
+ wrapper.append(image, buildButtonWrapper(image));
+ });
+}
diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjs
index 81cafba199c..7e3d9479b39 100644
--- a/frontend/discourse/app/lib/plugin-api.gjs
+++ b/frontend/discourse/app/lib/plugin-api.gjs
@@ -62,6 +62,7 @@ import classPrepend, {
} from "discourse/lib/class-prepend";
import { registerComposerAction } from "discourse/lib/composer/actions-registry";
import { addPopupMenuOption } from "discourse/lib/composer/custom-popup-menu-options";
+import { addImageWrapperButton } from "discourse/lib/composer/image-controls";
import { registerRichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";
import {
_INTERNAL_SOURCE_KEY,
@@ -164,7 +165,6 @@ import {
replaceCategoryLinkRenderer,
} from "discourse/ui-kit/helpers/d-category-link";
import { registerCustomAvatarHelper } from "discourse/ui-kit/helpers/d-user-avatar";
-import { addImageWrapperButton } from "discourse-markdown-it/features/image-controls";
const blockedModifications = ["component:topic-list"];
diff --git a/frontend/discourse/tests/acceptance/composer-image-grid-test.js b/frontend/discourse/tests/acceptance/composer-image-grid-test.js
index 07c3508b129..c021bb249f1 100644
--- a/frontend/discourse/tests/acceptance/composer-image-grid-test.js
+++ b/frontend/discourse/tests/acceptance/composer-image-grid-test.js
@@ -92,6 +92,96 @@ and a second group of images
);
});
+ test("Grid button counts only images in the same block", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+
+ await fillIn(
+ ".d-editor-input",
+ `- ![outer|10x10](upload://outer.png)\n - ![nested|20x20](upload://nested.png)`
+ );
+
+ assert
+ .dom(".wrap-image-grid-button")
+ .doesNotExist("a nested list item is a block of its own");
+
+ await fillIn(
+ ".d-editor-input",
+ `- ![first|10x10](upload://first.png) ![second|20x20](upload://second.png)`
+ );
+
+ assert
+ .dom(".wrap-image-grid-button")
+ .hasAttribute("data-image-count", "2", "two images share the list item");
+
+ await fillIn(
+ ".d-editor-input",
+ `- ![outer|10x10](upload://outer.png)\n # ![heading|20x20](upload://heading.png)`
+ );
+
+ assert
+ .dom(".wrap-image-grid-button")
+ .doesNotExist("a heading is a block of its own");
+
+ await fillIn(
+ ".d-editor-input",
+ `# ![first|10x10](upload://first.png) ![second|20x20](upload://second.png)`
+ );
+
+ assert
+ .dom(".wrap-image-grid-button")
+ .hasAttribute("data-image-count", "2", "two images share the heading");
+
+ await fillIn(
+ ".d-editor-input",
+ `- ![outer|10x10](upload://outer.png)\n # Heading\n ![after|20x20](upload://after.png)`
+ );
+
+ assert
+ .dom(".wrap-image-grid-button")
+ .doesNotExist("a heading in between ends the run");
+
+ await fillIn(
+ ".d-editor-input",
+ `- ![first|10x10](upload://first.png) ![second|20x20](upload://second.png)\n # Heading\n ![after|20x20](upload://after.png)`
+ );
+
+ assert
+ .dom(".wrap-image-grid-button")
+ .hasAttribute("data-image-count", "2", "the run stops at the heading");
+
+ await fillIn(
+ ".d-editor-input",
+ `- ![first|10x10](upload://first.png) <span>\n # ![inner|20x20](upload://inner.png)\n </span> ![last|30x30](upload://last.png)`
+ );
+
+ assert
+ .dom(".wrap-image-grid-button")
+ .doesNotExist("an inline wrapper holding a block ends the run");
+
+ await fillIn(
+ ".d-editor-input",
+ `- <!-- a comment -->\n ![first|10x10](upload://first.png) ![second|20x20](upload://second.png)`
+ );
+
+ assert
+ .dom(".wrap-image-grid-button")
+ .hasAttribute("data-image-count", "2", "a comment does not open a block");
+
+ await fillIn(
+ ".d-editor-input",
+ `![first|10x10](upload://first.png)<script>![gone|20x20](upload://gone.png)</script>![last|30x30](upload://last.png)`
+ );
+
+ assert
+ .dom(".wrap-image-grid-button")
+ .hasAttribute(
+ "data-image-count",
+ "3",
+ "the count follows the markdown, not the sanitized preview"
+ );
+ });
+
test("Image Grid Preview", async function (assert) {
await visit("/");
diff --git a/frontend/discourse/tests/acceptance/composer-image-preview-test.js b/frontend/discourse/tests/acceptance/composer-image-preview-test.js
index 0fed7dd65cc..563c140bf36 100644
--- a/frontend/discourse/tests/acceptance/composer-image-preview-test.js
+++ b/frontend/discourse/tests/acceptance/composer-image-preview-test.js
@@ -349,6 +349,42 @@ acceptance("Composer - Image Preview", function (needs) {
});
});
+acceptance(
+ "Composer - Image Preview - Hand-written attributes",
+ function (needs) {
+ needs.user({});
+ needs.settings({ allow_uncategorized_topics: true });
+ needs.pretender((server, helper) => {
+ server.post("/uploads/lookup-urls", () => helper.response([]));
+ });
+
+ test("controls for an image that is not in the draft change nothing", async function (assert) {
+ const draft = `![real|200x200](upload://real.png)\n\n<img src="/images/avatar.png" alt="fake" data-image-index="9" data-image-run="2" data-scale="100">`;
+
+ await visit("/");
+ await click("#create-topic");
+ await fillIn(".d-editor-input", draft);
+
+ const fake = ".button-wrapper[data-image-index='9']";
+
+ await click(`${fake} .alt-text-edit-btn`);
+ await fillIn(`${fake} .alt-text-input`, "changed");
+ await click(`${fake} .alt-text-edit-ok`);
+ assert.dom(".d-editor-input").hasValue(draft, "alt text check button");
+
+ await click(`${fake} .alt-text-edit-btn`);
+ await triggerKeyEvent(`${fake} .alt-text-input`, "keypress", "Enter");
+ assert.dom(".d-editor-input").hasValue(draft, "alt text enter key");
+
+ await click(`${fake} .delete-image-button`);
+ assert.dom(".d-editor-input").hasValue(draft, "delete button");
+
+ await click(`${fake} .wrap-image-grid-button`);
+ assert.dom(".d-editor-input").hasValue(draft, "grid button");
+ });
+ }
+);
+
acceptance("Composer - Image Preview - Plugin API", function (needs) {
needs.user({});
needs.settings({ allow_uncategorized_topics: true });
diff --git a/frontend/discourse/tests/unit/lib/pretty-text-test.js b/frontend/discourse/tests/unit/lib/pretty-text-test.js
index 9548eef823c..efb94e275fd 100644
--- a/frontend/discourse/tests/unit/lib/pretty-text-test.js
+++ b/frontend/discourse/tests/unit/lib/pretty-text-test.js
@@ -1568,6 +1568,22 @@ var bar = 'bar';
);
});
+ test("image controls add only identifying attributes when previewing", function (assert) {
+ assert.cookedOptions(
+ "![cat|690x313](upload://eyPnj7UzkU0AkGkx2dx8G4YM1Jx.png)",
+ { previewing: true },
+ `<p><img src="/images/transparent.png" alt="cat" data-orig-src="upload://eyPnj7UzkU0AkGkx2dx8G4YM1Jx.png" data-image-index="0" data-scale="100" data-image-run="1" width="690" height="313" class="resizable"></p>`
+ );
+ });
+
+ test("button tags are stripped when previewing", function (assert) {
+ assert.cookedOptions(
+ `<button class="delete-image-button">delete</button>`,
+ { previewing: true },
+ `<p>delete</p>`
+ );
+ });
+
test("typographer arrows", function (assert) {
const enabledTypographer = {
siteSettings: { enable_markdown_typographer: true },