Fix no-var problems (ESLint), run formatter on JS

This commit is contained in:
Hans5958 2022-04-16 19:44:50 +07:00
parent 4be8a36839
commit 2e728ef20f
9 changed files with 920 additions and 920 deletions

View file

@ -15,20 +15,20 @@
window.addEventListener("error", function (e) { window.addEventListener("error", function (e) {
console.log(e); console.log(e);
var errorMessage = "<p class=\"error\">An error has occurred:</p>"; let errorMessage = "<p class=\"error\">An error has occurred:</p>";
errorMessage += "<p class=\"errorBody\">" + e.message + "</p>"; errorMessage += "<p class=\"errorBody\">" + e.message + "</p>";
errorMessage += "<p class=\"errorBody\">on line " + e.lineno + "</p>"; errorMessage += "<p class=\"errorBody\">on line " + e.lineno + "</p>";
errorMessage += "<p class=\"error\">If this keeps happening, feel free to tell us on <a href=\"https://discord.gg/pJkm23b2nA\">our Discord server</a>.</p>"; errorMessage += "<p class=\"error\">If this keeps happening, feel free to tell us on <a href=\"https://discord.gg/pJkm23b2nA\">our Discord server</a>.</p>";
document.getElementById("loadingContent").innerHTML = errorMessage; document.getElementById("loadingContent").innerHTML = errorMessage;
}); });
function getPositionOfEntry(entry){ function getPositionOfEntry(entry) {
let startX = 2000, startY = 2000; let startX = 2000, startY = 2000;
for(const [x, y] of entry.path){ for (const [x, y] of entry.path) {
startX = Math.min(x, startX); startX = Math.min(x, startX);
startY = Math.min(y, startY) startY = Math.min(y, startY)
} }
if(startX === 2000 || startY === 2000) return null; if (startX === 2000 || startY === 2000) return null;
return [parseInt(startX), parseInt(startY)]; return [parseInt(startX), parseInt(startY)];
} }
@ -36,25 +36,25 @@ const areaMap = new Map();
// Modified from https://stackoverflow.com/a/33670691 // Modified from https://stackoverflow.com/a/33670691
function calcPolygonArea(vertices) { function calcPolygonArea(vertices) {
var hit = areaMap.get(vertices); const hit = areaMap.get(vertices);
if (hit != null) { if (hit != null) {
return hit; return hit;
} }
var total = 0; let total = 0;
for (var i = 0, l = vertices.length; i < l; i++) { for (let i = 0, l = vertices.length; i < l; i++) {
var addX = vertices[i][0]; const addX = vertices[i][0];
var addY = vertices[i == vertices.length - 1 ? 0 : i + 1][1]; const addY = vertices[i == vertices.length - 1 ? 0 : i + 1][1];
var subX = vertices[i == vertices.length - 1 ? 0 : i + 1][0]; const subX = vertices[i == vertices.length - 1 ? 0 : i + 1][0];
var subY = vertices[i][1]; const subY = vertices[i][1];
total += (addX * addY * 0.5); total += (addX * addY * 0.5);
total -= (subX * subY * 0.5); total -= (subX * subY * 0.5);
} }
var area = Math.floor(Math.abs(total)); const area = Math.floor(Math.abs(total));
areaMap.set(vertices, area); areaMap.set(vertices, area);
return area; return area;
} }

View file

