<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dark Code Previewer with Enhanced Compiler</title>
    <style>
        /* Reset some default styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html, body {
            height: 100%;
        }

        body {
            background-color: #1e1e1e;
            color: #cccccc;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            display: flex;
            flex-direction: column;
        }

        header {
            background-color: #252526;
            padding: 15px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 1.5rem;
            font-weight: bold;
            border-bottom: 1px solid #333;
            position: relative;
        }

        /* Tabs for Mobile */
        .tabs {
            display: none; /* Hidden by default, shown on mobile */
        }

        .tabs button {
            background: none;
            border: none;
            color: #cccccc;
            padding: 10px 15px;
            cursor: pointer;
            font-size: 1rem;
            transition: background-color 0.3s;
        }

        .tabs button.active, .tabs button:hover {
            background-color: #3a3a3a;
            border-radius: 4px;
        }

        .container {
            flex: 1;
            display: flex;
            overflow: hidden;
        }

        .editor, .preview {
            flex: 1;
            padding: 20px;
            overflow: auto;
        }

        .editor {
            background-color: #1e1e1e;
            border-right: 1px solid #333;
            display: flex;
            flex-direction: column;
        }

        .editor textarea {
            width: 100%;
            height: 100%;
            background-color: #1e1e1e;
            color: #cccccc;
            border: none;
            resize: none;
            font-family: 'Courier New', Courier, monospace;
            font-size: 1rem;
            outline: none;
        }

        .error {
            color: #e74c3c;
            margin-top: 10px;
            font-size: 0.9rem;
            display: none;
        }

        .preview {
            background-color: #2d2d2d;
        }

        /* Scrollbar styling for WebKit */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #1e1e1e;
        }

        ::-webkit-scrollbar-thumb {
            background-color: #555;
            border-radius: 4px;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }
            .editor, .preview {
                flex: 1; /* Allow flex items to grow */
                display: none; /* Hide both by default */
                height: 100%; /* Ensure they can take full height when displayed */
            }
            .editor.active, .preview.active {
                display: flex;
                flex-direction: column;
            }
            .editor {
                border-right: none;
                border-bottom: 1px solid #333;
            }
            .tabs {
                display: flex;
            }
            .error {
                display: block;
            }
        }
    </style>
</head>
<body>
    <header>
        <div>Dark Code Previewer</div>
        <div class="tabs">
            <button id="tab-editor" class="active">Editor</button>
            <button id="tab-preview">Preview</button>
        </div>
    </header>
    <div class="container">
        <div class="editor active">
            <textarea id="code" placeholder="Type your custom code here...">
