Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

Write the full complete code dont skip anything, write the full code with the new edits…

  1. User

    Write the full complete code dont skip anything, write the full code with the new edits you did just write the full complete code ,I want you to add on the tool box with shapes of adobe illustrator the shapes they use, make them a svg, vector whatever so later I can add strokes and gradient without being a problem, just add this in but make the shapes just like adobe illustator shapes they have, make it so there is icon a shape icon or something and when they click it will open the toolbox of shapes they can pick from, make it when they click it the user can add how adobe illstator with a shortcut saying what, dont change the css/ui though but do these changes and nothing else:

    <script>
        let copiedElement = null;
        let codeArea = document.getElementById('codeArea');
        let codeElement = document.getElementById('code');
        let undoStack = [];
        let redoStack = [];
    
        function toggleGrid() {
            const grid = document.getElementById('grid');
            grid.style.display = grid.style.display === 'none' ? 'block' : 'none';
            saveState();
        }
    
        function changeCanvasColor(color) {
            const canvas = document.getElementById('canvas');
            canvas.style.backgroundColor = color;
            updateCode(); // Update code when background color changes
            saveState();
        }
    
        function addText() {
            const canvas = document.getElementById('canvas');
            const text = document.createElement('div');
            text.className = 'canvas-text';
            text.id = 'text-' + Date.now();
            const textContent = document.createElement('div');
            textContent.contentEditable = true;
            textContent.textContent = 'Double click to edit';
            textContent.setAttribute('tabindex', '0'); // Make it focusable
            text.appendChild(textContent);
            text.style.left = '50px';
            text.style.top = '50px';
            text.style.width = '200px';
            text.style.height = '50px';
            textContent.style.fontSize = '16px';
            textContent.style.color = '#000000';
            text.style.opacity = 1;
    
            canvas.appendChild(text);
            makeDraggable(text);
            makeSelectable(text);
            addTextControls(text);
            text.addEventListener('dblclick', function() {
                textContent.focus();
                document.execCommand('selectAll', false, null);
            });
            textContent.addEventListener('input', function() {
                updateLayerPanel();
                updateCode();
                saveState();
            });
            updateLayerPanel();
            updateCode();
            saveState();
        }
    
        function addMedia() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/*';
            input.onchange = function(event) {
                const file = event.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const canvas = document.getElementById('canvas');
                        const media = document.createElement('div');
                        media.className = 'canvas-media';
                        media.id = 'media-' + Date.now();
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        img.dataset.scale = 1;
                        img.style.transformOrigin = 'center center';
                        img.onwheel = (e) => {
                            e.preventDefault();
                            zoomMedia(img, e);
                        };
                        img.ondragstart = () => false;
                        media.appendChild(img);
    
                        img.onload = function() {
                            let scale = 1;
                            if (img.naturalWidth > 400 || img.naturalHeight > 300) {
                                // Scale down if image is too big
                                scale = Math.min(400 / img.naturalWidth, 300 / img.naturalHeight);
                            }
                            media.style.width = img.naturalWidth * scale + 'px';
                            media.style.height = img.naturalHeight * scale + 'px';
                            media.style.left = '50px';
                            media.style.top = '50px';
                            media.style.opacity = 1;
                            img.style.width = '100%';
                            img.style.height = '100%';
                        };
    
                        canvas.appendChild(media);
                        makeDraggable(media);
                        makeSelectable(media);
                        addMediaControls(media);
                        updateLayerPanel();
                        updateCode();
                        saveState();
                    };
                    reader.readAsDataURL(file);
                }
            };
            input.click();
        }
    
        function makeDraggable(element) {
            let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
            const canvas = document.getElementById('canvas');
            let isResizing = false;
            let currentHandle = null;
    
            if (element.classList.contains('canvas-text') || element.classList.contains('canvas-media') || element.classList.contains('canvas-shape')) {
                addResizeHandles(element);
            }
    
            element.onmousedown = dragMouseDown;
    
            function dragMouseDown(e) {
                if (element.dataset.locked === 'true') {
                    return;
                }
                if (e.target.classList.contains('resize-handle')) {
                    isResizing = true;
                    currentHandle = e.target;
                    e.stopPropagation();
                    document.onmouseup = closeDragElement;
                    document.onmousemove = elementResize;
                } else {
                    e = e || window.event;
                    e.preventDefault();
                    e.stopPropagation();
                    pos3 = e.clientX;
                    pos4 = e.clientY;
                    document.onmouseup = closeDragElement;
                    document.onmousemove = elementDrag;
                    clearSelection();
                    element.classList.add('selected');
                    showElementControls(element);
                }
            }
    
            function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;
    
                let newTop = element.offsetTop - pos2;
                let newLeft = element.offsetLeft - pos1;
    
                // Constraints so that the element does not leave the canvas
                let maxTop = canvas.offsetHeight - element.offsetHeight;
                let maxLeft = canvas.offsetWidth - element.offsetWidth;
    
                if (newTop < 0) newTop = 0;
                if (newLeft < 0) newLeft = 0;
                if (newTop > maxTop) newTop = maxTop;
                if (newLeft > maxLeft) newLeft = maxLeft;
    
                element.style.top = newTop + "px";
                element.style.left = newLeft + "px";
    
                // Update controls position if visible
                if (element.classList.contains('selected')) {
                    showElementControls(element);
                }
            }
    
            function elementResize(e) {
                e.preventDefault();
                const rect = element.getBoundingClientRect();
                let width, height;
                if (currentHandle.classList.contains('bottom-right')) {
                    width = e.clientX - rect.left;
                    height = e.clientY - rect.top;
                } else if (currentHandle.classList.contains('bottom-left')) {
                    width = rect.right - e.clientX;
                    height = e.clientY - rect.top;
                    element.style.left = element.offsetLeft + (e.clientX - rect.left) + 'px';
                } else if (currentHandle.classList.contains('top-right')) {
                    width = e.clientX - rect.left;
                    height = rect.bottom - e.clientY;
                    element.style.top = element.offsetTop + (e.clientY - rect.top) + 'px';
                } else if (currentHandle.classList.contains('top-left')) {
                    width = rect.right - e.clientX;
                    height = rect.bottom - e.clientY;
                    element.style.left = element.offsetLeft + (e.clientX - rect.left) + 'px';
                    element.style.top = element.offsetTop + (e.clientY - rect.top) + 'px';
                }
                if (width > 20 && height > 20) {
                    element.style.width = width + 'px';
                    element.style.height = height + 'px';
    
                    // For images, adjust the img size
                    if (element.classList.contains('canvas-media')) {
                        const img = element.querySelector('img');
                        img.style.width = '100%';
                        img.style.height = '100%';
                    }
    
                    // For shapes, adjust SVG size
                    if (element.classList.contains('canvas-shape')) {
                        const svg = element.querySelector('svg');
                        svg.setAttribute('width', width);
                        svg.setAttribute('height', height);
                    }
                }
                // Update controls position if visible
                if (element.classList.contains('selected')) {
                    showElementControls(element);
                }
                updateCode();
                saveState();
            }
    
            function closeDragElement() {
                document.onmouseup = null;
                document.onmousemove = null;
                isResizing = false;
                currentHandle = null;
                updateCode(); // Update code after dragging completes
                saveState();
            }
        }
    
        function addResizeHandles(element) {
            const handles = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
            handles.forEach(handle => {
                const div = document.createElement('div');
                div.className = 'resize-handle ' + handle;
                element.appendChild(div);
            });
        }
    
        function makeSelectable(element) {
            element.addEventListener('click', function(e) {
                if (element.dataset.locked === 'true') {
                    return;
                }
                e.stopPropagation(); // prevent event bubbling
                clearSelection(); // Deselect others
                element.classList.add('selected'); // apply selected class
                showElementControls(element);
                // Update the global opacity slider
                const globalOpacity = document.getElementById('globalOpacity');
                globalOpacity.value = element.style.opacity * 100;
            });
        }
    
        function clearSelection() {
            document.querySelectorAll('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected').forEach(el => {
                el.classList.remove('selected');
            });
            hideAllControls();
        }
    
        function showElementControls(element) {
            hideAllControls();
            if (element.classList.contains('canvas-text')) {
                const controls = document.querySelector(`.text-controls[data-text-id="${element.id}"]`);
                if (controls) {
                    controls.style.display = 'flex';
                    const canvas = document.getElementById('canvas');
                    const canvasRect = canvas.getBoundingClientRect();
                    controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
                    controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
                }
            } else if (element.classList.contains('canvas-media')) {
                const controls = document.querySelector(`.media-controls[data-media-id="${element.id}"]`);
                if (controls) {
                    controls.style.display = 'flex';
                    const canvas = document.getElementById('canvas');
                    const canvasRect = canvas.getBoundingClientRect();
                    controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
                    controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
                }
            }
            // Show canvas outline
            const canvasOutline = document.getElementById('canvasOutline');
            canvasOutline.style.display = 'block';
            canvasOutline.style.top = `${element.offsetTop - 10}px`;
            canvasOutline.style.left = `${element.offsetLeft - 10}px`;
            canvasOutline.style.width = `${element.offsetWidth + 20}px`;
            canvasOutline.style.height = `${element.offsetHeight + 20}px`;
        }
    
        function hideAllControls() {
            document.querySelectorAll('.text-controls, .media-controls, .shape-controls').forEach(control => {
                control.style.display = 'none';
            });
            // Hide canvas outline
            const canvasOutline = document.getElementById('canvasOutline');
            canvasOutline.style.display = 'none';
        }
    
        function addTextControls(textElement) {
            const wrapper = document.getElementById('text-controls-wrapper');
            const controls = document.createElement('div');
            controls.className = 'text-controls';
            controls.setAttribute('data-text-id', textElement.id);
            controls.style.display = 'none';
            controls.innerHTML = `
                <button onclick="toggleBold(this, '${textElement.id}')" title="Bold"><i class="material-icons">format_bold</i></button>
                <button onclick="toggleItalic(this, '${textElement.id}')" title="Italic"><i class="material-icons">format_italic</i></button>
                <button onclick="toggleUnderline(this, '${textElement.id}')" title="Underline"><i class="material-icons">format_underline</i></button>
                <input type="color" onchange="changeTextColor(this.value, '${textElement.id}')" title="Text Color">
                <input type="number" min="1" max="100" value="16" onchange="changeFontSize(this.value, '${textElement.id}')" title="Font Size">
                <select onchange="changeFontFamily(this.value, '${textElement.id}')" title="Font Family">
                    <option value="Roboto">Roboto</option>
                    <option value="'Source Sans Pro'">Source Sans Pro</option>
                    <option value="Arial">Arial</option>
                    <option value="Helvetica">Helvetica</option>
                    <option value="'Times New Roman'">Times New Roman</option>
                    <option value="'Courier New'">Courier New</option>
                    <option value="Verdana">Verdana</option>
                    <option value="Georgia">Georgia</option>
                    <option value="Palatino">Palatino</option>
                    <option value="Garamond">Garamond</option>
                    <option value="Bookman">Bookman</option>
                    <option value="'Comic Sans MS'">Comic Sans MS</option>
                    <option value="'Trebuchet MS'">Trebuchet MS</option>
                    <option value="'Arial Black'">Arial Black</option>
                </select>
            `;
    
            wrapper.appendChild(controls);
        }
    
        function addMediaControls(mediaElement) {
            const wrapper = document.getElementById('media-controls-wrapper');
            const controls = document.createElement('div');
            controls.className = 'media-controls';
            controls.setAttribute('data-media-id', mediaElement.id);
            controls.style.display = 'none';
            controls.innerHTML = `
                <button onclick="removeMedia('${mediaElement.id}')" title="Remove"><i class="material-icons">delete</i></button>
                <button onclick="resetZoom('${mediaElement.id}')" title="Reset Zoom"><i class="material-icons">zoom_out_map</i></button>
            `;
    
            wrapper.appendChild(controls);
        }
    
        // Text Control Functions
        function changeTextColor(color, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            textContent.style.color = color;
            updateCode();
            saveState();
        }
    
        function changeFontSize(size, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            textContent.style.fontSize = size + 'px';
            updateCode();
            saveState();
        }
    
        function changeFontFamily(family, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            textContent.style.fontFamily = family;
            updateCode();
            saveState();
        }
    
        function toggleBold(button, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            const isBold = textContent.style.fontWeight === 'bold';
            textContent.style.fontWeight = isBold ? 'normal' : 'bold';
            button.classList.toggle('active', !isBold);
            updateCode();
            saveState();
        }
    
        function toggleItalic(button, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            const isItalic = textContent.style.fontStyle === 'italic';
            textContent.style.fontStyle = isItalic ? 'normal' : 'italic';
            button.classList.toggle('active', !isItalic);
            updateCode();
            saveState();
        }
    
        function toggleUnderline(button, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            const isUnderline = textContent.style.textDecoration === 'underline';
            textContent.style.textDecoration = isUnderline ? 'none' : 'underline';
            button.classList.toggle('active', !isUnderline);
            updateCode();
            saveState();
        }
    
        // Media Control Functions
        function removeMedia(mediaId) {
            const mediaElement = document.getElementById(mediaId);
            mediaElement.remove();
            const mediaControls = document.querySelector(`.media-controls[data-media-id="${mediaId}"]`);
            if (mediaControls) {
                mediaControls.style.display = 'none';
            }
            updateLayerPanel();
            updateCode();
            saveState();
        }
    
        function resetZoom(mediaId) {
            const mediaElement = document.getElementById(mediaId);
            const img = mediaElement.querySelector('img');
            img.style.transform = 'scale(1)';
            img.dataset.scale = 1;
            // Adjust the container size
            mediaElement.style.width = img.naturalWidth + 'px';
            mediaElement.style.height = img.naturalHeight + 'px';
            updateCode();
            saveState();
        }
    
        function zoomMedia(img, e) {
            e.preventDefault();
    
            const delta = e.deltaY;
    
            const zoomFactor = 0.05; // Smaller zoom factor for smoother zooming
    
            // Get current scale
            let scale = img.dataset.scale ? parseFloat(img.dataset.scale) : 1;
            // Update scale
            scale *= delta > 0 ? (1 - zoomFactor) : (1 + zoomFactor);
            // Limit scale
            scale = Math.min(Math.max(0.1, scale), 10);
            img.dataset.scale = scale;
    
            // Apply scale transform
            img.style.transform = `scale(${scale})`;
    
            // Adjust the container size based on the scaled image size
            const mediaElement = img.parentElement;
            mediaElement.style.width = img.naturalWidth * scale + 'px';
            mediaElement.style.height = img.naturalHeight * scale + 'px';
    
            updateCode();
            saveState();
        }
    
        // Global Opacity Control
        function changeGlobalOpacity(value) {
            const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
            if (selectedElement) {
                selectedElement.style.opacity = value / 100;
                updateCode();
                saveState();
            }
        }
    
        // Initial save state
        saveState();
    
        // Handle click outside to clear selection
        document.getElementById('canvas').addEventListener('click', function(e) {
            if (e.target === this) {
                clearSelection();
            }
        });
    
        // Code Editor Toggles and Updates
        function toggleCode() {
            updateCode();
            codeArea.style.display = codeArea.style.display === 'block' ? 'none' : 'block';
            saveState();
        }
    
        function makeElementDraggable(elmnt) {
            var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
            elmnt.onmousedown = dragMouseDown;
    
            function dragMouseDown(e) {
                e = e || window.event;
                e.preventDefault();
                // get the mouse cursor position at startup:
                pos3 = e.clientX;
                pos4 = e.clientY;
                document.onmouseup = closeDragElement;
                // call a function whenever the cursor moves:
                document.onmousemove = elementDrag;
            }
    
            function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();
                // calculate the new cursor position:
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;
                // set the element's new position:
                elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
                elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
            }
    
            function closeDragElement() {
                // stop moving when mouse button is released:
                document.onmouseup = null;
                document.onmousemove = null;
                updateCode();
                saveState();
            }
        }
    
        makeElementDraggable(codeArea);
        makeElementDraggable(document.getElementById('layerPanel'));
        makeElementDraggable(document.getElementById('layerPanelHeader'));
    
        function updateCode() {
            const canvas = document.getElementById('canvas');
            const canvasStyle = getComputedStyle(canvas);
            const backgroundColor = canvasStyle.backgroundColor;
    
            const elements = canvas.querySelectorAll('.canvas-text, .canvas-media, .canvas-shape');
            const elementsArray = Array.prototype.map.call(elements, function(element) {
                // Clone the element to avoid modifying the original
                let clone = element.cloneNode(true);
    
                // Adjust image src attribute for media elements
                if (clone.classList.contains('canvas-media')) {
                    let img = clone.querySelector('img');
                    if (img) {
                        let src = img.src;
                        let fileExtension = '';
                        if (src.startsWith('data:image/')) {
                            let match = src.match(/^data:image\/(png|jpeg|jpg);/);
                            let ext = match ? match[1] : 'png';
                            if (ext === 'jpeg') ext = 'jpg'; // use jpg instead of jpeg
                            // Generate 10-digit random number
                            let randomNumber = Math.floor(1000000000 + Math.random() * 9000000000);
                            let fileName = randomNumber + '.' + ext;
                            img.src = fileName;
                        }
                    }
                }
    
                // Remove selected class and inline styles related to selection
                clone.classList.remove('selected');
                clone.style.outline = '';
    
                // Remove resize handles
                if (clone.classList.contains('canvas-text') || clone.classList.contains('canvas-media') || clone.classList.contains('canvas-shape')) {
                    const handles = clone.querySelectorAll('.resize-handle');
                    handles.forEach(handle => handle.remove());
                }
    
                // Include transform styles
                const computedStyle = window.getComputedStyle(element);
                if (computedStyle.transform !== 'none') {
                    clone.style.transform = computedStyle.transform;
                }
    
                // Return the outerHTML of the cloned element
                return clone.outerHTML;
            });
    
            // Include styles in the code
            const styles = document.querySelector('style').outerHTML;
    
            // Build the complete HTML code
            let html = `<!DOCTYPE html>
    
            codeElement.textContent = html;
        }
    
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            const activeElement = document.activeElement;
            if (activeElement && (
                activeElement.tagName === 'INPUT' ||
                activeElement.tagName === 'TEXTAREA' ||
                activeElement.isContentEditable
            )) {
                // Don't interfere with typing in input fields or editable divs
                return;
            }
    
            if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
                e.preventDefault();
                copyElements();
            } else if (e.ctrlKey && (e.key === 'v' || e.key === 'V')) {
                e.preventDefault();
                pasteElements();
            } else if (e.key === 'Delete' || e.key === 'Backspace') {
                e.preventDefault();
                deleteElement();
            } else if (e.ctrlKey && (e.key === 'z' || e.key === 'Z')) {
                e.preventDefault();
                undo();
            } else if (e.ctrlKey && (e.key === 'y' || e.key === 'Y')) {
                e.preventDefault();
                redo();
            }
        });
    
        // Undo/Redo functionality
        function saveState() {
            const canvas = document.getElementById('canvas');
            const state = canvas.innerHTML;
            undoStack.push(state);
            redoStack = []; // Clear redo stack
        }
    
        function undo() {
            if (undoStack.length > 1) {
                redoStack.push(undoStack.pop());
                const lastState = undoStack[undoStack.length - 1];
                const canvas = document.getElementById('canvas');
                canvas.innerHTML = lastState;
                reinitializeCanvasElements();
                updateLayerPanel();
                updateCode();
            }
        }
    
        function redo() {
            if (redoStack.length > 0) {
                const state = redoStack.pop();
                undoStack.push(state);
                const canvas = document.getElementById('canvas');
                canvas.innerHTML = state;
                reinitializeCanvasElements();
                updateLayerPanel();
                updateCode();
            }
        }
    
        function reinitializeCanvasElements() {
            const elements = document.querySelectorAll('.canvas-text, .canvas-media, .canvas-shape');
            elements.forEach(element => {
                makeDraggable(element);
                makeSelectable(element);
                if (element.classList.contains('canvas-text')) {
                    addTextControls(element);
                    addResizeHandles(element);
                } else if (element.classList.contains('canvas-media')) {
                    addMediaControls(element);
                    addResizeHandles(element);
                    const img = element.querySelector('img');
                    if (img) {
                        img.onwheel = (e) => {
                            e.preventDefault();
                            zoomMedia(img, e);
                        };
                    }
                } else if (element.classList.contains('canvas-shape')) {
                    // Since Shape Tools are removed, this block can be left empty or removed
                    addResizeHandles(element);
                }
            });
        }
    
        // Layer Panel
        function updateLayerPanel() {
            const layerList = document.getElementById('layerList');
            layerList.innerHTML = '';
            const canvas = document.getElementById('canvas');
            const elements = Array.from(canvas.children).filter(el => el.classList.contains('canvas-text') || el.classList.contains('canvas-media') || el.classList.contains('canvas-shape'));
            // Reverse to show top layers first
            elements.reverse().forEach((element, index) => {
                const listItem = document.createElement('li');
                listItem.className = 'layer-list-item';
                listItem.setAttribute('data-element-id', element.id);
    
                const layerControls = document.createElement('div');
                layerControls.className = 'layer-controls';
    
                const visibility = document.createElement('span');
                visibility.className = 'layer-visible';
                visibility.innerHTML = `<i class="material-icons">${element.style.display === 'none' ? 'visibility_off' : 'visibility'}</i>`;
                visibility.addEventListener('click', function(e) {
                    e.stopPropagation();
                    toggleVisibility(element.id, visibility);
                });
    
                const lock = document.createElement('span');
                lock.className = 'layer-lock';
                lock.innerHTML = `<i class="material-icons">${element.dataset.locked === 'true' ? 'lock' : 'lock_open'}</i>`;
                lock.addEventListener('click', function(e) {
                    e.stopPropagation();
                    toggleLock(element.id, lock);
                });
    
                layerControls.appendChild(visibility);
                layerControls.appendChild(lock);
    
                const thumbnailContainer = document.createElement('div');
                thumbnailContainer.className = 'layer-thumbnail';
    
                const thumbnail = document.createElement('canvas');
                thumbnail.width = 40;
                thumbnail.height = 40;
                const ctx = thumbnail.getContext('2d');
    
                if (element.classList.contains('canvas-text')) {
                    ctx.font = '14px Arial';
                    ctx.fillStyle = window.getComputedStyle(element.querySelector('div')).color;
                    ctx.fillText(element.querySelector('div').textContent.trim().substring(0, 10), 2, 15);
                } else if (element.classList.contains('canvas-media')) {
                    const img = element.querySelector('img');
                    if (img.complete) {
                        ctx.drawImage(img, 0, 0, 40, 40);
                    } else {
                        img.onload = () => {
                            ctx.drawImage(img, 0, 0, 40, 40);
                        };
                    }
                } else if (element.classList.contains('canvas-shape')) {
                    const svg = element.querySelector('svg');
                    const data = new XMLSerializer().serializeToString(svg);
                    const DOMURL = window.URL || window.webkitURL || window;
                    const img = new Image();
                    const svgBlob = new Blob([data], { type: 'image/svg+xml;charset=utf-8' });
                    const url = DOMURL.createObjectURL(svgBlob);
                    img.onload = function() {
                        ctx.drawImage(img, 0, 0, 40, 40);
                        DOMURL.revokeObjectURL(url);
                    };
                    img.src = url;
                }
    
                thumbnailContainer.appendChild(thumbnail);
    
                const name = document.createElement('div');
                name.className = 'layer-name';
                name.textContent = element.id;
    
                listItem.appendChild(layerControls);
                listItem.appendChild(thumbnailContainer);
                listItem.appendChild(name);
    
                // Add double-click functionality to bring layer forward or send backward
                listItem.addEventListener('dblclick', function(e) {
                    e.stopPropagation();
                    // Toggle layer order: bring to front if not already
                    const currentZ = parseInt(window.getComputedStyle(element).zIndex) || 1;
                    element.style.zIndex = currentZ + 1;
                    updateLayerPanel();
                    updateCode();
                    saveState();
                });
    
                layerList.appendChild(listItem);
            });
            makeLayerListDraggable();
        }
    
        function makeLayerListDraggable() {
            const layerList = document.getElementById('layerList');
            const listItems = layerList.querySelectorAll('.layer-list-item');
            listItems.forEach(item => {
                item.draggable = true;
                item.addEventListener('dragstart', dragStart);
                item.addEventListener('dragover', dragOver);
                item.addEventListener('drop', drop);
            });
        }
    
        let dragSrcEl = null;
    
        function dragStart(e) {
            dragSrcEl = this;
            e.dataTransfer.effectAllowed = 'move';
        }
    
        function dragOver(e) {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
            return false;
        }
    
        function drop(e) {
            e.stopPropagation();
            if (dragSrcEl !== this) {
                const layerList = document.getElementById('layerList');
                const nodes = Array.from(layerList.children);
                const srcIndex = nodes.indexOf(dragSrcEl);
                const destIndex = nodes.indexOf(this);
    
                if (srcIndex > destIndex) {
                    layerList.insertBefore(dragSrcEl, this);
                } else {
                    layerList.insertBefore(dragSrcEl, this.nextSibling);
                }
    
                updateCanvasLayerOrder();
            }
            return false;
        }
    
        function updateCanvasLayerOrder() {
            const layerList = document.getElementById('layerList');
            const layerItems = Array.from(layerList.children);
            const canvas = document.getElementById('canvas');
            const elements = Array.from(canvas.children).filter(el => el.classList.contains('canvas-text') || el.classList.contains('canvas-media') || el.classList.contains('canvas-shape'));
            // Remove all elements
            elements.forEach(el => {
                canvas.removeChild(el);
            });
            // Re-append in new order based on layerList
            layerItems.reverse().forEach(item => { // Reverse to match visual order
                const elementId = item.getAttribute('data-element-id');
                const element = document.getElementById(elementId);
                if (element) {
                    canvas.appendChild(element);
                }
            });
            updateCode();
            saveState();
        }
    
        function toggleVisibility(elementId, visibilityIcon) {
            const element = document.getElementById(elementId);
            if (element.style.display === 'none') {
                element.style.display = '';
                visibilityIcon.innerHTML = '<i class="material-icons">visibility</i>';
            } else {
                element.style.display = 'none';
                visibilityIcon.innerHTML = '<i class="material-icons">visibility_off</i>';
            }
            updateCode();
            saveState();
        }
    
        function toggleLock(elementId, lockIcon) {
            const element = document.getElementById(elementId);
            if (element.dataset.locked === 'true') {
                element.dataset.locked = 'false';
                lockIcon.innerHTML = '<i class="material-icons">lock_open</i>';
                element.style.pointerEvents = 'auto';
            } else {
                element.dataset.locked = 'true';
                lockIcon.innerHTML = '<i class="material-icons">lock</i>';
                element.style.pointerEvents = 'none';
            }
            updateCode();
            saveState();
        }
    
        // Copy/Paste/Delete Functions
        function copyElements() {
            const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
            if (selectedElement) {
                copiedElement = selectedElement.outerHTML;
            }
        }
    
        function pasteElements() {
            const canvas = document.getElementById('canvas');
            if (copiedElement) {
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = copiedElement;
                const element = tempDiv.firstChild;
                // Adjust element ID to make it unique
                element.id = element.id + '-' + Date.now();
    
                // Keep the element at the same position
                element.style.top = parseInt(element.style.top) + 10 + 'px';
                element.style.left = parseInt(element.style.left) + 10 + 'px';
    
                canvas.appendChild(element);
                makeDraggable(element);
                makeSelectable(element);
                if (element.classList.contains('canvas-text')) {
                    addTextControls(element);
                    addResizeHandles(element);
                } else if (element.classList.contains('canvas-media')) {
                    addMediaControls(element);
                    addResizeHandles(element);
                    const img = element.querySelector('img');
                    if (img) {
                        img.onwheel = (e) => {
                            e.preventDefault();
                            zoomMedia(img, e);
                        };
                    }
                } else if (element.classList.contains('canvas-shape')) {
                    // Since Shape Tools are removed, this block can be left empty or removed
                    addResizeHandles(element);
                }
                updateLayerPanel();
                updateCode();
                saveState();
            }
        }
    
        function deleteElement() {
            const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
            if (selectedElement) {
                selectedElement.remove();
                updateLayerPanel();
                updateCode();
                saveState();
            }
        }
    
        // Chat Send Function
        function sendMessage(event) {
            event.preventDefault();
            const input = event.target.querySelector('input');
            const message = input.value.trim();
            if (message === "") return;
            const chatMessages = document.querySelector('.chat-messages');
            const newMessage = document.createElement('div');
            newMessage.className = 'message';
            newMessage.textContent = message;
            chatMessages.appendChild(newMessage);
            input.value = '';
            chatMessages.scrollTop = chatMessages.scrollHeight;
            saveState();
        }
    
        // Undo/Redo functionality is already implemented above
    
    </script>
    
  2. Assistant
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Enhanced Notion-like Canvas with Shapes</title>
        <!-- Include Material Icons for UI Icons -->
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <!-- Include Google Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&family=Source+Sans+Pro:wght@400;700&display=swap" rel="stylesheet">
        <style>
            /* General Styles */
            body, html {
                margin: 0;
                padding: 0;
                height: 100vh;
                overflow: hidden;
                font-family: 'Source Sans Pro', 'Roboto', sans-serif;
                color: #37352f;
                background-color: #f5f5f5;
            }
            .container {
                display: flex;
                height: 100%;
                position: relative;
            }
            .toolbar {
                width: 60px;
                background-color: #fbfbfa;
                border-right: 1px solid #e0e0e0;
                display: flex;
                flex-direction: column;
                align-items: center;
                padding-top: 20px;
                position: relative;
                z-index: 2;
            }
            .tool-button {
                width: 40px;
                height: 40px;
                border: none;
                background-color: transparent;
                cursor: pointer;
                margin-bottom: 10px;
                border-radius: 5px;
                display: flex;
                justify-content: center;
                align-items: center;
                transition: background-color 0.3s ease;
                color: #37352f;
                position: relative;
                font-size: 24px;
            }
            .tool-button:hover {
                background-color: #f1f1ef;
            }
            .tool-button i {
                pointer-events: none;
            }
            .tool-button .tooltip {
                visibility: hidden;
                background-color: #37352f;
                color: #fff;
                text-align: center;
                border-radius: 5px;
                padding: 5px;
                position: absolute;
                left: 45px;
                z-index: 1;
                font-size: 12px;
                white-space: nowrap;
            }
            .tool-button:hover .tooltip {
                visibility: visible;
            }
            .canvas-area {
                flex: 1;
                background-color: #f7f6f3;
                display: flex;
                flex-direction: column;
                align-items: center;
                padding: 20px;
                position: relative;
                overflow: hidden;
            }
            .canvas-controls {
                margin-bottom: 10px;
                display: flex;
                align-items: center;
                position: relative;
                z-index: 1;
                gap: 10px;
            }
            .canvas-controls button,
            .canvas-controls input[type="color"],
            .canvas-controls input[type="range"] {
                background-color: #e0e0e0;
                color: #37352f;
                border: none;
                padding: 8px 12px;
                border-radius: 5px;
                cursor: pointer;
                font-size: 14px;
                transition: background-color 0.3s ease;
                display: flex;
                align-items: center;
            }
            .canvas-controls button:hover,
            .canvas-controls input[type="color"]:hover {
                background-color: #d0d0d0;
            }
            .canvas-controls input[type="range"] {
                width: 100px;
                padding: 0;
                margin: 0;
                cursor: pointer;
                background-color: transparent;
            }
            .canvas-container {
                position: relative;
                flex: 1;
                width: 100%;
                max-width: 1200px;
                background-color: #fff;
                border: 1px solid #e0e0e0;
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                cursor: default;
                overflow: hidden;
            }
            .canvas {
                width: 100%;
                height: 100%;
                position: relative;
                overflow: hidden;
                background-color: #ffffff;
            }
            .grid {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-image: linear-gradient(to right, #f0f0f0 1px, transparent 1px),
                linear-gradient(to bottom, #f0f0f0 1px, transparent 1px);
                background-size: 20px 20px;
                pointer-events: none;
                display: none;
            }
            .chat-area {
                width: 350px;
                background-color: #fbfbfa;
                border-left: 1px solid #e0e0e0;
                display: flex;
                flex-direction: column;
                z-index: 1;
            }
            .chat-header {
                padding: 16px;
                font-size: 16px;
                font-weight: 600;
                border-bottom: 1px solid #e0e0e0;
                background-color: #f7f6f3;
            }
            .chat-messages {
                flex: 1;
                overflow-y: auto;
                padding: 16px;
            }
            .message {
                margin-bottom: 12px;
                padding: 8px 12px;
                background-color: #f1f1ef;
                border-radius: 8px;
                font-size: 14px;
            }
            .chat-input {
                border-top: 1px solid #e0e0e0;
                padding: 16px;
                background-color: #f7f6f3;
            }
            .chat-input form {
                display: flex;
                align-items: center;
            }
            .chat-input input {
                flex: 1;
                padding: 10px 12px;
                border: 1px solid #e0e0e0;
                border-radius: 5px;
                font-size: 14px;
                background-color: #ffffff;
            }
            .chat-input button {
                margin-left: 8px;
                padding: 10px 16px;
                background-color: #e0e0e0;
                color: #37352f;
                border: none;
                border-radius: 5px;
                cursor: pointer;
                font-size: 14px;
                transition: background-color 0.3s ease;
            }
            .chat-input button:hover {
                background-color: #d0d0d0;
            }
            .canvas-text, .canvas-media, .canvas-shape {
                position: absolute;
                cursor: move;
                user-select: none;
                min-width: 50px;
                min-height: 20px;
                z-index: 1;
            }
            .canvas-text {
                background-color: rgba(255, 255, 255, 0.8);
                border: 1px solid #ccc;
                border-radius: 4px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                overflow: hidden;
            }
            .canvas-text div {
                padding: 5px;
                outline: none;
                width: 100%;
                height: 100%;
                font-family: 'Roboto', sans-serif;
                font-size: 16px;
                color: #333;
                text-align: left;
                cursor: text;
            }
            .canvas-media img {
                max-width: 100%;
                max-height: 100%;
                display: block;
            }
            .canvas-media {
                padding: 0;
                overflow: hidden;
            }
            /* Shape styles */
            .canvas-shape {
                overflow: visible; /* Allow stroke to be visible */
            }
            .canvas-shape svg {
                overflow: visible; /* Ensure stroke is visible */
                width: 100%;
                height: 100%;
            }
            /* Gradient Tool */
            .gradient-tool,
            .gradient-stroke-tool {
                position: absolute;
                top: 60px;
                left: 70px;
                background-color: #ffffff;
                border: 1px solid #e0e0e0;
                border-radius: 5px;
                padding: 10px;
                display: none;
                flex-direction: column;
                gap: 10px;
                z-index: 1000;
            }
            .gradient-option {
                display: flex;
                align-items: center;
                gap: 5px;
            }
            .gradient-preview {
                width: 30px;
                height: 30px;
                border: 1px solid #e0e0e0;
                border-radius: 3px;
            }
            /* Resize Handles */
            .resize-handle {
                position: absolute;
                width: 10px;
                height: 10px;
                background-color: #fff;
                border: 1px solid #000;
                z-index: 10;
                cursor: pointer;
            }
            .resize-handle.top-left {
                left: -5px;
                top: -5px;
                cursor: nwse-resize;
            }
            .resize-handle.top-right {
                right: -5px;
                top: -5px;
                cursor: nesw-resize;
            }
            .resize-handle.bottom-left {
                left: -5px;
                bottom: -5px;
                cursor: nesw-resize;
            }
            .resize-handle.bottom-right {
                right: -5px;
                bottom: -5px;
                cursor: nwse-resize;
            }
            /* Layers Panel Styles */
            .layer-panel {
                position: absolute;
                top: 0;
                right: 0;
                width: 250px;
                height: 100%;
                background-color: #fbfbfa;
                color: #37352f;
                border-left: 1px solid #e0e0e0;
                display: flex;
                flex-direction: column;
                z-index: 1;
                overflow: hidden;
            }
            .layer-panel-header {
                padding: 10px;
                font-size: 16px;
                font-weight: bold;
                border-bottom: 1px solid #e0e0e0;
                background-color: #f7f6f3;
                cursor: move;
            }
            .layer-list {
                flex: 1;
                overflow-y: auto;
                padding: 10px;
            }
            .layer-list-item {
                display: flex;
                align-items: center;
                padding: 5px;
                margin-bottom: 5px;
                border: 1px solid transparent;
                cursor: pointer;
                background-color: #fbfbfa;
                border-radius: 3px;
            }
            .layer-list-item:hover {
                background-color: #f1f1ef;
                border-color: #e0e0e0;
            }
            .layer-thumbnail canvas {
                width: 40px;
                height: 40px;
                background-color: #fff;
                border: 1px solid #ccc;
            }
            .layer-name {
                flex: 1;
                margin-left: 10px;
                font-size: 14px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
            .layer-controls {
                display: flex;
                align-items: center;
                gap: 5px;
            }
            .layer-controls .material-icons {
                cursor: pointer;
                color: #999;
                font-size: 20px;
            }
            .layer-controls .material-icons:hover {
                color: #37352f;
            }
            /* Code Area */
            .code-area {
                position: absolute;
                bottom: 0;
                left: 0;
                right: 0;
                height: 200px;
                background-color: #1e1e1e;
                color: #dcdcdc;
                display: none;
                overflow: auto;
                padding: 10px;
                font-family: 'Courier New', Courier, monospace;
                font-size: 14px;
                z-index: 1000;
                resize: vertical;
                border-top: 1px solid #444;
            }
            .code-area pre {
                margin: 0;
            }
            /* Toggle Code Button */
            .toggle-code {
                position: absolute;
                bottom: 10px;
                right: 10px;
                background-color: #e0e0e0;
                border: none;
                padding: 6px 10px;
                border-radius: 5px;
                cursor: pointer;
                font-size: 14px;
                color: #37352f;
                transition: background-color 0.3s ease;
                z-index: 2;
            }
            .toggle-code:hover {
                background-color: #d0d0d0;
            }
            /* Font Controls Styling */
            .text-controls input[type="number"],
            .text-controls select {
                border: 1px solid #ccc;
                background-color: #f9f9f9;
            }
            .text-controls button {
                background-color: #f9f9f9;
                border: 1px solid #ccc;
            }
            .text-controls button.active {
                background-color: #e0e0e0;
            }
            .text-controls {
                font-family: 'Source Sans Pro', sans-serif;
                font-size: 13px;
            }
            /* Prevent toolboxes from overlapping gradient tools */
            #text-controls-wrapper,
            #media-controls-wrapper,
            #shape-controls-wrapper {
                position: absolute;
                top: 0;
                left: 0;
                z-index: 1001;
            }
            /* Shape Toolbox */
            .shape-tool {
                position: absolute;
                top: 60px;
                left: 70px;
                background-color: #ffffff;
                border: 1px solid #e0e0e0;
                border-radius: 5px;
                padding: 10px;
                display: none;
                flex-direction: row;
                gap: 10px;
                z-index: 1000;
            }
            .shape-tool button {
                background-color: transparent;
                border: none;
                cursor: pointer;
                padding: 5px;
                border-radius: 3px;
            }
            .shape-tool button:hover {
                background-color: #f1f1ef;
            }
            .shape-tool svg {
                width: 24px;
                height: 24px;
            }
            /* Responsive Adjustment for Toolboxes */
            @media (max-width: 1200px) {
                .layer-panel {
                    width: 200px;
                }
                .chat-area {
                    width: 300px;
                }
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="toolbar">
                <button class="tool-button" onclick="addText()" title="Add Text">
                    <i class="material-icons">text_fields</i>
                    <span class="tooltip">Add Text</span>
                </button>
                <button class="tool-button" onclick="addMedia()" title="Add Media">
                    <i class="material-icons">image</i>
                    <span class="tooltip">Add Media</span>
                </button>
                <button class="tool-button" onclick="openShapeTool()" title="Add Shape">
                    <i class="material-icons">category</i>
                    <span class="tooltip">Add Shape</span>
                </button>
                <button class="tool-button" onclick="copyElements()" title="Copy">
                    <i class="material-icons">content_copy</i>
                    <span class="tooltip">Copy (Ctrl+C)</span>
                </button>
                <button class="tool-button" onclick="pasteElements()" title="Paste">
                    <i class="material-icons">content_paste</i>
                    <span class="tooltip">Paste (Ctrl+V)</span>
                </button>
                <button class="tool-button" onclick="deleteElement()" title="Delete">
                    <i class="material-icons">delete</i>
                    <span class="tooltip">Delete (Delete)</span>
                </button>
                <button class="tool-button" onclick="undo()" title="Undo">
                    <i class="material-icons">undo</i>
                    <span class="tooltip">Undo (Ctrl+Z)</span>
                </button>
                <button class="tool-button" onclick="redo()" title="Redo">
                    <i class="material-icons">redo</i>
                    <span class="tooltip">Redo (Ctrl+Y)</span>
                </button>
            </div>
            <div class="canvas-area">
                <div class="canvas-controls">
                    <button class="toggle-grid" onclick="toggleGrid()" title="Toggle Grid">
                        <i class="material-icons">grid_on</i>
                    </button>
                    <input type="color" id="canvasColorPicker" oninput="changeCanvasColor(this.value)" title="Canvas Color">
                    <!-- Opacity Control -->
                    <input type="range" min="0" max="100" value="100" id="globalOpacity" oninput="changeGlobalOpacity(this.value)" title="Opacity">
                    <button class="toggle-code" onclick="toggleCode()" title="Toggle Code">
                        <i class="material-icons">code</i>
                    </button>
                </div>
                <div class="canvas-container" id="canvasContainer">
                    <div class="canvas" id="canvas">
                        <div class="grid" id="grid"></div>
                    </div>
                    <div class="canvas-outline" id="canvasOutline"></div>
                </div>
                <div class="layer-panel" id="layerPanel">
                    <div class="layer-panel-header" id="layerPanelHeader">Layers</div>
                    <ul class="layer-list" id="layerList"></ul>
                </div>
            </div>
            <!-- Shape Toolbox -->
            <div id="shape-tool" class="shape-tool">
                <button onclick="addShape('rectangle')" title="Rectangle">
                    <svg><rect width="20" height="20" x="2" y="2" fill="none" stroke="#000" stroke-width="2"/></svg>
                </button>
                <button onclick="addShape('ellipse')" title="Ellipse">
                    <svg><ellipse cx="12" cy="12" rx="10" ry="8" fill="none" stroke="#000" stroke-width="2"/></svg>
                </button>
                <button onclick="addShape('triangle')" title="Triangle">
                    <svg><polygon points="12,2 22,22 2,22" fill="none" stroke="#000" stroke-width="2"/></svg>
                </button>
                <button onclick="addShape('line')" title="Line">
                    <svg><line x1="2" y1="22" x2="22" y2="2" stroke="#000" stroke-width="2"/></svg>
                </button>
                <!-- Add more shapes as needed -->
            </div>
            <div class="code-area" id="codeArea">
                <pre id="code"></pre>
            </div>
            <div class="chat-area">
                <div class="chat-header">
                    Chat
                </div>
                <div class="chat-messages">
                    <div class="message">Hello! How can I help you with your design?</div>
                    <div class="message">You can use the canvas on the left to create your poster.</div>
                </div>
                <div class="chat-input">
                    <form onsubmit="sendMessage(event)">
                        <input type="text" placeholder="Type a message..." required>
                        <button type="submit">Send</button>
                    </form>
                </div>
            </div>
            <div id="text-controls-wrapper"></div>
            <div id="media-controls-wrapper"></div>
            <div id="shape-controls-wrapper"></div>
        </div>
    
        <script>
            let copiedElement = null;
            let codeArea = document.getElementById('codeArea');
            let codeElement = document.getElementById('code');
            let undoStack = [];
            let redoStack = [];
    
            function toggleGrid() {
                const grid = document.getElementById('grid');
                grid.style.display = grid.style.display === 'none' ? 'block' : 'none';
                saveState();
            }
    
            function changeCanvasColor(color) {
                const canvas = document.getElementById('canvas');
                canvas.style.backgroundColor = color;
                updateCode(); // Update code when background color changes
                saveState();
            }
    
            function addText() {
                const canvas = document.getElementById('canvas');
                const text = document.createElement('div');
                text.className = 'canvas-text';
                text.id = 'text-' + Date.now();
                const textContent = document.createElement('div');
                textContent.contentEditable = true;
                textContent.textContent = 'Double click to edit';
                textContent.setAttribute('tabindex', '0'); // Make it focusable
                text.appendChild(textContent);
                text.style.left = '50px';
                text.style.top = '50px';
                text.style.width = '200px';
                text.style.height = '50px';
                textContent.style.fontSize = '16px';
                textContent.style.color = '#000000';
                text.style.opacity = 1;
    
                canvas.appendChild(text);
                makeDraggable(text);
                makeSelectable(text);
                addTextControls(text);
                text.addEventListener('dblclick', function() {
                    textContent.focus();
                    document.execCommand('selectAll', false, null);
                });
                textContent.addEventListener('input', function() {
                    updateLayerPanel();
                    updateCode();
                    saveState();
                });
                updateLayerPanel();
                updateCode();
                saveState();
            }
    
            function addMedia() {
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = 'image/*';
                input.onchange = function(event) {
                    const file = event.target.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            const canvas = document.getElementById('canvas');
                            const media = document.createElement('div');
                            media.className = 'canvas-media';
                            media.id = 'media-' + Date.now();
                            const img = document.createElement('img');
                            img.src = e.target.result;
                            img.dataset.scale = 1;
                            img.style.transformOrigin = 'center center';
                            img.onwheel = (e) => {
                                e.preventDefault();
                                zoomMedia(img, e);
                            };
                            img.ondragstart = () => false;
                            media.appendChild(img);
    
                            img.onload = function() {
                                let scale = 1;
                                if (img.naturalWidth > 400 || img.naturalHeight > 300) {
                                    // Scale down if image is too big
                                    scale = Math.min(400 / img.naturalWidth, 300 / img.naturalHeight);
                                }
                                media.style.width = img.naturalWidth * scale + 'px';
                                media.style.height = img.naturalHeight * scale + 'px';
                                media.style.left = '50px';
                                media.style.top = '50px';
                                media.style.opacity = 1;
                                img.style.width = '100%';
                                img.style.height = '100%';
                            };
    
                            canvas.appendChild(media);
                            makeDraggable(media);
                            makeSelectable(media);
                            addMediaControls(media);
                            updateLayerPanel();
                            updateCode();
                            saveState();
                        };
                        reader.readAsDataURL(file);
                    }
                };
                input.click();
            }
    
            function openShapeTool() {
                const shapeTool = document.getElementById('shape-tool');
                shapeTool.style.display = shapeTool.style.display === 'flex' ? 'none' : 'flex';
            }
    
            function addShape(shapeType) {
                const canvas = document.getElementById('canvas');
                const shapeElement = document.createElement('div');
                shapeElement.className = 'canvas-shape';
                shapeElement.id = 'shape-' + Date.now();
                shapeElement.style.left = '100px';
                shapeElement.style.top = '100px';
                shapeElement.style.width = '100px';
                shapeElement.style.height = '100px';
                shapeElement.style.opacity = 1;
    
                let svgNS = "http://www.w3.org/2000/svg";
                let svg = document.createElementNS(svgNS, 'svg');
                svg.setAttribute('width', '100%');
                svg.setAttribute('height', '100%');
    
                let shape;
    
                if (shapeType === 'rectangle') {
                    shape = document.createElementNS(svgNS, 'rect');
                    shape.setAttribute('x', '0');
                    shape.setAttribute('y', '0');
                    shape.setAttribute('width', '100%');
                    shape.setAttribute('height', '100%');
                } else if (shapeType === 'ellipse') {
                    shape = document.createElementNS(svgNS, 'ellipse');
                    shape.setAttribute('cx', '50%');
                    shape.setAttribute('cy', '50%');
                    shape.setAttribute('rx', '50%');
                    shape.setAttribute('ry', '50%');
                } else if (shapeType === 'triangle') {
                    shape = document.createElementNS(svgNS, 'polygon');
                    shape.setAttribute('points', '50,0 100,100 0,100');
                } else if (shapeType === 'line') {
                    shape = document.createElementNS(svgNS, 'line');
                    shape.setAttribute('x1', '0');
                    shape.setAttribute('y1', '100%');
                    shape.setAttribute('x2', '100%');
                    shape.setAttribute('y2', '0');
                }
                // Add more shapes as needed
    
                shape.setAttribute('fill', 'none');
                shape.setAttribute('stroke', '#000000');
                shape.setAttribute('stroke-width', '2');
    
                svg.appendChild(shape);
                shapeElement.appendChild(svg);
                canvas.appendChild(shapeElement);
    
                makeDraggable(shapeElement);
                makeSelectable(shapeElement);
                addResizeHandles(shapeElement);
                // Close the shape toolbox
                const shapeTool = document.getElementById('shape-tool');
                shapeTool.style.display = 'none';
    
                updateLayerPanel();
                updateCode();
                saveState();
            }
    
            function makeDraggable(element) {
                let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
                const canvas = document.getElementById('canvas');
                let isResizing = false;
                let currentHandle = null;
    
                if (element.classList.contains('canvas-text') || element.classList.contains('canvas-media') || element.classList.contains('canvas-shape')) {
                    addResizeHandles(element);
                }
    
                element.onmousedown = dragMouseDown;
    
                function dragMouseDown(e) {
                    if (element.dataset.locked === 'true') {
                        return;
                    }
                    if (e.target.classList.contains('resize-handle')) {
                        isResizing = true;
                        currentHandle = e.target;
                        e.stopPropagation();
                        document.onmouseup = closeDragElement;
                        document.onmousemove = elementResize;
                    } else {
                        e = e || window.event;
                        e.preventDefault();
                        e.stopPropagation();
                        pos3 = e.clientX;
                        pos4 = e.clientY;
                        document.onmouseup = closeDragElement;
                        document.onmousemove = elementDrag;
                        clearSelection();
                        element.classList.add('selected');
                        showElementControls(element);
                    }
                }
    
                function elementDrag(e) {
                    e = e || window.event;
                    e.preventDefault();
                    pos1 = pos3 - e.clientX;
                    pos2 = pos4 - e.clientY;
                    pos3 = e.clientX;
                    pos4 = e.clientY;
    
                    let newTop = element.offsetTop - pos2;
                    let newLeft = element.offsetLeft - pos1;
    
                    // Constraints so that the element does not leave the canvas
                    let maxTop = canvas.offsetHeight - element.offsetHeight;
                    let maxLeft = canvas.offsetWidth - element.offsetWidth;
    
                    if (newTop < 0) newTop = 0;
                    if (newLeft < 0) newLeft = 0;
                    if (newTop > maxTop) newTop = maxTop;
                    if (newLeft > maxLeft) newLeft = maxLeft;
    
                    element.style.top = newTop + "px";
                    element.style.left = newLeft + "px";
    
                    // Update controls position if visible
                    if (element.classList.contains('selected')) {
                        showElementControls(element);
                    }
                }
    
                function elementResize(e) {
                    e.preventDefault();
                    const rect = element.getBoundingClientRect();
                    let width, height;
                    if (currentHandle.classList.contains('bottom-right')) {
                        width = e.clientX - rect.left;
                        height = e.clientY - rect.top;
                    } else if (currentHandle.classList.contains('bottom-left')) {
                        width = rect.right - e.clientX;
                        height = e.clientY - rect.top;
                        element.style.left = element.offsetLeft + (e.clientX - rect.left) + 'px';
                    } else if (currentHandle.classList.contains('top-right')) {
                        width = e.clientX - rect.left;
                        height = rect.bottom - e.clientY;
                        element.style.top = element.offsetTop + (e.clientY - rect.top) + 'px';
                    } else if (currentHandle.classList.contains('top-left')) {
                        width = rect.right - e.clientX;
                        height = rect.bottom - e.clientY;
                        element.style.left = element.offsetLeft + (e.clientX - rect.left) + 'px';
                        element.style.top = element.offsetTop + (e.clientY - rect.top) + 'px';
                    }
                    if (width > 20 && height > 20) {
                        element.style.width = width + 'px';
                        element.style.height = height + 'px';
    
                        // For images, adjust the img size
                        if (element.classList.contains('canvas-media')) {
                            const img = element.querySelector('img');
                            img.style.width = '100%';
                            img.style.height = '100%';
                        }
    
                        // For shapes, adjust SVG size
                        if (element.classList.contains('canvas-shape')) {
                            const svg = element.querySelector('svg');
                            svg.setAttribute('width', '100%');
                            svg.setAttribute('height', '100%');
                        }
                    }
                    // Update controls position if visible
                    if (element.classList.contains('selected')) {
                        showElementControls(element);
                    }
                    updateCode();
                    saveState();
                }
    
                function closeDragElement() {
                    document.onmouseup = null;
                    document.onmousemove = null;
                    isResizing = false;
                    currentHandle = null;
                    updateCode(); // Update code after dragging completes
                    saveState();
                }
            }
    
            function addResizeHandles(element) {
                const handles = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
                handles.forEach(handle => {
                    const div = document.createElement('div');
                    div.className = 'resize-handle ' + handle;
                    element.appendChild(div);
                });
            }
    
            function makeSelectable(element) {
                element.addEventListener('click', function(e) {
                    if (element.dataset.locked === 'true') {
                        return;
                    }
                    e.stopPropagation(); // prevent event bubbling
                    clearSelection(); // Deselect others
                    element.classList.add('selected'); // apply selected class
                    showElementControls(element);
                    // Update the global opacity slider
                    const globalOpacity = document.getElementById('globalOpacity');
                    globalOpacity.value = element.style.opacity * 100;
                });
            }
    
            function clearSelection() {
                document.querySelectorAll('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected').forEach(el => {
                    el.classList.remove('selected');
                });
                hideAllControls();
            }
    
            function showElementControls(element) {
                hideAllControls();
                if (element.classList.contains('canvas-text')) {
                    const controls = document.querySelector(`.text-controls[data-text-id="${element.id}"]`);
                    if (controls) {
                        controls.style.display = 'flex';
                        const canvas = document.getElementById('canvas');
                        const canvasRect = canvas.getBoundingClientRect();
                        controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
                        controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
                    }
                } else if (element.classList.contains('canvas-media')) {
                    const controls = document.querySelector(`.media-controls[data-media-id="${element.id}"]`);
                    if (controls) {
                        controls.style.display = 'flex';
                        const canvas = document.getElementById('canvas');
                        const canvasRect = canvas.getBoundingStyle = 'flex';
                        const canvas = document.getElementById('canvas');
                        const canvasRect = canvas.getBoundingClientRect();
                        controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
                        controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
                    }
                } else if (element.classList.contains('canvas-shape')) {
                    const controls = document.querySelector(`.shape-controls[data-shape-id="${element.id}"]`);
                    if (controls) {
                        controls.style.display = 'flex';
                        const canvas = document.getElementById('canvas');
                        const canvasRect = canvas.getBoundingClientRect();
                        controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
                        controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
                    }
                }
                // Show canvas outline
                const canvasOutline = document.getElementById('canvasOutline');
                canvasOutline.style.display = 'block';
                canvasOutline.style.top = `${element.offsetTop - 10}px`;
                canvasOutline.style.left = `${element.offsetLeft - 10}px`;
                canvasOutline.style.width = `${element.offsetWidth + 20}px`;
                canvasOutline.style.height = `${element.offsetHeight + 20}px`;
            }
    
            function hideAllControls() {
                document.querySelectorAll('.text-controls, .media-controls, .shape-controls').forEach(control => {
                    control.style.display = 'none';
                });
                // Hide canvas outline
                const canvasOutline = document.getElementById('canvasOutline');
                canvasOutline.style.display = 'none';
            }
    
            function addTextControls(textElement) {
                const wrapper = document.getElementById('text-controls-wrapper');
                const controls = document.createElement('div');
                controls.className = 'text-controls';
                controls.setAttribute('data-text-id', textElement.id);
                controls.style.display = 'none';
                controls.innerHTML = `
                    <button onclick="toggleBold(this, '${textElement.id}')" title="Bold"><i class="material-icons">format_bold</i></button>
                    <button onclick="toggleItalic(this, '${textElement.id}')" title="Italic"><i class="material-icons">format_italic</i></button>
                    <button onclick="toggleUnderline(this, '${textElement.id}')" title="Underline"><i class="material-icons">format_underline</i></button>
                    <input type="color" onchange="changeTextColor(this.value, '${textElement.id}')" title="Text Color">
                    <input type="number" min="1" max="100" value="16" onchange="changeFontSize(this.value, '${textElement.id}')" title="Font Size">
                    <select onchange="changeFontFamily(this.value, '${textElement.id}')" title="Font Family">
                        <option value="Roboto">Roboto</option>
                        <option value="'Source Sans Pro'">Source Sans Pro</option>
                        <option value="Arial">Arial</option>
                        <option value="Helvetica">Helvetica</option>
                        <option value="'Times New Roman'">Times New Roman</option>
                        <option value="'Courier New'">Courier New</option>
                        <option value="Verdana">Verdana</option>
                        <option value="Georgia">Georgia</option>
                        <option value="Palatino">Palatino</option>
                        <option value="Garamond">Garamond</option>
                        <option value="Bookman">Bookman</option>
                        <option value="'Comic Sans MS'">Comic Sans MS</option>
                        <option value="'Trebuchet MS'">Trebuchet MS</option>
                        <option value="'Arial Black'">Arial Black</option>
                    </select>
                `;
    
                wrapper.appendChild(controls);
            }
    
            function addMediaControls(mediaElement) {
                const wrapper = document.getElementById('media-controls-wrapper');
                const controls = document.createElement('div');
                controls.className = 'media-controls';
                controls.setAttribute('data-media-id', mediaElement.id);
                controls.style.display = 'none';
                controls.innerHTML = `
                    <button onclick="removeMedia('${mediaElement.id}')" title="Remove"><i class="material-icons">delete</i></button>
                    <button onclick="resetZoom('${mediaElement.id}')" title="Reset Zoom"><i class="material-icons">zoom_out_map</i></button>
                `;
    
                wrapper.appendChild(controls);
            }
    
            // Text Control Functions
            function changeTextColor(color, textId) {
                const textElement = document.getElementById(textId);
                const textContent = textElement.querySelector('div');
                textContent.style.color = color;
                updateCode();
                saveState();
            }
    
            function changeFontSize(size, textId) {
                const textElement = document.getElementById(textId);
                const textContent = textElement.querySelector('div');
                textContent.style.fontSize = size + 'px';
                updateCode();
                saveState();
            }
    
            function changeFontFamily(family, textId) {
                const textElement = document.getElementById(textId);
                const textContent = textElement.querySelector('div');
                textContent.style.fontFamily = family;
                updateCode();
                saveState();
            }
    
            function toggleBold(button, textId) {
                const textElement = document.getElementById(textId);
                const textContent = textElement.querySelector('div');
                const isBold = textContent.style.fontWeight === 'bold';
                textContent.style.fontWeight = isBold ? 'normal' : 'bold';
                button.classList.toggle('active', !isBold);
                updateCode();
                saveState();
            }
    
            function toggleItalic(button, textId) {
                const textElement = document.getElementById(textId);
                const textContent = textElement.querySelector('div');
                const isItalic = textContent.style.fontStyle === 'italic';
                textContent.style.fontStyle = isItalic ? 'normal' : 'italic';
                button.classList.toggle('active', !isItalic);
                updateCode();
                saveState();
            }
    
            function toggleUnderline(button, textId) {
                const textElement = document.getElementById(textId);
                const textContent = textElement.querySelector('div');
                const isUnderline = textContent.style.textDecoration === 'underline';
                textContent.style.textDecoration = isUnderline ? 'none' : 'underline';
                button.classList.toggle('active', !isUnderline);
                updateCode();
                saveState();
            }
    
            // Media Control Functions
            function removeMedia(mediaId) {
                const mediaElement = document.getElementById(mediaId);
                mediaElement.remove();
                const mediaControls = document.querySelector(`.media-controls[data-media-id="${mediaId}"]`);
                if (mediaControls) {
                    mediaControls.style.display = 'none';
                }
                updateLayerPanel();
                updateCode();
                saveState();
            }
    
            function resetZoom(mediaId) {
                const mediaElement = document.getElementById(mediaId);
                const img = mediaElement.querySelector('img');
                img.style.transform = 'scale(1)';
                img.dataset.scale = 1;
                // Adjust the container size
                mediaElement.style.width = img.naturalWidth + 'px';
                mediaElement.style.height = img.naturalHeight + 'px';
                updateCode();
                saveState();
            }
    
            function zoomMedia(img, e) {
                e.preventDefault();
    
                const delta = e.deltaY;
    
                const zoomFactor = 0.05; // Smaller zoom factor for smoother zooming
    
                // Get current scale
                let scale = img.dataset.scale ? parseFloat(img.dataset.scale) : 1;
                // Update scale
                scale *= delta > 0 ? (1 - zoomFactor) : (1 + zoomFactor);
                // Limit scale
                scale = Math.min(Math.max(0.1, scale), 10);
                img.dataset.scale = scale;
    
                // Apply scale transform
                img.style.transform = `scale(${scale})`;
    
                // Adjust the container size based on the scaled image size
                const mediaElement = img.parentElement;
                mediaElement.style.width = img.naturalWidth * scale + 'px';
                mediaElement.style.height = img.naturalHeight * scale + 'px';
    
                updateCode();
                saveState();
            }
    
            // Global Opacity Control
            function changeGlobalOpacity(value) {
                const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
                if (selectedElement) {
                    selectedElement.style.opacity = value / 100;
                    updateCode();
                    saveState();
                }
            }
    
            // Initial save state
            saveState();
    
            // Handle click outside to clear selection
            document.getElementById('canvas').addEventListener('click', function(e) {
                if (e.target === this) {
                    clearSelection();
                }
            });
    
            // Code Editor Toggles and Updates
            function toggleCode() {
                updateCode();
                codeArea.style.display = codeArea.style.display === 'block' ? 'none' : 'block';
                saveState();
            }
    
            function makeElementDraggable(elmnt) {
                var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
                elmnt.onmousedown = dragMouseDown;
    
                function dragMouseDown(e) {
                    e = e || window.event;
                    e.preventDefault();
                    // get the mouse cursor position at startup:
                    pos3 = e.clientX;
                    pos4 = e.clientY;
                    document.onmouseup = closeDragElement;
                    // call a function whenever the cursor moves:
                    document.onmousemove = elementDrag;
                }
    
                function elementDrag(e) {
                    e = e || window.event;
                    e.preventDefault();
                    // calculate the new cursor position:
                    pos1 = pos3 - e.clientX;
                    pos2 = pos4 - e.clientY;
                    pos3 = e.clientX;
                    pos4 = e.clientY;
                    // set the element's new position:
                    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
                    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
                }
    
                function closeDragElement() {
                    // stop moving when mouse button is released:
                    document.onmouseup = null;
                    document.onmousemove = null;
                    updateCode();
                    saveState();
                }
            }
    
            makeElementDraggable(codeArea);
            makeElementDraggable(document.getElementById('layerPanel'));
            makeElementDraggable(document.getElementById('layerPanelHeader'));
    
            function updateCode() {
                const canvas = document.getElementById('canvas');
                const canvasStyle = getComputedStyle(canvas);
                const backgroundColor = canvasStyle.backgroundColor;
    
                const elements = canvas.querySelectorAll('.canvas-text, .canvas-media, .canvas-shape');
                const elementsArray = Array.prototype.map.call(elements, function(element) {
                    // Clone the element to avoid modifying the original
                    let clone = element.cloneNode(true);
    
                    // Adjust image src attribute for media elements
                    if (clone.classList.contains('canvas-media')) {
                        let img = clone.querySelector('img');
                        if (img) {
                            let src = img.src;
                            let fileExtension = '';
                            if (src.startsWith('data:image/')) {
                                let match = src.match(/^data:image\/(png|jpeg|jpg);/);
                                let ext = match ? match[1] : 'png';
                                if (ext === 'jpeg') ext = 'jpg'; // use jpg instead of jpeg
                                // Generate 10-digit random number
                                let randomNumber = Math.floor(1000000000 + Math.random() * 9000000000);
                                let fileName = randomNumber + '.' + ext;
                                img.src = fileName;
                            }
                        }
                    }
    
                    // Remove selected class and inline styles related to selection
                    clone.classList.remove('selected');
                    clone.style.outline = '';
    
                    // Remove resize handles
                    if (clone.classList.contains('canvas-text') || clone.classList.contains('canvas-media') || clone.classList.contains('canvas-shape')) {
                        const handles = clone.querySelectorAll('.resize-handle');
                        handles.forEach(handle => handle.remove());
                    }
    
                    // Include transform styles
                    const computedStyle = window.getComputedStyle(element);
                    if (computedStyle.transform !== 'none') {
                        clone.style.transform = computedStyle.transform;
                    }
    
                    // Return the outerHTML of the cloned element
                    return clone.outerHTML;
                });
    
                // Include styles in the code
                const styles = document.querySelector('style').outerHTML;
    
                // Build the complete HTML code
                let html = `<!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Canvas Export</title>${styles}
    </head>
    <body>
    <div id="canvas" style="background-color:${backgroundColor}; position: relative; width:${canvas.offsetWidth}px; height:${canvas.offsetHeight}px;">${elementsArray.join('\n')}
    </div>
    </body>
    </html>`;
    
                codeElement.textContent = html;
            }
    
            // Keyboard shortcuts
            document.addEventListener('keydown', function(e) {
                const activeElement = document.activeElement;
                if (activeElement && (
                    activeElement.tagName === 'INPUT' ||
                    activeElement.tagName === 'TEXTAREA' ||
                    activeElement.isContentEditable
                )) {
                    // Don't interfere with typing in input fields or editable divs
                    return;
                }
    
                if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
                    e.preventDefault();
                    copyElements();
                } else if (e.ctrlKey && (e.key === 'v' || e.key === 'V')) {
                    e.preventDefault();
                    pasteElements();
                } else if (e.key === 'Delete' || e.key === 'Backspace') {
                    e.preventDefault();
                    deleteElement();
                } else if (e.ctrlKey && (e.key === 'z' || e.key === 'Z')) {
                    e.preventDefault();
                    undo();
                } else if (e.ctrlKey && (e.key === 'y' || e.key === 'Y')) {
                    e.preventDefault();
                    redo();
                }
            });
    
            // Undo/Redo functionality
            function saveState() {
                const canvas = document.getElementById('canvas');
                const state = canvas.innerHTML;
                undoStack.push(state);
                redoStack = []; // Clear redo stack
            }
    
            function undo() {
                if (undoStack.length > 1) {
                    redoStack.push(undoStack.pop());
                    const lastState = undoStack[undoStack.length - 1];
                    const canvas = document.getElementById('canvas');
                    canvas.innerHTML = lastState;
                    reinitializeCanvasElements();
                    updateLayerPanel();
                    updateCode();
                }
            }
    
            function redo() {
                if (redoStack.length > 0) {
                    const state = redoStack.pop();
                    undoStack.push(state);
                    const canvas = document.getElementById('canvas');
                    canvas.innerHTML = state;
                    reinitializeCanvasElements();
                    updateLayerPanel();
                    updateCode();
                }
            }
    
            function reinitializeCanvasElements() {
                const elements = document.querySelectorAll('.canvas-text, .canvas-media, .canvas-shape');
                elements.forEach(element => {
                    makeDraggable(element);
                    makeSelectable(element);
                    if (element.classList.contains('canvas-text')) {
                        addTextControls(element);
                        addResizeHandles(element);
                    } else if (element.classList.contains('canvas-media')) {
                        addMediaControls(element);
                        addResizeHandles(element);
                        const img = element.querySelector('img');
                        if (img) {
                            img.onwheel = (e) => {
                                e.preventDefault();
                                zoomMedia(img, e);
                            };
                        }
                    } else if (element.classList.contains('canvas-shape')) {
                        addResizeHandles(element);
                        // Optionally, add shape controls
                    }
                });
            }
    
            // Layer Panel
            function updateLayerPanel() {
                const layerList = document.getElementById('layerList');
                layerList.innerHTML = '';
                const canvas = document.getElementById('canvas');
                const elements = Array.from(canvas.children).filter(el => el.classList.contains('canvas-text') || el.classList.contains('canvas-media') || el.classList.contains('canvas-shape'));
                // Reverse to show top layers first
                elements.reverse().forEach((element, index) => {
                    const listItem = document.createElement('li');
                    listItem.className = 'layer-list-item';
                    listItem.setAttribute('data-element-id', element.id);
    
                    const layerControls = document.createElement('div');
                    layerControls.className = 'layer-controls';
    
                    const visibility = document.createElement('span');
                    visibility.className = 'layer-visible';
                    visibility.innerHTML = `<i class="material-icons">${element.style.display === 'none' ? 'visibility_off' : 'visibility'}</i>`;
                    visibility.addEventListener('click', function(e) {
                        e.stopPropagation();
                        toggleVisibility(element.id, visibility);
                    });
    
                    const lock = document.createElement('span');
                    lock.className = 'layer-lock';
                    lock.innerHTML = `<i class="material-icons">${element.dataset.locked === 'true' ? 'lock' : 'lock_open'}</i>`;
                    lock.addEventListener('click', function(e) {
                        e.stopPropagation();
                        toggleLock(element.id, lock);
                    });
    
                    layerControls.appendChild(visibility);
                    layerControls.appendChild(lock);
    
                    const thumbnailContainer = document.createElement('div');
                    thumbnailContainer.className = 'layer-thumbnail';
    
                    const thumbnail = document.createElement('canvas');
                    thumbnail.width = 40;
                    thumbnail.height = 40;
                    const ctx = thumbnail.getContext('2d');
    
                    if (element.classList.contains('canvas-text')) {
                        ctx.font = '14px Arial';
                        ctx.fillStyle = window.getComputedStyle(element.querySelector('div')).color;
                        ctx.fillText(element.querySelector('div').textContent.trim().substring(0, 10), 2, 15);
                    } else if (element.classList.contains('canvas-media')) {
                        const img = element.querySelector('img');
                        if (img.complete) {
                            ctx.drawImage(img, 0, 0, 40, 40);
                        } else {
                            img.onload = () => {
                                ctx.drawImage(img, 0, 0, 40, 40);
                            };
                        }
                    } else if (element.classList.contains('canvas-shape')) {
                        const svg = element.querySelector('svg');
                        const data = new XMLSerializer().serializeToString(svg);
                        const DOMURL = window.URL || window.webkitURL || window;
                        const img = new Image();
                        const svgBlob = new Blob([data], { type: 'image/svg+xml;charset=utf-8' });
                        const url = DOMURL.createObjectURL(svgBlob);
                        img.onload = function() {
                            ctx.drawImage(img, 0, 0, 40, 40);
                            DOMURL.revokeObjectURL(url);
                        };
                        img.src = url;
                    }
    
                    thumbnailContainer.appendChild(thumbnail);
    
                    const name = document.createElement('div');
                    name.className = 'layer-name';
                    name.textContent = element.id;
    
                    listItem.appendChild(layerControls);
                    listItem.appendChild(thumbnailContainer);
                    listItem.appendChild(name);
    
                    // Add double-click functionality to bring layer forward or send backward
                    listItem.addEventListener('dblclick', function(e) {
                        e.stopPropagation();
                        // Toggle layer order: bring to front if not already
                        const currentZ = parseInt(window.getComputedStyle(element).zIndex) || 1;
                        element.style.zIndex = currentZ + 1;
                        updateLayerPanel();
                        updateCode();
                        saveState();
                    });
    
                    layerList.appendChild(listItem);
                });
                makeLayerListDraggable();
            }
    
            function makeLayerListDraggable() {
                const layerList = document.getElementById('layerList');
                const listItems = layerList.querySelectorAll('.layer-list-item');
                listItems.forEach(item => {
                    item.draggable = true;
                    item.addEventListener('dragstart', dragStart);
                    item.addEventListener('dragover', dragOver);
                    item.addEventListener('drop', drop);
                });
            }
    
            let dragSrcEl = null;
    
            function dragStart(e) {
                dragSrcEl = this;
                e.dataTransfer.effectAllowed = 'move';
            }
    
            function dragOver(e) {
                e.preventDefault();
                e.dataTransfer.dropEffect = 'move';
                return false;
            }
    
            function drop(e) {
                e.stopPropagation();
                if (dragSrcEl !== this) {
                    const layerList = document.getElementById('layerList');
                    const nodes = Array.from(layerList.children);
                    const srcIndex = nodes.indexOf(dragSrcEl);
                    const destIndex = nodes.indexOf(this);
    
                    if (srcIndex > destIndex) {
                        layerList.insertBefore(dragSrcEl, this);
                    } else {
                        layerList.insertBefore(dragSrcEl, this.nextSibling);
                    }
    
                    updateCanvasLayerOrder();
                }
                return false;
            }
    
            function updateCanvasLayerOrder() {
                const layerList = document.getElementById('layerList');
                const layerItems = Array.from(layerList.children);
                const canvas = document.getElementById('canvas');
                const elements = Array.from(canvas.children).filter(el => el.classList.contains('canvas-text') || el.classList.contains('canvas-media') || el.classList.contains('canvas-shape'));
                // Remove all elements
                elements.forEach(el => {
                    canvas.removeChild(el);
                });
                // Re-append in new order based on layerList
                layerItems.reverse().forEach(item => { // Reverse to match visual order
                    const elementId = item.getAttribute('data-element-id');
                    const element = document.getElementById(elementId);
                    if (element) {
                        canvas.appendChild(element);
                    }
                });
                updateCode();
                saveState();
            }
    
            function toggleVisibility(elementId, visibilityIcon) {
                const element = document.getElementById(elementId);
                if (element.style.display === 'none') {
                    element.style.display = '';
                    visibilityIcon.innerHTML = '<i class="material-icons">visibility</i>';
                } else {
                    element.style.display = 'none';
                    visibilityIcon.innerHTML = '<i class="material-icons">visibility_off</i>';
                }
                updateCode();
                saveState();
            }
    
            function toggleLock(elementId, lockIcon) {
                const element = document.getElementById(elementId);
                if (element.dataset.locked === 'true') {
                    element.dataset.locked = 'false';
                    lockIcon.innerHTML = '<i class="material-icons">lock_open</i>';
                    element.style.pointerEvents = 'auto';
                } else {
                    element.dataset.locked = 'true';
                    lockIcon.innerHTML = '<i class="material-icons">lock</i>';
                    element.style.pointerEvents = 'none';
                }
                updateCode();
                saveState();
            }
    
            // Copy/Paste/Delete Functions
            function copyElements() {
                const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
                if (selectedElement) {
                    copiedElement = selectedElement.outerHTML;
                }
            }
    
            function pasteElements() {
                const canvas = document.getElementById('canvas');
                if (copiedElement) {
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = copiedElement;
                    const element = tempDiv.firstChild;
                    // Adjust element ID to make it unique
                    element.id = element.id + '-' + Date.now();
    
                    // Keep the element at the same position
                    element.style.top = parseInt(element.style.top) + 10 + 'px';
                    element.style.left = parseInt(element.style.left) + 10 + 'px';
    
                    canvas.appendChild(element);
                    makeDraggable(element);
                    makeSelectable(element);
                    if (element.classList.contains('canvas-text')) {
                        addTextControls(element);
                        addResizeHandles(element);
                    } else if (element.classList.contains('canvas-media')) {
                        addMediaControls(element);
                        addResizeHandles(element);
                        const img = element.querySelector('img');
                        if (img) {
                            img.onwheel = (e) => {
                                e.preventDefault();
                                zoomMedia(img, e);
                            };
                        }
                    } else if (element.classList.contains('canvas-shape')) {
                        addResizeHandles(element);
                    }
                    updateLayerPanel();
                    updateCode();
                    saveState();
                }
            }
    
            function deleteElement() {
                const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
                if (selectedElement) {
                    selectedElement.remove();
                    updateLayerPanel();
                    updateCode();
                    saveState();
                }
            }
    
            // Chat Send Function
            function sendMessage(event) {
                event.preventDefault();
                const input = event.target.querySelector('input');
                const message = input.value.trim();
                if (message === "") return;
                const chatMessages = document.querySelector('.chat-messages');
                const newMessage = document.createElement('div');
                newMessage.className = 'message';
                newMessage.textContent = message;
                chatMessages.appendChild(newMessage);
                input.value = '';
                chatMessages.scrollTop = chatMessages.scrollHeight;
                saveState();
            }
    
            // Undo/Redo functionality is already implemented above
    
        </script>
    </body>
    </html>
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.