@uxf/core
v11.127.0
Published
UXF Core
Readme
UXF Core
Constants
- common modifier classnames for interactive elements (eg.
CLASSES.IS_HOVERABLEfor is-hoverable classname)focus-visibleis-activeis-busyis-disabledis-focusedis-hoverableis-hoveredis-invalidis-loadingis-not-hoverableis-readonlyis-requiredis-selected
Resizer
!!! Required @uxf/resizer version >= 2.3.2 which supported quality parameter.
Config
[
{
"route": "/generated/static/:width(\\d+|x)_:height(\\d+|x)_:fit([a-z]+)_:position([a-z]+)_:background([a-z]+)_:trim([a-z]+)_:quality(\\d+|x)/:version/:filename(*).:extension.:toFormat",
"source": "https://uxf-base.uxf.dev/:filename+.:extension"
},
{
"route": "/generated/:namespace/:p1/:p2/:filename([a-f0-9\\-]+)_:width(\\d+|x)_:height(\\d+|x)_:fit([a-z]+)_:position([a-z]+)_:background([a-z]+)_:trim([a-z]+)_:quality(\\d+|x)_:extension.:toFormat",
"source": "https://s3.uxf.dev/${APP_NAME}-${APP_ENV}/:namespace/:p1/:p2/:filename.:extension"
}
]Usage for generated images
import { resizerImageUrl } from "@uxf/core/utils/resizer";
<img src={resizerImageUrl(file, width, height, params)} />;Usage for static images
import { resizerImageUrl } from "@uxf/core/utils/resizer";
import staticImage from "./path/to/static-image.png";
<img src={resizerImageUrl(staticImage, width, height, params)} />;QR code generator
Helper function for qr code generator.
https://gitlab.uxf.cz/uxf-internal-projects/qr#qr-code-generator
import { qrCodeUrl } from "@uxf/core/qr";
qrCodeUrl("https://www.uxf.cz", { width: 200, margin: 5, errorCorrectionLevel: "H" });Cookie
- Cookie options
secure?: boolean;httpOnly?: boolean;path?: string;
import { Cookie } from "@uxf/core/cookie";
// on client
const cookie = Cookie.create();
// in getInitialProps
const cookie = Cookie.create(ctx);
cookie.has("cookie-name");
cookie.get("cookie-name");
cookie.set("cookie-name", "value", /* ttl in seconds (optional) */, /* options (optional) */)
cookie.delete("cookie-name", /* options (optional) */);Money
Money is the monetary value type used across the packages — the amount is a string, so it can carry
more precision than a JS number holds.
import { Currency, Money } from "@uxf/core/money";
import { currencies } from "@uxf/core/money/currencies";
import { getCurrencySymbol } from "@uxf/core/money/get-currency-symbol";
const price: Money = { amount: "1000", currency: "CZK" };
getCurrencySymbol("CZK"); /* returns "Kč" */normalizeMoneyAmount
Rewrites an amount into its canonical decimal form. Returns null when the input does not describe a
decimal number.
import { normalizeMoneyAmount } from "@uxf/core/money/normalize-money";
normalizeMoneyAmount("1000.00"); /* returns "1000" */
normalizeMoneyAmount("15.50"); /* returns "15.5" */
normalizeMoneyAmount("015"); /* returns "15" */
normalizeMoneyAmount(".5"); /* returns "0.5" */
normalizeMoneyAmount("+15"); /* returns "15" */
normalizeMoneyAmount("-0.00"); /* returns "0" */
normalizeMoneyAmount("abc"); /* returns null */
normalizeMoneyAmount("1e5"); /* returns null - exponent notation is not a decimal amount */The rewriting is textual, never a Number() round-trip, so an amount a double cannot hold exactly
survives intact: "9007199254740993" and "100000000000000000000000" come back unchanged rather than as
a different number or as "1e+23". This is also why exponent notation is rejected instead of expanded.
Related but not a substitute: trimTrailingZeros only strips trailing zeros
from a fractional part and leaves leading zeros, signs and ".5" alone.
normalizeMoney
Normalizes a whole Money value: the amount goes through normalizeMoneyAmount and any extra properties
(a GraphQL __typename, for instance) are dropped. Returns null for a nullish value or an amount that
is not a number.
import { normalizeMoney } from "@uxf/core/money/normalize-money";
normalizeMoney({ amount: "1000.00", currency: "CZK" }); /* returns { amount: "1000", currency: "CZK" } */
normalizeMoney({ __typename: "Money", amount: "1000", currency: "CZK" }); /* drops __typename */
normalizeMoney({ amount: "", currency: "CZK" }); /* returns null */
normalizeMoney(null); /* returns null */Why you need this in a form. react-hook-form decides dirtiness with its own deepEqual, which
compares Object.keys().length first and then every leaf. A Money field therefore reads as dirty as
soon as its shape drifts from the default value — an extra __typename, or an amount retyped as
"1000.00" where the default says "1000" — even though the visible value is identical, and the
unsaved-changes bar never goes away.
A component can only make what it emits canonical; the default values are built by the consuming app's mappers, which no component can reach. So run both sides through the same normalizer:
const formApi = useForm<FormData>({
defaultValues: { price: normalizeMoney(data.price) },
});@uxf/form/money-input already normalizes what it emits, on blur.
Utils
adjustTextareaHeight
Dynamically adjusts the height of a <textarea> based on its content and an optional number of rows.
Parameters
element: The<textarea>to adjust.rows(optional): Minimum visible rows. Default is4.
Behavior
- Leverages MutationObserver API to measure content height.
- Adjusts height to fit content or the minimum height based on the
rowsparameter, calculated usingline-heightandfont-size.
Usage
adjustTextareaHeight(textarea); // Adjusts height (min 4 rows)
adjustTextareaHeight(textarea, 6); // With 6-row minimumIn React component:
import { useIsomorphicLayoutEffect } from "@uxf/core-react/hooks/use-isomorphic-layout-effect";
import { isNotNil } from "@uxf/core/utils/is-not-nil";
useIsomorphicLayoutEffect(() => {
const textarea = textareaRef.current;
if (isNotNil(textarea)) {
return;
}
const cleanup = adjustTextareaHeight(textarea);
return () => cleanup();
}, []);Note: Requires valid
line-heightandfont-sizestyles for accurate sizing.
assertNever
Checks that value is always type "never".
switch (value) {
case "a":
return "A";
case "b":
return "B";
default:
return assertNever(value);
}ts-pattern
Re-export of the ts-pattern library for exhaustive pattern matching. This provides a more powerful and type-safe alternative to switch statements with support for complex patterns, guards, and exhaustiveness checking.
import { match, Pattern } from "@uxf/core/utils/ts-pattern";
const result = match(value)
.with("a", () => "A")
.with("b", () => "B")
.with(Pattern.string, (str) => `String: ${str}`)
.exhaustive();For full documentation, see the official ts-pattern docs.
assertNotNil
import { assertNotNil } from "@uxf/core/utils/assert-not-nil";
const testObject: { value: number | null } = { value: 10 };
assertNotNil(testObject.value);
// is the same as
if (isNil(testObject.value)) {
throw new Error("Value is null");
}camelCaseToDash
import { camelCaseToDash } from "@uxf/core/utils/camelCaseToDash";
const example = camelCaseToDash("fooBar"); /* returns "foo-bar" */capitalize
import { capitalize } from "@uxf/core/utils/capitalize";
const example = capitalize("hello world"); /* returns "Hello world" */cn
A simple tag for template literals that returns the string as-is. Useful for tooling (e.g. Tailwind CSS IntelliSense) to recognize class strings.
import { cn } from "@uxf/core/utils/cn";
const className = cn`flex items-center justify-center`;composeRefs
import { composeRefs } from "@uxf/core/utils/composeRefs";
const firstRef = useRef<HTMLDivElement>(null);
const secondRef = useRef<HTMLDivElement>(null);
const example = <div ref={composeRefs(firstRef, secondRef)} />;cx, cxa
It is our fork of clsx library https://github.com/lukeed/clsx
We will mainly use cx, which is fork of clsx/lite – it accepts ONLY string values! Any non-string arguments are ignored!
import { cx } from "@uxf/core/utils/cx";
// string
cx("hello", true && "foo", false && "bar");
// => "hello foo"
// NOTE: Any non-string input(s) ignored
cx({ foo: true });
//=> ""The cxa function is full fork of clsx and can take any number of arguments, each of which can be an Object, Array, Boolean, or String.
Important: Any falsy values are discarded! Standalone Boolean values are discarded as well.
import { cxa } from "@uxf/core/utils/cxa";
cxa(true, false, "", null, undefined, 0, NaN);
//=> ""
// Strings (variadic)
cxa("foo", true && "bar", "baz");
//=> "foo bar baz"
// Objects
cxa({ foo: true, bar: false, baz: isTrue() });
//=> "foo baz"
// Objects (variadic)
cxa({ foo: true }, { bar: false }, null, { "--foobar": "hello" });
//=> "foo --foobar"
// Arrays
cxa(["foo", 0, false, "bar"]);
//=> "foo bar"
// Arrays (variadic)
cxa(["foo"], ["", 0, false, "bar"], [["baz", [["hello"], "there"]]]);
//=> "foo bar baz hello there"
// Kitchen sink (with nesting)
cxa("foo", [1 && "bar", { baz: false, bat: null }, ["hello", ["world"]]], "cya");
//=> "foo bar hello world cya"deepmerge
Re-export of the deepmerge library. Recursively merges two or more objects and arrays.
import { deepmerge } from "@uxf/core/utils/deepmerge";
const target = { a: 1, b: { x: 10 } };
const source = { b: { y: 20 }, c: 3 };
deepmerge(target, source);
/* returns { a: 1, b: { x: 10, y: 20 }, c: 3 } */deepEqualIgnoringKeyOrder
deepEqualIgnoringKeyOrder compares two values for deep equality while ignoring the order of object keys. It serializes values in a stable way, ensuring that objects with the same data but different key orders are treated as equal. Arrays remain order-sensitive, circular references are handled safely, and primitives are compared by value.
Use this helper for equality checks in tests, memoization, caching, or change detection scenarios where object key order shouldn’t matter. It’s especially useful when comparing payloads, configs, or API responses that may have non-deterministic key ordering.
import { deepEqualIgnoringKeyOrder } from "./deep-equal-ingoring-key-order";
const a = { b: 2, a: 1, nested: { y: 2, x: 1 } };
const b = { nested: { x: 1, y: 2 }, a: 1, b: 2 };
console.log(deepEqualIgnoringKeyOrder(a, b)); // true
const arr1 = [
{ a: 1, b: 2 },
{ c: 3, d: 4 },
];
const arr2 = [
{ b: 2, a: 1 },
{ d: 4, c: 3 },
];
console.log(deepEqualIgnoringKeyOrder(arr1, arr2)); // true (objects equal, same array order)
const arr3 = [
{ d: 4, c: 3 },
{ b: 2, a: 1 },
];
console.log(deepEqualIgnoringKeyOrder(arr1, arr3)); // false (array order differs)downloadFile
Intended as only way to programmatically download file if there is no option to use native anchor with download html attribute (eg. in form submit events).
import { downloadFile } from "@uxf/core/utils/download-file";
import { FormEventHandler } from "react";
const submitHandler: FormEventHandler<HTMLFormElement> = () => {
downloadFile("https://example.com/file", "file.txt");
};escapeQuotes
Escapes all double quotes (") in a string by replacing them with \".
import { escapeQuotes } from "@uxf/core/utils/escape-quotes";
escapeQuotes('The "quick" fox');
// Output: The \"quick\" foxhumanIndex
Converts a 0-based index to a 1-based (human-readable) index.
import { humanIndex } from "@uxf/core/utils/human-index";
humanIndex(0); /* returns 1 */
humanIndex(9); /* returns 10 */
humanIndex(-1); /* throws error */filterNullish
import { filterNullish } from "@uxf/core/utils/filter-nullish";
filterNullish([0, "text", null, undefined, [], {}]); /* returns [0, "text", [], {}] */filterNullishObjectValues
Filters out all properties with null or undefined values from an object, returning a new object with only non-nullish values.
import { filterNullishObjectValues } from "@uxf/core/utils/filter-nullish-object-values";
filterNullishObjectValues({ a: 1, b: null, c: "test", d: undefined });
/* returns { a: 1, c: "test" } */
filterNullishObjectValues({ a: 0, b: "", c: false });
/* returns { a: 0, b: "", c: false } - keeps falsy values that are not nullish */filterAriaAndDataAttrs
Filters an object to return only properties that start with aria- or data- prefixes. This utility is useful when you need to pass accessibility and data attributes to HTML elements while excluding other props like event handlers or component-specific props.
import { filterAriaAndDataAttrs } from "@uxf/core/utils/filter-aria-and-data-attrs";
// Filter accessibility and data attributes from component props
const props = {
"aria-label": "Close button",
"data-testid": "close-btn",
className: "button",
onClick: handleClick,
};
const htmlAttrs = filterAriaAndDataAttrs(props);
// Result: { "aria-label": "Close button", "data-testid": "close-btn" }
<button {...htmlAttrs}>Close</button>;// Use case: Passing only safe attributes to a native element
function CustomInput({ label, onChange, ...restProps }) {
const accessibilityAttrs = filterAriaAndDataAttrs(restProps);
return <input {...accessibilityAttrs} onChange={onChange} />;
}
<CustomInput aria-describedby="helper-text" data-analytics="email-input" customProp="ignored" />;formatBytes
Appends suitable unit to the byte value of data size.
formatBytes(17.5 * 1024);
//=> "17.5 kB"inArray
Type-safe helper for checking if a value exists in an array. Particularly useful with as const arrays where the value type is wider than the array element type.
import { inArray } from "@uxf/core/utils/in-array";
// Basic usage
inArray("a", ["a", "b", "c"]); /* returns true */
inArray("d", ["a", "b", "c"]); /* returns false */
// Useful with const arrays and wider value types
const statuses = ["pending", "active", "completed"] as const;
const status: string = getStatusFromApi();
if (inArray(status, statuses)) {
// status is now narrowed to the array values
}isEqual
Re-export of lodash.isequal. Performs a deep comparison between two values to determine if they are equivalent.
import { isEqual } from "@uxf/core/utils/is-equal";
isEqual({ a: 1, b: [2, 3] }, { a: 1, b: [2, 3] }); /* returns true */
isEqual({ a: 1 }, { a: 2 }); /* returns false */isEmpty
import { isEmpty } from "@uxf/core/utils/is-empty";
isEmpty("not-empty"); /* returns false */
isEmpty(""); /* returns true */
isEmpty(["1"]); /* returns false */
isEmpty([]); /* returns true */isEven
Checks if a number is even.
import { isEven } from "@uxf/core/utils/is-even";
isEven(2); /* returns true */
isEven(4); /* returns true */
isEven(1); /* returns false */
isEven(3); /* returns false */
isEven(0); /* returns true */
isEven(-2); /* returns true */isOdd
Checks if a number is odd.
import { isOdd } from "@uxf/core/utils/is-odd";
isOdd(1); /* returns true */
isOdd(3); /* returns true */
isOdd(2); /* returns false */
isOdd(4); /* returns false */
isOdd(0); /* returns false */
isOdd(-1); /* returns true */isBrowser / isServer
import { isBrowser } from "@uxf/core/utils/isBrowser";
import { isServer } from "@uxf/core/utils/isServer";
const browserExample = isBrowser; /* returns true if DOM is available */
const serverExample = isServer; /* returns true if DOM is NOT available */isNil
import { isNil } from "@uxf/core/utils/is-nil";
isNil(null); /* returns true */
isNil(undefined); /* returns true */
isNil(true); /* returns false */
isNil(1); /* returns false */
isNil(0); /* returns false */
isNil([]); /* returns false */
isNil("string"); /* returns false */isNotNil
import { isNotNil } from "@uxf/core/utils/is-not-nil";
isNotNil(null); /* returns false */
isNotNil(undefined); /* returns false */
isNotNil(true); /* returns true */
isNotNil(1); /* returns true */
isNotNil(0); /* returns true */
isNotNil([]); /* returns true */
isNotNil("string"); /* returns true */isNotNilNorEmpty
Type guard that checks if a value is not null, not undefined, and not empty. Works with strings, arrays, and plain objects.
import { isNotNilNorEmpty } from "@uxf/core/utils/is-not-nil-nor-empty";
isNotNilNorEmpty("not-empty"); /* returns true */
isNotNilNorEmpty({ not: "empty" }); /* returns true */
isNotNilNorEmpty(["1"]); /* returns true */
isNotNilNorEmpty(""); /* returns false */
isNotNilNorEmpty([]); /* returns false */
isNotNilNorEmpty({}); /* returns false */
isNotNilNorEmpty(null); /* returns false */
isNotNilNorEmpty(undefined); /* returns false */isPlainObject
Type guard that checks if a value is a plain object. Returns false for arrays, null, Date, Map, Set, RegExp, and other non-plain-object types.
import { isPlainObject } from "@uxf/core/utils/is-plain-object";
isPlainObject({}); /* returns true */
isPlainObject({ a: 1 }); /* returns true */
isPlainObject([]); /* returns false */
isPlainObject([1, 2, 3]); /* returns false */
isPlainObject(new Date()); /* returns false */
isPlainObject(new Map()); /* returns false */
isPlainObject(new Set()); /* returns false */
isPlainObject(/regex/); /* returns false */
isPlainObject(null); /* returns false */
isPlainObject(undefined); /* returns false */
isPlainObject("string"); /* returns false */
isPlainObject(123); /* returns false */last
import { last } from "@uxf/core/utils/last";
last([1, 2]); /* returns 2 */
last([]); /* returns undefined */nonEmptyArrayOrNull
Converts empty arrays, null, or undefined values to null, leaving all non-empty arrays unchanged. Useful for normalizing form inputs or API data where empty arrays should be treated as null.
import { nonEmptyArrayOrNull } from "@uxf/core/utils/non-empty-array-or-null";
nonEmptyArrayOrNull([]); /* returns null */
nonEmptyArrayOrNull(null); /* returns null */
nonEmptyArrayOrNull(undefined); /* returns null */
nonEmptyArrayOrNull([1, 2, 3]); /* returns [1, 2, 3] */
nonEmptyArrayOrNull(["a", "b"]); /* returns ["a", "b"] */nonEmptyStringOrNull
Converts empty strings and undefined values to null, leaving all other strings unchanged. Useful for normalizing form inputs or API data where empty strings should be treated as null.
import { nonEmptyStringOrNull } from "@uxf/core/utils/non-empty-string-or-null";
nonEmptyStringOrNull(""); /* returns null */
nonEmptyStringOrNull(undefined); /* returns null */
nonEmptyStringOrNull(null); /* returns null */
nonEmptyStringOrNull("test"); /* returns "test" */
nonEmptyStringOrNull(" "); /* returns " " - non-empty string */normalizeSelectableIds
Sorts a multi-choice value into a canonical order. Returns a new array (the input is never mutated), or
null for a nullish value.
import { normalizeSelectableIds } from "@uxf/core/utils/normalize-selectable-ids";
normalizeSelectableIds([3, 1, 2]); /* returns [1, 2, 3] */
normalizeSelectableIds(["b", "a"]); /* returns ["a", "b"] */
normalizeSelectableIds(null); /* returns null */Multi-choice inputs treat their value as a set but emit it as an array whose order follows the order the
user clicked, and react-hook-form compares arrays index by index — so unticking an option and ticking it
again leaves a semantically unchanged form reading as dirty. Run the form's defaultValues through this
too, so both sides agree:
const formApi = useForm<FormData>({
defaultValues: { tags: normalizeSelectableIds(data.tagIds) },
});@uxf/ui/checkbox-list and
@uxf/ui/multi-select already normalize what they emit.
nullishToEmptyString
Converts null or undefined values to an empty string, leaving all other strings unchanged. Useful for safely displaying nullable string values in UI components.
import { nullishToEmptyString } from "@uxf/core/utils/nullish-to-empty-string";
nullishToEmptyString(null); /* returns "" */
nullishToEmptyString(undefined); /* returns "" */
nullishToEmptyString(""); /* returns "" */
nullishToEmptyString("hello world"); /* returns "hello world" */numberOrNull
Converts NaN, null, or undefined values to null, leaving all valid numbers unchanged. Useful for normalizing numeric inputs or API data where invalid numbers should be treated as null.
import { numberOrNull } from "@uxf/core/utils/number-or-null";
numberOrNull(0); /* returns 0 */
numberOrNull(42); /* returns 42 */
numberOrNull(-1); /* returns -1 */
numberOrNull(3.14); /* returns 3.14 */
numberOrNull(NaN); /* returns null */
numberOrNull(null); /* returns null */
numberOrNull(undefined); /* returns null */plural
Simple pluralization function for a specific language and set of terms.
import { createPlural } from "@uxf/core/utils/plural";
const terms = {
items: {
one: "položka",
few: "položky",
other: "položek",
},
};
const t = createPlural(terms, "cs");
t("items", 1); // returns "položka"
t("items", 3); // returns "položky"
t("items", 5); // returns "položek"qs
Re-export of qs. A querystring parsing and stringifying library.
import { stringify, parse } from "@uxf/core/utils/qs";
stringify({ a: "b", c: [1, 2] }); /* returns "a=b&c%5B0%5D=1&c%5B1%5D=2" */
parse("a=b&c=1"); /* returns { a: "b", c: "1" } */safeLocalStorage / safeSessionStorage
Web storage that never throws. Safari in private mode, iOS with cookies blocked, sandboxed iframes and several in-app browsers throw SecurityError: The operation is insecure. on reads as well as writes — and in some browsers even on the bare window.localStorage property access — so unguarded storage access during render can take the whole app down. A full quota throws QuotaExceededError the same way.
A read that cannot happen returns null, a write that cannot happen returns false. The storage object is resolved per call, so importing this module on the server is safe.
import { safeLocalStorage, safeSessionStorage } from "@uxf/core/utils/safe-storage";
safeLocalStorage.setItem("theme", "dark"); /* returns true, or false when storage is unavailable */
safeLocalStorage.getItem("theme"); /* returns "dark", or null when storage is unavailable */
safeLocalStorage.removeItem("theme"); /* returns true when it went through */
safeLocalStorage.clear(); /* returns true when it went through */
safeLocalStorage.length; /* returns 0 when storage is unavailable */
safeLocalStorage.key(0); /* returns null when storage is unavailable */
safeSessionStorage.getItem("wizard-step"); /* same API for sessionStorage */slugify
import { slugify } from "@uxf/core/utils/slugify";
const example = slugify("Jak se dnes máte?"); /* returns "jak-se-dnes-mate" */stableStringify
Deterministically converts any JavaScript value into a JSON string by recursively sorting object keys while preserving array order. It safely handles circular references by replacing them with the string "[Circular]" and never mutates the input. This makes it ideal for creating stable cache keys, hashing inputs, logging, or equality checks that should ignore object key order.
// Example usage
import { stableStringify } from "./stable-stringify";
// Key order does not affect the output
const a = { b: 2, a: 1, nested: { y: 2, x: 1 } };
const b = { nested: { x: 1, y: 2 }, a: 1, b: 2 };
console.log(stableStringify(a));
// -> {"a":1,"b":2,"nested":{"x":1,"y":2}}
console.log(stableStringify(b));
// -> {"a":1,"b":2,"nested":{"x":1,"y":2}} // same as above
// Circular references are handled
const obj: any = { name: "root" };
obj.self = obj;
console.log(stableStringify(obj));
// -> {"name":"root","self":"[Circular]"}trimTrailingZeros
import { trimTrailingZeros } from "@uxf/core/utils/trimTrailingZeros";
const example = trimTrailingZeros("120,450"); /* returns "120,45" */Validators
import { Validator } from "@uxf/core";
Validator.isEmail("...");
Validator.isPhone("...");