@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
366 lines • 11.7 kB
JavaScript
import _JSON$parse from "core-js-pure/stable/json/parse.js";
import _Object$hasOwn from "core-js-pure/stable/object/has-own.js";
import _matchAllInstanceProperty from "core-js-pure/stable/instance/match-all.js";
import _pushInstanceProperty from "core-js-pure/stable/instance/push.js";
import React from 'react';
import keycode from "./keycode.js";
import whatInput from 'what-input';
import { warn } from "./helpers.js";
import { getClosestParent } from "./helpers/getClosest.js";
import { init } from "./Eufemia.js";
import { defineNavigator } from "./legacy/component-helper-legacy.js";
export * from "./legacy/component-helper-legacy.js";
export { InteractionInvalidation } from "./helpers/InteractionInvalidation.js";
export { extendPropsWithContext, extendPropsWithContextInClassComponent } from "./helpers/extendPropsWithContext.js";
export { assignPropsWithContext } from "./helpers/assignPropsWithContext.js";
export { filterProps } from "./helpers/filterProps.js";
export { keycode, getClosestParent, warn };
init();
whatInput.specificKeys([9]);
defineNavigator();
export const validateDOMAttributes = (props, params) => {
if (props && props.attributes) {
let attr = props.attributes;
if (attr) {
if (attr[0] === '{') {
try {
attr = _JSON$parse(attr);
} catch (e) {
warn('Failed to parse attributes JSON:', e);
attr = null;
}
}
if (attr && typeof attr === 'object') {
Object.entries(attr).forEach(([key, value]) => {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return;
}
Object.assign(params, {
[key]: value
});
});
}
delete params.attributes;
}
}
if (params.disabled === null || params.disabled === 'false') {
delete params.disabled;
}
if (typeof params.space !== 'undefined') {
delete params.space;
}
if (typeof params.top !== 'undefined') {
delete params.top;
}
if (typeof params.right !== 'undefined') {
delete params.right;
}
if (typeof params.bottom !== 'undefined') {
delete params.bottom;
}
if (typeof params.left !== 'undefined') {
delete params.left;
}
if (typeof params.no_collapse !== 'undefined') {
delete params.no_collapse;
}
if (typeof params.innerSpace !== 'undefined') {
delete params.innerSpace;
} else if (params.disabled === 'true') {
params.disabled = true;
}
if (params.disabled === true) {
params['aria-disabled'] = true;
}
if (props && props.tabindex) {
let tabIndex = props.tabindex;
if (tabIndex === 'off') {
tabIndex = '-1';
}
params['tabIndex'] = tabIndex;
}
if (params && typeof params === 'object') {
for (const i in params) {
if (typeof params[i] === 'function' && !/(^[a-z]{1,}[A-Z]{1})/.test(i)) {
delete params[i];
} else if (params[i] === null || /[^a-z-]/i.test(i)) {
delete params[i];
}
}
}
return params;
};
export const extendGracefully = (...objects) => {
let first = {};
const keepRef = objects[0];
if (keepRef === true || keepRef === false) {
objects.shift();
if (keepRef) {
first = objects.shift();
}
}
return objects.reduce((acc1, object) => {
if (object) {
acc1 = Object.assign(acc1, Object.entries(object).reduce((acc2, [key, value]) => {
if (value !== null) {
if (typeof value === 'object') {
value = extendGracefully(acc1[key] || {}, value);
if (Object.keys(value).length > 0) {
acc2[key] = value;
}
} else {
acc2[key] = value;
}
}
return acc2;
}, {}));
}
return acc1;
}, first);
};
export function isObject(item) {
return item && typeof item === 'object' && !Array.isArray(item);
}
export function extendDeep(target = {}, ...sources) {
for (const source of sources) {
if (isObject(source)) {
for (const key in source) {
if (key === '__proto__' || key === 'constructor') continue;
if (!_Object$hasOwn(source, key)) continue;
if (!isObject(target)) continue;
if (isObject(source[key])) {
if (!isObject(target[key])) {
target[key] = {};
}
extendDeep(target[key], source[key]);
} else {
target[key] = source[key];
}
}
}
}
return target;
}
export const isTrue = value => {
if (value !== null && typeof value !== 'undefined' && (String(value) === 'true' || String(value) === '1')) {
return true;
}
return false;
};
export const dispatchCustomElementEvent = (src, eventName, eventObjectOrig = undefined) => {
let ret = undefined;
const eventObject = {
...(eventObjectOrig && eventObjectOrig.event || {}),
...eventObjectOrig
};
if (eventObject && eventObject.attributes && eventObject.event) {
const currentTarget = eventObject.event.currentTarget;
if (currentTarget) {
try {
const dataset = {
...(currentTarget.dataset || {})
};
const attributes = {
...eventObject.attributes
};
for (const i in attributes) {
if (/^data-/.test(i)) {
dataset[String(i).replace(/^data-/, '')] = attributes[i];
}
}
for (const i in dataset) {
if (eventObject.event.currentTarget.dataset) {
eventObject.event.currentTarget.dataset[i] = dataset[i];
}
if (eventObject.event.target && eventObject.event.target.dataset) {
eventObject.event.target.dataset[i] = dataset[i];
}
}
} catch (e) {
warn('Error on handling dataset:', e);
}
}
}
const props = src && src.props || src;
if (eventName.includes('_')) {
if (typeof props[eventName] === 'function') {
const r = props[eventName].apply(src, [eventObject]);
if (typeof r !== 'undefined') {
ret = r;
}
}
eventName = toCamelCase(eventName);
if (typeof props[eventName] === 'function') {
const r = props[eventName].apply(src, [eventObject]);
if (typeof r !== 'undefined') {
ret = r;
}
}
} else {
if (typeof props[eventName] === 'function') {
const r = props[eventName].apply(src, [eventObject]);
if (typeof r !== 'undefined') {
ret = r;
}
}
eventName = toSnakeCase(eventName);
if (typeof props[eventName] === 'function') {
const r = props[eventName].apply(src, [eventObject]);
if (typeof r !== 'undefined') {
ret = r;
}
}
}
return ret;
};
export const toCamelCase = s => s.split(/_/g).reduce((acc, cur, i) => acc + (i === 0 ? cur : cur.replace(/(\w)(\w*)/g, (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase())), '');
export const toPascalCase = s => s.split(/_/g).reduce((acc, cur) => acc + cur.replace(/(\w)(\w*)/g, (g0, g1, g2) => g1.toUpperCase() + g2.toLowerCase()), '');
export const toSnakeCase = str => str.replace(/\B[A-Z]/g, letter => `_${letter}`).toLowerCase();
export const toKebabCase = str => str.replace(/\B[A-Z]/g, letter => `-${letter}`).toLowerCase();
export function toCapitalized(str) {
return typeof str === 'string' ? str.toLowerCase().split('').map((char, index, arr) => index === 0 || arr[index - 1] === ' ' || arr[index - 1] === '-' ? char.toUpperCase() : char).join('') : str;
}
export const makeUniqueId = (prefix = 'id-', length = 8) => prefix + String(Math.random().toString(36).substring(2, 2 + length) + idIncrement++).slice(-length);
let idIncrement = 0;
export const slugify = s => String(s).toLowerCase().replace(/[^\w\s-]/g, '').replace(/[\s_-]+/g, '-').replace(/^-+|-+$/g, '');
export const matchAll = (string, regex) => {
if (typeof _matchAllInstanceProperty(string) === 'function') {
return Array.from(_matchAllInstanceProperty(string).call(string, regex));
}
const matches = [];
let match;
while (match = regex.exec(string)) {
_pushInstanceProperty(matches).call(matches, match);
}
return matches;
};
export const isChildOfElement = (element, target, callback = null) => {
try {
const contains = element => {
if (callback) {
const res = callback(element);
if (res) {
return element;
}
}
return element && element === target;
};
if (contains(element)) {
return element;
}
while ((element = element && element.parentElement) && !contains(element));
} catch (e) {}
return element;
};
export const roundToNearest = (num, target) => {
const diff = num % target;
return diff > target / 2 ? num - diff + target : num - diff;
};
export const getClosestScrollViewElement = currentElement => {
return getClosestParent('.dnb-scroll-view', currentElement);
};
export function convertJsxToString(elements, separator = undefined, transformWord = undefined) {
if (!Array.isArray(elements)) {
elements = [elements];
}
const process = word => {
if (React.isValidElement(word)) {
if (transformWord) {
word = transformWord(word);
}
if (Array.isArray(word.props.children)) {
word = word.props.children.reduce((acc, word) => {
if (typeof word !== 'string') {
word = process(word);
}
if (typeof word === 'string') {
acc = (acc + (separator || '') + word).trim();
}
return acc;
}, '');
} else if (word.props.children) {
word = word.props.children;
if (typeof word !== 'string') {
word = process(word);
}
if (typeof word === 'string') {
word = word.trim();
} else {
return undefined;
}
} else {
return undefined;
}
}
return word;
};
return Array.from(elements).map(word => process(word)).filter(Boolean).join(separator).trim();
}
export function convertStatusToStateOnly(status, state) {
return status ? state : null;
}
export function getStatusState(status) {
return status && status !== 'error' && status !== 'warn' && status !== 'info';
}
export function combineLabelledBy(...params) {
return combineAriaBy('aria-labelledby', params);
}
export function combineDescribedBy(...params) {
return combineAriaBy('aria-describedby', params);
}
export function combineDetails(...params) {
return combineAriaBy('aria-details', params);
}
function combineAriaBy(type, params) {
params = params.map(cur => {
if (Array.isArray(cur)) {
return cur.join(' ');
}
if (cur && params.includes(cur[type])) {
return null;
}
if (cur && typeof cur[type] !== 'undefined') {
cur = cur[type];
}
if (typeof cur !== 'string') {
cur = null;
}
return cur;
});
params = params.filter(Boolean).join(' ');
if (params === '') {
params = undefined;
}
return params;
}
export function findElementInChildren(children, find) {
if (!Array.isArray(children)) {
children = [children];
}
let result = null;
children.some(cur => {
if (cur && cur.props && cur.props.children) {
const res = findElementInChildren(cur.props.children, find);
if (res) {
return result = res;
}
}
if (React.isValidElement(cur) && find(cur)) {
return result = cur;
}
return null;
});
return result;
}
export function escapeRegexChars(str) {
return str.replace(/[-[\]{}()*+?.,\\^$|#]/g, '\\$&');
}
export function removeUndefinedProps(object) {
Object.keys(object || {}).forEach(key => {
if (object[key] === undefined) {
delete object[key];
}
});
return object;
}
//# sourceMappingURL=component-helper.js.map