This is an automated email from the ASF dual-hosted git repository.
morningman pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris-website.git
The following commit(s) were added to refs/heads/master by this push:
new 31051bcc22b [opt](website) Reduce CDN requests and asset transfer
(#4735)
31051bcc22b is described below
commit 31051bcc22babc168663bd3567d6e040baea3ba9
Author: xxiao2018 <[email protected]>
AuthorDate: Mon Nov 30 19:47:29 2026 +0800
[opt](website) Reduce CDN requests and asset transfer (#4735)
## Summary
- Preload route JS on mouse hover, keyboard focus, or touch. This
reduces the number of route files fetched while a page is idle.
- Store each group of translated routes once in the client entry.
- Load search indexes on interaction. Assign document IDs
deterministically and name each index by its contents so it can be
reused across releases.
- Give content-addressed assets a one-year immutable cache policy.
Publish HTML and search manifests with a one-hour policy.
- Serve Inter and JetBrains Mono as WOFF2.
## Verification
| Change | Local result |
| --- | --- |
| Route JS | Distinct CDN JS URLs requested while idle fell from 284 to
9 on the English homepage and from 306 to 21 on the desktop docs page.
Keyboard focus still loaded chunks, and clicking opened the target. |
| Entry bundle | The full-version English client entry fell from 13.53
MB to 8.11 MB, below the CDN's 10 MB edge compression limit. Local gzip
produced 1.07 MB. |
| Search | The docs and empty search pages went from one idle index
request to zero. Changing only the Git revision preserved the URLs and
bytes for 11 English and 6 Japanese fixture indexes. |
| Caching | In Chromium with a simulated resource age over one hour, the
short policy made a conditional request and received HTTP 304. The
immutable policy reused the cached response without a second request. |
| Fonts | Combined font size fell from 1.17 MB to 463 KB. Character
coverage and variable font axes match the original files. |
- Passed 85 Node tests, 8 Python tests, and 36 browser search scenarios
across five languages.
- Compared homepage-to-blog and docs-to-next-page navigation in Chromium
at 100 ms simulated latency and 10 Mbps download. Measured times stayed
within single-digit milliseconds of the baseline. The first search now
fetches the index when needed.
- Production CDN response headers and billing changes can be assessed
after rollout.
---
.github/actions/upload-website-assets/action.yml | 17 +++---
.github/scripts/test_website_oss_publish.py | 28 ++++++++++
.github/scripts/website_oss_publish.py | 47 ++++++++++++++--
config/custom-docusaurus-plugin.js | 6 ++-
scripts/i18n/__tests__/multi-locale.test.cjs | 4 +-
scripts/i18n/__tests__/search-transport.test.cjs | 60 ++++++++++++++++++++-
scripts/i18n/search-document-ids.cjs | 12 +++++
scripts/i18n/search-plugin.cjs | 47 ++++++++++++----
scripts/i18n/status-plugin.cjs | 12 ++++-
scripts/patch-search-tokenize.js | 10 ++++
.../publish/__tests__/link-preload-loader.test.cjs | 15 ++++++
scripts/publish/__tests__/registry-loader.test.cjs | 10 ++--
scripts/publish/link-preload-loader.cjs | 22 ++++++++
scripts/publish/optimize.cjs | 2 +-
src/scss/custom.scss | 4 +-
src/theme/SearchBar/SearchBar.jsx | 47 ++++++----------
src/theme/SearchPage/SearchPage.jsx | 17 ++----
src/utils/fetchSearchIndex.js | 22 ++++++--
src/utils/translation.ts | 26 +++++++--
src/utils/useLocalizedRoute.ts | 7 +--
static/animations/what-is-apache-doris-intro.html | 2 +-
static/fonts/Inter-VariableFont_opsz,wght.woff2 | Bin 0 -> 348932 bytes
static/fonts/JetBrainsMono-VariableFont_wght.woff2 | Bin 0 -> 113704 bytes
23 files changed, 326 insertions(+), 91 deletions(-)
diff --git a/.github/actions/upload-website-assets/action.yml
b/.github/actions/upload-website-assets/action.yml
index 7c9bc810a05..d185dc2a532 100644
--- a/.github/actions/upload-website-assets/action.yml
+++ b/.github/actions/upload-website-assets/action.yml
@@ -8,6 +8,7 @@ runs:
run: |
python3 .github/scripts/website_oss_publish.py prepare \
--destination "$RUNNER_TEMP/website-public" \
+ --immutable-destination "$RUNNER_TEMP/website-immutable" \
--manifest "$RUNNER_TEMP/website-public-manifest.json"
- name: Install pinned ossutil
@@ -42,12 +43,16 @@ runs:
OSS_SESSION_TOKEN: ${{ steps.aliyun.outputs.aliyun-security-token }}
run: |
set -euo pipefail
- ossutil cp "$RUNNER_TEMP/website-public/"
"oss://$WEBSITE_OSS_BUCKET/site/" \
- --recursive --force --mode StsToken --config-file /dev/null \
- --region "$WEBSITE_OSS_REGION" --endpoint "$WEBSITE_OSS_ENDPOINT" \
- --cache-control 'public,max-age=3600' \
- --retry-times 3 --read-timeout 120 --connect-timeout 30 \
- --job 16 --parallel 4 --checkpoint-dir
"$RUNNER_TEMP/website-oss-checkpoints"
+ upload() {
+ ossutil cp "$RUNNER_TEMP/$1/" "oss://$WEBSITE_OSS_BUCKET/site/" \
+ --recursive --force --mode StsToken --config-file /dev/null \
+ --region "$WEBSITE_OSS_REGION" --endpoint "$WEBSITE_OSS_ENDPOINT" \
+ --cache-control "$2" \
+ --retry-times 3 --read-timeout 120 --connect-timeout 30 \
+ --job 16 --parallel 4 --checkpoint-dir
"$RUNNER_TEMP/$1-checkpoints"
+ }
+ upload website-immutable 'public,max-age=31536000,immutable'
+ upload website-public 'public,max-age=3600'
- name: Verify CDN delivery before publishing HTML
shell: bash
diff --git a/.github/scripts/test_website_oss_publish.py
b/.github/scripts/test_website_oss_publish.py
index cfeaaafd6ef..60835b33cd4 100644
--- a/.github/scripts/test_website_oss_publish.py
+++ b/.github/scripts/test_website_oss_publish.py
@@ -54,6 +54,34 @@ class PublishTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'complete optimized'):
publish.prepare(source, root / 'public', '123', '1', 'a' *
40)
+ def test_only_content_addressed_assets_receive_the_long_cache_policy(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ source, _ = self.artifact(root)
+ digest = hashlib.sha256(b'[]').hexdigest()[:16]
+ long_cache = ['assets/js/entry.1234abcd.js',
'assets/css/style.abcdef01.css',
+ 'assets/shared/' + 'a' * 32 + '.woff2',
f'ja/search-index-docs-4.x-{digest}.json']
+ short_cache = ['index.html', 'assets/js/main.js',
'ja/search-index-docs-' + 'a' * 16 + '.json',
+ 'ja/search-manifest-' + 'a' * 16 + '.json']
+ for key in [*long_cache, *short_cache[1:]]:
+ (source / key).parent.mkdir(parents=True, exist_ok=True)
+ (source / key).write_text('[]')
+ public, immutable = root / 'public', root / 'immutable'
+ manifest = publish.prepare(source, public, '123', '1', 'a' * 40)
+ publish.partition_immutable_assets(public, immutable, manifest)
+ for key in long_cache:
+ self.assertTrue((immutable / key).is_file())
+ self.assertFalse((public / key).exists())
+ self.assertTrue((source / key).is_file())
+ for key in short_cache:
+ self.assertTrue((public / key).is_file())
+ self.assertFalse((immutable / key).exists())
+ self.assertIn(short_cache[-1], manifest['checks'])
+ self.assertTrue((immutable / manifest['probe']).is_file())
+
self.assertEqual(manifest['checks'][manifest['probe']]['cacheControl'],
publish.IMMUTABLE_CACHE)
+ self.assertTrue(publish.cache_control_matches({'cache-control':
'public, max-age=31536000, immutable'}, publish.IMMUTABLE_CACHE))
+ self.assertFalse(publish.cache_control_matches({'cache-control':
'public,max-age=3600'}, publish.IMMUTABLE_CACHE))
+
def test_custom_redirect_pages_do_not_need_docusaurus_client_assets(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
diff --git a/.github/scripts/website_oss_publish.py
b/.github/scripts/website_oss_publish.py
index e0725dfb195..cd5348d5fdf 100644
--- a/.github/scripts/website_oss_publish.py
+++ b/.github/scripts/website_oss_publish.py
@@ -14,6 +14,11 @@ from urllib.parse import urlsplit
from urllib.request import Request, urlopen
BASE_URL = 'https://assets-cdn.selectdb.com/site'
+IMMUTABLE_CACHE = 'public,max-age=31536000,immutable'
+IMMUTABLE_ASSET =
re.compile(r'assets/(?:js/(?:[^/]+/)*[^/]+\.[a-f0-9]{8,32}\.js'
+
r'|css/[^/]+\.[a-f0-9]{8,32}\.css|shared/[a-f0-9]{32}\.[^/]+)')
+INDEX_HASH = re.compile(r'search-index(?:-[a-z0-9.-]+)?-([a-f0-9]{16})\.json')
+SEARCH_MANIFEST = re.compile(r'search-manifest-[a-f0-9]{16}\.json')
PRIVATE = {'.git', '.publish', '.htaccess', '.asf.yaml', '.actioninfo',
'.dummy',
'.ci-validation.json', '.ossutilconfig', 'auth.json',
'credentials.json'}
@@ -93,12 +98,15 @@ def prepare(source, destination, run_id, attempt,
source_sha, locales=('en',)):
if not parser.files:
raise ValueError('Website entry is missing its CDN assets')
checks.update(parser.files)
- # Include an index from each language/context in the delivery check.
+ # Check a data file from each index directory and all lookup manifests.
indexes = {}
for file in sorted(destination.rglob('search-index*.json')):
key = file.relative_to(destination).as_posix()
indexes.setdefault(file.parent.relative_to(destination).as_posix(),
key)
checks.update(indexes.values())
+ for file in destination.rglob('search-manifest-*.json'):
+ if SEARCH_MANIFEST.fullmatch(file.name):
+ checks.add(file.relative_to(destination).as_posix())
probe = f'rebuild-probes/publish-{run_id}-{attempt}-{source_sha[:12]}.txt'
(destination / probe).parent.mkdir(parents=True, exist_ok=True)
(destination / probe).write_text(f'{source_sha}\n{run_id}-{attempt}\n')
@@ -114,7 +122,31 @@ def prepare(source, destination, run_id, attempt,
source_sha, locales=('en',)):
raise ValueError('Referenced entry asset is absent from the public
copy: ' + key)
return {'schemaVersion': 1, 'assetBaseUrl': BASE_URL, 'sourceSha':
source_sha, 'locales': list(locales),
'uploadedFileCount': count + 1, 'files': records,
- 'checks': {key: records[key] for key in sorted(checks)}}
+ 'checks': {key: records[key] for key in sorted(checks)}, 'probe':
probe}
+
+
+def partition_immutable_assets(destination, immutable, manifest):
+ """Route only content-addressed assets to the long-cache upload tree."""
+ if immutable.exists():
+ raise ValueError('Immutable staging directory must be new')
+ immutable.mkdir()
+ for key, entry in manifest['files'].items():
+ index = INDEX_HASH.fullmatch(Path(key).name)
+ if (IMMUTABLE_ASSET.fullmatch(key) or
+ (index and entry['sha256'].startswith(index[1])) or key ==
manifest['probe']):
+ target = immutable / key
+ target.parent.mkdir(parents=True, exist_ok=True)
+ (destination / key).rename(target)
+ # Releases can reuse existing paths whose CDN headers still have the old
+ # TTL. Check the new policy on a unique path created for this upload.
+ manifest['checks'][manifest['probe']]['cacheControl'] = IMMUTABLE_CACHE
+
+
+def cache_control_matches(headers, expected):
+ def directives(value):
+ return {item.strip().lower() for item in value.split(',')}
+
+ return directives(headers.get('cache-control', '')) == directives(expected)
def verify(manifest, fetch=urlopen, pause=time.sleep):
@@ -131,12 +163,13 @@ def verify(manifest, fetch=urlopen, pause=time.sleep):
if (response.status == 200 and response.url == BASE_URL +
'/' + key
and len(data) == expected['bytes']
and hashlib.sha256(data).hexdigest() ==
expected['sha256']
- and headers.get('access-control-allow-origin') ==
'https://doris.apache.org'):
+ and headers.get('access-control-allow-origin') ==
'https://doris.apache.org'
+ and ('cacheControl' not in expected or
cache_control_matches(headers, expected['cacheControl']))):
break
except (HTTPError, URLError, TimeoutError, OSError):
pass
if attempt == 5:
- raise ValueError('CDN content or CORS verification failed: ' +
key)
+ raise ValueError('CDN content, CORS or cache policy
verification failed: ' + key)
pause(5)
print('Verified CDN asset: ' + key, flush=True)
@@ -146,6 +179,7 @@ def main():
parser.add_argument('operation', choices=['prepare', 'verify'])
parser.add_argument('--manifest', required=True)
parser.add_argument('--destination')
+ parser.add_argument('--immutable-destination')
args = parser.parse_args()
for name, expected in [('GITHUB_REPOSITORY', 'apache/doris-website'),
('GITHUB_REF', 'refs/heads/master'),
('WEBSITE_ASSET_BASE_URL', BASE_URL),
('WEBSITE_OSS_BUCKET', 'doris-website-assets-prod-bj'),
@@ -154,10 +188,13 @@ def main():
raise ValueError('Invalid publishing configuration: ' + name)
if args.operation == 'prepare':
target = Path(args.destination).resolve()
- if target.parent != Path(os.environ['RUNNER_TEMP']).resolve():
+ immutable = Path(args.immutable_destination).resolve()
+ runner_temp = Path(os.environ['RUNNER_TEMP']).resolve()
+ if target.parent != runner_temp or immutable.parent != runner_temp or
target == immutable:
raise ValueError('Public staging must stay in the runner temporary
directory')
manifest = prepare('build', target, os.environ['GITHUB_RUN_ID'],
os.environ['GITHUB_RUN_ATTEMPT'],
os.environ['DORIS_COMMIT'],
os.environ.get('WEBSITE_PUBLISH_LOCALES', '').split(','))
+ partition_immutable_assets(target, immutable, manifest)
Path(args.manifest).write_text(json.dumps(manifest, indent=2) + '\n')
print(f"Prepared {manifest['uploadedFileCount']} public files;
original ASF artifact preserved")
else:
diff --git a/config/custom-docusaurus-plugin.js
b/config/custom-docusaurus-plugin.js
index 5de04235899..0da167fd7b7 100644
--- a/config/custom-docusaurus-plugin.js
+++ b/config/custom-docusaurus-plugin.js
@@ -40,7 +40,9 @@ module.exports = function (context, options) {
const assetOrigin = getAssetOrigin();
const generated = config.resolve?.alias?.['@generated'] ??
context.generatedFilesDir;
const registry = typeof generated === 'string' ?
path.join(generated, 'registry.js') : null;
- const rules = [];
+ const link =
require.resolve('@docusaurus/core/lib/client/exports/Link.js');
+ const rules = [{enforce: 'pre', test: file => path.resolve(file)
=== link,
+ use: [{loader:
require.resolve('../scripts/publish/link-preload-loader.cjs')}]}];
if (config.mode === 'production' && registry) rules.push({
enforce: 'pre',
test: file => path.resolve(file) === registry,
@@ -54,7 +56,7 @@ module.exports = function (context, options) {
}
return {
- ...(rules.length ? {module: {rules}} : {}),
+ module: {rules},
...(!isServer && config.mode === 'production' ? {
mergeStrategy: {'optimization.minimizer': 'replace'},
optimization: {minimizer: clientMinimizers(config)},
diff --git a/scripts/i18n/__tests__/multi-locale.test.cjs
b/scripts/i18n/__tests__/multi-locale.test.cjs
index 2de44cf1307..a960f3213ea 100644
--- a/scripts/i18n/__tests__/multi-locale.test.cjs
+++ b/scripts/i18n/__tests__/multi-locale.test.cjs
@@ -89,9 +89,9 @@ test('native doc metadata, browser groups and per-locale
manifests agree, across
if (mask === 0) {assert.deepEqual(pages, []);
assert.deepEqual(data.alternates, {}); continue;}
const shared = pages.find(page => page.docId === 'shared' &&
page.version === 'current' && page.pluginId === 'default');
assert.deepEqual(Object.keys(shared.alternates), locales);
- for (const permalink of Object.values(shared.alternates))
assert.deepEqual(data.alternates[permalink], shared.alternates);
+ for (const permalink of Object.values(shared.alternates))
assert.deepEqual(data.alternateGroups[data.alternates[permalink]],
shared.alternates);
for (const page of pages) {
- if (data.alternates[page.permalink])
assert.deepEqual(data.alternates[page.permalink], page.alternates);
+ if (Object.hasOwn(data.alternates, page.permalink))
assert.deepEqual(data.alternateGroups[data.alternates[page.permalink]],
page.alternates);
else for (const [lang, permalink] of
Object.entries(page.alternates)) {
assert.equal(permalink, `${lang === 'en' ? '' : '/' +
lang}${page.englishPermalink}`,
'An omitted compatibility group must be inferable
without changing a slug');
diff --git a/scripts/i18n/__tests__/search-transport.test.cjs
b/scripts/i18n/__tests__/search-transport.test.cjs
index 95af606419f..3ac14205988 100644
--- a/scripts/i18n/__tests__/search-transport.test.cjs
+++ b/scripts/i18n/__tests__/search-transport.test.cjs
@@ -6,7 +6,8 @@ const os = require('node:os');
const ts = require('typescript');
const lunr = require('lunr');
const {adaptSearchWorker} = require('../search-worker-loader.cjs');
-const {targetFingerprint} = require('../search-plugin.cjs');
+const {contentAddressSearchIndexes, targetFingerprint} =
require('../search-plugin.cjs');
+const stableSearchDocuments = require('../search-document-ids.cjs');
const root = path.resolve(__dirname, '../../..');
function compile(source, imports = {}) {
const {outputText} = ts.transpileModule(source, {compilerOptions: {
@@ -54,6 +55,63 @@ test('prefixed CDN failures fall back to the page origin
without the CDN directo
]);
});
+test('build manifests resolve to the same index URL for unchanged index
bytes', t => {
+ const fixture = fs.mkdtempSync(path.join(os.tmpdir(),
'doris-search-addressing-'));
+ t.after(() => fs.rmSync(fixture, {recursive:true, force:true}));
+ const version = path.join(fixture, 'docs', '4.x');
+ fs.mkdirSync(version, {recursive:true});
+ const put = (revision, contents) => {
+ fs.writeFileSync(path.join(version,
`search-index-docs-${revision}.json`), contents);
+ contentAddressSearchIndexes(fixture, revision);
+ return JSON.parse(fs.readFileSync(path.join(version,
`search-manifest-${revision}.json`)))['search-index-docs'];
+ };
+ const first = put('a'.repeat(16), '[]');
+ const second = put('b'.repeat(16), '[]');
+ const third = put('c'.repeat(16), '[{}]');
+ assert.equal(first, second);
+ assert.notEqual(second, third);
+ assert.deepEqual(fs.readdirSync(version).filter(name =>
name.startsWith('search-index')).sort(),
+ [first, third].map(hash => `search-index-docs-${hash}.json`).sort());
+});
+
+test('parallel scan order and IDs from preceding contexts do not change an
index', () => {
+ const doc = (i, u, t, p) => ({i, u, t, ...(p === undefined ? {} : {p})});
+ const alphaFirst = [[doc(1, '/alpha/', 'Alpha'), doc(4, '/beta/', 'Beta')],
+ [doc(2, '/alpha/', 'Second', 1), doc(3, '/alpha/', 'First', 1), doc(5,
'/beta/', 'Usage', 4)],
+ [doc(1, '/alpha/', 'Description', 1)]];
+ const betaFirst = [[doc(31, '/beta/', 'Beta'), doc(37, '/alpha/',
'Alpha')],
+ [doc(32, '/beta/', 'Usage', 31), doc(38, '/alpha/', 'Second', 37),
doc(39, '/alpha/', 'First', 37)],
+ [doc(37, '/alpha/', 'Description', 37)]];
+ const normalized = stableSearchDocuments(alphaFirst);
+ assert.deepEqual(stableSearchDocuments(betaFirst), normalized);
+ assert.deepEqual(normalized[1].map(item => item.t), ['Second', 'First',
'Usage']);
+ assert.deepEqual(normalized[1].map(item => item.p), [1, 1, 2]);
+ assert.equal(normalized[2][0].i, normalized[0][0].i);
+});
+
+test('content-addressed indexes resolve on the CDN and retry the whole lookup
at the page origin', async () => {
+ const requests = [], assetOrigin = 'https://assets-cdn.selectdb.com/site';
+ const revision = 'a'.repeat(16), hash = 'b'.repeat(16);
+ await
fetchSearchIndex(`/zh-CN/docs/4.x/search-index-docs-${revision}.json?manifest=1`,
{...base, assetOrigin,
+ fetchImpl: async url => {
+ requests.push(url);
+ if (url.includes('search-manifest')) {
+ return {ok:true, json:async () => ({'search-index-docs':
hash})};
+ }
+ return url.startsWith(assetOrigin) ? {ok:false, status:404} :
{ok:true, json:async () => []};
+ }});
+ const manifest = `search-manifest-${revision}.json`;
+ const data = `search-index-docs-${hash}.json`;
+ assert.deepEqual(requests, [assetOrigin, base.origin].flatMap(origin =>
+ [manifest, data].map(file => `${origin}/zh-CN/docs/4.x/${file}`)));
+});
+
+test('a search manifest cannot select a different path or origin', async () =>
{
+ await
assert.rejects(fetchSearchIndex(`/search-index-docs-${'a'.repeat(16)}.json?manifest=1`,
{
+ ...base, assetOrigin:'', fetchImpl:async () => ({ok:true, json:async
() => ({'search-index-docs':'../other.json'})}),
+ }), /Invalid search manifest entry/);
+});
+
test('CDN HTTP, JSON and network failures fall back to the same-origin index',
async () => {
for (const failure of ['http','json','network']) {
const requests=[];
diff --git a/scripts/i18n/search-document-ids.cjs
b/scripts/i18n/search-document-ids.cjs
new file mode 100644
index 00000000000..a9c5c3fc30e
--- /dev/null
+++ b/scripts/i18n/search-document-ids.cjs
@@ -0,0 +1,12 @@
+// The native scanner assigns IDs as parallel HTML reads finish. Normalize
+// each index independently and keep the original section order within a page.
+module.exports = function stableSearchDocuments(sections) {
+ const ids = new Map();
+ const idFor = id => {
+ if (!ids.has(id)) ids.set(id, ids.size + 1);
+ return ids.get(id);
+ };
+ return Array.from(sections, documents => [...(documents ?? [])]
+ .sort((a, b) => a.u < b.u ? -1 : a.u > b.u ? 1 : 0)
+ .map(doc => ({...doc, i: idFor(doc.i), ...(doc.p !== undefined && {p:
idFor(doc.p)})})));
+};
diff --git a/scripts/i18n/search-plugin.cjs b/scripts/i18n/search-plugin.cjs
index 226d8e3a1ce..12611b47fa3 100644
--- a/scripts/i18n/search-plugin.cjs
+++ b/scripts/i18n/search-plugin.cjs
@@ -17,6 +17,7 @@ const {loadConfig, managedLocales} = require('./state.cjs');
const {normalizeRussianSearch} =
require('../../src/utils/searchNormalization.js');
const {fallbackOnly} = require('./docs-language-policy.cjs');
const {sourceSha} = require('./content-manifest.cjs');
+const stableSearchDocuments = require('./search-document-ids.cjs');
function contextsFor(root) {
const versions = JSON.parse(fs.readFileSync(path.join(root,
'versions.json'), 'utf8'));
@@ -60,6 +61,7 @@ function targetFingerprint(root, locale, {allVersions =
false} = {}) {
// The shared normalizer also changes indexed tokens independently of this
file.
digester.update(fs.readFileSync(require.resolve('../../src/utils/searchNormalization.js')));
digester.update(fs.readFileSync(require.resolve('./docs-language-policy.cjs')));
+
digester.update(fs.readFileSync(require.resolve('./search-document-ids.cjs')));
function scan(dir) {
if (!fs.existsSync(dir)) return;
for (const entry of
fs.readdirSync(dir,{withFileTypes:true}).sort((a,b) =>
a.name.localeCompare(b.name))) {
@@ -94,6 +96,28 @@ function indexFilename(context) {
if (!/^search-index\{dir\}(?:-[a-f0-9]+)?\.json$/.test(value)) throw new
Error('Unexpected search index filename');
return value;
}
+
+// The browser bundle is emitted before the indexes. A build-specific lookup
+// connects it to the actual index bytes, independently of other site changes.
+function contentAddressSearchIndexes(directory, revision) {
+ const suffix = `-${revision}.json`;
+ const indexes = {};
+ for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {
+ const file = path.join(directory, entry.name);
+ if (entry.isDirectory()) {
+ contentAddressSearchIndexes(file, revision);
+ } else if (entry.isFile() && entry.name.startsWith('search-index') &&
entry.name.endsWith(suffix)) {
+ const stem = entry.name.slice(0, -suffix.length);
+ const hash =
createHash('sha256').update(fs.readFileSync(file)).digest('hex').slice(0, 16);
+ fs.renameSync(file, path.join(directory, `${stem}-${hash}.json`));
+ indexes[stem] = hash;
+ }
+ }
+ if (Object.keys(indexes).length) {
+ fs.writeFileSync(path.join(directory,
`search-manifest-${revision}.json`), JSON.stringify(indexes));
+ }
+}
+
function localizedPages(plugins, locale, contextNames = contexts) {
const selected = new Map();
for (const plugin of plugins.filter(item => item.name ===
'docusaurus-plugin-content-docs')) {
@@ -116,7 +140,7 @@ function buildLocalizedIndexes(documents, config) {
? normalizeRussianSearch(value) :
value.replace(/[()\[\]{},"';`]/g, ' ')) : value, metadata), original);
try {
lunr.tokenizer = tokenizer;
- return buildNativeIndex(documents, config);
+ return buildNativeIndex(stableSearchDocuments(documents), config);
} finally {lunr.tokenizer = original;}
}
@@ -146,21 +170,19 @@ function searchPlugin(context, options) {
const generated = fs.readFileSync(constants,'utf8');
const fingerprint = targetFingerprint(context.siteDir, locale,
{allVersions: !managed});
const revision = sourceSha(context.siteDir);
- let filename;
+ let filename, buildKey;
const updated = generated.replace(/(export const searchIndexUrl =
)("[^"\n]+")/,
(_,prefix,value) => {
const url = JSON.parse(value);
- // A source-derived filename prevents a CDN from reusing an older
- // index at the same path, even when it ignores query parameters.
- const contentKey =
createHash('sha256').update(url).update(fingerprint).update(revision).digest('hex').slice(0,16);
- filename = config.hashed ? `search-index{dir}-${contentKey}.json`
: url.split('?')[0];
- return prefix + JSON.stringify(config.hashed ? filename
+ buildKey =
createHash('sha256').update(url).update(fingerprint).update(revision).digest('hex').slice(0,16);
+ filename = config.hashed ? `search-index{dir}-${buildKey}.json` :
url.split('?')[0];
+ return prefix + JSON.stringify(config.hashed ?
`${filename}?manifest=1`
: `${url}${url.includes('?') ? '&' :
'?'}${locale}=${fingerprint}`);
});
if (updated === generated) throw new Error('Could not fingerprint the
localized search index');
fs.writeFileSync(constants,updated);
if (indexFilename(context) !== filename) throw new Error('Search index
filename differs from its browser URL');
- return {...plugin, postBuild: managed
+ const buildIndexes = managed
? buildData =>
buildLocalizedIndex(buildData,config,filename,locale,contextNames)
: buildData => {
const hidden = new Set((buildData.plugins ??
[]).flatMap(plugin=>plugin.content?.contentIdentity?.entries ?? [])
@@ -168,9 +190,13 @@ function searchPlugin(context, options) {
.map(page=>normalize(page.route)));
// Native source-language indexing keeps its version/context
layout,
// but cannot advertise English fallbacks as Chinese translations.
- return postBuildFactory(config,filename)({...buildData,
+ return postBuildFactory({...config,
normalizeDocuments:stableSearchDocuments}, filename)({...buildData,
routesPaths:buildData.routesPaths.filter(route=>!hidden.has(normalize(route)))});
- }};
+ };
+ return {...plugin, async postBuild(buildData) {
+ await buildIndexes(buildData);
+ if (config.hashed) contentAddressSearchIndexes(buildData.outDir,
buildKey);
+ }};
}
module.exports = searchPlugin;
module.exports.validateOptions = nativeModule.validateOptions;
@@ -184,3 +210,4 @@ module.exports.buildLocalizedIndex = buildLocalizedIndex;
module.exports.buildLocalizedIndexes = buildLocalizedIndexes;
module.exports.targetFingerprint = targetFingerprint;
+module.exports.contentAddressSearchIndexes = contentAddressSearchIndexes;
diff --git a/scripts/i18n/status-plugin.cjs b/scripts/i18n/status-plugin.cjs
index b4a394c411f..f3fc330353a 100644
--- a/scripts/i18n/status-plugin.cjs
+++ b/scripts/i18n/status-plugin.cjs
@@ -37,10 +37,18 @@ module.exports = function translationStatusPlugin(context,
{browserData = true}
// Keep translated groups and source routes that prefix replacement
// cannot infer, including groups whose targets all fall back.
const alternates = {};
+ const alternateGroups = [];
+ const groupIndexes = new Map();
for (const page of allPages) {
const sourceRoutesDiffer =
page.alternates['zh-CN']?.replace('/zh-CN/', '/') !== page.englishPermalink;
if (sourceRoutesDiffer ||
Object.keys(page.alternates).some(lang => !['en', 'zh-CN'].includes(lang))) {
- for (const permalink of [page.permalink,
...Object.values(page.alternates)]) alternates[permalink] = page.alternates;
+ // mergeAlternates shares one group object per native
document.
+ if (!groupIndexes.has(page.alternates)) {
+ groupIndexes.set(page.alternates,
alternateGroups.length);
+ alternateGroups.push(page.alternates);
+ }
+ const group = groupIndexes.get(page.alternates);
+ for (const permalink of [page.permalink,
...Object.values(page.alternates)]) alternates[permalink] = group;
}
}
// The manifest describes one locale, so it carries only its pages.
@@ -51,7 +59,7 @@ module.exports = function translationStatusPlugin(context,
{browserData = true}
// localized documentation, search, or other plugin-owned UI.
const pageRoutes = [...new
Set(Object.values(allContent['docusaurus-plugin-content-pages'] ?? {})
.flatMap(content => content ?? []).map(page =>
page.permalink.replace(/\/$/, '') + '/'))];
- if (browserData) actions.setGlobalData({alternates, prefixes,
locales, pageRoutes});
+ if (browserData) actions.setGlobalData({alternates,
alternateGroups, prefixes, locales, pageRoutes});
const inputs = Object.values(allContent).flatMap(instances =>
Object.values(instances))
.map(content => content?.contentIdentity).filter(Boolean);
if (inputs.length) {
diff --git a/scripts/patch-search-tokenize.js b/scripts/patch-search-tokenize.js
index 09ed138b3f4..3a76243397d 100644
--- a/scripts/patch-search-tokenize.js
+++ b/scripts/patch-search-tokenize.js
@@ -142,6 +142,15 @@ function patchPostBuildFactoryContent(content) {
return content.replace(needle1, replacement1).replace(needle2, replacement2);
}
+function patchStableSearchDocuments(content) {
+ if (content.includes('PATCH(stable-search-document-ids)')) return content;
+ const target = 'const searchIndex = (0, buildIndex_1.buildIndex)(allDocs,
config);';
+ if (content.split(target).length !== 2) throw new Error('Unexpected search
post-build factory');
+ return content.replace(target,
+ '// PATCH(stable-search-document-ids): normalize each context before
indexing.\n' +
+ ' const searchIndex = (0,
buildIndex_1.buildIndex)(config.normalizeDocuments?.(allDocs) ?? allDocs,
config);');
+}
+
// The search worker fetches `${versionUrl}search-index-*.json`. `versionUrl`
// defaults to `siteConfig.baseUrl` (= "/"), which is locale-agnostic, so on
// /zh-CN/* pages the worker still hits the default-locale index files at the
@@ -245,6 +254,7 @@ function main() {
patchPostBuildFactoryContent,
"server-postBuildFactory-locale"
);
+ patchOneFile(targetPostBuildFactoryFile, patchStableSearchDocuments,
'server-stable-search-document-ids');
patchOneFile(
targetSearchBarFile,
patchSearchBarVersionUrlContent,
diff --git a/scripts/publish/__tests__/link-preload-loader.test.cjs
b/scripts/publish/__tests__/link-preload-loader.test.cjs
new file mode 100644
index 00000000000..44f294188a3
--- /dev/null
+++ b/scripts/publish/__tests__/link-preload-loader.test.cjs
@@ -0,0 +1,15 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const linkPreloadLoader = require('../link-preload-loader.cjs');
+
+test('Docusaurus Link preloads on interaction only and keeps native link
handling', () => {
+ const source =
fs.readFileSync(require.resolve('@docusaurus/core/lib/client/exports/Link.js'),
'utf8');
+ const output = linkPreloadLoader(source);
+ assert.doesNotMatch(output, /IntersectionObserver|docusaurus\.prefetch/);
+ assert.match(output, /window\.docusaurus\.preload\(targetLink\)/);
+ assert.match(output, /onMouseEnter=\{onInteractionEnter\}
onTouchStart=\{onInteractionEnter\}/);
+ assert.match(output, /props\.onFocus\?\.\(event\);
onInteractionEnter\(\)/);
+ assert.match(output, /innerRef=\{innerRef\} to=\{targetLink\}/);
+ assert.throws(() => linkPreloadLoader(source.replace('const IOSupported',
'const changed')), /Unexpected Docusaurus Link/);
+});
diff --git a/scripts/publish/__tests__/registry-loader.test.cjs
b/scripts/publish/__tests__/registry-loader.test.cjs
index d64bd3e4646..46087964599 100644
--- a/scripts/publish/__tests__/registry-loader.test.cjs
+++ b/scripts/publish/__tests__/registry-loader.test.cjs
@@ -54,10 +54,12 @@ for (const isServer of [true, false]) test(`production
${isServer ? 'SSR' : 'cli
optimization:{minimize:!isServer,minimizer:[new
rspack.SwcJsMinimizerRspackPlugin()]}};
const plugin =
createPlugin({siteDir:root,generatedFilesDir:generated,siteConfig:{baseUrl:'/'}});
const changes = plugin.configureWebpack(base,isServer);
- assert.equal(changes.module.rules.filter(rule =>
rule.test(path.join(generated,'registry.js'))).length,1);
- assert(changes.module.rules[0].test(path.join(generated,'registry.js')));
- assert(!changes.module.rules[0].test(path.join(root,'registry.js')));
-
assert.equal(plugin.configureWebpack({...base,mode:'development'},isServer).module,undefined);
+ const registryFile = path.join(generated, 'registry.js');
+ const matched = changes.module.rules.filter(rule =>
rule.test(registryFile));
+ assert.equal(matched.length, 1);
+ assert.equal(matched[0].use[0].loader,
require.resolve('../registry-loader.cjs'));
+ assert(!matched[0].test(path.join(root, 'registry.js')));
+ assert(!plugin.configureWebpack({...base, mode:'development'},
isServer).module.rules.some(rule => rule.test(registryFile)));
const compiler =
rspack({...base,module:{rules:[...base.module.rules,...changes.module.rules]},
optimization:changes.optimization??base.optimization});
const stats = await new
Promise((resolve,reject)=>compiler.run((error,result)=>error?reject(error):resolve(result)));
diff --git a/scripts/publish/link-preload-loader.cjs
b/scripts/publish/link-preload-loader.cjs
new file mode 100644
index 00000000000..559b62a4a2a
--- /dev/null
+++ b/scripts/publish/link-preload-loader.cjs
@@ -0,0 +1,22 @@
+// Docusaurus 3.6 prefetches every internal link entering the viewport. Keep
+// the native router and preload on interaction, including keyboard focus.
+module.exports = function linkPreloadLoader(source) {
+ const viewport = ' const IOSupported =
ExecutionEnvironment.canUseIntersectionObserver;';
+ const interaction = ' const onInteractionEnter = () => {';
+ const effect = ' useEffect(() => {';
+ const anchor = ' // It is simple local anchor link targeting current
page?';
+ const props = 'onTouchStart={onInteractionEnter} innerRef={handleRef}';
+ const start = source.indexOf(viewport);
+ const keep = source.indexOf(interaction, start);
+ const remove = source.indexOf(effect, keep);
+ const end = source.indexOf(anchor, remove);
+ if (start < 0 || keep < 0 || remove < 0 || end < 0 ||
source.split(props).length !== 2
+ || !source.slice(start,
keep).includes('window.docusaurus.prefetch(targetLink)')
+ || !source.slice(remove,
end).includes('window.docusaurus.prefetch(targetLink)')) {
+ throw new Error('Unexpected Docusaurus Link implementation; revalidate
intent-only loading');
+ }
+ return (source.slice(0, start) + source.slice(keep, remove) +
source.slice(end))
+ .replace('useEffect, useImperativeHandle', 'useImperativeHandle')
+ .replace("import ExecutionEnvironment from
'./ExecutionEnvironment';\n", '')
+ .replace(props, 'onTouchStart={onInteractionEnter} onFocus={event => {
props.onFocus?.(event); onInteractionEnter(); }} innerRef={innerRef}');
+};
diff --git a/scripts/publish/optimize.cjs b/scripts/publish/optimize.cjs
index 43f24ae86f5..076dc570306 100644
--- a/scripts/publish/optimize.cjs
+++ b/scripts/publish/optimize.cjs
@@ -54,7 +54,7 @@ function optimize({site, locales, reportFile}) {
// Cached clients may still request the old query-versioned index URL.
// Preserve it with a temporary alias, without duplicating the large JSON.
for (const item of before) {
- if
(!/(?:^|\/)search-index(?:-[a-z0-9-]+)?-[a-f0-9]{16}\.json$/.test(item.relative))
continue;
+ if
(!/(?:^|\/)search-index(?:-[a-z0-9.-]+)?-[a-f0-9]{16}\.json$/.test(item.relative))
continue;
const legacy = item.relative.replace(/-[a-f0-9]{16}\.json$/, '.json');
add(url(legacy), url(item.relative), true, 302);
}
diff --git a/src/scss/custom.scss b/src/scss/custom.scss
index 75bb7cb3b07..2fdb4b7de3f 100644
--- a/src/scss/custom.scss
+++ b/src/scss/custom.scss
@@ -22,14 +22,14 @@
@font-face {
font-family: 'Inter';
- src: url('/fonts/Inter-VariableFont_opsz,wght.ttf')
format('truetype-variations');
+ src: url('/fonts/Inter-VariableFont_opsz,wght.woff2') format('woff2');
font-weight: 100 900;
font-display: swap;
}
@font-face {
font-family: 'JetBrains Mono';
- src: url('/fonts/JetBrainsMono-VariableFont_wght.ttf')
format('truetype-variations');
+ src: url('/fonts/JetBrainsMono-VariableFont_wght.woff2') format('woff2');
font-weight: 100 800;
font-display: swap;
}
diff --git a/src/theme/SearchBar/SearchBar.jsx
b/src/theme/SearchBar/SearchBar.jsx
index 441b1a48896..a2f66cf15f5 100644
--- a/src/theme/SearchBar/SearchBar.jsx
+++ b/src/theme/SearchBar/SearchBar.jsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useEffect, useRef, useState } from 'react';
+import React, { useCallback, useEffect, useMemo, useRef, useState } from
'react';
import clsx from 'clsx';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import useIsBrowser from '@docusaurus/useIsBrowser';
@@ -70,8 +70,6 @@ export default function SearchBar({ handleSearchBarToggle }) {
const searchBarRef = useRef(null);
const sourceSearchRef = useRef(null);
const indexStateMap = useRef(new Map());
- // Should the input be focused after the index is loaded?
- const focusAfterIndexLoaded = useRef(false);
const [loading, setLoading] = useState(false);
const [loadError, setLoadError] = useState(false);
const [inputChanged, setInputChanged] = useState(false);
@@ -81,12 +79,10 @@ export default function SearchBar({ handleSearchBarToggle
}) {
// finished after a newer call started) can abort before wrapping the
// input with a second autocomplete instance — see #3655 race.
const loadToken = useRef(0);
- const [searchContext, setSearchContext] = useState('');
- useEffect(() => {
+ const searchContext = useMemo(() => {
if (!Array.isArray(searchContextByPaths)) {
- return;
+ return '';
}
- let nextSearchContext = '';
// searchContextByPaths is expressed relative to the docs root
// (e.g. ['docs']), so we must strip both the locale prefix and the
// /docs/<version>/ version segment before matching. Subtracting
@@ -101,18 +97,13 @@ export default function SearchBar({ handleSearchBarToggle
}) {
parts.splice(1, 1);
}
const uri = parts.join('/');
- let matchedPath;
for (const _path of searchContextByPaths) {
const path = typeof _path === 'string' ? _path : _path.path;
if (uri === path || uri.startsWith(`${path}/`)) {
- matchedPath = path;
- break;
+ return path;
}
}
- if (matchedPath) {
- nextSearchContext = matchedPath;
- }
- setSearchContext(nextSearchContext);
+ return '';
}, [location.pathname, locales, currentLocale]);
const hidden = !!hideSearchBarWithNoSearchContext &&
Array.isArray(searchContextByPaths) && searchContext === '';
const indexKey = `${versionUrl}:${searchContext}`;
@@ -222,6 +213,8 @@ export default function SearchBar({ handleSearchBarToggle
}) {
});
return a;
};
+ // Autocomplete reparents the input and can blur it while mounting.
+ const restoreFocus = document.activeElement ===
searchBarRef.current;
const pendingQuery = searchBarRef.current.value;
search.current = autoComplete(
searchBarRef.current,
@@ -305,12 +298,12 @@ export default function SearchBar({ handleSearchBarToggle
}) {
}
indexStateMap.current.set(indexKey, 'done');
setLoading(false);
- if (focusAfterIndexLoaded.current) {
+ if (restoreFocus) {
const input = searchBarRef.current;
+ input.focus();
if (input.value) {
search.current?.autocomplete.open();
}
- input.focus();
}
},
[hidden, indexKey, searchContext, versionUrl, baseUrl, history,
sourceOnlyVersion],
@@ -343,7 +336,6 @@ export default function SearchBar({ handleSearchBarToggle
}) {
}, [isBrowser, location.search, location.pathname, currentLocale]);
const [focused, setFocused] = useState(false);
const onInputFocus = useCallback(() => {
- focusAfterIndexLoaded.current = true;
loadIndex();
setFocused(true);
handleSearchBarToggle?.(true);
@@ -358,28 +350,17 @@ export default function SearchBar({ handleSearchBarToggle
}) {
},
[handleSearchBarToggle],
);
- const onInputMouseEnter = useCallback(() => {
- loadIndex();
- }, [loadIndex]);
const onInputChange = useCallback(event => {
setInputValue(event.target.value);
if (event.target.value) {
setInputChanged(true);
+ loadIndex();
}
- }, []);
+ }, [loadIndex]);
// Implement hint icons for the search shortcuts on mac and the rest
operating systems.
const isMac = isBrowser ? /mac/i.test(navigator.userAgentData?.platform ??
navigator.platform) : false;
- useEffect(() => {
- // On mount the page's search context is not resolved yet, and an empty
- // one can load the wrong index or every index. Leave outside-context
- // search to focus or hover, including the source-language search page.
- if (!searchContext) {
- return;
- }
- loadIndex(true);
- }, [loadIndex, searchContext]);
useEffect(() => {
if (!searchBarShortcut) {
return;
@@ -458,7 +439,6 @@ export default function SearchBar({ handleSearchBarToggle
}) {
placeholder={searchLabel}
aria-label={searchLabel}
className={clsx('navbar__search-input',
styles.navbarSearchInput)}
- onMouseEnter={onInputMouseEnter}
onFocus={onInputFocus}
onBlur={onInputBlur}
onChange={onInputChange}
@@ -468,7 +448,10 @@ export default function SearchBar({ handleSearchBarToggle
}) {
<LoadingRing className={styles.searchBarLoadingRing} />
{loadError && <div className={styles.searchLoadError}
role="status">
<span>{searchMessages(currentLocale).error}</span>
- <button type="button" onClick={() => loadIndex(true)}>
+ <button type="button" onClick={() => {
+ loadIndex(true);
+ searchBarRef.current?.focus();
+ }}>
{searchMessages(currentLocale).retry}
</button>
</div>}
diff --git a/src/theme/SearchPage/SearchPage.jsx
b/src/theme/SearchPage/SearchPage.jsx
index ddd2e487965..310fd4bd8e1 100644
--- a/src/theme/SearchPage/SearchPage.jsx
+++ b/src/theme/SearchPage/SearchPage.jsx
@@ -9,7 +9,7 @@ import { usePluralForm } from "@docusaurus/theme-common";
import { useAllDocsData } from "@docusaurus/plugin-content-docs/client";
import clsx from "clsx";
import useSearchQuery from "../../hooks/use-search-query";
-import { fetchIndexesByWorker, searchByWorker } from
'@yang1666204/docusaurus-search-local/dist/client/client/theme/searchByWorker'
+import { searchByWorker } from
'@yang1666204/docusaurus-search-local/dist/client/client/theme/searchByWorker'
import { SearchDocumentType, } from "../../../shared/interfaces";
import { highlight } from "../../utils/highlight";
import { highlightStemmed } from "../../utils/highlightStemmed";
@@ -21,7 +21,7 @@ import { searchResultLimits } from
"../../utils/proxiedGeneratedConstants";
import styles from "./SearchPage.module.css";
import { normalizeContextByPath } from "../../utils/normalizeContextByPath";
import {searchWithLocaleFallback} from "../../utils/searchInput";
-import {fetchContextIndexes, searchAcrossContexts} from
"../../utils/searchContexts";
+import {searchAcrossContexts} from "../../utils/searchContexts";
import {isTranslatedLocale} from "../../utils/localization";
import {searchIndexBaseUrl} from "../../utils/searchVersion";
import {searchMessages} from "../../utils/searchMessages";
@@ -88,14 +88,9 @@ function SearchPageContent() {
setSearchResults(undefined);
async function doFetchIndexes() {
try {
- if(sourceOnlyVersion)
{if(active)setSearchWorkerReady(true);return;}
- if (!Array.isArray(searchContextByPaths) ||
- searchContext ||
- useAllContextsWithNoSearchContext) {
- await fetchContextIndexes(fetchIndexesByWorker,
versionUrl, searchContext);
- }
- if (searchQuery) {
- const results = await
searchWithLocaleFallback(searchContextsByWorker, versionUrl, searchContext,
searchQuery, searchResultLimits);
+ const query = searchQuery?.trim();
+ if (!sourceOnlyVersion && query) {
+ const results = await
searchWithLocaleFallback(searchContextsByWorker, versionUrl, searchContext,
query, searchResultLimits);
if (active) setSearchResults(results);
}
if (active) setSearchWorkerReady(true);
@@ -103,8 +98,6 @@ function SearchPageContent() {
if (active) setLoadError(true);
}
}
- // The context comes from the query string, which is only read in the
- // browser; before that an empty one would load every context index.
if (isBrowser) {
doFetchIndexes();
}
diff --git a/src/utils/fetchSearchIndex.js b/src/utils/fetchSearchIndex.js
index c431c9d53da..ada3c7f7479 100644
--- a/src/utils/fetchSearchIndex.js
+++ b/src/utils/fetchSearchIndex.js
@@ -1,3 +1,20 @@
+async function fetchJson(url, fetchImpl, signal) {
+ const response = await fetchImpl(url.href, {signal});
+ if (!response.ok) throw new Error(`Search index HTTP ${response.status}`);
+ return response.json();
+}
+
+async function resolveIndex(candidate, fetchImpl, signal) {
+ if (candidate.searchParams.get('manifest') !== '1') return candidate;
+ const match =
candidate.pathname.match(/\/(search-index(?:-[a-z0-9.-]+)?)-([a-f0-9]{16})\.json$/);
+ if (!match) throw new Error('Invalid search index build key');
+ const [, stem, buildKey] = match;
+ const manifest = await fetchJson(new
URL(`search-manifest-${buildKey}.json`, candidate), fetchImpl, signal);
+ const hash = manifest?.[stem];
+ if (typeof hash !== 'string' || !/^[a-f0-9]{16}$/.test(hash)) throw new
Error('Invalid search manifest entry');
+ return new URL(`${stem}-${hash}.json`, candidate);
+}
+
// Only production pages use the configured asset CDN. Local previews and
// alternate hosts read their own index, just like their own same-origin
worker.
export async function fetchSearchIndex(url, {
@@ -19,9 +36,8 @@ export async function fetchSearchIndex(url, {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
- const response = await fetchImpl(candidate.href, {signal:
controller.signal});
- if (!response.ok) throw new Error(`Search index HTTP
${response.status}`);
- const data = await response.json();
+ const index = await resolveIndex(candidate, fetchImpl,
controller.signal);
+ const data = await fetchJson(index, fetchImpl, controller.signal);
if (!Array.isArray(data)) throw new Error('Invalid search index');
return data;
} catch (error) {
diff --git a/src/utils/translation.ts b/src/utils/translation.ts
index dd7d7f5d7e4..cbfca50c38a 100644
--- a/src/utils/translation.ts
+++ b/src/utils/translation.ts
@@ -23,10 +23,30 @@ export function docTranslation(metadata: unknown):
TranslationState | undefined
return (metadata as {translation?: TranslationState}).translation;
}
-type StatusData = {alternates: Record<string, Record<string, string>>;
prefixes: string[]; locales?: string[]; pageRoutes?: string[]};
+type StatusData = {
+ alternates: Record<string, number>;
+ alternateGroups: Record<string, string>[];
+ prefixes: string[];
+ locales?: string[];
+ pageRoutes?: string[];
+};
+
+function useTranslationStatusData() {
+ return useGlobalData()['doris-translation-status']?.default as StatusData
| undefined;
+}
+
+function alternatesForRoute(data: StatusData | undefined, route: string) {
+ const index = data?.alternates[route];
+ return index === undefined ? undefined : data?.alternateGroups[index];
+}
+
+export function useRouteAlternates(route: string) {
+ return alternatesForRoute(useTranslationStatusData(), route);
+}
+
export function useTranslationRoutes() {
const content = useContentRouteData();
- const data = useGlobalData()['doris-translation-status']?.default as
StatusData | undefined;
+ const data = useTranslationStatusData();
const {pathname} = useLocation();
const route = pathname.replace(/\/$/, '') + '/';
const pagePath = normalizePathname(pathname, i18n.locales).replace(/\/+$/,
'');
@@ -48,7 +68,7 @@ export function useTranslationRoutes() {
pageFallback,
};
}
- return {group: data?.alternates[route],
+ return {group: alternatesForRoute(data, route),
// Locales with translation state. A page outside a translated route
// group must not offer them as an alternate, because the target page
// would only repeat the default locale's content.
diff --git a/src/utils/useLocalizedRoute.ts b/src/utils/useLocalizedRoute.ts
index f30c5fb4415..efe2081efde 100644
--- a/src/utils/useLocalizedRoute.ts
+++ b/src/utils/useLocalizedRoute.ts
@@ -1,8 +1,8 @@
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import {useLocation} from '@docusaurus/router';
-import useGlobalData from '@docusaurus/useGlobalData';
import {useContentRouteData, useNavigationRoutes} from './contentRoute';
import {resolveLocalizedRoute, rootBaseUrl, localePath, routeForLocale, type
RouteRequest, type RouteGroup} from './localizedRoute';
+import {useRouteAlternates} from './translation';
export function useLocalizedRoute() {
const {siteConfig, i18n} = useDocusaurusContext();
@@ -15,10 +15,7 @@ export function useLocalizedRoute() {
// Retain the existing exact-route compatibility reader there; never copy
// the build registry into another client global. Missing managed targets
// have native English fallback routes in the same plugin/version.
- const legacy = useGlobalData()['doris-translation-status']?.default as {
- alternates?: Record<string, Record<string, string>>;
- } | undefined;
- const alternate = legacy?.alternates?.[pathname.replace(/\/+$/, '') + '/'];
+ const alternate = useRouteAlternates(pathname.replace(/\/+$/, '') + '/');
const source = alternate?.[i18n.defaultLocale];
const sourceInfo = source && localePath(source, options);
const compatibility: RouteGroup[] = !page && alternate && sourceInfo ?
[{contentId: 'native-doc:current',
diff --git a/static/animations/what-is-apache-doris-intro.html
b/static/animations/what-is-apache-doris-intro.html
index 34e2bae13bd..95a041dd57e 100644
--- a/static/animations/what-is-apache-doris-intro.html
+++ b/static/animations/what-is-apache-doris-intro.html
@@ -8,7 +8,7 @@
<style>
@font-face {
font-family: 'Inter';
- src: url('/fonts/Inter-VariableFont_opsz,wght.ttf')
format('truetype-variations');
+ src: url('/fonts/Inter-VariableFont_opsz,wght.woff2') format('woff2');
font-weight: 100 900;
font-display: swap;
}
diff --git a/static/fonts/Inter-VariableFont_opsz,wght.woff2
b/static/fonts/Inter-VariableFont_opsz,wght.woff2
new file mode 100644
index 00000000000..716dfcbbc3f
Binary files /dev/null and b/static/fonts/Inter-VariableFont_opsz,wght.woff2
differ
diff --git a/static/fonts/JetBrainsMono-VariableFont_wght.woff2
b/static/fonts/JetBrainsMono-VariableFont_wght.woff2
new file mode 100644
index 00000000000..ddfb5513c2f
Binary files /dev/null and b/static/fonts/JetBrainsMono-VariableFont_wght.woff2
differ
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]