unexpected input ")" <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8" />…
- User
unexpected input ")"
Likes & Playlists
API Mode
- Assistant
- User
- Assistant
unexpected input ")"
Likes & Playlists
API Mode
The error message "unexpected input ")" usually indicates a syntax problem in your JavaScript code somewhere, such as an extra or misplaced parenthesis.
Looking through your provided HTML and embedded JavaScript, there is a notable issue caused by duplicated event listener declarations and conflicting function definitions for consoleModeToggle click handling.
Specifically:
consoleModeToggle:You have this snippet twice:
function toggleConsoleMode() {
evaluationModeRawJS = !evaluationModeRawJS;
consoleModeToggle.setAttribute('aria-pressed', String(!evaluationModeRawJS));
consoleModeToggle.textContent = evaluationModeRawJS ? 'API Mode' : 'Raw JS/HTML Mode';
showToast(`Console evaluates: ${evaluationModeRawJS ? 'Raw JS/HTML' : 'Internal API commands'}`);
}
consoleModeToggle.addEventListener('click', toggleConsoleMode);
And then later:
// Switch console mode button
consoleModeToggle.addEventListener('click', () => {
evaluationModeRawJS = !evaluationModeRawJS;
consoleModeToggle.setAttribute('aria-pressed', String(!evaluationModeRawJS));
consoleModeToggle.textContent = evaluationModeRawJS ? 'API Mode' : 'Raw JS/HTML Mode';
showToast(`Console evaluates: ${evaluationModeRawJS ? 'Raw JS/HTML' : 'Internal API commands'}`);
});
This duplication can cause issues, but it should not produce a syntax error by itself.
But I can't spot any obvious unmatched parentheses or extra parentheses inside your code logic on a quick scan.
)" often appears in older browsers' dev tools or when copying/pasting code with template literals, or misplaced parenthesis inside inline arrow functions or event handlers.Since your code uses template literals extensively and complex functions, check for these small mistakes:
Unbalanced parentheses or braces in arrow functions or functions.
Functions without bodies or missing curly braces.
Inside your code you have this snippet (edited for clarity):
function createPlaylist(name) {
if (typeof name !== 'string') {
throw new Error('Playlist name must be a string');
}
const trimmedName = name.trim();
if (trimmedName.length === 0) {
throw new Error('Playlist name cannot be empty');
}
// Retrieve saved playlists or init empty object
const savedPlaylists = JSON.parse(localStorage.getItem('ultimate_savedPlaylists') || '{}');
// Check for duplicate names ignoring case
const normalizedNewName = trimmedName.toLowerCase();
for (const existingName of Object.keys(savedPlaylists)) {
if (existingName.toLowerCase() === normalizedNewName) {
throw new Error(`Playlist "${trimmedName}" already exists`);
}
}
// Add new empty playlist
savedPlaylists[trimmedName] = [];
// Save updated playlist object back to localStorage
localStorage.setItem('ultimate_savedPlaylists', JSON.stringify(savedPlaylists));
// Optional: update UI if function exists
if (typeof listPlaylists === 'function') {
listPlaylists();
}
return `Playlist "${trimmedName}" created successfully`;
}
This function is declared inside the IIFE block but you also add an event listener for createPlaylistBtn:
createPlaylistBtn.addEventListener('click', () => {
let name = newPlaylistName.value.trim();
if(!name) {
alert('Please enter a valid playlist name!');
return;
}
if(savedPlaylists[name]) {
alert('Playlist already exists.');
return;
}
savedPlaylists[name] = [];
localStorage.setItem(LS_KEYS.savedPlaylists, JSON.stringify(savedPlaylists));
newPlaylistName.value = "";
listPlaylists();
showToast(`Playlist "${name}" created`);
});
Note that you have two createPlaylist "concepts":
createPlaylist(name) which throws on bad input,)" error might be caused by:A missing or extra parenthesis somewhere in inline event handlers or function expressions.
Or a ) in a place where a semicolon would be expected.
Here’s what I suggest:
Open your browser's dev tools console (F12 usually).
Look at the exact line and column number generating the syntax error.
Verify the nearby code for unbalanced parentheses or syntax errors.
Since the full script is minimized into an IIFE, try pasting your JavaScript code into an online linter like JSHint or ESLint demo to catch syntax errors.
You can also copy your <script> section JS code into a standalone .js file and run the following Node.js command:
node --check yourfile.js
To check syntax.
Remove one of the duplicate consoleModeToggle event listeners.
Change the toggleConsoleMode function so it only declared once and event bound once.
If you want to unify those:
let evaluationModeRawJS = true; // You probably want this defined once
function toggleConsoleMode() {
evaluationModeRawJS = !evaluationModeRawJS;
consoleModeToggle.setAttribute('aria-pressed', String(!evaluationModeRawJS));
consoleModeToggle.textContent = evaluationModeRawJS ? 'API Mode' : 'Raw JS/HTML Mode';
showToast(`Console evaluates: ${evaluationModeRawJS ? 'Raw JS/HTML' : 'Internal API commands'}`);
}
consoleModeToggle.addEventListener('click', toggleConsoleMode);
Remove the second event listener.
"unexpected input ")" is a JavaScript syntax error: likely a missing opening ( or extra closing ).Check the exact error location in browser dev tools.
Remove duplicate event listeners, especially for consoleModeToggle.
Validate the entire JS code syntax with a linter.
Simplify your code blocks, especially event listeners with inline arrow functions.
If you want, I can review any smaller snippet or the exact part causing the syntax error if you provide a line or error line number.
add 30 features to this script make the 3d mode actually viewing so u can zoom and everything and make it so u can modify the stuff add better events fro the code and allat nad make this very well and with more sliders settings and defined everything
(function () { // ==== VARIABLES ==== const container = document.createElement('div'); const settingsBox = document.createElement('div'); const infoBox = document.createElement('div');
let currentSelection = []; // support multi-select
let draggedElement = null;
let dragOffset = { x: 0, y: 0 };
let isDraggingEnabled = true;
let isResizingEnabled = false;
let isRotatingEnabled = false;
let is3DViewEnabled = false;
let undoStack = [];
let redoStack = [];
let snapGridSize = 10;
let autoSaveInterval;
// Maintain list of objects for persistence and reference
const objects = [];
// ==== STYLES ====
// Add global styles and enhanced CSS
const style = document.createElement('style');
style.textContent = `
body, html {
margin: 0; padding: 0; overflow: hidden; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #c3cfe2 0%, #e9e4f0 100%);
user-select:none;
}
#container {
position: relative;
width: 100vw;
height: 100vh;
overflow: hidden;
perspective: 1200px;
border: 1px solid #444;
background: #f1f1f1;
}
#settingsBox {
position: fixed;
top: 10px; left: 10px;
width: 300px;
max-height: 85vh;
overflow-y: auto;
background: rgba(255 255 255 / 0.95);
box-shadow: 0 0 15px rgb(0 0 0 / 0.2);
padding: 20px;
border-radius: 12px;
font-size: 14px;
z-index: 9999;
}
#settingsBox h3 {
margin-top: 0; margin-bottom: 10px; font-weight: 700;
color: #222;
}
#infoBox {
position: fixed;
bottom: 10px; left: 10px;
background: rgba(0 0 0 / 0.75);
color: #eee;
padding: 10px 12px;
border-radius: 6px;
font-size: 13px;
font-weight: 600;
max-width: 350px;
z-index: 9998;
}
.object-box {
position: absolute;
border-radius: 12px;
box-shadow: 0 5px 10px rgb(0 0 0 / 0.15);
transition: box-shadow 0.3s ease, transform 0.3s ease;
user-select:none;
cursor: grab;
z-index: 1;
border: 2px solid transparent;
}
.object-box.selected {
border-color: dodgerblue;
box-shadow: 0 0 20px 3px dodgerblue;
cursor: grabbing;
}
.object-box.box {
background: coral;
color: #fff;
font-weight: 700;
font-size: 16px;
display: flex; align-items: center; justify-content: center;
text-shadow: 0 0 2px rgba(0,0,0,0.2);
}
.object-box.text-block {
background: #7ec0ee;
color: #fff;
font-size: 14px;
overflow-wrap: break-word;
padding: 6px 10px;
line-height: 1.3;
user-select: text;
cursor: text;
}
.object-box.image-block,
.object-box.gif-block {
background: #dedede;
overflow: hidden;
border-radius: 12px;
}
.object-box img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 12px;
pointer-events:none;
user-select:none;
}
/* Resize handles */
.resize-handle {
position: absolute;
width: 14px;
height: 14px;
background: #2d89ef;
border-radius: 50%;
border: 2px solid white;
cursor: pointer;
box-shadow: 0 0 5px #2d89ef;
transition: background 0.3s ease;
z-index: 100;
}
.resize-handle:hover {
background: #1e5faa;
}
/* Rotation handle */
.rotation-handle {
position: absolute;
width: 16px;
height: 16px;
background: yellowgreen;
border-radius: 50%;
border: 2px solid white;
cursor: grab;
top: -35px;
left: 50%;
transform: translateX(-50%);
box-shadow: 0 0 6px yellowgreen;
z-index: 100;
transition: background 0.3s ease;
}
.rotation-handle:hover {
background: #3c6d23;
}
/* Grid overlay */
#grid {
pointer-events:none;
position: absolute;
top: 0; left: 0;
width: 100%;
height: 100%;
background-image:
linear-gradient(to right, rgba(0,0,0,0.05) 1px, transparent 1px),
linear-gradient(to bottom, rgba(0,0,0,0.05) 1px, transparent 1px);
background-size: ${snapGridSize}px ${snapGridSize}px;
z-index: 0;
}
`;
document.head.appendChild(style);
// ==== SETUP CONTAINER AND UI ====
container.id = 'container';
settingsBox.id = 'settingsBox';
infoBox.id = 'infoBox';
document.body.appendChild(container);
document.body.appendChild(settingsBox);
document.body.appendChild(infoBox);
// Add grid overlay for snapping visualization
const grid = document.createElement('div');
grid.id = 'grid';
container.appendChild(grid);
// ==== HELPER FUNCTIONS ====
// Generate unique IDs
function generateId() {
return 'obj_' + Math.random().toString(36).substr(2, 9);
}
// Save current state for undo/redo
function pushToUndo() {
const savedState = objects.map(obj => ({
id: obj.id,
type: obj.type,
style: { ...obj.element.style },
innerHTML: obj.element.innerHTML,
contentEditable: obj.element.contentEditable,
imgSrc: obj.imgSrc || null,
rotation: obj.rotation || 0,
zIndex: obj.zIndex || 1
}));
undoStack.push(savedState);
if (undoStack.length > 100) undoStack.shift(); // Limit to 100 undo steps
redoStack = [];
}
// Load state from saved data
function loadState(state) {
// Clear current
objects.forEach(o => container.removeChild(o.element));
objects.length = 0;
currentSelection.length = 0;
state.forEach(data => {
let el;
switch (data.type) {
case 'box':
el = createBoxElement(data.style.width, data.style.height, data.style.backgroundColor, data.style.left, data.style.top, data.rotation, data.zIndex);
break;
case 'text':
el = createTextBlockElement(data.style.width, data.style.height, data.style.backgroundColor, data.style.left, data.style.top, data.innerHTML, data.contentEditable, data.rotation, data.zIndex);
break;
case 'image':
el = createImageBlockElement(data.style.width, data.style.height, data.style.left, data.style.top, data.imgSrc || null, data.rotation, data.zIndex);
break;
case 'gif':
el = createGifBlockElement(data.style.width, data.style.height, data.style.left, data.style.top, data.imgSrc || null, data.rotation, data.zIndex);
break;
default:
return;
}
el.id = data.id;
objects.push({
id: data.id,
type: data.type,
element: el,
rotation: data.rotation,
imgSrc: data.imgSrc,
zIndex: data.zIndex
});
container.appendChild(el);
});
infoBox.textContent = 'Layout loaded';
}
// Snap values to grid
function snapToGrid(value) {
return Math.round(value / snapGridSize) * snapGridSize;
}
// Select an object (multi-selection support)
function selectObject(obj, append = false) {
if(!append) {
// Clear current selection
currentSelection.forEach(o => o.element.classList.remove('selected'));
currentSelection.length = 0;
}
if (!currentSelection.includes(obj)) {
currentSelection.push(obj);
obj.element.classList.add('selected');
}
updateSettingsBox();
updateInfoBox();
}
// Deselect all
function clearSelection() {
currentSelection.forEach(o => o.element.classList.remove('selected'));
currentSelection.length = 0;
updateSettingsBox();
infoBox.textContent = 'No objects selected';
}
// Update UI info box
function updateInfoBox() {
if (currentSelection.length === 1) {
infoBox.textContent = `Selected: ${currentSelection[0].type} (ID: ${currentSelection[0].id})`;
} else if (currentSelection.length > 1) {
infoBox.textContent = `Selected: ${currentSelection.length} objects`;
} else {
infoBox.textContent = 'No objects selected';
}
}
// Create a box element
function createBoxElement(width='100px', height='100px', bgColor='coral', left='0px', top='0px', rotation=0, zIndex=1) {
const div = document.createElement('div');
div.classList.add('object-box', 'box');
div.style.width = width;
div.style.height = height;
div.style.backgroundColor = bgColor;
div.style.left = left;
div.style.top = top;
div.style.zIndex = zIndex;
div.style.transform = `rotate(${rotation}deg)`;
div.textContent = '3D Box';
div.setAttribute('tabindex', 0); // for keyboard focus
enableInteractivity(div);
return div;
}
// Create text block
function createTextBlockElement(width='150px', height='50px', bgColor='#7ec0ee', left='0px', top='0px', content='Editable Text', editable=true, rotation=0, zIndex=1) {
const div = document.createElement('div');
div.classList.add('object-box', 'text-block');
div.style.width = width;
div.style.height = height;
div.style.backgroundColor = bgColor;
div.style.left = left;
div.style.top = top;
div.style.zIndex = zIndex;
div.style.transform = `rotate(${rotation}deg)`;
div.textContent = content;
div.contentEditable = editable;
div.setAttribute('tabindex', 0);
enableInteractivity(div);
return div;
}
// Create image block
function createImageBlockElement(width='150px', height='150px', left='0px', top='0px', src=null, rotation=0, zIndex=1) {
const div = document.createElement('div');
div.classList.add('object-box', 'image-block');
div.style.width = width;
div.style.height = height;
div.style.left = left;
div.style.top = top;
div.style.zIndex = zIndex;
div.style.transform = `rotate(${rotation}deg)`;
if(!src) src = prompt("Enter Image URL", "https://via.placeholder.com/150");
const img = document.createElement('img');
img.src = src;
div.appendChild(img);
div.setAttribute('tabindex', 0);
enableInteractivity(div);
return div;
}
// Create gif block
function createGifBlockElement(width='150px', height='150px', left='0px', top='0px', src=null, rotation=0, zIndex=1) {
const div = document.createElement('div');
div.classList.add('object-box', 'gif-block');
div.style.width = width;
div.style.height = height;
div.style.left = left;
div.style.top = top;
div.style.zIndex = zIndex;
div.style.transform = `rotate(${rotation}deg)`;
if(!src) src = prompt("Enter GIF URL", "https://media.giphy.com/media/LmNwrBhejkK9EFP504/giphy.gif");
const img = document.createElement('img');
img.src = src;
div.appendChild(img);
div.setAttribute('tabindex', 0);
enableInteractivity(div);
return div;
}
// Enable drag, resize, select interactions on element
function enableInteractivity(el) {
// Prevent text edit drag interference
el.addEventListener('mousedown', e => {
e.stopPropagation();
});
// Select on click - with shift for multi-selection
el.addEventListener('click', e => {
if (e.shiftKey) {
const obj = objects.find(o => o.element === el);
if (obj) selectObject(obj, true);
} else {
const obj = objects.find(o => o.element === el);
if (obj) selectObject(obj, false);
}
e.preventDefault();
});
// Drag start
el.addEventListener('mousedown', e => {
if (!isDraggingEnabled) return;
if (e.button !== 0) return; // only left click
const obj = objects.find(o => o.element === el);
if (!obj) return;
draggedElement = obj;
const rect = el.getBoundingClientRect();
dragOffset.x = e.clientX - rect.left;
dragOffset.y = e.clientY - rect.top;
bringToFront(obj);
// If multi-selected and drag starts on selected group
if(!currentSelection.includes(obj)) {
selectObject(obj, false);
}
document.addEventListener('mousemove', dragHandler);
document.addEventListener('mouseup', dragEndHandler);
e.preventDefault();
});
// Keyboard accessibility for deletion and movement
el.addEventListener('keydown', e => {
const obj = objects.find(o => o.element === el);
if (!obj) return;
switch (e.key) {
case 'Delete':
case 'Backspace':
removeObject(obj);
break;
case 'ArrowUp':
moveObject(obj, 0, -snapGridSize);
break;
case 'ArrowDown':
moveObject(obj, 0, snapGridSize);
break;
case 'ArrowLeft':
moveObject(obj, -snapGridSize, 0);
break;
case 'ArrowRight':
moveObject(obj, snapGridSize, 0);
break;
case 'r':
rotateObject(obj, 15);
break;
case 'Shift':
case 'Control':
break; // ignore special keys
default:
return;
}
e.preventDefault();
});
}
// Drag handlers
function dragHandler(e) {
if (!draggedElement) return;
e.preventDefault();
// Calculate new positions for all selected elements (multi-drag support)
currentSelection.forEach(obj => {
if (!obj.element) return;
let newX = e.clientX - dragOffset.x;
let newY = e.clientY - dragOffset.y;
// For group drag: offset relative positions by the initial dragged element position vs others
if(obj !== draggedElement) {
const rectCur = obj.element.getBoundingClientRect();
const rectRef = draggedElement.element.getBoundingClientRect();
const dx = rectCur.left - rectRef.left;
const dy = rectCur.top - rectRef.top;
newX += dx;
newY += dy;
}
// Snap to grid
newX = snapToGrid(newX);
newY = snapToGrid(newY);
// Bound inside container
const maxX = container.clientWidth - obj.element.offsetWidth;
const maxY = container.clientHeight - obj.element.offsetHeight;
newX = Math.min(Math.max(0, newX), maxX);
newY = Math.min(Math.max(0, newY), maxY);
obj.element.style.left = newX + 'px';
obj.element.style.top = newY + 'px';
});
updateInfoBox();
}
function dragEndHandler(e) {
draggedElement = null;
document.removeEventListener('mousemove', dragHandler);
document.removeEventListener('mouseup', dragEndHandler);
pushToUndo();
}
// Move object by dx, dy pixels
function moveObject(obj, dx, dy) {
if (!obj || !obj.element) return;
let curX = parseInt(obj.element.style.left) || 0;
let curY = parseInt(obj.element.style.top) || 0;
let newX = snapToGrid(curX + dx);
let newY = snapToGrid(curY + dy);
newX = Math.min(Math.max(0, newX), container.clientWidth - obj.element.offsetWidth);
newY = Math.min(Math.max(0, newY), container.clientHeight - obj.element.offsetHeight);
obj.element.style.left = newX + 'px';
obj.element.style.top = newY + 'px';
pushToUndo();
updateInfoBox();
}
// Rotate object by degrees
function rotateObject(obj, degrees) {
if (!obj || !obj.element) return;
obj.rotation = ((obj.rotation || 0) + degrees) % 360;
obj.element.style.transform = `rotate(${obj.rotation}deg)`;
pushToUndo();
updateInfoBox();
}
// Bring selected object to front by updating z-index
function bringToFront(obj) {
// Find max z-index
const maxZ = Math.max(...objects.map(o => o.zIndex || 1), 1);
obj.zIndex = maxZ + 1;
obj.element.style.zIndex = obj.zIndex;
pushToUndo();
}
// Enabling resizing feature
function makeResizable(obj) {
if (!isResizingEnabled) return;
// Remove previous handles if any
removeResizeHandles(obj.element);
// Add 4 corner handles for resizing
const handlesPos = [
{ name: 'nw', cursor: 'nwse-resize', left: '-10px', top: '-10px' },
{ name: 'ne', cursor: 'nesw-resize', right: '-10px', top: '-10px' },
{ name: 'sw', cursor: 'nesw-resize', left: '-10px', bottom: '-10px' },
{ name: 'se', cursor: 'nwse-resize', right: '-10px', bottom: '-10px' }
];
handlesPos.forEach(pos => {
const handle = document.createElement('div');
handle.classList.add('resize-handle');
if (pos.left) handle.style.left = pos.left;
if (pos.right) handle.style.right = pos.right;
if (pos.top) handle.style.top = pos.top;
if (pos.bottom) handle.style.bottom = pos.bottom;
handle.style.cursor = pos.cursor;
// Resize logic
handle.addEventListener('mousedown', e => {
e.stopPropagation();
if (e.button !== 0) return;
const startX = e.clientX;
const startY = e.clientY;
const startWidth = obj.element.offsetWidth;
const startHeight = obj.element.offsetHeight;
const startLeft = parseInt(obj.element.style.left) || 0;
const startTop = parseInt(obj.element.style.top) || 0;
function resizeHandler(e2) {
e2.preventDefault();
let dx = e2.clientX - startX;
let dy = e2.clientY - startY;
let newWidth = startWidth;
let newHeight = startHeight;
let newLeft = startLeft;
let newTop = startTop;
switch(pos.name) {
case 'nw':
newWidth = startWidth - dx;
newHeight = startHeight - dy;
newLeft = startLeft + dx;
newTop = startTop + dy;
break;
case 'ne':
newWidth = startWidth + dx;
newHeight = startHeight - dy;
newTop = startTop + dy;
break;
case 'sw':
newWidth = startWidth - dx;
newHeight = startHeight + dy;
newLeft = startLeft + dx;
break;
case 'se':
newWidth = startWidth + dx;
newHeight = startHeight + dy;
break;
}
if (newWidth < 50) newWidth = 50;
if (newHeight < 50) newHeight = 50;
// Bound inside container
if (newLeft < 0) newLeft = 0;
if (newTop < 0) newTop = 0;
if (newLeft + newWidth > container.clientWidth) newWidth = container.clientWidth - newLeft;
if (newTop + newHeight > container.clientHeight) newHeight = container.clientHeight - newTop;
obj.element.style.width = newWidth + 'px';
obj.element.style.height = newHeight + 'px';
obj.element.style.left = newLeft + 'px';
obj.element.style.top = newTop + 'px';
}
function stopResize() {
document.removeEventListener('mousemove', resizeHandler);
document.removeEventListener('mouseup', stopResize);
pushToUndo();
}
document.addEventListener('mousemove', resizeHandler);
document.addEventListener('mouseup', stopResize);
});
obj.element.appendChild(handle);
});
}
// Remove all resize handles from an element
function removeResizeHandles(el) {
const handles = el.querySelectorAll('.resize-handle');
handles.forEach(h => h.remove());
}
// Add rotation handle
function makeRotatable(obj) {
if (!isRotatingEnabled) {
removeRotationHandles(obj.element);
return;
}
removeRotationHandles(obj.element);
const rotHandle = document.createElement('div');
rotHandle.classList.add('rotation-handle');
// Rotation logic
rotHandle.addEventListener('mousedown', e => {
e.stopPropagation();
e.preventDefault();
const center = obj.element.getBoundingClientRect();
const cx = center.left + center.width/2;
const cy = center.top + center.height/2;
function onRotate(ev) {
ev.preventDefault();
const radians = Math.atan2(ev.clientY - cy, ev.clientX - cx);
let deg = radians * (180 / Math.PI) + 90; // adjust, 0 degree points upwards
if (deg < 0) deg += 360;
deg = Math.round(deg);
obj.rotation = deg;
obj.element.style.transform = `rotate(${deg}deg)`;
}
function stopRotate() {
document.removeEventListener('mousemove', onRotate);
document.removeEventListener('mouseup', stopRotate);
pushToUndo();
}
document.addEventListener('mousemove', onRotate);
document.addEventListener('mouseup', stopRotate);
});
obj.element.appendChild(rotHandle);
}
// Remove rotation handles
function removeRotationHandles(el) {
const handles = el.querySelectorAll('.rotation-handle');
handles.forEach(h => h.remove());
}
// Spawn new object by type
function spawnObject(type) {
let obj, id = generateId();
const left = snapToGrid(container.clientWidth / 2 - 75) + 'px';
const top = snapToGrid(container.clientHeight / 2 - 75) + 'px';
switch(type) {
case 'box':
obj = {
id,
type,
element: createBoxElement('150px', '150px', '#ff6f61', left, top, 0, 1),
rotation: 0,
zIndex: 1
};
break;
case 'text':
obj = {
id,
type,
element: createTextBlockElement('180px', '60px', '#099', left, top, "Editable Text", true, 0, 1),
rotation: 0,
zIndex: 1
};
break;
case 'image':
obj = {
id,
type,
element: createImageBlockElement('150px', '150px', left, top, null, 0, 1),
imgSrc: null,
rotation: 0,
zIndex: 1
};
break;
case 'gif':
obj = {
id,
type,
element: createGifBlockElement('150px', '150px', left, top, null, 0, 1),
imgSrc: null,
rotation: 0,
zIndex: 1
};
break;
default:
console.warn('Unsupported object type:', type);
return;
}
container.appendChild(obj.element);
objects.push(obj);
makeResizable(obj);
makeRotatable(obj);
selectObject(obj);
pushToUndo();
}
// Remove object and its references
function removeObject(obj) {
if(!obj) return;
if(container.contains(obj.element)) container.removeChild(obj.element);
const idx = objects.findIndex(o => o.id === obj.id);
if(idx > -1) objects.splice(idx, 1);
if (currentSelection.includes(obj)) {
currentSelection.splice(currentSelection.indexOf(obj),1);
}
updateInfoBox();
pushToUndo();
}
// Clear all objects
function clearAllObjects() {
objects.forEach(o => {
if(container.contains(o.element)) container.removeChild(o.element);
});
objects.length = 0;
currentSelection.length = 0;
updateInfoBox();
pushToUndo();
}
// Update settings UI for selected object(s)
function updateSettingsBox() {
const boxSizeValue = currentSelection[0] ? currentSelection[0].element.offsetWidth : 100;
const rotationValue = currentSelection[0] ? (currentSelection[0].rotation || 0) : 0;
const colorValue = (currentSelection[0] && (currentSelection[0].type === 'box' || currentSelection[0].type === 'text')) ? currentSelection[0].element.style.backgroundColor : '#ff6f61';
const isDragChecked = isDraggingEnabled;
const isResizeChecked = isResizingEnabled;
const isRotateChecked = isRotatingEnabled;
const is3DChecked = is3DViewEnabled;
settingsBox.innerHTML = `
<h3>3D Manipulation Tool</h3>
<label>Select Object Type:</label>
<select id="objectType">
<option value="box">3D Box</option>
<option value="text">Text Block</option>
<option value="image">Image Block</option>
<option value="gif">GIF Block</option>
</select>
<button id="addObjectBtn">Add Object</button>
<hr>
<div ${currentSelection.length === 0 ? 'style="display:none"' : ''}>
<strong>Selected Object Settings (${currentSelection.length})</strong><br><br>
<label>Width:</label>
<input type="range" id="widthSlider" min="50" max="600" value="${boxSizeValue}" />
<span id="widthVal">${boxSizeValue}px</span><br>
<label>Height:</label>
<input type="range" id="heightSlider" min="50" max="600" value="${boxSizeValue}" />
<span id="heightVal">${boxSizeValue}px</span><br>
<label>Rotation:</label>
<input type="range" id="rotationSlider" min="0" max="360" value="${rotationValue}" />
<span id="rotationVal">${rotationValue}°</span><br>
<label>Background Color:</label>
<input type="color" id="colorPicker" value="${rgbToHex(colorValue)}" />
<br><br>
<button id="removeSelectedBtn">Remove Selected</button>
<button id="bringFrontBtn">Bring to Front</button>
<button id="sendBackBtn">Send to Back</button>
</div>
<hr>
<label><input type="checkbox" id="dragToggle" ${isDragChecked ? 'checked' : ''} /> Enable Dragging</label><br>
<label><input type="checkbox" id="resizeToggle" ${isResizeChecked ? 'checked' : ''} /> Enable Resizing</label><br>
<label><input type="checkbox" id="rotateToggle" ${isRotateChecked ? 'checked' : ''} /> Enable Rotation</label><br>
<label><input type="checkbox" id="snapToggle" checked /> Enable Snap to Grid</label><br>
<label><input type="checkbox" id="gridToggle" checked /> Show Grid</label><br>
<hr>
<button id="undoBtn">Undo (Ctrl+Z)</button>
<button id="redoBtn">Redo (Ctrl+Y)</button>
<button id="saveBtn">Save Layout</button>
<button id="loadBtn">Load Layout</button>
<button id="clearBtn">Clear All</button>
<hr>
<button id="toggle3DBtn">${is3DChecked ? 'Disable' : 'Enable'} 3D View (T)</button>
`;
// Controls events
const addButton = settingsBox.querySelector('#addObjectBtn');
addButton.onclick = () => {
const select = settingsBox.querySelector('#objectType');
spawnObject(select.value);
};
if(currentSelection.length > 0) {
const widthSlider = settingsBox.querySelector('#widthSlider');
const heightSlider = settingsBox.querySelector('#heightSlider');
const rotationSlider = settingsBox.querySelector('#rotationSlider');
const colorPicker = settingsBox.querySelector('#colorPicker');
const removeSelectedBtn = settingsBox.querySelector('#removeSelectedBtn');
const bringFrontBtn = settingsBox.querySelector('#bringFrontBtn');
const sendBackBtn = settingsBox.querySelector('#sendBackBtn');
widthSlider.oninput = () => {
settingsBox.querySelector('#widthVal').textContent = widthSlider.value + 'px';
currentSelection.forEach(obj => {
obj.element.style.width = widthSlider.value + 'px';
});
pushToUndo();
};
heightSlider.oninput = () => {
settingsBox.querySelector('#heightVal').textContent = heightSlider.value + 'px';
currentSelection.forEach(obj => {
obj.element.style.height = heightSlider.value + 'px';
});
pushToUndo();
};
rotationSlider.oninput = () => {
settingsBox.querySelector('#rotationVal').textContent = rotationSlider.value + '°';
currentSelection.forEach(obj => {
obj.rotation = parseInt(rotationSlider.value);
obj.element.style.transform = `rotate(${obj.rotation}deg)`;
});
pushToUndo();
};
colorPicker.oninput = () => {
currentSelection.forEach(obj => {
if(obj.type === 'box' || obj.type === 'text') {
obj.element.style.backgroundColor = colorPicker.value;
}
});
pushToUndo();
};
removeSelectedBtn.onclick = () => {
currentSelection.slice().forEach(removeObject);
clearSelection();
};
bringFrontBtn.onclick = () => {
currentSelection.forEach(bringToFront);
updateInfoBox();
};
sendBackBtn.onclick = () => {
currentSelection.forEach(sendToBack);
updateInfoBox();
};
}
// Toggles
settingsBox.querySelector('#dragToggle').onchange = e => {
isDraggingEnabled = e.target.checked;
};
settingsBox.querySelector('#resizeToggle').onchange = e => {
isResizingEnabled = e.target.checked;
objects.forEach(makeResizable);
};
settingsBox.querySelector('#rotateToggle').onchange = e => {
isRotatingEnabled = e.target.checked;
objects.forEach(makeRotatable);
};
settingsBox.querySelector('#snapToggle').onchange = e => {
// Enable snapping or not
// can be used in drag handlers if expanded
};
settingsBox.querySelector('#gridToggle').onchange = e => {
grid.style.display = e.target.checked ? 'block' : 'none';
};
// Undo and redo
settingsBox.querySelector('#undoBtn').onclick = undo;
settingsBox.querySelector('#redoBtn').onclick = redo;
// Save/load/clear
settingsBox.querySelector('#saveBtn').onclick = saveLayout;
settingsBox.querySelector('#loadBtn').onclick = loadLayout;
settingsBox.querySelector('#clearBtn').onclick = () => {
if(confirm('Clear all objects? This cannot be undone.')) {
clearAllObjects();
}
};
// 3D toggle
settingsBox.querySelector('#toggle3DBtn').onclick = toggle3DView;
}
// Convert rgb color to hex string
function rgbToHex(rgb) {
if(!rgb) return '#ff6f61';
const ctx = document.createElement('canvas').getContext('2d');
ctx.fillStyle = rgb;
return ctx.fillStyle; // browser converts rgb -> hex string automatically
}
// Bring object to front (zIndex max+1)
function bringToFront(obj) {
const maxZ = Math.max(...objects.map(o => o.zIndex || 1), 1);
obj.zIndex = maxZ + 1;
obj.element.style.zIndex = obj.zIndex;
pushToUndo();
}
// Send object to back (zIndex 0 or minimal)
function sendToBack(obj) {
const minZ = Math.min(...objects.map(o => o.zIndex || 1), 1);
obj.zIndex = minZ - 1;
obj.element.style.zIndex = obj.zIndex;
pushToUndo();
}
// Undo function
function undo() {
if (undoStack.length === 0) {
infoBox.textContent = "Nothing to undo";
return;
}
const lastState = undoStack.pop();
redoStack.push(objects.map(obj => ({
id: obj.id,
type: obj.type,
style: { ...obj.element.style },
innerHTML: obj.element.innerHTML,
contentEditable: obj.element.contentEditable,
imgSrc: obj.imgSrc || null,
rotation: obj.rotation || 0,
zIndex: obj.zIndex || 1
})));
loadState(lastState);
infoBox.textContent = "Undo performed";
}
// Redo function
function redo() {
if (redoStack.length === 0) {
infoBox.textContent = "Nothing to redo";
return;
}
const nextState = redoStack.pop();
undoStack.push(objects.map(obj => ({
id: obj.id,
type: obj.type,
style: { ...obj.element.style },
innerHTML: obj.element.innerHTML,
contentEditable: obj.element.contentEditable,
imgSrc: obj.imgSrc || null,
rotation: obj.rotation || 0,
zIndex: obj.zIndex || 1
})));
loadState(nextState);
infoBox.textContent = "Redo performed";
}
// Save layout to localStorage
function saveLayout() {
try {
localStorage.setItem('layout', JSON.stringify(objects.map(o => ({
id: o.id,
type: o.type,
style: { ...o.element.style },
innerHTML: o.element.innerHTML,
contentEditable: o.element.contentEditable,
imgSrc: o.imgSrc || null,
rotation: o.rotation || 0,
zIndex: o.zIndex || 1
}))));
infoBox.textContent = "Layout saved";
} catch(err) {
console.error("Saving failed", err);
infoBox.textContent = "Save failed";
}
}
// Load layout from localStorage
function loadLayout() {
try {
const saved = localStorage.getItem('layout');
if (saved) {
const data = JSON.parse(saved);
loadState(data);
infoBox.textContent = "Layout loaded";
} else {
infoBox.textContent = "No layout saved";
}
} catch(err) {
console.error("Load failed", err);
infoBox.textContent = "Load failed";
}
}
// Toggle 3D view by adding perspective and subtle 3D transform animations
function toggle3DView() {
is3DViewEnabled = !is3DViewEnabled;
if (is3DViewEnabled) {
container.style.perspective = '1200px';
container.style.transformStyle = 'preserve-3d';
// Add subtle 3D rotation animation to objects
objects.forEach(obj => {
obj.element.style.transition = 'transform 0.5s ease';
obj.element.style.transform += ' translateZ(20px)';
});
infoBox.textContent = "3D View enabled: Use WASD to move selected objects";
} else {
container.style.perspective = '';
objects.forEach(obj => {
obj.element.style.transition = 'transform 0.5s ease';
// Reset translateZ
let newTransform = obj.element.style.transform.replace(/translateZ\(.*?\)/g, '');
obj.element.style.transform = newTransform;
});
infoBox.textContent = "3D View disabled";
}
updateSettingsBox();
}
// Handle keyboard shortcuts globally
document.addEventListener('keydown', e => {
// Ctrl+Z and Ctrl+Y for undo/redo
if (e.ctrlKey && e.key.toLowerCase() === 'z') {
undo();
e.preventDefault();
}
if (e.ctrlKey && e.key.toLowerCase() === 'y') {
redo();
e.preventDefault();
}
// T toggles 3D view
if (e.key.toLowerCase() === 't') {
toggle3DView();
}
// Delete removes selected objects
if (e.key === 'Delete' || e.key === 'Backspace') {
currentSelection.slice().forEach(removeObject);
clearSelection();
e.preventDefault();
}
});
// Clicking on empty container clears selection
container.addEventListener('mousedown', e => {
if (e.target === container) {
clearSelection();
}
});
// Initialize UI on page load
function initializeUI() {
updateSettingsBox();
infoBox.textContent = 'Ready! Click "Add Object" to begin. Shift+Click multi-select.';
grid.style.display = 'block';
}
initializeUI();
// Auto-save every 30s to localStorage
autoSaveInterval = setInterval(() => {
saveLayout();
}, 30000);
console.log("Enhanced 3D manipulation tool ready");
// Expose some API for debugging (optional)
window._editor = {
spawnObject, selectObject, removeObject, clearSelection, undo, redo, saveLayout, loadLayout
};
})();
You've created a very solid base for an interactive 3D-ish manipulation tool with multi-object dragging, resizing, rotating, undo/redo, color pickers, persistent layout, and a toggleable 3D view.
To massively upgrade it with 30+ new features, improved 3D interaction (zoom, pan, orbit), more sliders and settings, better event handling, and more polished control, here is an outline and an improved version of the script that incorporates your requests:
(Note: Due to complexity, this example focuses on core features, you can extend as needed.)
position3D (X, Y, Z), rotations on X,Y,Z axes, and uniform scale, applied via CSS 3D transforms.This makes your tool significantly richer, interactive, and properly 3D.
Feel free to expand adding:
If you'd like, I can help with those too.
Let me know if you want me to prepare a runnable full HTML example or any other extension!
Not yet included in a published release.
(function () {
"use strict";
// ==== VARIABLES ====
const container = document.createElement("div");
const settingsBox = document.createElement("div");
const infoBox = document.createElement("div");
const helpBox = document.createElement("div");
// State
let currentSelection = []; // multi-select support
let draggedElement = null;
let dragOffset = { x: 0, y: 0 };
let dragAxisLock = null; // 'x' or 'y' if axis locked
let isDraggingEnabled = true;
let isResizingEnabled = true;
let isRotatingEnabled = true;
let isScalingEnabled = true;
let is3DViewEnabled = false;
let autoSaveInterval;
// Snap and Grid Settings
let snapToGridEnabled = true;
let snapGridSize = 10;
let gridVisible = true;
// Camera State for 3D interaction
let cameraRotation = { x: 15, y: 30 }; // degrees
let cameraDistance = 800; // zoom
let cameraPan = { x: 0, y: 0 };
let isOrbitingCamera = false;
let isPanningCamera = false;
let lastMousePos = null;
// Undo/Redo
let undoStack = [];
let redoStack = [];
// List of objects for persistence and reference
const objects = [];
// ==== STYLES ====
const style = document.createElement("style");
style.textContent = `
html, body {
margin:0; padding:0; overflow:hidden; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #202020 0%, #404040 100%);
color:#eee;
user-select:none;
height:100%;
width:100%;
}
#container {
position: relative;
width:100vw;
height:100vh;
background:#111;
perspective:1200px;
transform-style: preserve-3d;
overflow: visible;
perspective-origin: center center;
cursor: grab;
}
#container.grabbing {
cursor: grabbing;
}
#settingsBox {
position: fixed;
top: 10px; left: 10px;
width: 360px;
max-height: 90vh;
overflow-y: auto;
background: rgba(30,30,30,0.85);
box-shadow: 0 0 20px #00aaee77;
padding: 20px 24px;
border-radius: 18px;
font-size: 14px;
z-index: 9999;
color: #ccc;
user-select:none;
}
#settingsBox h3 {
margin-top: 0;
margin-bottom: 12px;
font-weight: 900;
color: #00aaff;
user-select:none;
}
#infoBox {
position: fixed;
bottom: 12px;
left: 12px;
background: rgba(0,0,0,0.7);
color: #0ff;
padding: 10px 16px;
border-radius: 10px;
font-weight: 600;
font-size: 13px;
z-index: 9998;
max-width: 360px;
user-select:none;
box-shadow: 0 0 15px #00aaff88 inset;
}
#helpBox {
position: fixed;
bottom: 12px;
right: 12px;
background: rgba(0,0,0,0.7);
color: #aaa;
padding: 10px 16px;
border-radius: 10px;
font-weight: 400;
font-size: 11px;
max-width: 380px;
max-height: 45vh;
overflow-y: auto;
z-index: 9998;
user-select:none;
box-shadow: 0 0 15px #00aaff88 inset;
display:none;
}
.object-box {
position: absolute;
border-radius: 12px;
box-shadow: 0 5px 15px rgba(0,170,255,0.8);
background: linear-gradient(145deg, #101010, #282828);
border: 2px solid #00aaff;
color: #0ff;
font-weight: 700;
user-select: none;
transition: box-shadow 0.3s ease, transform 0.3s ease;
cursor: grab;
overflow: visible;
backface-visibility: visible;
/* necessary for 3D transforms */
}
.object-box.grabbing {
cursor: grabbing;
}
.object-box.selected {
border-color: #00ffff;
box-shadow: 0 0 20px 3px #00ffff;
cursor: grabbing;
}
.object-box.text-block {
padding: 10px 14px;
overflow-wrap: break-word;
cursor: text;
user-select:text;
line-height: 1.3;
font-size: 15px;
background: linear-gradient(135deg, #004466, #0077aa);
border-radius: 12px;
border: 1.8px solid #00aaffaa;
}
.object-box img {
width: 100%;
height: 100%;
border-radius: 12px;
pointer-events:none;
user-select:none;
object-fit: cover;
filter: drop-shadow(0 0 6px #00aaffaa);
}
.resize-handle, .rotation-handle {
position: absolute;
border-radius: 50%;
border: 2px solid white;
user-select:none;
background: #00aaffcc;
box-shadow: 0 0 10px #00aaffcc;
transition: background 0.3s ease;
cursor: pointer;
z-index: 1000;
width: 18px;
height: 18px;
}
.resize-handle:hover, .rotation-handle:hover {
background: #0099ffdd;
box-shadow: 0 0 16px #0099ffdd;
}
.rotation-handle {
top: -40px;
left: 50%;
transform: translateX(-50%);
cursor: grab;
background: #33ccffcc;
box-shadow: 0 0 16px #33ccffcc;
}
#grid {
pointer-events:none;
position:absolute;
top:0;left:0;
width: 100%;
height: 100%;
background-size: ${snapGridSize}px ${snapGridSize}px;
background-image:
linear-gradient(to right, rgba(0,170,255,0.1) 1px, transparent 1px),
linear-gradient(to bottom, rgba(0,170,255,0.1) 1px, transparent 1px);
z-index: 0;
transition: opacity 0.3s ease;
}
input[type=range] {
width: 100%;
margin: 6px 0 12px 0;
cursor: pointer;
}
select, input[type=color], input[type=checkbox] {
cursor: pointer;
}
button {
display: inline-block;
font-size: 13px;
background: #0077aa;
border: none;
border-radius: 10px;
padding: 8px 14px;
margin: 4px 8px 8px 0;
color: #fff;
font-weight: 600;
cursor: pointer;
user-select:none;
transition: background-color 0.3s ease;
}
button:hover {
background: #00aaff;
box-shadow: 0 0 12px #00aaffaa;
}
/* Tooltip */
[data-tooltip] {
position: relative;
}
[data-tooltip]:hover::before {
content: attr(data-tooltip);
position: absolute;
bottom: 125%;
left: 50%;
transform: translateX(-50%);
background: #00aaffdd;
color: #222;
padding: 4px 8px;
border-radius: 6px;
white-space: nowrap;
font-size: 11px;
font-weight: 700;
pointer-events: none;
opacity: 1;
transition: opacity 0.2s ease;
z-index: 10000;
}
[data-tooltip]:hover::after {
content: '';
position: absolute;
bottom: 115%;
left: 50%;
transform: translateX(-50%);
border-width: 6px;
border-style: solid;
border-color: #00aaffdd transparent transparent transparent;
pointer-events: none;
opacity: 1;
transition: opacity 0.2s ease;
z-index: 10000;
}
`;
document.head.appendChild(style);
// ==== SETUP CONTAINER AND UI ====
container.id = "container";
settingsBox.id = "settingsBox";
infoBox.id = "infoBox";
helpBox.id = "helpBox";
document.body.appendChild(container);
document.body.appendChild(settingsBox);
document.body.appendChild(infoBox);
document.body.appendChild(helpBox);
// Add grid overlay for snapping visualization
const grid = document.createElement("div");
grid.id = "grid";
container.appendChild(grid);
// ==== HELPER FUNCTIONS ====
// Generate unique IDs
function generateId() {
return "obj_" + Math.random().toString(36).substr(2, 9);
}
function pushToUndo() {
const snapshot = objects.map((obj) => ({
id: obj.id,
type: obj.type,
style: { ...obj.element.style },
innerHTML: obj.element.innerHTML,
contentEditable: obj.element.contentEditable,
imgSrc: obj.imgSrc || null,
rotationX: obj.rotationX || 0,
rotationY: obj.rotationY || 0,
rotationZ: obj.rotationZ || 0,
scale: obj.scale || 1,
position3D: { ...obj.position3D },
zIndex: obj.zIndex || 1,
}));
undoStack.push(snapshot);
if (undoStack.length > 100) undoStack.shift();
redoStack = [];
}
function loadState(state) {
// Clear current
objects.forEach((o) => {
if (container.contains(o.element)) container.removeChild(o.element);
});
objects.length = 0;
currentSelection.length = 0;
state.forEach((data) => {
let el;
switch (data.type) {
case "box":
el = createBoxElement(
data.style.width,
data.style.height,
data.style.backgroundColor,
data.style.left,
data.style.top,
{
x: data.rotationX || 0,
y: data.rotationY || 0,
z: data.rotationZ || 0,
},
data.scale || 1,
data.zIndex || 1
);
break;
case "text":
el = createTextBlockElement(
data.style.width,
data.style.height,
data.style.backgroundColor,
data.style.left,
data.style.top,
data.innerHTML,
data.contentEditable,
{
x: data.rotationX || 0,
y: data.rotationY || 0,
z: data.rotationZ || 0,
},
data.scale || 1,
data.zIndex || 1
);
break;
case "image":
el = createImageBlockElement(
data.style.width,
data.style.height,
data.style.left,
data.style.top,
data.imgSrc || null,
{
x: data.rotationX || 0,
y: data.rotationY || 0,
z: data.rotationZ || 0,
},
data.scale || 1,
data.zIndex || 1
);
break;
case "gif":
el = createGifBlockElement(
data.style.width,
data.style.height,
data.style.left,
data.style.top,
data.imgSrc || null,
{
x: data.rotationX || 0,
y: data.rotationY || 0,
z: data.rotationZ || 0,
},
data.scale || 1,
data.zIndex || 1
);
break;
default:
return;
}
el.id = data.id;
objects.push({
id: data.id,
type: data.type,
element: el,
rotationX: data.rotationX || 0,
rotationY: data.rotationY || 0,
rotationZ: data.rotationZ || 0,
scale: data.scale || 1,
position3D: data.position3D || { x: 0, y: 0, z: 0 },
imgSrc: data.imgSrc,
zIndex: data.zIndex,
});
container.appendChild(el);
});
updateInfoBox();
updateSettingsBox();
}
// Snap value if snapping enabled
function snapToGrid(value) {
if (!snapToGridEnabled) return value;
return Math.round(value / snapGridSize) * snapGridSize;
}
// Update info box
function updateInfoBox() {
if (currentSelection.length === 1) {
const o = currentSelection[0];
infoBox.textContent = `Selected: ${o.type} (ID: ${o.id}) | Pos: X:${o.position3D.x.toFixed(
0
)} Y:${o.position3D.y.toFixed(0)} Z:${o.position3D.z.toFixed(
0
)} | Rot: X:${o.rotationX} Y:${o.rotationY} Z:${o.rotationZ} | Scale: ${o.scale.toFixed(
2
)}`;
} else if (currentSelection.length > 1) {
infoBox.textContent = `Selected ${currentSelection.length} objects`;
} else {
infoBox.textContent = "No objects selected";
}
}
// Enable keyboard accessibility and interactions
function enableInteractivity(el, obj) {
el.addEventListener("mousedown", (e) => {
e.stopPropagation();
});
el.addEventListener("click", (e) => {
if (e.shiftKey && currentSelection.includes(obj)) {
// deselect if shift-click already selected
deselectObject(obj);
} else if (e.shiftKey) {
selectObject(obj, true);
} else {
selectObject(obj, false);
}
e.preventDefault();
});
// Dragging only applicable if dragging enabled
el.addEventListener("mousedown", (e) => {
if (!isDraggingEnabled) return;
if (e.button !== 0) return; // only left mouse button
draggedElement = obj;
lastMousePos = { x: e.clientX, y: e.clientY };
// Lock drag axis if shift held
dragAxisLock = e.shiftKey ? "x" : null;
if (!currentSelection.includes(obj)) {
selectObject(obj, false);
}
container.classList.add("grabbing");
document.body.style.cursor = "grabbing";
e.preventDefault();
document.addEventListener("mousemove", dragHandler3D);
document.addEventListener("mouseup", dragEnd3D);
});
// Keyboard support for delete, rotate, scale, move etc
el.addEventListener("keydown", (e) => {
switch (e.key.toLowerCase()) {
case "delete":
case "backspace":
currentSelection.slice().forEach(removeObject);
clearSelection();
break;
// Arrow keys move object by snapGridSize units on screen plane (adjusted for 3D)
case "arrowup":
moveObject3DBy(e.shiftKey ? 1 : 10, "y", true);
break;
case "arrowdown":
moveObject3DBy(e.shiftKey ? -1 : -10, "y", true);
break;
case "arrowleft":
moveObject3DBy(e.shiftKey ? -1 : -10, "x", true);
break;
case "arrowright":
moveObject3DBy(e.shiftKey ? 1 : 10, "x", true);
break;
case "r":
rotateSelected("y", 15); // rotate Y axis 15deg
break;
case "s":
scaleSelected(0.1); // scale up by 10%
break;
case "d":
scaleSelected(-0.1); // scale down by 10%
break;
default:
return;
}
e.preventDefault();
});
// Show tooltips when focusing elements
el.addEventListener("focus", () => {
el.style.boxShadow = "0 0 30px 4px #00aaffcc";
});
el.addEventListener("blur", () => {
el.style.boxShadow = "";
});
}
// Select object, support multi-select append param
function selectObject(obj, append = false) {
if (!append) {
clearSelection();
}
if (!currentSelection.includes(obj)) {
currentSelection.push(obj);
obj.element.classList.add("selected");
}
updateSettingsBox();
updateInfoBox();
}
// Remove from selection
function deselectObject(obj) {
const idx = currentSelection.indexOf(obj);
if (idx > -1) {
currentSelection.splice(idx, 1);
obj.element.classList.remove("selected");
}
updateSettingsBox();
updateInfoBox();
}
// Clear selection
function clearSelection() {
currentSelection.forEach((obj) => obj.element.classList.remove("selected"));
currentSelection.length = 0;
updateSettingsBox();
updateInfoBox();
}
// Bring object(s) to front
function bringToFront(obj) {
const maxZ = Math.max(...objects.map((o) => o.zIndex || 1), 1);
obj.zIndex = maxZ + 1;
obj.element.style.zIndex = obj.zIndex;
pushToUndo();
}
// Send object(s) to back
function sendToBack(obj) {
const minZ = Math.min(...objects.map((o) => o.zIndex || 1), 1);
obj.zIndex = minZ - 1;
obj.element.style.zIndex = obj.zIndex;
pushToUndo();
}
// Remove object
function removeObject(obj) {
if (!obj) return;
if (container.contains(obj.element)) container.removeChild(obj.element);
const idx = objects.findIndex((o) => o.id === obj.id);
if (idx > -1) objects.splice(idx, 1);
if (currentSelection.includes(obj)) deselectObject(obj);
updateInfoBox();
pushToUndo();
}
// Clear all objects
function clearAllObjects() {
objects.forEach((o) => {
if (container.contains(o.element)) container.removeChild(o.element);
});
objects.length = 0;
currentSelection.length = 0;
updateInfoBox();
pushToUndo();
}
// Update container's CSS camera transform to simulate orbit and pan
function updateCameraTransform() {
// Compose camera transform string
container.style.transformOrigin = "50% 50%";
container.style.transform = `
translateX(${cameraPan.x}px)
translateY(${cameraPan.y}px)
translateZ(${-cameraDistance}px)
rotateX(${cameraRotation.x}deg)
rotateY(${cameraRotation.y}deg)
`;
}
// Create 3D object's CSS transform string from rotations, scale, and 3D position
function composeObjectTransform(obj) {
const pos = obj.position3D;
return `
translate3d(${pos.x}px, ${pos.y}px, ${pos.z}px)
rotateX(${obj.rotationX}deg)
rotateY(${obj.rotationY}deg)
rotateZ(${obj.rotationZ}deg)
scale(${obj.scale})
`;
}
function updateElement3DTransform(obj) {
obj.element.style.transform = composeObjectTransform(obj);
}
// Object creation functions with 3D position, rotation xyz, and scale
function createBoxElement(
width = "100px",
height = "100px",
bgColor = "#0077ff",
left = "0px",
top = "0px",
rotation = { x: 0, y: 0, z: 0 },
scale = 1,
zIndex = 1
) {
const div = document.createElement("div");
div.classList.add("object-box", "box");
div.style.width = width;
div.style.height = height;
div.style.backgroundColor = bgColor;
div.style.zIndex = zIndex;
div.tabIndex = 0;
return div;
}
function createTextBlockElement(
width = "150px",
height = "50px",
bgColor = "#004477",
left = "0px",
top = "0px",
content = "Editable Text",
editable = true,
rotation = { x: 0, y: 0, z: 0 },
scale = 1,
zIndex = 1
) {
const div = document.createElement("div");
div.classList.add("object-box", "text-block");
div.style.width = width;
div.style.height = height;
div.style.backgroundColor = bgColor;
div.innerHTML = content;
div.contentEditable = editable;
div.style.zIndex = zIndex;
div.tabIndex = 0;
return div;
}
function createImageBlockElement(
width = "150px",
height = "150px",
left = "0px",
top = "0px",
src = null,
rotation = { x: 0, y: 0, z: 0 },
scale = 1,
zIndex = 1
) {
const div = document.createElement("div");
div.classList.add("object-box", "image-block");
div.style.width = width;
div.style.height = height;
div.style.zIndex = zIndex;
div.tabIndex = 0;
if (!src) src = prompt("Enter Image URL", "https://via.placeholder.com/150");
const img = document.createElement("img");
img.src = src;
div.appendChild(img);
return div;
}
function createGifBlockElement(
width = "150px",
height = "150px",
left = "0px",
top = "0px",
src = null,
rotation = { x: 0, y: 0, z: 0 },
scale = 1,
zIndex = 1
) {
const div = document.createElement("div");
div.classList.add("object-box", "gif-block");
div.style.width = width;
div.style.height = height;
div.style.zIndex = zIndex;
div.tabIndex = 0;
if (!src)
src =
"https://media.giphy.com/media/LmNwrBhejkK9EFP504/giphy.gif";
const img = document.createElement("img");
img.src = src;
div.appendChild(img);
return div;
}
// Spawn object of given type
function spawnObject(type) {
const id = generateId();
// Center spawn
const centerX = container.clientWidth / 2;
const centerY = container.clientHeight / 2;
let obj;
switch (type) {
case "box":
obj = {
id,
type,
element: createBoxElement(
"150px",
"150px",
"#0077ff",
"0px",
"0px",
{ x: 0, y: 0, z: 0 },
1,
1
),
position3D: { x: centerX, y: centerY, z: 0 },
rotationX: 0,
rotationY: 0,
rotationZ: 0,
scale: 1,
zIndex: 1,
};
break;
case "text":
obj = {
id,
type,
element: createTextBlockElement(
"180px",
"60px",
"#004477",
"0px",
"0px",
"Editable Text",
true,
{ x: 0, y: 0, z: 0 },
1,
1
),
position3D: { x: centerX, y: centerY, z: 0 },
rotationX: 0,
rotationY: 0,
rotationZ: 0,
scale: 1,
zIndex: 1,
};
break;
case "image":
obj = {
id,
type,
element: createImageBlockElement(
"150px",
"150px",
"0px",
"0px",
null,
{ x: 0, y: 0, z: 0 },
1,
1
),
position3D: { x: centerX, y: centerY, z: 0 },
rotationX: 0,
rotationY: 0,
rotationZ: 0,
scale: 1,
imgSrc: null,
zIndex: 1,
};
break;
case "gif":
obj = {
id,
type,
element: createGifBlockElement(
"150px",
"150px",
"0px",
"0px",
null,
{ x: 0, y: 0, z: 0 },
1,
1
),
position3D: { x: centerX, y: centerY, z: 0 },
rotationX: 0,
rotationY: 0,
rotationZ: 0,
scale: 1,
imgSrc: null,
zIndex: 1,
};
break;
default:
console.warn("Unsupported object type:", type);
return;
}
container.appendChild(obj.element);
objects.push(obj);
updateElement3DTransform(obj);
enableInteractivity(obj.element, obj);
pushToUndo();
selectObject(obj);
}
// Move selected objects in the 3D space
// axis: 'x', 'y', 'z'; delta is amount to move, relative true to interpret in object space or else screen space
function moveObject3DBy(delta, axis, relative = false) {
currentSelection.forEach((obj) => {
if (obj.position3D && axis in obj.position3D) {
obj.position3D[axis] += delta;
if (snapToGridEnabled) {
obj.position3D[axis] = snapToGrid(obj.position3D[axis]);
}
updateElement3DTransform(obj);
}
});
pushToUndo();
updateInfoBox();
}
// Rotate selected objects on axis by degrees
function rotateSelected(axis, degrees) {
currentSelection.forEach((obj) => {
switch (axis) {
case "x":
obj.rotationX = (obj.rotationX + degrees) % 360;
break;
case "y":
obj.rotationY = (obj.rotationY + degrees) % 360;
break;
case "z":
obj.rotationZ = (obj.rotationZ + degrees) % 360;
break;
default:
break;
}
updateElement3DTransform(obj);
});
pushToUndo();
updateInfoBox();
}
// Scale selected objects by delta (signed float)
function scaleSelected(delta) {
currentSelection.forEach((obj) => {
obj.scale += delta;
if (obj.scale < 0.1) obj.scale = 0.1;
if (obj.scale > 10) obj.scale = 10;
updateElement3DTransform(obj);
});
pushToUndo();
updateInfoBox();
}
// Drag handler in 3D context (moves XY plane)
function dragHandler3D(e) {
if (!draggedElement) return;
e.preventDefault();
const dx = e.clientX - lastMousePos.x;
const dy = e.clientY - lastMousePos.y;
lastMousePos = { x: e.clientX, y: e.clientY };
currentSelection.forEach((obj) => {
if (!obj.position3D) return;
let moveX = dx;
let moveY = dy;
// Apply axis locking
if (dragAxisLock === "x") moveY = 0;
if (dragAxisLock === "y") moveX = 0;
// Adjust move for zoom level (camera distance) and invert Y because screen coords are inverted y axis
const zoomFactor = cameraDistance / 400;
obj.position3D.x += moveX * zoomFactor;
obj.position3D.y += moveY * zoomFactor;
if (snapToGridEnabled) {
obj.position3D.x = snapToGrid(obj.position3D.x);
obj.position3D.y = snapToGrid(obj.position3D.y);
}
updateElement3DTransform(obj);
});
updateInfoBox();
}
function dragEnd3D(e) {
draggedElement = null;
dragAxisLock = null;
container.classList.remove("grabbing");
document.body.style.cursor = "";
document.removeEventListener("mousemove", dragHandler3D);
document.removeEventListener("mouseup", dragEnd3D);
pushToUndo();
}
// Adjust camera on mouse wheel zoom
container.addEventListener("wheel", (e) => {
e.preventDefault();
const delta = e.deltaY;
cameraDistance += delta * 2;
cameraDistance = Math.min(Math.max(200, cameraDistance), 3000);
updateCameraTransform();
});
// Orbit and pan camera controls on container drag (right-click drag or middle-button drag)
container.addEventListener("mousedown", (e) => {
// Ignore dragging object on left click
if (
e.target !== container &&
!e.target.classList.contains("object-box")
)
return;
if (e.button === 2 || e.button === 1) {
lastMousePos = { x: e.clientX, y: e.clientY };
if (e.button === 2) {
isOrbitingCamera = true;
container.classList.add("grabbing");
} else if (e.button === 1) {
isPanningCamera = true;
container.classList.add("grabbing");
}
document.body.style.cursor = "grabbing";
e.preventDefault();
document.addEventListener("mousemove", cameraDragHandler);
document.addEventListener("mouseup", cameraDragEnd);
}
});
function cameraDragHandler(e) {
e.preventDefault();
const dx = e.clientX - lastMousePos.x;
const dy = e.clientY - lastMousePos.y;
lastMousePos = { x: e.clientX, y: e.clientY };
if (isOrbitingCamera) {
// Rotate camera rotation angle by mouse drag amount
cameraRotation.y += dx * 0.5;
cameraRotation.x -= dy * 0.5;
cameraRotation.x = Math.max(-90, Math.min(90, cameraRotation.x));
} else if (isPanningCamera) {
// Pan camera (move container in x,y)
cameraPan.x += dx;
cameraPan.y += dy;
}
updateCameraTransform();
}
function cameraDragEnd(e) {
isOrbitingCamera = false;
isPanningCamera = false;
container.classList.remove("grabbing");
document.body.style.cursor = "";
document.removeEventListener("mousemove", cameraDragHandler);
document.removeEventListener("mouseup", cameraDragEnd);
}
// Keyboard global shortcut listeners
document.addEventListener("keydown", (e) => {
// Ctrl+Z and Ctrl+Y
if (e.ctrlKey && e.key.toLowerCase() === "z") {
undo();
e.preventDefault();
return;
}
if (e.ctrlKey && e.key.toLowerCase() === "y") {
redo();
e.preventDefault();
return;
}
// T toggles 3D view
if (e.key.toLowerCase() === "t") {
toggle3DView();
e.preventDefault();
return;
}
// Delete removes selected objects
if (e.key === "Delete" || e.key === "Backspace") {
if (currentSelection.length) {
currentSelection.slice().forEach(removeObject);
clearSelection();
e.preventDefault();
}
}
// Show/Hide help panel
if (e.key === "h") {
toggleHelp();
}
});
// Clicking empty container clears selection
container.addEventListener("mousedown", (e) => {
if (e.target === container) clearSelection();
});
// Undo/Redo
function undo() {
if (undoStack.length === 0) {
infoBox.textContent = "Nothing to undo";
return;
}
const lastState = undoStack.pop();
redoStack.push(
objects.map((obj) => ({
id: obj.id,
type: obj.type,
style: { ...obj.element.style },
innerHTML: obj.element.innerHTML,
contentEditable: obj.element.contentEditable,
imgSrc: obj.imgSrc || null,
rotationX: obj.rotationX || 0,
rotationY: obj.rotationY || 0,
rotationZ: obj.rotationZ || 0,
scale: obj.scale || 1,
position3D: { ...obj.position3D },
zIndex: obj.zIndex || 1,
}))
);
loadState(lastState);
infoBox.textContent = "Undo performed";
}
function redo() {
if (redoStack.length === 0) {
infoBox.textContent = "Nothing to redo";
return;
}
const nextState = redoStack.pop();
undoStack.push(
objects.map((obj) => ({
id: obj.id,
type: obj.type,
style: { ...obj.element.style },
innerHTML: obj.element.innerHTML,
contentEditable: obj.element.contentEditable,
imgSrc: obj.imgSrc || null,
rotationX: obj.rotationX || 0,
rotationY: obj.rotationY || 0,
rotationZ: obj.rotationZ || 0,
scale: obj.scale || 1,
position3D: { ...obj.position3D },
zIndex: obj.zIndex || 1,
}))
);
loadState(nextState);
infoBox.textContent = "Redo performed";
}
// Save and Load Layout
function saveLayout() {
try {
localStorage.setItem(
"layout",
JSON.stringify(
objects.map((o) => ({
id: o.id,
type: o.type,
style: { ...o.element.style },
innerHTML: o.element.innerHTML,
contentEditable: o.element.contentEditable,
imgSrc: o.imgSrc || null,
rotationX: o.rotationX || 0,
rotationY: o.rotationY || 0,
rotationZ: o.rotationZ || 0,
scale: o.scale || 1,
position3D: o.position3D,
zIndex: o.zIndex || 1,
}))
)
);
infoBox.textContent = "Layout saved";
} catch (err) {
console.error("Saving failed", err);
infoBox.textContent = "Save failed";
}
}
function loadLayout() {
try {
const saved = localStorage.getItem("layout");
if (saved) {
const data = JSON.parse(saved);
loadState(data);
infoBox.textContent = "Layout loaded";
} else {
infoBox.textContent = "No layout saved";
}
} catch (err) {
console.error("Load failed", err);
infoBox.textContent = "Load failed";
}
}
// Show/hide 3D view toggle
function toggle3DView() {
is3DViewEnabled = !is3DViewEnabled;
if (is3DViewEnabled) {
container.style.perspective = "1200px";
updateCameraTransform();
infoBox.textContent = "3D View enabled (Right drag orbit, Scroll zoom, Middle drag pan)";
} else {
container.style.perspective = "";
container.style.transform = "";
infoBox.textContent = "3D View disabled";
}
}
// Resize handles and rotation handles are not as heavily used here given 3D transform controls
// (These can be enhanced separately with draggable 3D gizmo overlays if desired)
// Update settings panel with sliders and buttons
function updateSettingsBox() {
const sel = currentSelection[0];
const numSelected = currentSelection.length;
const maxX = container.clientWidth;
const maxY = container.clientHeight;
const bgColorVal = sel?.element?.style?.backgroundColor || "#0077ff";
const contentHTML = sel?.element?.innerHTML || "";
settingsBox.innerHTML = `
<h3>3D Manipulation Tool (${numSelected} selected)</h3>
<label for="objectType">Add Object:</label>
<select id="objectType" aria-label="Select object type to add">
<option value="box">3D Box</option>
<option value="text">Text Block</option>
<option value="image">Image Block</option>
<option value="gif">GIF Block</option>
</select>
<button id="addObjectBtn" aria-label="Add selected object type">Add Object</button>
<hr>
<div style="${numSelected === 0 ? "display:none;" : ""}">
<strong>Selected Object Settings</strong>
<p style="font-size:12px; color:#44cfff;">
To edit text, click inside text blocks.<br/>
Use keyboard arrows for small movements.<br/>
Hold SHIFT while dragging to lock movement axis.
</p>
<label>Position X:
<input type="range" id="posX" min="0" max="${maxX}" value="${sel?.position3D?.x || 0}">
<span id="posXVal">${sel?.position3D?.x.toFixed(0) || 0}</span> px
</label>
<label>Position Y:
<input type="range" id="posY" min="0" max="${maxY}" value="${sel?.position3D?.y || 0}">
<span id="posYVal">${sel?.position3D?.y.toFixed(0) || 0}</span> px
</label>
<label>Position Z (Depth):
<input type="range" id="posZ" min="-500" max="500" value="${sel?.position3D?.z || 0}">
<span id="posZVal">${sel?.position3D?.z.toFixed(0) || 0}</span> px
</label>
<label>Rotation X:
<input type="range" id="rotX" min="0" max="360" value="${sel?.rotationX || 0}">
<span id="rotXVal">${sel?.rotationX || 0}°</span>
</label>
<label>Rotation Y:
<input type="range" id="rotY" min="0" max="360" value="${sel?.rotationY || 0}">
<span id="rotYVal">${sel?.rotationY || 0}°</span>
</label>
<label>Rotation Z:
<input type="range" id="rotZ" min="0" max="360" value="${sel?.rotationZ || 0}">
<span id="rotZVal">${sel?.rotationZ || 0}°</span>
</label>
<label>Scale:
<input type="range" id="scaleSlider" min="0.1" max="5" step="0.01" value="${sel?.scale || 1}">
<span id="scaleVal">${sel?.scale?.toFixed(2) || "1.00"}</span>
</label>
<label>Background Color:
<input type="color" id="bgColor" value="${rgbToHex(bgColorVal)}">
</label>
${
sel?.type === "text"
? `<label>Text Content:<br>
<textarea id="textContent" rows="3" style="width:100%">${contentHTML}</textarea>
</label>`
: ""
}
<button id="removeSelectedBtn">Remove Selected</button>
<button id="bringFrontBtn">Bring to Front</button>
<button id="sendBackBtn">Send to Back</button>
<button id="resetPropsBtn">Reset Properties</button>
</div>
<hr>
<label><input type="checkbox" id="dragToggle" ${
isDraggingEnabled ? "checked" : ""
}> Enable Dragging</label><br>
<label><input type="checkbox" id="resizeToggle" ${
isResizingEnabled ? "checked" : ""
}> Enable Resizing (NOT Implemented)</label><br>
<label><input type="checkbox" id="rotateToggle" ${
isRotatingEnabled ? "checked" : ""
}> Enable Rotation (Keyboard)</label><br>
<label><input type="checkbox" id="snapToggle" ${
snapToGridEnabled ? "checked" : ""
}> Enable Snap to Grid</label><br>
<label><input type="checkbox" id="gridToggle" ${
gridVisible ? "checked" : ""
}> Show Grid</label><br>
<button id="undoBtn">Undo (Ctrl+Z)</button>
<button id="redoBtn">Redo (Ctrl+Y)</button>
<button id="saveBtn">Save Layout</button>
<button id="loadBtn">Load Layout</button>
<button id="clearBtn">Clear All</button>
<button id="resetCameraBtn">Reset Camera</button>
<button id="helpToggleBtn">Toggle Keyboard Help (H)</button>
<hr>
<button id="toggle3DBtn">${
is3DViewEnabled ? "Disable" : "Enable"
} 3D View (T)</button>
`;
// Add Object event
settingsBox.querySelector("#addObjectBtn").onclick = () => {
const typ = settingsBox.querySelector("#objectType").value;
spawnObject(typ);
};
if (numSelected === 0) return;
// Cache elements for update events
const posXel = settingsBox.querySelector("#posX");
const posYel = settingsBox.querySelector("#posY");
const posZel = settingsBox.querySelector("#posZ");
const rotXel = settingsBox.querySelector("#rotX");
const rotYel = settingsBox.querySelector("#rotY");
const rotZel = settingsBox.querySelector("#rotZ");
const scaleEl = settingsBox.querySelector("#scaleSlider");
const bgColorEl = settingsBox.querySelector("#bgColor");
const textContentEl = settingsBox.querySelector("#textContent");
// Updates to positions (slider)
if (posXel)
posXel.oninput = (e) => {
posXel.nextElementSibling.textContent = e.target.value + " px";
currentSelection.forEach((obj) => {
obj.position3D.x = Number(e.target.value);
updateElement3DTransform(obj);
});
pushToUndo();
updateInfoBox();
};
if (posYel)
posYel.oninput = (e) => {
posYel.nextElementSibling.textContent = e.target.value + " px";
currentSelection.forEach((obj) => {
obj.position3D.y = Number(e.target.value);
updateElement3DTransform(obj);
});
pushToUndo();
updateInfoBox();
};
if (posZel)
posZel.oninput = (e) => {
posZel.nextElementSibling.textContent = e.target.value + " px";
currentSelection.forEach((obj) => {
obj.position3D.z = Number(e.target.value);
updateElement3DTransform(obj);
});
pushToUndo();
updateInfoBox();
};
// Rotation sliders
if (rotXel)
rotXel.oninput = (e) => {
rotXel.nextElementSibling.textContent = e.target.value + "°";
currentSelection.forEach((obj) => {
obj.rotationX = Number(e.target.value);
updateElement3DTransform(obj);
});
pushToUndo();
updateInfoBox();
};
if (rotYel)
rotYel.oninput = (e) => {
rotYel.nextElementSibling.textContent = e.target.value + "°";
currentSelection.forEach((obj) => {
obj.rotationY = Number(e.target.value);
updateElement3DTransform(obj);
});
pushToUndo();
updateInfoBox();
};
if (rotZel)
rotZel.oninput = (e) => {
rotZel.nextElementSibling.textContent = e.target.value + "°";
currentSelection.forEach((obj) => {
obj.rotationZ = Number(e.target.value);
updateElement3DTransform(obj);
});
pushToUndo();
updateInfoBox();
};
// Scale slider
if (scaleEl)
scaleEl.oninput = (e) => {
scaleEl.nextElementSibling.textContent = Number(e.target.value).toFixed(2);
currentSelection.forEach((obj) => {
obj.scale = Number(e.target.value);
updateElement3DTransform(obj);
});
pushToUndo();
updateInfoBox();
};
// Background color picker
if (bgColorEl)
bgColorEl.oninput = (e) => {
currentSelection.forEach((obj) => {
if (obj.type === "box" || obj.type === "text") {
obj.element.style.backgroundColor = e.target.value;
}
});
pushToUndo();
};
// Text editing
if (textContentEl)
textContentEl.oninput = (e) => {
currentSelection.forEach((obj) => {
if (obj.type === "text") {
obj.element.innerHTML = e.target.value;
}
});
pushToUndo();
};
// Buttons handlers
settingsBox.querySelector("#removeSelectedBtn").onclick = () => {
currentSelection.slice().forEach(removeObject);
clearSelection();
};
settingsBox.querySelector("#bringFrontBtn").onclick = () => {
currentSelection.forEach(bringToFront);
};
settingsBox.querySelector("#sendBackBtn").onclick = () => {
currentSelection.forEach(sendToBack);
};
settingsBox.querySelector("#resetPropsBtn").onclick = () => {
currentSelection.forEach((obj) => {
obj.rotationX = 0;
obj.rotationY = 0;
obj.rotationZ = 0;
obj.scale = 1;
updateElement3DTransform(obj);
});
pushToUndo();
updateInfoBox();
};
// Toggles & buttons
const dragToggle = settingsBox.querySelector("#dragToggle");
dragToggle.onchange = (e) => {
isDraggingEnabled = e.target.checked;
};
const snapToggle = settingsBox.querySelector("#snapToggle");
snapToggle.onchange = (e) => {
snapToGridEnabled = e.target.checked;
if (snapToGridEnabled) grid.style.opacity = "1";
else grid.style.opacity = "0.15";
};
const gridToggle = settingsBox.querySelector("#gridToggle");
gridToggle.onchange = (e) => {
gridVisible = e.target.checked;
grid.style.display = gridVisible ? "block" : "none";
};
settingsBox.querySelector("#undoBtn").onclick = undo;
settingsBox.querySelector("#redoBtn").onclick = redo;
settingsBox.querySelector("#saveBtn").onclick = saveLayout;
settingsBox.querySelector("#loadBtn").onclick = loadLayout;
settingsBox.querySelector("#clearBtn").onclick = () => {
if (confirm("Clear all objects? This cannot be undone.")) {
clearAllObjects();
}
};
settingsBox.querySelector("#resetCameraBtn").onclick = () => {
cameraRotation = { x: 15, y: 30 };
cameraDistance = 800;
cameraPan = { x: 0, y: 0 };
updateCameraTransform();
};
settingsBox.querySelector("#helpToggleBtn").onclick = toggleHelp;
settingsBox.querySelector("#toggle3DBtn").onclick = toggle3DView;
}
// Convert rgb() or rgba() string to hex (basic)
function rgbToHex(rgb) {
if (!rgb) return "#0077ff";
if (rgb.startsWith("#")) return rgb;
const res = rgb.match(/\d+/g);
if (!res || res.length < 3) return "#0077ff";
const r = parseInt(res[0]).toString(16).padStart(2, "0");
const g = parseInt(res[1]).toString(16).padStart(2, "0");
const b = parseInt(res[2]).toString(16).padStart(2, "0");
return `#${r}${g}${b}`;
}
// Initialization
function initializeUI() {
updateSettingsBox();
updateCameraTransform();
infoBox.textContent = "Ready! Add objects and manipulate.";
grid.style.opacity = snapToGridEnabled ? "1" : "0.15";
grid.style.display = gridVisible ? "block" : "none";
}
// Help toggle
function toggleHelp() {
if (helpBox.style.display === "block") {
helpBox.style.display = "none";
} else {
helpBox.style.display = "block";
helpBox.innerHTML = `<h3>Keyboard & Controls Help</h3>
<ul style="padding-left:18px; font-size:12px; line-height:1.4;">
<li><b>Click</b>: Select object</li>
<li><b>Shift+Click</b>: Multi-select/Deselect</li>
<li><b>Drag (Left Mouse)</b>: Move selected object(s)</li>
<li><b>Shift (Hold While Dragging)</b>: Lock drag axis (X)</li>
<li><b>Arrows</b>: Move selected object by small steps</li>
<li><b>R</b>: Rotate selected object 15° Y axis</li>
<li><b>S</b>: Scale Up selected object</li>
<li><b>D</b>: Scale Down selected object</li>
<li><b>T</b>: Toggle 3D View</li>
<li><b>H</b>: Toggle this help</li>
<li><b>Delete/Backspace</b>: Delete selected object(s)</li>
<li><b>Mouse Wheel</b>: Zoom camera in/out (3D view)</li>
<li><b>Right Click + Drag</b>: Orbit camera (3D view)</li>
<li><b>Middle Click + Drag</b>: Pan camera (3D view)</li>
</ul>`;
}
}
initializeUI();
// Auto-save every 30 seconds
autoSaveInterval = setInterval(saveLayout, 30000);
// Expose API for debugging
window._editor3D = {
spawnObject,
selectObject,
removeObject,
clearSelection,
undo,
redo,
saveLayout,
loadLayout,
toggle3DView,
};
})();