:root {
--bg-color: #f4f4f4;
--editor-bg: #ffffff;
--text-color: #333;
--border-color: #ccc;
--line-number-color: #aaa;
--toolbar-bg: #e0e0e0;
--button-bg: #d0d0d0;
--button-hover-bg: #c0c0c0;
--iframe-bg: #ffffff;
/* Syntax Highlighting Colors */
--hl-tag: #2196F3; /* Синий для тегов */
--hl-attr: #FF9800; /* Оранжевый для атрибутов */
--hl-string: #4CAF50; /* Зеленый для строк */
--hl-comment: #9E9E9E; /* Серый для комментариев */
--hl-keyword: #9C27B0; /* Фиолетовый для JS/CSS ключей */
--hl-css-selector: #e91e63; /* Розовый для CSS селекторов */
--hl-css-prop: #009688; /* Бирюзовый для CSS свойств */
}
body.dark-theme {
--bg-color: #282c34;
--editor-bg: #21252b;
--text-color: #abb2bf;
--border-color: #444;
--line-number-color: #5c6370;
--toolbar-bg: #3a3f4a;
--button-bg: #4a4f5a;
--button-hover-bg: #5a5f6a;
--iframe-bg: #282c34;
--hl-tag: #61afef;
--hl-attr: #d19a66;
--hl-string: #98c379;
--hl-comment: #5c6370;
--hl-keyword: #c678dd;
--hl-css-selector: #e06c75;
--hl-css-prop: #56b6c2;
}
body {
font-family: sans-serif;
margin: 0;
background-color: var(--bg-color);
color: var(--text-color);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
transition: background-color 0.3s, color 0.3s;
}
.container {
display: flex;
flex-direction: column;
width: 95%;
max-width: 1400px;
height: 90vh;
background-color: var(--toolbar-bg);
border: 1px solid var(--border-color);
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
border-radius: 5px;
overflow: hidden; /* Ensure children fit */
}
.toolbar {
padding: 10px;
border-bottom: 1px solid var(--border-color);
background-color: var(--toolbar-bg);
display: flex;
align-items: center;
gap: 10px;
flex-shrink: 0; /* Prevent toolbar from shrinking */
}
.toolbar button {
padding: 8px 15px;
border: 1px solid var(--border-color);
background-color: var(--button-bg);
color: var(--text-color);
cursor: pointer;
border-radius: 3px;
transition: background-color 0.2s;
}
.toolbar button:hover {
background-color: var(--button-hover-bg);
}
.theme-switch {
margin-left: auto; /* Push theme switch to the right */
display: flex;
align-items: center;
gap: 5px;
font-size: 0.9em;
}
.editor-area {
display: flex;
flex-grow: 1; /* Allow editor area to take up space */
height: 50%; /* Default height, can be adjusted */
border-bottom: 1px solid var(--border-color);
overflow: hidden; /* Important for contained scrolling */
position: relative; /* Needed for absolute positioning inside */
background-color: var(--editor-bg);
}
.line-numbers {
width: 40px; /* Fixed width for line numbers */
padding: 10px 5px 10px 10px;
font-family: 'Courier New', Courier, monospace;
font-size: 14px;
line-height: 1.5;
text-align: right;
color: var(--line-number-color);
background-color: var(--editor-bg); /* Match editor background */
border-right: 1px solid var(--border-color);
overflow: hidden; /* Prevent line numbers from wrapping */
user-select: none; /* Prevent selecting line numbers */
box-sizing: border-box;
flex-shrink: 0; /* Don't let it shrink */
}
.code-wrapper {
flex-grow: 1;
position: relative; /* For positioning textarea and pre */
overflow: hidden; /* Hide scrollbars, handled by textarea */
}
#editor, #highlighting {
/* Shared styles for textarea and highlighting layer */
margin: 0;
padding: 10px;
font-family: 'Courier New', Courier, monospace;
font-size: 14px;
line-height: 1.5;
border: none;
outline: none;
resize: none;
white-space: pre; /* Preserve whitespace and prevent wrapping by default */
overflow-wrap: normal; /* Prevent word wrapping by default */
box-sizing: border-box;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: auto; /* Add scrollbars */
background-color: transparent; /* Important */
}
#editor {
z-index: 1; /* Textarea on top for typing */
color: transparent; /* Make text invisible, caret still visible */
caret-color: var(--text-color); /* Make caret visible */
}
#highlighting {
z-index: 0; /* Highlighting below textarea */
color: var(--text-color);
pointer-events: none; /* Ignore clicks */
background-color: var(--editor-bg); /* Actual background */
overflow: hidden; /* Scroll is handled by textarea */
}
#highlighting-content {
display: block; /* Ensure code tag takes block space */
}
/* Basic Syntax Highlighting Styles */
#highlighting .hl-comment { color: var(--hl-comment); font-style: italic; }
#highlighting .hl-string { color: var(--hl-string); }
#highlighting .hl-tag { color: var(--hl-tag); font-weight: bold; }
#highlighting .hl-attr-name { color: var(--hl-attr); }
#highlighting .hl-attr-value { color: var(--hl-string); } /* Often same as string */
#highlighting .hl-js-keyword { color: var(--hl-keyword); font-weight: bold; }
#highlighting .hl-css-selector { color: var(--hl-css-selector); }
#highlighting .hl-css-prop { color: var(--hl-css-prop); }
#highlighting .hl-css-value { color: var(--text-color); } /* Default */
#highlighting .hl-css-comment { color: var(--hl-comment); font-style: italic; }
.output-area {
height: 50%; /* Default height */
display: flex;
flex-direction: column;
background-color: var(--bg-color);
flex-grow: 1; /* Allow output area to take up space */
overflow: hidden; /* Prevent iframe overflow issues */
}
.output-area h3 {
margin: 0;
padding: 10px;
font-size: 1em;
font-weight: normal;
border-bottom: 1px solid var(--border-color);
background-color: var(--toolbar-bg);
flex-shrink: 0; /* Prevent header shrinking */
}
#output {
flex-grow: 1; /* Take remaining space */
border: none;
width: 100%;
height: 100%; /* Fill the container */
background-color: var(--iframe-bg);
}
document.addEventListener('DOMContentLoaded', () => {
const editor = document.getElementById('editor');
const lineNumbers = document.getElementById('lineNumbers');
const highlightingContent = document.getElementById('highlighting-content');
const highlightingElement = document.getElementById('highlighting'); // The <pre> element
const outputFrame = document.getElementById('output');
const runBtn = document.getElementById('runBtn');
const clearBtn = document.getElementById('clearBtn');
const downloadBtn = document.getElementById('downloadBtn');
const themeToggle = document.getElementById('themeToggle');
// --- Initial Content ---
const initialCode = `<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
body { font-family: sans-serif; background-color: #f0f0f0; }
h1 { color: navy; }
/* CSS comment */
</style>
</head>
<body>
<h1>Hello World!</h1>
<p id="myP">This is a paragraph.</p>
<script>
// JavaScript comment
const message = 'Hello from JavaScript!';
console.log(message);
document.getElementById('myP').textContent += ' ' + message;
function greet(name = "User") {
alert(\`Hello, \${name}!\`);
}
// greet(); // Uncomment to run alert on load
<\/script>
</body>
</html>`;
editor.value = initialCode;
// --- Core Editor Logic ---
function updateLineNumbers() {
const lines = editor.value.split('\n');
const lineCount = lines.length || 1; // Ensure at least 1 line number
lineNumbers.innerHTML = Array.from({ length: lineCount }, (_, i) => i + 1).join('\n');
// Adjust padding dynamically if line numbers get wide (optional)
const lastLineNumWidth = lineCount.toString().length * 8 + 15; // Approximate width
if (lineNumbers.offsetWidth < lastLineNumWidth ) {
lineNumbers.style.width = `${lastLineNumWidth}px`;
}
}
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function highlightSyntax(code) {
let highlightedCode = htmlEntities(code);
// Order matters! Apply more specific or problematic patterns first.
// 1. Comments (HTML, CSS, JS multi-line, JS single-line)
highlightedCode = highlightedCode.replace(/(<!--.*?-->)/gs, '<span class="hl-comment">$1</span>'); // HTML comments
highlightedCode = highlightedCode.replace(/(\/\*.*?\*\/)/gs, '<span class="hl-comment">$1</span>'); // CSS/JS multi-line comments
highlightedCode = highlightedCode.replace(/(\/\/.*?(?=\n|$))/g, '<span class="hl-comment">$1</span>'); // JS single-line comments
// 2. Strings (Double and Single Quotes, basic escape handling)
highlightedCode = highlightedCode.replace(/(["'])(?:(?=(\\?))\2.)*?\1/g, (match) => {
// Avoid highlighting inside comments that are already wrapped
if (match.includes('<span')) return match;
return `<span class="hl-string">${match}</span>`;
});
// 3. HTML Tags and Attributes (Improved)
highlightedCode = highlightedCode.replace(/(<\/?)([a-zA-Z0-9\-]+)(.*?)(\/?>)/g, (match, p1, p2, p3, p4) => {
if (match.includes('<span')) return match; // Avoid re-wrapping comments etc.
// Highlight attributes within the tag content (p3)
let attrs = p3.replace(/([a-zA-Z\-]+)=(".*?")/g, '<span class="hl-attr-name">$1</span>=<span class="hl-attr-value">$2</span>');
attrs = attrs.replace(/([a-zA-Z\-]+)=('.*?')/g, '<span class="hl-attr-name">$1</span>=<span class="hl-attr-value">$2</span>'); // Handle single quotes
return `<span class="hl-tag">${p1}${p2}</span>${attrs}<span class="hl-tag">${p4}</span>`;
});
// 4. CSS Rules (Basic: selector { prop: value; }) - Apply within <style> tags if possible (complex)
// For simplicity, apply globally for now. Could be refined.
highlightedCode = highlightedCode.replace(/([^{]+?)(\s*\{)/g, '<span class="hl-css-selector">$1</span>$2'); // Selector
highlightedCode = highlightedCode.replace(/([a-zA-Z\-]+)\s*:(.*?);/g, (match, prop, value) => {
// Avoid highlighting inside comments/strings
if (match.includes('<span')) return match;
return `<span class="hl-css-prop">${prop}</span>:<span class="hl-css-value">${value}</span>;`;
});
// 5. JavaScript Keywords (Basic list) - Apply within <script> tags if possible (complex)
const jsKeywords = ['const', 'let', 'var', 'function', 'return', 'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'break', 'continue', 'new', 'this', 'true', 'false', 'null', 'undefined', 'typeof', 'import', 'export', 'class', 'extends', 'super', 'async', 'await', 'try', 'catch', 'finally'];
const keywordRegex = new RegExp(`\\b(${jsKeywords.join('|')})\\b`, 'g');
highlightedCode = highlightedCode.replace(keywordRegex, (match) => {
// Avoid highlighting inside comments/strings/tags
// This basic check isn't perfect but helps
const preChar = highlightedCode[highlightedCode.lastIndexOf(match) - 1];
const postChar = highlightedCode[highlightedCode.lastIndexOf(match) + match.length];
// Simple check: avoid if inside quotes or angle brackets for now
if (preChar === '"' || preChar === "'" || preChar === '&' || postChar === '&') return match;
if (match.includes('<span')) return match; // Avoid re-wrapping
return `<span class="hl-js-keyword">${match}</span>`;
});
// Add a trailing newline/br if the original code ends with one
// This prevents the last line's height from collapsing in <pre>
if (code.endsWith('\n')) {
highlightedCode += '\n'; // Or use <br> if needed, but \n works with white-space: pre
}
return highlightedCode;
}
function updateHighlighting() {
const code = editor.value;
highlightingContent.innerHTML = highlightSyntax(code);
syncScroll(); // Ensure scroll is synced after content update
}
function syncScroll() {
// Sync scroll position between textarea and highlighting overlay
highlightingElement.scrollTop = editor.scrollTop;
highlightingElement.scrollLeft = editor.scrollLeft;
// Sync line numbers scroll with editor's vertical scroll
lineNumbers.scrollTop = editor.scrollTop;
}
// --- Event Listeners ---
editor.addEventListener('input', () => {
updateHighlighting();
updateLineNumbers();
});
editor.addEventListener('scroll', syncScroll);
// Adjust line numbers on window resize (if layout causes scrollbar changes)
window.addEventListener('resize', updateLineNumbers);
runBtn.addEventListener('click', () => {
const codeToRun = editor.value;
// Use srcdoc for better security and isolation than direct writing
outputFrame.srcdoc = codeToRun;
});
clearBtn.addEventListener('click', () => {
editor.value = '';
updateHighlighting();
updateLineNumbers();
outputFrame.srcdoc = ''; // Clear preview
});
downloadBtn.addEventListener('click', () => {
const codeToDownload = editor.value;
const blob = new Blob([codeToDownload], { type: 'text/html' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'index.html'; // Default filename
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
// --- Theme Toggle ---
themeToggle.addEventListener('change', () => {
document.body.classList.toggle('dark-theme', themeToggle.checked);
// Optional: Store preference in localStorage
localStorage.setItem('simpleIdeTheme', themeToggle.checked ? 'dark' : 'light');
});
// Load theme preference on start
const savedTheme = localStorage.getItem('simpleIdeTheme');
if (savedTheme === 'dark') {
themeToggle.checked = true;
document.body.classList.add('dark-theme');
} else {
themeToggle.checked = false; // Default to light
document.body.classList.remove('dark-theme');
}
// --- Initial Load ---
updateHighlighting();
updateLineNumbers();
runBtn.click(); // Run initial code on load
});