diff --git a/app/Services/CodeSpans.php b/app/Services/CodeSpans.php index 31a5fc7368..cd71b6b96d 100644 --- a/app/Services/CodeSpans.php +++ b/app/Services/CodeSpans.php @@ -156,11 +156,74 @@ 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' => $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)), + }, ]; } + + /** + * 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..cde3620030 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -990,6 +990,127 @@ 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; + } + + /* 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, + var(--foreground) 12%, + transparent + ); + color: inherit; + } + + /* 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/resources/js/components/commit-body.tsx b/resources/js/components/commit-body.tsx index 1136c2c538..8514d2840e 100644 --- a/resources/js/components/commit-body.tsx +++ b/resources/js/components/commit-body.tsx @@ -63,6 +63,236 @@ 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: '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) { + 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')) { + 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); + + 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(); + + if (fence !== null) { + blocks.push({ kind: 'code', text: fence.join('\n') }); + } + + 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} +
    + ) : ( + + ); + } + + if (block.kind === 'code') { + return ( +
    +                            {block.text}
    +                        
    + ); + } + + return ( + + ); + })} + + ); +} + export function BodySegments({ segments, mentions, @@ -84,8 +314,9 @@ export function BodySegments({ switch (segment.type) { case 'text': return ( - `[^`\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. + */ +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. + * 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, + isStatic, +}: { + children: ReactNode; + isStatic: boolean; +}) { + const [revealed, setRevealed] = useState(false); + + if (isStatic) { + // Static previews offer no tap to reveal with, so the hidden content stays out entirely. + return ; + } + + return ( + + {' '} + {children} + + ); +} + +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', + }, +}; + +/** + * 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; + + 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, date)} + + ); + } + + if (ahead >= 0) { + return ( + + soon + + ); + } + + return ( + + {formatRelativeTime(date.toISOString())} + + ); + } + + return ( + {absolute(timestampFormats[format])} + ); +} + +/** + * Words a future distance in the largest fitting unit, for upcoming timestamps. + */ +function formatFuture(totalSeconds: number, target: Date): 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(target); +} + +/** + * 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, + 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; + + // 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; + } + + // 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, + nestedOptions: InlineOptions = options, + ): ReactNode[] => + withRichInline( + inner, + offset + index + shift, + `${keyPrefix}-nested`, + nestedOptions, + ); + + 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, { + ...options, + isStatic: true, + })} + , + ); + } else { + parts.push( + + {nested(groups.maskedLabel, 1, { + ...options, + isStatic: true, + hashtags: [], + })} + , + ); + } + } else if (groups.timestampAt !== undefined) { + parts.push( + , + ); + } 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)}, + ); + } 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, @@ -904,11 +1207,80 @@ 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)]; + + // 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 ( + <> + {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, + 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)) { @@ -925,7 +1297,7 @@ export function LinkifiedText({ parts.push( ...withMentions( text.slice(position, match.index), - position, + offset + position, mentions, organizationMentions, colors, @@ -936,7 +1308,7 @@ export function LinkifiedText({ ), commitLink ? ( ) : forgeLink ? ( {parts}; + return parts; } diff --git a/resources/js/lib/code.ts b/resources/js/lib/code.ts index b819b20f4f..14c145dd43 100644 --- a/resources/js/lib/code.ts +++ b/resources/js/lib/code.ts @@ -2,14 +2,63 @@ 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) { + const tail = text.slice(position); + const unclosed = unclosedPattern.exec(tail); + + if (unclosed !== null && unclosed.index > 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; +} + /** * 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 e8b14424ae..3a93639bc0 100644 --- a/tests/Unit/LinkifiedText.test.tsx +++ b/tests/Unit/LinkifiedText.test.tsx @@ -3,11 +3,14 @@ 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'; -import { CommitBody } from '../../resources/js/components/commit-body'; +import { + BodySegments, + CommitBody, +} from '../../resources/js/components/commit-body'; import { LinkifiedText, typedLinks, @@ -1057,3 +1060,353 @@ 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')); +}); + +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('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', + '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', () => { + 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 ')); + + const soon = renderToStaticMarkup( + o clock`} + mentions={null} + />, + ); + + 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')); + } finally { + vi.useRealTimers(); + } +}); + +test('keeps spoiler links outside the reveal button', () => { + const markup = renderToStaticMarkup( + , + ); + + 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', () => { + 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')); +}); + +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)', + '[see @Original](https://example.com)', + ]) { + const markup = renderToStaticMarkup( + , + ); + + 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( + , + { + auth: { user, pasteis: null }, + }, + ); + + assert.ok(topLevel.includes('data-test="hashtag"')); + + const masked = renderPage( + , + { auth: { user, pasteis: null } }, + ); + + assert.equal(masked.match(/]/g)?.length, 1); + assert.ok(masked.includes('#topic')); + assert.ok(!masked.includes('data-test="hashtag"')); +}); diff --git a/tests/Unit/Services/CodeSpansTest.php b/tests/Unit/Services/CodeSpansTest.php index edc60e49cf..6e9e3a4e14 100644 --- a/tests/Unit/Services/CodeSpansTest.php +++ b/tests/Unit/Services/CodeSpansTest.php @@ -222,3 +222,57 @@ ->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'); +}); + +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>', + ], + ]); +});