import { withBase } from 'vuepress/client' import { treatAsHtml } from './html.js' import { isExternal } from './links.js' /** * Create a throttled and debounced version of a function * * The function runs immediately on the first call, then at most once per * `delay` milliseconds. * * 创建函数节流与防抖后的版本 * * 首次调用立即执行,之后每 `delay` 毫秒最多执行一次。 * * @param fn - The function to call / 要调用的函数 * @param delay - The throttle delay in milliseconds / 节流延迟(毫秒) * @returns The throttled function / 节流后的函数 */ export const throttleAndDebounce = ( fn: () => void, delay: number, ): (() => void) => { let timeoutId: number let called = false return () => { if (timeoutId) clearTimeout(timeoutId) if (!called) { fn() called = true window.setTimeout(() => { called = false }, delay) } else { timeoutId = window.setTimeout(fn, delay) } } } /** * Check whether a link points outside of the site * * 判断链接是否指向站点外部 * * @param href - The link to check / 要检查的链接 * @param target - The target of the link / 链接的打开方式 * @param external - Explicit external flag, takes precedence / 显式的外部标记,优先级最高 * @returns Whether the link is external / 链接是否指向站点外部 */ export const isLinkExternal = ( href?: string, target?: string, external?: boolean, ): boolean => { if (external !== undefined) return external return (!!href && isExternal(href)) || target === '_blank' } /** * Normalize a link to the route path of its page * * A link pointing to a page is rewritten to its `.html` path so that the client * router handles it, then prefixed with the site base. Links to assets, hash * links and external links are kept as is. * * 将链接归一化为页面的路由路径 * * 指向页面的链接会被改写为 `.html` 路径,以便客户端路由处理,然后加上站点 base。指向资源的链接、hash 链接与外部链接保持原样。 * * @param url - The link to normalize / 要归一化的链接 * @returns The normalized link / 归一化后的链接 */ export const normalizeLink = (url: string): string => { const { pathname, search, hash, protocol } = new URL(url, 'http://a.com') if ( isExternal(url) || url.startsWith('#') || !protocol.startsWith('http') || !treatAsHtml(pathname) ) return url const normalizedPath = pathname.endsWith('/') || pathname.endsWith('.html') ? url : url.replace( /(?:(^\.+)\/)?.*$/, `$1${pathname.replace(/\.md$/, '.html')}${search}${hash}`, ) return withBase(normalizedPath) } /** * Remove the duplicated items of an array, keeping the first occurrence * * 去重数组,保留每个键第一次出现的位置 * * @param array - The array to deduplicate / 要去重的数组 * @param keyFn - The function returning the deduplication key / 返回去重键的函数 * @returns The deduplicated array / 去重后的数组 */ export const uniqBy = (array: T[], keyFn: (item: T) => unknown): T[] => { const seen = new Set() return array.filter((item) => { const key = keyFn(item) if (seen.has(key)) return false seen.add(key) return true }) }