/** * Делает строку безопасной для использования с регулярными выражениями */ export function toSafeRegexString(regex: string): string { return regex.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&') } /** * Пример: highlight('apple and orange', 'and', '$&') // 'apple and orange' * @param text Изначальная строка * @param match Искомое значение * @param replace Подставляемое значение. Используйте "$&" там, куда нужно подставить параметр match. * @returns Строка с подставленным replace на место match */ export function highlight(text: string, match: string, replace = '*$&*'): string { if (!match || !text) return text return text.replaceAll(new RegExp(toSafeRegexString(match), 'gi'), replace) } export class DebounceRejectError extends Error {} export function asyncDebounce>(func: (...args: ARGS) => R, timeout = 500) : (...args: ARGS) => Promise { let timer: number let rejectCaptured: any return (...args: ARGS) => { clearTimeout(timer) if (rejectCaptured) { rejectCaptured() rejectCaptured = undefined } return new Promise((resolve, reject) => { rejectCaptured = () => { reject(new DebounceRejectError()) } timer = window.setTimeout(async () => { resolve(await func(...args)) }, timeout) }) } } export function copyTooltip(text: string, top: number, left: number): void { navigator.clipboard.writeText(text).then(() => { const tooltip = document.createElement('div') tooltip.textContent = 'Скопировано' tooltip.className = 'ark-ui-tooltip-cloud' document.body.appendChild(tooltip) tooltip.style.opacity = '1' tooltip.style.left = `${top}px` tooltip.style.top = `${left}px` setTimeout(() => { tooltip.remove() }, 1000) }) } /** * Получить ширину текста в пикселях * @param text Строка с текстом * @param font Настройки шрифта (CSS настройки). Например: 'bold 14px Roboto' * @returns Ширина в пикселях */ export function getTextWidth(text: string, font: string): number { const tag = document.createElement('div') tag.style.position = 'fixed' tag.style.left = '-100wh' tag.style.top = '-100vh' tag.style.whiteSpace = 'nowrap' tag.style.opacity = '0' tag.style.font = font tag.innerHTML = text document.body.appendChild(tag) const result = tag.clientWidth document.body.removeChild(tag) return result } export function setCountSpaces(num: number | string): string { const rx = /(\d+)(\d{3})/ return String(num).replace(/^\d+/, (w) => { while (rx.test(w)) { w = w.replace(rx, '$1 $2') } return w }) }