forked from MapComplete/MapComplete
Cleanup of textfield code
This commit is contained in:
parent
1f41444726
commit
3667f28f15
9 changed files with 293 additions and 219 deletions
|
@ -9,6 +9,7 @@ export default class InputElementMap<T, X> extends InputElement<X> {
|
|||
private readonly fromX: (x: X) => T;
|
||||
private readonly toX: (t: T) => X;
|
||||
private readonly _value: UIEventSource<X>;
|
||||
public readonly IsSelected: UIEventSource<boolean>;
|
||||
|
||||
constructor(inputElement: InputElement<T>,
|
||||
isSame: (x0: X, x1: X) => boolean,
|
||||
|
@ -32,8 +33,7 @@ export default class InputElementMap<T, X> extends InputElement<X> {
|
|||
}
|
||||
return newX;
|
||||
}), extraSources, x => {
|
||||
const newT = fromX(x);
|
||||
return newT;
|
||||
return fromX(x);
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -45,10 +45,15 @@ export default class InputElementMap<T, X> extends InputElement<X> {
|
|||
return this._inputElement.InnerRender();
|
||||
}
|
||||
|
||||
IsSelected: UIEventSource<boolean>;
|
||||
|
||||
IsValid(x: X): boolean {
|
||||
return this._inputElement.IsValid(this.fromX(x));
|
||||
if(x === undefined){
|
||||
return false;
|
||||
}
|
||||
const t = this.fromX(x);
|
||||
if(t === undefined){
|
||||
return false;
|
||||
}
|
||||
return this._inputElement.IsValid(t);
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -2,208 +2,86 @@ import {UIElement} from "../UIElement";
|
|||
import {InputElement} from "./InputElement";
|
||||
import Translations from "../i18n/Translations";
|
||||
import {UIEventSource} from "../../Logic/UIEventSource";
|
||||
import * as EmailValidator from "email-validator";
|
||||
import {parsePhoneNumberFromString} from "libphonenumber-js";
|
||||
import {DropDown} from "./DropDown";
|
||||
|
||||
export class ValidatedTextField {
|
||||
|
||||
public static explanations = {
|
||||
"string": "A basic, 255-char string",
|
||||
"date": "A date",
|
||||
"wikidata": "A wikidata identifier, e.g. Q42",
|
||||
"int": "A number",
|
||||
"nat": "A positive number",
|
||||
"float": "A decimal",
|
||||
"pfloat": "A positive decimal",
|
||||
"email": "An email adress",
|
||||
"url": "A url",
|
||||
"phone": "A phone number"
|
||||
}
|
||||
|
||||
public static TypeDropdown() : DropDown<string>{
|
||||
const values : {value: string, shown: string}[] = [];
|
||||
const expl = ValidatedTextField.explanations;
|
||||
for(const key in expl){
|
||||
values.push({value: key, shown: `${key} - ${expl[key]}`})
|
||||
}
|
||||
return new DropDown<string>("", values)
|
||||
}
|
||||
|
||||
|
||||
public static inputValidation = {
|
||||
"$": () => true,
|
||||
"string": () => true,
|
||||
"date": () => true, // TODO validate and add a date picker
|
||||
"wikidata": () => true, // TODO validate wikidata IDS
|
||||
"int": (str) => {str = ""+str; return str !== undefined && str.indexOf(".") < 0 && !isNaN(Number(str))},
|
||||
"nat": (str) => {str = ""+str; return str !== undefined && str.indexOf(".") < 0 && !isNaN(Number(str)) && Number(str) > 0},
|
||||
"float": (str) => !isNaN(Number(str)),
|
||||
"pfloat": (str) => !isNaN(Number(str)) && Number(str) >= 0,
|
||||
"email": (str) => EmailValidator.validate(str),
|
||||
"url": (str) => str,
|
||||
"phone": (str, country) => {
|
||||
return parsePhoneNumberFromString(str, country?.toUpperCase())?.isValid() ?? false;
|
||||
}
|
||||
}
|
||||
|
||||
public static formatting = {
|
||||
"phone": (str, country) => {
|
||||
console.log("country formatting", country)
|
||||
return parsePhoneNumberFromString(str, country?.toUpperCase()).formatInternational()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class TextField<T> extends InputElement<T> {
|
||||
|
||||
public static StringInput(textArea: boolean = false): TextField<string> {
|
||||
return new TextField<string>({
|
||||
toString: str => str,
|
||||
fromString: str => str,
|
||||
textArea: textArea
|
||||
});
|
||||
}
|
||||
|
||||
public static KeyInput(allowEmpty : boolean = false): TextField<string>{
|
||||
return new TextField<string>({
|
||||
placeholder: "key",
|
||||
fromString: str => {
|
||||
if (str?.match(/^[a-zA-Z][a-zA-Z0-9:_-]*$/)) {
|
||||
return str;
|
||||
}
|
||||
if(str === "" && allowEmpty){
|
||||
return "";
|
||||
}
|
||||
|
||||
return undefined
|
||||
},
|
||||
toString: str => str
|
||||
});
|
||||
}
|
||||
|
||||
public static NumberInput(type: string = "int", extraValidation: (number: Number) => boolean = undefined) : TextField<number>{
|
||||
const isValid = ValidatedTextField.inputValidation[type];
|
||||
extraValidation = extraValidation ?? (() => true)
|
||||
return new TextField({
|
||||
fromString: str => {
|
||||
if(!isValid(str)){
|
||||
return undefined;
|
||||
}
|
||||
const n = Number(str);
|
||||
if(!extraValidation(n)){
|
||||
return undefined;
|
||||
}
|
||||
return n;
|
||||
},
|
||||
toString: num => ""+num,
|
||||
placeholder: type
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export class TextField extends InputElement<string> {
|
||||
private readonly value: UIEventSource<string>;
|
||||
private readonly mappedValue: UIEventSource<T>;
|
||||
public readonly enterPressed = new UIEventSource<string>(undefined);
|
||||
private readonly _placeholder: UIElement;
|
||||
private readonly _fromString?: (string: string) => T;
|
||||
private readonly _toString: (t: T) => string;
|
||||
private readonly startValidated: boolean;
|
||||
public readonly IsSelected: UIEventSource<boolean> = new UIEventSource<boolean>(false);
|
||||
private readonly _isArea: boolean;
|
||||
private readonly _textAreaRows: number;
|
||||
|
||||
constructor(options: {
|
||||
/**
|
||||
* Shown as placeholder
|
||||
*/
|
||||
constructor(options?: {
|
||||
placeholder?: string | UIElement,
|
||||
|
||||
/**
|
||||
* Converts the T to a (canonical) string
|
||||
* @param t
|
||||
*/
|
||||
toString: (t: T) => string,
|
||||
/**
|
||||
* Converts the string to a T
|
||||
* Returns undefined if invalid
|
||||
* @param string
|
||||
*/
|
||||
fromString: (string: string) => T,
|
||||
value?: UIEventSource<T>,
|
||||
startValidated?: boolean,
|
||||
value?: UIEventSource<string>,
|
||||
textArea?: boolean,
|
||||
textAreaRows?: number,
|
||||
isValid?: ((s: string) => boolean)
|
||||
}) {
|
||||
super(undefined);
|
||||
const self = this;
|
||||
this.value = new UIEventSource<string>("");
|
||||
|
||||
options = options ?? {};
|
||||
this._isArea = options.textArea ?? false;
|
||||
this.startValidated = options.startValidated ?? false;
|
||||
this.mappedValue = options?.value ?? new UIEventSource<T>(undefined);
|
||||
this.mappedValue.addCallback(() => self.InnerUpdate());
|
||||
this.value = options?.value ?? new UIEventSource<string>(undefined);
|
||||
|
||||
// @ts-ignore
|
||||
this._fromString = options.fromString ?? ((str) => (str))
|
||||
this.value.addCallback((str) => this.mappedValue.setData(options.fromString(str)));
|
||||
this.mappedValue.addCallback((t) => this.value.setData(options.toString(t)));
|
||||
this._textAreaRows = options.textAreaRows;
|
||||
|
||||
this._placeholder = Translations.W(options.placeholder ?? "");
|
||||
this.ListenTo(this._placeholder._source);
|
||||
this._toString = options.toString ?? ((t) => ("" + t));
|
||||
|
||||
this.onClick(() => {
|
||||
self.IsSelected.setData(true)
|
||||
});
|
||||
this.mappedValue.addCallback((t) => {
|
||||
if (t === undefined || t === null) {
|
||||
return;
|
||||
}
|
||||
const field = document.getElementById('text-' + this.id);
|
||||
this.value.addCallback((t) => {
|
||||
const field = document.getElementById(this.id);
|
||||
if (field === undefined || field === null) {
|
||||
return;
|
||||
}
|
||||
// @ts-ignore
|
||||
field.value = options.toString(t);
|
||||
});
|
||||
}
|
||||
if (options.isValid) {
|
||||
field.className = options.isValid(t) ? "" : "invalid";
|
||||
}
|
||||
|
||||
GetValue(): UIEventSource<T> {
|
||||
return this.mappedValue;
|
||||
if (t === undefined || t === null) {
|
||||
// @ts-ignore
|
||||
return;
|
||||
}
|
||||
// @ts-ignore
|
||||
field.value = t;
|
||||
});
|
||||
}
|
||||
|
||||
GetValue(): UIEventSource<string> {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
InnerRender(): string {
|
||||
|
||||
if(this._isArea){
|
||||
return `<textarea id="text-${this.id}" class="form-text-field" rows="${this._textAreaRows}" cols="50" style="max-width: 100%; width: 100%; box-sizing: border-box"></textarea>`
|
||||
|
||||
if (this._isArea) {
|
||||
return `<textarea id="${this.id}" class="form-text-field" rows="${this._textAreaRows}" cols="50" style="max-width: 100%; width: 100%; box-sizing: border-box"></textarea>`
|
||||
}
|
||||
|
||||
|
||||
const placeholder = this._placeholder.InnerRender().replace("'", "'");
|
||||
|
||||
|
||||
return `<form onSubmit='return false' class='form-text-field'>` +
|
||||
`<input type='text' placeholder='${placeholder}' id='text-${this.id}'>` +
|
||||
`<input type='text' placeholder='${placeholder}' id='${this.id}'>` +
|
||||
`</form>`;
|
||||
}
|
||||
|
||||
InnerUpdate() {
|
||||
const field = document.getElementById('text-' + this.id);
|
||||
if (field === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.mappedValue.addCallback((data) => {
|
||||
field.className = data !== undefined ? "valid" : "invalid";
|
||||
});
|
||||
|
||||
field.className = this.mappedValue.data !== undefined ? "valid" : "invalid";
|
||||
|
||||
InnerUpdate(field) {
|
||||
const self = this;
|
||||
field.oninput = () => {
|
||||
// @ts-ignore
|
||||
self.value.setData(field.value);
|
||||
};
|
||||
|
||||
if (this.value.data !== undefined && this.value.data !== null) {
|
||||
// @ts-ignore
|
||||
field.value = this.value.data;
|
||||
}
|
||||
|
||||
field.addEventListener("focusin", () => self.IsSelected.setData(true));
|
||||
field.addEventListener("focusout", () => self.IsSelected.setData(false));
|
||||
|
||||
|
@ -215,16 +93,6 @@ export class TextField<T> extends InputElement<T> {
|
|||
}
|
||||
});
|
||||
|
||||
if (this.IsValid(this.mappedValue.data)) {
|
||||
const expected = this._toString(this.mappedValue.data);
|
||||
// @ts-ignore
|
||||
if (field.value !== expected) {
|
||||
// @ts-ignore
|
||||
field.value = expected;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public SetCursorPosition(i: number) {
|
||||
|
@ -232,7 +100,7 @@ export class TextField<T> extends InputElement<T> {
|
|||
if(field === undefined || field === null){
|
||||
return;
|
||||
}
|
||||
if(i === -1){
|
||||
if (i === -1) {
|
||||
// @ts-ignore
|
||||
i = field.value.length;
|
||||
}
|
||||
|
@ -241,12 +109,8 @@ export class TextField<T> extends InputElement<T> {
|
|||
field.setSelectionRange(i, i);
|
||||
}
|
||||
|
||||
IsValid(t: T): boolean {
|
||||
if (t === undefined || t === null) {
|
||||
return false;
|
||||
}
|
||||
const result = this._toString(t);
|
||||
return result !== undefined && result !== null;
|
||||
IsValid(t: string): boolean {
|
||||
return !(t === undefined || t === null);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
196
UI/Input/ValidatedTextField.ts
Normal file
196
UI/Input/ValidatedTextField.ts
Normal file
|
@ -0,0 +1,196 @@
|
|||
import {DropDown} from "./DropDown";
|
||||
import * as EmailValidator from "email-validator";
|
||||
import {parsePhoneNumberFromString} from "libphonenumber-js";
|
||||
import InputElementMap from "./InputElementMap";
|
||||
import {InputElement} from "./InputElement";
|
||||
import {TextField} from "./TextField";
|
||||
import {UIElement} from "../UIElement";
|
||||
import {UIEventSource} from "../../Logic/UIEventSource";
|
||||
|
||||
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)
|
||||
} {
|
||||
|
||||
if (isValid === undefined) {
|
||||
isValid = () => true;
|
||||
}
|
||||
|
||||
if (reformat === undefined) {
|
||||
reformat = (str, _) => str;
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
name: name,
|
||||
explanation: explanation,
|
||||
isValid: isValid,
|
||||
reformat: reformat
|
||||
}
|
||||
}
|
||||
|
||||
public static tpList = [
|
||||
ValidatedTextField.tp(
|
||||
"string",
|
||||
"A basic string"),
|
||||
ValidatedTextField.tp(
|
||||
"date",
|
||||
"A date"),
|
||||
ValidatedTextField.tp(
|
||||
"wikidata",
|
||||
"A wikidata identifier, e.g. Q42"),
|
||||
ValidatedTextField.tp(
|
||||
"int",
|
||||
"A number",
|
||||
(str) => {
|
||||
str = "" + str;
|
||||
return str !== undefined && str.indexOf(".") < 0 && !isNaN(Number(str))
|
||||
}),
|
||||
ValidatedTextField.tp(
|
||||
"nat",
|
||||
"A positive number or zero",
|
||||
(str) => {
|
||||
str = "" + str;
|
||||
return str !== undefined && str.indexOf(".") < 0 && !isNaN(Number(str)) && Number(str) >= 0
|
||||
}),
|
||||
ValidatedTextField.tp(
|
||||
"pnat",
|
||||
"A strict positive number",
|
||||
(str) => {
|
||||
str = "" + str;
|
||||
return str !== undefined && str.indexOf(".") < 0 && !isNaN(Number(str)) && Number(str) > 0
|
||||
}),
|
||||
ValidatedTextField.tp(
|
||||
"float",
|
||||
"A decimal",
|
||||
(str) => !isNaN(Number(str))),
|
||||
ValidatedTextField.tp(
|
||||
"pfloat",
|
||||
"A positive decimal (incl zero)",
|
||||
(str) => !isNaN(Number(str)) && Number(str) >= 0),
|
||||
ValidatedTextField.tp(
|
||||
"email",
|
||||
"An email adress",
|
||||
(str) => EmailValidator.validate(str)),
|
||||
ValidatedTextField.tp(
|
||||
"url",
|
||||
"A url"),
|
||||
ValidatedTextField.tp(
|
||||
"phone",
|
||||
"A phone number",
|
||||
(str, country: any) => {
|
||||
return parsePhoneNumberFromString(str, country?.toUpperCase())?.isValid() ?? false
|
||||
},
|
||||
(str, country: any) => {
|
||||
console.log("country formatting", country)
|
||||
return parsePhoneNumberFromString(str, country?.toUpperCase()).formatInternational()
|
||||
}
|
||||
)
|
||||
]
|
||||
|
||||
private static allTypesDict(){
|
||||
const types = {};
|
||||
for (const tp of ValidatedTextField.tpList) {
|
||||
types[tp.name] = tp;
|
||||
}
|
||||
return types;
|
||||
}
|
||||
|
||||
public static TypeDropdown(): DropDown<string> {
|
||||
const values: { value: string, shown: string }[] = [];
|
||||
const expl = ValidatedTextField.tpList;
|
||||
for (const key in expl) {
|
||||
values.push({value: key, shown: `${key} - ${expl[key]}`})
|
||||
}
|
||||
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 NumberInput(type: string = "int", extraValidation: (number: Number) => boolean = undefined): InputElement<number> {
|
||||
const isValid = ValidatedTextField.AllTypes[type].isValid;
|
||||
extraValidation = extraValidation ?? (() => true)
|
||||
|
||||
const fromString = str => {
|
||||
if (!isValid(str)) {
|
||||
return undefined;
|
||||
}
|
||||
const n = Number(str);
|
||||
if (!extraValidation(n)) {
|
||||
return undefined;
|
||||
}
|
||||
return n;
|
||||
};
|
||||
const toString = num => {
|
||||
if (num === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return "" + num;
|
||||
};
|
||||
const textField = ValidatedTextField.InputForType(type);
|
||||
return new InputElementMap(textField, (n0, n1) => n0 === n1, fromString, toString)
|
||||
}
|
||||
|
||||
public static KeyInput(allowEmpty: boolean = false): InputElement<string> {
|
||||
|
||||
function fromString(str) {
|
||||
if (str?.match(/^[a-zA-Z][a-zA-Z0-9:_-]*$/)) {
|
||||
return str;
|
||||
}
|
||||
if (str === "" && allowEmpty) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
const toString = str => str
|
||||
|
||||
function isSame(str0, str1) {
|
||||
return str0 === str1;
|
||||
}
|
||||
|
||||
const textfield = new TextField({
|
||||
placeholder: "key",
|
||||
isValid: str => fromString(str) !== undefined,
|
||||
value: new UIEventSource<string>("")
|
||||
});
|
||||
|
||||
return new InputElementMap(textfield, isSame, fromString, toString);
|
||||
}
|
||||
|
||||
|
||||
|
||||
static Mapped<T>(fromString: (str) => T, toString: (T) => string, options?: {
|
||||
placeholder?: string | UIElement,
|
||||
value?: UIEventSource<string>,
|
||||
startValidated?: boolean,
|
||||
textArea?: boolean,
|
||||
textAreaRows?: number,
|
||||
isValid?: ((string: string) => boolean)
|
||||
}): InputElement<T> {
|
||||
const textField = new TextField(options);
|
||||
|
||||
return new InputElementMap(
|
||||
textField, (a, b) => a === b,
|
||||
fromString, toString
|
||||
);
|
||||
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue