diff --git a/webroot/js/calculator.js b/webroot/js/calculator.js index 8fbc137..510fdfb 100644 --- a/webroot/js/calculator.js +++ b/webroot/js/calculator.js @@ -17,16 +17,32 @@ export class Calculator { const decStr = value.toString(10); const binStr = '0b' + value.toString(2); - // Update all calculator displays (for current active tab) - const inputs = document.querySelectorAll('[id*="calcInput"]'); - const hexElements = document.querySelectorAll('[id*="hexValue"]'); - const decElements = document.querySelectorAll('[id*="decValue"]'); - const binElements = document.querySelectorAll('[id*="binValue"]'); + // Update only the calculator inside the currently active tab to avoid duplicate-id issues + const activeContent = document.querySelector('.tab-content.active'); + if (!activeContent) { + // Fallback: try to update the first calculator on the page + const fallbackInput = document.querySelector('.calc-input-field'); + if (fallbackInput) fallbackInput.value = hexStr; + const fallbackHex = document.querySelector('.hex-value'); + if (fallbackHex) fallbackHex.textContent = hexStr; + const fallbackDec = document.querySelector('.dec-value'); + if (fallbackDec) fallbackDec.textContent = decStr; + const fallbackBin = document.querySelector('.bin-value'); + if (fallbackBin) fallbackBin.textContent = binStr; + return; + } - inputs.forEach(input => input.value = hexStr); - hexElements.forEach(el => el.textContent = hexStr); - decElements.forEach(el => el.textContent = decStr); - binElements.forEach(el => el.textContent = binStr); + const input = activeContent.querySelector('.calc-input-field'); + if (input) input.value = hexStr; + + const hexElement = activeContent.querySelector('.hex-value'); + if (hexElement) hexElement.textContent = hexStr; + + const decElement = activeContent.querySelector('.dec-value'); + if (decElement) decElement.textContent = decStr; + + const binElement = activeContent.querySelector('.bin-value'); + if (binElement) binElement.textContent = binStr; } input(digit) { @@ -47,7 +63,9 @@ export class Calculator { } operation(operation) { - if (this.state.previousValue !== 0 && !this.state.waitingForOperand) { + // If there is a pending operation and we are not waiting for a new operand, + // evaluate it first so chained operations work as expected. + if (this.state.operation !== null && !this.state.waitingForOperand) { this.equals(false); } @@ -166,7 +184,8 @@ export class Calculator { } else if (key === 'ENTER' || key === '=') { e.preventDefault(); this.equals(); - } else if (key === 'ESCAPE' || key === 'C') { + } else if (key === 'ESCAPE' || key === 'DELETE') { + // Use Escape or Delete to clear. Do not use 'C' since it collides with hex digit C. e.preventDefault(); this.clear(); } else if (key === 'BACKSPACE') { @@ -181,20 +200,20 @@ export class Calculator {