ストップウォッチを表示する
スペースキーを押すかストップウォッチをクリックするとスタート/ストップできる
コードめちゃくちゃなのでなんとかしたい
場所がかぶるとかの問題ではなく、両方ともCSSが効かなくなる
ページの本文1行目に deadline 300 のように書くと、300秒を過ぎたらタイマーが真っ赤になる
code:script.js
(() => {
const timerString = t => {
t = Math.floor(t);
const padZero = s => (s+'').padStart(2, '0');
const m = Math.floor(t / 60);
const s = t % 60;
return ${padZero(m)}:${padZero(s)};
};
const parseDeadline = () => {
// TODO: 可変にする
if (!scrapbox.Page || !scrapbox.Page.lines)
return undefined;
const deadlineLine = (() => {
const xs = scrapbox.Page.lines.map(line => line.text).filter(t => /^deadline/.test(t));
if (xs.length >= 1) return xs0; else return '';
})();
const arr = deadlineLine.match(/^deadline (\d+)/);
if (arr === null)
return undefined;
const deadLine = Number(arr1); return deadLine;
};
let timerElem = null;
let timerIntervalID = null;
let sec = 0;
let count = 0;
const deadline = parseDeadline();
if (deadline)
console.info(deadline is ${deadline} seconds);
else
console.info("deadline not set");
const refreshInterval = 100;
const incrementTime = () => {
count++;
if (count >= 10) {
count = 0;
sec++;
}
timerElem.textContent = timerString(sec);
if (deadline !== undefined && sec > deadline)
timerElem.classList.add('userjs-stopwatch-exceeded');
};
const toggleTimer = () => {
if (timerIntervalID === null) {
timerIntervalID = window.setInterval(incrementTime, refreshInterval);
} else {
window.clearInterval(timerIntervalID);
timerIntervalID = null;
}
timerElem.classList.toggle('userjs-stopwatch-stop');
};
const resetTimer = () => {
sec = 0;
timerElem.textContent = timerString(sec);
}
window.addEventListener('keyup', e => {
if (timerIntervalID === null) return;
if (e.key === ' ') toggleTimer();
//else if (e.key === 'Escape') resetTimer();
});
scrapbox.PageMenu.addItem({
title: 'Toggle stopwatch',
onClick: () => {
if (timerElem === null) {
timerElem = document.createElement('div');
timerElem.classList.add('userjs-stopwatch');
timerElem.classList.add('userjs-stopwatch-stop');
timerElem.textContent = timerString(sec);
timerElem.addEventListener('click', toggleTimer);
document.body.appendChild(timerElem);
} else {
if (timerIntervalID !== null)
window.clearInterval(timerIntervalID);
timerIntervalID = null;
timerElem.remove();
timerElem = null;
}
}
});
})();
code:style.css
.userjs-stopwatch {
background-color: white;
color: black;
font-size: 32pt;
position: fixed;
padding: 0 6px;
left: 0;
bottom: 0;
border: 1px solid black;
}
.userjs-stopwatch-stop {
background-color: black;
color: white;
}
.userjs-stopwatch-exceeded {
background-color: red;
color: white;
}