From fdedb75954d0b46ca976c4455bbc8e8331f73b2d Mon Sep 17 00:00:00 2001 From: Pieter Vander Vennet Date: Wed, 4 Sep 2024 00:07:23 +0200 Subject: [PATCH] Feature: allow to move and snap to a layer, fix #2120 --- .../bicycle_assisted_repair_workshop.md | 159 ++++++++++++++++++ .../climbing_opportunity.json | 3 + .../cycleways_and_roads.json | 4 + assets/layers/indoors/indoors.json | 4 + assets/layers/kerbs/kerbs.json | 3 + .../pedestrian_path/pedestrian_path.json | 3 + assets/layers/shelter/shelter.json | 3 + .../walls_and_buildings.json | 4 + assets/svg/license_info.json | 16 ++ assets/svg/snap.svg | 84 +++++++++ assets/svg/snap.svg.license | 2 + assets/svg/unsnap.svg | 83 +++++++++ assets/svg/unsnap.svg.license | 2 + .../mapcomplete-changes.json | 93 ++++------ assets/themes/postal_codes/postal_codes.json | 1 - .../street_lighting/street_lighting.json | 1 - assets/themes/uk_addresses/uk_addresses.json | 1 - langs/en.json | 3 +- langs/layers/en.json | 1 + langs/layers/nl.json | 1 + src/Logic/Osm/Actions/ChangeLocationAction.ts | 33 +++- src/Logic/Osm/Actions/CreateNewNodeAction.ts | 75 ++------- .../Osm/Actions/InsertPointIntoWayAction.ts | 96 +++++++++++ .../ThemeConfig/Conversion/PrepareTheme.ts | 143 ++++++++-------- .../ThemeConfig/DependencyCalculator.ts | 7 +- .../ThemeConfig/Json/LayerConfigJson.ts | 9 + src/Models/ThemeConfig/LayerConfig.ts | 117 +++++++++---- .../NewPointLocationInput.svelte | 25 ++- src/UI/Map/Icon.svelte | 3 + src/UI/Popup/MoveWizard.svelte | 37 ++-- src/UI/Popup/MoveWizardState.ts | 71 ++++++-- src/UI/SpecialVisualizations.ts | 31 +--- src/UI/i18n/Translation.ts | 3 + src/assets/svg/Snap.svelte | 4 + 34 files changed, 824 insertions(+), 301 deletions(-) create mode 100644 Docs/Layers/bicycle_assisted_repair_workshop.md create mode 100644 assets/svg/snap.svg create mode 100644 assets/svg/snap.svg.license create mode 100644 assets/svg/unsnap.svg create mode 100644 assets/svg/unsnap.svg.license create mode 100644 src/Logic/Osm/Actions/InsertPointIntoWayAction.ts create mode 100644 src/assets/svg/Snap.svelte diff --git a/Docs/Layers/bicycle_assisted_repair_workshop.md b/Docs/Layers/bicycle_assisted_repair_workshop.md new file mode 100644 index 000000000..1a5aa48d6 --- /dev/null +++ b/Docs/Layers/bicycle_assisted_repair_workshop.md @@ -0,0 +1,159 @@ +[//]: # (WARNING: this file is automatically generated. Please find the sources at the bottom and edit those sources) + +# bicycle_assisted_repair_workshop + +This layer is based on [assisted_repair](../Layers/assisted_repair.md) + +A self-assisted workshop is a location where people can come and repair their goods with help of volunteers and with the tools available at the given location. A repair café is a type of event organized regularly along the same principles. + + - This layer is shown at zoomlevel **11** and higher + +## Table of contents + +1. [Themes using this layer](#themes-using-this-layer) +2. [Basic tags for this layer](#basic-tags-for-this-layer) +3. [Supported attributes](#supported-attributes) + - [images](#images) + - [preset_description](#preset_description) + - [name](#name) + - [opening_hours_by_appointment](#opening_hours_by_appointment) + - [Opening hours](#opening-hours) + - [phone](#phone) + - [email](#email) + - [website](#website) + - [mastodon](#mastodon) + - [facebook](#facebook) + - [item:repair](#itemrepair) + - [leftover-questions](#leftover-questions) + - [move-button](#move-button) + - [delete-button](#delete-button) + - [lod](#lod) + +## Themes using this layer + + - [cyclofix](https://mapcomplete.org/cyclofix) + +## Basic tags for this layer + +Elements must match **all** of the following expressions: + +0. repair=assisted_self_service +1. bicycle:repair=yes | service:bicycle:repair=yes + +[Execute on overpass](http://overpass-turbo.eu/?Q=%5Bout%3Ajson%5D%5Btimeout%3A90%5D%3B%28%20%20%20%20nwr%5B%22repair%22%3D%22assisted_self_service%22%5D%5B%22bicycle%3Arepair%22%3D%22yes%22%5D%28%7B%7Bbbox%7D%7D%29%3B%0A%20%20%20%20nwr%5B%22repair%22%3D%22assisted_self_service%22%5D%5B%22service%3Abicycle%3Arepair%22%3D%22yes%22%5D%28%7B%7Bbbox%7D%7D%29%3B%0A%29%3Bout%20body%3B%3E%3Bout%20skel%20qt%3B) + +## Supported attributes + +**Warning:**,this quick overview is incomplete, + +| attribute | type | values which are supported by this layer | +-----|-----|----- | +| [name](https://wiki.openstreetmap.org/wiki/Key:name) | [string](../SpecialInputElements.md#string) | | +| [opening_hours](https://wiki.openstreetmap.org/wiki/Key:opening_hours) | [opening_hours](../SpecialInputElements.md#opening_hours) | ["by appointment"](https://wiki.openstreetmap.org/wiki/Tag:opening_hours%3D"by appointment") | +| [phone](https://wiki.openstreetmap.org/wiki/Key:phone) | [phone](../SpecialInputElements.md#phone) | | +| [email](https://wiki.openstreetmap.org/wiki/Key:email) | [email](../SpecialInputElements.md#email) | | +| [website](https://wiki.openstreetmap.org/wiki/Key:website) | [url](../SpecialInputElements.md#url) | | +| [contact:mastodon](https://wiki.openstreetmap.org/wiki/Key:contact:mastodon) | [fediverse](../SpecialInputElements.md#fediverse) | | +| [contact:facebook](https://wiki.openstreetmap.org/wiki/Key:contact:facebook) | [url](../SpecialInputElements.md#url) | | + +### images +This block shows the known images which are linked with the `image`-keys, but also via `mapillary` and `wikidata` and shows the button to upload new images +_This tagrendering has no question and is thus read-only_ +*{image_carousel()}{image_upload()}* + +### preset_description + +_This tagrendering has no question and is thus read-only_ +*{preset_description()}* + +### name + +The question is `What is the name of this repair workshop?` +*This workshop is called {name}* is shown if `name` is set + +### opening_hours_by_appointment + +The question is `What are the opening hours of {title()}?` +*

Opening hours

