mdorigin 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/adapters/cloudflare.js +2 -0
- package/dist/cli/build-index.js +3 -0
- package/dist/core/extensions.d.ts +13 -0
- package/dist/core/request-handler.js +256 -44
- package/dist/core/router.d.ts +9 -0
- package/dist/core/router.js +26 -0
- package/dist/core/site-config.d.ts +54 -0
- package/dist/core/site-config.js +107 -0
- package/dist/html/template.d.ts +16 -0
- package/dist/html/template.js +112 -33
- package/dist/html/theme.js +70 -0
- package/dist/i18n/messages.d.ts +45 -0
- package/dist/i18n/messages.js +104 -0
- package/dist/index-builder.d.ts +3 -1
- package/dist/index-builder.js +8 -2
- package/package.json +4 -4
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ContentStore } from './content-store.js';
|
|
2
2
|
import type { MdoPlugin } from './extensions.js';
|
|
3
|
+
import { type SiteMessages } from '../i18n/messages.js';
|
|
3
4
|
export interface SiteNavItem {
|
|
4
5
|
label: string;
|
|
5
6
|
href: string;
|
|
@@ -64,6 +65,16 @@ export interface SiteSearchConfig {
|
|
|
64
65
|
export interface SiteConfig {
|
|
65
66
|
siteTitle?: string;
|
|
66
67
|
siteDescription?: string;
|
|
68
|
+
/** Site UI locale (BCP 47) used for built-in chrome messages. Defaults to 'en'. */
|
|
69
|
+
locale?: string;
|
|
70
|
+
/** Flat overrides for built-in UI messages; keys are typed via SiteMessages. */
|
|
71
|
+
messages?: Partial<SiteMessages>;
|
|
72
|
+
/**
|
|
73
|
+
* Content locales for a multilingual site. Each non-default locale keeps its
|
|
74
|
+
* content under a top-level `{code}/` directory that maps 1:1 to its URL
|
|
75
|
+
* path prefix. Omit for single-language sites.
|
|
76
|
+
*/
|
|
77
|
+
locales?: LocaleConfigInput[];
|
|
67
78
|
siteUrl?: string;
|
|
68
79
|
favicon?: string;
|
|
69
80
|
socialImage?: string;
|
|
@@ -88,6 +99,9 @@ export interface UserSiteConfig extends SiteConfig {
|
|
|
88
99
|
export interface ResolvedSiteConfig {
|
|
89
100
|
siteTitle: string;
|
|
90
101
|
siteDescription?: string;
|
|
102
|
+
locale: string;
|
|
103
|
+
messages: Partial<SiteMessages>;
|
|
104
|
+
locales?: ResolvedLocaleConfig[];
|
|
91
105
|
siteUrl?: string;
|
|
92
106
|
favicon?: string;
|
|
93
107
|
socialImage?: string;
|
|
@@ -119,6 +133,46 @@ export interface LoadedSiteConfig {
|
|
|
119
133
|
configFilePath: string;
|
|
120
134
|
configModulePath?: string;
|
|
121
135
|
}
|
|
136
|
+
export interface LocaleConfigInput {
|
|
137
|
+
/** BCP 47 locale code, e.g. 'en' or 'zh-CN'. Also the content directory name. */
|
|
138
|
+
code: string;
|
|
139
|
+
/** Switcher display label. Defaults to the code. */
|
|
140
|
+
label?: string;
|
|
141
|
+
/**
|
|
142
|
+
* URL path prefix. Must be '' (only allowed for the default locale) or
|
|
143
|
+
* '/{code}'. Defaults to '' for the default locale and '/{code}' otherwise.
|
|
144
|
+
*/
|
|
145
|
+
pathPrefix?: string;
|
|
146
|
+
/** Mark exactly one locale as default. */
|
|
147
|
+
default?: boolean;
|
|
148
|
+
/** UI message overrides for this locale; win over global `messages`. */
|
|
149
|
+
messages?: Partial<SiteMessages>;
|
|
150
|
+
/** Site title override for this locale; wins over the global `siteTitle`. */
|
|
151
|
+
siteTitle?: string;
|
|
152
|
+
/** Site description override for this locale; wins over the global `siteDescription`. */
|
|
153
|
+
siteDescription?: string;
|
|
154
|
+
/** Explicit top navigation for this locale; wins over the global `topNav`. */
|
|
155
|
+
topNav?: SiteNavItem[];
|
|
156
|
+
/** Explicit footer navigation for this locale; wins over the global `footerNav`. */
|
|
157
|
+
footerNav?: SiteNavItem[];
|
|
158
|
+
}
|
|
159
|
+
export interface ResolvedLocaleConfig {
|
|
160
|
+
code: string;
|
|
161
|
+
label: string;
|
|
162
|
+
pathPrefix: string;
|
|
163
|
+
isDefault: boolean;
|
|
164
|
+
/** Content base directory: '' (content root) for an unprefixed default locale, otherwise `{code}`. */
|
|
165
|
+
contentBase: string;
|
|
166
|
+
messages: Partial<SiteMessages>;
|
|
167
|
+
/** Site title override; undefined falls back to the global `siteTitle`. */
|
|
168
|
+
siteTitle?: string;
|
|
169
|
+
/** Site description override; undefined falls back to the global `siteDescription`. */
|
|
170
|
+
siteDescription?: string;
|
|
171
|
+
/** Explicit top navigation override; empty array falls back to the global `topNav`. */
|
|
172
|
+
topNav: SiteNavItem[];
|
|
173
|
+
/** Explicit footer navigation override; empty array falls back to the global `footerNav`. */
|
|
174
|
+
footerNav: SiteNavItem[];
|
|
175
|
+
}
|
|
122
176
|
export declare function loadSiteConfig(options?: LoadSiteConfigOptions): Promise<ResolvedSiteConfig>;
|
|
123
177
|
export declare function loadUserSiteConfig(options?: LoadSiteConfigOptions): Promise<LoadedSiteConfig>;
|
|
124
178
|
export declare function applySiteConfigFrontmatterDefaults(store: ContentStore, siteConfig: ResolvedSiteConfig): Promise<ResolvedSiteConfig>;
|
package/dist/core/site-config.js
CHANGED
|
@@ -4,6 +4,7 @@ import { pathToFileURL } from 'node:url';
|
|
|
4
4
|
import { tsImport } from 'tsx/esm/api';
|
|
5
5
|
import { getDirectoryIndexCandidates } from './directory-index.js';
|
|
6
6
|
import { parseMarkdownDocument } from './markdown.js';
|
|
7
|
+
import { DEFAULT_SITE_LOCALE, validateSiteMessages, } from '../i18n/messages.js';
|
|
7
8
|
export async function loadSiteConfig(options = {}) {
|
|
8
9
|
return (await loadUserSiteConfig(options)).siteConfig;
|
|
9
10
|
}
|
|
@@ -15,6 +16,8 @@ export async function loadUserSiteConfig(options = {}) {
|
|
|
15
16
|
: await resolveDefaultConfigPath(cwd, rootDir);
|
|
16
17
|
const parsedConfig = await loadConfigSource(configFilePath);
|
|
17
18
|
const legacyConfig = parsedConfig;
|
|
19
|
+
const messageOverrides = resolveMessageOverrides(parsedConfig.messages, configFilePath);
|
|
20
|
+
const locales = resolveLocalesConfig(parsedConfig, configFilePath);
|
|
18
21
|
const stylesheetPath = parsedConfig.stylesheet
|
|
19
22
|
? path.resolve(path.dirname(configFilePath), parsedConfig.stylesheet)
|
|
20
23
|
: null;
|
|
@@ -29,6 +32,10 @@ export async function loadUserSiteConfig(options = {}) {
|
|
|
29
32
|
parsedConfig.siteDescription !== ''
|
|
30
33
|
? parsedConfig.siteDescription
|
|
31
34
|
: undefined,
|
|
35
|
+
locale: locales?.find((locale) => locale.isDefault)?.code ??
|
|
36
|
+
normalizeSiteLocale(parsedConfig.locale),
|
|
37
|
+
messages: messageOverrides,
|
|
38
|
+
locales,
|
|
32
39
|
siteUrl: normalizeSiteUrl(parsedConfig.siteUrl),
|
|
33
40
|
favicon: normalizeSiteHref(parsedConfig.favicon),
|
|
34
41
|
socialImage: normalizeSiteHref(parsedConfig.socialImage),
|
|
@@ -88,6 +95,99 @@ export async function applySiteConfigFrontmatterDefaults(store, siteConfig) {
|
|
|
88
95
|
}
|
|
89
96
|
return siteConfig;
|
|
90
97
|
}
|
|
98
|
+
function resolveMessageOverrides(value, configFilePath) {
|
|
99
|
+
if (value === undefined) {
|
|
100
|
+
return {};
|
|
101
|
+
}
|
|
102
|
+
const { messages, unknownKeys } = validateSiteMessages(value);
|
|
103
|
+
if (unknownKeys.length > 0) {
|
|
104
|
+
throw new Error(`[mdorigin] ${configFilePath}: "messages" contains unknown keys: ${unknownKeys.join(', ')}`);
|
|
105
|
+
}
|
|
106
|
+
return messages;
|
|
107
|
+
}
|
|
108
|
+
function normalizeSiteLocale(value) {
|
|
109
|
+
if (typeof value !== 'string') {
|
|
110
|
+
return DEFAULT_SITE_LOCALE;
|
|
111
|
+
}
|
|
112
|
+
const trimmed = value.trim();
|
|
113
|
+
return trimmed === '' ? DEFAULT_SITE_LOCALE : trimmed;
|
|
114
|
+
}
|
|
115
|
+
const LOCALE_CODE_PATTERN = /^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/;
|
|
116
|
+
function resolveLocalesConfig(parsedConfig, configFilePath) {
|
|
117
|
+
const input = parsedConfig.locales;
|
|
118
|
+
if (input === undefined) {
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
if (!Array.isArray(input) || input.length === 0) {
|
|
122
|
+
throw new Error(`[mdorigin] ${configFilePath}: "locales" must be a non-empty array when configured`);
|
|
123
|
+
}
|
|
124
|
+
const seenCodes = new Set();
|
|
125
|
+
const parsed = [];
|
|
126
|
+
for (const entry of input) {
|
|
127
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
128
|
+
throw new Error(`[mdorigin] ${configFilePath}: every "locales" entry must be an object`);
|
|
129
|
+
}
|
|
130
|
+
const locale = entry;
|
|
131
|
+
const code = typeof locale.code === 'string' ? locale.code.trim() : '';
|
|
132
|
+
if (code === '' || !LOCALE_CODE_PATTERN.test(code)) {
|
|
133
|
+
throw new Error(`[mdorigin] ${configFilePath}: "locales[].code" must be a BCP 47 style code like "en" or "zh-CN"`);
|
|
134
|
+
}
|
|
135
|
+
const normalizedCodeKey = code.toLowerCase();
|
|
136
|
+
if (seenCodes.has(normalizedCodeKey)) {
|
|
137
|
+
throw new Error(`[mdorigin] ${configFilePath}: duplicate "locales" code: ${code}`);
|
|
138
|
+
}
|
|
139
|
+
seenCodes.add(normalizedCodeKey);
|
|
140
|
+
const isDefault = locale.default === true;
|
|
141
|
+
const pathPrefix = resolveLocalePathPrefix(locale, isDefault, configFilePath);
|
|
142
|
+
const { messages, unknownKeys } = validateSiteMessages(locale.messages);
|
|
143
|
+
if (unknownKeys.length > 0) {
|
|
144
|
+
throw new Error(`[mdorigin] ${configFilePath}: "locales[${code}].messages" contains unknown keys: ${unknownKeys.join(', ')}`);
|
|
145
|
+
}
|
|
146
|
+
parsed.push({
|
|
147
|
+
code,
|
|
148
|
+
label: typeof locale.label === 'string' && locale.label.trim() !== ''
|
|
149
|
+
? locale.label.trim()
|
|
150
|
+
: code,
|
|
151
|
+
pathPrefix,
|
|
152
|
+
isDefault,
|
|
153
|
+
messages,
|
|
154
|
+
siteTitle: normalizeOptionalSiteText(locale.siteTitle),
|
|
155
|
+
siteDescription: normalizeOptionalSiteText(locale.siteDescription),
|
|
156
|
+
topNav: normalizeTopNav(locale.topNav),
|
|
157
|
+
footerNav: normalizeTopNav(locale.footerNav),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
const defaultCount = parsed.filter((locale) => locale.isDefault).length;
|
|
161
|
+
if (defaultCount !== 1) {
|
|
162
|
+
throw new Error(`[mdorigin] ${configFilePath}: "locales" must mark exactly one locale with "default": true (found ${defaultCount})`);
|
|
163
|
+
}
|
|
164
|
+
const defaultLocale = parsed.find((locale) => locale.isDefault);
|
|
165
|
+
const configuredLocale = typeof parsedConfig.locale === 'string' ? parsedConfig.locale.trim() : '';
|
|
166
|
+
if (configuredLocale !== '' &&
|
|
167
|
+
configuredLocale.toLowerCase() !== defaultLocale?.code.toLowerCase()) {
|
|
168
|
+
throw new Error(`[mdorigin] ${configFilePath}: "locale" (${configuredLocale}) conflicts with the default "locales" entry (${defaultLocale?.code}); remove "locale" or align it with the default locale`);
|
|
169
|
+
}
|
|
170
|
+
return parsed.map((locale) => ({
|
|
171
|
+
...locale,
|
|
172
|
+
contentBase: locale.pathPrefix === '' ? '' : locale.code,
|
|
173
|
+
}));
|
|
174
|
+
}
|
|
175
|
+
function resolveLocalePathPrefix(locale, isDefault, configFilePath) {
|
|
176
|
+
if (locale.pathPrefix === undefined) {
|
|
177
|
+
return isDefault ? '' : `/${locale.code}`;
|
|
178
|
+
}
|
|
179
|
+
const prefix = locale.pathPrefix;
|
|
180
|
+
if (prefix === '') {
|
|
181
|
+
if (!isDefault) {
|
|
182
|
+
throw new Error(`[mdorigin] ${configFilePath}: "locales[${locale.code}].pathPrefix" can only be empty for the default locale`);
|
|
183
|
+
}
|
|
184
|
+
return '';
|
|
185
|
+
}
|
|
186
|
+
if (prefix !== `/${locale.code}`) {
|
|
187
|
+
throw new Error(`[mdorigin] ${configFilePath}: "locales[${locale.code}].pathPrefix" must be "/${locale.code}" or "" (default locales only); got "${prefix}"`);
|
|
188
|
+
}
|
|
189
|
+
return prefix;
|
|
190
|
+
}
|
|
91
191
|
async function resolveDefaultConfigPath(cwd, rootDir) {
|
|
92
192
|
const rootConfigPath = rootDir ? await findConfigPath(rootDir) : null;
|
|
93
193
|
if (rootConfigPath) {
|
|
@@ -187,6 +287,13 @@ function normalizeTopNav(value) {
|
|
|
187
287
|
return [];
|
|
188
288
|
});
|
|
189
289
|
}
|
|
290
|
+
function normalizeOptionalSiteText(value) {
|
|
291
|
+
if (typeof value !== 'string') {
|
|
292
|
+
return undefined;
|
|
293
|
+
}
|
|
294
|
+
const trimmed = value.trim();
|
|
295
|
+
return trimmed === '' ? undefined : trimmed;
|
|
296
|
+
}
|
|
190
297
|
function normalizePositiveInteger(value, fallback) {
|
|
191
298
|
if (typeof value === 'number' && Number.isInteger(value) && value > 0) {
|
|
192
299
|
return value;
|
package/dist/html/template.d.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import type { SiteLogo, SiteNavItem, SiteSocialLink } from '../core/site-config.js';
|
|
2
|
+
import type { PageLanguage } from '../core/extensions.js';
|
|
2
3
|
import type { ManagedIndexEntry } from '../core/markdown.js';
|
|
4
|
+
import { type SiteMessages } from '../i18n/messages.js';
|
|
3
5
|
export interface RenderDocumentOptions {
|
|
4
6
|
siteTitle: string;
|
|
5
7
|
siteDescription?: string;
|
|
8
|
+
locale?: string;
|
|
9
|
+
messages?: SiteMessages;
|
|
6
10
|
siteUrl?: string;
|
|
7
11
|
favicon?: string;
|
|
8
12
|
socialImage?: string;
|
|
@@ -27,6 +31,18 @@ export interface RenderDocumentOptions {
|
|
|
27
31
|
listingInitialPostCount?: number;
|
|
28
32
|
listingLoadMoreStep?: number;
|
|
29
33
|
searchEnabled?: boolean;
|
|
34
|
+
/** Language switcher entries; rendered in the header when more than one is present. */
|
|
35
|
+
languages?: PageLanguage[];
|
|
36
|
+
/** hreflang alternates with absolute URLs, including x-default when applicable. */
|
|
37
|
+
hreflangAlternates?: Array<{
|
|
38
|
+
hreflang: string;
|
|
39
|
+
href: string;
|
|
40
|
+
}>;
|
|
41
|
+
/** Locale content filter handed to the search client script. */
|
|
42
|
+
searchLocaleFilter?: {
|
|
43
|
+
include: string;
|
|
44
|
+
exclude: string[];
|
|
45
|
+
};
|
|
30
46
|
headerHtml?: string;
|
|
31
47
|
footerHtml?: string;
|
|
32
48
|
}
|
package/dist/html/template.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import { DEFAULT_SITE_LOCALE, resolveSiteMessages, serializeMessagesForScript, } from '../i18n/messages.js';
|
|
1
2
|
import { getDefaultThemeStyles } from './theme.js';
|
|
2
3
|
export function renderDocument(options) {
|
|
4
|
+
const locale = options.locale ?? DEFAULT_SITE_LOCALE;
|
|
5
|
+
const messages = options.messages ?? resolveSiteMessages(locale);
|
|
3
6
|
const title = escapeHtml(options.title);
|
|
4
7
|
const siteTitle = escapeHtml(options.siteTitle);
|
|
5
8
|
const siteDescription = options.siteDescription
|
|
@@ -28,6 +31,11 @@ export function renderDocument(options) {
|
|
|
28
31
|
const rssMeta = options.rssFeedUrl
|
|
29
32
|
? `<link rel="alternate" type="application/rss+xml" title="${siteTitle}" href="${escapeHtml(options.rssFeedUrl)}">`
|
|
30
33
|
: '';
|
|
34
|
+
const hreflangMeta = options.hreflangAlternates && options.hreflangAlternates.length > 0
|
|
35
|
+
? options.hreflangAlternates
|
|
36
|
+
.map((alternate) => `<link rel="alternate" hreflang="${escapeHtml(alternate.hreflang)}" href="${escapeHtml(alternate.href)}">`)
|
|
37
|
+
.join('')
|
|
38
|
+
: '';
|
|
31
39
|
const stylesheetBlock = `<style>${getDefaultThemeStyles()}${options.stylesheetContent ? `\n${options.stylesheetContent}` : ''}</style>`;
|
|
32
40
|
const navBlock = options.topNav && options.topNav.length > 0
|
|
33
41
|
? `<nav class="site-nav"><ul>${options.topNav
|
|
@@ -37,21 +45,35 @@ export function renderDocument(options) {
|
|
|
37
45
|
const searchToggleBlock = options.searchEnabled
|
|
38
46
|
? [
|
|
39
47
|
'<div class="site-search" data-site-search>',
|
|
40
|
-
|
|
48
|
+
`<button type="button" class="site-search__toggle" aria-expanded="false" aria-controls="site-search-panel">${escapeHtml(messages['search.toggle'])}</button>`,
|
|
41
49
|
'<div id="site-search-panel" class="site-search__panel" hidden>',
|
|
42
50
|
'<form class="site-search__form" role="search" action="/api/search" method="get">',
|
|
43
|
-
|
|
51
|
+
`<label class="site-search__label" for="site-search-input">${escapeHtml(messages['search.label'])}</label>`,
|
|
44
52
|
'<div class="site-search__controls">',
|
|
45
|
-
|
|
46
|
-
|
|
53
|
+
`<input id="site-search-input" class="site-search__input" type="search" name="q" placeholder="${escapeHtml(messages['search.placeholder'])}" autocomplete="off">`,
|
|
54
|
+
`<button type="submit" class="site-search__submit">${escapeHtml(messages['search.go'])}</button>`,
|
|
47
55
|
'</div>',
|
|
48
|
-
|
|
56
|
+
`<p class="site-search__hint">${messages['search.hint']}</p>`,
|
|
49
57
|
'</form>',
|
|
50
58
|
'<div class="site-search__results" data-site-search-results></div>',
|
|
51
59
|
'</div>',
|
|
52
60
|
'</div>',
|
|
53
61
|
].join('')
|
|
54
62
|
: '';
|
|
63
|
+
const currentLanguage = options.languages?.find((language) => language.current) ??
|
|
64
|
+
options.languages?.[0];
|
|
65
|
+
const languagesBlock = options.languages && options.languages.length > 1 && currentLanguage
|
|
66
|
+
? [
|
|
67
|
+
`<nav class="site-languages" aria-label="${escapeHtml(messages['languages.ariaLabel'])}">`,
|
|
68
|
+
'<details class="site-languages__details" data-site-languages>',
|
|
69
|
+
`<summary class="site-languages__toggle"><span class="site-languages__label">${escapeHtml(currentLanguage.label)}</span><svg class="site-languages__chevron" viewBox="0 0 16 16" width="11" height="11" aria-hidden="true" focusable="false"><path d="M4 6.5 8 10.5 12 6.5" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"></path></svg></summary>`,
|
|
70
|
+
`<ul class="site-languages__panel">${options.languages
|
|
71
|
+
.map((language) => `<li><a href="${escapeHtml(language.href)}" hreflang="${escapeHtml(language.code)}"${language.current ? ' aria-current="page"' : ''}>${escapeHtml(language.label)}</a></li>`)
|
|
72
|
+
.join('')}</ul>`,
|
|
73
|
+
'</details>',
|
|
74
|
+
'</nav>',
|
|
75
|
+
].join('')
|
|
76
|
+
: '';
|
|
55
77
|
const footerNavBlock = options.footerNav && options.footerNav.length > 0
|
|
56
78
|
? `<nav class="site-footer__nav"><ul>${options.footerNav
|
|
57
79
|
.map((item) => `<li><a href="${escapeHtml(item.href)}">${escapeHtml(item.label)}</a></li>`)
|
|
@@ -70,10 +92,10 @@ export function renderDocument(options) {
|
|
|
70
92
|
: '';
|
|
71
93
|
const brandHref = escapeHtml(options.logo?.href ?? '/');
|
|
72
94
|
const editLinkBlock = options.editLinkHref
|
|
73
|
-
? `<a class="site-footer__edit-link" href="${escapeHtml(options.editLinkHref)}"
|
|
95
|
+
? `<a class="site-footer__edit-link" href="${escapeHtml(options.editLinkHref)}">${escapeHtml(messages['footer.editPage'])}</a>`
|
|
74
96
|
: '';
|
|
75
97
|
const markdownViewBlock = options.alternateMarkdownPath
|
|
76
|
-
? `<a class="site-footer__markdown-link" href="${escapeHtml(options.alternateMarkdownPath)}" aria-label="
|
|
98
|
+
? `<a class="site-footer__markdown-link" href="${escapeHtml(options.alternateMarkdownPath)}" aria-label="${escapeHtml(messages['footer.markdownViewAria'])}">${escapeHtml(messages['footer.markdownView'])}</a>`
|
|
77
99
|
: '';
|
|
78
100
|
const footerActionsBlock = markdownViewBlock || editLinkBlock
|
|
79
101
|
? `<div class="site-footer__actions">${markdownViewBlock}${editLinkBlock}</div>`
|
|
@@ -92,15 +114,18 @@ export function renderDocument(options) {
|
|
|
92
114
|
requestPath: options.listingRequestPath ?? '/',
|
|
93
115
|
initialPostCount: options.listingInitialPostCount ?? 10,
|
|
94
116
|
loadMoreStep: options.listingLoadMoreStep ?? 10,
|
|
95
|
-
})
|
|
117
|
+
}, messages)
|
|
96
118
|
: options.body;
|
|
97
|
-
const searchScript = options.searchEnabled
|
|
119
|
+
const searchScript = options.searchEnabled
|
|
120
|
+
? renderSearchScript(messages, options.searchLocaleFilter)
|
|
121
|
+
: '';
|
|
122
|
+
const languagesScript = options.headerHtml || !languagesBlock ? '' : renderLanguagesScript();
|
|
98
123
|
const headerBlock = options.headerHtml ??
|
|
99
|
-
`<header class="site-header"><div class="site-header__inner"><div class="site-header__brand"><p class="site-header__title"><a href="${brandHref}">${logoBlock}<span>${siteTitle}</span></a></p>${siteDescriptionBlock}</div><div class="site-header__actions">${navBlock}${searchToggleBlock}</div></div></header>`;
|
|
124
|
+
`<header class="site-header"><div class="site-header__inner"><div class="site-header__brand"><p class="site-header__title"><a href="${brandHref}">${logoBlock}<span>${siteTitle}</span></a></p>${siteDescriptionBlock}</div><div class="site-header__actions">${navBlock}${languagesBlock}${searchToggleBlock}</div></div></header>`;
|
|
100
125
|
const renderedFooterBlock = options.footerHtml ?? footerBlock;
|
|
101
126
|
return [
|
|
102
127
|
'<!doctype html>',
|
|
103
|
-
|
|
128
|
+
`<html lang="${escapeHtml(locale)}">`,
|
|
104
129
|
'<head>',
|
|
105
130
|
'<meta charset="utf-8">',
|
|
106
131
|
'<meta name="viewport" content="width=device-width, initial-scale=1">',
|
|
@@ -111,6 +136,7 @@ export function renderDocument(options) {
|
|
|
111
136
|
socialImageMeta,
|
|
112
137
|
alternateMarkdownMeta,
|
|
113
138
|
rssMeta,
|
|
139
|
+
hreflangMeta,
|
|
114
140
|
stylesheetBlock,
|
|
115
141
|
'</head>',
|
|
116
142
|
'<body>',
|
|
@@ -120,6 +146,7 @@ export function renderDocument(options) {
|
|
|
120
146
|
'</main>',
|
|
121
147
|
renderedFooterBlock,
|
|
122
148
|
searchScript,
|
|
149
|
+
languagesScript,
|
|
123
150
|
'</body>',
|
|
124
151
|
'</html>',
|
|
125
152
|
].join('');
|
|
@@ -163,7 +190,7 @@ function renderSocialIcon(icon) {
|
|
|
163
190
|
function iconSvg(pathData) {
|
|
164
191
|
return `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="${pathData}"></path></svg>`;
|
|
165
192
|
}
|
|
166
|
-
function renderListingArticle(body, entries, options) {
|
|
193
|
+
function renderListingArticle(body, entries, options, messages) {
|
|
167
194
|
if (entries.length === 0) {
|
|
168
195
|
return body;
|
|
169
196
|
}
|
|
@@ -174,26 +201,26 @@ function renderListingArticle(body, entries, options) {
|
|
|
174
201
|
const shouldLoadMore = articles.length > visibleArticles.length;
|
|
175
202
|
return [
|
|
176
203
|
`<div class="catalog-page__body">${body}</div>`,
|
|
177
|
-
|
|
178
|
-
directories.length > 0 ? renderListingDirectories(directories) : '',
|
|
204
|
+
`<section class="catalog-page" aria-label="${escapeHtml(messages['listing.ariaLabel'])}">`,
|
|
205
|
+
directories.length > 0 ? renderListingDirectories(directories, messages) : '',
|
|
179
206
|
articles.length > 0
|
|
180
207
|
? renderListingArticles(visibleArticles, {
|
|
181
208
|
requestPath: options.requestPath,
|
|
182
209
|
nextOffset: visibleArticles.length,
|
|
183
210
|
loadMoreStep: options.loadMoreStep,
|
|
184
211
|
hasMore: shouldLoadMore,
|
|
185
|
-
})
|
|
212
|
+
}, messages)
|
|
186
213
|
: '',
|
|
187
214
|
'</section>',
|
|
188
|
-
shouldLoadMore ? renderListingLoadMoreScript() : '',
|
|
215
|
+
shouldLoadMore ? renderListingLoadMoreScript(messages) : '',
|
|
189
216
|
].join('');
|
|
190
217
|
}
|
|
191
|
-
function renderListingDirectories(entries) {
|
|
218
|
+
function renderListingDirectories(entries, messages) {
|
|
192
219
|
return [
|
|
193
220
|
'<div class="catalog-list catalog-list--directories">',
|
|
194
221
|
...entries.map((entry) => `<a class="catalog-item catalog-item--directory" href="${escapeHtml(entry.href)}"><strong class="catalog-item__title">${escapeHtml(entry.title)}</strong>${entry.detail
|
|
195
222
|
? `<span class="catalog-item__detail">${escapeHtml(entry.detail)}</span>`
|
|
196
|
-
:
|
|
223
|
+
: `<span class="catalog-item__detail">${escapeHtml(messages['listing.browseSection'])}</span>`}</a>`),
|
|
197
224
|
'</div>',
|
|
198
225
|
].join('');
|
|
199
226
|
}
|
|
@@ -204,17 +231,17 @@ export function renderListingArticleItems(entries) {
|
|
|
204
231
|
: ''}</a>`)
|
|
205
232
|
.join('');
|
|
206
233
|
}
|
|
207
|
-
function renderListingArticles(entries, options) {
|
|
234
|
+
function renderListingArticles(entries, options, messages) {
|
|
208
235
|
return [
|
|
209
236
|
'<div class="catalog-list" data-listing-articles>',
|
|
210
237
|
renderListingArticleItems(entries),
|
|
211
238
|
'</div>',
|
|
212
239
|
options.hasMore
|
|
213
|
-
? `<div class="catalog-load-more"><button type="button" class="catalog-load-more__button" data-listing-load-more data-request-path="${escapeHtml(options.requestPath)}" data-next-offset="${escapeHtml(String(options.nextOffset))}" data-load-more-step="${escapeHtml(String(options.loadMoreStep))}"
|
|
240
|
+
? `<div class="catalog-load-more"><button type="button" class="catalog-load-more__button" data-listing-load-more data-request-path="${escapeHtml(options.requestPath)}" data-next-offset="${escapeHtml(String(options.nextOffset))}" data-load-more-step="${escapeHtml(String(options.loadMoreStep))}">${escapeHtml(messages['listing.loadMore'])}</button></div>`
|
|
214
241
|
: '',
|
|
215
242
|
].join('');
|
|
216
243
|
}
|
|
217
|
-
function renderListingLoadMoreScript() {
|
|
244
|
+
function renderListingLoadMoreScript(messages) {
|
|
218
245
|
return `<script>
|
|
219
246
|
(() => {
|
|
220
247
|
const button = document.querySelector('[data-listing-load-more]');
|
|
@@ -223,6 +250,11 @@ function renderListingLoadMoreScript() {
|
|
|
223
250
|
return;
|
|
224
251
|
}
|
|
225
252
|
|
|
253
|
+
const M = ${serializeMessagesForScript({
|
|
254
|
+
loadMore: messages['listing.loadMore'],
|
|
255
|
+
loading: messages['listing.loading'],
|
|
256
|
+
})};
|
|
257
|
+
|
|
226
258
|
const loadMore = async () => {
|
|
227
259
|
const requestPath = button.dataset.requestPath;
|
|
228
260
|
const nextOffset = button.dataset.nextOffset;
|
|
@@ -233,7 +265,7 @@ function renderListingLoadMoreScript() {
|
|
|
233
265
|
|
|
234
266
|
button.disabled = true;
|
|
235
267
|
const previousLabel = button.textContent;
|
|
236
|
-
button.textContent =
|
|
268
|
+
button.textContent = M.loading;
|
|
237
269
|
|
|
238
270
|
try {
|
|
239
271
|
const url = new URL(requestPath, window.location.origin);
|
|
@@ -256,14 +288,14 @@ function renderListingLoadMoreScript() {
|
|
|
256
288
|
if (payload.hasMore === true && typeof payload.nextOffset === 'number') {
|
|
257
289
|
button.dataset.nextOffset = String(payload.nextOffset);
|
|
258
290
|
button.disabled = false;
|
|
259
|
-
button.textContent = previousLabel ??
|
|
291
|
+
button.textContent = previousLabel ?? M.loadMore;
|
|
260
292
|
return;
|
|
261
293
|
}
|
|
262
294
|
|
|
263
295
|
button.remove();
|
|
264
296
|
} catch {
|
|
265
297
|
button.disabled = false;
|
|
266
|
-
button.textContent = previousLabel ??
|
|
298
|
+
button.textContent = previousLabel ?? M.loadMore;
|
|
267
299
|
}
|
|
268
300
|
};
|
|
269
301
|
|
|
@@ -273,7 +305,36 @@ function renderListingLoadMoreScript() {
|
|
|
273
305
|
})();
|
|
274
306
|
</script>`;
|
|
275
307
|
}
|
|
276
|
-
function
|
|
308
|
+
function renderLanguagesScript() {
|
|
309
|
+
return `<script>
|
|
310
|
+
(function () {
|
|
311
|
+
const menus = Array.from(document.querySelectorAll("details[data-site-languages]"));
|
|
312
|
+
if (menus.length === 0) return;
|
|
313
|
+
document.addEventListener("click", (event) => {
|
|
314
|
+
for (const menu of menus) {
|
|
315
|
+
if (menu.open && !menu.contains(event.target)) menu.open = false;
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
document.addEventListener("keydown", (event) => {
|
|
319
|
+
if (event.key !== "Escape") return;
|
|
320
|
+
for (const menu of menus) {
|
|
321
|
+
if (!menu.open) continue;
|
|
322
|
+
menu.open = false;
|
|
323
|
+
menu.querySelector("summary")?.focus();
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
for (const menu of menus) {
|
|
327
|
+
menu.addEventListener("toggle", () => {
|
|
328
|
+
if (!menu.open) return;
|
|
329
|
+
for (const other of menus) {
|
|
330
|
+
if (other !== menu) other.open = false;
|
|
331
|
+
}
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
})();
|
|
335
|
+
</script>`;
|
|
336
|
+
}
|
|
337
|
+
function renderSearchScript(messages, localeFilter) {
|
|
277
338
|
return [
|
|
278
339
|
'<script>',
|
|
279
340
|
'(function () {',
|
|
@@ -285,41 +346,59 @@ function renderSearchScript() {
|
|
|
285
346
|
' const input = root.querySelector(".site-search__input");',
|
|
286
347
|
' const results = root.querySelector("[data-site-search-results]");',
|
|
287
348
|
' if (!toggle || !panel || !form || !input || !results) return;',
|
|
349
|
+
` const M = ${serializeMessagesForScript({
|
|
350
|
+
resultsEmpty: messages['search.resultsEmpty'],
|
|
351
|
+
searching: messages['search.searching'],
|
|
352
|
+
failed: messages['search.failed'],
|
|
353
|
+
failedWithStatus: messages['search.failedWithStatus'],
|
|
354
|
+
enterQuery: messages['search.enterQuery'],
|
|
355
|
+
initialHint: messages['search.initialHint'],
|
|
356
|
+
untitled: messages['search.untitled'],
|
|
357
|
+
})};`,
|
|
358
|
+
` const F = ${localeFilter === undefined ? 'null' : serializeMessagesForScript(localeFilter)};`,
|
|
288
359
|
' let controller = null;',
|
|
289
360
|
' function renderMessage(message) {',
|
|
290
361
|
' results.innerHTML = `<p class="site-search__message">${escapeHtmlForScript(message)}</p>`;',
|
|
291
362
|
' }',
|
|
292
363
|
' function renderHits(hits) {',
|
|
293
364
|
' if (!Array.isArray(hits) || hits.length === 0) {',
|
|
294
|
-
' renderMessage(
|
|
365
|
+
' renderMessage(M.resultsEmpty);',
|
|
295
366
|
' return;',
|
|
296
367
|
' }',
|
|
297
368
|
' results.innerHTML = hits.map((hit) => {',
|
|
298
369
|
' const href = escapeHtmlForScript(hit.canonicalUrl || hit.docId || "#");',
|
|
299
|
-
' const title = escapeHtmlForScript(hit.title || hit.relativePath ||
|
|
370
|
+
' const title = escapeHtmlForScript(hit.title || hit.relativePath || M.untitled);',
|
|
300
371
|
' const summary = typeof hit.summary === "string" ? `<span class="site-search__item-summary">${escapeHtmlForScript(hit.summary)}</span>` : "";',
|
|
301
372
|
' const excerpt = hit.bestMatch && typeof hit.bestMatch.excerpt === "string" ? `<span class="site-search__item-excerpt">${escapeHtmlForScript(hit.bestMatch.excerpt)}</span>` : "";',
|
|
302
373
|
' return `<a class="site-search__item" href="${href}"><strong class="site-search__item-title">${title}</strong>${summary}${excerpt}</a>`;',
|
|
303
374
|
' }).join("");',
|
|
304
375
|
' }',
|
|
376
|
+
' function filterHits(hits) {',
|
|
377
|
+
' if (!F || !Array.isArray(hits)) return hits;',
|
|
378
|
+
' return hits.filter((hit) => {',
|
|
379
|
+
' if (typeof hit.relativePath !== "string") return false;',
|
|
380
|
+
' if (F.include !== "" && !hit.relativePath.startsWith(F.include)) return false;',
|
|
381
|
+
' return !F.exclude.some((prefix) => hit.relativePath.startsWith(prefix));',
|
|
382
|
+
' });',
|
|
383
|
+
' }',
|
|
305
384
|
' async function runSearch(query) {',
|
|
306
385
|
' if (controller) controller.abort();',
|
|
307
386
|
' controller = new AbortController();',
|
|
308
|
-
' renderMessage(
|
|
387
|
+
' renderMessage(M.searching);',
|
|
309
388
|
' try {',
|
|
310
389
|
' const url = new URL("/api/search", window.location.origin);',
|
|
311
390
|
' url.searchParams.set("q", query);',
|
|
312
391
|
' url.searchParams.set("topK", "8");',
|
|
313
392
|
' const response = await fetch(url, { signal: controller.signal });',
|
|
314
393
|
' if (!response.ok) {',
|
|
315
|
-
' renderMessage(
|
|
394
|
+
' renderMessage(M.failedWithStatus.replaceAll("{status}", String(response.status)));',
|
|
316
395
|
' return;',
|
|
317
396
|
' }',
|
|
318
397
|
' const payload = await response.json();',
|
|
319
|
-
' renderHits(payload.hits);',
|
|
398
|
+
' renderHits(filterHits(payload.hits));',
|
|
320
399
|
' } catch (error) {',
|
|
321
400
|
' if (error && typeof error === "object" && "name" in error && error.name === "AbortError") return;',
|
|
322
|
-
' renderMessage(
|
|
401
|
+
' renderMessage(M.failed);',
|
|
323
402
|
' }',
|
|
324
403
|
' }',
|
|
325
404
|
' function setOpen(open) {',
|
|
@@ -327,7 +406,7 @@ function renderSearchScript() {
|
|
|
327
406
|
' panel.hidden = !open;',
|
|
328
407
|
' if (open) {',
|
|
329
408
|
' input.focus();',
|
|
330
|
-
' if (!results.innerHTML) renderMessage(
|
|
409
|
+
' if (!results.innerHTML) renderMessage(M.initialHint);',
|
|
331
410
|
' }',
|
|
332
411
|
' }',
|
|
333
412
|
' toggle.addEventListener("click", () => setOpen(panel.hidden));',
|
|
@@ -335,7 +414,7 @@ function renderSearchScript() {
|
|
|
335
414
|
' event.preventDefault();',
|
|
336
415
|
' const query = input.value.trim();',
|
|
337
416
|
' if (!query) {',
|
|
338
|
-
' renderMessage(
|
|
417
|
+
' renderMessage(M.enterQuery);',
|
|
339
418
|
' return;',
|
|
340
419
|
' }',
|
|
341
420
|
' void runSearch(query);',
|