diff --git a/Logic/GeoOperations.ts b/Logic/GeoOperations.ts index bea4fa04c..ee4a4f3a9 100644 --- a/Logic/GeoOperations.ts +++ b/Logic/GeoOperations.ts @@ -1,20 +1,10 @@ -import * as turf from "@turf/turf" -import { BBox } from "./BBox" -import togpx from "togpx" -import Constants from "../Models/Constants" +import {BBox} from "./BBox" import LayerConfig from "../Models/ThemeConfig/LayerConfig" -import { - AllGeoJSON, - booleanWithin, - Coord, - Feature, - Geometry, - Lines, - MultiPolygon, - Polygon, - Properties, -} from "@turf/turf" -import { GeoJSON, LineString, Point } from "geojson" +import * as turf from "@turf/turf" +import {AllGeoJSON, booleanWithin, Coord, Feature, Geometry, MultiPolygon, Polygon,} from "@turf/turf" +import {LineString, Point} from "geojson" +import togpx from "togpx" +import Constants from "../Models/Constants"; export class GeoOperations { private static readonly _earthRadius = 6378137 @@ -393,21 +383,22 @@ export class GeoOperations { .features.map((p) => <[number, number]>p.geometry.coordinates) } - public static AsGpx(feature, generatedWithLayer?: LayerConfig) { - const metadata = {} + public static AsGpx(feature: Feature, options?: {layer?: LayerConfig, gpxMetadata?: any }) : string{ + + const metadata = options?.gpxMetadata ?? {} + metadata["time"] = metadata["time"] ?? new Date().toISOString() const tags = feature.properties - if (generatedWithLayer !== undefined) { - metadata["name"] = generatedWithLayer.title?.GetRenderValue(tags)?.Subs(tags)?.txt - metadata["desc"] = "Generated with MapComplete layer " + generatedWithLayer.id + if (options?.layer !== undefined) { + + metadata["name"] = options?.layer.title?.GetRenderValue(tags)?.Subs(tags)?.txt + metadata["desc"] = "Generated with MapComplete layer " + options?.layer.id if (tags._backend?.contains("openstreetmap")) { metadata["copyright"] = "Data copyrighted by OpenStreetMap-contributors, freely available under ODbL. See https://www.openstreetmap.org/copyright" metadata["author"] = tags["_last_edit:contributor"] metadata["link"] = "https://www.openstreetmap.org/" + tags.id metadata["time"] = tags["_last_edit:timestamp"] - } else { - metadata["time"] = new Date().toISOString() } } diff --git a/Logic/Osm/OsmConnection.ts b/Logic/Osm/OsmConnection.ts index cfa247e68..47420a08a 100644 --- a/Logic/Osm/OsmConnection.ts +++ b/Logic/Osm/OsmConnection.ts @@ -27,10 +27,12 @@ export default class UserDetails { export class OsmConnection { public static readonly oauth_configs = { - osm: { - oauth_consumer_key: "hivV7ec2o49Two8g9h8Is1VIiVOgxQ1iYexCbvem", - oauth_secret: "wDBRTCem0vxD7txrg1y6p5r8nvmz8tAhET7zDASI", - url: "https://www.openstreetmap.org", + "osm": { + oauth_consumer_key: 'hivV7ec2o49Two8g9h8Is1VIiVOgxQ1iYexCbvem', + oauth_secret: 'wDBRTCem0vxD7txrg1y6p5r8nvmz8tAhET7zDASI', + url: "https://www.openstreetmap.org" + // OAUTH 1.0 application + // https://www.openstreetmap.org/user/Pieter%20Vander%20Vennet/oauth_clients/7404 }, "osm-test": { oauth_consumer_key: "Zgr7EoKb93uwPv2EOFkIlf3n9NLwj5wbyfjZMhz2", @@ -333,6 +335,80 @@ export class OsmConnection { }) } + public async uploadGpxTrack(gpx: string, options: { + description: string, + visibility: "private" | "public" | "trackable" | "identifiable", + filename?: string + /** + * Some words to give some properties; + * + * Note: these are called 'tags' on the wiki, but I opted to name them 'labels' instead as they aren't "key=value" tags, but just words. + */ + labels: string[] + }): Promise<{ id: number }> { + if (this._dryRun.data) { + console.warn("Dryrun enabled - not actually uploading GPX ", gpx) + return new Promise<{ id: number }>((ok, error) => { + window.setTimeout(() => ok({id: Math.floor(Math.random() * 1000)}), Math.random() * 5000) + }); + } + + const contents = { + "file": gpx, + "description": options.description ?? "", + "tags": options.labels?.join(",") ?? "", + "visibility": options.visibility + } + + const extras = { + "file": "; filename=\""+(options.filename ?? ("gpx_track_mapcomplete_"+(new Date().toISOString())))+"\"\r\nContent-Type: application/gpx+xml" + } + + const auth = this.auth; + const boundary ="987654" + + let body = "" + for (const key in contents) { + body += "--" + boundary + "\r\n" + body += "Content-Disposition: form-data; name=\"" + key + "\"" + if(extras[key] !== undefined){ + body += extras[key] + } + body += "\r\n\r\n" + body += contents[key] + "\r\n" + } + body += "--" + boundary + "--\r\n" + + + return new Promise((ok, error) => { + auth.xhr({ + method: 'POST', + path: `/api/0.6/gpx/create`, + options: { + header: + { + "Content-Type": "multipart/form-data; boundary=" + boundary, + "Content-Length": body.length + } + }, + content: body + + }, function ( + err, + response: string) { + console.log("RESPONSE IS", response) + if (err !== null) { + error(err) + } else { + const parsed = JSON.parse(response) + console.log("Uploaded GPX track", parsed) + ok({id: parsed}) + } + }) + }) + + } + public addCommentToNote(id: number | string, text: string): Promise { if (this._dryRun.data) { console.warn("Dryrun enabled - not actually adding comment ", text, "to note ", id) diff --git a/Logic/State/MapState.ts b/Logic/State/MapState.ts index 9c52a09d2..6ae49aa35 100644 --- a/Logic/State/MapState.ts +++ b/Logic/State/MapState.ts @@ -68,7 +68,7 @@ export default class MapState extends UserRelatedState { public currentUserLocation: SimpleFeatureSource /** - * All previously visited points + * All previously visited points, with their metadata */ public historicalUserLocations: SimpleFeatureSource /** @@ -79,6 +79,11 @@ export default class MapState extends UserRelatedState { 7 * 24 * 60 * 60, "gps_location_retention" ) + /** + * A featureSource containing a single linestring which has the GPS-history of the user. + * However, metadata (such as when every single point was visited) is lost here (but is kept in `historicalUserLocations`. + * Note that this featureSource is _derived_ from 'historicalUserLocations' + */ public historicalUserLocationsTrack: FeatureSourceForLayer & Tiled /** diff --git a/Models/ThemeConfig/DependencyCalculator.ts b/Models/ThemeConfig/DependencyCalculator.ts index 8a8106d4d..8adeccf04 100644 --- a/Models/ThemeConfig/DependencyCalculator.ts +++ b/Models/ThemeConfig/DependencyCalculator.ts @@ -1,8 +1,8 @@ -import { SpecialVisualization } from "../../UI/SpecialVisualizations" import { SubstitutedTranslation } from "../../UI/SubstitutedTranslation" import TagRenderingConfig from "./TagRenderingConfig" import { ExtraFuncParams, ExtraFunctions } from "../../Logic/ExtraFunctions" import LayerConfig from "./LayerConfig" +import {SpecialVisualization} from "../../UI/SpecialVisualization"; export default class DependencyCalculator { public static GetTagRenderingDependencies(tr: TagRenderingConfig): string[] { diff --git a/UI/Base/SubtleButton.ts b/UI/Base/SubtleButton.ts index 90242fbc9..6d98b89a3 100644 --- a/UI/Base/SubtleButton.ts +++ b/UI/Base/SubtleButton.ts @@ -73,13 +73,11 @@ export class SubtleButton extends UIElement { } }) const loading = new Lazy(() => new Loading(loadingText)) - return new VariableUiElement( - state.map((st) => { - if (st === "idle") { - return button - } - return loading - }) - ) + return new VariableUiElement(state.map(st => { + if(st === "idle"){ + return button + } + return loading + })) } } diff --git a/UI/BigComponents/UploadTraceToOsmUI.ts b/UI/BigComponents/UploadTraceToOsmUI.ts new file mode 100644 index 000000000..5dae8b786 --- /dev/null +++ b/UI/BigComponents/UploadTraceToOsmUI.ts @@ -0,0 +1,107 @@ +import Toggle from "../Input/Toggle"; +import {RadioButton} from "../Input/RadioButton"; +import {FixedInputElement} from "../Input/FixedInputElement"; +import Combine from "../Base/Combine"; +import Translations from "../i18n/Translations"; +import {TextField} from "../Input/TextField"; +import {UIEventSource} from "../../Logic/UIEventSource"; +import Title from "../Base/Title"; +import {SubtleButton} from "../Base/SubtleButton"; +import Svg from "../../Svg"; +import {OsmConnection} from "../../Logic/Osm/OsmConnection"; +import LayoutConfig from "../../Models/ThemeConfig/LayoutConfig"; +import {Translation} from "../i18n/Translation"; + + +export default class UploadTraceToOsmUI extends Toggle { + + + constructor( + trace: (title: string) => string, + state: { + layoutToUse: LayoutConfig; + osmConnection: OsmConnection + }, options?: { + whenUploaded?: () => void | Promise + }) { + const t = Translations.t.general.uploadGpx + const uploadFinished = new UIEventSource(false) + const traceVisibilities: { + key: "private" | "public", + name: Translation, + docs: Translation + }[] = [ + { + key: "private", + ...t.modes.private + }, + { + key: "public", + ...t.modes.public + } + ] + + const dropdown = new RadioButton<"private" | "public">( + traceVisibilities.map(tv => new FixedInputElement<"private" | "public">( + new Combine([Translations.W( + tv.name + ).SetClass("font-bold"), tv.docs]).SetClass("flex flex-col") + , tv.key)), + { + value: state?.osmConnection?.GetPreference("gps.trace.visibility") + } + ) + const description = new TextField({ + placeholder: t.meta.descriptionPlaceHolder + }) + const title = new TextField({ + placeholder: t.meta.titlePlaceholder + }) + const clicked = new UIEventSource(false) + + const confirmPanel = new Combine([ + new Title(t.title), + t.intro0, + t.intro1, + + t.choosePermission, + dropdown, + new Title(t.meta.title, 4), + t.meta.intro, + title, + t.meta.descriptionIntro, + description, + new Combine([ + new SubtleButton(Svg.close_svg(), Translations.t.general.cancel).onClick(() => { + clicked.setData(false) + }).SetClass(""), + new SubtleButton(Svg.upload_svg(), t.confirm).OnClickWithLoading(t.uploading, async () => { + await state?.osmConnection?.uploadGpxTrack(trace(title.GetValue().data), { + visibility: dropdown.GetValue().data, + description: description.GetValue().data, + filename: title.GetValue().data+".gpx", + labels: ["MapComplete", state?.layoutToUse?.id] + }) + + if (options?.whenUploaded !== undefined) { + await options.whenUploaded() + } + uploadFinished.setData(true) + + }) + ]).SetClass("flex flex-wrap flex-wrap-reverse justify-between items-stretch") + ]).SetClass("flex flex-col p-4 rounded border-2 m-2 border-subtle") + + + super( + new Combine([Svg.confirm_svg().SetClass("w-12 h-12 mr-2"), + t.uploadFinished]) + .SetClass("flex p-2 rounded-xl border-2 subtle-border items-center"), + new Toggle( + confirmPanel, + new SubtleButton(Svg.upload_svg(), t.title) + .onClick(() => clicked.setData(true)), + clicked + ), uploadFinished) + } +} \ No newline at end of file diff --git a/UI/Input/RadioButton.ts b/UI/Input/RadioButton.ts index 03adaad69..4015425af 100644 --- a/UI/Input/RadioButton.ts +++ b/UI/Input/RadioButton.ts @@ -13,15 +13,16 @@ export class RadioButton extends InputElement { constructor( elements: InputElement[], options?: { - selectFirstAsDefault?: true | boolean - dontStyle?: boolean + selectFirstAsDefault?: true | boolean, + dontStyle?: boolean, + value?: UIEventSource } ) { super() options = options ?? {} this._selectFirstAsDefault = options.selectFirstAsDefault ?? true this._elements = Utils.NoNull(elements) - this.value = new UIEventSource(undefined) + this.value = options?.value ?? new UIEventSource(undefined) this._dontStyle = options.dontStyle ?? false } diff --git a/UI/Popup/AddNoteCommentViz.ts b/UI/Popup/AddNoteCommentViz.ts new file mode 100644 index 000000000..dc4a6e4dd --- /dev/null +++ b/UI/Popup/AddNoteCommentViz.ts @@ -0,0 +1,119 @@ +import Translations from "../i18n/Translations"; +import {TextField} from "../Input/TextField"; +import {SubtleButton} from "../Base/SubtleButton"; +import Svg from "../../Svg"; +import NoteCommentElement from "./NoteCommentElement"; +import {VariableUiElement} from "../Base/VariableUIElement"; +import Toggle from "../Input/Toggle"; +import {LoginToggle} from "./LoginButton"; +import Combine from "../Base/Combine"; +import Title from "../Base/Title"; +import {SpecialVisualization} from "../SpecialVisualization"; + +export class AddNoteCommentViz implements SpecialVisualization { + funcName = "add_note_comment" + docs = "A textfield to add a comment to a node (with the option to close the note)." + args = [ + { + name: "Id-key", + doc: "The property name where the ID of the note to close can be found", + defaultValue: "id", + }, + ] + + public constr(state, tags, args) { + const t = Translations.t.notes + const textField = new TextField({ + placeholder: t.addCommentPlaceholder, + inputStyle: "width: 100%; height: 6rem;", + textAreaRows: 3, + htmlType: "area", + }) + textField.SetClass("rounded-l border border-grey") + const txt = textField.GetValue() + + const addCommentButton = new SubtleButton( + Svg.speech_bubble_svg().SetClass("max-h-7"), + t.addCommentPlaceholder + ).onClick(async () => { + const id = tags.data[args[1] ?? "id"] + + if ((txt.data ?? "") == "") { + return + } + + if (isClosed.data) { + await state.osmConnection.reopenNote(id, txt.data) + await state.osmConnection.closeNote(id) + } else { + await state.osmConnection.addCommentToNote(id, txt.data) + } + NoteCommentElement.addCommentTo(txt.data, tags, state) + txt.setData("") + }) + + const close = new SubtleButton( + Svg.resolved_svg().SetClass("max-h-7"), + new VariableUiElement( + txt.map((txt) => { + if (txt === undefined || txt === "") { + return t.closeNote + } + return t.addCommentAndClose + }) + ) + ).onClick(() => { + const id = tags.data[args[1] ?? "id"] + state.osmConnection.closeNote(id, txt.data).then((_) => { + tags.data["closed_at"] = new Date().toISOString() + tags.ping() + }) + }) + + const reopen = new SubtleButton( + Svg.note_svg().SetClass("max-h-7"), + new VariableUiElement( + txt.map((txt) => { + if (txt === undefined || txt === "") { + return t.reopenNote + } + return t.reopenNoteAndComment + }) + ) + ).onClick(() => { + const id = tags.data[args[1] ?? "id"] + state.osmConnection.reopenNote(id, txt.data).then((_) => { + tags.data["closed_at"] = undefined + tags.ping() + }) + }) + + const isClosed = tags.map((tags) => (tags["closed_at"] ?? "") !== "") + const stateButtons = new Toggle( + new Toggle(reopen, close, isClosed), + undefined, + state.osmConnection.isLoggedIn + ) + + return new LoginToggle( + new Combine([ + new Title(t.addAComment), + textField, + new Combine([ + stateButtons.SetClass("sm:mr-2"), + new Toggle( + addCommentButton, + new Combine([t.typeText]).SetClass( + "flex items-center h-full subtle" + ), + textField + .GetValue() + .map((t) => t !== undefined && t.length >= 1) + ).SetClass("sm:mr-2"), + ]).SetClass("sm:flex sm:justify-between sm:items-stretch"), + ]).SetClass("border-2 border-black rounded-xl p-4 block"), + t.loginToAddComment, + state + ) + } +} diff --git a/UI/Popup/AutoApplyButton.ts b/UI/Popup/AutoApplyButton.ts index d005c83e5..73bf9280f 100644 --- a/UI/Popup/AutoApplyButton.ts +++ b/UI/Popup/AutoApplyButton.ts @@ -1,4 +1,3 @@ -import { SpecialVisualization } from "../SpecialVisualizations" import FeaturePipelineState from "../../Logic/State/FeaturePipelineState" import BaseUIElement from "../BaseUIElement" import { Stores, UIEventSource } from "../../Logic/UIEventSource" @@ -24,6 +23,7 @@ import FilteredLayer from "../../Models/FilteredLayer" import TagRenderingConfig from "../../Models/ThemeConfig/TagRenderingConfig" import Lazy from "../Base/Lazy" import List from "../Base/List" +import {SpecialVisualization} from "../SpecialVisualization"; export interface AutoAction extends SpecialVisualization { supportsAutoAction: boolean diff --git a/UI/Popup/CloseNoteButton.ts b/UI/Popup/CloseNoteButton.ts new file mode 100644 index 000000000..fd0667de7 --- /dev/null +++ b/UI/Popup/CloseNoteButton.ts @@ -0,0 +1,96 @@ +import FeaturePipelineState from "../../Logic/State/FeaturePipelineState"; +import BaseUIElement from "../BaseUIElement"; +import Translations from "../i18n/Translations"; +import {Utils} from "../../Utils"; +import Svg from "../../Svg"; +import Img from "../Base/Img"; +import {SubtleButton} from "../Base/SubtleButton"; +import Toggle from "../Input/Toggle"; +import {LoginToggle} from "./LoginButton"; +import {SpecialVisualization} from "../SpecialVisualization"; + +export class CloseNoteButton implements SpecialVisualization { + public readonly funcName = "close_note" + public readonly docs = + "Button to close a note. A predifined text can be defined to close the note with. If the note is already closed, will show a small text." + public readonly args = [ + { + name: "text", + doc: "Text to show on this button", + required: true, + }, + { + name: "icon", + doc: "Icon to show", + defaultValue: "checkmark.svg", + }, + { + name: "idkey", + doc: "The property name where the ID of the note to close can be found", + defaultValue: "id", + }, + { + name: "comment", + doc: "Text to add onto the note when closing", + }, + { + name: "minZoom", + doc: "If set, only show the closenote button if zoomed in enough", + }, + { + name: "zoomButton", + doc: "Text to show if not zoomed in enough", + }, + ] + + public constr(state: FeaturePipelineState, tags, args): BaseUIElement { + const t = Translations.t.notes + + const params: { + text: string + icon: string + idkey: string + comment: string + minZoom: string + zoomButton: string + } = Utils.ParseVisArgs(this.args, args) + + let icon = Svg.checkmark_svg() + if (params.icon !== "checkmark.svg" && (args[2] ?? "") !== "") { + icon = new Img(args[1]) + } + let textToShow = t.closeNote + if ((params.text ?? "") !== "") { + textToShow = Translations.T(args[0]) + } + + let closeButton: BaseUIElement = new SubtleButton(icon, textToShow) + const isClosed = tags.map((tags) => (tags["closed_at"] ?? "") !== "") + closeButton.onClick(() => { + const id = tags.data[args[2] ?? "id"] + state.osmConnection.closeNote(id, args[3])?.then((_) => { + tags.data["closed_at"] = new Date().toISOString() + tags.ping() + }) + }) + + if ((params.minZoom ?? "") !== "" && !isNaN(Number(params.minZoom))) { + closeButton = new Toggle( + closeButton, + params.zoomButton ?? "", + state.locationControl.map((l) => l.zoom >= Number(params.minZoom)) + ) + } + + return new LoginToggle( + new Toggle( + t.isClosed.SetClass("thanks"), + closeButton, + + isClosed + ), + t.loginToClose, + state + ) + } +} diff --git a/UI/Popup/EditableTagRendering.ts b/UI/Popup/EditableTagRendering.ts index 566257068..319bba2df 100644 --- a/UI/Popup/EditableTagRendering.ts +++ b/UI/Popup/EditableTagRendering.ts @@ -10,7 +10,6 @@ import TagRenderingConfig from "../../Models/ThemeConfig/TagRenderingConfig" import { Unit } from "../../Models/Unit" import Lazy from "../Base/Lazy" import { FixedUiElement } from "../Base/FixedUiElement" -import FeaturePipelineState from "../../Logic/State/FeaturePipelineState" export default class EditableTagRendering extends Toggle { constructor( @@ -57,7 +56,7 @@ export default class EditableTagRendering extends Toggle { } private static CreateRendering( - state: FeaturePipelineState, + state: any /*FeaturePipelineState*/, tags: UIEventSource, configuration: TagRenderingConfig, units: Unit[], diff --git a/UI/Popup/ExportAsGpxViz.ts b/UI/Popup/ExportAsGpxViz.ts new file mode 100644 index 000000000..f9ac6ee57 --- /dev/null +++ b/UI/Popup/ExportAsGpxViz.ts @@ -0,0 +1,41 @@ +import Translations from "../i18n/Translations"; +import {SubtleButton} from "../Base/SubtleButton"; +import Svg from "../../Svg"; +import Combine from "../Base/Combine"; +import {GeoOperations} from "../../Logic/GeoOperations"; +import {Utils} from "../../Utils"; +import {SpecialVisualization} from "../SpecialVisualization"; + +export class ExportAsGpxViz implements SpecialVisualization { + funcName = "export_as_gpx" + docs = "Exports the selected feature as GPX-file" + args = [] + + constr(state, tagSource) { + const t = Translations.t.general.download + + return new SubtleButton( + Svg.download_ui(), + new Combine([ + t.downloadFeatureAsGpx.SetClass("font-bold text-lg"), + t.downloadGpxHelper.SetClass("subtle"), + ]).SetClass("flex flex-col") + ).onClick(() => { + console.log("Exporting as GPX!") + const tags = tagSource.data + const feature = state.allElements.ContainingFeatures.get(tags.id) + const matchingLayer = state?.layoutToUse?.getMatchingLayer(tags) + const gpx = GeoOperations.AsGpx(feature, matchingLayer) + const title = + matchingLayer.title?.GetRenderValue(tags)?.Subs(tags)?.txt ?? + "gpx_track" + Utils.offerContentsAsDownloadableFile( + gpx, + title + "_mapcomplete_export.gpx", + { + mimetype: "{gpx=application/gpx+xml}", + } + ) + }) + } +} diff --git a/UI/Popup/HistogramViz.ts b/UI/Popup/HistogramViz.ts new file mode 100644 index 000000000..529dce5d3 --- /dev/null +++ b/UI/Popup/HistogramViz.ts @@ -0,0 +1,75 @@ +import {Store, UIEventSource} from "../../Logic/UIEventSource"; +import {FixedUiElement} from "../Base/FixedUiElement"; +// import Histogram from "../BigComponents/Histogram"; +// import {SpecialVisualization} from "../SpecialVisualization"; + +export class HistogramViz { + funcName = "histogram" + docs = "Create a histogram for a list of given values, read from the properties." + example = + "`{histogram('some_key')}` with properties being `{some_key: ['a','b','a','c']} to create a histogram" + args = [ + { + name: "key", + doc: "The key to be read and to generate a histogram from", + required: true, + }, + { + name: "title", + doc: "This text will be placed above the texts (in the first column of the visulasition)", + defaultValue: "", + }, + { + name: "countHeader", + doc: "This text will be placed above the bars", + defaultValue: "", + }, + { + name: "colors*", + doc: "(Matches all resting arguments - optional) Matches a regex onto a color value, e.g. `3[a-zA-Z+-]*:#33cc33`", + }, + ]; + + constr(state, tagSource: UIEventSource, args: string[]) { + let assignColors = undefined + if (args.length >= 3) { + const colors = [...args] + colors.splice(0, 3) + const mapping = colors.map((c) => { + const splitted = c.split(":") + const value = splitted.pop() + const regex = splitted.join(":") + return {regex: "^" + regex + "$", color: value} + }) + assignColors = (key) => { + for (const kv of mapping) { + if (key.match(kv.regex) !== null) { + return kv.color + } + } + return undefined + } + } + + const listSource: Store = tagSource.map((tags) => { + try { + const value = tags[args[0]] + if (value === "" || value === undefined) { + return undefined + } + return JSON.parse(value) + } catch (e) { + console.error( + "Could not load histogram: parsing of the list failed: ", + e + ) + return undefined + } + }) + return new FixedUiElement("HISTORGRAM") + /* + return new Histogram(listSource, args[1], args[2], { + assignColor: assignColors, + })*/ + } +} diff --git a/UI/Popup/ImportButton.ts b/UI/Popup/ImportButton.ts index 2f163edad..5a91583be 100644 --- a/UI/Popup/ImportButton.ts +++ b/UI/Popup/ImportButton.ts @@ -12,7 +12,6 @@ import Lazy from "../Base/Lazy" import ConfirmLocationOfPoint from "../NewPoint/ConfirmLocationOfPoint" import Img from "../Base/Img" import FilteredLayer from "../../Models/FilteredLayer" -import SpecialVisualizations from "../SpecialVisualizations" import { FixedUiElement } from "../Base/FixedUiElement" import Svg from "../../Svg" import { Utils } from "../../Utils" @@ -45,12 +44,13 @@ import { Changes } from "../../Logic/Osm/Changes" import { ElementStorage } from "../../Logic/ElementStorage" import Hash from "../../Logic/Web/Hash" import { PreciseInput } from "../../Models/ThemeConfig/PresetConfig" +import {SpecialVisualization} from "../SpecialVisualization"; /** * A helper class for the various import-flows. * An import-flow always starts with a 'Import this'-button. Upon click, a custom confirmation panel is provided */ -abstract class AbstractImportButton implements SpecialVisualizations { +abstract class AbstractImportButton implements SpecialVisualization { protected static importedIds = new Set() public readonly funcName: string public readonly docs: string diff --git a/UI/Popup/MapillaryLinkVis.ts b/UI/Popup/MapillaryLinkVis.ts new file mode 100644 index 000000000..1d364e37b --- /dev/null +++ b/UI/Popup/MapillaryLinkVis.ts @@ -0,0 +1,33 @@ +import {GeoOperations} from "../../Logic/GeoOperations"; +import {MapillaryLink} from "../BigComponents/MapillaryLink"; +import {UIEventSource} from "../../Logic/UIEventSource"; +import Loc from "../../Models/Loc"; +import {SpecialVisualization} from "../SpecialVisualization"; + +export class MapillaryLinkVis implements SpecialVisualization { + funcName = "mapillary_link" + docs = "Adds a button to open mapillary on the specified location" + args = [ + { + name: "zoom", + doc: "The startzoom of mapillary", + defaultValue: "18", + }, + ] + + public constr(state, tagsSource, args) { + const feat = state.allElements.ContainingFeatures.get(tagsSource.data.id) + const [lon, lat] = GeoOperations.centerpointCoordinates(feat) + let zoom = Number(args[0]) + if (isNaN(zoom)) { + zoom = 18 + } + return new MapillaryLink({ + locationControl: new UIEventSource({ + lat, + lon, + zoom, + }), + }) + } +} diff --git a/UI/Popup/MinimapViz.ts b/UI/Popup/MinimapViz.ts new file mode 100644 index 000000000..2d57caab3 --- /dev/null +++ b/UI/Popup/MinimapViz.ts @@ -0,0 +1,99 @@ +import {Store, UIEventSource} from "../../Logic/UIEventSource"; +import Loc from "../../Models/Loc"; +import Minimap from "../Base/Minimap"; +import ShowDataMultiLayer from "../ShowDataLayer/ShowDataMultiLayer"; +import StaticFeatureSource from "../../Logic/FeatureSource/Sources/StaticFeatureSource"; +import {SpecialVisualization} from "../SpecialVisualization"; + +export class MinimapViz implements SpecialVisualization { + funcName = "minimap" + docs = "A small map showing the selected feature." + args = [ + { + doc: "The (maximum) zoomlevel: the target zoomlevel after fitting the entire feature. The minimap will fit the entire feature, then zoom out to this zoom level. The higher, the more zoomed in with 1 being the entire world and 19 being really close", + name: "zoomlevel", + defaultValue: "18", + }, + { + doc: "(Matches all resting arguments) This argument should be the key of a property of the feature. The corresponding value is interpreted as either the id or the a list of ID's. The features with these ID's will be shown on this minimap. (Note: if the key is 'id', list interpration is disabled)", + name: "idKey", + defaultValue: "id", + }, + ] + example: + "`{minimap()}`, `{minimap(17, id, _list_of_embedded_feature_ids_calculated_by_calculated_tag):height:10rem; border: 2px solid black}`" + + constr(state, tagSource, args, _) { + if (state === undefined) { + return undefined + } + const keys = [...args] + keys.splice(0, 1) + const featureStore = state.allElements.ContainingFeatures + const featuresToShow: Store<{ freshness: Date; feature: any }[]> = + tagSource.map((properties) => { + const features: { freshness: Date; feature: any }[] = [] + for (const key of keys) { + const value = properties[key] + if (value === undefined || value === null) { + continue + } + + let idList = [value] + if (key !== "id" && value.startsWith("[")) { + // This is a list of values + idList = JSON.parse(value) + } + + for (const id of idList) { + const feature = featureStore.get(id) + if (feature === undefined) { + console.warn("No feature found for id ", id) + continue + } + features.push({ + freshness: new Date(), + feature, + }) + } + } + return features + }) + const properties = tagSource.data + let zoom = 18 + if (args[0]) { + const parsed = Number(args[0]) + if (!isNaN(parsed) && parsed > 0 && parsed < 25) { + zoom = parsed + } + } + const locationSource = new UIEventSource({ + lat: Number(properties._lat), + lon: Number(properties._lon), + zoom: zoom, + }) + const minimap = Minimap.createMiniMap({ + background: state.backgroundLayer, + location: locationSource, + allowMoving: false, + }) + + locationSource.addCallback((loc) => { + if (loc.zoom > zoom) { + // We zoom back + locationSource.data.zoom = zoom + locationSource.ping() + } + }) + + new ShowDataMultiLayer({ + leafletMap: minimap["leafletMap"], + zoomToFeatures: true, + layers: state.filteredLayers, + features: new StaticFeatureSource(featuresToShow), + }) + + minimap.SetStyle("overflow: hidden; pointer-events: none;") + return minimap + } +} diff --git a/UI/Popup/MultiApplyViz.ts b/UI/Popup/MultiApplyViz.ts new file mode 100644 index 000000000..14da8d39f --- /dev/null +++ b/UI/Popup/MultiApplyViz.ts @@ -0,0 +1,68 @@ +import {Store} from "../../Logic/UIEventSource"; +import MultiApply from "./MultiApply"; +import {SpecialVisualization} from "../SpecialVisualization"; + +export class MultiApplyViz implements SpecialVisualization { + funcName = "multi_apply" + docs = "A button to apply the tagging of this object onto a list of other features. This is an advanced feature for which you'll need calculatedTags" + args = [ + { + name: "feature_ids", + doc: "A JSON-serialized list of IDs of features to apply the tagging on", + }, + { + name: "keys", + doc: "One key (or multiple keys, seperated by ';') of the attribute that should be copied onto the other features.", + required: true, + }, + { name: "text", doc: "The text to show on the button" }, + { + name: "autoapply", + doc: "A boolean indicating wether this tagging should be applied automatically if the relevant tags on this object are changed. A visual element indicating the multi_apply is still shown", + required: true, + }, + { + name: "overwrite", + doc: "If set to 'true', the tags on the other objects will always be overwritten. The default behaviour will be to only change the tags on other objects if they are either undefined or had the same value before the change", + required: true, + }, + ] + example = + "{multi_apply(_features_with_the_same_name_within_100m, name:etymology:wikidata;name:etymology, Apply etymology information on all nearby objects with the same name)}" + + constr(state, tagsSource, args) { + const featureIdsKey = args[0] + const keysToApply = args[1].split(";") + const text = args[2] + const autoapply = args[3]?.toLowerCase() === "true" + const overwrite = args[4]?.toLowerCase() === "true" + const featureIds: Store = tagsSource.map((tags) => { + const ids = tags[featureIdsKey] + try { + if (ids === undefined) { + return [] + } + return JSON.parse(ids) + } catch (e) { + console.warn( + "Could not parse ", + ids, + "as JSON to extract IDS which should be shown on the map." + ) + return [] + } + }) + return new MultiApply( + { + featureIds, + keysToApply, + text, + autoapply, + overwrite, + tagsSource, + state + } + ); + + } +} diff --git a/UI/Popup/NearbyImageVis.ts b/UI/Popup/NearbyImageVis.ts new file mode 100644 index 000000000..bfc016490 --- /dev/null +++ b/UI/Popup/NearbyImageVis.ts @@ -0,0 +1,147 @@ +import FeaturePipelineState from "../../Logic/State/FeaturePipelineState"; +import {UIEventSource} from "../../Logic/UIEventSource"; +import {DefaultGuiState} from "../DefaultGuiState"; +import BaseUIElement from "../BaseUIElement"; +import Translations from "../i18n/Translations"; +import {GeoOperations} from "../../Logic/GeoOperations"; +import NearbyImages, {NearbyImageOptions, P4CPicture, SelectOneNearbyImage} from "./NearbyImages"; +import {SubstitutedTranslation} from "../SubstitutedTranslation"; +import {Tag} from "../../Logic/Tags/Tag"; +import ChangeTagAction from "../../Logic/Osm/Actions/ChangeTagAction"; +import {And} from "../../Logic/Tags/And"; +import {SaveButton} from "./SaveButton"; +import Lazy from "../Base/Lazy"; +import {CheckBox} from "../Input/Checkboxes"; +import Slider from "../Input/Slider"; +import AllImageProviders from "../../Logic/ImageProviders/AllImageProviders"; +import Combine from "../Base/Combine"; +import {VariableUiElement} from "../Base/VariableUIElement"; +import Toggle from "../Input/Toggle"; +import Title from "../Base/Title"; +import {MapillaryLinkVis} from "./MapillaryLinkVis"; +import {SpecialVisualization} from "../SpecialVisualization"; + +export class NearbyImageVis implements SpecialVisualization { + args: { name: string; defaultValue?: string; doc: string; required?: boolean }[] = [ + { + name: "mode", + defaultValue: "expandable", + doc: "Indicates how this component is initialized. Options are: \n\n- `open`: always show and load the pictures\n- `collapsable`: show the pictures, but a user can collapse them\n- `expandable`: shown by default; but a user can collapse them.", + }, + { + name: "mapillary", + defaultValue: "true", + doc: "If 'true', includes a link to mapillary on this location.", + }, + ] + docs = + "A component showing nearby images loaded from various online services such as Mapillary. In edit mode and when used on a feature, the user can select an image to add to the feature" + funcName = "nearby_images" + + constr( + state: FeaturePipelineState, + tagSource: UIEventSource, + args: string[], + guistate: DefaultGuiState + ): BaseUIElement { + const t = Translations.t.image.nearbyPictures + const mode: "open" | "expandable" | "collapsable" = args[0] + const feature = state.allElements.ContainingFeatures.get(tagSource.data.id) + const [lon, lat] = GeoOperations.centerpointCoordinates(feature) + const id: string = tagSource.data["id"] + const canBeEdited: boolean = !!id?.match("(node|way|relation)/-?[0-9]+") + const selectedImage = new UIEventSource(undefined) + + let saveButton: BaseUIElement = undefined + if (canBeEdited) { + const confirmText: BaseUIElement = new SubstitutedTranslation( + t.confirm, + tagSource, + state + ) + + const onSave = async () => { + console.log("Selected a picture...", selectedImage.data) + const osmTags = selectedImage.data.osmTags + const tags: Tag[] = [] + for (const key in osmTags) { + tags.push(new Tag(key, osmTags[key])) + } + await state?.changes?.applyAction( + new ChangeTagAction(id, new And(tags), tagSource.data, { + theme: state?.layoutToUse.id, + changeType: "link-image", + }) + ) + } + saveButton = new SaveButton( + selectedImage, + state.osmConnection, + confirmText, + t.noImageSelected + ) + .onClick(onSave) + .SetClass("flex justify-end") + } + + const nearby = new Lazy(() => { + const towardsCenter = new CheckBox(t.onlyTowards, false) + + const radiusValue = + state?.osmConnection?.GetPreference("nearby-images-radius", "300").sync( + (s) => Number(s), + [], + (i) => "" + i + ) ?? new UIEventSource(300) + + const radius = new Slider(25, 500, { + value: radiusValue, + step: 25, + }) + const alreadyInTheImage = AllImageProviders.LoadImagesFor(tagSource) + const options: NearbyImageOptions & { value } = { + lon, + lat, + searchRadius: 500, + shownRadius: radius.GetValue(), + value: selectedImage, + blacklist: alreadyInTheImage, + towardscenter: towardsCenter.GetValue(), + maxDaysOld: 365 * 5, + } + const slideshow = canBeEdited + ? new SelectOneNearbyImage(options, state) + : new NearbyImages(options, state) + const controls = new Combine([ + towardsCenter, + new Combine([ + new VariableUiElement( + radius.GetValue().map((radius) => t.withinRadius.Subs({radius})) + ), + radius, + ]).SetClass("flex justify-between"), + ]).SetClass("flex flex-col") + return new Combine([ + slideshow, + controls, + saveButton, + new MapillaryLinkVis().constr(state, tagSource, []).SetClass("mt-6"), + ]) + }) + + let withEdit: BaseUIElement = nearby + if (canBeEdited) { + withEdit = new Combine([t.hasMatchingPicture, nearby]).SetClass("flex flex-col") + } + + if (mode === "open") { + return withEdit + } + const toggleState = new UIEventSource(mode === "collapsable") + return new Toggle( + new Combine([new Title(t.title), withEdit]), + new Title(t.browseNearby).onClick(() => toggleState.setData(true)), + toggleState + ) + } +} diff --git a/UI/Popup/PlantNetDetectionViz.ts b/UI/Popup/PlantNetDetectionViz.ts new file mode 100644 index 000000000..7b3bece51 --- /dev/null +++ b/UI/Popup/PlantNetDetectionViz.ts @@ -0,0 +1,80 @@ +import {Store, UIEventSource} from "../../Logic/UIEventSource"; +import Toggle from "../Input/Toggle"; +import Lazy from "../Base/Lazy"; +import {ProvidedImage} from "../../Logic/ImageProviders/ImageProvider"; +import PlantNetSpeciesSearch from "../BigComponents/PlantNetSpeciesSearch"; +import Wikidata from "../../Logic/Web/Wikidata"; +import ChangeTagAction from "../../Logic/Osm/Actions/ChangeTagAction"; +import {And} from "../../Logic/Tags/And"; +import {Tag} from "../../Logic/Tags/Tag"; +import {SubtleButton} from "../Base/SubtleButton"; +import Combine from "../Base/Combine"; +import Svg from "../../Svg"; +import Translations from "../i18n/Translations"; +import AllImageProviders from "../../Logic/ImageProviders/AllImageProviders"; +import {SpecialVisualization} from "../SpecialVisualization"; + +export class PlantNetDetectionViz implements SpecialVisualization { + funcName = "plantnet_detection" + + docs = "Sends the images linked to the current object to plantnet.org and asks it what plant species is shown on it. The user can then select the correct species; the corresponding wikidata-identifier will then be added to the object (together with `source:species:wikidata=plantnet.org AI`). " + args = [ + { + name: "image_key", + defaultValue: AllImageProviders.defaultKeys.join(","), + doc: "The keys given to the images, e.g. if image is given, the first picture URL will be added as image, the second as image:0, the third as image:1, etc... Multiple values are allowed if ';'-separated ", + } + ] + + public constr(state, tags, args) { + let imagePrefixes: string[] = undefined + if (args.length > 0) { + imagePrefixes = [].concat(...args.map((a) => a.split(","))) + } + + const detect = new UIEventSource(false) + const toggle = new Toggle( + new Lazy(() => { + const allProvidedImages: Store = + AllImageProviders.LoadImagesFor(tags, imagePrefixes) + const allImages: Store = allProvidedImages.map((pi) => + pi.map((pi) => pi.url) + ) + return new PlantNetSpeciesSearch( + allImages, + async (selectedWikidata) => { + selectedWikidata = Wikidata.ExtractKey(selectedWikidata) + const change = new ChangeTagAction( + tags.data.id, + new And([ + new Tag("species:wikidata", selectedWikidata), + new Tag("source:species:wikidata", "PlantNet.org AI"), + ]), + tags.data, + { + theme: state.layoutToUse.id, + changeType: "plantnet-ai-detection", + } + ) + await state.changes.applyAction(change) + } + ) + }), + new SubtleButton( + undefined, + "Detect plant species with plantnet.org" + ).onClick(() => detect.setData(true)), + detect + ) + + return new Combine([ + toggle, + new Combine([ + Svg.plantnet_logo_svg().SetClass( + "w-10 h-10 p-1 mr-1 bg-white rounded-full" + ), + Translations.t.plantDetection.poweredByPlantnet, + ]).SetClass("flex p-2 bg-gray-200 rounded-xl self-end"), + ]).SetClass("flex flex-col") + } +} diff --git a/UI/Popup/ShareLinkViz.ts b/UI/Popup/ShareLinkViz.ts new file mode 100644 index 000000000..3e0acce84 --- /dev/null +++ b/UI/Popup/ShareLinkViz.ts @@ -0,0 +1,56 @@ +import {UIEventSource} from "../../Logic/UIEventSource"; +import LayerConfig from "../../Models/ThemeConfig/LayerConfig"; +import ShareButton from "../BigComponents/ShareButton"; +import Svg from "../../Svg"; +import {FixedUiElement} from "../Base/FixedUiElement"; +import {SpecialVisualization} from "../SpecialVisualization"; + +export class ShareLinkViz implements SpecialVisualization { + funcName = "share_link" + docs = "Creates a link that (attempts to) open the native 'share'-screen" + example = + "{share_link()} to share the current page, {share_link()} to share the given url" + args = [ + { + name: "url", + doc: "The url to share (default: current URL)", + }, + ] + + public constr(state, tagSource: UIEventSource, args) { + if (window.navigator.share) { + const generateShareData = () => { + const title = state?.layoutToUse?.title?.txt ?? "MapComplete" + + let matchingLayer: LayerConfig = state?.layoutToUse?.getMatchingLayer( + tagSource?.data + ) + let name = + matchingLayer?.title?.GetRenderValue(tagSource.data)?.txt ?? + tagSource.data?.name ?? + "POI" + if (name) { + name = `${name} (${title})` + } else { + name = title + } + let url = args[0] ?? "" + if (url === "") { + url = window.location.href + } + return { + title: name, + url: url, + text: state?.layoutToUse?.shortDescription?.txt ?? "MapComplete", + } + } + + return new ShareButton( + Svg.share_svg().SetClass("w-8 h-8"), + generateShareData + ) + } else { + return new FixedUiElement("") + } + } +} diff --git a/UI/Popup/SidedMinimap.ts b/UI/Popup/SidedMinimap.ts new file mode 100644 index 000000000..51d01a462 --- /dev/null +++ b/UI/Popup/SidedMinimap.ts @@ -0,0 +1,55 @@ +import {UIEventSource} from "../../Logic/UIEventSource"; +import Loc from "../../Models/Loc"; +import Minimap from "../Base/Minimap"; +import ShowDataLayer from "../ShowDataLayer/ShowDataLayer"; +import LayerConfig from "../../Models/ThemeConfig/LayerConfig"; +import * as left_right_style_json from "../../assets/layers/left_right_style/left_right_style.json"; +import StaticFeatureSource from "../../Logic/FeatureSource/Sources/StaticFeatureSource"; +import {SpecialVisualization} from "../SpecialVisualization"; + +export class SidedMinimap implements SpecialVisualization { + funcName = "sided_minimap" + docs = "A small map showing _only one side_ the selected feature. *This features requires to have linerenderings with offset* as only linerenderings with a postive or negative offset will be shown. Note: in most cases, this map will be automatically introduced" + args = [ + { + doc: "The side to show, either `left` or `right`", + name: "side", + required: true, + }, + ] + example = "`{sided_minimap(left)}`" + + public constr(state, tagSource, args) { + const properties = tagSource.data + const locationSource = new UIEventSource({ + lat: Number(properties._lat), + lon: Number(properties._lon), + zoom: 18, + }) + const minimap = Minimap.createMiniMap({ + background: state.backgroundLayer, + location: locationSource, + allowMoving: false, + }) + const side = args[0] + const feature = state.allElements.ContainingFeatures.get(tagSource.data.id) + const copy = {...feature} + copy.properties = { + id: side, + } + new ShowDataLayer({ + leafletMap: minimap["leafletMap"], + zoomToFeatures: true, + layerToShow: new LayerConfig( + left_right_style_json, + "all_known_layers", + true + ), + features: StaticFeatureSource.fromGeojson([copy]), + state, + }) + + minimap.SetStyle("overflow: hidden; pointer-events: none;") + return minimap + } +} diff --git a/UI/Popup/StealViz.ts b/UI/Popup/StealViz.ts new file mode 100644 index 000000000..86ada0b90 --- /dev/null +++ b/UI/Popup/StealViz.ts @@ -0,0 +1,72 @@ +import LayerConfig from "../../Models/ThemeConfig/LayerConfig"; +import TagRenderingConfig from "../../Models/ThemeConfig/TagRenderingConfig"; +import {VariableUiElement} from "../Base/VariableUIElement"; +import BaseUIElement from "../BaseUIElement"; +import EditableTagRendering from "./EditableTagRendering"; +import Combine from "../Base/Combine"; +import {SpecialVisualization} from "../SpecialVisualization"; + +export class StealViz implements SpecialVisualization { + funcName = "steal" + docs = "Shows a tagRendering from a different object as if this was the object itself" + args = [ + { + name: "featureId", + doc: "The key of the attribute which contains the id of the feature from which to use the tags", + required: true, + }, + { + name: "tagRenderingId", + doc: "The layer-id and tagRenderingId to render. Can be multiple value if ';'-separated (in which case every value must also contain the layerId, e.g. `layerId.tagRendering0; layerId.tagRendering1`). Note: this can cause layer injection", + required: true, + }, + ] + constr(state, featureTags, args) { + const [featureIdKey, layerAndtagRenderingIds] = args + const tagRenderings: [LayerConfig, TagRenderingConfig][] = [] + for (const layerAndTagRenderingId of layerAndtagRenderingIds.split(";")) { + const [layerId, tagRenderingId] = layerAndTagRenderingId.trim().split(".") + const layer = state.layoutToUse.layers.find((l) => l.id === layerId) + const tagRendering = layer.tagRenderings.find( + (tr) => tr.id === tagRenderingId + ) + tagRenderings.push([layer, tagRendering]) + } + if (tagRenderings.length === 0) { + throw "Could not create stolen tagrenddering: tagRenderings not found" + } + return new VariableUiElement( + featureTags.map((tags) => { + const featureId = tags[featureIdKey] + if (featureId === undefined) { + return undefined + } + const otherTags = state.allElements.getEventSourceById(featureId) + const elements: BaseUIElement[] = [] + for (const [layer, tagRendering] of tagRenderings) { + const el = new EditableTagRendering( + otherTags, + tagRendering, + layer.units, + state, + {} + ) + elements.push(el) + } + if (elements.length === 1) { + return elements[0] + } + return new Combine(elements).SetClass("flex flex-col") + }) + ) + } + + getLayerDependencies(args): string[] { + const [_, tagRenderingId] = args + if (tagRenderingId.indexOf(".") < 0) { + throw "Error: argument 'layerId.tagRenderingId' of special visualisation 'steal' should contain a dot" + } + const [layerId, __] = tagRenderingId.split(".") + return [layerId] + } +} diff --git a/UI/Popup/TagApplyButton.ts b/UI/Popup/TagApplyButton.ts index d8bf2091b..e8c34bbf3 100644 --- a/UI/Popup/TagApplyButton.ts +++ b/UI/Popup/TagApplyButton.ts @@ -14,8 +14,9 @@ import { Tag } from "../../Logic/Tags/Tag" import FeaturePipelineState from "../../Logic/State/FeaturePipelineState" import LayoutConfig from "../../Models/ThemeConfig/LayoutConfig" import { Changes } from "../../Logic/Osm/Changes" +import {SpecialVisualization} from "../SpecialVisualization"; -export default class TagApplyButton implements AutoAction { +export default class TagApplyButton implements AutoAction , SpecialVisualization{ public readonly funcName = "tag_apply" public readonly docs = "Shows a big button; clicking this button will apply certain tags onto the feature.\n\nThe first argument takes a specification of which tags to add.\n" + diff --git a/UI/Popup/UploadToOsmViz.ts b/UI/Popup/UploadToOsmViz.ts new file mode 100644 index 000000000..eb77fad3a --- /dev/null +++ b/UI/Popup/UploadToOsmViz.ts @@ -0,0 +1,45 @@ +import {Utils} from "../../Utils"; +import {Feature} from "geojson"; +import {Point} from "@turf/turf"; +import {GeoLocationPointProperties} from "../../Logic/Actors/GeoLocationHandler"; +import UploadTraceToOsmUI from "../BigComponents/UploadTraceToOsmUI"; +import {SpecialVisualization} from "../SpecialVisualization"; + +/** + * Wrapper around 'UploadTraceToOsmUI' + */ +export class UploadToOsmViz implements SpecialVisualization { + funcName = "upload_to_osm" + docs = "Uploads the GPS-history as GPX to OpenStreetMap.org; clears the history afterwards. The actual feature is ignored." + args = [] + + constr(state, featureTags, args) { + + function getTrace(title: string) { + title = title?.trim() + if (title === undefined || title === "") { + title = "Uploaded with MapComplete" + } + title = Utils.EncodeXmlValue(title) + const userLocations: Feature[] = state.historicalUserLocations.features.data.map(f => f.feature) + const trackPoints: string[] = [] + for (const l of userLocations) { + let trkpt = ` ` + trkpt += ` ` + if (l.properties.altitude !== null && l.properties.altitude !== undefined) { + trkpt += ` ${l.properties.altitude}` + } + trkpt += " " + trackPoints.push(trkpt) + } + const header = '' + return header + "\n" + title + "\n\n" + trackPoints.join("\n") + "\n" + } + + return new UploadTraceToOsmUI(getTrace, state, { + whenUploaded: async () => { + state.historicalUserLocations.features.setData([]) + } + }) + } +} diff --git a/UI/SpecialVisualization.ts b/UI/SpecialVisualization.ts new file mode 100644 index 000000000..c02fead59 --- /dev/null +++ b/UI/SpecialVisualization.ts @@ -0,0 +1,16 @@ +import {UIEventSource} from "../Logic/UIEventSource"; +import BaseUIElement from "./BaseUIElement"; + +export interface SpecialVisualization { + funcName: string + constr: ( + state: any, /*FeaturePipelineState*/ + tagSource: UIEventSource, + argument: string[], + guistate: any /*DefaultGuiState*/ + ) => BaseUIElement + docs: string | BaseUIElement + example?: string + args: { name: string; defaultValue?: string; doc: string; required?: false | boolean }[] + getLayerDependencies?: (argument: string[]) => string[] +} diff --git a/UI/SpecialVisualizations.ts b/UI/SpecialVisualizations.ts index 46c5a67cb..70fdb6695 100644 --- a/UI/SpecialVisualizations.ts +++ b/UI/SpecialVisualizations.ts @@ -1,409 +1,79 @@ -import { Store, Stores, UIEventSource } from "../Logic/UIEventSource" -import { VariableUiElement } from "./Base/VariableUIElement" -import LiveQueryHandler from "../Logic/Web/LiveQueryHandler" -import { ImageCarousel } from "./Image/ImageCarousel" import Combine from "./Base/Combine" -import { FixedUiElement } from "./Base/FixedUiElement" -import { ImageUploadFlow } from "./Image/ImageUploadFlow" -import ShareButton from "./BigComponents/ShareButton" -import Svg from "../Svg" -import ReviewElement from "./Reviews/ReviewElement" -import MangroveReviews from "../Logic/Web/MangroveReviews" -import Translations from "./i18n/Translations" -import ReviewForm from "./Reviews/ReviewForm" -import OpeningHoursVisualization from "./OpeningHours/OpeningHoursVisualization" +import {FixedUiElement} from "./Base/FixedUiElement" import BaseUIElement from "./BaseUIElement" import Title from "./Base/Title" import Table from "./Base/Table" -import Histogram from "./BigComponents/Histogram" -import Loc from "../Models/Loc" -import { Utils } from "../Utils" -import LayerConfig from "../Models/ThemeConfig/LayerConfig" -import StaticFeatureSource from "../Logic/FeatureSource/Sources/StaticFeatureSource" -import ShowDataMultiLayer from "./ShowDataLayer/ShowDataMultiLayer" -import Minimap from "./Base/Minimap" -import AllImageProviders from "../Logic/ImageProviders/AllImageProviders" -import WikipediaBox from "./Wikipedia/WikipediaBox" -import MultiApply from "./Popup/MultiApply" -import ShowDataLayer from "./ShowDataLayer/ShowDataLayer" -import { SubtleButton } from "./Base/SubtleButton" -import { DefaultGuiState } from "./DefaultGuiState" -import { GeoOperations } from "../Logic/GeoOperations" -import Hash from "../Logic/Web/Hash" -import FeaturePipelineState from "../Logic/State/FeaturePipelineState" -import { ConflateButton, ImportPointButton, ImportWayButton } from "./Popup/ImportButton" -import TagApplyButton from "./Popup/TagApplyButton" -import AutoApplyButton from "./Popup/AutoApplyButton" -import * as left_right_style_json from "../assets/layers/left_right_style/left_right_style.json" -import { OpenIdEditor, OpenJosm } from "./BigComponents/CopyrightPanel" -import Toggle from "./Input/Toggle" -import Img from "./Base/Img" -import NoteCommentElement from "./Popup/NoteCommentElement" -import ImgurUploader from "../Logic/ImageProviders/ImgurUploader" -import FileSelectorButton from "./Input/FileSelectorButton" -import { LoginToggle } from "./Popup/LoginButton" -import { SubstitutedTranslation } from "./SubstitutedTranslation" -import { TextField } from "./Input/TextField" -import Wikidata, { WikidataResponse } from "../Logic/Web/Wikidata" -import { Translation } from "./i18n/Translation" -import { AllTagsPanel } from "./AllTagsPanel" -import NearbyImages, { - NearbyImageOptions, - P4CPicture, - SelectOneNearbyImage, -} from "./Popup/NearbyImages" -import Lazy from "./Base/Lazy" -import ChangeTagAction from "../Logic/Osm/Actions/ChangeTagAction" -import { Tag } from "../Logic/Tags/Tag" -import { And } from "../Logic/Tags/And" -import { SaveButton } from "./Popup/SaveButton" -import { MapillaryLink } from "./BigComponents/MapillaryLink" -import { CheckBox } from "./Input/Checkboxes" -import Slider from "./Input/Slider" -import List from "./Base/List" -import StatisticsPanel from "./BigComponents/StatisticsPanel" -import { OsmFeature } from "../Models/OsmFeature" -import EditableTagRendering from "./Popup/EditableTagRendering" -import TagRenderingConfig from "../Models/ThemeConfig/TagRenderingConfig" -import { ProvidedImage } from "../Logic/ImageProviders/ImageProvider" -import PlantNetSpeciesSearch from "./BigComponents/PlantNetSpeciesSearch" - -export interface SpecialVisualization { - funcName: string - constr: ( - state: FeaturePipelineState, - tagSource: UIEventSource, - argument: string[], - guistate: DefaultGuiState - ) => BaseUIElement - docs: string | BaseUIElement - example?: string - args: { name: string; defaultValue?: string; doc: string; required?: false | boolean }[] - getLayerDependencies?: (argument: string[]) => string[] -} - -class CloseNoteButton implements SpecialVisualization { - public readonly funcName = "close_note" - public readonly docs = - "Button to close a note. A predifined text can be defined to close the note with. If the note is already closed, will show a small text." - public readonly args = [ - { - name: "text", - doc: "Text to show on this button", - required: true, - }, - { - name: "icon", - doc: "Icon to show", - defaultValue: "checkmark.svg", - }, - { - name: "idkey", - doc: "The property name where the ID of the note to close can be found", - defaultValue: "id", - }, - { - name: "comment", - doc: "Text to add onto the note when closing", - }, - { - name: "minZoom", - doc: "If set, only show the closenote button if zoomed in enough", - }, - { - name: "zoomButton", - doc: "Text to show if not zoomed in enough", - }, - ] - - public constr(state: FeaturePipelineState, tags, args): BaseUIElement { - const t = Translations.t.notes - - const params: { - text: string - icon: string - idkey: string - comment: string - minZoom: string - zoomButton: string - } = Utils.ParseVisArgs(this.args, args) - - let icon = Svg.checkmark_svg() - if (params.icon !== "checkmark.svg" && (args[2] ?? "") !== "") { - icon = new Img(args[1]) - } - let textToShow = t.closeNote - if ((params.text ?? "") !== "") { - textToShow = Translations.T(args[0]) - } - - let closeButton: BaseUIElement = new SubtleButton(icon, textToShow) - const isClosed = tags.map((tags) => (tags["closed_at"] ?? "") !== "") - closeButton.onClick(() => { - const id = tags.data[args[2] ?? "id"] - state.osmConnection.closeNote(id, args[3])?.then((_) => { - tags.data["closed_at"] = new Date().toISOString() - tags.ping() - }) - }) - - if ((params.minZoom ?? "") !== "" && !isNaN(Number(params.minZoom))) { - closeButton = new Toggle( - closeButton, - params.zoomButton ?? "", - state.locationControl.map((l) => l.zoom >= Number(params.minZoom)) - ) - } - - return new LoginToggle( - new Toggle( - t.isClosed.SetClass("thanks"), - closeButton, - - isClosed - ), - t.loginToClose, - state - ) - } -} - -class NearbyImageVis implements SpecialVisualization { - args: { name: string; defaultValue?: string; doc: string; required?: boolean }[] = [ - { - name: "mode", - defaultValue: "expandable", - doc: "Indicates how this component is initialized. Options are: \n\n- `open`: always show and load the pictures\n- `collapsable`: show the pictures, but a user can collapse them\n- `expandable`: shown by default; but a user can collapse them.", - }, - { - name: "mapillary", - defaultValue: "true", - doc: "If 'true', includes a link to mapillary on this location.", - }, - ] - docs = - "A component showing nearby images loaded from various online services such as Mapillary. In edit mode and when used on a feature, the user can select an image to add to the feature" - funcName = "nearby_images" - - constr( - state: FeaturePipelineState, - tagSource: UIEventSource, - args: string[], - guistate: DefaultGuiState - ): BaseUIElement { - const t = Translations.t.image.nearbyPictures - const mode: "open" | "expandable" | "collapsable" = args[0] - const feature = state.allElements.ContainingFeatures.get(tagSource.data.id) - const [lon, lat] = GeoOperations.centerpointCoordinates(feature) - const id: string = tagSource.data["id"] - const canBeEdited: boolean = !!id?.match("(node|way|relation)/-?[0-9]+") - const selectedImage = new UIEventSource(undefined) - - let saveButton: BaseUIElement = undefined - if (canBeEdited) { - const confirmText: BaseUIElement = new SubstitutedTranslation( - t.confirm, - tagSource, - state - ) - - const onSave = async () => { - console.log("Selected a picture...", selectedImage.data) - const osmTags = selectedImage.data.osmTags - const tags: Tag[] = [] - for (const key in osmTags) { - tags.push(new Tag(key, osmTags[key])) - } - await state?.changes?.applyAction( - new ChangeTagAction(id, new And(tags), tagSource.data, { - theme: state?.layoutToUse.id, - changeType: "link-image", - }) - ) - } - saveButton = new SaveButton( - selectedImage, - state.osmConnection, - confirmText, - t.noImageSelected - ) - .onClick(onSave) - .SetClass("flex justify-end") - } - - const nearby = new Lazy(() => { - const towardsCenter = new CheckBox(t.onlyTowards, false) - - const radiusValue = - state?.osmConnection?.GetPreference("nearby-images-radius", "300").sync( - (s) => Number(s), - [], - (i) => "" + i - ) ?? new UIEventSource(300) - - const radius = new Slider(25, 500, { - value: radiusValue, - step: 25, - }) - const alreadyInTheImage = AllImageProviders.LoadImagesFor(tagSource) - const options: NearbyImageOptions & { value } = { - lon, - lat, - searchRadius: 500, - shownRadius: radius.GetValue(), - value: selectedImage, - blacklist: alreadyInTheImage, - towardscenter: towardsCenter.GetValue(), - maxDaysOld: 365 * 5, - } - const slideshow = canBeEdited - ? new SelectOneNearbyImage(options, state) - : new NearbyImages(options, state) - const controls = new Combine([ - towardsCenter, - new Combine([ - new VariableUiElement( - radius.GetValue().map((radius) => t.withinRadius.Subs({ radius })) - ), - radius, - ]).SetClass("flex justify-between"), - ]).SetClass("flex flex-col") - return new Combine([ - slideshow, - controls, - saveButton, - new MapillaryLinkVis().constr(state, tagSource, []).SetClass("mt-6"), - ]) - }) - - let withEdit: BaseUIElement = nearby - if (canBeEdited) { - withEdit = new Combine([t.hasMatchingPicture, nearby]).SetClass("flex flex-col") - } - - if (mode === "open") { - return withEdit - } - const toggleState = new UIEventSource(mode === "collapsable") - return new Toggle( - new Combine([new Title(t.title), withEdit]), - new Title(t.browseNearby).onClick(() => toggleState.setData(true)), - toggleState - ) - } -} - -export class MapillaryLinkVis implements SpecialVisualization { - funcName = "mapillary_link" - docs = "Adds a button to open mapillary on the specified location" - args = [ - { - name: "zoom", - doc: "The startzoom of mapillary", - defaultValue: "18", - }, - ] - - public constr(state, tagsSource, args) { - const feat = state.allElements.ContainingFeatures.get(tagsSource.data.id) - const [lon, lat] = GeoOperations.centerpointCoordinates(feat) - let zoom = Number(args[0]) - if (isNaN(zoom)) { - zoom = 18 - } - return new MapillaryLink({ - locationControl: new UIEventSource({ - lat, - lon, - zoom, - }), - }) - } -} +import {SpecialVisualization} from "./SpecialVisualization"; +import {HistogramViz} from "./Popup/HistogramViz"; +import {StealViz} from "./Popup/StealViz"; +import {MinimapViz} from "./Popup/MinimapViz"; +import {SidedMinimap} from "./Popup/SidedMinimap"; +import {ShareLinkViz} from "./Popup/ShareLinkViz"; +import {UploadToOsmViz} from "./Popup/UploadToOsmViz"; +import {MultiApplyViz} from "./Popup/MultiApplyViz"; +import {ExportAsGpxViz} from "./Popup/ExportAsGpxViz"; +import {AddNoteCommentViz} from "./Popup/AddNoteCommentViz"; +import {PlantNetDetectionViz} from "./Popup/PlantNetDetectionViz"; +import {ConflateButton, ImportPointButton, ImportWayButton} from "./Popup/ImportButton"; +import TagApplyButton from "./Popup/TagApplyButton"; +import {CloseNoteButton} from "./Popup/CloseNoteButton"; +import {NearbyImageVis} from "./Popup/NearbyImageVis"; +import {MapillaryLinkVis} from "./Popup/MapillaryLinkVis"; +import {Stores, UIEventSource} from "../Logic/UIEventSource"; +import {AllTagsPanel} from "./AllTagsPanel"; +import AllImageProviders from "../Logic/ImageProviders/AllImageProviders"; +import {ImageCarousel} from "./Image/ImageCarousel"; +import {ImageUploadFlow} from "./Image/ImageUploadFlow"; +import {VariableUiElement} from "./Base/VariableUIElement"; +import {Utils} from "../Utils"; +import WikipediaBox from "./Wikipedia/WikipediaBox"; +import Wikidata, {WikidataResponse} from "../Logic/Web/Wikidata"; +import {Translation} from "./i18n/Translation"; +import Translations from "./i18n/Translations"; +import MangroveReviews from "../Logic/Web/MangroveReviews"; +import ReviewForm from "./Reviews/ReviewForm"; +import ReviewElement from "./Reviews/ReviewElement"; +import OpeningHoursVisualization from "./OpeningHours/OpeningHoursVisualization"; +import LiveQueryHandler from "../Logic/Web/LiveQueryHandler"; +import {SubtleButton} from "./Base/SubtleButton"; +import Svg from "../Svg"; +import {OpenIdEditor, OpenJosm} from "./BigComponents/CopyrightPanel"; +import Hash from "../Logic/Web/Hash"; +import NoteCommentElement from "./Popup/NoteCommentElement"; +import ImgurUploader from "../Logic/ImageProviders/ImgurUploader"; +import FileSelectorButton from "./Input/FileSelectorButton"; +import {LoginToggle} from "./Popup/LoginButton"; +import Toggle from "./Input/Toggle"; +import {SubstitutedTranslation} from "./SubstitutedTranslation"; +import List from "./Base/List"; +import {OsmFeature} from "../Models/OsmFeature"; +import LayerConfig from "../Models/ThemeConfig/LayerConfig"; +import {GeoOperations} from "../Logic/GeoOperations"; +import StatisticsPanel from "./BigComponents/StatisticsPanel"; +import AutoApplyButton from "./Popup/AutoApplyButton"; export default class SpecialVisualizations { - public static specialVisualizations: SpecialVisualization[] = SpecialVisualizations.init() + public static specialVisualizations: SpecialVisualization[] = SpecialVisualizations.initList(); - public static DocumentationFor(viz: string | SpecialVisualization): BaseUIElement | undefined { - if (typeof viz === "string") { - viz = SpecialVisualizations.specialVisualizations.find((sv) => sv.funcName === viz) - } - if (viz === undefined) { - return undefined - } - return new Combine([ - new Title(viz.funcName, 3), - viz.docs, - viz.args.length > 0 - ? new Table( - ["name", "default", "description"], - viz.args.map((arg) => { - let defaultArg = arg.defaultValue ?? "_undefined_" - if (defaultArg == "") { - defaultArg = "_empty string_" - } - return [arg.name, defaultArg, arg.doc] - }) - ) - : undefined, - new Title("Example usage of " + viz.funcName, 4), - new FixedUiElement( - viz.example ?? - "`{" + - viz.funcName + - "(" + - viz.args.map((arg) => arg.defaultValue).join(",") + - ")}`" - ).SetClass("literal-code"), - ]) - } - - public static HelpMessage() { - const helpTexts = SpecialVisualizations.specialVisualizations.map((viz) => - SpecialVisualizations.DocumentationFor(viz) - ) - - return new Combine([ - new Combine([ - new Title("Special tag renderings", 1), - - "In a tagrendering, some special values are substituted by an advanced UI-element. This allows advanced features and visualizations to be reused by custom themes or even to query third-party API's.", - "General usage is `{func_name()}`, `{func_name(arg, someotherarg)}` or `{func_name(args):cssStyle}`. Note that you _do not_ need to use quotes around your arguments, the comma is enough to separate them. This also implies you cannot use a comma in your args", - new Title("Using expanded syntax", 4), - `Instead of using \`{"render": {"en": "{some_special_visualisation(some_arg, some other really long message, more args)} , "nl": "{some_special_visualisation(some_arg, een boodschap in een andere taal, more args)}}\`, one can also write`, - new FixedUiElement( - JSON.stringify( - { - render: { - special: { - type: "some_special_visualisation", - before: { - en: "Some text to prefix before the special element (e.g. a title)", - nl: "Een tekst om voor het element te zetten (bv. een titel)", - }, - after: { - en: "Some text to put after the element, e.g. a footer", - }, - argname: "some_arg", - message: { - en: "some other really long message", - nl: "een boodschap in een andere taal", - }, - other_arg_name: "more args", - }, - }, - }, - null, - " " - ) - ).SetClass("code"), - ]).SetClass("flex flex-col"), - ...helpTexts, - ]).SetClass("flex flex-col") - } - - private static init() { + private static initList() : SpecialVisualization[] { const specialVisualizations: SpecialVisualization[] = [ + new HistogramViz(), + new StealViz(), + new MinimapViz(), + new SidedMinimap(), + new ShareLinkViz() , + new UploadToOsmViz(), + new MultiApplyViz(), + new ExportAsGpxViz(), + new AddNoteCommentViz(), + new PlantNetDetectionViz(), + new ImportPointButton(), + new ImportWayButton(), + new ConflateButton(), + new TagApplyButton(), + new CloseNoteButton(), + new NearbyImageVis(), + new MapillaryLinkVis(), { funcName: "all_tags", docs: "Prints all key-value pairs of the object - used for debugging", @@ -515,142 +185,6 @@ export default class SpecialVisualizations { }) ), }, - { - funcName: "minimap", - docs: "A small map showing the selected feature.", - args: [ - { - doc: "The (maximum) zoomlevel: the target zoomlevel after fitting the entire feature. The minimap will fit the entire feature, then zoom out to this zoom level. The higher, the more zoomed in with 1 being the entire world and 19 being really close", - name: "zoomlevel", - defaultValue: "18", - }, - { - doc: "(Matches all resting arguments) This argument should be the key of a property of the feature. The corresponding value is interpreted as either the id or the a list of ID's. The features with these ID's will be shown on this minimap. (Note: if the key is 'id', list interpration is disabled)", - name: "idKey", - defaultValue: "id", - }, - ], - example: - "`{minimap()}`, `{minimap(17, id, _list_of_embedded_feature_ids_calculated_by_calculated_tag):height:10rem; border: 2px solid black}`", - constr: (state, tagSource, args, _) => { - if (state === undefined) { - return undefined - } - const keys = [...args] - keys.splice(0, 1) - const featureStore = state.allElements.ContainingFeatures - const featuresToShow: Store<{ freshness: Date; feature: any }[]> = - tagSource.map((properties) => { - const features: { freshness: Date; feature: any }[] = [] - for (const key of keys) { - const value = properties[key] - if (value === undefined || value === null) { - continue - } - - let idList = [value] - if (key !== "id" && value.startsWith("[")) { - // This is a list of values - idList = JSON.parse(value) - } - - for (const id of idList) { - const feature = featureStore.get(id) - if (feature === undefined) { - console.warn("No feature found for id ", id) - continue - } - features.push({ - freshness: new Date(), - feature, - }) - } - } - return features - }) - const properties = tagSource.data - let zoom = 18 - if (args[0]) { - const parsed = Number(args[0]) - if (!isNaN(parsed) && parsed > 0 && parsed < 25) { - zoom = parsed - } - } - const locationSource = new UIEventSource({ - lat: Number(properties._lat), - lon: Number(properties._lon), - zoom: zoom, - }) - const minimap = Minimap.createMiniMap({ - background: state.backgroundLayer, - location: locationSource, - allowMoving: false, - }) - - locationSource.addCallback((loc) => { - if (loc.zoom > zoom) { - // We zoom back - locationSource.data.zoom = zoom - locationSource.ping() - } - }) - - new ShowDataMultiLayer({ - leafletMap: minimap["leafletMap"], - zoomToFeatures: true, - layers: state.filteredLayers, - features: new StaticFeatureSource(featuresToShow), - }) - - minimap.SetStyle("overflow: hidden; pointer-events: none;") - return minimap - }, - }, - { - funcName: "sided_minimap", - docs: "A small map showing _only one side_ the selected feature. *This features requires to have linerenderings with offset* as only linerenderings with a postive or negative offset will be shown. Note: in most cases, this map will be automatically introduced", - args: [ - { - doc: "The side to show, either `left` or `right`", - name: "side", - required: true, - }, - ], - example: "`{sided_minimap(left)}`", - constr: (state, tagSource, args) => { - const properties = tagSource.data - const locationSource = new UIEventSource({ - lat: Number(properties._lat), - lon: Number(properties._lon), - zoom: 18, - }) - const minimap = Minimap.createMiniMap({ - background: state.backgroundLayer, - location: locationSource, - allowMoving: false, - }) - const side = args[0] - const feature = state.allElements.ContainingFeatures.get(tagSource.data.id) - const copy = { ...feature } - copy.properties = { - id: side, - } - new ShowDataLayer({ - leafletMap: minimap["leafletMap"], - zoomToFeatures: true, - layerToShow: new LayerConfig( - left_right_style_json, - "all_known_layers", - true - ), - features: StaticFeatureSource.fromGeojson([copy]), - state, - }) - - minimap.SetStyle("overflow: hidden; pointer-events: none;") - return minimap - }, - }, { funcName: "reviews", docs: "Adds an overview of the mangrove-reviews of this object. Mangrove.Reviews needs - in order to identify the reviewed object - a coordinate and a name. By default, the name of the object is given, but this can be overwritten", @@ -750,121 +284,6 @@ export default class SpecialVisualizations { ) }, }, - { - funcName: "histogram", - docs: "Create a histogram for a list of given values, read from the properties.", - example: - "`{histogram('some_key')}` with properties being `{some_key: ['a','b','a','c']} to create a histogram", - args: [ - { - name: "key", - doc: "The key to be read and to generate a histogram from", - required: true, - }, - { - name: "title", - doc: "This text will be placed above the texts (in the first column of the visulasition)", - defaultValue: "", - }, - { - name: "countHeader", - doc: "This text will be placed above the bars", - defaultValue: "", - }, - { - name: "colors*", - doc: "(Matches all resting arguments - optional) Matches a regex onto a color value, e.g. `3[a-zA-Z+-]*:#33cc33`", - }, - ], - constr: (state, tagSource: UIEventSource, args: string[]) => { - let assignColors = undefined - if (args.length >= 3) { - const colors = [...args] - colors.splice(0, 3) - const mapping = colors.map((c) => { - const splitted = c.split(":") - const value = splitted.pop() - const regex = splitted.join(":") - return { regex: "^" + regex + "$", color: value } - }) - assignColors = (key) => { - for (const kv of mapping) { - if (key.match(kv.regex) !== null) { - return kv.color - } - } - return undefined - } - } - - const listSource: Store = tagSource.map((tags) => { - try { - const value = tags[args[0]] - if (value === "" || value === undefined) { - return undefined - } - return JSON.parse(value) - } catch (e) { - console.error( - "Could not load histogram: parsing of the list failed: ", - e - ) - return undefined - } - }) - return new Histogram(listSource, args[1], args[2], { - assignColor: assignColors, - }) - }, - }, - { - funcName: "share_link", - docs: "Creates a link that (attempts to) open the native 'share'-screen", - example: - "{share_link()} to share the current page, {share_link()} to share the given url", - args: [ - { - name: "url", - doc: "The url to share (default: current URL)", - }, - ], - constr: (state, tagSource: UIEventSource, args) => { - if (window.navigator.share) { - const generateShareData = () => { - const title = state?.layoutToUse?.title?.txt ?? "MapComplete" - - let matchingLayer: LayerConfig = state?.layoutToUse?.getMatchingLayer( - tagSource?.data - ) - let name = - matchingLayer?.title?.GetRenderValue(tagSource.data)?.txt ?? - tagSource.data?.name ?? - "POI" - if (name) { - name = `${name} (${title})` - } else { - name = title - } - let url = args[0] ?? "" - if (url === "") { - url = window.location.href - } - return { - title: name, - url: url, - text: state?.layoutToUse?.shortDescription?.txt ?? "MapComplete", - } - } - - return new ShareButton( - Svg.share_svg().SetClass("w-8 h-8"), - generateShareData - ) - } else { - return new FixedUiElement("") - } - }, - }, { funcName: "canonical", docs: "Converts a short, canonical value into the long, translated text including the unit. This only works if a `unit` is defined for the corresponding value. The unit specification will be included in the text. ", @@ -900,102 +319,6 @@ export default class SpecialVisualizations { ) }, }, - new ImportPointButton(), - new ImportWayButton(), - new ConflateButton(), - { - funcName: "multi_apply", - docs: "A button to apply the tagging of this object onto a list of other features. This is an advanced feature for which you'll need calculatedTags", - args: [ - { - name: "feature_ids", - doc: "A JSON-serialized list of IDs of features to apply the tagging on", - }, - { - name: "keys", - doc: "One key (or multiple keys, seperated by ';') of the attribute that should be copied onto the other features.", - required: true, - }, - { name: "text", doc: "The text to show on the button" }, - { - name: "autoapply", - doc: "A boolean indicating wether this tagging should be applied automatically if the relevant tags on this object are changed. A visual element indicating the multi_apply is still shown", - required: true, - }, - { - name: "overwrite", - doc: "If set to 'true', the tags on the other objects will always be overwritten. The default behaviour will be to only change the tags on other objects if they are either undefined or had the same value before the change", - required: true, - }, - ], - example: - "{multi_apply(_features_with_the_same_name_within_100m, name:etymology:wikidata;name:etymology, Apply etymology information on all nearby objects with the same name)}", - constr: (state, tagsSource, args) => { - const featureIdsKey = args[0] - const keysToApply = args[1].split(";") - const text = args[2] - const autoapply = args[3]?.toLowerCase() === "true" - const overwrite = args[4]?.toLowerCase() === "true" - const featureIds: Store = tagsSource.map((tags) => { - const ids = tags[featureIdsKey] - try { - if (ids === undefined) { - return [] - } - return JSON.parse(ids) - } catch (e) { - console.warn( - "Could not parse ", - ids, - "as JSON to extract IDS which should be shown on the map." - ) - return [] - } - }) - return new MultiApply({ - featureIds, - keysToApply, - text, - autoapply, - overwrite, - tagsSource, - state, - }) - }, - }, - new TagApplyButton(), - { - funcName: "export_as_gpx", - docs: "Exports the selected feature as GPX-file", - args: [], - constr: (state, tagSource) => { - const t = Translations.t.general.download - - return new SubtleButton( - Svg.download_ui(), - new Combine([ - t.downloadFeatureAsGpx.SetClass("font-bold text-lg"), - t.downloadGpxHelper.SetClass("subtle"), - ]).SetClass("flex flex-col") - ).onClick(() => { - console.log("Exporting as GPX!") - const tags = tagSource.data - const feature = state.allElements.ContainingFeatures.get(tags.id) - const matchingLayer = state?.layoutToUse?.getMatchingLayer(tags) - const gpx = GeoOperations.AsGpx(feature, matchingLayer) - const title = - matchingLayer.title?.GetRenderValue(tags)?.Subs(tags)?.txt ?? - "gpx_track" - Utils.offerContentsAsDownloadableFile( - gpx, - title + "_mapcomplete_export.gpx", - { - mimetype: "{gpx=application/gpx+xml}", - } - ) - }) - }, - }, { funcName: "export_as_geojson", docs: "Exports the selected feature as GeoJson-file", @@ -1043,7 +366,6 @@ export default class SpecialVisualizations { return new OpenJosm(state) }, }, - { funcName: "clear_location_history", docs: "A button to remove the travelled track information from the device", @@ -1058,113 +380,6 @@ export default class SpecialVisualizations { }) }, }, - new CloseNoteButton(), - { - funcName: "add_note_comment", - docs: "A textfield to add a comment to a node (with the option to close the note).", - args: [ - { - name: "Id-key", - doc: "The property name where the ID of the note to close can be found", - defaultValue: "id", - }, - ], - constr: (state, tags, args) => { - const t = Translations.t.notes - const textField = new TextField({ - placeholder: t.addCommentPlaceholder, - inputStyle: "width: 100%; height: 6rem;", - textAreaRows: 3, - htmlType: "area", - }) - textField.SetClass("rounded-l border border-grey") - const txt = textField.GetValue() - - const addCommentButton = new SubtleButton( - Svg.speech_bubble_svg().SetClass("max-h-7"), - t.addCommentPlaceholder - ).onClick(async () => { - const id = tags.data[args[1] ?? "id"] - - if ((txt.data ?? "") == "") { - return - } - - if (isClosed.data) { - await state.osmConnection.reopenNote(id, txt.data) - await state.osmConnection.closeNote(id) - } else { - await state.osmConnection.addCommentToNote(id, txt.data) - } - NoteCommentElement.addCommentTo(txt.data, tags, state) - txt.setData("") - }) - - const close = new SubtleButton( - Svg.resolved_svg().SetClass("max-h-7"), - new VariableUiElement( - txt.map((txt) => { - if (txt === undefined || txt === "") { - return t.closeNote - } - return t.addCommentAndClose - }) - ) - ).onClick(() => { - const id = tags.data[args[1] ?? "id"] - state.osmConnection.closeNote(id, txt.data).then((_) => { - tags.data["closed_at"] = new Date().toISOString() - tags.ping() - }) - }) - - const reopen = new SubtleButton( - Svg.note_svg().SetClass("max-h-7"), - new VariableUiElement( - txt.map((txt) => { - if (txt === undefined || txt === "") { - return t.reopenNote - } - return t.reopenNoteAndComment - }) - ) - ).onClick(() => { - const id = tags.data[args[1] ?? "id"] - state.osmConnection.reopenNote(id, txt.data).then((_) => { - tags.data["closed_at"] = undefined - tags.ping() - }) - }) - - const isClosed = tags.map((tags) => (tags["closed_at"] ?? "") !== "") - const stateButtons = new Toggle( - new Toggle(reopen, close, isClosed), - undefined, - state.osmConnection.isLoggedIn - ) - - return new LoginToggle( - new Combine([ - new Title(t.addAComment), - textField, - new Combine([ - stateButtons.SetClass("sm:mr-2"), - new Toggle( - addCommentButton, - new Combine([t.typeText]).SetClass( - "flex items-center h-full subtle" - ), - textField - .GetValue() - .map((t) => t !== undefined && t.length >= 1) - ).SetClass("sm:mr-2"), - ]).SetClass("sm:flex sm:justify-between sm:items-stretch"), - ]).SetClass("border-2 border-black rounded-xl p-4 block"), - t.loginToAddComment, - state - ) - }, - }, { funcName: "visualize_note_comments", docs: "Visualises the comments for notes", @@ -1267,8 +482,6 @@ export default class SpecialVisualizations { }) ), }, - new NearbyImageVis(), - new MapillaryLinkVis(), { funcName: "maproulette_task", args: [], @@ -1281,7 +494,7 @@ export default class SpecialVisualizations { ) ) - let details = new VariableUiElement( + return new VariableUiElement( challenge.map((challenge) => { let listItems: BaseUIElement[] = [] let title: BaseUIElement @@ -1305,7 +518,6 @@ export default class SpecialVisualizations { } }) ) - return details }, docs: "Show details of a MapRoulette task", }, @@ -1321,7 +533,7 @@ export default class SpecialVisualizations { element: OsmFeature layer: LayerConfig }[] - >([]) + >([]) function update() { const mapCenter = <[number, number]>[ @@ -1449,137 +661,95 @@ export default class SpecialVisualizations { ) }, }, - { - funcName: "steal", - docs: "Shows a tagRendering from a different object as if this was the object itself", - args: [ - { - name: "featureId", - doc: "The key of the attribute which contains the id of the feature from which to use the tags", - required: true, - }, - { - name: "tagRenderingId", - doc: "The layer-id and tagRenderingId to render. Can be multiple value if ';'-separated (in which case every value must also contain the layerId, e.g. `layerId.tagRendering0; layerId.tagRendering1`). Note: this can cause layer injection", - required: true, - }, - ], - constr(state, featureTags, args) { - const [featureIdKey, layerAndtagRenderingIds] = args - const tagRenderings: [LayerConfig, TagRenderingConfig][] = [] - for (const layerAndTagRenderingId of layerAndtagRenderingIds.split(";")) { - const [layerId, tagRenderingId] = layerAndTagRenderingId.trim().split(".") - const layer = state.layoutToUse.layers.find((l) => l.id === layerId) - const tagRendering = layer.tagRenderings.find( - (tr) => tr.id === tagRenderingId - ) - tagRenderings.push([layer, tagRendering]) - } - if (tagRenderings.length === 0) { - throw "Could not create stolen tagrenddering: tagRenderings not found" - } - return new VariableUiElement( - featureTags.map((tags) => { - const featureId = tags[featureIdKey] - if (featureId === undefined) { - return undefined - } - const otherTags = state.allElements.getEventSourceById(featureId) - const elements: BaseUIElement[] = [] - for (const [layer, tagRendering] of tagRenderings) { - const el = new EditableTagRendering( - otherTags, - tagRendering, - layer.units, - state, - {} - ) - elements.push(el) - } - if (elements.length === 1) { - return elements[0] - } - return new Combine(elements).SetClass("flex flex-col") - }) - ) - }, - getLayerDependencies(args): string[] { - const [_, tagRenderingId] = args - if (tagRenderingId.indexOf(".") < 0) { - throw "Error: argument 'layerId.tagRenderingId' of special visualisation 'steal' should contain a dot" - } - const [layerId, __] = tagRenderingId.split(".") - return [layerId] - }, - }, - { - funcName: "plantnet_detection", - docs: "Sends the images linked to the current object to plantnet.org and asks it what plant species is shown on it. The user can then select the correct species; the corresponding wikidata-identifier will then be added to the object (together with `source:species:wikidata=plantnet.org AI`). ", - args: [ - { - name: "image_key", - defaultValue: AllImageProviders.defaultKeys.join(","), - doc: "The keys given to the images, e.g. if image is given, the first picture URL will be added as image, the second as image:0, the third as image:1, etc... Multiple values are allowed if ';'-separated ", - }, - ], - constr: (state, tags, args) => { - let imagePrefixes: string[] = undefined - if (args.length > 0) { - imagePrefixes = [].concat(...args.map((a) => a.split(","))) - } - - const detect = new UIEventSource(false) - const toggle = new Toggle( - new Lazy(() => { - const allProvidedImages: Store = - AllImageProviders.LoadImagesFor(tags, imagePrefixes) - const allImages: Store = allProvidedImages.map((pi) => - pi.map((pi) => pi.url) - ) - return new PlantNetSpeciesSearch( - allImages, - async (selectedWikidata) => { - selectedWikidata = Wikidata.ExtractKey(selectedWikidata) - const change = new ChangeTagAction( - tags.data.id, - new And([ - new Tag("species:wikidata", selectedWikidata), - new Tag("source:species:wikidata", "PlantNet.org AI"), - ]), - tags.data, - { - theme: state.layoutToUse.id, - changeType: "plantnet-ai-detection", - } - ) - await state.changes.applyAction(change) - } - ) - }), - new SubtleButton( - undefined, - "Detect plant species with plantnet.org" - ).onClick(() => detect.setData(true)), - detect - ) - - return new Combine([ - toggle, - new Combine([ - Svg.plantnet_logo_svg().SetClass( - "w-10 h-10 p-1 mr-1 bg-white rounded-full" - ), - Translations.t.plantDetection.poweredByPlantnet, - ]).SetClass("flex p-2 bg-gray-200 rounded-xl self-end"), - ]).SetClass("flex flex-col") - }, - }, ] specialVisualizations.push(new AutoApplyButton(specialVisualizations)) + const invalid = specialVisualizations.map((sp,i) => ({sp, i})).filter(sp => sp.sp.funcName === undefined) + if(invalid.length > 0){ + throw "Invalid special visualisation found: funcName is undefined for "+invalid.map(sp => sp.i).join(", ")+". Did you perhaps type \n funcName: \"funcname\" // type declaration uses COLON\ninstead of:\n funcName = \"funcName\" // value definition uses EQUAL" + } + return specialVisualizations } + + public static DocumentationFor(viz: string | SpecialVisualization): BaseUIElement | undefined { + if (typeof viz === "string") { + viz = SpecialVisualizations.specialVisualizations.find((sv) => sv.funcName === viz) + } + if (viz === undefined) { + return undefined + } + return new Combine([ + new Title(viz.funcName, 3), + viz.docs, + viz.args.length > 0 + ? new Table( + ["name", "default", "description"], + viz.args.map((arg) => { + let defaultArg = arg.defaultValue ?? "_undefined_" + if (defaultArg == "") { + defaultArg = "_empty string_" + } + return [arg.name, defaultArg, arg.doc] + }) + ) + : undefined, + new Title("Example usage of " + viz.funcName, 4), + new FixedUiElement( + viz.example ?? + "`{" + + viz.funcName + + "(" + + viz.args.map((arg) => arg.defaultValue).join(",") + + ")}`" + ).SetClass("literal-code"), + ]) + } + + public static HelpMessage() { + const helpTexts = SpecialVisualizations.specialVisualizations.map((viz) => + SpecialVisualizations.DocumentationFor(viz) + ) + + return new Combine([ + new Combine([ + new Title("Special tag renderings", 1), + + "In a tagrendering, some special values are substituted by an advanced UI-element. This allows advanced features and visualizations to be reused by custom themes or even to query third-party API's.", + "General usage is `{func_name()}`, `{func_name(arg, someotherarg)}` or `{func_name(args):cssStyle}`. Note that you _do not_ need to use quotes around your arguments, the comma is enough to separate them. This also implies you cannot use a comma in your args", + new Title("Using expanded syntax", 4), + `Instead of using \`{"render": {"en": "{some_special_visualisation(some_arg, some other really long message, more args)} , "nl": "{some_special_visualisation(some_arg, een boodschap in een andere taal, more args)}}\`, one can also write`, + new FixedUiElement( + JSON.stringify( + { + render: { + special: { + type: "some_special_visualisation", + before: { + en: "Some text to prefix before the special element (e.g. a title)", + nl: "Een tekst om voor het element te zetten (bv. een titel)", + }, + after: { + en: "Some text to put after the element, e.g. a footer", + }, + argname: "some_arg", + message: { + en: "some other really long message", + nl: "een boodschap in een andere taal", + }, + other_arg_name: "more args", + }, + }, + }, + null, + " " + ) + ).SetClass("code"), + ]).SetClass("flex flex-col"), + ...helpTexts, + ]).SetClass("flex flex-col") + } } diff --git a/UI/SubstitutedTranslation.ts b/UI/SubstitutedTranslation.ts index da132496d..07c4731ad 100644 --- a/UI/SubstitutedTranslation.ts +++ b/UI/SubstitutedTranslation.ts @@ -2,7 +2,7 @@ import { UIEventSource } from "../Logic/UIEventSource" import { Translation } from "./i18n/Translation" import Locale from "./i18n/Locale" import { FixedUiElement } from "./Base/FixedUiElement" -import SpecialVisualizations, { SpecialVisualization } from "./SpecialVisualizations" +import SpecialVisualizations from "./SpecialVisualizations" import { Utils } from "../Utils" import { VariableUiElement } from "./Base/VariableUIElement" import Combine from "./Base/Combine" @@ -10,6 +10,7 @@ import BaseUIElement from "./BaseUIElement" import { DefaultGuiState } from "./DefaultGuiState" import FeaturePipelineState from "../Logic/State/FeaturePipelineState" import LinkToWeblate from "./Base/LinkToWeblate" +import {SpecialVisualization} from "./SpecialVisualization"; export class SubstitutedTranslation extends VariableUiElement { public constructor( diff --git a/Utils.ts b/Utils.ts index 8a169cd95..f708943c3 100644 --- a/Utils.ts +++ b/Utils.ts @@ -398,7 +398,7 @@ In the case that MapComplete is pointed to the testing grounds, the edit will be while (match) { const key = match[1] let v = tags === undefined ? undefined : tags[key] - if (v !== undefined) { + if (v !== undefined && v !== null) { if (v["toISOString"] != undefined) { // This is a date, probably the timestamp of the object // @ts-ignore diff --git a/assets/layers/gps_location/gps_location.json b/assets/layers/gps_location/gps_location.json index 7f4aaad3e..3e1a94f3a 100644 --- a/assets/layers/gps_location/gps_location.json +++ b/assets/layers/gps_location/gps_location.json @@ -11,7 +11,7 @@ "mapRendering": [ { "icon": { - "render":"crosshair:var(--catch-detail-color)", + "render": "crosshair:var(--catch-detail-color)", "mappings": [ { "if": "speed>2", @@ -22,12 +22,17 @@ "iconSize": "40,40,center", "rotation": { "render": "0deg", - "mappings": [{ - "if": { - "and":["speed>2","heading!=NaN"] - }, - "then": "{heading}deg" - }] + "mappings": [ + { + "if": { + "and": [ + "speed>2", + "heading!=NaN" + ] + }, + "then": "{heading}deg" + } + ] }, "location": [ "point", @@ -35,4 +40,4 @@ ] } ] -} +} \ No newline at end of file diff --git a/assets/layers/gps_location_history/gps_location_history.json b/assets/layers/gps_location_history/gps_location_history.json index 056ce5980..3e4f0f582 100644 --- a/assets/layers/gps_location_history/gps_location_history.json +++ b/assets/layers/gps_location_history/gps_location_history.json @@ -1,11 +1,22 @@ { "id": "gps_location_history", "description": "Meta layer which contains the previous locations of the user as single points. This is mainly for technical reasons, e.g. to keep match the distance to the modified object", - "minzoom": 0, + "minzoom": 1, + "name": null, "source": { "osmTags": "user:location=yes", "#": "Cache is disabled here as these points are kept seperately", "maxCacheAge": 0 }, - "mapRendering": null + "shownByDefault": false, + "mapRendering": [ + { + "location": [ + "point", + "centroid" + ], + "icon": "square:red", + "iconSize": "5,5,center" + } + ] } \ No newline at end of file diff --git a/assets/layers/gps_track/gps_track.json b/assets/layers/gps_track/gps_track.json index f64f0194d..458e046b4 100644 --- a/assets/layers/gps_track/gps_track.json +++ b/assets/layers/gps_track/gps_track.json @@ -1,6 +1,6 @@ { "id": "gps_track", - "description": "Meta layer showing the previous locations of the user as single line. Add this to your theme and override the icon to change the appearance of the current location.", + "description": "Meta layer showing the previous locations of the user as single line with controls, e.g. to erase, upload or download this track. Add this to your theme and override the maprendering to change the appearance of the travelled track.", "minzoom": 0, "source": { "osmTags": "id=location_track", @@ -22,6 +22,7 @@ }, "export_as_gpx", "export_as_geojson", + "{upload_to_osm()}", "minimap", { "id": "delete", diff --git a/assets/layers/map/map.json b/assets/layers/map/map.json index 8837c0290..3e53b2dff 100644 --- a/assets/layers/map/map.json +++ b/assets/layers/map/map.json @@ -270,4 +270,4 @@ } } ] -} +} \ No newline at end of file diff --git a/css/index-tailwind-output.css b/css/index-tailwind-output.css index a95f20575..3b599d2e1 100644 --- a/css/index-tailwind-output.css +++ b/css/index-tailwind-output.css @@ -728,6 +728,10 @@ video { margin: 0.25rem; } +.m-2 { + margin: 0.5rem; +} + .m-4 { margin: 1rem; } @@ -736,10 +740,6 @@ video { margin: 1.25rem; } -.m-2 { - margin: 0.5rem; -} - .m-0\.5 { margin: 0.125rem; } @@ -1052,6 +1052,10 @@ video { width: 2rem; } +.w-1\/3 { + width: 33.333333%; +} + .w-4 { width: 1rem; } @@ -1313,14 +1317,14 @@ video { border-radius: 9999px; } -.rounded-3xl { - border-radius: 1.5rem; -} - .rounded { border-radius: 0.25rem; } +.rounded-3xl { + border-radius: 1.5rem; +} + .rounded-md { border-radius: 0.375rem; } @@ -1342,14 +1346,14 @@ video { border-bottom-left-radius: 0.25rem; } -.border { - border-width: 1px; -} - .border-2 { border-width: 2px; } +.border { + border-width: 1px; +} + .border-4 { border-width: 4px; } diff --git a/index.ts b/index.ts index baad5d910..321b320ba 100644 --- a/index.ts +++ b/index.ts @@ -11,7 +11,6 @@ import ShowOverlayLayerImplementation from "./UI/ShowDataLayer/ShowOverlayLayerI import { DefaultGuiState } from "./UI/DefaultGuiState" import { QueryParameters } from "./Logic/Web/QueryParameters" import DashboardGui from "./UI/DashboardGui" -import StatisticsGUI from "./UI/StatisticsGUI" // Workaround for a stupid crash: inject some functions which would give stupid circular dependencies or crash the other nodejs scripts running from console MinimapImplementation.initialize() diff --git a/langs/en.json b/langs/en.json index 59fed3d5f..384da50b3 100644 --- a/langs/en.json +++ b/langs/en.json @@ -280,6 +280,32 @@ "skip": "Skip this question", "skippedQuestions": "Some questions are skipped", "testing": "Testing - changes won't be saved", + "uploadGpx": { + "choosePermission": "Choose below if your track should be shared:", + "confirm": "Confirm upload", + "intro0": "By uploading your track, OpenStreetMap.org will retain a full copy of the track.", + "intro1": "You will be able to download your track again and to load them into OpenStreetMap editing programs", + "meta": { + "descriptionIntro": "Optionally, you can enter a description of your trace:", + "descriptionPlaceHolder": "Enter a description of your trace", + "intro": "Add a title for your track:", + "title": "Title and description", + "titlePlaceholder": "Enter the title of your trace" + }, + "modes": { + "private": { + "docs": "The points of your track will be shared and aggregated among other tracks. The full track will be visible to you and you will be able to load it into other editing programs. OpenStreetMap.org retains a copy of your trace", + "name": "Anonymous" + }, + "public": { + "docs": "Your trace will be visible to everyone, both on your user profile and on the list of GPS-traces on openstreetmap.org", + "name": "Public" + } + }, + "title": "Upload your track to OpenStreetMap.org", + "uploadFinished": "Your track has been uploaded!", + "uploading": "Uploading your trace..." + }, "useSearch": "Use the search above to see presets", "useSearchForMore": "Use the search function to search within {total} more values....", "weekdays": { diff --git a/package.json b/package.json index 7d9460414..9375df9a7 100644 --- a/package.json +++ b/package.json @@ -45,7 +45,7 @@ "format": "npx prettier --write '**/*.ts'", "lint": "tslint --project . -c tslint.json '**.ts' ", "clean:tests": "(find . -type f -name \"*.doctest.ts\" | xargs rm)", - "clean": "rm -rf .cache/ && (find *.html | grep -v \"\\(404\\|index\\|land\\|test\\|preferences\\|customGenerator\\|professional\\|automaton\\|import_helper\\|import_viewer\\|theme\\).html\" | xargs rm) && (ls | grep \"^index_[a-zA-Z_-]\\+\\.ts$\" | xargs rm) && (ls | grep \".*.webmanifest$\" | grep -v \"manifest.webmanifest\" | xargs rm)", + "clean": "rm -rf .cache/ && (find *.html | grep -v \"^\\(404\\|index\\|land\\|test\\|preferences\\|customGenerator\\|professional\\|automaton\\|import_helper\\|import_viewer\\|theme\\).html\" | xargs rm) && (ls | grep \"^index_[a-zA-Z_-]\\+\\.ts$\" | xargs rm) && (ls | grep \".*.webmanifest$\" | grep -v \"manifest.webmanifest\" | xargs rm)", "generate:dependency-graph": "node_modules/.bin/depcruise --exclude \"^node_modules\" --output-type dot Logic/State/MapState.ts > dependencies.dot && dot dependencies.dot -T svg -o dependencies.svg && rm dependencies.dot", "script": "ts-node", "weblate-merge": "./scripts/automerge-translations.sh", diff --git a/test/UI/SpecialVisualisations.spec.ts b/test/UI/SpecialVisualisations.spec.ts index e5ac1c4a8..ff31bbf67 100644 --- a/test/UI/SpecialVisualisations.spec.ts +++ b/test/UI/SpecialVisualisations.spec.ts @@ -11,6 +11,11 @@ describe("SpecialVisualisations", () => { "type", "A special visualisation is not allowed to be named 'type', as this will conflict with the 'special'-blocks" ) + + if(special.args === undefined){ + throw "The field 'args' is undefined for special visualisation "+special.funcName + } + for (const arg of special.args) { expect(arg.name).not.eq( "type",