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:
@@ -11,7 +11,8 @@ class PostContentRenderer
|
||||
$paragraph = [];
|
||||
$listType = null;
|
||||
$listItems = [];
|
||||
$flush = function () use (&$blocks, &$paragraph, &$listType, &$listItems): void {
|
||||
$quote = [];
|
||||
$flush = function () use (&$blocks, &$paragraph, &$listType, &$listItems, &$quote): void {
|
||||
if ($paragraph !== []) {
|
||||
$blocks[] = '<p>' . nl2br($this->renderInline(implode("\n", $paragraph))) . '</p>';
|
||||
$paragraph = [];
|
||||
@@ -23,9 +24,35 @@ class PostContentRenderer
|
||||
$listType = null;
|
||||
$listItems = [];
|
||||
}
|
||||
if ($quote !== []) {
|
||||
$blocks[] = '<blockquote class="border-l-4 border-base-300 pl-4 text-base-content/80"><p>' . nl2br($this->renderInline(implode("\n", $quote))) . '</p></blockquote>';
|
||||
$quote = [];
|
||||
}
|
||||
};
|
||||
|
||||
$fence = 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>';
|
||||
$fence = null;
|
||||
$codeLines = [];
|
||||
continue;
|
||||
}
|
||||
$codeLines[] = $line;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^ {0,3}(`{3,}|~{3,})(.*)$/', $line, $matches)) {
|
||||
$flush();
|
||||
$fence = $matches[1];
|
||||
$codeLines = [];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (trim($line) === '') {
|
||||
$flush();
|
||||
continue;
|
||||
@@ -45,6 +72,23 @@ class PostContentRenderer
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$/', $line)) {
|
||||
$flush();
|
||||
$blocks[] = '<hr class="my-6 border-base-300">';
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^ {0,3}> ?(.*)$/', $line, $matches)) {
|
||||
if ($paragraph !== [] || $listType !== null) {
|
||||
$flush();
|
||||
}
|
||||
$quote[] = $matches[1];
|
||||
continue;
|
||||
}
|
||||
if ($quote !== []) {
|
||||
$flush();
|
||||
}
|
||||
|
||||
if (preg_match('/^ {0,3}[-*+]\s+(.+)$/', $line, $matches)) {
|
||||
$type = 'ul';
|
||||
} elseif (preg_match('/^ {0,3}\d+[.)]\s+(.+)$/', $line, $matches)) {
|
||||
@@ -67,6 +111,9 @@ 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>';
|
||||
}
|
||||
return implode("\n", $blocks);
|
||||
}
|
||||
|
||||
|
||||
@@ -57,29 +57,64 @@ $imageUploads = array_values(array_filter((new UploadRepository())->getAll(), st
|
||||
<label for="post-excerpt" class="label"><span class="label-text font-medium">Excerpt</span></label>
|
||||
<textarea id="post-excerpt" name="excerpt" rows="3" class="textarea w-full"><?= phpb_e($post['excerpt']) ?></textarea>
|
||||
</div>
|
||||
<div>
|
||||
<label for="post-body" class="label"><span class="label-text font-medium">Body</span></label>
|
||||
<textarea id="post-body" name="body" rows="12" class="textarea w-full" aria-describedby="post-body-help"><?= phpb_e($post['body']) ?></textarea>
|
||||
<p id="post-body-help" class="mt-1 text-sm text-base-content/60">Use Markdown for headings, links, lists, and emphasis.</p>
|
||||
<div class="mt-3 flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<div class="w-full sm:flex-1">
|
||||
<label for="post-inline-image" class="label"><span class="label-text font-medium">Insert inline image</span></label>
|
||||
<select id="post-inline-image" class="select w-full" aria-describedby="post-inline-image-help">
|
||||
<option value="">Choose an image</option>
|
||||
<?php foreach ($imageUploads as $file): ?>
|
||||
<?php
|
||||
$inlineImageUrl = $file->getUrl();
|
||||
if ($file->original_file !== '') {
|
||||
$inlineImageUrl = substr($inlineImageUrl, 0, -strlen($file->original_file)) . rawurlencode($file->original_file);
|
||||
}
|
||||
?>
|
||||
<option value="<?= phpb_e($file->public_id) ?>" data-url="<?= phpb_e($inlineImageUrl) ?>" data-alt="<?= phpb_e($file->alt_text ?? '') ?>"><?= phpb_e($file->original_file) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<div class="space-y-3">
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<label for="post-body" class="label py-0"><span class="label-text font-medium">Post content</span></label>
|
||||
<div id="post-body-view-tabs" role="tablist" class="tabs tabs-box hidden w-fit" aria-label="Post body view" hidden>
|
||||
<button id="post-body-write-tab" type="button" role="tab" class="tab tab-active" aria-controls="post-body-write-panel" aria-selected="true" tabindex="0" data-view="write">Write</button>
|
||||
<button id="post-body-preview-tab" type="button" role="tab" class="tab" aria-controls="post-body-preview-panel" aria-selected="false" tabindex="-1" data-view="preview">Preview</button>
|
||||
</div>
|
||||
<button type="button" id="insert-post-inline-image" class="btn btn-outline" aria-label="Insert selected image at the cursor">Insert image</button>
|
||||
</div>
|
||||
<p id="post-inline-image-help" class="mt-1 text-sm text-base-content/60">Alt text comes from the media library; the image Markdown is inserted at the cursor.</p>
|
||||
<div id="post-body-write-panel" role="tabpanel" aria-labelledby="post-body-write-tab" tabindex="0" class="space-y-3">
|
||||
<div class="overflow-hidden rounded-box border border-base-300 bg-base-100 shadow-sm">
|
||||
<div id="post-body-toolbar" class="hidden flex flex-wrap gap-1 border-b border-base-300 bg-base-200/50 px-3 py-2" role="toolbar" aria-label="Markdown formatting" hidden>
|
||||
<button type="button" class="btn btn-ghost btn-sm" data-format="bold" aria-label="Bold" title="Bold">Bold</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" data-format="italic" aria-label="Italic" title="Italic">Italic</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" data-format="heading" aria-label="Heading" title="Heading">Heading</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" data-format="link" aria-label="Link" title="Link">Link</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" data-format="list" aria-label="Bulleted list" title="Bulleted list">Bullets</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" data-format="ordered-list" aria-label="Numbered list" title="Numbered list">Numbered list</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" data-format="quote" aria-label="Blockquote" title="Blockquote">Quote</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" data-format="horizontal-rule" aria-label="Horizontal rule" title="Horizontal rule">Rule</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" data-format="code" aria-label="Inline code" title="Inline code">Code</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" data-format="code-block" aria-label="Code block" title="Code block">Code block</button>
|
||||
</div>
|
||||
<div id="post-body-editor" class="blog-markdown-editor hidden w-full" hidden></div>
|
||||
<textarea id="post-body" name="body" rows="16" class="textarea w-full rounded-none border-0 font-mono" aria-describedby="post-body-help"><?= phpb_e($post['body']) ?></textarea>
|
||||
<p id="post-body-help" class="border-t border-base-300 px-4 py-2 text-sm text-base-content/60">Use Markdown for headings, lists, quotes, rules, code blocks, links, and emphasis.</p>
|
||||
</div>
|
||||
<div class="flex flex-col gap-3 sm:flex-row sm:items-end">
|
||||
<div class="w-full sm:flex-1">
|
||||
<label for="post-inline-image" class="label"><span class="label-text font-medium">Insert inline image</span></label>
|
||||
<select id="post-inline-image" class="select w-full" aria-describedby="post-inline-image-help">
|
||||
<option value="">Choose an image</option>
|
||||
<?php foreach ($imageUploads as $file): ?>
|
||||
<?php
|
||||
$inlineImageUrl = $file->getUrl();
|
||||
if ($file->original_file !== '') {
|
||||
$inlineImageUrl = substr($inlineImageUrl, 0, -strlen($file->original_file)) . rawurlencode($file->original_file);
|
||||
}
|
||||
?>
|
||||
<option value="<?= phpb_e($file->public_id) ?>" data-url="<?= phpb_e($inlineImageUrl) ?>" data-alt="<?= phpb_e($file->alt_text ?? '') ?>"><?= phpb_e($file->original_file) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<button type="button" id="insert-post-inline-image" class="btn btn-outline" aria-label="Insert selected image at the cursor">Insert image</button>
|
||||
</div>
|
||||
<p id="post-inline-image-help" class="text-sm text-base-content/60">Alt text comes from the media library; the image Markdown is inserted at the cursor.</p>
|
||||
</div>
|
||||
<section id="post-body-preview-panel" role="tabpanel" aria-labelledby="post-body-preview-tab" tabindex="0" class="hidden" hidden>
|
||||
<div class="min-h-96 overflow-hidden rounded-box border border-base-300 bg-base-100 shadow-sm">
|
||||
<div class="flex flex-col gap-2 border-b border-base-300 bg-base-200/50 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h3 id="post-body-preview-heading" class="font-semibold">Live preview</h3>
|
||||
<p class="text-sm text-base-content/60">Rendered like the published post.</p>
|
||||
</div>
|
||||
<p id="post-body-preview-status" class="text-sm text-base-content/60" role="status" aria-live="polite">Waiting for the preview…</p>
|
||||
</div>
|
||||
<div id="post-body-preview" class="min-h-80 space-y-4 p-5 sm:p-8" role="region" aria-label="Rendered post preview" aria-busy="false"></div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div>
|
||||
<label for="post-featured-image" class="label"><span class="label-text font-medium">Featured image</span></label>
|
||||
@@ -141,11 +176,16 @@ $imageUploads = array_values(array_filter((new UploadRepository())->getAll(), st
|
||||
const altText = option.dataset.alt || option.textContent.trim();
|
||||
const markdownAlt = altText.replace(/[\r\n]+/g, ' ').replace(/&/g, '&').replace(/\[/g, '[').replace(/\]/g, ']');
|
||||
const markdown = ``;
|
||||
if (window.blogMarkdownEditor && window.blogMarkdownEditor.insertAtCursor(markdown)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const start = body.selectionStart;
|
||||
const end = body.selectionEnd;
|
||||
const prefix = start > 0 && !/\s/.test(body.value[start - 1]) ? ' ' : '';
|
||||
const suffix = end < body.value.length && !/\s/.test(body.value[end]) ? ' ' : '';
|
||||
body.setRangeText(prefix + markdown + suffix, start, end, 'end');
|
||||
body.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
body.focus();
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
.blog-markdown-editor .cm-editor {
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
height: clamp(20rem, 55vh, 38rem);
|
||||
color: var(--color-base-content);
|
||||
background: var(--color-base-100);
|
||||
}
|
||||
|
||||
.blog-markdown-editor .cm-editor.cm-focused {
|
||||
outline: 0;
|
||||
box-shadow: inset 0 0 0 2px var(--color-primary);
|
||||
}
|
||||
|
||||
.blog-markdown-editor .cm-scroller {
|
||||
min-height: 0;
|
||||
font-family: var(--default-mono-font, monospace);
|
||||
}
|
||||
|
||||
.blog-markdown-editor .cm-content {
|
||||
padding: 1rem 0.75rem;
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.blog-markdown-editor .cm-line {
|
||||
padding-inline: 0.25rem;
|
||||
}
|
||||
|
||||
.blog-markdown-editor .cm-activeLineGutter {
|
||||
color: var(--color-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
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,301 @@
|
||||
import { markdown } from '@codemirror/lang-markdown';
|
||||
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
|
||||
import { HighlightStyle, bracketMatching, indentOnInput, syntaxHighlighting } from '@codemirror/language';
|
||||
import { drawSelection, EditorView, highlightActiveLine, highlightActiveLineGutter, keymap, lineNumbers } from '@codemirror/view';
|
||||
import { tags } from '@lezer/highlight';
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const textarea = document.getElementById('post-body');
|
||||
const editorMount = document.getElementById('post-body-editor');
|
||||
const toolbar = document.getElementById('post-body-toolbar');
|
||||
const viewTabs = document.getElementById('post-body-view-tabs');
|
||||
const writePanel = document.getElementById('post-body-write-panel');
|
||||
const previewPanel = document.getElementById('post-body-preview-panel');
|
||||
if (!textarea || !editorMount || !toolbar || !viewTabs || !writePanel || !previewPanel) {
|
||||
return;
|
||||
}
|
||||
|
||||
let editor;
|
||||
try {
|
||||
editor = new EditorView({
|
||||
doc: textarea.value,
|
||||
extensions: [
|
||||
markdown(),
|
||||
lineNumbers(),
|
||||
highlightActiveLineGutter(),
|
||||
highlightActiveLine(),
|
||||
drawSelection(),
|
||||
history(),
|
||||
indentOnInput(),
|
||||
bracketMatching(),
|
||||
syntaxHighlighting(HighlightStyle.define([
|
||||
{ tag: tags.heading, color: 'var(--color-primary)', fontWeight: '700' },
|
||||
{ tag: tags.strong, color: 'var(--color-base-content)', fontWeight: '700' },
|
||||
{ tag: tags.emphasis, color: 'var(--color-base-content)', fontStyle: 'italic' },
|
||||
{ tag: tags.link, color: 'var(--color-primary)', textDecoration: 'underline' },
|
||||
{ tag: tags.url, color: 'var(--color-primary)' },
|
||||
{ tag: tags.monospace, color: 'var(--color-base-content)', backgroundColor: 'var(--color-base-200)' },
|
||||
{ tag: tags.quote, color: 'var(--color-base-content)', fontStyle: 'italic' },
|
||||
{ tag: tags.strikethrough, color: 'var(--color-base-content)', textDecoration: 'line-through' },
|
||||
])),
|
||||
EditorView.theme({
|
||||
'&': { color: 'var(--color-base-content)', backgroundColor: 'var(--color-base-100)' },
|
||||
'.cm-content': { caretColor: 'var(--color-primary)' },
|
||||
'.cm-cursor, .cm-dropCursor': { borderLeftColor: 'var(--color-primary)' },
|
||||
'.cm-selectionBackground, &.cm-focused .cm-selectionBackground': { backgroundColor: 'color-mix(in oklab, var(--color-primary) 35%, transparent)' },
|
||||
'.cm-gutters': { color: 'var(--color-base-content)', backgroundColor: 'var(--color-base-200)', borderRight: '1px solid var(--color-base-300)' },
|
||||
'.cm-activeLine, .cm-activeLineGutter': { backgroundColor: 'color-mix(in oklab, var(--color-base-200) 70%, transparent)' },
|
||||
'.cm-matchingBracket': { backgroundColor: 'var(--color-base-200)', outline: '1px solid var(--color-primary)' },
|
||||
}),
|
||||
keymap.of([...defaultKeymap, ...historyKeymap, indentWithTab]),
|
||||
EditorView.lineWrapping,
|
||||
EditorView.contentAttributes.of({
|
||||
'aria-label': 'Post body Markdown',
|
||||
'aria-describedby': 'post-body-help',
|
||||
}),
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged) {
|
||||
textarea.value = update.state.doc.toString();
|
||||
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
}
|
||||
}),
|
||||
],
|
||||
parent: editorMount,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Could not initialize the blog Markdown editor.', error);
|
||||
return;
|
||||
}
|
||||
|
||||
editorMount.hidden = false;
|
||||
editorMount.classList.remove('hidden');
|
||||
toolbar.hidden = false;
|
||||
toolbar.classList.remove('hidden');
|
||||
textarea.hidden = true;
|
||||
|
||||
const tabs = Array.from(viewTabs.querySelectorAll('[role="tab"]'));
|
||||
const activateView = (view, focus = false) => {
|
||||
const showPreview = view === 'preview';
|
||||
tabs.forEach((tab) => {
|
||||
const active = tab.dataset.view === view;
|
||||
tab.setAttribute('aria-selected', String(active));
|
||||
tab.tabIndex = active ? 0 : -1;
|
||||
tab.classList.toggle('tab-active', active);
|
||||
if (focus && active) {
|
||||
tab.focus();
|
||||
}
|
||||
});
|
||||
writePanel.hidden = showPreview;
|
||||
writePanel.classList.toggle('hidden', showPreview);
|
||||
previewPanel.hidden = !showPreview;
|
||||
previewPanel.classList.toggle('hidden', !showPreview);
|
||||
};
|
||||
|
||||
activateView('write');
|
||||
viewTabs.hidden = false;
|
||||
viewTabs.classList.remove('hidden');
|
||||
viewTabs.addEventListener('click', (event) => {
|
||||
const tab = event.target.closest('[role="tab"][data-view]');
|
||||
if (tab) {
|
||||
activateView(tab.dataset.view);
|
||||
}
|
||||
});
|
||||
viewTabs.addEventListener('keydown', (event) => {
|
||||
const currentIndex = tabs.indexOf(document.activeElement);
|
||||
if (currentIndex < 0) {
|
||||
return;
|
||||
}
|
||||
const nextIndex = event.key === 'ArrowRight'
|
||||
? (currentIndex + 1) % tabs.length
|
||||
: event.key === 'ArrowLeft'
|
||||
? (currentIndex - 1 + tabs.length) % tabs.length
|
||||
: event.key === 'Home'
|
||||
? 0
|
||||
: event.key === 'End'
|
||||
? tabs.length - 1
|
||||
: -1;
|
||||
if (nextIndex !== -1) {
|
||||
event.preventDefault();
|
||||
activateView(tabs[nextIndex].dataset.view, true);
|
||||
}
|
||||
});
|
||||
|
||||
const applyFormatting = (button) => {
|
||||
const selection = editor.state.selection.main;
|
||||
const format = button.dataset.format;
|
||||
|
||||
if (format === 'horizontal-rule') {
|
||||
const line = editor.state.doc.lineAt(selection.from);
|
||||
const insert = line.text ? '\n\n---' : '---';
|
||||
editor.dispatch({
|
||||
changes: { from: line.to, to: line.to, insert },
|
||||
selection: { anchor: line.to + insert.length },
|
||||
});
|
||||
editor.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (format === 'code-block' || format === 'quote') {
|
||||
const firstLine = editor.state.doc.lineAt(selection.from);
|
||||
const lastLine = editor.state.doc.lineAt(selection.to);
|
||||
const selectedText = editor.state.doc.sliceString(firstLine.from, lastLine.to);
|
||||
const lines = selectedText.split('\n');
|
||||
const insert = format === 'code-block'
|
||||
? `\`\`\`\n${selectedText || 'Code block'}\n\`\`\``
|
||||
: lines.every((line) => line.startsWith('> '))
|
||||
? lines.map((line) => line.slice(2)).join('\n')
|
||||
: lines.map((line) => `> ${line || 'Quote'}`).join('\n');
|
||||
editor.dispatch({
|
||||
changes: { from: firstLine.from, to: lastLine.to, insert },
|
||||
selection: format === 'code-block'
|
||||
? { anchor: firstLine.from + 4, head: firstLine.from + 4 + (selectedText || 'Code block').length }
|
||||
: { anchor: firstLine.from, head: firstLine.from + insert.length },
|
||||
});
|
||||
editor.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (format === 'heading' || format === 'list' || format === 'ordered-list') {
|
||||
const line = editor.state.doc.lineAt(selection.from);
|
||||
const prefix = format === 'heading' ? '## ' : format === 'ordered-list' ? '1. ' : '- ';
|
||||
const hasPrefix = format === 'ordered-list'
|
||||
? /^\d+[.)]\s/.test(line.text)
|
||||
: format === 'list'
|
||||
? /^[-*+]\s/.test(line.text)
|
||||
: line.text.startsWith(prefix);
|
||||
const lineText = hasPrefix
|
||||
? line.text.replace(format === 'ordered-list' ? /^\d+[.)]\s/ : format === 'list' ? /^[-*+]\s/ : /^## /, '')
|
||||
: `${prefix}${line.text || (format === 'heading' ? 'Heading' : 'List item')}`;
|
||||
const selectedFrom = line.from + (hasPrefix ? 0 : prefix.length);
|
||||
editor.dispatch({
|
||||
changes: { from: line.from, to: line.to, insert: lineText },
|
||||
selection: { anchor: selectedFrom, head: line.from + lineText.length },
|
||||
});
|
||||
editor.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
const formats = {
|
||||
bold: ['**', '**', 'bold text'],
|
||||
italic: ['*', '*', 'italic text'],
|
||||
link: ['[', '](https://example.com)', 'link text'],
|
||||
code: ['`', '`', 'code'],
|
||||
};
|
||||
const [before, after, placeholder] = formats[format] || [];
|
||||
if (before === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedText = editor.state.sliceDoc(selection.from, selection.to);
|
||||
const text = selectedText || placeholder;
|
||||
editor.dispatch({
|
||||
changes: { from: selection.from, to: selection.to, insert: `${before}${text}${after}` },
|
||||
selection: {
|
||||
anchor: selection.from + before.length,
|
||||
head: selection.from + before.length + text.length,
|
||||
},
|
||||
});
|
||||
editor.focus();
|
||||
};
|
||||
|
||||
toolbar.addEventListener('click', (event) => {
|
||||
const button = event.target.closest('button[data-format]');
|
||||
if (button) {
|
||||
applyFormatting(button);
|
||||
}
|
||||
});
|
||||
|
||||
const form = textarea.form;
|
||||
form?.addEventListener('submit', () => {
|
||||
textarea.value = editor.state.doc.toString();
|
||||
});
|
||||
|
||||
const preview = document.getElementById('post-body-preview');
|
||||
const previewStatus = document.getElementById('post-body-preview-status');
|
||||
if (form && preview && previewStatus) {
|
||||
let previewTimer;
|
||||
let previewRequestId = 0;
|
||||
let activePreviewRequest = null;
|
||||
|
||||
const setPreviewStatus = (message, isError = false) => {
|
||||
previewStatus.textContent = message;
|
||||
previewStatus.classList.toggle('text-error', isError);
|
||||
previewStatus.classList.toggle('text-base-content/60', !isError);
|
||||
};
|
||||
|
||||
const schedulePreview = () => {
|
||||
window.clearTimeout(previewTimer);
|
||||
const requestId = ++previewRequestId;
|
||||
activePreviewRequest?.abort();
|
||||
activePreviewRequest = null;
|
||||
preview.replaceChildren();
|
||||
preview.setAttribute('aria-busy', 'true');
|
||||
setPreviewStatus('Updating preview…');
|
||||
|
||||
previewTimer = window.setTimeout(async () => {
|
||||
const csrfToken = form.querySelector('[name="_csrf_token"]')?.value || '';
|
||||
if (!csrfToken) {
|
||||
if (requestId === previewRequestId) {
|
||||
setPreviewStatus('Preview unavailable. Your Markdown is unchanged and can still be saved.', true);
|
||||
preview.setAttribute('aria-busy', 'false');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const request = new AbortController();
|
||||
activePreviewRequest = request;
|
||||
const requestBody = new FormData();
|
||||
requestBody.set('body', textarea.value);
|
||||
requestBody.set('_csrf_token', csrfToken);
|
||||
|
||||
try {
|
||||
const response = await fetch('/ext--blog/preview-post', {
|
||||
method: 'POST',
|
||||
body: requestBody,
|
||||
credentials: 'same-origin',
|
||||
headers: { Accept: 'application/json' },
|
||||
signal: request.signal,
|
||||
});
|
||||
const result = await response.json();
|
||||
if (requestId !== previewRequestId) {
|
||||
return;
|
||||
}
|
||||
if (!response.ok || !result || typeof result.html !== 'string') {
|
||||
throw new Error('Preview request failed.');
|
||||
}
|
||||
|
||||
preview.innerHTML = result.html;
|
||||
setPreviewStatus(result.html === '' ? 'The post body is empty.' : 'Preview updated.');
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError' && requestId === previewRequestId) {
|
||||
setPreviewStatus('Preview unavailable. Your Markdown is unchanged and can still be saved.', true);
|
||||
}
|
||||
} finally {
|
||||
if (requestId === previewRequestId) {
|
||||
activePreviewRequest = null;
|
||||
preview.setAttribute('aria-busy', 'false');
|
||||
}
|
||||
}
|
||||
}, 300);
|
||||
};
|
||||
|
||||
textarea.addEventListener('input', schedulePreview);
|
||||
schedulePreview();
|
||||
}
|
||||
|
||||
window.blogMarkdownEditor = {
|
||||
insertAtCursor(markdown) {
|
||||
const selection = editor.state.selection.main;
|
||||
const document = editor.state.doc;
|
||||
const before = selection.from > 0 && !/\s/.test(document.sliceString(selection.from - 1, selection.from)) ? ' ' : '';
|
||||
const after = selection.to < document.length && !/\s/.test(document.sliceString(selection.to, selection.to + 1)) ? ' ' : '';
|
||||
const insertion = `${before}${markdown}${after}`;
|
||||
editor.dispatch({
|
||||
changes: { from: selection.from, to: selection.to, insert: insertion },
|
||||
selection: { anchor: selection.from + insertion.length },
|
||||
});
|
||||
editor.focus();
|
||||
return true;
|
||||
},
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user