// The CodeChat Editor, a word processor for software developers.
Copyright
// (C) 2024-2026 Bryan A. Jones.
//
// This file is part of the CodeChat Editor. The CodeChat Editor is free
// software: you can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// The CodeChat Editor is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// the CodeChat Editor. If not, see
// [http://www.gnu.org/licenses](http://www.gnu.org/licenses).
//
// `tinymce-config.ts` -- integrate and configure the TinyMCE editor for use
// with the CodeChat Editor
// =========================================================================
//
// Import TinyMCE.
import { default as tinymce, Editor, RawEditorOptions } from "tinymce";
// This is taken from the
// [TinyMCE example code](https://github.com/tinymce/tinymce/blob/main/modules/tinymce/src/core/demo/ts/demo/TinyMceDemo.ts).
// However, esbuild doesn't accept it. This is the workaround:
export { tinymce };
// Default icons are required for TinyMCE 5.3 or above.
import "tinymce/icons/default/index.js";
// A theme is also required.
import "tinymce/themes/silver/index.js";
// Import the skin to use; we're using an inline editor, so load the inline CSS.
import "tinymce/skins/ui/oxide/skin.css";
import "tinymce/skins/ui/oxide/content.inline.css";
// Without this, TinyMCE produces errors.
import "tinymce/models/dom/index.js";
// Import plugins.
import "tinymce/plugins/advlist/index.js";
import "tinymce/plugins/anchor/index.js";
import "tinymce/plugins/charmap/index.js";
import "tinymce/plugins/directionality/index.js";
// Omit these, since they're large and infrequently used. TODO: dynamically load
// these on first use.
/// import "tinymce/plugins/emoticons/index.js";
/// import "tinymce/plugins/emoticons/js/emojis.js";
/// import "tinymce/plugins/emoticons/js/emojiimages.js";
import "tinymce/plugins/help/index.js";
// TODO: this should be a dynamic import based on the current language.
import "tinymce/plugins/help/js/i18n/keynav/en.js";
import "tinymce/plugins/image/index.js";
import "tinymce/plugins/link/index.js";
import "tinymce/plugins/lists/index.js";
import "tinymce/plugins/media/index.js";
import "tinymce/plugins/quickbars/index.js";
import "tinymce/plugins/searchreplace/index.js";
import "tinymce/plugins/table/index.js";
import "tinymce/plugins/visualblocks/index.js";
import "tinymce/plugins/visualchars/index.js";
// Import premium plugins. NOTE: Download separately and add these to
// `src/plugins`.
/// import './plugins/checklist/plugin';
/// import './plugins/powerpaste/plugin';
/// import './plugins/powerpaste/js/wordimport';
// Import local code.
import { followLink } from "./CodeChatEditor.mjs";
// Initialize TinyMCE.
export const init = async (
// Provide additional editor options; note that the basic setup provided
// below can't be overridden by these options. The only exception is a value
// for `setup`, which will be combined with the setup defined in this
// function.
additionalOptions: RawEditorOptions,
) => {
// Merge the provided options with this basic setup, giving priority to the
// settings below.
const combinedOptions: RawEditorOptions = Object.assign(
{},
additionalOptions,
{
// See the list of
// [plugins](https://www.tiny.cloud/docs/tinymce/latest/plugins/).
// These must be accompanied by the corresponding import above.
plugins:
"advlist anchor charmap directionality help image link lists media quickbars searchreplace table visualblocks visualchars",
// The imports above apply the skins; don't try to dynamically load
// the skin's CSS.
skin: false,
// Enable the
// [browser-supplied spellchecker](https://www.tiny.cloud/docs/tinymce/latest/spelling/#browser_spellcheck),
// since TinyMCE's spellchecker is a premium feature.
browser_spellcheck: true,
// Place the Tiny MCE menu bar at the top of the screen; otherwise,
// it floats in front of text, sometimes obscuring what the user
// wants to edit. See the
// [docs](https://www.tiny.cloud/docs/configure/editor-appearance/#fixed_toolbar_container).
fixed_toolbar_container: "#CodeChat-menu",
inline: true,
// Use relative URLs in hyperlinks.
relative_urls: true,
// Disable the
// [TinyMCE toolbar buttons](https://www.tiny.cloud/blog/tinymce-toolbar/)
// to provide more real estate on the screen.
toolbar: false,
// Don't show the file option on the
// [menu](https://www.tiny.cloud/docs/tinymce/latest/menus-configuration-options/#menubar),
// which is useless.
menubar: "edit insert view format table tools help",
// See
// [License key](https://www.tiny.cloud/docs/tinymce/latest/license-key).
license_key: "gpl",
// Block drag-and-drop of unsupported images and files. See the
// [docs](https://www.tiny.cloud/docs/tinymce/latest/file-image-upload/#block_unsupported_drop).
block_unsupported_drop: true,
// Prevent drag-and-dropping images; this create a mess. See the
// [docs](https://www.tiny.cloud/docs/tinymce/latest/copy-and-paste/#paste_data_images).
paste_data_images: false,
// TinyMCE's "Get all features" promotional link breaks accessibility. It carries `aria-hidden="true"` yet remains in the tab order, which is the
// `aria-hidden-focus` failure: a keyboard user lands on a control their screen
// reader has been told does not exist. Separately, its text fails contrast at
// 4.31:1 (`#086be6` on `#e8f1f8`) against the 4.5:1 requirement.
// Disable it.
promotion: false,
// ### Settings for plugins
//
// [Image](https://www.tiny.cloud/docs/plugins/opensource/image/)
image_caption: true,
image_advtab: true,
image_title: true,
// Quickbar config: disable the insert toolbar (which doesn't seem
// useful, and also has the image insert, which is problematic
// currently).
quickbars_insert_toolbar: false,
// Put more buttons on the
// [quick toolbar](https://www.tiny.cloud/docs/tinymce/latest/quickbars/)
// that appears when text is selected.
quickbars_selection_toolbar:
"bold italic underline codeformat | quicklink h2 h3",
// Needed to allow custom elements. Without `l-n`, TinyMCE would
// drop each line marker but keep its number as visible text.
extended_valid_elements:
"graphviz-graph[scale],wc-mermaid,xref[contenteditable|ref],fragment[contenteditable|following|id],l-n",
// Per the [docs](https://www.tiny.cloud/docs/tinymce/latest/content-filtering/#custom_elements), `~` marks tags as an inline element, not a block element.
custom_elements: "graphviz-graph,wc-mermaid,~xref,~fragment,~l-n",
// Setting the
// [context menu](https://www.tiny.cloud/docs/tinymce/latest/contextmenu/#contextmenu)
// replaces TinyMCE's default list, so this must also name the
// context menus of the plugins imported above, except the link
// plugin's, which `LINK_MENU` replaces.
contextmenu: `${LINK_MENU} image table`,
},
);
// Merge in additional setup code.
const oldSetup = combinedOptions.setup;
combinedOptions.setup = (editor: Editor) => {
oldSetup?.(editor);
// Add a "Format as code" button (generated by Gemini).
editor.ui.registry.addToggleButton("codeformat", {
text: "<>",
tooltip: "Format as code",
onAction: () =>
editor.execCommand("mceToggleFormat", false, "code"),
onSetup: (api) => {
const changed = editor.formatter.formatChanged(
"code",
(state) => api.setActive(state),
);
return () => changed.unbind();
},
});
takeLinkGestures(editor);
addLinkMenu(editor);
handleLineMarkers(editor);
};
// Use these combined options to
// [init](https://www.tiny.cloud/docs/tinymce/latest/apis/tinymce.root/#init)
// TinyMCE.
return await tinymce.init(combinedOptions);
};
// Line markers
// ------------
//
// The Server puts a hidden marker before the content of each Markdown line;
// see [line-number-spec.md](../../line-number-spec.md).
//
// When Enter splits a block just before the text of a line, that line's marker
// stays at the end of the first half. TinyMCE counts the number inside it as
// content, so a first half holding only markers isn't treated as empty: it
// gets no `
`, so it has no height once saved, and Enter in an empty-looking
// list item adds an item instead of leaving the list. Move each marker with
// nothing after it to the second half, which holds the text of its line, and
// give an emptied first half the `
` of an empty block.
//
// TinyMCE makes the space at the end of a text node non-breaking when typing
// near it. A marker ends a text node at each line, so the space which stands
// for the newline before it would be saved as a non-breaking space; make it a
// space again in the HTML TinyMCE returns.
//
// A copy or cut puts the selected HTML on the clipboard. Leave the markers out
// of it: their numbers don't fit where the text is pasted, and an editor
// without the Client's CSS shows them.
//
const handleLineMarkers = (
// The editor whose markers are handled.
editor: Editor,
) => {
editor.on("NewBlock", ({ newBlock }) => {
// When Enter splits a block, the first half stays in place and the
// second half becomes `newBlock`.
const block = newBlock.previousElementSibling;
if (!block) {
return;
}
const rest = editor.dom.createRng();
rest.setEnd(block, block.childNodes.length);
const trailingMarkers = [...block.querySelectorAll("l-n")].filter(
(marker) => {
rest.setStartAfter(marker);
const after = rest.cloneContents();
after.querySelectorAll("l-n").forEach((m) => m.remove());
return editor.dom.isEmpty(after);
},
);
if (trailingMarkers.length) {
newBlock.prepend(...trailingMarkers);
if (editor.dom.isEmpty(block) && !block.querySelector("br")) {
editor.dom.add(block, "br", { "data-mce-bogus": "1" });
}
}
});
// TinyMCE builds the clipboard's HTML from the selection's contents. Its
// plain text comes from `innerText`, which already leaves out hidden
// markers, so a marker typed as text stays there.
editor.on("GetContent", (event) => {
if (typeof event.content === "string") {
event.content = event.content.replace(
/(?: |\u00a0)(?=)/g,
" ",
);
}
if (event.selection && event.format === "html") {
event.content = event.content.replace(/\d+<\/l-n>/g, "");
}
});
};
// Following links
// ---------------
//
// The Client, rather than TinyMCE's link plugin, follows the links in the
// editor, through `followLink`, so that they act like links everywhere else in
// the Client; see `Link navigation` in
// [implementation.md](../../docs/implementation.md). The plugin follows a link
// on Ctrl+click (Cmd+click on macOS) and Alt+Enter through its own private
// code, not through an item the Client could replace, so the handlers below
// take these gestures before the plugin sees them; handlers added during setup
// run before those the plugin adds when the editor initializes. The link
// context menu below likewise replaces the plugin's.
//
// Each link the code below finds is an HTML link, never an `a` element in
// inline SVG, whose `href` isn't a URL: the Server's sanitizer removes inline
// SVG (see `AMMONIA_OPTIONS` in
// [processing.rs](../../server/src/processing.rs)), replacing the Client's copy
// of any edit which added some.
//
// TODO: the "Open link" button of the plugin's quick link form, which the quick
// toolbar's `quicklink` button opens, still follows a link to an id itself,
// searching only the doc block holding TinyMCE. Route it through `followLink`
// when fixing links to an id elsewhere in the current file (see the TODO in
// `followLink`).
const takeLinkGestures = (
// The editor whose links the Client follows.
editor: Editor,
) => {
editor.on("click", (event) => {
const link =
event.target instanceof Element
? event.target.closest("a[href]")
: null;
if (link !== null && tinymce.util.VK.metaKeyPressed(event)) {
// The plugin follows a clicked link even when an earlier handler
// canceled the click, so stop the plugin from seeing it.
event.preventDefault();
event.stopImmediatePropagation();
followLink(link);
}
});
editor.on("keydown", (event) => {
if (
event.key === "Enter" &&
event.altKey &&
!event.ctrlKey &&
!event.metaKey &&
!event.shiftKey
) {
const link = selectedLink(editor);
if (link !== null) {
// The plugin ignores a canceled keydown.
event.preventDefault();
followLink(link);
}
}
});
};
// Return the link which the keyboard follows, through Alt+Enter or the context
// menu: the link holding the start of the selection, or else the first link in
// the selection. A selected non-editable element encloses its links instead of
// sitting in one, so this is its first link.
const selectedLink = (
// The editor holding the selection.
editor: Editor,
// The link, or `null` if there's none.
): HTMLAnchorElement | null => {
const range = editor.selection.getRng();
return (
editor.dom.getParent(
editor.selection.getStart(true),
"a[href]",
) ??
editor.dom
.select("a[href]", editor.selection.getNode())
.find((link) => range.intersectsNode(link)) ??
null
);
};
// ### The link context menu
//
// This replaces the link plugin's context menu, whose "Open link" follows a
// link to an id itself, and which offers nothing for non-editable content. The
// Server hydrates cross-references, fragments, gather lists, and math as
// non-editable content; see . This menu keeps
// the plugin's items for editing an editable link, and adds its own "Open link"
// for any link. TinyMCE shows its context menus on a long press as well as a
// right click, so this serves touch devices too.
//
// The names under which TinyMCE registers this context menu and its "Open link"
// item.
const LINK_MENU = "codechatlink";
const OPEN_LINK_ITEM = "codechatopenlink";
const addLinkMenu = (
// The editor whose context menu this is.
editor: Editor,
) => {
// The link which the context menu was most recently shown for.
let menuLink: HTMLAnchorElement | null = null;
// The target of the event which most recently opened the context menu.
// TinyMCE's theme starts listening for these events only once the editor
// initializes, so this listener, added during setup, runs first.
let menuEventTarget: EventTarget | null = null;
editor.on("contextmenu longpress", (event) => {
menuEventTarget = event.target;
});
editor.ui.registry.addContextMenu(LINK_MENU, {
update: (
// The element right-clicked or long-pressed, which is the target
// of the event opening the menu, or the start of the selection
// when TinyMCE judges that the keyboard opened the menu.
element,
) => {
menuLink =
element === menuEventTarget
? // A right click or long press beside a link offers no
// "Open link".
editor.dom.getParent(
element,
"a[href]",
)
: selectedLink(editor);
// Offer the plugin's
// [menu items](https://www.tiny.cloud/docs/tinymce/latest/link/#menu-items)
// for editing a link only in editable content, as the plugin's
// own menu does.
if (editor.dom.isEditable(element)) {
return menuLink === null
? "link"
: `link unlink ${OPEN_LINK_ITEM}`;
}
return menuLink === null ? "" : OPEN_LINK_ITEM;
},
});
editor.ui.registry.addMenuItem(OPEN_LINK_ITEM, {
text: "Open link",
icon: "new-tab",
onAction: () => {
// Content the IDE sent while the menu was open may have replaced
// the link; don't follow a link which is no longer shown.
if (menuLink !== null && editor.getBody().contains(menuLink)) {
followLink(menuLink);
}
},
});
};