Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

I made a markup language called NoirCode that compiles to HTML: [code]

  1. User

    I made a markup language called NoirCode that compiles to HTML:

    const textarea = document.getElementById('code');
    const previewFrame = document.getElementById('previewFrame');
    const errorMessage = document.getElementById('error-message');
    
    /**
     * Compiles custom code to HTML.
     * @param {string} customCode - The custom code to compile.
     * @returns {Object} - An object containing the compiled HTML and any errors.
     */
    function compileToHTML(customCode) {
        const lines = customCode.split('\n');
        let html = '';
        let errors = [];
        let i = 0;
        const totalLines = lines.length;
        let inBlockComment = false;
    
        while (i < totalLines) {
            let line = lines[i].trim();
    
            if (inBlockComment) {
                if (line.endsWith('#}')) {
                    inBlockComment = false;
                }
                i++;
                continue;
            }
    
            if (line.startsWith('#{')) {
                inBlockComment = true;
                i++;
                continue;
            }
    
            if (line.startsWith('#') && !line.startsWith('#{')) {
                i++;
                continue;
            }
    
            if (line === '\\}') {
                errors.push(`Unexpected block closure '\\}' at line ${i + 1}.`);
                i++;
                continue;
            }
    
            const blockStartMatch = line.match(/^(\w+)(\[[^\]]+\])?(#[\w\-]+)?((?:\.[\w\-]+)*?)\\\{$/);
            if (blockStartMatch) {
                const tag = blockStartMatch[1].toLowerCase();
                const attrs = blockStartMatch[2] ? replaceIndexPlaceholders(blockStartMatch[2].slice(1, -1), 1) : '';
                const id = blockStartMatch[3] ? replaceIndexPlaceholders(blockStartMatch[3].slice(1), 1) : '';
                const classesRaw = blockStartMatch[4] ? blockStartMatch[4] : '';
                const classes = classesRaw.split('.').filter(cls => cls !== '');
    
                let blockContent = '';
                i++;
                let openBlocks = 1;
    
                while (i < totalLines && openBlocks > 0) {
                    let currentLine = lines[i].trim();
    
                    if (currentLine.endsWith('\\{')) {
                        openBlocks++;
                    }
    
                    if (currentLine === '\\}') {
                        openBlocks--;
                        if (openBlocks === 0) {
                            i++;
                            break;
                        }
                    }
    
                    if (openBlocks > 0) {
                        blockContent += lines[i] + '\n';
                    }
    
                    i++;
                }
    
                if (openBlocks > 0) {
                    errors.push(`Unclosed block starting with <${tag}>.`);
                    break;
                }
    
                let innerHTML = '';
    
                if (tag === 'script' || tag === 'style' || tag === 'html') {
                    innerHTML = blockContent;
                } else {
                    let compiledBlock;
                    try {
                        compiledBlock = compileToHTML(blockContent);
                    } catch (error) {
                        errors.push(`Line ${i + 1}: Unexpected error: ${error.message}`);
                        compiledBlock = { html: '', errors: [`Line ${i + 1}: Unexpected error: ${error.message}`] };
                    }
    
                    if (compiledBlock.errors.length > 0) {
                        errors = errors.concat(compiledBlock.errors);
                    }
                    innerHTML = compiledBlock.html;
                }
    
                let attrString = '';
                if (attrs) attrString += ` ${attrs}`;
                if (id) attrString += ` id="${id}"`;
                if (classes.length > 0) attrString += ` class="${classes.join(' ')}"`;
    
                html += `<${tag}${attrString}>\n${innerHTML}</${tag}>\n`;
    
                continue;
            }
    
            const inlineMatch = line.match(/^(\w+)(\[[^\]]+\])?(#[\w\-]+)?((?:\.[\w\-]+)*?)(?:\{([^}]*)\})?(?:\*(\d+))?$/);
            if (inlineMatch) {
                try {
                    const tag = inlineMatch[1].toLowerCase();
                    const attrs = inlineMatch[2] ? replaceIndexPlaceholders(inlineMatch[2].slice(1, -1), 1) : '';
                    const id = inlineMatch[3] ? replaceIndexPlaceholders(inlineMatch[3].slice(1), 1) : '';
                    const classesRaw = inlineMatch[4] ? inlineMatch[4] : '';
                    const classes = classesRaw.split('.').filter(cls => cls !== '');
                    const content = inlineMatch[5] || '';
                    const repeat = inlineMatch[6] ? parseInt(inlineMatch[6]) : 1;
        
                    let finalAttrString = '';
                    if (attrs) finalAttrString += ` ${attrs}`;
                    if (id) finalAttrString += ` id="${id}"`;
                    if (classes.length > 0) finalAttrString += ` class="${classes.join(' ')}"`;
        
                    for (let j = 1; j <= repeat; j++) {
                        const currentContent = replaceIndexPlaceholders(content, j);
                        const currentAttrString = replaceIndexPlaceholders(finalAttrString, j);
                        html += `<${tag}${currentAttrString}>${currentContent}</${tag}>\n`;
                    }
        
                    i++;
                } catch (err) {
                    errors.push(`Line ${i + 1}: ${err.message}`);
                }
                continue;
            }
    
            const siblingTokens = splitRespectingBlocks(line, '+');
            siblingTokens.forEach(token => {
                const nestingTokens = splitRespectingBlocks(token, '>');
                const nestedHTML = processNesting(nestingTokens, 0, errors, i + 1);
                html += nestedHTML;
            });
    
            const textLineMatch = line.match(/^[^+\>]+$/);
            if (!blockStartMatch && !inlineMatch && textLineMatch) {
                html += `${escapeHTML(line)}\n`;
            }
    
            i++;
        }
    
        return { html, errors };
    
        /**
         * Recursive function to process nested tokens.
         * @param {Array} nestingTokens - Array of tokens split by '>'.
         * @param {number} index - Current index in the nestingTokens array.
         * @param {Array} errors - Array to collect error messages.
         * @param {number} lineNumber - Current line number for error reporting.
         * @returns {string} - The generated HTML string after processing nesting.
         */
        function processNesting(nestingTokens, index, errors, lineNumber) {
            if (index >= nestingTokens.length) return '';
    
            const nestedToken = nestingTokens[index].trim();
            const isLast = index === nestingTokens.length - 1;
    
            if (nestedToken === '') return '';
    
            let generatedHTML = '';
    
            try {
                const { tag, attributes, id, classes, content, repeat } = parseElement(nestedToken, lineNumber);
                let attrString = '';
                if (attributes) attrString += ` ${attributes}`;
                if (id) attrString += ` id="${id}"`;
                if (classes.length > 0) attrString += ` class="${classes.join(' ')}"`;
    
                for (let j = 1; j <= repeat; j++) {
                    let finalContent = replaceIndexPlaceholders(content, j);
                    let finalAttrString = replaceIndexPlaceholders(attrString, j);
                    let finalId = replaceIndexPlaceholders(id, j);
                    let finalClasses = classes.map(cls => replaceIndexPlaceholders(cls, j));
    
                    if (finalId) {
                        finalAttrString = finalAttrString.replace(` id="${id}"`, ` id="${finalId}"`);
                    }
    
                    if (finalClasses.length > 0) {
                        const classRegex = /class="([^"]+)"/;
                        const match = finalAttrString.match(classRegex);
                        if (match) {
                            const existingClasses = match[1].split(' ');
                            const updatedClasses = [...new Set([...existingClasses, ...finalClasses])];
                            finalAttrString = finalAttrString.replace(classRegex, `class="${updatedClasses.join(' ')}"`);
                        } else {
                            finalAttrString += ` class="${finalClasses.join(' ')}"`;
                        }
                    }
    
                    generatedHTML += `<${tag}${finalAttrString}>`;
    
                    if (finalContent) {
                        generatedHTML += finalContent;
                    }
    
                    if (!isLast) {
                        generatedHTML += '\n';
                        generatedHTML += processNesting(nestingTokens, index + 1, errors, lineNumber);
                        generatedHTML += `</${tag}>\n`;
                    } else {
                        generatedHTML += `</${tag}>\n`;
                    }
                }
            } catch (err) {
                if (nestedToken.startsWith('\\}')) {
                    return '';
                } else {
                    errors.push(`Line ${lineNumber}: ${err.message}`);
                    generatedHTML += `${escapeHTML(nestedToken)}\n`;
                }
            }
    
            return generatedHTML;
        }
    }
    
    /**
     * Splits a string by a delimiter but ignores delimiters inside quotes or blocks.
     * @param {string} str - The string to split.
     * @param {string} delimiter - The delimiter to split by.
     * @returns {Array} - Array of split tokens.
     */
    function splitRespectingBlocks(str, delimiter) {
        const tokens = [];
        let current = '';
        let inQuotes = false;
        let quoteChar = '';
        let escape = false;
        let blockDepth = 0;
    
        for (let i = 0; i < str.length; i++) {
            let char = str[i];
    
            if (escape) {
                current += char;
                escape = false;
                continue;
            }
    
            if (char === '\\') {
                escape = true;
                current += char;
                continue;
            }
    
            if ((char === '"' || char === "'") && !inQuotes) {
                inQuotes = true;
                quoteChar = char;
                current += char;
                continue;
            }
    
            if (char === quoteChar && inQuotes) {
                inQuotes = false;
                quoteChar = '';
                current += char;
                continue;
            }
    
            if (!inQuotes && char === '{') {
                blockDepth++;
                current += char;
                continue;
            }
    
            if (!inQuotes && char === '}') {
                blockDepth = Math.max(blockDepth - 1, 0);
                current += char;
                continue;
            }
    
            if (!inQuotes && blockDepth === 0 && char === delimiter) {
                tokens.push(current);
                current = '';
                continue;
            }
    
            current += char;
        }
    
        if (current !== '') {
            tokens.push(current);
        }
    
        return tokens;
    }
    
    /**
     * Replaces all instances of &index; with the provided index number.
     * @param {string} str - The string to process.
     * @param {number} index - The index to replace &index; with.
     * @returns {string} - The processed string.
     */
    function replaceIndexPlaceholders(str, index) {
        return str.replace(/&index;/g, index);
    }
    
    /**
     * Parses an element definition from the custom syntax.
     * @param {string} token - A token from the custom code.
     * @param {number} lineNumber - The line number for error reporting.
     * @returns {Object} - Parsed element details.
     */
    function parseElement(token, lineNumber) {
        const regex = /^(\w+)(\[[^\]]+\])?(#[\w\-]+)?((?:\.[\w\-]+)*?)(?:\{([^}]*)\})?(?:\*(\d+))?$/
        const match = token.match(regex);
    
        if (!match) {
            throw { message: `Invalid syntax near "${token}".`, line: lineNumber };
        }
    
        const [, tag, attrs, id, classNames, content, repeat] = match;
        let attributes = '';
        let classes = [];
    
        if (attrs) {
            const attrContent = attrs.slice(1, -1);
            const attrRegex = /(\w+)="([^"]+)"/g;
            let attrMatch;
            while ((attrMatch = attrRegex.exec(attrContent)) !== null) {
                const [, attrName, attrValue] = attrMatch;
                attributes += ` ${attrName}="${attrValue}"`;
            }
    
            const validAttrFormat = [...attrContent.matchAll(attrRegex)].length > 0;
            if (attributes.trim() === '' && attrContent.trim() !== '') {
                throw { message: `Attributes must be in the format key="value".`, line: lineNumber };
            }
        }
    
        if (classNames) {
            classes = classNames.split('.').filter(cls => cls !== '').map(cls => cls.trim());
        }
    
        const element = {
            tag: tag,
            attributes: attributes,
            id: id ? id.slice(1) : '',
            classes: classes,
            content: content ? content : '',
            repeat: repeat ? parseInt(repeat) : 1
        };
    
        return element;
    }
    
    /**
     * Escapes HTML special characters in a string.
     * @param {string} str - The string to escape.
     * @returns {string} - The escaped string.
     */
    function escapeHTML(str) {
        const replacements = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return str.replace(/[&<>"']/g, match => replacements[match]);
    }
    
    function updatePreview() {
        const textarea = document.getElementById('code');
        const previewFrame = document.getElementById('previewFrame');
        const errorMessage = document.getElementById('error-message');
    
        const customCode = textarea.value;
        let compilationResult;
        try {
            compilationResult = compileToHTML(customCode);
        } catch (error) {
            compilationResult = { html: '', errors: [`Unexpected error: ${error.message}`] };
        }
    
        const { html, errors } = compilationResult;
    
        if (errors && errors.length > 0) {
            errorMessage.textContent = errors.join(' | ');
            errorMessage.style.display = 'block';
            previewFrame.srcdoc = '';
        } else {
            errorMessage.textContent = '';
            errorMessage.style.display = 'none';
            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;
            }
            /* Embedded Styles */
            ${extractEmbeddedStyles(html)}
        </style>
    </head>
    <body>
    ${html}
    </body>
    </html>`;
            previewFrame.srcdoc = fullHTML;
        }
    }
    
    /**
     * Extracts embedded <style> blocks from the generated HTML to include in the preview's head.
     * @param {string} html - The generated HTML content.
     * @returns {string} - Extracted CSS from <style> blocks.
     */
    function extractEmbeddedStyles(html) {
        const styleRegex = /<style[^>]*>([\s\S]*?)<\/style>/gi;
        let styles = '';
        let match;
        while ((match = styleRegex.exec(html)) !== null) {
            styles += match[1] + '\n';
        }
        return styles;
    }
    
    updatePreview();
    
    let timeout;
    const textareaElement = document.getElementById('code');
    
    textareaElement.addEventListener('input', () => {
        clearTimeout(timeout);
        timeout = setTimeout(updatePreview, 300);
    });
    
    const tabEditor = document.getElementById('tab-editor');
    const tabPreview = document.getElementById('tab-preview');
    const editor = document.querySelector('.editor');
    const preview = document.querySelector('.preview');
    
    /**
     * Activates the specified tab and deactivates the other.
     * @param {string} tab - The tab to activate ('editor' or 'preview').
     */
    function activateTab(tab) {
        tabEditor.classList.remove('active');
        tabPreview.classList.remove('active');
    
        editor.classList.remove('active');
        preview.classList.remove('active');
    
        if (tab === 'editor') {
            tabEditor.classList.add('active');
            editor.classList.add('active');
        } else if (tab === 'preview') {
            tabPreview.classList.add('active');
            preview.classList.add('active');
        }
    
        handleResponsiveTabs();
    }
    
    function handleResponsiveTabs() {
        const isMobile = window.innerWidth <= 768;
    
        if (isMobile) {
            if (!editor.classList.contains('active') && !preview.classList.contains('active')) {
                editor.classList.add('active');
            }
        } else {
            editor.classList.add('active');
            preview.classList.add('active');
        }
    }
    
    handleResponsiveTabs();
    
    window.addEventListener('resize', handleResponsiveTabs);
    
    tabEditor.addEventListener('click', () => activateTab('editor'));
    tabPreview.addEventListener('click', () => activateTab('preview'));
    
    textareaElement.addEventListener('keydown', e => {
        const openingChars = {
            '"': '"',
            "'": "'",
            '(': ')',
            '{': '}',
            '[': ']',
            '<': '>'
        };
    
        const closingChars = Object.values(openingChars);
    
        if (e.key === 'Backspace') {
            const cursorPos = textareaElement.selectionStart;
            const textBeforeCursor = textareaElement.value.substring(0, cursorPos);
            const lastTwoChars = textBeforeCursor.slice(-2);
            return;
        }
    
        if (e.key === '"' || e.key === "'") {
            const closingChar = openingChars[e.key];
            const cursorPos = textareaElement.selectionStart;
            const beforeCursor = textareaElement.value.substring(0, cursorPos);
            const afterCursor = textareaElement.value.substring(cursorPos);
    
            if (afterCursor.startsWith(closingChar)) {
                e.preventDefault();
                textareaElement.setSelectionRange(cursorPos + 1, cursorPos + 1);
            } else {
                e.preventDefault();
                textareaElement.value = beforeCursor + e.key + closingChar + afterCursor;
                setTimeout(() => {
                    textareaElement.setSelectionRange(cursorPos + 1, cursorPos + 1);
                    textareaElement.dispatchEvent(new Event('input'));
                }, 0);
            }
            return;
        }
    
        if (e.key in openingChars) {
            e.preventDefault();
            const closingChar = openingChars[e.key];
            const cursorPos = textareaElement.selectionStart;
            const beforeCursor = textareaElement.value.substring(0, cursorPos);
            const afterCursor = textareaElement.value.substring(cursorPos);
    
            textareaElement.value = beforeCursor + e.key + closingChar + afterCursor;
            setTimeout(() => {
                textareaElement.setSelectionRange(cursorPos + e.key.length, cursorPos + e.key.length);
                textareaElement.dispatchEvent(new Event('input'));
            }, 0);
        }
    
        if (closingChars.includes(e.key)) {
            const cursorPos = textareaElement.selectionStart;
            const nextChar = textareaElement.value.substring(cursorPos, cursorPos + 1);
            if (e.key === nextChar) {
                e.preventDefault();
                textareaElement.setSelectionRange(cursorPos + 1, cursorPos + 1);
            }
        }
    });
    
  2. Assistant

    You've created a custom markup language called NoirCode that compiles to HTML using JavaScript. This is a great way to experiment with language design and learn about parsing and compiling. Let’s go over how your implementation works and some possible improvements or enhancements you could consider.

    Overview

    1. Basic Structure: The code uses a series of regular expressions to parse and identify the syntax of NoirCode, converting it block by block into HTML. The function compileToHTML() is at the core of this process, using other helper functions to manage specific tasks.

    2. Block and Inline Elements:

      • You support block elements (blocks of code with opening and closing tags) and inline elements (single-line definitions).
      • Blocks are determined by patterns like tag[attr]#id.classname\{, with nesting managed by counting braces.
      • Inline elements also support repetition (e.g., div*3 will render three div elements).
    3. Error Handling: The implementation identifies and collects errors related to syntax issues, such as unexpected block closures or invalid syntax.

    4. Index Placeholders: The use of &index; allows dynamic replacement of iterative elements, which is common in templating systems.

    5. Preview Update: The updatePreview() function generates the HTML view in the preview iframe by embedding the processed HTML and handling errors that are displayed to the user.

    6. Responsive UI: There are functions to switch between 'editor' and 'preview' tabs and to adjust the active view based on screen size, making the UI responsive.

    Improvements and Enhancements

    1. Syntax Highlighting and Editing Features:

      • Consider integrating a syntax highlighting library like CodeMirror or Monaco Editor to improve the editing experience with features like auto-completion and inline error indicators.
    2. Error Feedback:

      • Instead of just stating errors, providing visual feedback directly within the editor (e.g., highlighting the error line) would be beneficial.
      • Detailed error messages and corrective suggestions could help users fix issues more easily.
    3. Performance Optimizations:

      • Consider debouncing the input events a bit more aggressively. Currently, it waits 300ms, but this could be adjusted based on user testing for a better balance between responsiveness and performance.
    4. Extended Syntax Support:

      • Extend NoirCode to support more HTML features (actual HTML attributes parsing, handling of more complex styles, or even custom tags with special behaviors).
    5. Testing and Edge Cases:

      • Consider unit tests for your compilation function to catch edge cases and ensure the renderer works correctly with various input scenarios.
    6. Polyfill Support:

      • If you aim to support older browsers, consider adding polyfills for modern JavaScript constructs used in your code.

    This project offers a lot of room for expansion, both in terms of functionality and user experience, allowing you to explore more about parsing, compiling, and interactive UI design. Keep experimenting, and remember that user feedback can be invaluable in guiding improvements!

  3. User

    Write a simple, yet functional calculator using NoirCode

  4. Assistant

    Creating a functional calculator using NoirCode that compiles to HTML requires defining a simple button-based interface and handling user input to perform calculations. Below is an example of how you might structure NoirCode for a basic calculator:

    NoirCode for a Simple Calculator

    div#calculator
        input[type="text" #display readonly]{0}
        div#buttons
            button{7}
            button{8}
            button{9}
            button[attr="onclick=performOperation('/')"]{/}
            button{4}
            button{5}
            button{6}
            button[attr="onclick=performOperation('*')"]{*}
            button{1}
            button{2}
            button{3}
            button[attr="onclick=performOperation('-')"]{-}
            button{0}
            button{.}
            button[attr="onclick=calculateResult()"]{=}
            button[attr="onclick=performOperation('+')"]{+}
    .script{
    function performOperation(op) {
        const display = document.getElementById('display');
        if (display.value === '0') {
            display.value = '';
        }
        display.value += op;
    }
    
    function calculateResult() {
        const display = document.getElementById('display');
        try {
            display.value = eval(display.value);
        } catch (e) {
            display.value = 'Error';
        }
    }
    
    const buttons = document.getElementById('buttons').getElementsByTagName('button');
    for (let btn of buttons) {
        btn.addEventListener('click', () => {
            const display = document.getElementById('display');
            if (btn.textContent >= '0' && btn.textContent <= '9') {
                if (display.value === '0') display.value = '';
                display.value += btn.textContent;
            } else if (btn.textContent === '.') {
                if (!display.value.includes('.')) display.value += '.';
            }
        });
    }
    }
    

    Explanation

    • Containers and Structure:

      • The main calculator is wrapped in a div with an id of calculator.
      • An input field is used as the display; it starts showing 0 and is set to readonly to prevent direct user input.
    • Buttons and Operations:

      • Buttons are organized in a grid-like structure for numbers, basic operations (+, -, *, /), and decimal point (.).
      • Each operation button has onclick attributes that link to specific JavaScript functions defined in NoirCode's .script block.
    • Script Functionality:

      • performOperation(op): Appends the clicked operation (e.g., +, -) to the current display value.
      • calculateResult(): Evaluates the current expression in the display using eval() and updates the display. It handles exceptions by displaying an error message if the input is invalid.
      • A loop attaches click event listeners to each button for updating the display with numbers or performing decimal point logic.

    Usage

    To run this calculator, your NoirCode processor should compile this into HTML and JavaScript, attaching necessary event handlers to make the buttons functional. This simple NoirCode example creates a basic arithmetic calculator capable of handling simple operations, providing a foundation for more complex functionalities, such as positive and negative numbers, parenthesis handling, and more advanced math operations.

  5. User

    Syntax errors... to let CodeNoir know that you're going to code in more than one line, you gotta write \{ ... \}, example:

    script{ ... }

  6. Assistant

    Thanks for clarifying the block syntax for NoirCode. Let's adjust the calculator example to use your multiline syntax within the script block and ensure there are no syntax issues. The NoirCode for a simple calculator with this adjustment would look like this:

    NoirCode for a Simple Calculator with Multiline Script

    div#calculator\{
        input[type="text" #display readonly]{0}
        div#buttons\{
            button{7}
            button{8}
            button{9}
            button[attr="onclick=performOperation('/')"]{/}
            button{4}
            button{5}
            button{6}
            button[attr="onclick=performOperation('*')"]{*}
            button{1}
            button{2}
            button{3}
            button[attr="onclick=performOperation('-')"]{-}
            button{0}
            button{.}
            button[attr="onclick=calculateResult()"]{=}
            button[attr="onclick=performOperation('+')"]{+}
        \}
    \}
    
    script\{
    function performOperation(op) \{
        const display = document.getElementById('display');
        if (display.value === '0') \{
            display.value = '';
        \}
        display.value += op;
    \}
    
    function calculateResult() \{
        const display = document.getElementById('display');
        try \{
            display.value = eval(display.value);
        \} catch (e) \{
            display.value = 'Error';
        \}
    \}
    
    const buttons = document.getElementById('buttons').getElementsByTagName('button');
    for (let btn of buttons) \{
        btn.addEventListener('click', () => \{
            const display = document.getElementById('display');
            if (btn.textContent >= '0' && btn.textContent <= '9') \{
                if (display.value === '0') display.value = '';
                display.value += btn.textContent;
            \} else if (btn.textContent === '.') \{
                if (!display.value.includes('.')) display.value += '.';
            \}
        \});
    \}
    \}
    

    Description

    • HTML Elements:

      • The calculator structure is created using div, input, and button elements. Their respective attributes and contents are specified directly in the NoirCode format.
    • Multiline Syntax:

      • The script block and div#calculator block use \{ ... \} to indicate that they contain multiple lines.
    • JavaScript Logic:

      • This script manages calculator operations and updates the display with user inputs. Functions handle safe expression evaluation and provide basic error handling.

    Usage

    Compile this NoirCode to HTML using your compiler to see a working calculator. This update should align with the syntax expectations of your NoirCode implementation, facilitating correct parsing and execution.

  7. User

    One thing to consider, the NoirCode syntax doesn't work within script, style, and html elements, so using the \{ ... \} would give you a syntax error by JS, CSS, or HTML

  8. Assistant

    Thank you for pointing that out. Given the constraints that NoirCode syntax should not be used within script, style, and html elements, we need to ensure that these sections contain only plain JavaScript, CSS, or HTML. Let's refine the NoirCode sample for a simple calculator, ensuring that the JavaScript remains unmodified in the script block and stays valid:

    NoirCode for a Simple Calculator

    div#calculator
        input[type="text" #display readonly]{0}
        div#buttons
            button{7}
            button{8}
            button{9}
            button[attr="onclick=performOperation('/')"]{/}
            button{4}
            button{5}
            button{6}
            button[attr="onclick=performOperation('*')"]{*}
            button{1}
            button{2}
            button{3}
            button[attr="onclick=performOperation('-')"]{-}
            button{0}
            button{.}
            button[attr="onclick=calculateResult()"]{=}
            button[attr="onclick=performOperation('+')"]{+}
    
    script{
    function performOperation(op) {
        const display = document.getElementById('display');
        if (display.value === '0') {
            display.value = '';
        }
        display.value += op;
    }
    
    function calculateResult() {
        const display = document.getElementById('display');
        try {
            display.value = eval(display.value);
        } catch (e) {
            display.value = 'Error';
        }
    }
    
    const buttons = document.getElementById('buttons').getElementsByTagName('button');
    for (let btn of buttons) {
        btn.addEventListener('click', () => {
            const display = document.getElementById('display');
            if (btn.textContent >= '0' && btn.textContent <= '9') {
                if (display.value === '0') display.value = '';
                display.value += btn.textContent;
            } else if (btn.textContent === '.') {
                if (!display.value.includes('.')) display.value += '.';
            }
        });
    }
    }
    

    Explanation

    • NoirCode Layout:

      • The visual structure of the calculator is created with NoirCode syntax that references HTML elements.
    • Inline Attributes:

      • For buttons that trigger operations or calculations, HTML event attributes (onclick) are directly specified.
    • JavaScript Execution:

      • Plain JavaScript logic is encapsulated within a script{...} block. Since NoirCode does not interfere with the content of this block, you can include a full JS block with standard JavaScript syntax.

    Usage

    When compiling, ensure that the script contents are directly passed as valid JavaScript to function correctly, without being modified by your NoirCode parser. This should ensure correct execution of operations and updating of the display within the calculator. You may need to handle cases where the parser might incorrectly interpret these blocks, possibly by treating script, style, and html tags specially in your parser logic.