Fix #896: improve placeholder dynamism, add more tests for UI code

This commit is contained in:
pietervdvn 2022-06-30 03:07:54 +02:00
parent 94475e4d4d
commit 972d702315
7 changed files with 148 additions and 66 deletions

View file

@ -117,11 +117,12 @@ export default class TagRenderingConfig {
let placeholder: Translation = Translations.T(json.freeform.placeholder)
if (placeholder === undefined) {
const typeDescription = Translations.t.validation[type]?.description
const typeDescription = <Translation> Translations.t.validation[type]?.description
const key = json.freeform.key;
if(typeDescription !== undefined){
placeholder = Translations.T(json.freeform.key+" ({"+type+"})").Subs({[type]: typeDescription})
placeholder = typeDescription.OnEveryLanguage(l => key+" ("+l+")")
}else{
placeholder = Translations.T(json.freeform.key+" ("+type+")")
placeholder = Translations.T(key+" ("+type+")")
}
}

View file

@ -156,7 +156,6 @@ export default class MinimapImplementation extends BaseUIElement implements Mini
}
try {
console.log("SELF IS", self)
self.leafletMap?.data?.invalidateSize()
} catch (e) {
console.warn("Could not invalidate size of a minimap:", e)

View file

@ -7,6 +7,7 @@ import {Geocoding} from "../../Logic/Osm/Geocoding";
import Translations from "../i18n/Translations";
import Hash from "../../Logic/Web/Hash";
import Combine from "../Base/Combine";
import Locale from "../i18n/Locale";
export default class SearchAndGo extends Combine {
constructor(state: {
@ -21,7 +22,7 @@ export default class SearchAndGo extends Combine {
Translations.t.general.search.search
);
const searchField = new TextField({
placeholder: new VariableUiElement(placeholder),
placeholder: placeholder.map(tr => tr.textFor(Locale.language.data), [Locale.language]),
value: new UIEventSource<string>(""),
inputStyle:
" background: transparent;\n" +

View file

@ -1,35 +1,123 @@
import {InputElement} from "./InputElement";
import Translations from "../i18n/Translations";
import {UIEventSource} from "../../Logic/UIEventSource";
import {Store, UIEventSource} from "../../Logic/UIEventSource";
import BaseUIElement from "../BaseUIElement";
import {Translation} from "../i18n/Translation";
import Locale from "../i18n/Locale";
interface TextFieldOptions {
placeholder?: string | Store<string> | Translation,
value?: UIEventSource<string>,
htmlType?: "area" | "text" | "time" | string,
inputMode?: string,
label?: BaseUIElement,
textAreaRows?: number,
inputStyle?: string,
isValid?: (s: string) => boolean
}
export class TextField extends InputElement<string> {
public readonly enterPressed = new UIEventSource<string>(undefined);
private readonly value: UIEventSource<string>;
private _element: HTMLElement;
private _actualField : HTMLElement
private readonly _isValid: (s: string) => boolean;
private _rawValue: UIEventSource<string>
private readonly _rawValue: UIEventSource<string>
private _isFocused = false;
private readonly _options : TextFieldOptions;
constructor(options?: {
placeholder?: string | BaseUIElement,
value?: UIEventSource<string>,
htmlType?: "area" | "text" | "time" | string,
inputMode?: string,
label?: BaseUIElement,
textAreaRows?: number,
inputStyle?: string,
isValid?: (s: string) => boolean
}) {
constructor(options?: TextFieldOptions) {
super();
const self = this;
this._options = options ?? {}
options = options ?? {};
this.value = options?.value ?? new UIEventSource<string>(undefined);
this._rawValue = new UIEventSource<string>("")
this._isValid = options.isValid ?? (_ => true);
}
const placeholder = Translations.W(options.placeholder ?? "").ConstructElement().textContent.replace("'", "&#39");
private static SetCursorPosition(textfield: HTMLElement, i: number) {
if (textfield === undefined || textfield === null) {
return;
}
if (i === -1) {
// @ts-ignore
i = textfield.value.length;
}
textfield.focus();
// @ts-ignore
textfield.setSelectionRange(i, i);
}
GetValue(): UIEventSource<string> {
return this.value;
}
GetRawValue(): UIEventSource<string>{
return this._rawValue
}
IsValid(t: string): boolean {
if (t === undefined || t === null) {
return false
}
return this._isValid(t);
}
private static test(){
const placeholder = new UIEventSource<string>("placeholder")
const tf = new TextField({
placeholder
})
const html = <HTMLInputElement> tf.InnerConstructElement().children[0];
html.placeholder // => 'placeholder'
placeholder.setData("another piece of text")
html.placeholder// => "another piece of text"
}
/**
*
* // should update placeholders dynamically
* const placeholder = new UIEventSource<string>("placeholder")
* const tf = new TextField({
* placeholder
* })
* const html = <HTMLInputElement> tf.InnerConstructElement().children[0];
* html.placeholder // => 'placeholder'
* placeholder.setData("another piece of text")
* html.placeholder// => "another piece of text"
*
* // should update translated placeholders dynamically
* const placeholder = new Translation({nl: "Nederlands", en: "English"})
* Locale.language.setData("nl");
* const tf = new TextField({
* placeholder
* })
* const html = <HTMLInputElement> tf.InnerConstructElement().children[0];
* html.placeholder// => "Nederlands"
* Locale.language.setData("en");
* html.placeholder // => 'English'
*/
protected InnerConstructElement(): HTMLElement {
const options = this._options;
const self = this;
let placeholderStore: Store<string>
let placeholder : string = "";
if(options.placeholder){
if(typeof options.placeholder === "string"){
placeholder = options.placeholder;
placeholderStore = undefined;
}else {
if ((options.placeholder instanceof Store) && options.placeholder["data"] !== undefined) {
placeholderStore = options.placeholder;
} else if ((options.placeholder instanceof Translation) && options.placeholder["translations"] !== undefined) {
placeholderStore = <Store<string>>Locale.language.map(l => (<Translation>options.placeholder).textFor(l))
}
placeholder = placeholderStore?.data ?? placeholder ?? "";
}
}
this.SetClass("form-text-field")
let inputEl: HTMLElement
@ -41,6 +129,9 @@ export class TextField extends InputElement<string> {
el.cols = 50
el.style.width = "100%"
inputEl = el;
if(placeholderStore){
placeholderStore.addCallbackAndRunD(placeholder => el.placeholder = placeholder)
}
} else {
const el = document.createElement("input")
el.type = options.htmlType ?? "text"
@ -48,8 +139,13 @@ export class TextField extends InputElement<string> {
el.placeholder = placeholder
el.style.cssText = options.inputStyle ?? "width: 100%;"
inputEl = el
if(placeholderStore){
placeholderStore.addCallbackAndRunD(placeholder => el.placeholder = placeholder)
}
}
const form = document.createElement("form")
form.appendChild(inputEl)
form.onsubmit = () => false;
@ -58,7 +154,6 @@ export class TextField extends InputElement<string> {
form.appendChild(options.label.ConstructElement())
}
this._element = form;
const field = inputEl;
@ -110,47 +205,13 @@ export class TextField extends InputElement<string> {
self.enterPressed.setData(field.value);
}
});
if(this._isFocused){
field.focus()
}
this._actualField = field;
}
private static SetCursorPosition(textfield: HTMLElement, i: number) {
if (textfield === undefined || textfield === null) {
return;
}
if (i === -1) {
// @ts-ignore
i = textfield.value.length;
}
textfield.focus();
// @ts-ignore
textfield.setSelectionRange(i, i);
}
GetValue(): UIEventSource<string> {
return this.value;
}
GetRawValue(): UIEventSource<string>{
return this._rawValue
}
IsValid(t: string): boolean {
if (t === undefined || t === null) {
return false
}
return this._isValid(t);
}
protected InnerConstructElement(): HTMLElement {
return this._element;
return form;
}
public focus() {

View file

@ -70,7 +70,7 @@ export class TextFieldDef {
value?: UIEventSource<string>,
inputStyle?: string,
feedback?: UIEventSource<Translation>
placeholder?: string | BaseUIElement,
placeholder?: string | Translation | UIEventSource<string>,
country?: () => string,
location?: [number /*lat*/, number /*lon*/],
mapBackgroundLayer?: UIEventSource</*BaseLayer*/ any>,

View file

@ -114,29 +114,42 @@ export class Translation extends BaseUIElement {
/**
*
* // Should actually change the content based on the current language
* const tr = new Translation({"en":"English", nl: "Nederlands"})
* Locale.language.setData("en")
* const html = tr.InnerConstructElement()
* html.innerHTML // => "English"
* Locale.language.setData("nl")
* html.innerHTML // => "Nederlands"
*
* // Should include a link to weblate if context is set
* const tr = new Translation({"en":"English"}, "core:test.xyz")
* Locale.language.setData("nl")
* Locale.showLinkToWeblate.setData(true)
* const html = tr.InnerConstructElement()
* html.getElementsByTagName("a")[0].href // => "https://hosted.weblate.org/translate/mapcomplete/core/nl/?offset=1&q=context%3A%3D%22test.xyz%22"
*/
InnerConstructElement(): HTMLElement {
const el = document.createElement("span")
const self = this
el.innerHTML = self.txt
if (self.translations["*"] !== undefined) {
return el;
}
Locale.language.addCallbackAndRun(_ => {
Locale.language.addCallback(_ => {
if (self.isDestroyed) {
return true
}
el.innerHTML = self.txt
})
if (self.translations["*"] !== undefined || self.context === undefined || self.context?.indexOf(":") < 0) {
if(self.context === undefined || self.context?.indexOf(":") < 0){
return el;
}
const linkToWeblate = new LinkToWeblate(self.context, self.translations)
const wrapper = document.createElement("span")
@ -174,7 +187,10 @@ export class Translation extends BaseUIElement {
public AllValues(): string[] {
return this.SupportedLanguages().map(lng => this.translations[lng]);
}
/**
* Constructs a new Translation where every contained string has been modified
*/
public OnEveryLanguage(f: (s: string, language: string) => string, context?: string): Translation {
const newTranslations = {};
for (const lang in this.translations) {
@ -197,6 +213,7 @@ export class Translation extends BaseUIElement {
* const r = tr.replace("{key}", "value")
* r.textFor("nl") // => "Een voorbeeldtekst met value en {key1}, en nogmaals value"
* r.textFor("en") // => "Just a single value"
*
*/
public replace(a: string, b: string) {
return this.OnEveryLanguage(str => str.replace(new RegExp(a, "g"), b))
@ -290,6 +307,7 @@ export class TypedTranslation<T> extends Translation {
* const subbed = tr.Subs({part: subpart})
* subbed.textFor("en") // => "Full sentence with subpart"
* subbed.textFor("nl") // => "Volledige zin met onderdeel"
*
*/
Subs(text: T, context?: string): Translation {
return this.OnEveryLanguage((template, lang) => {

View file

@ -1,11 +1,13 @@
import ScriptUtils from "../scripts/ScriptUtils";
import {Utils} from "../Utils";
import * as fakedom from "fake-dom"
import Locale from "../UI/i18n/Locale";
export const mochaHooks = {
beforeEach(done) {
ScriptUtils.fixUtils();
Locale.language.setData("en")
if (fakedom === undefined || window === undefined) {
throw "FakeDom not initialized"