feat(ext-blog): Add syntax highlighting for code blocks
Added language-specific syntax highlighting support to the markdown editor and preview. New code-highlighter assets are registered for public pages and admin headers. The PostContentRenderer detects language identifiers in code fences to apply appropriate CSS classes for highlighting. Tests verify the highlighting works correctly and unsafe content is escaped properly.
This commit is contained in:
@@ -23,7 +23,7 @@ namespace {
|
||||
}
|
||||
}
|
||||
|
||||
$previewMarkdown = "## Preview\n\nSafe **source**.\n\n- list item\n\n---\n\n> Quoted text.\n\n```php\n<code>safe</code>\n```";
|
||||
$previewMarkdown = "## Preview\n\nSafe **source**.\n\n- list item\n\n---\n\n> Quoted text.\n\n```php\n<code>safe</code>\n```\n\n~~~php\" onclick=\"alert(1)\n<script>alert(1)</script>\n~~~";
|
||||
|
||||
if (($argv[1] ?? '') === '--child') {
|
||||
$scenario = $argv[2] ?? '';
|
||||
@@ -111,6 +111,7 @@ namespace {
|
||||
assertPreviewRoute($response['status'] === 200, 'A valid preview request should succeed.');
|
||||
assertPreviewRoute($payload === ['html' => $expectedHtml], 'The preview should return shared renderer output as JSON.');
|
||||
assertPreviewRoute(str_contains($payload['html'], '<ul class="list-disc') && str_contains($payload['html'], '<hr class="my-6 border-base-300">') && str_contains($payload['html'], '<blockquote') && str_contains($payload['html'], '<pre'), 'The live preview should render lists, horizontal rules, quotes, and code blocks.');
|
||||
assertPreviewRoute(str_contains($payload['html'], '<code class="language-php"><code>safe</code></code>') && str_contains($payload['html'], '<code><script>alert(1)</script></code>') && !str_contains($payload['html'], 'onclick='), 'The preview should keep safe language metadata, reject malformed labels, and escape code.');
|
||||
assertPreviewRoute($response['repository_instances'] === 0, 'Preview rendering must not read or write saved posts.');
|
||||
|
||||
fwrite(STDOUT, "Blog preview route tests passed.\n");
|
||||
|
||||
@@ -146,6 +146,15 @@ $phpb_db->createSchema();
|
||||
assertBlog(isset($phpb_db->getDBDefinition()['ext__blog_posts'], $phpb_db->getDBDefinition()['ext__blog_categories']), 'The blog tables should be included in the core database definition.');
|
||||
assertBlog(isset(\Plugi\Extensions::getBackends()['ext--blog']), 'The blog admin backend should be registered.');
|
||||
assertBlog(in_array('/admin/assets/markdown-editor.js', array_column($blogConfig['assets'], 'src'), true) && in_array('/admin/assets/markdown-editor.css', array_column($blogConfig['assets'], 'src'), true), 'The editor script and stylesheet should be registered as extension assets.');
|
||||
$publicAssets = array_values(array_filter($blogConfig['assets'], fn(array $asset): bool => $asset['location'] === 'footer'));
|
||||
$adminAssets = array_values(array_filter($blogConfig['assets'], fn(array $asset): bool => $asset['location'] === 'admin-header'));
|
||||
assertBlog(in_array(['src' => '/assets/code-highlighter.css', 'type' => 'style', 'location' => 'footer'], $publicAssets, true) && in_array(['src' => '/assets/code-highlighter.js', 'type' => 'script', 'location' => 'footer'], $publicAssets, true), 'The highlighter assets should be registered for public pages.');
|
||||
assertBlog(in_array(['src' => '/assets/code-highlighter.css', 'type' => 'style', 'location' => 'admin-header'], $adminAssets, true) && in_array(['src' => '/assets/code-highlighter.js', 'type' => 'script', 'location' => 'admin-header'], $adminAssets, true), 'The highlighter assets should be registered for admin pages.');
|
||||
assertBlog(array_search('/assets/code-highlighter.js', array_column($adminAssets, 'src'), true) < array_search('/admin/assets/markdown-editor.js', array_column($adminAssets, 'src'), true), 'The admin highlighter should load before the Markdown editor.');
|
||||
$highlighterSource = file_get_contents(dirname(__DIR__) . '/assets/src/code-highlighter.js');
|
||||
$editorSource = file_get_contents(dirname(__DIR__) . '/admin/assets/src/markdown-editor.js');
|
||||
assertBlog(str_contains($highlighterSource, 'highlightPage') && str_contains($highlighterSource, "document.addEventListener('DOMContentLoaded'"), 'The highlighter should initialize code blocks on initial page content.');
|
||||
assertBlog(str_contains($editorSource, 'window.blogCodeHighlighter?.highlight(preview)'), 'The editor should highlight preview code after replacing its contents.');
|
||||
assertBlog(count(array_intersect(['/ext--blog/save-post', '/ext--blog/preview-post', '/ext--blog/delete-post', '/ext--blog/save-category', '/ext--blog/delete-category'], array_keys(\Plugi\Extensions::getRoutes()))) === 5, 'Blog post and category routes should be registered.');
|
||||
assertBlog(\Plugi\Extensions::getBlock('post-list') === dirname(__DIR__) . '/blocks/post-list', 'The published-post block should be registered.');
|
||||
assertBlog((require dirname(__DIR__) . '/blocks/post-list/config.php')['cache'] === false, 'The listing block should avoid stale cached post data.');
|
||||
@@ -186,7 +195,7 @@ $olderPost = $posts->create([
|
||||
'title' => 'Older published post',
|
||||
'slug' => 'older-published-post',
|
||||
'excerpt' => 'Older excerpt',
|
||||
'body' => "## Markdown heading\n\nA **bold** and *emphasized* phrase with `inline code`, a [safe link](https://example.com), an [unsafe link](javascript:alert), and an [encoded unsafe link](javascript:alert).\n\n- first item\n- second item\n\n1. first numbered item\n2. second numbered item\n\n![Inline & ]](https://images.example/photo.jpg)\n\n\n\n\n<script>alert(\"x\")</script>&safe\n\n---\n\n> Quoted **text**.\n\n```php\n<script>alert(\"code\")</script>\n````",
|
||||
'body' => "## Markdown heading\n\nA **bold** and *emphasized* phrase with `inline code`, a [safe link](https://example.com), an [unsafe link](javascript:alert), and an [encoded unsafe link](javascript:alert).\n\n- first item\n- second item\n\n1. first numbered item\n2. second numbered item\n\n![Inline & ]](https://images.example/photo.jpg)\n\n\n\n\n<script>alert(\"x\")</script>&safe\n\n---\n\n> Quoted **text**.\n\n```php\n<script>alert(\"code\")</script>\n```\n\n~~~php\" onmouseover=\"alert(1)\n<script>alert(1)</script>\n~~~",
|
||||
'category_id' => '',
|
||||
'status' => 'published',
|
||||
'published_at' => '2020-01-01T00:00',
|
||||
@@ -243,7 +252,8 @@ assertBlog(str_contains($detailHtml, '<ol class="list-decimal') && str_contains(
|
||||
assertBlog(str_contains($detailHtml, '<code>inline code</code>'), 'The detail block should render inline code.');
|
||||
assertBlog(str_contains($detailHtml, '<hr class="my-6 border-base-300">'), 'The detail block should render Markdown horizontal rules.');
|
||||
assertBlog(str_contains($detailHtml, '<blockquote class="border-l-4 border-base-300 pl-4 text-base-content/80"><p>Quoted <strong>text</strong>.</p></blockquote>'), 'The detail block should render Markdown blockquotes with inline formatting.');
|
||||
assertBlog(str_contains($detailHtml, '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code><script>alert("code")</script></code></pre>'), 'The detail block should render fenced code blocks as escaped code.');
|
||||
assertBlog(str_contains($detailHtml, '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code class="language-php"><script>alert("code")</script></code></pre>'), 'The detail block should add a language class and escape fenced code.');
|
||||
assertBlog(str_contains($detailHtml, '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code><script>alert(1)</script></code></pre>') && !str_contains($detailHtml, 'onmouseover='), 'Malformed fence info should not create attributes, and its code should remain escaped.');
|
||||
assertBlog(str_contains($detailHtml, '<img src="https://images.example/photo.jpg" alt="Inline & ]" class="max-w-full rounded-box">'), 'The detail block should render inline Markdown images with escaped alt text.');
|
||||
assertBlog(!str_contains($detailHtml, 'src="javascript:') && !str_contains($detailHtml, 'src="java') && !str_contains($detailHtml, 'src="data:'), 'The detail block should reject unsafe image URL protocols.');
|
||||
assertBlog(str_contains($detailHtml, '<script>alert("x")</script>&safe') && !str_contains($detailHtml, '<script>alert'), 'The detail block should escape raw HTML in post bodies.');
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
const createCodeBlock = (className, text) => {
|
||||
const classes = new Set(className.split(/\s+/).filter(Boolean));
|
||||
const code = {
|
||||
className: [...classes].join(' '),
|
||||
children: [],
|
||||
dataset: {},
|
||||
innerHTML: '',
|
||||
textContent: text,
|
||||
classList: {
|
||||
add(name) {
|
||||
classes.add(name);
|
||||
code.className = [...classes].join(' ');
|
||||
},
|
||||
},
|
||||
};
|
||||
return code;
|
||||
};
|
||||
|
||||
globalThis.document = { readyState: 'complete', querySelectorAll: () => [] };
|
||||
globalThis.window = {};
|
||||
await import('../assets/src/code-highlighter.js');
|
||||
|
||||
test('unsupported language labels remain plain without interrupting later blocks', () => {
|
||||
const unsupported = createCodeBlock('language-not-a-language', '<?php echo 1;');
|
||||
const supported = createCodeBlock('language-php', '<?php echo 1;');
|
||||
const warnings = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args) => warnings.push(args);
|
||||
|
||||
try {
|
||||
window.blogCodeHighlighter.highlight({ querySelectorAll: () => [unsupported, supported] });
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
|
||||
assert.deepEqual(warnings, []);
|
||||
assert.equal(unsupported.className, 'language-not-a-language');
|
||||
assert.deepEqual(unsupported.dataset, {});
|
||||
assert.equal(supported.dataset.highlighted, 'yes');
|
||||
assert.match(supported.innerHTML, /<span class="hljs-/);
|
||||
});
|
||||
Reference in New Issue
Block a user