/
shared.ts
178 lines (150 loc) · 4.58 KB
/
shared.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import {
SiteData,
PageData,
LocaleConfig,
HeadConfig
} from '../../types/shared.js'
export type {
SiteData,
PageData,
HeadConfig,
LocaleConfig,
Header,
DefaultTheme,
PageDataPayload,
CleanUrlsMode,
Awaitable
} from '../../types/shared.js'
export const EXTERNAL_URL_RE = /^[a-z]+:/i
export const APPEARANCE_KEY = 'vitepress-theme-appearance'
export const inBrowser = typeof window !== 'undefined'
export const notFoundPageData: PageData = {
relativePath: '',
title: '404',
description: 'Not Found',
headers: [],
frontmatter: { sidebar: false, layout: 'page' },
lastUpdated: 0
}
function findMatchRoot(route: string, roots: string[]): string | undefined {
// first match to the routes with the most deep level.
roots.sort((a, b) => {
const levelDelta = b.split('/').length - a.split('/').length
if (levelDelta !== 0) {
return levelDelta
} else {
return b.length - a.length
}
})
for (const r of roots) {
if (route.startsWith(r)) return r
}
}
function resolveLocales<T>(
locales: Record<string, T>,
route: string
): T | undefined {
const localeRoot = findMatchRoot(route, Object.keys(locales))
return localeRoot ? locales[localeRoot] : undefined
}
export function createLangDictionary(siteData: {
themeConfig?: Record<string, any>
locales?: Record<string, LocaleConfig>
}) {
const { locales } = siteData.themeConfig || {}
const siteLocales = siteData.locales
return locales && siteLocales
? Object.keys(locales).reduce((langs, path) => {
langs[path] = {
label: locales![path].label,
lang: siteLocales[path].lang
}
return langs
}, {} as Record<string, { lang: string; label: string }>)
: {}
}
// this merges the locales data to the main data by the route
export function resolveSiteDataByRoute(
siteData: SiteData,
route: string
): SiteData {
route = cleanRoute(siteData, route)
const localeData = resolveLocales(siteData.locales || {}, route)
const localeThemeConfig = resolveLocales<any>(
siteData.themeConfig.locales || {},
route
)
// avoid object rest spread since this is going to run in the browser
// and spread is going to result in polyfill code
return Object.assign({}, siteData, localeData, {
themeConfig: Object.assign({}, siteData.themeConfig, localeThemeConfig, {
// clean the locales to reduce the bundle size
locales: {}
}),
lang: (localeData || siteData).lang,
// clean the locales to reduce the bundle size
locales: {},
langs: createLangDictionary(siteData)
})
}
/**
* Create the page title string based on configs.
*/
export function createTitle(siteData: SiteData, pageData: PageData): string {
const title = pageData.title || siteData.title
const template = pageData.titleTemplate ?? siteData.titleTemplate
if (typeof template === 'string' && template.includes(':title')) {
return template.replace(/:title/g, title)
}
const templateString = createTitleTemplate(siteData.title, template)
return `${title}${templateString}`
}
function createTitleTemplate(
siteTitle: string,
template?: string | boolean
): string {
if (template === false) {
return ''
}
if (template === true || template === undefined) {
return ` | ${siteTitle}`
}
if (siteTitle === template) {
return ''
}
return ` | ${template}`
}
/**
* Clean up the route by removing the `base` path if it's set in config.
*/
function cleanRoute(siteData: SiteData, route: string): string {
if (!inBrowser) {
return route
}
const base = siteData.base
const baseWithoutSuffix = base.endsWith('/') ? base.slice(0, -1) : base
return route.slice(baseWithoutSuffix.length)
}
function hasTag(head: HeadConfig[], tag: HeadConfig) {
const [tagType, tagAttrs] = tag
if (tagType !== 'meta') return false
const keyAttr = Object.entries(tagAttrs)[0] // First key
if (keyAttr == null) return false
return head.some(
([type, attrs]) => type === tagType && attrs[keyAttr[0]] === keyAttr[1]
)
}
export function mergeHead(prev: HeadConfig[], curr: HeadConfig[]) {
return [...prev.filter((tagAttrs) => !hasTag(curr, tagAttrs)), ...curr]
}
// https://github.com/rollup/rollup/blob/fec513270c6ac350072425cc045db367656c623b/src/utils/sanitizeFileName.ts
const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$&*+,:;<=>?[\]^`{|}\u007F]/g
const DRIVE_LETTER_REGEX = /^[a-z]:/i
export function sanitizeFileName(name: string): string {
const match = DRIVE_LETTER_REGEX.exec(name)
const driveLetter = match ? match[0] : ''
return (
driveLetter +
name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_')
)
}