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 305feb4bd21 [opt](website) Reduce search index downloads and compute
body highlights on demand (#4737)
305feb4bd21 is described below
commit 305feb4bd219af92f930c2a57aa18d355611da8e
Author: xxiao2018 <[email protected]>
AuthorDate: Tue Dec 1 14:16:24 2026 +0800
[opt](website) Reduce search index downloads and compute body highlights on
demand (#4737)
## Changes
- Default unscoped Japanese, Korean, and Russian searches to the latest
stable docs. Keep explicit Everywhere and document-version scopes,
including bookmarked `ctx=` links.
- Omit body-text positions from the Lunr index. The search worker
reconstructs positions for returned body hits after ranking. Titles and
headings keep their stored positions.
## Validation
- Passed 88 search, localization, and publication tests and 42 Chromium
cases using production builds of the five-language fixture.
- Confirmed the default search fetches only the stable index in
Japanese, Korean, and Russian. Selecting Everywhere fetches the other
four indexes and preserves the query.
- Replayed 65 queries against published 4.x indexes. The result order
and scores matched for every query. All 1,380 body hits with previously
stored positions retained at least one of those highlights. For 25
Chinese hits, the worker also highlighted matching text inside other
words.
Estimated compressed index downloads for a cold default search, based on
the published index payloads compressed with the same gzip settings on
both sides.
| Locale | Before | After | Reduction |
| --- | ---: | ---: | ---: |
| English | 9.07 MB | 6.19 MB | 32% |
| Chinese | 9.72 MB | 6.83 MB | 30% |
| Japanese | 26.37 MB | 7.26 MB | 72% |
| Korean | 22.75 MB | 7.58 MB | 67% |
| Russian | 21.23 MB | 7.12 MB | 66% |
---
scripts/i18n/__tests__/search-contexts.test.cjs | 8 ++--
scripts/i18n/__tests__/search-scopes.test.cjs | 12 ++++-
scripts/i18n/__tests__/search-transport.test.cjs | 21 +++++++++
scripts/i18n/search-plugin.cjs | 9 ++--
scripts/i18n/search-worker-loader.cjs | 16 +++++--
scripts/i18n/verify-search-transport.cjs | 42 +++++++++++++++++
scripts/patch-search-tokenize.js | 24 ++++++++++
src/hooks/use-search-query.ts | 5 +-
src/theme/SearchBar/SearchBar.jsx | 16 +++----
src/theme/SearchPage/SearchPage.jsx | 6 +--
src/utils/getStemmedPositions.ts | 4 +-
src/utils/highlightStemmed.ts | 3 ++
src/utils/searchBodyPositions.js | 58 ++++++++++++++++++++++++
src/utils/searchContexts.js | 9 ++--
src/utils/searchNormalization.js | 7 ++-
src/utils/searchScopes.js | 17 +++++--
16 files changed, 216 insertions(+), 41 deletions(-)
diff --git a/scripts/i18n/__tests__/search-contexts.test.cjs
b/scripts/i18n/__tests__/search-contexts.test.cjs
index a8716e86550..8d527ce0880 100644
--- a/scripts/i18n/__tests__/search-contexts.test.cjs
+++ b/scripts/i18n/__tests__/search-contexts.test.cjs
@@ -52,19 +52,19 @@ function ranked(results) {
const shape = results => results.map(({document, type, score, isInterOfTree,
isLastOfTree}) =>
({id: document.i, type, score, tree: isInterOfTree ? 'inter' :
isLastOfTree ? 'last' : ''}));
-test('a page outside every context searches each context index, not a union',
async () => {
+test('an explicit everywhere search queries each context index', async () => {
const {indexContexts, fetchContextIndexes, searchAcrossContexts} =
searchContexts(japanese);
- assert.deepEqual(indexContexts(''), ['docs/dev', 'docs/4.x', 'community']);
+ assert.deepEqual(indexContexts('all'), ['docs/dev', 'docs/4.x',
'community']);
assert.deepEqual(indexContexts('docs/4.x'), ['docs/4.x']);
const fetched = [];
- await fetchContextIndexes(async (...args) => {fetched.push(args);},
'/ja/', '');
+ await fetchContextIndexes(async (...args) => {fetched.push(args);},
'/ja/', 'all');
assert.deepEqual(fetched, [['/ja/', 'docs/dev'], ['/ja/', 'docs/4.x'],
['/ja/', 'community']]);
const calls = [];
const search = searchAcrossContexts(async (...args) => {calls.push(args);
return [];});
await search('/ja/', 'community', 'sql', 10);
assert.deepEqual(calls, [['/ja/', 'community', 'sql', 10]]);
calls.length = 0;
- await search('/ja/', '', 'sql', 10);
+ await search('/ja/', 'all', 'sql', 10);
assert.deepEqual(calls.map(call => call[1]), ['docs/dev', 'docs/4.x',
'community']);
});
diff --git a/scripts/i18n/__tests__/search-scopes.test.cjs
b/scripts/i18n/__tests__/search-scopes.test.cjs
index 077711755a0..a249f928b9d 100644
--- a/scripts/i18n/__tests__/search-scopes.test.cjs
+++ b/scripts/i18n/__tests__/search-scopes.test.cjs
@@ -1,7 +1,7 @@
const
test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),ts=require('typescript');
const
{outputText}=ts.transpileModule(fs.readFileSync(path.resolve(__dirname,'../../../src/utils/searchScopes.js'),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2020}});
const moduleValue={exports:{}};new
Function('exports',outputText)(moduleValue.exports);
-const
{resolveSearchScope,convertSearchParams,docSearchSourceVersion}=moduleValue.exports;
+const
{resolveSearchScope,readSearchScope,convertSearchParams,docSearchSourceVersion}=moduleValue.exports;
const {verifySourceSearchHref}=require('../verify-search.cjs');
const
versions=['dev','4.x','3.x','2.1'].map(name=>({path:'/docs/'+name,isLast:name==='4.x'}));
const
source={versions,contexts:['docs','community','course','releases'],managed:false};
@@ -62,6 +62,16 @@ test('an implicit native default stays on the stable version
when switching lang
assert.equal(target.get('ctx'),'docs/4.x');
assert.equal(target.get('q'),'Doris');assert(!target.has('version'));
});
+test('managed search defaults to stable and preserves explicit and bookmarked
everywhere scopes',()=>{
+ assert.equal(readSearchScope(new
URLSearchParams('q=Doris'),managed).context,'docs/4.x');
+ for (const search of ['q=Doris&ctx=all','q=Doris&ctx=']) {
+ const params=new URLSearchParams(search);
+ assert.equal(readSearchScope(params,managed).context,'all');
+
assert.equal(convertSearchParams(params,managed,managed).get('ctx'),'all');
+
assert.equal(convertSearchParams(params,source,managed).get('ctx'),'docs');
+ }
+
assert.equal(resolveSearchScope({},{...managed,contexts:['docs/dev','community']}).context,'docs/dev');
+});
test('latest version and unsupported status come from native metadata and
registered contexts',()=>{
const
futureVersions=[{path:'/site/ru/docs/dev'},{path:'/site/ru/docs/5.x',isLast:true},{path:'/site/ru/docs/4.x'}];
const
options={managed:true,versions:futureVersions,contexts:['docs/dev','docs/5.x','community']};
diff --git a/scripts/i18n/__tests__/search-transport.test.cjs
b/scripts/i18n/__tests__/search-transport.test.cjs
index 3ac14205988..36691618c7b 100644
--- a/scripts/i18n/__tests__/search-transport.test.cjs
+++ b/scripts/i18n/__tests__/search-transport.test.cjs
@@ -5,6 +5,7 @@ const path = require('node:path');
const os = require('node:os');
const ts = require('typescript');
const lunr = require('lunr');
+const {createBodyHighlighter} =
require('../../../src/utils/searchBodyPositions');
const {adaptSearchWorker} = require('../search-worker-loader.cjs');
const {contentAddressSearchIndexes, targetFingerprint} =
require('../search-plugin.cjs');
const stableSearchDocuments = require('../search-document-ids.cjs');
@@ -155,6 +156,7 @@ test('the actual worker discards rejected cache entries and
reuses successful on
let calls=0;
const {SearchWorker}=compile(adaptSearchWorker(source,base), {
[require.resolve('../../../src/utils/fetchSearchIndex.js')]:{fetchSearchIndex:async()=>{if(++calls===1)throw
new Error('offline');return payload;}},
+
[require.resolve('../../../src/utils/searchBodyPositions.js')]:{createBodyHighlighter},
comlink:{expose(){}},
'../utils/proxiedGeneratedConstants':{searchIndexUrl:'search-index{dir}-aabb.json',language:['en']},
'../utils/tokenize':{},'../utils/smartQueries':{},'../../shared/interfaces':{},
@@ -169,6 +171,25 @@ test('the actual worker discards rejected cache entries
and reuses successful on
assert.throws(()=>adaptSearchWorker(source.replace('const cache = new
Map();','const changed = 1;')),/Unexpected search worker/);
});
+test('old positions survive and missing English positions are restored from
stemmed terms', () => {
+ const restore = createBodyHighlighter(['en']);
+ const metadata = {index:{t:{}}, query:{t:{position:[[0,5]]}}};
+ restore('Query indexes and indexing.', metadata);
+ assert.deepEqual(metadata.index.t.position, [[6,7],[18,9]]);
+ assert.deepEqual(metadata.query.t.position, [[0,5]]);
+});
+
+test('the production index builder omits body positions and keeps heading
positions', () => {
+ const {buildIndex} =
require('@yang1666204/docusaurus-search-local/dist/server/server/utils/buildIndex');
+ const doc = {i:1, t:'Doris', u:'/docs/dev/intro/'};
+ const indexes = buildIndex([[doc], [doc], [], [], [doc]],
{language:['en']});
+
assert.deepEqual(indexes[1].index.search('Doris')[0].matchData.metadata.dori.t.position,
[[0,5]]);
+ const {metadata} = indexes[4].index.search('Doris')[0].matchData;
+ assert.equal(metadata.dori.t.position, undefined);
+ createBodyHighlighter(['en'])(doc.t, metadata);
+ assert.deepEqual(metadata.dori.t.position, [[0,5]]);
+});
+
test('source-language search fingerprints include historical versions; managed
fallback versions do not', t => {
const
fixture=fs.mkdtempSync(path.join(os.tmpdir(),'doris-search-fingerprint-'));
t.after(()=>fs.rmSync(fixture,{recursive:true,force:true}));
diff --git a/scripts/i18n/search-plugin.cjs b/scripts/i18n/search-plugin.cjs
index 12611b47fa3..061db408737 100644
--- a/scripts/i18n/search-plugin.cjs
+++ b/scripts/i18n/search-plugin.cjs
@@ -14,7 +14,7 @@ const {scanDocuments} =
require('@yang1666204/docusaurus-search-local/dist/serve
const {buildIndex: buildNativeIndex} =
require('@yang1666204/docusaurus-search-local/dist/server/server/utils/buildIndex');
const {postBuildFactory} =
require('@yang1666204/docusaurus-search-local/dist/server/server/utils/postBuildFactory');
const {loadConfig, managedLocales} = require('./state.cjs');
-const {normalizeRussianSearch} =
require('../../src/utils/searchNormalization.js');
+const {normalizeRussianSearch, normalizeSearchDelimiters} =
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');
@@ -41,8 +41,8 @@ function localizedOptions(options, locale, labels,
contextNames = contexts) {
docsRouteBasePath:['docs','community','course','releases',`${locale}/docs`,`${locale}/community`,`${locale}/course`,`${locale}/releases`],
// A locale without configured labels falls back to the context path.
searchContextByPaths:contextNames.map(value =>
({path:value,label:{[locale]:labels?.[value] ?? value}})),
- // Outside every context, search all of them. The browser queries each
- // context index for that (src/utils/searchContexts.js); see
indexGroups.
+ // Keep the explicit "Everywhere" scope available. The browser merges
+ // its context indexes on demand (src/utils/searchContexts.js).
useAllContextsWithNoSearchContext:true, ignoreFiles:[]};
}
// One index per context, plus the root index for documents outside every
@@ -62,6 +62,7 @@ function targetFingerprint(root, locale, {allVersions =
false} = {}) {
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')));
+
digester.update(fs.readFileSync(require.resolve('../patch-search-tokenize.js')));
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))) {
@@ -137,7 +138,7 @@ function buildLocalizedIndexes(documents, config) {
const original = lunr.tokenizer;
const tokenizer = Object.assign((value, metadata) => original(
typeof value === 'string' ? (config.language.includes('ru')
- ? normalizeRussianSearch(value) :
value.replace(/[()\[\]{},"';`]/g, ' ')) : value, metadata), original);
+ ? normalizeRussianSearch(value) :
normalizeSearchDelimiters(value)) : value, metadata), original);
try {
lunr.tokenizer = tokenizer;
return buildNativeIndex(stableSearchDocuments(documents), config);
diff --git a/scripts/i18n/search-worker-loader.cjs
b/scripts/i18n/search-worker-loader.cjs
index 8c852b4ed68..3985ef31542 100644
--- a/scripts/i18n/search-worker-loader.cjs
+++ b/scripts/i18n/search-worker-loader.cjs
@@ -1,17 +1,25 @@
-const helper = require.resolve('../../src/utils/fetchSearchIndex.js');
+const fetchIndex = require.resolve('../../src/utils/fetchSearchIndex.js');
+const highlightBody =
require.resolve('../../src/utils/searchBodyPositions.js');
-// Keep the pinned plugin's tokenizer, ranking and result shape. Adapt only
-// transport and its rejected-promise cache; fail closed on an upstream change.
+// Adapt transport and enrich ranked body hits with snippet positions.
+// Fail closed if the pinned worker changes.
function adaptSearchWorker(source, options = {}) {
const replacements = [
['const cache = new Map();',
- `import {fetchSearchIndex} from ${JSON.stringify(helper)};\nconst
cache = new Map();`],
+ `import {fetchSearchIndex} from ${JSON.stringify(fetchIndex)};\n` +
+ `import {createBodyHighlighter} from
${JSON.stringify(highlightBody)};\n` +
+ 'const cache = new Map();\nconst restoreBodyPositions =
createBodyHighlighter(language);'],
['promise = legacyFetchIndexes(baseUrl, searchContext);',
`promise = legacyFetchIndexes(baseUrl, searchContext).catch(error
=> {\n` +
` if (cache.get(cacheKey) === promise)
cache.delete(cacheKey);\n` +
` throw error;\n });`],
['const json = (await (await fetch(url)).json());',
`const json = await fetchSearchIndex(fullUrl,
${JSON.stringify(options)});`],
+ ['processTreeStatusOfSearchResults(results);\n return results;',
+ 'processTreeStatusOfSearchResults(results);\n' +
+ ' for (const result of results) {\n' +
+ ' if (result.type === SearchDocumentType.Content)
restoreBodyPositions(result.document.t, result.metadata);\n' +
+ ' }\n return results;'],
];
for (const [before, after] of replacements) {
if (source.split(before).length !== 2) throw new Error('Unexpected
search worker format; revalidate the pinned search plugin');
diff --git a/scripts/i18n/verify-search-transport.cjs
b/scripts/i18n/verify-search-transport.cjs
index b9bf2eba310..495930dd369 100644
--- a/scripts/i18n/verify-search-transport.cjs
+++ b/scripts/i18n/verify-search-transport.cjs
@@ -47,6 +47,9 @@ async function build() {
}
write('src/theme/Root.tsx',`import React, {useEffect} from 'react';
export default function
Root({children}){useEffect(()=>{document.documentElement.dataset.hasHydrated='true';},[]);return
children;}\n`);
+ write('src/pages/index.tsx',`import React from 'react';
+import Layout from '@theme/Layout';
+export default function Home(){return
<Layout><main>Fixture</main></Layout>;}\n`);
fs.appendFileSync(path.join(fixture,'docusaurus.config.js'),`
const base = module.exports;
module.exports = () => {const config = base();
@@ -145,6 +148,7 @@ async function verify() {
assert(doc);await open(page,doc.route);
await input(page).fill('Doris');
await suggestions(page).first().waitFor();
+ await
suggestions(page).locator('mark').filter({hasText:/^Doris$/}).first().waitFor();
assert.equal(await input(page).inputValue(),'Doris');
assert(requests.some(r=>r.origin==='https://assets-cdn.selectdb.com'));
assert(requests.every(r=>/search-index.*-[a-f0-9]{16}\.json$/.test(new
URL(r.url).pathname)));
@@ -153,6 +157,44 @@ async function verify() {
results.push({locale,earlyQueryPreserved:true,results:await
suggestions(page).count(),requests,accessibility:ax});
await close(ctx);
}
+ for (const locale of ['en','zh-CN','ja','ko','ru']) {
+ const {ctx,page,requests}=await context();
+ const prefix=locale==='en'?'':'/'+locale;
+ const managed=['ja','ko','ru'].includes(locale);
+ await open(page,prefix+'/search/?q=Doris');
+ const snippet=page.locator('article p
mark').filter({hasText:/^Doris$/}).first();
+ await snippet.waitFor();
+ const result={locale,bodyHighlight:true};
+ if (managed) {
+ const scope=page.locator('#context-selector');
+ assert.equal(await scope.inputValue(),'docs/4.x');
+ const indexedContexts=()=>new Set(requests.map(({url})=>
+ new
URL(url).pathname.match(/search-index-([\w.-]+)-[a-f0-9]{16}\.json$/)?.[1]));
+ assert.deepEqual([...indexedContexts()],['docs-4.x']);
+ assert(await page.locator('article h2
a').evaluateAll(links=>links.every(link=>link.pathname.includes('/docs/4.x/'))));
+ result.defaultIndexes=[...indexedContexts()];
+ await scope.selectOption('all');
+ await page.locator('article h2
a[href*="/docs/dev/"]').first().waitFor();
+ assert.equal(new
URL(page.url()).searchParams.get('ctx'),'all');
+ assert.equal(await
page.locator('input[name="q"]').inputValue(),'Doris');
+
assert.deepEqual([...indexedContexts()].sort(),['community','course','docs-4.x','docs-dev','releases']);
+ result.everywhereIndexes=[...indexedContexts()];
+ }
+ results.push(result);await close(ctx);
+ }
+ {
+ const {ctx,page,requests}=await context();
+ await open(page,'/ja/');
+ await input(page).fill('Doris');
+ await suggestions(page).first().waitFor();
+ assert(requests.length &&
requests.every(({url})=>url.includes('/ja/search-index-docs-4.x-')));
+ await input(page).fill('courseFixtureSQL');
+ const allLink=page.locator('.navbar__search
a[href*="ctx=all"]').first();
+ await allLink.waitFor();
+ await allLink.click();
+ await page.locator('article h2
a[href*="/ja/course/"]').first().waitFor();
+
results.push({managedNavbarDefault:true,expandsAfterEmptyResults:true});await
close(ctx);
+ }
{
const {ctx,page,requests}=await context({failCdn:true});
await open(page,'/docs/dev/english-shared/');await
input(page).fill('Doris');
diff --git a/scripts/patch-search-tokenize.js b/scripts/patch-search-tokenize.js
index 3a76243397d..d259c0956a0 100644
--- a/scripts/patch-search-tokenize.js
+++ b/scripts/patch-search-tokenize.js
@@ -27,6 +27,7 @@ const targetPostBuildFactoryFile = path.join(
"utils",
"postBuildFactory.js"
);
+const targetBuildIndexFile =
path.join(path.dirname(targetPostBuildFactoryFile), "buildIndex.js");
const targetSearchPageFile = path.join(
process.cwd(),
@@ -224,6 +225,28 @@ function patchSearchPageVersionUrlContent(content) {
return content.replace(needle1, replacement1).replace(needle2, replacement2);
}
+function patchBodyPositions(content) {
+ if (content.includes("PATCH(on-demand-body-positions)")) {
+ return content;
+ }
+ const replacements = [
+ ['const lunr_1 = tslib_1.__importDefault(require("lunr"));',
+ 'const lunr_1 = tslib_1.__importDefault(require("lunr"));\n' +
+ 'const { SearchDocumentType } = require("../../shared/interfaces");'],
+ ['.map((documents) => ({', '.map((documents, type) => ({'],
+ ['this.metadataWhitelist = ["position"];',
+ '// PATCH(on-demand-body-positions): keep term frequencies without
serializing body offsets.\n' +
+ ' this.metadataWhitelist = type ===
SearchDocumentType.Content ? [] : ["position"];'],
+ ];
+ for (const [before, after] of replacements) {
+ if (content.split(before).length !== 2) {
+ throw new Error("Unexpected search index builder format; revalidate the
pinned search plugin");
+ }
+ content = content.replace(before, after);
+ }
+ return content;
+}
+
function patchOneFile(filePath, patchFn, label) {
if (!fs.existsSync(filePath)) {
console.warn(`[patch-search-tokenize] skip(${label}): file not found:
${filePath}`);
@@ -255,6 +278,7 @@ function main() {
"server-postBuildFactory-locale"
);
patchOneFile(targetPostBuildFactoryFile, patchStableSearchDocuments,
'server-stable-search-document-ids');
+ patchOneFile(targetBuildIndexFile, patchBodyPositions,
"server-on-demand-body-positions");
patchOneFile(
targetSearchBarFile,
patchSearchBarVersionUrlContent,
diff --git a/src/hooks/use-search-query.ts b/src/hooks/use-search-query.ts
index 267d82d4239..c9992ba7ec9 100644
--- a/src/hooks/use-search-query.ts
+++ b/src/hooks/use-search-query.ts
@@ -7,7 +7,7 @@
import { useHistory, useLocation } from "@docusaurus/router";
import useIsBrowser from "@docusaurus/useIsBrowser";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
-import { resolveSearchScope } from "../utils/searchScopes";
+import { readSearchScope } from "../utils/searchScopes";
const SEARCH_PARAM_QUERY = "q";
const SEARCH_PARAM_CONTEXT = "ctx";
const SEARCH_PARAM_VERSION = "version";
@@ -18,8 +18,7 @@ function useSearchQuery(scopeOptions) {
const { siteConfig: { baseUrl }, } = useDocusaurusContext();
const params = isBrowser ? new URLSearchParams(location.search) : null;
const searchValue = params?.get(SEARCH_PARAM_QUERY) || "";
- const scope =
resolveSearchScope({context:params?.get(SEARCH_PARAM_CONTEXT) || '',
- version:params?.get(SEARCH_PARAM_VERSION) || ''}, scopeOptions);
+ const scope = readSearchScope(params, scopeOptions);
const getSearchParams = (searchValue) => {
const searchParams = new URLSearchParams(location.search);
if (searchValue) {
diff --git a/src/theme/SearchBar/SearchBar.jsx
b/src/theme/SearchBar/SearchBar.jsx
index a2f66cf15f5..96428402775 100644
--- a/src/theme/SearchBar/SearchBar.jsx
+++ b/src/theme/SearchBar/SearchBar.jsx
@@ -31,7 +31,7 @@ import {fetchContextIndexes, searchAcrossContexts} from
'@site/src/utils/searchC
import {isTranslatedLocale} from '@site/src/utils/localization';
import {searchIndexBaseUrl} from '@site/src/utils/searchVersion';
import {searchMessages} from '@site/src/utils/searchMessages';
-import {docSearchSourceVersion} from '@site/src/utils/searchScopes';
+import {ALL_SEARCH_CONTEXT, docSearchSourceVersion, resolveSearchScope} from
'@site/src/utils/searchScopes';
const searchContextsByWorker = searchAcrossContexts(searchByWorker);
@@ -103,8 +103,10 @@ export default function SearchBar({ handleSearchBarToggle
}) {
return path;
}
}
- return '';
- }, [location.pathname, locales, currentLocale]);
+ return isTranslatedLocale(currentLocale) ? resolveSearchScope({}, {
+ contexts: searchContextByPaths, versions: sourceVersions, managed:
true,
+ }).context : '';
+ }, [location.pathname, locales, currentLocale, sourceVersions]);
const hidden = !!hideSearchBarWithNoSearchContext &&
Array.isArray(searchContextByPaths) && searchContext === '';
const indexKey = `${versionUrl}:${searchContext}`;
@@ -186,12 +188,8 @@ export default function SearchBar({ handleSearchBarToggle
}) {
message: 'See all results',
});
}
- if (
- searchContext &&
- Array.isArray(searchContextByPaths) &&
- (!useAllContextsWithNoSearchContext || !isEmpty)
- ) {
- params.set('ctx', searchContext);
+ if (searchContext && Array.isArray(searchContextByPaths)) {
+ params.set('ctx', useAllContextsWithNoSearchContext &&
isEmpty ? ALL_SEARCH_CONTEXT : searchContext);
}
if (!isTranslatedLocale(currentLocale) && versionUrl !==
baseUrl) {
if (!versionUrl.startsWith(baseUrl)) {
diff --git a/src/theme/SearchPage/SearchPage.jsx
b/src/theme/SearchPage/SearchPage.jsx
index 310fd4bd8e1..d512b7fa03a 100644
--- a/src/theme/SearchPage/SearchPage.jsx
+++ b/src/theme/SearchPage/SearchPage.jsx
@@ -25,7 +25,7 @@ import {searchAcrossContexts} from
"../../utils/searchContexts";
import {isTranslatedLocale} from "../../utils/localization";
import {searchIndexBaseUrl} from "../../utils/searchVersion";
import {searchMessages} from "../../utils/searchMessages";
-import {convertSearchParams} from "../../utils/searchScopes";
+import {ALL_SEARCH_CONTEXT, convertSearchParams} from
"../../utils/searchScopes";
const searchContextsByWorker = searchAcrossContexts(searchByWorker);
export default function SearchPage() {
return (<Layout>
@@ -127,7 +127,7 @@ function SearchPageContent() {
{Array.isArray(searchContextByPaths) ? (<div className={clsx("col",
"col--3", "padding-left--none", styles.searchContextColumn)}>
<select name="search-context"
className={styles.searchContextInput} aria-label={translate({id:
'site.search.context', message: 'Search context'})} id="context-selector"
value={sourceOnlyVersion?'docs/'+sourceOnlyVersion:searchContext} onChange={(e)
=> updateSearchContext(e.target.value)}>
{sourceOnlyVersion&&<option value={'docs/'+sourceOnlyVersion}
disabled>{sourceOnlyVersion} ·
{searchMessages(currentLocale).sourceOnly}</option>}
- {useAllContextsWithNoSearchContext && (<option value="">
+ {useAllContextsWithNoSearchContext && (<option
value={ALL_SEARCH_CONTEXT}>
{translate({
id: "theme.SearchPage.searchContext.everywhere",
message: "Everywhere",
@@ -178,7 +178,7 @@ function SearchPageContent() {
<section>
{searchResults &&
- searchResults.map((item) => (<SearchResultItem
key={item.document.i} searchResult={item}/>))}
+ searchResults.map((item) => (<SearchResultItem
key={JSON.stringify([item.document.u, item.type, item.document.i])}
searchResult={item}/>))}
</section>
</div>
</React.Fragment>);
diff --git a/src/utils/getStemmedPositions.ts b/src/utils/getStemmedPositions.ts
index 52f4ec51e5e..71fddc13b6a 100644
--- a/src/utils/getStemmedPositions.ts
+++ b/src/utils/getStemmedPositions.ts
@@ -6,9 +6,7 @@ export function getStemmedPositions(
): MetadataPosition[] {
const positions: MetadataPosition[] = [];
for (const match of Object.values(metadata)) {
- if (match[field]) {
- positions.push(...match[field].position);
- }
+ positions.push(...(match[field]?.position ?? []));
}
// Put positions with lower start pos before those with higher start pos.
diff --git a/src/utils/highlightStemmed.ts b/src/utils/highlightStemmed.ts
index b0158058147..32fffcf8cd1 100644
--- a/src/utils/highlightStemmed.ts
+++ b/src/utils/highlightStemmed.ts
@@ -10,6 +10,9 @@ export function highlightStemmed(
tokens: string[],
maxLength = searchResultContextMaxLength
): string {
+ if (positions.length === 0) {
+ return highlight(content.slice(0, maxLength), tokens) + (content.length >
maxLength ? "…" : "");
+ }
const { chunkIndex, chunks } = splitIntoChunks(content, positions, tokens);
const leadingChunks = chunks.slice(0, chunkIndex);
diff --git a/src/utils/searchBodyPositions.js b/src/utils/searchBodyPositions.js
new file mode 100644
index 00000000000..6146aa983ca
--- /dev/null
+++ b/src/utils/searchBodyPositions.js
@@ -0,0 +1,58 @@
+const lunr = require('lunr');
+const {normalizeRussianSearch, normalizeSearchDelimiters} =
require('./searchNormalization');
+
+function createBodyHighlighter(language) {
+ const analyzer = new lunr.Builder();
+ const usesJieba = language.includes('zh');
+ const usesTinySegmenter = language.includes('ja') ||
language.includes('jp');
+ const normalize = language.includes('ru') ? normalizeRussianSearch
+ : language[0] === 'ko' ? normalizeSearchDelimiters : null;
+ if (language.length > 1) analyzer.use(lunr.multiLanguage(...language));
+ else if (language[0] !== 'en') analyzer.use(lunr[language[0]]);
+ else analyzer.pipeline.add(lunr.trimmer, lunr.stopWordFilter,
lunr.stemmer);
+
+ return function restoreBodyPositions(text, metadata) {
+ const missing = new Map(
+ Object.entries(metadata).filter(([, fields]) => fields.t &&
!Array.isArray(fields.t.position))
+ .map(([term, fields]) => [term, fields.t]),
+ );
+ if (missing.size === 0) return;
+
+ if (usesJieba) {
+ // The index uses server-side Jieba. Match only its returned Han
terms
+ // and use its ASCII boundaries, including underscore-separated
words.
+ const tokens = [];
+ const addToken = (value, offset) => tokens.push(new
lunr.Token(value, {position: [offset, value.length]}));
+ for (const word of text.matchAll(/\w+/g)) {
+ const value = word[0].toLowerCase();
+ addToken(value, word.index);
+ if (value.includes('_')) {
+ for (const part of value.matchAll(/[^_]+/g))
addToken(part[0], word.index + part.index);
+ }
+ }
+ for (const token of analyzer.pipeline.run(tokens))
addPosition(token.toString(), token.metadata.position);
+ for (const term of missing.keys()) {
+ if (!/^\p{Unified_Ideograph}/u.test(term)) continue;
+ for (let start = text.indexOf(term); start !== -1; start =
text.indexOf(term, start + term.length)) {
+ addPosition(term, [start, term.length]);
+ }
+ }
+ } else {
+ const input = normalize ? normalize(text) : text;
+ const tokens = analyzer.pipeline.run(analyzer.tokenizer(input));
+ // TinySegmenter drops leading whitespace before assigning offsets.
+ const offset = usesTinySegmenter ? text.length -
text.trimStart().length : 0;
+ for (const token of tokens) {
+ const [start, length] = token.metadata.position;
+ addPosition(token.toString(), [start + offset, length]);
+ }
+ }
+
+ function addPosition(term, position) {
+ const field = missing.get(term);
+ if (field) (field.position ??= []).push(position);
+ }
+ };
+}
+
+module.exports = {createBodyHighlighter};
diff --git a/src/utils/searchContexts.js b/src/utils/searchContexts.js
index eeb53392d7b..ffec64ead57 100644
--- a/src/utils/searchContexts.js
+++ b/src/utils/searchContexts.js
@@ -2,13 +2,12 @@ import {sortSearchResults} from
'@yang1666204/docusaurus-search-local/dist/clien
import {processTreeStatusOfSearchResults} from
'@yang1666204/docusaurus-search-local/dist/client/client/utils/processTreeStatusOfSearchResults';
import {SearchDocumentType} from '../../shared/interfaces';
import {searchContextByPaths, useAllContextsWithNoSearchContext} from
'./proxiedGenerated';
+import {ALL_SEARCH_CONTEXT} from './searchScopes';
-// With useAllContextsWithNoSearchContext, a page outside every search context
-// searches all of them. The localized build writes no union of the context
-// indexes for that (see indexGroups in scripts/i18n/search-plugin.cjs), so the
-// browser queries each context index and merges the results.
+// The localized build writes one index per context. Merge them only when the
+// user explicitly searches "Everywhere".
export function indexContexts(searchContext) {
- if (searchContext || !useAllContextsWithNoSearchContext ||
!Array.isArray(searchContextByPaths)) {
+ if (searchContext !== ALL_SEARCH_CONTEXT ||
!useAllContextsWithNoSearchContext || !Array.isArray(searchContextByPaths)) {
return [searchContext];
}
return searchContextByPaths.map(item => (typeof item === 'string' ? item :
item.path));
diff --git a/src/utils/searchNormalization.js b/src/utils/searchNormalization.js
index 17b13b7da27..9a404639f46 100644
--- a/src/utils/searchNormalization.js
+++ b/src/utils/searchNormalization.js
@@ -1,6 +1,9 @@
// Length-preserving normalization keeps Lunr highlight positions bound to the
// original text. Russian spelling with е and ё shares one search token.
function normalizeRussianSearch(value) {
- return value.replace(/ё/g, 'е').replace(/Ё/g,
'Е').replace(/[()\[\]{},"';`]/g, ' ');
+ return normalizeSearchDelimiters(value.replace(/ё/g, 'е').replace(/Ё/g,
'Е'));
}
-module.exports = {normalizeRussianSearch};
+function normalizeSearchDelimiters(value) {
+ return value.replace(/[()\[\]{},"';`]/g, ' ');
+}
+module.exports = {normalizeRussianSearch, normalizeSearchDelimiters};
diff --git a/src/utils/searchScopes.js b/src/utils/searchScopes.js
index e23d2eb25e0..fb795d5b596 100644
--- a/src/utils/searchScopes.js
+++ b/src/utils/searchScopes.js
@@ -1,11 +1,14 @@
const pathOf = item => typeof item === 'string' ? item : item.path;
+export const ALL_SEARCH_CONTEXT = 'all';
export const versionId = version =>
version?.path?.split('/').filter(Boolean).pop();
export const defaultSearchVersion = versions =>
versionId(versions.find(version => version.isLast) ?? versions[0]) ?? 'dev';
// Source-language indexes use ctx=docs plus a version path. Managed languages
// use ctx=docs/<version>. Translate that logical scope, not just the URL
prefix.
export function resolveSearchScope({context = '', version = ''}, {contexts =
[], versions = [], managed = false} = {}) {
- const paths = contexts.map(pathOf), fallback = managed ? '' : paths[0] ??
'';
+ const paths = contexts.map(pathOf);
+ const current = `docs/${defaultSearchVersion(versions)}`;
+ const fallback = managed && paths.includes(current) ? current : paths[0]
?? '';
if (context && context !== 'docs' && !context.startsWith('docs/') &&
paths.includes(context))
return {context, version:'', sourceOnlyVersion:null};
const requested = context.startsWith('docs/') ? context.slice(5)
@@ -21,18 +24,26 @@ export function resolveSearchScope({context = '', version =
''}, {contexts = [],
return {context:paths.includes('docs')?'docs':fallback,
version:selected === defaultSearchVersion(versions) ? '' :
'docs/'+selected+'/',sourceOnlyVersion:null};
}
+ if (managed && context === ALL_SEARCH_CONTEXT) return
{context,version:'',sourceOnlyVersion:null};
return
{context:paths.includes(context)?context:fallback,version:'',sourceOnlyVersion:null};
}
+export function readSearchScope(params, options) {
+ const context = params?.get('ctx');
+ // A previously selected "Everywhere" was serialized as an explicit empty
ctx.
+ return resolveSearchScope({context:context === '' && options.managed ?
ALL_SEARCH_CONTEXT : context ?? '',
+ version:params?.get('version') ?? ''}, options);
+}
+
export function convertSearchParams(params, options, sourceOptions) {
const result = new URLSearchParams(params);
if(sourceOptions) {
- const
current=resolveSearchScope({context:result.get('ctx')??'',version:result.get('version')??''},sourceOptions);
+ const current=readSearchScope(result,sourceOptions);
if(current.sourceOnlyVersion)result.set('ctx','docs');
else if(current.context)result.set('ctx',current.context);else
result.delete('ctx');
if(current.version)result.set('version',current.version);else
result.delete('version');
}
- const scope =
resolveSearchScope({context:result.get('ctx')??'',version:result.get('version')??''},options);
+ const scope = readSearchScope(result,options);
const context = scope.sourceOnlyVersion ? 'docs' : scope.context;
if (context) result.set('ctx',context); else result.delete('ctx');
if (scope.version) result.set('version',scope.version); else
result.delete('version');
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]