-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
utils.ts
48 lines (39 loc) · 1.19 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { withBase } from 'vitepress'
import { useData } from '../composables/data'
import { isExternal } from '../../shared'
export function throttleAndDebounce(fn: () => void, delay: number): () => void {
let timeoutId: NodeJS.Timeout
let called = false
return () => {
if (timeoutId) clearTimeout(timeoutId)
if (!called) {
fn()
;(called = true) && setTimeout(() => (called = false), delay)
} else timeoutId = setTimeout(fn, delay)
}
}
export function ensureStartingSlash(path: string): string {
return /^\//.test(path) ? path : `/${path}`
}
export function normalizeLink(url: string): string {
const { pathname, search, hash, protocol } = new URL(url, 'http://a.com')
if (
isExternal(url) ||
url.startsWith('#') ||
!protocol.startsWith('http') ||
/\.(?!html|md)\w+($|\?)/i.test(url)
)
return url
const { site } = useData()
const normalizedPath =
pathname.endsWith('/') || pathname.endsWith('.html')
? url
: url.replace(
/(?:(^\.+)\/)?.*$/,
`$1${pathname.replace(
/(\.md)?$/,
site.value.cleanUrls ? '' : '.html'
)}${search}${hash}`
)
return withBase(normalizedPath)
}