|
function attachStopWatch() { |
|
if (document.getElementById("stopwatch")) { |
|
// Already attached |
|
return; |
|
} |
|
const container = document.querySelectorAll("#ide-top-btns .flex.flex-none.cursor-pointer.items-center"); |
|
if (container.length > 0) { |
|
container[0].innerHTML = ""; |
|
container[0].appendChild(createStopWatchElement()); |
|
container[0].classList.add("stopwatch--parent"); |
|
} |
|
} |
|
|
|
function createStopWatchElement() { |
|
const root = document.createElement("div"); |
|
root.className = "stopwatch--root"; |
|
root.id = "stopwatch"; |
|
root.innerHTML = '<div class="css-1uwsqgo-TabHeaderRow e5i1odf3"><div class="stopwatch--content"><span class="stopwatch--label"></span> <span class="stopwatch--clock"></span></div></div>'; |
|
|
|
const stateNode = root.getElementsByClassName("stopwatch--label")[0]; |
|
const clockNode = root.getElementsByClassName("stopwatch--clock")[0]; |
|
|
|
const startCounting = function (startTimeMillis) { |
|
if (root.intervalId) { |
|
return; |
|
} |
|
localStorage.setItem(getStorageKey(), startTimeMillis); |
|
root.intervalId = setInterval(clockTick, 500, clockNode, startTimeMillis); |
|
stateNode.innerText = "Stop"; |
|
clockNode.innerText = toTimeString(getCurrentTimeInMillis() - startTimeMillis); |
|
} |
|
const stopCounting = function () { |
|
clearInterval(root.intervalId); |
|
root.intervalId = null; |
|
localStorage.removeItem(getStorageKey()); |
|
stateNode.innerText = "Start"; |
|
} |
|
|
|
const previousRunTime = localStorage.getItem(getStorageKey()); |
|
if (previousRunTime) { |
|
startCounting(parseInt(previousRunTime)); |
|
} else { |
|
stateNode.innerText = "Start"; |
|
clockNode.innerText = "00:00:00"; |
|
} |
|
|
|
root.onclick = function () { |
|
if (root.intervalId) { |
|
stopCounting(); |
|
} else { |
|
startCounting(getCurrentTimeInMillis()); |
|
} |
|
} |
|
const ONE_MIN = 60*1000; |
|
setTimeout(function() {startCounting(getCurrentTimeInMillis() - ONE_MIN)}, 2*ONE_MIN); |
|
|
|
return root; |
|
} |
|
|
|
function getStorageKey() { |
|
const path = location.pathname; |
|
const arr = path.split('/'); |
|
return "stopwatch_" + arr[2]; |
|
} |
|
|
|
function clockTick(clockNode, startTime) { |
|
const diff = getCurrentTimeInMillis() - startTime; |
|
clockNode.innerText = toTimeString(diff); |
|
} |
|
|
|
function getCurrentTimeInMillis() { |
|
return new Date().getTime(); |
|
} |
|
|
|
function toTimeString(time) { |
|
const hours = Math.floor(time / (1000 * 60 * 60)); |
|
const minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60)); |
|
const seconds = Math.floor((time % (1000 * 60)) / 1000); |
|
return pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2); |
|
} |
|
|
|
function pad(num, size) { |
|
var s = "000000000" + num; |
|
return s.substr(s.length - size); |
|
} |
|
|
|
setInterval(attachStopWatch, 1000); |