Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .github/pr-assets/preview-line-numbers.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
67 changes: 55 additions & 12 deletions apps/preview/app/src/components/code/code-block.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Check, Copy, Download } from 'iconoir-react';
import beautify from 'js-beautify';
import { useMemo, useState } from 'react';
import type { ShikiTransformer } from 'shiki';
import { createHighlighterCoreSync } from 'shiki/core';
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
import shikiHtmlLang from 'shiki/langs/html.mjs';
Expand All @@ -15,6 +16,31 @@ const shiki = createHighlighterCoreSync({
themes: [shikiGithubLightTheme, shikiGithubDarkHighContrastTheme]
});

const lineNumberTransformer: ShikiTransformer = {
name: 'jsx-email-preview-line-numbers',
line(node, line) {
const { children } = node;
node.children = [
{
type: 'element',
tagName: 'span',
properties: {
ariaHidden: 'true',
className: ['code-line-number'],
dataLineNumber: String(line)
},
children: [{ type: 'text', value: String(line) }]
},
{
type: 'element',
tagName: 'span',
properties: { className: ['code-line-content'] },
children
}
];
}
};

interface CodeBlockProps {
code: string;
fileName: string;
Expand All @@ -26,17 +52,28 @@ export function formatCode(code: string, lang: CodeBlockProps['lang']) {
return code;
}

export function codeToLineNumberedHtml(
code: string,
lang: CodeBlockProps['lang'],
theme: 'github-light' | 'github-dark-high-contrast'
) {
if (lang === 'text') return escapeHtml(code);
return shiki.codeToHtml(code, {
lang,
theme,
transformers: [lineNumberTransformer]
});
}

export function CodeBlock({ code, fileName, lang }: CodeBlockProps) {
const [copied, setCopied] = useState(false);
const visibleCode = useMemo(() => formatCode(code, lang), [code, lang]);
const html = useMemo(() => {
if (lang === 'text') return escapeHtml(visibleCode);
return shiki.codeToHtml(visibleCode, {
lang,
theme: document.documentElement.classList.contains('dark')
? 'github-dark-high-contrast'
: 'github-light'
});
const theme = document.documentElement.classList.contains('dark')
? 'github-dark-high-contrast'
: 'github-light';

return codeToLineNumberedHtml(visibleCode, lang, theme);
}, [lang, visibleCode]);

async function copy() {
Expand Down Expand Up @@ -68,16 +105,22 @@ export function CodeBlock({ code, fileName, lang }: CodeBlockProps) {
</button>
</div>
<div
className="card-code h-full overflow-auto rounded-[6px] border border-[var(--border)] p-4 pr-24 text-xs leading-5"
className="card-code h-full overflow-auto rounded-[6px] border border-[var(--border)] py-4 pl-3 pr-24 text-xs leading-5"
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
);
}

function escapeHtml(value: string) {
return `<pre class="shiki"><code>${value
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')}</code></pre>`;
const lines = value.split('\n');
return `<pre class="shiki"><code>${lines
.map((line, index) => {
const lineNumber = index + 1;
return `<span class="line"><span class="code-line-number" aria-hidden="true" data-line-number="${lineNumber}">${lineNumber}</span><span class="code-line-content">${line
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')}</span></span>`;
})
.join('')}</code></pre>`;
}
25 changes: 25 additions & 0 deletions apps/preview/app/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -683,6 +683,31 @@ body {
padding: 0;
}

.card-code code {
display: grid;
min-width: max-content;
}

.card-code .line {
display: grid;
grid-template-columns: 2.5rem minmax(0, 1fr);
min-height: 1.25rem;
}

.card-code .code-line-number {
border-right: 1px solid var(--border);
color: var(--text-subtle);
padding-right: 0.75rem;
text-align: right;
user-select: none;
}

.card-code .code-line-content {
padding-left: 1rem;
padding-right: 1rem;
white-space: pre;
}

.code-block-wrap {
position: relative;
}
Expand Down
27 changes: 27 additions & 0 deletions apps/preview/app/test/components/code/code-block.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest';

import { codeToLineNumberedHtml, formatCode } from '../../../src/components/code/code-block';

describe('codeToLineNumberedHtml', () => {
it('adds aligned line number markup to highlighted TSX code', () => {
const html = codeToLineNumberedHtml(
['const subject = "Hi";', '<Text>{subject}</Text>'].join('\n'),
'tsx',
'github-light'
);

expect(html).toContain('class="line"');
expect(html).toContain('class="code-line-number"');
expect(html).toContain('data-line-number="1"');
expect(html).toContain('data-line-number="2"');
expect(html).toContain('class="code-line-content"');
});
});

describe('formatCode', () => {
it('formats HTML before it is highlighted', () => {
expect(formatCode('<main><p>Hello</p></main>', 'html')).toBe(
['<main>', ' <p>Hello</p>', '</main>'].join('\n')
);
});
});
1 change: 1 addition & 0 deletions apps/preview/scripts/pack-preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ const importHeader = `import React, {
import ReactDOM from 'react-dom/client';
import { createPortal } from 'react-dom';
import { createRoot } from 'react-dom/client';
import type { ShikiTransformer } from 'shiki';
import {
Check,
Copy,
Expand Down
40 changes: 40 additions & 0 deletions scripts/agents/capture-preview-line-numbers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { chromium } from 'playwright';

const defaultUrl = 'http://localhost:8789';
const defaultPath = '/tmp/preview-line-numbers.png';

function getArg(name: string, fallback: string) {
const index = process.argv.indexOf(name);
return index === -1 ? fallback : (process.argv[index + 1] ?? fallback);
}

async function main() {
const url = getArg('--url', defaultUrl);
const path = getArg('--path', defaultPath);
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({
deviceScaleFactor: 2,
viewport: { height: 900, width: 1280 }
});

await page.goto(`${url}?lineNumbers=${Date.now()}`, { waitUntil: 'networkidle' });
await page.getByRole('button', { exact: true, name: 'Google Play Policy Update' }).click();
await page.waitForTimeout(900);
await page.getByRole('tab', { exact: true, name: 'JSX' }).click();
await page.waitForTimeout(300);

const card = page.locator('main article').filter({ hasText: 'Google Play Policy Update' });
await card.screenshot({ path });

const lineNumbers = await card.locator('.code-line-number').count();
const firstLine = await card.locator('.code-line-number').first().textContent();
const hasCodeContent = (await card.locator('.code-line-content').count()) > 0;
await browser.close();

console.log(JSON.stringify({ firstLine, hasCodeContent, lineNumbers, path }, null, 2));
}

main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Loading