A platform for community discussion. Free, open, simple.
DEV: Tighten composer and rich editor types for strict mode (#44399)
Sérgio Saquetima53e039015f6
diff --git a/frontend/discourse/app/lib/composer/toolbar.ts b/frontend/discourse/app/lib/composer/toolbar.tsindex 8ff03e9ddcc..37a326cb01b 100644--- a/frontend/discourse/app/lib/composer/toolbar.ts+++ b/frontend/discourse/app/lib/composer/toolbar.ts@@ -1,3 +1,4 @@+import { assert } from "@ember/debug";import { customPopupMenuOptions } from "discourse/lib/composer/custom-popup-menu-options";import { waitForClosedKeyboard } from "discourse/lib/wait-for-keyboard";import type Site from "discourse/models/site";@@ -258,6 +259,7 @@ export class ToolbarBase {createdButton.className ||= buttonAttrs.id;createdButton.condition ||= () => true;createdButton.hiddenByUser =+ buttonAttrs.id !== undefined &&HIDEABLE_BUTTON_IDS.has(buttonAttrs.id) &&this.hiddenButtons.includes(buttonAttrs.id);@@ -272,7 +274,9 @@ export class ToolbarBase {const actionFn =buttonAttrs.action ?? buttonAttrs.sendAction ?? buttonAttrs.perform;- actionFn?.(toolbarEvent);+ // Undefined only on a toolbar without a context, such as the rich editor's+ // floating toolbars, whose actions take no arguments.+ actionFn?.(toolbarEvent as ToolbarEvent);// appEvents is only available on the main toolbar// only custom plugins listen to this event@@ -303,8 +307,13 @@ 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) =>+ buttonAttrs.popupMenu.action ??= (option) => {+ assert(+ "A popup menu needs a toolbar with a context",+ this.context.newToolbarEvent+ );option.action(this.context.newToolbarEvent());+ };buttonAttrs.popupMenu.options()?.forEach((option) => {if (option.shortcut) {@@ -351,6 +360,10 @@ export class ToolbarBase {* Standard editor toolbar with default buttons*/export default class Toolbar extends ToolbarBase {+ /** Always complete: the editor that creates this toolbar installs itself as the context. */+ declare context: ToolbarContext &+ Required<Pick<ToolbarContext, "newToolbarEvent" | "send">>;+#listOptions?: PopupMenuOption[];constructor(opts: ToolbarOptions) {@@ -400,7 +413,10 @@ export default class Toolbar extends ToolbarBase {return true;}- if (!state.inHeading || state.inHeadingLevel > 4) {+ if (+ !state.inHeading ||+ (state.inHeadingLevel !== undefined && state.inHeadingLevel > 4)+ ) {return false;}@@ -411,7 +427,7 @@ export default class Toolbar extends ToolbarBase {return "discourse-text";}- if (state.inHeadingLevel > 4) {+ if (state.inHeadingLevel !== undefined && state.inHeadingLevel > 4) {return "discourse-text";}@@ -420,7 +436,7 @@ export default class Toolbar extends ToolbarBase {title: "composer.text_size_title",popupMenu: {options: () => {- const headingOptions = [];+ const headingOptions: PopupMenuOption[] = [];for (let headingLevel = 1; headingLevel <= 4; headingLevel++) {headingOptions.push({name: `heading-${headingLevel}`,diff --git a/frontend/discourse/app/lib/textarea-text-manipulation.ts b/frontend/discourse/app/lib/textarea-text-manipulation.tsindex 91f3f296412..c7e829efc6f 100644--- a/frontend/discourse/app/lib/textarea-text-manipulation.ts+++ b/frontend/discourse/app/lib/textarea-text-manipulation.ts@@ -1,3 +1,4 @@+import { assert } from "@ember/debug";import { destroy } from "@ember/destroyable";import { type default as Owner, getOwner, setOwner } from "@ember/owner";import { trackedObject } from "@ember/reactive/collections";@@ -162,6 +163,18 @@ export default class TextareaTextManipulation implements TextManipulation {this.addText(this.getSelected(), text, options);}+ /** Returns the current selection, including its line's text. */+ getSelected(+ trimLeading: boolean | null | "" | undefined,+ opts: SelectionOptions & { lineVal: true }+ ): SelectedText & { lineVal: string };++ /** Returns the current selection. */+ getSelected(+ trimLeading?: boolean | null | "",+ opts?: SelectionOptions+ ): SelectedText;+getSelected(trimLeading?: boolean | null | "",opts?: SelectionOptions@@ -493,7 +506,9 @@ export default class TextareaTextManipulation implements TextManipulation {!selectedValue.match(/\[\/?[a-z =]+?\]/g)) {if (this._cachedLinkify.test(plainText)) {- const match = this._cachedLinkify.match(plainText)[0];+ const matches = this._cachedLinkify.match(plainText);+ assert("linkify matched text it just tested positive", matches);+ const match = matches[0];if (match &&match.index === 0 &&@@ -729,7 +744,7 @@ export default class TextareaTextManipulation implements TextManipulation {const selected = this.getSelected();const captures = selected.pre.match(/\B:([\p{L}\p{N}_]*)$/u);- if (isEmpty(captures)) {+ if (!captures) {if (selected.pre.match(/\S$/)) {this.addText(selected, ` :${code}:`);} else {@@ -1001,7 +1016,7 @@ export default class TextareaTextManipulation implements TextManipulation {}const modifier = dAutocomplete.setupAutocomplete(- getOwner(this),+ getOwner(this)!,this.textarea,this.autocompleteHandler,optionsdiff --git a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gtsindex 278ba754b9d..252cbb5fe5b 100644--- a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts+++ b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts@@ -1,4 +1,5 @@import Component from "@glimmer/component";+import { assert } from "@ember/debug";import { action } from "@ember/object";import { getOwner } from "@ember/owner";import { trackedArray } from "@ember/reactive/collections";@@ -119,7 +120,7 @@ type NodeViewComponent = ComponentLike<{dom: HTMLElement;contentDOM?: HTMLElement;pluginParams: PluginParams;- options: Record<string, unknown>;+ options?: Record<string, unknown>;onSetup: (instance: unknown) => void;};}>;@@ -153,7 +154,7 @@ export default class ProsemirrorEditor extends Component<ProsemirrorEditorSignat@service declare currentUser: User;schema: Schema = createSchema(this.extensions, this.args.includeDefault);- view: EditorView;+ declare view: EditorView;declare parser: Parser;declare serializer: Serializer;declare textManipulation: TextManipulation;@@ -311,8 +312,10 @@ export default class ProsemirrorEditor extends Component<ProsemirrorEditorSignatpaste: (view, event) => {// When !authorizesOneOrMoreExtensions, we don't ComposerUpload#setup,// which is originally responsible for preventDefault.+ const { clipboardData } = event;+ assert("A paste event carries clipboard data", clipboardData);if (- event.clipboardData.files.length > 0 &&+ clipboardData.files.length > 0 &&!authorizesOneOrMoreExtensions(this.currentUser.staff,this.siteSettings@@ -330,9 +333,9 @@ export default class ProsemirrorEditor extends Component<ProsemirrorEditorSignatreturn;}- if (- [...event.dataTransfer.items].some((item) => item.kind === "file")- ) {+ const { dataTransfer } = event;+ assert("A drop event carries a data transfer", dataTransfer);+ if ([...dataTransfer.items].some((item) => item.kind === "file")) {// Skip processing the drop event (e.g. Safari cross-window content drag),// Uppy's DropTarget should handle that instead.return true;@@ -348,7 +351,7 @@ export default class ProsemirrorEditor extends Component<ProsemirrorEditorSignat},});- this.textManipulation = new TextManipulation(getOwner(this), {+ this.textManipulation = new TextManipulation(getOwner(this)!, {schema: this.schema,view: this.view,convertFromMarkdown: this.convertFromMarkdown,diff --git a/frontend/discourse/app/static/prosemirror/extensions/link.ts b/frontend/discourse/app/static/prosemirror/extensions/link.tsindex 7ed0636b921..9c4a816bdd4 100644--- a/frontend/discourse/app/static/prosemirror/extensions/link.ts+++ b/frontend/discourse/app/static/prosemirror/extensions/link.ts@@ -1,10 +1,20 @@+import type { Node, ResolvedPos, Slice } from "prosemirror-model";import { ReplaceAroundStep, ReplaceStep } from "prosemirror-transform";-import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";+import type { EditorProps, EditorView } from "prosemirror-view";+import type {+ PluginParams,+ RichEditorExtension,+} from "discourse/lib/composer/rich-editor-extensions";import {getChangedRanges,markInputRule,} from "discourse/static/prosemirror/lib/plugin-utils";+/** ProseMirror's `isText`, narrowing `text` to the string every text node has. */+function isTextNode(node: Node): node is Node & { text: string } {+ return node.isText;+}+const extension: RichEditorExtension = {markSpec: {link: {@@ -143,17 +153,27 @@ const extension: RichEditorExtension = {}),],- plugins: ({ pmState: { Plugin }, utils }) =>- new Plugin({- props: {- // Auto-linkify plain-text pasted URLs over a selection- clipboardTextParser(text, $context, plain, view) {- if (view.state.selection.empty || !utils.getLinkify().test(text)) {- return;- }+ plugins: ({ pmState: { Plugin }, utils }) => {+ // Auto-linkify plain-text pasted URLs over a selection+ function parseClipboardText(+ text: string,+ $context: ResolvedPos,+ plain: boolean,+ view: EditorView+ ): Slice | undefined {+ if (view.state.selection.empty || !utils.getLinkify().test(text)) {+ return;+ }- return addLinkMark(view, text, utils);- },+ return addLinkMark(view, text, utils);+ }++ return new Plugin({+ props: {+ // prosemirror-view keeps the first truthy result and otherwise uses its+ // default parser, but types this hook as always returning a Slice.+ clipboardTextParser:+ parseClipboardText as EditorProps["clipboardTextParser"],// Auto-linkify pasted rich content with a single text node that is a URL over a selectiontransformPasted(slice, view) {if (view.state.selection.empty) {@@ -163,14 +183,15 @@ const extension: RichEditorExtension = {let node = null;if (slice.content.childCount === 1) {- if (slice.content.firstChild.isText) {- node = slice.content.firstChild;+ const only = slice.content.child(0);+ if (only.isText) {+ node = only;} else if (- slice.content.firstChild.type.name === "paragraph" &&- slice.content.firstChild.childCount === 1 &&- slice.content.firstChild.firstChild.isText+ only.type.name === "paragraph" &&+ only.childCount === 1 &&+ only.child(0).isText) {- node = slice.content.firstChild.firstChild;+ node = only.child(0);}}@@ -222,7 +243,7 @@ const extension: RichEditorExtension = {state.doc.nodesBetween(from, to, (node, pos) => {if (visited.has(node) ||- !node.isText ||+ !isTextNode(node) ||node.marks.some((mark) =>(mark.type.name === "link" &&@@ -257,7 +278,8 @@ const extension: RichEditorExtension = {if (wordStart === 0 &&- nodeBefore?.isText &&+ nodeBefore &&+ isTextNode(nodeBefore) &&!utils.isWhiteSpace(nodeBefore.text[nodeBefore.text.length - 1]) &&@@ -274,7 +296,8 @@ const extension: RichEditorExtension = {let textAfter = "";if (wordEnd === text.length &&- nodeAfter?.isText &&+ nodeAfter &&+ isTextNode(nodeAfter) &&!utils.isWhiteSpace(text[text.length - 1]) &&!utils.isWhiteSpace(nodeAfter.text[0]) &&nodeAfter.marks.length === 1 &&@@ -324,10 +347,15 @@ const extension: RichEditorExtension = {return tr;},- }),+ });+ },};-function addLinkMark(view, text, utils) {+function addLinkMark(+ view: EditorView,+ text: string,+ utils: PluginParams["utils"]+): Slice | undefined {const matches = utils.getLinkify().match(text);const isFullMatch = matches?.length === 1 && matches[0].raw === text;diff --git a/frontend/discourse/app/static/prosemirror/extensions/override-drag-ghost.ts b/frontend/discourse/app/static/prosemirror/extensions/override-drag-ghost.tsindex 65a7b6f50b8..0b9289fbe4a 100644--- a/frontend/discourse/app/static/prosemirror/extensions/override-drag-ghost.ts+++ b/frontend/discourse/app/static/prosemirror/extensions/override-drag-ghost.ts@@ -1,3 +1,4 @@+import { assert } from "@ember/debug";import { Fragment, Slice } from "prosemirror-model";import { NodeSelection, Plugin } from "prosemirror-state";import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";@@ -27,7 +28,7 @@ const dropSelectionPlugin = new Plugin({selection instanceof NodeSelection &&selection.node.type.name === "paragraph" &&selection.node.childCount === 1 &&- selection.node.firstChild.type.name === "image"+ selection.node.child(0).type.name === "image") {// Select the image inside the paragraph insteadconst imagePos = selection.from + 1; // paragraph boundary + image position@@ -54,6 +55,7 @@ const extension: RichEditorExtension = {}const dragging = view.dragging.slice.content.firstChild;+ assert("A dragged slice has content", dragging);if (dragging.type.name === "image") {const wrappedNode = view.state.schema.nodes.paragraph.create(null,@@ -64,7 +66,9 @@ const extension: RichEditorExtension = {return false;},dragstart(view, event) {- event.dataTransfer.setDragImage(EMPTY_DRAG_IMG, 0, 0);+ const { dataTransfer } = event;+ assert("A dragstart event carries a data transfer", dataTransfer);+ dataTransfer.setDragImage(EMPTY_DRAG_IMG, 0, 0);return false;},},diff --git a/frontend/discourse/app/static/prosemirror/extensions/placeholder.ts b/frontend/discourse/app/static/prosemirror/extensions/placeholder.tsindex c56adce8044..e1fad417f42 100644--- a/frontend/discourse/app/static/prosemirror/extensions/placeholder.ts+++ b/frontend/discourse/app/static/prosemirror/extensions/placeholder.ts@@ -10,7 +10,7 @@ const extension: RichEditorExtension = {pmView: { Decoration, DecorationSet },getContext,}) {- let placeholder;+ let placeholder: string | undefined;return new Plugin({key: new PluginKey("placeholder"),diff --git a/frontend/discourse/app/static/prosemirror/extensions/trailing-inline-space.ts b/frontend/discourse/app/static/prosemirror/extensions/trailing-inline-space.tsindex 83a6f316b91..0b82632f949 100644--- a/frontend/discourse/app/static/prosemirror/extensions/trailing-inline-space.ts+++ b/frontend/discourse/app/static/prosemirror/extensions/trailing-inline-space.ts@@ -4,7 +4,7 @@ import { TextSelection } from "prosemirror-state";import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";function isInlineContainer(node: Node): boolean {- return (+ return Boolean(node.isInline &&!node.isText &&node.type?.spec?.content &&diff --git a/frontend/discourse/app/static/prosemirror/lib/plugin-utils.js b/frontend/discourse/app/static/prosemirror/lib/plugin-utils.jsindex f6e188e7194..60c3419dc5e 100644--- a/frontend/discourse/app/static/prosemirror/lib/plugin-utils.js+++ b/frontend/discourse/app/static/prosemirror/lib/plugin-utils.js@@ -17,7 +17,7 @@ export { buildBBCodeAttrs } from "discourse/lib/text";** @param {RegExp} regexp* @param {import("prosemirror-model").MarkType} markType- * @param {Function} [getAttrs]+ * @param {Record<string, unknown> | ((match: RegExpMatchArray) => Record<string, unknown> | null | undefined)} [getAttrs]** @returns {import("prosemirror-inputrules").InputRule}*/@@ -132,6 +132,15 @@ export function atBlockStart(state, view) {}// https://github.com/discourse/discourse/pull/31933#discussion_r2019739410+/**+ * Calls `f` for each node in `cur` that is not shared with `old`, descending into+ * changed nodes. `f` also serves as a `nodesBetween` callback, hence its return type.+ *+ * @param {import("prosemirror-model").Node} old+ * @param {import("prosemirror-model").Node} cur+ * @param {(node: import("prosemirror-model").Node, pos: number) => boolean | void} f+ * @param {number} [offset]+ */export function changedDescendants(old, cur, f, offset = 0) {const oldSize = old.childCount,curSize = cur.childCount;diff --git a/frontend/discourse/app/static/prosemirror/lib/text-manipulation.ts b/frontend/discourse/app/static/prosemirror/lib/text-manipulation.tsindex 3d1d4b218d2..d0cb55eb4a3 100644--- a/frontend/discourse/app/static/prosemirror/lib/text-manipulation.ts+++ b/frontend/discourse/app/static/prosemirror/lib/text-manipulation.ts@@ -1,3 +1,4 @@+import { assert } from "@ember/debug";import { destroy } from "@ember/destroyable";import { type default as Owner, getOwner, setOwner } from "@ember/owner";import { trackedObject } from "@ember/reactive/collections";@@ -7,6 +8,7 @@ import { lookupCachedUploadUrl } from "pretty-text/upload-short-url";import { lift, setBlockType, toggleMark, wrapIn } from "prosemirror-commands";import {type Fragment,+ type MarkType,type Node,type NodeType,type Schema,@@ -18,6 +20,7 @@ import {wrapInList,} from "prosemirror-schema-list";import {+ type Command,type EditorState,NodeSelection,Selection,@@ -90,6 +93,16 @@ function isPlainTextFragment(fragment: Fragment, schema: Schema): boolean {});}+/**+ * The first block of a document parsed from markdown. Non-empty markdown always+ * yields at least one block, which every caller here relies on.+ */+function firstBlockOf(doc: Node): Node {+ const block = doc.content.firstChild;+ assert("Parsed markdown has a first block", block);+ return block;+}+export default class ProsemirrorTextManipulation implements TextManipulation {autocompletes: object[] = [];@@ -192,7 +205,7 @@ export default class ProsemirrorTextManipulation implements TextManipulation {}const modifier = dAutocomplete.setupAutocomplete(- getOwner(this),+ getOwner(this)!,this.view.dom,this.autocompleteHandler,options@@ -215,17 +228,15 @@ export default class ProsemirrorTextManipulation implements TextManipulation {tail: string,exampleKey: string): void {- const applySurroundMap = {+ const applySurroundMap: Partial<Record<string, MarkType>> = {italic_text: this.schema.marks.em,bold_text: this.schema.marks.strong,code_title: this.schema.marks.code,};- if (applySurroundMap[exampleKey]) {- toggleMark(applySurroundMap[exampleKey])(- this.view.state,- this.view.dispatch- );+ const mark = applySurroundMap[exampleKey];+ if (mark) {+ toggleMark(mark)(this.view.state, this.view.dispatch);return;}@@ -241,10 +252,10 @@ export default class ProsemirrorTextManipulation implements TextManipulation {text = this.convertToMarkdown(selectedFragment);}- const doc = this.convertFromMarkdown(head + text + tail);+ const block = firstBlockOf(this.convertFromMarkdown(head + text + tail));this.view.dispatch(- this.view.state.tr.replaceWith(sel.start, sel.end, doc.content.firstChild)+ this.view.state.tr.replaceWith(sel.start, sel.end, block));}@@ -261,13 +272,9 @@ export default class ProsemirrorTextManipulation implements TextManipulation {}addText(sel: SelectedText, text: string): void {- const doc = this.convertFromMarkdown(text);-// assumes it returns a single block node- const content =- doc.content.firstChild.type.name === "paragraph"- ? doc.content.firstChild.content- : doc.content.firstChild;+ const block = firstBlockOf(this.convertFromMarkdown(text));+ const content = block.type.name === "paragraph" ? block.content : block;this.view.dispatch(this.view.state.tr.replaceWith(sel.start, sel.end, content)@@ -295,7 +302,7 @@ export default class ProsemirrorTextManipulation implements TextManipulation {head: string | ((previous?: string) => string),exampleKey: string): void {- let command;+ let command: Command | undefined;const findParentList = () => {const $from = this.view.state.selection.$from;@@ -315,7 +322,7 @@ export default class ProsemirrorTextManipulation implements TextManipulation {return null;};- const replaceSelectionWithList = (targetType) => {+ const replaceSelectionWithList = (targetType: NodeType) => {const { state } = this.view;const selectedContent = state.selection.content().content;@@ -424,7 +431,7 @@ export default class ProsemirrorTextManipulation implements TextManipulation {let index = 0;const value = this.autocompleteHandler.getValue();- const match = value.match(/\B:([\p{L}\p{N}_]*)$/u);+ const match = /\B:([\p{L}\p{N}_]*)$/u.exec(value);if (match) {index = value.length - match.index;}@@ -489,12 +496,10 @@ export default class ProsemirrorTextManipulation implements TextManipulation {}insertText(text: string): void {- const doc = this.convertFromMarkdown(text);+ const block = firstBlockOf(this.convertFromMarkdown(text));this.view.dispatch(- this.view.state.tr- .replaceSelectionWith(doc.content.firstChild)- .scrollIntoView()+ this.view.state.tr.replaceSelectionWith(block).scrollIntoView());this.focus();@@ -567,7 +572,11 @@ export default class ProsemirrorTextManipulation implements TextManipulation {}const imagesToWrapGrid = new Set(consecutiveImages);- const placeholderNodes = [];+ const placeholderNodes: Array<{+ node: Node;+ pos: number;+ filename: string;+ }> = [];this.view.state.doc.descendants((node, pos) => {if (node.type === this.schema.nodes.grid) {@@ -697,15 +706,14 @@ class ProsemirrorAutocompleteHandler implements AutocompleteHandler {*/replaceTerm(start: number, end: number, term: string): void {const node = this.view.state.selection.$head.nodeBefore;+ assert("Autocomplete replaces a term before the caret", node);const from = this.view.state.selection.from - node.nodeSize + start;const to = this.view.state.selection.from - node.nodeSize + end + 1;- const doc = this.convertFromMarkdown(term);-const tr = this.view.state.tr.replaceWith(from,to,- doc.content.firstChild.content+ firstBlockOf(this.convertFromMarkdown(term)).content);tr.insertText(" ", tr.selection.from);@@ -728,6 +736,7 @@ class ProsemirrorAutocompleteHandler implements AutocompleteHandler {getCaretCoords(start: number): { left: number; top: number } {const node = this.view.state.selection.$head.nodeBefore;+ assert("Autocomplete measures a term before the caret", node);const pos = this.view.state.selection.from - node.nodeSize + start;const { left, top } = this.view.coordsAtPos(pos);@@ -847,9 +856,10 @@ class ProsemirrorPlaceholderHandler implements PlaceholderHandler {const wasSelected = this.view.state.selection.from === found.pos;// keeping compatibility with plugins that change the upload markdown- const doc = this.convertFromMarkdown(markdown);const tr = this.view.state.tr;- const replacement = doc.content.firstChild.content;+ const replacement = firstBlockOf(+ this.convertFromMarkdown(markdown)+ ).content;if (found.node.type === this.schema.nodes.image) {this.#revokeBlobUrl(found.node);