Chore: linting

This commit is contained in:
Pieter Vander Vennet 2024-04-13 02:40:21 +02:00
parent 4625ad9a5c
commit 097141f944
307 changed files with 5346 additions and 2147 deletions

View file

@ -24,7 +24,7 @@ export interface RasterLayerProperties {
readonly url: string
readonly category?: string | EliCategory
readonly type?: "vector" | "raster" | string
readonly style?: string,
readonly style?: string
readonly attribution?: {
readonly url?: string

View file

@ -51,9 +51,10 @@ export class AvailableRasterLayers {
/**
* The default background layer that any theme uses which does not explicitly define a background
*/
public static readonly defaultBackgroundLayer: RasterLayerPolygon = AvailableRasterLayers.globalLayers.find(l => {
return l.properties.id === "protomaps.sunny"
})
public static readonly defaultBackgroundLayer: RasterLayerPolygon =
AvailableRasterLayers.globalLayers.find((l) => {
return l.properties.id === "protomaps.sunny"
})
public static layersAvailableAt(
location: Store<{ lon: number; lat: number }>,

View file

@ -65,31 +65,37 @@ class ExpandFilter extends DesugaringStep<LayerConfigJson> {
const newFilters: FilterConfigJson[] = []
const filters = <(FilterConfigJson | string)[]>json.filter
for (let i = 0; i < filters.length; i++){
for (let i = 0; i < filters.length; i++) {
const filter = filters[i]
if (typeof filter !== "string") {
newFilters.push(filter)
continue
}
const matchingTr =<TagRenderingConfigJson> json.tagRenderings.find(tr => !!tr && tr["id"] === filter)
if(matchingTr){
if(!(matchingTr.mappings?.length >= 1)){
context.enters("filter",i ).err("Found a matching tagRendering to base a filter on, but this tagRendering does not contain any mappings")
const matchingTr = <TagRenderingConfigJson>(
json.tagRenderings.find((tr) => !!tr && tr["id"] === filter)
)
if (matchingTr) {
if (!(matchingTr.mappings?.length >= 1)) {
context
.enters("filter", i)
.err(
"Found a matching tagRendering to base a filter on, but this tagRendering does not contain any mappings"
)
}
const options = matchingTr.mappings.map(mapping => ({
const options = matchingTr.mappings.map((mapping) => ({
question: mapping.then,
osmTags: mapping.if
osmTags: mapping.if,
}))
options.unshift({
question: {
en:"All types"
en: "All types",
},
osmTags: undefined
osmTags: undefined,
})
newFilters.push({
id: filter,
options
options,
})
continue
}
@ -521,9 +527,9 @@ export class AddQuestionBox extends DesugaringStep<LayerConfigJson> {
json = { ...json }
json.tagRenderings = [...json.tagRenderings]
const allSpecials: Exclude<RenderingSpecification, string>[] = <any>(
ValidationUtils.getAllSpecialVisualisations(<QuestionableTagRenderingConfigJson[]> json.tagRenderings).filter(
(spec) => typeof spec !== "string"
)
ValidationUtils.getAllSpecialVisualisations(
<QuestionableTagRenderingConfigJson[]>json.tagRenderings
).filter((spec) => typeof spec !== "string")
)
const questionSpecials = allSpecials.filter((sp) => sp.func.funcName === "questions")

View file

@ -289,7 +289,10 @@ class AddContextToTranslationsInLayout extends DesugaringStep<LayoutConfigJson>
convert(json: LayoutConfigJson): LayoutConfigJson {
const conversion = new AddContextToTranslations<LayoutConfigJson>("themes:")
// The context is used to generate the 'context' in the translation .It _must_ be `json.id` to correctly link into weblate
return conversion.convert(json, ConversionContext.construct([json.id],["AddContextToTranslation"]))
return conversion.convert(
json,
ConversionContext.construct([json.id], ["AddContextToTranslation"])
)
}
}
@ -602,19 +605,32 @@ class PostvalidateTheme extends DesugaringStep<LayoutConfigJson> {
}
for (const layer of json.layers) {
if(typeof layer === "string"){
if (typeof layer === "string") {
continue
}
const config = <LayerConfigJson> layer;
const config = <LayerConfigJson>layer
const sameAs = config.filter?.["sameAs"]
if(!sameAs){
if (!sameAs) {
continue
}
const matchingLayer = json.layers.find(l => l["id"] === sameAs)
if(!matchingLayer){
const closeLayers = Utils.sortedByLevenshteinDistance(sameAs, json.layers, l => l["id"]).map(l => l["id"])
context.enters("layers", config.id, "filter","sameAs").err("The layer "+config.id+" follows the filter state of layer "+sameAs+", but no layer with this name was found.\n\tDid you perhaps mean one of: "+closeLayers.slice(0, 3).join(", "))
const matchingLayer = json.layers.find((l) => l["id"] === sameAs)
if (!matchingLayer) {
const closeLayers = Utils.sortedByLevenshteinDistance(
sameAs,
json.layers,
(l) => l["id"]
).map((l) => l["id"])
context
.enters("layers", config.id, "filter", "sameAs")
.err(
"The layer " +
config.id +
" follows the filter state of layer " +
sameAs +
", but no layer with this name was found.\n\tDid you perhaps mean one of: " +
closeLayers.slice(0, 3).join(", ")
)
}
}

View file

@ -278,10 +278,14 @@ export class ValidateTheme extends DesugaringStep<LayoutConfigJson> {
if (!isCategory && !ValidateTheme._availableLayers.has(backgroundId)) {
const options = Array.from(ValidateTheme._availableLayers)
const nearby = Utils.sortedByLevenshteinDistance(backgroundId, options, t => t)
const nearby = Utils.sortedByLevenshteinDistance(backgroundId, options, (t) => t)
context
.enter("defaultBackgroundId")
.err(`This layer ID is not known: ${backgroundId}. Perhaps you meant one of ${nearby.slice(0,5).join(", ")}`)
.err(
`This layer ID is not known: ${backgroundId}. Perhaps you meant one of ${nearby
.slice(0, 5)
.join(", ")}`
)
}
}
@ -1014,7 +1018,7 @@ class MiscTagRenderingChecks extends DesugaringStep<TagRenderingConfigJson> {
) {
continue
}
if(json.freeform.key.indexOf("wikidata")>=0){
if (json.freeform.key.indexOf("wikidata") >= 0) {
context
.enter("render")
.err(
@ -1273,7 +1277,14 @@ export class PrevalidateLayer extends DesugaringStep<LayerConfigJson> {
// It is tempting to add an index to this warning; however, due to labels the indices here might be different from the index in the tagRendering list
context
.enter("tagRenderings")
.err("Some tagrenderings have a duplicate id: " + duplicates.join(", ")+"\n"+JSON.stringify(json.tagRenderings.filter(tr=> duplicates.indexOf(tr["id"])>=0)))
.err(
"Some tagrenderings have a duplicate id: " +
duplicates.join(", ") +
"\n" +
JSON.stringify(
json.tagRenderings.filter((tr) => duplicates.indexOf(tr["id"]) >= 0)
)
)
}
}
@ -1865,11 +1876,14 @@ export class ValidateThemeEnsemble extends Conversion<
string,
{
tags: TagsFilter
foundInTheme: string[],
foundInTheme: string[]
isCounted: boolean
}
> {
const idToSource = new Map<string, { tags: TagsFilter; foundInTheme: string[], isCounted: boolean }>()
const idToSource = new Map<
string,
{ tags: TagsFilter; foundInTheme: string[]; isCounted: boolean }
>()
for (const theme of json) {
for (const layer of theme.layers) {

View file

@ -62,8 +62,6 @@ export default class ValidationUtils {
}
for (const key in translation) {
const template = translation[key]
const parts = SpecialVisualizations.constructSpecification(template)
const specials = parts.filter((p) => typeof p !== "string")

View file

@ -91,7 +91,7 @@ export default class LayerConfig extends WithContextLoader {
mercatorCrs: json.source["mercatorCrs"],
idKey: json.source["idKey"],
},
json.id,
json.id
)
}
@ -106,8 +106,8 @@ export default class LayerConfig extends WithContextLoader {
}
this.units = [].concat(
...(json.units ?? []).map((unitJson, i) =>
Unit.fromJson(unitJson, `${context}.unit[${i}]`),
),
Unit.fromJson(unitJson, `${context}.unit[${i}]`)
)
)
if (json.description !== undefined) {
@ -122,7 +122,7 @@ export default class LayerConfig extends WithContextLoader {
if (json.calculatedTags !== undefined) {
if (!official) {
console.warn(
`Unofficial theme ${this.id} with custom javascript! This is a security risk`,
`Unofficial theme ${this.id} with custom javascript! This is a security risk`
)
}
this.calculatedTags = []
@ -191,7 +191,7 @@ export default class LayerConfig extends WithContextLoader {
tags: pr.tags.map((t) => TagUtils.SimpleTag(t)),
description: Translations.T(
pr.description,
`${translationContext}.presets.${i}.description`,
`${translationContext}.presets.${i}.description`
),
preciseInput: preciseInput,
exampleImages: pr.exampleImages,
@ -205,7 +205,7 @@ export default class LayerConfig extends WithContextLoader {
if (json.lineRendering) {
this.lineRendering = Utils.NoNull(json.lineRendering).map(
(r, i) => new LineRenderingConfig(r, `${context}[${i}]`),
(r, i) => new LineRenderingConfig(r, `${context}[${i}]`)
)
} else {
this.lineRendering = []
@ -213,7 +213,7 @@ export default class LayerConfig extends WithContextLoader {
if (json.pointRendering) {
this.mapRendering = Utils.NoNull(json.pointRendering).map(
(r, i) => new PointRenderingConfig(r, `${context}[${i}](${this.id})`),
(r, i) => new PointRenderingConfig(r, `${context}[${i}](${this.id})`)
)
} else {
this.mapRendering = []
@ -225,7 +225,7 @@ export default class LayerConfig extends WithContextLoader {
r.location.has("centroid") ||
r.location.has("projected_centerpoint") ||
r.location.has("start") ||
r.location.has("end"),
r.location.has("end")
)
if (
@ -247,7 +247,7 @@ export default class LayerConfig extends WithContextLoader {
Constants.priviliged_layers.indexOf(<any>this.id) < 0 &&
this.source !== null /*library layer*/ &&
!this.source?.geojsonSource?.startsWith(
"https://api.openstreetmap.org/api/0.6/notes.json",
"https://api.openstreetmap.org/api/0.6/notes.json"
)
) {
throw (
@ -266,7 +266,7 @@ export default class LayerConfig extends WithContextLoader {
typeof tr !== "string" &&
tr["builtin"] === undefined &&
tr["id"] === undefined &&
tr["rewrite"] === undefined,
tr["rewrite"] === undefined
) ?? []
if (missingIds?.length > 0 && official) {
console.error("Some tagRenderings of", this.id, "are missing an id:", missingIds)
@ -277,8 +277,8 @@ export default class LayerConfig extends WithContextLoader {
(tr, i) =>
new TagRenderingConfig(
<QuestionableTagRenderingConfigJson>tr,
this.id + ".tagRenderings[" + i + "]",
),
this.id + ".tagRenderings[" + i + "]"
)
)
if (
@ -352,7 +352,7 @@ export default class LayerConfig extends WithContextLoader {
public GetBaseTags(): Record<string, string> {
return TagUtils.changeAsProperties(
this.source?.osmTags?.asChange({ id: "node/-1" }) ?? [{ k: "id", v: "node/-1" }],
this.source?.osmTags?.asChange({ id: "node/-1" }) ?? [{ k: "id", v: "node/-1" }]
)
}
@ -365,7 +365,7 @@ export default class LayerConfig extends WithContextLoader {
neededLayer: string
}[] = [],
addedByDefault = false,
canBeIncluded = true,
canBeIncluded = true
): BaseUIElement {
const extraProps: (string | BaseUIElement)[] = []
@ -374,32 +374,32 @@ export default class LayerConfig extends WithContextLoader {
if (canBeIncluded) {
if (addedByDefault) {
extraProps.push(
"**This layer is included automatically in every theme. This layer might contain no points**",
"**This layer is included automatically in every theme. This layer might contain no points**"
)
}
if (this.shownByDefault === false) {
extraProps.push(
"This layer is not visible by default and must be enabled in the filter by the user. ",
"This layer is not visible by default and must be enabled in the filter by the user. "
)
}
if (this.title === undefined) {
extraProps.push(
"Elements don't have a title set and cannot be toggled nor will they show up in the dashboard. If you import this layer in your theme, override `title` to make this toggleable.",
"Elements don't have a title set and cannot be toggled nor will they show up in the dashboard. If you import this layer in your theme, override `title` to make this toggleable."
)
}
if (this.name === undefined && this.shownByDefault === false) {
extraProps.push(
"This layer is not visible by default and the visibility cannot be toggled, effectively resulting in a fully hidden layer. This can be useful, e.g. to calculate some metatags. If you want to render this layer (e.g. for debugging), enable it by setting the URL-parameter layer-<id>=true",
"This layer is not visible by default and the visibility cannot be toggled, effectively resulting in a fully hidden layer. This can be useful, e.g. to calculate some metatags. If you want to render this layer (e.g. for debugging), enable it by setting the URL-parameter layer-<id>=true"
)
}
if (this.name === undefined) {
extraProps.push(
"Not visible in the layer selection by default. If you want to make this layer toggable, override `name`",
"Not visible in the layer selection by default. If you want to make this layer toggable, override `name`"
)
}
if (this.mapRendering.length === 0) {
extraProps.push(
"Not rendered on the map by default. If you want to rendering this on the map, override `mapRenderings`",
"Not rendered on the map by default. If you want to rendering this on the map, override `mapRenderings`"
)
}
@ -411,26 +411,27 @@ export default class LayerConfig extends WithContextLoader {
: undefined,
"This layer is loaded from an external source, namely ",
new FixedUiElement(this.source.geojsonSource).SetClass("code"),
]),
])
)
}
} else {
extraProps.push(
"This layer can **not** be included in a theme. It is solely used by [special renderings](SpecialRenderings.md) showing a minimap with custom data.",
"This layer can **not** be included in a theme. It is solely used by [special renderings](SpecialRenderings.md) showing a minimap with custom data."
)
}
let usingLayer: BaseUIElement[] = []
if (!addedByDefault) {
if (usedInThemes?.length > 0) {
usingLayer = [
new Title("Themes using this layer", 4),
new List(
(usedInThemes ?? []).map((id) => new Link(id, "https://mapcomplete.org/" + id)),
(usedInThemes ?? []).map(
(id) => new Link(id, "https://mapcomplete.org/" + id)
)
),
]
} else if(this.source !== null) {
} else if (this.source !== null) {
usingLayer = [new FixedUiElement("No themes use this layer")]
}
}
@ -443,7 +444,7 @@ export default class LayerConfig extends WithContextLoader {
" into the layout as it depends on it: ",
dep.reason,
"(" + dep.context + ")",
]),
])
)
}
@ -452,7 +453,7 @@ export default class LayerConfig extends WithContextLoader {
new Combine([
"This layer is needed as dependency for layer",
new Link(revDep, "#" + revDep),
]),
])
)
}
@ -464,14 +465,14 @@ export default class LayerConfig extends WithContextLoader {
return undefined
}
const embedded: (Link | string)[] = values.values?.map((v) =>
Link.OsmWiki(values.key, v, true).SetClass("mr-2"),
Link.OsmWiki(values.key, v, true).SetClass("mr-2")
) ?? ["_no preset options defined, or no values in them_"]
return [
new Combine([
new Link(
"<img src='https://mapcomplete.org/assets/svg/statistics.svg' height='18px'>",
"https://taginfo.openstreetmap.org/keys/" + values.key + "#values",
true,
true
),
Link.OsmWiki(values.key),
]).SetClass("flex"),
@ -480,7 +481,7 @@ export default class LayerConfig extends WithContextLoader {
: new Link(values.type, "../SpecialInputElements.md#" + values.type),
new Combine(embedded).SetClass("flex"),
]
}),
})
)
let quickOverview: BaseUIElement = undefined
@ -490,7 +491,7 @@ export default class LayerConfig extends WithContextLoader {
"this quick overview is incomplete",
new Table(
["attribute", "type", "values which are supported by this layer"],
tableRows,
tableRows
).SetClass("zebra-table"),
]).SetClass("flex-col flex")
}
@ -504,7 +505,7 @@ export default class LayerConfig extends WithContextLoader {
(mr) =>
mr.RenderIcon(new ImmutableStore<OsmTags>({ id: "node/-1" }), {
includeBadges: false,
}).html,
}).html
)
.find((i) => i !== undefined)
}
@ -516,7 +517,7 @@ export default class LayerConfig extends WithContextLoader {
"Execute on overpass",
Overpass.AsOverpassTurboLink(<TagsFilter>this.source.osmTags.optimize())
.replaceAll("(", "%28")
.replaceAll(")", "%29"),
.replaceAll(")", "%29")
)
} catch (e) {
console.error("Could not generate overpasslink for " + this.id)
@ -538,19 +539,19 @@ export default class LayerConfig extends WithContextLoader {
const parts = neededTags["and"]
tagsDescription.push(
"Elements must match **all** of the following expressions:",
parts.map((p, i) => i + ". " + p.asHumanString(true, false, {})).join("\n"),
parts.map((p, i) => i + ". " + p.asHumanString(true, false, {})).join("\n")
)
} else if (neededTags["or"]) {
const parts = neededTags["or"]
tagsDescription.push(
"Elements must match **any** of the following expressions:",
parts.map((p) => " - " + p.asHumanString(true, false, {})).join("\n"),
parts.map((p) => " - " + p.asHumanString(true, false, {})).join("\n")
)
} else {
tagsDescription.push(
"Elements must match the expression **" +
neededTags.asHumanString(true, false, {}) +
"**",
neededTags.asHumanString(true, false, {}) +
"**"
)
}
@ -561,7 +562,7 @@ export default class LayerConfig extends WithContextLoader {
return new Combine([
new Combine([new Title(this.id, 1), iconImg, this.description, "\n"]).SetClass(
"flex flex-col",
"flex flex-col"
),
new List(extraProps),
...usingLayer,

View file

@ -313,7 +313,7 @@ export default class LayoutConfig implements LayoutInformation {
if (tags === undefined) {
return undefined
}
if(tags.id.startsWith("current_view")){
if (tags.id.startsWith("current_view")) {
return this.getLayer("current_view")
}
for (const layer of this.layers) {

View file

@ -232,11 +232,10 @@ export default class TagRenderingConfig {
throw "Tagrendering has a 'mappings'-object, but expected a list (" + context + ")"
}
const firstMappingSize: string = json.mappings.map((m) => (m.icon?.["class"])).find(c => !!c)
const commonIconSize =
firstMappingSize ??
json["#iconsize"] ??
"small"
const firstMappingSize: string = json.mappings
.map((m) => m.icon?.["class"])
.find((c) => !!c)
const commonIconSize = firstMappingSize ?? json["#iconsize"] ?? "small"
this.mappings = json.mappings.map((m, i) =>
TagRenderingConfig.ExtractMapping(
m,