besper-frontend-site-dev-main
Version:
Professional B-esper Frontend Site - Site-wide integration toolkit for full website bot deployment
117 lines (103 loc) • 3.01 kB
text/typescript
// DOM utility functions
export function createElement(
tag: string,
className?: string,
textContent?: string
): HTMLElement {
const element = document.createElement(tag);
if (className) element.className = className;
if (textContent) element.textContent = textContent;
return element;
}
export function querySelector(
selector: string,
parent: Element | Document = document
): HTMLElement | null {
return parent.querySelector(selector);
}
export function querySelectorAll(
selector: string,
parent: Element | Document = document
): NodeListOf<HTMLElement> {
return parent.querySelectorAll(selector);
}
export function addEventListeners(
element: HTMLElement,
events: { [key: string]: EventListener }
): void {
Object.entries(events).forEach(([event, listener]) => {
element.addEventListener(event, listener);
});
}
export function removeEventListeners(
element: HTMLElement,
events: { [key: string]: EventListener }
): void {
Object.entries(events).forEach(([event, listener]) => {
element.removeEventListener(event, listener);
});
}
export function injectStyles(styles: string, id?: string): HTMLStyleElement {
const existingStyle = id
? (document.getElementById(id) as HTMLStyleElement)
: null;
if (existingStyle) return existingStyle;
const styleElement = document.createElement('style');
if (id) styleElement.id = id;
styleElement.textContent = styles;
document.head.appendChild(styleElement);
return styleElement;
}
export function removeStyles(id: string): void {
const styleElement = document.getElementById(id);
if (styleElement) {
styleElement.remove();
}
}
export function isMobile(): boolean {
return (
window.innerWidth <= 768 ||
/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
)
);
}
export function isElementInViewport(element: HTMLElement): boolean {
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <=
(window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
export function scrollToElement(
element: HTMLElement,
behavior: ScrollBehavior = 'smooth'
): void {
element.scrollIntoView({ behavior, block: 'center' });
}
export function debounce<T extends (...args: any[]) => any>(
func: T,
delay: number
): (...args: Parameters<T>) => void {
let timeoutId: ReturnType<typeof setTimeout>;
return (...args: Parameters<T>) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(null, args), delay);
};
}
export function throttle<T extends (...args: any[]) => any>(
func: T,
limit: number
): (...args: Parameters<T>) => void {
let inThrottle: boolean;
return (...args: Parameters<T>) => {
if (!inThrottle) {
func.apply(null, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}