создание редактора кода с подсветкой синтаксиса на JS
Я хочу сделать редактор кода (для моего языка), на JS. Если кто-то редакторы сделанные с помощью атрибута с contenteditable, пожалуйста скиньте ссылку. Конкретно меня интересует подсветка синтаксиса "на лету". Сделать подсветку по кнопке - просто, а вот чтобы сразу - проблематично.
Ответы (1 шт):
Чтоб его, я это сделал. Только нужно еще немного с css поработать, но в целом все ок. Короче, мне надоело все и я взял textarea, сделал у него все прозрачным кроме каретки и поверх наложил div, а в нем уже рисую весь текст. Вот код:
const textarea = document.getElementById('textarea');
const textDiv = document.getElementById('text');
const highlighterRules = [
{class: "operator", filter: /for|if|else|=|\<|\>|\+/g},
{class: "key_word", filter: /let|function|window/g},
{class: "digit", filter: /\d+/g},
];
const highlighter = function (input, output) {
let text = input.value;
for (let i of highlighterRules) {
text = text.replaceAll(i.filter, `<span class="${i.class}">$&</span>`);
}
text = text.replaceAll("\n", "<br>");
output.innerHTML = text;
};
const adaptive = function () {
textDiv.style.width = textarea.offsetWidth + "px";
textDiv.style.height = textarea.offsetHeight + "px";
};
textarea.addEventListener("input", () => {
adaptive();
highlighter(textarea, textDiv);
});
window.onload = adaptive;
* {
font-family: monospace;
}
body {
margin: 0;
background-color: #6D6D69;
}
.mainContainer {
position: relative;
margin: 10px;
}
.text, .textarea {
position: absolute;
resize: none;
}
.textarea {
background-color: rgba(0, 0, 0, 0);
width: 100%;
min-height: 200px;
border: none;
color: rgba(0, 0, 0, 0);
caret-color: #F8F8F2;
outline: none;
}
.text {
margin: 0;
background-color: #282923;
color: #F8F8F2;
padding-top: 1px;
padding-left: 3px;
}
.operator {
color: #F4005F;
}
.key_word {
color: #58D1EB;
font-style: italic;
}
.digit {
color: #9D65FF;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>editor</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="mainContainer">
<pre id="text" class="text"></pre>
<textarea id="textarea" class="textarea" contenteditable="true"></textarea>
</div>
<script src="script.js"></script>
</body>
</html>
Как видите, на длинных строках текст немного сбивается, если кто знает как это быстро исправить - прошу в комментарии. А так, надеюсь эта тема кому-то поможет. Здесь приведен пример с подсветкой (частичной) JS, но можно в highlighterRules что угодно прописать.