A platform for community discussion. Free, open, simple.
UX: improvements to rich editor spoiler (#34149)
Renato Atilioe8aeb272bba8
diff --git a/app/assets/javascripts/discourse-markdown-it/src/features/bbcode-block.js b/app/assets/javascripts/discourse-markdown-it/src/features/bbcode-block.jsindex f2c519a9b01..78815afdb44 100644--- a/app/assets/javascripts/discourse-markdown-it/src/features/bbcode-block.js+++ b/app/assets/javascripts/discourse-markdown-it/src/features/bbcode-block.js@@ -285,6 +285,12 @@ function applyBBCode(state, startLine, endLine, silent, md) {return false;}+ // If an inline close tag is found and there's content after it on the same line,+ // let the inline processor handle it instead of block processing+ if (!closeTag.block && closeTag.start + closeTag.length < max) {+ return false;+ }+nextLine = closeTag.line || startLine;oldParent = state.parentType;diff --git a/app/assets/javascripts/discourse/app/components/d-editor.gjs b/app/assets/javascripts/discourse/app/components/d-editor.gjsindex e948e143778..cdb0a274931 100644--- a/app/assets/javascripts/discourse/app/components/d-editor.gjs+++ b/app/assets/javascripts/discourse/app/components/d-editor.gjs@@ -509,6 +509,7 @@ export default class DEditor extends Component {lineVal: true,});return {+ commands: this.textManipulation.commands,selected,selectText: (from, length) =>this.textManipulation.selectText(from, length, { scroll: false }),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.jsindex 2761ad1fee4..2a6f31a408a 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@@ -93,6 +93,8 @@* ProseMirror node views* @property {RichKeymap} [keymap]* Additional keymap definitions+ * @property {(params: PluginParams) => Record<string, import('prosemirror-state').Command>} [commands]+ * Command definitions that will be available on view.state.commands*//** @type {RichEditorExtension[]} */diff --git a/app/assets/javascripts/discourse/app/lib/textarea-text-manipulation.js b/app/assets/javascripts/discourse/app/lib/textarea-text-manipulation.jsindex 0a661500e63..9a1cf66171a 100644--- a/app/assets/javascripts/discourse/app/lib/textarea-text-manipulation.js+++ b/app/assets/javascripts/discourse/app/lib/textarea-text-manipulation.js@@ -3,6 +3,7 @@ import { getOwner, setOwner } from "@ember/owner";import { next, schedule } from "@ember/runloop";import { service } from "@ember/service";import { isEmpty } from "@ember/utils";+import { TrackedObject } from "@ember-compat/tracked-built-ins";import $ from "jquery";import { bind } from "discourse/lib/decorators";import { isTesting } from "discourse/lib/environment";@@ -71,6 +72,9 @@ export default class TextareaTextManipulation {autocompleteHandler;placeholder;+ /** @type {import("discourse/lib/composer/text-manipulation").ToolbarState} */+ state = new TrackedObject();+constructor(owner, { markdownOptions, textarea, eventPrefix = "composer" }) {setOwner(this, owner);this.placeholder = new TextareaPlaceholderHandler(owner, this);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.gjsindex 8a5593ba0fb..54740fb6483 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@@ -24,6 +24,7 @@ import * as ProsemirrorView from "prosemirror-view";import { EditorView } from "prosemirror-view";import { getExtensions } from "discourse/lib/composer/rich-editor-extensions";import { bind } from "discourse/lib/decorators";+import { buildCommands, buildCustomState } from "../core/commands";import { buildInputRules } from "../core/inputrules";import { buildKeymap } from "../core/keymap";import Parser from "../core/parser";@@ -174,14 +175,10 @@ export default class ProsemirrorEditor extends Component {...extractPlugins(this.extensions, params, this.handleAsyncPlugin),];- this.parser = new Parser(- this.extensions,- this.pluginParams,- this.args.includeDefault- );+ this.parser = new Parser(this.extensions, params, this.args.includeDefault);this.serializer = new Serializer(this.extensions,- this.pluginParams,+ params,this.args.includeDefault);@@ -189,7 +186,7 @@ export default class ProsemirrorEditor extends Component {this.view = new EditorView(container, {state,- nodeViews: extractNodeViews(this.extensions, this.pluginParams),+ nodeViews: extractNodeViews(this.extensions, params),attributes: { class: this.args.class ?? "" },editable: () => this.args.disabled !== true,dispatchTransaction: (tr) => {@@ -228,6 +225,8 @@ export default class ProsemirrorEditor extends Component {view: this.view,convertFromMarkdown: this.convertFromMarkdown,convertToMarkdown: this.convertToMarkdown,+ commands: buildCommands(this.extensions, params, this.view),+ customState: buildCustomState(this.extensions, params),});this.#destructor = this.args.onSetup?.(this.textManipulation);diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/core/commands.js b/app/assets/javascripts/discourse/app/static/prosemirror/core/commands.jsnew file mode 100644index 00000000000..14d5dd9e156--- /dev/null+++ b/app/assets/javascripts/discourse/app/static/prosemirror/core/commands.js@@ -0,0 +1,32 @@+export function buildCommands(extensions, pluginParams, view) {+ const allCommands = {};++ for (const { commands } of extensions) {+ if (commands) {+ for (let [name, command] of Object.entries(commands(pluginParams))) {+ allCommands[name] = (...args) => {+ view.focus();+ return command(...args)(view.state, view.dispatch, view);+ };+ }+ }+ }+ return allCommands;+}++export function buildCustomState(extensions, params) {+ return (viewState) => {+ const allCustomStates = {};++ for (const { state } of extensions) {+ if (state) {+ for (let [name, stateResult] of Object.entries(+ state(params, viewState)+ )) {+ allCustomStates[name] = stateResult;+ }+ }+ }+ return allCustomStates;+ };+}diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/core/keymap.js b/app/assets/javascripts/discourse/app/static/prosemirror/core/keymap.jsindex 2adda4be70f..bf0f5459ba6 100644--- a/app/assets/javascripts/discourse/app/static/prosemirror/core/keymap.js+++ b/app/assets/javascripts/discourse/app/static/prosemirror/core/keymap.js@@ -28,8 +28,16 @@ export function buildKeymap(...extractKeymap(extensions, params),};- keys["Mod-z"] = undo;- keys["Shift-Mod-z"] = redo;+ function chainWithExisting(key, ...commands) {+ if (keys[key]) {+ keys[key] = chainCommands(keys[key], ...commands);+ } else {+ keys[key] = chainCommands(...commands);+ }+ }++ chainWithExisting("Mod-z", undo);+ chainWithExisting("Shift-Mod-z", redo);const backspaceUnset = (state, dispatch, view) => {const $pos = atBlockStart(state, view);@@ -39,17 +47,18 @@ export function buildKeymap(return false;};- keys["Backspace"] = chainCommands(+ chainWithExisting(+ "Backspace",undoInputRule,backspaceUnset,joinTextblockBackward);if (!isMac) {- keys["Mod-y"] = redo;+ chainWithExisting("Mod-y", redo);}- keys["Escape"] = selectParentNode;+ chainWithExisting("Escape", selectParentNode);// The above keys are always includedif (!includeDefault) {@@ -58,7 +67,7 @@ export function buildKeymap(const schema = params.schema;- keys["Shift-Enter"] = chainCommands(exitCode, (state, dispatch) => {+ chainWithExisting("Shift-Enter", exitCode, (state, dispatch) => {if (dispatch) {dispatch(state.tr@@ -90,27 +99,35 @@ export function buildKeymap(return false;};- keys["Enter"] = chainCommands(+ chainWithExisting(+ "Enter",doubleSpaceHardBreak,splitListItem(schema.nodes.list_item));- keys["Mod-Shift-_"] = (state, dispatch) => {+ chainWithExisting("Mod-Shift-_", (state, dispatch) => {dispatch?.(state.tr.replaceSelectionWith(schema.nodes.horizontal_rule.create()).scrollIntoView());return true;- };+ });return keys;}function extractKeymap(extensions, params) {- return {- ...extensions.map(({ keymap }) => {+ const keymaps = extensions+ .map(({ keymap }) => {return keymap instanceof Function ? keymap(params) : keymap;- }),- };+ })+ .filter(Boolean);++ const combined = {};+ keymaps.forEach((keymap) => {+ Object.assign(combined, keymap);+ });++ return combined;}diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/html-inline.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/html-inline.jsindex f9d55c72c4f..84f9f5f79cd 100644--- a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/html-inline.js+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/html-inline.js@@ -24,12 +24,10 @@ const ALL_ALLOWED_TAGS = [...Object.keys(HTML_INLINE_MARKS), ...ALLOWED_INLINE];/** @type {RichEditorExtension} */const extension = {nodeSpec: {- // TODO(renato): this node is hard to get past when at the end of a block- // and is added to a newline unintentionally, investigatehtml_inline: {group: "inline",inline: true,- isolating: true,+ defining: true,content: "inline*",attrs: { tag: {} },parseDOM: ALLOWED_INLINE.map((tag) => ({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.jsindex 43add860648..2bf445cb89c 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@@ -17,6 +17,7 @@ import orderedList from "./ordered-list";import quote from "./quote";import strikethrough from "./strikethrough";import table from "./table";+import trailingInlineSpace from "./trailing-inline-space";import trailingParagraph from "./trailing-paragraph";import typographerReplacements from "./typographer-replacements";import underline from "./underline";@@ -49,6 +50,7 @@ const defaultExtensions = [markdownPaste,orderedList,bulletList,+ trailingInlineSpace,];defaultExtensions.forEach(registerRichEditorExtension);diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/trailing-inline-space.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/trailing-inline-space.jsnew file mode 100644index 00000000000..c5ece35cce4--- /dev/null+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/trailing-inline-space.js@@ -0,0 +1,116 @@+import { splitBlock } from "prosemirror-commands";+import { TextSelection } from "prosemirror-state";++function isInlineContainer(node) {+ return (+ node.isInline &&+ !node.isText &&+ node.type?.spec?.content &&+ !node.type?.spec?.atom+ );+}++function findInlineContainerDepth($from) {+ for (let depth = $from.depth; depth > 0; depth--) {+ if (isInlineContainer($from.node(depth))) {+ return depth;+ }+ }+ return null;+}++/** @type {RichEditorExtension} */+const extension = {+ keymap: () => ({+ Enter: (state, dispatch) => {+ const selection = state.selection;+ if (!(selection instanceof TextSelection)) {+ return false;+ }++ const initialDepth = findInlineContainerDepth(selection.$from);+ if (!dispatch) {+ return selection.empty ? initialDepth !== null : true;+ }+ if (selection.empty && initialDepth === null) {+ return false;+ }++ const tr = state.tr;+ if (!selection.empty) {+ tr.delete(selection.from, selection.to);+ }++ const basePos = selection.empty ? selection.$from.pos : selection.from;+ const mappedBasePos = tr.mapping.map(basePos, -1);+ let $from = tr.doc.resolve(mappedBasePos);+ const depth = findInlineContainerDepth($from);+ if (depth === null) {+ if (tr.steps.length) {+ dispatch(tr);+ }+ return splitBlock(tr.steps.length ? state.apply(tr) : state, dispatch);+ }++ const atStart = $from.pos === $from.start(depth);+ const atEnd = $from.pos === $from.end(depth);++ if (atStart) {+ const pos = $from.before(depth);+ tr.setSelection(TextSelection.create(tr.doc, pos));+ dispatch(tr);+ return splitBlock(state.apply(tr), dispatch);+ }++ if (atEnd) {+ let pos = $from.after(depth);+ const next = tr.doc.resolve(pos).nodeAfter;+ if (next?.isText && next.text?.[0] === " ") {+ pos += 1;+ }+ tr.setSelection(TextSelection.create(tr.doc, pos));+ dispatch(tr);+ return splitBlock(state.apply(tr), dispatch);+ }++ const fromPos = $from.pos;+ const containerEnd = $from.end(depth);+ const rightSlice = tr.doc.slice(fromPos, containerEnd);++ tr.delete(fromPos, containerEnd);+ $from = tr.doc.resolve(fromPos);+ const outsidePos = $from.after(depth);+ if (rightSlice.content.size) {+ tr.insert(outsidePos, rightSlice.content);+ }+ tr.setSelection(TextSelection.create(tr.doc, outsidePos));+ dispatch(tr);+ return splitBlock(state.apply(tr), dispatch);+ },+ }),+ plugins: ({+ pmState: { Plugin, PluginKey },+ utils: { changedDescendants },+ }) =>+ new Plugin({+ key: new PluginKey("trailingInlineSpace"),++ appendTransaction(transactions, oldState, newState) {+ const tr = newState.tr;++ changedDescendants(oldState.doc, newState.doc, (node, pos) => {+ if (!node.isBlock || !node.inlineContent || node.childCount === 0) {+ return;+ }+ const lastChild = node.lastChild;+ if (lastChild && isInlineContainer(lastChild)) {+ tr.insert(pos + node.nodeSize - 1, newState.schema.text(" "));+ }+ });++ return tr.steps.length ? tr : null;+ },+ }),+};++export default extension;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.jsindex 61349cfac79..28411c79fd7 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@@ -40,12 +40,24 @@ export default class ProsemirrorTextManipulation {convertFromMarkdown;convertToMarkdown;- constructor(owner, { schema, view, convertFromMarkdown, convertToMarkdown }) {+ constructor(+ owner,+ {+ schema,+ view,+ convertFromMarkdown,+ convertToMarkdown,+ commands,+ customState,+ }+ ) {setOwner(this, owner);this.schema = schema;this.view = view;this.convertFromMarkdown = convertFromMarkdown;this.convertToMarkdown = convertToMarkdown;+ this.commands = commands;+ this.customState = customState;this.placeholder = new ProsemirrorPlaceholderHandler({schema,@@ -394,6 +406,7 @@ export default class ProsemirrorTextManipulation {inHeading: !!activeHeadingLevel,inHeadingLevel: activeHeadingLevel,inParagraph: inNode(this.view.state, this.schema.nodes.paragraph),+ ...this.customState(this.view.state),});}}diff --git a/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/html-inline-test.js b/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/html-inline-test.jsindex 34420f13e0b..e9d12e33bcd 100644--- a/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/html-inline-test.js+++ b/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/html-inline-test.js@@ -10,13 +10,13 @@ module(Object.entries({"basic inline HTML tags": ["<kbd>Ctrl</kbd>",- "<p><kbd>Ctrl</kbd></p>",- "<kbd>Ctrl</kbd>",+ "<p><kbd>Ctrl</kbd> </p>",+ "<kbd>Ctrl</kbd> ",],"nested inline HTML": ["<sup><small>text</small></sup>",- "<p><sup><small>text</small></sup></p>",- "<sup><small>text</small></sup>",+ "<p><sup><small>text</small></sup> </p>",+ "<sup><small>text</small></sup> ",],"inline marks using HTML": ["<strong>bold</strong> and <em>italic</em>",@@ -25,13 +25,13 @@ module(],"mixed HTML inline and marks": ["<kbd><strong>Ctrl+B</strong></kbd>",- "<p><kbd><strong>Ctrl+B</strong></kbd></p>",- "<kbd>**Ctrl+B**</kbd>",+ "<p><kbd><strong>Ctrl+B</strong></kbd> </p>",+ "<kbd>**Ctrl+B**</kbd> ",],"multiple inline elements": ["Text with <sub>subscript</sub> and <sup>superscript</sup>",- "<p>Text with <sub>subscript</sub> and <sup>superscript</sup></p>",- "Text with <sub>subscript</sub> and <sup>superscript</sup>",+ "<p>Text with <sub>subscript</sub> and <sup>superscript</sup> </p>",+ "Text with <sub>subscript</sub> and <sup>superscript</sup> ",],"HTML mark aliases": ["<b>bold</b> and <i>italic</i>",@@ -40,8 +40,8 @@ module(],"semantic HTML elements": ["<ins>inserted</ins> and <del>deleted</del>",- "<p><ins>inserted</ins> and <del>deleted</del></p>",- "<ins>inserted</ins> and <del>deleted</del>",+ "<p><ins>inserted</ins> and <del>deleted</del> </p>",+ "<ins>inserted</ins> and <del>deleted</del> ",],}).forEach(([name, [markdown, html, expectedMarkdown]]) => {test(name, async function (assert) {diff --git a/app/assets/stylesheets/common/toolbar-popup-menu-options.scss b/app/assets/stylesheets/common/toolbar-popup-menu-options.scssindex 16e3e42a945..6714e40f3a4 100644--- a/app/assets/stylesheets/common/toolbar-popup-menu-options.scss+++ b/app/assets/stylesheets/common/toolbar-popup-menu-options.scss@@ -26,6 +26,34 @@}}+.toolbar-menu__options-content {+ .dropdown-menu {+ .btn {+ &.--active {+ .d-button-label__active-icon {+ visibility: visible;+ margin-left: auto;+ }+ }+ }++ .d-button-label {+ display: flex;+ flex: 1;+ justify-content: space-between;+ align-items: center;++ &__active-icon {+ visibility: hidden;+ }++ .shortcut {+ margin-left: var(--space-4);+ }+ }+ }+}+.toolbar-menu__heading-content {.dropdown-menu {.btn {diff --git a/plugins/spoiler-alert/assets/javascripts/initializers/spoiler-alert.js b/plugins/spoiler-alert/assets/javascripts/initializers/spoiler-alert.jsindex ca596948e7b..c36d05589a3 100644--- a/plugins/spoiler-alert/assets/javascripts/initializers/spoiler-alert.js+++ b/plugins/spoiler-alert/assets/javascripts/initializers/spoiler-alert.js@@ -19,12 +19,18 @@ export function initializeSpoiler(api) {api.addComposerToolbarPopupMenuOption({icon: "wand-magic",+ active: ({ state }) => state.inSpoiler,+ showActiveIcon: true,label: "spoiler.title",action: (toolbarEvent) => {- toolbarEvent.applySurround("[spoiler]", "[/spoiler]", "spoiler_text", {- multiline: false,- useBlockMode: true,- });+ if (toolbarEvent.commands) {+ toolbarEvent.commands.toggleSpoiler();+ } else {+ toolbarEvent.applySurround("[spoiler]", "[/spoiler]", "spoiler_text", {+ multiline: false,+ useBlockMode: true,+ });+ }},});@@ -46,6 +52,7 @@ export function initializeSpoiler(api) {return text.trim();}});+api.registerRichEditorExtension(richEditorExtension);}diff --git a/plugins/spoiler-alert/assets/javascripts/lib/discourse-markdown/spoiler-alert.js b/plugins/spoiler-alert/assets/javascripts/lib/discourse-markdown/spoiler-alert.jsindex 2354e98bad7..e75e3616b5a 100644--- a/plugins/spoiler-alert/assets/javascripts/lib/discourse-markdown/spoiler-alert.js+++ b/plugins/spoiler-alert/assets/javascripts/lib/discourse-markdown/spoiler-alert.js@@ -1,26 +1,6 @@-const CONTAINS_BLOCK_REGEX = /\n|<img|!\[[^\]]*\][(\[]/;--function insertSpoiler(_, spoiler) {- const element = CONTAINS_BLOCK_REGEX.test(spoiler) ? "div" : "span";- return `<${element} class='spoiler'>${spoiler}</${element}>`;-}--function replaceSpoilers(text) {- text ||= "";- let previousText;-- do {- previousText = text;- text = text.replace(- /\[spoiler\]((?:(?!\[spoiler\]|\[\/spoiler\])[\S\s])*)\[\/spoiler\]/gi,- insertSpoiler- );- } while (text !== previousText);-- return text;-}+export function setup(helper) {+ helper.allowList(["span.spoiler", "div.spoiler"]);-function setupMarkdownIt(helper) {helper.registerOptions((opts, siteSettings) => {opts.features["spoiler-alert"] = !!siteSettings.spoiler_enabled;});@@ -37,13 +17,3 @@ function setupMarkdownIt(helper) {});});}--export function setup(helper) {- helper.allowList(["span.spoiler", "div.spoiler"]);-- if (helper.markdownIt) {- setupMarkdownIt(helper);- } else {- helper.addPreProcessor(replaceSpoilers);- }-}diff --git a/plugins/spoiler-alert/assets/javascripts/lib/rich-editor-extension.js b/plugins/spoiler-alert/assets/javascripts/lib/rich-editor-extension.jsindex 6c70127e2e0..a6fc23ba677 100644--- a/plugins/spoiler-alert/assets/javascripts/lib/rich-editor-extension.js+++ b/plugins/spoiler-alert/assets/javascripts/lib/rich-editor-extension.js@@ -1,3 +1,5 @@+import { i18n } from "discourse-i18n";+const SPOILER_NODES = ["inline_spoiler", "spoiler"];/** @type {RichEditorExtension} */@@ -43,38 +45,215 @@ const extension = {state.write("[/spoiler]");},},+ inputRules: ({ pmState: { TextSelection } }) => ({+ match: /\[spoiler\]$/,+ handler: (state, match, start, end) => {+ const { schema } = state;+ const textNode = schema.text(i18n("composer.spoiler_text"));++ const atStart = state.doc.resolve(start).parentOffset === 0;++ const tr = state.tr;++ if (atStart) {+ tr.replaceWith(+ start - 1,+ end,+ schema.nodes.spoiler.createAndFill(+ null,+ schema.nodes.paragraph.createAndFill(null, textNode)+ )+ );+ } else {+ tr.replaceWith(+ start,+ end,+ schema.nodes.inline_spoiler.createAndFill(null, textNode)+ );+ }++ return tr.setSelection(+ TextSelection.create(tr.doc, start + 1, start + 1 + textNode.nodeSize)+ );+ },+ }),+ state: ({ utils, schema }, state) => ({+ inSpoiler: SPOILER_NODES.some((nodeType) =>+ utils.inNode(state, schema.nodes[nodeType])+ ),+ }),+ commands: ({ schema, utils, pmState: { TextSelection }, pmCommands }) => ({+ toggleSpoiler() {+ return (state, dispatch, view) => {+ const { selection } = state;+ const { empty, $from, $to } = selection;++ const inSpoiler = SPOILER_NODES.some((nodeType) =>+ utils.inNode(state, schema.nodes[nodeType])+ );++ if (inSpoiler) {+ // Find the nearest spoiler node and unwrap it by replacing with its contents+ for (let depth = $from.depth; depth > 0; depth--) {+ const node = $from.node(depth);+ if (SPOILER_NODES.includes(node.type.name)) {+ const spoilerStart = $from.before(depth);+ const spoilerEnd = spoilerStart + node.nodeSize;++ // Extract content and replace spoiler with it+ const tr = state.tr.replaceWith(+ spoilerStart,+ spoilerEnd,+ node.content+ );++ dispatch?.(tr);++ return true;+ }+ }++ return false;+ }++ // For empty selection, create spoiler with placeholder text+ if (empty) {+ const textNode = schema.text(i18n("composer.spoiler_text"));+ const isBlockSpoiler = view.endOfTextblock("backward");+ const spoilerNode = isBlockSpoiler+ ? schema.nodes.spoiler.createAndFill(+ null,+ schema.nodes.paragraph.createAndFill(null, textNode)+ )+ : schema.nodes.inline_spoiler.createAndFill(null, textNode);++ const tr = state.tr.replaceSelectionWith(spoilerNode);+ tr.setSelection(+ TextSelection.create(+ tr.doc,+ $from.pos + 1,+ $from.pos + 1 + textNode.nodeSize+ )+ );++ dispatch?.(tr);++ return true;+ }++ const isBlockNodeSelection =+ $from.parent === $to.parent &&+ $from.parentOffset === 0 &&+ $to.parentOffset === $from.parent.content.size &&+ $from.parent.isBlock &&+ $from.depth > 0;+ if (isBlockNodeSelection) {+ return pmCommands.wrapIn(schema.nodes.spoiler)(state, dispatch);+ }++ const slice = selection.content();+ const isInlineSelection = slice.openStart > 0 || slice.openEnd > 0;++ if (isInlineSelection) {+ const content = [];+ slice.content.forEach((node) =>+ node.isBlock+ ? node.content.forEach((child) => content.push(child))+ : content.push(node)+ );+ const spoilerNode = schema.nodes.inline_spoiler.createAndFill(+ null,+ content+ );++ const tr = state.tr.replaceWith($from.pos, $to.pos, spoilerNode);+ tr.setSelection(+ TextSelection.create(+ tr.doc,+ $from.pos + 1,+ $from.pos + 1 + spoilerNode.content.size+ )+ );++ dispatch?.(tr);++ return true;+ } else {+ return pmCommands.wrapIn(schema.nodes.spoiler)(state, (tr) => {+ tr.setSelection(+ TextSelection.create(tr.doc, $from.pos + 2, $to.pos)+ );++ dispatch?.(tr);+ });+ }+ };+ },+ }),plugins({ pmState: { Plugin }, pmView: { Decoration, DecorationSet } }) {return new Plugin({props: {decorations(state) {return this.getState(state);},- handleClickOn(view, pos, node, nodePos) {- if (SPOILER_NODES.includes(node.type.name)) {- const decoSet = this.getState(view.state) || DecorationSet.empty;-- const isBlurred =- decoSet.find(nodePos, nodePos + node.nodeSize).length > 0;-- const newDeco = isBlurred- ? decoSet.remove(decoSet.find(nodePos, nodePos + node.nodeSize))- : decoSet.add(view.state.doc, [- Decoration.node(nodePos, nodePos + node.nodeSize, {- class: "spoiler-blurred",- }),- ]);-- view.dispatch(view.state.tr.setMeta(this, newDeco));- return true;- }- },},state: {- init() {- return DecorationSet.empty;+ init(config, state) {+ // Initially blur all spoilers+ const decorations = [];++ state.doc.descendants((node, pos) => {+ if (SPOILER_NODES.includes(node.type.name)) {+ decorations.push(+ Decoration.node(pos, pos + node.nodeSize, {+ class: "spoiler-blurred",+ })+ );+ }+ return true;+ });++ return DecorationSet.create(state.doc, decorations);},- apply(tr, set) {- return tr.getMeta(this) || set.map(tr.mapping, tr.doc);+ apply(tr, set, oldState, newState) {+ // If there's a meta update, use it (for manual updates)+ if (tr.getMeta(this)) {+ return tr.getMeta(this);+ }++ // Map existing decorations through the transaction+ set = set.map(tr.mapping, tr.doc);++ // Only recalculate if selection changed (which includes document changes that affect selection)+ if (tr.selectionSet || tr.docChanged) {+ const decorations = [];+ const { selection } = newState;++ newState.doc.descendants((node, pos) => {+ if (SPOILER_NODES.includes(node.type.name)) {+ const nodeStart = pos;+ const nodeEnd = pos + node.nodeSize;++ const cursorInSpoiler =+ (selection.from > nodeStart && selection.from < nodeEnd) ||+ (selection.to > nodeStart && selection.to < nodeEnd) ||+ (selection.from <= nodeStart && selection.to >= nodeEnd);++ if (!cursorInSpoiler) {+ decorations.push(+ Decoration.node(nodeStart, nodeEnd, {+ class: "spoiler-blurred",+ })+ );+ }+ }+ return true;+ });++ return DecorationSet.create(newState.doc, decorations);+ }++ return set;},},});diff --git a/plugins/spoiler-alert/assets/stylesheets/discourse_spoiler_alert.scss b/plugins/spoiler-alert/assets/stylesheets/discourse_spoiler_alert.scssindex fd14f9ce258..db98c3aa7f4 100644--- a/plugins/spoiler-alert/assets/stylesheets/discourse_spoiler_alert.scss+++ b/plugins/spoiler-alert/assets/stylesheets/discourse_spoiler_alert.scss@@ -53,11 +53,12 @@}}-.ProseMirror {- .spoiled:not(.spoiler-blurred) {+.ProseMirror .spoiled {+ padding-inline: var(--space-1);++ &:not(.spoiler-blurred) {+ border-radius: var(--d-border-radius);box-shadow: 0 0 4px 4px rgb(var(--primary-rgb), 0.2);- inline-size: max-content;- padding-left: 2px;- padding-right: 2px;+ max-width: 100%;}}diff --git a/plugins/spoiler-alert/spec/system/composer_spoiler_spec.rb b/plugins/spoiler-alert/spec/system/composer_spoiler_spec.rbnew file mode 100644index 00000000000..3cbac69aace--- /dev/null+++ b/plugins/spoiler-alert/spec/system/composer_spoiler_spec.rb@@ -0,0 +1,254 @@+# frozen_string_literal: true++describe "Composer - ProseMirror editor - Spoiler extension", type: :system do+ fab!(:current_user) do+ Fabricate(+ :user,+ refresh_auto_groups: true,+ composition_mode: UserOption.composition_mode_types[:rich],+ )+ end++ let(:cdp) { PageObjects::CDP.new }+ let(:composer) { PageObjects::Components::Composer.new }+ let(:rich) { composer.rich_editor }++ def click_spoiler_button+ find(".toolbar-menu__options-trigger").click+ find("[title='#{I18n.t("js.spoiler.title")}']").click+ end++ before { sign_in(current_user) }++ def open_composer+ page.visit "/new-topic"+ expect(composer).to be_opened+ composer.focus+ end++ it "creates inline spoiler when cursor is at end of line" do+ open_composer++ composer.type_content("This is a test ")+ click_spoiler_button++ expect(rich).to have_css("span.spoiled", text: I18n.t("js.composer.spoiler_text"))++ composer.type_content("spoiler")++ expect(rich).to have_css("span.spoiled", text: "spoiler")++ composer.toggle_rich_editor++ expect(composer).to have_value("This is a test [spoiler]spoiler[/spoiler] ")+ end++ it "creates block spoiler when cursor is at start of line" do+ open_composer++ click_spoiler_button++ expect(rich).to have_css("div.spoiled", text: I18n.t("js.composer.spoiler_text"))++ composer.type_content("spoiler")+ composer.toggle_rich_editor++ expect(composer).to have_value("[spoiler]\nspoiler\n\n[/spoiler]\n\n")+ end++ it "creates block spoiler with input rule when cursor is at start of line" do+ open_composer+ composer.type_content("[spoiler]")+ composer.type_content("inside")+ composer.toggle_rich_editor++ expect(composer).to have_value("[spoiler]\ninside\n\n[/spoiler]\n\n")+ end++ it "wraps selected text in inline spoiler when selection is within same paragraph" do+ open_composer++ composer.type_content("This is **secret** text here")+ find("strong", text: "secret").double_click+ click_spoiler_button++ expect(rich).to have_css("span.spoiled strong", text: "secret")+ expect(rich).to have_content("This is secret text here")++ composer.toggle_rich_editor+ expect(composer).to have_value("This is [spoiler]**secret**[/spoiler] text here")+ end++ it "wraps selected text in block spoiler when selection spans multiple paragraphs" do+ open_composer++ composer.type_content("First paragraph")+ composer.send_keys(:enter)+ composer.type_content("Second paragraph")+ composer.select_all+ click_spoiler_button++ expect(rich).to have_css("div.spoiled p", text: "First paragraph")+ expect(rich).to have_css("div.spoiled p", text: "Second paragraph")++ composer.toggle_rich_editor+ expect(composer).to have_value(+ "[spoiler]\nFirst paragraph\n\nSecond paragraph\n\n[/spoiler]\n\n",+ )+ end++ it "removes inline spoiler when cursor is inside inline spoiler" do+ open_composer++ composer.type_content("This is a test")+ click_spoiler_button++ expect(rich).to have_css("span.spoiled", text: I18n.t("js.composer.spoiler_text"))++ composer.type_content("secret")+ composer.send_keys(:left, :left, :left)+ click_spoiler_button++ expect(rich).to have_no_css("span.spoiled")+ expect(rich).to have_content("This is a testsecret")+ end++ it "removes spoiler when cursor is inside block spoiler" do+ open_composer++ click_spoiler_button++ expect(rich).to have_css("div.spoiled")++ composer.type_content("secret content")++ click_spoiler_button++ expect(rich).to have_no_css("div.spoiled")+ expect(rich).to have_css("p", text: "secret content")+ end++ it "removes spoiler when text is selected within spoiler" do+ open_composer++ composer.type_content("Normal text")+ click_spoiler_button++ expect(rich).to have_css("span.spoiled", text: I18n.t("js.composer.spoiler_text"))++ composer.type_content("hidden text")++ expect(rich).to have_css("span.spoiled", text: "hidden text")++ click_spoiler_button++ expect(rich).to have_no_css("span.spoiled")+ expect(rich).to have_content("Normal texthidden text")+ end++ it "handles multi-blocks spoiler full lift" do+ open_composer+ click_spoiler_button++ expect(rich).to have_css("div.spoiled")++ composer.type_content("First paragraph\nSecond paragraph")+ composer.send_keys(:up)+ click_spoiler_button++ expect(rich).to have_no_css("div.spoiled")+ expect(rich).to have_css("p", text: "First paragraph")+ expect(rich).to have_css("p", text: "Second paragraph")++ composer.toggle_rich_editor+ expect(composer).to have_value("First paragraph\n\nSecond paragraph")+ end++ it "breaks out of inline spoiler when pressing Enter" do+ open_composer++ composer.type_content("Test ")++ expect(rich).to have_css("p", text: "Test")++ click_spoiler_button++ expect(rich).to have_css("span.spoiled", text: I18n.t("js.composer.spoiler_text"))++ composer.type_content("hello")+ composer.send_keys(:right)+ composer.type_content("X")++ expect(rich).to have_css("span.spoiled.spoiler-blurred", text: "hello")++ composer.send_keys(:left)+ composer.send_keys(:left)++ expect(rich).to have_css("span.spoiled:not(.spoiler-blurred)", text: "hello")++ # ENTER at the end of the node+ composer.send_keys(:enter)++ # Backspace, position cursor at hell|o, ENTER+ composer.send_keys(:backspace)+ composer.send_keys(:left)+ composer.send_keys(:left)+ sleep 0.01+ composer.send_keys(:enter)++ expect(rich).to have_css("p", text: "Test")+ expect(rich).to have_css("span.spoiled", text: "hell")+ expect(rich).to have_css("p:has(span.spoiled) + p", text: "o X")+ end++ it "keeps inline spoiler when pressing Enter at start of node" do+ open_composer++ composer.type_content(" ")+ click_spoiler_button++ expect(rich).to have_css("span.spoiled", text: I18n.t("js.composer.spoiler_text"))++ composer.type_content("hello")++ expect(rich).to have_css("span.spoiled", text: "hello")++ composer.send_keys(:control, :left)+ composer.send_keys(:backspace)+ sleep 0.01+ composer.send_keys(:enter)++ expect(rich).to have_css("p:not(:has(span.spoiled)) + p:has(span.spoiled)", text: "hello")+ end++ it "selects the resulting node after a select all and spoiler click" do+ open_composer++ composer.type_content("This is a test")+ composer.select_all+ click_spoiler_button++ expect(rich).to have_css("div.spoiled", text: "This is a test")++ composer.type_content("spoiled")++ composer.toggle_rich_editor+ expect(composer).to have_value("[spoiler]\nspoiled\n\n[/spoiler]\n\n")+ end++ it "can spoiler a block node selection" do+ open_composer++ composer.type_content("> Blockquote")++ find("blockquote").click(SystemHelpers::PLATFORM_KEY_MODIFIER)+ find("blockquote").click(SystemHelpers::PLATFORM_KEY_MODIFIER)++ click_spoiler_button++ expect(rich).to have_css("div.spoiled", text: "Blockquote")++ composer.toggle_rich_editor+ expect(composer).to have_value("[spoiler]\n> Blockquote\n\n[/spoiler]\n\n")+ end+enddiff --git a/plugins/spoiler-alert/test/javascripts/integration/rich-editor-extension-test.js b/plugins/spoiler-alert/test/javascripts/integration/rich-editor-extension-test.jsindex 03ca14ac5b7..804a74e5ad6 100644--- a/plugins/spoiler-alert/test/javascripts/integration/rich-editor-extension-test.js+++ b/plugins/spoiler-alert/test/javascripts/integration/rich-editor-extension-test.js@@ -23,14 +23,19 @@ module(Object.entries({"inline spoiler": ["Hey [spoiler]did you know the good guys die[/spoiler] in the end?",- '<p>Hey <span class="spoiled">did you know the good guys die</span> in the end?</p>',+ '<p>Hey <span class="spoiled spoiler-blurred">did you know the good guys die</span> in the end?</p>',"Hey [spoiler]did you know the good guys die[/spoiler] in the end?",],"block spoiler": ["hey\n\n[spoiler]\n> did you know the good guys die\n\n[/spoiler]\n\nin the end?",- '<p>hey</p><div class="spoiled"><blockquote><p>did you know the good guys die</p></blockquote></div><p>in the end?</p>',+ '<p>hey</p><div class="spoiled spoiler-blurred"><blockquote><p>did you know the good guys die</p></blockquote></div><p>in the end?</p>',"hey\n\n[spoiler]\n> did you know the good guys die\n\n[/spoiler]\n\nin the end?",],+ "inline spoiler with trailing space": [+ "[spoiler]the answer is 42[/spoiler] ",+ '<p><span class="spoiled spoiler-blurred">the answer is 42</span> </p>',+ "[spoiler]the answer is 42[/spoiler] ",+ ],}).forEach(([name, [markdown, html, expectedMarkdown]]) => {test(name, async function (assert) {await testMarkdown(assert, markdown, html, expectedMarkdown);diff --git a/spec/system/composer/prosemirror_editor_spec.rb b/spec/system/composer/prosemirror_editor_spec.rbindex 5ff2f24df1e..92bb0d9cffc 100644--- a/spec/system/composer/prosemirror_editor_spec.rb+++ b/spec/system/composer/prosemirror_editor_spec.rb@@ -821,7 +821,7 @@ describe "Composer - ProseMirror editor", type: :system docomposer.toggle_rich_editor- expect(composer).to have_value("<mark>mark</mark> my <ins>words</ins> <kbd>ctrl</kbd>")+ expect(composer).to have_value("<mark>mark</mark> my <ins>words</ins> <kbd>ctrl</kbd> ")endend