junkerstock
 簡易的な計算機14 

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>最強の電卓</title>
<style>
/* 基本設定 */
* {
box-sizing: border-box;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
}
body {
margin: 0;
padding: 0;
height: 100dvh;
width: 100vw;
display: flex;
flex-direction: column;
background-color: #000;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
overflow: hidden;
}

/* 画面上部エリア */
#display-container {
flex: 1;
display: flex;
flex-direction: column;
justify-content: flex-end;
padding: 20px;
padding-bottom: 10px;
overflow: hidden;
}

/* 履歴表示エリア */
#history {
width: 100%;
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: flex-end;
color: #888;
font-size: 0.9rem;
line-height: 1.4;
padding-bottom: 5px;
margin-bottom: 5px;
border-bottom: 1px solid #333;
}

.history-item {
font-family: monospace;
display: flex;
align-items: center;
gap: 10px;
width: 100%;
justify-content: flex-end;
}

.m-tag {
color: #FFD60A;
font-weight: bold;
display: inline-block;
min-width: 30px;
text-align: right;
}

/* メイン数値表示部分 */
#display {
width: 100%;
color: white;
font-size: 3.5rem;
font-weight: 300;
text-align: right;
word-break: break-all;
line-height: 1.1;
max-height: calc(3.5rem * 1.1 * 2);
overflow-y: auto;
flex-shrink: 0;
}

#display::-webkit-scrollbar, #history::-webkit-scrollbar {
display: none;
}

/* ボタンエリア */
.buttons {
height: 55%;
padding-bottom: env(safe-area-inset-bottom);
margin-bottom: 10px;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: repeat(5, 1fr);
gap: 8px;
padding-left: 15px;
padding-right: 15px;
}

button {
border: none;
font-size: 1.7rem;
border-radius: 1000px;
cursor: pointer;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.1s;
height: 100%;
}

button:active {
filter: brightness(1.2);
transform: scale(0.98);
}

