@dialpad/dialtone
Version:
Dialpad's Dialtone design system monorepo
306 lines (305 loc) • 10.1 kB
JavaScript
import { DEFAULT_PREFIX, DEFAULT_VALIDATION_MESSAGE_TYPE, VALIDATION_MESSAGE_TYPES } from "./constants.js";
import { configVue2StyleClassAttrs } from "./config.js";
import { h, Comment, Text } from "vue";
let UNIQUE_ID_COUNTER = 0;
let TIMER;
const FOCUSABLE_SELECTOR_NOT_HIDDEN = "input:not([type=hidden]):not(:disabled)";
const FOCUSABLE_SELECTOR_NOT_DISABLED = "select:not(:disabled),textarea:not(:disabled),button:not(:disabled)";
const FOCUSABLE_SELECTOR_NOT_HIDDEN_DISABLED = `${FOCUSABLE_SELECTOR_NOT_HIDDEN},${FOCUSABLE_SELECTOR_NOT_DISABLED}`;
const FOCUSABLE_SELECTOR = `a,frame,iframe,${FOCUSABLE_SELECTOR_NOT_HIDDEN_DISABLED},*[tabindex]`;
const scheduler = typeof setImmediate === "function" ? setImmediate : setTimeout;
function getUniqueString(prefix = DEFAULT_PREFIX) {
return `${prefix}${UNIQUE_ID_COUNTER++}`;
}
function getRandomElement(array, seed) {
if (seed) {
const hash = javaHashCode(seed);
return array[Math.abs(hash) % array.length];
} else {
return array[getRandomInt(array.length)];
}
}
function javaHashCode(str) {
let h2;
for (let i = 0; i < str.length; i++) {
h2 = Math.imul(31, h2) + str.charCodeAt(i) | 0;
}
return h2;
}
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function formatMessages(messages) {
if (!messages) {
return [];
}
return messages.map((message) => {
if (typeof message === "string") {
return {
message,
type: DEFAULT_VALIDATION_MESSAGE_TYPE
};
}
return message;
});
}
function filterFormattedMessages(formattedMessages) {
const validationState = getValidationState(formattedMessages);
if (!formattedMessages || !validationState) {
return [];
}
return formattedMessages.filter((message) => !!message.message && message.type === validationState);
}
function getValidationState(formattedMessages) {
if (!formattedMessages) {
return null;
}
if (hasFormattedMessageOfType(formattedMessages, VALIDATION_MESSAGE_TYPES.ERROR)) {
return VALIDATION_MESSAGE_TYPES.ERROR;
}
if (hasFormattedMessageOfType(formattedMessages, VALIDATION_MESSAGE_TYPES.WARNING)) {
return VALIDATION_MESSAGE_TYPES.WARNING;
}
if (hasFormattedMessageOfType(formattedMessages, VALIDATION_MESSAGE_TYPES.SUCCESS)) {
return VALIDATION_MESSAGE_TYPES.SUCCESS;
}
return null;
}
function hasFormattedMessageOfType(formattedMessages, messageType) {
if (!formattedMessages || !messageType) {
return false;
}
return formattedMessages.some((message) => (message == null ? void 0 : message.type) === messageType);
}
function findFirstFocusableNode(element) {
return element == null ? void 0 : element.querySelector(FOCUSABLE_SELECTOR);
}
const htmlFragment = (props) => {
return h("div", { innerHTML: props.html });
};
const flushPromises = () => {
return new Promise((resolve) => {
scheduler(resolve);
});
};
function hasSlotContent(slot, slotProps = {}) {
if (!slot) return false;
return slot(slotProps).some((vnode) => {
if (vnode.type === Comment) return false;
if (Array.isArray(vnode.children) && !vnode.children.length) return false;
return vnode.type !== Text || typeof vnode.children === "string" && vnode.children.trim() !== "";
});
}
const kebabCaseToPascalCase = (string) => {
return string == null ? void 0 : string.toLowerCase().split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
};
const pascalCaseToKebabCase = (string) => {
return string.replace(/\.?([A-Z0-9]+)/g, (x, y) => "-" + y.toLowerCase()).replace(/^-/, "");
};
const extractVueListeners = (attrs) => {
const listeners = Object.entries(attrs).filter(([key]) => key.match(/on[A-Z]/));
return Object.fromEntries(listeners);
};
const returnFirstEl = (el) => {
if ((el == null ? void 0 : el.nodeType) === Node.ELEMENT_NODE) {
return el;
} else if (!(el == null ? void 0 : el.nodeType)) {
return null;
} else {
return returnFirstEl(el == null ? void 0 : el.nextSibling);
}
};
function removeClassStyleAttrs(attrs) {
if (!configVue2StyleClassAttrs) return attrs;
const listeners = Object.entries(attrs).filter(([key]) => !["class", "style"].includes(key));
return Object.fromEntries(listeners);
}
function addClassStyleAttrs(attrs) {
if (!configVue2StyleClassAttrs) return {};
return {
class: attrs.class,
style: attrs.style
};
}
function debounce(func, timeout = 300) {
clearTimeout(TIMER);
TIMER = setTimeout(func, timeout);
}
function isOutOfViewPort(element) {
const bounding = element.getBoundingClientRect();
const isOut = {
top: bounding.top < 0,
left: bounding.left < 0,
bottom: bounding.bottom > (window.innerHeight || document.documentElement.clientHeight),
right: bounding.right > (window.innerWidth || document.documentElement.clientWidth)
};
isOut.any = Object.values(isOut).some((val) => val);
isOut.all = Object.values(isOut).every((val) => val);
return isOut;
}
const domainNameRegex = /(?:(?:[^\s!@#$%^&*()_=+[\]{}\\|;:'",.<>/?]+)\.)/;
const tldRegerx = new RegExp(
"(?:com|ru|org|net|de|jp|uk|br|it|pl|fr|in|au|ir|info|nl|cn|es|cz|kr|ca|eu|ua|co|gr|za|ro|biz|ch|se|tw|mx|vn|hu|be|tr|at|dk|tv|me|ar|sk|no|us|fi|id|cl|xyz|io|pt|by|il|ie|nz|kz|hk|lt|cc|my|sg|club|bg|edu|рф|pk|su|top|th|hr|rs|pe|pro|si|az|lv|pw|ae|ph|online|ng|ee|ws|ve|cat)"
);
const ipv4Regex = new RegExp(
"(?:(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])"
);
const hostnameOrIpRegex = new RegExp(
"(?:" + [
[
domainNameRegex.source,
tldRegerx.source
].join("+"),
ipv4Regex.source
].join("|") + ")"
);
const urlPathRegex = /(?:(?:[;/][^#?<>\s]*)?)/;
const urlQueryOrFragmentRegex = /(?:(?:\?[^#<>\s]+)?(?:#[^<>\s]+)?)/;
const urlWithoutProtocolRegex = new RegExp(
"\\b" + [
hostnameOrIpRegex.source,
urlPathRegex.source,
urlQueryOrFragmentRegex.source,
"(?!\\w)"
].join("+")
);
const urlWithProtocolRegex = /\b[a-z\d.-]+:\/\/[^<>\s]+/;
const emailAddressRegex = new RegExp(
"(?:mailto:)?[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@" + [
hostnameOrIpRegex.source,
urlQueryOrFragmentRegex.source
].join("+") + "(?!\\w)"
);
function getPhoneNumberRegex(minLength = 7, maxLength = 15) {
try {
return new RegExp(
`(?:^|(?<=\\W))(?![\\s\\-])\\+?(?:[0-9()\\- \\t]{${minLength},${maxLength}})(?=\\b)(?=\\W(?=\\W|$)|\\s|$)`
);
} catch (e) {
console.warn("This browser doesn't support regex lookahead/lookbehind");
}
return new RegExp(
`(?![\\s\\-])\\+?(?:[0-9()\\- \\t]{${minLength},${maxLength}})(?=\\b)(?=\\W(?=\\W|$)|\\s|$)`
);
}
const phoneNumberRegex = getPhoneNumberRegex();
const linkRegex = new RegExp(
[
urlWithoutProtocolRegex.source,
urlWithProtocolRegex.source,
emailAddressRegex.source,
phoneNumberRegex.source
].join("|"),
"gi"
);
function isPhoneNumber(input) {
var _a;
if (!input || !["string", "number"].includes(typeof input)) return false;
input = input.toString();
return ((_a = phoneNumberRegex.exec(input)) == null ? void 0 : _a[0]) === input;
}
function isURL(input) {
var _a, _b;
if (!input || typeof input !== "string") return false;
return ((_a = urlWithoutProtocolRegex.exec(input)) == null ? void 0 : _a[0]) === input || ((_b = urlWithProtocolRegex.exec(input)) == null ? void 0 : _b[0]) === input;
}
function isEmailAddress(input) {
var _a;
if (!input || typeof input !== "string") return false;
return ((_a = emailAddressRegex.exec(input)) == null ? void 0 : _a[0]) === input;
}
function safeConcatStrings(elements) {
return elements.filter((str) => !!str).join(" ");
}
function capitalizeFirstLetter(str, locale = "en-US") {
return str.replace(new RegExp("^\\p{CWU}", "u"), (char) => char.toLocaleUpperCase(locale));
}
function warnIfUnmounted(componentRef, componentName) {
if (typeof process === "undefined") return;
if (process.env.NODE_ENV !== "test") return;
if (!componentRef || !(componentRef instanceof HTMLElement) || !(document == null ? void 0 : document.body)) return;
if (!document.body.contains(componentRef)) {
console.warn(`The ${componentName} component is not attached to the document body. This may cause issues.`);
}
}
function isDtScrollbarInUse(rootElement = document.documentElement) {
if (rootElement.hasAttribute("data-overlayscrollbars")) {
return true;
}
return false;
}
function disableRootScrolling(rootElement = document.documentElement) {
if (isDtScrollbarInUse(rootElement)) {
rootElement.classList.add("d-scrollbar-disabled");
} else {
rootElement.classList.add("d-of-hidden");
}
}
function enableRootScrolling(rootElement = document.documentElement) {
if (isDtScrollbarInUse(rootElement)) {
rootElement.classList.remove("d-scrollbar-disabled");
} else {
rootElement.classList.remove("d-of-hidden");
}
}
const utils = {
getUniqueString,
getRandomElement,
getRandomInt,
formatMessages,
filterFormattedMessages,
hasFormattedMessageOfType,
getValidationState,
htmlFragment,
flushPromises,
kebabCaseToPascalCase,
extractVueListeners,
removeClassStyleAttrs,
addClassStyleAttrs,
returnFirstEl,
debounce,
isOutOfViewPort,
getPhoneNumberRegex,
linkRegex,
isEmailAddress,
isPhoneNumber,
isURL,
safeConcatStrings,
capitalizeFirstLetter,
disableRootScrolling,
enableRootScrolling
};
export {
addClassStyleAttrs,
capitalizeFirstLetter,
debounce,
utils as default,
disableRootScrolling,
enableRootScrolling,
extractVueListeners,
filterFormattedMessages,
findFirstFocusableNode,
flushPromises,
formatMessages,
getPhoneNumberRegex,
getRandomElement,
getRandomInt,
getUniqueString,
getValidationState,
hasFormattedMessageOfType,
hasSlotContent,
htmlFragment,
isEmailAddress,
isOutOfViewPort,
isPhoneNumber,
isURL,
javaHashCode,
kebabCaseToPascalCase,
linkRegex,
pascalCaseToKebabCase,
removeClassStyleAttrs,
returnFirstEl,
safeConcatStrings,
warnIfUnmounted
};
//# sourceMappingURL=utils.js.map