forked from laysense/laysense.cn
Rebuild Laysense site with Webman and SQLite CMS
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
|
||||
const formats = {
|
||||
markdown: {
|
||||
heading: ['## ', '', '小标题'],
|
||||
bold: ['**', '**', '粗体文字'],
|
||||
list: ['- ', '', '列表项'],
|
||||
link: ['[', '](https://)', '链接文字']
|
||||
},
|
||||
html: {
|
||||
heading: ['<h3>', '</h3>', '小标题'],
|
||||
bold: ['<strong>', '</strong>', '粗体文字'],
|
||||
list: ['<ul>\n <li>', '</li>\n</ul>', '列表项'],
|
||||
link: ['<a href="https://">', '</a>', '链接文字']
|
||||
}
|
||||
};
|
||||
|
||||
for (const editor of document.querySelectorAll('[data-editor]')) {
|
||||
const area = editor.querySelector('textarea');
|
||||
const format = editor.dataset.format;
|
||||
const preview = editor.querySelector('.editor-preview');
|
||||
const previewButton = editor.querySelector('[data-preview-button]');
|
||||
const form = editor.closest('form');
|
||||
|
||||
for (const button of editor.querySelectorAll('[data-insert]')) {
|
||||
button.addEventListener('click', () => {
|
||||
const [before, after, example] = formats[format][button.dataset.insert];
|
||||
const start = area.selectionStart;
|
||||
const end = area.selectionEnd;
|
||||
const selection = area.value.slice(start, end) || example;
|
||||
area.setRangeText(before + selection + after, start, end, 'end');
|
||||
area.focus();
|
||||
area.setSelectionRange(start + before.length, start + before.length + selection.length);
|
||||
});
|
||||
}
|
||||
|
||||
previewButton.addEventListener('click', async () => {
|
||||
const show = preview.hidden;
|
||||
preview.hidden = !show;
|
||||
previewButton.textContent = show ? '收起预览' : '预览正文';
|
||||
previewButton.setAttribute('aria-expanded', String(show));
|
||||
if (!show) return;
|
||||
|
||||
preview.textContent = '正在加载预览…';
|
||||
try {
|
||||
const body = new URLSearchParams({body: area.value, format, csrf: form.elements.csrf.value});
|
||||
const response = await fetch('/admin/preview', {method: 'POST', body, redirect: 'error'});
|
||||
if (!response.ok) throw new Error('Preview could not be loaded');
|
||||
const markup = await response.text();
|
||||
preview.innerHTML = markup;
|
||||
} catch {
|
||||
preview.textContent = '预览无法加载,请刷新后重试。';
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user