'use strict';
(function () {
var editor = document.getElementById('editor');
var preview = document.getElementById('preview');
var gutter = document.getElementById('gutter');
var fileInput = document.getElementById('file-input');
var btnSave = document.getElementById('btn-save');
var btnLoad = document.getElementById('btn-load');
var btnExample = document.getElementById('btn-example');
var btnReset = document.getElementById('btn-reset');
var btnLoadIndex = document.getElementById('btn-load-index');
var btnRemoveCss = document.getElementById('btn-remove-css');
var colorPicker = document.getElementById('colorPicker');
var btnColor = document.getElementById('btnColor');
var btnSymbols = document.getElementById('btnSymbols');
var symbolsDropdown = document.getElementById('symbolsDropdown');
var chkComments = document.getElementById('chkComments');
/* ─── Управление комментариями ──────────────────────────────── */
function stripComments(text) {
return text.replace(/\s*\n?/g, '');
}
function getTemplate(key) {
var raw = tags[key];
if (!raw) return '';
return chkComments.checked ? raw : stripComments(raw);
}
/* ─── Шаблоны тегов ─────────────────────────────────────────── */
var tags = {
doctype: '\n\n',
html: '\n\n\n',
head: '\n
\n \n Заголовок \n',
body: '\n\n\n',
title: '\nЗаголовок ',
meta: '\n ',
h1: '\nЗаголовок 1 ',
h2: '\nЗаголовок 2 ',
h3: '\nЗаголовок 3 ',
h4: '\nЗаголовок 4 ',
p: '\nТекст
',
br: '\n ',
hr: '\n ',
strong: '\nЖирный текст ',
em: '\nКурсив ',
mark: '\nВыделенный текст ',
code: '\nКод',
ul: '\n',
ol: '\n\n Пункт 1 \n Пункт 2 \n ',
li: '\nПункт ',
a: '\nСсылка ',
img: '\n ',
div: '\n\n\n
',
span: '\nТекст ',
table: '\n\n \n Заголовок 1 \n Заголовок 2 \n \n \n Ячейка 1 \n Ячейка 2 \n \n
',
tr: '\n\n Ячейка \n ',
td: '\nТекст ',
th: '\nЗаголовок '
};
/* ─── Подсветка номеров строк ───────────────────────────────── */
function updateGutter() {
var lines = editor.value.split('\n').length;
var html = '';
for (var i = 1; i <= lines; i++) {
html += '' + i + ' ';
}
gutter.innerHTML = html;
}
/* Синхронизация прокрутки gutter */
editor.addEventListener('scroll', function () {
gutter.scrollTop = editor.scrollTop;
});
/* ─── Обновление предпросмотра ───────────────────────────────── */
var updateTimer;
function updatePreview() {
clearTimeout(updateTimer);
updateTimer = setTimeout(function () {
var code = editor.value;
/* Blob URL не резолвит относительные пути — добавляем на текущую папку */
code = code.replace('', ' ');
var blob = new Blob([code], { type: 'text/html; charset=utf-8' });
var url = URL.createObjectURL(blob);
preview.src = url;
preview.onload = function () {
URL.revokeObjectURL(url);
};
}, 300);
}
editor.addEventListener('input', function () {
updateGutter();
updatePreview();
});
/* Tab в textarea */
editor.addEventListener('keydown', function (e) {
if (e.key === 'Tab') {
e.preventDefault();
var start = editor.selectionStart;
var end = editor.selectionEnd;
editor.value = editor.value.substring(0, start) + ' ' + editor.value.substring(end);
editor.selectionStart = editor.selectionEnd = start + 2;
updateGutter();
updatePreview();
}
});
/* ─── Вставка тегов из панели ───────────────────────────────── */
document.getElementById('toolbar').addEventListener('click', function (e) {
var btn = e.target.closest('.editor-btn');
if (!btn) return;
var tagKey = btn.getAttribute('data-tag');
var template = getTemplate(tagKey);
if (!template) return;
var start = editor.selectionStart;
var end = editor.selectionEnd;
var text = editor.value;
editor.value = text.substring(0, start) + template + text.substring(end);
/* Перемещаем курсор внутрь тега, если это парный тег */
if (tagKey !== 'doctype' && tagKey !== 'meta' && tagKey !== 'br' && tagKey !== 'hr' && tagKey !== 'img') {
var innerStart = start + template.indexOf('>') + 1;
var innerEnd = innerStart + (template.includes('\n') ? 0 : template.length - template.indexOf('>') - 1);
editor.selectionStart = innerStart;
editor.selectionEnd = innerEnd;
} else {
editor.selectionStart = editor.selectionEnd = start + template.length;
}
editor.focus();
updateGutter();
updatePreview();
});
/* ─── Цвет текста ─────────────────────────────────────────── */
btnColor.addEventListener('click', function () {
var color = colorPicker.value;
var start = editor.selectionStart;
var end = editor.selectionEnd;
var selected = editor.value.substring(start, end);
var insert = '' + (selected || 'Цветной текст') + ' ';
editor.value = editor.value.substring(0, start) + insert + editor.value.substring(end);
if (!selected) {
editor.selectionStart = start + 24;
editor.selectionEnd = start + 35;
}
editor.focus();
updateGutter();
updatePreview();
});
/* ─── Выпадающее меню символов ─────────────────────────────── */
btnSymbols.addEventListener('click', function (e) {
e.stopPropagation();
var visible = symbolsDropdown.style.display !== 'none';
symbolsDropdown.style.display = visible ? 'none' : 'block';
});
symbolsDropdown.addEventListener('click', function (e) {
var btn = e.target.closest('.symbol-btn');
if (!btn) return;
e.stopPropagation();
var html = btn.getAttribute('data-html');
if (!html) return;
var start = editor.selectionStart;
var text = editor.value;
editor.value = text.substring(0, start) + html + text.substring(editor.selectionEnd);
editor.selectionStart = editor.selectionEnd = start + html.length;
editor.focus();
updateGutter();
updatePreview();
symbolsDropdown.style.display = 'none';
});
/* Закрыть меню при клике вне */
document.addEventListener('click', function (e) {
if (!symbolsDropdown.contains(e.target) && e.target !== btnSymbols) {
symbolsDropdown.style.display = 'none';
}
});
/* ─── Загрузить пример ──────────────────────────────────────── */
btnExample.addEventListener('click', function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'bot-diagram.html', true);
xhr.onload = function () {
if (xhr.status === 200) {
editor.value = xhr.responseText;
updateGutter();
updatePreview();
} else {
alert('Не удалось загрузить пример bot-diagram.html');
}
};
xhr.send();
});
/* ─── Загрузить index.html текущего класса ────────────────────── */
btnLoadIndex.addEventListener('click', function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', './index.html', true);
xhr.onload = function () {
if (xhr.status === 200) {
editor.value = xhr.responseText;
updateGutter();
updatePreview();
} else {
alert('Не удалось загрузить index.html');
}
};
xhr.send();
});
/* ─── Убрать ссылки на CSS ──────────────────────────────────── */
btnRemoveCss.addEventListener('click', function () {
var code = editor.value;
var before = code;
/* Удаляем все теги с CSS */
code = code.replace(/ ]*rel="stylesheet"[^>]*>\s*/gi, '');
code = code.replace(/ ]*type="text\/css"[^>]*>\s*/gi, '');
/* Также удаляем инлайн