.number { background-color: #333333; }
.func { background-color: #a5a5a5; color: black; font-weight: 500; }

/* 切替ボタン */
.shift-btn {
background-color: #a5a5a5;
color: black;
font-size: 1.2rem;
font-weight: bold;
}

.m-key {
background-color: #FFD60A;
color: black;
font-weight: bold;
}

.mode-active-green {
background-color: #30d158 !important;
color: white !important;
font-weight: bold;
}

.shift-active {
background-color: #fff !important;
color: #000 !important;
}

/* --- 通常モードのボタン色(グラデーション) --- */
#btn-div { background-color: #FF3B30; color: white; transition: background-color 0.3s; }
#btn-mul { background-color: #FF2D55; color: white; transition: background-color 0.3s; }
#btn-sub { background-color: #AF52DE; color: white; transition: background-color 0.3s; }
#btn-add { background-color: #5856D6; color: white; transition: background-color 0.3s; }

/* --- 切替モード時のボタン色(新デザイン) --- */
/* 時間: シアン */
.style-time { background-color: #32ADE6 !important; color: black !important; font-weight: bold; }
/* 進数: パープル */
.style-hex { background-color: #BF5AF2 !important; color: white !important; font-weight: bold; }
/* かっこ: イエロー */
.style-paren { background-color: #FFCC00 !important; color: black !important; font-weight: bold; }

/* =キー */
#btn-equal {
background-color: #007AFF;
color: white;
}

</style>
</head>
<body>

<div id="display-container">
<div id="history"></div>
<div id="display">0</div>
</div>

<div class="buttons">
<button class="func" id="btn-clear" onclick="handleClear()">C</button>
<button class="func" onclick="deleteLast()">←</button>

<button class="shift-btn" id="btn-shift" onclick="toggleShiftMode()">切替</button>

<button class="operator" id="btn-div" onclick="appendDisplay('/')">÷</button>

<button class="number" onclick="appendDisplay('7')">7</button>
<button class="number" onclick="appendDisplay('8')">8</button>
<button class="number" onclick="appendDisplay('9')">9</button>
<button class="operator" id="btn-mul" onclick="appendDisplay('*')">×</button>

<button class="number" onclick="appendDisplay('4')">4</button>
<button class="number" onclick="appendDisplay('5')">5</button>
<button class="number" onclick="appendDisplay('6')">6</button>
<button class="operator" id="btn-sub" onclick="appendDisplay('-')">−</button>

<button class="number" onclick="appendDisplay('1')">1</button>
<button class="number" onclick="appendDisplay('2')">2</button>
<button class="number" onclick="appendDisplay('3')">3</button>
<button class="operator" id="btn-add" onclick="appendDisplay('+')">+</button>

<button class="m-key" id="btn-m" onclick="toggleMemoryMode()">M</button>
<button class="number" onclick="appendDisplay('0')">0</button>
<button class="number" onclick="appendDisplay('.')">.</button>
<button class="operator" id="btn-equal" onclick="handleEqual()">=</button>
</div>

<script>
const display = document.getElementById('display');
const historyDiv = document.getElementById('history');

const btnShift = document.getElementById('btn-shift');
const btnDiv = document.getElementById('btn-div');
const btnMul = document.getElementById('btn-mul');
const btnSub = document.getElementById('btn-sub');
const btnAdd = document.getElementById('btn-add');
const btnEqual = document.getElementById('btn-equal');
const btnClear = document.getElementById('btn-clear');
const btnM = document.getElementById('btn-m');

const operators = ['/', '*', '-', '+'];
const unitNames = ["分", "時間", "日", "年", "秒"];
let timeState = 0;

let historyList = [];
const STORAGE_KEY = 'super_calculator_history_v3';

let isMemoryMode = false;
let isShiftMode = false;
let memoryInput = "";

// 履歴ロード
window.addEventListener('DOMContentLoaded', () => {
const savedData = localStorage.getItem(STORAGE_KEY);
if (savedData) {
try {
historyList = JSON.parse(savedData);
renderHistory();
} catch (e) {
historyList = [];
}
}
});

function saveHistory() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(historyList));
}

function getDisplayValue() {
return display.innerText;
}

function setDisplayValue(val) {
display.innerText = val;
}

function renderHistory() {
historyDiv.innerHTML = "";
historyList.forEach((item, index) => {
const div = document.createElement('div');
div.className = 'history-item';
const mNumber = index + 1;
div.innerHTML = `<span>${item.text} = ${item.result}</span> <span class="m-tag">M${mNumber}</span>`;
historyDiv.appendChild(div);
});
historyDiv.scrollTop = historyDiv.scrollHeight;
}

function appendDisplay(input) {
// エラー表示中は操作を受け付けない、またはリセットしてから
if (getDisplayValue() === "ERROR") {
setDisplayValue("0");
}

if (isMemoryMode) {
if (!operators.includes(input) && input !== '.' && input !== '(' && input !== ')') {
memoryInput += input;
updateMemoryButtons();
}
return;
}

const currentVal = getDisplayValue();
const lastChar = currentVal.slice(-1);

if (currentVal === '0' && !operators.includes(input) && input !== '.') {
setDisplayValue(input);
return;
}

// かっこ入力の例外:記号の後にかっこはOK、数値の後にかっこはNG(バリデーションで弾くが入力はさせる)
if (operators.includes(input) && operators.includes(lastChar)) {
// ただし、かっこ関連は許可するなどの制御が必要だが、
// 基本的にはバリデーションで弾くのでここでは簡易チェックのみ
// 例: * のあとに - (マイナス) はOKとするか?今回はシンプルにするため
// 記号連続は弾くが、かっこは記号リストに入れていないので素通りして入力される
return;
}

setDisplayValue(currentVal + input);
}

function toggleShiftMode() {
isShiftMode = !isShiftMode;

if (isShiftMode) {
btnShift.classList.add("shift-active");

// --- スタイル適用 ---
btnDiv.className = "operator style-time";
btnMul.className = "operator style-hex";
btnSub.className = "operator style-paren";
btnAdd.className = "operator style-paren";

// --- 機能変更 ---
btnDiv.innerText = unitNames[timeState];
btnDiv.style.fontSize = "1.2rem";
btnDiv.onclick = cycleTime;

btnMul.innerText = "進数";
btnMul.style.fontSize = "1.2rem";
btnMul.onclick = () => { };

btnSub.innerText = "(";
btnSub.onclick = () => appendDisplay('(');

btnAdd.innerText = ")";
btnAdd.onclick = () => appendDisplay(')');

} else {
btnShift.classList.remove("shift-active");

// --- スタイル戻し ---
btnDiv.className = "operator"; // IDによる色が適用される
btnMul.className = "operator";
btnSub.className = "operator";
btnAdd.className = "operator";

// --- 機能戻し ---
btnDiv.innerText = "÷";
btnDiv.style.fontSize = "1.7rem"; // 元のサイズに戻す
btnDiv.onclick = () => appendDisplay('/');

btnMul.innerText = "×";
btnMul.style.fontSize = "1.7rem";
btnMul.onclick = () => appendDisplay('*');

btnSub.innerText = "−";
btnSub.onclick = () => appendDisplay('-');

btnAdd.innerText = "+";
btnAdd.onclick = () => appendDisplay('+');
}
}

function cycleTime() {
if (!isShiftMode) return;
if (isMemoryMode) return;

try {
let val = parseFloat(eval(getDisplayValue()));

if (timeState === 0) val = val / 60;
else if (timeState === 1) val = val / 24;
else if (timeState === 2) val = val / 365;
else if (timeState === 3) val = val * 365 * 24 * 60 * 60;
else if (timeState === 4) val = val / 60;

timeState++;
if (timeState >= unitNames.length) timeState = 0;

setDisplayValue(val);
btnDiv.innerText = unitNames[timeState];

} catch (e) {
showError();
}
}

function toggleMemoryMode() {
if (isShiftMode) toggleShiftMode();

if (isMemoryMode) {
endMemoryMode();
} else {
isMemoryMode = true;
memoryInput = "";
btnM.style.filter = "brightness(0.8)";
btnEqual.classList.add("mode-active-green");
btnClear.classList.add("mode-active-green");
updateMemoryButtons();
}
}

function updateMemoryButtons() {
if (memoryInput === "") {
btnEqual.innerText = "E";
btnClear.innerText = "C";
} else {
btnEqual.innerText = "E(" + memoryInput + ")";
btnClear.innerText = "C(" + memoryInput + ")";
}
}

function endMemoryMode() {
isMemoryMode = false;
memoryInput = "";
btnM.style.filter = "none";
btnEqual.innerText = "=";
btnEqual.classList.remove("mode-active-green");
btnClear.innerText = "C";
btnClear.classList.remove("mode-active-green");
}

function handleClear() {
if (isMemoryMode) {
if (memoryInput === "") {
if (confirm("MEMORY ALL CLEAR OK?")) {
historyList = [];
saveHistory();
renderHistory();
endMemoryMode();
}
return;
}
if (memoryInput !== "") {
const targetIndex = parseInt(memoryInput) - 1;
if (targetIndex >= 0 && targetIndex < historyList.length) {
historyList.splice(targetIndex, 1);
saveHistory();
renderHistory();
endMemoryMode();
} else {
memoryInput = "";
updateMemoryButtons();
}
}
return;
}
setDisplayValue("0");
}

function handleEqual() {
if (isMemoryMode) {
if (memoryInput === "") {
if (historyList.length === 0) {
endMemoryMode();
return;
}
if (confirm("MEMORY ALL SUM OK?")) {
let totalSum = 0;
let expressionParts = [];
historyList.forEach(item => {
const val = Number(item.result);
totalSum += val;
expressionParts.push(val);
});

const sumExpression = expressionParts.join("+");
historyList.push({ text: sumExpression, result: totalSum });
saveHistory();
renderHistory();
endMemoryMode();

const currentVal = getDisplayValue();
if (currentVal === "0") {
setDisplayValue(totalSum);
} else {
setDisplayValue(currentVal + totalSum);
}
}
return;
}

const targetIndex = parseInt(memoryInput) - 1;
if (targetIndex >= 0 && targetIndex < historyList.length) {
endMemoryMode();
const val = historyList[targetIndex].result;
const currentVal = getDisplayValue();
if (currentVal === "0") {
setDisplayValue(val);
} else {
setDisplayValue(currentVal + val);
}
} else {
endMemoryMode();
}
return;
}

calculateResult();
}

function deleteLast() {
if (isMemoryMode) {
memoryInput = memoryInput.slice(0, -1);
updateMemoryButtons();
return;
}
const currentVal = getDisplayValue();
if (currentVal === "ERROR") {
setDisplayValue("0");
return;
}
if (currentVal.length > 1) {
setDisplayValue(currentVal.slice(0, -1));
} else {
setDisplayValue("0");
}
}

// --- エラー表示用関数 ---
function showError() {
setDisplayValue("ERROR");
setTimeout(() => {
// まだERROR表示のままなら0に戻す(ユーザーが別の入力をしていたら消さない)
if (getDisplayValue() === "ERROR") {
setDisplayValue("0");
}
}, 1500);
}

// --- 計算前のバリデーション関数 ---
function validateExpression(expr) {
// 1. かっこの数が合わない
const openParens = (expr.match(/\(/g) || []).length;
const closeParens = (expr.match(/\)/g) || []).length;
if (openParens !== closeParens) return false;

// 2. 数値の直後に ( がある (例: 99( )
// 正規表現: 数字またはドットの後に、空白(任意)があり、( が続く
if (/[0-9.]\s*\(/.test(expr)) return false;

// 3. ) の直後に数値がある (例: )99 )
// 正規表現: ) の後に、空白(任意)があり、数字またはドットが続く
if (/\)\s*[0-9.]/.test(expr)) return false;

// 4. 空のかっこ () がある (計算不能)
if (/\(\s*\)/.test(expr)) return false;

return true;
}

function calculateResult() {
let expression = getDisplayValue();

// ★ バリデーション実行
if (!validateExpression(expression)) {
showError();
return;
}

try {
let result = new Function('return ' + expression)();

// 結果がNaNやInfinityになった場合もエラー扱いにする
if (!isFinite(result) || isNaN(result)) {
showError();
return;
}

historyList.push({ text: expression, result: result });
saveHistory();

renderHistory();
setDisplayValue(result);
} catch (error) {
showError();
}
}
</script>
</body>
</html>


使用変数

appendDisplay -------( Function )
btnAdd
btnClear
btnDiv
btnEqual
btnM
btnMul
btnShift
btnSub
calculateResult -------( Function )
charset
class
className
closeParens
content
currentVal
cycleTime -------( Function )
deleteLast -------( Function )
display
div
endMemoryMode -------( Function )
expression
expressionParts
filter
fit
fontSize
getDisplayValue -------( Function )
handleClear -------( Function )
handleEqual -------( Function )
historyDiv
historyList
id
innerHTML
innerText
isMemoryMode
isShiftMode
item
lang
lastChar
length
memoryInput
mNumber
name
onclick
openParens
operators
renderHistory -------( Function )
result
savedData
saveHistory -------( Function )
scalable
scale
scrollTop
setDisplayValue -------( Function )
showError -------( Function )
STORAGE_KEY
sumExpression
targetIndex
timeState
toggleMemoryMode -------( Function )
toggleShiftMode -------( Function )
totalSum
unitNames
updateMemoryButtons -------( Function )
val
validateExpression -------( Function )
width