Intermediary

This commit is contained in:
Pieter Vander Vennet 2020-07-20 13:28:45 +02:00
parent 5c9fb293e9
commit dcf5d24002
10 changed files with 140 additions and 608 deletions

View file

@ -6,7 +6,6 @@ import {OsmConnection} from "./OsmConnection";
import {OsmNode, OsmObject} from "./OsmObject"; import {OsmNode, OsmObject} from "./OsmObject";
import {ElementStorage} from "./ElementStorage"; import {ElementStorage} from "./ElementStorage";
import {UIEventSource} from "../UI/UIEventSource"; import {UIEventSource} from "../UI/UIEventSource";
import {Question, QuestionDefinition} from "./Question";
import {And, Tag, TagsFilter} from "./TagsFilter"; import {And, Tag, TagsFilter} from "./TagsFilter";
export class Changes { export class Changes {

View file

@ -1,508 +0,0 @@
import {Changes} from "./Changes";
import {UIElement} from "../UI/UIElement";
import {UIEventSource} from "../UI/UIEventSource";
export class QuestionUI extends UIElement {
private readonly _q: Question;
private readonly _tags: UIEventSource<any>;
/**
* The ID of the calling question - used to trigger it's onsave
*/
private readonly _qid;
constructor(q: Question, qid: number, tags: UIEventSource<any>) {
super(tags);
this._q = q;
this._tags = tags;
this._qid = qid;
}
private RenderRadio() {
let radios = "";
let c = 0;
for (let answer of this._q.question.answers) {
const human = answer.text;
const ansId = "q" + this._qid + "-answer" + c;
radios +=
"<input type='radio' name='q" + this._qid + "' id='" + ansId + "' value='" + c + "' />" +
"<label for='" + ansId + "'>" + human + "</label>" +
"<br />";
c++;
}
return radios;
}
private RenderRadioText() {
let radios = "";
let c = 0;
for (let answer of this._q.question.answers) {
const human = answer.text;
const ansId = "q" + this._qid + "-answer" + c;
radios +=
"<input type='radio' name='q" + this._qid + "' id='" + ansId + "' value='" + c + "' />" +
"<label for='" + ansId + "'>" + human + "</label>" +
"<br />";
c++;
}
const ansId = "q" + this._qid + "-answer" + c;
radios +=
"<input type='radio' name='q" + this._qid + "' id='" + ansId + "' value='" + c + "' />" +
"<label for='" + ansId + "'><input type='text' id='q-" + this._qid + "-textbox' onclick='checkRadioButton(\"" + ansId + "\")'/></label>" +
"<br />";
return radios;
}
InnerRender(): string {
if (!this._q.Applicable(this._tags.data)) {
return "";
}
const q = this._q.question;
let answers = "";
if (q.type == "radio") {
answers += this.RenderRadio();
} else if (q.type == "text") {
answers += "<input type='text' id='q-" + this._qid + "-textbox'/><br/>"
} else if (q.type == "radio+text") {
answers += this.RenderRadioText();
} else {
alert("PLZ RENDER TYPE " + q.type);
}
const embeddedScriptSave = 'questionAnswered(' + this._qid + ', "' + this._tags.data.id + '", false )';
const embeddedScriptSkip = 'questionAnswered(' + this._qid + ', "' + this._tags.data.id + '", true )';
const saveButton = "<input class='save-button' type='button' onclick='" + embeddedScriptSave + "' value='Opslaan' />";
const skip = "<input class='skip-button' type='button' onclick='" + embeddedScriptSkip + "' value='Ik ben niet zeker (vraag overslaan)' />";
return q.question + "<br/> " + answers + saveButton + skip;
}
InnerUpdate(htmlElement: HTMLElement) {
}
}
export class QuestionDefinition {
static noNameOrNameQuestion(question: string, noExplicitName : string, severity : number) : QuestionDefinition{
const q = new QuestionDefinition(question);
q.type = 'radio+text';
q.addAnwser(noExplicitName, "noname","yes");
q.addUnrequiredTag("name", "*");
q.addUnrequiredTag("noname", "yes");
q.key = "name";
q.severity = severity;
return q;
}
static textQuestion(
question: string,
key: string,
severity: number
): QuestionDefinition {
const q = new QuestionDefinition(question);
q.type = 'text';
q.key = key;
q.severity = severity;
q.addUnrequiredTag(key, '*');
return q;
}
static radioQuestionSimple(
question: string,
severity: number,
key: string,
answers: { text: string, value: string }[]) {
const answers0: {
text: string,
tags: { k: string, v: string }[],
}[] = [];
for (const i in answers) {
const answer = answers[i];
answers0.push({text: answer.text, tags: [{k: key, v: answer.value}]})
}
var q = this.radioQuestion(question, severity, answers0);
q.key = key;
q.addUnrequiredTag(key, '*');
return q;
}
static radioAndTextQuestion(
question: string,
severity: number,
key: string,
answers: { text: string, value: string }[]) {
const q = this.radioQuestionSimple(question, severity, key, answers);
q.type = 'radio+text';
return q;
}
static radioQuestion(
question: string,
severity: number,
answers:
{
text: string,
tags: { k: string, v: string }[],
}[]
): QuestionDefinition {
const q = new QuestionDefinition(question);
q.severity = severity;
q.type = 'radio';
q.answers = answers;
for (const i in answers) {
const answer = answers[i];
for (const j in answer.tags) {
const tag = answer.tags[j];
q.addUnrequiredTag(tag.k, tag.v);
}
}
return q;
}
static GrbNoNumberQuestion() : QuestionDefinition{
const q = new QuestionDefinition("Heeft dit gebouw een huisnummer?");
q.type = "radio";
q.severity = 10;
q.answers = [{
text: "Ja, het OSM-huisnummer is correct",
tags: [{k: "fixme", v: ""}]
}, {
text: "Nee, het is een enkele garage",
tags: [{k: "building", v: "garage"}, {k: "fixme", v: ""}]
}, {
text: "Nee, het zijn meerdere garages",
tags: [{k: "building", v: "garages"}, {k: "fixme", v: ""}]
}
];
q.addRequiredTag("fixme", "GRB thinks that this has number no number")
return q;
}
static GrbHouseNumberQuestion() : QuestionDefinition{
const q = new QuestionDefinition("Wat is het huisnummer?");
q.type = "radio+text";
q.severity = 10;
q.answers = [{
text: "Het OSM-huisnummer is correct",
tags: [{k: "fixme", v: ""}],
}]
q.key = "addr:housenumber";
q.addRequiredTag("fixme", "*");
return q;
}
private constructor(question: string) {
this.question = question;
}
/**
* Question for humans
*/
public question: string;
/**
* 'type' indicates how the answers are rendered and must be one of:
* 'text' for a free to fill text field
* 'radio' for radiobuttons
* 'radio+text' for radiobuttons and a freefill text field
* 'dropdown' for a dropdown menu
* 'number' for a number field
*
* If 'text' or 'number' is specified, 'key' is used as tag for the answer.
* If 'radio' or 'dropdown' is specified, the answers are used from 'tags'
*
*/
public type: string = 'radio';
/**
* Only used for 'text' or 'number' questions
*/
public key: string = null;
public answers: {
text: string,
tags: { k: string, v: string }[]
}[];
/**
* Indicates that the element must have _all_ the tags defined below
* Dictionary 'key' => [values]; empty list is wildcard
*/
private mustHaveAllTags = [];
/**
* Indicates that the element must _not_ have any of the tags defined below.
* Dictionary 'key' => [values]
*/
private mustNotHaveTags = [];
/**
* Severity: how important the question is
* The higher, the sooner it'll be shown
*/
public severity: number = 0;
addRequiredTag(key: string, value: string) {
if (this.mustHaveAllTags[key] === undefined) {
this.mustHaveAllTags[key] = [value];
} else {
if(this.mustHaveAllTags[key] === []){
// Wildcard
return;
}
this.mustHaveAllTags[key].push(value);
}
if (value === '*') {
this.mustHaveAllTags[key] = [];
}
return this;
}
addUnrequiredTag(key: string, value: string) {
let valueList = this.mustNotHaveTags[key];
if (valueList === undefined) {
valueList = [value];
this.mustNotHaveTags[key] = valueList;
} else {
if (valueList === []) {
return;
}
valueList.push(value);
}
if (value === '*') {
this.mustNotHaveTags[key] = [];
}
return this;
}
private addAnwser(anwser: string, key: string, value: string) {
if (this.answers === undefined) {
this.answers = [{text: anwser, tags: [{k: key, v: value}]}];
} else {
this.answers.push({text: anwser, tags: [{k: key, v: value}]});
}
this.addUnrequiredTag(key, value);
}
public isApplicable(alreadyExistingTags): boolean {
for (let k in this.mustHaveAllTags) {
var actual = alreadyExistingTags[k];
if (actual === undefined) {
return false;
}
let possibleVals = this.mustHaveAllTags[k];
if (possibleVals.length == 0) {
// Wildcard
continue;
}
let index = possibleVals.indexOf(actual);
if (index < 0) {
return false
}
}
for (var k in this.mustNotHaveTags) {
var actual = alreadyExistingTags[k];
if (actual === undefined) {
continue;
}
let impossibleVals = this.mustNotHaveTags[k];
if (impossibleVals.length == 0) {
// Wildcard
return false;
}
let index = impossibleVals.indexOf(actual);
if (index >= 0) {
return false
}
}
return true;
}
}
export class Question {
// All the questions are stored in here, to be able to retrieve them globaly. This is a workaround, see below
static questions = Question.InitCallbackFunction();
static InitCallbackFunction(): Question[] {
// This needs some explanation, as it is a workaround
Question.questions = [];
// The html in a popup is only created when the user actually clicks to open it
// This means that we can not bind code to an HTML-element (as it doesn't exist yet)
// We work around this, by letting the 'save' button just call the function 'questionAnswered' with the ID of the question
// THis defines and registers this global function
/**
* Calls back to the question with either the answer or 'skip'
* @param questionId
* @param elementId
*/
function questionAnswered(questionId, elementId, dontKnow) {
if (dontKnow) {
Question.questions[questionId].Skip(elementId);
} else {
Question.questions[questionId].OnSave(elementId);
}
}
function checkRadioButton(id) {
// @ts-ignore
document.getElementById(id).checked = true;
}
// must cast as any to set property on window
// @ts-ignore
const _global = (window /* browser */ || global /* node */) as any;
_global.questionAnswered = questionAnswered;
_global.checkRadioButton = checkRadioButton;
return [];
}
public readonly question: QuestionDefinition;
private _changeHandler: Changes;
private readonly _qId;
public skippedElements: string[] = [];
constructor(
changeHandler: Changes,
question: QuestionDefinition) {
this.question = question;
this._qId = Question.questions.length;
this._changeHandler = changeHandler;
Question.questions.push(this);
}
/**
* SHould this question be asked?
* Returns false if question is already there or if a premise is missing
*/
public Applicable(tags): boolean {
if (this.skippedElements.indexOf(tags.id) >= 0) {
return false;
}
return this.question.isApplicable(tags);
}
/**
*
* @param elementId: the OSM-id of the element to perform the change on, format 'way/123', 'node/456' or 'relation/789'
* @constructor
*/
protected OnSave(elementId: string) {
let tagsToApply: { k: string, v: string }[] = [];
const q: QuestionDefinition = this.question;
let tp = this.question.type;
if (tp === "radio") {
const selected = document.querySelector('input[name="q' + this._qId + '"]:checked');
if (selected === null) {
console.log("No answer selected");
return
}
let index = (selected as any).value;
tagsToApply = q.answers[index].tags;
} else if (tp === "text") {
// @ts-ignore
let value = document.getElementById("q-" + this._qId + "-textbox").value;
if (value === undefined || value.length == 0) {
console.log("Answer too short");
return;
}
tagsToApply = [{k: q.key, v: value}];
} else if (tp === "radio+text") {
const selected = document.querySelector('input[name="q' + this._qId + '"]:checked');
if (selected === null) {
console.log("No answer selected");
return
}
let index = (selected as any).value;
if (index < q.answers.length) {
// A 'proper' answer was selected
tagsToApply = q.answers[index].tags;
} else {
// The textfield was selected
// @ts-ignore
let value = document.getElementById("q-" + this._qId + "-textbox").value;
if (value === undefined || value.length < 3) {
console.log("Answer too short");
return;
}
tagsToApply = [{k: q.key, v: value}];
}
}
console.log("Question.ts: Applying tags",tagsToApply," to element ", elementId);
for (const toApply of tagsToApply) {
this._changeHandler.addChange(elementId, toApply.k, toApply.v);
}
}
/**
* Creates the HTML question for this tag collection
*/
public CreateHtml(tags: UIEventSource<any>): UIElement {
return new QuestionUI(this, this._qId, tags);
}
private Skip(elementId: any) {
this.skippedElements.push(elementId);
console.log("SKIP");
// Yeah, this is cheating below
// It is an easy way to notify the UIElement that something has changed
this._changeHandler._allElements.getElement(elementId).ping();
}
}

View file

@ -0,0 +1,25 @@
import {UIInputElement} from "./UIInputElement";
import {UIEventSource} from "../UIEventSource";
import {UIElement} from "../UIElement";
import {FixedUiElement} from "./FixedUiElement";
export class FixedInputElement<T> extends UIInputElement<T> {
private rendering: UIElement;
private value: UIEventSource<T>;
constructor(rendering: UIElement | string, value: T) {
super(undefined);
this.value = new UIEventSource<T>(value);
this.rendering = typeof (rendering) === 'string' ? new FixedUiElement(rendering) : rendering;
}
GetValue(): UIEventSource<T> {
return this.value;
}
protected InnerRender(): string {
return this.rendering.Render();
}
}

View file

@ -5,33 +5,59 @@ import {UIInputElement} from "./UIInputElement";
export class TextField<T> extends UIInputElement<T> { export class TextField<T> extends UIInputElement<T> {
public value: UIEventSource<string> = new UIEventSource<string>(""); private value: UIEventSource<string>;
private mappedValue: UIEventSource<T>;
/** /**
* Pings and has the value data * Pings and has the value data
*/ */
public enterPressed = new UIEventSource<string>(undefined); public enterPressed = new UIEventSource<string>(undefined);
private _placeholder: UIEventSource<string>; private _placeholder: UIEventSource<string>;
private _mapping: (string) => T; private _pretext: string;
private _fromString: (string: string) => T;
constructor(placeholder: UIEventSource<string>, constructor(options: {
mapping: ((string) => T)) { placeholder?: UIEventSource<string>,
super(placeholder); toString: (t: T) => string,
this._placeholder = placeholder; fromString: (string: string) => T,
this._mapping = mapping; pretext?: string,
value?: UIEventSource<T>
}) {
super(options?.placeholder);
this.value = new UIEventSource<string>("");
this.mappedValue = options?.value ?? new UIEventSource<T>(undefined);
this.value.addCallback((str) => this.mappedValue.setData(options.fromString(str)));
this.mappedValue.addCallback((t) => this.value.setData(options.toString(t)));
this._placeholder = options?.placeholder ?? new UIEventSource<string>("");
this._pretext = options?.pretext ?? "";
const self = this;
this.mappedValue.addCallback((t) => {
if (t === undefined && t === null) {
return;
}
const field = document.getElementById('text-' + this.id);
if (field === undefined && field === null) {
return;
}
field.value = options.toString(t);
})
} }
GetValue(): UIEventSource<T> { GetValue(): UIEventSource<T> {
return this.value.map(this._mapping); return this.mappedValue;
} }
protected InnerRender(): string { protected InnerRender(): string {
return "<form onSubmit='return false' class='form-text-field'>" + return this._pretext + "<form onSubmit='return false' class='form-text-field'>" +
"<input type='text' placeholder='" + (this._placeholder.data ?? "") + "' id='text-" + this.id + "'>" + "<input type='text' placeholder='" + (this._placeholder.data ?? "") + "' id='text-" + this.id + "'>" +
"</form>"; "</form>";
} }
InnerUpdate(htmlElement: HTMLElement) { InnerUpdate(htmlElement: HTMLElement) {
super.InnerUpdate(htmlElement);
const field = document.getElementById('text-' + this.id); const field = document.getElementById('text-' + this.id);
const self = this; const self = this;
field.oninput = () => { field.oninput = () => {

View file

@ -5,4 +5,6 @@ export abstract class UIInputElement<T> extends UIElement{
abstract GetValue() : UIEventSource<T>; abstract GetValue() : UIEventSource<T>;
} }

View file

@ -7,25 +7,45 @@ export class UIRadioButton<T> extends UIInputElement<T> {
public readonly SelectedElementIndex: UIEventSource<number> public readonly SelectedElementIndex: UIEventSource<number>
= new UIEventSource<number>(null); = new UIEventSource<number>(null);
private readonly _elements: UIEventSource<UIElement[]> private value: UIEventSource<T>;
private readonly _elements: UIInputElement<T>[]
private _selectFirstAsDefault: boolean; private _selectFirstAsDefault: boolean;
private _valueMapping: (i: number) => T; private _valueMapping: (i: number) => T;
constructor(elements: UIEventSource<UIElement[]>,
valueMapping: ((i: number) => T), constructor(elements: UIInputElement<T>[],
selectFirstAsDefault = true) { selectFirstAsDefault = true) {
super(elements); super(undefined);
this._elements = elements; this._elements = elements;
this._selectFirstAsDefault = selectFirstAsDefault; this._selectFirstAsDefault = selectFirstAsDefault;
const self = this; const self = this;
this._valueMapping = valueMapping;
this.SelectedElementIndex.addCallback(() => { this.SelectedElementIndex.addCallback(() => {
self.InnerUpdate(undefined); self.InnerUpdate(undefined);
}) })
this.value =
UIEventSource.flatten(this.SelectedElementIndex.map(
(selectedIndex) => {
if (selectedIndex !== undefined && selectedIndex !== null) {
return elements[selectedIndex].GetValue()
}
}
), elements.map(e => e.GetValue()))
;
for (let i = 0; i < elements.length; i ++){
elements[i].onClick(( ) => {
self.SelectedElementIndex.setData(i);
});
}
} }
GetValue(): UIEventSource<T> { GetValue(): UIEventSource<T> {
return this.SelectedElementIndex.map(this._valueMapping); return this.value;
} }
@ -37,7 +57,7 @@ export class UIRadioButton<T> extends UIInputElement<T> {
let body = ""; let body = "";
let i = 0; let i = 0;
for (const el of this._elements.data) { for (const el of this._elements) {
const htmlElement = const htmlElement =
'<input type="radio" id="' + this.IdFor(i) + '" name="radiogroup-' + this.id + '">' + '<input type="radio" id="' + this.IdFor(i) + '" name="radiogroup-' + this.id + '">' +
'<label for="' + this.IdFor(i) + '">' + el.Render() + '</label>' + '<label for="' + this.IdFor(i) + '">' + el.Render() + '</label>' +
@ -54,7 +74,7 @@ export class UIRadioButton<T> extends UIInputElement<T> {
const self = this; const self = this;
function checkButtons() { function checkButtons() {
for (let i = 0; i < self._elements.data.length; i++) { for (let i = 0; i < self._elements.length; i++) {
const el = document.getElementById(self.IdFor(i)); const el = document.getElementById(self.IdFor(i));
// @ts-ignore // @ts-ignore
if (el.checked) { if (el.checked) {
@ -87,7 +107,7 @@ export class UIRadioButton<T> extends UIInputElement<T> {
var expected = this.SelectedElementIndex.data; var expected = this.SelectedElementIndex.data;
if (expected) { if (expected) {
for (let i = 0; i < self._elements.data.length; i++) { for (let i = 0; i < self._elements.length; i++) {
const el = document.getElementById(self.IdFor(i)); const el = document.getElementById(self.IdFor(i));
// @ts-ignore // @ts-ignore
if (el.checked) { if (el.checked) {

View file

@ -1,72 +0,0 @@
import {UIInputElement} from "./UIInputElement";
import {UIEventSource} from "../UIEventSource";
import {UIRadioButton} from "./UIRadioButton";
import {UIElement} from "../UIElement";
import {TextField} from "./TextField";
import {FixedUiElement} from "./FixedUiElement";
export class UIRadioButtonWithOther<T> extends UIInputElement<T> {
private readonly _radioSelector: UIRadioButton<T>;
private readonly _freeformText: TextField<T>;
private readonly _value: UIEventSource<T> = new UIEventSource<T>(undefined)
constructor(choices: UIElement[],
otherChoiceTemplate: string,
placeholder: string,
choiceToValue: ((i: number) => T),
stringToValue: ((string: string) => T)) {
super(undefined);
const self = this;
this._freeformText = new TextField(
new UIEventSource<string>(placeholder),
stringToValue);
const otherChoiceElement = new FixedUiElement(
otherChoiceTemplate.replace("$$$", this._freeformText.Render()));
choices.push(otherChoiceElement);
this._radioSelector = new UIRadioButton(new UIEventSource(choices),
(i) => {
if (i === undefined || i === null) {
return undefined;
}
if (i + 1 >= choices.length) {
return this._freeformText.GetValue().data
}
return choiceToValue(i);
},
false);
this._radioSelector.GetValue().addCallback(
(i) => {
self._value.setData(i);
});
this._freeformText.GetValue().addCallback((str) => {
self._value.setData(str);
}
);
this._freeformText.onClick(() => {
self._radioSelector.SelectedElementIndex.setData(choices.length - 1);
})
}
GetValue(): UIEventSource<T> {
return this._value;
}
protected InnerRender(): string {
return this._radioSelector.Render();
}
InnerUpdate(htmlElement: HTMLElement) {
super.InnerUpdate(htmlElement);
this._radioSelector.Update();
this._freeformText.Update();
}
}

View file

@ -27,6 +27,23 @@ export class UIEventSource<T>{
} }
} }
public static flatten<X>(source: UIEventSource<UIEventSource<X>>, possibleSources: UIEventSource<any>[]): UIEventSource<X> {
const sink = new UIEventSource<X>(source.data?.data);
source.addCallback((latestData) => {
sink.setData(latestData?.data);
});
for (const possibleSource of possibleSources) {
possibleSource.addCallback(() => {
sink.setData(source.data?.data);
})
}
return sink;
}
public map<J>(f: ((T) => J), public map<J>(f: ((T) => J),
extraSources: UIEventSource<any>[] = []): UIEventSource<J> { extraSources: UIEventSource<any>[] = []): UIEventSource<J> {
const self = this; const self = this;

View file

@ -21,6 +21,7 @@ export class UserBadge extends UIElement {
pendingChanges: UIElement, pendingChanges: UIElement,
basemap: Basemap) { basemap: Basemap) {
super(userDetails); super(userDetails);
this._userDetails = userDetails; this._userDetails = userDetails;
this._pendingChanges = pendingChanges; this._pendingChanges = pendingChanges;
this._basemap = basemap; this._basemap = basemap;

30
test.ts
View file

@ -7,11 +7,33 @@ import {OsmLink} from "./Customizations/Questions/OsmLink";
import {ConfirmDialog} from "./UI/ConfirmDialog"; import {ConfirmDialog} from "./UI/ConfirmDialog";
import {Imgur} from "./Logic/Imgur"; import {Imgur} from "./Logic/Imgur";
import {VariableUiElement} from "./UI/Base/VariableUIElement"; import {VariableUiElement} from "./UI/Base/VariableUIElement";
import {UIRadioButton} from "./UI/Base/UIRadioButton";
import {FixedInputElement} from "./UI/Base/FixedInputElement";
import {TextField} from "./UI/Base/TextField";
const html = new UIEventSource<string>("Some text"); const buttons = new UIRadioButton<number>(
[new FixedInputElement("Five", 5),
new FixedInputElement("Ten", 10),
new TextField<number>({
fromString: (str) => parseInt(str),
toString: (i) => ("" + i),
})
]
).AttachTo("maindiv");
const uielement = new VariableUiElement(html); buttons.GetValue().addCallback(console.log);
uielement.AttachTo("maindiv") buttons.GetValue().setData(10)
window.setTimeout(() => {html.setData("Different text")}, 1000) const value = new TextField<number>({
fromString: (str) => parseInt(str),
toString: (i) => {
if(isNaN(i)){
return ""
}
return ("" + i)
},
}).AttachTo("extradiv").GetValue();
value.setData(42);
value.addCallback(console.log)