mirror of
https://github.com/SableClient/Sable.git
synced 2026-12-05 00:02:22 -08:00
feat: support misskey-flavored markdown for colors
This commit is contained in:
1 parent
58ffeb00b8
commit
4c8af8aa3b
15 files changed
+359
-69
No files matched your search
Whitespace-only changes.
@@ -160,7 +160,6 @@ const LINK_URL = `(https?:\\/\\/.[A-Za-z0-9-._~:/?#[\\()@!$&'*+,;%=]+)`;
|
||||
export const LINKINPUTREGEX = new RegExp(`\\(?(${LINK_URL})\\)?`, 'g');
|
||||
const SPOILEREDLINKINPUTREGEX = new RegExp(`<(${LINK_URL})>`, 'g');
|
||||
const SPOILEREDLINKDIRECTREGEX = new RegExp(`\\|\\|(${LINK_URL})\\|\\|`, 'g');
|
||||
|
||||
/**
|
||||
* convert slate internal representation to a plain text string that can be sent to the server
|
||||
* @param node the slate node
|
||||
|
||||
@@ -4,15 +4,11 @@ import { escapeNonAllowlistedHtmlTags } from './allowedHtmlTags';
|
||||
describe('escapeNonAllowlistedHtmlTags', () => {
|
||||
it('entity-escapes unknown tags', () => {
|
||||
expect(escapeNonAllowlistedHtmlTags('<test>')).toBe('<test>');
|
||||
expect(escapeNonAllowlistedHtmlTags('<test> </test>')).toBe(
|
||||
'<test> </test>'
|
||||
);
|
||||
expect(escapeNonAllowlistedHtmlTags('<test> </test>')).toBe('<test> </test>');
|
||||
});
|
||||
|
||||
it('leaves well-formed allowlisted tags unchanged', () => {
|
||||
expect(escapeNonAllowlistedHtmlTags('<strong>bold</strong>')).toBe(
|
||||
'<strong>bold</strong>'
|
||||
);
|
||||
expect(escapeNonAllowlistedHtmlTags('<strong>bold</strong>')).toBe('<strong>bold</strong>');
|
||||
expect(escapeNonAllowlistedHtmlTags('<br>')).toBe('<br>');
|
||||
expect(escapeNonAllowlistedHtmlTags('<img src="mxc://x/y" alt="e" />')).toBe(
|
||||
'<img src="mxc://x/y" alt="e" />'
|
||||
@@ -25,9 +21,7 @@ describe('escapeNonAllowlistedHtmlTags', () => {
|
||||
});
|
||||
|
||||
it('entity-escapes mismatched closing tags', () => {
|
||||
expect(escapeNonAllowlistedHtmlTags('<strong>foo</em>')).toBe(
|
||||
'<strong>foo</em>'
|
||||
);
|
||||
expect(escapeNonAllowlistedHtmlTags('<strong>foo</em>')).toBe('<strong>foo</em>');
|
||||
});
|
||||
|
||||
it('entity-escapes orphan closing tags', () => {
|
||||
|
||||
@@ -1,44 +1,44 @@
|
||||
import { getMarkdownCodeSpanRanges } from "$components/editor/utils";
|
||||
import { getMarkdownCodeSpanRanges } from '$components/editor/utils';
|
||||
|
||||
export const MARKDOWN_ALLOWED_HTML_TAGS = new Set([
|
||||
"a",
|
||||
"blockquote",
|
||||
"br",
|
||||
"code",
|
||||
"del",
|
||||
"details",
|
||||
"div",
|
||||
"em",
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"hr",
|
||||
"img",
|
||||
"li",
|
||||
"mx-reply",
|
||||
"ol",
|
||||
"p",
|
||||
"pre",
|
||||
"s",
|
||||
"span",
|
||||
"strong",
|
||||
"sub",
|
||||
"summary",
|
||||
"table",
|
||||
"tbody",
|
||||
"td",
|
||||
"th",
|
||||
"thead",
|
||||
"tr",
|
||||
"u",
|
||||
"ul",
|
||||
'a',
|
||||
'blockquote',
|
||||
'br',
|
||||
'code',
|
||||
'del',
|
||||
'details',
|
||||
'div',
|
||||
'em',
|
||||
'h1',
|
||||
'h2',
|
||||
'h3',
|
||||
'h4',
|
||||
'h5',
|
||||
'h6',
|
||||
'hr',
|
||||
'img',
|
||||
'li',
|
||||
'mx-reply',
|
||||
'ol',
|
||||
'p',
|
||||
'pre',
|
||||
's',
|
||||
'span',
|
||||
'strong',
|
||||
'sub',
|
||||
'summary',
|
||||
'table',
|
||||
'tbody',
|
||||
'td',
|
||||
'th',
|
||||
'thead',
|
||||
'tr',
|
||||
'u',
|
||||
'ul',
|
||||
]);
|
||||
|
||||
/** Void elements that do not require a separate closing tag. */
|
||||
export const VOID_HTML_TAGS = new Set(["br", "hr", "img"]);
|
||||
export const VOID_HTML_TAGS = new Set(['br', 'hr', 'img']);
|
||||
|
||||
export const isAllowedHtmlTag = (tagName: string): boolean =>
|
||||
MARKDOWN_ALLOWED_HTML_TAGS.has(tagName.toLowerCase());
|
||||
@@ -46,37 +46,37 @@ export const isAllowedHtmlTag = (tagName: string): boolean =>
|
||||
/** Matches HTML open/close/self-closing tags (not `<https://…>` preview suppressors). */
|
||||
const RAW_HTML_TAG = /<\/?([a-zA-Z][\da-zA-Z-]*)(?:\s(?:[^>"']|"[^"]*"|'[^']*')*)?\s*\/?>/g;
|
||||
|
||||
const CODE_PLACEHOLDER_START = "\uE000";
|
||||
const CODE_PLACEHOLDER_END = "\uE001";
|
||||
const CODE_PLACEHOLDER_START = '\uE000';
|
||||
const CODE_PLACEHOLDER_END = '\uE001';
|
||||
|
||||
type HtmlTagToken = {
|
||||
index: number;
|
||||
length: number;
|
||||
raw: string;
|
||||
tagName: string;
|
||||
kind: "open" | "close" | "void";
|
||||
kind: 'open' | 'close' | 'void';
|
||||
};
|
||||
|
||||
const entityEscapeTag = (raw: string): string =>
|
||||
raw.replaceAll("<", "<").replaceAll(">", ">");
|
||||
raw.replaceAll('<', '<').replaceAll('>', '>');
|
||||
|
||||
const isVoidHtmlTag = (tagName: string, raw: string): boolean =>
|
||||
VOID_HTML_TAGS.has(tagName.toLowerCase()) || /\/>\s*$/.test(raw);
|
||||
|
||||
const scanHtmlTags = (input: string): HtmlTagToken[] => {
|
||||
const tokens: HtmlTagToken[] = [];
|
||||
const re = new RegExp(RAW_HTML_TAG.source, "g");
|
||||
const re = new RegExp(RAW_HTML_TAG.source, 'g');
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = re.exec(input)) !== null) {
|
||||
const raw = match[0];
|
||||
const tagName = match[1]!.toLowerCase();
|
||||
const isClose = raw.startsWith("</");
|
||||
const kind: HtmlTagToken["kind"] = isClose
|
||||
? "close"
|
||||
const isClose = raw.startsWith('</');
|
||||
const kind: HtmlTagToken['kind'] = isClose
|
||||
? 'close'
|
||||
: isVoidHtmlTag(tagName, raw)
|
||||
? "void"
|
||||
: "open";
|
||||
? 'void'
|
||||
: 'open';
|
||||
|
||||
tokens.push({
|
||||
index: match.index,
|
||||
@@ -100,11 +100,11 @@ const collectTagsToEscape = (tokens: HtmlTagToken[]): Set<number> => {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token.kind === "void") {
|
||||
if (token.kind === 'void') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token.kind === "open") {
|
||||
if (token.kind === 'open') {
|
||||
openStack.push({ tagName: token.tagName, index: token.index });
|
||||
continue;
|
||||
}
|
||||
@@ -127,7 +127,7 @@ const collectTagsToEscape = (tokens: HtmlTagToken[]): Set<number> => {
|
||||
const applyTagEscapes = (input: string, tokens: HtmlTagToken[], escapeAt: Set<number>): string => {
|
||||
if (escapeAt.size === 0) return input;
|
||||
|
||||
let out = "";
|
||||
let out = '';
|
||||
let cursor = 0;
|
||||
|
||||
for (const token of tokens) {
|
||||
@@ -166,8 +166,8 @@ const maskMarkdownVerbatimRegions = (text: string): { masked: string; chunks: st
|
||||
|
||||
const unmaskMarkdownVerbatimRegions = (text: string, chunks: string[]): string =>
|
||||
text.replace(
|
||||
new RegExp(`${CODE_PLACEHOLDER_START}CODE(\\d+)${CODE_PLACEHOLDER_END}`, "g"),
|
||||
(_, index) => chunks[parseInt(index, 10)] ?? "",
|
||||
new RegExp(`${CODE_PLACEHOLDER_START}CODE(\\d+)${CODE_PLACEHOLDER_END}`, 'g'),
|
||||
(_, index) => chunks[parseInt(index, 10)] ?? ''
|
||||
);
|
||||
|
||||
const escapeHtmlTagsInMarkdown = (input: string): string => {
|
||||
|
||||
@@ -256,6 +256,7 @@ export const matrixMathExtension = {
|
||||
name: 'math',
|
||||
level: 'inline',
|
||||
start(src: string) {
|
||||
if (/^\$\[(?:fg|bg)\.color=/.test(src)) return -1;
|
||||
return src.indexOf('$');
|
||||
},
|
||||
tokenizer(src: string) {
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseMfmColorFnArgs, tryParseMfmColor } from './matrix-mfm-color';
|
||||
import { markdownToHtml } from '../markdownToHtml';
|
||||
import { htmlToMarkdown } from '../htmlToMarkdown';
|
||||
|
||||
describe('tryParseMfmColor', () => {
|
||||
it('parses a color function block', () => {
|
||||
const src = '$[fg.color=ff0000 red text]';
|
||||
expect(tryParseMfmColor(src)).toMatchObject({
|
||||
text: 'red text',
|
||||
dataMd: '$[fg.color=ff0000',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseMfmColorFnArgs', () => {
|
||||
it('parses fg only', () => {
|
||||
expect(parseMfmColorFnArgs('fg.color=ff0000')).toEqual({ fg: '#ff0000' });
|
||||
});
|
||||
|
||||
it('parses fg and bg', () => {
|
||||
expect(parseMfmColorFnArgs('fg.color=ff0000 bg.color=00ff00')).toEqual({
|
||||
fg: '#ff0000',
|
||||
bg: '#00ff00',
|
||||
});
|
||||
});
|
||||
|
||||
it('expands 3-digit hex', () => {
|
||||
expect(parseMfmColorFnArgs('fg.color=fff')).toEqual({ fg: '#ffffff' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('matrixMfmColorExtension', () => {
|
||||
it('converts fg.color to data-mx-color', () => {
|
||||
const html = markdownToHtml('$[fg.color=ff0000 red text]');
|
||||
expect(html).toContain('data-mx-color="#ff0000"');
|
||||
expect(html).toContain('red text');
|
||||
});
|
||||
|
||||
it('converts bg.color with 3-digit hex', () => {
|
||||
const html = markdownToHtml('$[bg.color=0f0 highlighted]');
|
||||
expect(html).toContain('data-mx-bg-color="#00ff00"');
|
||||
});
|
||||
|
||||
it('does not parse 4- or 8-digit hex (no alpha)', () => {
|
||||
expect(markdownToHtml('$[fg.color=ff00 no color]')).not.toContain('data-mx-color');
|
||||
expect(markdownToHtml('$[fg.color=ff0000ff no color]')).not.toContain('data-mx-color');
|
||||
});
|
||||
|
||||
it('round-trips via htmlToMarkdown', () => {
|
||||
const md = '$[fg.color=f00 hello]';
|
||||
const html = markdownToHtml(md);
|
||||
expect(htmlToMarkdown(html)).toBe(md);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { TokenizerExtension, RendererExtension, Tokens } from 'marked';
|
||||
import { MFM_HEX_COLOR_VALUE_PATTERN, normalizeMfmHexToMatrixColor } from '$utils/matrixHtml';
|
||||
|
||||
export type MfmColorArgs = {
|
||||
fg?: string;
|
||||
bg?: string;
|
||||
};
|
||||
|
||||
const MFM_COLOR_FN_START = /^\$\[(?=(?:fg\.color|bg\.color)=)/;
|
||||
const MFM_COLOR_ARGS_PREFIX = new RegExp(
|
||||
`^((?:(?:fg|bg)\\.color=${MFM_HEX_COLOR_VALUE_PATTERN}\\s*)+)`
|
||||
);
|
||||
|
||||
/** Parses `fg.color=…` / `bg.color=…` tokens from the inside of `$[…]`. */
|
||||
export function parseMfmColorFnArgs(argsPart: string): MfmColorArgs | undefined {
|
||||
const trimmed = argsPart.trim();
|
||||
if (!trimmed) return undefined;
|
||||
|
||||
const result: MfmColorArgs = {};
|
||||
const tokens = trimmed.split(/\s+/);
|
||||
|
||||
for (const token of tokens) {
|
||||
const m = new RegExp(`^(fg|bg)\\.color=(${MFM_HEX_COLOR_VALUE_PATTERN})$`).exec(token);
|
||||
if (!m) return undefined;
|
||||
const normalized = normalizeMfmHexToMatrixColor(m[2]!);
|
||||
if (!normalized) return undefined;
|
||||
if (m[1] === 'fg') result.fg = normalized;
|
||||
else result.bg = normalized;
|
||||
}
|
||||
|
||||
return result.fg !== undefined || result.bg !== undefined ? result : undefined;
|
||||
}
|
||||
|
||||
/** Opening args for `data-md` round-trip, e.g. `$[fg.color=ff0000 bg.color=00ff00`. */
|
||||
export function formatMfmColorDataMd(args: MfmColorArgs): string {
|
||||
const parts: string[] = [];
|
||||
if (args.fg) {
|
||||
parts.push(`fg.color=${args.fg.replace(/^#/, '').toLowerCase()}`);
|
||||
}
|
||||
if (args.bg) {
|
||||
parts.push(`bg.color=${args.bg.replace(/^#/, '').toLowerCase()}`);
|
||||
}
|
||||
return `$[${parts.join(' ')}`;
|
||||
}
|
||||
|
||||
export function tryParseMfmColor(
|
||||
src: string
|
||||
): { raw: string; args: MfmColorArgs; text: string; dataMd: string } | undefined {
|
||||
if (!MFM_COLOR_FN_START.test(src)) return undefined;
|
||||
|
||||
const close = src.indexOf(']');
|
||||
if (close <= 2) return undefined;
|
||||
|
||||
const inner = src.slice(2, close);
|
||||
const argsMatch = MFM_COLOR_ARGS_PREFIX.exec(inner);
|
||||
if (!argsMatch) return undefined;
|
||||
|
||||
const argsPart = argsMatch[1]!.trimEnd();
|
||||
const text = inner.slice(argsMatch[0].length).trimStart();
|
||||
if (!text) return undefined;
|
||||
const args = parseMfmColorFnArgs(argsPart);
|
||||
if (!args) return undefined;
|
||||
|
||||
return {
|
||||
raw: src.slice(0, close + 1),
|
||||
args,
|
||||
text,
|
||||
dataMd: `$[${argsPart}`,
|
||||
};
|
||||
}
|
||||
|
||||
export const matrixMfmColorExtension = {
|
||||
name: 'mfmColor',
|
||||
level: 'inline',
|
||||
priority: 10,
|
||||
start(src: string) {
|
||||
const fg = src.indexOf('$[fg.color=');
|
||||
const bg = src.indexOf('$[bg.color=');
|
||||
if (fg === -1) return bg;
|
||||
if (bg === -1) return fg;
|
||||
return Math.min(fg, bg);
|
||||
},
|
||||
tokenizer(
|
||||
this: { lexer: { inlineTokens: (t: string, tokens: Tokens.Generic[]) => void } },
|
||||
src: string
|
||||
) {
|
||||
const parsed = tryParseMfmColor(src);
|
||||
if (!parsed) return undefined;
|
||||
|
||||
const token = {
|
||||
type: 'mfmColor',
|
||||
raw: parsed.raw,
|
||||
text: parsed.text,
|
||||
mfmArgs: parsed.args,
|
||||
dataMd: parsed.dataMd,
|
||||
tokens: [] as Tokens.Generic[],
|
||||
};
|
||||
this.lexer.inlineTokens(parsed.text, token.tokens);
|
||||
return token;
|
||||
},
|
||||
renderer(
|
||||
this: { parser: { parseInline: (tokens: Tokens.Generic[]) => string } },
|
||||
token: Tokens.Generic
|
||||
) {
|
||||
const t = token as {
|
||||
tokens: Tokens.Generic[];
|
||||
mfmArgs: MfmColorArgs;
|
||||
dataMd: string;
|
||||
};
|
||||
const inner = this.parser.parseInline(t.tokens ?? []);
|
||||
const attrs: string[] = [`data-md="${t.dataMd}"`];
|
||||
if (t.mfmArgs.fg) attrs.push(`data-mx-color="${t.mfmArgs.fg}"`);
|
||||
if (t.mfmArgs.bg) attrs.push(`data-mx-bg-color="${t.mfmArgs.bg}"`);
|
||||
return `<span ${attrs.join(' ')}>${inner}</span>`;
|
||||
},
|
||||
} satisfies TokenizerExtension & RendererExtension;
|
||||
@@ -7,10 +7,11 @@ import {
|
||||
shieldDollarRunsForMarked,
|
||||
} from './matrix-math';
|
||||
import { matrixSubscriptExtension } from './matrix-subscript';
|
||||
|
||||
import { matrixMfmColorExtension } from './matrix-mfm-color';
|
||||
function parse(input: string): string {
|
||||
const processor = marked.use({
|
||||
extensions: [
|
||||
matrixMfmColorExtension,
|
||||
matrixSpoilerExtension,
|
||||
matrixMathExtension,
|
||||
matrixMathBlockExtension,
|
||||
@@ -20,6 +21,14 @@ function parse(input: string): string {
|
||||
return processor.parse(shieldDollarRunsForMarked(input)) as string;
|
||||
}
|
||||
|
||||
describe('matrixMfmColorExtension', () => {
|
||||
it('parses fg.color syntax', () => {
|
||||
const result = parse('$[fg.color=ff0000 red text]');
|
||||
expect(result).toContain('data-mx-color="#ff0000"');
|
||||
expect(result).toContain('red text');
|
||||
});
|
||||
});
|
||||
|
||||
describe('matrixSpoilerExtension', () => {
|
||||
it('parses ||spoiler|| syntax', () => {
|
||||
expect(parse('Hello ||spoiler|| world')).toContain('data-mx-spoiler');
|
||||
|
||||
@@ -73,8 +73,7 @@ describe('htmlToMarkdown', () => {
|
||||
});
|
||||
|
||||
it('does not use preview-suppressed destinations for matrix.to event permalinks', () => {
|
||||
const url =
|
||||
'https://matrix.to/#/!room:example.org/$event123?via=sable.moe&via=matrix.org';
|
||||
const url = 'https://matrix.to/#/!room:example.org/$event123?via=sable.moe&via=matrix.org';
|
||||
const html = `<p><<a href="${url}">${url}</a>></p>`;
|
||||
expect(htmlToMarkdown(html)).toBe(`[${url}](${url})`);
|
||||
});
|
||||
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
import { escapeMarkdownInlineSequences } from './utils';
|
||||
import { testMatrixTo } from '$plugins/matrix-to';
|
||||
import { isAllowedHtmlTag } from './allowedHtmlTags';
|
||||
import { formatMfmColorDataMd } from './extensions/matrix-mfm-color';
|
||||
import { isMatrixHexColor } from '$utils/matrixHtml';
|
||||
|
||||
/**
|
||||
* Converts Matrix-compatible HTML back to markdown for round-trip editing.
|
||||
@@ -99,13 +101,17 @@ function processNode(node: ChildNode, listDepth: number = 0, insideCode: boolean
|
||||
return processMath(node, 'inline');
|
||||
}
|
||||
if (node.attribs['data-md'] !== undefined) {
|
||||
const dataMd = node.attribs['data-md'];
|
||||
if (typeof dataMd === 'string' && dataMd.startsWith('$[')) {
|
||||
return processMfmColorSpan(node, listDepth, insideCode);
|
||||
}
|
||||
return processInlineMarkdown(node, listDepth, insideCode);
|
||||
}
|
||||
if (
|
||||
node.attribs['data-mx-color'] !== undefined ||
|
||||
node.attribs['data-mx-bg-color'] !== undefined
|
||||
) {
|
||||
return reconstructTag(node, listDepth, insideCode);
|
||||
return processMfmColorSpan(node, listDepth, insideCode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -436,6 +442,30 @@ function processLink(node: Element, listDepth = 0, insideCode = false): string {
|
||||
return `[${content}](${href})`;
|
||||
}
|
||||
|
||||
function processMfmColorSpan(
|
||||
node: Element,
|
||||
listDepth: number = 0,
|
||||
insideCode: boolean = false
|
||||
): string {
|
||||
const content = processChildren(node.children, listDepth, insideCode);
|
||||
const dataMd = node.attribs['data-md'];
|
||||
if (typeof dataMd === 'string' && dataMd.startsWith('$[')) {
|
||||
return `${dataMd} ${content}]`;
|
||||
}
|
||||
|
||||
const args: { fg?: string; bg?: string } = {};
|
||||
const fg = node.attribs['data-mx-color'];
|
||||
const bg = node.attribs['data-mx-bg-color'];
|
||||
if (typeof fg === 'string' && isMatrixHexColor(fg)) args.fg = fg;
|
||||
if (typeof bg === 'string' && isMatrixHexColor(bg)) args.bg = bg;
|
||||
|
||||
if (args.fg !== undefined || args.bg !== undefined) {
|
||||
return `${formatMfmColorDataMd(args)} ${content}]`;
|
||||
}
|
||||
|
||||
return reconstructTag(node, listDepth, insideCode);
|
||||
}
|
||||
|
||||
function processSpoiler(node: Element, listDepth = 0, insideCode = false): string {
|
||||
const content = node.children.map((c) => processNode(c, listDepth, insideCode)).join('');
|
||||
return `||${content}||`;
|
||||
|
||||
@@ -88,6 +88,27 @@ export function injectDataMd(html: string): string {
|
||||
return `<del data-md="~~"${attrs}>${content}</del>`;
|
||||
});
|
||||
|
||||
// Inject MFM color data-md on colored spans from other clients
|
||||
html = html.replace(
|
||||
/<span([^>]*data-mx-color="(#[0-9a-fA-F]{6})"[^>]*)>([^<]*)<\/span>/g,
|
||||
(match, attrs, _color, content) => {
|
||||
if (attrs.includes('data-md')) return match;
|
||||
const bgMatch = /data-mx-bg-color="(#[0-9a-fA-F]{6})"/.exec(attrs);
|
||||
const fg = _color as string;
|
||||
const bg = bgMatch?.[1];
|
||||
const parts: string[] = [`fg.color=${fg.replace(/^#/, '').toLowerCase()}`];
|
||||
if (bg) parts.push(`bg.color=${bg.replace(/^#/, '').toLowerCase()}`);
|
||||
return `<span data-md="$[${parts.join(' ')}"${attrs}>${content}</span>`;
|
||||
}
|
||||
);
|
||||
html = html.replace(
|
||||
/<span([^>]*data-mx-bg-color="(#[0-9a-fA-F]{6})"[^>]*)>([^<]*)<\/span>/g,
|
||||
(match, attrs, bg, content) => {
|
||||
if (attrs.includes('data-md') || attrs.includes('data-mx-color')) return match;
|
||||
return `<span data-md="$[bg.color=${(bg as string).replace(/^#/, '').toLowerCase()}"${attrs}>${content}</span>`;
|
||||
}
|
||||
);
|
||||
|
||||
// Inject inline code marker
|
||||
html = html.replace(/<code([^>]*)>([^<]*)<\/code>/g, (_, attrs, content) => {
|
||||
if (attrs.includes('data-md')) return `<code${attrs}>${content}</code>`;
|
||||
|
||||
@@ -43,6 +43,17 @@ describe('markdownToHtml', () => {
|
||||
expect(result).toContain('spoiler');
|
||||
});
|
||||
|
||||
it('converts MFM fg.color syntax', () => {
|
||||
const result = markdownToHtml('$[fg.color=f00 red]');
|
||||
expect(result).toContain('data-mx-color="#ff0000"');
|
||||
expect(result).toContain('red');
|
||||
});
|
||||
|
||||
it('converts MFM bg.color with 6-digit hex', () => {
|
||||
const result = markdownToHtml('$[bg.color=00ff00 green]');
|
||||
expect(result).toContain('data-mx-bg-color="#00ff00"');
|
||||
});
|
||||
|
||||
it('converts inline math syntax', () => {
|
||||
const result = markdownToHtml('$E = mc^2$');
|
||||
expect(result).toContain('data-mx-maths');
|
||||
|
||||
@@ -12,20 +12,19 @@ import {
|
||||
import { matrixSubscriptExtension } from './extensions/matrix-subscript';
|
||||
import { matrixEmoticonExtension, preprocessEmoticon } from './extensions/matrix-emoticon';
|
||||
import { matrixUnderlineExtension } from './extensions/matrix-underline';
|
||||
import { matrixMfmColorExtension } from './extensions/matrix-mfm-color';
|
||||
import {
|
||||
escapeLineStartBlockquoteWithoutFollowingSpace,
|
||||
unescapeMarkdownInlineSequencesExceptInCodeHtml,
|
||||
} from './utils';
|
||||
import { expandBlockBoundariesAfterSingleNewlines } from './expandBlockNewlines';
|
||||
import {
|
||||
escapeNonAllowlistedHtmlTags,
|
||||
MARKDOWN_ALLOWED_HTML_TAGS,
|
||||
} from './allowedHtmlTags';
|
||||
import { escapeNonAllowlistedHtmlTags, MARKDOWN_ALLOWED_HTML_TAGS } from './allowedHtmlTags';
|
||||
|
||||
// Configure marked with Matrix extensions
|
||||
const processor = marked.use({
|
||||
breaks: true,
|
||||
extensions: [
|
||||
matrixMfmColorExtension,
|
||||
matrixUnderlineExtension,
|
||||
matrixSpoilerExtension,
|
||||
matrixMathExtension,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { normalizeMfmHexToMatrixColor } from './matrixHtml';
|
||||
|
||||
describe('normalizeMfmHexToMatrixColor', () => {
|
||||
it('expands 3-digit hex', () => {
|
||||
expect(normalizeMfmHexToMatrixColor('f00')).toBe('#ff0000');
|
||||
expect(normalizeMfmHexToMatrixColor('#f00')).toBe('#ff0000');
|
||||
});
|
||||
|
||||
it('accepts 6-digit hex', () => {
|
||||
expect(normalizeMfmHexToMatrixColor('ff0000')).toBe('#ff0000');
|
||||
expect(normalizeMfmHexToMatrixColor('#00ff00')).toBe('#00ff00');
|
||||
});
|
||||
|
||||
it('rejects invalid values', () => {
|
||||
expect(normalizeMfmHexToMatrixColor('red')).toBeUndefined();
|
||||
expect(normalizeMfmHexToMatrixColor('ffff')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('rejects 4- and 8-digit hex (alpha channels)', () => {
|
||||
expect(normalizeMfmHexToMatrixColor('ff00')).toBeUndefined();
|
||||
expect(normalizeMfmHexToMatrixColor('#ff00')).toBeUndefined();
|
||||
expect(normalizeMfmHexToMatrixColor('ff0000ff')).toBeUndefined();
|
||||
expect(normalizeMfmHexToMatrixColor('#ff0000ff')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -3,3 +3,33 @@ export const MATRIX_HEX_COLOR_REGEX = /^#[0-9a-fA-F]{6}$/;
|
||||
export function isMatrixHexColor(value: string): boolean {
|
||||
return MATRIX_HEX_COLOR_REGEX.test(value);
|
||||
}
|
||||
|
||||
/** MFM / composer input: optional `#` then exactly 3 or 6 hex digits (no alpha). */
|
||||
export const MFM_HEX_INPUT_REGEX = /^#?(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/;
|
||||
|
||||
/** One `fg.color=` / `bg.color=` value in a `$[…]` block (no alpha). */
|
||||
export const MFM_HEX_COLOR_VALUE_PATTERN = '[#]?(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})(?![0-9a-fA-F])';
|
||||
|
||||
/**
|
||||
* Normalizes MFM-style hex (3 or 6 digits, optional `#`) to Matrix `#RRGGBB`.
|
||||
*/
|
||||
export function normalizeMfmHexToMatrixColor(hex: string): string | undefined {
|
||||
const trimmed = hex.trim();
|
||||
if (!MFM_HEX_INPUT_REGEX.test(trimmed)) return undefined;
|
||||
|
||||
const digits = trimmed.replace(/^#/, '').toLowerCase();
|
||||
if (digits.length === 3) {
|
||||
const expanded = `${digits[0]}${digits[0]}${digits[1]}${digits[1]}${digits[2]}${digits[2]}`;
|
||||
const color = `#${expanded}`;
|
||||
return isMatrixHexColor(color) ? color : undefined;
|
||||
}
|
||||
|
||||
const color = `#${digits}`;
|
||||
return isMatrixHexColor(color) ? color : undefined;
|
||||
}
|
||||
|
||||
/** Strips `#` for MFM `fg.color=` / `bg.color=` round-trip. */
|
||||
export function matrixColorToMfmHex(value: string): string | undefined {
|
||||
if (!isMatrixHexColor(value)) return undefined;
|
||||
return value.slice(1).toLowerCase();
|
||||
}
|
||||
Reference in new issue
Block a user