feat(ext-blog): Add rich Markdown editor for blog posts
Replace the plain textarea with a CodeMirror-based editor supporting syntax highlighting, formatting toolbar (bold, italic, lists, code blocks), and a live preview toggle. Update PostContentRenderer to handle new Markdown syntax (blockquotes, fenced code blocks). Add a preview endpoint for rendering content without saving.
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace Plugi\Extensions\Blog {
|
||||
class PostsRepository
|
||||
{
|
||||
public static int $instances = 0;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
self::$instances++;
|
||||
throw new \RuntimeException('Preview must not access the posts repository.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require_once dirname(__DIR__) . '/admin/Classes/PostContentRenderer.php';
|
||||
|
||||
function assertPreviewRoute(bool $condition, string $message): void
|
||||
{
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
}
|
||||
|
||||
$previewMarkdown = "## Preview\n\nSafe **source**.\n\n- list item\n\n---\n\n> Quoted text.\n\n```php\n<code>safe</code>\n```";
|
||||
|
||||
if (($argv[1] ?? '') === '--child') {
|
||||
$scenario = $argv[2] ?? '';
|
||||
$GLOBALS['previewAuthenticated'] = $scenario !== 'unauthenticated';
|
||||
$GLOBALS['previewCsrfValid'] = $scenario !== 'invalid-csrf';
|
||||
|
||||
function phpb_requires_authenticated(): void
|
||||
{
|
||||
if (!$GLOBALS['previewAuthenticated']) {
|
||||
http_response_code(403);
|
||||
exit();
|
||||
}
|
||||
}
|
||||
|
||||
function phpb_validate_csrf(): bool
|
||||
{
|
||||
return $GLOBALS['previewCsrfValid'];
|
||||
}
|
||||
|
||||
register_shutdown_function(static function (): void {
|
||||
echo "\n__STATUS__" . http_response_code() . "\n";
|
||||
echo '__REPOSITORY_INSTANTIATIONS__' . \Plugi\Extensions\Blog\PostsRepository::$instances . "\n";
|
||||
});
|
||||
|
||||
$_SERVER['REQUEST_METHOD'] = $scenario === 'non-post' ? 'GET' : 'POST';
|
||||
$_POST = match ($scenario) {
|
||||
'invalid-body' => ['body' => ['not', 'markdown']],
|
||||
'oversized-body' => ['body' => str_repeat('x', 1000001)],
|
||||
default => ['body' => $previewMarkdown],
|
||||
};
|
||||
|
||||
include dirname(__DIR__) . '/routes/previewPost.php';
|
||||
exit();
|
||||
}
|
||||
|
||||
function requestPreviewRoute(string $scenario): array
|
||||
{
|
||||
$process = proc_open(
|
||||
[PHP_BINARY, __FILE__, '--child', $scenario],
|
||||
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
|
||||
$pipes,
|
||||
dirname(__DIR__, 3)
|
||||
);
|
||||
if (!is_resource($process)) {
|
||||
throw new RuntimeException('Could not start the preview route test process.');
|
||||
}
|
||||
|
||||
fclose($pipes[0]);
|
||||
$output = stream_get_contents($pipes[1]);
|
||||
$error = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
$exitCode = proc_close($process);
|
||||
if ($exitCode !== 0 || !preg_match('/\n__STATUS__(\d+)\n__REPOSITORY_INSTANTIATIONS__(\d+)\n$/', $output, $matches)) {
|
||||
throw new RuntimeException('Preview route subprocess failed: ' . $error . $output);
|
||||
}
|
||||
|
||||
$responseLength = strpos($output, "\n__STATUS__");
|
||||
return [
|
||||
'status' => (int) $matches[1],
|
||||
'repository_instances' => (int) $matches[2],
|
||||
'body' => substr($output, 0, $responseLength),
|
||||
];
|
||||
}
|
||||
|
||||
foreach ([
|
||||
'unauthenticated' => 403,
|
||||
'non-post' => 405,
|
||||
'invalid-csrf' => 403,
|
||||
'invalid-body' => 400,
|
||||
'oversized-body' => 413,
|
||||
] as $scenario => $expectedStatus) {
|
||||
$response = requestPreviewRoute($scenario);
|
||||
assertPreviewRoute($response['status'] === $expectedStatus, 'The preview route should reject ' . $scenario . ' requests.');
|
||||
assertPreviewRoute($response['repository_instances'] === 0, 'Rejected preview requests must not access saved posts.');
|
||||
if ($scenario !== 'unauthenticated') {
|
||||
$payload = json_decode($response['body'], true);
|
||||
assertPreviewRoute(is_array($payload) && isset($payload['error']), 'Rejected preview requests should return a JSON error.');
|
||||
}
|
||||
}
|
||||
|
||||
$response = requestPreviewRoute('valid');
|
||||
$payload = json_decode($response['body'], true);
|
||||
$expectedHtml = (new \Plugi\Extensions\Blog\PostContentRenderer())->render($previewMarkdown);
|
||||
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($response['repository_instances'] === 0, 'Preview rendering must not read or write saved posts.');
|
||||
|
||||
fwrite(STDOUT, "Blog preview route tests passed.\n");
|
||||
}
|
||||
@@ -145,7 +145,8 @@ $phpb_db = new BlogTestDatabase();
|
||||
$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(count(array_intersect(['/ext--blog/save-post', '/ext--blog/delete-post', '/ext--blog/save-category', '/ext--blog/delete-category'], array_keys(\Plugi\Extensions::getRoutes()))) === 4, 'Blog CRUD routes 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.');
|
||||
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.');
|
||||
assertBlog(\Plugi\Extensions::getBlock('post-detail') === dirname(__DIR__) . '/blocks/post-detail', 'The post-detail block should be registered.');
|
||||
@@ -185,7 +186,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",
|
||||
'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````",
|
||||
'category_id' => '',
|
||||
'status' => 'published',
|
||||
'published_at' => '2020-01-01T00:00',
|
||||
@@ -217,11 +218,17 @@ assertBlog($publishedPosts[0]['slug'] === $post['slug'] && $publishedPosts[0]['c
|
||||
assertBlog($publishedPosts[1]['slug'] === $olderPost['slug'], 'Older published posts should follow newer posts.');
|
||||
|
||||
$editorHtml = renderBlogEditor((int) $post['id']);
|
||||
assertBlog(str_contains($editorHtml, '<textarea id="post-body" name="body"') && str_contains($editorHtml, 'Post body'), 'The visible fallback textarea should retain and submit the stored body value.');
|
||||
assertBlog(str_contains($editorHtml, 'id="post-body-toolbar"') && str_contains($editorHtml, 'data-format="bold"') && str_contains($editorHtml, 'data-format="heading"'), 'The editor should provide accessible Markdown formatting controls.');
|
||||
assertBlog(str_contains($editorHtml, 'data-format="list"') && str_contains($editorHtml, 'data-format="ordered-list"') && str_contains($editorHtml, 'data-format="quote"') && str_contains($editorHtml, 'data-format="horizontal-rule"') && str_contains($editorHtml, 'data-format="code-block"'), 'The editor toolbar should offer unordered and ordered lists, quotes, horizontal rules, and code blocks.');
|
||||
assertBlog(str_contains($editorHtml, 'id="post-body-editor"') && str_contains($editorHtml, 'id="post-body-preview"') && str_contains($editorHtml, 'id="post-body-view-tabs"'), 'The editor should include a CodeMirror mount and a preview toggle in the editor workspace.');
|
||||
assertBlog(str_contains($editorHtml, 'data-view="write"') && str_contains($editorHtml, 'data-view="preview"') && str_contains($editorHtml, 'role="tabpanel"') && str_contains($editorHtml, 'aria-live="polite"'), 'The editor and preview tabs should expose accessible panels and status.');
|
||||
assertBlog(str_contains($editorHtml, 'name="featured_image_id"') && str_contains($editorHtml, 'value="blog-cover-1" selected'), 'The editor should select a post featured image.');
|
||||
assertBlog(!str_contains($editorHtml, 'notes.pdf'), 'The featured-image selector should omit non-image uploads.');
|
||||
assertBlog(str_contains($editorHtml, 'id="post-inline-image"') && str_contains($editorHtml, 'id="insert-post-inline-image"'), 'The editor should offer a control for inserting inline images.');
|
||||
assertBlog(str_contains($editorHtml, 'data-url="https://blog.example/uploads/blog-cover-1/cover.jpg"') && str_contains($editorHtml, 'data-alt="A "featured" & <cover>"'), 'The inline picker should expose escaped media URL and alt metadata.');
|
||||
assertBlog(str_contains($editorHtml, 'selectionStart') && str_contains($editorHtml, 'setRangeText'), 'The inline picker should insert Markdown at the textarea cursor.');
|
||||
assertBlog(str_contains($editorHtml, 'window.blogMarkdownEditor.insertAtCursor(markdown)'), 'The inline picker should insert at the CodeMirror cursor when the editor is initialized.');
|
||||
$listingHtml = renderBlogListing();
|
||||
assertBlog(str_contains($listingHtml, 'href="https://blog.example/blog/first-post"'), 'The listing should link to the configured post detail URL.');
|
||||
assertBlog(str_contains($listingHtml, 'src="https://blog.example/uploads/blog-cover-1/cover.jpg" alt="A "featured" & <cover>"'), 'The public listing should display a featured image with escaped alt text.');
|
||||
@@ -234,6 +241,9 @@ assertBlog(str_contains($detailHtml, '<a class="link link-hover" href="https://e
|
||||
assertBlog(str_contains($detailHtml, '<ul class="list-disc') && str_contains($detailHtml, '<li>first item</li>') && str_contains($detailHtml, '<li>second item</li>'), 'The detail block should render Markdown lists.');
|
||||
assertBlog(str_contains($detailHtml, '<ol class="list-decimal') && str_contains($detailHtml, '<li>first numbered item</li>'), 'The detail block should render ordered Markdown lists.');
|
||||
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, '<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.');
|
||||
|
||||
Reference in New Issue
Block a user