diff --git a/Docs/MapComplete-Auto_apply.gif b/Docs/MapComplete-Auto_apply.gif new file mode 100644 index 000000000..dc3b500e9 Binary files /dev/null and b/Docs/MapComplete-Auto_apply.gif differ diff --git a/Logic/ExtraFunctions.ts b/Logic/ExtraFunctions.ts index 6e8ca9bca..054603e52 100644 --- a/Logic/ExtraFunctions.ts +++ b/Logic/ExtraFunctions.ts @@ -134,6 +134,7 @@ class ClosestNObjectFunc implements ExtraFunction { "If a 'unique tag key' is given, the tag with this key will only appear once (e.g. if 'name' is given, all features will have a different name)" _args = ["list of features or layer name or '*' to get all features", "amount of features", "unique tag key (optional)", "maxDistanceInMeters (optional)"] + /** * Gets the closes N features, sorted by ascending distance. * @@ -164,8 +165,11 @@ class ClosestNObjectFunc implements ExtraFunction { const selfCenter = GeoOperations.centerpointCoordinates(feature) let closestFeatures: { feat: any, distance: number }[] = []; + for (const featureList of features) { + // Features is provided by 'getFeaturesWithin' which returns a list of lists of features, hence the double loop here for (const otherFeature of featureList) { + if (otherFeature === feature || otherFeature.properties.id === feature.properties.id) { continue; // We ignore self } @@ -187,6 +191,7 @@ class ClosestNObjectFunc implements ExtraFunction { } if (closestFeatures.length === 0) { + // This is the first matching feature we find - always add it closestFeatures.push({ feat: otherFeature, distance: distance @@ -194,6 +199,7 @@ class ClosestNObjectFunc implements ExtraFunction { continue; } + if (closestFeatures.length >= maxFeatures && closestFeatures[maxFeatures - 1].distance < distance) { // The last feature of the list (and thus the furthest away is still closer // No use for checking, as we already have plenty of features! @@ -257,6 +263,8 @@ class ClosestNObjectFunc implements ExtraFunction { } } + + } } return closestFeatures; diff --git a/Logic/FeatureSource/Sources/GeoJsonSource.ts b/Logic/FeatureSource/Sources/GeoJsonSource.ts index e2269d621..e22835808 100644 --- a/Logic/FeatureSource/Sources/GeoJsonSource.ts +++ b/Logic/FeatureSource/Sources/GeoJsonSource.ts @@ -126,7 +126,7 @@ export default class GeoJsonSource implements FeatureSourceForLayer, Tiled { eventSource.setData(eventSource.data.concat(newFeatures)) - }).catch(msg => console.error("Could not load geojon layer", url, "due to", msg)) + }).catch(msg => console.error("Could not load geojson layer", url, "due to", msg)) } } diff --git a/Logic/MetaTagging.ts b/Logic/MetaTagging.ts index 73342f964..0203aa561 100644 --- a/Logic/MetaTagging.ts +++ b/Logic/MetaTagging.ts @@ -107,51 +107,57 @@ export default class MetaTagging { } return atLeastOneFeatureChanged } - - - public static createFunctionsForFeature(layerId: string, calculatedTags: [string, string][]): ((feature: any) => void)[] { + public static createFunctionsForFeature(layerId: string, calculatedTags: [string, string, boolean][]): ((feature: any) => void)[] { const functions: ((feature: any) => void)[] = []; + for (const entry of calculatedTags) { const key = entry[0] const code = entry[1]; + const isStrict = entry[2] if (code === undefined) { continue; } - const func = new Function("feat", "return " + code + ";"); + const calculateAndAssign = (feat) => { + + try { + let result = new Function("feat", "return " + code + ";")(feat); + if (result === "") { + result === undefined + } + if (result !== undefined && typeof result !== "string") { + // Make sure it is a string! + result = JSON.stringify(result); + } + delete feat.properties[key] + feat.properties[key] = result; + return result; + }catch(e){ + if (MetaTagging.errorPrintCount < MetaTagging.stopErrorOutputAt) { + console.warn("Could not calculate a " + (isStrict ? "strict " : "") + " calculated tag for key " + key + " defined by " + code + " (in layer" + layerId + ") due to \n" + e + "\n. Are you the theme creator? Doublecheck your code. Note that the metatags might not be stable on new features", e, e.stack) + MetaTagging.errorPrintCount++; + if (MetaTagging.errorPrintCount == MetaTagging.stopErrorOutputAt) { + console.error("Got ", MetaTagging.stopErrorOutputAt, " errors calculating this metatagging - stopping output now") + } + } + } + } + + + if(isStrict){ + functions.push(calculateAndAssign) + continue + } + + // Lazy function const f = (feature: any) => { - - delete feature.properties[key] Object.defineProperty(feature.properties, key, { configurable: true, enumerable: false, // By setting this as not enumerable, the localTileSaver will _not_ calculate this get: function () { - try { - // Lazyness for the win! - let result = func(feature); - - if (result === "") { - result === undefined - } - if (result !== undefined && typeof result !== "string") { - // Make sure it is a string! - result = JSON.stringify(result); - } - delete feature.properties[key] - feature.properties[key] = result; - return result; - } catch (e) { - if (MetaTagging.errorPrintCount < MetaTagging.stopErrorOutputAt) { - console.warn("Could not calculate a calculated tag for key " + key + " defined by " + code + " (in layer" + layerId + ") due to \n" + e + "\n. Are you the theme creator? Doublecheck your code. Note that the metatags might not be stable on new features", e, e.stack) - MetaTagging.errorPrintCount++; - if (MetaTagging.errorPrintCount == MetaTagging.stopErrorOutputAt) { - console.error("Got ", MetaTagging.stopErrorOutputAt, " errors calculating this metatagging - stopping output now") - } - } - } - + return calculateAndAssign(feature) } }) } @@ -167,7 +173,7 @@ export default class MetaTagging { private static createRetaggingFunc(layer: LayerConfig): ((params: ExtraFuncParams, feature: any) => void) { - const calculatedTags: [string, string][] = layer.calculatedTags; + const calculatedTags: [string, string, boolean][] = layer.calculatedTags; if (calculatedTags === undefined || calculatedTags.length === 0) { return undefined; } diff --git a/Logic/Osm/Changes.ts b/Logic/Osm/Changes.ts index 41ff276e0..1a5de5781 100644 --- a/Logic/Osm/Changes.ts +++ b/Logic/Osm/Changes.ts @@ -98,7 +98,7 @@ export class Changes { * Uploads all the pending changes in one go. * Triggered by the 'PendingChangeUploader'-actor in Actors */ - public flushChanges(flushreason: string = undefined) { + public async flushChanges(flushreason: string = undefined) : Promise{ if (this.pendingChanges.data.length === 0) { return; } @@ -108,16 +108,14 @@ export class Changes { } console.log("Uploading changes due to: ", flushreason) this.isUploading.setData(true) - - this.flushChangesAsync() - .then(_ => { - this.isUploading.setData(false) - console.log("Changes flushed!"); - }) - .catch(e => { - this.isUploading.setData(false) - console.error("Flushing changes failed due to", e); - }) + try { + const csNumber = await this.flushChangesAsync() + this.isUploading.setData(false) + console.log("Changes flushed!"); + } catch (e) { + this.isUploading.setData(false) + console.error("Flushing changes failed due to", e); + } } private calculateDistanceToChanges(change: OsmChangeAction, changeDescriptions: ChangeDescription[]) { diff --git a/Logic/State/MapState.ts b/Logic/State/MapState.ts index 7fc59e394..7bcdbada6 100644 --- a/Logic/State/MapState.ts +++ b/Logic/State/MapState.ts @@ -17,7 +17,6 @@ import {FeatureSourceForLayer, Tiled} from "../FeatureSource/FeatureSource"; import SimpleFeatureSource from "../FeatureSource/Sources/SimpleFeatureSource"; import {LocalStorageSource} from "../Web/LocalStorageSource"; import {GeoOperations} from "../GeoOperations"; -import StaticFeatureSource from "../FeatureSource/Sources/StaticFeatureSource"; /** * Contains all the leaflet-map related state @@ -186,6 +185,7 @@ export default class MapState extends UserRelatedState { let i = 0 + const self = this; const features : UIEventSource<{ feature: any, freshness: Date }[]>= this.currentBounds.map(bounds => { if(bounds === undefined){ return [] @@ -197,7 +197,8 @@ export default class MapState extends UserRelatedState { type: "Feature", properties:{ id:"current_view-"+i, - "current_view":"yes" + "current_view":"yes", + "zoom": ""+self.locationControl.data.zoom }, geometry:{ type:"Polygon", diff --git a/Models/ThemeConfig/Json/LayerConfigJson.ts b/Models/ThemeConfig/Json/LayerConfigJson.ts index 06c94304f..f570d627c 100644 --- a/Models/ThemeConfig/Json/LayerConfigJson.ts +++ b/Models/ThemeConfig/Json/LayerConfigJson.ts @@ -82,6 +82,15 @@ export interface LayerConfigJson { * "_max_overlap_ratio=Number(feat._max_overlap_m2)/feat.area * ] * + * The specified tags are evaluated lazily. E.g. if a calculated tag is only used in the popup (e.g. the number of nearby features), + * the expensive calculation will only be performed then for that feature. This avoids clogging up the contributors PC when all features are loaded. + * + * If a tag has to be evaluated strictly, use ':=' instead: + * + * [ + * "_some_key:=some_javascript_expression" + * ] + * */ calculatedTags?: string[]; diff --git a/Models/ThemeConfig/LayerConfig.ts b/Models/ThemeConfig/LayerConfig.ts index e4cab1c86..bad7871df 100644 --- a/Models/ThemeConfig/LayerConfig.ts +++ b/Models/ThemeConfig/LayerConfig.ts @@ -30,7 +30,7 @@ export default class LayerConfig extends WithContextLoader { public readonly name: Translation; public readonly description: Translation; public readonly source: SourceConfig; - public readonly calculatedTags: [string, string][]; + public readonly calculatedTags: [string, string, boolean][]; public readonly doNotDownload: boolean; public readonly passAllFeatures: boolean; public readonly isShown: TagRenderingConfig; @@ -130,7 +130,11 @@ export default class LayerConfig extends WithContextLoader { this.calculatedTags = []; for (const kv of json.calculatedTags) { const index = kv.indexOf("="); - const key = kv.substring(0, index); + let key = kv.substring(0, index); + const isStrict = key.endsWith(':') + if(isStrict){ + key = key.substr(0, key.length - 1) + } const code = kv.substring(index + 1); try { @@ -140,7 +144,7 @@ export default class LayerConfig extends WithContextLoader { } - this.calculatedTags.push([key, code]); + this.calculatedTags.push([key, code, isStrict]); } } diff --git a/UI/Base/Minimap.ts b/UI/Base/Minimap.ts index d4eaf6b51..c55dd3549 100644 --- a/UI/Base/Minimap.ts +++ b/UI/Base/Minimap.ts @@ -37,5 +37,9 @@ export default class Minimap { public static createMiniMap: (options: MinimapOptions) => (BaseUIElement & MinimapObj) = (_) => { throw "CreateMinimap hasn't been initialized yet. Please call MinimapImplementation.initialize()" } + + private constructor() { + } + } \ No newline at end of file diff --git a/UI/BigComponents/LeftControls.ts b/UI/BigComponents/LeftControls.ts index f8d6784af..4b0f56aa9 100644 --- a/UI/BigComponents/LeftControls.ts +++ b/UI/BigComponents/LeftControls.ts @@ -72,6 +72,7 @@ export default class LeftControls extends Combine { return new Lazy(() => { const tagsSource= state.allElements.getEventSourceById(feature.properties.id) return new FeatureInfoBox(tagsSource, currentViewFL.layerDef, "currentview", guiState.currentViewControlIsOpened) + .SetClass("md:floating-element-width") }) })) @@ -94,7 +95,7 @@ export default class LeftControls extends Combine { const toggledDownload = new Toggle( new AllDownloads( guiState.downloadControlIsOpened - ).SetClass("block p-1 rounded-full"), + ).SetClass("block p-1 rounded-full md:floating-element-width"), new MapControlButton(Svg.download_svg()) .onClick(() => guiState.downloadControlIsOpened.setData(true)), guiState.downloadControlIsOpened @@ -116,7 +117,7 @@ export default class LeftControls extends Combine { ), "filters", guiState.filterViewIsOpened - ).SetClass("rounded-lg"), + ).SetClass("rounded-lg md:floating-element-width"), new MapControlButton(Svg.filter_svg()) .onClick(() => guiState.filterViewIsOpened.setData(true)), guiState.filterViewIsOpened diff --git a/UI/Popup/AutoApplyButton.ts b/UI/Popup/AutoApplyButton.ts new file mode 100644 index 000000000..034485f52 --- /dev/null +++ b/UI/Popup/AutoApplyButton.ts @@ -0,0 +1,182 @@ +import {SpecialVisualization} from "../SpecialVisualizations"; +import FeaturePipelineState from "../../Logic/State/FeaturePipelineState"; +import BaseUIElement from "../BaseUIElement"; +import {UIEventSource} from "../../Logic/UIEventSource"; +import {DefaultGuiState} from "../DefaultGuiState"; +import {SubtleButton} from "../Base/SubtleButton"; +import Img from "../Base/Img"; +import {FixedUiElement} from "../Base/FixedUiElement"; +import Combine from "../Base/Combine"; +import Link from "../Base/Link"; +import {SubstitutedTranslation} from "../SubstitutedTranslation"; +import {Utils} from "../../Utils"; +import Minimap from "../Base/Minimap"; +import ShowDataLayer from "../ShowDataLayer/ShowDataLayer"; +import StaticFeatureSource from "../../Logic/FeatureSource/Sources/StaticFeatureSource"; +import {VariableUiElement} from "../Base/VariableUIElement"; +import Loading from "../Base/Loading"; +import {OsmConnection} from "../../Logic/Osm/OsmConnection"; +import Translations from "../i18n/Translations"; + +export interface AutoAction extends SpecialVisualization { + supportsAutoAction: boolean + + applyActionOn(state: FeaturePipelineState, tagSource: UIEventSource, argument: string[]): Promise +} + +export default class AutoApplyButton implements SpecialVisualization { + public readonly docs: string; + public readonly funcName: string = "auto_apply"; + public readonly args: { name: string; defaultValue?: string; doc: string }[] = [ + { + name: "target_layer", + doc: "The layer that the target features will reside in" + }, + { + name: "target_feature_ids", + doc: "The key, of which the value contains a list of ids" + }, + { + name: "tag_rendering_id", + doc: "The ID of the tagRendering containing the autoAction. This tagrendering will be calculated. The embedded actions will be executed" + }, + { + name: "text", + doc: "The text to show on the button" + }, + { + name: "icon", + doc: "The icon to show on the button", + defaultValue: "./assets/svg/robot.svg" + } + ]; + + constructor(allSpecialVisualisations: SpecialVisualization[]) { + this.docs = AutoApplyButton.generateDocs(allSpecialVisualisations.filter(sv => sv["supportsAutoAction"] === true).map(sv => sv.funcName)) + } + + constr(state: FeaturePipelineState, tagSource: UIEventSource, argument: string[], guistate: DefaultGuiState): BaseUIElement { + + if (!state.layoutToUse.official && !(state.featureSwitchIsTesting.data || state.osmConnection._oauth_config.url === OsmConnection.oauth_configs["osm-test"].url)) { + const t = Translations.t.general.add.import; + return new Combine([new FixedUiElement("The auto-apply button is only available in official themes (or in testing mode)").SetClass("alert"), t.howToTest]) + } + + const to_parse = tagSource.data[argument[1]] + if (to_parse === undefined) { + return new Loading("Gathering which elements support auto-apply... ") + } + try { + + + const target_layer_id = argument[0] + const target_feature_ids = JSON.parse(to_parse) + + if(target_feature_ids.length === 0){ + return new FixedUiElement("No elements found to perform action") + } + + const targetTagRendering = argument[2] + const text = argument[3] + const icon = argument[4] + + const layer = state.filteredLayers.data.filter(l => l.layerDef.id === target_layer_id)[0] + + const tagRenderingConfig = layer.layerDef.tagRenderings.filter(tr => tr.id === targetTagRendering)[0] + + if (tagRenderingConfig === undefined) { + return new FixedUiElement("Target tagrendering " + targetTagRendering + " not found").SetClass("alert") + } + + const buttonState = new UIEventSource<"idle" | "running" | "done" | {error: string}>("idle") + + const button = new SubtleButton( + new Img(icon), + text + ).onClick(async () => { + buttonState.setData("running") + try { + + + for (const targetFeatureId of target_feature_ids) { + const featureTags = state.allElements.getEventSourceById(targetFeatureId) + const rendering = tagRenderingConfig.GetRenderValue(featureTags.data).txt + const specialRenderings = Utils.NoNull(SubstitutedTranslation.ExtractSpecialComponents(rendering) + .map(x => x.special)) + .filter(v => v.func["supportsAutoAction"] === true) + + for (const specialRendering of specialRenderings) { + const action = specialRendering.func + await action.applyActionOn(state, featureTags, specialRendering.args) + } + } + console.log("Flushing changes...") + await state.changes.flushChanges("Auto button") + buttonState.setData("done") + } catch (e) { + console.error("Error while running autoApply: ", e) + buttonState.setData({error: e}) + } + }); + + const explanation = new Combine(["The following objects will be updated: ", + ...target_feature_ids.map(id => new Combine([new Link(id, "https:/ /openstreetmap.org/" + id, true), ", "]))]).SetClass("subtle") + + const previewMap = Minimap.createMiniMap({ + allowMoving: false, + background: state.backgroundLayer, + addLayerControl: true, + }).SetClass("h-48") + + const features = target_feature_ids.map(id => state.allElements.ContainingFeatures.get(id)) + + new ShowDataLayer({ + leafletMap: previewMap.leafletMap, + enablePopups: false, + zoomToFeatures: true, + features: new StaticFeatureSource(features, false), + allElements: state.allElements, + layerToShow: layer.layerDef, + }) + + + return new VariableUiElement(buttonState.map( + st => { + if (st === "idle") { + return new Combine([button, previewMap, explanation]); + } + if (st === "done") { + return new FixedUiElement("All done!").SetClass("thanks") + } + if (st === "running") { + return new Loading("Applying changes...") + } + const error =st.error + return new Combine([new FixedUiElement("Something went wrong...").SetClass("alert"), new FixedUiElement(error).SetClass("subtle")]).SetClass("flex flex-col") + } + )) + + + } catch (e) { + console.log("To parse is", to_parse) + return new FixedUiElement("Could not generate a auto_apply-button for key " + argument[0] + " due to " + e).SetClass("alert") + } + } + + getLayerDependencies(args: string[]): string[] { + return [args[0]] + } + + private static generateDocs(supportedActions: string[]) { + return [ + "A button to run many actions for many features at once.\n", + "To effectively use this button, you'll need some ingredients:\n" + + "- A target layer with features for which an action is defined in a tag rendering. The following special visualisations support an autoAction: " + supportedActions.join(", "), + "- A host feature to place the auto-action on. This can be a big outline (such as a city). Another good option for this is the [current_view](./BuiltinLayers.md#current_view)", + "- Then, use a calculated tag on the host feature to determine the overlapping object ids", + "- At last, add this component" + ].join("\n") + } + + +} \ No newline at end of file diff --git a/UI/Popup/ImportButton.ts b/UI/Popup/ImportButton.ts index 53567668c..88c862cbc 100644 --- a/UI/Popup/ImportButton.ts +++ b/UI/Popup/ImportButton.ts @@ -34,6 +34,7 @@ import {And} from "../../Logic/Tags/And"; import ReplaceGeometryAction from "../../Logic/Osm/Actions/ReplaceGeometryAction"; import CreateMultiPolygonWithPointReuseAction from "../../Logic/Osm/Actions/CreateMultiPolygonWithPointReuseAction"; import {Tag} from "../../Logic/Tags/Tag"; +import TagApplyButton from "./TagApplyButton"; abstract class AbstractImportButton implements SpecialVisualizations { @@ -131,7 +132,7 @@ ${Utils.special_visualizations_importRequirementDocs} // Explanation of the tags that will be applied onto the imported/conflated object - const newTags = SpecialVisualizations.generateTagsToApply(args.tags, tagSource) + const newTags = TagApplyButton.generateTagsToApply(args.tags, tagSource) const appliedTags = new Toggle( new VariableUiElement( newTags.map(tgs => { @@ -198,7 +199,7 @@ ${Utils.special_visualizations_importRequirementDocs} private parseArgs(argsRaw: string[], originalFeatureTags: UIEventSource): { minzoom: string, max_snap_distance: string, snap_onto_layers: string, icon: string, text: string, tags: string, targetLayer: string, newTags: UIEventSource } { const baseArgs = Utils.ParseVisArgs(this.args, argsRaw) if (originalFeatureTags !== undefined) { - baseArgs["newTags"] = SpecialVisualizations.generateTagsToApply(baseArgs.tags, originalFeatureTags) + baseArgs["newTags"] = TagApplyButton.generateTagsToApply(baseArgs.tags, originalFeatureTags) } return baseArgs } diff --git a/UI/Popup/TagApplyButton.ts b/UI/Popup/TagApplyButton.ts new file mode 100644 index 000000000..fd4751fbf --- /dev/null +++ b/UI/Popup/TagApplyButton.ts @@ -0,0 +1,136 @@ +import {AutoAction} from "./AutoApplyButton"; +import Translations from "../i18n/Translations"; +import {VariableUiElement} from "../Base/VariableUIElement"; +import BaseUIElement from "../BaseUIElement"; +import {FixedUiElement} from "../Base/FixedUiElement"; +import {UIEventSource} from "../../Logic/UIEventSource"; +import {SubtleButton} from "../Base/SubtleButton"; +import Combine from "../Base/Combine"; +import ChangeTagAction from "../../Logic/Osm/Actions/ChangeTagAction"; +import {And} from "../../Logic/Tags/And"; +import Toggle from "../Input/Toggle"; +import {Utils} from "../../Utils"; +import {Tag} from "../../Logic/Tags/Tag"; +import FeaturePipelineState from "../../Logic/State/FeaturePipelineState"; + +export default class TagApplyButton implements AutoAction { + 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" + Utils.Special_visualizations_tagsToApplyHelpText; + public readonly supportsAutoAction = true; + public readonly args = [ + { + name: "tags_to_apply", + doc: "A specification of the tags to apply" + }, + { + name: "message", + doc: "The text to show to the contributor" + }, + { + name: "image", + doc: "An image to show to the contributor on the button" + }, + { + name: "id_of_object_to_apply_this_one", + defaultValue: undefined, + doc: "If specified, applies the the tags onto _another_ object. The id will be read from properties[id_of_object_to_apply_this_one] of the selected object. The tags are still calculated based on the tags of the _selected_ element" + } + ]; + + public static generateTagsToApply(spec: string, tagSource: UIEventSource): UIEventSource { + + const tgsSpec = spec.split(";").map(spec => { + const kv = spec.split("=").map(s => s.trim()); + if (kv.length != 2) { + throw "Invalid key spec: multiple '=' found in " + spec + } + return kv + }) + + for (const spec of tgsSpec) { + if (spec[0].endsWith(':')) { + throw "A tag specification for import or apply ends with ':'. The theme author probably wrote key:=otherkey instead of key=$otherkey" + } + } + + return tagSource.map(tags => { + const newTags: Tag [] = [] + for (const [key, value] of tgsSpec) { + if (value.indexOf('$') >= 0) { + + let parts = value.split("$") + // THe first of the split won't start with a '$', so no substitution needed + let actualValue = parts[0] + parts.shift() + + for (const part of parts) { + const [_, varName, leftOver] = part.match(/([a-zA-Z0-9_:]*)(.*)/) + actualValue += (tags[varName] ?? "") + leftOver + } + newTags.push(new Tag(key, actualValue)) + } else { + newTags.push(new Tag(key, value)) + } + } + return newTags + }) + + } + + public readonly example = "`{tag_apply(survey_date=$_now:date, Surveyed today!)}`, `{tag_apply(addr:street=$addr:street, Apply the address, apply_icon.svg, _closest_osm_id)"; + + async applyActionOn(state: FeaturePipelineState, tags: UIEventSource, args: string[]) : Promise{ + const tagsToApply = TagApplyButton.generateTagsToApply(args[0], tags) + const targetIdKey = args[3] + + const targetId = tags.data[targetIdKey] ?? tags.data.id + const changeAction = new ChangeTagAction(targetId, + new And(tagsToApply.data), + tags.data, // We pass in the tags of the selected element, not the tags of the target element! + { + theme: state.layoutToUse.id, + changeType: "answer" + } + ) + await state.changes.applyAction(changeAction) + } + + public constr(state: FeaturePipelineState, tags: UIEventSource, args: string[]): BaseUIElement { + const tagsToApply = TagApplyButton.generateTagsToApply(args[0], tags) + const msg = args[1] + let image = args[2]?.trim() + if (image === "" || image === "undefined") { + image = undefined + } + const targetIdKey = args[3] + const t = Translations.t.general.apply_button + + const tagsExplanation = new VariableUiElement(tagsToApply.map(tagsToApply => { + const tagsStr = tagsToApply.map(t => t.asHumanString(false, true)).join("&"); + let el: BaseUIElement = new FixedUiElement(tagsStr) + if (targetIdKey !== undefined) { + const targetId = tags.data[targetIdKey] ?? tags.data.id + el = t.appliedOnAnotherObject.Subs({tags: tagsStr, id: targetId}) + } + return el; + } + )).SetClass("subtle") + const self = this + const applied = new UIEventSource(false) + const applyButton = new SubtleButton(image, new Combine([msg, tagsExplanation]).SetClass("flex flex-col")) + .onClick(() => { + self.applyActionOn(state, tags, args) + applied.setData(true) + }) + + + return new Toggle( + new Toggle( + t.isApplied.SetClass("thanks"), + applyButton, + applied + ), + undefined, state.osmConnection.isLoggedIn) + } +} + \ No newline at end of file diff --git a/UI/SpecialVisualizations.ts b/UI/SpecialVisualizations.ts index 7ffdae034..e7d098da0 100644 --- a/UI/SpecialVisualizations.ts +++ b/UI/SpecialVisualizations.ts @@ -20,7 +20,6 @@ import Histogram from "./BigComponents/Histogram"; import Loc from "../Models/Loc"; import {Utils} from "../Utils"; import LayerConfig from "../Models/ThemeConfig/LayerConfig"; -import {Tag} from "../Logic/Tags/Tag"; import StaticFeatureSource from "../Logic/FeatureSource/Sources/StaticFeatureSource"; import ShowDataMultiLayer from "./ShowDataLayer/ShowDataMultiLayer"; import Minimap from "./Base/Minimap"; @@ -31,14 +30,13 @@ import MultiApply from "./Popup/MultiApply"; import AllKnownLayers from "../Customizations/AllKnownLayers"; import ShowDataLayer from "./ShowDataLayer/ShowDataLayer"; import {SubtleButton} from "./Base/SubtleButton"; -import ChangeTagAction from "../Logic/Osm/Actions/ChangeTagAction"; -import {And} from "../Logic/Tags/And"; -import Toggle from "./Input/Toggle"; 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"; export interface SpecialVisualization { funcName: string, @@ -51,639 +49,538 @@ export interface SpecialVisualization { export default class SpecialVisualizations { - static tagsToApplyHelpText = Utils.Special_visualizations_tagsToApplyHelpText - public static specialVisualizations: SpecialVisualization[] = - [ - { - funcName: "all_tags", - docs: "Prints all key-value pairs of the object - used for debugging", - args: [], - constr: ((state: State, tags: UIEventSource) => { - const calculatedTags = [].concat( - SimpleMetaTagger.lazyTags, - ...state.layoutToUse.layers.map(l => l.calculatedTags?.map(c => c[0]) ?? [])) - return new VariableUiElement(tags.map(tags => { - const parts = []; - for (const key in tags) { - if (!tags.hasOwnProperty(key)) { - continue + public static specialVisualizations = SpecialVisualizations.init() + + + private static init(){ + const specialVisualizations: SpecialVisualization[] = + [ + { + funcName: "all_tags", + docs: "Prints all key-value pairs of the object - used for debugging", + args: [], + constr: ((state: State, tags: UIEventSource) => { + const calculatedTags = [].concat( + SimpleMetaTagger.lazyTags, + ...state.layoutToUse.layers.map(l => l.calculatedTags?.map(c => c[0]) ?? [])) + return new VariableUiElement(tags.map(tags => { + const parts = []; + for (const key in tags) { + if (!tags.hasOwnProperty(key)) { + continue + } + let v = tags[key] + if (v === "") { + v = "empty string" + } + parts.push([key, v ?? "undefined"]); } - let v = tags[key] - if (v === "") { - v = "empty string" + + for (const key of calculatedTags) { + const value = tags[key] + if (value === undefined) { + continue + } + parts.push(["" + key + "", value]) } - parts.push([key, v ?? "undefined"]); + + return new Table( + ["key", "value"], + parts + ) + })).SetStyle("border: 1px solid black; border-radius: 1em;padding:1em;display:block;") + }) + }, + { + funcName: "image_carousel", + docs: "Creates an image carousel for the given sources. An attempt will be made to guess what source is used. Supported: Wikidata identifiers, Wikipedia pages, Wikimedia categories, IMGUR (with attribution, direct links)", + args: [{ + name: "image key/prefix (multiple values allowed if comma-seperated)", + 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... " + }], + constr: (state: State, tags, args) => { + let imagePrefixes: string[] = undefined; + if (args.length > 0) { + imagePrefixes = [].concat(...args.map(a => a.split(","))); } - - for (const key of calculatedTags) { - const value = tags[key] - if (value === undefined) { - continue - } - parts.push(["" + key + "", value]) + return new ImageCarousel(AllImageProviders.LoadImagesFor(tags, imagePrefixes), tags, imagePrefixes); + } + }, + { + funcName: "image_upload", + docs: "Creates a button where a user can upload an image to IMGUR", + args: [{ + name: "image-key", + doc: "Image tag to add the URL to (or image-tag:0, image-tag:1 when multiple images are added)", + defaultValue: "image" + }, { + name: "label", + doc: "The text to show on the button", + defaultValue: "Add image" + }], + constr: (state: State, tags, args) => { + return new ImageUploadFlow(tags, args[0], args[1]) + } + }, + { + funcName: "wikipedia", + docs: "A box showing the corresponding wikipedia article - based on the wikidata tag", + args: [ + { + name: "keyToShowWikipediaFor", + doc: "Use the wikidata entry from this key to show the wikipedia article for", + defaultValue: "wikidata" } - - return new Table( - ["key", "value"], - parts - ) - })).SetStyle("border: 1px solid black; border-radius: 1em;padding:1em;display:block;") - }) - }, - { - funcName: "image_carousel", - docs: "Creates an image carousel for the given sources. An attempt will be made to guess what source is used. Supported: Wikidata identifiers, Wikipedia pages, Wikimedia categories, IMGUR (with attribution, direct links)", - args: [{ - name: "image key/prefix (multiple values allowed if comma-seperated)", - 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... " - }], - constr: (state: State, tags, args) => { - let imagePrefixes: string[] = undefined; - if (args.length > 0) { - imagePrefixes = [].concat(...args.map(a => a.split(","))); - } - return new ImageCarousel(AllImageProviders.LoadImagesFor(tags, imagePrefixes), tags, imagePrefixes); - } - }, - { - funcName: "image_upload", - docs: "Creates a button where a user can upload an image to IMGUR", - args: [{ - name: "image-key", - doc: "Image tag to add the URL to (or image-tag:0, image-tag:1 when multiple images are added)", - defaultValue: "image" - }, { - name: "label", - doc: "The text to show on the button", - defaultValue: "Add image" - }], - constr: (state: State, tags, args) => { - return new ImageUploadFlow(tags, args[0], args[1]) - } - }, - { - funcName: "wikipedia", - docs: "A box showing the corresponding wikipedia article - based on the wikidata tag", - args: [ - { - name: "keyToShowWikipediaFor", - doc: "Use the wikidata entry from this key to show the wikipedia article for", - defaultValue: "wikidata" - } - ], - example: "`{wikipedia()}` is a basic example, `{wikipedia(name:etymology:wikidata)}` to show the wikipedia page of whom the feature was named after. Also remember that these can be styled, e.g. `{wikipedia():max-height: 10rem}` to limit the height", - constr: (_, tagsSource, args) => - new VariableUiElement( - tagsSource.map(tags => tags[args[0]]) - .map(wikidata => { - const wikidatas: string[] = - Utils.NoEmpty(wikidata?.split(";")?.map(wd => wd.trim()) ?? []) - return new WikipediaBox(wikidatas) - }) - ) - - }, - { - 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.", - 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, defaultGuiState) => { - - const keys = [...args] - keys.splice(0, 1) - const featureStore = state.allElements.ContainingFeatures - const featuresToShow: UIEventSource<{ freshness: Date, feature: any }[]> = tagSource.map(properties => { - const values: string[] = Utils.NoNull(keys.map(key => properties[key])) - const features: { freshness: Date, feature: any }[] = [] - for (const value of values) { - let idList = [value] - if (value.startsWith("[")) { - // This is a list of values - idList = JSON.parse(value) - } - - for (const id of idList) { - const feature = featureStore.get(id) - features.push({ - freshness: new Date(), - feature + ], + example: "`{wikipedia()}` is a basic example, `{wikipedia(name:etymology:wikidata)}` to show the wikipedia page of whom the feature was named after. Also remember that these can be styled, e.g. `{wikipedia():max-height: 10rem}` to limit the height", + constr: (_, tagsSource, args) => + new VariableUiElement( + tagsSource.map(tags => tags[args[0]]) + .map(wikidata => { + const wikidatas: string[] = + Utils.NoEmpty(wikidata?.split(";")?.map(wd => wd.trim()) ?? []) + return new WikipediaBox(wikidatas) }) + ) + + }, + { + 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.", + 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, defaultGuiState) => { + + const keys = [...args] + keys.splice(0, 1) + const featureStore = state.allElements.ContainingFeatures + const featuresToShow: UIEventSource<{ freshness: Date, feature: any }[]> = tagSource.map(properties => { + const values: string[] = Utils.NoNull(keys.map(key => properties[key])) + const features: { freshness: Date, feature: any }[] = [] + for (const value of values) { + let idList = [value] + if (value.startsWith("[")) { + // This is a list of values + idList = JSON.parse(value) + } + + for (const id of idList) { + const feature = featureStore.get(id) + 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; } } - 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"], + enablePopups: false, + zoomToFeatures: true, + layers: State.state.filteredLayers, + features: new StaticFeatureSource(featuresToShow, true), + allElements: State.state.allElements + } + ) + + + minimap.SetStyle("overflow: hidden; pointer-events: none;") + return minimap; } - const locationSource = new UIEventSource({ - lat: Number(properties._lat), - lon: Number(properties._lon), - zoom: zoom - }) - const minimap = Minimap.createMiniMap( + }, + { + 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: [ { - background: state.backgroundLayer, - location: locationSource, - allowMoving: false + doc: "The side to show, either `left` or `right`", + name: "side", } - ) + ], + example: "`{sided_minimap(left)}`", + constr: (state, tagSource, args) => { - locationSource.addCallback(loc => { - if (loc.zoom > zoom) { - // We zoom back - locationSource.data.zoom = zoom; - locationSource.ping(); + 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 ShowDataMultiLayer( - { - leafletMap: minimap["leafletMap"], - enablePopups: false, - zoomToFeatures: true, - layers: State.state.filteredLayers, - features: new StaticFeatureSource(featuresToShow, true), - allElements: State.state.allElements - } - ) + new ShowDataLayer( + { + leafletMap: minimap["leafletMap"], + enablePopups: false, + zoomToFeatures: true, + layerToShow: AllKnownLayers.sharedLayers.get("left_right_style"), + features: new StaticFeatureSource([copy], false), + allElements: State.state.allElements + } + ) - 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", + minimap.SetStyle("overflow: hidden; pointer-events: none;") + return minimap; } - ], - 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 + }, + { + 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", + example: "`{reviews()}` for a vanilla review, `{reviews(name, play_forest)}` to review a play forest. If a name is known, the name will be used as identifier, otherwise 'play_forest' is used", + args: [{ + name: "subjectKey", + defaultValue: "name", + doc: "The key to use to determine the subject. If specified, the subject will be tags[subjectKey]" + }, { + name: "fallback", + doc: "The identifier to use, if tags[subjectKey] as specified above is not available. This is effectively a fallback value" + }], + constr: (state: State, tags, args) => { + const tgs = tags.data; + const key = args[0] ?? "name" + let subject = tgs[key] ?? args[1]; + if (subject === undefined || subject === "") { + return Translations.t.reviews.name_required; } - ) - const side = args[0] - const feature = state.allElements.ContainingFeatures.get(tagSource.data.id) - const copy = {...feature} - copy.properties = { - id: side + const mangrove = MangroveReviews.Get(Number(tgs._lon), Number(tgs._lat), + encodeURIComponent(subject), + state.mangroveIdentity, + state.osmConnection._dryRun + ); + const form = new ReviewForm((r, whenDone) => mangrove.AddReview(r, whenDone), state.osmConnection); + return new ReviewElement(mangrove.GetSubjectUri(), mangrove.GetReviews(), form); } - new ShowDataLayer( - { - leafletMap: minimap["leafletMap"], - enablePopups: false, - zoomToFeatures: true, - layerToShow: AllKnownLayers.sharedLayers.get("left_right_style"), - features: new StaticFeatureSource([copy], false), - allElements: State.state.allElements - } - ) - - - 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", - example: "`{reviews()}` for a vanilla review, `{reviews(name, play_forest)}` to review a play forest. If a name is known, the name will be used as identifier, otherwise 'play_forest' is used", - args: [{ - name: "subjectKey", - defaultValue: "name", - doc: "The key to use to determine the subject. If specified, the subject will be tags[subjectKey]" - }, { - name: "fallback", - doc: "The identifier to use, if tags[subjectKey] as specified above is not available. This is effectively a fallback value" - }], - constr: (state: State, tags, args) => { - const tgs = tags.data; - const key = args[0] ?? "name" - let subject = tgs[key] ?? args[1]; - if (subject === undefined || subject === "") { - return Translations.t.reviews.name_required; - } - const mangrove = MangroveReviews.Get(Number(tgs._lon), Number(tgs._lat), - encodeURIComponent(subject), - state.mangroveIdentity, - state.osmConnection._dryRun - ); - const form = new ReviewForm((r, whenDone) => mangrove.AddReview(r, whenDone), state.osmConnection); - return new ReviewElement(mangrove.GetSubjectUri(), mangrove.GetReviews(), form); - } - }, - { - funcName: "opening_hours_table", - docs: "Creates an opening-hours table. Usage: {opening_hours_table(opening_hours)} to create a table of the tag 'opening_hours'.", - args: [{ - name: "key", - defaultValue: "opening_hours", - doc: "The tagkey from which the table is constructed." - }, { - name: "prefix", - defaultValue: "", - doc: "Remove this string from the start of the value before parsing. __Note: use `&LPARENs` to indicate `(` if needed__" - }, { - name: "postfix", - defaultValue: "", - doc: "Remove this string from the end of the value before parsing. __Note: use `&RPARENs` to indicate `)` if needed__" - }], - example: "A normal opening hours table can be invoked with `{opening_hours_table()}`. A table for e.g. conditional access with opening hours can be `{opening_hours_table(access:conditional, no @ &LPARENS, &RPARENS)}`", - constr: (state: State, tagSource: UIEventSource, args) => { - return new OpeningHoursVisualization(tagSource, args[0], args[1], args[2]) - } - }, - { - funcName: "live", - docs: "Downloads a JSON from the given URL, e.g. '{live(example.org/data.json, shorthand:x.y.z, other:a.b.c, shorthand)}' will download the given file, will create an object {shorthand: json[x][y][z], other: json[a][b][c] out of it and will return 'other' or 'json[a][b][c]. This is made to use in combination with tags, e.g. {live({url}, {url:format}, needed_value)}", - example: "{live({url},{url:format},hour)} {live(https://data.mobility.brussels/bike/api/counts/?request=live&featureID=CB2105,hour:data.hour_cnt;day:data.day_cnt;year:data.year_cnt,hour)}", - args: [{ - name: "Url", doc: "The URL to load" - }, { - name: "Shorthands", - doc: "A list of shorthands, of the format 'shorthandname:path.path.path'. separated by ;" - }, { - name: "path", doc: "The path (or shorthand) that should be returned" - }], - constr: (state: State, tagSource: UIEventSource, args) => { - const url = args[0]; - const shorthands = args[1]; - const neededValue = args[2]; - const source = LiveQueryHandler.FetchLiveData(url, shorthands.split(";")); - return new VariableUiElement(source.map(data => data[neededValue] ?? "Loading...")); - } - }, - { - 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: [ - { + }, + { + funcName: "opening_hours_table", + docs: "Creates an opening-hours table. Usage: {opening_hours_table(opening_hours)} to create a table of the tag 'opening_hours'.", + args: [{ name: "key", - doc: "The key to be read and to generate a histogram from" - }, - { - name: "title", - doc: "The text to put above the given values column", - defaultValue: "" - }, - { - name: "countHeader", - doc: "The text to put above the counts", - defaultValue: "" - }, - { - name: "colors*", - doc: "(Matches all resting arguments - optional) Matches a regex onto a color value, e.g. `3[a-zA-Z+-]*:#33cc33`" - + defaultValue: "opening_hours", + doc: "The tagkey from which the table is constructed." + }, { + name: "prefix", + defaultValue: "", + doc: "Remove this string from the start of the value before parsing. __Note: use `&LPARENs` to indicate `(` if needed__" + }, { + name: "postfix", + defaultValue: "", + doc: "Remove this string from the end of the value before parsing. __Note: use `&RPARENs` to indicate `)` if needed__" + }], + example: "A normal opening hours table can be invoked with `{opening_hours_table()}`. A table for e.g. conditional access with opening hours can be `{opening_hours_table(access:conditional, no @ &LPARENS, &RPARENS)}`", + constr: (state: State, tagSource: UIEventSource, args) => { + return new OpeningHoursVisualization(tagSource, args[0], args[1], args[2]) } - ], - constr: (state: State, tagSource: UIEventSource, args: string[]) => { + }, + { + funcName: "live", + docs: "Downloads a JSON from the given URL, e.g. '{live(example.org/data.json, shorthand:x.y.z, other:a.b.c, shorthand)}' will download the given file, will create an object {shorthand: json[x][y][z], other: json[a][b][c] out of it and will return 'other' or 'json[a][b][c]. This is made to use in combination with tags, e.g. {live({url}, {url:format}, needed_value)}", + example: "{live({url},{url:format},hour)} {live(https://data.mobility.brussels/bike/api/counts/?request=live&featureID=CB2105,hour:data.hour_cnt;day:data.day_cnt;year:data.year_cnt,hour)}", + args: [{ + name: "Url", doc: "The URL to load" + }, { + name: "Shorthands", + doc: "A list of shorthands, of the format 'shorthandname:path.path.path'. separated by ;" + }, { + name: "path", doc: "The path (or shorthand) that should be returned" + }], + constr: (state: State, tagSource: UIEventSource, args) => { + const url = args[0]; + const shorthands = args[1]; + const neededValue = args[2]; + const source = LiveQueryHandler.FetchLiveData(url, shorthands.split(";")); + return new VariableUiElement(source.map(data => data[neededValue] ?? "Loading...")); + } + }, + { + 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" + }, + { + name: "title", + doc: "The text to put above the given values column", + defaultValue: "" + }, + { + name: "countHeader", + doc: "The text to put above the counts", + defaultValue: "" + }, + { + name: "colors*", + doc: "(Matches all resting arguments - optional) Matches a regex onto a color value, e.g. `3[a-zA-Z+-]*:#33cc33`" - 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 } - } + ], + constr: (state: State, tagSource: UIEventSource, args: string[]) => { - const listSource: UIEventSource = tagSource - .map(tags => { - try { - const value = tags[args[0]] - if (value === "" || value === undefined) { - return undefined + 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 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], 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: 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", - example: "{canonical(length)} will give 42 metre (in french)", - args: [{ - name: "key", - doc: "The key of the tag to give the canonical text for" - }], - constr: (state, tagSource, args) => { - const key = args [0] - return new VariableUiElement( - tagSource.map(tags => tags[key]).map(value => { - if (value === undefined) { return undefined } - const allUnits = [].concat(...state.layoutToUse.layers.map(lyr => lyr.units)) - const unit = allUnits.filter(unit => unit.isApplicableToKey(key))[0] - if (unit === undefined) { - return value; - } - return unit.asHumanLongValue(value); + } - }) - ) - } - }, - 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." - }, - {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" - }, - { - 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" + const listSource: UIEventSource = 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], assignColors) } - ], - 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: UIEventSource = tagsSource.map(tags => { - const ids = tags[featureIdsKey] - try { - if (ids === undefined) { + }, + { + 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: 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", + example: "{canonical(length)} will give 42 metre (in french)", + args: [{ + name: "key", + doc: "The key of the tag to give the canonical text for" + }], + constr: (state, tagSource, args) => { + const key = args [0] + return new VariableUiElement( + tagSource.map(tags => tags[key]).map(value => { + if (value === undefined) { + return undefined + } + const allUnits = [].concat(...state.layoutToUse.layers.map(lyr => lyr.units)) + const unit = allUnits.filter(unit => unit.isApplicableToKey(key))[0] + if (unit === undefined) { + return value; + } + return unit.asHumanLongValue(value); + + }) + ) + } + }, + 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." + }, + {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" + }, + { + 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" + } + ], + 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: UIEventSource = 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 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 - } - ); - - } - }, - { - funcName: "tag_apply", - 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" + SpecialVisualizations.tagsToApplyHelpText, - args: [ - { - name: "tags_to_apply", - doc: "A specification of the tags to apply" - }, - { - name: "message", - doc: "The text to show to the contributor" - }, - { - name: "image", - doc: "An image to show to the contributor on the button" - }, - { - name: "id_of_object_to_apply_this_one", - defaultValue: undefined, - doc: "If specified, applies the the tags onto _another_ object. The id will be read from properties[id_of_object_to_apply_this_one] of the selected object. The tags are still calculated based on the tags of the _selected_ element" - } - ], - example: "`{tag_apply(survey_date=$_now:date, Surveyed today!)}`, `{tag_apply(addr:street=$addr:street, Apply the address, apply_icon.svg, _closest_osm_id)", - constr: (state, tags, args) => { - const tagsToApply = SpecialVisualizations.generateTagsToApply(args[0], tags) - const msg = args[1] - let image = args[2]?.trim() - if (image === "" || image === "undefined") { - image = undefined - } - const targetIdKey = args[3] - const t = Translations.t.general.apply_button - - const tagsExplanation = new VariableUiElement(tagsToApply.map(tagsToApply => { - const tagsStr = tagsToApply.map(t => t.asHumanString(false, true)).join("&"); - let el: BaseUIElement = new FixedUiElement(tagsStr) - if (targetIdKey !== undefined) { - const targetId = tags.data[targetIdKey] ?? tags.data.id - el = t.appliedOnAnotherObject.Subs({tags: tagsStr, id: targetId}) + }) + return new MultiApply( + { + featureIds, + keysToApply, + text, + autoapply, + overwrite, + tagsSource, + state } - return el; - } - )).SetClass("subtle") + ); - const applied = new UIEventSource(false) - const applyButton = new SubtleButton(image, new Combine([msg, tagsExplanation]).SetClass("flex flex-col")) - .onClick(() => { - const targetId = tags.data[targetIdKey] ?? tags.data.id - const changeAction = new ChangeTagAction(targetId, - new And(tagsToApply.data), - tags.data, // We pass in the tags of the selected element, not the tags of the target element! - { - theme: state.layoutToUse.id, - changeType: "answer" - } - ) - state.changes.applyAction(changeAction) - applied.setData(true) - }) - - - return new Toggle( - new Toggle( - t.isApplied.SetClass("thanks"), - applyButton, - applied - ) - , undefined, state.osmConnection.isLoggedIn) - } - }, - { - funcName: "export_as_gpx", - docs: "Exports the selected feature as GPX-file", - args: [], - constr: (state, tagSource, args) => { - const t = Translations.t.general.download; - - return new SubtleButton(Svg.download_ui(), - new Combine([t.downloadGpx.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: "clear_location_history", - docs: "A button to remove the travelled track information from the device", - args: [], - constr: state => { - return new SubtleButton( - Svg.delete_icon_svg().SetStyle("height: 1.5rem"), Translations.t.general.removeLocationHistory - ).onClick(() => { - state.historicalUserLocations.features.setData([]) - Hash.hash.setData(undefined) - }) - } - } - ] - - - static generateTagsToApply(spec: string, tagSource: UIEventSource): UIEventSource { - - const tgsSpec = spec.split(";").map(spec => { - const kv = spec.split("=").map(s => s.trim()); - if (kv.length != 2) { - throw "Invalid key spec: multiple '=' found in " + spec - } - return kv - }) - - for (const spec of tgsSpec) { - if(spec[0].endsWith(':')){ - throw "A tag specification for import or apply ends with ':'. The theme author probably wrote key:=otherkey instead of key=$otherkey" - } - } - - return tagSource.map(tags => { - const newTags: Tag [] = [] - for (const [key, value] of tgsSpec) { - if (value.indexOf('$') >= 0) { - - let parts = value.split("$") - // THe first of the split won't start with a '$', so no substitution needed - let actualValue = parts[0] - parts.shift() - - for (const part of parts) { - const [_, varName, leftOver] = part.match(/([a-zA-Z0-9_:]*)(.*)/) - actualValue += (tags[varName] ?? "") + leftOver } - newTags.push(new Tag(key, actualValue)) - } else { - newTags.push(new Tag(key, value)) + }, + new TagApplyButton(), + { + funcName: "export_as_gpx", + docs: "Exports the selected feature as GPX-file", + args: [], + constr: (state, tagSource, args) => { + const t = Translations.t.general.download; + + return new SubtleButton(Svg.download_ui(), + new Combine([t.downloadGpx.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: "clear_location_history", + docs: "A button to remove the travelled track information from the device", + args: [], + constr: state => { + return new SubtleButton( + Svg.delete_icon_svg().SetStyle("height: 1.5rem"), Translations.t.general.removeLocationHistory + ).onClick(() => { + state.historicalUserLocations.features.setData([]) + Hash.hash.setData(undefined) + }) + } } - } - return newTags - }) - + ] + + specialVisualizations.push(new AutoApplyButton(specialVisualizations)) + + return specialVisualizations; } - + + public static HelpMessage() { const helpTexts = diff --git a/assets/layers/named_streets/named_streets.json b/assets/layers/named_streets/named_streets.json new file mode 100644 index 000000000..03bab2dc8 --- /dev/null +++ b/assets/layers/named_streets/named_streets.json @@ -0,0 +1,24 @@ +{ + "id": "named_streets", + "description": "Hidden layer with all streets which have a name. Useful to detect addresses", + "minzoom": 18, + "source": { + "osmTags": { + "and": [ + "highway~*", + "name~*" + ] + } + }, + "mapRendering": [ + { + "color": { + "render": "#ccc" + }, + "width": { + "render": "3" + } + } + ], + "shownByDefault": false +} \ No newline at end of file diff --git a/assets/svg/license_info.json b/assets/svg/license_info.json index 844bc24ce..0b19904d7 100644 --- a/assets/svg/license_info.json +++ b/assets/svg/license_info.json @@ -1135,6 +1135,16 @@ "authors": [], "sources": [] }, + { + "path": "robot.svg", + "license": "CC-BY 4.0 International", + "authors": [ + "Font Awesome" + ], + "sources": [ + "https://commons.wikimedia.org/wiki/File:Font_Awesome_5_solid_robot.svg" + ] + }, { "path": "satellite.svg", "license": "CC0", diff --git a/assets/themes/grb_import/robot.svg b/assets/svg/robot.svg similarity index 100% rename from assets/themes/grb_import/robot.svg rename to assets/svg/robot.svg diff --git a/assets/themes/grb_import/grb.json b/assets/themes/grb_import/grb.json index 0b5865f4b..6f499615e 100644 --- a/assets/themes/grb_import/grb.json +++ b/assets/themes/grb_import/grb.json @@ -42,14 +42,19 @@ } ], "calculatedTags": [ - "_x='y'", - "_embedded_crab_addresses=undefined // feat.overlapWith('crab_address').length" + "_embedded_crab_addresses= Number(feat.properties.zoom) >= 18 ? feat.overlapWith('crab_address').length : undefined" ], + "minZoom": 18, "tagRenderings": [ { "id": "hw", "render": "There are {_embedded_crab_addresses} adresses in view", - "mappings": [{ + "mappings": [ + { + "if": "zoom<18", + "then": "Zoom in more..." + }, + { "if": "_embedded_crab_addresses=", "then": "Loading..." },{ diff --git a/assets/themes/grb_import/license_info.json b/assets/themes/grb_import/license_info.json index a3deb7f3e..8ea1617ec 100644 --- a/assets/themes/grb_import/license_info.json +++ b/assets/themes/grb_import/license_info.json @@ -6,15 +6,5 @@ "Pieter Vander Vennet" ], "sources": [] - }, - { - "path": "robot.svg", - "license": "CC-BY 4.0 International", - "authors": [ - "Font Awesome" - ], - "sources": [ - "https://commons.wikimedia.org/wiki/File:Font_Awesome_5_solid_robot.svg" - ] } ] \ No newline at end of file diff --git a/assets/themes/grb_import/missing_streets.json b/assets/themes/grb_import/missing_streets.json new file mode 100644 index 000000000..1537abd31 --- /dev/null +++ b/assets/themes/grb_import/missing_streets.json @@ -0,0 +1,154 @@ +{ + "id": "missing_streets", + "title": { + "nl": "GRB import helper" + }, + "shortDescription": { + "nl": "Grb import helper tool" + }, + "description": { + "nl": "Dit thema voegt semi-automatisch straatnamen toe aan gebouwen met huisnummer en overeenkomstig CRAB-adres." + }, + "language": [ + "nl" + ], + "maintainer": "", + "icon": "./assets/svg/robot.svg", + "version": "0", + "startLat": 51.0249, + "startLon": 4.026489, + "startZoom": 9, + "widenFactor": 2, + "socialImage": "", + "clustering": { + "maxZoom": 15 + }, + "overrideAll": { + "minzoom": 14 + }, + "layers": [ + { + "builtin": "current_view", + "override": { + "+mapRendering": [ + { + "location": [ + "point" + ], + "icon": { + "render": "./assets/themes/grb_import/robot.svg" + }, + "iconSize": "15,15,center" + } + ], + "calculatedTags": [ + "_overlapping=Number(feat.properties.zoom) >= 14 ? feat.overlapWith('OSM-buildings').map(ff => ff.feat.properties) : undefined", + "_applicable=feat.get('_overlapping').filter(p => (p._spelling_is_correct === 'true') && (p._singular_import === 'true')).map(p => p.id)", + "_applicable_count=feat.get('_applicable')?.length" + ], + "tagRenderings": [ + { + "id": "hw", + "render": "There are {_applicable_count} applicable elements in view", + "mappings": [ + { + "if": "zoom<14", + "then": "Zoom in more to see the automatic action" + }, + { + "if": "_applicable_count=", + "then": "Loading..." + }, + { + "if": "_applicable_count=0", + "then": "No buildings with missing street names in view" + } + ] + }, + { + "id": "autoapply", + "render": "{auto_apply(OSM-buildings, _applicable, apply_streetname, Automatically add all missing streetnames on buildings in view)}" + } + ] + } + }, + "named_streets", + { + "builtin": "crab_address", + "override": { + "mapRendering": [ + { + "iconSize": "5,5,center", + "icon": "circle:black;" + } + ] + } + }, + { + "id": "OSM-buildings", + "name": "Alle OSM-gebouwen met een huisnummer en zonder straat", + "source": { + "osmTags": { + "and": [ + "building~*", + "addr:housenumber~*", + "addr:street=" + ] + }, + "maxCacheAge": 0 + }, + "calculatedTags": [ + "_embedded_crab_addresses:=Array.from(new Set(feat.overlapWith('crab_address').map(ff => ff.feat.properties).filter(p => p._HNRLABEL.toLowerCase() === (feat.properties['addr:housenumber'] + (feat.properties['addr:unit']??'')).toLowerCase()).map(p => p.STRAATNM)))", + "_singular_import:=feat.get('_embedded_crab_addresses')?.length == 1", + "_name_to_apply:=feat.get('_embedded_crab_addresses')[0]", + "_nearby_street_names:=feat.closestn('named_streets',5,'name', 500).map(ff => ff.feat.properties.name)", + "_spelling_is_correct:= feat.get('_nearby_street_names').indexOf(feat.properties['_name_to_apply']) >= 0" + ], + "mapRendering": [ + { + "width": { + "render": "2", + "mappings": [ + { + "if": "fixme~*", + "then": "5" + } + ] + }, + "color": { + "render": "#00c", + "mappings": [ + { + "if": "_spelling_is_correct=false", + "then": "#ff00ff" + }, + { + "if": "_singular_import=ffalse", + "then": "#f00" + } + ] + } + } + ], + "title": "OSM-gebouw", + "tagRenderings": [ + { + "id": "apply_streetname", + "render": "{tag_apply(addr:street=$_name_to_apply ,Apply the CRAB-street onto this building)}", + "mappings": [ + { + "if": "_spelling_is_correct=false", + "then": "No nearby street has the same name. The CRAB-name is {_name_to_apply}" + }, + { + "if": "_singular_import=false", + "then": "There are multiple streetnames applicable here" + } + ] + } + ], + "passAllFeatures": true + } + ], + "hideFromOverview": true +} \ No newline at end of file diff --git a/assets/themes/uk_addresses/uk_addresses.json b/assets/themes/uk_addresses/uk_addresses.json index 9ad8c73b4..1b4faa5be 100644 --- a/assets/themes/uk_addresses/uk_addresses.json +++ b/assets/themes/uk_addresses/uk_addresses.json @@ -326,28 +326,7 @@ } ] }, - { - "id": "named_streets", - "minzoom": 18, - "source": { - "osmTags": { - "and": [ - "highway~*", - "name~*" - ] - } - }, - "mapRendering": [ - { - "color": { - "render": "#ccc" - }, - "width": { - "render": "0" - } - } - ] - } +"named_streets" ], "enableShareScreen": false, "enableMoreQuests": false diff --git a/css/index-tailwind-output.css b/css/index-tailwind-output.css index 82d7201ff..c650760df 100644 --- a/css/index-tailwind-output.css +++ b/css/index-tailwind-output.css @@ -1032,6 +1032,10 @@ video { height: 0.75rem; } +.h-48 { + height: 12rem; +} + .max-h-20vh { max-height: 20vh; } @@ -1611,6 +1615,10 @@ video { text-decoration: underline; } +.line-through { + text-decoration: line-through; +} + .opacity-50 { opacity: 0.5; } @@ -2223,6 +2231,11 @@ li::marker { border: unset !important; } +.floating-element-width { + max-width: calc(100vw - 5em); + width: 40em; +} + .leaflet-div-icon svg { width: calc(100%); height: calc(100%); diff --git a/index.css b/index.css index 2e08dfcce..7f7262740 100644 --- a/index.css +++ b/index.css @@ -439,6 +439,10 @@ li::marker { border: unset !important; } +.floating-element-width { + max-width: calc(100vw - 5em); + width: 40em; +} .leaflet-div-icon svg { width: calc(100%);