A platform for community discussion. Free, open, simple.
FEATURE: consolidate composer toolbar list and add check list (#37336)
Renato Atilio97bf16459269
diff --git a/app/assets/stylesheets/common/toolbar-popup-menu-options.scss b/app/assets/stylesheets/common/toolbar-popup-menu-options.scssindex 0ea31c18b2e..e0f1cba36ef 100644--- a/app/assets/stylesheets/common/toolbar-popup-menu-options.scss+++ b/app/assets/stylesheets/common/toolbar-popup-menu-options.scss@@ -30,7 +30,9 @@}}-.toolbar-menu__options-content {+.toolbar-menu__options-content,+.toolbar-menu__list-content,+.toolbar-menu__heading-content {.dropdown-menu {.btn {&.--active {@@ -58,16 +60,10 @@}}-.toolbar-menu__heading-content {+.toolbar-menu__heading-content,+.toolbar-menu__list-content {.dropdown-menu {.btn {- &.--active {- .d-button-label__active-icon {- visibility: visible;- margin-left: auto;- }- }-&:hover,&:focus,&:focus-visible {@@ -106,7 +102,11 @@font-size: var(--font-down-1-rem);}}+ }+}+.toolbar-menu__heading-content {+ .dropdown-menu {.btn[data-name="heading-1"] {.d-button-label__text,.d-icon[class*="d-icon-discourse"] {diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 94e83205b53..968dccf86fc 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -3153,6 +3153,7 @@ en:upload_description: "enter upload description here"olist_title: "Numbered list"ulist_title: "Bulleted list"+ list_title: "Lists"list_item: "List item"toggle_direction: "Toggle direction"apply_wrap_title: "Apply wrap"diff --git a/frontend/discourse/app/components/d-editor.gjs b/frontend/discourse/app/components/d-editor.gjsindex cc59f83a96b..2d5caba6201 100644--- a/frontend/discourse/app/components/d-editor.gjs+++ b/frontend/discourse/app/components/d-editor.gjs@@ -196,13 +196,13 @@ export default class DEditor extends Component {keymap[sc] = () => {const customAction = shortcuts[sc].shortcutAction;+ const toolbarEvent = this.newToolbarEvent();if (customAction) {- const toolbarEvent = this.newToolbarEvent();if (!button.condition || button.condition(toolbarEvent)) {customAction(toolbarEvent);}} else {- button.action(button);+ button.action(toolbarEvent);}return false;};diff --git a/frontend/discourse/app/components/toolbar-popup-menu-options.gjs b/frontend/discourse/app/components/toolbar-popup-menu-options.gjsindex 2256c3901da..94679072d6b 100644--- a/frontend/discourse/app/components/toolbar-popup-menu-options.gjs+++ b/frontend/discourse/app/components/toolbar-popup-menu-options.gjs@@ -33,7 +33,7 @@ export default class ToolbarPopupmenuOptions extends Component {}#convertMenuOption(content) {- if (content.condition) {+ if (content.condition !== false) {const label = this.#calculateLabel(content);const title = this.#calculateTitle(content);diff --git a/frontend/discourse/app/lib/composer/rich-editor-extensions.js b/frontend/discourse/app/lib/composer/rich-editor-extensions.jsindex 04150df20c9..dd471a92546 100644--- a/frontend/discourse/app/lib/composer/rich-editor-extensions.js+++ b/frontend/discourse/app/lib/composer/rich-editor-extensions.js@@ -32,6 +32,7 @@* @property {typeof import('prosemirror-history')} pmHistory* @property {typeof import('prosemirror-transform')} pmTransform* @property {typeof import('prosemirror-commands')} pmCommands+ * @property {typeof import('prosemirror-schema-list')} pmSchemaList* @property {import('prosemirror-model').Schema} schema* @property {() => PluginContext} getContext*/diff --git a/frontend/discourse/app/lib/composer/toolbar.js b/frontend/discourse/app/lib/composer/toolbar.jsindex 872ff25cf94..3853ffb96fd 100644--- a/frontend/discourse/app/lib/composer/toolbar.js+++ b/frontend/discourse/app/lib/composer/toolbar.js@@ -1,5 +1,5 @@// @ts-check-import { action } from "@ember/object";+import { customPopupMenuOptions } from "discourse/lib/composer/custom-popup-menu-options";import { translateModKey } from "discourse/lib/utilities";import { waitForClosedKeyboard } from "discourse/lib/wait-for-keyboard";import { PLATFORM_KEY_MODIFIER } from "discourse/services/keyboard-shortcuts";@@ -134,6 +134,10 @@ export class ToolbarBase {// Popup menu option item shortcut bindings and title text.if (buttonAttrs.popupMenu) {+ // Default action passes toolbarEvent to option.action+ buttonAttrs.popupMenu.action ??= (option) =>+ option.action(this.context.newToolbarEvent());+buttonAttrs.popupMenu.options()?.forEach((option) => {if (option.shortcut) {const shortcutKeyTranslated = translateModKey(@@ -181,6 +185,8 @@ export class ToolbarBase {* Standard editor toolbar with default buttons*/export default class Toolbar extends ToolbarBase {+ #listOptions;+constructor(opts) {super(opts);@@ -269,7 +275,8 @@ export default class Toolbar extends ToolbarBase {return false;},- action: this.onHeadingMenuAction.bind(this),+ action: (toolbarEvent) =>+ toolbarEvent.applyHeading(headingLevel, "heading"),});}headingOptions.push({@@ -281,11 +288,10 @@ export default class Toolbar extends ToolbarBase {showActiveIcon: true,shortcut: "Alt+0",active: ({ state }) => state?.inParagraph,- action: this.onHeadingMenuAction.bind(this),+ action: (toolbarEvent) => toolbarEvent.applyHeading(0, "heading"),});return headingOptions;},- action: this.onHeadingMenuAction.bind(this),},});@@ -325,28 +331,25 @@ export default class Toolbar extends ToolbarBase {active: ({ state }) => state.inCode || state.inCodeBlock,});- this.addButton({- id: "bullet",- group: "extras",- icon: "list-ul",- shortcut: "Shift+8",- title: "composer.ulist_title",- perform: (e) => e.applyList("* ", "list_item"),- active: ({ state }) => state.inBulletList,- });-this.addButton({id: "list",group: "extras",- icon: "list-ol",- shortcut: "Shift+7",- title: "composer.olist_title",- perform: (e) =>- e.applyList(- (i) => (!i ? "1. " : `${parseInt(i, 10) + 1}. `),- "list_item"- ),- active: ({ state }) => state.inOrderedList,+ active: ({ state }) => {+ return this.getListPopupMenuOptions().some((option) =>+ option.active({ state })+ );+ },+ icon: ({ state }) => {+ return (+ this.getListPopupMenuOptions().find((option) =>+ option.active({ state })+ )?.icon || "list-ul"+ );+ },+ title: "composer.list_title",+ popupMenu: {+ options: () => this.getListPopupMenuOptions(),+ },});}@@ -362,16 +365,46 @@ export default class Toolbar extends ToolbarBase {}}- @action- onHeadingMenuAction(menuItem) {- let level;-- if (menuItem.name === "heading-paragraph") {- level = 0;- } else {- level = parseInt(menuItem.name.split("-")[1], 10);- }+ getListPopupMenuOptions() {+ this.#listOptions ??= [+ {+ name: "list-bullet",+ icon: "list-ul",+ label: "composer.ulist_title",+ shortcut: "Shift+8",+ showActiveIcon: true,+ active: ({ state }) => state?.inBulletList,+ action: (toolbarEvent) => {+ if (+ !toolbarEvent.commands?.toggleBulletList ||+ !toolbarEvent.commands.toggleBulletList()+ ) {+ toolbarEvent.applyList("* ", "list_item");+ }+ },+ },+ {+ name: "list-ordered",+ icon: "list-ol",+ label: "composer.olist_title",+ shortcut: "Shift+7",+ showActiveIcon: true,+ active: ({ state }) => state?.inOrderedList,+ action: (toolbarEvent) => {+ if (+ !toolbarEvent.commands?.toggleOrderedList ||+ !toolbarEvent.commands.toggleOrderedList()+ ) {+ toolbarEvent.applyList(+ (i) => (!i ? "1. " : `${parseInt(i, 10) + 1}. `),+ "list_item"+ );+ }+ },+ },+ ...customPopupMenuOptions.filter((option) => option.menu === "list"),+ ];- this.context.newToolbarEvent().applyHeading(level, "heading");+ return this.#listOptions;}}diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjsindex 188055f9ae0..9e4506cc78a 100644--- a/frontend/discourse/app/lib/plugin-api.gjs+++ b/frontend/discourse/app/lib/plugin-api.gjs@@ -848,6 +848,8 @@ class _PluginApi {* @returns {boolean} - Whether the button should be displayed.** @param {Object} opts - An Object.+ * @param {string} [opts.menu] - Target menu: 'list' for list dropdown, omit for options popup (default).+ * @param {string} [opts.name] - Unique identifier for the option.* @param {string} opts.icon - The name of the FontAwesome icon to display for the button.* @param {string} opts.label - The I18n translation key for the button's label.* @param {string} opts.shortcut - The keyboard shortcut to apply, NOTE: this will unconditionally add CTRL/META key (eg: m means CTRL+m).@@ -866,6 +868,18 @@ class _PluginApi {* return composer.editingPost;* }* });+ *+ * @example+ * // Add option to list dropdown+ * api.addComposerToolbarPopupMenuOption({+ * menu: 'list',+ * name: 'my-custom-list',+ * icon: 'list-check',+ * label: 'my_plugin.custom_list',+ * action: (toolbarEvent) => {+ * toolbarEvent.applyList("- [x] ", "list_item");+ * }+ * });**/addComposerToolbarPopupMenuOption(opts) {addPopupMenuOption(opts);diff --git a/frontend/discourse/app/services/composer.js b/frontend/discourse/app/services/composer.jsindex bd563c676c2..65823de5521 100644--- a/frontend/discourse/app/services/composer.js+++ b/frontend/discourse/app/services/composer.js@@ -487,13 +487,14 @@ export default class ComposerService extends Service {}),];- return options- .concat(- customPopupMenuOptions- .map((option) => this._setupPopupMenuOption({ ...option }))- .filter((o) => o)- )- .concat(secondaryOptions);+ return [+ ...options,+ ...customPopupMenuOptions+ .filter((option) => !option.menu)+ .map((option) => this._setupPopupMenuOption({ ...option }))+ .filter(Boolean),+ ...secondaryOptions,+ ];}}@@ -725,12 +726,9 @@ export default class ComposerService extends Service {menuItem);if (typeof menuItem.action === "function") {- // note: due to the way args are passed to actions we need- // to create the explicity toolbarEvent as a fallback for no- // event- // Long term we want to avoid needing this awkwardness and pass- // the event explicitly- return menuItem.action(this.toolbarEvent || toolbarEvent);+ // toolbarEvent is passed when triggered via keyboard shortcut,+ // otherwise fall back to stored toolbarEvent from menu open+ return menuItem.action(toolbarEvent ?? this.toolbarEvent);} else {return (this.actions?.[menuItem.action]?.bind(this) || // Legacy-style contributions from themes/pluginsdiff --git a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjs b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjsindex c938cb0d77f..a5424d09785 100644--- a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjs+++ b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjs@@ -17,6 +17,7 @@ import * as ProsemirrorHistory from "prosemirror-history";import { history } from "prosemirror-history";import { keymap } from "prosemirror-keymap";import * as ProsemirrorModel from "prosemirror-model";+import * as ProsemirrorSchemaList from "prosemirror-schema-list";import * as ProsemirrorState from "prosemirror-state";import { EditorState } from "prosemirror-state";import * as ProsemirrorTransform from "prosemirror-transform";@@ -106,6 +107,7 @@ export default class ProsemirrorEditor extends Component {pmView: ProsemirrorView,pmHistory: ProsemirrorHistory,pmTransform: ProsemirrorTransform,+ pmSchemaList: ProsemirrorSchemaList,pmCommands: ProsemirrorCommands,getContext: () => ({placeholder: this.args.placeholder,diff --git a/frontend/discourse/app/static/prosemirror/lib/text-manipulation.js b/frontend/discourse/app/static/prosemirror/lib/text-manipulation.jsindex 4b94070275c..afed1b07813 100644--- a/frontend/discourse/app/static/prosemirror/lib/text-manipulation.js+++ b/frontend/discourse/app/static/prosemirror/lib/text-manipulation.js@@ -5,7 +5,11 @@ import { isEmpty } from "@ember/utils";import { TrackedObject } from "@ember-compat/tracked-built-ins";import { lift, setBlockType, toggleMark, wrapIn } from "prosemirror-commands";import { Slice } from "prosemirror-model";-import { liftListItem, sinkListItem } from "prosemirror-schema-list";+import {+ liftListItem,+ sinkListItem,+ wrapInList,+} from "prosemirror-schema-list";import { Selection, TextSelection } from "prosemirror-state";import { bind } from "discourse/lib/decorators";import escapeRegExp from "discourse/lib/escape-regexp";@@ -186,26 +190,63 @@ export default class ProsemirrorTextManipulation {applyList(_selection, head, exampleKey) {let command;- const isInside = (type) => {+ const findParentList = () => {const $from = this.view.state.selection.$from;for (let depth = $from.depth; depth > 0; depth--) {- const parent = $from.node(depth);- if (parent.type === type) {- return true;+ const node = $from.node(depth);+ if (+ node.type === this.schema.nodes.bullet_list ||+ node.type === this.schema.nodes.ordered_list+ ) {+ return {+ node,+ pos: $from.before(depth),+ type: node.type,+ };}}- return false;+ return null;};if (exampleKey === "list_item") {- const nodeType =+ const targetType =head === "* "? this.schema.nodes.bullet_list: this.schema.nodes.ordered_list;- command = isInside(this.schema.nodes.list_item) ? lift : wrapIn(nodeType);+ const parentList = findParentList();++ if (parentList) {+ if (parentList.type === targetType) {+ // Same list type - toggle off (lift)+ command = liftListItem(this.schema.nodes.list_item);+ } else {+ // Different list type - convert selection+ // We achieve this by lifting out of the current list, then wrapping in the new type+ command = (state, dispatch) => {+ if (dispatch) {+ const liftCmd = liftListItem(this.schema.nodes.list_item);+ let lifted = false;+ liftCmd(state, (tr) => {+ dispatch(tr);+ lifted = true;+ });++ if (lifted) {+ // If lift succeeded, now wrap in the new list type+ // We need to re-fetch state from view since dispatch updated it+ wrapInList(targetType)(this.view.state, dispatch);+ }+ }+ return true;+ };+ }+ } else {+ // Not in a list - wrap in the target type+ command = wrapInList(targetType);+ }} else if (exampleKey === "blockquote_text") {- command = isInside(this.schema.nodes.blockquote)+ command = inNode(this.view.state, this.schema.nodes.blockquote)? lift: wrapIn(this.schema.nodes.blockquote);} else {@@ -213,6 +254,7 @@ export default class ProsemirrorTextManipulation {}command?.(this.view.state, this.view.dispatch);+ this.focus();}applyHeading(_selection, level) {diff --git a/frontend/discourse/tests/integration/components/d-editor-test.gjs b/frontend/discourse/tests/integration/components/d-editor-test.gjsindex 03f8cabe239..f5280e79276 100644--- a/frontend/discourse/tests/integration/components/d-editor-test.gjs+++ b/frontend/discourse/tests/integration/components/d-editor-test.gjs@@ -567,12 +567,14 @@ third line`async function (assert, textarea) {const example = i18n("composer.list_item");- await click(`button.bullet`);+ await click(`button.list`);+ await click('.btn[data-name="list-bullet"]');assert.strictEqual(this.value, `hello world.\n\n* ${example}`);assert.strictEqual(textarea.selectionStart, 14);assert.strictEqual(textarea.selectionEnd, 16 + example.length);- await click(`button.bullet`);+ await click(`button.list`);+ await click('.btn[data-name="list-bullet"]');assert.strictEqual(this.value, `hello world.\n\n${example}`);});@@ -583,12 +585,14 @@ third line`textarea.selectionStart = 6;textarea.selectionEnd = 11;- await click(`button.bullet`);+ await click(`button.list`);+ await click('.btn[data-name="list-bullet"]');assert.strictEqual(this.value, `hello\n\n* world\n\n.`);assert.strictEqual(textarea.selectionStart, 7);assert.strictEqual(textarea.selectionEnd, 14);- await click(`button.bullet`);+ await click(`button.list`);+ await click('.btn[data-name="list-bullet"]');assert.strictEqual(this.value, `hello\n\nworld\n\n.`);assert.strictEqual(textarea.selectionStart, 7);assert.strictEqual(textarea.selectionEnd, 12);@@ -603,12 +607,14 @@ third line`textarea.selectionStart = 0;textarea.selectionEnd = 20;- await click(`button.bullet`);+ await click(`button.list`);+ await click('.btn[data-name="list-bullet"]');assert.strictEqual(this.value, "Hello\n\nWorld\n\nEvil");assert.strictEqual(textarea.selectionStart, 0);assert.strictEqual(textarea.selectionEnd, 18);- await click(`button.bullet`);+ await click(`button.list`);+ await click('.btn[data-name="list-bullet"]');assert.strictEqual(this.value, "* Hello\n\n* World\n\n* Evil");assert.strictEqual(textarea.selectionStart, 0);assert.strictEqual(textarea.selectionEnd, 24);@@ -621,11 +627,13 @@ third line`const example = i18n("composer.list_item");await click(`button.list`);+ await click('.btn[data-name="list-ordered"]');assert.strictEqual(this.value, `hello world.\n\n1. ${example}`);assert.strictEqual(textarea.selectionStart, 14);assert.strictEqual(textarea.selectionEnd, 17 + example.length);await click(`button.list`);+ await click('.btn[data-name="list-ordered"]');assert.strictEqual(this.value, `hello world.\n\n${example}`);assert.strictEqual(textarea.selectionStart, 14);assert.strictEqual(textarea.selectionEnd, 14 + example.length);@@ -639,11 +647,13 @@ third line`textarea.selectionEnd = 11;await click(`button.list`);+ await click('.btn[data-name="list-ordered"]');assert.strictEqual(this.value, `hello\n\n1. world\n\n.`);assert.strictEqual(textarea.selectionStart, 7);assert.strictEqual(textarea.selectionEnd, 15);await click(`button.list`);+ await click('.btn[data-name="list-ordered"]');assert.strictEqual(this.value, `hello\n\nworld\n\n.`);assert.strictEqual(textarea.selectionStart, 7);assert.strictEqual(textarea.selectionEnd, 12);@@ -659,11 +669,13 @@ third line`textarea.selectionEnd = 18;await click(`button.list`);+ await click('.btn[data-name="list-ordered"]');assert.strictEqual(this.value, "1. Hello\n\n2. World\n\n3. Evil");assert.strictEqual(textarea.selectionStart, 0);assert.strictEqual(textarea.selectionEnd, 27);await click(`button.list`);+ await click('.btn[data-name="list-ordered"]');assert.strictEqual(this.value, "Hello\n\nWorld\n\nEvil");assert.strictEqual(textarea.selectionStart, 0);assert.strictEqual(textarea.selectionEnd, 18);@@ -678,6 +690,7 @@ third line`textarea.selectionEnd = 8;await click("button.list");+ await click('.btn[data-name="list-ordered"]');assert.strictEqual(this.value, "1. existing");document.execCommand("undo");diff --git a/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js b/plugins/checklist/assets/javascripts/discourse/initializers/checklist.jsindex d65ee040d1e..a187c8b183f 100644--- a/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js+++ b/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js@@ -10,6 +10,22 @@ function initializePlugin(api) {if (siteSettings.checklist_enabled) {api.decorateCookedElement(checklistSyntax);api.registerRichEditorExtension(richEditorExtension);++ api.addComposerToolbarPopupMenuOption({+ menu: "list",+ name: "list-checklist",+ icon: "list-check",+ label: "checklist.composer.checklist",+ showActiveIcon: true,+ active: ({ state }) => state?.inCheckList,+ action: (toolbarEvent) => {+ if (toolbarEvent.commands?.toggleChecklist) {+ toolbarEvent.commands.toggleChecklist();+ } else {+ toolbarEvent.applyList("- [ ] ", "list_item");+ }+ },+ });}}diff --git a/plugins/checklist/assets/javascripts/lib/rich-editor-extension.js b/plugins/checklist/assets/javascripts/lib/rich-editor-extension.jsindex adb8a232007..f9366eedf5d 100644--- a/plugins/checklist/assets/javascripts/lib/rich-editor-extension.js+++ b/plugins/checklist/assets/javascripts/lib/rich-editor-extension.js@@ -1,8 +1,5 @@/** @type {RichEditorExtension} */const extension = {- // TODO(renato): make the checkbox clickable- // TODO(renato): auto-continue checkbox list on ENTER- // TODO(renato): apply .has-checkbox style to the <li> to avoid :hasnodeSpec: {check: {attrs: { checked: { default: false } },@@ -23,9 +20,7 @@ const extension = {parseDOM: [{tag: "span.chcklst-box",- getAttrs: (dom) => {- return { checked: hasCheckedClass(dom.className) };- },+ getAttrs: (dom) => ({ checked: hasCheckedClass(dom.className) }),},],},@@ -34,12 +29,16 @@ const extension = {inputRules: [{match: /(^|\s)\[(x? ?)]$/,- handler: (state, match, start, end) =>- state.tr.replaceWith(- start + match[1].length,- end,- state.schema.nodes.check.create({ checked: match[2] === "x" })- ),+ handler: (state, match, start, end) => {+ const checkNode = state.schema.nodes.check.create({+ checked: match[2] === "x",+ });+ const spaceNode = state.schema.text(" ");+ return state.tr.replaceWith(start + match[1].length, end, [+ checkNode,+ spaceNode,+ ]);+ },},],@@ -58,6 +57,515 @@ const extension = {state.write(node.attrs.checked ? "[x]" : "[ ]");},},++ plugins({+ pmState: { Plugin },+ pmView: { Decoration, DecorationSet },+ schema,+ utils: { changedDescendants },+ }) {+ const checkType = schema.nodes.check;+ const listItemType = schema.nodes.list_item;+ const bulletListType = schema.nodes.bullet_list;++ const startsWithCheck = (node) =>+ node?.isTextblock && node.firstChild?.type === checkType;++ const findBulletListContext = ($from) => {+ for (let depth = $from.depth; depth > 0; depth--) {+ if ($from.node(depth).type === listItemType) {+ if ($from.node(depth - 1)?.type === bulletListType) {+ return { bulletListDepth: depth - 1, listItemDepth: depth };+ }+ return null;+ }+ }+ return null;+ };++ const inBulletListItem = (doc, pos) =>+ findBulletListContext(doc.resolve(pos)) !== null;++ const ensureSpaceAfterChecks = (tr, oldState, newState) => {+ const positionsToInsert = [];++ changedDescendants(oldState.doc, newState.doc, (node, pos) => {+ if (!startsWithCheck(node) || !inBulletListItem(newState.doc, pos)) {+ return;+ }++ const secondChild = node.childCount > 1 ? node.child(1) : null;+ const hasSpaceAfter =+ secondChild?.isText && secondChild.text?.[0] === " ";++ if (!hasSpaceAfter) {+ positionsToInsert.push(pos + 1 + node.firstChild.nodeSize);+ }+ });++ for (let i = positionsToInsert.length - 1; i >= 0; i--) {+ tr.insert(positionsToInsert[i], schema.text(" "));+ }+ };++ const exitChecklist = (tr, ctx) => {+ const { bulletListDepth, listItemDepth } = ctx;+ const { selection } = tr;+ const { $from } = selection;+ const bulletList = $from.node(bulletListDepth);+ const listItemIndex = $from.index(bulletListDepth);+ const prevListItem = bulletList.child(listItemIndex - 1);+ const bulletListStart = $from.before(bulletListDepth);++ tr.delete($from.before(listItemDepth), $from.after(listItemDepth));++ let prevOffset = 1;+ for (let i = 0; i < listItemIndex - 1; i++) {+ prevOffset += bulletList.child(i).nodeSize;+ }+ const prevItemStart = tr.mapping.map(bulletListStart + prevOffset);+ tr.delete(prevItemStart, prevItemStart + prevListItem.nodeSize);++ const mappedListStart = tr.mapping.map(bulletListStart);+ const listAfter = tr.doc.nodeAt(mappedListStart);++ if (listAfter && listAfter.childCount > 0) {+ const listEnd = mappedListStart + listAfter.nodeSize;+ tr.insert(listEnd, schema.nodes.paragraph.create());+ tr.setSelection(+ selection.constructor.near(tr.doc.resolve(listEnd + 1))+ );+ } else {+ tr.replaceWith(+ mappedListStart,+ mappedListStart + (listAfter?.nodeSize || 0),+ schema.nodes.paragraph.create()+ );+ tr.setSelection(+ selection.constructor.near(tr.doc.resolve(mappedListStart + 1))+ );+ }+ return tr;+ };++ const handleChecklistContinuation = (tr, transactions) => {+ if (!transactions.some((t) => t.docChanged)) {+ return null;+ }++ const { selection } = tr;+ const { $from } = selection;++ if (!selection.empty) {+ return null;+ }++ const parent = $from.parent;+ if (!parent.isTextblock || parent.content.size !== 0) {+ return null;+ }++ const ctx = findBulletListContext($from);+ if (!ctx) {+ return null;+ }++ const bulletList = $from.node(ctx.bulletListDepth);+ const listItemIndex = $from.index(ctx.bulletListDepth);+ if (listItemIndex === 0) {+ return null;+ }++ const prevParagraph = bulletList.child(listItemIndex - 1).firstChild;+ if (!startsWithCheck(prevParagraph)) {+ return null;+ }++ if (prevParagraph.content.size > 2) {+ const checkNode = checkType.create({ checked: false });+ tr.insert($from.pos, [checkNode, schema.text(" ")]);+ tr.setSelection(+ selection.constructor.near(tr.doc.resolve($from.pos + 2))+ );+ return tr;+ }++ return exitChecklist(tr, ctx);+ };++ const adjustCursorPosition = (tr) => {+ const { doc, selection } = tr;+ const { $from } = selection;++ if (!selection.empty) {+ return null;+ }++ const parent = $from.parent;+ if (!startsWithCheck(parent) || !inBulletListItem(doc, $from.pos)) {+ return null;+ }++ const checkSize = parent.firstChild.nodeSize;+ const secondChild = parent.childCount > 1 ? parent.child(1) : null;+ const hasSpaceAfter =+ secondChild?.isText && secondChild.text?.[0] === " ";+ const minPos = hasSpaceAfter ? checkSize + 1 : checkSize;++ if ($from.parentOffset < minPos) {+ tr.setSelection(+ selection.constructor.near(doc.resolve($from.start() + minPos))+ );+ return tr;+ }++ return null;+ };++ return [+ new Plugin({+ props: {+ handleClickOn(view, pos, node, nodePos) {+ if (node.type.name === "check") {+ view.dispatch(+ view.state.tr.setNodeMarkup(nodePos, null, {+ checked: !node.attrs.checked,+ })+ );+ return true;+ }+ return false;+ },++ handleKeyDown(view, event) {+ if (event.key !== "Backspace" && event.key !== "ArrowLeft") {+ return false;+ }++ const { state, dispatch } = view;+ const { selection } = state;+ const { $from } = selection;++ // Only handle at position 2 (right after check+space) in a checklist+ if (+ !selection.empty ||+ $from.parentOffset !== 2 ||+ !startsWithCheck($from.parent) ||+ !inBulletListItem(state.doc, $from.pos)+ ) {+ return false;+ }++ if (event.key === "Backspace") {+ const ctx = findBulletListContext($from);++ const checkStart = $from.start();+ let tr = state.tr.delete(checkStart, checkStart + 2);++ if (ctx) {+ const listItemPos = tr.mapping.map(+ $from.before(ctx.listItemDepth)+ );+ const $listItem = tr.doc.resolve(listItemPos);++ if ($listItem.nodeBefore?.type === listItemType) {+ tr = tr.join(listItemPos, 2);+ }+ }++ dispatch(tr);+ return true;+ }++ const beforeTextblock = $from.before();+ if (beforeTextblock > 0) {+ dispatch(+ state.tr.setSelection(+ selection.constructor.near(+ state.doc.resolve(beforeTextblock),+ -1+ )+ )+ );+ return true;+ }++ return false;+ },+ },++ appendTransaction(transactions, oldState, newState) {+ const isFullReplace = transactions.some(+ (t) =>+ t.steps.length === 1 &&+ t.steps[0].from === 0 &&+ t.steps[0].to === oldState.doc.content.size+ );+ if (isFullReplace) {+ return null;+ }++ const tr = newState.tr;+ ensureSpaceAfterChecks(tr, oldState, newState);++ return (+ handleChecklistContinuation(tr, transactions) ??+ adjustCursorPosition(tr) ??+ (tr.docChanged ? tr : null)+ );+ },+ }),++ // Decoration plugin to add has-checkbox class to checklist items+ new Plugin({+ props: {+ decorations(state) {+ const decorations = [];++ state.doc.descendants((node, pos, parent) => {+ if (+ node.type === listItemType &&+ parent?.type === bulletListType &&+ startsWithCheck(node.firstChild)+ ) {+ decorations.push(+ Decoration.node(pos, pos + node.nodeSize, {+ class: "has-checkbox",+ })+ );+ }+ });++ return DecorationSet.create(state.doc, decorations);+ },+ },+ }),+ ];+ },++ commands: ({ schema, pmSchemaList }) => {+ const checkType = schema.nodes.check;+ const bulletListType = schema.nodes.bullet_list;+ const orderedListType = schema.nodes.ordered_list;+ const listItemType = schema.nodes.list_item;++ const listItemHasCheck = (listItem) => {+ const p = listItem.firstChild;+ return p?.isTextblock && p.firstChild?.type === checkType;+ };++ const findListContext = (state) => {+ const { $from, $to } = state.selection;+ for (let depth = $from.depth; depth > 0; depth--) {+ if ($from.node(depth).type === listItemType) {+ const list = $from.node(depth - 1);+ if (list?.type === bulletListType || list?.type === orderedListType) {+ return {+ listDepth: depth - 1,+ listItemDepth: depth,+ listType: list.type,+ list,+ listStart: $from.before(depth - 1),+ $from,+ $to,+ };+ }+ }+ }+ return null;+ };++ const forEachSelectedItem = (ctx, callback) => {+ const { list, listStart, $from, $to } = ctx;+ const collapsed = $from.pos === $to.pos;++ list.forEach((item, offset) => {+ const itemStart = listStart + 1 + offset;+ const itemEnd = itemStart + item.nodeSize;+ const inSelection = collapsed+ ? $from.pos >= itemStart && $from.pos <= itemEnd+ : !(itemEnd <= $from.pos || itemStart >= $to.pos);++ if (inSelection) {+ callback(item, itemStart);+ }+ });+ };++ const hasCheckInSelection = (ctx) => {+ if (!ctx || ctx.listType !== bulletListType) {+ return false;+ }+ let found = false;+ forEachSelectedItem(ctx, (item) => {+ if (listItemHasCheck(item)) {+ found = true;+ }+ });+ return found;+ };++ const removeChecksFromSelection = (state, ctx) => {+ const toDelete = [];+ forEachSelectedItem(ctx, (item, itemStart) => {+ if (listItemHasCheck(item)) {+ const textblock = item.firstChild;+ const checkSize = textblock.firstChild.nodeSize;+ const second = textblock.childCount > 1 ? textblock.child(1) : null;+ const hasSpace = second?.isText && second.text?.[0] === " ";+ toDelete.push({+ from: itemStart + 2,+ to: itemStart + 2 + checkSize + (hasSpace ? 1 : 0),+ });+ }+ });++ let tr = state.tr;+ for (let i = toDelete.length - 1; i >= 0; i--) {+ tr = tr.delete(toDelete[i].from, toDelete[i].to);+ }+ return tr;+ };++ const addChecksToSelection = (state, ctx) => {+ const toInsert = [];+ forEachSelectedItem(ctx, (item, itemStart) => {+ if (!listItemHasCheck(item) && item.firstChild?.isTextblock) {+ toInsert.push(itemStart + 2);+ }+ });++ let tr = state.tr;+ let offset = 0;+ for (const pos of toInsert) {+ const check = checkType.create({ checked: false });+ const space = schema.text(" ");+ tr = tr.insert(pos + offset, [check, space]);+ offset += check.nodeSize + space.nodeSize;+ }+ return tr;+ };++ return {+ toggleBulletList() {+ return (state, dispatch) => {+ const ctx = findListContext(state);+ if (hasCheckInSelection(ctx)) {+ if (dispatch) {+ dispatch(removeChecksFromSelection(state, ctx));+ }+ return true;+ }+ return false;+ };+ },++ toggleOrderedList() {+ return (state, dispatch, view) => {+ const ctx = findListContext(state);+ if (!hasCheckInSelection(ctx)) {+ return false;+ }++ if (!dispatch) {+ return true;+ }++ const liftListItem = pmSchemaList?.liftListItem;+ const wrapInList = pmSchemaList?.wrapInList;+ if (!liftListItem || !wrapInList) {+ return false;+ }++ dispatch(removeChecksFromSelection(state, ctx));+ if (view) {+ liftListItem(listItemType)(view.state, dispatch);+ wrapInList(orderedListType)(view.state, dispatch);+ }+ return true;+ };+ },++ toggleChecklist() {+ return (state, dispatch, view) => {+ const ctx = findListContext(state);+ const wrapInList = pmSchemaList?.wrapInList;+ const liftListItem = pmSchemaList?.liftListItem;++ if (hasCheckInSelection(ctx)) {+ if (!dispatch || !liftListItem) {+ return !!liftListItem;+ }+ dispatch(removeChecksFromSelection(state, ctx));+ if (view) {+ liftListItem(listItemType)(view.state, dispatch);+ }+ return true;+ }++ if (ctx?.listType === bulletListType) {+ if (dispatch) {+ dispatch(addChecksToSelection(state, ctx));+ }+ return true;+ }++ if (ctx?.listType === orderedListType) {+ if (!dispatch || !liftListItem || !wrapInList) {+ return !!(liftListItem && wrapInList);+ }+ liftListItem(listItemType)(state, dispatch);+ if (view) {+ wrapInList(bulletListType)(view.state, dispatch);+ const newCtx = findListContext(view.state);+ if (newCtx) {+ dispatch(addChecksToSelection(view.state, newCtx));+ }+ }+ return true;+ }++ if (!wrapInList) {+ return false;+ }+ if (!dispatch) {+ return wrapInList(bulletListType)(state, undefined);+ }++ wrapInList(bulletListType)(state, dispatch);+ if (view) {+ const newCtx = findListContext(view.state);+ if (newCtx) {+ dispatch(addChecksToSelection(view.state, newCtx));+ }+ }+ return true;+ };+ },+ };+ },++ state: ({ schema, utils: { inNode } }, viewState) => {+ const { $from } = viewState.selection;+ let inCheckList = false;++ for (let depth = $from.depth; depth > 0; depth--) {+ const node = $from.node(depth);+ if (node.type === schema.nodes.list_item) {+ if ($from.node(depth - 1)?.type === schema.nodes.bullet_list) {+ const p = node.firstChild;+ inCheckList =+ p?.isTextblock && p.firstChild?.type === schema.nodes.check;+ }+ break;+ }+ }++ return {+ inCheckList,+ inBulletList: !inCheckList && inNode(viewState, schema.nodes.bullet_list),+ };+ },};const CHECKED_REGEX = /\bchecked\b/;diff --git a/plugins/checklist/assets/stylesheets/checklist.scss b/plugins/checklist/assets/stylesheets/checklist.scssindex 238a9e0e66a..a1519e93416 100644--- a/plugins/checklist/assets/stylesheets/checklist.scss+++ b/plugins/checklist/assets/stylesheets/checklist.scss@@ -83,8 +83,7 @@ ul li.has-checkbox {}.ProseMirror {- // TODO(renato): this is temporary, we should use `has-checkbox` instead- li:has(p:first-of-type > span.chcklst-box) {+ ul > li.has-checkbox {list-style-type: none;.chcklst-box:first-of-type {diff --git a/plugins/checklist/config/locales/client.en.yml b/plugins/checklist/config/locales/client.en.ymlnew file mode 100644index 00000000000..4c5f683d2d1--- /dev/null+++ b/plugins/checklist/config/locales/client.en.yml@@ -0,0 +1,5 @@+en:+ js:+ checklist:+ composer:+ checklist: "Check list"diff --git a/plugins/checklist/spec/system/page_objects/components/rich_checklist.rb b/plugins/checklist/spec/system/page_objects/components/rich_checklist.rbnew file mode 100644index 00000000000..88c0f82e2aa--- /dev/null+++ b/plugins/checklist/spec/system/page_objects/components/rich_checklist.rb@@ -0,0 +1,40 @@+# frozen_string_literal: true++module PageObjects+ module Components+ class RichChecklist < PageObjects::Components::Base+ CHECKBOX_SELECTOR = ".chcklst-box"+ UNCHECKED_SELECTOR = "#{CHECKBOX_SELECTOR}.fa.fa-square-o"+ CHECKED_SELECTOR = "#{CHECKBOX_SELECTOR}.checked.fa.fa-square-check-o"++ def initialize(rich_editor)+ @rich_editor = rich_editor+ end++ def click_checkbox(index = 0)+ @rich_editor.find_all(CHECKBOX_SELECTOR)[index].click+ self+ end++ def has_checkboxes?(count:)+ @rich_editor.has_css?(CHECKBOX_SELECTOR, count: count)+ end++ def has_no_checkboxes?+ @rich_editor.has_no_css?(CHECKBOX_SELECTOR)+ end++ def has_checked?(count: 1)+ @rich_editor.has_css?(CHECKED_SELECTOR, count: count)+ end++ def has_unchecked?(count: 1)+ @rich_editor.has_css?(UNCHECKED_SELECTOR, count: count)+ end++ def has_items?(count:)+ @rich_editor.has_css?("ul li", count: count)+ end+ end+ end+enddiff --git a/plugins/checklist/spec/system/rich_editor_extension_spec.rb b/plugins/checklist/spec/system/rich_editor_extension_spec.rbnew file mode 100644index 00000000000..2b5f4171e24--- /dev/null+++ b/plugins/checklist/spec/system/rich_editor_extension_spec.rb@@ -0,0 +1,141 @@+# frozen_string_literal: true++describe "Composer - ProseMirror editor - Checklist extension", type: :system do+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }+ let(:composer) { PageObjects::Components::Composer.new }+ let(:rich) { composer.rich_editor }+ let(:checklist) { PageObjects::Components::RichChecklist.new(rich) }++ before do+ sign_in(user)+ SiteSetting.rich_editor = true+ end++ def open_composer_and_toggle_rich_editor+ page.visit "/new-topic"+ expect(composer).to be_opened+ composer.toggle_rich_editor+ end++ def click_checklist_toolbar_option+ find(".toolbar__button.list").click+ find("button[data-name='list-checklist']").click+ end++ describe "checklist functionality" do+ it "toggles checked state when clicking checkbox" do+ open_composer_and_toggle_rich_editor+ rich.click++ rich.send_keys("[ ] Item 1")+ expect(checklist).to have_unchecked(count: 1)++ checklist.click_checkbox+ expect(checklist).to have_checked(count: 1)+ end++ it "shows checklist option in toolbar" do+ open_composer_and_toggle_rich_editor+ rich.click++ find(".toolbar__button.list").click++ expect(page).to have_css("button[data-name='list-checklist']")+ end+ end++ describe "checklist structure" do+ it "creates proper list structure with toolbar" do+ open_composer_and_toggle_rich_editor+ rich.click++ click_checklist_toolbar_option+ rich.send_keys("First item")++ expect(checklist).to have_items(count: 1)+ expect(checklist).to have_checkboxes(count: 1)+ end++ it "continues checklist on Enter" do+ open_composer_and_toggle_rich_editor+ rich.click++ click_checklist_toolbar_option+ rich.send_keys("First item")+ rich.send_keys(:enter)++ expect(checklist).to have_items(count: 2)+ expect(checklist).to have_checkboxes(count: 2)+ end++ it "allows double-Enter to escape checklist" do+ open_composer_and_toggle_rich_editor+ rich.click++ click_checklist_toolbar_option+ rich.send_keys("First item")+ rich.send_keys(:enter)++ expect(checklist).to have_checkboxes(count: 2)++ rich.send_keys(:enter)++ expect(checklist).to have_checkboxes(count: 1)+ expect(checklist).to have_items(count: 1)+ end+ end++ describe "backspace behavior" do+ it "joins with previous item when backspacing at start of checklist item with content" do+ open_composer_and_toggle_rich_editor+ rich.click++ click_checklist_toolbar_option+ rich.send_keys("First item")+ rich.send_keys(:enter)+ rich.send_keys("Second item")++ expect(checklist).to have_checkboxes(count: 2)+ expect(checklist).to have_items(count: 2)++ rich.send_keys(:home)+ rich.send_keys(:backspace)++ expect(checklist).to have_checkboxes(count: 1)+ expect(rich).to have_text("First itemSecond item")+ end++ it "joins with previous item when backspacing on empty checklist item" do+ open_composer_and_toggle_rich_editor+ rich.click++ click_checklist_toolbar_option+ rich.send_keys("First item")+ rich.send_keys(:enter)++ expect(checklist).to have_checkboxes(count: 2)++ rich.send_keys(:backspace)++ expect(checklist).to have_checkboxes(count: 1)+ expect(rich).to have_text("First item")+ end++ it "removes checkbox when backspacing on first/only checklist item" do+ open_composer_and_toggle_rich_editor+ rich.click++ click_checklist_toolbar_option+ rich.send_keys("Only item")++ expect(checklist).to have_checkboxes(count: 1)+ expect(checklist).to have_items(count: 1)++ rich.send_keys(:home)+ rich.send_keys(:backspace)++ expect(checklist).to have_no_checkboxes+ expect(rich).to have_text("Only item")+ end+ end+enddiff --git a/plugins/checklist/test/javascripts/integration/rich-editor-extension-test.js b/plugins/checklist/test/javascripts/integration/rich-editor-extension-test.jsindex 505316932fd..d2c95174f6c 100644--- a/plugins/checklist/test/javascripts/integration/rich-editor-extension-test.js+++ b/plugins/checklist/test/javascripts/integration/rich-editor-extension-test.js@@ -43,7 +43,7 @@ module(],"handles checkboxes in lists": ["* [ ] unchecked list item\n* [x] checked list item",- `<ul data-tight="true"><li><p>${unchecked} unchecked list item</p></li><li><p>${checked} checked list item</p></li></ul>`,+ `<ul data-tight="true"><li class="has-checkbox"><p>${unchecked} unchecked list item</p></li><li class="has-checkbox"><p>${checked} checked list item</p></li></ul>`,"* [ ] unchecked list item\n* [x] checked list item",],"handles checkboxes with formatting": [@@ -51,21 +51,26 @@ module(`<p>${unchecked} <em>italics</em> and ${checked} <strong>bold</strong></p>`,"[ ] *italics* and [x] **bold**",],- "does not render escaped opening bracket as checkbox": [+ "does not render escaped checkbox": ["\\[x] not a checkbox","<p>[x] not a checkbox</p>","\\[x\\] not a checkbox",],- "does not render escaped closing bracket as checkbox": [- "[x\\] not a checkbox",- "<p>[x] not a checkbox</p>",- "\\[x\\] not a checkbox",- ],"handles escaped checkbox followed by real checkbox": ["\\[x] escaped [x] real",`<p>[x] escaped ${checked} real</p>`,"\\[x\\] escaped [x] real",],+ "preserves checkbox state in ordered lists": [+ "1. [ ] unchecked\n2. [x] checked",+ `<ol data-tight="true"><li><p>${unchecked} unchecked</p></li><li><p>${checked} checked</p></li></ol>`,+ "1. [ ] unchecked\n2. [x] checked",+ ],+ "handles nested list with checkboxes": [+ "* [ ] parent\n * [x] child",+ `<ul data-tight="true"><li class="has-checkbox"><p>${unchecked} parent</p><ul data-tight="true"><li class="has-checkbox"><p>${checked} child</p></li></ul></li></ul>`,+ "* [ ] parent\n * [x] child",+ ],}).forEach(([name, [markdown, html, expectedMarkdown]]) => {test(name, async function (assert) {await testMarkdown(assert, markdown, html, expectedMarkdown);diff --git a/spec/system/composer/prosemirror_toolbar_spec.rb b/spec/system/composer/prosemirror_toolbar_spec.rbindex 28c8c9863d0..adc67add78f 100644--- a/spec/system/composer/prosemirror_toolbar_spec.rb+++ b/spec/system/composer/prosemirror_toolbar_spec.rb@@ -11,7 +11,6 @@ describe "Composer - ProseMirror - Toolbar", type: :system doexpect(page).to have_css(".toolbar__button.italic.--active", count: 0)expect(page).to have_css(".toolbar__button.heading.--active", count: 0)expect(page).to have_css(".toolbar__button.link.--active", count: 0)- expect(page).to have_css(".toolbar__button.bullet.--active", count: 0)expect(page).to have_css(".toolbar__button.list.--active", count: 0)expect(page).to have_css(".toolbar__button.code.--active", count: 0)expect(page).to have_css(".toolbar__button.blockquote.--active", count: 0)@@ -22,16 +21,9 @@ describe "Composer - ProseMirror - Toolbar", type: :system doexpect(page).to have_css(".toolbar__button.bold.--active", count: 1)expect(page).to have_css(".toolbar__button.italic.--active", count: 1)expect(page).to have_css(".toolbar__button.link.--active", count: 1)- expect(page).to have_css(".toolbar__button.bullet.--active", count: 1)- expect(page).to have_css(".toolbar__button.list.--active", count: 0)+ expect(page).to have_css(".toolbar__button.list.--active", count: 1)expect(page).to have_css(".toolbar__button.code.--active", count: 1)expect(page).to have_css(".toolbar__button.blockquote.--active", count: 1)-- page.find(".toolbar__button.bullet").click- page.find(".toolbar__button.list").click-- expect(page).to have_css(".toolbar__button.list.--active", count: 1)- expect(page).to have_css(".toolbar__button.bullet.--active", count: 0)endend