mapcomplete/UI/TagRendering.ts

539 lines
19 KiB
TypeScript
Raw Normal View History

import {UIEventSource} from "../Logic/UIEventSource";
import {And, Tag, TagsFilter, TagUtils} from "../Logic/Tags";
2020-07-21 00:07:04 +02:00
import Translations from "../UI/i18n/Translations";
import Locale from "../UI/i18n/Locale";
import {State} from "../State";
import Translation from "../UI/i18n/Translation";
import Combine from "../UI/Base/Combine";
2020-09-10 19:33:06 +02:00
import {TagDependantUIElement} from "../Customizations/UIElementConstructor";
import {UIElement} from "./UIElement";
import {VariableUiElement} from "./Base/VariableUIElement";
import InputElementMap from "./Input/InputElementMap";
import {CheckBoxes} from "./Input/Checkboxes";
import {InputElement} from "./Input/InputElement";
import {SaveButton} from "./SaveButton";
import {RadioButton} from "./Input/RadioButton";
import {FixedInputElement} from "./Input/FixedInputElement";
import {TagRenderingOptions} from "../Customizations/TagRenderingOptions";
import {FixedUiElement} from "./Base/FixedUiElement";
2020-09-25 12:44:04 +02:00
import ValidatedTextField from "./Input/ValidatedTextField";
2020-09-09 18:42:13 +02:00
export class TagRendering extends UIElement implements TagDependantUIElement {
2020-07-05 18:59:47 +02:00
private readonly _question: string | Translation;
private readonly _mapping: { k: TagsFilter, txt: string | UIElement, priority?: number }[];
2020-07-08 16:24:12 +02:00
2020-09-09 18:42:13 +02:00
private currentTags: UIEventSource<any>;
private readonly _freeform: {
key: string,
template: string | UIElement,
renderTemplate: string | Translation,
placeholder?: string | UIElement,
2020-07-05 18:59:47 +02:00
extraTags?: TagsFilter
};
2020-07-20 15:54:50 +02:00
private readonly _questionElement: InputElement<TagsFilter>;
2020-07-05 18:59:47 +02:00
private readonly _saveButton: UIElement;
private readonly _friendlyLogin: UIElement;
2020-07-05 18:59:47 +02:00
private readonly _skipButton: UIElement;
private readonly _editButton: UIElement;
private readonly _appliedTags: UIElement;
2020-07-05 18:59:47 +02:00
private readonly _questionSkipped: UIEventSource<boolean> = new UIEventSource<boolean>(false);
private readonly _editMode: UIEventSource<boolean> = new UIEventSource<boolean>(false);
2020-07-31 17:38:03 +02:00
static injectFunction() {
// This is a workaround as not to import tagrendering into TagREnderingOptions
TagRenderingOptions.tagRendering = (tags, options) => new TagRendering(tags, options);
return true;
}
constructor(tags: UIEventSource<any>, options: {
question?: string | Translation,
2020-07-05 18:59:47 +02:00
freeform?: {
2020-07-31 17:38:03 +02:00
key: string,
template: string | Translation,
renderTemplate: string | Translation,
placeholder?: string | Translation,
2020-07-05 18:59:47 +02:00
extraTags?: TagsFilter,
},
tagsPreprocessor?: ((tags: any) => any),
2020-09-10 19:33:06 +02:00
multiAnswer?: boolean,
mappings?: { k: TagsFilter, txt: string | Translation, priority?: number, substitute?: boolean, hideInAnswer?: boolean }[]
2020-07-05 18:59:47 +02:00
}) {
super(tags);
this.ListenTo(Locale.language);
2020-07-05 18:59:47 +02:00
this.ListenTo(this._questionSkipped);
this.ListenTo(this._editMode);
this.ListenTo(State.state?.osmConnection?.userDetails);
2020-07-05 18:59:47 +02:00
const self = this;
2020-07-27 01:19:38 +02:00
this.currentTags = this._source.map(tags =>
{
if (options.tagsPreprocessor === undefined) {
return tags;
}
// we clone the tags...
let newTags = {};
for (const k in tags) {
newTags[k] = tags[k];
}
// ... in order to safely edit them here
options.tagsPreprocessor(newTags);
return newTags;
}
);
2020-07-27 01:19:38 +02:00
if (options.question !== undefined) {
this._question = options.question;
2020-07-27 01:19:38 +02:00
}
2020-07-05 18:59:47 +02:00
this._mapping = [];
this._freeform = options.freeform;
2020-07-08 16:07:16 +02:00
2020-07-05 18:59:47 +02:00
for (const choice of options.mappings ?? []) {
2020-07-21 00:07:04 +02:00
let choiceSubbed = {
k: choice.k?.substituteValues(this.currentTags.data),
2020-07-21 23:31:41 +02:00
txt: choice.txt,
2020-07-21 00:07:04 +02:00
priority: choice.priority
2020-07-05 18:59:47 +02:00
}
2020-07-08 11:23:36 +02:00
2020-07-21 00:07:04 +02:00
this._mapping.push({
k: choiceSubbed.k,
txt: choiceSubbed.txt
});
2020-07-05 18:59:47 +02:00
}
// Prepare the actual input element -> pick an appropriate implementation
2020-09-02 11:37:34 +02:00
this._questionElement = this.InputElementFor(options) ??
2020-09-10 19:33:06 +02:00
new FixedInputElement<TagsFilter>("<span class='alert'>No input possible</span>", new Tag("a", "b"));
2020-07-05 18:59:47 +02:00
const save = () => {
2020-07-20 15:54:50 +02:00
const selection = self._questionElement.GetValue().data;
console.log("Tagrendering: saving tags ", selection);
2020-07-05 18:59:47 +02:00
if (selection) {
2020-09-02 11:37:34 +02:00
State.state?.changes?.addTag(tags.data.id, selection);
2020-07-05 18:59:47 +02:00
}
self._editMode.setData(false);
}
this._appliedTags = new VariableUiElement(
self._questionElement.GetValue().map(
(tags: TagsFilter) => {
2020-09-02 11:37:34 +02:00
const csCount = State.state?.osmConnection?.userDetails?.data?.csCount ?? 1000;
if (csCount < State.userJourney.tagsVisibleAt) {
return "";
}
2020-09-24 23:56:08 +02:00
if (tags === undefined) {
return Translations.t.general.noTagsSelected.SetClass("subtle").Render();
}
if (csCount < State.userJourney.tagsVisibleAndWikiLinked) {
const tagsStr = tags.asHumanString(false, true);
2020-08-26 00:21:34 +02:00
return new FixedUiElement(tagsStr).SetClass("subtle").Render();
}
return tags.asHumanString(true, true);
}
)
2020-09-02 11:37:34 +02:00
).ListenTo(self._questionElement);
2020-07-05 18:59:47 +02:00
const cancel = () => {
self._questionSkipped.setData(true);
self._editMode.setData(false);
2020-07-08 16:07:16 +02:00
self._source.ping(); // Send a ping upstream to render the next question
2020-07-05 18:59:47 +02:00
}
// Setup the save button and it's action
2020-07-20 15:54:50 +02:00
this._saveButton = new SaveButton(this._questionElement.GetValue())
2020-07-05 18:59:47 +02:00
.onClick(save);
this._friendlyLogin = Translations.t.general.loginToStart.Clone()
.SetClass("login-button-friendly")
.onClick(() => State.state.osmConnection.AttemptLogin())
2020-07-20 15:54:50 +02:00
this._editButton = new FixedUiElement("");
2020-07-05 18:59:47 +02:00
if (this._question !== undefined) {
2020-09-13 00:53:24 +02:00
// 2.3em total width
2020-09-05 01:40:43 +02:00
this._editButton = new FixedUiElement(
"<img style='width: 1.3em;height: 1.3em;padding: 0.5em;border-radius: 0.65em;border: solid black 1px;font-size: medium;float: right;' " +
"src='./assets/pencil.svg' alt='edit'>")
2020-07-05 18:59:47 +02:00
.onClick(() => {
self._editMode.setData(true);
2020-07-20 21:39:07 +02:00
self._questionElement.GetValue().setData(self.CurrentValue());
2020-07-05 18:59:47 +02:00
});
}
const cancelContents = this._editMode.map((isEditing) => {
2020-09-12 23:15:17 +02:00
const tr = Translations.t.general;
const text = isEditing ? tr.cancel : tr.skip;
return text
.SetStyle("display: inline-block;border: solid black 0.5px;padding: 0.2em 0.3em;border-radius: 1.5em;")
.Render();
}, [Locale.language]);
2020-07-05 18:59:47 +02:00
// And at last, set up the skip button
2020-09-05 01:40:43 +02:00
this._skipButton = new VariableUiElement(cancelContents).onClick(cancel);
2020-07-20 15:54:50 +02:00
}
2020-07-05 18:59:47 +02:00
2020-07-20 15:54:50 +02:00
private InputElementFor(options: {
freeform?: {
2020-09-10 19:33:06 +02:00
key: string,
template: string | Translation,
renderTemplate: string | Translation,
placeholder?: string | Translation,
2020-07-20 15:54:50 +02:00
extraTags?: TagsFilter,
},
2020-09-10 19:33:06 +02:00
multiAnswer?: boolean,
mappings?: { k: TagsFilter, txt: string | Translation, priority?: number, substitute?: boolean, hideInAnswer?: boolean }[]
2020-07-20 15:54:50 +02:00
}):
InputElement<TagsFilter> {
2020-09-25 12:44:04 +02:00
let freeformElement: InputElement<TagsFilter> = undefined;
if (options.freeform !== undefined) {
freeformElement = this.InputForFreeForm(options.freeform);
}
2020-09-10 19:33:06 +02:00
if (options.mappings === undefined || options.mappings.length === 0) {
return freeformElement;
}
const elements: InputElement<TagsFilter>[] = [];
for (const mapping of options.mappings) {
if (mapping.k === null) {
continue;
}
if (mapping.hideInAnswer) {
continue;
2020-07-20 15:54:50 +02:00
}
2020-09-10 19:33:06 +02:00
elements.push(this.InputElementForMapping(mapping, mapping.substitute));
2020-07-20 15:54:50 +02:00
}
2020-09-10 19:33:06 +02:00
if (freeformElement !== undefined) {
elements.push(freeformElement);
2020-07-20 15:54:50 +02:00
}
if (!options.multiAnswer) {
return new RadioButton(elements, false);
} else {
2020-09-10 19:33:06 +02:00
const possibleTags = elements.map(el => el.GetValue().data);
const checkBoxes = new CheckBoxes(elements);
2020-09-10 21:06:56 +02:00
const inputEl = new InputElementMap<number[], TagsFilter>(checkBoxes,
(t0, t1) => {
return t0?.isEquivalent(t1) ?? false
2020-09-10 19:33:06 +02:00
},
2020-09-10 21:06:56 +02:00
(indices) => {
if (indices.length === 0) {
return undefined;
2020-09-10 19:33:06 +02:00
}
2020-09-10 21:06:56 +02:00
let tags: TagsFilter[] = indices.map(i => elements[i].GetValue().data);
return TagUtils.FlattenMultiAnswer(tags);
2020-09-10 19:33:06 +02:00
},
2020-09-10 21:06:56 +02:00
(tags: TagsFilter) => {
const splitUpValues = TagUtils.SplitMultiAnswer(tags, possibleTags, this._freeform?.key, this._freeform?.extraTags);
const indices: number[] = []
for (let i = 0; i < splitUpValues.length; i++) {
let splitUpValue = splitUpValues[i];
for (let j = 0; j < elements.length; j++) {
let inputElement = elements[j];
if (inputElement.IsValid(splitUpValue)) {
indices.push(j);
inputElement.GetValue().setData(splitUpValue);
break;
}
}
}
return indices;
2020-09-11 00:23:19 +02:00
},
[freeformElement?.GetValue()]
2020-09-10 19:33:06 +02:00
);
2020-09-11 00:23:19 +02:00
freeformElement?.GetValue()?.addCallbackAndRun(value => {
2020-09-10 21:06:56 +02:00
const es = checkBoxes.GetValue();
2020-09-11 00:23:19 +02:00
const i = elements.length - 1;
const index = es.data.indexOf(i);
if (value === undefined) {
if (index >= 0) {
es.data.splice(index, 1);
es.ping();
}
} else if (index < 0) {
2020-09-10 21:06:56 +02:00
es.data.push(i);
es.ping();
}
});
2020-07-20 15:54:50 +02:00
2020-09-10 21:06:56 +02:00
return inputEl;
2020-09-10 19:33:06 +02:00
}
2020-07-05 18:59:47 +02:00
}
2020-07-20 15:54:50 +02:00
2020-09-10 19:33:06 +02:00
private InputElementForMapping(mapping: { k: TagsFilter, txt: (string | Translation) }, substituteValues: boolean): FixedInputElement<TagsFilter> {
2020-09-09 18:42:13 +02:00
if (substituteValues) {
return new FixedInputElement(this.ApplyTemplate(mapping.txt),
mapping.k.substituteValues(this.currentTags.data),
(t0, t1) => t0.isEquivalent(t1)
);
}
2020-09-10 19:33:06 +02:00
return new FixedInputElement(this.ApplyTemplate(mapping.txt), mapping.k,
2020-09-14 20:16:03 +02:00
(t0, t1) => t1.isEquivalent(t0));
2020-07-20 15:54:50 +02:00
}
2020-09-26 01:11:17 +02:00
private InputForFreeForm(freeform: {
2020-09-09 18:42:13 +02:00
key: string,
template: string | Translation,
renderTemplate: string | Translation,
placeholder?: string | Translation,
extraTags?: TagsFilter,
2020-09-25 12:44:04 +02:00
}): InputElement<TagsFilter> {
2020-09-02 11:37:34 +02:00
if (freeform?.template === undefined) {
2020-07-20 15:54:50 +02:00
return undefined;
}
2020-07-29 20:19:29 +02:00
const prepost = Translations.W(freeform.template).InnerRender()
.replace("$$$", "$string$")
2020-07-29 20:19:29 +02:00
.split("$");
2020-09-25 12:44:04 +02:00
let type = prepost[1];
2020-09-26 01:11:17 +02:00
2020-09-25 12:44:04 +02:00
let isTextArea = false;
if(type === "text"){
isTextArea = true;
type = "string";
}
if(ValidatedTextField.AllTypes[type] === undefined){
console.error("Type:",type, ValidatedTextField.AllTypes)
throw "Unkown type: "+type;
}
2020-07-20 15:54:50 +02:00
const pickString =
2020-07-23 17:32:18 +02:00
(string: any) => {
2020-07-20 15:54:50 +02:00
if (string === "" || string === undefined) {
return undefined;
}
2020-09-02 11:37:34 +02:00
2020-09-26 21:00:03 +02:00
const tag = new Tag(freeform.key, string);
2020-09-02 11:37:34 +02:00
2020-07-20 15:54:50 +02:00
if (freeform.extraTags === undefined) {
return tag;
}
return new And([
tag,
freeform.extraTags
2020-07-20 15:54:50 +02:00
]
);
};
2020-09-10 21:06:56 +02:00
const toString = (tag) => {
if (tag instanceof And) {
for (const subtag of tag.and) {
if (subtag instanceof Tag && subtag.key === freeform.key) {
return subtag.value;
2020-09-09 18:42:13 +02:00
}
2020-07-20 15:54:50 +02:00
}
2020-09-10 21:06:56 +02:00
2020-07-20 15:54:50 +02:00
return undefined;
2020-09-10 21:06:56 +02:00
} else if (tag instanceof Tag) {
return tag.value
2020-07-20 15:54:50 +02:00
}
2020-09-10 21:06:56 +02:00
return undefined;
}
2020-09-26 01:11:17 +02:00
return ValidatedTextField.Mapped(pickString, toString, {
placeholder: freeform.placeholder,
type: type,
isValid: (str) => (str.length <= 255),
2020-09-26 21:00:03 +02:00
textArea: isTextArea,
country: this._source.data._country
2020-09-26 01:11:17 +02:00
})
2020-07-05 18:59:47 +02:00
}
2020-07-20 15:54:50 +02:00
2020-07-05 18:59:47 +02:00
IsKnown(): boolean {
const tags = TagUtils.proprtiesToKV(this._source.data);
2020-07-21 23:31:41 +02:00
for (const oneOnOneElement of this._mapping) {
if (oneOnOneElement.k === null || oneOnOneElement.k === undefined || oneOnOneElement.k.matches(tags)) {
2020-07-05 18:59:47 +02:00
return true;
}
}
return this._freeform !== undefined && this._source.data[this._freeform.key] !== undefined;
}
2020-07-25 01:07:02 +02:00
IsSkipped(): boolean {
return this._questionSkipped.data;
}
2020-07-20 15:54:50 +02:00
private CurrentValue(): TagsFilter {
const tags = TagUtils.proprtiesToKV(this._source.data);
2020-07-21 23:31:41 +02:00
for (const oneOnOneElement of this._mapping) {
if (oneOnOneElement.k !== null && oneOnOneElement.k.matches(tags)) {
2020-07-20 15:54:50 +02:00
return oneOnOneElement.k;
}
}
if (this._freeform === undefined) {
return undefined;
}
return new Tag(this._freeform.key, this._source.data[this._freeform.key]);
}
2020-07-05 18:59:47 +02:00
IsQuestioning(): boolean {
if (this.IsKnown()) {
return false;
}
2020-09-02 11:37:34 +02:00
if (this._question === undefined ||
this._question === "" ||
2020-09-02 11:37:34 +02:00
(this._freeform?.template === undefined && (this._mapping?.length ?? 0) == 0)) {
2020-07-05 18:59:47 +02:00
// We don't ask this question in the first place
return false;
}
if (this._questionSkipped.data) {
// We don't ask for this question anymore, skipped by user
return false;
}
return true;
}
private RenderAnswer(): UIElement {
2020-07-05 18:59:47 +02:00
const tags = TagUtils.proprtiesToKV(this._source.data);
2020-07-21 00:07:04 +02:00
let freeform: UIElement = new FixedUiElement("");
2020-07-05 18:59:47 +02:00
let freeformScore = -10;
if (this._freeform !== undefined && this._source.data[this._freeform.key] !== undefined) {
freeform = this.ApplyTemplate(this._freeform.renderTemplate);
freeformScore = 0;
}
2020-07-21 00:07:04 +02:00
let highestScore = -100;
let highestTemplate = undefined;
2020-07-21 23:31:41 +02:00
for (const oneOnOneElement of this._mapping) {
2020-07-21 00:07:04 +02:00
if (oneOnOneElement.k == null ||
oneOnOneElement.k.matches(tags)) {
// We have found a matching key -> we use the template, but only if it scores better
let score = oneOnOneElement.priority ??
(oneOnOneElement.k === null ? -1 : 0);
if (score > highestScore) {
highestScore = score;
highestTemplate = oneOnOneElement.txt
2020-07-05 18:59:47 +02:00
}
}
2020-07-21 00:07:04 +02:00
}
2020-07-05 18:59:47 +02:00
2020-07-21 00:07:04 +02:00
if (freeformScore > highestScore) {
return freeform;
}
if (highestTemplate !== undefined) {
// we render the found template
return this.ApplyTemplate(highestTemplate);
}
2020-07-05 18:59:47 +02:00
}
2020-07-20 18:24:00 +02:00
InnerRender(): string {
2020-09-02 11:37:34 +02:00
if (this.IsQuestioning()
&& (State.state !== undefined) // If State.state is undefined, we are testing/custom theme building -> show regular save
&& !State.state.osmConnection.userDetails.data.loggedIn) {
const question =
this.ApplyTemplate(this._question).SetClass('question-text');
return "<div class='question'>" +
new Combine([
question,
"<br/>",
this._questionElement,
2020-09-02 11:37:34 +02:00
this._friendlyLogin,
]).Render() + "</div>";
}
2020-07-05 18:59:47 +02:00
if (this.IsQuestioning() || this._editMode.data) {
// Not yet known or questioning, we have to ask a question
return "<div class='question'>" +
2020-08-26 00:21:34 +02:00
new Combine([
"<span class='question-text'>",
this.ApplyTemplate(this._question),
"</span>",
"<br/>",
"<div>", this._questionElement , "</div>",
this._skipButton,
this._saveButton,
"<br/>",
this._appliedTags
]).Render() +
2020-07-05 18:59:47 +02:00
"</div>"
}
if (this.IsKnown()) {
const answer = this.RenderAnswer();
2020-09-13 00:53:24 +02:00
if (answer.IsEmpty()) {
2020-07-05 18:59:47 +02:00
return "";
}
2020-09-13 00:53:24 +02:00
const answerStyle = " display: inline-block;" +
" margin: 0.1em;" +
" width: 100%;" +
" font-size: large;"
2020-09-02 11:37:34 +02:00
if (State.state === undefined || // state undefined -> we are custom testing
State.state?.osmConnection?.userDetails?.data?.loggedIn && this._question !== undefined) {
2020-09-13 00:53:24 +02:00
answer.SetStyle("display:inline-block;width:calc(100% - 2.3em);")
return new Combine([
answer,
this._editButton])
.SetStyle(answerStyle)
.Render();
}
2020-07-20 15:54:50 +02:00
2020-09-13 00:53:24 +02:00
return answer.SetStyle(answerStyle).Render();
2020-07-05 18:59:47 +02:00
}
return "";
}
2020-07-20 15:54:50 +02:00
private ApplyTemplate(template: string | Translation): UIElement {
2020-07-27 01:19:38 +02:00
if (template === undefined || template === null) {
return undefined;
2020-07-21 00:07:04 +02:00
}
return new VariableUiElement(this.currentTags.map(tags => {
const tr = Translations.WT(template);
if (tr.Subs === undefined) {
// This is a weird edge case
return tr.InnerRender();
}
return tr.Subs(tags).InnerRender()
2020-09-10 19:33:06 +02:00
})).ListenTo(Locale.language);
2020-07-05 18:59:47 +02:00
}
2020-07-21 00:07:04 +02:00
2020-07-27 01:19:38 +02:00
2020-07-05 18:59:47 +02:00
}