Feature: allow to move and snap to a layer, fix #2120

This commit is contained in:
Pieter Vander Vennet 2024-09-04 00:07:23 +02:00
parent eb89427bfc
commit fdedb75954
34 changed files with 824 additions and 301 deletions

View file

@ -22,6 +22,7 @@ import { Overpass } from "../../Logic/Osm/Overpass"
import Constants from "../Constants"
import { QuestionableTagRenderingConfigJson } from "./Json/QuestionableTagRenderingConfigJson"
import MarkdownUtils from "../../Utils/MarkdownUtils"
import { And } from "../../Logic/Tags/And"
export default class LayerConfig extends WithContextLoader {
public static readonly syncSelectionAllowed = ["no", "local", "theme-only", "global"] as const
@ -48,6 +49,7 @@ export default class LayerConfig extends WithContextLoader {
public readonly allowSplit: boolean
public readonly shownByDefault: boolean
public readonly doCount: boolean
public readonly snapName?: Translation
/**
* In seconds
*/
@ -97,12 +99,13 @@ export default class LayerConfig extends WithContextLoader {
mercatorCrs: json.source["mercatorCrs"],
idKey: json.source["idKey"],
},
json.id
json.id,
)
}
this.allowSplit = json.allowSplit ?? false
this.name = Translations.T(json.name, translationContext + ".name")
this.snapName = Translations.T(json.snapName, translationContext + ".snapName")
if (json.description !== undefined) {
if (Object.keys(json.description).length === 0) {
@ -116,7 +119,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 = []
@ -186,7 +189,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,
@ -200,7 +203,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 = []
@ -208,7 +211,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 = []
@ -220,7 +223,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 (
@ -242,7 +245,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 (
@ -261,7 +264,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)
@ -272,8 +275,8 @@ export default class LayerConfig extends WithContextLoader {
(tr, i) =>
new TagRenderingConfig(
<QuestionableTagRenderingConfigJson>tr,
this.id + ".tagRenderings[" + i + "]"
)
this.id + ".tagRenderings[" + i + "]",
),
)
if (json.units !== undefined && !Array.isArray(json.units)) {
throw (
@ -283,7 +286,7 @@ export default class LayerConfig extends WithContextLoader {
)
}
this.units = (json.units ?? []).flatMap((unitJson, i) =>
Unit.fromJson(unitJson, this.tagRenderings, `${context}.unit[${i}]`)
Unit.fromJson(unitJson, this.tagRenderings, `${context}.unit[${i}]`),
)
if (
@ -359,7 +362,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" }],
)
}
@ -372,7 +375,7 @@ export default class LayerConfig extends WithContextLoader {
neededLayer: string
}[] = [],
addedByDefault = false,
canBeIncluded = true
canBeIncluded = true,
): string {
const extraProps: string[] = []
extraProps.push("This layer is shown at zoomlevel **" + this.minzoom + "** and higher")
@ -380,32 +383,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`",
)
}
@ -415,12 +418,12 @@ export default class LayerConfig extends WithContextLoader {
"<img src='../warning.svg' height='1rem'/>",
"This layer is loaded from an external source, namely ",
"`" + this.source.geojsonSource + "`",
].join("\n\n")
].join("\n\n"),
)
}
} 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.",
)
}
@ -430,7 +433,7 @@ export default class LayerConfig extends WithContextLoader {
usingLayer = [
"## Themes using this layer",
MarkdownUtils.list(
(usedInThemes ?? []).map((id) => `[${id}](https://mapcomplete.org/${id})`)
(usedInThemes ?? []).map((id) => `[${id}](https://mapcomplete.org/${id})`),
),
]
} else if (this.source !== null) {
@ -446,15 +449,31 @@ export default class LayerConfig extends WithContextLoader {
" into the layout as it depends on it: ",
dep.reason,
"(" + dep.context + ")",
].join(" ")
].join(" "),
)
}
let presets: string[] = []
if (this.presets.length > 0) {
presets = [
"## Presets",
"The following options to create new points are included:",
MarkdownUtils.list(this.presets.map(preset => {
let snaps = ""
if (preset.preciseInput?.snapToLayers) {
snaps = " (snaps to layers " + preset.preciseInput.snapToLayers.map(id => `\`${id}\``).join(", ") + ")"
}
return "**" + preset.title.txt + "** which has the following tags:" + new And(preset.tags).asHumanString(true) + snaps
})),
]
}
for (const revDep of Utils.Dedup(layerIsNeededBy?.get(this.id) ?? [])) {
extraProps.push(
["This layer is needed as dependency for layer", `[${revDep}](#${revDep})`].join(
" "
)
" ",
),
)
}
@ -465,10 +484,10 @@ export default class LayerConfig extends WithContextLoader {
.filter((values) => values.key !== "id")
.map((values) => {
const embedded: string[] = values.values?.map((v) =>
Link.OsmWiki(values.key, v, true).SetClass("mr-2").AsMarkdown()
Link.OsmWiki(values.key, v, true).SetClass("mr-2").AsMarkdown(),
) ?? ["_no preset options defined, or no values in them_"]
const statistics = `https://taghistory.raifer.tech/?#***/${encodeURIComponent(
values.key
values.key,
)}/`
const tagInfo = `https://taginfo.openstreetmap.org/keys/${values.key}#values`
return [
@ -483,7 +502,7 @@ export default class LayerConfig extends WithContextLoader {
: `[${values.type}](../SpecialInputElements.md#${values.type})`,
embedded.join(" "),
]
})
}),
)
let quickOverview: string[] = []
@ -493,7 +512,7 @@ export default class LayerConfig extends WithContextLoader {
"this quick overview is incomplete",
MarkdownUtils.table(
["attribute", "type", "values which are supported by this layer"],
tableRows
tableRows,
),
]
}
@ -527,19 +546,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, {}) +
"**",
)
}
@ -559,6 +578,7 @@ export default class LayerConfig extends WithContextLoader {
].join("\n\n"),
MarkdownUtils.list(extraProps),
...usingLayer,
...presets,
...tagsDescription,
"## Supported attributes",
quickOverview,
@ -583,4 +603,35 @@ export default class LayerConfig extends WithContextLoader {
public isLeftRightSensitive(): boolean {
return this.lineRendering.some((lr) => lr.leftRightSensitive)
}
public getMostMatchingPreset(tags: Record<string, string>): PresetConfig {
const presets = this.presets
if (!presets) {
return undefined
}
const matchingPresets = presets
.filter((pr) => new And(pr.tags).matchesProperties(tags))
let mostShadowed = matchingPresets[0]
let mostShadowedTags = new And(mostShadowed.tags)
for (let i = 1; i < matchingPresets.length; i++) {
const pr = matchingPresets[i]
const prTags = new And(pr.tags)
if (mostShadowedTags.shadows(prTags)) {
if (!prTags.shadows(mostShadowedTags)) {
// We have a new most shadowed item
mostShadowed = pr
mostShadowedTags = prTags
} else {
// Both shadow each other: abort
mostShadowed = undefined
break
}
} else if (!prTags.shadows(mostShadowedTags)) {
// The new contender does not win, but it might defeat the current contender
mostShadowed = undefined
break
}
}
return mostShadowed ?? matchingPresets[0]
}
}