From 4c8af8aa3b5784eeba65440f3bf5cab2d0884291 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sun, 17 May 2026 21:42:45 -0500 Subject: [PATCH] feat: support misskey-flavored markdown for colors --- .changeset/add-misskey-flavored-markdown.md | 0 src/app/components/editor/output.ts | 1 - .../plugins/markdown/allowedHtmlTags.test.ts | 12 +- src/app/plugins/markdown/allowedHtmlTags.ts | 102 +++++++-------- .../markdown/extensions/matrix-math.ts | 1 + .../extensions/matrix-mfm-color.test.ts | 55 +++++++++ .../markdown/extensions/matrix-mfm-color.ts | 116 ++++++++++++++++++ .../markdown/extensions/matrix.test.ts | 11 +- .../plugins/markdown/htmlToMarkdown.test.ts | 3 +- src/app/plugins/markdown/htmlToMarkdown.ts | 32 ++++- src/app/plugins/markdown/injectDataMd.ts | 21 ++++ .../plugins/markdown/markdownToHtml.test.ts | 11 ++ src/app/plugins/markdown/markdownToHtml.ts | 7 +- src/app/utils/matrixHtml.test.ts | 26 ++++ src/app/utils/matrixHtml.ts | 30 +++++ 15 files changed, 359 insertions(+), 69 deletions(-) create mode 100644 .changeset/add-misskey-flavored-markdown.md create mode 100644 src/app/plugins/markdown/extensions/matrix-mfm-color.test.ts create mode 100644 src/app/plugins/markdown/extensions/matrix-mfm-color.ts create mode 100644 src/app/utils/matrixHtml.test.ts diff --git a/.changeset/add-misskey-flavored-markdown.md b/.changeset/add-misskey-flavored-markdown.md new file mode 100644 index 000000000..e69de29bb diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts index 665da06a9..0a06a2330 100644 --- a/src/app/components/editor/output.ts +++ b/src/app/components/editor/output.ts @@ -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 diff --git a/src/app/plugins/markdown/allowedHtmlTags.test.ts b/src/app/plugins/markdown/allowedHtmlTags.test.ts index d4a0e73fe..13a6eff1a 100644 --- a/src/app/plugins/markdown/allowedHtmlTags.test.ts +++ b/src/app/plugins/markdown/allowedHtmlTags.test.ts @@ -4,15 +4,11 @@ import { escapeNonAllowlistedHtmlTags } from './allowedHtmlTags'; describe('escapeNonAllowlistedHtmlTags', () => { it('entity-escapes unknown tags', () => { expect(escapeNonAllowlistedHtmlTags('')).toBe('<test>'); - expect(escapeNonAllowlistedHtmlTags(' ')).toBe( - '<test> </test>' - ); + expect(escapeNonAllowlistedHtmlTags(' ')).toBe('<test> </test>'); }); it('leaves well-formed allowlisted tags unchanged', () => { - expect(escapeNonAllowlistedHtmlTags('bold')).toBe( - 'bold' - ); + expect(escapeNonAllowlistedHtmlTags('bold')).toBe('bold'); expect(escapeNonAllowlistedHtmlTags('
')).toBe('
'); expect(escapeNonAllowlistedHtmlTags('e')).toBe( 'e' @@ -25,9 +21,7 @@ describe('escapeNonAllowlistedHtmlTags', () => { }); it('entity-escapes mismatched closing tags', () => { - expect(escapeNonAllowlistedHtmlTags('foo')).toBe( - '<strong>foo</em>' - ); + expect(escapeNonAllowlistedHtmlTags('foo')).toBe('<strong>foo</em>'); }); it('entity-escapes orphan closing tags', () => { diff --git a/src/app/plugins/markdown/allowedHtmlTags.ts b/src/app/plugins/markdown/allowedHtmlTags.ts index 92b08dac3..e522d53ae 100644 --- a/src/app/plugins/markdown/allowedHtmlTags.ts +++ b/src/app/plugins/markdown/allowedHtmlTags.ts @@ -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 `` 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(" => { 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 => { const applyTagEscapes = (input: string, tokens: HtmlTagToken[], escapeAt: Set): 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 => { diff --git a/src/app/plugins/markdown/extensions/matrix-math.ts b/src/app/plugins/markdown/extensions/matrix-math.ts index da94783fa..21265f70f 100644 --- a/src/app/plugins/markdown/extensions/matrix-math.ts +++ b/src/app/plugins/markdown/extensions/matrix-math.ts @@ -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) { diff --git a/src/app/plugins/markdown/extensions/matrix-mfm-color.test.ts b/src/app/plugins/markdown/extensions/matrix-mfm-color.test.ts new file mode 100644 index 000000000..037553aeb --- /dev/null +++ b/src/app/plugins/markdown/extensions/matrix-mfm-color.test.ts @@ -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); + }); +}); diff --git a/src/app/plugins/markdown/extensions/matrix-mfm-color.ts b/src/app/plugins/markdown/extensions/matrix-mfm-color.ts new file mode 100644 index 000000000..8be06315b --- /dev/null +++ b/src/app/plugins/markdown/extensions/matrix-mfm-color.ts @@ -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 `${inner}`; + }, +} satisfies TokenizerExtension & RendererExtension; diff --git a/src/app/plugins/markdown/extensions/matrix.test.ts b/src/app/plugins/markdown/extensions/matrix.test.ts index 707a3f003..4dcaa5d23 100644 --- a/src/app/plugins/markdown/extensions/matrix.test.ts +++ b/src/app/plugins/markdown/extensions/matrix.test.ts @@ -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'); diff --git a/src/app/plugins/markdown/htmlToMarkdown.test.ts b/src/app/plugins/markdown/htmlToMarkdown.test.ts index 01dbeddae..f98a50637 100644 --- a/src/app/plugins/markdown/htmlToMarkdown.test.ts +++ b/src/app/plugins/markdown/htmlToMarkdown.test.ts @@ -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 = `

<${url}>

`; expect(htmlToMarkdown(html)).toBe(`[${url}](${url})`); }); diff --git a/src/app/plugins/markdown/htmlToMarkdown.ts b/src/app/plugins/markdown/htmlToMarkdown.ts index a7c6713f7..2ceb6d87e 100644 --- a/src/app/plugins/markdown/htmlToMarkdown.ts +++ b/src/app/plugins/markdown/htmlToMarkdown.ts @@ -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}||`; diff --git a/src/app/plugins/markdown/injectDataMd.ts b/src/app/plugins/markdown/injectDataMd.ts index ca1403650..059b054bf 100644 --- a/src/app/plugins/markdown/injectDataMd.ts +++ b/src/app/plugins/markdown/injectDataMd.ts @@ -88,6 +88,27 @@ export function injectDataMd(html: string): string { return `${content}`; }); + // Inject MFM color data-md on colored spans from other clients + html = html.replace( + /]*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 `${content}`; + } + ); + html = html.replace( + /]*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 `${content}`; + } + ); + // Inject inline code marker html = html.replace(/]*)>([^<]*)<\/code>/g, (_, attrs, content) => { if (attrs.includes('data-md')) return `${content}`; diff --git a/src/app/plugins/markdown/markdownToHtml.test.ts b/src/app/plugins/markdown/markdownToHtml.test.ts index a70540138..e1e36ee6b 100644 --- a/src/app/plugins/markdown/markdownToHtml.test.ts +++ b/src/app/plugins/markdown/markdownToHtml.test.ts @@ -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'); diff --git a/src/app/plugins/markdown/markdownToHtml.ts b/src/app/plugins/markdown/markdownToHtml.ts index 72a5b7f6d..dded0509c 100644 --- a/src/app/plugins/markdown/markdownToHtml.ts +++ b/src/app/plugins/markdown/markdownToHtml.ts @@ -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, diff --git a/src/app/utils/matrixHtml.test.ts b/src/app/utils/matrixHtml.test.ts new file mode 100644 index 000000000..00dd5704c --- /dev/null +++ b/src/app/utils/matrixHtml.test.ts @@ -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(); + }); +}); diff --git a/src/app/utils/matrixHtml.ts b/src/app/utils/matrixHtml.ts index 0176c804d..953496eea 100644 --- a/src/app/utils/matrixHtml.ts +++ b/src/app/utils/matrixHtml.ts @@ -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(); +}