div>p{&index;. Hey}*5
button[role="button"]#click-me{Click Me}
            </textarea>
            <div id="error-message" class="error"></div>
        </div>
        <div class="preview">
            <iframe id="previewFrame" srcdoc="" frameborder="0" style="width: 100%; height: 100%; background-color: transparent;"></iframe>
        </div>
    </div>

    <script>
        const textarea = document.getElementById('code');
        const previewFrame = document.getElementById('previewFrame');
        const errorMessage = document.getElementById('error-message');

        /**
         * Compiler Function:
         * Transforms custom syntax into standard HTML.
         * Supports:
         * - Tag definitions (e.g., h1{Hello})
         * - Attributes and IDs (e.g., button[role="button"]#click-me{Click Me})
         * - Nesting with '>' (e.g., div>p{Text})
         * - Sibling with '+' (e.g., h1{Title}+p{Subtitle})
         * - Repetition with '*' (e.g., p{&index;. Hey}*5)
         */
        function compileToHTML(customCode) {
            const lines = customCode.split('\n').map(line => line.trim()).filter(line => line !== '');
            let html = '';
            let stack = [];

            try {
                lines.forEach(line => {
                    html += parseLine(line, stack);
                });

                // Close any remaining open tags
                while (stack.length > 0) {
                    const tag = stack.pop();
                    html += `</${tag}>\n`;
                }

                return { html, errors: [] };
            } catch (error) {
                return { html: '', errors: [error.message] };
            }
        }

        /**
         * Parses a single line of custom syntax and returns the HTML.
         * Updates the stack based on nesting.
         * @param {string} line - A line of custom code.
         * @param {Array} stack - The current stack of open tags.
         * @returns {string} - The compiled HTML string.
         */
        function parseLine(line, stack) {
            let html = '';
            let currentIndex = 0;
            const length = line.length;

            while (currentIndex < length) {
                const char = line[currentIndex];

                if (char === '>') {
                    // Nesting operator; expects the next tag to be a child
                    currentIndex++;
                } else if (char === '+') {
                    // Sibling operator; close the current tag
                    if (stack.length === 0) {
                        throw new Error(`Unexpected sibling operator '+' with no open tags.`);
                    }
                    const lastTag = stack.pop();
                    html += `</${lastTag}>\n`;
                    currentIndex++;
                } else {
                    // Parse the tag with optional attributes, ID, content, and repetition
                    const { element, nextIndex } = parseElement(line, currentIndex);
                    currentIndex = nextIndex;

                    if (element.repeat > 1) {
                        for (let i = 1; i <= element.repeat; i++) {
                            let content = element.content.replace(/&index;/g, i);
                            html += `<${element.tag}${element.attributes}>${content}</${element.tag}>\n`;
                        }
                    } else {
                        html += `<${element.tag}${element.attributes}>${element.content}`;
                        if (!element.selfClosing) {
                            // If the next character is '>', this tag has children
                            // Push to stack to keep it open
                            stack.push(element.tag);
                            // Check if next operator is '>'
                            if (line[nextIndex] === '>') {
                                html += `\n`;
                            } else {
                                // Otherwise, close it immediately since no children
                                html += `</${element.tag}>\n`;
                                stack.pop();
                            }
                        } else {
                            html += `\n`;
                        }
                    }
                }
            }

            return html;
        }

        /**
         * Parses an element definition from the custom syntax.
         * @param {string} line - The entire line of custom code.
         * @param {number} start - The starting index to parse from.
         * @returns {Object} - Parsed element and the next index to parse.
         */
        function parseElement(line, start) {
            // Regex to match the element definition with optional attributes, ID, content, and repetition
            // Example matches:
            // div>p{&index;. Hey}*5
            // button[role="button"]#click-me{Click Me}
            const regex = /^(\w+)(?:\[(.*?)\])?(?:#([\w-]+))?(?:\{(.*?)\})?(?:\*(\d+))?/y;
            regex.lastIndex = start;
            const match = regex.exec(line);

            if (!match) {
                throw new Error(`Invalid syntax near "${line.substring(start)}".`);
            }

            const [fullMatch, tag, attrs, id, content, repeat] = match;
            let attributes = '';

            if (attrs) {
                // Attributes are expected to be in key="value" format, separated by spaces
                const attrRegex = /(\w+)="([^"]+)"/g;
                let attrMatch;
                while ((attrMatch = attrRegex.exec(attrs)) !== null) {
                    const [ , attrName, attrValue ] = attrMatch;
                    attributes += ` ${attrName}="${attrValue}"`;
                }

                if (attributes === '') {
                    throw new Error(`Attributes must be in the format key="value".`);
                }
            }

            if (id) {
                attributes += ` id="${id}"`;
            }

            // List of self-closing tags
            const selfClosingTags = ['img', 'br', 'hr', 'input', 'meta', 'link'];
            const isSelfClosing = selfClosingTags.includes(tag.toLowerCase());

            const element = {
                tag,
                attributes,
                content: content || '',
                selfClosing: isSelfClosing,
                repeat: repeat ? parseInt(repeat) : 1
            };

            return { element, nextIndex: regex.lastIndex };
        }

        /**
         * Updates the preview iframe based on the compiled HTML.
         */
        function updatePreview() {
            const customCode = textarea.value;
            const { html, errors } = compileToHTML(customCode);

            if (errors.length > 0) {
                errorMessage.textContent = errors.join(' | ');
                errorMessage.style.display = 'block';
                previewFrame.srcdoc = ''; // Clear preview if there are errors
            } else {
                errorMessage.textContent = '';
                errorMessage.style.display = 'none';
                // Wrap with basic HTML structure and custom dark theme
                const fullHTML = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Preview</title>
    <style>
        body {
            background-color: #1e1e1e;
            color: #cccccc;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
        }
        h1, h2, h3, h4, h5, h6 {
            color: #ffffff;
        }
        p {
            color: #dcdcdc;
            margin-bottom: 10px;
        }
        button {
            padding: 10px 20px;
            background-color: #3498db;
            color: #fff;
            border: none;
            cursor: pointer;
            border-radius: 4px;
            margin-top: 10px;
        }
        button:hover {
            background-color: #2980b9;
        }
        a {
            color: #9b59b6;
        }
        a:hover {
            color: #8e44ad;
        }
        /* Additional styles for various elements */
        ul {
            list-style-type: disc;
            padding-left: 20px;
            margin-bottom: 10px;
        }
        li {
            margin-bottom: 5px;
        }
        input, textarea {
            background-color: #333333;
            color: #ffffff;
            border: 1px solid #555555;
            padding: 8px;
            border-radius: 4px;
            margin-top: 5px;
        }
        input:focus, textarea:focus {
            border-color: #3498db;
            outline: none;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        th, td {
            border: 1px solid #555555;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #444444;
        }
        tr:nth-child(even) {
            background-color: #2d2d2d;
        }
    </style>
</head>
<body>
${html}
</body>
</html>`;
                previewFrame.srcdoc = fullHTML;
            }
        }

        // Initialize preview
        updatePreview();

        // Update preview on input with a slight debounce
        let timeout;
        textarea.addEventListener('input', () => {
            clearTimeout(timeout);
            timeout = setTimeout(updatePreview, 300);
        });

        // Tab functionality for mobile
        const tabEditor = document.getElementById('tab-editor');
        const tabPreview = document.getElementById('tab-preview');
        const editor = document.querySelector('.editor');
        const preview = document.querySelector('.preview');

        function activateTab(tab) {
            if (tab === 'editor') {
                tabEditor.classList.add('active');
                tabPreview.classList.remove('active');
                editor.classList.add('active');
                preview.classList.remove('active');
            } else if (tab === 'preview') {
                tabPreview.classList.add('active');
                tabEditor.classList.remove('active');
                preview.classList.add('active');
                editor.classList.remove('active');
            }
        }

        tabEditor.addEventListener('click', () => activateTab('editor'));
        tabPreview.addEventListener('click', () => activateTab('preview'));
    </script>
</body>
</html>

---

div>p{&index;. Hey}*5
button[role="button"]#click-me{Click Me}

---

Expected result:

<div>
  <p>1. Hey</p>
  <p>2. Hey</p>
  <p>3. Hey</p>
  <p>4. Hey</p>
  <p>5. Hey</p>
</div>
<button role="button" id="click-me">Click Me</button>

---

I got this error instead:

Invalid syntax near "p{&index;. Hey}*5".