Add special visualisation for automated actions, add missing_street-theme, various fixes

This commit is contained in:
Pieter Vander Vennet 2021-12-12 02:59:24 +01:00
parent e61c25fd6e
commit 20ec12b23c
23 changed files with 1116 additions and 690 deletions

182
UI/Popup/AutoApplyButton.ts Normal file
View file

@ -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<any>, argument: string[]): Promise<void>
}
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<any>, 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 = <string[]>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 = <AutoAction>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")
}
}

View file

@ -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<any>): { minzoom: string, max_snap_distance: string, snap_onto_layers: string, icon: string, text: string, tags: string, targetLayer: string, newTags: UIEventSource<Tag[]> } {
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
}

136
UI/Popup/TagApplyButton.ts Normal file
View file

@ -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<any>): UIEventSource<Tag[]> {
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<any>, args: string[]) : Promise<void>{
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<any>, 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)
}
}