space-grid-wizard / script.js
excopstig's picture
🐳 27/08 - 12:50 - a warning "overflow" is displayed if an item is added which exceeds the remaining available space, can we change that to a pop warning that is displayed? or something that is more o
f02e764 verified
Raw History Blame Contribute Delete
20.2 kB
class Item {
constructor(name, length, width, weight) {
this.name = name;
this.length = parseFloat(length);
this.width = parseFloat(width);
this.weight = parseFloat(weight) || 0;
this.area = this.length * this.width;
}
}
class SpaceAllocator {
constructor() {
this.containerWidth = 600;
this.containerHeight = 250;
this.items = [];
this.canvas = document.getElementById('space-canvas');
this.ctx = this.canvas.getContext('2d');
this.scale = 1;
this.offsetX = 0;
this.offsetY = 0;
this.placements = [];
this.overflowItems = [];
this.initElements();
this.initEventListeners();
this.resizeCanvas();
this.updateUI();
}
initElements() {
this.containerWidthInput = document.getElementById('container-width');
this.containerHeightInput = document.getElementById('container-height');
this.containerWeightInput = document.getElementById('container-weight');
this.itemNameInput = document.getElementById('item-name');
this.itemLengthInput = document.getElementById('item-length');
this.itemWidthInput = document.getElementById('item-width');
this.itemWeightInput = document.getElementById('item-weight');
this.itemQuantityInput = document.getElementById('item-quantity');
this.addItemBtn = document.getElementById('add-item-btn');
this.removeItemBtn = document.getElementById('remove-item-btn');
this.updateContainerBtn = document.getElementById('update-container-btn');
this.clearAllBtn = document.getElementById('clear-all-btn');
this.itemsTable = document.getElementById('items-table');
this.spaceStats = document.getElementById('space-stats');
this.visualizationContainer = document.getElementById('visualization-container');
}
initEventListeners() {
// Set default container dimensions
this.containerWidthInput.value = this.containerWidth;
this.containerHeightInput.value = this.containerHeight;
// Button events
this.addItemBtn.addEventListener('click', () => this.addItem());
this.removeItemBtn.addEventListener('click', () => this.removeSelectedItem());
this.updateContainerBtn.addEventListener('click', () => this.updateContainer());
this.clearAllBtn.addEventListener('click', () => this.clearAll());
// Allow adding items with Enter key
this.itemNameInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.addItem();
});
this.itemLengthInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.addItem();
});
this.itemWidthInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.addItem();
});
this.itemWeightInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.addItem();
});
this.itemQuantityInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.addItem();
});
// Handle window resize
window.addEventListener('resize', () => {
this.resizeCanvas();
this.drawContainer();
});
// Initialize visualization
this.resizeCanvas();
this.drawContainer();
}
resizeCanvas() {
const container = this.visualizationContainer;
this.canvas.width = container.clientWidth;
this.canvas.height = container.clientHeight;
}
addItem() {
const name = this.itemNameInput.value.trim() || `Item ${this.items.length + 1}`;
const length = parseFloat(this.itemLengthInput.value);
const width = parseFloat(this.itemWidthInput.value);
const weight = parseFloat(this.itemWeightInput.value);
const quantity = parseInt(this.itemQuantityInput.value) || 1;
if (isNaN(length) || isNaN(width) || length <= 0 || width <= 0 || quantity <= 0) {
alert('Please enter valid positive numbers for length and width.');
return;
}
const newItemNames = [];
for (let i = 0; i < quantity; i++) {
const itemName = quantity > 1 ? `${name} #${i+1}` : name;
const item = new Item(itemName, length, width, weight);
this.items.push(item);
newItemNames.push(itemName);
}
// Clear inputs
this.itemNameInput.value = '';
this.itemLengthInput.value = '';
this.itemWidthInput.value = '';
this.itemWeightInput.value = '';
this.itemQuantityInput.value = '1';
this.updateUI();
// Show toast if newly added items overflow
if (this.overflowItems && this.overflowItems.length > 0) {
const overflowingNewItems = this.overflowItems
.filter(p => newItemNames.includes(p.item.name))
.map(p => p.item.name);
if (overflowingNewItems.length > 0) {
this.showToast(`⚠️ Not enough space for: ${overflowingNewItems.join(', ')}`, 'warning');
}
}
}
removeSelectedItem() {
const selectedRow = this.itemsTable.querySelector('tr.selected');
if (!selectedRow) {
alert('Please select an item to remove.');
return;
}
const itemName = selectedRow.getAttribute('data-name');
this.items = this.items.filter(item => item.name !== itemName);
this.updateUI();
}
updateContainer() {
const width = parseFloat(this.containerWidthInput.value);
const height = parseFloat(this.containerHeightInput.value);
if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0) {
alert('Please enter valid positive numbers for container dimensions.');
return;
}
this.containerWidth = width;
this.containerHeight = height;
this.updateUI();
}
clearAll() {
if (confirm('Are you sure you want to clear all items?')) {
this.items = [];
this.updateUI();
}
}
showToast(message, type = 'info') {
const container = document.getElementById('toast-container');
if (!container) return;
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.innerHTML = message;
container.appendChild(toast);
requestAnimationFrame(() => {
toast.classList.add('show');
});
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 4000);
}
updateUI() {
this.placements = this.gridPackItems();
this.overflowItems = this.placements.filter(p => !p.fits);
this.updateItemsTable();
this.updateSpaceStats();
this.drawContainer();
}
updateItemsTable() {
this.itemsTable.innerHTML = '';
this.items.forEach(item => {
const row = document.createElement('tr');
row.setAttribute('data-name', item.name);
const isOverflow = this.overflowItems && this.overflowItems.some(p => p.item.name === item.name);
if (isOverflow) {
row.classList.add('overflow-row');
}
row.innerHTML = `
<td class="p-2 border-b border-gray-600 ${isOverflow ? 'text-red-400 font-bold' : ''}">${isOverflow ? '⚠️ ' : ''}${item.name}</td>
<td class="p-2 border-b border-gray-600 text-center ${isOverflow ? 'text-red-400' : ''}">${item.length.toFixed(1)} cm</td>
<td class="p-2 border-b border-gray-600 text-center ${isOverflow ? 'text-red-400' : ''}">${item.width.toFixed(1)} cm</td>
<td class="p-2 border-b border-gray-600 text-center ${isOverflow ? 'text-red-400' : ''}">${item.area.toFixed(1)} cm²</td>
<td class="p-2 border-b border-gray-600 text-center ${isOverflow ? 'text-red-400' : ''}">${item.weight.toFixed(1)} kg</td>
`;
row.addEventListener('click', () => {
this.itemsTable.querySelectorAll('tr').forEach(r => r.classList.remove('selected'));
row.classList.add('selected');
});
this.itemsTable.appendChild(row);
});
}
updateSpaceStats() {
const totalArea = this.containerWidth * this.containerHeight;
const usedArea = this.items.reduce((sum, item) => sum + item.area, 0);
const freeArea = Math.max(0, totalArea - usedArea);
const efficiency = totalArea > 0 ? (usedArea / totalArea * 100).toFixed(1) : 0;
const containerWeight = parseFloat(this.containerWeightInput.value) || 7200;
const usedWeight = this.items.reduce((sum, item) => sum + item.weight, 0);
const freeWeight = Math.max(0, containerWeight - usedWeight);
const weightEfficiency = containerWeight > 0 ? (usedWeight / containerWeight * 100).toFixed(1) : 0;
this.spaceStats.innerHTML = `
<div class="grid grid-cols-4 gap-2 text-center">
<div>
<div class="text-sm text-gray-400">Total</div>
<div class="font-bold">${totalArea.toFixed(1)} cm²</div>
</div>
<div>
<div class="text-sm text-gray-400">Used</div>
<div class="font-bold">${usedArea.toFixed(1)} cm²</div>
</div>
<div>
<div class="text-sm text-gray-400">Free</div>
<div class="font-bold">${freeArea.toFixed(1)} cm²</div>
<div>
<div class="text-sm text-gray-400">Max Weight</div>
<div class="font-bold">${containerWeight.toFixed(1)} kg</div>
</div>
<div>
<div class="text-sm text-gray-400">Used Weight</div>
<div class="font-bold">${usedWeight.toFixed(1)} kg</div>
</div>
<div>
<div class="text-sm text-gray-400">Free Weight</div>
<div class="font-bold ${freeWeight < 0 ? 'text-red-500' : ''}">${freeWeight.toFixed(1)} kg</div>
</div>
</div>
</div>
<div class="mt-2">
<div class="text-sm text-gray-400 mb-1">Weight Usage</div>
<div class="w-full bg-gray-600 rounded-full h-2.5">
<div class="${usedWeight > containerWeight ? 'bg-red-600' : 'bg-green-600'} h-2.5 rounded-full" style="width: ${Math.min(100, weightEfficiency)}%"></div>
</div>
<div class="text-right text-sm mt-1">${weightEfficiency}%</div>
<div class="mt-2">
<div class="text-sm text-gray-400 mb-1">Efficiency</div>
<div class="w-full bg-gray-600 rounded-full h-2.5">
<div class="bg-blue-600 h-2.5 rounded-full" style="width: ${efficiency}%"></div>
</div>
<div class="text-right text-sm mt-1">${efficiency}%</div>
</div>
${this.overflowItems && this.overflowItems.length > 0 ? `
<div class="mt-3 p-3 bg-red-900 bg-opacity-40 border border-red-500 rounded-lg text-red-300 text-sm">
⚠️ <strong>Overflow!</strong> ${this.overflowItems.length} item(s) cannot fit: ${this.overflowItems.map(p => p.item.name).join(', ')}
</div>
` : ''}
`;
}
drawContainer() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// Calculate scale and offsets to maintain aspect ratio
this.scale = Math.min(
this.canvas.width / this.containerWidth,
this.canvas.height / this.containerHeight
) * 0.9; // 90% of available space
this.offsetX = (this.canvas.width - this.containerWidth * this.scale) / 2;
this.offsetY = (this.canvas.height - this.containerHeight * this.scale) / 2;
// Draw container
const hasOverflow = this.overflowItems && this.overflowItems.length > 0;
this.ctx.fillStyle = '#111827';
this.ctx.fillRect(
this.offsetX,
this.offsetY,
this.containerWidth * this.scale,
this.containerHeight * this.scale
);
if (hasOverflow) {
this.ctx.setLineDash([8, 4]);
this.ctx.strokeStyle = '#EF4444';
this.ctx.lineWidth = 3;
} else {
this.ctx.setLineDash([]);
this.ctx.strokeStyle = '#374151';
this.ctx.lineWidth = 2;
}
this.ctx.strokeRect(
this.offsetX,
this.offsetY,
this.containerWidth * this.scale,
this.containerHeight * this.scale
);
this.ctx.setLineDash([]);
// Draw grid
this.ctx.strokeStyle = 'rgba(55, 65, 81, 0.5)';
this.ctx.lineWidth = 1;
const gridSize = 50; // cm
const gridStep = gridSize * this.scale;
for (let x = this.offsetX; x <= this.offsetX + this.containerWidth * this.scale; x += gridStep) {
this.ctx.beginPath();
this.ctx.moveTo(x, this.offsetY);
this.ctx.lineTo(x, this.offsetY + this.containerHeight * this.scale);
this.ctx.stroke();
}
for (let y = this.offsetY; y <= this.offsetY + this.containerHeight * this.scale; y += gridStep) {
this.ctx.beginPath();
this.ctx.moveTo(this.offsetX, y);
this.ctx.lineTo(this.offsetX + this.containerWidth * this.scale, y);
this.ctx.stroke();
}
// Draw items
const colors = [
'#3B82F6', '#10B981', '#F59E0B', '#EF4444',
'#8B5CF6', '#EC4899', '#14B8A6', '#F97316'
];
const placements = this.placements;
let overflowIndex = 0;
// Draw overflow warning banner at top of canvas
if (hasOverflow) {
const bannerHeight = 30;
this.ctx.fillStyle = 'rgba(220, 38, 38, 0.95)';
this.ctx.fillRect(0, 0, this.canvas.width, bannerHeight);
this.ctx.fillStyle = '#fff';
this.ctx.font = 'bold 13px Arial';
this.ctx.textAlign = 'center';
this.ctx.fillText(
`⚠️ OVERFLOW: ${this.overflowItems.length} item(s) cannot fit in container`,
this.canvas.width / 2,
20
);
}
placements.forEach((placement, index) => {
const item = placement.item;
const fits = placement.fits;
if (!fits) {
// Draw overflow item outside container with prominent styling
const overflowAreaX = this.offsetX + this.containerWidth * this.scale + 10;
const overflowBoxWidth = Math.min(160, this.canvas.width - overflowAreaX - 5);
const overflowBoxHeight = 40;
const overflowY = this.offsetY + 10 + overflowIndex * (overflowBoxHeight + 6);
if (overflowAreaX + overflowBoxWidth <= this.canvas.width && overflowY + overflowBoxHeight <= this.canvas.height) {
this.ctx.save();
this.ctx.setLineDash([6, 3]);
this.ctx.fillStyle = 'rgba(239, 68, 68, 0.15)';
this.ctx.strokeStyle = '#EF4444';
this.ctx.lineWidth = 2;
this.ctx.fillRect(overflowAreaX, overflowY, overflowBoxWidth, overflowBoxHeight);
this.ctx.strokeRect(overflowAreaX, overflowY, overflowBoxWidth, overflowBoxHeight);
this.ctx.setLineDash([]);
this.ctx.restore();
this.ctx.fillStyle = '#FCA5A5';
this.ctx.font = 'bold 11px Arial';
this.ctx.textAlign = 'left';
this.ctx.fillText(`⚠ ${item.name}`, overflowAreaX + 5, overflowY + 15);
this.ctx.fillStyle = '#EF4444';
this.ctx.font = '9px Arial';
this.ctx.fillText(`${item.length.toFixed(0)}×${item.width.toFixed(0)} cm (no fit)`, overflowAreaX + 5, overflowY + 30);
}
overflowIndex++;
return;
}
const color = colors[index % colors.length];
const x = this.offsetX + placement.x_cm * this.scale;
const y = this.offsetY + placement.y_cm * this.scale;
const width = placement.w_cm * this.scale;
const height = placement.h_cm * this.scale;
// Draw item rectangle
this.ctx.fillStyle = color;
this.ctx.strokeStyle = '#1F2937';
this.ctx.lineWidth = 1;
this.ctx.fillRect(x, y, width, height);
this.ctx.strokeRect(x, y, width, height);
// Draw item label
this.ctx.fillStyle = '#fff';
this.ctx.font = 'bold 10px Arial';
this.ctx.textAlign = 'left';
this.ctx.fillText(
`${item.name} (${item.length.toFixed(0)}×${item.width.toFixed(0)})`,
x + 5,
y + 15
);
});
}
gridPackItems(cellSize = 5) {
const cols = Math.max(1, Math.floor(this.containerWidth / cellSize));
const rows = Math.max(1, Math.floor(this.containerHeight / cellSize));
const grid = Array(rows).fill().map(() => Array(cols).fill(false));
const findSpace = (wCells, hCells) => {
for (let r = 0; r <= rows - hCells; r++) {
for (let c = 0; c <= cols - wCells; c++) {
let spaceAvailable = true;
for (let dr = 0; dr < hCells; dr++) {
for (let dc = 0; dc < wCells; dc++) {
if (grid[r + dr][c + dc]) {
spaceAvailable = false;
break;
}
}
if (!spaceAvailable) break;
}
if (spaceAvailable) return { r, c };
}
}
return null;
};
const placements = [];
const sortedItems = [...this.items].sort((a, b) => b.area - a.area);
for (const item of sortedItems) {
const wCells = Math.max(1, Math.floor(item.length / cellSize));
const hCells = Math.max(1, Math.floor(item.width / cellSize));
const pos = findSpace(wCells, hCells);
if (!pos) {
placements.push({
item,
x_cm: null,
y_cm: null,
w_cm: item.length,
h_cm: item.width,
fits: false
});
continue;
}
const { r, c } = pos;
for (let dr = 0; dr < hCells; dr++) {
for (let dc = 0; dc < wCells; dc++) {
grid[r + dr][c + dc] = true;
}
}
placements.push({
item,
x_cm: c * cellSize,
y_cm: r * cellSize,
w_cm: item.length,
h_cm: item.width,
fits: true
});
}
return placements;
}
}
// Initialize the app when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
new SpaceAllocator();
});