Skip to content

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

FEATURE: rich editor link ui for editing it (#32583)

Renato Atiliofd4890b5d3bc
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 8ad9cc62b05..28f742e289a 100644
--- a/app/assets/javascripts/discourse/app/components/composer/toolbar-buttons.gjs
+++ b/app/assets/javascripts/discourse/app/components/composer/toolbar-buttons.gjs
@@ -1,5 +1,6 @@
import Component from "@glimmer/component";
import { fn, hash } from "@ember/helper";
+import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { eq } from "truth-helpers";
import DButton from "discourse/components/d-button";
@@ -13,26 +14,37 @@ export default class ComposerToolbarButtons extends Component {
return button === this.firstButton ? 0 : button.tabindex;
}
+ @action
+ getHref(button) {
+ return typeof button.href === "function" ? button.href() : button.href;
+ }
+
get firstButton() {
+ const { isFirst = true } = this.args;
return (
- this.args.isFirst &&
+ isFirst &&
this.args.data.groups.find((group) => group.buttons?.length > 0)
?.buttons[0]
);
}
+ get rovingButtonBar() {
+ return this.args.rovingButtonBar || this.args.data.rovingButtonBar;
+ }
+
<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}}
+ href={{this.getHref button}}
target="_blank"
rel="noopener noreferrer"
class={{concatClass "btn no-text btn-icon" button.className}}
title={{button.title}}
tabindex={{this.tabIndex button}}
+ {{on "keydown" this.rovingButtonBar}}
>
{{icon button.icon}}
</a>
@@ -42,7 +54,7 @@ export default class ComposerToolbarButtons extends Component {
@onChange={{button.popupMenu.action}}
@onOpen={{fn button.action button}}
@tabindex={{this.tabIndex button}}
- @onKeydown={{@rovingButtonBar}}
+ @onKeydown={{this.rovingButtonBar}}
@options={{hash icon=button.icon focusAfterOnChange=false}}
class={{button.className}}
/>
@@ -55,7 +67,7 @@ export default class ComposerToolbarButtons extends Component {
@label={{button.label}}
@icon={{button.icon}}
@preventFocus={{button.preventFocus}}
- @onKeyDown={{@rovingButtonBar}}
+ @onKeyDown={{this.rovingButtonBar}}
tabindex={{this.tabIndex button}}
class={{button.className}}
/>
diff --git a/app/assets/javascripts/discourse/app/components/d-editor.gjs b/app/assets/javascripts/discourse/app/components/d-editor.gjs
index 25bbd9431f5..aacacf10f3d 100644
--- a/app/assets/javascripts/discourse/app/components/d-editor.gjs
+++ b/app/assets/javascripts/discourse/app/components/d-editor.gjs
@@ -7,6 +7,7 @@ import { schedule, scheduleOnce } from "@ember/runloop";
import { service } from "@ember/service";
import { classNames } from "@ember-decorators/component";
import { observes, on as onEvent } from "@ember-decorators/object";
+import curryComponent from "ember-curry-component";
import { emojiSearch, isSkinTonableEmoji } from "pretty-text/emoji";
import { translations } from "pretty-text/emoji/data";
import { Promise } from "rsvp";
@@ -34,6 +35,7 @@ import { hashtagAutocompleteOptions } from "discourse/lib/hashtag-autocomplete";
import { PLATFORM_KEY_MODIFIER } from "discourse/lib/keyboard-shortcuts";
import loadEmojiSearchAliases from "discourse/lib/load-emoji-search-aliases";
import loadRichEditor from "discourse/lib/load-rich-editor";
+import { rovingButtonBar } from "discourse/lib/roving-button-bar";
import { emojiUrlFor, generateCookFunction } from "discourse/lib/text";
import userSearch from "discourse/lib/user-search";
import {
@@ -441,41 +443,7 @@ export default class DEditor extends Component {
@action
rovingButtonBar(event) {
- let target = event.target;
- let siblingFinder;
- if (event.code === "ArrowRight") {
- siblingFinder = "nextElementSibling";
- } else if (event.code === "ArrowLeft") {
- siblingFinder = "previousElementSibling";
- } else {
- return true;
- }
-
- while (
- target.parentNode &&
- !target.parentNode.classList.contains("d-editor-button-bar")
- ) {
- target = target.parentNode;
- }
-
- let focusable = target[siblingFinder];
- if (focusable) {
- while (
- (focusable.tagName !== "BUTTON" &&
- !focusable.classList.contains("select-kit")) ||
- focusable.classList.contains("hidden")
- ) {
- focusable = focusable[siblingFinder];
- }
-
- if (focusable?.tagName === "DETAILS") {
- focusable = focusable.querySelector("summary");
- }
-
- focusable?.focus();
- }
-
- return true;
+ return rovingButtonBar(event, "d-editor-button-bar");
}
/**
@@ -662,7 +630,21 @@ export default class DEditor extends Component {
"indentSelection"
);
+ const replaceToolbar = ({ component, data }) => {
+ this.replacedToolbarComponent = curryComponent(
+ component,
+ { data },
+ getOwner(this)
+ );
+ };
+
+ this.appEvents.on("composer:replace-toolbar", replaceToolbar);
+ this.appEvents.on("composer:reset-toolbar", this, "resetToolbar");
+
return () => {
+ this.appEvents.off("composer:replace-toolbar", replaceToolbar);
+ this.appEvents.off("composer:reset-toolbar", this, "resetToolbar");
+
this.appEvents.off(
"composer:insert-block",
textManipulation,
@@ -733,11 +715,12 @@ export default class DEditor extends Component {
@icon="angle-left"
@preventFocus={{true}}
@onKeyDown={{this.rovingButtonBar}}
- class="btn-flat d-editor-button-bar__back"
+ class="d-editor-button-bar__back"
/>
<ToolbarButtons
@data={{this.replacedToolbarInstance}}
@rovingButtonBar={{this.rovingButtonBar}}
+ @isFirst={{false}}
/>
</div>
{{else}}
diff --git a/app/assets/javascripts/discourse/app/components/modal/insert-hyperlink.gjs b/app/assets/javascripts/discourse/app/components/modal/insert-hyperlink.gjs
index 33d940cbd49..a8b7790d570 100644
--- a/app/assets/javascripts/discourse/app/components/modal/insert-hyperlink.gjs
+++ b/app/assets/javascripts/discourse/app/components/modal/insert-hyperlink.gjs
@@ -18,7 +18,7 @@ import { i18n } from "discourse-i18n";
export default class InsertHyperlink extends Component {
@tracked linkText = this.args.model.linkText;
- @tracked linkUrl = "";
+ @tracked linkUrl = this.args.model.linkUrl ?? "";
@tracked selectedRow = -1;
@tracked searchResults = [];
@tracked searchLoading = false;
@@ -177,7 +177,11 @@ export default class InsertHyperlink extends Component {
{{on "keydown" this.keyDown}}
{{on "mousedown" this.mouseDown}}
@closeModal={{@closeModal}}
- @title={{i18n "composer.link_dialog_title"}}
+ @title={{i18n
+ (if
+ @model.editing "composer.link_edit_title" "composer.link_dialog_title"
+ )
+ }}
@bodyClass="insert-link"
class="insert-hyperlink-modal"
>
@@ -234,7 +238,11 @@ export default class InsertHyperlink extends Component {
<:footer>
<DButton
@action={{this.ok}}
- @label="composer.modal_ok"
+ @label={{if
+ @model.editing
+ "composer.link_edit_action"
+ "composer.link_dialog_action"
+ }}
type="submit"
class="btn-primary"
/>
@@ -242,7 +250,7 @@ export default class InsertHyperlink extends Component {
<DButton
@action={{@closeModal}}
@label="composer.cancel"
- class="btn-danger"
+ class="btn-transparent"
/>
</:footer>
</DModal>
diff --git a/app/assets/javascripts/discourse/app/lib/composer/toolbar.js b/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
index b5966bbf696..61b856cf0f2 100644
--- a/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
+++ b/app/assets/javascripts/discourse/app/lib/composer/toolbar.js
@@ -12,7 +12,7 @@ const DEFAULT_GROUP = "main";
export class ToolbarBase {
constructor(opts = {}) {
this.shortcuts = {};
- this.context = null;
+ this.context = {};
this.groups = [{ group: DEFAULT_GROUP, buttons: [] }];
this.siteSettings = opts.siteSettings || {};
this.capabilities = opts.capabilities || {};
@@ -75,13 +75,13 @@ export class ToolbarBase {
}
}
- addSeparator(group = DEFAULT_GROUP) {
+ addSeparator({ group = DEFAULT_GROUP, condition }) {
const g = this.groups.findBy("group", group);
if (!g) {
throw new Error(`Couldn't find toolbar group ${group}`);
}
- g.buttons.push({ type: "separator" });
+ g.buttons.push({ type: "separator", condition: condition || (() => true) });
}
}
diff --git a/app/assets/javascripts/discourse/app/lib/roving-button-bar.js b/app/assets/javascripts/discourse/app/lib/roving-button-bar.js
new file mode 100644
index 00000000000..87c2240d3b8
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/lib/roving-button-bar.js
@@ -0,0 +1,41 @@
+export function rovingButtonBar(event, containerClass = null) {
+ let target = event.target;
+ let siblingFinder;
+
+ if (event.code === "ArrowRight") {
+ siblingFinder = "nextElementSibling";
+ } else if (event.code === "ArrowLeft") {
+ siblingFinder = "previousElementSibling";
+ } else {
+ return true;
+ }
+
+ if (containerClass) {
+ while (
+ target.parentNode &&
+ !target.parentNode.classList.contains(containerClass)
+ ) {
+ target = target.parentNode;
+ }
+ }
+
+ 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];
+ }
+
+ if (focusable?.tagName === "DETAILS") {
+ focusable = focusable.querySelector("summary");
+ }
+
+ focusable?.focus();
+ }
+
+ return true;
+}
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 247c9b43ef0..411348f5b90 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
@@ -50,6 +50,7 @@ const AUTOCOMPLETE_KEY_DOWN_SUPPRESS = ["Enter", "Tab"];
* @property {string} [class] The class to be added to the ProseMirror contentEditable editor
* @property {boolean} [includeDefault] If default node and mark spec/parse/serialize/inputRules definitions from ProseMirror should be included
* @property {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension[]} [extensions] A list of extensions to be used with the editor INSTEAD of the ones registered through the API
+ * @property {(toolbar: import("discourse/lib/composer/toolbar").ToolbarBase) => void} [replaceToolbar] A function that replaces the default toolbar in a container with a custom/temporary one
*/
/**
@@ -63,6 +64,10 @@ const AUTOCOMPLETE_KEY_DOWN_SUPPRESS = ["Enter", "Tab"];
export default class ProsemirrorEditor extends Component {
@service session;
@service dialog;
+ @service menu;
+ @service capabilities;
+ @service modal;
+ @service toasts;
schema = createSchema(this.extensions, this.args.includeDefault);
view;
@@ -73,7 +78,11 @@ export default class ProsemirrorEditor extends Component {
get pluginParams() {
return {
- utils: { ...utils, convertFromMarkdown: this.convertFromMarkdown },
+ utils: {
+ ...utils,
+ convertFromMarkdown: this.convertFromMarkdown,
+ convertToMarkdown: this.convertToMarkdown,
+ },
schema: this.schema,
pmState: ProsemirrorState,
pmModel: ProsemirrorModel,
@@ -86,6 +95,11 @@ export default class ProsemirrorEditor extends Component {
topicId: this.args.topicId,
categoryId: this.args.categoryId,
session: this.session,
+ menu: this.menu,
+ capabilities: this.capabilities,
+ modal: this.modal,
+ toasts: this.toasts,
+ replaceToolbar: this.args.replaceToolbar,
}),
};
}
@@ -165,7 +179,7 @@ export default class ProsemirrorEditor extends Component {
if (tr.docChanged && tr.getMeta("addToHistory") !== false) {
// If this gets expensive, we can debounce it
- const value = this.serializer.convert(this.view.state.doc);
+ const value = this.convertToMarkdown(this.view.state.doc);
this.#lastSerialized = value;
this.args.change?.({ target: { value } });
}
@@ -193,7 +207,7 @@ export default class ProsemirrorEditor extends Component {
schema: this.schema,
view: this.view,
convertFromMarkdown: this.convertFromMarkdown,
- convertToMarkdown: this.serializer.convert.bind(this.serializer),
+ convertToMarkdown: this.convertToMarkdown,
});
this.#destructor = this.args.onSetup?.(this.textManipulation);
@@ -230,6 +244,11 @@ export default class ProsemirrorEditor extends Component {
this.view.updateState(this.view.state.apply(tr));
}
+ @bind
+ convertToMarkdown(doc) {
+ return this.serializer.convert(doc);
+ }
+
@action
teardown() {
this.#destructor?.();
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
new file mode 100644
index 00000000000..a9c5f105cc2
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/link-toolbar.js
@@ -0,0 +1,352 @@
+import { TrackedObject } from "@ember-compat/tracked-built-ins";
+import { 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";
+import { rovingButtonBar } from "discourse/lib/roving-button-bar";
+import { clipboardCopy } from "discourse/lib/utilities";
+import { i18n } from "discourse-i18n";
+import { updatePosition } from "float-kit/lib/update-position";
+
+const AUTO_LINKS = ["autolink", "linkify"];
+const MENU_OFFSET = 12;
+
+class LinkToolbar extends ToolbarBase {
+ constructor(opts = {}) {
+ super(opts);
+
+ this.addButton({
+ id: "link-edit",
+ icon: "pen",
+ title: "composer.link_toolbar.edit",
+ className: "composer-link-toolbar__edit",
+ preventFocus: true,
+ action: opts.editLink,
+ });
+
+ this.addButton({
+ id: "link-copy",
+ icon: "copy",
+ title: "composer.link_toolbar.copy",
+ className: "composer-link-toolbar__copy",
+ preventFocus: true,
+ action: opts.copyLink,
+ });
+
+ this.addButton({
+ id: "link-unlink",
+ icon: "link-slash",
+ title: "composer.link_toolbar.remove",
+ className: "composer-link-toolbar__unlink",
+ preventFocus: true,
+ condition: opts.canUnlink,
+ action: opts.unlinkText,
+ });
+
+ this.addSeparator({ condition: opts.canVisit });
+
+ this.addButton({
+ id: "link-visit",
+ icon: "up-right-from-square",
+ title: "composer.link_toolbar.visit",
+ className: "btn-flat composer-link-toolbar__visit",
+ preventFocus: true,
+ href: opts.getHref,
+ condition: opts.canVisit,
+ });
+ }
+}
+
+class LinkToolbarPluginView {
+ #menuInstance;
+ #toolbarReplaced = false;
+ #linkToolbar;
+ #linkState;
+
+ #view;
+
+ #utils;
+ #getContext;
+
+ constructor({ utils, getContext }) {
+ this.#utils = utils;
+ this.#getContext = getContext;
+ }
+
+ /**
+ * ProseMirror view update handler
+ *
+ * @param {import("prosemirror-view").EditorView} view
+ */
+ update(view) {
+ this.#view = view;
+
+ const markRange = this.#utils.getMarkRange(
+ view.state.selection.$head,
+ view.state.schema.marks.link
+ );
+
+ if (!markRange) {
+ this.#resetToolbar();
+ return;
+ }
+
+ this.#updateLinkState(markRange);
+ this.#displayToolbar();
+ }
+
+ #resetToolbar() {
+ this.#menuInstance?.destroy();
+ this.#menuInstance = null;
+
+ if (this.#toolbarReplaced) {
+ this.#getContext().replaceToolbar(null);
+ this.#toolbarReplaced = false;
+ }
+ }
+
+ #updateLinkState(markRange) {
+ const attrs = {
+ ...markRange.mark.attrs,
+ range: markRange,
+ head: this.#view.state.selection.head,
+ };
+
+ if (!this.#linkToolbar) {
+ this.#linkState = new TrackedObject(attrs);
+
+ this.#linkToolbar = new LinkToolbar({
+ editLink: () => this.#openLinkEditor(),
+ copyLink: () => this.#copyLink(),
+ unlinkText: () => this.#unlinkText(),
+ canVisit: () => this.#canVisit(),
+ getHref: () => this.#linkState.href,
+ canUnlink: () => this.#canUnlink(),
+ });
+
+ this.#linkToolbar.rovingButtonBar = this.#rovingButtonBar.bind(this);
+ } else {
+ Object.assign(this.#linkState, attrs);
+ }
+ }
+
+ #rovingButtonBar(event) {
+ if (event.key === "Tab") {
+ event.preventDefault();
+ this.#view.focus();
+ return false;
+ }
+ return rovingButtonBar(event);
+ }
+
+ #displayToolbar() {
+ if (this.#getContext().capabilities.viewport.sm) {
+ this.#showMobileToolbar();
+ } else {
+ this.#getContext().replaceToolbar(this.#linkToolbar);
+ this.#toolbarReplaced = true;
+ }
+ }
+
+ #openLinkEditor() {
+ const { range } = this.#linkState;
+ const tempTr = this.#view.state.tr.removeMark(
+ range.from,
+ range.to,
+ this.#view.state.schema.marks.link
+ );
+
+ const currentLinkText = this.#utils.convertToMarkdown(
+ this.#view.state.schema.topNodeType.create(
+ null,
+ this.#view.state.schema.nodes.paragraph.create(
+ null,
+ tempTr.doc.slice(range.from, range.to).content
+ )
+ )
+ );
+
+ this.#getContext().modal.show(InsertHyperlink, {
+ model: {
+ editing: true,
+ linkText: currentLinkText,
+ linkUrl: this.#linkState.href,
+ toolbarEvent: {
+ addText: (text) => this.#replaceText(text),
+ },
+ },
+ });
+ }
+
+ #replaceText(text) {
+ const { content } = this.#utils.convertFromMarkdown(text);
+ const { range } = this.#linkState;
+
+ if (content.firstChild?.content.size > 0) {
+ const { state, dispatch } = this.#view;
+ const tr = state.tr.replaceWith(
+ range.from,
+ range.to,
+ content.firstChild.content
+ );
+
+ const newPos = Math.min(
+ this.#view.state.selection.from,
+ range.from + content.firstChild.content.size
+ );
+ const resolvedPos = tr.doc.resolve(newPos);
+ tr.setSelection(new TextSelection(resolvedPos, resolvedPos));
+ dispatch(tr);
+ this.#view.focus();
+ }
+ }
+
+ async #copyLink() {
+ await clipboardCopy(this.#linkState.href);
+ this.#getContext().toasts.success({
+ duration: "short",
+ data: {
+ message: i18n("composer.link_toolbar.link_copied"),
+ },
+ });
+ }
+
+ #unlinkText() {
+ const range = this.#view.state.selection.empty
+ ? this.#linkState.range
+ : this.#view.state.selection;
+
+ if (range) {
+ const { state, dispatch } = this.#view;
+ dispatch(
+ state.tr.removeMark(range.from, range.to, state.schema.marks.link)
+ );
+ this.#view.focus();
+ }
+ }
+
+ #canVisit() {
+ return !!this.#utils.getLinkify().matchAtStart(this.#linkState.href);
+ }
+
+ #canUnlink() {
+ return !AUTO_LINKS.includes(this.#linkState.markup);
+ }
+
+ #showMobileToolbar() {
+ const element = this.#view.domAtPos(this.#linkState.head).node;
+ const trigger =
+ element.nodeType === Node.TEXT_NODE ? element.parentElement : element;
+
+ trigger.getBoundingClientRect = () => this.#getTriggerClientRect();
+
+ if (this.#menuInstance?.expanded) {
+ this.#menuInstance.trigger = trigger;
+ updatePosition(
+ this.#menuInstance.trigger,
+ this.#menuInstance.content,
+ {}
+ );
+ return;
+ }
+
+ this.#menuInstance?.destroy();
+ this.#getContext()
+ .menu.show(trigger, {
+ portalOutletElement: this.#view.dom.parentElement,
+ identifier: "composer-link-toolbar",
+ component: ToolbarButtons,
+ placement: "bottom",
+ padding: 0,
+ hide: true,
+ boundary: this.#view.dom.parentElement,
+ fallbackPlacements: [
+ "bottom-end",
+ "bottom-start",
+ "top",
+ "top-end",
+ "top-start",
+ ],
+ closeOnClickOutside: false,
+ onClose: () => this.#view.focus(),
+ data: this.#linkToolbar,
+ })
+ .then((instance) => {
+ this.#menuInstance = instance;
+ });
+ }
+
+ #getTriggerClientRect() {
+ const { docView } = this.#view;
+ const { head } = this.#linkState;
+ const { doc } = this.#view.state;
+
+ if (!docView || head > doc.content.size) {
+ return { left: 0, top: 0, width: 0, height: 0 };
+ }
+
+ const { left, top } = this.#view.coordsAtPos(head);
+ return { left, top: top + MENU_OFFSET, width: 0, height: 0 };
+ }
+
+ /**
+ * ProseMirror view destroy handler
+ */
+ destroy() {
+ this.#menuInstance?.destroy();
+ this.#menuInstance = null;
+ this.#linkToolbar = null;
+ }
+}
+
+/** @type {RichEditorExtension} */
+const extension = {
+ plugins: ({ pmState: { Plugin }, utils, getContext }) => {
+ return new Plugin({
+ props: {
+ handleKeyDown(view, event) {
+ if (event.key !== "Tab" || event.shiftKey) {
+ return false;
+ }
+
+ const range = utils.getMarkRange(
+ view.state.selection.$head,
+ view.state.schema.marks.link
+ );
+ if (!range) {
+ return false;
+ }
+
+ const activeMenu = document.querySelector(
+ '[data-identifier="composer-link-toolbar"]'
+ );
+ if (!activeMenu) {
+ return false;
+ }
+
+ event.preventDefault();
+
+ const focusable = activeMenu.querySelector(
+ 'button, a, [tabindex]:not([tabindex="-1"]), .select-kit'
+ );
+
+ if (focusable) {
+ focusable.focus();
+ return true;
+ }
+
+ return false;
+ },
+ },
+
+ view() {
+ return new LinkToolbarPluginView({
+ utils,
+ getContext,
+ });
+ },
+ });
+ },
+};
+
+export default extension;
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/register-default.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/register-default.js
index a6b36b770d3..43add860648 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/register-default.js
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/register-default.js
@@ -9,6 +9,7 @@ import htmlBlock from "./html-block";
import htmlInline from "./html-inline";
import image from "./image";
import link from "./link";
+import linkToolbar from "./link-toolbar";
import markdownPaste from "./markdown-paste";
import mention from "./mention";
import onebox from "./onebox";
@@ -32,6 +33,7 @@ const defaultExtensions = [
onebox,
code,
link,
+ linkToolbar,
heading,
codeBlock,
quote,
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 8b5750af3f7..0de2f9642cc 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
@@ -117,3 +117,75 @@ export function changedDescendants(old, cur, f, offset = 0) {
offset += child.nodeSize;
}
}
+
+/**
+ * Get the continuous range of a mark at a given position.
+ *
+ * @param $pos
+ * {import("prosemirror-model").ResolvedPos} - The position in the document.
+ * @param type
+ * {import("prosemirror-model").MarkType} - The type of mark to find.
+ * @param attrs
+ * {Object} - Optional attributes to match against the mark.
+ * @returns {{ from: number, to: number, mark: import("prosemirror-model").Mark } | undefined}
+ */
+export function getMarkRange($pos, type, attrs = {}) {
+ if (!$pos || !type) {
+ return;
+ }
+
+ // Try node after, then before, return if neither has the mark
+ let start = $pos.parent.childAfter($pos.parentOffset);
+ if (!start.node || !findMarkOfType(start.node.marks, type, attrs)) {
+ start = $pos.parent.childBefore($pos.parentOffset);
+ if (!start.node || !findMarkOfType(start.node.marks, type, attrs)) {
+ return;
+ }
+ }
+
+ const mark = findMarkOfType(start.node.marks, type, attrs);
+
+ let from = $pos.start() + start.offset;
+ let to = from + start.node.nodeSize;
+
+ // Expand backward
+ let { index } = start;
+ while (
+ index > 0 &&
+ findMarkOfType($pos.parent.child(index - 1).marks, type, mark.attrs)
+ ) {
+ index--;
+ from -= $pos.parent.child(index).nodeSize;
+ }
+
+ // Expand forward
+ index = start.index + 1;
+ while (
+ index < $pos.parent.childCount &&
+ findMarkOfType($pos.parent.child(index).marks, type, mark.attrs)
+ ) {
+ to += $pos.parent.child(index).nodeSize;
+ index++;
+ }
+
+ return { from, to, mark };
+}
+
+/**
+ * Find a mark of a specific type within marks, matching the attributes if provided.
+ *
+ * @param marks
+ * {import("prosemirror-model").Mark[]} - Array of marks to search through.
+ * @param type
+ * {import("prosemirror-model").MarkType} - The type of mark to find.
+ * @param attrs
+ * {Object} - Optional attributes to match against the mark.
+ * @returns {import("prosemirror-model").Mark | undefined}
+ */
+export function findMarkOfType(marks, type, attrs = {}) {
+ return marks.find(
+ (item) =>
+ item.type === type &&
+ Object.keys(attrs).every((key) => item.attrs[key] === attrs[key])
+ );
+}
diff --git a/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.js b/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.js
index 0e71d0de05e..eff1bc4c1d2 100644
--- a/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.js
+++ b/app/assets/javascripts/discourse/tests/acceptance/composer-hyperlink-test.js
@@ -45,7 +45,7 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";
await click(".d-editor button.link");
await fillIn(".d-modal__body .link-url", "google.com");
await fillIn(".d-modal__body .link-text", "Google");
- await click(".d-modal__footer button.btn-danger");
+ await click(".d-modal__footer button.btn-transparent");
assert
.dom(".d-editor-input")
diff --git a/app/assets/javascripts/float-kit/addon/lib/d-menu-instance.js b/app/assets/javascripts/float-kit/addon/lib/d-menu-instance.js
index 59e5e93773f..cdec6ad90a5 100644
--- a/app/assets/javascripts/float-kit/addon/lib/d-menu-instance.js
+++ b/app/assets/javascripts/float-kit/addon/lib/d-menu-instance.js
@@ -29,6 +29,7 @@ export default class DMenuInstance extends FloatKitInstance {
* @property {Object} options - Options object that configures the menu behavior and display.
*/
@tracked options;
+ @tracked portalOutletOverrideElement;
@tracked _trigger;
@@ -37,10 +38,14 @@ export default class DMenuInstance extends FloatKitInstance {
setOwner(this, owner);
this.options = { ...MENU.options, ...options };
+ this.portalOutletOverrideElement = options.portalOutletElement;
}
get portalOutletElement() {
- return document.getElementById("d-menu-portals");
+ return (
+ this.portalOutletOverrideElement ||
+ document.getElementById("d-menu-portals")
+ );
}
get trigger() {
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 4f5ca701614..79eed829025 100644
--- a/app/assets/javascripts/float-kit/addon/lib/update-position.js
+++ b/app/assets/javascripts/float-kit/addon/lib/update-position.js
@@ -2,6 +2,7 @@ import {
arrow,
computePosition,
flip,
+ hide,
inline,
offset,
shift,
@@ -19,7 +20,7 @@ const centerOffset = offset(({ rects }) => {
export async function updatePosition(trigger, content, options) {
let padding = 0;
if (!isTesting()) {
- padding = options.padding || {
+ padding = options.padding ?? {
top: headerOffset(),
left: 10,
right: 10,
@@ -30,6 +31,7 @@ export async function updatePosition(trigger, content, options) {
const flipOptions = {
fallbackPlacements: options.fallbackPlacements ?? FLOAT_UI_PLACEMENTS,
padding,
+ boundary: options.boundary,
};
const middleware = [];
@@ -62,6 +64,10 @@ export async function updatePosition(trigger, content, options) {
middleware.push(arrow({ element: arrowElement }));
}
+ if (options.hide) {
+ middleware.push(hide({ padding }));
+ }
+
content.dataset.strategy = options.strategy || "absolute";
const { x, y, placement, middlewareData } = await computePosition(
@@ -84,9 +90,11 @@ export async function updatePosition(trigger, content, options) {
});
} else {
content.dataset.placement = placement;
+
Object.assign(content.style, {
left: `${x}px`,
top: `${y}px`,
+ visibility: middlewareData.hide?.referenceHidden ? "hidden" : "visible",
});
if (middlewareData.arrow && arrowElement) {
diff --git a/app/assets/stylesheets/common/d-editor.scss b/app/assets/stylesheets/common/d-editor.scss
index 276d4f3720b..3dd1e147339 100644
--- a/app/assets/stylesheets/common/d-editor.scss
+++ b/app/assets/stylesheets/common/d-editor.scss
@@ -351,6 +351,22 @@
.select-kit-header-wrapper {
justify-content: center;
}
+
+ &.--replaced-toolbar {
+ animation: float-left ease 0.2s 1 forwards;
+
+ @keyframes float-left {
+ 0% {
+ opacity: 0;
+ transform: translateX(10px);
+ }
+
+ 100% {
+ opacity: 1;
+ transform: translateX(0);
+ }
+ }
+ }
}
.d-editor #form-template-form {
diff --git a/app/assets/stylesheets/common/rich-editor/rich-editor.scss b/app/assets/stylesheets/common/rich-editor/rich-editor.scss
index 6194a3d1ba0..167e51211e9 100644
--- a/app/assets/stylesheets/common/rich-editor/rich-editor.scss
+++ b/app/assets/stylesheets/common/rich-editor/rich-editor.scss
@@ -127,6 +127,10 @@
color: var(--primary);
}
+ a:not([contenteditable="false"] a) {
+ cursor: inherit;
+ }
+
kbd {
// I believe this shouldn't be `inline-flex` in posts either (test with emojis before/after text to see why),
// but overriding just for the editor for now
@@ -191,6 +195,37 @@
}
}
+.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__inner-content {
+ overflow: visible;
+ }
+
+ .btn {
+ background-color: var(--secondary);
+
+ .d-icon {
+ color: var(--primary-medium);
+ }
+
+ &:hover {
+ .d-icon {
+ color: var(--primary);
+ }
+ }
+
+ &:active {
+ background: var(--secondary);
+ }
+
+ &:focus-visible {
+ @include default-focus;
+ }
+ }
+}
+
/*********************************************************
Section below from prosemirror-view/style/prosemirror.css
********************************************************/
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index ca7aa561fd2..eb8ef53af3d 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -2794,7 +2794,10 @@ en:
italic_text: "emphasized text"
link_title: "Hyperlink"
link_description: "enter link description here"
- link_dialog_title: "Insert Hyperlink"
+ link_dialog_title: "Insert hyperlink"
+ link_dialog_action: "Insert"
+ link_edit_title: "Edit hyperlink"
+ link_edit_action: "Update"
link_optional_text: "optional title"
link_url_placeholder: "Paste a URL or type to search topics"
blockquote_title: "Blockquote"
@@ -2872,6 +2875,13 @@ en:
delete_image_button: Delete Image
toggle_image_grid: Toggle image grid
+ link_toolbar:
+ edit: "Edit link"
+ copy: "Copy link"
+ remove: "Remove link"
+ visit: "Open link in external tab"
+ link_copied: "Link copied!"
+
notifications:
tooltip:
regular:
diff --git a/spec/system/composer/prosemirror_editor_spec.rb b/spec/system/composer/prosemirror_editor_spec.rb
index be6cd31baeb..80fd7cfe9f5 100644
--- a/spec/system/composer/prosemirror_editor_spec.rb
+++ b/spec/system/composer/prosemirror_editor_spec.rb
@@ -884,4 +884,176 @@ describe "Composer - ProseMirror editor", type: :system do
expect(rich).to have_no_css("a.mention", text: "@unknown")
end
end
+
+ describe "link toolbar" do
+ let(:insert_hyperlink_modal) { PageObjects::Modals::InsertHyperlink.new }
+
+ it "shows link toolbar when cursor is on a link" do
+ open_composer_and_toggle_rich_editor
+
+ composer.type_content("[Example](https://example.com)")
+ composer.send_keys(:left, :left, :left)
+
+ expect(page).to have_css("[data-identifier='composer-link-toolbar']")
+ expect(page).to have_css("button.composer-link-toolbar__edit")
+ expect(page).to have_css("button.composer-link-toolbar__copy")
+ expect(page).to have_css("a.composer-link-toolbar__visit")
+ end
+
+ it "allows editing a link via toolbar" do
+ cdp.allow_clipboard
+ open_composer_and_toggle_rich_editor
+
+ composer.type_content("[Example](https://example.com)")
+ composer.send_keys(:left, :left, :left)
+
+ # Use Tab to navigate to the toolbar and Enter to activate edit
+ composer.send_keys(:tab, :enter)
+
+ expect(insert_hyperlink_modal).to be_open
+
+ expect(insert_hyperlink_modal.link_text_value).to eq("Example")
+ expect(insert_hyperlink_modal.link_url_value).to eq("https://example.com")
+
+ insert_hyperlink_modal.fill_in_link_text("Updated Example")
+ insert_hyperlink_modal.fill_in_link_url("https://updated-example.com")
+ insert_hyperlink_modal.click_primary_button
+
+ expect(rich).to have_css("a[href='https://updated-example.com']", text: "Updated Example")
+
+ composer.toggle_rich_editor
+ expect(composer).to have_value("[Updated Example](https://updated-example.com)")
+ end
+
+ it "allows copying a link URL via toolbar" do
+ cdp.allow_clipboard
+ open_composer_and_toggle_rich_editor
+
+ composer.type_content("[Example](https://example.com)")
+ composer.send_keys(:left, :left, :left)
+
+ find("button.composer-link-toolbar__copy").click
+
+ expect(page).to have_content(I18n.t("js.composer.link_toolbar.link_copied"))
+ end
+
+ it "allows unlinking a link via toolbar when markup is not auto or linkify" do
+ open_composer_and_toggle_rich_editor
+
+ composer.type_content("[Manual Link](https://example.com)")
+
+ find("button.composer-link-toolbar__unlink").click
+
+ expect(rich).to have_no_css("a")
+ expect(rich).to have_content("Manual Link")
+
+ composer.toggle_rich_editor
+ expect(composer).to have_value("Manual Link")
+ end
+
+ it "doesn't show unlink button for auto-detected links" do
+ open_composer_and_toggle_rich_editor
+
+ composer.type_content("<https://example.com>")
+
+ expect(page).to have_css("[data-identifier='composer-link-toolbar']")
+ expect(page).to have_no_css("button.composer-link-toolbar__unlink")
+ end
+
+ it "doesn't show unlink button for auto-linkified URLs" do
+ open_composer_and_toggle_rich_editor
+
+ composer.type_content("https://example.com")
+
+ expect(page).to have_css("[data-identifier='composer-link-toolbar']")
+ expect(page).to have_no_css("button.composer-link-toolbar__unlink")
+ end
+
+ it "shows visit button for valid URLs" do
+ open_composer_and_toggle_rich_editor
+
+ composer.type_content("[Example](https://example.com)")
+
+ expect(page).to have_css("a.composer-link-toolbar__visit")
+
+ expect(find("a.composer-link-toolbar__visit")["href"]).to eq("https://example.com/")
+ end
+
+ it "doesn't show visit button for invalid URLs" do
+ open_composer_and_toggle_rich_editor
+
+ composer.type_content("[Example](not-a-url)")
+
+ expect(page).to have_css("[data-identifier='composer-link-toolbar']")
+ expect(page).to have_no_css("a.composer-link-toolbar__visit")
+ expect(page).to have_no_css(".composer-link-toolbar__divider")
+ end
+
+ it "closes toolbar when cursor moves outside link" do
+ open_composer_and_toggle_rich_editor
+
+ composer.type_content("Text before [Example](https://example.com),")
+
+ composer.send_keys(:left)
+
+ expect(page).to have_css("[data-identifier='composer-link-toolbar']")
+
+ composer.send_keys(:right)
+
+ expect(page).to have_no_css("[data-identifier='composer-link-toolbar']")
+ end
+
+ it "preserves emojis when editing a link via toolbar" do
+ open_composer_and_toggle_rich_editor
+
+ composer.type_content("[Party :tada: Time](https://example.com)")
+ composer.send_keys(:left, :left, :left)
+
+ # Use Tab to navigate to the toolbar and Enter to activate edit
+ composer.send_keys(:tab, :enter)
+
+ expect(insert_hyperlink_modal).to be_open
+
+ expect(insert_hyperlink_modal.link_text_value).to eq("Party :tada: Time")
+ expect(insert_hyperlink_modal.link_url_value).to eq("https://example.com")
+
+ insert_hyperlink_modal.fill_in_link_text("Updated :tada: Party")
+ insert_hyperlink_modal.fill_in_link_url("https://updated-party.com")
+ insert_hyperlink_modal.click_primary_button
+
+ expect(rich).to have_css("a[href='https://updated-party.com']")
+ expect(rich).to have_css("a img[title=':tada:'], a img[alt=':tada:']")
+
+ composer.toggle_rich_editor
+ expect(composer).to have_value("[Updated :tada: Party](https://updated-party.com)")
+ end
+
+ it "preserves bold and italic formatting when editing a link via toolbar" do
+ open_composer_and_toggle_rich_editor
+
+ composer.type_content("[**Bold** and *italic* text](https://example.com)")
+ composer.send_keys(:left, :left, :left)
+
+ # Use Tab to navigate to the toolbar and Enter to activate edit
+ composer.send_keys(:tab, :enter)
+
+ expect(insert_hyperlink_modal).to be_open
+
+ expect(insert_hyperlink_modal.link_text_value).to eq("**Bold** and *italic* text")
+ expect(insert_hyperlink_modal.link_url_value).to eq("https://example.com")
+
+ insert_hyperlink_modal.fill_in_link_text("Updated **bold** and *italic* content")
+ insert_hyperlink_modal.fill_in_link_url("https://updated-example.com")
+ insert_hyperlink_modal.click_primary_button
+
+ expect(rich).to have_css("a[href='https://updated-example.com']")
+ expect(rich).to have_css("strong a", text: "bold")
+ expect(rich).to have_css("em a", text: "italic")
+
+ composer.toggle_rich_editor
+ expect(composer).to have_value(
+ "[Updated **bold** and *italic* content](https://updated-example.com)",
+ )
+ end
+ end
end
diff --git a/spec/system/page_objects/modals/insert_hyperlink.rb b/spec/system/page_objects/modals/insert_hyperlink.rb
new file mode 100644
index 00000000000..a2140c06f54
--- /dev/null
+++ b/spec/system/page_objects/modals/insert_hyperlink.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+module PageObjects
+ module Modals
+ class InsertHyperlink < PageObjects::Modals::Base
+ BODY_SELECTOR = ".insert-hyperlink-modal"
+ MODAL_SELECTOR = ".insert-hyperlink-modal"
+ LINK_TEXT_SELECTOR = ".d-modal__body input.link-text"
+ LINK_URL_SELECTOR = ".d-modal__body input.link-url"
+
+ def fill_in_link_text(text)
+ find(LINK_TEXT_SELECTOR).fill_in(with: text)
+ end
+
+ def fill_in_link_url(url)
+ find(LINK_URL_SELECTOR).fill_in(with: url)
+ end
+
+ def link_text_value
+ find(LINK_TEXT_SELECTOR).value
+ end
+
+ def link_url_value
+ find(LINK_URL_SELECTOR).value
+ end
+ end
+ end
+end