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.initElements();
this.initEventListeners();
this.resizeCanvas();
this.updateUI();
}
initElements() {
this.exportBtn = document.getElementById('export-btn');
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());
this.exportBtn.addEventListener('click', () => this.exportToCSV());
this.exportBtn.addEventListener('click', () => this.exportToCSV());
// 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;
}
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);
}
// Clear inputs
this.itemNameInput.value = '';
this.itemLengthInput.value = '';
this.itemWidthInput.value = '';
this.itemWeightInput.value = '';
this.itemQuantityInput.value = '1';
this.updateUI();
}
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();
}
}
updateUI() {
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);
row.innerHTML = `
Total
${totalArea.toFixed(1)} cm²
Used
${usedArea.toFixed(1)} cm²
Free
${freeArea.toFixed(1)} cm²
Max Weight
${containerWeight.toFixed(1)} kg
Used Weight
${usedWeight.toFixed(1)} kg
Free Weight
${freeWeight.toFixed(1)} kg
Weight Usage
${weightEfficiency}%
${weightEfficiency >= 100 ?
'OVER CAPACITY!' : ''}
Efficiency
${efficiency}%
${efficiency >= 100 ?
'FULL!' : ''}
`;
}
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
this.ctx.fillStyle = '#111827';
this.ctx.strokeStyle = '#374151';
this.ctx.lineWidth = 2;
this.ctx.fillRect(
this.offsetX,
this.offsetY,
this.containerWidth * this.scale,
this.containerHeight * this.scale
);
this.ctx.strokeRect(
this.offsetX,
this.offsetY,
this.containerWidth * this.scale,
this.containerHeight * this.scale
);
// 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.gridPackItems();
placements.forEach((placement, index) => {
const item = placement.item;
const fits = placement.fits;
if (!fits) {
// Draw overflow indicator
this.ctx.fillStyle = 'rgba(239, 68, 68, 0.2)';
this.ctx.strokeStyle = 'rgba(239, 68, 68, 0.5)';
this.ctx.lineWidth = 1;
this.ctx.fillRect(
this.offsetX + this.containerWidth * this.scale - 120,
this.offsetY + 20 + index * 25,
120,
20
);
this.ctx.strokeRect(
this.offsetX + this.containerWidth * this.scale - 120,
this.offsetY + 20 + index * 25,
120,
20
);
this.ctx.fillStyle = '#fff';
this.ctx.font = '10px Arial';
this.ctx.textAlign = 'center';
this.ctx.fillText(
`Overflow: ${item.name}`,
this.offsetX + this.containerWidth * this.scale - 60,
this.offsetY + 34 + index * 25
);
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
);
});
}
exportToCSV() {
if (this.items.length === 0) {
alert('No items to export');
return;
}
const headers = ['Item Name', 'Length (cm)', 'Width (cm)', 'Weight (kg)'];
const csvRows = [
headers.join(','),
...this.items.map(item =>
[item.name, item.length, item.width, item.weight]
.map(field => `"${field}"`) // quote fields to handle commas
.join(',')
)
];
const csvContent = csvRows.join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', `space-allocation-${new Date().toISOString().slice(0,10)}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
exportToCSV() {
if (this.items.length === 0) {
alert('No items to export');
return;
}
const headers = ['Item Name', 'Length (cm)', 'Width (cm)', 'Height (cm)', 'Weight (kg)'];
const csvRows = [
headers.join(','),
...this.items.map(item =>
[item.name, item.length, item.width, item.length, item.weight] // Using length for height since height isn't tracked separately
.map(field => `"${String(field).replace(/"/g, '""')}"`) // Proper CSV escaping
.join(',')
)
];
const csvContent = csvRows.join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', `space-allocation-${new Date().toISOString().slice(0,10)}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
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();
});