51 lines
2.1 KiB
JavaScript
51 lines
2.1 KiB
JavaScript
(function () {
|
|
var textarea = document.getElementById('editor');
|
|
if (!textarea) return;
|
|
|
|
function wrap(before, after, placeholder) {
|
|
var start = textarea.selectionStart;
|
|
var end = textarea.selectionEnd;
|
|
var selected = textarea.value.slice(start, end) || placeholder;
|
|
var replacement = before + selected + after;
|
|
textarea.value = textarea.value.slice(0, start) + replacement + textarea.value.slice(end);
|
|
if (selected === placeholder) {
|
|
textarea.selectionStart = start + before.length;
|
|
textarea.selectionEnd = start + before.length + placeholder.length;
|
|
} else {
|
|
textarea.selectionStart = start + replacement.length;
|
|
textarea.selectionEnd = start + replacement.length;
|
|
}
|
|
textarea.focus();
|
|
}
|
|
|
|
function linePrefix(prefix) {
|
|
var start = textarea.selectionStart;
|
|
var lineStart = textarea.value.lastIndexOf('\n', start - 1) + 1;
|
|
textarea.value = textarea.value.slice(0, lineStart) + prefix + textarea.value.slice(lineStart);
|
|
textarea.selectionStart = textarea.selectionEnd = start + prefix.length;
|
|
textarea.focus();
|
|
}
|
|
|
|
var actions = {
|
|
bold: function () { wrap('**', '**', 'bold text'); },
|
|
italic: function () { wrap('*', '*', 'italic text'); },
|
|
h1: function () { linePrefix('# '); },
|
|
h2: function () { linePrefix('## '); },
|
|
h3: function () { linePrefix('### '); },
|
|
code: function () { wrap('`', '`', 'code'); },
|
|
codeblock: function () { wrap('```\n', '\n```', 'code'); },
|
|
quote: function () { linePrefix('> '); },
|
|
link: function () { wrap('[', '](url)', 'link text'); },
|
|
ul: function () { linePrefix('- '); },
|
|
ol: function () { linePrefix('1. '); },
|
|
hr: function () { wrap('\n\n---\n\n', '', ''); },
|
|
};
|
|
|
|
document.querySelectorAll('[data-action]').forEach(function (btn) {
|
|
btn.addEventListener('click', function () {
|
|
var action = actions[btn.dataset.action];
|
|
if (action) action();
|
|
});
|
|
});
|
|
})();
|