Files
ThreadNet-Web/src/editor/serialize.ts
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

229 lines
9.1 KiB
TypeScript
Raw Normal View History

2019-05-22 16:16:32 +02:00
/*
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
Copyright 2019, 2020 The Matrix.org Foundation C.I.C.
2024-09-09 14:57:16 +01:00
Copyright 2019 New Vector Ltd
2019-05-22 16:16:32 +02:00
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
2024-09-09 14:57:16 +01:00
Please see LICENSE files in the repository root for full details.
2019-05-22 16:16:32 +02:00
*/
import { encode } from "html-entities";
import escapeHtml from "escape-html";
2021-10-22 17:23:32 -05:00
2019-05-21 17:59:54 +02:00
import Markdown from "../Markdown";
2021-06-29 13:11:58 +01:00
import { makeGenericPermalink } from "../utils/permalinks/Permalinks";
import EditorModel from "./model";
2020-10-10 16:32:49 +01:00
import SettingsStore from "../settings/SettingsStore";
import SdkConfig from "../SdkConfig";
2021-07-12 13:26:34 +01:00
import { Type } from "./parts";
2019-05-21 17:59:54 +02:00
2021-07-12 13:26:34 +01:00
export function mdSerialize(model: EditorModel): string {
return model.parts.reduce((html, part) => {
switch (part.type) {
2021-07-12 13:26:34 +01:00
case Type.Newline:
2019-05-21 17:59:54 +02:00
return html + "\n";
2021-07-12 13:26:34 +01:00
case Type.Plain:
2022-01-24 07:53:05 -05:00
case Type.Emoji:
2021-07-12 13:26:34 +01:00
case Type.Command:
case Type.PillCandidate:
case Type.AtRoomPill:
return html + part.text;
2023-07-06 00:00:27 +02:00
case Type.RoomPill: {
const url = makeGenericPermalink(part.resourceId, true);
2023-07-06 00:00:27 +02:00
// Escape square brackets and backslashes
2021-03-11 08:29:03 +01:00
// Here we use the resourceId for compatibility with non-rich text clients
// See https://github.com/vector-im/element-web/issues/16660
2023-07-06 00:00:27 +02:00
const title = part.resourceId.replace(/[[\\\]]/g, (c) => "\\" + c);
return html + `[${title}](${url})`;
}
case Type.UserPill: {
const url = makeGenericPermalink(part.resourceId, true);
2023-07-06 00:00:27 +02:00
// Escape square brackets and backslashes; convert newlines to HTML
const title = part.text.replace(/[[\\\]]/g, (c) => "\\" + c).replace(/\n/g, "<br>");
return html + `[${title}](${url})`;
}
}
}, "");
}
interface ISerializeOpts {
forceHTML?: boolean;
useMarkdown?: boolean;
}
export function htmlSerializeIfNeeded(
model: EditorModel,
{ forceHTML = false, useMarkdown = true }: ISerializeOpts = {},
): string | undefined {
if (!useMarkdown) {
return escapeHtml(textSerialize(model)).replace(/\n/g, "<br/>");
}
const md = mdSerialize(model);
return htmlSerializeFromMdIfNeeded(md, { forceHTML });
}
export function htmlSerializeFromMdIfNeeded(md: string, { forceHTML = false } = {}): string | undefined {
// copy of raw input to remove unwanted math later
const orig = md;
2020-09-20 12:59:22 +01:00
2020-10-10 16:32:49 +01:00
if (SettingsStore.getValue("feature_latex_maths")) {
2023-02-13 11:39:16 +00:00
const patternNames = ["tex", "latex"] as const;
const patternTypes = ["display", "inline"] as const;
2021-04-01 12:09:51 +02:00
const patternDefaults = {
tex: {
// detect math with tex delimiters, inline: $...$, display $$...$$
// preferably use negative lookbehinds, not supported in all major browsers:
// const displayPattern = "^(?<!\\\\)\\$\\$(?![ \\t])(([^$]|\\\\\\$)+?)\\$\\$$";
// const inlinePattern = "(?:^|\\s)(?<!\\\\)\\$(?!\\s)(([^$]|\\\\\\$)+?)(?<!\\\\|\\s)\\$";
2020-09-20 12:59:22 +01:00
2021-04-01 12:09:51 +02:00
// conditions for display math detection $$...$$:
2021-04-28 19:39:38 +02:00
// - pattern starts and ends on a new line
2021-04-01 12:09:51 +02:00
// - left delimiter ($$) is not escaped by backslash
2021-04-28 19:39:38 +02:00
display: "(^)\\$\\$(([^$]|\\\\\\$)+?)\\$\\$$",
2021-04-01 12:09:51 +02:00
// conditions for inline math detection $...$:
// - pattern starts at beginning of line, follows whitespace character or punctuation
// - pattern is on a single line
// - left and right delimiters ($) are not escaped by backslashes
// - left delimiter is not followed by whitespace character
// - right delimiter is not prefixed with whitespace character
inline: "(^|\\s|[.,!?:;])(?!\\\\)\\$(?!\\s)(([^$\\n]|\\\\\\$)*([^\\\\\\s\\$]|\\\\\\$)(?:\\\\\\$)?)\\$",
},
latex: {
// detect math with latex delimiters, inline: \(...\), display \[...\]
2021-04-01 12:09:51 +02:00
// conditions for display math detection \[...\]:
2021-04-28 19:39:38 +02:00
// - pattern starts and ends on a new line
2021-04-01 12:09:51 +02:00
// - pattern is not empty
2021-04-28 19:39:38 +02:00
display: "(^)\\\\\\[(?!\\\\\\])(.*?)\\\\\\]$",
2021-04-01 12:09:51 +02:00
// conditions for inline math detection \(...\):
// - pattern starts at beginning of line or is not prefixed with backslash
// - pattern is not empty
inline: "(^|[^\\\\])\\\\\\((?!\\\\\\))(.*?)\\\\\\)",
},
};
2021-04-01 12:09:51 +02:00
patternNames.forEach(function (patternName) {
patternTypes.forEach(function (patternType) {
// get the regex replace pattern from config or use the default
const pattern =
2023-02-13 11:39:16 +00:00
SdkConfig.get("latex_maths_delims")?.[patternType]?.["pattern"]?.[patternName] ||
2021-04-01 12:09:51 +02:00
patternDefaults[patternName][patternType];
2021-04-01 12:09:51 +02:00
md = md.replace(RegExp(pattern, "gms"), function (m, p1, p2) {
const p2e = encode(p2);
2021-04-01 12:09:51 +02:00
switch (patternType) {
case "display":
return `${p1}<div data-mx-maths="${p2e}">\n\n</div>\n\n`;
case "inline":
return `${p1}<span data-mx-maths="${p2e}"></span>`;
}
});
});
2021-01-29 13:05:49 +01:00
});
2023-05-23 14:31:05 +01:00
// make sure div tags always start on a new line, otherwise it will confuse the markdown parser
md = md.replace(/(.)<div/g, function (m, p1) {
return `${p1}\n<div`;
});
2020-09-20 12:59:22 +01:00
}
2019-05-21 17:59:54 +02:00
const parser = new Markdown(md);
2019-07-08 16:55:56 +02:00
if (!parser.isPlainText() || forceHTML) {
// feed Markdown output to HTML parser
2023-05-23 14:31:05 +01:00
const phtml = new DOMParser().parseFromString(parser.toHTML(), "text/html");
if (SettingsStore.getValue("feature_latex_maths")) {
// original Markdown without LaTeX replacements
const parserOrig = new Markdown(orig);
2023-05-23 14:31:05 +01:00
const phtmlOrig = new DOMParser().parseFromString(parserOrig.toHTML(), "text/html");
// since maths delimiters are handled before Markdown,
// code blocks could contain mangled content.
// replace code blocks with original content
2023-05-23 14:31:05 +01:00
[...phtmlOrig.getElementsByTagName("code")].forEach((e, i) => {
phtml.getElementsByTagName("code").item(i)!.textContent = e.textContent;
});
// add fallback output for latex math, which should not be interpreted as markdown
2023-05-23 14:31:05 +01:00
[...phtml.querySelectorAll("div, span")].forEach((e, i) => {
const tex = e.getAttribute("data-mx-maths");
if (tex) {
2023-05-23 14:31:05 +01:00
e.innerHTML = `<code>${tex}</code>`;
}
});
}
2023-05-23 14:31:05 +01:00
return phtml.body.innerHTML;
2019-05-21 17:59:54 +02:00
}
// ensure removal of escape backslashes in non-Markdown messages
if (md.indexOf("\\") > -1) {
return parser.toPlaintext();
}
2019-05-21 17:59:54 +02:00
}
2021-07-12 13:26:34 +01:00
export function textSerialize(model: EditorModel): string {
return model.parts.reduce((text, part) => {
switch (part.type) {
2021-07-12 13:26:34 +01:00
case Type.Newline:
return text + "\n";
2021-07-12 13:26:34 +01:00
case Type.Plain:
2022-01-24 07:53:05 -05:00
case Type.Emoji:
2021-07-12 13:26:34 +01:00
case Type.Command:
case Type.PillCandidate:
case Type.AtRoomPill:
return text + part.text;
2021-07-12 13:26:34 +01:00
case Type.RoomPill:
2021-03-11 18:50:35 +01:00
// Here we use the resourceId for compatibility with non-rich text clients
// See https://github.com/vector-im/element-web/issues/16660
return text + `${part.resourceId}`;
2021-07-12 13:26:34 +01:00
case Type.UserPill:
return text + `${part.text}`;
}
}, "");
}
2021-07-12 13:26:34 +01:00
export function containsEmote(model: EditorModel): boolean {
2022-03-21 15:09:43 -04:00
const hasCommand = startsWith(model, "/me ", false);
const hasArgument = model.parts[0]?.text?.length > 4 || model.parts.length > 1;
return hasCommand && hasArgument;
}
2021-07-12 13:26:34 +01:00
export function startsWith(model: EditorModel, prefix: string, caseSensitive = true): boolean {
const firstPart = model.parts[0];
2019-08-21 15:27:50 +02:00
// part type will be "plain" while editing,
// and "command" while composing a message.
2021-09-28 16:04:25 +02:00
let text = firstPart?.text || "";
2020-06-16 14:06:42 +01:00
if (!caseSensitive) {
prefix = prefix.toLowerCase();
text = text.toLowerCase();
}
2021-07-12 13:26:34 +01:00
return firstPart && (firstPart.type === Type.Plain || firstPart.type === Type.Command) && text.startsWith(prefix);
}
2021-07-12 13:26:34 +01:00
export function stripEmoteCommand(model: EditorModel): EditorModel {
// trim "/me "
return stripPrefix(model, "/me ");
}
2021-07-12 13:26:34 +01:00
export function stripPrefix(model: EditorModel, prefix: string): EditorModel {
model = model.clone();
2021-06-29 13:11:58 +01:00
model.removeText({ index: 0, offset: 0 }, prefix.length);
return model;
}
2021-07-12 13:26:34 +01:00
export function unescapeMessage(model: EditorModel): EditorModel {
2021-06-29 13:11:58 +01:00
const { parts } = model;
if (parts.length) {
const firstPart = parts[0];
// only unescape \/ to / at start of editor
2021-07-12 13:26:34 +01:00
if (firstPart.type === Type.Plain && firstPart.text.startsWith("\\/")) {
model = model.clone();
2021-06-29 13:11:58 +01:00
model.removeText({ index: 0, offset: 0 }, 1);
}
}
return model;
}