Utilities Library _
The form engine provides a few utility methods that can be useful.
_.get
(obj: any, path: string, dflt: any = null): any
Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.
Argument | Description |
---|---|
obj | The object to query |
path | The path of the property to get |
dflt | The value returned for undefined resolved values |
Example
_.get(definition, "extraSettings.layoutDefinition.rows[0].cols[0]")
_.clone
(value: any): any
Returns a clone of the value. This is not a deep clone, so the attributes of the cloned object will be references the original ones.
Example:
const a = {
a1: [1, 2]
};
const b = _.clone(a);
// a === b => false
// a.a1 === b.a1 => true
_.lazyCloneEdit
(scope: any, pathStr: string, value: any): any
Creates a copy of scope object and assigns the value to the pathStr. It keeps the references to the original scope children unless a clone is necessary to keep the original scope ummodified.
Note that pathStr containing value will be deleted if value is undefined
.
Example:
const a = {
a1: [1, 2],
a2: {
a21: 1
}
};
const b = _.lazyCloneEdit(a, "a1[1]", 3);
// b.a1[1] === 3
// b.a2 === a.a2
_.no
(value: any): boolean
Returns true when value is null, undefined or "".
Example:
_.no(null) // true
_.equals
(a: any, b: any): boolean
Performs a deep comparison between two values to determine if they are equivalent.
Example:
const a = {
a1: 1
};
const b = {
a1: 1
};
_.equals(a, b) // true
// a !== b
_.bem
(elementName: string, propsClassNames: string = "", modifiers: string[] = []): (subElement: string) => string
Returns a function that returns the BEM-like classNames.
Example:
const bem = _.bem("textarea", "component", ["required", "red"]);
bem() // flw__textarea component flw__textarea--required flw__textarea--red component--required component--red
bem("label") // flw__textarea__label component__label flw__textarea--required__label flw__textarea--red__label component--required__label component--red__label
_.errorClasses
(errors: string[]): string[]
Prepends invalid- to every item in the errors array and adds the item invalid when the list is not empty.
Example:
_.errorClasses(["minLength"]) // ["invalid-minLength", "invalid"]
_.uid
(): string
Returns a different identifier "id-number" every time it's called.
Example:
_.uid() // id-1
_.uid() // id-2
_.equalProps
(propsA: Props, propsB: Props): boolean
Compares the properties that are subject to change in a component (config, className and lang).
Example:
shouldComponentUpdate(nextProps: Props, nextState?: any) {
return !_.equalProps(this.props, nextProps);
}
_.traverse
(o: any, func: (key: any, value: any, acc: string) => void, acc: string)
Executes func
with every child of o
.
Example:
_.traverse(formDefinition, (key, value, acc) => {
if (value && value.type === "upload" && _.no(value.value)) {
value.value = "{{_files}}";
}
});
_.futch
(url: string, opts: RequestInit = {}, onProgress?: (x: {}) => void): Promise<Response>
Similar to window.fetch but with an additional onProgress
parameter.
Example:
const headers = new Headers();
headers.append("Content-Type", "text/json");
const users = _.futch("/users", {
headers,
method: "get",
mode: "cors"
}).then(response => response.json());
_.evalExpression
(expression: string, scope: any): any
Resolves the expression using the data and functions in scope.
Example:
const payload = {
date1: new Date(2010, 10, 10, 5, 25)
};
const additionalData = {
timeFormat: date => date.toLocaleTimeString().substr(0, 5)
}
_.evalExpression("{{date1 |> timeFormat}}", {...payload, ...additionalData}) // 05:25
_.asArray
(obj: any): any[]
Converts an object to an array if it wasn't already an array.
Example:
_.asArray(null) // []
_.asArray(1) // [1]
_.asArray([1, 2]) // [1, 2]
_.toArray
(obj: any): any[]
Converts an array-like object into a proper array.
Example:
_.toArray(arguments)
_.has
(collection: { [key: string]: any }[], element: { [key: string]: any }): boolean
Returns true
if a collection contains an item that matches the element.
Example:
_.has(collection, {id: "XXX-Y"})
_.throttle
(callback: (args: any) => void, wait: number, context: any): (args: any) => void
Creates a throttled function that only invokes callback at most once per every given milliseconds.
Example:
handleScroll = () => {
let scrollTop = element.getBoundingClientRect().top;
element.style.transform = `translateY(${-scrollTop}px)`;
});
window.addEventListener("scroll", _.throttle(handleScroll, 100, this));
_.translate
(translations: any, lang: string, key: string, context?: Record<string, unknown>): string
Returns the translation of a key given a language, a list of translations and an optional context of expressions.
Example:
const { translations, lang } = props;
const numFiles = (files || []).length;
_.translate(translations, lang, "upload.maxfiles", { numFiles });
_.withoutTemp
(payload: Payload, tempName = "$temp"): Payload
Removes all variables named $temp from the payload recursively. The temp variable name can be changed by passing the optional parameter tempName
Example:
const payload = {
a: 1,
b: "hi",
$temp: "to be removed",
c: {
a: 2,
$temp: "to be removed"
}
}
_.withoutTemp(payload);
_.encode v3.10.0+
(obj: Record<string, any>, prefix?: string): string
Transform an object into a valid query URL.
Example:
const obj = { foo: 123 };
const out = _.encode(obj);
expect(out).toEqual("foo=123");
_.sanitizeHtml v3.10.3+
(html?: string): string
Runs DOMPurify
library to sanitize any HTML from any possible XSS attack.
Example:
const out = _.sanitizeHtml("<img src='x' onerror='javascript:alert(1)' />");
expect(out).toEqual("<img src='x' />");
_.escapeHtml v3.10.3+
(html?: string): string
Runs some regular expressions to escape any HTML markup. This will avoid the browser executing the HTML.
Example:
const out = _.escapeHtml(`<a href="javascript:alert(959)">click</a>`);
expect(out).toEqual(
"<a href="javascript:alert(959)">click</a>"
);