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:
2026-12-02 10:20:36 +00:00
parent 745f33f17d
commit 6f0e39b5f5
16 changed files with 202 additions and 11 deletions
+1 -1
View File
@@ -20,6 +20,6 @@ Keep `/blog` and `/blog/{slug}` unique among the site’s page routes.
## Authoring content and images
Write post bodies in Markdown using the syntax-highlighted source editor. Its toolbar inserts bold, italic, headings, links, unordered and ordered lists, blockquotes, horizontal rules, inline code, and fenced code blocks; the live preview uses the same server-side renderer as the public detail page. If JavaScript is unavailable, the source textarea remains usable and can still save the post. The detail page supports headings, paragraphs and line breaks, bold and italic text, inline code, links, ordered and unordered lists, blockquotes, horizontal rules, and fenced code blocks. Code-block contents are displayed as escaped text. Raw HTML is displayed as text; links only render with relative URLs or `http`, `https`, and `mailto` schemes.
Write post bodies in Markdown using the syntax-highlighted source editor. Its toolbar inserts bold, italic, headings, links, unordered and ordered lists, blockquotes, horizontal rules, inline code, and fenced code blocks; the live preview uses the same server-side renderer as the public detail page. If JavaScript is unavailable, the source textarea remains usable and can still save the post. The detail page supports headings, paragraphs and line breaks, bold and italic text, inline code, links, ordered and unordered lists, blockquotes, horizontal rules, and fenced code blocks. Add a language identifier after the opening fence (for example, `php`) to enable language-specific highlighting. Bash, CSS, diff, HTML/XML, JavaScript/TypeScript, JSON, Markdown, PHP, Python, SQL, and YAML are highlighted; unlabeled blocks are auto-detected from this set, and other language labels remain plain text. Code-block contents are rendered as escaped text before highlighting. Raw HTML is displayed as text; links only render with relative URLs or `http`, `https`, and `mailto` schemes.
Choose a featured image from the existing Website Manager media library to show it on post cards and detail pages. Use the editor’s inline-image selector to insert Markdown image syntax at the body cursor; image alt text comes from the selected media item. Inline images render only with relative, `http`, or `https` sources. Unsafe link and image protocols are not rendered.
@@ -31,14 +31,17 @@ class PostContentRenderer
};
$fence = null;
$fenceLanguage = null;
$codeLines = [];
foreach (preg_split('/\R/', $markdown) ?: [] as $line) {
if ($fence !== null) {
if (preg_match('/^ {0,3}(`{3,}|~{3,})[ \t]*$/', $line, $matches)
&& $matches[1][0] === $fence[0]
&& strlen($matches[1]) >= strlen($fence)) {
$blocks[] = '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code>' . $this->escape(implode("\n", $codeLines)) . '</code></pre>';
$codeClass = $fenceLanguage === null ? '' : ' class="language-' . $fenceLanguage . '"';
$blocks[] = '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code' . $codeClass . '>' . $this->escape(implode("\n", $codeLines)) . '</code></pre>';
$fence = null;
$fenceLanguage = null;
$codeLines = [];
continue;
}
@@ -49,6 +52,10 @@ class PostContentRenderer
if (preg_match('/^ {0,3}(`{3,}|~{3,})(.*)$/', $line, $matches)) {
$flush();
$fence = $matches[1];
$info = trim($matches[2]);
$fenceLanguage = preg_match('/^([A-Za-z0-9][A-Za-z0-9_+-]*)(?:[ \t]+|$)/', $info, $languageMatches)
? $languageMatches[1]
: null;
$codeLines = [];
continue;
}
@@ -112,7 +119,8 @@ class PostContentRenderer
$flush();
if ($fence !== null) {
$blocks[] = '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code>' . $this->escape(implode("\n", $codeLines)) . '</code></pre>';
$codeClass = $fenceLanguage === null ? '' : ' class="language-' . $fenceLanguage . '"';
$blocks[] = '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code' . $codeClass . '>' . $this->escape(implode("\n", $codeLines)) . '</code></pre>';
}
return implode("\n", $blocks);
}
@@ -38,5 +38,5 @@
---`:`---`;o.dispatch({changes:{from:e.to,to:e.to,insert:n},selection:{anchor:e.to+n.length}}),o.focus();return}if(n===`code-block`||n===`quote`){let e=o.state.doc.lineAt(t.from),r=o.state.doc.lineAt(t.to),i=o.state.doc.sliceString(e.from,r.to),a=i.split(`
`),s=n===`code-block`?`\`\`\`\n${i||`Code block`}\n\`\`\``:a.every(e=>e.startsWith(`> `))?a.map(e=>e.slice(2)).join(`
`):a.map(e=>`> ${e||`Quote`}`).join(`
`);o.dispatch({changes:{from:e.from,to:r.to,insert:s},selection:n===`code-block`?{anchor:e.from+4,head:e.from+4+(i||`Code block`).length}:{anchor:e.from,head:e.from+s.length}}),o.focus();return}if(n===`heading`||n===`list`||n===`ordered-list`){let e=o.state.doc.lineAt(t.from),r=n===`heading`?`## `:n===`ordered-list`?`1. `:`- `,i=n===`ordered-list`?/^\d+[.)]\s/.test(e.text):n===`list`?/^[-*+]\s/.test(e.text):e.text.startsWith(r),a=i?e.text.replace(n===`ordered-list`?/^\d+[.)]\s/:n===`list`?/^[-*+]\s/:/^## /,``):`${r}${e.text||(n===`heading`?`Heading`:`List item`)}`,s=e.from+(i?0:r.length);o.dispatch({changes:{from:e.from,to:e.to,insert:a},selection:{anchor:s,head:e.from+a.length}}),o.focus();return}let[r,i,a]={bold:[`**`,`**`,`bold text`],italic:[`*`,`*`,`italic text`],link:[`[`,`](https://example.com)`,`link text`],code:["`","`",`code`]}[n]||[];if(r===void 0)return;let s=o.state.sliceDoc(t.from,t.to)||a;o.dispatch({changes:{from:t.from,to:t.to,insert:`${r}${s}${i}`},selection:{anchor:t.from+r.length,head:t.from+r.length+s.length}}),o.focus()};n.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-format]`);t&&l(t)});let u=e.form;u?.addEventListener(`submit`,()=>{e.value=o.state.doc.toString()});let d=document.getElementById(`post-body-preview`),f=document.getElementById(`post-body-preview-status`);if(u&&d&&f){let t,n=0,r=null,i=(e,t=!1)=>{f.textContent=e,f.classList.toggle(`text-error`,t),f.classList.toggle(`text-base-content/60`,!t)},a=()=>{window.clearTimeout(t);let a=++n;r?.abort(),r=null,d.replaceChildren(),d.setAttribute(`aria-busy`,`true`),i(`Updating preview…`),t=window.setTimeout(async()=>{let t=u.querySelector(`[name="_csrf_token"]`)?.value||``;if(!t){a===n&&(i(`Preview unavailable. Your Markdown is unchanged and can still be saved.`,!0),d.setAttribute(`aria-busy`,`false`));return}let o=new AbortController;r=o;let s=new FormData;s.set(`body`,e.value),s.set(`_csrf_token`,t);try{let e=await fetch(`/ext--blog/preview-post`,{method:`POST`,body:s,credentials:`same-origin`,headers:{Accept:`application/json`},signal:o.signal}),t=await e.json();if(a!==n)return;if(!e.ok||!t||typeof t.html!=`string`)throw Error(`Preview request failed.`);d.innerHTML=t.html,i(t.html===``?`The post body is empty.`:`Preview updated.`)}catch(e){e.name!==`AbortError`&&a===n&&i(`Preview unavailable. Your Markdown is unchanged and can still be saved.`,!0)}finally{a===n&&(r=null,d.setAttribute(`aria-busy`,`false`))}},300)};e.addEventListener(`input`,a),a()}window.blogMarkdownEditor={insertAtCursor(e){let t=o.state.selection.main,n=o.state.doc,r=`${t.from>0&&!/\s/.test(n.sliceString(t.from-1,t.from))?` `:``}${e}${t.to<n.length&&!/\s/.test(n.sliceString(t.to,t.to+1))?` `:``}`;return o.dispatch({changes:{from:t.from,to:t.to,insert:r},selection:{anchor:t.from+r.length}}),o.focus(),!0}}})})();
`);o.dispatch({changes:{from:e.from,to:r.to,insert:s},selection:n===`code-block`?{anchor:e.from+4,head:e.from+4+(i||`Code block`).length}:{anchor:e.from,head:e.from+s.length}}),o.focus();return}if(n===`heading`||n===`list`||n===`ordered-list`){let e=o.state.doc.lineAt(t.from),r=n===`heading`?`## `:n===`ordered-list`?`1. `:`- `,i=n===`ordered-list`?/^\d+[.)]\s/.test(e.text):n===`list`?/^[-*+]\s/.test(e.text):e.text.startsWith(r),a=i?e.text.replace(n===`ordered-list`?/^\d+[.)]\s/:n===`list`?/^[-*+]\s/:/^## /,``):`${r}${e.text||(n===`heading`?`Heading`:`List item`)}`,s=e.from+(i?0:r.length);o.dispatch({changes:{from:e.from,to:e.to,insert:a},selection:{anchor:s,head:e.from+a.length}}),o.focus();return}let[r,i,a]={bold:[`**`,`**`,`bold text`],italic:[`*`,`*`,`italic text`],link:[`[`,`](https://example.com)`,`link text`],code:["`","`",`code`]}[n]||[];if(r===void 0)return;let s=o.state.sliceDoc(t.from,t.to)||a;o.dispatch({changes:{from:t.from,to:t.to,insert:`${r}${s}${i}`},selection:{anchor:t.from+r.length,head:t.from+r.length+s.length}}),o.focus()};n.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-format]`);t&&l(t)});let u=e.form;u?.addEventListener(`submit`,()=>{e.value=o.state.doc.toString()});let d=document.getElementById(`post-body-preview`),f=document.getElementById(`post-body-preview-status`);if(u&&d&&f){let t,n=0,r=null,i=(e,t=!1)=>{f.textContent=e,f.classList.toggle(`text-error`,t),f.classList.toggle(`text-base-content/60`,!t)},a=()=>{window.clearTimeout(t);let a=++n;r?.abort(),r=null,d.replaceChildren(),d.setAttribute(`aria-busy`,`true`),i(`Updating preview…`),t=window.setTimeout(async()=>{let t=u.querySelector(`[name="_csrf_token"]`)?.value||``;if(!t){a===n&&(i(`Preview unavailable. Your Markdown is unchanged and can still be saved.`,!0),d.setAttribute(`aria-busy`,`false`));return}let o=new AbortController;r=o;let s=new FormData;s.set(`body`,e.value),s.set(`_csrf_token`,t);try{let e=await fetch(`/ext--blog/preview-post`,{method:`POST`,body:s,credentials:`same-origin`,headers:{Accept:`application/json`},signal:o.signal}),t=await e.json();if(a!==n)return;if(!e.ok||!t||typeof t.html!=`string`)throw Error(`Preview request failed.`);d.innerHTML=t.html,window.blogCodeHighlighter?.highlight(d),i(t.html===``?`The post body is empty.`:`Preview updated.`)}catch(e){e.name!==`AbortError`&&a===n&&i(`Preview unavailable. Your Markdown is unchanged and can still be saved.`,!0)}finally{a===n&&(r=null,d.setAttribute(`aria-busy`,`false`))}},300)};e.addEventListener(`input`,a),a()}window.blogMarkdownEditor={insertAtCursor(e){let t=o.state.selection.main,n=o.state.doc,r=`${t.from>0&&!/\s/.test(n.sliceString(t.from-1,t.from))?` `:``}${e}${t.to<n.length&&!/\s/.test(n.sliceString(t.to,t.to+1))?` `:``}`;return o.dispatch({changes:{from:t.from,to:t.to,insert:r},selection:{anchor:t.from+r.length}}),o.focus(),!0}}})})();
//# sourceMappingURL=markdown-editor.js.map
File diff suppressed because one or more lines are too long
@@ -265,6 +265,7 @@ document.addEventListener('DOMContentLoaded', () => {
}
preview.innerHTML = result.html;
window.blogCodeHighlighter?.highlight(preview);
setPreviewStatus(result.html === '' ? 'The post body is empty.' : 'Preview updated.');
} catch (error) {
if (error.name !== 'AbortError' && requestId === previewRequestId) {
@@ -0,0 +1,48 @@
.hljs {
color: var(--color-base-content);
}
.hljs-comment,
.hljs-quote {
opacity: 0.7;
font-style: italic;
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-literal,
.hljs-section {
color: var(--color-primary);
}
.hljs-string,
.hljs-title,
.hljs-name,
.hljs-type,
.hljs-attribute,
.hljs-symbol,
.hljs-bullet,
.hljs-addition {
color: var(--color-success);
}
.hljs-number,
.hljs-regexp,
.hljs-variable,
.hljs-template-variable {
color: var(--color-secondary);
}
.hljs-built_in,
.hljs-class .hljs-title {
color: var(--color-info);
}
.hljs-meta,
.hljs-meta .hljs-keyword {
color: var(--color-warning);
}
.hljs-deletion {
color: var(--color-error);
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,33 @@
import hljs from 'highlight.js/lib/core';
import bash from 'highlight.js/lib/languages/bash';
import css from 'highlight.js/lib/languages/css';
import diff from 'highlight.js/lib/languages/diff';
import javascript from 'highlight.js/lib/languages/javascript';
import json from 'highlight.js/lib/languages/json';
import markdown from 'highlight.js/lib/languages/markdown';
import php from 'highlight.js/lib/languages/php';
import python from 'highlight.js/lib/languages/python';
import sql from 'highlight.js/lib/languages/sql';
import typescript from 'highlight.js/lib/languages/typescript';
import xml from 'highlight.js/lib/languages/xml';
import yaml from 'highlight.js/lib/languages/yaml';
Object.entries({ bash, css, diff, javascript, json, markdown, php, python, sql, typescript, xml, yaml })
.forEach(([name, language]) => hljs.registerLanguage(name, language));
window.blogCodeHighlighter = {
highlight(root = document) {
root.querySelectorAll('pre code:not(.hljs)').forEach((code) => {
const language = code.className.match(/(?:^|\s)language-([^\s]+)/)?.[1];
if (language && !hljs.getLanguage(language)) return;
hljs.highlightElement(code);
});
},
};
const highlightPage = () => window.blogCodeHighlighter.highlight(document);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', highlightPage, { once: true });
} else {
highlightPage();
}
+8
View File
@@ -6,4 +6,12 @@ await bundle.write({
format: 'iife',
sourcemap: true,
minify: true,
});
const highlighterBundle = await rolldown({ input: 'assets/src/code-highlighter.js' });
await highlighterBundle.write({
file: 'assets/code-highlighter.js',
format: 'iife',
sourcemap: true,
minify: true,
});
+20
View File
@@ -7,6 +7,26 @@ return [
'licence' => 'MIT',
'version' => '1.0.0',
'assets' => [
[
'src' => '/assets/code-highlighter.css',
'type' => 'style',
'location' => 'footer',
],
[
'src' => '/assets/code-highlighter.js',
'type' => 'script',
'location' => 'footer',
],
[
'src' => '/assets/code-highlighter.css',
'type' => 'style',
'location' => 'admin-header',
],
[
'src' => '/assets/code-highlighter.js',
'type' => 'script',
'location' => 'admin-header',
],
[
'src' => '/admin/assets/markdown-editor.css',
'type' => 'style',
+11 -1
View File
@@ -10,7 +10,8 @@
"@codemirror/lang-markdown": "^6.5.3",
"@codemirror/language": "^6.13.1",
"@codemirror/view": "^6.44.2",
"@lezer/highlight": "^1.2.5"
"@lezer/highlight": "^1.2.5",
"highlight.js": "^11.11.1"
},
"devDependencies": {
"rolldown": "^1.3.3"
@@ -521,6 +522,15 @@
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
"license": "MIT"
},
"node_modules/highlight.js": {
"version": "11.12.0",
"resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.12.0.tgz",
"integrity": "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/rolldown": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.4.tgz",
+4 -2
View File
@@ -6,12 +6,14 @@
"@codemirror/lang-markdown": "^6.5.3",
"@codemirror/language": "^6.13.1",
"@codemirror/view": "^6.44.2",
"@lezer/highlight": "^1.2.5"
"@lezer/highlight": "^1.2.5",
"highlight.js": "^11.11.1"
},
"devDependencies": {
"rolldown": "^1.3.3"
},
"scripts": {
"build": "node build.js"
"build": "node build.js",
"test": "node --test tests/CodeHighlighterTest.js"
}
}
@@ -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">&lt;code&gt;safe&lt;/code&gt;</code>') && str_contains($payload['html'], '<code>&lt;script&gt;alert(1)&lt;/script&gt;</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](java&#x73;cript:alert).\n\n- first item\n- second item\n\n1. first numbered item\n2. second numbered item\n\n![Inline &amp; &#93;](https://images.example/photo.jpg)\n![Unsafe JavaScript](javascript:alert)\n![Encoded JavaScript](java&#x73;cript:alert)\n![Unsafe data](data:text/html;base64,abc)\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](java&#x73;cript:alert).\n\n- first item\n- second item\n\n1. first numbered item\n2. second numbered item\n\n![Inline &amp; &#93;](https://images.example/photo.jpg)\n![Unsafe JavaScript](javascript:alert)\n![Encoded JavaScript](java&#x73;cript:alert)\n![Unsafe data](data:text/html;base64,abc)\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>&lt;script&gt;alert(&quot;code&quot;)&lt;/script&gt;</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">&lt;script&gt;alert(&quot;code&quot;)&lt;/script&gt;</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>&lt;script&gt;alert(1)&lt;/script&gt;</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 &amp; ]" 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, '&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;&amp;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-/);
});