@ -13,96 +13,96 @@
======================================================================== ========================================================================
*/ */
var finishButton = document.getElementById("finishButton"); const finishButton = document.getElementById("finishButton");
var resetButton = document.getElementById("resetButton"); const resetButton = document.getElementById("resetButton");
var undoButton = document.getElementById("undoButton"); const undoButton = document.getElementById("undoButton");
var redoButton = document.getElementById("redoButton"); const redoButton = document.getElementById("redoButton");
var highlightUnchartedLabel = document.getElementById("highlightUnchartedLabel"); const highlightUnchartedLabel = document.getElementById("highlightUnchartedLabel");
var entryId = 0 let entryId = 0
var objectInfoBox = document.getElementById("objectInfo"); const objectInfoBox = document.getElementById("objectInfo");
var hintText = document.getElementById("hint"); const hintText = document.getElementById("hint");
var periodsStatus = document.getElementById('periodsStatus') const periodsStatus = document.getElementById('periodsStatus')
var periodGroups = document.getElementById('periodGroups') const periodGroups = document.getElementById('periodGroups')
var periodGroupTemplate = document.getElementById('period-group').content.firstElementChild.cloneNode(true) const periodGroupTemplate = document.getElementById('period-group').content.firstElementChild.cloneNode(true)
var periodsAdd = document.getElementById('periodsAdd') const periodsAdd = document.getElementById('periodsAdd')
var exportButton = document.getElementById("exportButton"); const exportButton = document.getElementById("exportButton");
var cancelButton = document.getElementById("cancelButton"); const cancelButton = document.getElementById("cancelButton");
var exportOverlay = document.getElementById("exportOverlay"); const exportOverlay = document.getElementById("exportOverlay");
var exportCloseButton = document.getElementById("exportCloseButton"); const exportCloseButton = document.getElementById("exportCloseButton");
var exportBackButton = document.getElementById("exportBackButton") const exportBackButton = document.getElementById("exportBackButton")
var path = []; let path = [];
var center = [1000, 1000]; let center = [1000, 1000];
var pathWithPeriods = [] let pathWithPeriods = []
var periodGroupElements = [] let periodGroupElements = []
var disableDrawingOverride = false let disableDrawingOverride = false
var drawing = true; let drawing = true;
var periodClipboard = { const periodClipboard = {
"index": null, "index": null,
"path": null "path": null
} }
;[...document.querySelectorAll("#drawControlsContainer textarea")].forEach(el => { ;[...document.querySelectorAll("#drawControlsContainer textarea")].forEach(el => {
el.addEventListener("input", function() { el.addEventListener("input", function () {
this.style.height = "auto"; this.style.height = "auto";
this.style.height = (this.scrollHeight) + "px" this.style.height = (this.scrollHeight) + "px"
})
}) })
})
function initDraw(){ function initDraw() {
wrapper.classList.remove('listHidden') wrapper.classList.remove('listHidden')
window.render = render window.render = render
window.renderBackground = renderBackground window.renderBackground = renderBackground
window.updateHovering = updateHovering window.updateHovering = updateHovering
// var startPeriodField = document.getElementById('startPeriodField') // let startPeriodField = document.getElementById('startPeriodField')
// var endPeriodField = document.getElementById('endPeriodField') // let endPeriodField = document.getElementById('endPeriodField')
// var periodVisbilityInfo = document.getElementById('periodVisbilityInfo') // let periodVisbilityInfo = document.getElementById('periodVisbilityInfo')
var rShiftPressed = false; let rShiftPressed = false;
var lShiftPressed = false; let lShiftPressed = false;
var shiftPressed = false; let shiftPressed = false;
var highlightUncharted = true; let highlightUncharted = true;
renderBackground(); renderBackground();
applyView(); applyView();
container.style.cursor = "crosshair"; container.style.cursor = "crosshair";
var undoHistory = []; let undoHistory = [];
render(path); render(path);
container.addEventListener("mousedown", function(e){ container.addEventListener("mousedown", function (e) {
lastPos = [ lastPos = [
e.clientX, e.clientX,
e.clientY e.clientY
]; ];
}); });
function getCanvasCoords(x, y){ function getCanvasCoords(x, y) {
x = x - container.offsetLeft; x = x - container.offsetLeft;
y = y - container.offsetTop; y = y - container.offsetTop;
var pos = [ const pos = [
~~((x - (container.clientWidth/2 - innerContainer.clientWidth/2 + zoomOrigin[0]))/zoom)+0.5, ~~((x - (container.clientWidth / 2 - innerContainer.clientWidth / 2 + zoomOrigin[0])) / zoom) + 0.5,
~~((y - (container.clientHeight/2 - innerContainer.clientHeight/2 + zoomOrigin[1]))/zoom)+0.5 ~~((y - (container.clientHeight / 2 - innerContainer.clientHeight / 2 + zoomOrigin[1])) / zoom) + 0.5
]; ];
if(shiftPressed && path.length > 0){ if (shiftPressed && path.length > 0) {
var previous = path[path.length-1]; const previous = path[path.length - 1];
if(Math.abs(pos[1] - previous[1]) > Math.abs(pos[0] - previous[0]) ){ if (Math.abs(pos[1] - previous[1]) > Math.abs(pos[0] - previous[0])) {
pos[0] = previous[0]; pos[0] = previous[0];
} else { } else {
pos[1] = previous[1]; pos[1] = previous[1];
@ -112,13 +112,13 @@ function initDraw(){
return pos; return pos;
} }
container.addEventListener("mouseup", function(e){ container.addEventListener("mouseup", function (e) {
if(Math.abs(lastPos[0] - e.clientX) + Math.abs(lastPos[1] - e.clientY) <= 4 && drawing){
var coords = getCanvasCoords(e.clientX, e.clientY); if (Math.abs(lastPos[0] - e.clientX) + Math.abs(lastPos[1] - e.clientY) <= 4 && drawing) {
const coords = getCanvasCoords(e.clientX, e.clientY);
path.push(coords); path.push(coords);
render(path); render(path);
@ -126,7 +126,7 @@ function initDraw(){
redoButton.disabled = true; redoButton.disabled = true;
undoButton.disabled = false; undoButton.disabled = false;
if(path.length >= 3){ if (path.length >= 3) {
finishButton.disabled = false; finishButton.disabled = false;
} }
@ -134,68 +134,68 @@ function initDraw(){
} }
}); });
window.addEventListener("mousemove", function(e){ window.addEventListener("mousemove", function (e) {
if(!dragging && drawing && path.length > 0){
var coords = getCanvasCoords(e.clientX, e.clientY); if (!dragging && drawing && path.length > 0) {
const coords = getCanvasCoords(e.clientX, e.clientY);
render(path.concat([coords])); render(path.concat([coords]));
} }
}); });
window.addEventListener("keyup", function(e){ window.addEventListener("keyup", function (e) {
if(e.key == "Enter"){ if (e.key == "Enter") {
finish(); finish();
} else if(e.key == "z" && e.ctrlKey){ } else if (e.key == "z" && e.ctrlKey) {
undo(); undo();
} else if(e.key == "y" && e.ctrlKey){ } else if (e.key == "y" && e.ctrlKey) {
redo(); redo();
} else if(e.key == "Escape"){ } else if (e.key == "Escape") {
exportOverlay.style.display = "none"; exportOverlay.style.display = "none";
} else if (e.key === "Shift" ){ } else if (e.key === "Shift") {
if(e.code === "ShiftRight"){ if (e.code === "ShiftRight") {
rShiftPressed = false; rShiftPressed = false;
} else if(e.code === "ShiftLeft"){ } else if (e.code === "ShiftLeft") {
lShiftPressed = false; lShiftPressed = false;
} }
shiftPressed = rShiftPressed || lShiftPressed; shiftPressed = rShiftPressed || lShiftPressed;
} }
}); });
window.addEventListener("keydown", function(e){ window.addEventListener("keydown", function (e) {
if (e.key === "Shift" ){ if (e.key === "Shift") {
if(e.code === "ShiftRight"){ if (e.code === "ShiftRight") {
rShiftPressed = true; rShiftPressed = true;
} else if(e.code === "ShiftLeft"){ } else if (e.code === "ShiftLeft") {
lShiftPressed = true; lShiftPressed = true;
} }
shiftPressed = rShiftPressed || lShiftPressed; shiftPressed = rShiftPressed || lShiftPressed;
} }
}); });
finishButton.addEventListener("click", function(e){ finishButton.addEventListener("click", function (e) {
finish(); finish();
}); });
undoButton.addEventListener("click", function(e){ undoButton.addEventListener("click", function (e) {
undo(); undo();
}); });
redoButton.addEventListener("click", function(e){ redoButton.addEventListener("click", function (e) {
redo(); redo();
}); });
resetButton.addEventListener("click", function(e){ resetButton.addEventListener("click", function (e) {
reset(); reset();
}); });
cancelButton.addEventListener("click", function(e){ cancelButton.addEventListener("click", function (e) {
back(); back();
}); });
document.getElementById("nameField").addEventListener("keyup", function(e){ document.getElementById("nameField").addEventListener("keyup", function (e) {
if(e.key == "Enter"){ if (e.key == "Enter") {
exportJson(); exportJson();
} }
}); });
@ -212,27 +212,27 @@ function initDraw(){
// } // }
// }); // });
exportButton.addEventListener("click", function(e){ exportButton.addEventListener("click", function (e) {
exportJson(); exportJson();
}); });
exportCloseButton.addEventListener("click", function(e){ exportCloseButton.addEventListener("click", function (e) {
reset(); reset();
exportOverlay.style.display = "none"; exportOverlay.style.display = "none";
}); });
exportBackButton.addEventListener("click", function(e){ exportBackButton.addEventListener("click", function (e) {
finish(); finish();
exportOverlay.style.display = "none"; exportOverlay.style.display = "none";
}); });
document.getElementById("highlightUncharted").addEventListener("click", function(e){ document.getElementById("highlightUncharted").addEventListener("click", function (e) {
highlightUncharted = this.checked; highlightUncharted = this.checked;
render(path); render(path);
}); });
function exportJson(){ function exportJson() {
var exportObject = { const exportObject = {
id: entryId, id: entryId,
name: document.getElementById("nameField").value, name: document.getElementById("nameField").value,
description: document.getElementById("descriptionField").value, description: document.getElementById("descriptionField").value,
@ -269,41 +269,41 @@ function initDraw(){
if (inputWebsite.length) exportObject.links.website = inputWebsite if (inputWebsite.length) exportObject.links.website = inputWebsite
if (inputSubreddit.length) exportObject.links.subreddit = inputSubreddit if (inputSubreddit.length) exportObject.links.subreddit = inputSubreddit
var jsonString = JSON.stringify(exportObject, null, "\t"); let jsonString = JSON.stringify(exportObject, null, "\t");
var textarea = document.getElementById("exportString"); const textarea = document.getElementById("exportString");
jsonString = jsonString.split("\n"); jsonString = jsonString.split("\n");
jsonString = jsonString.join("\n "); jsonString = jsonString.join("\n ");
jsonString = " "+jsonString; jsonString = " " + jsonString;
textarea.value = jsonString; textarea.value = jsonString;
var directPostUrl = "https://www.reddit.com/r/placeAtlas2/submit?selftext=true&title=New%20Submission&text="+encodeURIComponent(document.getElementById("exportString").value); let directPostUrl = "https://www.reddit.com/r/placeAtlas2/submit?selftext=true&title=New%20Submission&text=" + encodeURIComponent(document.getElementById("exportString").value);
if (jsonString.length > 7493) { if (jsonString.length > 7493) {
directPostUrl = "https://www.reddit.com/r/placeAtlas2/submit?selftext=true&title=New%20Submission&text="+encodeURIComponent(" " + JSON.stringify(exportObject)); directPostUrl = "https://www.reddit.com/r/placeAtlas2/submit?selftext=true&title=New%20Submission&text=" + encodeURIComponent(" " + JSON.stringify(exportObject));
} }
document.getElementById("exportDirectPost").href=directPostUrl; document.getElementById("exportDirectPost").href = directPostUrl;
exportOverlay.style.display = "flex"; exportOverlay.style.display = "flex";
textarea.focus(); textarea.focus();
textarea.select(); textarea.select();
} }
function undo(){ function undo() {
if(path.length > 0 && drawing){ if (path.length > 0 && drawing) {
undoHistory.push(path.pop()); undoHistory.push(path.pop());
redoButton.disabled = false; redoButton.disabled = false;
updatePath() updatePath()
} }
} }
function redo(){ function redo() {
if(undoHistory.length > 0 && drawing){ if (undoHistory.length > 0 && drawing) {
path.push(undoHistory.pop()); path.push(undoHistory.pop());
undoButton.disabled = false; undoButton.disabled = false;
updatePath() updatePath()
} }
} }
function finish(){ function finish() {
if (objectInfoBox.style.display === "block") return if (objectInfoBox.style.display === "block") return
updatePath() updatePath()
drawing = false; drawing = false;
@ -313,7 +313,7 @@ function initDraw(){
hintText.style.display = "none"; hintText.style.display = "none";
[...document.querySelectorAll("#drawControlsContainer textarea")].forEach(el => { [...document.querySelectorAll("#drawControlsContainer textarea")].forEach(el => {
if (el.value) el.style.height = (el.scrollHeight) + "px" if (el.value) el.style.height = (el.scrollHeight) + "px"
}) })
// if (isOnPeriod()) { // if (isOnPeriod()) {
// periodVisbilityInfo.textContent = "" // periodVisbilityInfo.textContent = ""
// } else { // } else {
@ -321,7 +321,7 @@ function initDraw(){
// } // }
} }
function reset(){ function reset() {
updatePath([]) updatePath([])
undoHistory = []; undoHistory = [];
drawing = true; drawing = true;
@ -336,7 +336,7 @@ function initDraw(){
document.getElementById("subredditField").value = ""; document.getElementById("subredditField").value = "";
} }
function back(){ function back() {
drawing = true; drawing = true;
disableDrawingOverride = false; disableDrawingOverride = false;
updatePath() updatePath()
@ -345,54 +345,54 @@ function initDraw(){
hintText.style.display = "block"; hintText.style.display = "block";
} }
function renderBackground(){ function renderBackground() {
backgroundContext.clearRect(0, 0, canvas.width, canvas.height); backgroundContext.clearRect(0, 0, canvas.width, canvas.height);
backgroundContext.fillStyle = "rgba(0, 0, 0, 1)"; backgroundContext.fillStyle = "rgba(0, 0, 0, 1)";
//backgroundContext.fillRect(0, 0, canvas.width, canvas.height); //backgroundContext.fillRect(0, 0, canvas.width, canvas.height);
for(var i = 0; i < atlas.length; i++){
var path = atlas[i].path; for (let i = 0; i < atlas.length; i++) {
const path = atlas[i].path;
backgroundContext.beginPath(); backgroundContext.beginPath();
if(path[0]){ if (path[0]) {
backgroundContext.moveTo(path[0][0], path[0][1]); backgroundContext.moveTo(path[0][0], path[0][1]);
} }
for(var p = 1; p < path.length; p++){ for (let p = 1; p < path.length; p++) {
backgroundContext.lineTo(path[p][0], path[p][1]); backgroundContext.lineTo(path[p][0], path[p][1]);
} }
backgroundContext.closePath(); backgroundContext.closePath();
backgroundContext.fill(); backgroundContext.fill();
} }
} }
function render(path){ function render(path) {
context.globalCompositeOperation = "source-over"; context.globalCompositeOperation = "source-over";
context.clearRect(0, 0, canvas.width, canvas.height); context.clearRect(0, 0, canvas.width, canvas.height);
if(highlightUncharted){ if (highlightUncharted) {
context.drawImage(backgroundCanvas, 0, 0); context.drawImage(backgroundCanvas, 0, 0);
context.fillStyle = "rgba(0, 0, 0, 0.4)"; context.fillStyle = "rgba(0, 0, 0, 0.4)";
} else { } else {
context.fillStyle = "rgba(0, 0, 0, 0.6)"; context.fillStyle = "rgba(0, 0, 0, 0.6)";
} }
context.fillRect(0, 0, canvas.width, canvas.height); context.fillRect(0, 0, canvas.width, canvas.height);
context.beginPath(); context.beginPath();
if(path[0]){ if (path[0]) {
context.moveTo(path[0][0], path[0][1]); context.moveTo(path[0][0], path[0][1]);
} }
for(var i = 1; i < path.length; i++){ for (let i = 1; i < path.length; i++) {
context.lineTo(path[i][0], path[i][1]); context.lineTo(path[i][0], path[i][1]);
} }
@ -405,16 +405,16 @@ function initDraw(){
context.fillStyle = "rgba(0, 0, 0, 1)"; context.fillStyle = "rgba(0, 0, 0, 1)";
context.fill(); context.fill();
} }
function updateHovering(e, tapped){ function updateHovering(e, tapped) {
if(!dragging && (!fixed || tapped)){ if (!dragging && (!fixed || tapped)) {
var pos = [ const pos = [
(e.clientX - (container.clientWidth/2 - innerContainer.clientWidth/2 + zoomOrigin[0] + container.offsetLeft))/zoom (e.clientX - (container.clientWidth / 2 - innerContainer.clientWidth / 2 + zoomOrigin[0] + container.offsetLeft)) / zoom
,(e.clientY - (container.clientHeight/2 - innerContainer.clientHeight/2 + zoomOrigin[1] + container.offsetTop))/zoom , (e.clientY - (container.clientHeight / 2 - innerContainer.clientHeight / 2 + zoomOrigin[1] + container.offsetTop)) / zoom
]; ];
var coords_p = document.getElementById("coords_p"); const coords_p = document.getElementById("coords_p");
coords_p.innerText = Math.ceil(pos[0]) + ", " + Math.ceil(pos[1]); coords_p.innerText = Math.ceil(pos[0]) + ", " + Math.ceil(pos[1]);
} }
} }
@ -452,16 +452,16 @@ function initDraw(){
zoom = 4; zoom = 4;
zoomOrigin = [ zoomOrigin = [
innerContainer.clientWidth/2 - center[0] * zoom,// + container.offsetLeft innerContainer.clientWidth / 2 - center[0] * zoom,// + container.offsetLeft
innerContainer.clientHeight/2 - center[1] * zoom// + container.offsetTop innerContainer.clientHeight / 2 - center[1] * zoom// + container.offsetTop
]; ];
scaleZoomOrigin = [ scaleZoomOrigin = [
2000/2 - center[0],// + container.offsetLeft 2000 / 2 - center[0],// + container.offsetLeft
2000/2 - center[1]// + container.offsetTop 2000 / 2 - center[1]// + container.offsetTop
]; ];
applyView(); applyView();
document.addEventListener('timeupdate', (event) => { document.addEventListener('timeupdate', (event) => {
renderBackground() renderBackground()
@ -476,9 +476,9 @@ function initDraw(){
} }
function calculateCenter(path){ function calculateCenter(path) {
var area = 0, let area = 0,
i, i,
j, j,
point1, point1,
@ -487,7 +487,7 @@ function calculateCenter(path){
y = 0, y = 0,
f; f;
for (i = 0, j = path.length - 1; i < path.length; j=i,i++) { for (i = 0, j = path.length - 1; i < path.length; j = i, i++) {
point1 = path[i]; point1 = path[i];
point2 = path[j]; point2 = path[j];
f = point1[0] * point2[1] - point2[0] * point1[1]; f = point1[0] * point2[1] - point2[0] * point1[1];
@ -497,7 +497,7 @@ function calculateCenter(path){
} }
area *= 3; area *= 3;
return [Math.floor(x / area)+0.5, Math.floor(y / area)+0.5]; return [Math.floor(x / area) + 0.5, Math.floor(y / area) + 0.5];
} }
function initPeriodGroups() { function initPeriodGroups() {
@ -560,7 +560,7 @@ function initPeriodGroups() {
startPeriodEl.value = newVariationConfig.default startPeriodEl.value = newVariationConfig.default
startPeriodEl.max = newVariationConfig.versions.length - 1 startPeriodEl.max = newVariationConfig.versions.length - 1
endPeriodEl.value = newVariationConfig.default endPeriodEl.value = newVariationConfig.default
endPeriodEl.max = newVariationConfig.versions.length - 1 endPeriodEl.max = newVariationConfig.versions.length - 1
updateTime(newVariationConfig.default, newVariation) updateTime(newVariationConfig.default, newVariation)
// console.log(parseInt(event.target.value)) // console.log(parseInt(event.target.value))
}) })
@ -613,10 +613,10 @@ function initPeriodGroups() {
function updatePeriodGroups() { function updatePeriodGroups() {
// console.log('updatePeriodGroups') // console.log('updatePeriodGroups')
var pathToActive = [] let pathToActive = []
var lastActivePathIndex let lastActivePathIndex
var currentActivePathIndex let currentActivePathIndex
var currentActivePathIndexes = [] const currentActivePathIndexes = []
periodGroupElements.forEach((elements, index) => { periodGroupElements.forEach((elements, index) => {
const { const {
@ -632,7 +632,7 @@ function updatePeriodGroups() {
periodGroupEl.dataset.active = "" periodGroupEl.dataset.active = ""
if (isOnPeriod( if (isOnPeriod(
parseInt(startPeriodEl.value), parseInt(startPeriodEl.value),
parseInt(endPeriodEl.value), parseInt(endPeriodEl.value),
periodVariationEl.value, periodVariationEl.value,
currentPeriod, currentPeriod,
@ -645,7 +645,7 @@ function updatePeriodGroups() {
} }
pathWithPeriods[index][0] = formatPeriod( pathWithPeriods[index][0] = formatPeriod(
parseInt(startPeriodEl.value), parseInt(startPeriodEl.value),
parseInt(endPeriodEl.value), parseInt(endPeriodEl.value),
periodVariationEl.value periodVariationEl.value
) )
@ -681,7 +681,7 @@ function updatePeriodGroups() {
// }) // })
// currentActivePathIndex = undefined // currentActivePathIndex = undefined
// } // }
// console.log(lastActivePathIndex) // console.log(lastActivePathIndex)
if (lastActivePathIndex !== undefined) { if (lastActivePathIndex !== undefined) {
if (lastActivePathIndex === currentActivePathIndex) { if (lastActivePathIndex === currentActivePathIndex) {
@ -715,11 +715,11 @@ function updatePeriodGroups() {
} }
drawing = disableDrawingOverride ? false : currentActivePathIndex !== undefined drawing = disableDrawingOverride ? false : currentActivePathIndex !== undefined
} }
function formatPeriod(start, end, variation) { function formatPeriod(start, end, variation) {
let periodString let periodString
if (start === end) periodString = start if (start === end) periodString = start
else periodString = start + "-" + end else periodString = start + "-" + end
if (variation !== "default") periodString = variationsConfig[variation].code + ":" + periodString if (variation !== "default") periodString = variationsConfig[variation].code + ":" + periodString
@ -766,11 +766,11 @@ function updateErrors() {
}) })
} }
} }
function getConflicts() { function getConflicts() {
let conflicts = new Set() let conflicts = new Set()
for (let i = pathWithPeriods.length - 1; i > 0; i--) { for (let i = pathWithPeriods.length - 1; i > 0; i--) {
const [start1, end1, period1] = parsePeriod(pathWithPeriods[i][0]) const [start1, end1, period1] = parsePeriod(pathWithPeriods[i][0])
for (let j = 0; j < i; j++) { for (let j = 0; j < i; j++) {
@ -801,7 +801,7 @@ function getErrors() {
pathWithPeriods.forEach(([period, path], i) => { pathWithPeriods.forEach(([period, path], i) => {
if (path.length < 3) invalidPaths.push(i) if (path.length < 3) invalidPaths.push(i)
}) })
// console.info('conflicts', conflicts) // console.info('conflicts', conflicts)
// console.info('invalid paths', invalidPaths) // console.info('invalid paths', invalidPaths)

View file

@ -14,93 +14,93 @@
*/ */
function createInfoBlock(entry) { function createInfoBlock(entry) {
// console.log(entry) // console.log(entry)
function createInfoParagraph(name, value){ function createInfoParagraph(name, value) {
const entryParagraphPositionElement = document.createElement("p"); const entryParagraphPositionElement = document.createElement("p");
const nameElement = document.createElement("span"); const nameElement = document.createElement("span");
nameElement.style.fontWeight = "bold"; nameElement.style.fontWeight = "bold";
nameElement.innerText = name; nameElement.innerText = name;
const valueElement = document.createElement("span"); const valueElement = document.createElement("span");
valueElement.innerText = value; valueElement.innerText = value;
entryParagraphPositionElement.appendChild(nameElement); entryParagraphPositionElement.appendChild(nameElement);
entryParagraphPositionElement.appendChild(valueElement); entryParagraphPositionElement.appendChild(valueElement);
return entryParagraphPositionElement; return entryParagraphPositionElement;
} }
var element = document.createElement("div"); const element = document.createElement("div");
element.className = "object"; element.className = "object";
const headerElement = document.createElement("h2"); const headerElement = document.createElement("h2");
const linkElement = document.createElement("a"); const linkElement = document.createElement("a");
linkElement.href = "#" + entry.id; linkElement.href = "#" + entry.id;
linkElement.innerText = entry.name; linkElement.innerText = entry.name;
headerElement.appendChild(linkElement); headerElement.appendChild(linkElement);
element.appendChild(headerElement); element.appendChild(headerElement);
if (entry.diff) { if (entry.diff) {
const diffElement = createInfoParagraph("Diff: ", entry.diff); const diffElement = createInfoParagraph("Diff: ", entry.diff);
diffElement.className = entry.diff; diffElement.className = entry.diff;
element.appendChild(diffElement); element.appendChild(diffElement);
} }
if (entry.description) { if (entry.description) {
const descElement = document.createElement("p"); const descElement = document.createElement("p");
descElement.innerText = entry.description; descElement.innerText = entry.description;
element.appendChild(descElement); element.appendChild(descElement);
} }
const [x, y] = entry.center;
element.appendChild(createInfoParagraph("Position: ", `${Math.floor(x)}, ${Math.floor(y)}`));
if(entry.path){ const [x, y] = entry.center;
const area = calcPolygonArea(entry.path); element.appendChild(createInfoParagraph("Position: ", `${Math.floor(x)}, ${Math.floor(y)}`));
element.appendChild(createInfoParagraph("Area: ", `${area} pixels`));
}
entry.links.subreddit.forEach(subreddit => { if (entry.path) {
subreddit = "/r/" + subreddit; const area = calcPolygonArea(entry.path);
const subredditLinkElement = document.createElement("a"); element.appendChild(createInfoParagraph("Area: ", `${area} pixels`));
subredditLinkElement.target = "_blank"; }
subredditLinkElement.href = "https://reddit.com" + subreddit;
subredditLinkElement.innerText = subreddit;
element.appendChild(subredditLinkElement);
})
entry.links.website.forEach(link => { entry.links.subreddit.forEach(subreddit => {
const websiteLinkElement = document.createElement("a"); subreddit = "/r/" + subreddit;
websiteLinkElement.target = "_blank"; const subredditLinkElement = document.createElement("a");
websiteLinkElement.href = link; subredditLinkElement.target = "_blank";
websiteLinkElement.innerText = "Website"; subredditLinkElement.href = "https://reddit.com" + subreddit;
element.appendChild(websiteLinkElement); subredditLinkElement.innerText = subreddit;
}) element.appendChild(subredditLinkElement);
})
entry.links.discord.forEach(link => { entry.links.website.forEach(link => {
const websiteLinkElement = document.createElement("a"); const websiteLinkElement = document.createElement("a");
websiteLinkElement.target = "_blank"; websiteLinkElement.target = "_blank";
websiteLinkElement.href = "https://discord.gg/" + link; websiteLinkElement.href = link;
websiteLinkElement.innerText = "Discord"; websiteLinkElement.innerText = "Website";
element.appendChild(websiteLinkElement); element.appendChild(websiteLinkElement);
}) })
entry.links.wiki.forEach(link => { entry.links.discord.forEach(link => {
const websiteLinkElement = document.createElement("a"); const websiteLinkElement = document.createElement("a");
websiteLinkElement.target = "_blank"; websiteLinkElement.target = "_blank";
websiteLinkElement.href = "https://place-wiki.stefanocoding.me/wiki/" + link.replace(/ /g, '_'); websiteLinkElement.href = "https://discord.gg/" + link;
websiteLinkElement.innerText = "Wiki Article"; websiteLinkElement.innerText = "Discord";
element.appendChild(websiteLinkElement); element.appendChild(websiteLinkElement);
}) })
const idElement = createInfoParagraph("ID: ", entry.id); entry.links.wiki.forEach(link => {
element.appendChild(idElement); const websiteLinkElement = document.createElement("a");
websiteLinkElement.target = "_blank";
websiteLinkElement.href = "https://place-wiki.stefanocoding.me/wiki/" + link.replace(/ /g, '_');
websiteLinkElement.innerText = "Wiki Article";
element.appendChild(websiteLinkElement);
})
if (!entry.diff || entry.diff !== "delete") { const idElement = createInfoParagraph("ID: ", entry.id);
const editElement = document.createElement("a"); element.appendChild(idElement);
editElement.innerText = "Edit"
editElement.className = "objectEdit"
editElement.href = "./?mode=draw&id=" + entry.id
element.appendChild(editElement);
}
return element; if (!entry.diff || entry.diff !== "delete") {
const editElement = document.createElement("a");
editElement.innerText = "Edit"
editElement.className = "objectEdit"
editElement.href = "./?mode=draw&id=" + entry.id
element.appendChild(editElement);
}
return element;
} }

View file

@ -15,64 +15,64 @@
const prodDomain = "place-atlas.stefanocoding.me" const prodDomain = "place-atlas.stefanocoding.me"
var innerContainer = document.getElementById("innerContainer"); const innerContainer = document.getElementById("innerContainer");
var container = document.getElementById("container"); const container = document.getElementById("container");
var canvas = document.getElementById("highlightCanvas"); const canvas = document.getElementById("highlightCanvas");
var context = canvas.getContext("2d"); const context = canvas.getContext("2d");
var zoom = 1; let zoom = 1;
if(window.devicePixelRatio){ if (window.devicePixelRatio) {
zoom = 1/window.devicePixelRatio; zoom = 1 / window.devicePixelRatio;
} }
var maxZoom = 128; const maxZoom = 128;
var minZoom = 0.1; const minZoom = 0.1;
var zoomOrigin = [0, 0]; let zoomOrigin = [0, 0];
var scaleZoomOrigin = [0, 0]; let scaleZoomOrigin = [0, 0];
var dragging = false; let dragging = false;
var lastPosition = [0, 0]; let lastPosition = [0, 0];
var viewportSize = [0, 0]; const viewportSize = [0, 0];
document.getElementById("entriesListDonate").addEventListener("click", function(e){ document.getElementById("entriesListDonate").addEventListener("click", function (e) {
document.getElementById("donateOverlay").style.display = "flex"; document.getElementById("donateOverlay").style.display = "flex";
}); });
document.getElementById("closeDonateButton").addEventListener("click", function(e){ document.getElementById("closeDonateButton").addEventListener("click", function (e) {
document.getElementById("donateOverlay").style.display = "none"; document.getElementById("donateOverlay").style.display = "none";
}); });
function applyView(){ function applyView() {
//console.log(zoomOrigin, scaleZoomOrigin); //console.log(zoomOrigin, scaleZoomOrigin);
//console.log(scaleZoomOrigin[0]); //console.log(scaleZoomOrigin[0]);
scaleZoomOrigin[0] = Math.max(-1000, Math.min(1000, scaleZoomOrigin[0])); scaleZoomOrigin[0] = Math.max(-1000, Math.min(1000, scaleZoomOrigin[0]));
scaleZoomOrigin[1] = Math.max(-1000, Math.min(1000, scaleZoomOrigin[1])); scaleZoomOrigin[1] = Math.max(-1000, Math.min(1000, scaleZoomOrigin[1]));
zoomOrigin = [scaleZoomOrigin[0]*zoom, scaleZoomOrigin[1]*zoom]; zoomOrigin = [scaleZoomOrigin[0] * zoom, scaleZoomOrigin[1] * zoom];
innerContainer.style.height = (~~(zoom * 2000)) + "px";
innerContainer.style.width = (~~(zoom * 2000)) + "px";
innerContainer.style.left = ~~(container.clientWidth / 2 - innerContainer.clientWidth / 2 + zoomOrigin[0] + container.offsetLeft) + "px";
innerContainer.style.top = ~~(container.clientHeight / 2 - innerContainer.clientHeight / 2 + zoomOrigin[1] + container.offsetTop) + "px";
innerContainer.style.height = (~~(zoom*2000))+"px";
innerContainer.style.width = (~~(zoom*2000))+"px";
innerContainer.style.left = ~~(container.clientWidth/2 - innerContainer.clientWidth/2 + zoomOrigin[0] + container.offsetLeft)+"px";
innerContainer.style.top = ~~(container.clientHeight/2 - innerContainer.clientHeight/2 + zoomOrigin[1] + container.offsetTop)+"px";
} }
var atlas = null; let atlas = null;
window.atlas = atlas window.atlas = atlas
var atlasAll = null let atlasAll = null
window.atlasAll = atlasAll window.atlasAll = atlasAll
if (document.location.host !== prodDomain) document.body.dataset.dev = "" if (document.location.host !== prodDomain) document.body.dataset.dev = ""
init(); init();
async function init(){ async function init() {
// For Reviewing Reddit Changes // For Reviewing Reddit Changes
//let resp = await fetch("../tools/temp_atlas.json"); //let resp = await fetch("../tools/temp_atlas.json");
const resp = await fetch("./atlas.json"); const resp = await fetch("./atlas.json");
@ -89,7 +89,7 @@ async function init(){
}); });
atlasAll = updateAtlasAll(atlas); atlasAll = updateAtlasAll(atlas);
await updateTime(currentPeriod, currentVariation) await updateTime(currentPeriod, currentVariation)
//console.log(document.documentElement.clientWidth, document.documentElement.clientHeight); //console.log(document.documentElement.clientWidth, document.documentElement.clientHeight);
@ -97,18 +97,18 @@ async function init(){
zoomOrigin = [0, 0]; zoomOrigin = [0, 0];
applyView(); applyView();
var initialPinchDistance = 0; let initialPinchDistance = 0;
var initialPinchZoom = 0; let initialPinchZoom = 0;
var initialPinchZoomOrigin = [0, 0]; let initialPinchZoomOrigin = [0, 0];
var desiredZoom; let desiredZoom;
var zoomAnimationFrame; let zoomAnimationFrame;
var mode = "view"; let mode = "view";
var args = window.location.search; const args = window.location.search;
var params = new URLSearchParams(args) const params = new URLSearchParams(args)
if (args){ if (args) {
mode = params.get("mode") mode = params.get("mode")
if (!mode) { if (!mode) {
mode = "view"; mode = "view";
@ -130,41 +130,41 @@ async function init(){
initGlobal() initGlobal()
if (mode !== "draw") initViewGlobal() if (mode !== "draw") initViewGlobal()
if(mode === "draw"){ if (mode === "draw") {
initDraw(); initDraw();
} else if(mode === "about"){ } else if (mode === "about") {
window.location = "./about.html"; window.location = "./about.html";
} else if(mode === "overlap"){ } else if (mode === "overlap") {
if(initOverlap){ if (initOverlap) {
initOverlap(); initOverlap();
} }
} else if(mode.startsWith("diff")){ } else if (mode.startsWith("diff")) {
try { try {
const liveResp = await fetch("https://place-atlas.stefanocoding.me/atlas.json"); const liveResp = await fetch("https://place-atlas.stefanocoding.me/atlas.json");
let liveJson = await liveResp.json(); let liveJson = await liveResp.json();
liveJson = updateAtlasAll(liveJson) liveJson = updateAtlasAll(liveJson)
// console.log(liveJson) // console.log(liveJson)
const liveAtlasReduced = liveJson.reduce(function(a, c) { const liveAtlasReduced = liveJson.reduce(function (a, c) {
a[c.id] = c; a[c.id] = c;
return a; return a;
},{}); }, {});
// Mark added/edited entries // Mark added/edited entries
atlasAll = atlasAll.map(function(entry) { atlasAll = atlasAll.map(function (entry) {
if(liveAtlasReduced[entry.id] === undefined){ if (liveAtlasReduced[entry.id] === undefined) {
entry.diff = "add"; entry.diff = "add";
}else if(JSON.stringify(entry) !== JSON.stringify(liveAtlasReduced[entry.id])){ } else if (JSON.stringify(entry) !== JSON.stringify(liveAtlasReduced[entry.id])) {
entry.diff = "edit"; entry.diff = "edit";
} }
return entry; return entry;
}); });
// Mark removed entries // Mark removed entries
const atlasReduced = atlasAll.reduce(function(a, c) { const atlasReduced = atlasAll.reduce(function (a, c) {
a[c.id] = c; a[c.id] = c;
return a; return a;
},{}); }, {});
const removedEntries = liveJson.filter(entry => const removedEntries = liveJson.filter(entry =>
atlasReduced[entry.id] === undefined atlasReduced[entry.id] === undefined
).map(entry => { ).map(entry => {
entry.diff = "delete" entry.diff = "delete"
@ -172,8 +172,8 @@ async function init(){
}) })
atlasAll.push(...removedEntries) atlasAll.push(...removedEntries)
if(mode.includes("only")){ if (mode.includes("only")) {
atlasAll = atlasAll.filter(function(entry) { atlasAll = atlasAll.filter(function (entry) {
return typeof entry.diff == "string" return typeof entry.diff == "string"
}); });
} }
@ -182,26 +182,26 @@ async function init(){
console.warn("Diff mode failed to load, reverting to normal view.", error); console.warn("Diff mode failed to load, reverting to normal view.", error);
} finally { } finally {
await updateTime() await updateTime()
if(initOverlap && mode.includes("overlap")){ if (initOverlap && mode.includes("overlap")) {
initOverlap(); initOverlap();
} else { } else {
initView(); initView();
} }
} }
} else if(mode === "explore"){ } else if (mode === "explore") {
initExplore(); initExplore();
} else { } else {
initView(); initView();
} }
document.getElementById("zoomInButton").addEventListener("click", function(e){ document.getElementById("zoomInButton").addEventListener("click", function (e) {
/*if(zoomAnimationFrame){ /*if(zoomAnimationFrame){
window.cancelAnimationFrame(zoomAnimationFrame); window.cancelAnimationFrame(zoomAnimationFrame);
}*/ }*/
var x = container.clientWidth/2; const x = container.clientWidth / 2;
var y = container.clientHeight/2; const y = container.clientHeight / 2;
initialPinchZoomOrigin = [ initialPinchZoomOrigin = [
scaleZoomOrigin[0], scaleZoomOrigin[0],
@ -209,23 +209,23 @@ async function init(){
]; ];
initialPinchZoom = zoom; initialPinchZoom = zoom;
lastPosition = [x, y]; lastPosition = [x, y];
zoom = zoom * 2; zoom = zoom * 2;
zoom = Math.max(minZoom, Math.min(maxZoom, zoom)); zoom = Math.max(minZoom, Math.min(maxZoom, zoom));
applyZoom(x, y, zoom); applyZoom(x, y, zoom);
}); });
document.getElementById("zoomOutButton").addEventListener("click", function(e){ document.getElementById("zoomOutButton").addEventListener("click", function (e) {
/*if(zoomAnimationFrame){ /*if(zoomAnimationFrame){
window.cancelAnimationFrame(zoomAnimationFrame); window.cancelAnimationFrame(zoomAnimationFrame);
}*/ }*/
var x = container.clientWidth/2; const x = container.clientWidth / 2;
var y = container.clientHeight/2; const y = container.clientHeight / 2;
initialPinchZoomOrigin = [ initialPinchZoomOrigin = [
scaleZoomOrigin[0], scaleZoomOrigin[0],
@ -233,15 +233,15 @@ async function init(){
]; ];
initialPinchZoom = zoom; initialPinchZoom = zoom;
lastPosition = [x, y]; lastPosition = [x, y];
zoom = zoom / 2; zoom = zoom / 2;
zoom = Math.max(minZoom, Math.min(maxZoom, zoom)); zoom = Math.max(minZoom, Math.min(maxZoom, zoom));
applyZoom(x, y, zoom); applyZoom(x, y, zoom);
}); });
document.getElementById("zoomResetButton").addEventListener("click", function(e){ document.getElementById("zoomResetButton").addEventListener("click", function (e) {
zoom = 1; zoom = 1;
zoomOrigin = [0, 0]; zoomOrigin = [0, 0];
scaleZoomOrigin = [0, 0]; scaleZoomOrigin = [0, 0];
@ -249,13 +249,13 @@ async function init(){
applyView(); applyView();
}); });
container.addEventListener("dblclick", function(e){ container.addEventListener("dblclick", function (e) {
/*if(zoomAnimationFrame){ /*if(zoomAnimationFrame){
window.cancelAnimationFrame(zoomAnimationFrame); window.cancelAnimationFrame(zoomAnimationFrame);
}*/ }*/
var x = e.clientX - container.offsetLeft; const x = e.clientX - container.offsetLeft;
var y = e.clientY - container.offsetTop; const y = e.clientY - container.offsetTop;
initialPinchZoomOrigin = [ initialPinchZoomOrigin = [
scaleZoomOrigin[0], scaleZoomOrigin[0],
@ -263,15 +263,15 @@ async function init(){
]; ];
initialPinchZoom = zoom; initialPinchZoom = zoom;
lastPosition = [x, y]; lastPosition = [x, y];
if(e.ctrlKey){ if (e.ctrlKey) {
zoom = zoom / 2; zoom = zoom / 2;
} else { } else {
zoom = zoom * 2; zoom = zoom * 2;
} }
@ -282,14 +282,14 @@ async function init(){
}); });
container.addEventListener("wheel", function(e){ container.addEventListener("wheel", function (e) {
/*if(zoomAnimationFrame){ /*if(zoomAnimationFrame){
window.cancelAnimationFrame(zoomAnimationFrame); window.cancelAnimationFrame(zoomAnimationFrame);
}*/ }*/
var x = e.clientX - container.offsetLeft; const x = e.clientX - container.offsetLeft;
var y = e.clientY - container.offsetTop; const y = e.clientY - container.offsetTop;
initialPinchZoomOrigin = [ initialPinchZoomOrigin = [
scaleZoomOrigin[0], scaleZoomOrigin[0],
@ -297,7 +297,7 @@ async function init(){
]; ];
initialPinchZoom = zoom; initialPinchZoom = zoom;
lastPosition = [x, y]; lastPosition = [x, y];
// Check if we are zooming by pixels // Check if we are zooming by pixels
@ -308,12 +308,12 @@ async function init(){
// This creates a smoother experience // This creates a smoother experience
zoom -= e.deltaY * (0.001 * zoom); zoom -= e.deltaY * (0.001 * zoom);
} else { } else {
if(e.deltaY > 0){ if (e.deltaY > 0) {
zoom = zoom / 2; zoom = zoom / 2;
} else if(e.deltaY < 0){ } else if (e.deltaY < 0) {
zoom = zoom * 2; zoom = zoom * 2;
} }
} }
@ -322,7 +322,7 @@ async function init(){
applyZoom(x, y, zoom); applyZoom(x, y, zoom);
e.preventDefault(); e.preventDefault();
}, {passive: true}); }, { passive: true });
/*function setDesiredZoom(x, y, target){ /*function setDesiredZoom(x, y, target){
zoom = (zoom*2 + target)/3; zoom = (zoom*2 + target)/3;
@ -338,36 +338,36 @@ async function init(){
} }
}*/ }*/
container.addEventListener("mousedown", function(e){ container.addEventListener("mousedown", function (e) {
mousedown(e.clientX, e.clientY); mousedown(e.clientX, e.clientY);
e.preventDefault(); e.preventDefault();
}); });
container.addEventListener("touchstart", function(e){
if(e.touches.length == 2){ container.addEventListener("touchstart", function (e) {
if (e.touches.length == 2) {
e.preventDefault(); e.preventDefault();
} }
touchstart(e); touchstart(e);
}, {passive: true}); }, { passive: true });
function mousedown(x, y){ function mousedown(x, y) {
lastPosition = [x, y]; lastPosition = [x, y];
dragging = true; dragging = true;
} }
function touchstart(e){ function touchstart(e) {
if(e.touches.length == 1){ if (e.touches.length == 1) {
mousedown(e.touches[0].clientX, e.touches[0].clientY); mousedown(e.touches[0].clientX, e.touches[0].clientY);
} else if(e.touches.length == 2){ } else if (e.touches.length == 2) {
initialPinchDistance = Math.sqrt( initialPinchDistance = Math.sqrt(
Math.pow(e.touches[0].clientX - e.touches[1].clientX, 2) Math.pow(e.touches[0].clientX - e.touches[1].clientX, 2)
+ Math.pow(e.touches[0].clientY - e.touches[1].clientY, 2) + Math.pow(e.touches[0].clientY - e.touches[1].clientY, 2)
); );
@ -376,46 +376,46 @@ async function init(){
scaleZoomOrigin[0], scaleZoomOrigin[0],
scaleZoomOrigin[1] scaleZoomOrigin[1]
]; ];
mousedown( mousedown(
(e.touches[0].clientX + e.touches[1].clientX)/2, (e.touches[0].clientX + e.touches[1].clientX) / 2,
(e.touches[0].clientY + e.touches[1].clientY)/2 (e.touches[0].clientY + e.touches[1].clientY) / 2
); );
} }
} }
window.addEventListener("mousemove", function(e){ window.addEventListener("mousemove", function (e) {
updateLines(); updateLines();
mousemove(e.clientX, e.clientY); mousemove(e.clientX, e.clientY);
if(dragging){ if (dragging) {
e.preventDefault(); e.preventDefault();
} }
}); });
window.addEventListener("touchmove", function(e){ window.addEventListener("touchmove", function (e) {
if(e.touches.length == 2 || e.scale > 1){ if (e.touches.length == 2 || e.scale > 1) {
e.preventDefault(); e.preventDefault();
} }
touchmove(e); touchmove(e);
}, },
{passive: false} { passive: false }
); );
function mousemove(x, y){ function mousemove(x, y) {
if(dragging){ if (dragging) {
var deltaX = x - lastPosition[0]; const deltaX = x - lastPosition[0];
var deltaY = y - lastPosition[1]; const deltaY = y - lastPosition[1];
lastPosition = [x, y]; lastPosition = [x, y];
zoomOrigin[0] += deltaX; zoomOrigin[0] += deltaX;
zoomOrigin[1] += deltaY; zoomOrigin[1] += deltaY;
scaleZoomOrigin[0] += deltaX/zoom; scaleZoomOrigin[0] += deltaX / zoom;
scaleZoomOrigin[1] += deltaY/zoom; scaleZoomOrigin[1] += deltaY / zoom;
previousZoomOrigin = [zoomOrigin[0], zoomOrigin[1]]; previousZoomOrigin = [zoomOrigin[0], zoomOrigin[1]];
previousScaleZoomOrigin = [scaleZoomOrigin[0], scaleZoomOrigin[1]]; previousScaleZoomOrigin = [scaleZoomOrigin[0], scaleZoomOrigin[1]];
@ -425,83 +425,83 @@ async function init(){
} }
} }
function touchmove(e){ function touchmove(e) {
updateLines(); updateLines();
if(e.touches.length == 1){ if (e.touches.length == 1) {
mousemove(e.touches[0].clientX, e.touches[0].clientY); mousemove(e.touches[0].clientX, e.touches[0].clientY);
} else if(e.touches.length == 2){ } else if (e.touches.length == 2) {
var newPinchDistance = Math.sqrt( const newPinchDistance = Math.sqrt(
Math.pow(e.touches[0].clientX - e.touches[1].clientX, 2) Math.pow(e.touches[0].clientX - e.touches[1].clientX, 2)
+ Math.pow(e.touches[0].clientY - e.touches[1].clientY, 2) + Math.pow(e.touches[0].clientY - e.touches[1].clientY, 2)
); );
zoom = initialPinchZoom * newPinchDistance / initialPinchDistance; zoom = initialPinchZoom * newPinchDistance / initialPinchDistance;
var x = (e.touches[0].clientX + e.touches[1].clientX)/2 - container.offsetLeft; const x = (e.touches[0].clientX + e.touches[1].clientX) / 2 - container.offsetLeft;
var y = (e.touches[0].clientY + e.touches[1].clientY)/2 - container.offsetTop; const y = (e.touches[0].clientY + e.touches[1].clientY) / 2 - container.offsetTop;
applyZoom(x, y, zoom); applyZoom(x, y, zoom);
} }
} }
function applyZoom(x, y, zoom){ function applyZoom(x, y, zoom) {
var deltaX = x - lastPosition[0]; const deltaX = x - lastPosition[0];
var deltaY = y - lastPosition[1]; const deltaY = y - lastPosition[1];
var pinchTranslateX = (x - container.clientWidth/2 - deltaX); const pinchTranslateX = (x - container.clientWidth / 2 - deltaX);
var pinchTranslateY = (y - container.clientHeight/2 - deltaY); const pinchTranslateY = (y - container.clientHeight / 2 - deltaY);
scaleZoomOrigin[0] = initialPinchZoomOrigin[0] + deltaX/zoom + pinchTranslateX/zoom - pinchTranslateX/initialPinchZoom; scaleZoomOrigin[0] = initialPinchZoomOrigin[0] + deltaX / zoom + pinchTranslateX / zoom - pinchTranslateX / initialPinchZoom;
scaleZoomOrigin[1] = initialPinchZoomOrigin[1] + deltaY/zoom + pinchTranslateY/zoom - pinchTranslateY/initialPinchZoom; scaleZoomOrigin[1] = initialPinchZoomOrigin[1] + deltaY / zoom + pinchTranslateY / zoom - pinchTranslateY / initialPinchZoom;
zoomOrigin[0] = scaleZoomOrigin[0]*zoom; zoomOrigin[0] = scaleZoomOrigin[0] * zoom;
zoomOrigin[1] = scaleZoomOrigin[1]*zoom; zoomOrigin[1] = scaleZoomOrigin[1] * zoom;
applyView(); applyView();
updateLines(); updateLines();
} }
window.addEventListener("mouseup", function(e){ window.addEventListener("mouseup", function (e) {
if(dragging){ if (dragging) {
e.preventDefault(); e.preventDefault();
} }
mouseup(e.clientX, e.clientY); mouseup(e.clientX, e.clientY);
}); });
window.addEventListener("touchend", touchend); window.addEventListener("touchend", touchend);
function mouseup(x, y){ function mouseup(x, y) {
if(dragging){ if (dragging) {
dragging = false; dragging = false;
} }
} }
function touchend(e){ function touchend(e) {
if(e.touches.length == 0){ if (e.touches.length == 0) {
mouseup(); mouseup();
} else if(e.touches.length == 1){ } else if (e.touches.length == 1) {
initialPinchZoom = zoom; initialPinchZoom = zoom;
lastPosition = [e.touches[0].clientX, e.touches[0].clientY]; lastPosition = [e.touches[0].clientX, e.touches[0].clientY];
} }
} }
window.addEventListener("resize", function(){ window.addEventListener("resize", function () {
//console.log(document.documentElement.clientWidth, document.documentElement.clientHeight); //console.log(document.documentElement.clientWidth, document.documentElement.clientHeight);
applyView(); applyView();
}); });
document.body.dataset.initDone = '' document.body.dataset.initDone = ''
} }

View file

@ -13,11 +13,11 @@
======================================================================== ========================================================================
*/ */
function initOverlap(){ function initOverlap() {
window.renderBackground = renderBackground window.renderBackground = renderBackground
var hovered = []; const hovered = [];
buildObjectsList(null, null); buildObjectsList(null, null);
renderBackground(atlas); renderBackground(atlas);
@ -34,7 +34,7 @@ function initOverlap(){
render(); render();
updateLines(); updateLines();
if(window.location.hash){ if (window.location.hash) {
highlightEntryFromUrl(); highlightEntryFromUrl();
} }
@ -45,17 +45,17 @@ function initOverlap(){
backgroundContext.fillStyle = "rgba(255, 255, 255, 1)"; backgroundContext.fillStyle = "rgba(255, 255, 255, 1)";
backgroundContext.fillRect(0, 0, canvas.width, canvas.height); backgroundContext.fillRect(0, 0, canvas.width, canvas.height);
for(var i = 0; i < atlas.length; i++){ for (let i = 0; i < atlas.length; i++) {
var path = atlas[i].path; const path = atlas[i].path;
backgroundContext.beginPath(); backgroundContext.beginPath();
if(path[0]){ if (path[0]) {
backgroundContext.moveTo(path[0][0], path[0][1]); backgroundContext.moveTo(path[0][0], path[0][1]);
} }
for(var p = 1; p < path.length; p++){ for (let p = 1; p < path.length; p++) {
backgroundContext.lineTo(path[p][0], path[p][1]); backgroundContext.lineTo(path[p][0], path[p][1]);
} }
@ -65,16 +65,16 @@ function initOverlap(){
backgroundContext.fill(); backgroundContext.fill();
} }
var pixels = backgroundContext.getImageData(0, 0, backgroundCanvas.width, backgroundCanvas.height).data; const pixels = backgroundContext.getImageData(0, 0, backgroundCanvas.width, backgroundCanvas.height).data;
var blank = 0; let blank = 0;
for(var i = 0; i < pixels.length; i+=4){ for (let i = 0; i < pixels.length; i += 4) {
if(pixels[i] == 255){ if (pixels[i] == 255) {
blank++; blank++;
} }
} }
console.log(blank+" blank pixels, which are "+Math.round(blank/100)/100+"% of the canvas ("+(100-Math.round(blank/100)/100)+"% mapped)"); console.log(blank + " blank pixels, which are " + Math.round(blank / 100) / 100 + "% of the canvas (" + (100 - Math.round(blank / 100) / 100) + "% mapped)");
} }
} }

View file

@ -24,21 +24,21 @@ SOFTWARE.
*/ */
function pointIsInPolygon (point, polygon) { function pointIsInPolygon(point, polygon) {
// ray-casting algorithm based on // ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var x = point[0], y = point[1]; const x = point[0], y = point[1];
var inside = false; let inside = false;
for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
var xi = polygon[i][0], yi = polygon[i][1]; const xi = polygon[i][0], yi = polygon[i][1];
var xj = polygon[j][0], yj = polygon[j][1]; const xj = polygon[j][0], yj = polygon[j][1];
var intersect = ((yi > y) != (yj > y)) const intersect = ((yi > y) != (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi); && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside; if (intersect) inside = !inside;
} }
return inside; return inside;
}; }

View file

@ -13,94 +13,94 @@
======================================================================== ========================================================================
*/ */
var areasSum = 0; let areasSum = 0;
var areas = []; const areas = [];
for(var q = 0; q < atlas.length; q++){ for (let q = 0; q < atlas.length; q++) {
var path = atlas[q].path; const path = atlas[q].path;
var area = 0, let area = 0,
i, i,
j, j,
point1, point1,
point2; point2;
for (i = 0, j = path.length - 1; i < path.length; j=i,i++) { for (i = 0, j = path.length - 1; i < path.length; j = i, i++) {
point1 = path[i]; point1 = path[i];
point2 = path[j]; point2 = path[j];
area += point1[0] * point2[1]; area += point1[0] * point2[1];
area -= point1[1] * point2[0]; area -= point1[1] * point2[0];
} }
area = Math.abs(area/2); area = Math.abs(area / 2);
areasSum += area; areasSum += area;
areas.push(area); areas.push(area);
atlas[q].area = area; atlas[q].area = area;
} }
areas.sort(function(a, b){ areas.sort(function (a, b) {
if (a < b) { if (a < b) {
return -1; return -1;
} }
if (a > b) { if (a > b) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
atlas.sort(function(a, b){ atlas.sort(function (a, b) {
if (a.area < b.area) { if (a.area < b.area) {
return -1; return -1;
} }
if (a.area > b.area) { if (a.area > b.area) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
var el = document.createElement("canvas"); const el = document.createElement("canvas");
el.style.position = "absolute"; el.style.position = "absolute";
el.style.top = "0px"; el.style.top = "0px";
el.style.zIndex = "10000"; el.style.zIndex = "10000";
var ctx = el.getContext("2d"); const ctx = el.getContext("2d");
el.width = 1600; el.width = 1600;
el.height = 500; el.height = 500;
var steps = 150; const steps = 150;
var max = 1500; const max = 1500;
var largerThanMax = 0; let largerThanMax = 0;
for(var i in areas){ for (const i in areas) {
if(areas[i] > max){ if (areas[i] > max) {
largerThanMax++; largerThanMax++;
} }
} }
console.log("There are "+largerThanMax+" entries larger than "+max+", accounting for "+(largerThanMax/areas.length*100)+"% of all entries."); console.log("There are " + largerThanMax + " entries larger than " + max + ", accounting for " + (largerThanMax / areas.length * 100) + "% of all entries.");
console.log("The largest entry has an area of "+areas[areas.length-1]+" pixels."); console.log("The largest entry has an area of " + areas[areas.length - 1] + " pixels.");
var counts = [0]; const counts = [0];
var brackets = [max/steps]; const brackets = [max / steps];
var bracket = 0; let bracket = 0;
var mostCounts = 0; let mostCounts = 0;
for(var i in areas){ for (const i in areas) {
if(areas[i] > (bracket+1)*(max/steps)){ if (areas[i] > (bracket + 1) * (max / steps)) {
mostCounts = Math.max(mostCounts, counts[bracket]); mostCounts = Math.max(mostCounts, counts[bracket]);
bracket++; bracket++;
if(bracket >= steps){ if (bracket >= steps) {
break; break;
} }
counts[bracket] = 0; counts[bracket] = 0;
brackets[bracket] = (bracket+1)*(max/steps); brackets[bracket] = (bracket + 1) * (max / steps);
} }
counts[bracket]++; counts[bracket]++;
} }
@ -117,17 +117,17 @@ ctx.font = "15px sans";
ctx.textAlign = "right"; ctx.textAlign = "right";
ctx.textBaseline = "middle"; ctx.textBaseline = "middle";
var linesDistance = 1; let linesDistance = 1;
for(var i = 0; i <= Math.ceil((mostCounts/linesDistance)/5)*5; i++){ for (let i = 0; i <= Math.ceil((mostCounts / linesDistance) / 5) * 5; i++) {
ctx.beginPath(); ctx.beginPath();
ctx.moveTo( ctx.moveTo(
50 50
,~~(el.height - 50 - i*(linesDistance/mostCounts)*(el.height-100))+0.5 , ~~(el.height - 50 - i * (linesDistance / mostCounts) * (el.height - 100)) + 0.5
); );
ctx.lineTo( ctx.lineTo(
el.width-25 el.width - 25
,~~(el.height - 50 - i*(linesDistance/mostCounts)*(el.height-100))+0.5 , ~~(el.height - 50 - i * (linesDistance / mostCounts) * (el.height - 100)) + 0.5
); );
ctx.stroke(); ctx.stroke();
} }
@ -135,56 +135,56 @@ for(var i = 0; i <= Math.ceil((mostCounts/linesDistance)/5)*5; i++){
ctx.strokeStyle = "#333333"; ctx.strokeStyle = "#333333";
linesDistance = 5; linesDistance = 5;
for(var i = 0; i <= Math.ceil(mostCounts/linesDistance); i++){ for (let i = 0; i <= Math.ceil(mostCounts / linesDistance); i++) {
ctx.beginPath(); ctx.beginPath();
ctx.moveTo( ctx.moveTo(
50 50
,~~(el.height - 50 - i*(linesDistance/mostCounts)*(el.height-100))+0.5 , ~~(el.height - 50 - i * (linesDistance / mostCounts) * (el.height - 100)) + 0.5
); );
ctx.lineTo( ctx.lineTo(
el.width-25 el.width - 25
,~~(el.height - 50 - i*(linesDistance/mostCounts)*(el.height-100))+0.5 , ~~(el.height - 50 - i * (linesDistance / mostCounts) * (el.height - 100)) + 0.5
); );
ctx.stroke(); ctx.stroke();
ctx.fillText( ctx.fillText(
i*linesDistance i * linesDistance
,40 , 40
,~~(el.height - 50 - i*(linesDistance/mostCounts)*(el.height-100))+0.5 , ~~(el.height - 50 - i * (linesDistance / mostCounts) * (el.height - 100)) + 0.5
); );
} }
var skip = 2; const skip = 2;
ctx.textAlign = "center"; ctx.textAlign = "center";
ctx.textBaseline = "hanging"; ctx.textBaseline = "hanging";
ctx.font = "10px sans"; ctx.font = "10px sans";
var a = 0; let a = 0;
for(var i=0; i <= counts.length; i++){ for (let i = 0; i <= counts.length; i++) {
if(i%skip == 0){ if (i % skip == 0) {
var y = 0; let y = 0;
if(a % 2 == 0){ if (a % 2 == 0) {
y = ~~(el.height - 30)+0.5; y = ~~(el.height - 30) + 0.5;
} else { } else {
y = ~~(el.height - 45)+0.5; y = ~~(el.height - 45) + 0.5;
} }
a++; a++;
ctx.beginPath(); ctx.beginPath();
ctx.moveTo( ctx.moveTo(
~~(((i)/steps)*(el.width-125)+75)+0.5 ~~(((i) / steps) * (el.width - 125) + 75) + 0.5
,~~(el.height - 50)+0.5 , ~~(el.height - 50) + 0.5
); );
ctx.lineTo( ctx.lineTo(
~~(((i)/steps)*(el.width-125)+75)+0.5 ~~(((i) / steps) * (el.width - 125) + 75) + 0.5
,y , y
); );
ctx.stroke(); ctx.stroke();
ctx.fillText( ctx.fillText(
(i)*(max/steps) (i) * (max / steps)
,~~(((i)/steps)*(el.width-125)+75)-0.5 , ~~(((i) / steps) * (el.width - 125) + 75) - 0.5
,y+5 , y + 5
); );
} }
} }
@ -192,18 +192,18 @@ for(var i=0; i <= counts.length; i++){
ctx.fillStyle = "#FF0000"; ctx.fillStyle = "#FF0000";
ctx.strokeStyle = "#CC0000"; ctx.strokeStyle = "#CC0000";
for(var i = 0; i < counts.length; i++){ for (let i = 0; i < counts.length; i++) {
if(i%2 == 0){ if (i % 2 == 0) {
ctx.fillStyle = "#FF0000"; ctx.fillStyle = "#FF0000";
} else { } else {
ctx.fillStyle = "#DD0000"; ctx.fillStyle = "#DD0000";
} }
ctx.fillRect( ctx.fillRect(
~~((i/steps)*(el.width-125)+75) ~~((i / steps) * (el.width - 125) + 75)
,el.height - 50 , el.height - 50
,Math.ceil(1/steps*(el.width-125)) , Math.ceil(1 / steps * (el.width - 125))
,~~(-(counts[i]/mostCounts)*(el.height-100)) , ~~(-(counts[i] / mostCounts) * (el.height - 100))
); );
/*ctx.beginPath(); /*ctx.beginPath();
@ -230,46 +230,46 @@ document.getElementById("wrapper").appendChild(el);
//console.log(areas); //console.log(areas);
console.log("Median area: "+areas[~~(areas.length/2)]); console.log("Median area: " + areas[~~(areas.length / 2)]);
console.log("Average area: "+(areasSum/atlas.length)); console.log("Average area: " + (areasSum / atlas.length));
var topCount = 50; const topCount = 50;
console.log("The "+topCount+" largest entries:"); console.log("The " + topCount + " largest entries:");
var outstring = ""; let outstring = "";
for(var i = 0; i < topCount; i++){ for (let i = 0; i < topCount; i++) {
outstring += ((i+1)+"|["+atlas[atlas.length-i-1].name +"](http://place-atlas.stefanocoding.me/?id="+atlas[atlas.length-i-1].id+")|"+ ~~atlas[atlas.length-i-1].area+"|"+Math.round(atlas[atlas.length-i-1].area/100)/100+"%\n"); outstring += ((i + 1) + "|[" + atlas[atlas.length - i - 1].name + "](http://place-atlas.stefanocoding.me/?id=" + atlas[atlas.length - i - 1].id + ")|" + ~~atlas[atlas.length - i - 1].area + "|" + Math.round(atlas[atlas.length - i - 1].area / 100) / 100 + "%\n");
} }
console.log(outstring); console.log(outstring);
atlas.sort(function(a, b){ atlas.sort(function (a, b) {
if (a.center[0] < b.center[0]) { if (a.center[0] < b.center[0]) {
return -1; return -1;
} }
if (a.center[0] > b.center[0]) { if (a.center[0] > b.center[0]) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
console.log("Median x: "+atlas[~~(atlas.length/2)].center[0]); console.log("Median x: " + atlas[~~(atlas.length / 2)].center[0]);
atlas.sort(function(a, b){ atlas.sort(function (a, b) {
if (a.center[1] < b.center[1]) { if (a.center[1] < b.center[1]) {
return -1; return -1;
} }
if (a.center[1] > b.center[1]) { if (a.center[1] > b.center[1]) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
}); });
console.log("Median y: "+atlas[~~(atlas.length/2)].center[1]); console.log("Median y: " + atlas[~~(atlas.length / 2)].center[1]);

View file

@ -14,73 +14,73 @@
*/ */
const variationsConfig = { const variationsConfig = {
default: { default: {
name: "r/place", name: "r/place",
code: "", code: "",
default: 14, default: 14,
versions: [ versions: [
{ {
timestamp: 1648822500, timestamp: 1648822500,
url: "./_img/place/1648822500.png" url: "./_img/place/1648822500.png"
}, },
{ {
timestamp: 1648847036, timestamp: 1648847036,
url: "./_img/place/1648847036.png" url: "./_img/place/1648847036.png"
}, },
{ {
timestamp: 1648870452, timestamp: 1648870452,
url: "./_img/place/1648870452.png" url: "./_img/place/1648870452.png"
}, },
{ {
timestamp: 1648893666, timestamp: 1648893666,
url: "./_img/place/1648893666.png" url: "./_img/place/1648893666.png"
}, },
{ {
timestamp: 1648917500, timestamp: 1648917500,
url: "./_img/place/1648917500.png" url: "./_img/place/1648917500.png"
}, },
{ {
timestamp: 1648942113, timestamp: 1648942113,
url: "./_img/place/1648942113.png" url: "./_img/place/1648942113.png"
}, },
{ {
timestamp: 1648956234, timestamp: 1648956234,
url: "./_img/place/1648956234.png" url: "./_img/place/1648956234.png"
}, },
{ {
timestamp: 1648968061, timestamp: 1648968061,
url: "./_img/place/1648968061.png" url: "./_img/place/1648968061.png"
}, },
{ {
timestamp: 1648979987, timestamp: 1648979987,
url: "./_img/place/1648979987.png" url: "./_img/place/1648979987.png"
}, },
{ {
timestamp: 1648992274, timestamp: 1648992274,
url: "./_img/place/1648992274.png" url: "./_img/place/1648992274.png"
}, },
{ {
timestamp: 1649012915, timestamp: 1649012915,
url: "./_img/place/1649012915.png" url: "./_img/place/1649012915.png"
}, },
{ {
timestamp: 1649037182, timestamp: 1649037182,
url: "./_img/place/1649037182.png" url: "./_img/place/1649037182.png"
}, },
{ {
timestamp: 1649060793, timestamp: 1649060793,
url: "./_img/place/1649060793.png" url: "./_img/place/1649060793.png"
}, },
{ {
timestamp: 1649084741, timestamp: 1649084741,
url: "./_img/place/1649084741.png" url: "./_img/place/1649084741.png"
}, },
{ {
timestamp: 1649113199, timestamp: 1649113199,
url: "./_img/place/final.png" url: "./_img/place/final.png"
} }
] ]
} }
} }
const codeReference = {} const codeReference = {}
@ -89,11 +89,11 @@ const imageCache = {}
const variantsEl = document.getElementById("variants") const variantsEl = document.getElementById("variants")
for (const variation in variationsConfig) { for (const variation in variationsConfig) {
codeReference[variationsConfig[variation].code] = variation codeReference[variationsConfig[variation].code] = variation
const optionEl = document.createElement('option') const optionEl = document.createElement('option')
optionEl.value = variation optionEl.value = variation
optionEl.textContent = variationsConfig[variation].name optionEl.textContent = variationsConfig[variation].name
variantsEl.appendChild(optionEl) variantsEl.appendChild(optionEl)
} }
const timelineSlider = document.getElementById("timeControlsSlider"); const timelineSlider = document.getElementById("timeControlsSlider");
@ -114,15 +114,15 @@ timelineSlider.max = variationsConfig[currentVariation].versions.length - 1;
timelineSlider.value = currentPeriod; timelineSlider.value = currentPeriod;
timelineSlider.addEventListener("input", (event) => { timelineSlider.addEventListener("input", (event) => {
updateTooltip(parseInt(event.target.value), currentVariation) updateTooltip(parseInt(event.target.value), currentVariation)
clearTimeout(updateTimeout) clearTimeout(updateTimeout)
updateTimeout = setTimeout(() => { updateTimeout = setTimeout(() => {
updateTime(parseInt(event.target.value), currentVariation) updateTime(parseInt(event.target.value), currentVariation)
}, 100) }, 10)
}) })
variantsEl.addEventListener("input", (event) => { variantsEl.addEventListener("input", (event) => {
updateTime(currentPeriod, event.target.value) updateTime(currentPeriod, event.target.value)
}) })
// document.querySelector('#period-group .period-start').oninput = (event) => { // document.querySelector('#period-group .period-start').oninput = (event) => {
@ -136,140 +136,140 @@ variantsEl.addEventListener("input", (event) => {
// }; // };
const dispatchTimeUpdateEvent = (period = timelineSlider.value, atlas = atlas) => { const dispatchTimeUpdateEvent = (period = timelineSlider.value, atlas = atlas) => {
const timeUpdateEvent = new CustomEvent('timeupdate', { const timeUpdateEvent = new CustomEvent('timeupdate', {
detail: { detail: {
period: period, period: period,
atlas: atlas atlas: atlas
} }
}); });
document.dispatchEvent(timeUpdateEvent); document.dispatchEvent(timeUpdateEvent);
} }
async function updateBackground(newPeriod = currentPeriod, newVariation = currentVariation) { async function updateBackground(newPeriod = currentPeriod, newVariation = currentVariation) {
console.log(newPeriod, newVariation) console.log(newPeriod, newVariation)
abortController.abort() abortController.abort()
abortController = new AbortController() abortController = new AbortController()
currentUpdateIndex++ currentUpdateIndex++
const myUpdateIndex = currentUpdateIndex const myUpdateIndex = currentUpdateIndex
currentPeriod = newPeriod currentPeriod = newPeriod
// console.log(newPeriod, newVariation) // console.log(newPeriod, newVariation)
const variationConfig = variationsConfig[newVariation] const variationConfig = variationsConfig[newVariation]
if (currentVariation !== newVariation) { if (currentVariation !== newVariation) {
currentVariation = newVariation currentVariation = newVariation
timelineSlider.max = variationConfig.versions.length - 1; timelineSlider.max = variationConfig.versions.length - 1;
currentPeriod = variationConfig.default; currentPeriod = variationConfig.default;
newPeriod = currentPeriod newPeriod = currentPeriod
} }
timelineSlider.value = currentPeriod timelineSlider.value = currentPeriod
variantsEl.value = currentVariation variantsEl.value = currentVariation
const configObject = variationConfig.versions[currentPeriod]; const configObject = variationConfig.versions[currentPeriod];
if (typeof configObject.url === "string") { if (typeof configObject.url === "string") {
if (imageCache[configObject.url] === undefined) { if (imageCache[configObject.url] === undefined) {
const fetchResult = await fetch(configObject.url, { const fetchResult = await fetch(configObject.url, {
signal: abortController.signal signal: abortController.signal
}); });
if (currentUpdateIndex !== myUpdateIndex) { if (currentUpdateIndex !== myUpdateIndex) {
hideLoading() hideLoading()
return return
} }
const imageBlob = await fetchResult.blob() const imageBlob = await fetchResult.blob()
imageCache[configObject.url] = URL.createObjectURL(imageBlob) imageCache[configObject.url] = URL.createObjectURL(imageBlob)
} }
image.src = imageCache[configObject.url] image.src = imageCache[configObject.url]
} else { } else {
const canvas = document.createElement('canvas') const canvas = document.createElement('canvas')
const context = canvas.getContext('2d') const context = canvas.getContext('2d')
context.canvas.width = 2000 context.canvas.width = 2000
context.canvas.height = 2000 context.canvas.height = 2000
for await (const url of configObject.url) { for await (const url of configObject.url) {
if (imageCache[url] === undefined) { if (imageCache[url] === undefined) {
const fetchResult = await fetch(url, { const fetchResult = await fetch(url, {
signal: abortController.signal signal: abortController.signal
}); });
if (currentUpdateIndex !== myUpdateIndex) { if (currentUpdateIndex !== myUpdateIndex) {
hideLoading() hideLoading()
break break
} }
const imageBlob = await fetchResult.blob() const imageBlob = await fetchResult.blob()
imageCache[url] = URL.createObjectURL(imageBlob) imageCache[url] = URL.createObjectURL(imageBlob)
} }
const imageLayer = new Image() const imageLayer = new Image()
console.log(imageCache[url]) console.log(imageCache[url])
await new Promise(resolve => { await new Promise(resolve => {
imageLayer.onload = () => { imageLayer.onload = () => {
context.drawImage(imageLayer, 0, 0) context.drawImage(imageLayer, 0, 0)
console.log("image done") console.log("image done")
resolve() resolve()
} }
imageLayer.src = imageCache[url] imageLayer.src = imageCache[url]
}) })
}
if (currentUpdateIndex !== myUpdateIndex) return
const blob = await new Promise(resolve => canvas.toBlob(resolve))
console.log(URL.createObjectURL(blob))
image.src = URL.createObjectURL(blob)
}
return [configObject, newPeriod, newVariation] }
if (currentUpdateIndex !== myUpdateIndex) return
const blob = await new Promise(resolve => canvas.toBlob(resolve))
console.log(URL.createObjectURL(blob))
image.src = URL.createObjectURL(blob)
}
return [configObject, newPeriod, newVariation]
} }
async function updateTime(newPeriod = currentPeriod, newVariation = currentVariation) { async function updateTime(newPeriod = currentPeriod, newVariation = currentVariation) {
document.body.dataset.canvasLoading = true document.body.dataset.canvasLoading = true
let configObject let configObject
[configObject, newPeriod, newVariation] = await updateBackground(newPeriod, newVariation) [configObject, newPeriod, newVariation] = await updateBackground(newPeriod, newVariation)
atlas = []
for ( var atlasIndex in atlasAll ) {
let pathChosen, centerChosen, chosenIndex
const validPeriods2 = Object.keys(atlasAll[atlasIndex].path) atlas = []
for (const atlasIndex in atlasAll) {
let pathChosen, centerChosen, chosenIndex
// console.log(chosenIndex) const validPeriods2 = Object.keys(atlasAll[atlasIndex].path)
for (const i in validPeriods2) { // console.log(chosenIndex)
const validPeriods = validPeriods2[i].split(', ')
for (const j in validPeriods) {
const [start, end, variation] = parsePeriod(validPeriods[j])
// console.log(start, end, variation, newPeriod, newVariation)
if (isOnPeriod(start, end, variation, newPeriod, newVariation)) {
// console.log("match", start, end, variation, newPeriod, newVariation, i)
chosenIndex = i
break
}
}
if (chosenIndex !== undefined) break
}
// console.log(testMatches) for (const i in validPeriods2) {
const validPeriods = validPeriods2[i].split(', ')
for (const j in validPeriods) {
const [start, end, variation] = parsePeriod(validPeriods[j])
// console.log(start, end, variation, newPeriod, newVariation)
if (isOnPeriod(start, end, variation, newPeriod, newVariation)) {
// console.log("match", start, end, variation, newPeriod, newVariation, i)
chosenIndex = i
break
}
}
if (chosenIndex !== undefined) break
}
// console.log(chosenIndex) // console.log(testMatches)
if (chosenIndex === undefined) continue
pathChosen = Object.values(atlasAll[atlasIndex].path)[chosenIndex]
centerChosen = Object.values(atlasAll[atlasIndex].center)[chosenIndex]
if (pathChosen === undefined) continue // console.log(chosenIndex)
if (chosenIndex === undefined) continue
pathChosen = Object.values(atlasAll[atlasIndex].path)[chosenIndex]
centerChosen = Object.values(atlasAll[atlasIndex].center)[chosenIndex]
// console.log(123) if (pathChosen === undefined) continue
atlas.push({ // console.log(123)
...atlasAll[atlasIndex],
path: pathChosen,
center: centerChosen,
})
}
// console.log(atlas)
dispatchTimeUpdateEvent(newPeriod, atlas) atlas.push({
document.body.dataset.canvasLoading = false ...atlasAll[atlasIndex],
path: pathChosen,
center: centerChosen,
})
}
// console.log(atlas)
dispatchTimeUpdateEvent(newPeriod, atlas)
document.body.dataset.canvasLoading = false
} }
function updateTooltip(newPeriod, newVariation) { function updateTooltip(newPeriod, newVariation) {
var configObject = variationsConfig[newVariation].versions[newPeriod] const configObject = variationsConfig[newVariation].versions[newPeriod]
if (typeof configObject.timestamp === "number") tooltip.querySelector('p').textContent = new Date(configObject.timestamp*1000).toUTCString() if (typeof configObject.timestamp === "number") tooltip.querySelector('p').textContent = new Date(configObject.timestamp * 1000).toUTCString()
else tooltip.querySelector('p').textContent = configObject.timestamp else tooltip.querySelector('p').textContent = configObject.timestamp
tooltip.style.left = Math.max(((timelineSlider.offsetWidth)*(timelineSlider.value >= 1 ? timelineSlider.value - 1:0)/(timelineSlider.max-1)) - tooltip.offsetWidth/2, 0) + "px" tooltip.style.left = Math.max(((timelineSlider.offsetWidth) * (timelineSlider.value >= 1 ? timelineSlider.value - 1 : 0) / (timelineSlider.max - 1)) - tooltip.offsetWidth / 2, 0) + "px"
} }
tooltip.parentElement.addEventListener('mouseenter', () => updateTooltip(parseInt(timelineSlider.value), currentVariation)) tooltip.parentElement.addEventListener('mouseenter', () => updateTooltip(parseInt(timelineSlider.value), currentVariation))
@ -277,20 +277,20 @@ tooltip.parentElement.addEventListener('mouseenter', () => updateTooltip(parseIn
window.addEventListener('resize', () => updateTooltip(parseInt(timelineSlider.value), currentVariation)) window.addEventListener('resize', () => updateTooltip(parseInt(timelineSlider.value), currentVariation))
function isOnPeriod(start, end, variation, currentPeriod, currentVariation) { function isOnPeriod(start, end, variation, currentPeriod, currentVariation) {
return currentPeriod >= start && currentPeriod <= end && variation === currentVariation return currentPeriod >= start && currentPeriod <= end && variation === currentVariation
} }
function parsePeriod(periodString) { function parsePeriod(periodString) {
// console.log(periodString) // console.log(periodString)
let variation = "default" let variation = "default"
periodString = periodString + "" periodString = periodString + ""
if (periodString.split(':').length > 1) { if (periodString.split(':').length > 1) {
const split = periodString.split(':') const split = periodString.split(':')
variation = codeReference[split[0]] variation = codeReference[split[0]]
periodString = split[1] periodString = split[1]
} }
if (periodString.search('-') + 1) { if (periodString.search('-') + 1) {
var [start, end] = periodString.split('-').map(i => parseInt(i)) const [start, end] = periodString.split('-').map(i => parseInt(i))
return [start, end, variation] return [start, end, variation]
} else { } else {
const periodNew = parseInt(periodString) const periodNew = parseInt(periodString)

View file

@ -13,65 +13,65 @@
======================================================================== ========================================================================
*/ */
var linesCanvas = document.getElementById("linesCanvas"); const linesCanvas = document.getElementById("linesCanvas");
var linesContext = linesCanvas.getContext("2d"); const linesContext = linesCanvas.getContext("2d");
var hovered = []; let hovered = [];
var previousZoomOrigin = [0, 0]; let previousZoomOrigin = [0, 0];
var previousScaleZoomOrigin = [0, 0]; let previousScaleZoomOrigin = [0, 0];
var backgroundCanvas = document.createElement("canvas"); const backgroundCanvas = document.createElement("canvas");
backgroundCanvas.width = 2000; backgroundCanvas.width = 2000;
backgroundCanvas.height = 2000; backgroundCanvas.height = 2000;
var backgroundContext = backgroundCanvas.getContext("2d"); const backgroundContext = backgroundCanvas.getContext("2d");
var wrapper = document.getElementById("wrapper"); const wrapper = document.getElementById("wrapper");
var objectsContainer = document.getElementById("objectsList");
var closeObjectsListButton = document.getElementById("closeObjectsListButton");
var filterInput = document.getElementById("searchList"); const objectsContainer = document.getElementById("objectsList");
const closeObjectsListButton = document.getElementById("closeObjectsListButton");
var entriesList = document.getElementById("entriesList"); const filterInput = document.getElementById("searchList");
var hideListButton = document.getElementById("hideListButton");
var entriesListShown = false;
var sortedAtlas; const entriesList = document.getElementById("entriesList");
const hideListButton = document.getElementById("hideListButton");
let entriesListShown = false;
var entriesLimit = 50; let sortedAtlas;
var entriesOffset = 0;
var moreEntriesButton = document.createElement("button"); const entriesLimit = 50;
moreEntriesButton.innerHTML = "Show "+entriesLimit+" more"; let entriesOffset = 0;
const moreEntriesButton = document.createElement("button");
moreEntriesButton.innerHTML = "Show " + entriesLimit + " more";
moreEntriesButton.id = "moreEntriesButton"; moreEntriesButton.id = "moreEntriesButton";
moreEntriesButton.onclick = function(){ moreEntriesButton.onclick = function () {
buildObjectsList(null, null); buildObjectsList(null, null);
renderBackground(); renderBackground();
render(); render();
}; };
var defaultSort = "shuffle"; let defaultSort = "shuffle";
document.getElementById("sort").value = defaultSort; document.getElementById("sort").value = defaultSort;
var lastPos = [0, 0]; let lastPos = [0, 0];
var fixed = false; // Fix hovered items in place, so that clicking on links is possible let fixed = false; // Fix hovered items in place, so that clicking on links is possible
if(document.documentElement.clientWidth > 2000){ if (document.documentElement.clientWidth > 2000) {
entriesListShown = true; entriesListShown = true;
wrapper.classList.remove('listHidden') wrapper.classList.remove('listHidden')
} }
if(document.documentElement.clientWidth < 2000){ if (document.documentElement.clientWidth < 2000) {
entriesListShown = false; entriesListShown = false;
wrapper.classList.add('listHidden') wrapper.classList.add('listHidden')
} }
filterInput.addEventListener("input", function(e){ filterInput.addEventListener("input", function (e) {
entriesOffset = 0; entriesOffset = 0;
entriesList.innerHTML = ""; entriesList.innerHTML = "";
entriesList.appendChild(moreEntriesButton); entriesList.appendChild(moreEntriesButton);
if(this.value === ""){ if (this.value === "") {
document.getElementById("relevantOption").disabled = true; document.getElementById("relevantOption").disabled = true;
sortedAtlas = atlas.concat(); sortedAtlas = atlas.concat();
buildObjectsList(null, null); buildObjectsList(null, null);
@ -82,8 +82,8 @@ filterInput.addEventListener("input", function(e){
}); });
document.getElementById("sort").addEventListener("input", function(e){ document.getElementById("sort").addEventListener("input", function (e) {
if(this.value != "relevant"){ if (this.value != "relevant") {
defaultSort = this.value; defaultSort = this.value;
} }
@ -91,9 +91,9 @@ document.getElementById("sort").addEventListener("input", function(e){
}); });
hideListButton.addEventListener("click", function(e){ hideListButton.addEventListener("click", function (e) {
entriesListShown = !entriesListShown; entriesListShown = !entriesListShown;
if(entriesListShown){ if (entriesListShown) {
wrapper.classList.remove('listHidden') wrapper.classList.remove('listHidden')
} else { } else {
wrapper.classList.add('listHidden') wrapper.classList.add('listHidden')
@ -105,7 +105,7 @@ hideListButton.addEventListener("click", function(e){
return false; return false;
}); });
closeObjectsListButton.addEventListener("click", function(e){ closeObjectsListButton.addEventListener("click", function (e) {
hovered = []; hovered = [];
objectsContainer.innerHTML = ""; objectsContainer.innerHTML = "";
updateLines(); updateLines();
@ -115,12 +115,12 @@ closeObjectsListButton.addEventListener("click", function(e){
}); });
function toggleFixed(e, tapped){ function toggleFixed(e, tapped) {
if(!fixed && hovered.length == 0){ if (!fixed && hovered.length == 0) {
return 0; return 0;
} }
fixed = !fixed; fixed = !fixed;
if(!fixed){ if (!fixed) {
updateHovering(e, tapped); updateHovering(e, tapped);
render(); render();
} }
@ -132,56 +132,56 @@ window.addEventListener("dblClick", updateLines);
window.addEventListener("wheel", updateLines); window.addEventListener("wheel", updateLines);
objectsContainer.addEventListener("scroll", function(e){ objectsContainer.addEventListener("scroll", function (e) {
updateLines(); updateLines();
}); });
window.addEventListener("resize", function(e){ window.addEventListener("resize", function (e) {
//console.log(document.documentElement.clientWidth, document.documentElement.clientHeight); //console.log(document.documentElement.clientWidth, document.documentElement.clientHeight);
var viewportWidth = document.documentElement.clientWidth; let viewportWidth = document.documentElement.clientWidth;
if(document.documentElement.clientWidth > 2000 && viewportWidth <= 2000){ if (document.documentElement.clientWidth > 2000 && viewportWidth <= 2000) {
entriesListShown = true; entriesListShown = true;
wrapper.className = wrapper.className.replace(/ listHidden/g, ""); wrapper.className = wrapper.className.replace(/ listHidden/g, "");
} }
if(document.documentElement.clientWidth < 2000 && viewportWidth >= 2000){ if (document.documentElement.clientWidth < 2000 && viewportWidth >= 2000) {
entriesListShown = false; entriesListShown = false;
wrapper.className += " listHidden"; wrapper.className += " listHidden";
} }
updateHovering(e); updateHovering(e);
viewportWidth = document.documentElement.clientWidth; viewportWidth = document.documentElement.clientWidth;
applyView(); applyView();
render(); render();
updateLines(); updateLines();
}); });
function updateLines(){ function updateLines() {
linesCanvas.width = linesCanvas.clientWidth; linesCanvas.width = linesCanvas.clientWidth;
linesCanvas.height = linesCanvas.clientHeight; linesCanvas.height = linesCanvas.clientHeight;
linesContext.lineCap = "round"; linesContext.lineCap = "round";
linesContext.lineWidth = Math.max(Math.min(zoom*1.5, 16*1.5), 6); linesContext.lineWidth = Math.max(Math.min(zoom * 1.5, 16 * 1.5), 6);
linesContext.strokeStyle = "#000000"; linesContext.strokeStyle = "#000000";
for(var i = 0; i < hovered.length; i++){ for (let i = 0; i < hovered.length; i++) {
var element = hovered[i].element; const element = hovered[i].element;
if(element.getBoundingClientRect().left != 0){ if (element.getBoundingClientRect().left != 0) {
linesContext.beginPath(); linesContext.beginPath();
//linesContext.moveTo(element.offsetLeft + element.clientWidth - 10, element.offsetTop + 20); //linesContext.moveTo(element.offsetLeft + element.clientWidth - 10, element.offsetTop + 20);
linesContext.moveTo( linesContext.moveTo(
element.getBoundingClientRect().left + document.documentElement.scrollLeft + element.clientWidth/2 element.getBoundingClientRect().left + document.documentElement.scrollLeft + element.clientWidth / 2
,element.getBoundingClientRect().top + document.documentElement.scrollTop + 20 , element.getBoundingClientRect().top + document.documentElement.scrollTop + 20
); );
linesContext.lineTo( linesContext.lineTo(
~~(hovered[i].center[0]*zoom) + innerContainer.offsetLeft ~~(hovered[i].center[0] * zoom) + innerContainer.offsetLeft
,~~(hovered[i].center[1]*zoom) + innerContainer.offsetTop , ~~(hovered[i].center[1] * zoom) + innerContainer.offsetTop
); );
linesContext.stroke(); linesContext.stroke();
@ -191,26 +191,26 @@ function updateLines(){
linesContext.lineWidth = Math.max(Math.min(zoom, 16), 4); linesContext.lineWidth = Math.max(Math.min(zoom, 16), 4);
linesContext.strokeStyle = "#FFFFFF"; linesContext.strokeStyle = "#FFFFFF";
for(var i = 0; i < hovered.length; i++){ for (let i = 0; i < hovered.length; i++) {
var element = hovered[i].element; const element = hovered[i].element;
if (element.getBoundingClientRect().left != 0) {
if(element.getBoundingClientRect().left != 0){
linesContext.beginPath(); linesContext.beginPath();
linesContext.moveTo( linesContext.moveTo(
element.getBoundingClientRect().left + document.documentElement.scrollLeft + element.clientWidth/2 element.getBoundingClientRect().left + document.documentElement.scrollLeft + element.clientWidth / 2
,element.getBoundingClientRect().top + document.documentElement.scrollTop + 20 , element.getBoundingClientRect().top + document.documentElement.scrollTop + 20
); );
linesContext.lineTo( linesContext.lineTo(
~~(hovered[i].center[0]*zoom) + innerContainer.offsetLeft ~~(hovered[i].center[0] * zoom) + innerContainer.offsetLeft
,~~(hovered[i].center[1]*zoom) + innerContainer.offsetTop , ~~(hovered[i].center[1] * zoom) + innerContainer.offsetTop
); );
linesContext.stroke(); linesContext.stroke();
} }
} }
} }
function renderBackground(atlas){ function renderBackground(atlas) {
backgroundContext.clearRect(0, 0, canvas.width, canvas.height); backgroundContext.clearRect(0, 0, canvas.width, canvas.height);
@ -218,29 +218,29 @@ function renderBackground(atlas){
//backgroundCanvas.height = 1000 * zoom; //backgroundCanvas.height = 1000 * zoom;
//backgroundContext.lineWidth = zoom; //backgroundContext.lineWidth = zoom;
backgroundContext.fillStyle = "rgba(0, 0, 0, 0.6)"; backgroundContext.fillStyle = "rgba(0, 0, 0, 0.6)";
backgroundContext.fillRect(0, 0, backgroundCanvas.width, backgroundCanvas.height); backgroundContext.fillRect(0, 0, backgroundCanvas.width, backgroundCanvas.height);
for(var i = 0; i < atlas.length; i++){ for (let i = 0; i < atlas.length; i++) {
var path = atlas[i].path; const path = atlas[i].path;
backgroundContext.beginPath(); backgroundContext.beginPath();
if(path[0]){ if (path[0]) {
//backgroundContext.moveTo(path[0][0]*zoom, path[0][1]*zoom); //backgroundContext.moveTo(path[0][0]*zoom, path[0][1]*zoom);
backgroundContext.moveTo(path[0][0], path[0][1]); backgroundContext.moveTo(path[0][0], path[0][1]);
} }
for(var p = 1; p < path.length; p++){ for (let p = 1; p < path.length; p++) {
//backgroundContext.lineTo(path[p][0]*zoom, path[p][1]*zoom); //backgroundContext.lineTo(path[p][0]*zoom, path[p][1]*zoom);
backgroundContext.lineTo(path[p][0], path[p][1]); backgroundContext.lineTo(path[p][0], path[p][1]);
} }
backgroundContext.closePath(); backgroundContext.closePath();
var bgStrokeStyle; let bgStrokeStyle;
switch (atlas[i].diff) { switch (atlas[i].diff) {
case "add": case "add":
bgStrokeStyle = "rgba(0, 255, 0, 1)"; bgStrokeStyle = "rgba(0, 255, 0, 1)";
@ -264,32 +264,32 @@ function renderBackground(atlas){
} }
} }
function buildObjectsList(filter = null, sort = null){ function buildObjectsList(filter = null, sort = null) {
if(entriesList.contains(moreEntriesButton)){ if (entriesList.contains(moreEntriesButton)) {
entriesList.removeChild(moreEntriesButton); entriesList.removeChild(moreEntriesButton);
} }
if(!sortedAtlas){ if (!sortedAtlas) {
sortedAtlas = atlas.concat(); sortedAtlas = atlas.concat();
document.getElementById("atlasSize").innerHTML = "The Atlas contains "+sortedAtlas.length+" entries."; document.getElementById("atlasSize").innerHTML = "The Atlas contains " + sortedAtlas.length + " entries.";
} }
if(filter){ if (filter) {
sortedAtlas = atlas.filter(function(value){ sortedAtlas = atlas.filter(function (value) {
return ( return (
value.name.toLowerCase().indexOf(filter) !== -1 value.name.toLowerCase().indexOf(filter) !== -1
|| value.description.toLowerCase().indexOf(filter) !== -1 || value.description.toLowerCase().indexOf(filter) !== -1
|| value.subreddit && value.subreddit.toLowerCase().indexOf(filter) !== -1 || value.subreddit && value.subreddit.toLowerCase().indexOf(filter) !== -1
|| value.id === filter || value.id === filter
); );
}); });
document.getElementById("atlasSize").innerHTML = "Found "+sortedAtlas.length+" entries."; document.getElementById("atlasSize").innerHTML = "Found " + sortedAtlas.length + " entries.";
} else { } else {
document.getElementById("atlasSize").innerHTML = "The Atlas contains "+sortedAtlas.length+" entries."; document.getElementById("atlasSize").innerHTML = "The Atlas contains " + sortedAtlas.length + " entries.";
} }
if(sort === null){ if (sort === null) {
sort = defaultSort; sort = defaultSort;
} }
@ -300,59 +300,59 @@ function buildObjectsList(filter = null, sort = null){
//console.log(sort); //console.log(sort);
var sortFunction; let sortFunction;
//console.log(sort); //console.log(sort);
switch(sort){ switch (sort) {
case "shuffle": case "shuffle":
sortFunction = null; sortFunction = null;
if(entriesOffset == 0){ if (entriesOffset == 0) {
shuffle(); shuffle();
} }
break; break;
case "alphaAsc": case "alphaAsc":
sortFunction = function(a, b){ sortFunction = function (a, b) {
return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
} }
break; break;
case "alphaDesc": case "alphaDesc":
sortFunction = function(a, b){ sortFunction = function (a, b) {
return b.name.toLowerCase().localeCompare(a.name.toLowerCase()); return b.name.toLowerCase().localeCompare(a.name.toLowerCase());
} }
break; break;
case "newest": case "newest":
sortFunction = function(a, b){ sortFunction = function (a, b) {
if (a.id > b.id) { if (a.id > b.id) {
return -1; return -1;
} }
if (a.id < b.id) { if (a.id < b.id) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
} }
break; break;
case "oldest": case "oldest":
sortFunction = function(a, b){ sortFunction = function (a, b) {
if (a.id < b.id) { if (a.id < b.id) {
return -1; return -1;
} }
if (a.id > b.id) { if (a.id > b.id) {
return 1; return 1;
} }
// a must be equal to b // a must be equal to b
return 0; return 0;
} }
break; break;
case "area": case "area":
sortFunction = function(a, b){ sortFunction = function (a, b) {
return calcPolygonArea(b.path) - calcPolygonArea(a.path); return calcPolygonArea(b.path) - calcPolygonArea(a.path);
} }
break; break;
case "relevant": case "relevant":
sortFunction = function(a, b){ sortFunction = function (a, b) {
if(a.name.toLowerCase().indexOf(filter) !== -1 && b.name.toLowerCase().indexOf(filter) !== -1){ if (a.name.toLowerCase().indexOf(filter) !== -1 && b.name.toLowerCase().indexOf(filter) !== -1) {
if (a.name.toLowerCase().indexOf(filter) < b.name.toLowerCase().indexOf(filter)) { if (a.name.toLowerCase().indexOf(filter) < b.name.toLowerCase().indexOf(filter)) {
return -1; return -1;
} }
@ -361,9 +361,9 @@ function buildObjectsList(filter = null, sort = null){
} else { } else {
return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
} }
} else if(a.name.toLowerCase().indexOf(filter) !== -1){ } else if (a.name.toLowerCase().indexOf(filter) !== -1) {
return -1; return -1;
} else if(b.name.toLowerCase().indexOf(filter) !== -1){ } else if (b.name.toLowerCase().indexOf(filter) !== -1) {
return 1; return 1;
} else { } else {
if (a.description.toLowerCase().indexOf(filter) < b.description.toLowerCase().indexOf(filter)) { if (a.description.toLowerCase().indexOf(filter) < b.description.toLowerCase().indexOf(filter)) {
@ -376,47 +376,47 @@ function buildObjectsList(filter = null, sort = null){
} }
} }
} }
break; break;
} }
if(sortFunction){ if (sortFunction) {
sortedAtlas.sort(sortFunction); sortedAtlas.sort(sortFunction);
} }
for(var i = entriesOffset; i < entriesOffset+entriesLimit; i++){ for (let i = entriesOffset; i < entriesOffset + entriesLimit; i++) {
if(i >= sortedAtlas.length){ if (i >= sortedAtlas.length) {
break; break;
} }
// console.log(sortedAtlas[i]) // console.log(sortedAtlas[i])
var element = createInfoBlock(sortedAtlas[i]); const element = createInfoBlock(sortedAtlas[i]);
element.entry = sortedAtlas[i]; element.entry = sortedAtlas[i];
element.addEventListener("mouseenter", function(e){ element.addEventListener("mouseenter", function (e) {
if(!fixed && !dragging){ if (!fixed && !dragging) {
objectsContainer.innerHTML = ""; objectsContainer.innerHTML = "";
previousZoomOrigin = [zoomOrigin[0], zoomOrigin[1]]; previousZoomOrigin = [zoomOrigin[0], zoomOrigin[1]];
previousScaleZoomOrigin = [scaleZoomOrigin[0], scaleZoomOrigin[1]]; previousScaleZoomOrigin = [scaleZoomOrigin[0], scaleZoomOrigin[1]];
applyView(); applyView();
zoomOrigin = [ zoomOrigin = [
innerContainer.clientWidth/2 - this.entry.center[0]* zoom// + container.offsetLeft innerContainer.clientWidth / 2 - this.entry.center[0] * zoom// + container.offsetLeft
,innerContainer.clientHeight/2 - this.entry.center[1]* zoom// + container.offsetTop , innerContainer.clientHeight / 2 - this.entry.center[1] * zoom// + container.offsetTop
] ]
scaleZoomOrigin = [ scaleZoomOrigin = [
2000/2 - this.entry.center[0] 2000 / 2 - this.entry.center[0]
,2000/2 - this.entry.center[1] , 2000 / 2 - this.entry.center[1]
] ]
//console.log(zoomOrigin); //console.log(zoomOrigin);
applyView(); applyView();
hovered = [this.entry]; hovered = [this.entry];
render(); render();
@ -426,14 +426,14 @@ function buildObjectsList(filter = null, sort = null){
}); });
element.addEventListener("click", function(e){ element.addEventListener("click", function (e) {
toggleFixed(e); toggleFixed(e);
if(fixed){ if (fixed) {
previousZoomOrigin = [zoomOrigin[0], zoomOrigin[1]]; previousZoomOrigin = [zoomOrigin[0], zoomOrigin[1]];
previousScaleZoomOrigin = [scaleZoomOrigin[0], scaleZoomOrigin[1]]; previousScaleZoomOrigin = [scaleZoomOrigin[0], scaleZoomOrigin[1]];
applyView(); applyView();
} }
if(document.documentElement.clientWidth < 500){ if (document.documentElement.clientWidth < 500) {
objectsContainer.innerHTML = ""; objectsContainer.innerHTML = "";
entriesListShown = false; entriesListShown = false;
@ -443,15 +443,15 @@ function buildObjectsList(filter = null, sort = null){
renderBackground(atlas); renderBackground(atlas);
applyView(); applyView();
updateHovering(e); updateHovering(e);
zoomOrigin = [ zoomOrigin = [
innerContainer.clientWidth/2 - this.entry.center[0]* zoom// + container.offsetLeft innerContainer.clientWidth / 2 - this.entry.center[0] * zoom// + container.offsetLeft
,innerContainer.clientHeight/2 - this.entry.center[1]* zoom// + container.offsetTop , innerContainer.clientHeight / 2 - this.entry.center[1] * zoom// + container.offsetTop
] ]
scaleZoomOrigin = [ scaleZoomOrigin = [
2000/2 - this.entry.center[0] 2000 / 2 - this.entry.center[0]
,2000/2 - this.entry.center[1] , 2000 / 2 - this.entry.center[1]
] ]
previousZoomOrigin = [zoomOrigin[0], zoomOrigin[1]]; previousZoomOrigin = [zoomOrigin[0], zoomOrigin[1]];
@ -461,18 +461,18 @@ function buildObjectsList(filter = null, sort = null){
hovered = [this.entry]; hovered = [this.entry];
hovered[0].element = this; hovered[0].element = this;
applyView(); applyView();
render(); render();
updateLines(); updateLines();
} }
}); });
element.addEventListener("mouseleave", function(e){ element.addEventListener("mouseleave", function (e) {
if(!fixed && !dragging){ if (!fixed && !dragging) {
zoomOrigin = [previousScaleZoomOrigin[0]*zoom, previousScaleZoomOrigin[1]*zoom]; zoomOrigin = [previousScaleZoomOrigin[0] * zoom, previousScaleZoomOrigin[1] * zoom];
scaleZoomOrigin = [previousScaleZoomOrigin[0], previousScaleZoomOrigin[1]]; scaleZoomOrigin = [previousScaleZoomOrigin[0], previousScaleZoomOrigin[1]];
applyView(); applyView();
hovered = []; hovered = [];
@ -487,17 +487,17 @@ function buildObjectsList(filter = null, sort = null){
entriesOffset += entriesLimit; entriesOffset += entriesLimit;
if(sortedAtlas.length > entriesOffset){ if (sortedAtlas.length > entriesOffset) {
moreEntriesButton.innerHTML = "Show "+Math.min(entriesLimit, sortedAtlas.length - entriesOffset)+" more"; moreEntriesButton.innerHTML = "Show " + Math.min(entriesLimit, sortedAtlas.length - entriesOffset) + " more";
entriesList.appendChild(moreEntriesButton); entriesList.appendChild(moreEntriesButton);
} }
} }
function shuffle(){ function shuffle() {
//console.log("shuffled atlas"); //console.log("shuffled atlas");
for (var i = sortedAtlas.length - 1; i > 0; i--) { for (let i = sortedAtlas.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1)); const j = Math.floor(Math.random() * (i + 1));
var temp = sortedAtlas[i]; const temp = sortedAtlas[i];
sortedAtlas[i] = sortedAtlas[j]; sortedAtlas[i] = sortedAtlas[j];
sortedAtlas[j] = temp; sortedAtlas[j] = temp;
} }
@ -512,36 +512,36 @@ function resetEntriesList() {
} }
async function render(){ async function render() {
context.clearRect(0, 0, canvas.width, canvas.height); context.clearRect(0, 0, canvas.width, canvas.height);
//canvas.width = 1000*zoom; //canvas.width = 1000*zoom;
//canvas.height = 1000*zoom; //canvas.height = 1000*zoom;
context.globalCompositeOperation = "source-over"; context.globalCompositeOperation = "source-over";
context.clearRect(0, 0, canvas.width, canvas.height); context.clearRect(0, 0, canvas.width, canvas.height);
if(hovered.length > 0){ if (hovered.length > 0) {
container.style.cursor = "pointer"; container.style.cursor = "pointer";
} else { } else {
container.style.cursor = "default"; container.style.cursor = "default";
} }
for(var i = 0; i < hovered.length; i++){ for (let i = 0; i < hovered.length; i++) {
var path = hovered[i].path; const path = hovered[i].path;
context.beginPath(); context.beginPath();
if(path[0]){ if (path[0]) {
//context.moveTo(path[0][0]*zoom, path[0][1]*zoom); //context.moveTo(path[0][0]*zoom, path[0][1]*zoom);
context.moveTo(path[0][0], path[0][1]); context.moveTo(path[0][0], path[0][1]);
} }
for(var p = 1; p < path.length; p++){ for (let p = 1; p < path.length; p++) {
//context.lineTo(path[p][0]*zoom, path[p][1]*zoom); //context.lineTo(path[p][0]*zoom, path[p][1]*zoom);
context.lineTo(path[p][0], path[p][1]); context.lineTo(path[p][0], path[p][1]);
} }
@ -557,11 +557,11 @@ async function render(){
context.globalCompositeOperation = "source-out"; context.globalCompositeOperation = "source-out";
context.drawImage(backgroundCanvas, 0, 0); context.drawImage(backgroundCanvas, 0, 0);
if(hovered.length === 1 && hovered[0].path.length && hovered[0].overrideImage){ if (hovered.length === 1 && hovered[0].path.length && hovered[0].overrideImage) {
const undisputableHovered = hovered[0]; const undisputableHovered = hovered[0];
// Find the left-topmost point of all the paths // Find the left-topmost point of all the paths
const entryPosition = getPositionOfEntry(undisputableHovered); const entryPosition = getPositionOfEntry(undisputableHovered);
if(entryPosition){ if (entryPosition) {
const [startX, startY] = entryPosition; const [startX, startY] = entryPosition;
const overrideImage = new Image(); const overrideImage = new Image();
const loadingPromise = new Promise((res, rej) => { const loadingPromise = new Promise((res, rej) => {
@ -569,29 +569,29 @@ async function render(){
overrideImage.onload = res; overrideImage.onload = res;
}); });
overrideImage.src = "imageOverrides/" + undisputableHovered.overrideImage; overrideImage.src = "imageOverrides/" + undisputableHovered.overrideImage;
try{ try {
await loadingPromise; await loadingPromise;
context.globalCompositeOperation = "source-over"; context.globalCompositeOperation = "source-over";
context.drawImage(overrideImage, startX, startY); context.drawImage(overrideImage, startX, startY);
}catch(ex){ } catch (ex) {
console.log("Cannot override image."); console.log("Cannot override image.");
console.log(ex); console.log(ex);
} }
} }
} }
for(var i = 0; i < hovered.length; i++){ for (let i = 0; i < hovered.length; i++) {
var path = hovered[i].path; const path = hovered[i].path;
context.beginPath(); context.beginPath();
if(path[0]){ if (path[0]) {
//context.moveTo(path[0][0]*zoom, path[0][1]*zoom); //context.moveTo(path[0][0]*zoom, path[0][1]*zoom);
context.moveTo(path[0][0], path[0][1]); context.moveTo(path[0][0], path[0][1]);
} }
for(var p = 1; p < path.length; p++){ for (let p = 1; p < path.length; p++) {
//context.lineTo(path[p][0]*zoom, path[p][1]*zoom); //context.lineTo(path[p][0]*zoom, path[p][1]*zoom);
context.lineTo(path[p][0], path[p][1]); context.lineTo(path[p][0], path[p][1]);
} }
@ -600,7 +600,7 @@ async function render(){
context.globalCompositeOperation = "source-over"; context.globalCompositeOperation = "source-over";
var hoverStrokeStyle; let hoverStrokeStyle;
switch (hovered[i].diff) { switch (hovered[i].diff) {
case "add": case "add":
hoverStrokeStyle = "rgba(0, 155, 0, 1)"; hoverStrokeStyle = "rgba(0, 155, 0, 1)";
@ -619,29 +619,29 @@ async function render(){
} }
function updateHovering(e, tapped){ function updateHovering(e, tapped) {
if(!dragging && (!fixed || tapped)){ if (!dragging && (!fixed || tapped)) {
var pos = [ const pos = [
(e.clientX - (container.clientWidth/2 - innerContainer.clientWidth/2 + zoomOrigin[0] + container.offsetLeft))/zoom (e.clientX - (container.clientWidth / 2 - innerContainer.clientWidth / 2 + zoomOrigin[0] + container.offsetLeft)) / zoom
,(e.clientY - (container.clientHeight/2 - innerContainer.clientHeight/2 + zoomOrigin[1] + container.offsetTop))/zoom , (e.clientY - (container.clientHeight / 2 - innerContainer.clientHeight / 2 + zoomOrigin[1] + container.offsetTop)) / zoom
]; ];
var coords_p = document.getElementById("coords_p"); const coords_p = document.getElementById("coords_p");
coords_p.innerText = Math.ceil(pos[0]) + ", " + Math.ceil(pos[1]); coords_p.innerText = Math.ceil(pos[0]) + ", " + Math.ceil(pos[1]);
if(pos[0] <= 2200 && pos[0] >= -100 && pos[0] <= 2200 && pos[0] >= -100){ if (pos[0] <= 2200 && pos[0] >= -100 && pos[0] <= 2200 && pos[0] >= -100) {
var newHovered = []; const newHovered = [];
for(var i = 0; i < atlas.length; i++){ for (let i = 0; i < atlas.length; i++) {
if(pointIsInPolygon(pos, atlas[i].path)){ if (pointIsInPolygon(pos, atlas[i].path)) {
newHovered.push(atlas[i]); newHovered.push(atlas[i]);
} }
} }
var changed = false; let changed = false;
if(hovered.length == newHovered.length){ if (hovered.length == newHovered.length) {
for(var i = 0; i < hovered.length; i++){ for (let i = 0; i < hovered.length; i++) {
if(hovered[i].id != newHovered[i].id){ if (hovered[i].id != newHovered[i].id) {
changed = true; changed = true;
break; break;
} }
@ -650,22 +650,22 @@ function updateHovering(e, tapped){
changed = true; changed = true;
} }
if(changed){ if (changed) {
hovered = newHovered.sort(function(a, b){ hovered = newHovered.sort(function (a, b) {
return calcPolygonArea(a.path) - calcPolygonArea(b.path); return calcPolygonArea(a.path) - calcPolygonArea(b.path);
}); });
objectsContainer.innerHTML = ""; objectsContainer.innerHTML = "";
for(var i in hovered){ for (const i in hovered) {
var element = createInfoBlock(hovered[i]); const element = createInfoBlock(hovered[i]);
objectsContainer.appendChild(element); objectsContainer.appendChild(element);
hovered[i].element = element; hovered[i].element = element;
} }
if(hovered.length > 0){ if (hovered.length > 0) {
closeObjectsListButton.className = ""; closeObjectsListButton.className = "";
} else { } else {
closeObjectsListButton.className = "hidden"; closeObjectsListButton.className = "hidden";
@ -680,22 +680,22 @@ function updateHovering(e, tapped){
window.addEventListener("hashchange", highlightEntryFromUrl); window.addEventListener("hashchange", highlightEntryFromUrl);
function highlightEntryFromUrl(){ function highlightEntryFromUrl() {
var objectsContainer = document.getElementById("objectsList"); const objectsContainer = document.getElementById("objectsList");
var id = window.location.hash.substring(1); //Remove hash prefix const id = window.location.hash.substring(1); //Remove hash prefix
var entries = atlas.filter(function(e){ const entries = atlas.filter(function (e) {
return e.id === id; return e.id === id;
}); });
if (entries.length === 1){ if (entries.length === 1) {
const entry = entries[0]; const entry = entries[0];
document.title = entry.name + " on the 2022 /r/place Atlas"; document.title = entry.name + " on the 2022 /r/place Atlas";
var infoElement = createInfoBlock(entry); const infoElement = createInfoBlock(entry);
objectsContainer.innerHTML = ""; objectsContainer.innerHTML = "";
objectsContainer.appendChild(infoElement); objectsContainer.appendChild(infoElement);
@ -705,19 +705,19 @@ function highlightEntryFromUrl(){
zoom = 4; zoom = 4;
renderBackground(atlas); renderBackground(atlas);
applyView(); applyView();
zoomOrigin = [ zoomOrigin = [
innerContainer.clientWidth/2 - entry.center[0]* zoom// + container.offsetLeft innerContainer.clientWidth / 2 - entry.center[0] * zoom// + container.offsetLeft
,innerContainer.clientHeight/2 - entry.center[1]* zoom// + container.offsetTop , innerContainer.clientHeight / 2 - entry.center[1] * zoom// + container.offsetTop
]; ];
scaleZoomOrigin = [ scaleZoomOrigin = [
2000/2 - entry.center[0]// + container.offsetLeft 2000 / 2 - entry.center[0]// + container.offsetLeft
,2000/2 - entry.center[1]// + container.offsetTop , 2000 / 2 - entry.center[1]// + container.offsetTop
]; ];
//console.log(zoomOrigin); //console.log(zoomOrigin);
applyView(); applyView();
hovered = [entry]; hovered = [entry];
render(); render();
@ -728,7 +728,7 @@ function highlightEntryFromUrl(){
} }
} }
function initView(){ function initView() {
buildObjectsList(null, null); buildObjectsList(null, null);
renderBackground(atlas); renderBackground(atlas);
@ -750,26 +750,26 @@ function initView(){
render(); render();
updateLines(); updateLines();
if(window.location.hash){ // both "/" and just "/#" will be an empty hash string if (window.location.hash) { // both "/" and just "/#" will be an empty hash string
highlightEntryFromUrl(); highlightEntryFromUrl();
} }
} }
function initExplore(){ function initExplore() {
window.updateHovering = updateHovering window.updateHovering = updateHovering
window.render = function() {} window.render = function () { }
function updateHovering(e, tapped){ function updateHovering(e, tapped) {
if(!dragging && (!fixed || tapped)){ if (!dragging && (!fixed || tapped)) {
var pos = [ const pos = [
(e.clientX - (container.clientWidth/2 - innerContainer.clientWidth/2 + zoomOrigin[0] + container.offsetLeft))/zoom (e.clientX - (container.clientWidth / 2 - innerContainer.clientWidth / 2 + zoomOrigin[0] + container.offsetLeft)) / zoom
,(e.clientY - (container.clientHeight/2 - innerContainer.clientHeight/2 + zoomOrigin[1] + container.offsetTop))/zoom , (e.clientY - (container.clientHeight / 2 - innerContainer.clientHeight / 2 + zoomOrigin[1] + container.offsetTop)) / zoom
]; ];
var coords_p = document.getElementById("coords_p"); const coords_p = document.getElementById("coords_p");
coords_p.innerText = Math.ceil(pos[0]) + ", " + Math.ceil(pos[1]); coords_p.innerText = Math.ceil(pos[0]) + ", " + Math.ceil(pos[1]);
} }
} }
@ -780,9 +780,9 @@ function initExplore(){
} }
function initGlobal() { function initGlobal() {
container.addEventListener("mousemove", function(e){ container.addEventListener("mousemove", function (e) {
if(e.sourceCapabilities){ if (e.sourceCapabilities) {
if(!e.sourceCapabilities.firesTouchEvents){ if (!e.sourceCapabilities.firesTouchEvents) {
updateHovering(e); updateHovering(e);
} }
} else { } else {
@ -792,45 +792,45 @@ function initGlobal() {
} }
function initViewGlobal() { function initViewGlobal() {
container.addEventListener("mousedown", function(e){ container.addEventListener("mousedown", function (e) {
lastPos = [ lastPos = [
e.clientX e.clientX
,e.clientY , e.clientY
]; ];
}); });
container.addEventListener("touchstart", function(e){ container.addEventListener("touchstart", function (e) {
if(e.touches.length == 1){ if (e.touches.length == 1) {
lastPos = [ lastPos = [
e.touches[0].clientX e.touches[0].clientX
,e.touches[0].clientY , e.touches[0].clientY
]; ];
} }
},{passive: true} ); }, { passive: true });
container.addEventListener("mouseup", function(e){ container.addEventListener("mouseup", function (e) {
if(Math.abs(lastPos[0] - e.clientX) + Math.abs(lastPos[1] - e.clientY) <= 4){ if (Math.abs(lastPos[0] - e.clientX) + Math.abs(lastPos[1] - e.clientY) <= 4) {
toggleFixed(e); toggleFixed(e);
} }
}); });
container.addEventListener("touchend", function(e){ container.addEventListener("touchend", function (e) {
e.preventDefault() e.preventDefault()
//console.log(e); //console.log(e);
//console.log(e.changedTouches[0].clientX); //console.log(e.changedTouches[0].clientX);
if(e.changedTouches.length == 1){ if (e.changedTouches.length == 1) {
e = e.changedTouches[0]; e = e.changedTouches[0];
//console.log(lastPos[0] - e.clientX); //console.log(lastPos[0] - e.clientX);
if(Math.abs(lastPos[0] - e.clientX) + Math.abs(lastPos[1] - e.clientY) <= 4){ if (Math.abs(lastPos[0] - e.clientX) + Math.abs(lastPos[1] - e.clientY) <= 4) {
//console.log("Foo!!"); //console.log("Foo!!");
dragging = false; dragging = false;
fixed = false; fixed = false;
setTimeout( setTimeout(
function(){ function () {
updateHovering(e, true); updateHovering(e, true);
} }
, 10); , 10);
} }
} }
}); });