From 112e78f40a4a9c12b3d5eebc2dc38e34e01e712e Mon Sep 17 00:00:00 2001 From: Peter Date: Sun, 27 Nov 2022 16:56:11 -0500 Subject: [PATCH] merge module ui --- index.html | 6 +- modules/ui/burg-editor.js | 2 +- modules/ui/editors.js | 144 ++++++-------- modules/ui/heightmap-editor.js | 149 +++++++------- modules/ui/layers.js | 341 ++++++++++++++------------------ modules/ui/markers-editor.js | 2 - modules/ui/markers-overview.js | 1 - modules/ui/military-overview.js | 62 +++--- modules/ui/namesbase-editor.js | 18 +- modules/ui/notes-editor.js | 68 +------ modules/ui/options.js | 118 +++++------ modules/ui/provinces-editor.js | 163 ++++++++------- modules/ui/regiment-editor.js | 128 ++++++------ modules/ui/relief-editor.js | 94 ++++----- 14 files changed, 579 insertions(+), 717 deletions(-) diff --git a/index.html b/index.html index 80fb7da6..f58474db 100644 --- a/index.html +++ b/index.html @@ -8116,14 +8116,14 @@ - - - + + + diff --git a/modules/ui/burg-editor.js b/modules/ui/burg-editor.js index 5bd0f8a9..d79ed0b2 100644 --- a/modules/ui/burg-editor.js +++ b/modules/ui/burg-editor.js @@ -611,7 +611,7 @@ function editBurg(id) { } } }); - } + } } function closeBurgEditor() { diff --git a/modules/ui/editors.js b/modules/ui/editors.js index 6e38166d..df7291f1 100644 --- a/modules/ui/editors.js +++ b/modules/ui/editors.js @@ -1,5 +1,5 @@ // module stub to store common functions for ui editors -'use strict'; +"use strict"; modules.editors = true; @@ -41,9 +41,9 @@ function clicked() { function unselect() { restoreDefaultEvents(); if (!elSelected) return; - elSelected.call(d3.drag().on('drag', null)).attr('class', null); - debug.selectAll('*').remove(); - viewbox.style('cursor', 'default'); + elSelected.call(d3.drag().on("drag", null)).attr("class", null); + debug.selectAll("*").remove(); + viewbox.style("cursor", "default"); elSelected = null; } @@ -65,9 +65,9 @@ function moveCircle(x, y, r = 20) { const html = /* html */ ``; byId("debug").insertAdjacentHTML("afterBegin", html); } else { - circle.setAttribute('cx', x); - circle.setAttribute('cy', y); - circle.setAttribute('r', r); + circle.setAttribute("cx", x); + circle.setAttribute("cy", y); + circle.setAttribute("r", r); } } @@ -77,7 +77,7 @@ function removeCircle() { // get browser-defined fit-content function fitContent() { - return !window.chrome ? '-moz-max-content' : 'fit-content'; + return !window.chrome ? "-moz-max-content" : "fit-content"; } // apply sorting behaviour for lines on Editor header click @@ -117,8 +117,8 @@ function applySorting(headers) { const header = headers.querySelector("div[class*='icon-sort']"); if (!header) return; const sortby = header.dataset.sortby; - const name = header.classList.contains('alphabetically'); - const desc = header.className.includes('-down') ? -1 : 1; + const name = header.classList.contains("alphabetically"); + const desc = header.className.includes("-down") ? -1 : 1; const list = headers.nextElementSibling; const lines = Array.from(list.children); @@ -149,7 +149,7 @@ function addBurg(point) { // generate emblem const coa = COA.generate(pack.states[state].coa, 0.25, null, type); coa.shield = COA.getShield(culture, state); - COArenderer.add('burg', i, coa, x, y); + COArenderer.add("burg", i, coa, x, y); pack.burgs.push({name, cell, x, y, state, i, culture, feature, capital: 0, port: 0, temple, population, coa, type}); cells.burg[cell] = i; @@ -189,9 +189,9 @@ function moveBurgToGroup(id, g) { document.querySelector("#burgLabels > #" + g).appendChild(label); document.querySelector("#burgIcons > #" + g).appendChild(icon); - const iconSize = icon.parentNode.getAttribute('size'); - icon.setAttribute('r', iconSize); - label.setAttribute('dy', `${iconSize * -1.5}px`); + const iconSize = icon.parentNode.getAttribute("size"); + icon.setAttribute("r", iconSize); + label.setAttribute("dy", `${iconSize * -1.5}px`); if (anchor) { document.querySelector("#anchors > #" + g).appendChild(anchor); @@ -260,8 +260,8 @@ function toggleCapital(burg) { pack.states[state].center = pack.burgs[burg].cell; pack.burgs[burg].capital = 1; pack.burgs[old].capital = 0; - moveBurgToGroup(burg, 'cities'); - moveBurgToGroup(old, 'towns'); + moveBurgToGroup(burg, "cities"); + moveBurgToGroup(old, "towns"); } function togglePort(burg) { @@ -275,7 +275,7 @@ function togglePort(burg) { const haven = pack.cells.haven[b.cell]; const port = haven ? pack.cells.f[haven] : -1; - if (!haven) tip("Port haven is not found, system won't be able to make a searoute", false, 'warn'); + if (!haven) tip("Port haven is not found, system won't be able to make a searoute", false, "warn"); b.port = port; const g = b.capital ? "cities" : "towns"; @@ -358,11 +358,11 @@ function getMFCGlink(burg) { // draw legend box function drawLegend(name, data) { - legend.selectAll('*').remove(); // fully redraw every time - legend.attr('data', data.join('|')); // store data + legend.selectAll("*").remove(); // fully redraw every time + legend.attr("data", data.join("|")); // store data const itemsInCol = +styleLegendColItems.value; - const fontSize = +legend.attr('font-size'); + const fontSize = +legend.attr("font-size"); const backClr = styleLegendBack.value; const opacity = +styleLegendOpacity.value; @@ -429,9 +429,9 @@ function drawLegend(name, data) { // fit Legend box to canvas size function fitLegendBox() { - if (!legend.selectAll('*').size()) return; - const px = isNaN(+legend.attr('data-x')) ? 99 : legend.attr('data-x') / 100; - const py = isNaN(+legend.attr('data-y')) ? 93 : legend.attr('data-y') / 100; + if (!legend.selectAll("*").size()) return; + const px = isNaN(+legend.attr("data-x")) ? 99 : legend.attr("data-x") / 100; + const py = isNaN(+legend.attr("data-y")) ? 93 : legend.attr("data-y") / 100; const bbox = legend.node().getBBox(); const x = rn(svgWidth * px - bbox.width), y = rn(svgHeight * py - bbox.height); @@ -464,13 +464,12 @@ function dragLegendBox() { } function clearLegend() { - legend.selectAll('*').remove(); - legend.attr('data', null); + legend.selectAll("*").remove(); + legend.attr("data", null); } // draw color (fill) picker function createPicker() { - const COLORS_IN_ROW = 14; const pos = () => tip("Drag to change the picker position"); const cl = () => tip("Click to close the picker"); const closePicker = () => container.style("display", "none"); @@ -500,12 +499,12 @@ function createPicker() { .on("start", dragPicker) ); - const controls = picker.append('g').attr('id', 'pickerControls'); - const h = controls.append('g'); - h.append('text').attr('x', 4).attr('y', 14).text('H:'); - h.append('line').attr('x1', 18).attr('y1', 10).attr('x2', 107).attr('y2', 10); - h.append('circle').attr('cx', 75).attr('cy', 10).attr('r', 5).attr('id', 'pickerH'); - h.on('mousemove', () => tip('Set palette hue')); + const controls = picker.append("g").attr("id", "pickerControls"); + const h = controls.append("g"); + h.append("text").attr("x", 4).attr("y", 14).text("H:"); + h.append("line").attr("x1", 18).attr("y1", 10).attr("x2", 107).attr("y2", 10); + h.append("circle").attr("cx", 75).attr("cy", 10).attr("r", 5).attr("id", "pickerH"); + h.on("mousemove", () => tip("Set palette hue")); const s = controls.append("g"); s.append("text").attr("x", 113).attr("y", 14).text("S:"); @@ -513,14 +512,14 @@ function createPicker() { s.append("circle").attr("cx", 181.4).attr("cy", 10).attr("r", 5).attr("id", "pickerS"); s.on("mousemove", () => tip("Set palette saturation")); - const l = controls.append('g'); - l.append('text').attr('x', 213).attr('y', 14).text('L:'); - l.append('line').attr('x1', 226).attr('y1', 10).attr('x2', 306).attr('y2', 10); - l.append('circle').attr('cx', 282).attr('cy', 10).attr('r', 5).attr('id', 'pickerL'); - l.on('mousemove', () => tip('Set palette lightness')); + const l = controls.append("g"); + l.append("text").attr("x", 213).attr("y", 14).text("L:"); + l.append("line").attr("x1", 226).attr("y1", 10).attr("x2", 306).attr("y2", 10); + l.append("circle").attr("cx", 282).attr("cy", 10).attr("r", 5).attr("id", "pickerL"); + l.on("mousemove", () => tip("Set palette lightness")); - controls.selectAll('line').on('click', clickPickerControl); - controls.selectAll('circle').call(d3.drag().on('start', dragPickerControl)); + controls.selectAll("line").on("click", clickPickerControl); + controls.selectAll("circle").call(d3.drag().on("start", dragPickerControl)); const spaces = picker .append("foreignObject") @@ -659,7 +658,7 @@ function updateSpaces() { } function updatePickerColors() { - const colors = d3.select('#picker > #pickerColors').selectAll('rect'); + const colors = d3.select("#picker > #pickerColors").selectAll("rect"); const number = colors.size(); const h = getPickerControl(pickerH, 360); @@ -673,10 +672,12 @@ function updatePickerColors() { }); } -function openPicker(fill, callback, options = {allowHatching: true}) { - createPicker(options.allowHatching); +function openPicker(fill, callback) { + const picker = d3.select("#picker"); + if (!picker.size()) createPicker(); + d3.select("#pickerContainer").style("display", "block"); - if (fill[0] === '#') { + if (fill[0] === "#") { const hsl = d3.hsl(fill); if (!isNaN(hsl.h)) setPickerControl(pickerH, hsl.h, 360); if (!isNaN(hsl.s)) setPickerControl(pickerS, hsl.s, 1); @@ -695,10 +696,10 @@ function openPicker(fill, callback, options = {allowHatching: true}) { } function setPickerControl(control, value, max) { - const min = +control.previousSibling.getAttribute('x1'); - const delta = +control.previousSibling.getAttribute('x2') - min; + const min = +control.previousSibling.getAttribute("x1"); + const delta = +control.previousSibling.getAttribute("x2") - min; const percent = value / max; - control.setAttribute('cx', min + delta * percent); + control.setAttribute("cx", min + delta * percent); } function getPickerControl(control, max) { @@ -724,7 +725,7 @@ function dragPicker() { } function pickerFillClicked() { - const fill = this.getAttribute('fill'); + const fill = this.getAttribute("fill"); updateSelectedRect(fill); openPicker.updateFill(); @@ -736,19 +737,19 @@ function pickerFillClicked() { function clickPickerControl() { const min = this.getScreenCTM().e; - this.nextSibling.setAttribute('cx', d3.event.x - min); + this.nextSibling.setAttribute("cx", d3.event.x - min); updateSpaces(); updatePickerColors(); openPicker.updateFill(); } function dragPickerControl() { - const min = +this.previousSibling.getAttribute('x1'); - const max = +this.previousSibling.getAttribute('x2'); + const min = +this.previousSibling.getAttribute("x1"); + const max = +this.previousSibling.getAttribute("x2"); d3.event.on("drag", function () { const x = Math.max(Math.min(d3.event.x, max), min); - this.setAttribute('cx', x); + this.setAttribute("cx", x); updateSpaces(); updatePickerColors(); openPicker.updateFill(); @@ -799,9 +800,9 @@ function fog(id, path) { .transition(fadeIn) .attr("opacity", 1); } else { - defs.select('#fog').append('path').attr('d', path).attr('id', id).attr('opacity', 1); - const opacity = fogging.attr('opacity'); - fogging.style('display', 'block').attr('opacity', 0).transition(fadeIn).attr('opacity', opacity); + defs.select("#fog").append("path").attr("d", path).attr("id", id).attr("opacity", 1); + const opacity = fogging.attr("opacity"); + fogging.style("display", "block").attr("opacity", 0).transition(fadeIn).attr("opacity", opacity); } } @@ -811,13 +812,13 @@ function unfog(id) { if (!id || !el.size()) el = defs.select("#fog").selectAll("path"); el.remove(); - if (!defs.selectAll('#fog path').size()) fogging.style('display', 'none'); + if (!defs.selectAll("#fog path").size()) fogging.style("display", "none"); } function getFileName(dataType) { const formatTime = time => (time < 10 ? "0" + time : time); const name = mapName.value; - const type = dataType ? dataType + ' ' : ''; + const type = dataType ? dataType + " " : ""; const date = new Date(); const year = date.getFullYear(); const month = formatTime(date.getMonth() + 1); @@ -828,10 +829,10 @@ function getFileName(dataType) { return name + " " + type + dateString; } -function downloadFile(data, name, type = 'text/plain') { +function downloadFile(data, name, type = "text/plain") { const dataBlob = new Blob([data], {type}); const url = window.URL.createObjectURL(dataBlob); - const link = document.createElement('a'); + const link = document.createElement("a"); link.download = name; link.href = url; link.click(); @@ -840,9 +841,9 @@ function downloadFile(data, name, type = 'text/plain') { function uploadFile(el, callback) { const fileReader = new FileReader(); - fileReader.readAsText(el.files[0], 'UTF-8'); - el.value = ''; - fileReader.onload = (loaded) => callback(loaded.target.result); + fileReader.readAsText(el.files[0], "UTF-8"); + el.value = ""; + fileReader.onload = loaded => callback(loaded.target.result); } function getBBox(element) { @@ -887,7 +888,7 @@ function highlightElement(element, zoom) { function selectIcon(initial, callback) { if (!callback) return; - $('#iconSelector').dialog(); + $("#iconSelector").dialog(); const table = byId("iconTable"); const input = byId("iconInput"); @@ -1190,22 +1191,3 @@ async function editReligions() { const Editor = await import("../dynamic/editors/religions-editor.js?v=1.87.01"); Editor.open(); } - -// dynamically loaded editors -async function editStates() { - if (customization) return; - const StateEditor = await import("../dynamic/editors/states-editor.js"); - StateEditor.open(); -} - -async function editCultures() { - if (customization) return; - const Editor = await import("../dynamic/editors/cultures-editor.js?v=05062022"); - Editor.open(); -} - -async function editReligions() { - if (customization) return; - const Editor = await import("../dynamic/editors/religions-editor.js?v=06062022"); - Editor.open(); -} diff --git a/modules/ui/heightmap-editor.js b/modules/ui/heightmap-editor.js index 88953262..69856bd9 100644 --- a/modules/ui/heightmap-editor.js +++ b/modules/ui/heightmap-editor.js @@ -87,8 +87,8 @@ function editHeightmap(options) { allowErosionBox.style.display = mode === "keep" ? "none" : "inline-block"; // show finalize button - if (!sessionStorage.getItem('noExitButtonAnimation')) { - sessionStorage.setItem('noExitButtonAnimation', true); + if (!sessionStorage.getItem("noExitButtonAnimation")) { + sessionStorage.setItem("noExitButtonAnimation", true); exitCustomization.style.opacity = 0; const width = 12 * uiSizeOutput.value * 11; exitCustomization.style.right = (svgWidth - width) / 2 + "px"; @@ -145,7 +145,7 @@ function editHeightmap(options) { if (h >= 20) height = Math.pow(h - 18, +heightExponentInput.value); else if (h < 20 && h > 0) height = ((h - 20) / h) * 50; - return rn(height * unitRatio) + ' ' + unit; + return rn(height * unitRatio) + " " + unit; } // Exit customization mode @@ -166,7 +166,7 @@ function editHeightmap(options) { customizationMenu.style.display = "none"; if (byId("options").querySelector(".tab > button.active").id === "toolsTab") toolsContent.style.display = "block"; layersPreset.disabled = false; - exitCustomization.style.display = 'none'; // hide finalize button + exitCustomization.style.display = "none"; // hide finalize button restoreDefaultEvents(); clearMainTip(); closeDialogs(); @@ -176,9 +176,9 @@ function editHeightmap(options) { if (byId("canvas3d")) enterStandardView(); const mode = heightmapEditMode.innerHTML; - if (mode === 'erase') regenerateErasedData(); - else if (mode === 'keep') restoreKeptData(); - else if (mode === 'risk') restoreRiskedData(); + if (mode === "erase") regenerateErasedData(); + else if (mode === "keep") restoreKeptData(); + else if (mode === "risk") restoreRiskedData(); // restore initial layers //viewbox.select("#heights").remove(); @@ -196,8 +196,8 @@ function editHeightmap(options) { } function regenerateErasedData() { - INFO && console.group('Edit Heightmap'); - TIME && console.time('regenerateErasedData'); + INFO && console.group("Edit Heightmap"); + TIME && console.time("regenerateErasedData"); const erosionAllowed = allowErosion.checked; markFeatures(); @@ -247,12 +247,12 @@ function editHeightmap(options) { Military.generate(); Markers.generate(); addZones(); - TIME && console.timeEnd('regenerateErasedData'); - INFO && console.groupEnd('Edit Heightmap'); + TIME && console.timeEnd("regenerateErasedData"); + INFO && console.groupEnd("Edit Heightmap"); } function restoreKeptData() { - viewbox.selectAll('#landmass, #lakes').style('display', null); + viewbox.selectAll("#landmass, #lakes").style("display", null); for (const i of pack.cells.i) { pack.cells.h[i] = grid.cells.h[pack.cells.g[i]]; } @@ -318,11 +318,11 @@ function editHeightmap(options) { // recalculate zones to grid zones.selectAll("g").each(function () { const zone = d3.select(this); - const dataCells = zone.attr('data-cells'); - const cells = dataCells ? dataCells.split(',').map((i) => +i) : []; - const g = cells.map((i) => pack.cells.g[i]); - zone.attr('data-cells', g); - zone.selectAll('*').remove(); + const dataCells = zone.attr("data-cells"); + const cells = dataCells ? dataCells.split(",").map(i => +i) : []; + const g = cells.map(i => pack.cells.g[i]); + zone.attr("data-cells", g); + zone.selectAll("*").remove(); }); markFeatures(); @@ -404,7 +404,7 @@ function editHeightmap(options) { for (const p of pack.provinces) { if (!p.i || p.removed) continue; - const provCells = pack.cells.i.filter((i) => pack.cells.province[i] === p.i); + const provCells = pack.cells.i.filter(i => pack.cells.province[i] === p.i); if (!provCells.length) { const state = p.state; const stateProvs = pack.states[state].provinces; @@ -438,9 +438,9 @@ function editHeightmap(options) { // restore zones from grid zones.selectAll("g").each(function () { const zone = d3.select(this); - const g = zone.attr('data-cells'); - const gCells = g ? g.split(',').map((i) => +i) : []; - const cells = pack.cells.i.filter((i) => gCells.includes(pack.cells.g[i])); + const g = zone.attr("data-cells"); + const gCells = g ? g.split(",").map(i => +i) : []; + const cells = pack.cells.i.filter(i => gCells.includes(pack.cells.g[i])); zone.attr("data-cells", cells); zone.selectAll("*").remove(); @@ -454,8 +454,8 @@ function editHeightmap(options) { .attr("id", d => base + d); }); - TIME && console.timeEnd('restoreRiskedData'); - INFO && console.groupEnd('Edit Heightmap'); + TIME && console.timeEnd("restoreRiskedData"); + INFO && console.groupEnd("Edit Heightmap"); } // trigger heightmap redraw and history update if at least 1 cell is changed @@ -478,7 +478,7 @@ function editHeightmap(options) { // draw or update heightmap function mockHeightmap() { - const data = renderOcean.checked ? grid.cells.i : grid.cells.i.filter((i) => grid.cells.h[i] >= 20); + const data = renderOcean.checked ? grid.cells.i : grid.cells.i.filter(i => grid.cells.h[i] >= 20); const scheme = getColorScheme(); viewbox .select("#heights") @@ -600,12 +600,7 @@ function editHeightmap(options) { if (!pressed) return; pressed.classList.remove("pressed"); - function exitBrushMode() { - const pressed = document.querySelector('#brushesButtons > button.pressed'); - if (!pressed) return; - pressed.classList.remove('pressed'); - - viewbox.style('cursor', 'default').on('.drag', null); + viewbox.style("cursor", "default").on(".drag", null); removeCircle(); byId("brushesSliders").style.display = "none"; } @@ -627,17 +622,17 @@ function editHeightmap(options) { const [x, y] = d3.mouse(this); const start = findGridCell(x, y, grid); - d3.event.on('drag', () => { + d3.event.on("drag", () => { const p = d3.mouse(this); - moveCircle(p[0], p[1], r, '#333'); + moveCircle(p[0], p[1], r, "#333"); if (~~d3.event.sourceEvent.timeStamp % 5 != 0) return; // slow down the edit const inRadius = findGridAll(p[0], p[1], r); - const selection = changeOnlyLand.checked ? inRadius.filter((i) => grid.cells.h[i] >= 20) : inRadius; + const selection = changeOnlyLand.checked ? inRadius.filter(i => grid.cells.h[i] >= 20) : inRadius; if (selection && selection.length) changeHeightForSelection(selection, start); }); - d3.event.on('end', updateHeightmap); + d3.event.on("end", updateHeightmap); } function changeHeightForSelection(s, start) { @@ -674,9 +669,9 @@ function editHeightmap(options) { } function changeOnlyLandClick(e) { - if (heightmapEditMode.innerHTML !== 'keep') return; + if (heightmapEditMode.innerHTML !== "keep") return; e.preventDefault(); - tip("You cannot change the coastline in 'Keep' edit mode", false, 'error'); + tip("You cannot change the coastline in 'Keep' edit mode", false, "error"); } function rescale(v) { @@ -687,7 +682,7 @@ function editHeightmap(options) { } function rescaleWithCondition() { - const range = rescaleLower.value + '-' + rescaleHigher.value; + const range = rescaleLower.value + "-" + rescaleHigher.value; const operator = conditionSign.value; const operand = rescaleModifier.valueAsNumber; if (Number.isNaN(operand)) return tip("Operand should be a number", false, "error"); @@ -725,7 +720,7 @@ function editHeightmap(options) { return tip("Heightmap is already cleared, please do not click twice if not required", false, "error"); grid.cells.h = new Uint8Array(grid.cells.i.length); - viewbox.select('#heights').selectAll('*').remove(); + viewbox.select("#heights").selectAll("*").remove(); updateHistory(); } } @@ -762,9 +757,9 @@ function editHeightmap(options) { $body.dataset.changed = 1; return; } - if (el.classList.contains('icon-check-empty')) { - el.classList.add('icon-check'); - el.classList.remove('icon-check-empty'); + if (el.classList.contains("icon-check-empty")) { + el.classList.add("icon-check"); + el.classList.remove("icon-check-empty"); el.parentElement.style.opacity = 1; return; } @@ -928,7 +923,7 @@ function editHeightmap(options) { } function setRange(event) { - if (event.target.value !== 'interval') return; + if (event.target.value !== "interval") return; prompt("Set a height interval. Avoid space, use hyphen as a separator", {default: "17-20"}, v => { const opt = document.createElement("option"); @@ -982,14 +977,11 @@ function editHeightmap(options) { const steps = byId("templateBody").querySelectorAll("#templateBody > div"); if (!steps.length) return; - grid.cells.h = createTypedArray({maxValue: 100, length: grid.points.length}); - HeightmapGenerator.setGraph(grid); - restartHistory(); - const seed = byId("templateSeed").value; if (seed) Math.random = aleaPRNG(seed); - HeightmapGenerator.resetHeights(); + grid.cells.h = createTypedArray({maxValue: 100, length: grid.points.length}); + HeightmapGenerator.setGraph(grid); restartHistory(); for (const step of steps) { @@ -1027,10 +1019,10 @@ function editHeightmap(options) { function downloadTemplate() { const body = byId("templateBody"); body.dataset.changed = 0; - const steps = body.querySelectorAll('#templateBody > div'); + const steps = body.querySelectorAll("#templateBody > div"); if (!steps.length) return; - let data = ''; + let data = ""; for (const s of steps) { if (s.style.opacity === "0.5") continue; @@ -1042,7 +1034,7 @@ function editHeightmap(options) { data += `${type} ${count} ${arg3} ${x} ${y}\r\n`; } - const name = 'template_' + Date.now() + '.txt'; + const name = "template_" + Date.now() + ".txt"; downloadFile(data, name); } @@ -1065,7 +1057,7 @@ function editHeightmap(options) { function openImageConverter() { if ($("#imageConverter").is(":visible")) return; imageToLoad.click(); - closeDialogs('#imageConverter'); + closeDialogs("#imageConverter"); $("#imageConverter").dialog({ title: "Image Converter", @@ -1077,8 +1069,8 @@ function editHeightmap(options) { }); // create canvas for image - const canvas = document.createElement('canvas'); - canvas.id = 'canvas'; + const canvas = document.createElement("canvas"); + canvas.id = "canvas"; canvas.width = graphWidth; canvas.height = graphHeight; document.body.insertBefore(canvas, optionsContainer); @@ -1089,7 +1081,7 @@ function editHeightmap(options) { // remove all heights grid.cells.h = new Uint8Array(grid.cells.i.length); - viewbox.select('#heights').selectAll('*').remove(); + viewbox.select("#heights").selectAll("*").remove(); updateHistory(); if (modules.openImageConverter) return; @@ -1126,7 +1118,7 @@ function editHeightmap(options) { }); function showPalleteHeight() { - const height = +this.getAttribute('data-color'); + const height = +this.getAttribute("data-color"); colorsSelectValue.innerHTML = height; colorsSelectFriendly.innerHTML = getHeight(height); const former = imageConverterPalette.querySelector(".hoveredColor"); @@ -1136,7 +1128,7 @@ function editHeightmap(options) { function loadImage() { const file = this.files[0]; - this.value = ''; // reset input value to get triggered if the file is re-uploaded + this.value = ""; // reset input value to get triggered if the file is re-uploaded const reader = new FileReader(); const img = new Image(); @@ -1167,11 +1159,11 @@ function editHeightmap(options) { const data = q.reduce(sampleCanvas); const pallete = q.palette(true); - viewbox.select('#heights').selectAll('*').remove(); - d3.select('#imageConverter').selectAll('div.color-div').remove(); - colorsSelect.style.display = 'block'; - colorsUnassigned.style.display = 'block'; - colorsAssigned.style.display = 'none'; + viewbox.select("#heights").selectAll("*").remove(); + d3.select("#imageConverter").selectAll("div.color-div").remove(); + colorsSelect.style.display = "block"; + colorsUnassigned.style.display = "block"; + colorsAssigned.style.display = "none"; sampleCanvas.remove(); // no need to keep viewbox @@ -1199,27 +1191,27 @@ function editHeightmap(options) { } function mapClicked() { - const fill = this.getAttribute('fill'); + const fill = this.getAttribute("fill"); const palleteColor = imageConverter.querySelector(`div[data-color="${fill}"]`); palleteColor.click(); } function colorClicked() { - viewbox.select('#heights').selectAll('.selectedCell').attr('class', null); - const unselect = this.classList.contains('selectedColor'); + viewbox.select("#heights").selectAll(".selectedCell").attr("class", null); + const unselect = this.classList.contains("selectedColor"); - const selectedColor = imageConverter.querySelector('div.selectedColor'); - if (selectedColor) selectedColor.classList.remove('selectedColor'); - const hoveredColor = imageConverterPalette.querySelector('div.hoveredColor'); - if (hoveredColor) hoveredColor.classList.remove('hoveredColor'); + const selectedColor = imageConverter.querySelector("div.selectedColor"); + if (selectedColor) selectedColor.classList.remove("selectedColor"); + const hoveredColor = imageConverterPalette.querySelector("div.hoveredColor"); + if (hoveredColor) hoveredColor.classList.remove("hoveredColor"); colorsSelectValue.innerHTML = colorsSelectFriendly.innerHTML = 0; if (unselect) return; - this.classList.add('selectedColor'); + this.classList.add("selectedColor"); if (this.dataset.height) { const height = +this.dataset.height; - imageConverterPalette.querySelector(`div[data-color="${height}"]`).classList.add('hoveredColor'); + imageConverterPalette.querySelector(`div[data-color="${height}"]`).classList.add("hoveredColor"); colorsSelectValue.innerHTML = height; colorsSelectFriendly.innerHTML = getHeight(height); } @@ -1237,8 +1229,8 @@ function editHeightmap(options) { const rgb = color(1 - (height < 20 ? height - 5 : height) / 100); const selectedColor = imageConverter.querySelector("div.selectedColor"); selectedColor.style.backgroundColor = rgb; - selectedColor.setAttribute('data-color', rgb); - selectedColor.setAttribute('data-height', height); + selectedColor.setAttribute("data-color", rgb); + selectedColor.setAttribute("data-height", height); viewbox .select("#heights") @@ -1291,7 +1283,7 @@ function editHeightmap(options) { }; const assinged = []; // store assigned heights - unassigned.forEach((el) => { + unassigned.forEach(el => { const clr = el.dataset.color; const height = type === "hue" ? getHeightByHue(clr) : type === "lum" ? getHeightByLum(clr) : getHeightByScheme(clr); @@ -1351,7 +1343,7 @@ function editHeightmap(options) { grid.cells.h[i] = height; }); - viewbox.select('#heights').selectAll('polygon').remove(); + viewbox.select("#heights").selectAll("polygon").remove(); updateHeightmap(); restoreImageConverterState(); } @@ -1373,9 +1365,9 @@ function editHeightmap(options) { colorsAssigned.style.display = "none"; colorsUnassigned.style.display = "none"; colorsSelectValue.innerHTML = colorsSelectFriendly.innerHTML = 0; - viewbox.style('cursor', 'default').on('.drag', null); + viewbox.style("cursor", "default").on(".drag", null); tip('Heightmap edit mode is active. Click on "Exit Customization" to finalize the heightmap', true); - $('#imageConverter').dialog('destroy'); + $("#imageConverter").dialog("destroy"); openBrushesPanel(); } @@ -1412,8 +1404,8 @@ function editHeightmap(options) { byId("preview").remove(); return; } - const preview = document.createElement('canvas'); - preview.id = 'preview'; + const preview = document.createElement("canvas"); + preview.id = "preview"; preview.width = grid.cellsX; preview.height = grid.cellsY; document.body.insertBefore(preview, optionsContainer); @@ -1463,4 +1455,3 @@ function editHeightmap(options) { }; } } -} diff --git a/modules/ui/layers.js b/modules/ui/layers.js index d39dfc21..c9c2d5fd 100644 --- a/modules/ui/layers.js +++ b/modules/ui/layers.js @@ -1,5 +1,5 @@ // UI module stub to control map layers -'use strict'; +"use strict"; let presets = {}; // global object restoreCustomPresets(); // run on-load @@ -85,7 +85,7 @@ function getDefaultPresets() { function restoreCustomPresets() { presets = getDefaultPresets(); - const storedPresets = JSON.parse(localStorage.getItem('presets')); + const storedPresets = JSON.parse(localStorage.getItem("presets")); if (!storedPresets) return; for (const preset in storedPresets) { @@ -98,7 +98,7 @@ function restoreCustomPresets() { // run on map generation function applyPreset() { - const preset = localStorage.getItem('preset') || document.getElementById('layersPreset').value; + const preset = localStorage.getItem("preset") || document.getElementById("layersPreset").value; changePreset(preset); } @@ -113,12 +113,12 @@ function changePreset(preset) { else if (!layers.includes(e.id) && layerIsOn(e.id)) e.click(); }); layersPreset.value = preset; - localStorage.setItem('preset', preset); + localStorage.setItem("preset", preset); const isDefault = getDefaultPresets()[preset]; - removePresetButton.style.display = isDefault ? 'none' : 'inline-block'; - savePresetButton.style.display = 'none'; - if (document.getElementById('canvas3d')) setTimeout(ThreeD.update(), 400); + removePresetButton.style.display = isDefault ? "none" : "inline-block"; + savePresetButton.style.display = "none"; + if (document.getElementById("canvas3d")) setTimeout(ThreeD.update(), 400); } function savePreset() { @@ -127,24 +127,24 @@ function savePreset() { .map(node => node.id) .sort(); layersPreset.add(new Option(preset, preset, false, true)); - localStorage.setItem('presets', JSON.stringify(presets)); - localStorage.setItem('preset', preset); - removePresetButton.style.display = 'inline-block'; - savePresetButton.style.display = 'none'; + localStorage.setItem("presets", JSON.stringify(presets)); + localStorage.setItem("preset", preset); + removePresetButton.style.display = "inline-block"; + savePresetButton.style.display = "none"; }); } function removePreset() { const preset = layersPreset.value; delete presets[preset]; - const index = Array.from(layersPreset.options).findIndex((o) => o.value === preset); + const index = Array.from(layersPreset.options).findIndex(o => o.value === preset); layersPreset.options.remove(index); - layersPreset.value = 'custom'; - removePresetButton.style.display = 'none'; - savePresetButton.style.display = 'inline-block'; + layersPreset.value = "custom"; + removePresetButton.style.display = "none"; + savePresetButton.style.display = "inline-block"; - localStorage.setItem('presets', JSON.stringify(presets)); - localStorage.removeItem('preset'); + localStorage.setItem("presets", JSON.stringify(presets)); + localStorage.removeItem("preset"); } function getCurrentPreset() { @@ -156,14 +156,14 @@ function getCurrentPreset() { for (const preset in presets) { if (JSON.stringify(presets[preset]) !== JSON.stringify(layers)) continue; layersPreset.value = preset; - removePresetButton.style.display = defaultPresets[preset] ? 'none' : 'inline-block'; - savePresetButton.style.display = 'none'; + removePresetButton.style.display = defaultPresets[preset] ? "none" : "inline-block"; + savePresetButton.style.display = "none"; return; } - layersPreset.value = 'custom'; - removePresetButton.style.display = 'none'; - savePresetButton.style.display = 'inline-block'; + layersPreset.value = "custom"; + removePresetButton.style.display = "none"; + savePresetButton.style.display = "inline-block"; } // run on map regeneration @@ -193,14 +193,14 @@ function restoreLayers() { function toggleHeight(event) { if (customization === 1) { - tip('You cannot turn off the layer when heightmap is in edit mode', false, 'error'); + tip("You cannot turn off the layer when heightmap is in edit mode", false, "error"); return; } - if (!terrs.selectAll('*').size()) { - turnButtonOn('toggleHeight'); + if (!terrs.selectAll("*").size()) { + turnButtonOn("toggleHeight"); drawHeightmap(); - if (event && isCtrlClick(event)) editStyle('terrs'); + if (event && isCtrlClick(event)) editStyle("terrs"); } else { if (event && isCtrlClick(event)) { editStyle("terrs"); @@ -218,7 +218,7 @@ function drawHeightmap() { const {cells, vertices} = pack; const n = cells.i.length; const used = new Uint8Array(cells.i.length); - const paths = new Array(101).fill(''); + const paths = new Array(101).fill(""); const scheme = getColorScheme(terrs.attr("scheme")); const terracing = terrs.attr("terracing") / 10; // add additional shifted darker layer for pseudo-3d effect @@ -247,12 +247,12 @@ function drawHeightmap() { if (currentLayer > 100) break; // no layers possible with height > 100 if (h < currentLayer) continue; if (used[i]) continue; // already marked - const onborder = cells.c[i].some((n) => cells.h[n] < h); + const onborder = cells.c[i].some(n => cells.h[n] < h); if (!onborder) continue; - const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.h[i] < h)); + const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.h[i] < h)); const chain = connectVertices(vertex, h); if (chain.length < 3) continue; - const points = simplifyLine(chain).map((v) => vertices.p[v]); + const points = simplifyLine(chain).map(v => vertices.p[v]); paths[h] += round(lineGen(points)); } @@ -305,7 +305,7 @@ function drawHeightmap() { return chain.filter((d, i) => i % n === 0); } - TIME && console.timeEnd('drawHeightmap'); + TIME && console.timeEnd("drawHeightmap"); } function getColorScheme(scheme) { @@ -321,10 +321,10 @@ function getColor(value, scheme = getColorScheme()) { } function toggleTemp(event) { - if (!temperature.selectAll('*').size()) { - turnButtonOn('toggleTemp'); + if (!temperature.selectAll("*").size()) { + turnButtonOn("toggleTemp"); drawTemp(); - if (event && isCtrlClick(event)) editStyle('temperature'); + if (event && isCtrlClick(event)) editStyle("temperature"); } else { if (event && isCtrlClick(event)) { editStyle("temperature"); @@ -336,8 +336,8 @@ function toggleTemp(event) { } function drawTemp() { - TIME && console.time('drawTemp'); - temperature.selectAll('*').remove(); + TIME && console.time("drawTemp"); + temperature.selectAll("*").remove(); lineGen.curve(d3.curveBasisClosed); const scheme = d3.scaleSequential(d3.interpolateSpectral); const tMax = +temperatureEquatorOutput.max, @@ -366,7 +366,7 @@ function drawTemp() { const chain = connectVertices(start, t); // vertices chain to form a path const relaxed = chain.filter((v, i) => i % 4 === 0 || vertices.c[v].some(c => c >= n)); if (relaxed.length < 6) continue; - const points = relaxed.map((v) => vertices.p[v]); + const points = relaxed.map(v => vertices.p[v]); chains.push([t, points]); addLabel(points, t); } @@ -401,8 +401,8 @@ function drawTemp() { // find cell with temp < isotherm and find vertex to start path detection function findStart(i, t) { - if (cells.b[i]) return cells.v[i].find((v) => vertices.c[v].some((c) => c >= n)); // map border cell - return cells.v[i][cells.c[i].findIndex((c) => cells.temp[c] < t || !cells.temp[c])]; + if (cells.b[i]) return cells.v[i].find(v => vertices.c[v].some(c => c >= n)); // map border cell + return cells.v[i][cells.c[i].findIndex(c => cells.temp[c] < t || !cells.temp[c])]; } function addLabel(points, t) { @@ -448,14 +448,14 @@ function drawTemp() { chain.push(start); return chain; } - TIME && console.timeEnd('drawTemp'); + TIME && console.timeEnd("drawTemp"); } function toggleBiomes(event) { - if (!biomes.selectAll('path').size()) { - turnButtonOn('toggleBiomes'); + if (!biomes.selectAll("path").size()) { + turnButtonOn("toggleBiomes"); drawBiomes(); - if (event && isCtrlClick(event)) editStyle('biomes'); + if (event && isCtrlClick(event)) editStyle("biomes"); } else { if (event && isCtrlClick(event)) { editStyle("biomes"); @@ -472,15 +472,15 @@ function drawBiomes() { vertices = pack.vertices, n = cells.i.length; const used = new Uint8Array(cells.i.length); - const paths = new Array(biomesData.i.length).fill(''); + const paths = new Array(biomesData.i.length).fill(""); for (const i of cells.i) { if (!cells.biome[i]) continue; // no need to mark marine biome (liquid water) if (used[i]) continue; // already marked const b = cells.biome[i]; - const onborder = cells.c[i].some((n) => cells.biome[n] !== b); + const onborder = cells.c[i].some(n => cells.biome[n] !== b); if (!onborder) continue; - const edgeVerticle = cells.v[i].find((v) => vertices.c[v].some((i) => cells.biome[i] !== b)); + const edgeVerticle = cells.v[i].find(v => vertices.c[v].some(i => cells.biome[i] !== b)); const chain = connectVertices(edgeVerticle, b); if (chain.length < 3) continue; const points = clipPoly( @@ -525,10 +525,10 @@ function drawBiomes() { } function togglePrec(event) { - if (!prec.selectAll('circle').size()) { - turnButtonOn('togglePrec'); + if (!prec.selectAll("circle").size()) { + turnButtonOn("togglePrec"); drawPrec(); - if (event && isCtrlClick(event)) editStyle('prec'); + if (event && isCtrlClick(event)) editStyle("prec"); } else { if (event && isCtrlClick(event)) { editStyle("prec"); @@ -536,9 +536,9 @@ function togglePrec(event) { } turnButtonOff("togglePrec"); const hide = d3.transition().duration(1000).ease(d3.easeSinIn); - prec.selectAll('text').attr('opacity', 1).transition(hide).attr('opacity', 0); - prec.selectAll('circle').transition(hide).attr('r', 0).remove(); - prec.transition().delay(1000).style('display', 'none'); + prec.selectAll("text").attr("opacity", 1).transition(hide).attr("opacity", 0); + prec.selectAll("circle").transition(hide).attr("r", 0).remove(); + prec.transition().delay(1000).style("display", "none"); } } @@ -548,7 +548,7 @@ function drawPrec() { prec.style("display", "block"); const show = d3.transition().duration(800).ease(d3.easeSinIn); - prec.selectAll('text').attr('opacity', 0).transition(show).attr('opacity', 1); + prec.selectAll("text").attr("opacity", 0).transition(show).attr("opacity", 1); const cellsNumberModifier = (pointsInput.dataset.cells / 10000) ** 0.25; const data = cells.i.filter(i => cells.h[i] >= 20 && cells.prec[i]); @@ -567,10 +567,10 @@ function drawPrec() { } function togglePopulation(event) { - if (!population.selectAll('line').size()) { - turnButtonOn('togglePopulation'); + if (!population.selectAll("line").size()) { + turnButtonOn("togglePopulation"); drawPopulation(); - if (event && isCtrlClick(event)) editStyle('population'); + if (event && isCtrlClick(event)) editStyle("population"); } else { if (event && isCtrlClick(event)) { editStyle("population"); @@ -580,7 +580,7 @@ function togglePopulation(event) { const isD3data = population.select("line").datum(); if (!isD3data) { // just remove - population.selectAll('line').remove(); + population.selectAll("line").remove(); } else { // remove with animation const hide = d3.transition().duration(1000).ease(d3.easeSinIn); @@ -642,10 +642,10 @@ function drawPopulation(event) { } function toggleCells(event) { - if (!cells.selectAll('path').size()) { - turnButtonOn('toggleCells'); + if (!cells.selectAll("path").size()) { + turnButtonOn("toggleCells"); drawCells(); - if (event && isCtrlClick(event)) editStyle('cells'); + if (event && isCtrlClick(event)) editStyle("cells"); } else { if (event && isCtrlClick(event)) { editStyle("cells"); @@ -657,7 +657,7 @@ function toggleCells(event) { } function drawCells() { - cells.selectAll('path').remove(); + cells.selectAll("path").remove(); const data = customization === 1 ? grid.cells.i : pack.cells.i; const polygon = customization === 1 ? getGridPolygon : getPackPolygon; let path = ""; @@ -701,19 +701,19 @@ function drawIce() { if (t <= shieldMin) { // very cold: ice shield if (used[i]) continue; // already rendered - const onborder = cells.c[i].some((n) => temp[n] > shieldMin); + const onborder = cells.c[i].some(n => temp[n] > shieldMin); if (!onborder) continue; // need to start from onborder cell - const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => temp[i] > shieldMin)); + const vertex = cells.v[i].find(v => vertices.c[v].some(i => temp[i] > shieldMin)); const chain = connectVertices(vertex); if (chain.length < 3) continue; - const points = clipPoly(chain.map((v) => vertices.p[v])); - ice.append('polygon').attr('points', points).attr('type', 'iceShield'); + const points = clipPoly(chain.map(v => vertices.p[v])); + ice.append("polygon").attr("points", points).attr("type", "iceShield"); continue; } // mildly cold: iceberd if (P(normalize(t, -7, 2.5))) continue; // t[-5; 2] cold: skip some cells - if (grid.features[cells.f[i]].type === 'lake') continue; // lake: no icebers + if (grid.features[cells.f[i]].type === "lake") continue; // lake: no icebers let size = (6.5 + t) / 10; // iceberg size: 0 = full size, 1 = zero size if (cells.t[i] === -1) size *= 1.3; // coasline: smaller icebers size = Math.min(size * (0.4 + rand() * 1.2), 0.95); // randomize iceberg size @@ -755,12 +755,12 @@ function drawIce() { } function toggleCultures(event) { - const cultures = pack.cultures.filter((c) => c.i && !c.removed); - const empty = !cults.selectAll('path').size(); + const cultures = pack.cultures.filter(c => c.i && !c.removed); + const empty = !cults.selectAll("path").size(); if (empty && cultures.length) { - turnButtonOn('toggleCultures'); + turnButtonOn("toggleCultures"); drawCultures(); - if (event && isCtrlClick(event)) editStyle('cults'); + if (event && isCtrlClick(event)) editStyle("cults"); } else { if (event && isCtrlClick(event)) { editStyle("cults"); @@ -772,26 +772,26 @@ function toggleCultures(event) { } function drawCultures() { - TIME && console.time('drawCultures'); + TIME && console.time("drawCultures"); cults.selectAll("path").remove(); const {cells, vertices, cultures} = pack; const n = cells.i.length; const used = new Uint8Array(cells.i.length); - const paths = new Array(cultures.length).fill(''); + const paths = new Array(cultures.length).fill(""); for (const i of cells.i) { if (!cells.culture[i]) continue; if (used[i]) continue; used[i] = 1; const c = cells.culture[i]; - const onborder = cells.c[i].some((n) => cells.culture[n] !== c); + const onborder = cells.c[i].some(n => cells.culture[n] !== c); if (!onborder) continue; - const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.culture[i] !== c)); + const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.culture[i] !== c)); const chain = connectVertices(vertex, c); if (chain.length < 3) continue; - const points = chain.map((v) => vertices.p[v]); - paths[c] += 'M' + points.join('L') + 'Z'; + const points = chain.map(v => vertices.p[v]); + paths[c] += "M" + points.join("L") + "Z"; } const data = paths.map((p, i) => [p, i]).filter(d => d[0].length > 10); @@ -826,15 +826,15 @@ function drawCultures() { } return chain; } - TIME && console.timeEnd('drawCultures'); + TIME && console.timeEnd("drawCultures"); } function toggleReligions(event) { - const religions = pack.religions.filter((r) => r.i && !r.removed); - if (!relig.selectAll('path').size() && religions.length) { - turnButtonOn('toggleReligions'); + const religions = pack.religions.filter(r => r.i && !r.removed); + if (!relig.selectAll("path").size() && religions.length) { + turnButtonOn("toggleReligions"); drawReligions(); - if (event && isCtrlClick(event)) editStyle('relig'); + if (event && isCtrlClick(event)) editStyle("relig"); } else { if (event && isCtrlClick(event)) { editStyle("relig"); @@ -846,7 +846,7 @@ function toggleReligions(event) { } function drawReligions() { - TIME && console.time('drawReligions'); + TIME && console.time("drawReligions"); relig.selectAll("path").remove(); const {cells, vertices, religions} = pack; @@ -854,21 +854,21 @@ function drawReligions() { const used = new Uint8Array(cells.i.length); const vArray = new Array(religions.length); // store vertices array - const body = new Array(religions.length).fill(''); // store path around each religion - const gap = new Array(religions.length).fill(''); // store path along water for each religion to fill the gaps + const body = new Array(religions.length).fill(""); // store path around each religion + const gap = new Array(religions.length).fill(""); // store path along water for each religion to fill the gaps for (const i of cells.i) { if (!cells.religion[i]) continue; if (used[i]) continue; used[i] = 1; const r = cells.religion[i]; - const onborder = cells.c[i].filter((n) => cells.religion[n] !== r); + const onborder = cells.c[i].filter(n => cells.religion[n] !== r); if (!onborder.length) continue; - const borderWith = cells.c[i].map((c) => cells.religion[c]).find((n) => n !== r); - const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.religion[i] === borderWith)); + const borderWith = cells.c[i].map(c => cells.religion[c]).find(n => n !== r); + const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.religion[i] === borderWith)); const chain = connectVertices(vertex, r, borderWith); if (chain.length < 3) continue; - const points = chain.map((v) => vertices.p[v[0]]); + const points = chain.map(v => vertices.p[v[0]]); if (!vArray[r]) vArray[r] = []; vArray[r].push(points); body[r] += "M" + points.join("L") + "Z"; @@ -938,15 +938,15 @@ function drawReligions() { } return chain; } - TIME && console.timeEnd('drawReligions'); + TIME && console.timeEnd("drawReligions"); } function toggleStates(event) { - if (!layerIsOn('toggleStates')) { - turnButtonOn('toggleStates'); - regions.style('display', null); + if (!layerIsOn("toggleStates")) { + turnButtonOn("toggleStates"); + regions.style("display", null); drawStates(); - if (event && isCtrlClick(event)) editStyle('regions'); + if (event && isCtrlClick(event)) editStyle("regions"); } else { if (event && isCtrlClick(event)) { editStyle("regions"); @@ -958,8 +958,8 @@ function toggleStates(event) { } function drawStates() { - TIME && console.time('drawStates'); - regions.selectAll('path').remove(); + TIME && console.time("drawStates"); + regions.selectAll("path").remove(); const {cells, vertices, features} = pack; const states = pack.states; @@ -1058,7 +1058,7 @@ function drawStates() { .join(""); statesBody.html(bodyString + gapString); - defs.select('#statePaths').html(clipString); + defs.select("#statePaths").html(clipString); statesHalo.html(haloString); // connect vertices to chain @@ -1102,7 +1102,7 @@ function drawStates() { } invokeActiveZooming(); - TIME && console.timeEnd('drawStates'); + TIME && console.timeEnd("drawStates"); } function toggleBorders(event) { @@ -1122,8 +1122,8 @@ function toggleBorders(event) { // draw state and province borders function drawBorders() { - TIME && console.time('drawBorders'); - borders.selectAll('path').remove(); + TIME && console.time("drawBorders"); + borders.selectAll("path").remove(); const {cells, vertices} = pack; const n = cells.i.length; @@ -1146,34 +1146,34 @@ function drawBorders() { if (provToCell) { const provTo = cells.province[provToCell]; pUsed[p][provToCell] = provTo; - const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.province[i] === provTo)); + const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.province[i] === provTo)); const chain = connectVertices(vertex, p, cells.province, provTo, pUsed); if (chain.length > 1) { - pPath.push('M' + chain.map((c) => vertices.p[c]).join(' ')); + pPath.push("M" + chain.map(c => vertices.p[c]).join(" ")); i--; continue; } } // if cell is on state border - const stateToCell = cells.c[i].find((n) => cells.h[n] >= 20 && s > cells.state[n] && sUsed[s][n] !== cells.state[n]); + const stateToCell = cells.c[i].find(n => cells.h[n] >= 20 && s > cells.state[n] && sUsed[s][n] !== cells.state[n]); if (stateToCell !== undefined) { const stateTo = cells.state[stateToCell]; sUsed[s][stateToCell] = stateTo; - const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.h[i] >= 20 && cells.state[i] === stateTo)); + const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.h[i] >= 20 && cells.state[i] === stateTo)); const chain = connectVertices(vertex, s, cells.state, stateTo, sUsed); if (chain.length > 1) { - sPath.push('M' + chain.map((c) => vertices.p[c]).join(' ')); + sPath.push("M" + chain.map(c => vertices.p[c]).join(" ")); i--; continue; } } } - stateBorders.append('path').attr('d', sPath.join(' ')); - provinceBorders.append('path').attr('d', pPath.join(' ')); + stateBorders.append("path").attr("d", sPath.join(" ")); + provinceBorders.append("path").attr("d", pPath.join(" ")); // connect vertices to chain function connectVertices(current, f, array, t, used) { @@ -1224,14 +1224,14 @@ function drawBorders() { return chain; } - TIME && console.timeEnd('drawBorders'); + TIME && console.timeEnd("drawBorders"); } function toggleProvinces(event) { - if (!layerIsOn('toggleProvinces')) { - turnButtonOn('toggleProvinces'); + if (!layerIsOn("toggleProvinces")) { + turnButtonOn("toggleProvinces"); drawProvinces(); - if (event && isCtrlClick(event)) editStyle('provs'); + if (event && isCtrlClick(event)) editStyle("provs"); } else { if (event && isCtrlClick(event)) { editStyle("provs"); @@ -1243,9 +1243,9 @@ function toggleProvinces(event) { } function drawProvinces() { - TIME && console.time('drawProvinces'); - const labelsOn = provs.attr('data-labels') == 1; - provs.selectAll('*').remove(); + TIME && console.time("drawProvinces"); + const labelsOn = provs.attr("data-labels") == 1; + provs.selectAll("*").remove(); const provinces = pack.provinces; const {body, gap} = getProvincesVertices(); @@ -1283,7 +1283,7 @@ function drawProvinces() { .attr("id", d => "provinceLabel" + d.i) .text(d => d.name); - TIME && console.timeEnd('drawProvinces'); + TIME && console.timeEnd("drawProvinces"); } function getProvincesVertices() { @@ -1293,20 +1293,20 @@ function getProvincesVertices() { n = cells.i.length; const used = new Uint8Array(cells.i.length); const vArray = new Array(provinces.length); // store vertices array - const body = new Array(provinces.length).fill(''); // store path around each province - const gap = new Array(provinces.length).fill(''); // store path along water for each province to fill the gaps + const body = new Array(provinces.length).fill(""); // store path around each province + const gap = new Array(provinces.length).fill(""); // store path along water for each province to fill the gaps for (const i of cells.i) { if (!cells.province[i] || used[i]) continue; const p = cells.province[i]; - const onborder = cells.c[i].some((n) => cells.province[n] !== p); + const onborder = cells.c[i].some(n => cells.province[n] !== p); if (!onborder) continue; - const borderWith = cells.c[i].map((c) => cells.province[c]).find((n) => n !== p); - const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.province[i] === borderWith)); + const borderWith = cells.c[i].map(c => cells.province[c]).find(n => n !== p); + const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.province[i] === borderWith)); const chain = connectVertices(vertex, p, borderWith); if (chain.length < 3) continue; - const points = chain.map((v) => vertices.p[v[0]]); + const points = chain.map(v => vertices.p[v[0]]); if (!vArray[p]) vArray[p] = []; vArray[p].push(points); body[p] += "M" + points.join("L"); @@ -1367,8 +1367,8 @@ function getProvincesVertices() { } function toggleGrid(event) { - if (!gridOverlay.selectAll('*').size()) { - turnButtonOn('toggleGrid'); + if (!gridOverlay.selectAll("*").size()) { + turnButtonOn("toggleGrid"); drawGrid(); calculateFriendlyGridSize(); @@ -1413,10 +1413,10 @@ function drawGrid() { } function toggleCoordinates(event) { - if (!coordinates.selectAll('*').size()) { - turnButtonOn('toggleCoordinates'); + if (!coordinates.selectAll("*").size()) { + turnButtonOn("toggleCoordinates"); drawCoordinates(); - if (event && isCtrlClick(event)) editStyle('coordinates'); + if (event && isCtrlClick(event)) editStyle("coordinates"); } else { if (event && isCtrlClick(event)) { editStyle("coordinates"); @@ -1446,11 +1446,11 @@ function drawCoordinates() { .stepMinor([step, step]); const projection = d3.geoEquirectangular().fitSize([graphWidth, graphHeight], graticule()); - const grid = coordinates.append('g').attr('id', 'coordinateGrid'); - const labels = coordinates.append('g').attr('id', 'coordinateLabels'); + const grid = coordinates.append("g").attr("id", "coordinateGrid"); + const labels = coordinates.append("g").attr("id", "coordinateLabels"); const p = getViewPoint(scale + desired + 2, scale + desired / 2); // on border point on viexBox - const data = graticule.lines().map((d) => { + const data = graticule.lines().map(d => { const lat = d.coordinates[0][1] === d.coordinates[1][1]; // check if line is latitude or longitude const c = d.coordinates[0], pos = projection(c); // map coordinates @@ -1499,7 +1499,7 @@ function toggleCompass(event) { compass.append("use").attr("xlink:href", "#rose"); shiftCompass(); } - if (event && isCtrlClick(event)) editStyle('compass'); + if (event && isCtrlClick(event)) editStyle("compass"); } else { if (event && isCtrlClick(event)) { editStyle("compass"); @@ -1527,8 +1527,8 @@ function toggleRelief(event) { } function toggleTexture(event) { - if (!layerIsOn('toggleTexture')) { - turnButtonOn('toggleTexture'); + if (!layerIsOn("toggleTexture")) { + turnButtonOn("toggleTexture"); // append default texture image selected by default. Don't append on load to not harm performance if (!texture.selectAll("*").size()) { const x = +styleTextureShiftX.value; @@ -1545,7 +1545,7 @@ function toggleTexture(event) { } $("#texture").fadeIn(); zoom.scaleBy(svg, 1.00001); // enforce browser re-draw - if (event && isCtrlClick(event)) editStyle('texture'); + if (event && isCtrlClick(event)) editStyle("texture"); } else { if (event && isCtrlClick(event)) return editStyle("texture"); $("#texture").fadeOut(); @@ -1681,7 +1681,7 @@ function toggleLabels(event) { turnButtonOn("toggleLabels"); labels.style("display", null); invokeActiveZooming(); - if (event && isCtrlClick(event)) editStyle('labels'); + if (event && isCtrlClick(event)) editStyle("labels"); } else { if (event && isCtrlClick(event)) { editStyle("labels"); @@ -1708,11 +1708,11 @@ function toggleIcons(event) { } function toggleRulers(event) { - if (!layerIsOn('toggleRulers')) { - turnButtonOn('toggleRulers'); - if (event && isCtrlClick(event)) editStyle('ruler'); + if (!layerIsOn("toggleRulers")) { + turnButtonOn("toggleRulers"); + if (event && isCtrlClick(event)) editStyle("ruler"); rulers.draw(); - ruler.style('display', null); + ruler.style("display", null); } else { if (event && isCtrlClick(event)) { editStyle("ruler"); @@ -1771,12 +1771,12 @@ function toggleEmblems(event) { } function drawEmblems() { - TIME && console.time('drawEmblems'); + TIME && console.time("drawEmblems"); const {states, provinces, burgs} = pack; - const validStates = states.filter((s) => s.i && !s.removed && s.coa && s.coaSize != 0); - const validProvinces = provinces.filter((p) => p.i && !p.removed && p.coa && p.coaSize != 0); - const validBurgs = burgs.filter((b) => b.i && !b.removed && b.coa && b.coaSize != 0); + const validStates = states.filter(s => s.i && !s.removed && s.coa && s.coaSize != 0); + const validProvinces = provinces.filter(p => p.i && !p.removed && p.coa && p.coaSize != 0); + const validBurgs = burgs.filter(b => b.i && !b.removed && b.coa && b.coaSize != 0); const getStateEmblemsSize = () => { const startSize = minmax((graphHeight + graphWidth) / 40, 10, 100); @@ -1800,7 +1800,7 @@ function drawEmblems() { }; const sizeBurgs = getBurgEmblemSize(); - const burgCOAs = validBurgs.map((burg) => { + const burgCOAs = validBurgs.map(burg => { const {x, y} = burg; const size = burg.coaSize || 1; const shift = (sizeBurgs * size) / 2; @@ -1808,7 +1808,7 @@ function drawEmblems() { }); const sizeProvinces = getProvinceEmblemsSize(); - const provinceCOAs = validProvinces.map((province) => { + const provinceCOAs = validProvinces.map(province => { if (!province.pole) getProvincesVertices(); const [x, y] = province.pole || pack.cells.p[province.center]; const size = province.coaSize || 1; @@ -1817,7 +1817,7 @@ function drawEmblems() { }); const sizeStates = getStateEmblemsSize(); - const stateCOAs = validStates.map((state) => { + const stateCOAs = validStates.map(state => { const [x, y] = state.pole || pack.cells.p[state.center]; const size = state.coaSize || 1; const shift = (sizeStates * size) / 2; @@ -1896,49 +1896,6 @@ function toggleResources(event) { } } -function drawResources() { - console.time("drawResources"); - const someArePinned = pack.resources.some((resource) => resource.pinned); - const drawCircle = +goods.attr("data-circle"); - - let resourcesHTML = ""; - for (const i of pack.cells.i) { - if (!pack.cells.resource[i]) continue; - const resource = Resources.get(pack.cells.resource[i]); - if (someArePinned && !resource.pinned) continue; - const [x, y] = pack.cells.p[i]; - const stroke = Resources.getStroke(resource.color); - - // if (!drawCircle) { - // resourcesHTML += ``; - // continue; - // } - - resourcesHTML += ` - - - `; - } - - goods.html(resourcesHTML); - console.timeEnd('drawResources'); -} - -function toggleResources(event) { - if (!layerIsOn('toggleResources')) { - turnButtonOn('toggleResources'); - drawResources(); - if (event && isCtrlClick(event)) editStyle('goods'); - } else { - if (event && isCtrlClick(event)) { - editStyle('goods'); - return; - } - goods.selectAll('*').remove(); - turnButtonOff('toggleResources'); - } -} - function drawResources() { console.time('drawResources'); const someArePinned = pack.resources.some((resource) => resource.pinned); @@ -1968,24 +1925,24 @@ function drawResources() { } function layerIsOn(el) { - const buttonoff = document.getElementById(el).classList.contains('buttonoff'); + const buttonoff = document.getElementById(el).classList.contains("buttonoff"); return !buttonoff; } function turnButtonOff(el) { - document.getElementById(el).classList.add('buttonoff'); + document.getElementById(el).classList.add("buttonoff"); getCurrentPreset(); } function turnButtonOn(el) { - document.getElementById(el).classList.remove('buttonoff'); + document.getElementById(el).classList.remove("buttonoff"); getCurrentPreset(); } // move layers on mapLayers dragging (jquery sortable) -$('#mapLayers').sortable({items: 'li:not(.solid)', containment: 'parent', cancel: '.solid', update: moveLayer}); +$("#mapLayers").sortable({items: "li:not(.solid)", containment: "parent", cancel: ".solid", update: moveLayer}); function moveLayer(event, ui) { - const el = getLayer(ui.item.attr('id')); + const el = getLayer(ui.item.attr("id")); if (!el) return; const prev = getLayer(ui.item.prev().attr("id")); const next = getLayer(ui.item.next().attr("id")); diff --git a/modules/ui/markers-editor.js b/modules/ui/markers-editor.js index e24da80f..26f035fa 100644 --- a/modules/ui/markers-editor.js +++ b/modules/ui/markers-editor.js @@ -10,8 +10,6 @@ function editMarker(markerI) { if (document.getElementById("notesEditor").offsetParent) editNotes(element.id, element.id); - elSelected = d3.select(element).raise().call(d3.drag().on("start", dragMarker)).classed("draggable", true); - // dom elements const markerType = document.getElementById("markerType"); const markerIcon = document.getElementById("markerIcon"); diff --git a/modules/ui/markers-overview.js b/modules/ui/markers-overview.js index e1126e66..5570ffb9 100644 --- a/modules/ui/markers-overview.js +++ b/modules/ui/markers-overview.js @@ -45,7 +45,6 @@ function overviewMarkers() { if (el.classList.contains("icon-pin")) return pinMarker(el, i); if (el.classList.contains("locks")) return toggleLockStatus(el, i); if (el.classList.contains("icon-trash-empty")) return triggerRemove(i); - // TODO: hidden attribute } function addLines() { diff --git a/modules/ui/military-overview.js b/modules/ui/military-overview.js index c0e8eb36..35a23ed4 100644 --- a/modules/ui/military-overview.js +++ b/modules/ui/military-overview.js @@ -1,14 +1,14 @@ -'use strict'; +"use strict"; function overviewMilitary() { if (customization) return; - closeDialogs('#militaryOverview, .stable'); - if (!layerIsOn('toggleStates')) toggleStates(); - if (!layerIsOn('toggleBorders')) toggleBorders(); - if (!layerIsOn('toggleMilitary')) toggleMilitary(); + closeDialogs("#militaryOverview, .stable"); + if (!layerIsOn("toggleStates")) toggleStates(); + if (!layerIsOn("toggleBorders")) toggleBorders(); + if (!layerIsOn("toggleMilitary")) toggleMilitary(); - const body = document.getElementById('militaryBody'); + const body = document.getElementById("militaryBody"); addLines(); - $('#militaryOverview').dialog(); + $("#militaryOverview").dialog(); if (modules.overviewMilitary) return; modules.overviewMilitary = true; @@ -22,13 +22,13 @@ function overviewMilitary() { }); // add listeners - document.getElementById('militaryOverviewRefresh').addEventListener('click', addLines); - document.getElementById('militaryPercentage').addEventListener('click', togglePercentageMode); - document.getElementById('militaryOptionsButton').addEventListener('click', militaryCustomize); - document.getElementById('militaryRegimentsList').addEventListener('click', () => overviewRegiments(-1)); - document.getElementById('militaryOverviewRecalculate').addEventListener('click', militaryRecalculate); - document.getElementById('militaryExport').addEventListener('click', downloadMilitaryData); - document.getElementById('militaryWiki').addEventListener('click', () => wiki('Military-Forces')); + document.getElementById("militaryOverviewRefresh").addEventListener("click", addLines); + document.getElementById("militaryPercentage").addEventListener("click", togglePercentageMode); + document.getElementById("militaryOptionsButton").addEventListener("click", militaryCustomize); + document.getElementById("militaryRegimentsList").addEventListener("click", () => overviewRegiments(-1)); + document.getElementById("militaryOverviewRecalculate").addEventListener("click", militaryRecalculate); + document.getElementById("militaryExport").addEventListener("click", downloadMilitaryData); + document.getElementById("militaryWiki").addEventListener("click", () => wiki("Military-Forces")); body.addEventListener("change", function (ev) { const el = ev.target, @@ -65,9 +65,9 @@ function overviewMilitary() { // add line for each state function addLines() { - body.innerHTML = ''; - let lines = ''; - const states = pack.states.filter((s) => s.i && !s.removed); + body.innerHTML = ""; + let lines = ""; + const states = pack.states.filter(s => s.i && !s.removed); for (const s of states) { const population = rn((s.rural + s.urban * urbanization) * populationRate); @@ -75,8 +75,8 @@ function overviewMilitary() { const total = options.military.reduce((s, u) => s + getForces(u) * u.crew, 0); const rate = (total / population) * 100; - const sortData = options.military.map((u) => `data-${u.name}="${getForces(u)}"`).join(' '); - const lineData = options.military.map((u) => `
${getForces(u)}
`).join(' '); + const sortData = options.military.map(u => `data-${u.name}="${getForces(u)}"`).join(" "); + const lineData = options.military.map(u => `
${getForces(u)}
`).join(" "); lines += /* html */ `
`; } - body.insertAdjacentHTML('beforeend', lines); + body.insertAdjacentHTML("beforeend", lines); updateFooter(); // add listeners - body.querySelectorAll('div.states').forEach((el) => el.addEventListener('mouseenter', (ev) => stateHighlightOn(ev))); - body.querySelectorAll('div.states').forEach((el) => el.addEventListener('mouseleave', (ev) => stateHighlightOff(ev))); + body.querySelectorAll("div.states").forEach(el => el.addEventListener("mouseenter", ev => stateHighlightOn(ev))); + body.querySelectorAll("div.states").forEach(el => el.addEventListener("mouseleave", ev => stateHighlightOff(ev))); if (body.dataset.type === "percentage") { body.dataset.type = "absolute"; @@ -137,7 +137,7 @@ function overviewMilitary() { const total = (line.dataset.total = options.military.reduce((s, u) => s + getForces(u) * u.crew, 0)); const rate = (line.dataset.rate = (total / population) * 100); line.querySelector("div[data-type='total']").innerHTML = si(total); - line.querySelector("div[data-type='rate']").innerHTML = rn(rate, 2) + '%'; + line.querySelector("div[data-type='rate']").innerHTML = rn(rate, 2) + "%"; updateFooter(); } @@ -148,8 +148,8 @@ function overviewMilitary() { const total = d3.sum(lines.map(el => el.dataset.total)); militaryFooterForcesTotal.innerHTML = si(total); militaryFooterForces.innerHTML = si(total / statesNumber); - militaryFooterRate.innerHTML = rn(d3.sum(lines.map((el) => el.dataset.rate)) / statesNumber, 2) + '%'; - militaryFooterAlert.innerHTML = rn(d3.sum(lines.map((el) => el.dataset.alert)) / statesNumber, 2); + militaryFooterRate.innerHTML = rn(d3.sum(lines.map(el => el.dataset.rate)) / statesNumber, 2) + "%"; + militaryFooterAlert.innerHTML = rn(d3.sum(lines.map(el => el.dataset.alert)) / statesNumber, 2); } function stateHighlightOn(event) { @@ -207,7 +207,7 @@ function overviewMilitary() { const total = function (type) { if (cache[type]) cache[type]; - cache[type] = d3.sum(array.map((el) => +el.dataset[type])); + cache[type] = d3.sum(array.map(el => +el.dataset[type])); return cache[type]; }; @@ -219,7 +219,7 @@ function overviewMilitary() { }); }); } else { - body.dataset.type = 'absolute'; + body.dataset.type = "absolute"; addLines(); } } @@ -388,11 +388,11 @@ function overviewMilitary() { const unitLines = Array.from(tableBody.querySelectorAll("tr")); const names = unitLines.map(r => r.querySelector("input").value.replace(/[&\/\\#, +()$~%.'":*?<>{}]/g, "_")); if (new Set(names).size !== names.length) { - tip('All units should have unique names', false, 'error'); + tip("All units should have unique names", false, "error"); return; } - $('#militaryOptions').dialog('close'); + $("#militaryOptions").dialog("close"); options.military = unitLines.map((r, i) => { const elements = Array.from(r.querySelectorAll("input, button, select")); const [icon, name, biomes, states, cultures, religions, rural, urban, crew, power, type, separate] = elements.map(el => { @@ -411,7 +411,7 @@ function overviewMilitary() { if (religions) unit.religions = religions; return unit; }); - localStorage.setItem('military', JSON.stringify(options.military)); + localStorage.setItem("military", JSON.stringify(options.military)); Military.generate(); updateHeaders(); addLines(); @@ -450,7 +450,7 @@ function overviewMilitary() { data += el.dataset.alert + "\n"; }); - const name = getFileName('Military') + '.csv'; + const name = getFileName("Military") + ".csv"; downloadFile(data, name); } } diff --git a/modules/ui/namesbase-editor.js b/modules/ui/namesbase-editor.js index 38db89f6..e2d214ff 100644 --- a/modules/ui/namesbase-editor.js +++ b/modules/ui/namesbase-editor.js @@ -1,8 +1,8 @@ -'use strict'; +"use strict"; function editNamesbase() { if (customization) return; - closeDialogs('#namesbaseEditor, .stable'); - $('#namesbaseEditor').dialog(); + closeDialogs("#namesbaseEditor, .stable"); + $("#namesbaseEditor").dialog(); if (modules.editNamesbase) return; modules.editNamesbase = true; @@ -58,8 +58,8 @@ function editNamesbase() { }); function createBasesList() { - const select = document.getElementById('namesbaseSelect'); - select.innerHTML = ''; + const select = document.getElementById("namesbaseSelect"); + select.innerHTML = ""; nameBases.forEach((b, i) => select.options.add(new Option(b.name, i))); } @@ -81,13 +81,13 @@ function editNamesbase() { for (let i = 0; i < 10; i++) { const example = Names.getBase(base); if (example === undefined) { - examples = 'Cannot generate examples. Please verify the data'; + examples = "Cannot generate examples. Please verify the data"; break; } - if (i) examples += ', '; + if (i) examples += ", "; examples += example; } - document.getElementById('namesbaseExamples').innerHTML = examples; + document.getElementById("namesbaseExamples").innerHTML = examples; } function updateNamesData() { @@ -130,7 +130,7 @@ function editNamesbase() { } function updateBaseDublication() { - const base = +document.getElementById('namesbaseSelect').value; + const base = +document.getElementById("namesbaseSelect").value; nameBases[base].d = this.value; } diff --git a/modules/ui/notes-editor.js b/modules/ui/notes-editor.js index ab16ab6c..4362fb25 100644 --- a/modules/ui/notes-editor.js +++ b/modules/ui/notes-editor.js @@ -21,10 +21,10 @@ function editNotes(id, name) { // select an object if (notes.length || id) { if (!id) id = notes[0].id; - let note = notes.find((note) => note.id === id); + let note = notes.find(note => note.id === id); if (note === undefined) { if (!name) name = id; - note = {id, name, legend: ''}; + note = {id, name, legend: ""}; notes.push(note); notesSelect.options.add(new Option(id, id)); } @@ -166,70 +166,6 @@ function editNotes(id, name) { }); } - function updateLegend() { - const note = notes.find(note => note.id === notesSelect.value); - if (note && tinymce?.activeEditor) { - note.legend = tinymce.activeEditor.getContent(); - updateNotesBox(note); - } - } - - function updateNotesBox(note) { - document.getElementById("notesHeader").innerHTML = note.name; - document.getElementById("notesBody").innerHTML = note.legend; - } - - function changeElement() { - const note = notes.find(note => note.id === this.value); - if (!note) return tip("Note element is not found", true, "error", 4000); - - notesName.value = note.name; - tinymce.activeEditor.setContent(note.legend); - updateNotesBox(note); - } - - function changeName() { - const note = notes.find(note => note.id === notesSelect.value); - if (!note) return tip("Note element is not found", true, "error", 4000); - - note.name = this.value; - } - - function validateHighlightElement() { - const element = document.getElementById(notesSelect.value); - if (element) return highlightElement(element, 3); - - confirmationDialog({ - title: "Element not found", - message: "Note element is not found. Would you like to remove the note?", - confirm: "Remove", - cancel: "Keep", - onConfirm: removeLegend - }); - } - - function downloadLegends() { - const notesData = JSON.stringify(notes); - const name = getFileName("Notes") + ".txt"; - downloadFile(notesData, name); - } - - function uploadLegends(dataLoaded) { - if (!dataLoaded) return tip("Cannot load the file. Please check the data format", false, "error"); - notes = JSON.parse(dataLoaded); - notesSelect.options.length = 0; - editNotes(notes[0].id, notes[0].name); - } - - function triggerNotesRemove() { - confirmationDialog({ - title: "Remove note", - message: "Are you sure you want to remove the selected note? There is no way to undo this action", - confirm: "Remove", - onConfirm: removeLegend - }); - } - function removeLegend() { const index = notes.findIndex(n => n.id === notesSelect.value); notes.splice(index, 1); diff --git a/modules/ui/options.js b/modules/ui/options.js index 7391cfd2..c072d1cb 100644 --- a/modules/ui/options.js +++ b/modules/ui/options.js @@ -1,41 +1,41 @@ // UI module to control the options (preferences) -'use strict'; +"use strict"; -$('#optionsContainer').draggable({handle: '.drag-trigger', snap: 'svg', snapMode: 'both'}); -$('#exitCustomization').draggable({handle: 'div'}); -$('#mapLayers').disableSelection(); +$("#optionsContainer").draggable({handle: ".drag-trigger", snap: "svg", snapMode: "both"}); +$("#exitCustomization").draggable({handle: "div"}); +$("#mapLayers").disableSelection(); // remove glow if tip is aknowledged if (stored("disable_click_arrow_tooltip")) { clearMainTip(); - optionsTrigger.classList.remove('glow'); + optionsTrigger.classList.remove("glow"); } // Show options pane on trigger click function showOptions(event) { if (!stored("disable_click_arrow_tooltip")) { clearMainTip(); - localStorage.setItem('disable_click_arrow_tooltip', true); - optionsTrigger.classList.remove('glow'); + localStorage.setItem("disable_click_arrow_tooltip", true); + optionsTrigger.classList.remove("glow"); } - regenerate.style.display = 'none'; - document.getElementById('options').style.display = 'block'; - optionsTrigger.style.display = 'none'; + regenerate.style.display = "none"; + document.getElementById("options").style.display = "block"; + optionsTrigger.style.display = "none"; if (event) event.stopPropagation(); } // Hide options pane on trigger click function hideOptions(event) { - document.getElementById('options').style.display = 'none'; - optionsTrigger.style.display = 'block'; + document.getElementById("options").style.display = "none"; + optionsTrigger.style.display = "block"; if (event) event.stopPropagation(); } // To toggle options on hotkey press function toggleOptions(event) { - if (document.getElementById('options').style.display === 'none') showOptions(event); + if (document.getElementById("options").style.display === "none") showOptions(event); else hideOptions(event); } @@ -158,15 +158,15 @@ optionsContent.addEventListener("click", function (event) { function mapSizeInputChange() { changeMapSize(); - localStorage.setItem('mapWidth', mapWidthInput.value); - localStorage.setItem('mapHeight', mapHeightInput.value); + localStorage.setItem("mapWidth", mapWidthInput.value); + localStorage.setItem("mapHeight", mapHeightInput.value); } // change svg size on manual size change or window resize, do not change graph size function changeMapSize() { svgWidth = Math.min(+mapWidthInput.value, window.innerWidth); svgHeight = Math.min(+mapHeightInput.value, window.innerHeight); - svg.attr('width', svgWidth).attr('height', svgHeight); + svg.attr("width", svgWidth).attr("height", svgHeight); const maxWidth = Math.max(+mapWidthInput.value, graphWidth); const maxHeight = Math.max(+mapHeightInput.value, graphHeight); @@ -207,8 +207,8 @@ function toggleFullscreen() { if (mapWidthInput.value != window.innerWidth || mapHeightInput.value != window.innerHeight) { mapWidthInput.value = window.innerWidth; mapHeightInput.value = window.innerHeight; - localStorage.removeItem('mapHeight'); - localStorage.removeItem('mapWidth'); + localStorage.removeItem("mapHeight"); + localStorage.removeItem("mapWidth"); } else { mapWidthInput.value = graphWidth; mapHeightInput.value = graphHeight; @@ -236,7 +236,7 @@ const voiceInterval = setInterval(function () { if (voices.length) clearInterval(voiceInterval); else return; - const select = document.getElementById('speakerVoice'); + const select = document.getElementById("speakerVoice"); voices.forEach((voice, i) => { select.options.add(new Option(voice.name, i, false)); }); @@ -250,7 +250,7 @@ function testSpeaker() { const speaker = new SpeechSynthesisUtterance(text); const voices = speechSynthesis.getVoices(); if (voices.length) { - const voiceId = +document.getElementById('speakerVoice').value; + const voiceId = +document.getElementById("speakerVoice").value; speaker.voice = voices[voiceId]; } speechSynthesis.speak(speaker); @@ -349,9 +349,9 @@ function changeCultureSet() { } function changeEmblemShape(emblemShape) { - const image = document.getElementById('emblemShapeImage'); + const image = document.getElementById("emblemShapeImage"); const shapePath = window.COArenderer && COArenderer.shieldPaths[emblemShape]; - shapePath ? image.setAttribute('d', shapePath) : image.removeAttribute('d'); + shapePath ? image.setAttribute("d", shapePath) : image.removeAttribute("d"); const specificShape = ["culture", "state", "random"].includes(emblemShape) ? null : emblemShape; if (emblemShape === "random") @@ -364,25 +364,25 @@ function changeEmblemShape(emblemShape) { COArenderer.trigger(id, coa); }; - pack.states.forEach((state) => { - if (!state.i || state.removed || !state.coa || state.coa === 'custom') return; + pack.states.forEach(state => { + if (!state.i || state.removed || !state.coa || state.coa === "custom") return; const newShield = specificShape || COA.getShield(state.culture, null); if (newShield === state.coa.shield) return; state.coa.shield = newShield; - rerenderCOA('stateCOA' + state.i, state.coa); + rerenderCOA("stateCOA" + state.i, state.coa); }); - pack.provinces.forEach((province) => { - if (!province.i || province.removed || !province.coa || province.coa === 'custom') return; + pack.provinces.forEach(province => { + if (!province.i || province.removed || !province.coa || province.coa === "custom") return; const culture = pack.cells.culture[province.center]; const newShield = specificShape || COA.getShield(culture, province.state); if (newShield === province.coa.shield) return; province.coa.shield = newShield; - rerenderCOA('provinceCOA' + province.i, province.coa); + rerenderCOA("provinceCOA" + province.i, province.coa); }); - pack.burgs.forEach((burg) => { - if (!burg.i || burg.removed || !burg.coa || burg.coa === 'custom') return; + pack.burgs.forEach(burg => { + if (!burg.i || burg.removed || !burg.coa || burg.coa === "custom") return; const newShield = specificShape || COA.getShield(burg.culture, burg.state); if (newShield === burg.coa.shield) return; burg.coa.shield = newShield; @@ -521,8 +521,8 @@ function applyStoredOptions() { // search params overwrite stored and default options const params = new URL(window.location.href).searchParams; - const width = +params.get('width'); - const height = +params.get('height'); + const width = +params.get("width"); + const height = +params.get("height"); if (width) mapWidthInput.value = width; if (height) mapHeightInput.value = height; @@ -647,7 +647,7 @@ function changeYear() { function changeEra() { if (!eraInput.value) return; - lock('era'); + lock("era"); options.era = eraInput.value; } @@ -810,7 +810,7 @@ function loadURL() { return; } loadMapFromURL(value); - $(this).dialog('close'); + $(this).dialog("close"); }, Cancel: function () { $(this).dialog("close"); @@ -822,7 +822,7 @@ function loadURL() { // load map document.getElementById("mapToLoad").addEventListener("change", function () { const fileToLoad = this.files[0]; - this.value = ''; + this.value = ""; closeDialogs(); uploadMap(fileToLoad); }); @@ -904,30 +904,30 @@ function updateTilesOptions() { } // View mode -viewMode.addEventListener('click', changeViewMode); +viewMode.addEventListener("click", changeViewMode); function changeViewMode(event) { const button = event.target; - if (button.tagName !== 'BUTTON') return; - const pressed = button.classList.contains('pressed'); + if (button.tagName !== "BUTTON") return; + const pressed = button.classList.contains("pressed"); enterStandardView(); - if (!pressed && button.id !== 'viewStandard') { - viewStandard.classList.remove('pressed'); - button.classList.add('pressed'); + if (!pressed && button.id !== "viewStandard") { + viewStandard.classList.remove("pressed"); + button.classList.add("pressed"); enter3dView(button.id); } } function enterStandardView() { - viewMode.querySelectorAll('.pressed').forEach((button) => button.classList.remove('pressed')); - heightmap3DView.classList.remove('pressed'); - viewStandard.classList.add('pressed'); + viewMode.querySelectorAll(".pressed").forEach(button => button.classList.remove("pressed")); + heightmap3DView.classList.remove("pressed"); + viewStandard.classList.add("pressed"); - if (!document.getElementById('canvas3d')) return; + if (!document.getElementById("canvas3d")) return; ThreeD.stop(); - document.getElementById('canvas3d').remove(); - if (options3dUpdate.offsetParent) $('#options3d').dialog('close'); - if (preview3d.offsetParent) $('#preview3d').dialog('close'); + document.getElementById("canvas3d").remove(); + if (options3dUpdate.offsetParent) $("#options3d").dialog("close"); + if (preview3d.offsetParent) $("#preview3d").dialog("close"); } async function enter3dView(type) { @@ -935,21 +935,21 @@ async function enter3dView(type) { canvas.id = "canvas3d"; canvas.dataset.type = type; - if (type === 'heightmap3DView') { + if (type === "heightmap3DView") { canvas.width = parseFloat(preview3d.style.width) || graphWidth / 3; canvas.height = canvas.width / (graphWidth / graphHeight); - canvas.style.display = 'block'; + canvas.style.display = "block"; } else { canvas.width = svgWidth; canvas.height = svgHeight; - canvas.style.position = 'absolute'; - canvas.style.display = 'none'; + canvas.style.position = "absolute"; + canvas.style.display = "none"; } const started = await ThreeD.create(canvas, type); if (!started) return; - canvas.style.display = 'block'; + canvas.style.display = "block"; canvas.onmouseenter = () => { const help = "Left mouse to change angle, middle mouse / mousewheel to zoom, right mouse to pan. O to toggle options"; @@ -972,7 +972,7 @@ async function enter3dView(type) { } function resize3d() { - const canvas = document.getElementById('canvas3d'); + const canvas = document.getElementById("canvas3d"); canvas.width = parseFloat(preview3d.style.width); canvas.height = parseFloat(preview3d.style.height) - 2; ThreeD.redraw(); @@ -995,9 +995,9 @@ function toggle3dOptions() { if (modules.options3d) return; modules.options3d = true; - document.getElementById('options3dUpdate').addEventListener('click', ThreeD.update); - document.getElementById('options3dSave').addEventListener('click', ThreeD.saveScreenshot); - document.getElementById('options3dOBJSave').addEventListener('click', ThreeD.saveOBJ); + document.getElementById("options3dUpdate").addEventListener("click", ThreeD.update); + document.getElementById("options3dSave").addEventListener("click", ThreeD.saveScreenshot); + document.getElementById("options3dOBJSave").addEventListener("click", ThreeD.saveOBJ); document.getElementById("options3dScaleRange").addEventListener("input", changeHeightScale); document.getElementById("options3dScaleNumber").addEventListener("change", changeHeightScale); @@ -1030,7 +1030,7 @@ function toggle3dOptions() { options3dGlobeRotationRange.value = options3dGlobeRotationNumber.value = ThreeD.options.rotateGlobe; options3dMeshLabels3d.value = ThreeD.options.labels3d; options3dMeshSkyMode.value = ThreeD.options.extendedWater; - options3dColorSection.style.display = ThreeD.options.extendedWater ? 'block' : 'none'; + options3dColorSection.style.display = ThreeD.options.extendedWater ? "block" : "none"; options3dMeshSky.value = ThreeD.options.skyColor; options3dMeshWater.value = ThreeD.options.waterColor; options3dGlobeResolution.value = ThreeD.options.resolution; @@ -1065,7 +1065,7 @@ function toggle3dOptions() { function toggleSkyMode() { const hide = ThreeD.options.extendedWater; - options3dColorSection.style.display = hide ? 'none' : 'block'; + options3dColorSection.style.display = hide ? "none" : "block"; ThreeD.toggleSky(); } diff --git a/modules/ui/provinces-editor.js b/modules/ui/provinces-editor.js index d217ad0e..3cac626f 100644 --- a/modules/ui/provinces-editor.js +++ b/modules/ui/provinces-editor.js @@ -1,14 +1,14 @@ -'use strict'; +"use strict"; function editProvinces() { if (customization) return; - closeDialogs('#provincesEditor, .stable'); - if (!layerIsOn('toggleProvinces')) toggleProvinces(); - if (!layerIsOn('toggleBorders')) toggleBorders(); - if (layerIsOn('toggleStates')) toggleStates(); - if (layerIsOn('toggleCultures')) toggleCultures(); + closeDialogs("#provincesEditor, .stable"); + if (!layerIsOn("toggleProvinces")) toggleProvinces(); + if (!layerIsOn("toggleBorders")) toggleBorders(); + if (layerIsOn("toggleStates")) toggleStates(); + if (layerIsOn("toggleCultures")) toggleCultures(); - provs.selectAll('text').call(d3.drag().on('drag', dragLabel)).classed('draggable', true); - const body = document.getElementById('provincesBodySection'); + provs.selectAll("text").call(d3.drag().on("drag", dragLabel)).classed("draggable", true); + const body = document.getElementById("provincesBodySection"); refreshProvincesEditor(); if (modules.editProvinces) return; @@ -91,14 +91,14 @@ function editProvinces() { provinces[p].burgs.push(cells.burg[i]); } - provinces.forEach((p) => { + provinces.forEach(p => { if (!p.i || p.removed) return; if (!p.burg && p.burgs.length) p.burg = p.burgs[0]; }); } function updateFilter() { - const stateFilter = document.getElementById('provincesFilterState'); + const stateFilter = document.getElementById("provincesFilterState"); const selectedState = stateFilter.value || 1; stateFilter.options.length = 0; // remove all options stateFilter.options.add(new Option(`all`, -1, false, selectedState == -1)); @@ -175,10 +175,10 @@ function editProvinces() { provincesFooterArea.dataset.area = totalArea; provincesFooterPopulation.dataset.population = totalPopulation; - body.querySelectorAll('div.states').forEach((el) => { - el.addEventListener('click', selectProvinceOnLineClick); - el.addEventListener('mouseenter', (ev) => provinceHighlightOn(ev)); - el.addEventListener('mouseleave', (ev) => provinceHighlightOff(ev)); + body.querySelectorAll("div.states").forEach(el => { + el.addEventListener("click", selectProvinceOnLineClick); + el.addEventListener("mouseenter", ev => provinceHighlightOn(ev)); + el.addEventListener("mouseleave", ev => provinceHighlightOff(ev)); }); if (body.dataset.type === "percentage") { @@ -186,7 +186,7 @@ function editProvinces() { togglePercentageMode(); } applySorting(provincesHeader); - $('#provincesEditor').dialog({width: fitContent()}); + $("#provincesEditor").dialog({width: fitContent()}); } function getCapitalOptions(burgs, capital) { @@ -198,9 +198,9 @@ function editProvinces() { function provinceHighlightOn(event) { const province = +event.target.dataset.id; const el = body.querySelector(`div[data-id='${province}']`); - if (el) el.classList.add('active'); + if (el) el.classList.add("active"); - if (!layerIsOn('toggleProvinces')) return; + if (!layerIsOn("toggleProvinces")) return; if (customization) return; const animate = d3.transition().duration(2000).ease(d3.easeSinIn); provs @@ -214,7 +214,7 @@ function editProvinces() { function provinceHighlightOff(event) { const province = +event.target.dataset.id; const el = body.querySelector(`div[data-id='${province}']`); - if (el) el.classList.remove('active'); + if (el) el.classList.remove("active"); if (!layerIsOn("toggleProvinces")) return; provs @@ -370,7 +370,7 @@ function editProvinces() { const rural = rn(p.rural * populationRate); const urban = rn(p.urban * populationRate * urbanization); const total = rural + urban; - const l = (n) => Number(n).toLocaleString(); + const l = n => Number(n).toLocaleString(); alertMessage.innerHTML = /* html */ ` Rural: Urban: @@ -450,11 +450,11 @@ function editProvinces() { unfog("focusProvince" + p); - const coaId = 'provinceCOA' + p; - if (document.getElementById(coaId)) document.getElementById(coaId).remove(); - emblems.select(`#provinceEmblems > use[data-i='${p}']`).remove(); + const coaId = "provinceCOA" + p; + if (document.getElementById(coaId)) document.getElementById(coaId).remove(); + emblems.select(`#provinceEmblems > use[data-i='${p}']`).remove(); - pack.provinces[p] = {i: p, removed: true}; + pack.provinces[p] = {i: p, removed: true}; const g = provs.select("#provincesBody"); g.select("#province" + p).remove(); @@ -497,41 +497,41 @@ function editProvinces() { modules.editProvinceName = true; // add listeners - document.getElementById('provinceNameEditorShortCulture').addEventListener('click', regenerateShortNameCuture); - document.getElementById('provinceNameEditorShortRandom').addEventListener('click', regenerateShortNameRandom); - document.getElementById('provinceNameEditorAddForm').addEventListener('click', addCustomForm); - document.getElementById('provinceNameEditorFullRegenerate').addEventListener('click', regenerateFullName); + document.getElementById("provinceNameEditorShortCulture").addEventListener("click", regenerateShortNameCuture); + document.getElementById("provinceNameEditorShortRandom").addEventListener("click", regenerateShortNameRandom); + document.getElementById("provinceNameEditorAddForm").addEventListener("click", addCustomForm); + document.getElementById("provinceNameEditorFullRegenerate").addEventListener("click", regenerateFullName); function regenerateShortNameCuture() { const province = +provinceNameEditor.dataset.province; const culture = pack.cells.culture[pack.provinces[province].center]; const name = Names.getState(Names.getCultureShort(culture), culture); - document.getElementById('provinceNameEditorShort').value = name; + document.getElementById("provinceNameEditorShort").value = name; } function regenerateShortNameRandom() { const base = rand(nameBases.length - 1); const name = Names.getState(Names.getBase(base), undefined, base); - document.getElementById('provinceNameEditorShort').value = name; + document.getElementById("provinceNameEditorShort").value = name; } function addCustomForm() { const value = provinceNameEditorCustomForm.value; - const displayed = provinceNameEditorCustomForm.style.display === 'inline-block'; - provinceNameEditorCustomForm.style.display = displayed ? 'none' : 'inline-block'; - provinceNameEditorSelectForm.style.display = displayed ? 'inline-block' : 'none'; + const displayed = provinceNameEditorCustomForm.style.display === "inline-block"; + provinceNameEditorCustomForm.style.display = displayed ? "none" : "inline-block"; + provinceNameEditorSelectForm.style.display = displayed ? "inline-block" : "none"; if (displayed) applyOption(provinceNameEditorSelectForm, value); } function regenerateFullName() { - const short = document.getElementById('provinceNameEditorShort').value; - const form = document.getElementById('provinceNameEditorSelectForm').value; - document.getElementById('provinceNameEditorFull').value = getFullName(); + const short = document.getElementById("provinceNameEditorShort").value; + const form = document.getElementById("provinceNameEditorSelectForm").value; + document.getElementById("provinceNameEditorFull").value = getFullName(); function getFullName() { if (!form) return short; - if (!short && form) return 'The ' + form; - return short + ' ' + form; + if (!short && form) return "The " + form; + return short + " " + form; } } @@ -551,8 +551,8 @@ function editProvinces() { } function togglePercentageMode() { - if (body.dataset.type === 'absolute') { - body.dataset.type = 'percentage'; + if (body.dataset.type === "absolute") { + body.dataset.type = "percentage"; const totalArea = +provincesFooterArea.dataset.area; const totalPopulation = +provincesFooterPopulation.dataset.population; @@ -561,7 +561,7 @@ function editProvinces() { el.querySelector(".culturePopulation").innerHTML = rn((+el.dataset.population / totalPopulation) * 100) + "%"; }); } else { - body.dataset.type = 'absolute'; + body.dataset.type = "absolute"; provincesEditorAddLines(); } } @@ -628,7 +628,7 @@ function editProvinces() { .on("mouseleave", d => hideInfo(event, d)); function showInfo(ev, d) { - d3.select(ev.target).select('rect').classed('selected', 1); + d3.select(ev.target).select("rect").classed("selected", 1); const name = d.data.fullName; const state = pack.states[d.data.state].fullName; @@ -651,9 +651,9 @@ function editProvinces() { function hideInfo(ev) { provinceHighlightOff(ev); - if (!document.getElementById('provinceInfo')) return; - provinceInfo.innerHTML = '‍'; - d3.select(ev.target).select('rect').classed('selected', 0); + if (!document.getElementById("provinceInfo")) return; + provinceInfo.innerHTML = "‍"; + d3.select(ev.target).select("rect").classed("selected", 0); } node @@ -677,7 +677,7 @@ function editProvinces() { node.select("text").each(function (d) { this.innerHTML = d.data.name; let b = this.getBBox(); - if (b.y + b.height > d.y1 + 1) this.innerHTML = ''; + if (b.y + b.height > d.y1 + 1) this.innerHTML = ""; for (let i = 0; i < 15 && b.width > 0 && b.x + b.width > d.x1; i++) { if (this.innerHTML.length < 3) { @@ -730,10 +730,10 @@ function editProvinces() { } function toggleLabels() { - const hidden = provs.select('#provinceLabels').style('display') === 'none'; - provs.select('#provinceLabels').style('display', `${hidden ? 'block' : 'none'}`); - provs.attr('data-labels', +hidden); - provs.selectAll('text').call(d3.drag().on('drag', dragLabel)).classed('draggable', true); + const hidden = provs.select("#provinceLabels").style("display") === "none"; + provs.select("#provinceLabels").style("display", `${hidden ? "block" : "none"}`); + provs.attr("data-labels", +hidden); + provs.selectAll("text").call(d3.drag().on("drag", dragLabel)).classed("draggable", true); } function triggerProvincesRelease() { @@ -765,8 +765,8 @@ function editProvinces() { } function enterProvincesManualAssignent() { - if (!layerIsOn('toggleProvinces')) toggleProvinces(); - if (!layerIsOn('toggleBorders')) toggleBorders(); + if (!layerIsOn("toggleProvinces")) toggleProvinces(); + if (!layerIsOn("toggleBorders")) toggleBorders(); // make province and state borders more visible provinceBorders.select("path").attr("stroke", "#000").attr("stroke-width", 0.5); @@ -788,15 +788,15 @@ function editProvinces() { tip("Click on a province to select, drag the circle to change province", true); viewbox.style("cursor", "crosshair").on("click", selectProvinceOnMapClick).call(d3.drag().on("start", dragBrush)).on("touchmove mousemove", moveBrush); - body.querySelector('div').classList.add('selected'); - selectProvince(+body.querySelector('div').dataset.id); + body.querySelector("div").classList.add("selected"); + selectProvince(+body.querySelector("div").dataset.id); } function selectProvinceOnLineClick() { if (customization !== 11) return; - if (this.parentNode.id !== 'provincesBodySection') return; - body.querySelector('div.selected').classList.remove('selected'); - this.classList.add('selected'); + if (this.parentNode.id !== "provincesBodySection") return; + body.querySelector("div.selected").classList.remove("selected"); + this.classList.add("selected"); selectProvince(+this.dataset.id); } @@ -814,8 +814,8 @@ function editProvinces() { return; } - body.querySelector('div.selected').classList.remove('selected'); - editorLine.classList.add('selected'); + body.querySelector("div.selected").classList.remove("selected"); + editorLine.classList.add("selected"); selectProvince(province); } @@ -828,7 +828,7 @@ function editProvinces() { function dragBrush() { const r = +provincesManuallyBrush.value; - d3.event.on('drag', () => { + d3.event.on("drag", () => { if (!d3.event.dx && !d3.event.dy) return; const p = d3.mouse(this); moveCircle(p[0], p[1], r); @@ -847,9 +847,9 @@ function editProvinces() { const provinceNew = +selected.dataset.id; const state = pack.provinces[provinceNew].state; - const fill = pack.provinces[provinceNew].color || '#ffffff'; + const fill = pack.provinces[provinceNew].color || "#ffffff"; - selection.forEach((i) => { + selection.forEach(i => { if (!pack.cells.state[i] || pack.cells.state[i] !== state) return; const exists = temp.select("polygon[data-cell='" + i + "']"); const provinceOld = exists.size() ? +exists.attr("data-province") : pack.cells.province[i]; @@ -864,7 +864,7 @@ function editProvinces() { // change of append new element if (exists.size()) { if (pack.cells.province[i] === provinceNew) exists.remove(); - else exists.attr('data-province', provinceNew).attr('fill', fill); + else exists.attr("data-province", provinceNew).attr("fill", fill); } else { temp .append("polygon") @@ -903,14 +903,14 @@ function editProvinces() { function exitProvincesManualAssignment(close) { customization = 0; - provs.select('#temp').remove(); - provs.select('#centers').remove(); + provs.select("#temp").remove(); + provs.select("#centers").remove(); removeCircle(); // restore borders style - provinceBorders.select('path').attr('stroke', null).attr('stroke-width', null); - stateBorders.select('path').attr('stroke', null).attr('stroke-width', null); - debug.selectAll('path.selected').remove(); + provinceBorders.select("path").attr("stroke", null).attr("stroke-width", null); + stateBorders.select("path").attr("stroke", null).attr("stroke-width", null); + debug.selectAll("path.selected").remove(); document.querySelectorAll("#provincesBottom > *").forEach(el => (el.style.display = "inline-block")); document.getElementById("provincesManuallyButtons").style.display = "none"; @@ -923,8 +923,8 @@ function editProvinces() { restoreDefaultEvents(); clearMainTip(); - const selected = body.querySelector('div.selected'); - if (selected) selected.classList.remove('selected'); + const selected = body.querySelector("div.selected"); + if (selected) selected.classList.remove("selected"); } function enterAddProvinceMode() { @@ -969,14 +969,14 @@ function editProvinces() { const type = BurgsAndStates.getType(center, parent.port); const coa = COA.generate(parent, kinship, P(0.1), type); coa.shield = COA.getShield(c, state); - COArenderer.add('province', province, coa, point[0], point[1]); + COArenderer.add("province", province, coa, point[0], point[1]); provinces.push({i: province, state, center, burg, name, formName, fullName, color, coa}); cells.province[center] = province; - cells.c[center].forEach((c) => { + cells.c[center].forEach(c => { if (cells.h[c] < 20 || cells.state[c] !== state) return; - if (provinces.find((p) => !p.removed && p.center === c)) return; + if (provinces.find(p => !p.removed && p.center === c)) return; cells.province[c] = province; }); @@ -985,7 +985,7 @@ function editProvinces() { if (!layerIsOn("toggleProvinces")) toggleProvinces(); else drawProvinces(); collectStatistics(); - document.getElementById('provincesFilterState').value = state; + document.getElementById("provincesFilterState").value = state; provincesEditorAddLines(); } @@ -998,9 +998,9 @@ function editProvinces() { } function recolorProvinces() { - const state = +document.getElementById('provincesFilterState').value; + const state = +document.getElementById("provincesFilterState").value; - pack.provinces.forEach((p) => { + pack.provinces.forEach(p => { if (!p || p.removed) return; if (state !== -1 && p.state !== state) return; const stateColor = pack.states[p.state].color; @@ -1032,7 +1032,7 @@ function editProvinces() { data += `${Math.round(provincePack.urban * populationRate * urbanization)}\n`; }); - const name = getFileName('Provinces') + '.csv'; + const name = getFileName("Provinces") + ".csv"; downloadFile(data, name); } @@ -1045,10 +1045,9 @@ function editProvinces() { Remove: function () { $(this).dialog("close"); - // remove data - pack.provinces = [0]; - pack.cells.province = new Uint16Array(pack.cells.i.length); - pack.states.forEach((s) => (s.provinces = [])); + // remove emblems + document.querySelectorAll("[id^='provinceCOA']").forEach(el => el.remove()); + emblems.select("#provinceEmblems").selectAll("*").remove(); // remove data pack.provinces = [0]; @@ -1082,8 +1081,8 @@ function editProvinces() { } function closeProvincesEditor() { - provs.selectAll('text').call(d3.drag().on('drag', null)).attr('class', null); - if (customization === 11) exitProvincesManualAssignment('close'); + provs.selectAll("text").call(d3.drag().on("drag", null)).attr("class", null); + if (customization === 11) exitProvincesManualAssignment("close"); if (customization === 12) exitAddProvinceMode(); } } diff --git a/modules/ui/regiment-editor.js b/modules/ui/regiment-editor.js index 50c40b50..3c0fe73c 100644 --- a/modules/ui/regiment-editor.js +++ b/modules/ui/regiment-editor.js @@ -1,11 +1,11 @@ -'use strict'; +"use strict"; function editRegiment(selector) { if (customization) return; - closeDialogs('.stable'); - if (!layerIsOn('toggleMilitary')) toggleMilitary(); + closeDialogs(".stable"); + if (!layerIsOn("toggleMilitary")) toggleMilitary(); - armies.selectAll(':scope > g').classed('draggable', true); - armies.selectAll(':scope > g > g').call(d3.drag().on('drag', dragRegiment)); + armies.selectAll(":scope > g").classed("draggable", true); + armies.selectAll(":scope > g > g").call(d3.drag().on("drag", dragRegiment)); elSelected = selector ? document.querySelector(selector) : d3.event.target.parentElement; // select g element if (!pack.states[elSelected.dataset.state]) return; if (!regiment()) return; @@ -23,22 +23,22 @@ function editRegiment(selector) { modules.editRegiment = true; // add listeners - document.getElementById('regimentNameRestore').addEventListener('click', restoreName); - document.getElementById('regimentType').addEventListener('click', changeType); - document.getElementById('regimentName').addEventListener('change', changeName); - document.getElementById('regimentEmblem').addEventListener('input', changeEmblem); - document.getElementById('regimentEmblemSelect').addEventListener('click', selectEmblem); - document.getElementById('regimentAttack').addEventListener('click', toggleAttack); - document.getElementById('regimentRegenerateLegend').addEventListener('click', regenerateLegend); - document.getElementById('regimentLegend').addEventListener('click', editLegend); - document.getElementById('regimentSplit').addEventListener('click', splitRegiment); - document.getElementById('regimentAdd').addEventListener('click', toggleAdd); - document.getElementById('regimentAttach').addEventListener('click', toggleAttach); - document.getElementById('regimentRemove').addEventListener('click', removeRegiment); + document.getElementById("regimentNameRestore").addEventListener("click", restoreName); + document.getElementById("regimentType").addEventListener("click", changeType); + document.getElementById("regimentName").addEventListener("change", changeName); + document.getElementById("regimentEmblem").addEventListener("input", changeEmblem); + document.getElementById("regimentEmblemSelect").addEventListener("click", selectEmblem); + document.getElementById("regimentAttack").addEventListener("click", toggleAttack); + document.getElementById("regimentRegenerateLegend").addEventListener("click", regenerateLegend); + document.getElementById("regimentLegend").addEventListener("click", editLegend); + document.getElementById("regimentSplit").addEventListener("click", splitRegiment); + document.getElementById("regimentAdd").addEventListener("click", toggleAdd); + document.getElementById("regimentAttach").addEventListener("click", toggleAttach); + document.getElementById("regimentRemove").addEventListener("click", removeRegiment); // get regiment data element function regiment() { - return pack.states[elSelected.dataset.state].military.find((r) => r.i == elSelected.dataset.id); + return pack.states[elSelected.dataset.state].military.find(r => r.i == elSelected.dataset.id); } function updateRegimentData(regiment) { @@ -56,7 +56,7 @@ function editRegiment(selector) { }) .join(""); - composition.querySelectorAll('input').forEach((el) => el.addEventListener('change', changeUnit)); + composition.querySelectorAll("input").forEach(el => el.addEventListener("change", changeUnit)); } function drawBase() { @@ -117,7 +117,7 @@ function editRegiment(selector) { const reg = regiment(), regs = pack.states[elSelected.dataset.state].military; const name = Military.getName(reg, regs); - elSelected.dataset.name = reg.name = document.getElementById('regimentName').value = name; + elSelected.dataset.name = reg.name = document.getElementById("regimentName").value = name; } function selectEmblem() { @@ -128,8 +128,8 @@ function editRegiment(selector) { } function changeEmblem() { - const emblem = document.getElementById('regimentEmblem').value; - regiment().icon = elSelected.querySelector('.regimentIcon').innerHTML = emblem; + const emblem = document.getElementById("regimentEmblem").value; + regiment().icon = elSelected.querySelector(".regimentIcon").innerHTML = emblem; } function changeUnit() { @@ -137,7 +137,7 @@ function editRegiment(selector) { const reg = regiment(); reg.u[u] = +this.value || 0; reg.a = d3.sum(Object.values(reg.u)); - elSelected.querySelector('text').innerHTML = Military.getTotal(reg); + elSelected.querySelector("text").innerHTML = Military.getTotal(reg); if (militaryOverviewRefresh.offsetParent) militaryOverviewRefresh.click(); if (regimentsOverviewRefresh.offsetParent) regimentsOverviewRefresh.click(); } @@ -193,13 +193,13 @@ function editRegiment(selector) { } function toggleAdd() { - document.getElementById('regimentAdd').classList.toggle('pressed'); - if (document.getElementById('regimentAdd').classList.contains('pressed')) { - viewbox.style('cursor', 'crosshair').on('click', addRegimentOnClick); - tip('Click on map to create new regiment or fleet', true); + document.getElementById("regimentAdd").classList.toggle("pressed"); + if (document.getElementById("regimentAdd").classList.contains("pressed")) { + viewbox.style("cursor", "crosshair").on("click", addRegimentOnClick); + tip("Click on map to create new regiment or fleet", true); } else { clearMainTip(); - viewbox.on('click', clicked).style('cursor', 'default'); + viewbox.on("click", clicked).style("cursor", "default"); } } @@ -222,15 +222,15 @@ function editRegiment(selector) { } function toggleAttack() { - document.getElementById('regimentAttack').classList.toggle('pressed'); - if (document.getElementById('regimentAttack').classList.contains('pressed')) { - viewbox.style('cursor', 'crosshair').on('click', attackRegimentOnClick); - tip('Click on another regiment to initiate battle', true); - armies.selectAll(':scope > g').classed('draggable', false); + document.getElementById("regimentAttack").classList.toggle("pressed"); + if (document.getElementById("regimentAttack").classList.contains("pressed")) { + viewbox.style("cursor", "crosshair").on("click", attackRegimentOnClick); + tip("Click on another regiment to initiate battle", true); + armies.selectAll(":scope > g").classed("draggable", false); } else { clearMainTip(); - armies.selectAll(':scope > g').classed('draggable', true); - viewbox.on('click', clicked).style('cursor', 'default'); + armies.selectAll(":scope > g").classed("draggable", true); + viewbox.on("click", clicked).style("cursor", "default"); } } @@ -290,19 +290,19 @@ function editRegiment(selector) { .remove(); clearMainTip(); - $('#regimentEditor').dialog('close'); + $("#regimentEditor").dialog("close"); } function toggleAttach() { - document.getElementById('regimentAttach').classList.toggle('pressed'); - if (document.getElementById('regimentAttach').classList.contains('pressed')) { - viewbox.style('cursor', 'crosshair').on('click', attachRegimentOnClick); - tip('Click on another regiment to unite both regiments. The current regiment will be removed', true); - armies.selectAll(':scope > g').classed('draggable', false); + document.getElementById("regimentAttach").classList.toggle("pressed"); + if (document.getElementById("regimentAttach").classList.contains("pressed")) { + viewbox.style("cursor", "crosshair").on("click", attachRegimentOnClick); + tip("Click on another regiment to unite both regiments. The current regiment will be removed", true); + armies.selectAll(":scope > g").classed("draggable", false); } else { clearMainTip(); - armies.selectAll(':scope > g').classed('draggable', true); - viewbox.on('click', clicked).style('cursor', 'default'); + armies.selectAll(":scope > g").classed("draggable", true); + viewbox.on("click", clicked).style("cursor", "default"); } } @@ -323,19 +323,19 @@ function editRegiment(selector) { } const reg = regiment(); // reg to be attached - const sel = pack.states[newState].military.find((r) => r.i == regSelected.dataset.id); // reg to attach to + const sel = pack.states[newState].military.find(r => r.i == regSelected.dataset.id); // reg to attach to for (const unit of options.military) { const u = unit.name; if (reg.u[u]) sel.u[u] ? (sel.u[u] += reg.u[u]) : (sel.u[u] = reg.u[u]); } sel.a = d3.sum(Object.values(sel.u)); // reg total - regSelected.querySelector('text').innerHTML = Military.getTotal(sel); // update selected reg total text + regSelected.querySelector("text").innerHTML = Military.getTotal(sel); // update selected reg total text // remove attached regiment const military = pack.states[oldState].military; military.splice(military.indexOf(reg), 1); - const index = notes.findIndex((n) => n.id === elSelected.id); + const index = notes.findIndex(n => n.id === elSelected.id); if (index != -1) notes.splice(index, 1); elSelected.remove(); @@ -345,7 +345,7 @@ function editRegiment(selector) { } function regenerateLegend() { - const index = notes.findIndex((n) => n.id === elSelected.id); + const index = notes.findIndex(n => n.id === elSelected.id); if (index != -1) notes.splice(index, 1); const s = pack.states[elSelected.dataset.state]; @@ -369,7 +369,7 @@ function editRegiment(selector) { if (regIndex === -1) return; military.splice(regIndex, 1); - const index = notes.findIndex((n) => n.id === elSelected.id); + const index = notes.findIndex(n => n.id === elSelected.id); if (index != -1) notes.splice(index, 1); elSelected.remove(); @@ -388,20 +388,20 @@ function editRegiment(selector) { d3.select(this).raise(); d3.select(this.parentNode).raise(); - const reg = pack.states[this.dataset.state].military.find((r) => r.i == this.dataset.id); - const size = +armies.attr('box-size'); + const reg = pack.states[this.dataset.state].military.find(r => r.i == this.dataset.id); + const size = +armies.attr("box-size"); const w = reg.n ? size * 4 : size * 6; const h = size * 2; - const x1 = (x) => rn(x - w / 2, 2); - const y1 = (y) => rn(y - size, 2); + const x1 = x => rn(x - w / 2, 2); + const y1 = y => rn(y - size, 2); - const baseRect = this.querySelector('rect'); - const text = this.querySelector('text'); - const iconRect = this.querySelectorAll('rect')[1]; - const icon = this.querySelector('.regimentIcon'); + const baseRect = this.querySelector("rect"); + const text = this.querySelector("text"); + const iconRect = this.querySelectorAll("rect")[1]; + const icon = this.querySelector(".regimentIcon"); const self = elSelected === this; - const baseLine = viewbox.select('g#regimentBase > line'); + const baseLine = viewbox.select("g#regimentBase > line"); d3.event.on("drag", function () { const x = (reg.x = d3.event.x), @@ -420,7 +420,7 @@ function editRegiment(selector) { } function dragBase() { - const baseLine = viewbox.select('g#regimentBase > line'); + const baseLine = viewbox.select("g#regimentBase > line"); const reg = regiment(); d3.event.on("drag", function () { @@ -436,12 +436,12 @@ function editRegiment(selector) { } function closeEditor() { - armies.selectAll(':scope > g').classed('draggable', false); - armies.selectAll('g>g').call(d3.drag().on('drag', null)); - viewbox.selectAll('g#regimentBase').remove(); - document.getElementById('regimentAdd').classList.remove('pressed'); - document.getElementById('regimentAttack').classList.remove('pressed'); - document.getElementById('regimentAttach').classList.remove('pressed'); + armies.selectAll(":scope > g").classed("draggable", false); + armies.selectAll("g>g").call(d3.drag().on("drag", null)); + viewbox.selectAll("g#regimentBase").remove(); + document.getElementById("regimentAdd").classList.remove("pressed"); + document.getElementById("regimentAttack").classList.remove("pressed"); + document.getElementById("regimentAttach").classList.remove("pressed"); restoreDefaultEvents(); elSelected = null; } diff --git a/modules/ui/relief-editor.js b/modules/ui/relief-editor.js index b7c7397e..abb800cd 100644 --- a/modules/ui/relief-editor.js +++ b/modules/ui/relief-editor.js @@ -1,10 +1,10 @@ -'use strict'; +"use strict"; function editReliefIcon() { if (customization) return; - closeDialogs('.stable'); - if (!layerIsOn('toggleRelief')) toggleRelief(); + closeDialogs(".stable"); + if (!layerIsOn("toggleRelief")) toggleRelief(); - terrain.selectAll('use').call(d3.drag().on('drag', dragReliefIcon)).classed('draggable', true); + terrain.selectAll("use").call(d3.drag().on("drag", dragReliefIcon)).classed("draggable", true); elSelected = d3.select(d3.event.target); restoreEditMode(); @@ -23,24 +23,24 @@ function editReliefIcon() { modules.editReliefIcon = true; // add listeners - document.getElementById('reliefIndividual').addEventListener('click', enterIndividualMode); - document.getElementById('reliefBulkAdd').addEventListener('click', enterBulkAddMode); - document.getElementById('reliefBulkRemove').addEventListener('click', enterBulkRemoveMode); + document.getElementById("reliefIndividual").addEventListener("click", enterIndividualMode); + document.getElementById("reliefBulkAdd").addEventListener("click", enterBulkAddMode); + document.getElementById("reliefBulkRemove").addEventListener("click", enterBulkRemoveMode); - document.getElementById('reliefSize').addEventListener('input', changeIconSize); - document.getElementById('reliefSizeNumber').addEventListener('input', changeIconSize); - document.getElementById('reliefEditorSet').addEventListener('change', changeIconsSet); - reliefIconsDiv.querySelectorAll('svg').forEach((el) => el.addEventListener('click', changeIcon)); + document.getElementById("reliefSize").addEventListener("input", changeIconSize); + document.getElementById("reliefSizeNumber").addEventListener("input", changeIconSize); + document.getElementById("reliefEditorSet").addEventListener("change", changeIconsSet); + reliefIconsDiv.querySelectorAll("svg").forEach(el => el.addEventListener("click", changeIcon)); - document.getElementById('reliefEditStyle').addEventListener('click', () => editStyle('terrain')); - document.getElementById('reliefCopy').addEventListener('click', copyIcon); - document.getElementById('reliefMoveFront').addEventListener('click', () => elSelected.raise()); - document.getElementById('reliefMoveBack').addEventListener('click', () => elSelected.lower()); - document.getElementById('reliefRemove').addEventListener('click', removeIcon); + document.getElementById("reliefEditStyle").addEventListener("click", () => editStyle("terrain")); + document.getElementById("reliefCopy").addEventListener("click", copyIcon); + document.getElementById("reliefMoveFront").addEventListener("click", () => elSelected.raise()); + document.getElementById("reliefMoveBack").addEventListener("click", () => elSelected.lower()); + document.getElementById("reliefRemove").addEventListener("click", removeIcon); function dragReliefIcon() { - const dx = +this.getAttribute('x') - d3.event.x; - const dy = +this.getAttribute('y') - d3.event.y; + const dx = +this.getAttribute("x") - d3.event.x; + const dy = +this.getAttribute("y") - d3.event.y; d3.event.on("drag", function () { const x = d3.event.x, @@ -68,18 +68,18 @@ function editReliefIcon() { } function updateReliefSizeInput() { - const size = +elSelected.attr('width'); + const size = +elSelected.attr("width"); reliefSize.value = reliefSizeNumber.value = rn(size); } function enterIndividualMode() { - reliefTools.querySelectorAll('button.pressed').forEach((b) => b.classList.remove('pressed')); - reliefIndividual.classList.add('pressed'); + reliefTools.querySelectorAll("button.pressed").forEach(b => b.classList.remove("pressed")); + reliefIndividual.classList.add("pressed"); - reliefSizeDiv.style.display = 'block'; - reliefRadiusDiv.style.display = 'none'; - reliefSpacingDiv.style.display = 'none'; - reliefIconsSeletionAny.style.display = 'none'; + reliefSizeDiv.style.display = "block"; + reliefRadiusDiv.style.display = "none"; + reliefSpacingDiv.style.display = "none"; + reliefIconsSeletionAny.style.display = "none"; removeCircle(); updateReliefSizeInput(); @@ -88,13 +88,13 @@ function editReliefIcon() { } function enterBulkAddMode() { - reliefTools.querySelectorAll('button.pressed').forEach((b) => b.classList.remove('pressed')); - reliefBulkAdd.classList.add('pressed'); + reliefTools.querySelectorAll("button.pressed").forEach(b => b.classList.remove("pressed")); + reliefBulkAdd.classList.add("pressed"); - reliefSizeDiv.style.display = 'block'; - reliefRadiusDiv.style.display = 'block'; - reliefSpacingDiv.style.display = 'block'; - reliefIconsSeletionAny.style.display = 'none'; + reliefSizeDiv.style.display = "block"; + reliefRadiusDiv.style.display = "block"; + reliefSpacingDiv.style.display = "block"; + reliefIconsSeletionAny.style.display = "none"; const pressedType = reliefIconsDiv.querySelector("svg.pressed"); if (pressedType.id === "reliefIconsSeletionAny") { @@ -103,8 +103,8 @@ function editReliefIcon() { reliefIconsDiv.querySelector("svg").classList.add("pressed"); } - viewbox.style('cursor', 'crosshair').call(d3.drag().on('start', dragToAdd)).on('touchmove mousemove', moveBrush); - tip('Drag to place relief icons within radius', true); + viewbox.style("cursor", "crosshair").call(d3.drag().on("start", dragToAdd)).on("touchmove mousemove", moveBrush); + tip("Drag to place relief icons within radius", true); } function moveBrush() { @@ -172,13 +172,13 @@ function editReliefIcon() { } function enterBulkRemoveMode() { - reliefTools.querySelectorAll('button.pressed').forEach((b) => b.classList.remove('pressed')); - reliefBulkRemove.classList.add('pressed'); + reliefTools.querySelectorAll("button.pressed").forEach(b => b.classList.remove("pressed")); + reliefBulkRemove.classList.add("pressed"); - reliefSizeDiv.style.display = 'none'; - reliefRadiusDiv.style.display = 'block'; - reliefSpacingDiv.style.display = 'none'; - reliefIconsSeletionAny.style.display = 'inline-block'; + reliefSizeDiv.style.display = "none"; + reliefRadiusDiv.style.display = "block"; + reliefSpacingDiv.style.display = "none"; + reliefIconsSeletionAny.style.display = "inline-block"; viewbox.style("cursor", "crosshair").call(d3.drag().on("start", dragToRemove)).on("touchmove mousemove", moveBrush); tip("Drag to remove relief icons in radius", true); @@ -201,13 +201,13 @@ function editReliefIcon() { d3.event.on("drag", function () { const p = d3.mouse(this); moveCircle(p[0], p[1], r); - tree.findAll(p[0], p[1], r).forEach((f) => f[2].remove()); + tree.findAll(p[0], p[1], r).forEach(f => f[2].remove()); }); } function changeIconSize() { const size = +reliefSizeNumber.value; - if (!reliefIndividual.classList.contains('pressed')) return; + if (!reliefIndividual.classList.contains("pressed")) return; const shift = (size - +elSelected.attr("width")) / 2; elSelected.attr("width", size).attr("height", size); @@ -223,14 +223,14 @@ function editReliefIcon() { } function changeIcon() { - if (this.classList.contains('pressed')) return; + if (this.classList.contains("pressed")) return; reliefIconsDiv.querySelectorAll("svg.pressed").forEach(b => b.classList.remove("pressed")); this.classList.add("pressed"); - if (reliefIndividual.classList.contains('pressed')) { + if (reliefIndividual.classList.contains("pressed")) { const type = this.dataset.type; - elSelected.attr('href', type); + elSelected.attr("href", type); } } @@ -245,8 +245,8 @@ function editReliefIcon() { y -= 3; } - copy.setAttribute('x', x); - copy.setAttribute('y', y); + copy.setAttribute("x", x); + copy.setAttribute("y", y); parent.insertBefore(copy, null); } @@ -280,7 +280,7 @@ function editReliefIcon() { } function closeReliefEditor() { - terrain.selectAll('use').call(d3.drag().on('drag', null)).classed('draggable', false); + terrain.selectAll("use").call(d3.drag().on("drag", null)).classed("draggable", false); removeCircle(); unselect(); clearMainTip();