From 756a7c8ff92a6890d0bd05d8a25c05bf07afe4e0 Mon Sep 17 00:00:00 2001 From: PacketByte Date: Tue, 10 Nov 2026 21:47:45 -0200 Subject: [PATCH 1/7] feat: render ANSI colored code blocks like Discord ```ansi blocks only differ by their color codes today, which the highlighter ignores and escapes raw. Parse the classic ESC[m sequences the reference reserves and wrap runs in fixed ansi-* spans, so only our own theme classes can ever reach the page. Unknown codes and stray escapes are dropped. Refs #1532. --- app/Services/CodeSpans.php | 59 +++++++++++++++++++++- resources/css/app.css | 73 +++++++++++++++++++++++++++ tests/Unit/Services/CodeSpansTest.php | 41 +++++++++++++++ 3 files changed, 172 insertions(+), 1 deletion(-) diff --git a/app/Services/CodeSpans.php b/app/Services/CodeSpans.php index 31a5fc7368..078a596fc1 100644 --- a/app/Services/CodeSpans.php +++ b/app/Services/CodeSpans.php @@ -160,7 +160,64 @@ private function block(string $part): array 'type' => 'block', 'language' => $language, 'filename' => $attributes['title'] ?? $attributes['filename'] ?? null, - 'html' => $this->highlighter->parse(implode("\n", array_slice($lines, 1, -1)), $language === null ? null : mb_strtolower($language)), + 'html' => $language !== null && mb_strtolower($language) === 'ansi' + ? $this->ansi(implode("\n", array_slice($lines, 1, -1))) + : $this->highlighter->parse(implode("\n", array_slice($lines, 1, -1)), $language === null ? null : mb_strtolower($language)), ]; } + + /** + * Renders an ANSI colored block the way Discord does: ESC[m runs set the style until ESC[0m resets it. + * Only the classic codes are supported (bold, underline, the 30-37 foreground and 40-47 background colors), which + * the reference reserves for this. Anything else, including a stray escape, is dropped so no control character + * reaches the page. Every span class comes from this fixed list, never from the code itself. + */ + private function ansi(string $code): string + { + $parts = preg_split('/\x1b\[([0-9;]*)m/', str_replace("\r\n", "\n", $code), -1, PREG_SPLIT_DELIM_CAPTURE) ?: []; + $html = ''; + $open = false; + $classes = []; + + foreach ($parts as $index => $part) { + if ($index % 2 === 1) { + if ($open) { + $html .= ''; + $open = false; + } + + foreach (explode(';', $part) as $value) { + $classes = match ($value) { + '', '0' => [], + '1' => [...array_diff($classes, ['ansi-1']), 'ansi-1'], + '4' => [...array_diff($classes, ['ansi-4']), 'ansi-4'], + '30', '31', '32', '33', '34', '35', '36', '37' => [ + ...array_filter($classes, static fn (string $class): bool => ! str_starts_with($class, 'ansi-3')), + "ansi-{$value}", + ], + '40', '41', '42', '43', '44', '45', '46', '47' => [ + ...array_filter($classes, static fn (string $class): bool => preg_match('/^ansi-4\d$/', $class) !== 1), + "ansi-{$value}", + ], + default => $classes, + }; + } + + if ($classes !== []) { + $html .= ''; + $open = true; + } + + continue; + } + + $text = str_replace("\x1b", '', $part); + + if ($text !== '') { + $html .= htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); + } + } + + return $open ? $html.'' : $html; + } } diff --git a/resources/css/app.css b/resources/css/app.css index c1291a8d2b..1c59233069 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -990,6 +990,79 @@ html body[data-scroll-locked] { color: var(--destructive); } + /* ANSI colored code blocks, the classic Discord codes only. */ + .ansi-1 { + font-weight: 700; + } + + .ansi-4 { + text-decoration: underline; + } + + .ansi-30 { + color: var(--foreground); + } + + .ansi-31 { + color: var(--destructive); + } + + .ansi-32 { + color: var(--lane-1); + } + + .ansi-33 { + color: var(--lane-5); + } + + .ansi-34 { + color: var(--primary); + } + + .ansi-35 { + color: var(--lane-4); + } + + .ansi-36 { + color: var(--lane-3); + } + + .ansi-37 { + color: var(--muted-foreground); + } + + .ansi-40 { + background-color: color-mix(in srgb, var(--foreground) 22%, transparent); + } + + .ansi-41 { + background-color: color-mix(in srgb, var(--destructive) 22%, transparent); + } + + .ansi-42 { + background-color: color-mix(in srgb, var(--lane-1) 22%, transparent); + } + + .ansi-43 { + background-color: color-mix(in srgb, var(--lane-5) 22%, transparent); + } + + .ansi-44 { + background-color: color-mix(in srgb, var(--primary) 22%, transparent); + } + + .ansi-45 { + background-color: color-mix(in srgb, var(--lane-4) 22%, transparent); + } + + .ansi-46 { + background-color: color-mix(in srgb, var(--lane-3) 22%, transparent); + } + + .ansi-47 { + background-color: color-mix(in srgb, var(--muted-foreground) 22%, transparent); + } + /* A GitHub profile README, sanitized on the server: it keeps GitHub's layout without GitHub's stylesheet. */ .readme { overflow-wrap: anywhere; diff --git a/tests/Unit/Services/CodeSpansTest.php b/tests/Unit/Services/CodeSpansTest.php index edc60e49cf..f603c630fc 100644 --- a/tests/Unit/Services/CodeSpansTest.php +++ b/tests/Unit/Services/CodeSpansTest.php @@ -222,3 +222,44 @@ ->toContain('evil.example') ->toContain('class="hl-operator"'); }); + +it('renders ANSI colors the way Discord does', function (): void { + $codeSpans = resolve(CodeSpans::class); + + expect($codeSpans->highlight("```ansi\n\x1b[1;32mBold green\x1b[0m plain\n```"))->toBe([ + [ + 'type' => 'block', + 'language' => 'ansi', + 'filename' => null, + 'html' => 'Bold green plain', + ], + ])->and($codeSpans->highlight("```ANSI\n\x1b[4;41;33mW\x1b[0m\n```"))->toBe([ + [ + 'type' => 'block', + 'language' => 'ANSI', + 'filename' => null, + 'html' => 'W', + ], + ]); +}); + +it('closes an ANSI style at the next sequence and at the end of the block', function (): void { + $codeSpans = resolve(CodeSpans::class); + + expect($codeSpans->highlight("```ansi\n\x1b[31mR\x1b[32mG\n```"))->toBe([ + [ + 'type' => 'block', + 'language' => 'ansi', + 'filename' => null, + 'html' => 'RG', + ], + ]); +}); + +it('escapes HTML inside ANSI code and drops unknown codes and stray escapes', function (): void { + $codeSpans = resolve(CodeSpans::class); + + $html = $codeSpans->highlight("```ansi\n\x1b[999mX\x1b\n```")[0]['html']; + + expect($html)->toBe('<b>X'); +}); From e205d712f166def0ba80e540c136199baadcf1fd Mon Sep 17 00:00:00 2001 From: PacketByte Date: Tue, 10 Nov 2026 22:25:00 -0200 Subject: [PATCH 2/7] feat: render Discord-style rich text in commit bodies Inline bold, italic, underline, strikethrough, spoilers, masked links and local timestamps, plus block headings, subtext and lists, and yellow fix code blocks. ANSI blocks from the earlier commit complete the set. Refs #1532. --- app/Services/CodeSpans.php | 12 +- resources/css/app.css | 42 +++- resources/js/components/commit-body.tsx | 182 +++++++++++++- resources/js/components/linkified-text.tsx | 279 ++++++++++++++++++++- tests/Unit/LinkifiedText.test.tsx | 107 +++++++- tests/Unit/Services/CodeSpansTest.php | 13 + 6 files changed, 618 insertions(+), 17 deletions(-) diff --git a/app/Services/CodeSpans.php b/app/Services/CodeSpans.php index 078a596fc1..cd71b6b96d 100644 --- a/app/Services/CodeSpans.php +++ b/app/Services/CodeSpans.php @@ -156,13 +156,19 @@ private function block(string $part): array } } + $code = implode("\n", array_slice($lines, 1, -1)); + return [ 'type' => 'block', 'language' => $language, 'filename' => $attributes['title'] ?? $attributes['filename'] ?? null, - 'html' => $language !== null && mb_strtolower($language) === 'ansi' - ? $this->ansi(implode("\n", array_slice($lines, 1, -1))) - : $this->highlighter->parse(implode("\n", array_slice($lines, 1, -1)), $language === null ? null : mb_strtolower($language)), + 'html' => match (mb_strtolower($language ?? '')) { + 'ansi' => $this->ansi($code), + // Tempest has no Fix grammar, but Discord colors these blocks yellow, so keep the escape-only + // rendering and paint it the same way. + 'fix' => ''.htmlspecialchars(str_replace("\r\n", "\n", $code), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8').'', + default => $this->highlighter->parse($code, $language === null ? null : mb_strtolower($language)), + }, ]; } diff --git a/resources/css/app.css b/resources/css/app.css index 1c59233069..9ae44934fb 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -990,6 +990,30 @@ html body[data-scroll-locked] { color: var(--destructive); } + .hl-fix { + color: var(--lane-5); + } + + /* Spoilers hide their text until tapped. */ + .spoiler { + border-radius: 0.25rem; + background-color: color-mix( + in srgb, + var(--foreground) 85%, + transparent + ); + color: transparent; + } + + .spoiler[data-revealed='true'] { + background-color: color-mix( + in srgb, + var(--foreground) 12%, + transparent + ); + color: inherit; + } + /* ANSI colored code blocks, the classic Discord codes only. */ .ansi-1 { font-weight: 700; @@ -1032,11 +1056,19 @@ html body[data-scroll-locked] { } .ansi-40 { - background-color: color-mix(in srgb, var(--foreground) 22%, transparent); + background-color: color-mix( + in srgb, + var(--foreground) 22%, + transparent + ); } .ansi-41 { - background-color: color-mix(in srgb, var(--destructive) 22%, transparent); + background-color: color-mix( + in srgb, + var(--destructive) 22%, + transparent + ); } .ansi-42 { @@ -1060,7 +1092,11 @@ html body[data-scroll-locked] { } .ansi-47 { - background-color: color-mix(in srgb, var(--muted-foreground) 22%, transparent); + background-color: color-mix( + in srgb, + var(--muted-foreground) 22%, + transparent + ); } /* A GitHub profile README, sanitized on the server: it keeps GitHub's layout without GitHub's stylesheet. */ diff --git a/resources/js/components/commit-body.tsx b/resources/js/components/commit-body.tsx index 1136c2c538..cb5879a145 100644 --- a/resources/js/components/commit-body.tsx +++ b/resources/js/components/commit-body.tsx @@ -63,6 +63,185 @@ export function CommitBody({ ); } +/** + * The block structure of a text segment: headings, subtext and lists render as blocks the way Discord does, + * anything else stays a paragraph with the usual inline rendering. + */ +const headingPattern = /^(#{1,3}) (.+)$/; +const subtextPattern = /^-# (.+)$/; +const listItemPattern = /^([-*]|\d+\.) (.+)$/; + +type TextBlock = + | { kind: 'paragraph'; text: string } + | { kind: 'heading'; level: number; text: string } + | { kind: 'subtext'; text: string } + | { kind: 'list'; ordered: boolean; start: number; items: string[] }; + +function splitTextBlocks(text: string): TextBlock[] { + const blocks: TextBlock[] = []; + let paragraph: string[] = []; + let list: TextBlock | null = null; + + const flushParagraph = (): void => { + if (paragraph.length > 0) { + blocks.push({ kind: 'paragraph', text: paragraph.join('\n') }); + paragraph = []; + } + }; + + const flushList = (): void => { + if (list !== null) { + blocks.push(list); + list = null; + } + }; + + for (const line of text.split('\n')) { + const heading = headingPattern.exec(line); + const subtext = subtextPattern.exec(line); + const item = listItemPattern.exec(line); + + if (heading !== null) { + flushParagraph(); + flushList(); + blocks.push({ + kind: 'heading', + level: heading[1].length, + text: heading[2], + }); + } else if (subtext !== null) { + flushParagraph(); + flushList(); + blocks.push({ kind: 'subtext', text: subtext[1] }); + } else if (item !== null) { + flushParagraph(); + const ordered = /^\d/.test(item[1]); + + if ( + list === null || + list.kind !== 'list' || + list.ordered !== ordered + ) { + flushList(); + list = { + kind: 'list', + ordered, + start: ordered ? Number.parseInt(item[1], 10) : 1, + items: [], + }; + } + + (list as { items: string[] }).items.push(item[2]); + } else { + flushList(); + paragraph.push(line); + } + } + + flushParagraph(); + flushList(); + + return blocks; +} + +function BodyTextBlocks({ + segmentKey, + text, + mentions, + organizationMentions = null, + pasteisMode, + isStatic, + linksEveryMention, +}: { + segmentKey: number; + text: string; + mentions: Commit['mentions']; + organizationMentions?: Commit['organization_mentions']; + pasteisMode: boolean; + isStatic: boolean; + linksEveryMention: boolean; +}) { + const shared = { + mentions, + organizationMentions, + pasteisMode, + isStatic, + linksEveryMention, + }; + + return ( + <> + {splitTextBlocks(text).map((block, index) => { + const key = `block-${segmentKey}-${index}`; + + if (block.kind === 'heading') { + const Heading = `h${block.level}` as 'h1' | 'h2' | 'h3'; + + return ( + + + + ); + } + + if (block.kind === 'subtext') { + return ( + + + + ); + } + + if (block.kind === 'list') { + const items = block.items.map((item, itemIndex) => ( +
  • + +
  • + )); + + return block.ordered ? ( +
      + {items} +
    + ) : ( +
      + {items} +
    + ); + } + + return ( + + ); + })} + + ); +} + export function BodySegments({ segments, mentions, @@ -84,8 +263,9 @@ export function BodySegments({ switch (segment.type) { case 'text': return ( - `[^`\n]*`)|(?\[(?[^\]\n]+)\]\((?https?:\/\/[^)\s]+)\))|(?\d+)(?::(?[tTdDfFR]))?>)|(?\|\|(?[\s\S]+?)\|\|)|(?\*\*(?[^*\n]+?)\*\*)|(?__(?[^_\n]+?)__)|(?~~(?[^~\n]+?)~~)|(?\*(?[^*\n]+?)\*)|(?_(?[^_\n]+?)_)/g; + +function isWordCharacter(character: string | undefined): boolean { + return character !== undefined && /[\p{L}\p{M}\p{N}_]/u.test(character); +} + +function SpoilerText({ + children, + isStatic, +}: { + children: ReactNode; + isStatic: boolean; +}) { + const [revealed, setRevealed] = useState(false); + + if (isStatic) { + return ( + + {children} + + ); + } + + return ( + + ); +} + +const timestampFormats: Record = { + t: { hour: 'numeric', minute: '2-digit' }, + T: { hour: 'numeric', minute: '2-digit', second: '2-digit' }, + d: { day: '2-digit', month: '2-digit', year: 'numeric' }, + D: { day: 'numeric', month: 'long', year: 'numeric' }, + f: { + day: 'numeric', + month: 'long', + year: 'numeric', + hour: 'numeric', + minute: '2-digit', + }, + F: { + weekday: 'long', + day: 'numeric', + month: 'long', + year: 'numeric', + hour: 'numeric', + minute: '2-digit', + }, +}; + +function TimestampText({ at, format }: { at: string; format: string }) { + const date = new Date(Number(at) * 1000); + + if (Number.isNaN(date.getTime())) { + return ``; + } + + if (format === 'R') { + return ( + + {formatRelativeTime(date.toISOString())} + + ); + } + + return ( + + {new Intl.DateTimeFormat( + undefined, + timestampFormats[format], + ).format(date)} + + ); +} + +function withRichInline( + text: string, + offset: number, + keyPrefix: string, + options: InlineOptions, +): ReactNode[] { + const parts: ReactNode[] = []; + let position = 0; + // Links resolve after this pass, so markers inside a URL are left alone for the link pass. + const linkRanges = [...text.matchAll(urlPattern)].map((link) => [ + link.index, + link.index + withoutTrailingPunctuation(link[0]).length, + ]); + + for (const match of text.matchAll(richInlinePattern)) { + const groups = match.groups ?? {}; + const index = match.index; + + if ( + linkRanges.some( + ([start, end]) => + index >= start && index + match[0].length <= end, + ) + ) { + continue; + } + + // Underscore italics only stand alone, so snake_case words keep their underscores. + if ( + groups.italicUnderContent !== undefined && + (isWordCharacter(text[index - 1]) || + isWordCharacter(text[index + match[0].length])) + ) { + continue; + } + + parts.push( + ...withLinksAndMentions( + text.slice(position, index), + offset + position, + keyPrefix, + options, + ), + ); + position = index + match[0].length; + + const key = `${keyPrefix}-${offset + index}`; + const nested = (inner: string, shift: number): ReactNode[] => + withRichInline( + inner, + offset + index + shift, + `${keyPrefix}-nested`, + options, + ); + + if (groups.code !== undefined) { + parts.push(match[0]); + } else if (groups.maskedLabel !== undefined) { + const href = hrefFor(groups.maskedUrl); + + if (href === null) { + parts.push(match[0]); + } else if (options.isStatic) { + parts.push( + + {nested(groups.maskedLabel, 1)} + , + ); + } else { + parts.push( + + {nested(groups.maskedLabel, 1)} + , + ); + } + } else if (groups.timestampAt !== undefined) { + parts.push( + , + ); + } else if (groups.spoilerContent !== undefined) { + parts.push( + + {nested(groups.spoilerContent, 2)} + , + ); + } else if (groups.boldContent !== undefined) { + parts.push( + {nested(groups.boldContent, 2)}, + ); + } else if (groups.underlineContent !== undefined) { + parts.push({nested(groups.underlineContent, 2)}); + } else if (groups.strikeContent !== undefined) { + parts.push({nested(groups.strikeContent, 2)}); + } else if (groups.italicStarContent !== undefined) { + parts.push( + {nested(groups.italicStarContent, 1)}, + ); + } else if (groups.italicUnderContent !== undefined) { + parts.push( + {nested(groups.italicUnderContent, 1)}, + ); + } + } + + parts.push( + ...withLinksAndMentions( + text.slice(position), + offset + position, + keyPrefix, + options, + ), + ); + + return parts; +} + export function LinkifiedText({ text, mentions, @@ -848,11 +1078,42 @@ export function LinkifiedText({ // Whether the text is a whole body, so its start is the start of a line. startsText?: boolean; }) { - const parts: ReactNode[] = []; // Colors are found in the prose only, for callers that pass a whole body, code included. const prose = withoutCode(text); const colors = colorsIn(prose, startsText); const hashtags = isStatic ? [] : [...prose.matchAll(hashtagPattern)]; + + return ( + <> + {withRichInline(text, 0, 'rich', { + mentions, + organizationMentions, + colors, + hashtags, + pasteisMode, + isStatic, + linksEveryMention, + })} + + ); +} + +function withLinksAndMentions( + text: string, + offset: number, + keyPrefix: string, + options: InlineOptions, +): ReactNode[] { + const { + mentions, + organizationMentions, + colors, + hashtags, + pasteisMode, + isStatic, + linksEveryMention, + } = options; + const parts: ReactNode[] = []; let position = 0; for (const match of text.matchAll(urlPattern)) { @@ -869,7 +1130,7 @@ export function LinkifiedText({ parts.push( ...withMentions( text.slice(position, match.index), - position, + offset + position, mentions, organizationMentions, colors, @@ -880,7 +1141,7 @@ export function LinkifiedText({ ), commitLink ? ( ) : forgeLink ? ( {parts}; + return parts; } diff --git a/tests/Unit/LinkifiedText.test.tsx b/tests/Unit/LinkifiedText.test.tsx index d963024a18..1fbeef5c8c 100644 --- a/tests/Unit/LinkifiedText.test.tsx +++ b/tests/Unit/LinkifiedText.test.tsx @@ -7,7 +7,10 @@ import { test } from 'vite-plus/test'; import { BodyCounter } from '../../resources/js/components/body-counter'; import { ConversationList } from '../../resources/js/components/chat/conversation-list'; import { MessageText } from '../../resources/js/components/chat/message-parts'; -import { CommitBody } from '../../resources/js/components/commit-body'; +import { + BodySegments, + CommitBody, +} from '../../resources/js/components/commit-body'; import { LinkifiedText, typedLinks, @@ -988,3 +991,105 @@ for (const link of [ assert.ok(markup.includes(`href="${link}"`)); }); } + +test('renders Discord inline styles and leaves snake_case alone', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('bold')); + assert.ok(markup.includes('star')); + assert.ok(markup.includes('under')); + assert.ok(markup.includes('line')); + assert.ok(markup.includes('gone')); + assert.ok(markup.includes('foo_bar_baz')); + assert.ok(!markup.includes('bar')); +}); + +test('keeps inline code free of styling', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('**not bold**')); + assert.ok(!markup.includes('')); +}); + +test('renders masked links with their label and keeps invalid ones raw', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('href="https://example.com/docs"')); + assert.ok(markup.includes('>the docs')); + assert.ok(markup.includes('[nope](not a url)')); +}); + +test('resolves mentions inside bold text', () => { + const id = '019a2b3c-4d5e-7f60-8a9b-0c1d2e3f4a5b'; + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('')); + assert.ok(markup.includes(`href="/mentions/${id}"`)); +}); + +test('renders timestamps as local times and relative times', () => { + const absolute = renderToStaticMarkup( + , + ); + const relative = renderToStaticMarkup( + , + ); + + for (const markup of [absolute, relative]) { + assert.ok(markup.includes('data-test="timestamp"')); + assert.ok(!markup.includes(' { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('data-test="spoiler"')); + assert.ok(markup.includes('data-revealed="false"')); + assert.ok(markup.includes('secret')); + assert.ok(markup.includes('||half')); +}); + +test('renders headings, subtext and lists as blocks', () => { + const markup = renderPage( + , + ); + + assert.ok(markup.includes('')); + assert.ok(markup.includes('bold')); +}); diff --git a/tests/Unit/Services/CodeSpansTest.php b/tests/Unit/Services/CodeSpansTest.php index f603c630fc..6e9e3a4e14 100644 --- a/tests/Unit/Services/CodeSpansTest.php +++ b/tests/Unit/Services/CodeSpansTest.php @@ -263,3 +263,16 @@ expect($html)->toBe('<b>X'); }); + +it('paints fix blocks yellow the way Discord does', function (): void { + $codeSpans = resolve(CodeSpans::class); + + expect($codeSpans->highlight("```fix\n[x] \n```"))->toBe([ + [ + 'type' => 'block', + 'language' => 'fix', + 'filename' => null, + 'html' => '[x] <b>', + ], + ]); +}); From 82513f561e9473419361efb2070b78bf6bf09e2f Mon Sep 17 00:00:00 2001 From: PacketByte Date: Tue, 10 Nov 2026 23:00:42 -0200 Subject: [PATCH 3/7] fix: harden rich text per review Keep style markers attached to words, hide spoiler subtrees, block out subtext, scope link keys, flatten masked labels, word future timestamps and use the app locale and clock. Refs #1532. --- resources/css/app.css | 5 ++ resources/js/components/commit-body.tsx | 2 +- resources/js/components/linkified-text.tsx | 86 ++++++++++++++++------ tests/Unit/LinkifiedText.test.tsx | 69 +++++++++++++++++ 4 files changed, 139 insertions(+), 23 deletions(-) diff --git a/resources/css/app.css b/resources/css/app.css index 9ae44934fb..16672e54b1 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -1005,6 +1005,11 @@ html body[data-scroll-locked] { color: transparent; } + /* Colored children like links would shine through, so hide the whole subtree. */ + .spoiler:not([data-revealed='true']) * { + visibility: hidden; + } + .spoiler[data-revealed='true'] { background-color: color-mix( in srgb, diff --git a/resources/js/components/commit-body.tsx b/resources/js/components/commit-body.tsx index cb5879a145..5bd5589e28 100644 --- a/resources/js/components/commit-body.tsx +++ b/resources/js/components/commit-body.tsx @@ -201,7 +201,7 @@ function BodyTextBlocks({ return ( `[^`\n]*`)|(?\[(?[^\]\n]+)\]\((?https?:\/\/[^)\s]+)\))|(?\d+)(?::(?[tTdDfFR]))?>)|(?\|\|(?[\s\S]+?)\|\|)|(?\*\*(?[^*\n]+?)\*\*)|(?__(?[^_\n]+?)__)|(?~~(?[^~\n]+?)~~)|(?\*(?[^*\n]+?)\*)|(?_(?[^_\n]+?)_)/g; + /(?`[^`\n]*`)|(?\[(?[^\]\n]+)\]\((?https?:\/\/[^)\s]+)\))|(?\d+)(?::(?[tTdDfFR]))?>)|(?\|\|(?[\s\S]+?)\|\|)|(?\*\*(?[^\s*](?:[^*\n]*?[^\s*])?)\*\*)|(?__(?[^\s_](?:[^_\n]*?[^\s_])?)__)|(?~~(?[^\s~](?:[^~\n]*?[^\s~])?)~~)|(?\*(?[^\s*](?:[^*\n]*?[^\s*])?)\*)|(?_(?[^\s_](?:[^_\n]*?[^\s_])?)_)/g; function isWordCharacter(character: string | undefined): boolean { return character !== undefined && /[\p{L}\p{M}\p{N}_]/u.test(character); @@ -904,35 +910,61 @@ const timestampFormats: Record = { function TimestampText({ at, format }: { at: string; format: string }) { const date = new Date(Number(at) * 1000); + const timeZone = readerClock().timeZone; if (Number.isNaN(date.getTime())) { return ``; } + const absolute = (options: Intl.DateTimeFormatOptions): string => + new Intl.DateTimeFormat(dateLocale, { timeZone, ...options }).format( + date, + ); + if (format === 'R') { + const title = absolute({ dateStyle: 'full', timeStyle: 'long' }); + const ahead = Math.round((date.getTime() - Date.now()) / 1000); + + if (ahead >= 60) { + return ( + + in {formatFuture(ahead)} + + ); + } + return ( - + {formatRelativeTime(date.toISOString())} ); } return ( - - {new Intl.DateTimeFormat( - undefined, - timestampFormats[format], - ).format(date)} - + {absolute(timestampFormats[format])} ); } +function formatFuture(totalSeconds: number): string { + if (totalSeconds < 3600) { + return `${Math.floor(totalSeconds / 60)}m`; + } + + if (totalSeconds < 86400) { + return `${Math.floor(totalSeconds / 3600)}h`; + } + + if (totalSeconds < 604800) { + return `${Math.floor(totalSeconds / 86400)}d`; + } + + return new Intl.DateTimeFormat(dateLocale, { + timeZone: readerClock().timeZone, + month: 'short', + day: 'numeric', + }).format(new Date(Date.now() + totalSeconds * 1000)); +} + function withRichInline( text: string, offset: number, @@ -980,12 +1012,16 @@ function withRichInline( position = index + match[0].length; const key = `${keyPrefix}-${offset + index}`; - const nested = (inner: string, shift: number): ReactNode[] => + const nested = ( + inner: string, + shift: number, + nestedOptions: InlineOptions = options, + ): ReactNode[] => withRichInline( inner, offset + index + shift, `${keyPrefix}-nested`, - options, + nestedOptions, ); if (groups.code !== undefined) { @@ -998,7 +1034,10 @@ function withRichInline( } else if (options.isStatic) { parts.push( - {nested(groups.maskedLabel, 1)} + {nested(groups.maskedLabel, 1, { + ...options, + isStatic: true, + })} , ); } else { @@ -1011,7 +1050,10 @@ function withRichInline( title={href} className="wrap-anywhere text-primary hover:underline" > - {nested(groups.maskedLabel, 1)} + {nested(groups.maskedLabel, 1, { + ...options, + isStatic: true, + })} , ); } @@ -1141,7 +1183,7 @@ function withLinksAndMentions( ), commitLink ? ( ) : forgeLink ? ( { assert.ok(markup.includes('
  • ')); assert.ok(markup.includes('bold')); }); + +test('leaves math, globs and kwargs markers alone', () => { + for (const text of [ + '2 * 3 * 4', + 'update *.php and *.js', + 'pass **kwargs and **opts', + ]) { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(!markup.includes(''), text); + assert.ok(!markup.includes(''), text); + assert.ok(markup.includes(text), text); + } +}); + +test('keeps links in separate slices distinct', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('href="https://example.com/a"')); + assert.ok(markup.includes('href="https://example.com/b"')); +}); + +test('never nests links inside masked labels', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.strictEqual(markup.match(/ { + const markup = renderPage( + , + ); + + assert.ok(markup.includes('block text-sm text-muted-foreground')); +}); + +test('words future timestamps as upcoming', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('data-test="timestamp"')); + assert.ok(markup.includes('in ')); +}); + +test('keeps linked children inside hidden spoilers', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('data-test="spoiler"')); + assert.ok(markup.includes('href="https://example.com"')); +}); From 389efc2a3978e39931aec3a40d144e0ddc844bb4 Mon Sep 17 00:00:00 2001 From: PacketByte Date: Thu, 12 Nov 2026 08:54:54 -0200 Subject: [PATCH 4/7] fix: keep fenced code verbatim and hide static spoilers - split fenced blocks out before rich inline formatting, rendering them verbatim (fixes formatting leaking into code from whole bodies) - text segments render fenced blocks as code, not paragraphs - static spoilers omit hidden content instead of revealing it - document the new rich-text helpers --- resources/js/components/commit-body.tsx | 51 ++++++++++++++ resources/js/components/linkified-text.tsx | 80 ++++++++++++++++++---- resources/js/lib/code.ts | 41 ++++++++++- tests/Unit/LinkifiedText.test.tsx | 57 +++++++++++++++ 4 files changed, 213 insertions(+), 16 deletions(-) diff --git a/resources/js/components/commit-body.tsx b/resources/js/components/commit-body.tsx index 5bd5589e28..8514d2840e 100644 --- a/resources/js/components/commit-body.tsx +++ b/resources/js/components/commit-body.tsx @@ -75,12 +75,22 @@ type TextBlock = | { kind: 'paragraph'; text: string } | { kind: 'heading'; level: number; text: string } | { kind: 'subtext'; text: string } + | { kind: 'code'; text: string } | { kind: 'list'; ordered: boolean; start: number; items: string[] }; +/** + * A fenced code block opens on a line starting with three or more backticks, like the committed-code pattern in + * lib/code, and runs to a line that is only backticks, or to the end of the text when never closed. + */ +const fencePattern = /^(`{3,})[^`]*$/; +const fenceClosePattern = /^`{3,}\s*$/; + function splitTextBlocks(text: string): TextBlock[] { const blocks: TextBlock[] = []; let paragraph: string[] = []; let list: TextBlock | null = null; + let fence: string[] | null = null; + let fenceRun = ''; const flushParagraph = (): void => { if (paragraph.length > 0) { @@ -97,6 +107,32 @@ function splitTextBlocks(text: string): TextBlock[] { }; for (const line of text.split('\n')) { + if (fence !== null) { + if ( + fenceClosePattern.test(line) && + line.replace(/\s/g, '').length >= fenceRun.length + ) { + fence.push(line); + blocks.push({ kind: 'code', text: fence.join('\n') }); + fence = null; + } else { + fence.push(line); + } + + continue; + } + + const fenceOpen = fencePattern.exec(line); + + if (fenceOpen !== null) { + flushParagraph(); + flushList(); + fence = [line]; + fenceRun = fenceOpen[1]; + + continue; + } + const heading = headingPattern.exec(line); const subtext = subtextPattern.exec(line); const item = listItemPattern.exec(line); @@ -141,6 +177,10 @@ function splitTextBlocks(text: string): TextBlock[] { flushParagraph(); flushList(); + if (fence !== null) { + blocks.push({ kind: 'code', text: fence.join('\n') }); + } + return blocks; } @@ -234,6 +274,17 @@ function BodyTextBlocks({ ); } + if (block.kind === 'code') { + return ( +
    +                            {block.text}
    +                        
    + ); + } + return ( ); diff --git a/resources/js/components/linkified-text.tsx b/resources/js/components/linkified-text.tsx index 0581e52a04..71ef5d8d4d 100644 --- a/resources/js/components/linkified-text.tsx +++ b/resources/js/components/linkified-text.tsx @@ -11,7 +11,7 @@ import { CodebergIcon } from '@/components/codeberg-icon'; import { GitHubIcon } from '@/components/github-icon'; import { GitLabIcon } from '@/components/gitlab-icon'; import { UserPreview } from '@/components/user-preview'; -import { typedProse, withoutCode } from '@/lib/code'; +import { splitFencedCode, typedProse, withoutCode } from '@/lib/code'; import type { Color } from '@/lib/colors'; import { colorsIn } from '@/lib/colors'; import { mentionPattern } from '@/lib/mentions'; @@ -852,10 +852,17 @@ type InlineOptions = { const richInlinePattern = /(?`[^`\n]*`)|(?\[(?[^\]\n]+)\]\((?https?:\/\/[^)\s]+)\))|(?\d+)(?::(?[tTdDfFR]))?>)|(?\|\|(?[\s\S]+?)\|\|)|(?\*\*(?[^\s*](?:[^*\n]*?[^\s*])?)\*\*)|(?__(?[^\s_](?:[^_\n]*?[^\s_])?)__)|(?~~(?[^\s~](?:[^~\n]*?[^\s~])?)~~)|(?\*(?[^\s*](?:[^*\n]*?[^\s*])?)\*)|(?_(?[^\s_](?:[^_\n]*?[^\s_])?)_)/g; +/** + * Whether the character counts as part of a word, so underscore italics keep their underscores in snake_case. + */ function isWordCharacter(character: string | undefined): boolean { return character !== undefined && /[\p{L}\p{M}\p{N}_]/u.test(character); } +/** + * Hides the children behind a tap to reveal, holding them back only while hidden so nothing interactive escapes. + * Static previews offer no tap, so they omit the hidden content entirely. + */ function SpoilerText({ children, isStatic, @@ -866,11 +873,8 @@ function SpoilerText({ const [revealed, setRevealed] = useState(false); if (isStatic) { - return ( - - {children} - - ); + // Static previews offer no tap to reveal with, so the hidden content stays out entirely. + return ; } return ( @@ -908,6 +912,9 @@ const timestampFormats: Record = { }, }; +/** + * Renders a Discord-style timestamp, wording near-future relative times as upcoming and the rest absolutely. + */ function TimestampText({ at, format }: { at: string; format: string }) { const date = new Date(Number(at) * 1000); const timeZone = readerClock().timeZone; @@ -945,6 +952,9 @@ function TimestampText({ at, format }: { at: string; format: string }) { ); } +/** + * Words a future distance in the largest fitting unit, for upcoming timestamps. + */ function formatFuture(totalSeconds: number): string { if (totalSeconds < 3600) { return `${Math.floor(totalSeconds / 60)}m`; @@ -965,6 +975,10 @@ function formatFuture(totalSeconds: number): string { }).format(new Date(Date.now() + totalSeconds * 1000)); } +/** + * Applies the rich inline pass to a prose slice: code, masked links, timestamps, spoilers, emphasis and mentions, + * in that order, with absolute offsets so keys stay stable across slices. + */ function withRichInline( text: string, offset: number, @@ -1125,21 +1139,59 @@ export function LinkifiedText({ const colors = colorsIn(prose, startsText); const hashtags = isStatic ? [] : [...prose.matchAll(hashtagPattern)]; + // Fenced code stays verbatim: formatting only runs on the prose around it, so whole bodies from any caller, + // suggestions included, keep their code blocks intact. Colors and hashtags keep whole-text indexes; each slice + // ignores the ones outside it. Without fences this is exactly the old single pass, same elements and keys. + const segments = splitFencedCode(text); + + if (segments.length === 1 && !segments[0].code) { + return ( + <> + {withRichInline(text, 0, 'rich', { + mentions, + organizationMentions, + colors, + hashtags, + pasteisMode, + isStatic, + linksEveryMention, + })} + + ); + } + + let offset = 0; + return ( <> - {withRichInline(text, 0, 'rich', { - mentions, - organizationMentions, - colors, - hashtags, - pasteisMode, - isStatic, - linksEveryMention, + {segments.map((segment, index) => { + const segmentOffset = offset; + offset += segment.text.length; + + return segment.code ? ( + {segment.text} + ) : ( + + {withRichInline(segment.text, segmentOffset, 'rich', { + mentions, + organizationMentions, + colors, + hashtags, + pasteisMode, + isStatic, + linksEveryMention, + })} + + ); })} ); } +/** + * Links the URLs, forge references, commits, colors, hashtags and mentions in plain prose, leaving code to its own + * pass. Static mode flattens links to text so no anchor nests inside a masked label. + */ function withLinksAndMentions( text: string, offset: number, diff --git a/resources/js/lib/code.ts b/resources/js/lib/code.ts index a00a5989d1..5129493280 100644 --- a/resources/js/lib/code.ts +++ b/resources/js/lib/code.ts @@ -2,14 +2,51 @@ import type { BodySegment } from '@/types'; // Keep in sync with app/Services/CodeSpans.php: a fenced code block, from a line starting with ``` or more (and maybe // a language) to a line that is only as many backticks or more, so a block can hold a shorter fence, or inline code -// between two backticks on one line. -const committedCode = String.raw`(? position) { + parts.push({ + code: false, + text: text.slice(position, match.index), + }); + } + + parts.push({ code: true, text: match[0] }); + position = match.index + match[0].length; + } + + if (position < text.length) { + parts.push({ code: false, text: text.slice(position) }); + } + + return parts; +} + /** * Splits the text into prose and code, alternating: even indexes are prose (maybe empty), odd ones are code. The * fence the pattern captures to close a block isn't a part. diff --git a/tests/Unit/LinkifiedText.test.tsx b/tests/Unit/LinkifiedText.test.tsx index 5c814886e8..5112613319 100644 --- a/tests/Unit/LinkifiedText.test.tsx +++ b/tests/Unit/LinkifiedText.test.tsx @@ -1094,6 +1094,26 @@ test('renders headings, subtext and lists as blocks', () => { assert.ok(markup.includes('bold')); }); +test('keeps fenced blocks verbatim in text segments', () => { + const markup = renderPage( + , + ); + + assert.ok(markup.includes('not bold
    ')); + assert.ok(!markup.includes('href="https://example.com"')); + assert.ok(markup.includes('bold')); +}); + test('leaves math, globs and kwargs markers alone', () => { for (const text of [ '2 * 3 * 4', @@ -1152,6 +1172,16 @@ test('words future timestamps as upcoming', () => { assert.ok(markup.includes('data-test="timestamp"')); assert.ok(markup.includes('in ')); + + const soon = renderToStaticMarkup( + o clock`} + mentions={null} + />, + ); + + assert.ok(soon.includes('data-test="timestamp"')); + assert.ok(soon.includes('in 2h')); }); test('keeps linked children inside hidden spoilers', () => { @@ -1160,5 +1190,32 @@ test('keeps linked children inside hidden spoilers', () => { ); assert.ok(markup.includes('data-test="spoiler"')); + assert.ok(markup.includes('data-revealed="false"')); assert.ok(markup.includes('href="https://example.com"')); }); + +test('leaves fenced code verbatim while formatting the prose around it', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('bold')); + assert.ok(markup.includes('**not bold** https://example.com')); + assert.ok(!markup.includes('not bold')); + assert.ok(!markup.includes('href="https://example.com"')); + assert.ok(markup.includes('href="/@Original"')); +}); + +test('omits spoiler content from static previews', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('data-revealed="false"')); + assert.ok(!markup.includes('secret')); +}); From 1f21e8df666ba6b88dee498eba802684bfad13c6 Mon Sep 17 00:00:00 2001 From: PacketByte Date: Thu, 12 Nov 2026 09:55:50 -0200 Subject: [PATCH 5/7] fix: unfinished fences stay verbatim, imminent timestamps read soon - unclosed trailing fences render as code in whole-body rendering, matching the text blocks - timestamps under a minute out render soon instead of now - regression test against nested anchors in masked labels --- resources/js/components/linkified-text.tsx | 8 +++++ resources/js/lib/code.ts | 16 +++++++-- tests/Unit/LinkifiedText.test.tsx | 38 ++++++++++++++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/resources/js/components/linkified-text.tsx b/resources/js/components/linkified-text.tsx index 71ef5d8d4d..32ba1c9837 100644 --- a/resources/js/components/linkified-text.tsx +++ b/resources/js/components/linkified-text.tsx @@ -940,6 +940,14 @@ function TimestampText({ at, format }: { at: string; format: string }) { ); } + if (ahead >= 0) { + return ( + + soon + + ); + } + return ( {formatRelativeTime(date.toISOString())} diff --git a/resources/js/lib/code.ts b/resources/js/lib/code.ts index 5129493280..3b8ef1604c 100644 --- a/resources/js/lib/code.ts +++ b/resources/js/lib/code.ts @@ -19,12 +19,14 @@ const typedCodePattern = new RegExp( /** * Splits the text at committed fenced code blocks, keeping exact spans: each part is either prose or a whole fenced * block, in order, with nothing dropped, so callers can leave code verbatim. Inline code stays prose here; the - * inline pass handles it. + * inline pass handles it. A fence that never closes runs to the end of the text, the way typing already treats it, + * so both whole-body paths agree. */ export function splitFencedCode( text: string, ): { code: boolean; text: string }[] { const pattern = new RegExp(fencedBlock, 'g'); + const unclosedPattern = /(? 0) { + parts.push({ code: false, text: tail.slice(0, unclosed.index) }); + } + + parts.push({ + code: unclosed !== null, + text: unclosed !== null ? tail.slice(unclosed.index) : tail, + }); } return parts; diff --git a/tests/Unit/LinkifiedText.test.tsx b/tests/Unit/LinkifiedText.test.tsx index 5112613319..c188849d23 100644 --- a/tests/Unit/LinkifiedText.test.tsx +++ b/tests/Unit/LinkifiedText.test.tsx @@ -1114,6 +1114,20 @@ test('keeps fenced blocks verbatim in text segments', () => { assert.ok(markup.includes('bold')); }); +test('keeps an unfinished fence verbatim like the text blocks do', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('bold')); + assert.ok(markup.includes('```js\n**not bold** https://example.com')); + assert.ok(!markup.includes('not bold')); + assert.ok(!markup.includes('href="https://example.com"')); +}); + test('leaves math, globs and kwargs markers alone', () => { for (const text of [ '2 * 3 * 4', @@ -1182,6 +1196,17 @@ test('words future timestamps as upcoming', () => { assert.ok(soon.includes('data-test="timestamp"')); assert.ok(soon.includes('in 2h')); + + const imminent = renderToStaticMarkup( + o clock`} + mentions={null} + />, + ); + + assert.ok(imminent.includes('data-test="timestamp"')); + assert.ok(imminent.includes('soon')); + assert.ok(!imminent.includes('now')); }); test('keeps linked children inside hidden spoilers', () => { @@ -1219,3 +1244,16 @@ test('omits spoiler content from static previews', () => { assert.ok(markup.includes('data-revealed="false"')); assert.ok(!markup.includes('secret')); }); + +test('never nests an anchor inside a masked label', () => { + for (const text of [ + '[https://a.com](https://b.com)', + '[see @Original](https://example.com)', + ]) { + const markup = renderToStaticMarkup( + , + ); + + assert.equal(markup.match(/]/g)?.length, 1, text); + } +}); From d005585504055e9829bfa9c803b7f4bf68861e1e Mon Sep 17 00:00:00 2001 From: PacketByte Date: Thu, 12 Nov 2026 10:20:48 -0200 Subject: [PATCH 6/7] fix: keep hashtags out of masked labels when signed in - clear precomputed hashtags in the masked-label recursion so a signed-in user never gets a Link nested inside the outer anchor - signed-in regression test: top-level hashtags still link, masked ones stay plain --- resources/js/components/linkified-text.tsx | 1 + tests/Unit/LinkifiedText.test.tsx | 24 ++++++++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/resources/js/components/linkified-text.tsx b/resources/js/components/linkified-text.tsx index 32ba1c9837..51a786082b 100644 --- a/resources/js/components/linkified-text.tsx +++ b/resources/js/components/linkified-text.tsx @@ -1075,6 +1075,7 @@ function withRichInline( {nested(groups.maskedLabel, 1, { ...options, isStatic: true, + hashtags: [], })} , ); diff --git a/tests/Unit/LinkifiedText.test.tsx b/tests/Unit/LinkifiedText.test.tsx index c188849d23..8a48ab1efd 100644 --- a/tests/Unit/LinkifiedText.test.tsx +++ b/tests/Unit/LinkifiedText.test.tsx @@ -82,7 +82,7 @@ test('the counter discounts commit links but not issue links', () => { ); }); -function renderPage(content: ReactElement): string { +function renderPage(content: ReactElement, user: unknown = null): string { return renderToStaticMarkup( content} @@ -91,7 +91,7 @@ function renderPage(content: ReactElement): string { component: 'Commit', url: '/', version: null, - props: { errors: {}, auth: { user: null, pasteis: null } }, + props: { errors: {}, auth: { user, pasteis: null } }, clearHistory: false, encryptHistory: false, } as unknown as ComponentProps['initialPage'] @@ -1257,3 +1257,23 @@ test('never nests an anchor inside a masked label', () => { assert.equal(markup.match(/]/g)?.length, 1, text); } }); + +test('keeps hashtags plain inside masked labels when signed in', () => { + const user = { id: 1 }; + + const topLevel = renderPage( + , + user, + ); + + assert.ok(topLevel.includes('data-test="hashtag"')); + + const masked = renderPage( + , + user, + ); + + assert.equal(masked.match(/]/g)?.length, 1); + assert.ok(masked.includes('#topic')); + assert.ok(!masked.includes('data-test="hashtag"')); +}); From 1b9d704a46ab4b2b4e8a33653b381ca07a03a6a7 Mon Sep 17 00:00:00 2001 From: PacketByte Date: Thu, 19 Nov 2026 04:45:53 -0500 Subject: [PATCH 7/7] feat: harden rich inline markdown per review --- resources/css/app.css | 11 +- resources/js/components/linkified-text.tsx | 50 +++++---- tests/Unit/LinkifiedText.test.tsx | 119 ++++++++++++++++----- 3 files changed, 129 insertions(+), 51 deletions(-) diff --git a/resources/css/app.css b/resources/css/app.css index 16672e54b1..cde3620030 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -1005,11 +1005,18 @@ html body[data-scroll-locked] { color: transparent; } - /* Colored children like links would shine through, so hide the whole subtree. */ - .spoiler:not([data-revealed='true']) * { + /* Colored children like links would shine through, so the content hides as a whole. */ + .spoiler:not([data-revealed='true']) .spoiler-content { visibility: hidden; } + /* The reveal control sits beside the content and stays readable on the hidden block. */ + .spoiler-toggle { + color: var(--background); + text-decoration: underline; + font-size: 0.75rem; + } + .spoiler[data-revealed='true'] { background-color: color-mix( in srgb, diff --git a/resources/js/components/linkified-text.tsx b/resources/js/components/linkified-text.tsx index 8344fa4d82..d7337a8e49 100644 --- a/resources/js/components/linkified-text.tsx +++ b/resources/js/components/linkified-text.tsx @@ -906,7 +906,7 @@ type InlineOptions = { // pieces recurse through the same pass, so mentions and links still resolve inside bold or spoilers. Plain // `code` passes through untouched. const richInlinePattern = - /(?`[^`\n]*`)|(?\[(?[^\]\n]+)\]\((?https?:\/\/[^)\s]+)\))|(?\d+)(?::(?[tTdDfFR]))?>)|(?\|\|(?[\s\S]+?)\|\|)|(?\*\*(?[^\s*](?:[^*\n]*?[^\s*])?)\*\*)|(?__(?[^\s_](?:[^_\n]*?[^\s_])?)__)|(?~~(?[^\s~](?:[^~\n]*?[^\s~])?)~~)|(?\*(?[^\s*](?:[^*\n]*?[^\s*])?)\*)|(?_(?[^\s_](?:[^_\n]*?[^\s_])?)_)/g; + /(?`[^`\n]*`)|(?\[(?[^\]\n]+)\]\((?https?:\/\/(?:[^()\s]|\([^()\s]*\))*)\))|(?\d+)(?::(?[tTdDfFR]))?>)|(?\|\|(?[\s\S]+?)\|\|)|(?\*\*\*(?[^\s*](?:[^*\n]*?[^\s*])?)\*\*\*)|(?\*\*(?[^\s*](?:[^*\n]*?[^\s*])?)\*\*)|(?__(?[^\s_](?:[^_\n]*?[^\s_])?)__)|(?~~(?[^\s~](?:[^~\n]*?[^\s~])?)~~)|(?\*(?[^\s*](?:[^*\n]*?[^\s*])?)\*)|(?_(?[^\s_](?:[^_\n]*?[^\s_])?)_)/g; /** * Whether the character counts as part of a word, so underscore italics keep their underscores in snake_case. @@ -917,7 +917,8 @@ function isWordCharacter(character: string | undefined): boolean { /** * Hides the children behind a tap to reveal, holding them back only while hidden so nothing interactive escapes. - * Static previews offer no tap, so they omit the hidden content entirely. + * The reveal control and the content are siblings, so links never land inside the button and the button's + * accessible name never leaks the hidden text. Static previews offer no tap, so they omit the content entirely. */ function SpoilerText({ children, @@ -934,15 +935,17 @@ function SpoilerText({ } return ( - + + {' '} + {children} + ); } @@ -991,7 +994,7 @@ function TimestampText({ at, format }: { at: string; format: string }) { if (ahead >= 60) { return ( - in {formatFuture(ahead)} + in {formatFuture(ahead, date)} ); } @@ -1019,7 +1022,7 @@ function TimestampText({ at, format }: { at: string; format: string }) { /** * Words a future distance in the largest fitting unit, for upcoming timestamps. */ -function formatFuture(totalSeconds: number): string { +function formatFuture(totalSeconds: number, target: Date): string { if (totalSeconds < 3600) { return `${Math.floor(totalSeconds / 60)}m`; } @@ -1036,7 +1039,7 @@ function formatFuture(totalSeconds: number): string { timeZone: readerClock().timeZone, month: 'short', day: 'numeric', - }).format(new Date(Date.now() + totalSeconds * 1000)); + }).format(target); } /** @@ -1061,12 +1064,8 @@ function withRichInline( const groups = match.groups ?? {}; const index = match.index; - if ( - linkRanges.some( - ([start, end]) => - index >= start && index + match[0].length <= end, - ) - ) { + // A match opening inside a bare URL belongs to the URL, even when it runs past it. + if (linkRanges.some(([start, end]) => index >= start && index < end)) { continue; } @@ -1146,10 +1145,19 @@ function withRichInline( ); } else if (groups.spoilerContent !== undefined) { parts.push( - + {nested(groups.spoilerContent, 2)} , ); + } else if (groups.boldItalicContent !== undefined) { + parts.push( + + {nested(groups.boldItalicContent, 3)} + , + ); } else if (groups.boldContent !== undefined) { parts.push( {nested(groups.boldContent, 2)}, diff --git a/tests/Unit/LinkifiedText.test.tsx b/tests/Unit/LinkifiedText.test.tsx index 77f9a79fd9..3a93639bc0 100644 --- a/tests/Unit/LinkifiedText.test.tsx +++ b/tests/Unit/LinkifiedText.test.tsx @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { App } from '@inertiajs/react'; import type { ComponentProps, ReactElement } from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; -import { test } from 'vite-plus/test'; +import { test, vi } from 'vite-plus/test'; import { BodyCounter } from '../../resources/js/components/body-counter'; import { ConversationList } from '../../resources/js/components/chat/conversation-list'; import { MessageText } from '../../resources/js/components/chat/message-parts'; @@ -84,7 +84,6 @@ test('the counter discounts commit links but not issue links', () => { function renderPage( content: ReactElement, - user: unknown = null, props: Record = {}, ): string { return renderToStaticMarkup( @@ -97,7 +96,7 @@ function renderPage( version: null, props: { errors: {}, - auth: { user, pasteis: null }, + auth: { user: null, pasteis: null }, ...props, }, clearHistory: false, @@ -1250,36 +1249,45 @@ test('separates subtext from surrounding paragraphs', () => { }); test('words future timestamps as upcoming', () => { - const markup = renderToStaticMarkup( - , - ); + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-06-15T12:00:00Z')); + try { + const markup = renderToStaticMarkup( + , + ); - assert.ok(markup.includes('data-test="timestamp"')); - assert.ok(markup.includes('in ')); + assert.ok(markup.includes('data-test="timestamp"')); + assert.ok(markup.includes('in ')); - const soon = renderToStaticMarkup( - o clock`} - mentions={null} - />, - ); + const soon = renderToStaticMarkup( + o clock`} + mentions={null} + />, + ); - assert.ok(soon.includes('data-test="timestamp"')); - assert.ok(soon.includes('in 2h')); + assert.ok(soon.includes('data-test="timestamp"')); + assert.ok(soon.includes('in 2h')); - const imminent = renderToStaticMarkup( - o clock`} - mentions={null} - />, - ); + const imminent = renderToStaticMarkup( + o clock`} + mentions={null} + />, + ); - assert.ok(imminent.includes('data-test="timestamp"')); - assert.ok(imminent.includes('soon')); - assert.ok(!imminent.includes('now')); + assert.ok(imminent.includes('data-test="timestamp"')); + assert.ok(imminent.includes('soon')); + assert.ok(!imminent.includes('now')); + } finally { + vi.useRealTimers(); + } }); -test('keeps linked children inside hidden spoilers', () => { +test('keeps spoiler links outside the reveal button', () => { const markup = renderToStaticMarkup( , ); @@ -1287,6 +1295,9 @@ test('keeps linked children inside hidden spoilers', () => { assert.ok(markup.includes('data-test="spoiler"')); assert.ok(markup.includes('data-revealed="false"')); assert.ok(markup.includes('href="https://example.com"')); + // The link sits beside the reveal control, never inside it. + assert.ok(markup.indexOf('') < markup.indexOf(']*aria-label="Reveal spoiler"/)); }); test('leaves fenced code verbatim while formatting the prose around it', () => { @@ -1315,6 +1326,56 @@ test('omits spoiler content from static previews', () => { assert.ok(!markup.includes('secret')); }); +test('formats far-future timestamps from the validated date', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('data-test="timestamp"')); +}); + +test('renders combined bold and italic markers', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(markup.includes('both')); + assert.ok(!markup.includes('*both*')); + assert.ok(markup.includes('bold')); + assert.ok(markup.includes('italic')); +}); + +test('keeps balanced parentheses inside masked destinations', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok( + markup.includes( + 'href="https://en.wikipedia.org/wiki/Mercury_(planet)"', + ), + ); + assert.ok(!markup.includes('))')); +}); + +test('leaves formatting markers inside bare URLs literal', () => { + const markup = renderToStaticMarkup( + , + ); + + assert.ok(!markup.includes('')); + assert.ok(markup.includes(' { for (const text of [ '[https://a.com](https://b.com)', @@ -1333,14 +1394,16 @@ test('keeps hashtags plain inside masked labels when signed in', () => { const topLevel = renderPage( , - user, + { + auth: { user, pasteis: null }, + }, ); assert.ok(topLevel.includes('data-test="hashtag"')); const masked = renderPage( , - user, + { auth: { user, pasteis: null } }, ); assert.equal(masked.match(/]/g)?.length, 1);