Fix autoapply for GRB theme

This commit is contained in:
Pieter Vander Vennet 2022-02-10 23:16:14 +01:00
parent db770f2c35
commit 30be86668e
16 changed files with 392 additions and 209 deletions

View file

@ -126,6 +126,9 @@ export default class MoreScreen extends Combine {
for (let i = 0; i < length; i++) {
str += allPreferences[id + "-" + i]
}
if(str === undefined || str === "undefined"){
return undefined
}
try {
const value: {
id: string
@ -157,13 +160,9 @@ export default class MoreScreen extends Combine {
return ids
});
currentIds.addCallback(ids => {
console.log("Current special ids are:", ids)
})
var stableIds = UIEventSource.ListStabilized<string>(currentIds)
currentIds.addCallback(ids => {
console.log("Stabilized special ids are:", ids)
})
return new VariableUiElement(
stableIds.map(ids => {
const allThemes: BaseUIElement[] = []

View file

@ -19,6 +19,10 @@ import {OsmConnection} from "../../Logic/Osm/OsmConnection";
import Translations from "../i18n/Translations";
import LayoutConfig from "../../Models/ThemeConfig/LayoutConfig";
import {Changes} from "../../Logic/Osm/Changes";
import {UIElement} from "../UIElement";
import FilteredLayer from "../../Models/FilteredLayer";
import TagRenderingConfig from "../../Models/ThemeConfig/TagRenderingConfig";
import Lazy from "../Base/Lazy";
export interface AutoAction extends SpecialVisualization {
supportsAutoAction: boolean
@ -29,6 +33,120 @@ export interface AutoAction extends SpecialVisualization {
}, tagSource: UIEventSource<any>, argument: string[]): Promise<void>
}
class ApplyButton extends UIElement {
private readonly icon: string;
private readonly text: string;
private readonly targetTagRendering: string;
private readonly target_layer_id: string;
private readonly state: FeaturePipelineState;
private readonly target_feature_ids: string[];
private readonly buttonState = new UIEventSource<"idle" | "running" | "done" | { error: string }>("idle")
private readonly layer: FilteredLayer;
private readonly tagRenderingConfig: TagRenderingConfig;
constructor(state: FeaturePipelineState, target_feature_ids: string[], options: {
target_layer_id: string,
targetTagRendering: string,
text: string,
icon: string
}) {
super()
this.state = state;
this.target_feature_ids = target_feature_ids;
this.target_layer_id = options.target_layer_id;
this.targetTagRendering = options.targetTagRendering;
this.text = options.text
this.icon = options.icon
this.layer = this.state.filteredLayers.data.find(l => l.layerDef.id === this.target_layer_id)
this. tagRenderingConfig = this.layer.layerDef.tagRenderings.find(tr => tr.id === this.targetTagRendering)
}
private async Run() {
this.buttonState.setData("running")
try {
console.log("Applying auto-action on " + this.target_feature_ids.length + " features")
for (const targetFeatureId of this.target_feature_ids) {
const featureTags = this.state.allElements.getEventSourceById(targetFeatureId)
const rendering = this.tagRenderingConfig.GetRenderValue(featureTags.data).txt
const specialRenderings = Utils.NoNull(SubstitutedTranslation.ExtractSpecialComponents(rendering)
.map(x => x.special))
.filter(v => v.func["supportsAutoAction"] === true)
if(specialRenderings.length == 0){
console.warn("AutoApply: feature "+targetFeatureId+" got a rendering without supported auto actions:", rendering)
}
for (const specialRendering of specialRenderings) {
const action = <AutoAction>specialRendering.func
await action.applyActionOn(this.state, featureTags, specialRendering.args)
}
}
console.log("Flushing changes...")
await this.state.changes.flushChanges("Auto button")
this.buttonState.setData("done")
} catch (e) {
console.error("Error while running autoApply: ", e)
this. buttonState.setData({error: e})
}
}
protected InnerRender(): string | BaseUIElement {
if (this.target_feature_ids.length === 0) {
return new FixedUiElement("No elements found to perform action")
}
if (this.tagRenderingConfig === undefined) {
return new FixedUiElement("Target tagrendering " + this.targetTagRendering + " not found").SetClass("alert")
}
const self = this;
const button = new SubtleButton(
new Img(this.icon),
this.text
).onClick(() => self.Run());
const explanation = new Combine(["The following objects will be updated: ",
...this.target_feature_ids.map(id => new Combine([new Link(id, "https:/ /openstreetmap.org/" + id, true), ", "]))]).SetClass("subtle")
const previewMap = Minimap.createMiniMap({
allowMoving: false,
background: this.state.backgroundLayer,
addLayerControl: true,
}).SetClass("h-48")
const features = this.target_feature_ids.map(id => this.state.allElements.ContainingFeatures.get(id))
new ShowDataLayer({
leafletMap: previewMap.leafletMap,
popup: undefined,
zoomToFeatures: true,
features: new StaticFeatureSource(features, false),
state: this.state,
layerToShow:this. layer.layerDef,
})
return new VariableUiElement(this.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")
}
))
}
}
export default class AutoApplyButton implements SpecialVisualization {
public readonly docs: string;
public readonly funcName: string = "auto_apply";
@ -72,109 +190,44 @@ export default class AutoApplyButton implements SpecialVisualization {
}
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")
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 target_layer_id = argument[0]
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 options = {
target_layer_id, targetTagRendering, text, icon
}
const buttonState = new UIEventSource<"idle" | "running" | "done" | { error: string }>("idle")
return new Lazy(() => {
const to_parse = new UIEventSource(undefined)
// Very ugly hack: read the value every 500ms
UIEventSource.Chronic(500, () => to_parse.data === undefined).addCallback(() => {
const applicable = tagSource.data[argument[1]]
console.log("Current applicable value is: ", applicable)
to_parse.setData(applicable)
})
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)
}
const loading = new Loading("Gathering which elements support auto-apply... ");
return new VariableUiElement(to_parse.map(ids => {
if(ids === undefined){
return loading
}
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,
popup: undefined,
zoomToFeatures: true,
features: new StaticFeatureSource(features, false),
state,
layerToShow: layer.layerDef,
return new ApplyButton(state, JSON.parse(ids), options);
}))
})
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")
}
}

