A platform for community discussion. Free, open, simple.
FEATURE: inline and block wrap nodes rich editor support (#36591)
Renato Atilioc0e9e4bea56c
diff --git a/app/assets/stylesheets/common/base/modal.scss b/app/assets/stylesheets/common/base/modal.scssindex 97eaa05c06f..9d0014eab5a 100644--- a/app/assets/stylesheets/common/base/modal.scss+++ b/app/assets/stylesheets/common/base/modal.scss@@ -806,3 +806,22 @@ html:not(.keyboard-visible).mobile-device {}}}++.wrap-attributes-modal {+ .wrap-modal__attribute-row {+ display: flex;+ gap: var(--space-2);++ .form-kit__field {+ flex: 1;+ }++ .btn {+ align-self: end;+ }+ }++ &__unwrap {+ margin-left: auto;+ }+}diff --git a/app/assets/stylesheets/common/rich-editor/rich-editor.scss b/app/assets/stylesheets/common/rich-editor/rich-editor.scssindex 3acccd81fa9..b45492fa919 100644--- a/app/assets/stylesheets/common/rich-editor/rich-editor.scss+++ b/app/assets/stylesheets/common/rich-editor/rich-editor.scss@@ -17,7 +17,7 @@> div:first-child,> details:first-child {- margin-top: 0.5rem;+ margin-top: var(--space-4);// This is hacky, but helps having the leading gapcursor at the right position&.ProseMirror-gapcursor {@@ -221,6 +221,49 @@}}+ .composer-wrap-node {+ position: relative;+ white-space: normal;+ border: 2px dashed var(--primary-low-mid);+ border-radius: var(--d-border-radius);+ padding-inline: var(--space-2);+ margin-block: var(--space-4);++ &.ProseMirror-selectednode {+ outline-offset: -2px;+ border-radius: calc(var(--d-border-radius) + 2px);+ }++ .d-wrap-indicator {+ color: var(--primary-medium);+ background-color: var(--secondary);+ border: none;+ cursor: pointer;++ &:hover {+ color: var(--primary);+ }++ &.--inline {+ font-size: var(--font-down-2);+ padding: var(--space-half) 0;+ margin-left: calc(-1 * var(--space-1));+ margin-right: var(--space-2);+ vertical-align: text-top;+ display: inline-block;+ }++ &.--block {+ position: absolute;+ z-index: 1;+ font-size: var(--font-down-1);+ left: var(--space-2);+ top: calc(-1 * var(--space-3) + 1px);+ padding: 0 var(--space-1);+ }+ }+ }+.onebox-loading {border-radius: var(--d-border-radius);padding: 0 0.125rem;diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 9d9fe893892..91faa9772a7 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -3083,6 +3083,17 @@ en:ulist_title: "Bulleted list"list_item: "List item"toggle_direction: "Toggle direction"+ apply_wrap_title: "Apply wrap"+ wrap_modal:+ title: "Edit Wrap"+ name_label: "Wrap name"+ attributes_label: "Attributes"+ add_attribute: "Add attribute"+ remove_attribute: "Remove attribute"+ apply: "Apply"+ unwrap: "Unwrap"+ no_attributes: "No attributes added yet."+ wrap_text: "Wrap content"help: "Markdown Editing Help"collapse: "Minimize the composer panel"open: "Open the composer panel"diff --git a/frontend/discourse/app/components/d-editor.gjs b/frontend/discourse/app/components/d-editor.gjsindex eea493f6024..60b45f0992b 100644--- a/frontend/discourse/app/components/d-editor.gjs+++ b/frontend/discourse/app/components/d-editor.gjs@@ -526,6 +526,8 @@ export default class DEditor extends Component {* @property {function} addText - Adds text* @property {function} applyList - Applies a list format* @property {*} selected - The current selection+ * @property {Object} commands - Available commands+ * @property {Object} state - Current editor state (inWrap, inBold, etc.)*//**@@ -540,6 +542,7 @@ export default class DEditor extends Component {});return {commands: this.textManipulation.commands,+ state: this.textManipulation.state,selected,selectText: (from, length) =>this.textManipulation.selectText(from, length, { scroll: false }),diff --git a/frontend/discourse/app/services/composer.js b/frontend/discourse/app/services/composer.jsindex de481904df3..929df2451e3 100644--- a/frontend/discourse/app/services/composer.js+++ b/frontend/discourse/app/services/composer.js@@ -48,6 +48,8 @@ import Composer, {import Draft from "discourse/models/draft";import PostLocalization from "discourse/models/post-localization";import TopicLocalization from "discourse/models/topic-localization";+import WrapAttributesModal from "discourse/static/prosemirror/components/wrap-attributes-modal";+import { parseAttributesString } from "discourse/static/prosemirror/lib/wrap-utils";import { i18n } from "discourse-i18n";async function loadDraft(store, opts = {}) {@@ -468,6 +470,17 @@ export default class ComposerService extends Service {}));+ options.push(+ this._setupPopupMenuOption({+ name: "toggle-wrap",+ action: this.toggleWrap,+ icon: "right-to-bracket",+ label: "composer.apply_wrap_title",+ showActiveIcon: true,+ active: ({ state }) => state?.inWrap,+ })+ );+return options.concat(customPopupMenuOptions.map((option) => this._setupPopupMenuOption({ ...option }))@@ -832,6 +845,40 @@ export default class ComposerService extends Service {});}+ @action+ toggleWrap(toolbarEvent) {+ const initialAttributes = toolbarEvent.state?.inWrap+ ? toolbarEvent.state.wrapAttributes || ""+ : "";++ this.modal.show(WrapAttributesModal, {+ model: {+ initialAttributes,+ onApply: (attributesString) => {+ if (toolbarEvent.state?.inWrap) {+ toolbarEvent.commands?.updateWrap(attributesString);+ } else if (toolbarEvent.commands?.insertWrap) {+ toolbarEvent.commands.insertWrap(+ parseAttributesString(attributesString)+ );+ } else {+ const wrapTag = attributesString.trim()+ ? `[wrap ${attributesString}]`+ : "[wrap]";+ toolbarEvent.applySurround(+ `${wrapTag}\n`,+ "\n[/wrap]",+ "wrap_text"+ );+ }+ },+ onRemove: toolbarEvent.state?.inWrap+ ? () => toolbarEvent.commands?.removeWrap()+ : undefined,+ },+ });+ }+@actiontoggleToolbar() {this.toggleProperty("showToolbar");diff --git a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjs b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjsindex 88042ad7c19..246a988fb85 100644--- a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjs+++ b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjs@@ -363,15 +363,15 @@ export default class ProsemirrorEditor extends Component {{{forceScrollingElementPosition}}></div>{{#each this.glimmerNodeViews key="dom" as |nodeView|}}- {{#in-element nodeView.dom insertBefore=null}}+ {{~#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}}+ >{{nodeView.contentDOM}}</nodeView.component>+ {{~/in-element~}}{{/each}}</template>}diff --git a/frontend/discourse/app/static/prosemirror/components/wrap-attributes-modal.gjs b/frontend/discourse/app/static/prosemirror/components/wrap-attributes-modal.gjsnew file mode 100644index 00000000000..33abdfa879d--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/components/wrap-attributes-modal.gjs@@ -0,0 +1,164 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn, hash } from "@ember/helper";+import { action } from "@ember/object";+import DButton from "discourse/components/d-button";+import DModal from "discourse/components/d-modal";+import Form from "discourse/components/form";+import { i18n } from "discourse-i18n";+import { parseAttributesString, serializeFromForm } from "../lib/wrap-utils";++/**+ * @typedef WrapAttributesModalArgs+ * @property {(attributes: string) => void} onApply - Callback when wrap is applied+ * @property {() => void} closeModal - Function to close the modal+ * @property {string} [initialAttributes] - Initial attributes string+ */++/**+ * @typedef WrapAttributesModalSignature+ * @property {WrapAttributesModalArgs} Args+ */++/**+ * Modal for defining wrap token attributes+ *+ * @extends {Component<WrapAttributesModalSignature>}+ */+export default class WrapAttributesModal extends Component {+ @tracked formApi;++ get initialData() {+ const initialAttrs = this.args.model?.initialAttributes || "";+ const parsedAttrs = parseAttributesString(initialAttrs);+ return {+ name: parsedAttrs.wrap || "",+ attributes: Object.entries(parsedAttrs)+ .filter(([key]) => key !== "wrap")+ .map(([key, value]) => ({ key, value })),+ };+ }++ @action+ onSubmit(data) {+ const attrsString = serializeFromForm(data.name, data.attributes);+ this.args.model.onApply(attrsString);+ this.args.closeModal();+ }++ @action+ unwrap() {+ this.args.model.onRemove?.();+ this.args.closeModal();+ }++ get hasAttributeRows() {+ return this.formApi?.get("attributes")?.length > 0;+ }++ @action+ onRegisterApi(api) {+ this.formApi = api;+ }++ @action+ submitForm() {+ this.formApi?.submit();+ }++ @action+ cancel() {+ this.args.closeModal();+ }++ <template>+ <DModal+ @title={{i18n "composer.wrap_modal.title"}}+ @closeModal={{@closeModal}}+ class="wrap-attributes-modal"+ >+ <:body>+ <Form+ @data={{this.initialData}}+ @onSubmit={{this.onSubmit}}+ @onRegisterApi={{this.onRegisterApi}}+ as |form|+ >+ <form.Field+ @name="name"+ @title={{i18n "composer.wrap_modal.name_label"}}+ as |field|+ >+ <field.Input @type="text" autocomplete="off" />+ </form.Field>++ <form.Section @title={{i18n "composer.wrap_modal.attributes_label"}}>+ {{#unless this.hasAttributeRows}}+ <div>+ {{i18n "composer.wrap_modal.no_attributes"}}+ </div>+ {{/unless}}++ <form.Collection @name="attributes" as |collection index|>+ <collection.Object as |object|>+ <div class="wrap-modal__attribute-row">+ <object.Field+ @name="key"+ @title="Key"+ @validation="required"+ as |field|+ >+ <field.Input @type="text" />+ </object.Field>++ <object.Field+ @name="value"+ @title="Value"+ @validation="required"+ as |field|+ >+ <field.Input @type="text" />+ </object.Field>++ <DButton+ @action={{fn collection.remove index}}+ @icon="trash-can"+ class="btn-default btn-small"+ @title="composer.wrap_modal.remove_attribute"+ />+ </div>+ </collection.Object>+ </form.Collection>++ <form.Button+ @action={{fn+ form.addItemToCollection+ "attributes"+ (hash key="" value="")+ }}+ class="btn-default btn-small"+ >+ {{i18n "composer.wrap_modal.add_attribute"}}+ </form.Button>+ </form.Section>++ </Form>+ </:body>+ <:footer>+ <DButton+ @action={{this.submitForm}}+ @label="composer.wrap_modal.apply"+ class="btn-primary"+ />+ <DButton @action={{this.cancel}} @label="cancel" class="btn-default" />+ {{#if @model.onRemove}}+ <DButton+ @action={{this.unwrap}}+ @label="composer.wrap_modal.unwrap"+ class="btn-danger wrap-attributes-modal__unwrap"+ />+ {{/if}}+ </:footer>+ </DModal>+ </template>+}diff --git a/frontend/discourse/app/static/prosemirror/components/wrap-node-view.gjs b/frontend/discourse/app/static/prosemirror/components/wrap-node-view.gjsnew file mode 100644index 00000000000..f3d050ea24f--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/components/wrap-node-view.gjs@@ -0,0 +1,102 @@+import Component from "@glimmer/component";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { NodeSelection } from "prosemirror-state";+import { parseAttributesString, serializeAttributes } from "../lib/wrap-utils";+import WrapAttributesModal from "./wrap-attributes-modal";++export default class WrapNodeView extends Component {+ @service modal;++ constructor() {+ super(...arguments);+ this.args.onSetup?.(this);+ }++ willDestroy() {+ super.willDestroy(...arguments);+ }++ get isInline() {+ return this.args.node.type.name === "wrap_inline";+ }++ get wrapAttributes() {+ return this.args.node.attrs.data || {};+ }++ get attributesDisplay() {+ const attrs = this.wrapAttributes;+ if (!attrs || Object.keys(attrs).length === 0) {+ return "[wrap]";+ }++ // Display only the wrap name if it exists, otherwise show [wrap]+ if (attrs.wrap) {+ return `[wrap=${attrs.wrap}]`;+ }++ return "[wrap]";+ }++ @action+ editAttributes() {+ const attrsString = serializeAttributes(this.wrapAttributes);++ this.modal.show(WrapAttributesModal, {+ model: {+ initialAttributes: attrsString,+ onApply: this.#updateAttributes.bind(this),+ onRemove: this.removeWrap.bind(this),+ },+ });+ }++ @action+ removeWrap() {+ const pos = this.args.getPos();+ const node = this.args.node;++ if (node.content.size === 0) {+ // Empty wrap, just delete it+ this.args.view.dispatch(+ this.args.view.state.tr.delete(pos, pos + node.nodeSize)+ );+ } else {+ // Replace wrap with its content+ const tr = this.args.view.state.tr;+ tr.replaceWith(pos, pos + node.nodeSize, node.content);+ this.args.view.dispatch(tr);+ }+ }++ #updateAttributes(attrsString) {+ const pos = this.args.getPos();+ const attrs = parseAttributesString(attrsString);+ const tr = this.args.view.state.tr;++ tr.setNodeMarkup(pos, null, { data: attrs });+ tr.setSelection(NodeSelection.create(tr.doc, pos));+ this.args.view.dispatch(tr);+ }++ selectNode() {+ this.args.dom.classList.add("ProseMirror-selectednode");+ }++ deselectNode() {+ this.args.dom.classList.remove("ProseMirror-selectednode");+ }++ <template>+ {{~! strip whitespace ~}}<button+ type="button"+ class="d-wrap-indicator btn-flat+ {{if this.isInline '--inline' '--block'}}"+ contenteditable="false"+ {{on "click" this.editAttributes}}+ >{{~this.attributesDisplay~}}</button>+ {{~yield~}}{{~! strip whitespace ~}}+ </template>+}diff --git a/frontend/discourse/app/static/prosemirror/extensions/register-default.js b/frontend/discourse/app/static/prosemirror/extensions/register-default.jsindex 9e63700c01e..5402cae55e9 100644--- a/frontend/discourse/app/static/prosemirror/extensions/register-default.js+++ b/frontend/discourse/app/static/prosemirror/extensions/register-default.js@@ -26,6 +26,7 @@ import trailingInlineSpace from "./trailing-inline-space";import trailingParagraph from "./trailing-paragraph";import typographerReplacements from "./typographer-replacements";import underline from "./underline";+import wrap from "./wrap";/*** List of default extensions@@ -55,6 +56,7 @@ const defaultExtensions = [markdownPaste,orderedList,bulletList,+ wrap,trailingInlineSpace,overrideDragGhost,hardBreak,diff --git a/frontend/discourse/app/static/prosemirror/extensions/wrap.js b/frontend/discourse/app/static/prosemirror/extensions/wrap.jsnew file mode 100644index 00000000000..19a054ce3de--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/extensions/wrap.js@@ -0,0 +1,308 @@+import { camelCaseToDash } from "discourse/lib/case-converter";+import { i18n } from "discourse-i18n";+import WrapNodeView from "../components/wrap-node-view";+import GlimmerNodeView from "../lib/glimmer-node-view";+import { parseAttributesString, serializeAttributes } from "../lib/wrap-utils";++const toDataAttrs = (data) => {+ if (!data) {+ return {};+ }+ const attrs = {};+ for (const [key, value] of Object.entries(data)) {+ if (value != null && value !== "") {+ attrs[`data-${camelCaseToDash(key)}`] = value;+ }+ }+ return attrs;+};++const createWrapNodeView =+ ({ getContext }) =>+ (node, view, getPos) =>+ new GlimmerNodeView({+ node,+ view,+ getPos,+ getContext,+ component: WrapNodeView,+ name: "wrap",+ hasContent: true,+ });++/** @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension} */+const extension = {+ nodeViews: {+ wrap_block: createWrapNodeView,+ wrap_inline: createWrapNodeView,+ },++ commands: ({ schema }) => ({+ insertWrap:+ (attributes = {}) =>+ (state, dispatch, view) => {+ const { selection } = state;+ const { empty, $from, $to } = selection;++ const attrs = { data: attributes };+ const tr = state.tr;++ if (empty) {+ // Empty selection: choose block vs inline based on cursor position+ const isBlockWrap = view?.endOfTextblock?.("backward");+ const wrapType = isBlockWrap+ ? schema.nodes.wrap_block+ : schema.nodes.wrap_inline;++ if (!wrapType) {+ return false;+ }++ const wrap = isBlockWrap+ ? wrapType.create(attrs, schema.nodes.paragraph.create())+ : wrapType.create(attrs);++ tr.replaceSelectionWith(wrap);++ if (isBlockWrap) {+ tr.setSelection(+ selection.constructor.create(tr.doc, $from.pos + 2)+ );+ }+ } else {+ // Non-empty selection: check if it's a full block selection+ const isBlockSelection =+ $from.parent === $to.parent &&+ $from.parentOffset === 0 &&+ $to.parentOffset === $from.parent.content.size &&+ $from.parent.isBlock &&+ $from.depth > 0;++ if (isBlockSelection) {+ const wrapType = schema.nodes.wrap_block;+ if (!wrapType) {+ return false;+ }++ const range = $from.blockRange($to);+ if (!range) {+ return false;+ }++ tr.wrap(range, [{ type: wrapType, attrs }]);+ } else {+ const wrapType = schema.nodes.wrap_inline;+ if (!wrapType) {+ return false;+ }++ const content = state.doc.slice(selection.from, selection.to);+ const wrap = wrapType.create(attrs, content.content);+ tr.replaceWith(selection.from, selection.to, wrap);+ }+ }++ dispatch?.(tr);+ return true;+ },++ updateWrap: (attributesString) => (state, dispatch) => {+ const { $from } = state.selection;++ for (let depth = $from.depth; depth >= 0; depth--) {+ const node = $from.node(depth);+ if (+ node.type.name === "wrap_block" ||+ node.type.name === "wrap_inline"+ ) {+ const pos = $from.before(depth);+ const newAttrs = parseAttributesString(attributesString);+ const tr = state.tr.setNodeMarkup(pos, null, { data: newAttrs });+ dispatch?.(tr);+ return true;+ }+ }++ return false;+ },++ removeWrap: () => (state, dispatch) => {+ const { $from } = state.selection;++ for (let depth = $from.depth; depth >= 0; depth--) {+ const node = $from.node(depth);+ if (+ node.type.name === "wrap_block" ||+ node.type.name === "wrap_inline"+ ) {+ const pos = $from.before(depth);+ const tr = state.tr;++ if (node.content.size === 0) {+ // Empty wrap, just delete it+ tr.delete(pos, pos + node.nodeSize);+ } else {+ // Replace wrap with its content+ tr.replaceWith(pos, pos + node.nodeSize, node.content);+ }++ dispatch?.(tr);+ return true;+ }+ }++ return false;+ },+ }),++ state: ({ utils, schema }, state) => {+ const inWrap =+ utils.inNode(state, schema.nodes.wrap_block) ||+ utils.inNode(state, schema.nodes.wrap_inline);++ if (!inWrap) {+ return { inWrap: false };+ }++ const { $from } = state.selection;+ for (let depth = $from.depth; depth >= 0; depth--) {+ const node = $from.node(depth);+ if (node.type.name === "wrap_block" || node.type.name === "wrap_inline") {+ return {+ inWrap: true,+ wrapAttributes: serializeAttributes(node.attrs.data || {}),+ };+ }+ }++ return { inWrap: false };+ },++ nodeSpec: {+ wrap_block: {+ content: "block+",+ group: "block",+ defining: true,+ createGapCursor: true,+ attrs: {+ data: { default: {} },+ },+ parseDOM: [+ {+ tag: "div.d-wrap",+ getAttrs: (dom) => ({ data: { ...dom.dataset } }),+ },+ ],+ toDOM: (node) => [+ "div",+ { class: "d-wrap", ...toDataAttrs(node.attrs.data) },+ 0,+ ],+ },++ wrap_inline: {+ inline: true,+ group: "inline",+ content: "inline*",+ defining: true,+ attrs: {+ data: { default: {} },+ },+ parseDOM: [+ {+ tag: "span.d-wrap",+ getAttrs: (dom) => ({ data: { ...dom.dataset } }),+ },+ ],+ toDOM: (node) => [+ "span",+ { class: "d-wrap", ...toDataAttrs(node.attrs.data) },+ 0,+ ],+ },+ },++ parse: {+ wrap_open(state, token) {+ const isInline = token.tag === "span";+ const nodeType = isInline+ ? state.schema.nodes.wrap_inline+ : state.schema.nodes.wrap_block;++ const data = {};+ if (token?.attrs) {+ for (const [name, value] of token.attrs) {+ if (name.startsWith("data-")) {+ data[name.slice(5)] = value;+ } else if (name !== "class" || value !== "d-wrap") {+ data[name] = value;+ }+ }+ }+ state.openNode(nodeType, { data });+ return true;+ },++ wrap_close(state) {+ const top = state.top();+ if (!top) {+ return;+ }+ if (top.type.name === "wrap_block" || top.type.name === "wrap_inline") {+ state.closeNode();+ return true;+ }+ },+ },++ serializeNode: {+ wrap_block(state, node) {+ const attrs = serializeAttributes(node.attrs.data);+ state.write(`[wrap${attrs}]\n`);+ state.renderContent(node);+ state.write("[/wrap]\n\n");+ },++ wrap_inline(state, node) {+ const attrs = serializeAttributes(node.attrs.data);+ state.write(`[wrap${attrs}]`);+ state.renderInline(node);+ state.write("[/wrap]");+ },+ },++ inputRules: () => ({+ match: /\[wrap([^\]]*)]$/,+ handler: (state, match, start, end) => {+ const { schema } = state;+ const isAtStart = state.doc.resolve(start).parentOffset === 0;++ const attributeString = match[1] || "";+ const attributes = parseAttributesString(attributeString);++ const tr = state.tr;++ if (isAtStart) {+ const wrapNode = schema.nodes.wrap_block.createAndFill(+ { data: attributes },+ schema.nodes.paragraph.createAndFill()+ );++ tr.replaceWith(start - 1, end, wrapNode);+ } else {+ // Inline wrap: placeholder text+ const textNode = schema.text(i18n("composer.wrap_text"));+ const wrapNode = schema.nodes.wrap_inline.createAndFill(+ { data: attributes },+ textNode+ );++ tr.replaceWith(start, end, wrapNode);+ }++ return tr;+ },+ }),+};++export default extension;diff --git a/frontend/discourse/app/static/prosemirror/lib/glimmer-node-view.js b/frontend/discourse/app/static/prosemirror/lib/glimmer-node-view.jsindex 6f0ec085043..4227741b348 100644--- a/frontend/discourse/app/static/prosemirror/lib/glimmer-node-view.js+++ b/frontend/discourse/app/static/prosemirror/lib/glimmer-node-view.js@@ -19,7 +19,15 @@ export default class GlimmerNodeView {/*** @param {GlimmerNodeViewArgs} args*/- constructor({ node, view, getPos, getContext, component, name }) {+ constructor({+ node,+ view,+ getPos,+ getContext,+ component,+ name,+ hasContent = false,+ }) {this.node = node;this.view = view;this.getPos = getPos;@@ -28,13 +36,24 @@ export default class GlimmerNodeView {getContext().addGlimmerNodeView(this);- this.dom = document.createElement("div");+ this.dom = document.createElement(node.isInline ? "span" : "div");this.dom.classList.add(`composer-${name}-node`);+ if (hasContent) {+ this.contentDOM = document.createElement(node.isInline ? "span" : "div");+ }}@actionsetComponentInstance(instance) {this.#componentInstance = instance;++ if (this.#componentInstance?.setSelection) {+ this.setSelection = this.#componentInstance.setSelection.bind(+ this.#componentInstance+ );+ } else {+ this.setSelection = undefined;+ }}update(node) {@@ -51,16 +70,12 @@ export default class GlimmerNodeView {next(() => this.#componentInstance?.deselectNode?.());}- setSelection() {- this.#componentInstance?.setSelection?.(...arguments);- }-stopEvent(event) {return this.#componentInstance?.stopEvent?.(event) ?? false;}- ignoreMutation() {- return this.#componentInstance?.ignoreMutation?.() ?? true;+ ignoreMutation(mutation) {+ return this.#componentInstance?.ignoreMutation?.(mutation) ?? true;}destroy() {diff --git a/frontend/discourse/app/static/prosemirror/lib/wrap-utils.js b/frontend/discourse/app/static/prosemirror/lib/wrap-utils.jsnew file mode 100644index 00000000000..afe341806ec--- /dev/null+++ b/frontend/discourse/app/static/prosemirror/lib/wrap-utils.js@@ -0,0 +1,77 @@+/**+ * Parse an attributes string into flat object (matches server behavior)+ * @param {string} attrsString - The attributes string to parse+ * @returns {Object} Flat object like {wrap: "toc", id: "123"}+ */+export function parseAttributesString(attrsString) {+ if (!attrsString.trim()) {+ return {};+ }++ const attrs = {};+ const parts = attrsString.trim().split(/\s+/);++ for (const part of parts) {+ if (part.startsWith("=")) {+ attrs.wrap = part.slice(1);+ } else if (part.includes("=")) {+ const [key, ...valueParts] = part.split("=");+ attrs[key] = valueParts.join("=");+ }+ }++ return attrs;+}++/**+ * Serialize flat object back to BBCode format+ * @param {Object} data - Flat object like {wrap: "toc", id: "123"}+ * @returns {string} Serialized attributes string+ */+export function serializeAttributes(data) {+ if (!data || Object.keys(data).length === 0) {+ return "";+ }++ let result = "";++ // Handle wrap name first+ if (data.wrap) {+ result = `=${data.wrap}`;+ }++ // Handle other attributes+ const otherAttrs = Object.entries(data)+ .filter(([key]) => key !== "wrap")+ .map(([key, value]) => `${key}=${value}`)+ .join(" ");++ if (otherAttrs) {+ if (result) {+ result += ` ${otherAttrs}`;+ } else {+ result = ` ${otherAttrs}`;+ }+ }++ return result;+}++/**+ * Serialize name and attributes array to BBCode format (for modal)+ * @param {string} name - Wrap name+ * @param {Array} attributes - Array of {key, value} objects+ * @returns {string} Serialized attributes string+ */+export function serializeFromForm(name, attributes = []) {+ const data = {};+ if (name) {+ data.wrap = name;+ }+ for (const attr of attributes) {+ if (attr.key && attr.value) {+ data[attr.key] = attr.value;+ }+ }+ return serializeAttributes(data);+}diff --git a/spec/system/composer/prosemirror_wrap_spec.rb b/spec/system/composer/prosemirror_wrap_spec.rbnew file mode 100644index 00000000000..c22ae95e36b--- /dev/null+++ b/spec/system/composer/prosemirror_wrap_spec.rb@@ -0,0 +1,108 @@+# frozen_string_literal: true++describe "Composer - ProseMirror - Inline and Block Wrap", type: :system do+ include_context "with prosemirror editor"++ it "supports [wrap] to create a wrap block" do+ open_composer+ composer.type_content("[wrap]")++ expect(rich).to have_css(".composer-wrap-node")++ composer.toggle_rich_editor++ expect(composer).to have_value("[wrap]\n\n[/wrap]\n\n")+ end++ it "supports [wrap=name] to create a named wrap block" do+ open_composer+ composer.type_content("[wrap=example]")++ expect(rich).to have_css(".composer-wrap-node")++ composer.toggle_rich_editor++ expect(composer).to have_value("[wrap=example]\n\n[/wrap]\n\n")+ end++ it "supports [wrap class=foo] to create a wrap block with attributes" do+ open_composer+ composer.type_content("[wrap class=highlight]")++ expect(rich).to have_css(".composer-wrap-node")++ composer.toggle_rich_editor++ expect(composer).to have_value("[wrap class=highlight]\n\n[/wrap]\n\n")+ end++ it "creates inline wrap when not at start of line" do+ open_composer+ composer.type_content("Text before [wrap=inline]")++ expect(rich).to have_css(".composer-wrap-node")+ expect(rich).to have_content("Text before")+ expect(rich).to have_content("Wrap content")++ composer.toggle_rich_editor++ expect(composer).to have_value("Text before [wrap=inline]Wrap content[/wrap] ")+ end++ it "opens edit modal when clicking wrap indicator" do+ open_composer+ composer.type_content("[wrap=outer]")++ expect(rich).to have_css(".composer-wrap-node")++ rich.find(".d-wrap-indicator").click++ expect(page).to have_css(".wrap-attributes-modal")+ expect(page).to have_field("name", with: "outer") # Should show existing wrap name++ page.fill_in("name", with: "updated")++ page.find("button", text: "Add attribute").click++ within(".wrap-modal__attribute-row") do+ page.fill_in("Key", with: "class")+ page.fill_in("Value", with: "highlight")+ end++ page.find("button", text: "Apply").click++ expect(rich).to have_css(".composer-wrap-node", count: 1)++ composer.toggle_rich_editor++ expect(composer).to have_value("[wrap=updated class=highlight]\n\n[/wrap]\n\n")+ end++ it "opens edit modal from toolbar when cursor is inside existing wrap" do+ open_composer+ composer.type_content("[wrap=example class=test]")++ expect(rich).to have_css(".composer-wrap-node")++ rich.find(".composer-wrap-node").click++ find("#reply-control .d-editor-button-bar .toolbar__button.options").click++ find("[data-name='toggle-wrap']").click++ expect(page).to have_css(".wrap-attributes-modal")+ expect(page).to have_field("name", with: "example") # Should show existing wrap name+ expect(page).to have_field("Key", with: "class") # Should show existing class attribute+ expect(page).to have_field("Value", with: "test")++ page.fill_in("name", with: "updated")+ page.fill_in("Value", with: "highlight")+ page.find("button", text: "Apply").click++ expect(rich).to have_css(".composer-wrap-node", count: 1)++ composer.toggle_rich_editor++ expect(composer).to have_value("[wrap=updated class=highlight]\n\n[/wrap]\n\n")+ end+end