Merge develop

This commit is contained in:
Pieter Vander Vennet 2020-09-27 00:42:33 +02:00
commit 620a1f8df2
27 changed files with 1206 additions and 1151 deletions

View file

@ -0,0 +1,35 @@
import {InputElement} from "./InputElement";
import {UIEventSource} from "../../Logic/UIEventSource";
import Combine from "../Base/Combine";
import {UIElement} from "../UIElement";
export default class CombinedInputElement<T> extends InputElement<T> {
private readonly _a: InputElement<T>;
private readonly _b: UIElement;
private readonly _combined: UIElement;
public readonly IsSelected: UIEventSource<boolean>;
constructor(a: InputElement<T>, b: InputElement<T>) {
super();
this._a = a;
this._b = b;
this.IsSelected = this._a.IsSelected.map((isSelected) => {
return isSelected || b.IsSelected.data
}, [b.IsSelected])
this._combined = new Combine([this._a, this._b]);
}
GetValue(): UIEventSource<T> {
return this._a.GetValue();
}
InnerRender(): string {
return this._combined.Render();
}
IsValid(t: T): boolean {
return this._a.IsValid(t);
}
}

View file

@ -6,13 +6,11 @@ export default class MultiLingualTextFields extends InputElement<any> {
private _fields: Map<string, TextField> = new Map<string, TextField>();
private readonly _value: UIEventSource<any>;
public readonly IsSelected: UIEventSource<boolean> = new UIEventSource<boolean>(false);
constructor(languages: UIEventSource<string[]>,
textArea: boolean = false,
value: UIEventSource<Map<string, UIEventSource<string>>> = undefined) {
super(undefined);
this._value = value ?? new UIEventSource({});
this._value.addCallbackAndRun(latestData => {
if (typeof (latestData) === "string") {
console.warn("Refusing string for multilingual input", latestData);

View file

@ -3,7 +3,6 @@ import TagInput from "./SingleTagInput";
import {MultiInput} from "./MultiInput";
export class MultiTagInput extends MultiInput<string> {
constructor(value: UIEventSource<string[]> = new UIEventSource<string[]>([])) {
super("Add a new tag",

View file

@ -11,8 +11,7 @@ export class RadioButton<T> extends InputElement<T> {
private readonly value: UIEventSource<T>;
private readonly _elements: InputElement<T>[]
private readonly _selectFirstAsDefault: boolean;
constructor(elements: InputElement<T>[],
selectFirstAsDefault = true) {
super(undefined);
@ -20,7 +19,6 @@ export class RadioButton<T> extends InputElement<T> {
this._selectFirstAsDefault = selectFirstAsDefault;
const self = this;
this.value =
UIEventSource.flatten(this._selectedElementIndex.map(
(selectedIndex) => {

View file

@ -0,0 +1,60 @@
import {InputElement} from "./InputElement";
import {UIEventSource} from "../../Logic/UIEventSource";
export default class SimpleDatePicker extends InputElement<string> {
private readonly value: UIEventSource<string>
constructor(
value?: UIEventSource<string>
) {
super();
this.value = value ?? new UIEventSource<string>(undefined);
const self = this;
this.value.addCallbackAndRun(v => {
if(v === undefined){
return;
}
self.SetValue(v);
});
}
InnerRender(): string {
return `<span id="${this.id}"><input type='date' id='date-${this.id}'></span>`;
}
private SetValue(date: string){
const field = document.getElementById("date-" + this.id);
if (field === undefined || field === null) {
return;
}
// @ts-ignore
field.value = date;
}
protected InnerUpdate() {
const field = document.getElementById("date-" + this.id);
if (field === undefined || field === null) {
return;
}
const self = this;
field.oninput = () => {
// Already in YYYY-MM-DD value!
// @ts-ignore
self.value.setData(field.value);
}
}
GetValue(): UIEventSource<string> {
return this.value;
}
IsSelected: UIEventSource<boolean> = new UIEventSource<boolean>(false);
IsValid(t: string): boolean {
return false;
}
}

View file

@ -22,7 +22,6 @@ export default class SingleTagInput extends InputElement<string> {
constructor(value: UIEventSource<string> = undefined) {
super(undefined);
this._value = value ?? new UIEventSource<string>("");
this.helpMessage = new VariableUiElement(this._value.map(tagDef => {
try {
FromJSON.Tag(tagDef, "");

View file

@ -11,12 +11,14 @@ export class TextField extends InputElement<string> {
private readonly _isArea: boolean;
private readonly _textAreaRows: number;
private readonly _isValid: (string, country) => boolean;
constructor(options?: {
placeholder?: string | UIElement,
value?: UIEventSource<string>,
textArea?: boolean,
textAreaRows?: number,
isValid?: ((s: string) => boolean)
isValid?: ((s: string, country?: string) => boolean)
}) {
super(undefined);
const self = this;
@ -25,9 +27,8 @@ export class TextField extends InputElement<string> {
this._isArea = options.textArea ?? false;
this.value = options?.value ?? new UIEventSource<string>(undefined);
// @ts-ignore
this._fromString = options.fromString ?? ((str) => (str))
this._textAreaRows = options.textAreaRows;
this._isValid = options.isValid ?? ((str, country) => true);
this._placeholder = Translations.W(options.placeholder ?? "");
this.ListenTo(this._placeholder._source);
@ -36,23 +37,20 @@ export class TextField extends InputElement<string> {
self.IsSelected.setData(true)
});
this.value.addCallback((t) => {
const field = document.getElementById(this.id);
console.log("Setting actual value to", t);
const field = document.getElementById("txt-"+this.id);
if (field === undefined || field === null) {
return;
}
if (options.isValid) {
field.className = options.isValid(t) ? "" : "invalid";
}
field.className = self.IsValid(t) ? "" : "invalid";
if (t === undefined || t === null) {
// @ts-ignore
return;
}
// @ts-ignore
field.value = t;
});
this.dumbMode = false;
this.SetClass("deadbeef")
}
GetValue(): UIEventSource<string> {
@ -72,16 +70,37 @@ export class TextField extends InputElement<string> {
`</form></span>`;
}
Update() {
super.Update();
}
InnerUpdate() {
const field = document.getElementById("txt-" + this.id);
const self = this;
field.oninput = () => {
// How much characters are on the right, not including spaces?
// @ts-ignore
self.value.setData(field.value);
const endDistance = field.value.substring(field.selectionEnd).replace(/ /g,'').length;
// @ts-ignore
let val: string = field.value;
if (!self.IsValid(val)) {
self.value.setData(undefined);
} else {
self.value.setData(val);
}
// Setting the value might cause the value to be set again. We keep the distance _to the end_ stable, as phone number formatting might cause the start to change
// See https://github.com/pietervdvn/MapComplete/issues/103
// We reread the field value - it might have changed!
// @ts-ignore
val = field.value;
let newCursorPos = val.length - endDistance;
while(newCursorPos >= 0 &&
// We count the number of _actual_ characters (non-space characters) on the right of the new value
// This count should become bigger then the end distance
val.substr(newCursorPos).replace(/ /g, '').length < endDistance
){
newCursorPos --;
}
// @ts-ignore
self.SetCursorPosition(newCursorPos);
};
if (this.value.data !== undefined && this.value.data !== null) {
@ -103,7 +122,7 @@ export class TextField extends InputElement<string> {
}
public SetCursorPosition(i: number) {
const field = document.getElementById('text-' + this.id);
const field = document.getElementById('txt-' + this.id);
if(field === undefined || field === null){
return;
}
@ -114,11 +133,14 @@ export class TextField extends InputElement<string> {
field.focus();
// @ts-ignore
field.setSelectionRange(i, i);
}
IsValid(t: string): boolean {
return !(t === undefined || t === null);
if (t === undefined || t === null) {
return false
}
return this._isValid(t, undefined);
}
}
}

View file

@ -6,6 +6,16 @@ import {InputElement} from "./InputElement";
import {TextField} from "./TextField";
import {UIElement} from "../UIElement";
import {UIEventSource} from "../../Logic/UIEventSource";
import CombinedInputElement from "./CombinedInputElement";
import SimpleDatePicker from "./SimpleDatePicker";
interface TextFieldDef {
name: string,
explanation: string,
isValid: ((s: string, country?: string) => boolean),
reformat?: ((s: string, country?: string) => string),
inputHelper?: (value:UIEventSource<string>) => InputElement<string>
}
export default class ValidatedTextField {
@ -13,12 +23,8 @@ export default class ValidatedTextField {
private static tp(name: string,
explanation: string,
isValid?: ((s: string, country?: string) => boolean),
reformat?: ((s: string, country?: string) => string)): {
name: string,
explanation: string,
isValid: ((s: string, country?: string) => boolean),
reformat?: ((s: string, country?: string) => string)
} {
reformat?: ((s: string, country?: string) => string),
inputHelper?: (value: UIEventSource<string>) => InputElement<string>): TextFieldDef {
if (isValid === undefined) {
isValid = () => true;
@ -33,17 +39,36 @@ export default class ValidatedTextField {
name: name,
explanation: explanation,
isValid: isValid,
reformat: reformat
reformat: reformat,
inputHelper: inputHelper
}
}
public static tpList = [
public static tpList: TextFieldDef[] = [
ValidatedTextField.tp(
"string",
"A basic string"),
ValidatedTextField.tp(
"date",
"A date"),
"A date",
(str) => {
const time = Date.parse(str);
return !isNaN(time);
},
(str) => {
const d = new Date(str);
let month = '' + (d.getMonth() + 1);
let day = '' + d.getDate();
const year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
},
(value) => new SimpleDatePicker(value)),
ValidatedTextField.tp(
"wikidata",
"A wikidata identifier, e.g. Q42"),
@ -82,17 +107,40 @@ export default class ValidatedTextField {
(str) => EmailValidator.validate(str)),
ValidatedTextField.tp(
"url",
"A url"),
"A url",
(str) => {
try {
new URL(str);
return true;
} catch (e) {
return false;
}
}, (str) => {
try {
const url = new URL(str);
const blacklistedTrackingParams = [
"fbclid",// Oh god, how I hate the fbclid. Let it burn, burn in hell!
"gclid",
"cmpid", "agid", "utm", "utm_source"]
for (const dontLike of blacklistedTrackingParams) {
url.searchParams.delete(dontLike)
}
return url.toString();
} catch (e) {
console.error(e)
return undefined;
}
}),
ValidatedTextField.tp(
"phone",
"A phone number",
(str, country: any) => {
if (str === undefined) {
return false;
}
return parsePhoneNumberFromString(str, country?.toUpperCase())?.isValid() ?? false
},
(str, country: any) => {
console.log("country formatting", country)
return parsePhoneNumberFromString(str, country?.toUpperCase()).formatInternational()
}
(str, country: any) => parsePhoneNumberFromString(str, country?.toUpperCase()).formatInternational()
)
]
@ -112,15 +160,50 @@ export default class ValidatedTextField {
}
return new DropDown<string>("", values)
}
public static AllTypes = ValidatedTextField.allTypesDict();
public static InputForType(type: string): TextField {
return new TextField({
placeholder: type,
isValid: ValidatedTextField.AllTypes[type]
})
public static InputForType(type: string, options?: {
placeholder?: string | UIElement,
value?: UIEventSource<string>,
textArea?: boolean,
textAreaRows?: number,
isValid?: ((s: string, country: string) => boolean),
country?: string
}): InputElement<string> {
options = options ?? {};
options.placeholder = options.placeholder ?? type;
const tp: TextFieldDef = ValidatedTextField.AllTypes[type]
const isValidTp = tp.isValid;
let isValid;
if (options.isValid) {
const optValid = options.isValid;
isValid = (str, country) => {
if(str === undefined){
return false;
}
return isValidTp(str, country ?? options.country) && optValid(str, country ?? options.country);
}
}else{
isValid = isValidTp;
}
options.isValid = isValid;
let input: InputElement<string> = new TextField(options);
if (tp.reformat) {
input.GetValue().addCallbackAndRun(str => {
if (!options.isValid(str, options.country)) {
return;
}
const formatted = tp.reformat(str, options.country);
input.GetValue().setData(formatted);
})
}
if (tp.inputHelper) {
input = new CombinedInputElement(input, tp.inputHelper(input.GetValue()));
}
return input;
}
public static NumberInput(type: string = "int", extraValidation: (number: Number) => boolean = undefined): InputElement<number> {
@ -179,13 +262,20 @@ export default class ValidatedTextField {
static Mapped<T>(fromString: (str) => T, toString: (T) => string, options?: {
placeholder?: string | UIElement,
type?: string,
value?: UIEventSource<string>,
startValidated?: boolean,
textArea?: boolean,
textAreaRows?: number,
isValid?: ((string: string) => boolean)
isValid?: ((string: string) => boolean),
country?: string
}): InputElement<T> {
const textField = new TextField(options);
let textField: InputElement<string>;
if (options.type) {
textField = ValidatedTextField.InputForType(options.type, options);
} else {
textField = new TextField(options);
}
return new InputElementMap(
textField, (a, b) => a === b,
fromString, toString