junkerstock
 簡易的な計算機13 

<!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; }
.time-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;
}

/* グラデーション記号 */
.buttons button:nth-child(4) { background-color: #FF3B30; color: white; }
.buttons button:nth-child(8) { background-color: #FF2D55; color: white; }
.buttons button:nth-child(12) { background-color: #AF52DE; color: white; }
.buttons button:nth-child(16) { background-color: #5856D6; color: white; }

/* =キー (通常時:青) */
#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="time-btn" id="btn-time" onclick="cycleTime()">分</button>
<button class="operator" 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" 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" 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" 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 btnTime = document.getElementById('btn-time');
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_v1';

// メモリモード管理
let isMemoryMode = 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 (isMemoryMode) {
if (!operators.includes(input) && input !== '.') {
memoryInput += input;
updateMemoryButtons();
}
return;
}

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

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

function toggleMemoryMode() {
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");
}

// =ボタン / Eボタンの処理
function handleEqual() {
// ■ Eキーとして動作 ■
if (isMemoryMode) {

// 【全合計計算】数字なしでEを押した場合
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;
// 式を作るために配列に保存 (例: "2", "4")
expressionParts.push(val);
});

// 式の文字列を作成 "2+4"
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.length > 1) {
setDisplayValue(currentVal.slice(0, -1));
} else {
setDisplayValue("0");
}
}

function cycleTime() {
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);
updateUnitDisplay();
} catch (e) {
setDisplayValue("Error");
}
}

function updateUnitDisplay() {
btnTime.innerText = unitNames[timeState];
}

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

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

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


使用変数

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