View file

@ -36,7 +36,7 @@ export default class EditableTagRendering extends Toggle {
const editMode = options.editMode ?? new UIEventSource<boolean>(false)
let rendering = EditableTagRendering.CreateRendering(state, tags, configuration, units, editMode);
rendering.SetClass(options.innerElementClasses)
if(state.featureSwitchIsDebugging.data){
if(state.featureSwitchIsDebugging.data || state.featureSwitchIsTesting.data){
rendering = new Combine([
new FixedUiElement(configuration.id).SetClass("self-end subtle"),
rendering

View file

@ -21,7 +21,7 @@ import ShowDataLayer from "../ShowDataLayer/ShowDataLayer";
import StaticFeatureSource from "../../Logic/FeatureSource/Sources/StaticFeatureSource";
import ShowDataMultiLayer from "../ShowDataLayer/ShowDataMultiLayer";
import CreateWayWithPointReuseAction, {MergePointConfig} from "../../Logic/Osm/Actions/CreateWayWithPointReuseAction";
import OsmChangeAction, {OsmCreateAction} from "../../Logic/Osm/Actions/OsmChangeAction";
import OsmChangeAction from "../../Logic/Osm/Actions/OsmChangeAction";
import FeatureSource from "../../Logic/FeatureSource/FeatureSource";
import {OsmObject, OsmWay} from "../../Logic/Osm/OsmObject";
import FeaturePipelineState from "../../Logic/State/FeaturePipelineState";
@ -37,12 +37,17 @@ import LayerConfig from "../../Models/ThemeConfig/LayerConfig";
import * as conflation_json from "../../assets/layers/conflation/conflation.json";
import {GeoOperations} from "../../Logic/GeoOperations";
import {LoginToggle} from "./LoginButton";
import {AutoAction} from "./AutoApplyButton";
import LayoutConfig from "../../Models/ThemeConfig/LayoutConfig";
import {Changes} from "../../Logic/Osm/Changes";
import {ElementStorage} from "../../Logic/ElementStorage";
/**
* 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 {
protected static importedIds = new Set<string>()
public readonly funcName: string
public readonly docs: string
public readonly args: { name: string, defaultValue?: string, doc: string }[]
@ -157,7 +162,10 @@ ${Utils.special_visualizations_importRequirementDocs}
state.featureSwitchUserbadge)
const isImported = tagSource.map(tags => tags._imported === "yes")
const isImported = tagSource.map(tags => {
AbstractImportButton.importedIds.add(tags.id)
return tags._imported === "yes";
})
/**** THe actual panel showing the import guiding map ****/
@ -269,7 +277,7 @@ ${Utils.special_visualizations_importRequirementDocs}
return new Combine([confirmationMap, confirmButton, cancel]).SetClass("flex flex-col")
}
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[]> } {
protected 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) {
@ -351,7 +359,8 @@ export class ConflateButton extends AbstractImportButton {
}
export class ImportWayButton extends AbstractImportButton {
export class ImportWayButton extends AbstractImportButton implements AutoAction {
public readonly supportsAutoAction = true;
constructor() {
super("import_way_button",
@ -386,6 +395,39 @@ export class ImportWayButton extends AbstractImportButton {
)
}
async applyActionOn(state: { layoutToUse: LayoutConfig; changes: Changes, allElements: ElementStorage },
originalFeatureTags: UIEventSource<any>,
argument: string[]): Promise<void> {
const id = originalFeatureTags.data.id;
if (AbstractImportButton.importedIds.has(originalFeatureTags.data.id)
) {
return;
}
AbstractImportButton.importedIds.add(originalFeatureTags.data.id)
const args = this.parseArgs(argument, originalFeatureTags)
const feature = state.allElements.ContainingFeatures.get(id)
console.log("Geometry to auto-import is:", feature)
const geom = feature.geometry
let coordinates: [number, number][]
if (geom.type === "LineString") {
coordinates = geom.coordinates
} else if (geom.type === "Polygon") {
coordinates = geom.coordinates[0]
}
const mergeConfigs = this.GetMergeConfig(args);
const action = this.CreateAction(
feature,
args,
<FeaturePipelineState>state,
mergeConfigs,
coordinates
)
await state.changes.applyAction(action)
}
canBeImported(feature: any) {
const type = feature.geometry.type
return type === "LineString" || type === "Polygon"
@ -420,7 +462,24 @@ export class ImportWayButton extends AbstractImportButton {
} else if (geom.type === "Polygon") {
coordinates = geom.coordinates[0]
}
const mergeConfigs = this.GetMergeConfig(args);
let action = this.CreateAction(feature, args, state, mergeConfigs, coordinates);
return this.createConfirmPanelForWay(
state,
args,
feature,
originalFeatureTags,
action,
onCancel
)
}
private GetMergeConfig(args: { max_snap_distance: string; snap_onto_layers: string; icon: string; text: string; tags: string; newTags: UIEventSource<any>; targetLayer: string })
: MergePointConfig[] {
const nodesMustMatch = args["snap_to_point_if"]?.split(";")?.map((tag, i) => TagUtils.Tag(tag, "TagsSpec for import button " + i))
const mergeConfigs = []
@ -446,14 +505,21 @@ export class ImportWayButton extends AbstractImportButton {
mergeConfigs.push(mergeConfig)
}
let action: OsmCreateAction & { getPreview(): Promise<FeatureSource> };
return mergeConfigs;
}
private CreateAction(feature,
args: { max_snap_distance: string; snap_onto_layers: string; icon: string; text: string; tags: string; newTags: UIEventSource<any>; targetLayer: string },
state: FeaturePipelineState,
mergeConfigs: any[],
coordinates: [number, number][]) {
const coors = feature.geometry.coordinates
if (feature.geometry.type === "Polygon" && coors.length > 1) {
const outer = coors[0]
const inner = [...coors]
inner.splice(0, 1)
action = new CreateMultiPolygonWithPointReuseAction(
return new CreateMultiPolygonWithPointReuseAction(
args.newTags.data,
outer,
inner,
@ -463,24 +529,13 @@ export class ImportWayButton extends AbstractImportButton {
)
} else {
action = new CreateWayWithPointReuseAction(
return new CreateWayWithPointReuseAction(
args.newTags.data,
coordinates,
state,
mergeConfigs
)
}
return this.createConfirmPanelForWay(
state,
args,
feature,
originalFeatureTags,
action,
onCancel
)
}
}
@ -525,11 +580,11 @@ export class ImportPointButton extends AbstractImportButton {
let specialMotivation = undefined
let note_id = args.note_id
if (args.note_id !== undefined && isNaN(Number(args.note_id))) {
if (args.note_id !== undefined && isNaN(Number(args.note_id))) {
note_id = originalFeatureTags.data[args.note_id]
specialMotivation = "source: https://osm.org/note/" + note_id
}
const newElementAction = new CreateNewNodeAction(tags, location.lat, location.lon, {
theme: state.layoutToUse.id,
changeType: "import",

View file

@ -29,7 +29,7 @@ export default class NoteCommentElement extends Combine {
} else if (comment.action === "closed") {
actionIcon = Svg.resolved_svg()
} else {
actionIcon = Svg.addSmall_svg()
actionIcon = Svg.speech_bubble_svg()
}
let user: BaseUIElement

View file

@ -534,7 +534,7 @@ export default class SpecialVisualizations {
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: "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."
@ -725,7 +725,7 @@ export default class SpecialVisualizations {
textField.SetClass("rounded-l border border-grey")
const txt = textField.GetValue()
const addCommentButton = new SubtleButton(Svg.addSmall_svg().SetClass("max-h-7"), t.addCommentPlaceholder)
const addCommentButton = new SubtleButton(Svg.speech_bubble_svg().SetClass("max-h-7"), t.addCommentPlaceholder)
.onClick(async () => {
const id = tags.data[args[1] ?? "id"]
@ -778,7 +778,9 @@ export default class SpecialVisualizations {
new Combine([
new Title("Add a comment"),
textField,
new Combine([addCommentButton.SetClass("mr-2"), stateButtons]).SetClass("flex justify-end")
new Combine([
new Toggle(addCommentButton, undefined, textField.GetValue().map(t => t !==undefined && t.length > 1)).SetClass("mr-2")
, stateButtons]).SetClass("flex justify-end")
]).SetClass("border-2 border-black rounded-xl p-4 block"),
t.loginToAddComment, state)
}