A platform for community discussion. Free, open, simple.
DEV: Convert composer and rich editor libraries to TypeScript (#41995)
Sérgio Saquetima41959545408
diff --git a/frontend/discourse/app/lib/composer/rich-editor-extensions.js b/frontend/discourse/app/lib/composer/rich-editor-extensions.jsdeleted file mode 100644index 320d848155b..00000000000--- a/frontend/discourse/app/lib/composer/rich-editor-extensions.js+++ /dev/null@@ -1,186 +0,0 @@-// @ts-check--import { waitForPromise } from "@ember/test-waiters";--/**- * @typedef PluginContext- * @property {string} placeholder- * @property {number} topicId- * @property {number} categoryId- * @property {import("discourse/models/session").default} session- * @property {import("discourse/float-kit/services/menu").default} menu- * @property {import("discourse/services/capabilities").default} capabilities- * @property {import("discourse/services/modal").default} modal- * @property {import("discourse/float-kit/services/toasts").default} toasts- * @property {import("discourse/models/site").default} site- * @property {Record<string, unknown>} siteSettings- * @property {(toolbar: import("discourse/lib/composer/toolbar").ToolbarBase) => void} replaceToolbar- * @property {(nodeView: import("discourse/static/prosemirror/lib/glimmer-node-view").default) => void} addGlimmerNodeView- * @property {(nodeView: import("discourse/static/prosemirror/lib/glimmer-node-view").default) => void} removeGlimmerNodeView- */--/**- * @typedef {Object} EditorInstanceUtils- * @property {(markdown: string) => import("prosemirror-model").Node} convertFromMarkdown- * @property {(doc: import("prosemirror-model").Node) => string} convertToMarkdown- * @property {(text: string) => string[]} splitNonEmptyLines- * @property {(schema: import("prosemirror-model").Schema, listType: import("prosemirror-model").NodeType, lines: string[]) => import("prosemirror-model").Node} buildListNode- * @property {() => void} toggleRichEditor- */--/**- * @typedef PluginParams- * @property {typeof import("discourse/static/prosemirror/lib/plugin-utils") & EditorInstanceUtils} utils- * @property {typeof import('prosemirror-model')} pmModel- * @property {typeof import('prosemirror-view')} pmView- * @property {typeof import('prosemirror-state')} pmState- * @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- */--/** @typedef {import('prosemirror-state').PluginSpec} PluginSpec */-/** @typedef {((params: PluginParams) => PluginSpec)} RichPluginFn */-/** @typedef {PluginSpec | RichPluginFn} RichPlugin */--/**- * @typedef InputRuleObject- * @property {RegExp} match- * @property {((state: import('prosemirror-state').EditorState, match: RegExpMatchArray, start: number, end: number) => import('prosemirror-state').Transaction | null)} handler- * @property {{ undoable?: boolean, inCode?: boolean | "only" }} [options]- */--/**- * @typedef InputRuleParams- * @property {import('prosemirror-model').Schema} schema- * @property {Function} markInputRule- */--/** @typedef {((params: InputRuleParams) => InputRuleObject) | InputRuleObject} RichInputRule */--/**- * @typedef {(params: PluginParams, state: import('prosemirror-state').EditorState) => Record<string, unknown>} StateFunction- */--/**- * @typedef {(params: PluginParams) => import('prosemirror-state').PluginSpec | import('prosemirror-state').PluginSpec} PluginsFunction- */--/** @typedef {PluginsFunction | import('prosemirror-state').PluginSpec} PluginsProperty */--// @ts-ignore we don't have type definitions for markdown-it-/** @typedef {import("markdown-it").Token} MarkdownItToken */-/** @typedef {(state: unknown, token: MarkdownItToken, tokenStream: MarkdownItToken[], index: number) => boolean | void} ParseFunction */-/** @typedef {import("prosemirror-markdown").ParseSpec | ParseFunction} RichParseSpec */--/**- * NodeView constructor signature - can be a class or constructor function- * @typedef {new (node: import('prosemirror-model').Node, view: import('prosemirror-view').EditorView, getPos: (() => number) | boolean) => Object} NodeViewConstructor- */--/**- * Extended MarkdownSerializerState with additional properties used by Discourse- * @typedef {Object} ExtendedMarkdownSerializerState- * @property {string} out - The output string being built- * @property {string} delim - Current delimiter for block formatting- * @property {boolean} [inTable] - Whether currently serializing inside a table (Discourse-specific)- * @property {(size?: number) => void} flushClose - Flush closed blocks with optional size- * @property {() => boolean} atBlank - Check if output is currently at a blank line- */--/**- * @typedef {import("prosemirror-markdown").MarkdownSerializerState & ExtendedMarkdownSerializerState} DiscourseMarkdownSerializerState- */--/**- * @typedef {(state: DiscourseMarkdownSerializerState, node: import("prosemirror-model").Node, parent: import("prosemirror-model").Node, index: number) => void} SerializeNodeFn- */--/** @typedef {Record<string, import('prosemirror-state').Command>} KeymapSpec */-/** @typedef {((params: PluginParams) => KeymapSpec)} RichKeymapFn */-/** @typedef {KeymapSpec | RichKeymapFn} RichKeymap */--// @ts-ignore MarkSerializerSpec not currently exported-/** @typedef {import('prosemirror-markdown').MarkSerializerSpec} MarkSerializerSpec */--/**- * @typedef {Object} RichEditorExtension- * @property {Record<string, import('prosemirror-model').NodeSpec>} [nodeSpec]- * Map containing Prosemirror node spec definitions, each key being the node name- * See https://prosemirror.net/docs/ref/#model.NodeSpec- * @property {Record<string, import('prosemirror-model').MarkSpec>} [markSpec]- * Map containing Prosemirror mark spec definitions, each key being the mark name- * See https://prosemirror.net/docs/ref/#model.MarkSpec- * @property {InputRuleObject | InputRuleObject[] | ((params: PluginParams) => InputRuleObject | InputRuleObject[] | import('prosemirror-inputrules').InputRule | import('prosemirror-inputrules').InputRule[])} [inputRules]- * ProseMirror input rules. See https://prosemirror.net/docs/ref/#inputrules.InputRule- * can be a single rule, array of rules, or function returning rule(s)- * @property {((params: PluginParams) => Record<string, SerializeNodeFn>) | Record<string, SerializeNodeFn>} [serializeNode]- * Node serialization definition - can be a function returning an object with node serializers, or a direct object- * @property {((params: PluginParams) => Record<string, MarkSerializerSpec>) | Record<string, MarkSerializerSpec>} [serializeMark]- * Mark serialization definition - can be a function returning an object with mark serializers, or a direct object- * @property {Record<string, RichParseSpec>} [parse]- * Markdown-it token parse definition- * @property {PluginsProperty} [plugins]- * ProseMirror plugins - can be a function returning plugin spec or plugin spec object- * @property {Record<string, NodeViewConstructor | ((params: PluginParams) => NodeViewConstructor) | { component: any, name?: string }>} [nodeViews]- * ProseMirror node views. Can be a NodeViewConstructor or an object with { component, name } for automatic Glimmer component wrapping- * @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- * @property {StateFunction} [state]- * State function that computes editor state data- */--/** @type {RichEditorExtension[]} */-const registeredExtensions = [];-let defaultExtensionsRegistered = false;--export function markDefaultExtensionsRegistered() {- defaultExtensionsRegistered = true;-}--export function areDefaultExtensionsRegistered() {- return defaultExtensionsRegistered;-}--/**- * Registers an extension for the rich editor- *- * EXPERIMENTAL: This API will change without warning- *- * @param {RichEditorExtension} extension- */-export function registerRichEditorExtension(extension) {- registeredExtensions.push(extension);-}--export async function clearRichEditorExtensions() {- // Import it first - a lazy import later would re-register the defaults.- const module = await waitForPromise(- import(- /* dynamicChunkName: "prosemirror-extensions" */ "discourse/static/prosemirror/extensions/register-default"- )- );- registeredExtensions.length = 0;- defaultExtensionsRegistered = false;- return module;-}--export async function resetRichEditorExtensions() {- const { default: extensions } = await clearRichEditorExtensions();- extensions.forEach(registerRichEditorExtension);- markDefaultExtensionsRegistered();-}--/**- * Get all extensions registered for the rich editor- *- * @returns {RichEditorExtension[]}- */-export function getExtensions() {- return registeredExtensions;-}diff --git a/frontend/discourse/app/lib/composer/rich-editor-extensions.ts b/frontend/discourse/app/lib/composer/rich-editor-extensions.tsnew file mode 100644index 00000000000..7ff1d4e2b0f--- /dev/null+++ b/frontend/discourse/app/lib/composer/rich-editor-extensions.ts@@ -0,0 +1,341 @@+import { waitForPromise } from "@ember/test-waiters";+import type { InputRule } from "prosemirror-inputrules";+import type { MarkdownSerializerState, ParseSpec } from "prosemirror-markdown";+import type {+ Mark,+ MarkSpec,+ Node,+ NodeSpec,+ NodeType,+ Schema,+} from "prosemirror-model";+import type {+ Command,+ EditorState,+ Plugin,+ PluginSpec,+ Transaction,+} from "prosemirror-state";+import type { EditorView, NodeViewConstructor } from "prosemirror-view";+import type DialogService from "discourse/dialog-holder/services/dialog";+import type MenuService from "discourse/float-kit/services/menu";+import type ToastsService from "discourse/float-kit/services/toasts";+import type Session from "discourse/models/session";+import type Site from "discourse/models/site";+import type AppEventsService from "discourse/services/app-events";+import type { CapabilitiesService } from "discourse/services/capabilities";+import type ModalService from "discourse/services/modal";+import type GlimmerNodeView from "discourse/static/prosemirror/lib/glimmer-node-view";+import type { ToolbarBase } from "./toolbar";++export interface PluginContext {+ /** Placeholder shown when the document is empty. */+ placeholder?: string;+ /** ID of the topic being edited. */+ topicId?: number;+ /** ID of the category being edited. */+ categoryId?: number;+ /** Current application session. */+ session: Session;+ /** Service used to show contextual menus. */+ menu: MenuService;+ /** Browser capability information. */+ capabilities: CapabilitiesService;+ /** Service used to show modal components. */+ modal: ModalService;+ /** Service used to show toast messages. */+ toasts: ToastsService;+ /** Current site metadata. */+ site: Site;+ /** Client site settings available to extensions. */+ siteSettings: Record<string, unknown>;+ /** Application event bus. */+ appEvents: AppEventsService;+ /** Service used to show confirmation and alert dialogs. */+ dialog: DialogService;+ /** Replaces or restores the toolbar displayed by the editor container. */+ replaceToolbar?: (toolbar: ToolbarBase | null, owner?: ToolbarBase) => void;+ /** Registers a rendered component-backed node view. */+ addGlimmerNodeView: (nodeView: GlimmerNodeView) => void;+ /** Unregisters a rendered component-backed node view. */+ removeGlimmerNodeView: (nodeView: GlimmerNodeView) => void;+}++export interface EditorInstanceUtils {+ /** Parses markdown into a document. */+ convertFromMarkdown: (markdown: string) => Node;+ /** Serializes a document to markdown. */+ convertToMarkdown: (doc: Node) => string;+ /** Splits text into non-empty lines. */+ splitNonEmptyLines: (text: string) => string[];+ /** Builds a list node from text lines. */+ buildListNode: (+ schema: Schema,+ listType: NodeType | string,+ lines: string[]+ ) => Node;+ /** Toggles between the rich and plain-text editors when available. */+ toggleRichEditor?: () => void;+}++export interface PluginParams {+ /** Editor utilities available to extensions. */+ utils: typeof import("discourse/static/prosemirror/lib/plugin-utils") &+ EditorInstanceUtils;+ /** ProseMirror model module namespace. */+ pmModel: typeof import("prosemirror-model");+ /** ProseMirror view module namespace. */+ pmView: typeof import("prosemirror-view");+ /** ProseMirror state module namespace. */+ pmState: typeof import("prosemirror-state");+ /** ProseMirror history module namespace. */+ pmHistory: typeof import("prosemirror-history");+ /** ProseMirror transform module namespace. */+ pmTransform: typeof import("prosemirror-transform");+ /** ProseMirror command module namespace. */+ pmCommands: typeof import("prosemirror-commands");+ /** ProseMirror list-schema module namespace. */+ pmSchemaList: typeof import("prosemirror-schema-list");+ /** Schema used by the editor instance. */+ schema: Schema;+ /** Returns application context for the editor instance. */+ getContext: () => PluginContext;+}++export interface InputRuleObject {+ /** Pattern that triggers the rule. */+ match: RegExp;+ /** Applies the rule to a matching text range. */+ handler: (+ state: EditorState,+ match: RegExpMatchArray,+ start: number,+ end: number+ ) => Transaction | null;+ /** Behavior applied when wrapping the rule in an input-rule instance. */+ options?: {+ /** Whether the rule can be undone as a single input action. */+ undoable?: boolean;+ /** Whether the rule is allowed inside code blocks. */+ inCode?: boolean | "only";+ /** Whether the rule is allowed inside inline code marks. */+ inCodeMark?: boolean | "only";+ };+}++type RichInputRuleValue = InputRuleObject | InputRule;+export type RichInputRule =+ | RichInputRuleValue+ | RichInputRuleValue[]+ | ((params: PluginParams) => RichInputRuleValue | RichInputRuleValue[]);++export type StateFunction = (+ params: PluginParams,+ state: EditorState+) => Record<string, unknown>;++type RichPluginValue = Plugin | PluginSpec<unknown>;+export type RichPlugin =+ | RichPluginValue+ | RichPluginValue[]+ | ((+ params: PluginParams+ ) =>+ | RichPluginValue+ | RichPluginValue[]+ | Promise<RichPluginValue | RichPluginValue[]>);++export type ParseFunction = (+ state: unknown,+ token: MarkdownItToken,+ tokenStream: MarkdownItToken[],+ index: number+) => boolean | void;+export type RichParseSpec = ParseSpec | ParseFunction;++export interface MarkdownItToken {+ /** Parser token type. */+ type: string;+ /** HTML tag associated with the token. */+ tag: string;+ /** Token attributes. */+ attrs: [string, string][] | null;+ /** Source line range for block tokens. */+ map: [number, number] | null;+ /** Change in nesting level introduced by the token. */+ nesting: number;+ /** Token nesting level. */+ level: number;+ /** Child tokens for inline content. */+ children: MarkdownItToken[] | null;+ /** Token text content. */+ content: string;+ /** Source markup that produced the token. */+ markup: string;+ /** Fence or other token-specific metadata string. */+ info: string;+ /** Additional parser metadata. */+ meta: unknown;+ /** Whether the token represents block content. */+ block: boolean;+ /** Whether renderers should omit the token. */+ hidden: boolean;+ /** Returns the index of an attribute. */+ attrIndex(name: string): number;+ /** Appends an attribute pair. */+ attrPush(attrData: [string, string]): void;+ /** Sets an attribute value. */+ attrSet(name: string, value: string): void;+ /** Returns an attribute value. */+ attrGet(name: string): string | null;+ /** Appends text to an attribute value. */+ attrJoin(name: string, value: string): void;+}++export interface GlimmerNodeViewDescriptor {+ /** Component rendered for the node view. */+ component: unknown;+ /** Name used to identify the rendered node view. */+ name?: string;+ /** Whether the node view exposes editable child content. */+ hasContent?: boolean;+ /** Determines whether the node view should be rendered. */+ shouldRender?: (params: {+ /** Node represented by the view. */+ node: Node;+ /** Editor view containing the node. */+ view: EditorView;+ /** Returns the node's current document position. */+ getPos: () => number | undefined;+ /** Extension API for the editor instance. */+ pluginParams: PluginParams;+ }) => boolean;+}++export type DiscourseMarkdownSerializerState = MarkdownSerializerState & {+ inTable?: boolean;+ inAutolink?: boolean;+ linkMarkup?: string;+};++export type SerializeNodeFn = (+ state: DiscourseMarkdownSerializerState,+ node: Node,+ parent: Node,+ index: number+) => void;++export type NodeSerializerSpec = Record<string, SerializeNodeFn> & {+ afterSerialize?: (state: DiscourseMarkdownSerializerState) => void;+};++export interface MarkSerializerSpec {+ /** Markdown written before marked content. */+ open:+ | string+ | ((+ state: DiscourseMarkdownSerializerState,+ mark: Mark,+ parent: Node,+ index: number+ ) => string);+ /** Markdown written after marked content. */+ close:+ | string+ | ((+ state: DiscourseMarkdownSerializerState,+ mark: Mark,+ parent: Node,+ index: number+ ) => string);+ /** Whether this mark may be reordered with other mixable marks. */+ mixable?: boolean;+ /** Whether enclosing whitespace should move outside the mark. */+ expelEnclosingWhitespace?: boolean;+ /** Whether content inside the mark should be escaped. */+ escape?: boolean;+}++export type KeymapSpec = Record<string, Command>;+export type RichKeymap = KeymapSpec | ((params: PluginParams) => KeymapSpec);++type RichCommand = (...args: unknown[]) => Command;++export interface RichEditorExtension {+ /** ProseMirror node specifications keyed by node name. */+ nodeSpec?: Record<string, NodeSpec>;+ /** ProseMirror mark specifications keyed by mark name. */+ markSpec?: Record<string, MarkSpec>;+ /** Input rules contributed by the extension. */+ inputRules?: RichInputRule;+ /** Node serializers contributed by the extension. */+ serializeNode?:+ | NodeSerializerSpec+ | ((params: PluginParams) => NodeSerializerSpec);+ /** Mark serializers contributed by the extension. */+ serializeMark?:+ | Record<string, MarkSerializerSpec>+ | ((params: PluginParams) => Record<string, MarkSerializerSpec>);+ /** Markdown token parsers keyed by token name. */+ parse?: Record<string, RichParseSpec>;+ /** ProseMirror plugins contributed by the extension. */+ plugins?: RichPlugin;+ /** Node views keyed by node name. */+ nodeViews?: Record<+ string,+ | NodeViewConstructor+ | ((params: PluginParams) => NodeViewConstructor)+ | GlimmerNodeViewDescriptor+ >;+ /** Keyboard shortcuts contributed by the extension. */+ keymap?: RichKeymap;+ /** Commands exposed on the editor view state. */+ commands?: (params: PluginParams) => Record<string, RichCommand>;+ /** Custom toolbar state contributed by the extension. */+ state?: StateFunction;+}++const registeredExtensions: RichEditorExtension[] = [];+let defaultExtensionsRegistered = false;++export function markDefaultExtensionsRegistered() {+ defaultExtensionsRegistered = true;+}++export function areDefaultExtensionsRegistered() {+ return defaultExtensionsRegistered;+}++/**+ * Registers an extension for the rich editor+ *+ * EXPERIMENTAL: This API will change without warning+ */+export function registerRichEditorExtension(extension: RichEditorExtension) {+ registeredExtensions.push(extension);+}++export async function clearRichEditorExtensions() {+ // Import it first - a lazy import later would re-register the defaults.+ const module = await waitForPromise(+ import(+ /* dynamicChunkName: "prosemirror-extensions" */ "discourse/static/prosemirror/extensions/register-default"+ )+ );+ registeredExtensions.length = 0;+ defaultExtensionsRegistered = false;+ return module;+}++export async function resetRichEditorExtensions() {+ const { default: extensions } = await clearRichEditorExtensions();+ extensions.forEach(registerRichEditorExtension);+ markDefaultExtensionsRegistered();+}++/**+ * Get all extensions registered for the rich editor+ */+export function getExtensions(): RichEditorExtension[] {+ return registeredExtensions;+}diff --git a/frontend/discourse/app/lib/composer/text-manipulation.js b/frontend/discourse/app/lib/composer/text-manipulation.jsdeleted file mode 100644index d1b37a6b642..00000000000--- a/frontend/discourse/app/lib/composer/text-manipulation.js+++ /dev/null@@ -1,326 +0,0 @@-// @ts-check--/**- * Interface for text manipulation with an underlying editor implementation.- *- * @interface TextManipulation- */-export const TextManipulation = {};--/**- * @typedef ToolbarState- * @property {boolean} [inBold]- * @property {boolean} [inItalic]- * @property {boolean} [inLink]- * @property {boolean} [inBulletList]- * @property {boolean} [inOrderedList]- * @property {boolean} [inCode]- * @property {boolean} [inCodeBlock]- * @property {boolean} [inBlockquote]- * @property {boolean} [inHeading]- * @property {number} [inHeadingLevel]- */--/**- * The current state of the editor for toolbar button active states- * @name TextManipulation#state- * @type {ToolbarState | undefined}- * @readonly- */--/**- * Whether the editor allows a preview being shown- * @name TextManipulation#allowPreview- * @type {boolean}- * @readonly- */--/**- * Focuses the editor- *- * @method- * @name TextManipulation#focus- * @returns {void}- */--/**- * Blurs and focuses the editor- *- * @method- * @name TextManipulation#blurAndFocus- * @returns {void}- */--/**- * Indents/un-indents the current selection- *- * @method- * @name TextManipulation#indentSelection- * @param {string} direction The direction to indent in. Either "right" or "left"- * @returns {void}- */--/**- * Configures an Autocomplete for the editor- *- * @method- * @name TextManipulation#autocomplete- * @param {unknown} options The options for the jQuery autocomplete- * @returns {void}- */--/**- * Checks if the current selection is in a code block- *- * @method- * @name TextManipulation#inCodeBlock- * @returns {Promise<boolean>}- */--/**- * Gets the current selection- *- * @method- * @name TextManipulation#getSelected- * @param {unknown} trimLeading- * @returns {unknown}- */--/**- * Selects the text from the given range- *- * @method- * @name TextManipulation#selectText- * @param {number} from- * @param {number} to- * @param {unknown} [options]- * @returns {void}- */--/**- * Applies the given head/tail to the selected text- *- * @method- * @name TextManipulation#applySurround- * @param {string} selected The selected text- * @param {string} head The text to be inserted before the selection- * @param {string} tail The text to be inserted after the selection- * @param {string} exampleKey The key of the example- * @param {unknown} [opts]- */--/**- * Applies the list format to the selected text- *- * @method- * @name TextManipulation#applyList- * @param {string} selected The selected text- * @param {string} head The text to be inserted before the selection- * @param {string} exampleKey The key of the example- * @param {unknown} [opts]- */--/**- * Formats the current selection as code- *- * @method- * @name TextManipulation#formatCode- * @returns {void}- */--/**- * Adds text- *- * @method- * @name TextManipulation#addText- * @param {string} selected The selected text- * @param {string} text The text to be inserted- */--/**- * Toggles the text (LTR/RTL) direction- *- * @method- * @name TextManipulation#toggleDirection- * @returns {void}- */--/**- * Replaces text- *- * @method- * @name TextManipulation#replaceText- * @param {string} oldValue The old value- * @param {string} newValue The new value- * @param {unknown} [opts]- * @returns {void}- */--/**- * Handles the paste event- *- * @method- * @name TextManipulation#paste- * @param {ClipboardEvent} event The paste event- * @returns {void}- */--/**- * Inserts the block- *- * @method- * @name TextManipulation#insertBlock- * @param {string} block The block to be inserted- * @returns {void}- */--/**- * Inserts text- *- * @method- * @name TextManipulation#insertText- * @param {string} text The text to be inserted- * @returns {void}- */--/**- * Applies the head/tail to the selected text- *- * @method- * @name TextManipulation#applySurroundSelection- * @param {string} head The text to be inserted before the selection- * @param {string} tail The text to be inserted after the selection- * @param {string} exampleKey The key of the example- * @param {unknown} [opts]- * @returns {void}- */--/**- * Puts cursor at the end of the editor- *- * @method- * @name TextManipulation#putCursorAtEnd- * @returns {void}- */--/**- * The placeholder handler instance- *- * @name TextManipulation#placeholder- * @type {PlaceholderHandler}- * @readonly- */--/** @typedef {import("@uppy/utils").MinimalRequiredUppyFile<any,any>} UppyFile */--/**- * Interface for handling placeholders on upload events- *- * @interface PlaceholderHandler- */-export const PlaceholderHandler = {};--/**- * Inserts a file- *- * @method- * @name PlaceholderHandler#insert- * @param {UppyFile} file The uploaded file- * @returns {void}- */--/**- * Success event for file upload- *- * @method- * @name PlaceholderHandler#success- * @param {UppyFile} file The uploaded file- * @param {string} markdown The markdown for the uploaded file- * @returns {void}- */--/**- * Cancels all uploads- *- * @method- * @name PlaceholderHandler#cancelAll- * @returns {void}- */--/**- * Cancels one uploaded file- *- * @method- * @name PlaceholderHandler#cancel- * @param {UppyFile} file The uploaded file- * @returns {void}- */--/**- * Progress event- *- * @method- * @name PlaceholderHandler#progress- * @param {UppyFile} file The uploaded file- * @returns {void}- */--/**- * Progress complete event- *- * @method- * @name PlaceholderHandler#progressComplete- * @param {UppyFile} file The uploaded file- * @returns {void}- */--/**- * Interface for the Autocomplete handler- *- * @interface AutocompleteHandler- */-export const AutocompleteHandler = {};--/**- * Replaces the range with the given text- *- * @method- * @name AutocompleteHandler#replaceTerm- * @param {number} start The start of the range- * @param {number} end The end of the range- * @param {string} text The text to be inserted- * @returns {void}- */--/**- * Gets the caret position- *- * @method- * @name AutocompleteHandler#getCaretPosition- * @returns {number}- */--/**- * Checks if the current selection is in a code block- *- * @method- * @name AutocompleteHandler#inCodeBlock- * @returns {Promise<boolean>}- */--/**- * Gets the caret coordinates- *- * @method- * @name AutocompleteHandler#getCaretCoords- * @param {number} caretPositon The caret position to get the coords for- * @returns {{ top: number, left: number }}- */--/**- * Gets the current value for the autocomplete- *- * @method- * @name AutocompleteHandler#getValue- * @returns {string}- */diff --git a/frontend/discourse/app/lib/composer/text-manipulation.ts b/frontend/discourse/app/lib/composer/text-manipulation.tsnew file mode 100644index 00000000000..ef77ec34f44--- /dev/null+++ b/frontend/discourse/app/lib/composer/text-manipulation.ts@@ -0,0 +1,222 @@+import type {+ Body,+ LocalUppyFileNonGhost,+ Meta,+ MinimalRequiredUppyFile,+} from "@uppy/utils";++export interface ToolbarState {+ /** Whether the selection has strong emphasis. */+ inBold?: boolean;+ /** Whether the selection has italic emphasis. */+ inItalic?: boolean;+ /** Whether the selection is inside a link. */+ inLink?: boolean;+ /** Whether the selection is inside a bullet list. */+ inBulletList?: boolean;+ /** Whether the selection is inside an ordered list. */+ inOrderedList?: boolean;+ /** Whether the selection has inline code formatting. */+ inCode?: boolean;+ /** Whether the selection is inside a code block. */+ inCodeBlock?: boolean;+ /** Whether the selection is inside a block quote. */+ inBlockquote?: boolean;+ /** Whether the selection is inside a heading. */+ inHeading?: boolean;+ /** Heading level at the selection. */+ inHeadingLevel?: number;+ /** Whether the selection is inside a paragraph. */+ inParagraph?: boolean;+}++export interface SelectedText {+ /** Start offset of the selection. */+ start: number;+ /** End offset of the selection. */+ end: number;+ /** Selected text. */+ value: string;+ /** Text before the selection. */+ pre: string;+ /** Text after the selection. */+ post: string;+ /** Full text of the line containing the selection. */+ lineVal?: string;+}++export interface SelectionOptions {+ /** Include the current line's text in the selection result. */+ lineVal?: boolean;+}++export interface SelectTextOptions {+ /** Restore scrolling, optionally to a supplied vertical position. */+ scroll?: boolean | number;+}++export interface ReplaceTextOptions {+ /** Zero-based match occurrence to replace. */+ index?: number;+ /** Pattern used to locate replacement candidates. */+ regex?: RegExp;+ /** Focus the editor after replacement. */+ forceFocus?: boolean;+ /** Preserve the current selection after replacement. */+ skipNewSelection?: boolean;+ /** Avoid focusing before inserting replacement text. */+ skipFocus?: boolean;+}++export interface SurroundOptions {+ /** Apply formatting independently across multiple lines. */+ multiline?: boolean;+ /** Put multiline content on lines between the delimiters. */+ useBlockMode?: boolean;+ /** Apply formatting to empty lines. */+ applyEmptyLines?: boolean;+ /** Leave the leading marker outside the restored selection. */+ excludeHeadInSelection?: boolean;+}++export interface AddTextOptions {+ /** Add separating whitespace when adjacent text requires it. */+ ensureSpace?: boolean;+}++export type AutocompleteOptions = Record<string, unknown> | "destroy";++export type UppyFile = MinimalRequiredUppyFile<Meta, Body> & {+ /** Stable identifier used to track the upload placeholder. */+ id: string;+ /** Local file data used to determine placeholder rendering. */+ data: LocalUppyFileNonGhost<Meta, Body>["data"];+};++/**+ * Text operations shared by the plain-text and rich composer editors.+ */+export interface TextManipulation {+ /** Current toolbar-active state. */+ readonly state: ToolbarState & Record<string, unknown>;+ /** Whether this editor supports a rendered preview. */+ readonly allowPreview: boolean;+ /** Upload placeholder operations for this editor. */+ readonly placeholder: PlaceholderHandler;+ /** Autocomplete text operations for this editor. */+ readonly autocompleteHandler: AutocompleteHandler;+ /** Commands contributed by rich-editor extensions. */+ readonly commands?: Record<string, (...args: unknown[]) => unknown>;+ /** Focuses the editor. */+ focus(): void;+ /** Restores focus after a text operation. */+ blurAndFocus(): void;+ /** Indents or outdents the current selection. */+ indentSelection(direction: "left" | "right"): boolean | void;+ /** Configures or destroys autocomplete behavior. */+ autocomplete(options: AutocompleteOptions): unknown;+ /** Reports whether the selection is in code formatting. */+ inCodeBlock(): boolean | Promise<boolean>;+ /** Returns the current editor selection. */+ getSelected(+ trimLeading?: boolean | null | "",+ options?: SelectionOptions+ ): SelectedText;+ /** Selects a text range. */+ selectText(from: number, length: number, options?: SelectTextOptions): void;+ /** Surrounds a supplied selection with formatting text. */+ applySurround(+ selected: SelectedText,+ head: string | ((previous?: string) => string),+ tail: string,+ exampleKey: string,+ options?: SurroundOptions+ ): void;+ /** Applies list-like formatting to a supplied selection. */+ applyList(+ selected: SelectedText,+ head: string | ((previous?: string) => string),+ exampleKey: string,+ options?: SurroundOptions+ ): void;+ /** Applies heading formatting to a supplied selection. */+ applyHeading(+ selected: SelectedText,+ level: number,+ exampleKey?: string+ ): void;+ /** Formats the current selection as code. */+ formatCode(): boolean | void;+ /** Adds text at a supplied selection. */+ addText(selected: SelectedText, text: string, options?: AddTextOptions): void;+ /** Applies a link to the current selection. */+ applyLink(url: string): void;+ /** Toggles the editor's text direction. */+ toggleDirection(): void;+ /** Replaces matching text. */+ replaceText(+ oldValue: string,+ newValue: string,+ options?: ReplaceTextOptions+ ): void;+ /** Handles pasted content. */+ paste(event?: ClipboardEvent): void | Promise<void>;+ /** Inserts a standalone block. */+ insertBlock(block: string): void;+ /** Inserts text at the current selection. */+ insertText(text: string, options?: AddTextOptions): void;+ /** Surrounds the current selection with formatting text. */+ applySurroundSelection(+ head: string | ((previous?: string) => string),+ tail: string,+ exampleKey: string,+ options?: SurroundOptions+ ): void;+ /** Places the cursor at the end of the editor. */+ putCursorAtEnd(): void;+ /** Inserts a selected emoji. */+ emojiSelected(code: string): void;+ /** Wraps the supplied upload placeholders in a grid. */+ autoGridImages(consecutiveImages: string[]): void;+}++/**+ * Upload placeholder operations shared by composer editors.+ */+export interface PlaceholderHandler {+ /** Inserts a placeholder for a file. */+ insert(file: UppyFile): void;+ /** Replaces a completed placeholder with upload markdown. */+ success(file: UppyFile, markdown: string): void;+ /** Cancels every active placeholder. */+ cancelAll(): void;+ /** Cancels one file's placeholder. */+ cancel(file: UppyFile): void;+ /** Marks one placeholder as processing. */+ progress(file: UppyFile): void;+ /** Restores one placeholder after processing. */+ progressComplete(file: UppyFile): void;+}++/**+ * Text and caret operations used by autocomplete.+ */+export interface AutocompleteHandler {+ /** Replaces an autocomplete term in the current text block. */+ replaceTerm(start: number, end: number, text: string): void;+ /** Returns the caret position within the current text block. */+ getCaretPosition(): number;+ /** Reports whether the caret is in code formatting. */+ inCodeBlock(): Promise<boolean>;+ /** Returns caret coordinates relative to the editor. */+ getCaretCoords(caretPosition: number): { top: number; left: number };+ /** Returns the text used for autocomplete matching. */+ getValue(): string;+ /** Reports whether the caret is within a link. */+ inLink?(): Promise<boolean>;+}++// These runtime exports are retained for compatibility with existing consumers.+export const TextManipulation = {};+export const PlaceholderHandler = {};+export const AutocompleteHandler = {};diff --git a/frontend/discourse/app/lib/composer/toolbar.js b/frontend/discourse/app/lib/composer/toolbar.tssimilarity index 58%rename from frontend/discourse/app/lib/composer/toolbar.jsrename to frontend/discourse/app/lib/composer/toolbar.tsindex cc8656c38d6..7f4a0526a8c 100644--- a/frontend/discourse/app/lib/composer/toolbar.js+++ b/frontend/discourse/app/lib/composer/toolbar.ts@@ -1,34 +1,180 @@-// @ts-checkimport { customPopupMenuOptions } from "discourse/lib/composer/custom-popup-menu-options";import { translateModKey } from "discourse/lib/utilities";import { waitForClosedKeyboard } from "discourse/lib/wait-for-keyboard";+import type Site from "discourse/models/site";+import type { CapabilitiesService } from "discourse/services/capabilities";import { PLATFORM_KEY_MODIFIER } from "discourse/services/keyboard-shortcuts";import { i18n } from "discourse-i18n";+import type {+ SelectedText,+ SurroundOptions,+ ToolbarState,+} from "./text-manipulation";++type ToolbarCommand = (...args: unknown[]) => unknown;+type ListHead = string | ((previous?: string) => string);++export interface ToolbarEvent {+ /** Current editor formatting state. */+ state: ToolbarState & Record<string, unknown>;+ /** Selection captured when the toolbar action began. */+ selected: SelectedText;+ /** Commands contributed by editor extensions. */+ commands?: Record<string, ToolbarCommand>;+ /** Applies surrounding markup to the captured selection. */+ applySurround(+ head: ListHead,+ tail: string,+ exampleKey: string,+ options?: SurroundOptions+ ): void;+ /** Applies list-like markup to the captured selection. */+ applyList(+ head: ListHead,+ exampleKey: string,+ options?: SurroundOptions+ ): void;+ /** Applies a heading level to the captured selection. */+ applyHeading(level: number, exampleKey?: string): void;+ /** Formats the captured selection as code. */+ formatCode(): boolean | void;+ /** Adds text at the captured selection. */+ addText(text: string): void;+ /** Applies a link to the captured selection. */+ applyLink(url: string): void;+ /** Toggles the editor's text direction. */+ toggleDirection(): void;+ /** Replaces matching text in the editor. */+ replaceText(oldValue: string, newValue: string): void;+ /** Selects a text range. */+ selectText(from: number, length: number): void;+ /** Returns the editor's complete text value. */+ getText(): string;+}-/**- * @typedef ToolbarButton- * @property {string} id- * @property {string} [group]- * @property {string} [tabindex]- * @property {string} [className]- * @property {string} [label]- * @property {string} [icon]- * @property {string} [href]- * @property {Function} action- * @property {Function} [perform]- * @property {Function} [sendAction]- * @property {boolean} [trimLeading]- * @property {boolean} [preventFocus]- * @property {Function} condition- * @property {boolean} [hideShortcutInTitle]- * @property {string} title- * @property {string} [shortcut]- * @property {string} [ariaKeyshortcuts]- * @property {boolean} [unshift]- * @property {Function} [active]- */+type ToolbarStateContext = Pick<ToolbarEvent, "state">;++export interface PopupMenuOption {+ /** Stable option name. */+ name: string;+ /** Icon displayed for the option. */+ icon: string;+ /** Translation key for the option label. */+ label?: string;+ /** Translation key for the option title. */+ title?: string;+ /** Pre-translated option label. */+ translatedLabel?: string;+ /** Pre-translated option title. */+ translatedTitle?: string;+ /** Keyboard shortcut that invokes the option. */+ shortcut?: string;+ /** Shortcut exposed to assistive technology. */+ ariaKeyshortcuts?: string;+ /** Whether the option is available. */+ condition: boolean | (() => boolean);+ /** Whether the active option displays its status icon. */+ showActiveIcon?: boolean;+ /** Reports whether the option matches the editor state. */+ active: (context: ToolbarStateContext) => boolean | undefined;+ /** Invokes the option. */+ action: (event: ToolbarEvent) => void;+ /** Popup menu that owns the option. */+ menu?: string;+}-function getButtonLabel(labelKey, defaultLabel) {+interface PopupMenu {+ options: () => PopupMenuOption[] | undefined;+ action?: (option: PopupMenuOption) => void;+}++export interface ToolbarButton {+ /** Stable button identifier. */+ id?: string;+ /** Toolbar group containing the button. */+ group?: string;+ /** Keyboard tab index applied to the button. */+ tabindex?: string;+ /** Additional class applied to the button. */+ className?: string;+ /** Translation key for the button label. */+ label?: string | null;+ /** Icon name or state-dependent icon resolver. */+ icon?: string | null | ((context: ToolbarStateContext) => string);+ /** Link target for buttons that navigate. */+ href?: string;+ /** Action invoked by the rendered button. */+ action: () => void | Promise<void>;+ /** Text operation invoked by the button. */+ perform?: (event: ToolbarEvent) => void;+ /** Controller action invoked by the button. */+ sendAction?: (event: ToolbarEvent) => void;+ /** Whether leading whitespace is excluded from the captured selection. */+ trimLeading?: boolean;+ /** Whether the button keeps focus in the editor. */+ preventFocus?: boolean;+ /** Reports whether the button is available. */+ condition: () => boolean;+ /** Whether the shortcut is omitted from the title. */+ hideShortcutInTitle?: boolean;+ /** Localized button title. */+ title: string;+ /** Keyboard shortcut that invokes the button. */+ shortcut?: string;+ /** Shortcut exposed to assistive technology. */+ ariaKeyshortcuts?: string;+ /** Whether the button is inserted at the beginning of its group. */+ unshift?: boolean;+ /** Reports whether the button matches the editor state. */+ active?: (context: ToolbarStateContext) => boolean | undefined;+ /** Menu opened by the button. */+ popupMenu?: PopupMenu;+ /** Custom handler for the button shortcut. */+ shortcutAction?: (event: ToolbarEvent) => void;+ /** Whether the button is disabled. */+ disabled?: boolean;+}++type ToolbarButtonAttrs = Omit<+ Partial<ToolbarButton>,+ "action" | "condition" | "title"+> & {+ id?: string;+ action?: (event: ToolbarEvent) => void;+ condition?: () => boolean;+ title?: string;+};++interface ToolbarSeparator {+ type: "separator";+ condition: () => boolean;+}++interface ToolbarGroup {+ group: string;+ buttons: Array<ToolbarButton | ToolbarSeparator>;+}++interface ToolbarContext {+ newToolbarEvent?: (trimLeading?: boolean) => ToolbarEvent;+ send?: (actionName: string, event?: ToolbarEvent) => void;+ appEvents?: {+ trigger(name: string, button: ToolbarButton): void;+ };+}++export interface ToolbarOptions {+ /** Client site settings used to configure toolbar buttons. */+ siteSettings?: Record<string, unknown>;+ /** Browser capabilities used to configure toolbar behavior. */+ capabilities?: Partial<CapabilitiesService>;+ /** Site state used to configure toolbar behavior. */+ site?: Partial<Site>;+ /** Whether the link button is included. */+ showLink?: boolean;+}++function getButtonLabel(labelKey: string, defaultLabel: string): string | null {// use the Font Awesome icon if the label matches the defaultreturn i18n(labelKey) === defaultLabel ? null : labelKey;}@@ -36,7 +182,20 @@ function getButtonLabel(labelKey, defaultLabel) {const DEFAULT_GROUP = "main";export class ToolbarBase {- constructor(opts = {}) {+ /** Buttons and menu options keyed by keyboard shortcut. */+ shortcuts: Record<string, ToolbarButton | PopupMenuOption>;+ /** Editor callbacks used by toolbar actions. */+ context: ToolbarContext;+ /** Ordered groups rendered by the toolbar. */+ groups: ToolbarGroup[];+ /** Client settings used to configure toolbar behavior. */+ siteSettings: Record<string, unknown>;+ /** Browser capabilities used to configure toolbar behavior. */+ capabilities: Partial<CapabilitiesService>;+ /** Site state used to configure toolbar behavior. */+ site: Partial<Site>;++ constructor(opts: ToolbarOptions = {}) {this.shortcuts = {};this.context = {};this.groups = [{ group: DEFAULT_GROUP, buttons: [] }];@@ -45,39 +204,18 @@ export class ToolbarBase {this.site = opts.site || {};}- /**- * @param {Object} buttonAttrs- * @param {string=} buttonAttrs.id- * @param {string=} buttonAttrs.group- * @param {string=} buttonAttrs.tabindex- * @param {string=} buttonAttrs.className- * @param {string=} buttonAttrs.label- * @param {string|Function} buttonAttrs.icon- * @param {string=} buttonAttrs.icon- * @param {string=} buttonAttrs.href- * @param {Function=} buttonAttrs.action- * @param {Function=} buttonAttrs.perform- * @param {boolean=} buttonAttrs.trimLeading- * @param {Object=} buttonAttrs.popupMenu- * @param {boolean=} buttonAttrs.preventFocus- * @param {Function=} buttonAttrs.condition- * @param {Function=} buttonAttrs.sendAction- * @param {Function=} buttonAttrs.shortcutAction custom shortcut action- * @param {boolean=} buttonAttrs.hideShortcutInTitle hide shortcut in title- * @param {string=} buttonAttrs.title- * @param {string=} buttonAttrs.shortcut- * @param {boolean=} buttonAttrs.unshift- * @param {boolean=} buttonAttrs.disabled- * @param {Function=} buttonAttrs.active callback function that receives state and returns boolean- */- addButton(buttonAttrs) {+ /** Adds a button to its configured toolbar group. */+ addButton(buttonAttrs: ToolbarButtonAttrs): void {const group = this.groups.find((item) => item.group === (buttonAttrs.group || DEFAULT_GROUP));- const createdButton = /** @type {ToolbarButton} */ (- Object.defineProperties({}, Object.getOwnPropertyDescriptors(buttonAttrs))- );+ // Object.defineProperties preserves the descriptor-backed input, but its+ // standard-library return type does not retain the source object's shape.+ const createdButton = Object.defineProperties(+ {},+ Object.getOwnPropertyDescriptors(buttonAttrs)+ ) as ToolbarButton;createdButton.preventFocus ??= true;createdButton.tabindex ??= "-1";@@ -163,13 +301,20 @@ export class ToolbarBase {}if (buttonAttrs.unshift) {- group.buttons.unshift(createdButton);+ group!.buttons.unshift(createdButton);} else {- group.buttons.push(createdButton);+ group!.buttons.push(createdButton);}}- addSeparator({ group: groupName = DEFAULT_GROUP, condition }) {+ /** Adds a visual separator to a toolbar group. */+ addSeparator({+ group: groupName = DEFAULT_GROUP,+ condition,+ }: {+ group?: string;+ condition?: () => boolean;+ }): void {const group = this.groups.find((item) => item.group === groupName);if (!group) {@@ -187,9 +332,9 @@ export class ToolbarBase {* Standard editor toolbar with default buttons*/export default class Toolbar extends ToolbarBase {- #listOptions;+ #listOptions?: PopupMenuOption[];- constructor(opts) {+ constructor(opts: ToolbarOptions) {super(opts);this.groups = [@@ -367,7 +512,8 @@ export default class Toolbar extends ToolbarBase {}}- getListPopupMenuOptions() {+ /** Returns the options shown by the list-formatting menu. */+ getListPopupMenuOptions(): PopupMenuOption[] {this.#listOptions ??= [{name: "list-bullet",diff --git a/frontend/discourse/app/lib/textarea-text-manipulation.js b/frontend/discourse/app/lib/textarea-text-manipulation.tssimilarity index 81%rename from frontend/discourse/app/lib/textarea-text-manipulation.jsrename to frontend/discourse/app/lib/textarea-text-manipulation.tsindex 6266882b23b..2e2e5a745de 100644--- a/frontend/discourse/app/lib/textarea-text-manipulation.js+++ b/frontend/discourse/app/lib/textarea-text-manipulation.ts@@ -1,10 +1,23 @@-// @ts-check-import { getOwner, setOwner } from "@ember/owner";+import { type default as Owner, getOwner, setOwner } from "@ember/owner";import { trackedObject } from "@ember/reactive/collections";import { next, schedule } from "@ember/runloop";import { service } from "@ember/service";import { isEmpty } from "@ember/utils";import { caretCoordinates } from "discourse/lib/caret-position";+import type {+ AddTextOptions,+ AutocompleteHandler,+ AutocompleteOptions,+ PlaceholderHandler,+ ReplaceTextOptions,+ SelectedText,+ SelectionOptions,+ SelectTextOptions,+ SurroundOptions,+ TextManipulation,+ ToolbarState,+ UppyFile,+} from "discourse/lib/composer/text-manipulation";import { bind } from "discourse/lib/decorators";import { isTesting } from "discourse/lib/environment";import escapeRegExp from "discourse/lib/escape-regexp";@@ -19,14 +32,49 @@ import {inCodeBlock,setCaretPosition,} from "discourse/lib/utilities";+import type AppEventsService from "discourse/services/app-events";+import type { CapabilitiesService } from "discourse/services/capabilities";+import type ComposerService from "discourse/services/composer";import dAutocomplete from "discourse/ui-kit/modifiers/d-autocomplete";import { i18n } from "discourse-i18n";-/**- * @typedef {import("discourse/lib/composer/text-manipulation").TextManipulation} TextManipulation- * @typedef {import("discourse/lib/composer/text-manipulation").AutocompleteHandler} AutocompleteHandler- * @typedef {import("discourse/lib/composer/text-manipulation").PlaceholderHandler} PlaceholderHandler- */+type SiteSettings = {+ enable_rich_text_paste: boolean;+ code_formatting_style: string;+};++type ComposerServiceWithModel = ComposerService & {+ model: {+ reply: string;+ };+};++interface TextareaTextManipulationOptions {+ markdownOptions?: Record<string, unknown>;+ textarea: HTMLTextAreaElement;+ eventPrefix?: string;+}++interface InsertAtOptions {+ skipFocus?: boolean;+}++interface PlaceholderData {+ uploadPlaceholder: string;+ processingPlaceholder?: string;+}++interface LinkifyMatch {+ index: number;+ lastIndex: number;+ raw: string;+ url: string;+}++interface Linkify {+ test(text: string): boolean;+ match(text: string): LinkifyMatch[] | null;+}const INDENT_DIRECTION_LEFT = "left";const INDENT_DIRECTION_RIGHT = "right";@@ -45,10 +93,11 @@ const FOUR_SPACES_INDENT = "4-spaces-indent";/*** Our head can be a static string or a function that returns a string* based on input (like for numbered lists).- *- * @returns {[string, number]}*/-function getHead(head, prev) {+function getHead(+ head: string | ((previous?: string) => string),+ prev?: string+): [string, number] {if (typeof head === "string") {return [head, head.length];} else {@@ -56,24 +105,35 @@ function getHead(head, prev) {}}-/** @implements {TextManipulation} */-export default class TextareaTextManipulation {- @service appEvents;- @service siteSettings;- @service capabilities;+export default class TextareaTextManipulation implements TextManipulation {+ @service declare appEvents: AppEventsService;++ // TODO(devxp-typescript-pending): use the canonical typed site-settings+ // registry once dynamic client settings are represented in core.+ @service declare siteSettings: SiteSettings;++ @service declare capabilities: CapabilitiesService;allowPreview = true;- eventPrefix;- textarea;+ eventPrefix: string;+ textarea: HTMLTextAreaElement;++ autocompleteHandler: TextareaAutocompleteHandler;+ placeholder: PlaceholderHandler;- autocompleteHandler;- placeholder;+ state = trackedObject<ToolbarState & Record<string, unknown>>({});- /** @type {import("discourse/lib/composer/text-manipulation").ToolbarState} */- state = trackedObject();+ _cachedLinkify?: Linkify;- constructor(owner, { markdownOptions, textarea, eventPrefix = "composer" }) {+ constructor(+ owner: Owner,+ {+ markdownOptions,+ textarea,+ eventPrefix = "composer",+ }: TextareaTextManipulationOptions+ ) {setOwner(this, owner);this.placeholder = new TextareaPlaceholderHandler(owner, this);@@ -88,29 +148,32 @@ export default class TextareaTextManipulation {});}- get value() {+ get value(): string {return this.textarea.value;}// ensures textarea scroll position is correct- blurAndFocus() {+ blurAndFocus(): void {this.textarea?.blur();this.textarea?.focus({ preventScroll: true });}- focus() {+ focus(): void {this.textarea.focus({ preventScroll: true });}- insertBlock(text) {+ insertBlock(text: string): void {this._addBlock(this.getSelected(), text);}- insertText(text, options) {+ insertText(text: string, options?: AddTextOptions): void {this.addText(this.getSelected(), text, options);}- getSelected(trimLeading, opts) {+ getSelected(+ trimLeading?: boolean | null | "",+ opts?: SelectionOptions+ ): SelectedText {const value = this.value;let start = this.textarea.selectionStart;let end = this.textarea.selectionEnd;@@ -142,7 +205,11 @@ export default class TextareaTextManipulation {}}- selectText(from, length, opts = { scroll: true }) {+ selectText(+ from: number,+ length: number,+ opts: SelectTextOptions = { scroll: true }+ ): void {this.textarea.selectionStart = from;this.textarea.selectionEnd = from + length;if (opts.scroll === true || typeof opts.scroll === "number") {@@ -155,7 +222,11 @@ export default class TextareaTextManipulation {}}- replaceText(oldVal, newVal, opts = {}) {+ replaceText(+ oldVal: string,+ newVal: string,+ opts: ReplaceTextOptions = {}+ ): void {const val = this.value;const needleStart = val.indexOf(oldVal);@@ -209,11 +280,22 @@ export default class TextareaTextManipulation {}}- applySurroundSelection(head, tail, exampleKey, opts) {+ applySurroundSelection(+ head: string | ((previous?: string) => string),+ tail: string,+ exampleKey: string,+ opts?: SurroundOptions+ ): void {this.applySurround(this.getSelected(), head, tail, exampleKey, opts);}- applySurround(sel, head, tail, exampleKey, opts) {+ applySurround(+ sel: SelectedText,+ head: string | ((previous?: string) => string),+ tail: string,+ exampleKey: string,+ opts?: SurroundOptions+ ): void {const pre = sel.pre;const post = sel.post;@@ -247,7 +329,7 @@ export default class TextareaTextManipulation {} else {const lines = sel.value.split("\n");- let [hval, hlen] = getHead(head);+ const [hval, hlen] = getHead(head);if (lines.length === 1 &&pre.slice(-tlen) === tail &&@@ -278,7 +360,15 @@ export default class TextareaTextManipulation {}// perform the same operation over many lines of text- _getMultilineContents(lines, head, hval, hlen, tail, tlen, opts) {+ _getMultilineContents(+ lines: string[],+ head: string | ((previous?: string) => string),+ hval: string,+ hlen: number,+ tail: string,+ tlen: number,+ opts?: SurroundOptions+ ): string {let operation = OP.NONE;const applyEmptyLines = opts && opts.applyEmptyLines;@@ -317,7 +407,7 @@ export default class TextareaTextManipulation {.join("\n");}- _addBlock(sel, text) {+ _addBlock(sel: SelectedText, text: string): void {text = (text || "").trim();if (text.length === 0) {return;@@ -351,7 +441,7 @@ export default class TextareaTextManipulation {schedule("afterRender", this, this.blurAndFocus);}- applyLink(url) {+ applyLink(url: string): void {const sel = this.getSelected();if (sel.start === sel.end) {return;@@ -360,7 +450,7 @@ export default class TextareaTextManipulation {this.blurAndFocus();}- addText(sel, text, options) {+ addText(sel: SelectedText, text: string, options?: AddTextOptions): void {if (options && options.ensureSpace) {if ((sel.pre + "").length > 0) {if (!sel.pre.match(/\s$/)) {@@ -378,33 +468,42 @@ export default class TextareaTextManipulation {this.blurAndFocus();}- _insertAt(start, end, text, opts = {}) {+ _insertAt(+ start: number,+ end: number,+ text: string,+ opts: InsertAtOptions = {}+ ): void {insertAtTextarea(this.textarea, start, end, text, opts);}- extractTable(text) {+ extractTable(text: string): string | null {if (text.endsWith("\n")) {text = text.substring(0, text.length - 1);}- text = text.split("");+ const characters = text.split("");let cell = false;- text.forEach((char, index) => {+ characters.forEach((char, index) => {if (char === "\n" && cell) {- text[index] = "\r";+ characters[index] = "\r";}if (char === '"') {- text[index] = "";+ characters[index] = "";cell = !cell;}});- let rows = text.join("").replace(/\r/g, "<br>").split("\n");+ const rows = characters.join("").replace(/\r/g, "<br>").split("\n");if (rows.length > 1) {const columns = rows.map((r) => r.split("\t").length);const isTable =- columns.reduce((a, b) => a && columns[0] === b && b > 1) &&+ columns+ .slice(1)+ .reduce<+ number | boolean+ >((a, b) => a && columns[0] === b && b > 1, columns[0]) &&!(columns[0] === 2 && rows[0].split("\t")[0].match(/^•$|^\d+.$/)); // to skip tab delimited listsif (isTable) {@@ -419,25 +518,27 @@ export default class TextareaTextManipulation {return null;}- isInside(text, regex) {+ isInside(text: string, regex: RegExp): number | null {const matches = text.match(regex);return matches && matches.length % 2;}@bind- async paste(e) {+ async paste(e: ClipboardEvent): Promise<void> {const isComposer = this.textarea === e.target;if (!isComposer && !isTesting()) {return;}+ // eslint-disable-next-line prefer-constlet { clipboard, canPasteHtml, canUpload } = clipboardHelpers(e, {siteSettings: this.siteSettings,canUpload: isComposer,});let plainText = clipboard.getData("text/plain");+ // eslint-disable-next-line prefer-constlet html = clipboard.getData("text/html");let handled = false;@@ -455,6 +556,7 @@ export default class TextareaTextManipulation {plainText = plainText.replace(/\r/g, "");const table = this.extractTable(plainText);if (table) {+ // eslint-disable-next-line @typescript-eslint/no-unused-expressionsthis.eventPrefix? this.appEvents.trigger(`${this.eventPrefix}:insert-text`, table): this.insertText(table);@@ -511,6 +613,7 @@ export default class TextareaTextManipulation {}if (isComposer) {+ // eslint-disable-next-line @typescript-eslint/no-unused-expressionsthis.eventPrefix? this.appEvents.trigger(`${this.eventPrefix}:insert-text`,@@ -520,6 +623,7 @@ export default class TextareaTextManipulation {handled = true;}} else if (plainText && isComposer) {+ // eslint-disable-next-line @typescript-eslint/no-unused-expressionsthis.eventPrefix? this.appEvents.trigger(`${this.eventPrefix}:insert-text`, plainText): this.insertText(plainText);@@ -537,7 +641,7 @@ export default class TextareaTextManipulation {* until the limit, or until a character that is _not_* the provided one is encountered.*/- _deindentLine(str, char, limit) {+ _deindentLine(str: string, char: string, limit: number): string {let eaten = 0;for (let i = 0; i < str.length; i++) {if (eaten < limit && str[i] === char) {@@ -549,7 +653,7 @@ export default class TextareaTextManipulation {return str;}- _updateListNumbers(text, currentNumber) {+ _updateListNumbers(text: string, currentNumber: number): string {return text.split("\n").map((line) => {@@ -566,11 +670,11 @@ export default class TextareaTextManipulation {.join("\n");}- #isAfterStartedCodeFence(beforeText) {+ #isAfterStartedCodeFence(beforeText: string): number | null {return this.isInside(beforeText, /(^|\n)```/g);}- maybeContinueList() {+ maybeContinueList(): void {const offset = caretPosition(this.textarea);const text = this.value;const lines = text.substring(0, offset).split("\n");@@ -678,7 +782,7 @@ export default class TextareaTextManipulation {}}- indentSelection(direction) {+ indentSelection(direction: "left" | "right"): boolean | void {if (![INDENT_DIRECTION_LEFT, INDENT_DIRECTION_RIGHT].includes(direction)) {return;}@@ -694,8 +798,8 @@ export default class TextareaTextManipulation {spaces, and for the cases with no tabs it's safer to use spaces*/let indentationSteps, indentationChar;- let linesStartingWithTabCount = value.match(/^\t/gm)?.length || 0;- let linesStartingWithSpaceCount = value.match(/^ /gm)?.length || 0;+ const linesStartingWithTabCount = value.match(/^\t/gm)?.length || 0;+ const linesStartingWithSpaceCount = value.match(/^ /gm)?.length || 0;if (linesStartingWithTabCount > linesStartingWithSpaceCount) {indentationSteps = 1;indentationChar = "\t";@@ -755,8 +859,8 @@ export default class TextareaTextManipulation {}@bind- emojiSelected(code) {- let selected = this.getSelected();+ emojiSelected(code: string): void {+ const selected = this.getSelected();const captures = selected.pre.match(/\B:([\p{L}\p{N}_]*)$/u);if (isEmpty(captures)) {@@ -766,7 +870,7 @@ export default class TextareaTextManipulation {this.addText(selected, `:${code}:`);}} else {- let numOfRemovedChars = captures[1].length;+ const numOfRemovedChars = captures[1].length;this._insertAt(selected.start - numOfRemovedChars,selected.end,@@ -775,12 +879,12 @@ export default class TextareaTextManipulation {}}- async inCodeBlock() {+ async inCodeBlock(): Promise<boolean> {return await this.autocompleteHandler.inCodeBlock();}@bind- toggleDirection() {+ toggleDirection(): void {const currentDir = this.textarea.getAttribute("dir") || siteDir();const newDir = currentDir === "ltr" ? "rtl" : "ltr";@@ -789,7 +893,12 @@ export default class TextareaTextManipulation {}@bind- applyList(sel, head, exampleKey, opts) {+ applyList(+ sel: SelectedText,+ head: string | ((previous?: string) => string),+ exampleKey: string,+ opts?: SurroundOptions+ ): void {if (sel.value.includes("\n")) {this.applySurround(sel, head, "", exampleKey, opts);} else {@@ -856,14 +965,14 @@ export default class TextareaTextManipulation {}@bind- applyHeading(sel, level) {+ applyHeading(sel: SelectedText, level: number): void {if (level > 0) {this.applyList(sel, "#".repeat(level) + " ", "heading_text", {excludeHeadInSelection: true,});} else {// Remove heading when the Paragraph level (0) is selected.- const currentHeadingLevel = sel.lineVal.search(/[^#]/);+ const currentHeadingLevel = sel.lineVal!.search(/[^#]/);if (currentHeadingLevel >= 0) {// When you apply the list with the same head chars, then they// are removed, so we can use the same function.@@ -877,7 +986,7 @@ export default class TextareaTextManipulation {}@bind- formatCode() {+ formatCode(): void {const sel = this.getSelected("", { lineVal: true });const selValue = sel.value;const hasNewLine = selValue.includes("\n");@@ -911,7 +1020,7 @@ export default class TextareaTextManipulation {}}- putCursorAtEnd() {+ putCursorAtEnd(): void {if (this.capabilities.isIOS) {putCursorAtEnd(this.textarea);} else {@@ -923,9 +1032,10 @@ export default class TextareaTextManipulation {/*** Wraps consecutive upload placeholders in grid tags.- * @param {string[]} consecutiveImages - Array of consecutive image filenames to wrap+ *+ * @param consecutiveImages - Consecutive image filenames to wrap.*/- autoGridImages(consecutiveImages) {+ autoGridImages(consecutiveImages: string[]): void {if (isEmpty(consecutiveImages)) {return;}@@ -951,8 +1061,8 @@ export default class TextareaTextManipulation {"g");- const matches = reply.match(uploadingImagePattern) || [];- const foundImages = [];+ const matches: string[] = reply.match(uploadingImagePattern) || [];+ const foundImages: string[] = [];const existingGridPattern = /\[grid\]([\s\S]*?)\[\/grid\]/g;const gridMatches = reply.match(existingGridPattern);@@ -1006,7 +1116,7 @@ export default class TextareaTextManipulation {}}- autocomplete(options) {+ autocomplete(options: AutocompleteOptions): unknown {return dAutocomplete.setupAutocomplete(getOwner(this),this.textarea,@@ -1017,12 +1127,12 @@ export default class TextareaTextManipulation {}function insertAtTextarea(- textarea,- start,- end,- text,- { skipFocus = false } = {}-) {+ textarea: HTMLTextAreaElement,+ start: number,+ end: number,+ text: string,+ { skipFocus = false }: InsertAtOptions = {}+): void {if (skipFocus && document.activeElement !== textarea) {textarea.setRangeText(text, start, end, "preserve");textarea.dispatchEvent(new InputEvent("input", { bubbles: true }));@@ -1038,54 +1148,53 @@ function insertAtTextarea(}}-/** @implements {AutocompleteHandler} */-export class TextareaAutocompleteHandler {- textarea;+export class TextareaAutocompleteHandler implements AutocompleteHandler {+ textarea: HTMLTextAreaElement;- constructor(textarea) {+ constructor(textarea: HTMLTextAreaElement) {this.textarea = textarea;}- getValue() {+ getValue(): string {return this.textarea.value;}- replaceTerm(start, end, term) {+ replaceTerm(start: number, end: number, term: string): void {const space =this.getValue().substring(end + 1, end + 2) === " " ? "" : " ";insertAtTextarea(this.textarea, start, end + 1, term + space);setCaretPosition(this.textarea, start + 1 + term.trim().length);}- getCaretPosition() {+ getCaretPosition(): number {return caretPosition(this.textarea);}- getCaretCoords(start) {+ getCaretCoords(start: number): { left: number; top: number } {return caretCoordinates(this.textarea, { pos: start + 1 });}- async inCodeBlock() {+ async inCodeBlock(): Promise<boolean> {return await inCodeBlock(this.textarea.value, caretPosition(this.textarea));}}-/** @implements {PlaceholderHandler} */-class TextareaPlaceholderHandler {- @service composer;+class TextareaPlaceholderHandler implements PlaceholderHandler {+ // TODO(devxp-typescript-pending): remove the local model refinement once the+ // composer service exposes its current model type.+ @service declare composer: ComposerServiceWithModel;- /** @type {TextareaTextManipulation} */- textManipulation;+ textManipulation: TextareaTextManipulation;- #placeholders = {};+ #placeholders: Record<string, PlaceholderData> = {};- constructor(owner, textManipulation) {+ constructor(owner: Owner, textManipulation: TextareaTextManipulation) {setOwner(this, owner);this.textManipulation = textManipulation;}- #uploadPlaceholder(file, currentMarkdown) {+ #uploadPlaceholder(file: UppyFile, currentMarkdown: string): string {const clipboard = i18n("clipboard");const uploadFilenamePlaceholder = this.#uploadFilenamePlaceholder(file,@@ -1103,7 +1212,7 @@ class TextareaPlaceholderHandler {return placeholder;}- #cursorIsOnEmptyLine() {+ #cursorIsOnEmptyLine(): boolean {const selectionStart = this.textManipulation.textarea.selectionStart;return (selectionStart === 0 ||@@ -1111,7 +1220,7 @@ class TextareaPlaceholderHandler {);}- #uploadFilenamePlaceholder(file, currentMarkdown) {+ #uploadFilenamePlaceholder(file: UppyFile, currentMarkdown: string): string {const filename = this.#filenamePlaceholder(file);// when adding two separate files with the same filename search for matching@@ -1128,8 +1237,8 @@ class TextareaPlaceholderHandler {// capturing group and apply +1 to the placeholderconst lastMatch = matchingPlaceholder[matchingPlaceholder.length - 1];const regex = new RegExp(regexString);- const orderNr = regex.exec(lastMatch)[1]- ? parseInt(regex.exec(lastMatch)[1], 10) + 1+ const orderNr = regex.exec(lastMatch)![1]+ ? parseInt(regex.exec(lastMatch)![1]!, 10) + 1: 1;return `${filename}(${orderNr})`;}@@ -1137,11 +1246,11 @@ class TextareaPlaceholderHandler {return filename;}- #filenamePlaceholder(data) {+ #filenamePlaceholder(data: UppyFile): string {return data.name.replace(/\u200B-\u200D\uFEFF]/g, "");}- insert(file) {+ insert(file: UppyFile): void {const placeholder = this.#uploadPlaceholder(file,this.composer.model.reply@@ -1152,8 +1261,8 @@ class TextareaPlaceholderHandler {this.#placeholders[file.id] = { uploadPlaceholder: placeholder };}- progress(file) {- let placeholderData = this.#placeholders[file.id];+ progress(file: UppyFile): void {+ const placeholderData = this.#placeholders[file.id]!;placeholderData.processingPlaceholder = `[${i18n("processing_filename", {filename: file.name,})}]()\n`;@@ -1172,21 +1281,21 @@ class TextareaPlaceholderHandler {);}- progressComplete(file) {- let placeholderData = this.#placeholders[file.id];+ progressComplete(file: UppyFile): void {+ const placeholderData = this.#placeholders[file.id]!;this.textManipulation.replaceText(placeholderData.processingPlaceholder,placeholderData.uploadPlaceholder);}- cancelAll() {+ cancelAll(): void {Object.values(this.#placeholders).forEach((data) => {this.textManipulation.replaceText(data.uploadPlaceholder, "");});}- cancel(file) {+ cancel(file: UppyFile): void {if (this.#placeholders[file.id]) {this.textManipulation.replaceText(this.#placeholders[file.id].uploadPlaceholder,@@ -1195,7 +1304,7 @@ class TextareaPlaceholderHandler {}}- success(file, markdown) {+ success(file: UppyFile, markdown: string): void {this.textManipulation.replaceText(this.#placeholders[file.id].uploadPlaceholder.trim(),markdowndiff --git a/frontend/discourse/app/lib/types/pretty-text-upload-short-url.d.ts b/frontend/discourse/app/lib/types/pretty-text-upload-short-url.d.tsnew file mode 100644index 00000000000..cc513e01939--- /dev/null+++ b/frontend/discourse/app/lib/types/pretty-text-upload-short-url.d.ts@@ -0,0 +1,16 @@+// TODO(devxp-typescript-pending): the pretty-text package ships no type+// declarations and is not mapped into this project's type graph, so this+// ambient declaration types the one symbol consumed by the rich editor as a+// stopgap. A `declare module` for an otherwise-unresolvable module must live+// in a `.d.ts` (in a `.ts` module it becomes an augmentation and fails with+// TS2664). The proper fix is to wire pretty-text into the type-checking+// pipeline and convert the source module to TypeScript; remove this file once+// pretty-text/upload-short-url provides its own types.+declare module "pretty-text/upload-short-url" {+ interface CachedUploadUrl {+ url?: string;+ short_path?: string;+ }++ export function lookupCachedUploadUrl(shortUrl: string): CachedUploadUrl;+}diff --git a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjs b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gtssimilarity index 64%rename from frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjsrename to frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gtsindex 8d88199f312..3509f164be0 100644--- a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gjs+++ b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts@@ -1,4 +1,3 @@-// @ts-checkimport Component from "@glimmer/component";import { action } from "@ember/object";import { getOwner } from "@ember/owner";@@ -9,6 +8,7 @@ import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";import { next } from "@ember/runloop";import { service } from "@ember/service";import "../extensions/register-default";+import type { ComponentLike } from "@glint/template";import * as ProsemirrorCommands from "prosemirror-commands";import { baseKeymap } from "prosemirror-commands";import { dropCursor } from "prosemirror-dropcursor";@@ -16,17 +16,39 @@ import { gapCursor } from "prosemirror-gapcursor";import * as ProsemirrorHistory from "prosemirror-history";import { history } from "prosemirror-history";import { keymap } from "prosemirror-keymap";+import type {+ Fragment,+ Node,+ NodeType,+ Schema,+ Slice,+} from "prosemirror-model";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 { type Command, EditorState, type Plugin } from "prosemirror-state";import * as ProsemirrorTransform from "prosemirror-transform";import * as ProsemirrorView from "prosemirror-view";import { EditorView } from "prosemirror-view";-import { getExtensions } from "discourse/lib/composer/rich-editor-extensions";+import type DialogService from "discourse/dialog-holder/services/dialog";+import type MenuService from "discourse/float-kit/services/menu";+import type ToastsService from "discourse/float-kit/services/toasts";+import {+ getExtensions,+ type PluginParams,+ type RichEditorExtension,+} from "discourse/lib/composer/rich-editor-extensions";+import type { TextManipulation as TextManipulationInterface } from "discourse/lib/composer/text-manipulation";+import type { ToolbarBase } from "discourse/lib/composer/toolbar";import { bind } from "discourse/lib/decorators";+import type Session from "discourse/models/session";+import type Site from "discourse/models/site";+import type User from "discourse/models/user";import forceScrollingElementPosition from "discourse/modifiers/force-scrolling-element-position";import { focusOffScreen } from "discourse/modifiers/prevent-scroll-on-focus";+import type AppEventsService from "discourse/services/app-events";+import type { CapabilitiesService } from "discourse/services/capabilities";+import type ModalService from "discourse/services/modal";import { i18n } from "discourse-i18n";import { authorizesOneOrMoreExtensions } from "../../../lib/uploads";import { buildCommands, buildCustomState } from "../core/commands";@@ -37,63 +59,103 @@ import { extractNodeViews, extractPlugins } from "../core/plugin";import { createSchema } from "../core/schema";import Serializer from "../core/serializer";import placeholder from "../extensions/placeholder";+import type GlimmerNodeView from "../lib/glimmer-node-view";import * as utils from "../lib/plugin-utils";-import TextManipulation from "../lib/text-manipulation";+import TextManipulation, {+ type CustomState,+ type EditorCommands,+} from "../lib/text-manipulation";const AUTOCOMPLETE_KEY_DOWN_SUPPRESS = ["Enter", "Tab", "ArrowDown", "ArrowUp"];-/**- * @typedef ProsemirrorEditorArgs- * @property {string} [value] The markdown content to be rendered in the editor- * @property {string} [placeholder] The placeholder text to be displayed when the editor is empty- * @property {boolean} [disabled] Whether the editor should be disabled- * @property {Record<string, () => void>} [keymap] A mapping of keybindings to commands- * @property {(value: { target: { value: string } }) => void} [change] A callback called when the editor content changes- * @property {() => void} [focusIn] A callback called when the editor gains focus- * @property {() => void} [focusOut] A callback called when the editor loses focus- * @property {(textManipulation: TextManipulation) => undefined | (() => void)} [onSetup] A callback called when the editor is set up, may return a destructor- * @property {number} [topicId] The ID of the topic being edited, if any- * @property {number} [categoryId] The ID of the category of the topic being edited, if any- * @property {string} [class] The class to be added to the ProseMirror contentEditable editor- * @property {boolean} [includeDefault] If default node and mark spec/parse/serialize/inputRules definitions from ProseMirror should be included- * @property {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension[]} [extensions] A list of extensions to be used with the editor INSTEAD of the ones registered through the API- * @property {(toolbar: import("discourse/lib/composer/toolbar").ToolbarBase) => void} [replaceToolbar] A function that replaces the default toolbar in a container with a custom/temporary one- * @property {() => void} [toggleRichEditor] A callback to toggle the rich editor on and off if in such a context- */--/**- * @typedef ProsemirrorEditorSignature- * @property {ProsemirrorEditorArgs} Args- */--/** @typedef {import("../lib/glimmer-node-view").default} GlimmerNodeView */--/**- * @extends {Component<ProsemirrorEditorSignature>}- */-export default class ProsemirrorEditor extends Component {- @service session;- @service dialog;- @service menu;- @service capabilities;- @service modal;- @service toasts;- @service site;- @service siteSettings;- @service appEvents;- @service currentUser;-- schema = createSchema(this.extensions, this.args.includeDefault);- view;-- /** @type {Array<GlimmerNodeView>} */- glimmerNodeViews = trackedArray();- #lastSerialized;- /** @type {undefined | (() => void)} */- #destructor;-- /** @type {import("discourse/lib/composer/rich-editor-extensions").PluginParams} */- get pluginParams() {+interface ProsemirrorEditorSignature {+ Args: {+ /** Markdown content displayed in the editor. */+ value?: string;+ /** Placeholder displayed when the editor is empty. */+ placeholder?: string;+ /** Whether the editor is read-only. */+ disabled?: boolean;+ /** Additional keyboard shortcuts keyed by shortcut expression. */+ keymap?: Record<string, () => boolean | void>;+ /** Called when the serialized markdown changes. */+ change?: (value: { target: { value: string } }) => void;+ /** Called when the editor receives focus. */+ focusIn?: () => void;+ /** Called when the editor loses focus. */+ focusOut?: () => void;+ /** Called with the editor's text operations after setup. */+ onSetup?: (+ textManipulation: TextManipulationInterface+ ) => undefined | (() => void);+ /** ID of the topic being edited. */+ topicId?: number;+ /** ID of the category being edited. */+ categoryId?: number;+ /** Class added to the editable element. */+ class?: string;+ /** Whether the default schema and editor behavior are included. */+ includeDefault?: boolean;+ /** Extensions used instead of the globally registered extensions. */+ extensions?: RichEditorExtension[];+ /** Replaces or restores the toolbar displayed by the editor container. */+ replaceToolbar?: (toolbar: ToolbarBase | null, owner?: ToolbarBase) => void;+ /** Toggles between the rich and plain-text editors. */+ toggleRichEditor?: () => void;+ };+}++type SiteSettings = Record<string, unknown>;++type NodeViewComponent = ComponentLike<{+ Args: {+ node: Node;+ view: EditorView;+ getPos: () => number | undefined;+ dom: HTMLElement;+ pluginParams: PluginParams;+ onSetup: (instance: unknown) => void;+ };+}>;++type RenderableGlimmerNodeView = Omit<+ GlimmerNodeView,+ "component" | "dom" | "getPos" | "pluginParams" | "setComponentInstance"+> & {+ component: NodeViewComponent;+ dom: HTMLElement;+ getPos: () => number | undefined;+ pluginParams: PluginParams;+ setComponentInstance: (instance: unknown) => void;+};++export default class ProsemirrorEditor extends Component<ProsemirrorEditorSignature> {+ @service declare session: Session;+ @service declare dialog: DialogService;+ @service declare menu: MenuService;+ @service declare capabilities: CapabilitiesService;+ @service declare modal: ModalService;+ @service declare toasts: ToastsService;+ @service declare site: Site;++ // TODO(devxp-typescript-pending): use the canonical typed site-settings+ // registry once dynamic client settings are represented in core.+ @service declare siteSettings: SiteSettings;++ @service declare appEvents: AppEventsService;+ @service declare currentUser: User;++ schema: Schema = createSchema(this.extensions, this.args.includeDefault);+ view: EditorView;+ declare parser: Parser;+ declare serializer: Serializer;+ declare textManipulation: TextManipulation;++ glimmerNodeViews = trackedArray<RenderableGlimmerNodeView>();+ #lastSerialized?: string;+ #destructor?: () => void;++ get pluginParams(): PluginParams {return {utils: {...utils,@@ -125,17 +187,22 @@ export default class ProsemirrorEditor extends Component {appEvents: this.appEvents,dialog: this.dialog,replaceToolbar: this.args.replaceToolbar,- addGlimmerNodeView: (nodeView) => this.glimmerNodeViews.push(nodeView),+ // TODO(devxp-typescript-pending): remove the cast once GlimmerNodeView's+ // component field has a typed invocation signature.+ addGlimmerNodeView: (nodeView) =>+ this.glimmerNodeViews.push(nodeView as RenderableGlimmerNodeView),removeGlimmerNodeView: (nodeView) =>this.glimmerNodeViews.splice(- this.glimmerNodeViews.indexOf(nodeView),+ this.glimmerNodeViews.indexOf(+ nodeView as RenderableGlimmerNodeView+ ),1),}),};}- get extensions() {+ get extensions(): RichEditorExtension[] {const extensions = this.args.extensions ?? getExtensions();// enforcing core extensions@@ -144,9 +211,9 @@ export default class ProsemirrorEditor extends Component {: [placeholder, ...extensions];}- get keymapFromArgs() {- const replacements = { tab: "Tab" };- const result = {};+ get keymapFromArgs(): Record<string, Command> {+ const replacements: Record<string, string> = { tab: "Tab" };+ const result: Record<string, Command> = {};for (const [key, value] of Object.entries(this.args.keymap ?? {})) {const pmKey = key.split("+")@@ -158,7 +225,7 @@ export default class ProsemirrorEditor extends Component {}@action- handleAsyncPlugin(plugin) {+ handleAsyncPlugin(plugin: Plugin): void {const state = this.view.state.reconfigure({plugins: [...this.view.state.plugins, plugin],});@@ -167,7 +234,7 @@ export default class ProsemirrorEditor extends Component {}@action- setup(container) {+ setup(container: HTMLElement): void {const params = this.pluginParams;const plugins = [@@ -266,8 +333,14 @@ export default class ProsemirrorEditor extends Component {convertToMarkdown: this.convertToMarkdown,splitNonEmptyLines: this.splitNonEmptyLines,buildListNode: this.buildListNode,- commands: buildCommands(this.extensions, params, this.view),- customState: buildCustomState(this.extensions, params),+ // TODO(devxp-typescript-pending): remove these casts when the command+ // builders are converted and export their return types.+ commands: buildCommands(+ this.extensions,+ params,+ this.view+ ) as EditorCommands,+ customState: buildCustomState(this.extensions, params) as CustomState,});this.#destructor = this.args.onSetup?.(this.textManipulation);@@ -278,7 +351,7 @@ export default class ProsemirrorEditor extends Component {}@bind- convertFromMarkdown(markdown) {+ convertFromMarkdown(markdown: string): Node {try {return this.parser.convert(this.schema, markdown);} catch (e) {@@ -308,12 +381,16 @@ export default class ProsemirrorEditor extends Component {}@bind- splitNonEmptyLines(text) {+ splitNonEmptyLines(text: string): string[] {return text.split(/\r?\n/).filter((line) => line.trim().length > 0);}@bind- buildListNode(schema, listType, lines) {+ buildListNode(+ schema: Schema,+ listType: NodeType | string,+ lines: string[]+ ): Node {const listItems = lines.map((line) =>schema.nodes.list_item.create(null, [schema.nodes.paragraph.create(@@ -331,7 +408,7 @@ export default class ProsemirrorEditor extends Component {}@bind- convertFromValue() {+ convertFromValue(): void {const value = this.args.value ?? "";// Ignore the markdown we just serialized@@ -363,18 +440,18 @@ export default class ProsemirrorEditor extends Component {}@bind- convertToMarkdown(doc) {+ convertToMarkdown(doc: Node | Fragment | Slice): string {return this.serializer.convert(doc);}@action- teardown() {+ teardown(): void {this.#destructor?.();this.view.destroy();}@action- updateContext(element, [key, value]) {+ updateContext(element: HTMLElement, [key, value]: [string, unknown]): void {this.view.dispatch(this.view.state.tr.setMeta("addToHistory", false)diff --git a/frontend/discourse/app/static/prosemirror/extensions/code.js b/frontend/discourse/app/static/prosemirror/extensions/code.tssimilarity index 54%rename from frontend/discourse/app/static/prosemirror/extensions/code.jsrename to frontend/discourse/app/static/prosemirror/extensions/code.tsindex 8a7cb2c87f5..9ac64157395 100644--- a/frontend/discourse/app/static/prosemirror/extensions/code.js+++ b/frontend/discourse/app/static/prosemirror/extensions/code.ts@@ -1,9 +1,7 @@-// @ts-check-import codemark from "prosemirror-codemark";+import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";-/** @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension} */-const extension = {+const extension: RichEditorExtension = {plugins({ schema }) {return codemark({ markType: schema.marks.code });},diff --git a/frontend/discourse/app/static/prosemirror/extensions/hard-break.js b/frontend/discourse/app/static/prosemirror/extensions/hard-break.tssimilarity index 59%rename from frontend/discourse/app/static/prosemirror/extensions/hard-break.jsrename to frontend/discourse/app/static/prosemirror/extensions/hard-break.tsindex f0638518595..1ad6c229608 100644--- a/frontend/discourse/app/static/prosemirror/extensions/hard-break.js+++ b/frontend/discourse/app/static/prosemirror/extensions/hard-break.ts@@ -1,9 +1,7 @@-// @ts-check-import { schema } from "prosemirror-markdown";+import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";-/** @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension} */-const extension = {+const extension: RichEditorExtension = {nodeSpec: {hard_break: {...schema.nodes.hard_break.spec,diff --git a/frontend/discourse/app/static/prosemirror/extensions/link.js b/frontend/discourse/app/static/prosemirror/extensions/link.tssimilarity index 98%rename from frontend/discourse/app/static/prosemirror/extensions/link.jsrename to frontend/discourse/app/static/prosemirror/extensions/link.tsindex 8f679fcaef1..8b75b384ec6 100644--- a/frontend/discourse/app/static/prosemirror/extensions/link.js+++ b/frontend/discourse/app/static/prosemirror/extensions/link.ts@@ -1,13 +1,11 @@-// @ts-check-import { ReplaceAroundStep, ReplaceStep } from "prosemirror-transform";+import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";import {getChangedRanges,markInputRule,} from "discourse/static/prosemirror/lib/plugin-utils";-/** @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension} */-const extension = {+const extension: RichEditorExtension = {markSpec: {link: {attrs: {diff --git a/frontend/discourse/app/static/prosemirror/extensions/override-drag-ghost.js b/frontend/discourse/app/static/prosemirror/extensions/override-drag-ghost.tssimilarity index 94%rename from frontend/discourse/app/static/prosemirror/extensions/override-drag-ghost.jsrename to frontend/discourse/app/static/prosemirror/extensions/override-drag-ghost.tsindex e5f532e56d2..65a7b6f50b8 100644--- a/frontend/discourse/app/static/prosemirror/extensions/override-drag-ghost.js+++ b/frontend/discourse/app/static/prosemirror/extensions/override-drag-ghost.ts@@ -1,7 +1,6 @@-// @ts-check-import { Fragment, Slice } from "prosemirror-model";import { NodeSelection, Plugin } from "prosemirror-state";+import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";// A 1px transparent image to use as drag image// This prevents the default drag image from appearing, the image gets in the way and make it harder@@ -42,11 +41,8 @@ const dropSelectionPlugin = new Plugin({/*** Overrides the default drag image with an empty image, giving room for the drop cursor.- *- * @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension}- *- **/-const extension = {+ */+const extension: RichEditorExtension = {plugins: [dropSelectionPlugin,{diff --git a/frontend/discourse/app/static/prosemirror/extensions/placeholder.js b/frontend/discourse/app/static/prosemirror/extensions/placeholder.tssimilarity index 85%rename from frontend/discourse/app/static/prosemirror/extensions/placeholder.jsrename to frontend/discourse/app/static/prosemirror/extensions/placeholder.tsindex 9914d0932df..c56adce8044 100644--- a/frontend/discourse/app/static/prosemirror/extensions/placeholder.js+++ b/frontend/discourse/app/static/prosemirror/extensions/placeholder.ts@@ -1,11 +1,10 @@-// @ts-check+import type { Node } from "prosemirror-model";+import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";/*** This extension is considered a "core" extension, it's autoloaded by ProsemirrorEditor- *- * @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension}*/-const extension = {+const extension: RichEditorExtension = {plugins({pmState: { Plugin, PluginKey },pmView: { Decoration, DecorationSet },@@ -52,7 +51,7 @@ const extension = {},};-function isEmptyParagraph(node) {+function isEmptyParagraph(node: Node): boolean {return node.type.name === "paragraph" && node.nodeSize === 2;}diff --git a/frontend/discourse/app/static/prosemirror/extensions/register-default.js b/frontend/discourse/app/static/prosemirror/extensions/register-default.tssimilarity index 93%rename from frontend/discourse/app/static/prosemirror/extensions/register-default.jsrename to frontend/discourse/app/static/prosemirror/extensions/register-default.tsindex 2d86af0affc..4fcea2f860c 100644--- a/frontend/discourse/app/static/prosemirror/extensions/register-default.js+++ b/frontend/discourse/app/static/prosemirror/extensions/register-default.ts@@ -1,8 +1,7 @@-// @ts-check-import {markDefaultExtensionsRegistered,registerRichEditorExtension,+ type RichEditorExtension,} from "discourse/lib/composer/rich-editor-extensions";import bulletList from "./bullet-list";import code from "./code";@@ -36,10 +35,8 @@ import wrap from "./wrap";/*** List of default extensions* ProsemirrorEditor autoloads them when includeDefault=true (the default)- *- * @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension[]}*/-const defaultExtensions = [+const defaultExtensions: RichEditorExtension[] = [emoji,image,onebox,diff --git a/frontend/discourse/app/static/prosemirror/extensions/strikethrough.js b/frontend/discourse/app/static/prosemirror/extensions/strikethrough.tssimilarity index 85%rename from frontend/discourse/app/static/prosemirror/extensions/strikethrough.jsrename to frontend/discourse/app/static/prosemirror/extensions/strikethrough.tsindex 3666e991ddd..07fd759b8e6 100644--- a/frontend/discourse/app/static/prosemirror/extensions/strikethrough.js+++ b/frontend/discourse/app/static/prosemirror/extensions/strikethrough.ts@@ -1,7 +1,6 @@-// @ts-check+import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";-/** @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension} */-const extension = {+const extension: RichEditorExtension = {markSpec: {strikethrough: {before: "link",diff --git a/frontend/discourse/app/static/prosemirror/extensions/trailing-inline-space.js b/frontend/discourse/app/static/prosemirror/extensions/trailing-inline-space.tssimilarity index 91%rename from frontend/discourse/app/static/prosemirror/extensions/trailing-inline-space.jsrename to frontend/discourse/app/static/prosemirror/extensions/trailing-inline-space.tsindex 0f2456e5c06..ba092a44bc8 100644--- a/frontend/discourse/app/static/prosemirror/extensions/trailing-inline-space.js+++ b/frontend/discourse/app/static/prosemirror/extensions/trailing-inline-space.ts@@ -1,9 +1,9 @@-// @ts-check-import { splitBlock } from "prosemirror-commands";+import type { Node, ResolvedPos } from "prosemirror-model";import { TextSelection } from "prosemirror-state";+import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";-function isInlineContainer(node) {+function isInlineContainer(node: Node): boolean {return (node.isInline &&!node.isText &&@@ -12,7 +12,7 @@ function isInlineContainer(node) {);}-function findInlineContainerDepth($from) {+function findInlineContainerDepth($from: ResolvedPos): number | null {for (let depth = $from.depth; depth > 0; depth--) {if (isInlineContainer($from.node(depth))) {return depth;@@ -21,8 +21,7 @@ function findInlineContainerDepth($from) {return null;}-/** @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension} */-const extension = {+const extension: RichEditorExtension = {keymap: () => ({Enter: (state, dispatch) => {const selection = state.selection;diff --git a/frontend/discourse/app/static/prosemirror/extensions/trailing-paragraph.js b/frontend/discourse/app/static/prosemirror/extensions/trailing-paragraph.tssimilarity index 71%rename from frontend/discourse/app/static/prosemirror/extensions/trailing-paragraph.jsrename to frontend/discourse/app/static/prosemirror/extensions/trailing-paragraph.tsindex 81d66b21db7..f63115531f8 100644--- a/frontend/discourse/app/static/prosemirror/extensions/trailing-paragraph.js+++ b/frontend/discourse/app/static/prosemirror/extensions/trailing-paragraph.ts@@ -1,7 +1,7 @@-// @ts-check+import type { EditorState, Transaction } from "prosemirror-state";+import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";-/** @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension} */-const extension = {+const extension: RichEditorExtension = {plugins({ pmState: { Plugin, PluginKey } }) {const plugin = new PluginKey("trailing-paragraph");@@ -35,11 +35,11 @@ const extension = {},};-function isLastChildParagraph(state) {+function isLastChildParagraph(state: EditorState | Transaction): boolean {const { doc } = state;const lastChild = doc.lastChild;- return lastChild.type.name === "paragraph";+ return lastChild!.type.name === "paragraph";}export default extension;diff --git a/frontend/discourse/app/static/prosemirror/extensions/underline.js b/frontend/discourse/app/static/prosemirror/extensions/underline.tssimilarity index 81%rename from frontend/discourse/app/static/prosemirror/extensions/underline.jsrename to frontend/discourse/app/static/prosemirror/extensions/underline.tsindex 0c2cc551e5b..2fc1ef8e5be 100644--- a/frontend/discourse/app/static/prosemirror/extensions/underline.js+++ b/frontend/discourse/app/static/prosemirror/extensions/underline.ts@@ -1,7 +1,6 @@-// @ts-check+import type { RichEditorExtension } from "discourse/lib/composer/rich-editor-extensions";-/** @type {import("discourse/lib/composer/rich-editor-extensions").RichEditorExtension} */-const extension = {+const extension: RichEditorExtension = {markSpec: {underline: {before: "link",diff --git a/frontend/discourse/app/static/prosemirror/lib/text-manipulation.js b/frontend/discourse/app/static/prosemirror/lib/text-manipulation.tssimilarity index 80%rename from frontend/discourse/app/static/prosemirror/lib/text-manipulation.jsrename to frontend/discourse/app/static/prosemirror/lib/text-manipulation.tsindex e89c172d9f0..8b8d72531f9 100644--- a/frontend/discourse/app/static/prosemirror/lib/text-manipulation.js+++ b/frontend/discourse/app/static/prosemirror/lib/text-manipulation.ts@@ -1,25 +1,77 @@-// @ts-check-import { getOwner, setOwner } from "@ember/owner";+import { type default as Owner, getOwner, setOwner } from "@ember/owner";import { trackedObject } from "@ember/reactive/collections";import { next } from "@ember/runloop";import { isEmpty } from "@ember/utils";-// @ts-ignore — pretty-text has no type declarationsimport { lookupCachedUploadUrl } from "pretty-text/upload-short-url";import { lift, setBlockType, toggleMark, wrapIn } from "prosemirror-commands";-import { Slice } from "prosemirror-model";+import {+ type Fragment,+ type Node,+ type NodeType,+ type Schema,+ Slice,+} from "prosemirror-model";import {liftListItem,sinkListItem,wrapInList,} from "prosemirror-schema-list";-import { NodeSelection, Selection, TextSelection } from "prosemirror-state";+import {+ type EditorState,+ NodeSelection,+ Selection,+ TextSelection,+} from "prosemirror-state";+import type { EditorView } from "prosemirror-view";+import type {+ AutocompleteHandler,+ AutocompleteOptions,+ PlaceholderHandler,+ ReplaceTextOptions,+ SelectedText,+ SelectTextOptions,+ TextManipulation,+ ToolbarState,+ UppyFile,+} from "discourse/lib/composer/text-manipulation";import { bind } from "discourse/lib/decorators";import escapeRegExp from "discourse/lib/escape-regexp";import dAutocomplete from "discourse/ui-kit/modifiers/d-autocomplete";import { i18n } from "discourse-i18n";import { hasMark, inNode, isNodeActive } from "./plugin-utils";-function isPlainTextFragment(fragment, schema) {+export type EditorCommands = Record<string, (...args: unknown[]) => unknown> & {+ formatCode: (state: EditorState, dispatch: EditorView["dispatch"]) => boolean;+};+export type CustomState = (state: EditorState) => Record<string, unknown>;++interface ProsemirrorTextManipulationOptions {+ schema: Schema;+ view: EditorView;+ convertFromMarkdown: (markdown: string) => Node;+ convertToMarkdown: (doc: Node | Fragment | Slice) => string;+ splitNonEmptyLines: (text: string) => string[];+ buildListNode: (+ schema: Schema,+ listType: NodeType | string,+ lines: string[]+ ) => Node;+ commands: EditorCommands;+ customState: CustomState;+}++interface HandlerOptions {+ schema: Schema;+ view: EditorView;+ convertFromMarkdown: (markdown: string) => Node;+}++interface FoundPlaceholder {+ node: Node;+ pos: number;+}++function isPlainTextFragment(fragment: Fragment, schema: Schema): boolean {return fragment.content.every((node) => {if (node.isText) {return node.marks.length === 0;@@ -37,34 +89,27 @@ function isPlainTextFragment(fragment, schema) {});}-/**- * @typedef {import("discourse/lib/composer/text-manipulation").TextManipulation} TextManipulation- * @typedef {import("discourse/lib/composer/text-manipulation").AutocompleteHandler} AutocompleteHandler- * @typedef {import("discourse/lib/composer/text-manipulation").PlaceholderHandler} PlaceholderHandler- * @typedef {import("discourse/lib/composer/text-manipulation").ToolbarState} ToolbarState- */--/** @implements {TextManipulation} */-export default class ProsemirrorTextManipulation {+export default class ProsemirrorTextManipulation implements TextManipulation {allowPreview = false;- /** @type {import("prosemirror-model").Schema} */- schema;- /** @type {import("prosemirror-view").EditorView} */- view;- /** @type {PlaceholderHandler} */- placeholder;- /** @type {AutocompleteHandler} */- autocompleteHandler;- /** @type {ToolbarState} */- state = trackedObject({});- convertFromMarkdown;- convertToMarkdown;- splitNonEmptyLines;- buildListNode;+ schema: Schema;+ view: EditorView;+ placeholder: PlaceholderHandler;+ autocompleteHandler: AutocompleteHandler;+ state = trackedObject<ToolbarState & Record<string, unknown>>({});+ convertFromMarkdown: (markdown: string) => Node;+ convertToMarkdown: (doc: Node | Fragment | Slice) => string;+ splitNonEmptyLines: (text: string) => string[];+ buildListNode: (+ schema: Schema,+ listType: NodeType | string,+ lines: string[]+ ) => Node;+ commands: EditorCommands;+ customState: CustomState;constructor(- owner,+ owner: Owner,{schema,view,@@ -74,7 +119,7 @@ export default class ProsemirrorTextManipulation {buildListNode,commands,customState,- }+ }: ProsemirrorTextManipulationOptions) {setOwner(this, owner);this.schema = schema;@@ -98,7 +143,7 @@ export default class ProsemirrorTextManipulation {});}- getSelected() {+ getSelected(): SelectedText {const { state } = this.view;const { from, to } = state.selection;const value = this.convertToMarkdown(state.selection.content());@@ -116,15 +161,15 @@ export default class ProsemirrorTextManipulation {};}- focus() {+ focus(): void {this.view.focus();}- blurAndFocus() {+ blurAndFocus(): void {this.focus();}- putCursorAtEnd() {+ putCursorAtEnd(): void {this.focus();next(() => {@@ -136,7 +181,7 @@ export default class ProsemirrorTextManipulation {});}- autocomplete(options) {+ autocomplete(options: AutocompleteOptions): unknown {return dAutocomplete.setupAutocomplete(getOwner(this),this.view.dom,@@ -145,11 +190,20 @@ export default class ProsemirrorTextManipulation {);}- applySurroundSelection(head, tail, exampleKey) {+ applySurroundSelection(+ head: string | ((previous?: string) => string),+ tail: string,+ exampleKey: string+ ): void {this.applySurround(this.getSelected(), head, tail, exampleKey);}- applySurround(sel, head, tail, exampleKey) {+ applySurround(+ sel: SelectedText,+ head: string | ((previous?: string) => string),+ tail: string,+ exampleKey: string+ ): void {const applySurroundMap = {italic_text: this.schema.marks.em,bold_text: this.schema.marks.strong,@@ -183,7 +237,7 @@ export default class ProsemirrorTextManipulation {);}- applyLink(url) {+ applyLink(url: string): void {const { state, dispatch } = this.view;const { from, to, empty } = state.selection;if (empty) {@@ -195,7 +249,7 @@ export default class ProsemirrorTextManipulation {this.focus();}- addText(sel, text) {+ addText(sel: SelectedText, text: string): void {const doc = this.convertFromMarkdown(text);// assumes it returns a single block node@@ -211,7 +265,7 @@ export default class ProsemirrorTextManipulation {this.focus();}- insertBlock(block) {+ insertBlock(block: string): void {const doc = this.convertFromMarkdown(block);const tr = this.view.state.tr.replaceSelection(@@ -225,7 +279,11 @@ export default class ProsemirrorTextManipulation {this.focus();}- applyList(_selection, head, exampleKey) {+ applyList(+ _selection: SelectedText,+ head: string | ((previous?: string) => string),+ exampleKey: string+ ): void {let command;const findParentList = () => {@@ -329,7 +387,7 @@ export default class ProsemirrorTextManipulation {this.focus();}- applyHeading(_selection, level) {+ applyHeading(_selection: SelectedText, level: number): void {let command;if (level === 0) {command = setBlockType(this.schema.nodes.paragraph);@@ -343,13 +401,13 @@ export default class ProsemirrorTextManipulation {/*** Bridge method from pre-existing API to the new command system*- * @returns {boolean} whether the command was applied+ * @returns Whether the command was applied.*/- formatCode() {+ formatCode(): boolean {return this.commands.formatCode(this.view.state, this.view.dispatch);}- emojiSelected(code) {+ emojiSelected(code: string): void {let index = 0;const value = this.autocompleteHandler.getValue();@@ -374,13 +432,13 @@ export default class ProsemirrorTextManipulation {}@bind- paste() {+ paste(): void {// Intentionally no-op// Pasting markdown is being handled by the markdown-paste extension// Pasting a url on top of a text is being handled by the link extension}- selectText(from, length, opts) {+ selectText(from: number, length: number, opts?: SelectTextOptions): void {const tr = this.view.state.tr.setSelection(new TextSelection(this.view.state.doc.resolve(from),@@ -388,7 +446,7 @@ export default class ProsemirrorTextManipulation {));- if (opts.scroll) {+ if (opts?.scroll) {tr.scrollIntoView();}@@ -396,11 +454,11 @@ export default class ProsemirrorTextManipulation {}@bind- inCodeBlock() {+ inCodeBlock(): Promise<boolean> {return this.autocompleteHandler.inCodeBlock();}- indentSelection(direction) {+ indentSelection(direction: "left" | "right"): boolean | void {const { selection } = this.view.state;const isInsideListItem =@@ -417,7 +475,7 @@ export default class ProsemirrorTextManipulation {}}- insertText(text) {+ insertText(text: string): void {const doc = this.convertFromMarkdown(text);this.view.dispatch(@@ -429,7 +487,11 @@ export default class ProsemirrorTextManipulation {this.focus();}- replaceText(oldValue, newValue, opts = {}) {+ replaceText(+ oldValue: string,+ newValue: string,+ opts: ReplaceTextOptions = {}+ ): void {// Replacing Markdown text is not reliable and should eventually be deprecatedconst markdown = this.convertToMarkdown(this.view.state.doc);@@ -477,15 +539,16 @@ export default class ProsemirrorTextManipulation {this.view.dispatch(tr);}- toggleDirection() {+ toggleDirection(): void {this.view.dom.dir = this.view.dom.dir === "rtl" ? "ltr" : "rtl";}/*** Wraps consecutive upload placeholders in grid tags.- * @param {string[]} consecutiveImages - Array of consecutive image filenames to wrap+ *+ * @param consecutiveImages - Consecutive image filenames to wrap.*/- autoGridImages(consecutiveImages) {+ autoGridImages(consecutiveImages: string[]): void {if (isEmpty(consecutiveImages)) {return;}@@ -561,7 +624,7 @@ export default class ProsemirrorTextManipulation {/*** Updates the toolbar state object based on the current editor active states*/- updateState() {+ updateState(): void {const activeHeadingLevel = [1, 2, 3, 4, 5, 6].find((headingLevel) =>isNodeActive(this.view.state, this.schema.nodes.heading, {level: headingLevel,@@ -585,15 +648,12 @@ export default class ProsemirrorTextManipulation {}}-/** @implements {AutocompleteHandler} */-class ProsemirrorAutocompleteHandler {- /** @type {import("prosemirror-view").EditorView} */- view;- /** @type {import("prosemirror-model").Schema} */- schema;- convertFromMarkdown;+class ProsemirrorAutocompleteHandler implements AutocompleteHandler {+ view: EditorView;+ schema: Schema;+ convertFromMarkdown: (markdown: string) => Node;- constructor({ schema, view, convertFromMarkdown }) {+ constructor({ schema, view, convertFromMarkdown }: HandlerOptions) {this.schema = schema;this.view = view;this.convertFromMarkdown = convertFromMarkdown;@@ -601,9 +661,8 @@ class ProsemirrorAutocompleteHandler {/*** The textual value of the selected text block- * @returns {string}*/- getValue() {+ getValue(): string {return ((this.view.state.selection.$head.nodeBefore?.textContent ?? "") +(this.view.state.selection.$head.nodeAfter?.textContent ?? "") || " "@@ -613,11 +672,8 @@ class ProsemirrorAutocompleteHandler {/*** Replaces the term between start-end in the currently selected text block*- * @param {number} start- * @param {number} end- * @param {String} term*/- replaceTerm(start, end, term) {+ replaceTerm(start: number, end: number, term: string): void {const node = this.view.state.selection.$head.nodeBefore;const from = this.view.state.selection.from - node.nodeSize + start;const to = this.view.state.selection.from - node.nodeSize + end + 1;@@ -637,9 +693,8 @@ class ProsemirrorAutocompleteHandler {/*** Gets the textual caret position within the selected text block*- * @returns {number}*/- getCaretPosition() {+ getCaretPosition(): number {const node = this.view.state.selection.$head.nodeBefore;if (!node?.isText) {@@ -649,7 +704,7 @@ class ProsemirrorAutocompleteHandler {return node.nodeSize;}- getCaretCoords(start) {+ getCaretCoords(start: number): { left: number; top: number } {const node = this.view.state.selection.$head.nodeBefore;const pos = this.view.state.selection.from - node.nodeSize + start;const { left, top } = this.view.coordsAtPos(pos);@@ -662,7 +717,7 @@ class ProsemirrorAutocompleteHandler {};}- async inCodeBlock() {+ async inCodeBlock(): Promise<boolean> {const { schema, view } = this;const { selection } = view.state;@@ -676,7 +731,7 @@ class ProsemirrorAutocompleteHandler {return isInCodeBlock || hasCodeMark;}- async inLink() {+ async inLink(): Promise<boolean> {const { schema, view } = this;const { $from } = view.state.selection;@@ -684,26 +739,25 @@ class ProsemirrorAutocompleteHandler {}}-/** @implements {PlaceholderHandler} */-class ProsemirrorPlaceholderHandler {- view;- schema;- convertFromMarkdown;+class ProsemirrorPlaceholderHandler implements PlaceholderHandler {+ view: EditorView;+ schema: Schema;+ convertFromMarkdown: (markdown: string) => Node;- constructor({ schema, view, convertFromMarkdown }) {+ constructor({ schema, view, convertFromMarkdown }: HandlerOptions) {this.schema = schema;this.view = view;this.convertFromMarkdown = convertFromMarkdown;}- #revokeBlobUrl(node) {+ #revokeBlobUrl(node: Node): void {if (node.attrs.src?.startsWith("blob:")) {URL.revokeObjectURL(node.attrs.src);}}- #findPlaceholder(fileId) {- let result = null;+ #findPlaceholder(fileId: string): FoundPlaceholder | null {+ let result: FoundPlaceholder | null = null;this.view.state.doc.descendants((node, pos) => {if (result) {return false;@@ -722,7 +776,7 @@ class ProsemirrorPlaceholderHandler {return result;}- insert(file) {+ insert(file: UppyFile): void {const isImage = file.data?.type?.startsWith("image/");const isEmptyParagraph =this.view.state.selection.$from.parent.type.name === "paragraph" &&@@ -752,12 +806,12 @@ class ProsemirrorPlaceholderHandler {);}- progress() {}+ progress(): void {}- progressComplete() {}+ progressComplete(): void {}- cancelAll() {- const toDelete = [];+ cancelAll(): void {+ const toDelete: Array<{ pos: number; size: number }> = [];this.view.state.doc.descendants((node, pos) => {if (node.type === this.schema.nodes.image && node.attrs.placeholder) {this.#revokeBlobUrl(node);@@ -776,7 +830,7 @@ class ProsemirrorPlaceholderHandler {}}- cancel(file) {+ cancel(file: UppyFile): void {const found = this.#findPlaceholder(file.id);if (found) {this.#revokeBlobUrl(found.node);@@ -788,7 +842,7 @@ class ProsemirrorPlaceholderHandler {}}- success(file, markdown) {+ success(file: UppyFile, markdown: string): void {const found = this.#findPlaceholder(file.id);if (!found) {return;