PixelPlacerBot/resources/js/grid.js
2024-07-28 18:06:05 -04:00

71 lines
2.6 KiB
JavaScript
Executable File

function colorCell(cellName, hexValue) {
console.log(`colorCell called with: ${cellName}, ${hexValue}`);
// Find the cell using its class name
const cell = document.querySelector(`.cell.${cellName}`);
// If the cell exists, change its background color to the provided hex value
if (cell) {
cell.style.backgroundColor = hexValue;
} else {
console.warn(`Cell ${cellName} not found.`);
}
}
// Attach colorCell function to the window object to make it globally accessible
window.colorCell = colorCell;
document.addEventListener('DOMContentLoaded', function() {
const gridSize = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--grid-size').trim());
const grid = document.querySelector('.grid-container');
function getLabel(index) {
let label = '';
while (index >= 0) {
label = String.fromCharCode((index % 26) + 65) + label;
index = Math.floor(index / 26) - 1;
}
return label;
}
// Create top labels
grid.innerHTML += '<div class="label"></div>'; // Empty top-left corner
for (let i = 0; i < gridSize; i++) {
grid.innerHTML += `<div class="label">${getLabel(i)}</div>`;
}
grid.innerHTML += '<div class="label"></div>'; // Empty top-right corner
// Create rows with side labels and cells
for (let i = 1; i <= gridSize; i++) {
grid.innerHTML += `<div class="label">${i}</div>`;
for (let j = 0; j < gridSize; j++) {
let cellName = `${getLabel(j)}${i}`; // This will generate names like A1, A2, B1, etc.
grid.innerHTML += `<div class="cell ${cellName}"></div>`;
}
grid.innerHTML += `<div class="label">${i}</div>`;
}
// Create bottom labels
grid.innerHTML += '<div class="label"></div>'; // Empty bottom-left corner
for (let i = 0; i < gridSize; i++) {
grid.innerHTML += `<div class="label">${getLabel(i)}</div>`;
}
grid.innerHTML += '<div class="label"></div>'; // Empty bottom-right corner
// Fetch and apply the current state
fetch('/api/current-state')
.then(response => response.json())
.then(data => {
data.forEach(pixel => {
if (pixel.color && pixel.color.hex_value) {
colorCell(`${pixel.x}${pixel.y}`, pixel.color.hex_value);
} else {
console.warn(`No color found for pixel at ${pixel.x}${pixel.y}`);
}
});
})
.catch(error => {
console.error('Error fetching current state:', error);
});
});