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.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; } 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 = ` ${item.name} ${item.length.toFixed(1)} cm ${item.width.toFixed(1)} cm ${item.area.toFixed(1)} cm² ${item.weight.toFixed(1)} kg `; 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 = `
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}%
Efficiency
${efficiency}%
`; } 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 ); }); } 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(); });