{opening_hours_table(opening_hours)}* is shown if `opening_hours` is set + + - *Only by appointment* is shown if with opening_hours="by appointment" + - *Only by appointment* is shown if with opening_hours~^("by appointment"|by appointment)$. _This option cannot be chosen as answer_ + - *Marked as closed for an unspecified time* is shown if with opening_hours=closed. _This option cannot be chosen as answer_ + +### phone + +The question is `What is the phone number of {title()}?` +*{link(&LBRACEphone&RBRACE,tel:&LBRACEphone&RBRACE,,,,)}* is shown if `phone` is set + + - *{link(&LBRACEcontact:phone&RBRACE,tel:&LBRACEcontact:phone&RBRACE,,,,)}* is shown if with contact:phone~.+. _This option cannot be chosen as answer_ + +This tagrendering has labels +`contact` + +### email + +The question is `What is the email address of {title()}?` +*{email}* is shown if `email` is set + + - *{contact:email}* is shown if with contact:email~.+. _This option cannot be chosen as answer_ + - *{operator:email}* is shown if with operator:email~.+. _This option cannot be chosen as answer_ + +This tagrendering has labels +`contact` + +### website + +The question is `What is the website of {title()}?` +*{website}* is shown if `website` is set + + - *{contact:website}* is shown if with contact:website~.+. _This option cannot be chosen as answer_ + +This tagrendering has labels +`contact` + +### mastodon +Shows and asks for the mastodon handle +The question is `What is the Mastodon-handle of {title()}?` +*{fediverse_link(contact:mastodon)}* is shown if `contact:mastodon` is set + +### facebook +Shows and asks for the facebook handle +The question is `What is the facebook page of of {title()}?` +*{link(Facebook page,&LBRACEcontact:facebook&RBRACE,,,,)}
Facebook is known to harm mental health, manipulate public opinion and cause hate. Try to use healthier alternatives
* is shown if `contact:facebook` is set + +### item:repair + +The question is `What type of items are repaired here?` + + - *Mobile phones are repaired here* is shown if with service:mobile_phone:repair=yes. Unselecting this answer will add service:mobile_phone:repair=no + - *Computers are repaired here* is shown if with service:computer:repair=yes. Unselecting this answer will add service:computer:repair=no + - *Bicycles are repaired here* is shown if with service:bicycle:repair=yes. Unselecting this answer will add service:bicycle:repair=no + - *Electronic devices are repaired here* is shown if with service:electronics:repair=yes. Unselecting this answer will add service:electronics:repair=no + - *Furniture is repaired here* is shown if with service:furniture:repair=yes. Unselecting this answer will add service:furniture:repair=no + - *Clothes are repaired here* is shown if with service:clothes:repair=yes. Unselecting this answer will add service:clothes:repair=no + +### leftover-questions + +_This tagrendering has no question and is thus read-only_ +*{questions( ,)}* + +### move-button + +_This tagrendering has no question and is thus read-only_ +*{move_button()}* + +### delete-button + +_This tagrendering has no question and is thus read-only_ +*{delete_button()}* + +### lod + +_This tagrendering has no question and is thus read-only_ +*{linked_data_from_website()}* + +This tagrendering has labels +`added_by_default` + + +This document is autogenerated from [assets/themes/cyclofix/cyclofix.json](https://github.com/pietervdvn/MapComplete/blob/develop/assets/themes/cyclofix/cyclofix.json) diff --git a/assets/layers/climbing_opportunity/climbing_opportunity.json b/assets/layers/climbing_opportunity/climbing_opportunity.json index 371897325..b25ca2c69 100644 --- a/assets/layers/climbing_opportunity/climbing_opportunity.json +++ b/assets/layers/climbing_opportunity/climbing_opportunity.json @@ -34,6 +34,9 @@ ] } }, + "snapName": { + "en": "a wall, cliff or rock" + }, "minzoom": 18, "title": { "render": { diff --git a/assets/layers/cycleways_and_roads/cycleways_and_roads.json b/assets/layers/cycleways_and_roads/cycleways_and_roads.json index bb126a08b..61337d9a5 100644 --- a/assets/layers/cycleways_and_roads/cycleways_and_roads.json +++ b/assets/layers/cycleways_and_roads/cycleways_and_roads.json @@ -9,6 +9,10 @@ "ca": "Vies ciclistes i carreteres", "cs": "Cyklostezky a silnice" }, + "snapName": { + "en": "a road or a cycleway", + "nl": "een weg, straat of fietspad" + }, "description": { "en": "All infrastructure that someone can cycle over, accompanied with questions about this infrastructure", "nl": "Alle infrastructuur waar je over kunt fietsen, met vragen over die infrastructuur", diff --git a/assets/layers/indoors/indoors.json b/assets/layers/indoors/indoors.json index 7eea28037..abef3fbb7 100644 --- a/assets/layers/indoors/indoors.json +++ b/assets/layers/indoors/indoors.json @@ -8,6 +8,10 @@ "ca": "Interiors", "cs": "Vnitřní prostory" }, + "snapName": { + "en": "an indoor wall", + "nl": "een binnenmuur" + }, "description": { "en": "Basic indoor mapping: shows room outlines", "de": "Grundlegende Innenraumkartierung: zeigt Umrisse von Räumen", diff --git a/assets/layers/kerbs/kerbs.json b/assets/layers/kerbs/kerbs.json index 2b5c4aa19..b10bc4061 100644 --- a/assets/layers/kerbs/kerbs.json +++ b/assets/layers/kerbs/kerbs.json @@ -11,6 +11,9 @@ "ca": "Vroades", "cs": "Obrubníky" }, + "snapName": { + "en": "a kerb" + }, "description": { "en": "A layer showing kerbs.", "nl": "Een laag met stoepranden.", diff --git a/assets/layers/pedestrian_path/pedestrian_path.json b/assets/layers/pedestrian_path/pedestrian_path.json index e1bac0a66..ac8ccef8c 100644 --- a/assets/layers/pedestrian_path/pedestrian_path.json +++ b/assets/layers/pedestrian_path/pedestrian_path.json @@ -8,6 +8,9 @@ "ca": "Camins per a vianants", "cs": "Cesty pro chodce" }, + "snapName": { + "en": "a pedestrian path" + }, "description": { "en": "Pedestrian footpaths, especially used for indoor navigation and snapping entrances to this layer", "nl": "Pad voor voetgangers, in het bijzonder gebruikt voor navigatie binnen gebouwen en om aan toegangen vast te klikken in deze laag", diff --git a/assets/layers/shelter/shelter.json b/assets/layers/shelter/shelter.json index 79cc2fae9..26361dc07 100644 --- a/assets/layers/shelter/shelter.json +++ b/assets/layers/shelter/shelter.json @@ -8,6 +8,9 @@ "fr": "Abri", "cs": "Přístřešek" }, + "snapName": { + "en": "a shelter" + }, "description": { "en": "Layer showing shelter structures", "de": "Eine Ebene, die verschiedene Bauformen von Unterständen zeigt", diff --git a/assets/layers/walls_and_buildings/walls_and_buildings.json b/assets/layers/walls_and_buildings/walls_and_buildings.json index 5cfca96fa..d1e62cbfa 100644 --- a/assets/layers/walls_and_buildings/walls_and_buildings.json +++ b/assets/layers/walls_and_buildings/walls_and_buildings.json @@ -12,6 +12,10 @@ "zh_Hant": "特殊的內建圖層顯示所有牆壁與建築。這個圖層對於規畫要靠牆的東西 (例如 AED、郵筒、入口、地址、監視器等) 相當實用。這個圖層預設顯示而且無法由使用者開關。", "pl": "Specjalna warstwa zabudowana zapewniająca wszystkie mury i budynki. Warstwa ta jest przydatna w ustawieniach wstępnych obiektów, które można umieścić przy ścianach (np. AED, skrzynki pocztowe, wejścia, adresy, kamery monitorujące itp.). Warstwa ta jest domyślnie niewidoczna i użytkownik nie może jej przełączać." }, + "snapName": { + "en": "a wall or building", + "nl": "een muur of gebouw" + }, "source": { "osmTags": { "or": [ diff --git a/assets/svg/license_info.json b/assets/svg/license_info.json index c15cd4df8..9a6714190 100644 --- a/assets/svg/license_info.json +++ b/assets/svg/license_info.json @@ -1065,6 +1065,14 @@ "https://phabricator.wikimedia.org/diffusion/GOJU/browse/master/AUTHORS.txt" ] }, + { + "path": "snap.svg", + "license": "CC0-1.0", + "authors": [ + "Pieter Vander Vennet" + ], + "sources": [] + }, { "path": "speech_bubble.svg", "license": "CC-BY-4.0", @@ -1203,6 +1211,14 @@ ], "sources": [] }, + { + "path": "unsnap.svg", + "license": "CC0-1.0", + "authors": [ + "Pieter Vander Vennet" + ], + "sources": [] + }, { "path": "wikidata.svg", "license": "LOGO", diff --git a/assets/svg/snap.svg b/assets/svg/snap.svg new file mode 100644 index 000000000..ed4b40d12 --- /dev/null +++ b/assets/svg/snap.svg @@ -0,0 +1,84 @@ + + + + diff --git a/assets/svg/snap.svg.license b/assets/svg/snap.svg.license new file mode 100644 index 000000000..ed0288300 --- /dev/null +++ b/assets/svg/snap.svg.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Pieter Vander Vennet +SPDX-License-Identifier: CC0-1.0 \ No newline at end of file diff --git a/assets/svg/unsnap.svg b/assets/svg/unsnap.svg new file mode 100644 index 000000000..c35760744 --- /dev/null +++ b/assets/svg/unsnap.svg @@ -0,0 +1,83 @@ + + + + diff --git a/assets/svg/unsnap.svg.license b/assets/svg/unsnap.svg.license new file mode 100644 index 000000000..2452bee1e --- /dev/null +++ b/assets/svg/unsnap.svg.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Pieter Vander Vennet +SPDX-License-Identifier: CC0 \ No newline at end of file diff --git a/assets/themes/mapcomplete-changes/mapcomplete-changes.json b/assets/themes/mapcomplete-changes/mapcomplete-changes.json index ac8e738f6..7873f6b66 100644 --- a/assets/themes/mapcomplete-changes/mapcomplete-changes.json +++ b/assets/themes/mapcomplete-changes/mapcomplete-changes.json @@ -1,16 +1,13 @@ { "id": "mapcomplete-changes", "title": { - "en": "Changes made with MapComplete", - "de": "Änderungen mit MapComplete vorgenommen" - }, - "description": { - "en": "This maps shows all the changes made with MapComplete", - "de": "Diese Karte zeigt alle mit MapComplete vorgenommenen Änderungen" + "en": "Changes made with MapComplete" }, "shortDescription": { - "en": "Shows changes made by MapComplete", - "de": "Änderungen von MapComplete anzeigen" + "en": "Shows changes made by MapComplete" + }, + "description": { + "en": "This maps shows all the changes made with MapComplete" }, "icon": "./assets/svg/logo.svg", "hideFromOverview": true, @@ -21,8 +18,7 @@ { "id": "mapcomplete-changes", "name": { - "en": "Changeset centers", - "de": "Zentrum der Änderungssätze" + "en": "Changeset centers" }, "minzoom": 0, "source": { @@ -32,48 +28,41 @@ }, "title": { "render": { - "en": "Changeset for {theme}", - "de": "Änderungssatz für {theme}" + "en": "Changeset for {theme}" } }, "description": { - "en": "Shows all MapComplete changes", - "de": "Zeigt alle MapComplete-Änderungen" + "en": "Shows all MapComplete changes" }, "tagRenderings": [ { "id": "show_changeset_id", "render": { - "en": "Changeset {id}", - "de": "Änderungssatz {id}" + "en": "Changeset {id}" } }, { "id": "contributor", "question": { - "en": "What contributor did make this change?", - "de": "Wer hat diese Änderung vorgenommen?" + "en": "What contributor did make this change?" }, "freeform": { "key": "user" }, "render": { - "en": "Change made by {user}", - "de": "Änderung von {user}" + "en": "Change made by {user}" } }, { "id": "theme-id", "question": { - "en": "What theme was used to make this change?", - "de": "Welches Thema wurde für die Änderung verwendet?" + "en": "What theme was used to make this change?" }, "freeform": { "key": "theme" }, "render": { - "en": "Change with theme {theme}", - "de": "Änderung mit Thema {theme}" + "en": "Change with theme {theme}" } }, { @@ -82,23 +71,19 @@ "key": "locale" }, "question": { - "en": "What locale (language) was this change made in?", - "de": "In welcher Benutzersprache wurde die Änderung vorgenommen?" + "en": "What locale (language) was this change made in?" }, "render": { - "en": "User locale is {locale}", - "de": "Benutzersprache ist {locale}" + "en": "User locale is {locale}" } }, { "id": "host", "render": { - "en": "Change with with {host}", - "de": "Änderung mit {host}" + "en": "Change with with {host}" }, "question": { - "en": "What host (website) was this change made with?", - "de": "Mit welchem Host (Website) wurde diese Änderung vorgenommen?" + "en": "What host (website) was this change made with?" }, "freeform": { "key": "host" @@ -119,12 +104,10 @@ { "id": "version", "question": { - "en": "What version of MapComplete was used to make this change?", - "de": "Welche Version von MapComplete wurde für diese Änderung verwendet?" + "en": "What version of MapComplete was used to make this change?" }, "render": { - "en": "Made with {editor}", - "de": "Erstellt mit {editor}" + "en": "Made with {editor}" }, "freeform": { "key": "editor" @@ -522,8 +505,7 @@ } ], "question": { - "en": "Themename contains {search}", - "de": "Themename enthält {search}" + "en": "Themename contains {search}" } } ] @@ -539,8 +521,7 @@ } ], "question": { - "en": "Themename does not contain {search}", - "de": "Themenname enthält nicht {search}" + "en": "Themename does not contain {search}" } } ] @@ -556,8 +537,7 @@ } ], "question": { - "en": "Made by contributor {search}", - "de": "Der Name enthält nicht {search}" + "en": "Made by contributor {search}" } } ] @@ -573,8 +553,7 @@ } ], "question": { - "en": "Not made by contributor {search}", - "de": "Nicht erstellt von Mitwirkendem {search}" + "en": "Not made by contributor {search}" } } ] @@ -591,8 +570,7 @@ } ], "question": { - "en": "Made before {search}", - "de": "Erstellt nach {search}" + "en": "Made before {search}" } } ] @@ -609,8 +587,7 @@ } ], "question": { - "en": "Made after {search}", - "de": "Erstellt nach {search}" + "en": "Made after {search}" } } ] @@ -626,8 +603,7 @@ } ], "question": { - "en": "User language (iso-code) {search}", - "de": "Benutzersprache (ISO-Code) {search}" + "en": "User language (iso-code) {search}" } } ] @@ -643,8 +619,7 @@ } ], "question": { - "en": "Made with host {search}", - "de": "Erstellt mit Host {search}" + "en": "Made with host {search}" } } ] @@ -655,8 +630,7 @@ { "osmTags": "add-image>0", "question": { - "en": "Changeset added at least one image", - "de": "Änderungssatz fügte mindestens ein Bild hinzu" + "en": "Changeset added at least one image" } } ] @@ -667,8 +641,7 @@ { "osmTags": "theme!=grb", "question": { - "en": "Exclude GRB theme", - "de": "GRB-Thema ausschließen" + "en": "Exclude GRB theme" } } ] @@ -679,8 +652,7 @@ { "osmTags": "theme!=etymology", "question": { - "en": "Exclude etymology theme", - "de": "Etymologie-Thema ausschließen" + "en": "Exclude etymology theme" } } ] @@ -695,8 +667,7 @@ { "id": "link_to_more", "render": { - "en": "More statistics can be found here", - "de": "Weitere Statistiken findest du hier" + "en": "More statistics can be found here" } }, { @@ -730,4 +701,4 @@ } } ] -} +} \ No newline at end of file diff --git a/assets/themes/postal_codes/postal_codes.json b/assets/themes/postal_codes/postal_codes.json index 2cfbeda0f..5d61e4b37 100644 --- a/assets/themes/postal_codes/postal_codes.json +++ b/assets/themes/postal_codes/postal_codes.json @@ -166,7 +166,6 @@ } ], "allowMove": false - }, { "id": "town_hall", diff --git a/assets/themes/street_lighting/street_lighting.json b/assets/themes/street_lighting/street_lighting.json index 970246e67..b75266575 100644 --- a/assets/themes/street_lighting/street_lighting.json +++ b/assets/themes/street_lighting/street_lighting.json @@ -370,7 +370,6 @@ } ], "allowMove": false - } ] } diff --git a/assets/themes/uk_addresses/uk_addresses.json b/assets/themes/uk_addresses/uk_addresses.json index 52ea31313..85959a8e2 100644 --- a/assets/themes/uk_addresses/uk_addresses.json +++ b/assets/themes/uk_addresses/uk_addresses.json @@ -686,7 +686,6 @@ "enableImproveAccuraccy": true, "enableRelocation": false } - }, "named_streets" ], diff --git a/langs/en.json b/langs/en.json index 12d3fe147..1b3afef9e 100644 --- a/langs/en.json +++ b/langs/en.json @@ -643,7 +643,8 @@ "pointIsMoved": "The point has been moved", "reasons": { "reasonInaccurate": "The location is inaccurate by a few meter", - "reasonRelocation": "The object has been relocated to a totally different location" + "reasonRelocation": "The object has been relocated to a totally different location", + "reasonSnapTo": "This should be snapped onto {name}" }, "selectReason": "Why do you move this object?", "whyMove": "Why do you want to move this point?", diff --git a/langs/layers/en.json b/langs/layers/en.json index 20fb21f13..a985eba4e 100644 --- a/langs/layers/en.json +++ b/langs/layers/en.json @@ -12002,6 +12002,7 @@ }, "walls_and_buildings": { "description": "Special builtin layer providing all walls and buildings. This layer is useful in presets for objects which can be placed against walls (e.g. AEDs, postboxes, entrances, addresses, surveillance cameras, …). This layer is invisible by default and not toggleable by the user.", + "snapName": "a wall or building", "tagRenderings": { "entrance_info": { "mappings": { diff --git a/langs/layers/nl.json b/langs/layers/nl.json index b7534c17a..59d6c7fda 100644 --- a/langs/layers/nl.json +++ b/langs/layers/nl.json @@ -9671,6 +9671,7 @@ }, "walls_and_buildings": { "description": "Speciale ingebouwde laag voor alle muren en gebouwen. Deze laag is nuttig in voorkeuzen voor objecten die tegen muren geplaatst kunnen worden (bv. AEDs, brievenbussen, ingangen, adressen, beveiligingscamera's,…). Deze laag is standaard onzichtbaar en niet in te schakelen door de gebruiker.", + "snapName": "een muur of gebouw", "tagRenderings": { "entrance_info": { "mappings": { diff --git a/src/Logic/Osm/Actions/ChangeLocationAction.ts b/src/Logic/Osm/Actions/ChangeLocationAction.ts index 9c774b839..85b6a34b1 100644 --- a/src/Logic/Osm/Actions/ChangeLocationAction.ts +++ b/src/Logic/Osm/Actions/ChangeLocationAction.ts @@ -1,10 +1,15 @@ import { ChangeDescription } from "./ChangeDescription" import OsmChangeAction from "./OsmChangeAction" +import { WayId } from "../../../Models/OsmFeature" +import InsertPointIntoWayAction from "./InsertPointIntoWayAction" +import { SpecialVisualizationState } from "../../../UI/SpecialVisualization" export default class ChangeLocationAction extends OsmChangeAction { private readonly _id: number private readonly _newLonLat: [number, number] private readonly _meta: { theme: string; reason: string } + private readonly state: SpecialVisualizationState + private snapTo: WayId | undefined static metatags: { readonly key?: string readonly value?: string @@ -21,28 +26,30 @@ export default class ChangeLocationAction extends OsmChangeAction { ] constructor( + state: SpecialVisualizationState, id: string, newLonLat: [number, number], + snapTo: WayId | undefined, meta: { theme: string reason: string - } + }, ) { super(id, true) + this.state = state if (!id.startsWith("node/")) { throw "Invalid ID: only 'node/number' is accepted" } this._id = Number(id.substring("node/".length)) this._newLonLat = newLonLat + this.snapTo = snapTo this._meta = meta } protected async CreateChangeDescriptions(): Promise { + const [lon, lat] = this._newLonLat const d: ChangeDescription = { - changes: { - lat: this._newLonLat[1], - lon: this._newLonLat[0], - }, + changes: { lon, lat }, type: "node", id: this._id, meta: { @@ -51,7 +58,21 @@ export default class ChangeLocationAction extends OsmChangeAction { specialMotivation: this._meta.reason, }, } + if (!this.snapTo) { + return [d] + } + const snapToWay = await this.state.osmObjectDownloader.DownloadObjectAsync(this.snapTo, 0) + if (snapToWay === "deleted") { + return [d] + } - return [d] + const insertIntoWay = new InsertPointIntoWayAction( + lat, lon, this._id, snapToWay, { + allowReuseOfPreviouslyCreatedPoints: false, + reusePointWithinMeters: 0.25, + }, + ).prepareChangeDescription() + + return [d, { ...insertIntoWay, meta: d.meta }] } } diff --git a/src/Logic/Osm/Actions/CreateNewNodeAction.ts b/src/Logic/Osm/Actions/CreateNewNodeAction.ts index 251a9413a..a935575d2 100644 --- a/src/Logic/Osm/Actions/CreateNewNodeAction.ts +++ b/src/Logic/Osm/Actions/CreateNewNodeAction.ts @@ -5,6 +5,7 @@ import { ChangeDescription } from "./ChangeDescription" import { And } from "../../Tags/And" import { OsmWay } from "../OsmObject" import { GeoOperations } from "../../GeoOperations" +import InsertPointIntoWayAction from "./InsertPointIntoWayAction" export default class CreateNewNodeAction extends OsmCreateAction { /** @@ -37,7 +38,7 @@ export default class CreateNewNodeAction extends OsmCreateAction { theme: string changeType: "create" | "import" | null specialMotivation?: string - } + }, ) { super(null, basicTags !== undefined && basicTags.length > 0) this._basicTags = basicTags @@ -101,72 +102,20 @@ export default class CreateNewNodeAction extends OsmCreateAction { return [newPointChange] } - // Project the point onto the way - console.log("Snapping a node onto an existing way...") - const geojson = this._snapOnto.asGeoJson() - const projected = GeoOperations.nearestPoint(GeoOperations.outerRing(geojson), [ - this._lon, + const change = new InsertPointIntoWayAction( this._lat, - ]) - const projectedCoor = <[number, number]>projected.geometry.coordinates - const index = projected.properties.index - console.log("Attempting to snap:", { geojson, projected, projectedCoor, index }) - // We check that it isn't close to an already existing point - let reusedPointId = undefined - let reusedPointCoordinates: [number, number] = undefined - let outerring: [number, number][] + this._lon, + id, + this._snapOnto, + { + reusePointWithinMeters: this._reusePointDistance, + allowReuseOfPreviouslyCreatedPoints: this._reusePreviouslyCreatedPoint, + }, + ).prepareChangeDescription() - if (geojson.geometry.type === "LineString") { - outerring = <[number, number][]>geojson.geometry.coordinates - } else if (geojson.geometry.type === "Polygon") { - outerring = <[number, number][]>geojson.geometry.coordinates[0] - } - - const prev = outerring[index] - if (GeoOperations.distanceBetween(prev, projectedCoor) < this._reusePointDistance) { - // We reuse this point instead! - reusedPointId = this._snapOnto.nodes[index] - reusedPointCoordinates = this._snapOnto.coordinates[index] - } - const next = outerring[index + 1] - if (GeoOperations.distanceBetween(next, projectedCoor) < this._reusePointDistance) { - // We reuse this point instead! - reusedPointId = this._snapOnto.nodes[index + 1] - reusedPointCoordinates = this._snapOnto.coordinates[index + 1] - } - if (reusedPointId !== undefined) { - this.setElementId(reusedPointId) - return [ - { - tags: new And(this._basicTags).asChange(properties), - type: "node", - id: reusedPointId, - meta: this.meta, - changes: { lat: reusedPointCoordinates[0], lon: reusedPointCoordinates[1] }, - }, - ] - } - - const locations = [ - ...this._snapOnto.coordinates?.map(([lat, lon]) => <[number, number]>[lon, lat]), - ] - const ids = [...this._snapOnto.nodes] - - locations.splice(index + 1, 0, [this._lon, this._lat]) - ids.splice(index + 1, 0, id) - - // Allright, we have to insert a new point in the way return [ newPointChange, - { - type: "way", - id: this._snapOnto.id, - changes: { - coordinates: locations, - nodes: ids, - }, - meta: this.meta, - }, + { ...change, meta: this.meta }, ] } diff --git a/src/Logic/Osm/Actions/InsertPointIntoWayAction.ts b/src/Logic/Osm/Actions/InsertPointIntoWayAction.ts new file mode 100644 index 000000000..fb013e56e --- /dev/null +++ b/src/Logic/Osm/Actions/InsertPointIntoWayAction.ts @@ -0,0 +1,96 @@ +import { ChangeDescription } from "./ChangeDescription" +import { GeoOperations } from "../../GeoOperations" +import { OsmWay } from "../OsmObject" + +export default class InsertPointIntoWayAction { + private readonly _lat: number + private readonly _lon: number + private readonly _idToInsert: number + private readonly _snapOnto: OsmWay + private readonly _options: { + allowReuseOfPreviouslyCreatedPoints?: boolean + reusePointWithinMeters?: number + } + + constructor( + lat: number, + lon: number, + idToInsert: number, + snapOnto: OsmWay, + options: { + allowReuseOfPreviouslyCreatedPoints?: boolean + reusePointWithinMeters?: number + } + ){ + this._lat = lat + this._lon = lon + this._idToInsert = idToInsert + this._snapOnto = snapOnto + this._options = options + + } + + /** + * Tries to create the changedescription of the way where the point is inserted + * Returns `undefined` if inserting failed + */ + public prepareChangeDescription(): Omit | undefined { + + + // Project the point onto the way + console.log("Snapping a node onto an existing way...") + const geojson = this._snapOnto.asGeoJson() + const projected = GeoOperations.nearestPoint(GeoOperations.outerRing(geojson), [ + this._lon, + this._lat, + ]) + const projectedCoor = <[number, number]>projected.geometry.coordinates + const index = projected.properties.index + console.log("Attempting to snap:", { geojson, projected, projectedCoor, index }) + // We check that it isn't close to an already existing point + let reusedPointId = undefined + let reusedPointCoordinates: [number, number] = undefined + let outerring: [number, number][] + + if (geojson.geometry.type === "LineString") { + outerring = <[number, number][]>geojson.geometry.coordinates + } else if (geojson.geometry.type === "Polygon") { + outerring = <[number, number][]>geojson.geometry.coordinates[0] + } + + const prev = outerring[index] + if (GeoOperations.distanceBetween(prev, projectedCoor) < this._options.reusePointWithinMeters) { + // We reuse this point instead! + reusedPointId = this._snapOnto.nodes[index] + reusedPointCoordinates = this._snapOnto.coordinates[index] + } + const next = outerring[index + 1] + if (GeoOperations.distanceBetween(next, projectedCoor) < this._options.reusePointWithinMeters) { + // We reuse this point instead! + reusedPointId = this._snapOnto.nodes[index + 1] + reusedPointCoordinates = this._snapOnto.coordinates[index + 1] + } + if (reusedPointId !== undefined) { + return undefined + } + + const locations = [ + ...this._snapOnto.coordinates?.map(([lat, lon]) => <[number, number]>[lon, lat]), + ] + const ids = [...this._snapOnto.nodes] + + locations.splice(index + 1, 0, [this._lon, this._lat]) + ids.splice(index + 1, 0, this._idToInsert) + + return { + type: "way", + id: this._snapOnto.id, + changes: { + coordinates: locations, + nodes: ids, + } + } + + } + +} diff --git a/src/Models/ThemeConfig/Conversion/PrepareTheme.ts b/src/Models/ThemeConfig/Conversion/PrepareTheme.ts index 4a14b1aa4..3ff4268c5 100644 --- a/src/Models/ThemeConfig/Conversion/PrepareTheme.ts +++ b/src/Models/ThemeConfig/Conversion/PrepareTheme.ts @@ -30,7 +30,7 @@ class SubstituteLayer extends Conversion 0 ) { context.err( - `When overriding a layer, an override is not allowed to override into tagRenderings. Use "+tagRenderings" or "tagRenderings+" instead to prepend or append some questions.` + `When overriding a layer, an override is not allowed to override into tagRenderings. Use "+tagRenderings" or "tagRenderings+" instead to prepend or append some questions.`, ) } try { const trPlus = json["override"]["tagRenderings+"] if (trPlus) { let index = found.tagRenderings.findIndex( - (tr) => tr["id"] === "leftover-questions" + (tr) => tr["id"] === "leftover-questions", ) if (index < 0) { index = found.tagRenderings.length @@ -107,8 +107,8 @@ class SubstituteLayer extends Conversion 0) { context.err( "This theme specifies that certain tagrenderings have to be removed based on forbidden layers. One or more of these layers did not match any tagRenderings and caused no deletions: " + - unused.join(", ") + - "\n This means that this label can be removed or that the original tagRendering that should be deleted does not have this label anymore" + unused.join(", ") + + "\n This means that this label can be removed or that the original tagRendering that should be deleted does not have this label anymore", ) } found.tagRenderings = filtered @@ -184,7 +184,7 @@ class AddDefaultLayers extends DesugaringStep { super( "Adds the default layers, namely: " + Constants.added_by_default.join(", "), ["layers"], - "AddDefaultLayers" + "AddDefaultLayers", ) this._state = state } @@ -207,10 +207,10 @@ class AddDefaultLayers extends DesugaringStep { if (alreadyLoaded.has(v.id)) { context.warn( "Layout " + - context + - " already has a layer with name " + - v.id + - "; skipping inclusion of this builtin layer" + context + + " already has a layer with name " + + v.id + + "; skipping inclusion of this builtin layer", ) continue } @@ -226,14 +226,14 @@ class AddImportLayers extends DesugaringStep { super( "For every layer in the 'layers'-list, create a new layer which'll import notes. (Note that priviliged layers and layers which have a geojson-source set are ignored)", ["layers"], - "AddImportLayers" + "AddImportLayers", ) } convert(json: LayoutConfigJson, context: ConversionContext): LayoutConfigJson { if (!(json.enableNoteImports ?? true)) { context.info( - "Not creating a note import layers for theme " + json.id + " as they are disabled" + "Not creating a note import layers for theme " + json.id + " as they are disabled", ) return json } @@ -268,7 +268,7 @@ class AddImportLayers extends DesugaringStep { try { const importLayerResult = creator.convert( layer, - context.inOperation(this.name).enter(i1) + context.inOperation(this.name).enter(i1), ) if (importLayerResult !== undefined) { json.layers.push(importLayerResult) @@ -288,7 +288,7 @@ class AddContextToTranslationsInLayout extends DesugaringStep super( "Adds context to translations, including the prefix 'themes:json.id'; this is to make sure terms in an 'overrides' or inline layer are linkable too", ["_context"], - "AddContextToTranlationsInLayout" + "AddContextToTranlationsInLayout", ) } @@ -297,7 +297,7 @@ class AddContextToTranslationsInLayout extends DesugaringStep // 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"]) + ConversionContext.construct([json.id], ["AddContextToTranslation"]), ) } } @@ -307,7 +307,7 @@ class ApplyOverrideAll extends DesugaringStep { super( "Applies 'overrideAll' onto every 'layer'. The 'overrideAll'-field is removed afterwards", ["overrideAll", "layers"], - "ApplyOverrideAll" + "ApplyOverrideAll", ) } @@ -336,7 +336,7 @@ class ApplyOverrideAll extends DesugaringStep { layer.tagRenderings = tagRenderingsPlus } else { let index = layer.tagRenderings.findIndex( - (tr) => tr["id"] === "leftover-questions" + (tr) => tr["id"] === "leftover-questions", ) if (index < 0) { index = layer.tagRenderings.length - 1 @@ -357,14 +357,9 @@ class AddDependencyLayersToTheme extends DesugaringStep { constructor(state: DesugaringContext) { super( - `If a layer has a dependency on another layer, these layers are added automatically on the theme. (For example: defibrillator depends on 'walls_and_buildings' to snap onto. This layer is added automatically) - - Note that these layers are added _at the start_ of the layer list, meaning that they will see _every_ feature. - Furthermore, \`passAllFeatures\` will be set, so that they won't steal away features from further layers. - Some layers (e.g. \`all_buildings_and_walls\' or \'streets_with_a_name\') are invisible, so by default, \'force_load\' is set too. - `, + `If a layer has a dependency on another layer, these layers are added automatically on the theme. (For example: defibrillator depends on 'walls_and_buildings' to snap onto. This layer is added automatically)`, ["layers"], - "AddDependencyLayersToTheme" + "AddDependencyLayersToTheme", ) this._state = state } @@ -373,7 +368,7 @@ class AddDependencyLayersToTheme extends DesugaringStep { alreadyLoaded: LayerConfigJson[], allKnownLayers: Map, themeId: string, - context: ConversionContext + context: ConversionContext, ): { config: LayerConfigJson; reason: string }[] { const dependenciesToAdd: { config: LayerConfigJson; reason: string }[] = [] const loadedLayerIds: Set = new Set(alreadyLoaded.map((l) => l?.id)) @@ -391,12 +386,13 @@ class AddDependencyLayersToTheme extends DesugaringStep { reason: string context?: string neededBy: string + checkHasSnapName: boolean }[] = [] for (const layerConfig of alreadyLoaded) { try { const layerDeps = DependencyCalculator.getLayerDependencies( - new LayerConfig(layerConfig, themeId + "(dependencies)") + new LayerConfig(layerConfig, themeId + "(dependencies)"), ) dependencies.push(...layerDeps) } catch (e) { @@ -413,7 +409,11 @@ class AddDependencyLayersToTheme extends DesugaringStep { for (const dependency of dependencies) { if (loadedLayerIds.has(dependency.neededLayer)) { // We mark the needed layer as 'mustLoad' - alreadyLoaded.find((l) => l.id === dependency.neededLayer).forceLoad = true + const loadedLayer = alreadyLoaded.find((l) => l.id === dependency.neededLayer) + loadedLayer.forceLoad = true + if(dependency.checkHasSnapName && !loadedLayer.snapName){ + context.enters("layer dependency").err("Layer "+dependency.neededLayer+" is loaded because "+dependency.reason+"; so it must specify a `snapName`. This is used in the sentence `move this point to snap it to {snapName}`") + } } } @@ -436,10 +436,10 @@ class AddDependencyLayersToTheme extends DesugaringStep { if (dep === undefined) { const message = [ "Loading a dependency failed: layer " + - unmetDependency.neededLayer + - " is not found, neither as layer of " + - themeId + - " nor as builtin layer.", + unmetDependency.neededLayer + + " is not found, neither as layer of " + + themeId + + " nor as builtin layer.", reason, "Loaded layers are: " + alreadyLoaded.map((l) => l.id).join(","), ] @@ -455,11 +455,12 @@ class AddDependencyLayersToTheme extends DesugaringStep { }) loadedLayerIds.add(dep.id) unmetDependencies = unmetDependencies.filter( - (d) => d.neededLayer !== unmetDependency.neededLayer + (d) => d.neededLayer !== unmetDependency.neededLayer, ) } } while (unmetDependencies.length > 0) + return dependenciesToAdd } @@ -477,12 +478,12 @@ class AddDependencyLayersToTheme extends DesugaringStep { layers, allKnownLayers, theme.id, - context + context, ) if (dependencies.length > 0) { for (const dependency of dependencies) { context.info( - "Added " + dependency.config.id + " to the theme. " + dependency.reason + "Added " + dependency.config.id + " to the theme. " + dependency.reason, ) } } @@ -530,7 +531,7 @@ class WarnForUnsubstitutedLayersInTheme extends DesugaringStep super( "Generates a warning if a theme uses an unsubstituted layer", ["layers"], - "WarnForUnsubstitutedLayersInTheme" + "WarnForUnsubstitutedLayersInTheme", ) } @@ -542,7 +543,7 @@ class WarnForUnsubstitutedLayersInTheme extends DesugaringStep context .enter("layers") .err( - "No layers are defined. You must define at least one layer to have a valid theme" + "No layers are defined. You must define at least one layer to have a valid theme", ) return json } @@ -566,10 +567,10 @@ class WarnForUnsubstitutedLayersInTheme extends DesugaringStep context.warn( "The theme " + - json.id + - " has an inline layer: " + - layer["id"] + - ". This is discouraged." + json.id + + " has an inline layer: " + + layer["id"] + + ". This is discouraged.", ) } return json @@ -578,6 +579,7 @@ class WarnForUnsubstitutedLayersInTheme extends DesugaringStep class PostvalidateTheme extends DesugaringStep { private readonly _state: DesugaringContext + constructor(state: DesugaringContext) { super("Various validation steps when everything is done", [], "PostvalidateTheme") this._state = state @@ -596,13 +598,13 @@ class PostvalidateTheme extends DesugaringStep { } const sameBasedOn = ( json.layers.filter( - (l) => l["_basedOn"] === layer["_basedOn"] && l["id"] !== layer.id + (l) => l["_basedOn"] === layer["_basedOn"] && l["id"] !== layer.id, ) ) const minZoomAll = Math.min(...sameBasedOn.map((sbo) => sbo.minzoom)) const sameNameDetected = sameBasedOn.some( - (same) => JSON.stringify(layer["name"]) === JSON.stringify(same["name"]) + (same) => JSON.stringify(layer["name"]) === JSON.stringify(same["name"]), ) if (!sameNameDetected) { // The name is unique, so it'll won't be confusing @@ -611,12 +613,12 @@ class PostvalidateTheme extends DesugaringStep { if (minZoomAll < layer.minzoom) { context.err( "There are multiple layers based on " + - basedOn + - ". The layer with id " + - layer.id + - " has a minzoom of " + - layer.minzoom + - ", and has a name set. Another similar layer has a lower minzoom. As such, the layer selection might show 'zoom in to see features' even though some of the features are already visible. Set `\"name\": null` for this layer and eventually remove the 'name':null for the other layer." + basedOn + + ". The layer with id " + + layer.id + + " has a minzoom of " + + layer.minzoom + + ", and has a name set. Another similar layer has a lower minzoom. As such, the layer selection might show 'zoom in to see features' even though some of the features are already visible. Set `\"name\": null` for this layer and eventually remove the 'name':null for the other layer.", ) } } @@ -636,17 +638,17 @@ class PostvalidateTheme extends DesugaringStep { const closeLayers = Utils.sortedByLevenshteinDistance( sameAs, json.layers, - (l) => l["id"] + (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(", ") + 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(", "), ) } } @@ -654,6 +656,7 @@ class PostvalidateTheme extends DesugaringStep { return json } } + export class PrepareTheme extends Fuse { private state: DesugaringContext @@ -661,7 +664,7 @@ export class PrepareTheme extends Fuse { state: DesugaringContext, options?: { skipDefaultLayers: false | boolean - } + }, ) { super( "Fully prepares and expands a theme", @@ -683,7 +686,7 @@ export class PrepareTheme extends Fuse { : new AddDefaultLayers(state), new AddDependencyLayersToTheme(state), new AddImportLayers(), - new PostvalidateTheme(state) + new PostvalidateTheme(state), ) this.state = state } @@ -698,13 +701,13 @@ export class PrepareTheme extends Fuse { const needsNodeDatabase = result.layers?.some((l: LayerConfigJson) => l.tagRenderings?.some((tr) => ValidationUtils.getSpecialVisualisations(tr)?.some( - (special) => special.needsNodeDatabase - ) - ) + (special) => special.needsNodeDatabase, + ), + ), ) if (needsNodeDatabase) { context.info( - "Setting 'enableNodeDatabase' as this theme uses a special visualisation which needs to keep track of _all_ nodes" + "Setting 'enableNodeDatabase' as this theme uses a special visualisation which needs to keep track of _all_ nodes", ) result.enableNodeDatabase = true } diff --git a/src/Models/ThemeConfig/DependencyCalculator.ts b/src/Models/ThemeConfig/DependencyCalculator.ts index 0b2b814c9..66fa129f5 100644 --- a/src/Models/ThemeConfig/DependencyCalculator.ts +++ b/src/Models/ThemeConfig/DependencyCalculator.ts @@ -33,8 +33,8 @@ export default class DependencyCalculator { */ public static getLayerDependencies( layer: LayerConfig - ): { neededLayer: string; reason: string; context?: string; neededBy: string }[] { - const deps: { neededLayer: string; reason: string; context?: string; neededBy: string }[] = + ): { neededLayer: string; reason: string; context?: string; neededBy: string, checkHasSnapName: boolean }[] { + const deps: { neededLayer: string; reason: string; context?: string; neededBy: string, checkHasSnapName: boolean }[] = [] for (let i = 0; layer.presets !== undefined && i < layer.presets.length; i++) { @@ -51,6 +51,7 @@ export default class DependencyCalculator { reason: `preset \`${preset.title.textFor("en")}\` snaps to this layer`, context: `${layer.id}.presets[${i}]`, neededBy: layer.id, + checkHasSnapName: true }) }) } @@ -62,6 +63,7 @@ export default class DependencyCalculator { reason: "a tagrendering needs this layer", context: tr.id, neededBy: layer.id, + checkHasSnapName: false }) } } @@ -97,6 +99,7 @@ export default class DependencyCalculator { "] which calculates the value for " + currentKey, neededBy: layer.id, + checkHasSnapName: false }) return [] diff --git a/src/Models/ThemeConfig/Json/LayerConfigJson.ts b/src/Models/ThemeConfig/Json/LayerConfigJson.ts index e7df9a562..c645e1608 100644 --- a/src/Models/ThemeConfig/Json/LayerConfigJson.ts +++ b/src/Models/ThemeConfig/Json/LayerConfigJson.ts @@ -579,4 +579,13 @@ export interface LayerConfigJson { * iftrue: Do not write 'change_within_x_m' and do not indicate that this was done by survey */ enableMorePrivacy?: boolean + + /** + * question: When a feature is snapped to this name, how should this item be called? + * + * In the move wizard, the option `snap object onto {snapName}` is shown + * + * group: hidden + */ + snapName?: Translatable } diff --git a/src/Models/ThemeConfig/LayerConfig.ts b/src/Models/ThemeConfig/LayerConfig.ts index c73c4c8ab..c712ae09f 100644 --- a/src/Models/ThemeConfig/LayerConfig.ts +++ b/src/Models/ThemeConfig/LayerConfig.ts @@ -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(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( 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 { 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-=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-=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 { "", "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): 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] + } } diff --git a/src/UI/BigComponents/NewPointLocationInput.svelte b/src/UI/BigComponents/NewPointLocationInput.svelte index 0ba608143..f677841f1 100644 --- a/src/UI/BigComponents/NewPointLocationInput.svelte +++ b/src/UI/BigComponents/NewPointLocationInput.svelte @@ -18,6 +18,7 @@ import StaticFeatureSource from "../../Logic/FeatureSource/Sources/StaticFeatureSource" import { Tag } from "../../Logic/Tags/Tag" import { TagUtils } from "../../Logic/Tags/TagUtils" + import type { WayId } from "../../Models/OsmFeature" /** * An advanced location input, which has support to: @@ -45,11 +46,16 @@ } export let snapToLayers: string[] | undefined = undefined export let targetLayer: LayerConfig | undefined = undefined + /** + * If a 'targetLayer' is given, objects of this layer will be shown as well to avoid duplicates + * If you want to hide some of them, blacklist them here + */ + export let dontShow: string[] = [] export let maxSnapDistance: number = undefined export let presetProperties: Tag[] = [] let presetPropertiesUnpacked = TagUtils.KVtoProperties(presetProperties) - export let snappedTo: UIEventSource + export let snappedTo: UIEventSource let preciseLocation: UIEventSource<{ lon: number; lat: number }> = new UIEventSource<{ lon: number @@ -57,7 +63,7 @@ }>(undefined) const map: UIEventSource = new UIEventSource(undefined) - let initialMapProperties: Partial & { location } = { + export let mapProperties: Partial & { location } = { zoom: new UIEventSource(19), maxbounds: new UIEventSource(undefined), /*If no snapping needed: the value is simply the map location; @@ -77,8 +83,11 @@ if (targetLayer) { // Show already existing items - const featuresForLayer = state.perLayer.get(targetLayer.id) + let featuresForLayer: FeatureSource = state.perLayer.get(targetLayer.id) if (featuresForLayer) { + if (dontShow) { + featuresForLayer = new StaticFeatureSource(featuresForLayer.features.map(feats => feats.filter(f => dontShow.indexOf(f.properties.id) < 0))) + } new ShowDataLayer(map, { layer: targetLayer, features: featuresForLayer, @@ -104,13 +113,13 @@ const snappedLocation = new SnappingFeatureSource( new FeatureSourceMerger(...Utils.NoNull(snapSources)), // We snap to the (constantly updating) map location - initialMapProperties.location, + mapProperties.location, { maxDistance: maxSnapDistance ?? 15, allowUnsnapped: true, snappedTo, snapLocation: value, - } + }, ) const withCorrectedAttributes = new StaticFeatureSource( snappedLocation.features.mapD((feats) => @@ -124,8 +133,8 @@ ...f, properties, } - }) - ) + }), + ), ) // The actual point to be created, snapped at the new location new ShowDataLayer(map, { @@ -139,7 +148,7 @@ {:else if icon === "key"} + {:else if icon === "snap"} + {:else if Utils.isEmoji(icon)} {icon} diff --git a/src/UI/Popup/MoveWizard.svelte b/src/UI/Popup/MoveWizard.svelte index afb014155..604bbf3dc 100644 --- a/src/UI/Popup/MoveWizard.svelte +++ b/src/UI/Popup/MoveWizard.svelte @@ -10,7 +10,6 @@ import type { MapProperties } from "../../Models/MapProperties" import type { Feature, Point } from "geojson" import { GeoOperations } from "../../Logic/GeoOperations" - import LocationInput from "../InputElement/Helpers/LocationInput.svelte" import OpenBackgroundSelectorButton from "../BigComponents/OpenBackgroundSelectorButton.svelte" import Geosearch from "../BigComponents/Geosearch.svelte" import If from "../Base/If.svelte" @@ -21,6 +20,8 @@ import ChevronLeft from "@babeard/svelte-heroicons/solid/ChevronLeft" import ThemeViewState from "../../Models/ThemeViewState" import Icon from "../Map/Icon.svelte" + import NewPointLocationInput from "../BigComponents/NewPointLocationInput.svelte" + import type { WayId } from "../../Models/OsmFeature" export let state: ThemeViewState @@ -36,20 +37,22 @@ let newLocation = new UIEventSource<{ lon: number; lat: number }>(undefined) - function initMapProperties() { + let snappedTo = new UIEventSource(undefined) + + function initMapProperties(reason: MoveReason) { return { allowMoving: new UIEventSource(true), allowRotating: new UIEventSource(false), allowZooming: new UIEventSource(true), bounds: new UIEventSource(undefined), location: new UIEventSource({ lon, lat }), - minzoom: new UIEventSource($reason.minZoom), + minzoom: new UIEventSource(reason.minZoom), rasterLayer: state.mapProperties.rasterLayer, - zoom: new UIEventSource($reason?.startZoom ?? 16), + zoom: new UIEventSource(reason?.startZoom ?? 16), } } - let moveWizardState = new MoveWizardState(id, layer.allowMove, state) + let moveWizardState = new MoveWizardState(id, layer.allowMove, layer, state) if (moveWizardState.reasons.length === 1) { reason.setData(moveWizardState.reasons[0]) } @@ -57,8 +60,8 @@ let currentMapProperties: MapProperties = undefined - - {#if moveWizardState.reasons.length > 0} +{#if moveWizardState.reasons.length > 0} + {#if $notAllowed}
@@ -81,7 +84,7 @@ {#if currentStep === "reason" && moveWizardState.reasons.length > 1} {#each moveWizardState.reasons as reasonSpec} -