Skip to content
3 changes: 3 additions & 0 deletions site/docs/.vitepress/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ export const en: Messages = {
'search.metaCountTime': '{count} hits, {ms} ms',
'search.loadingBar': 'Loading body index ({loaded} / {total} MB), showing title and heading matches first',
'search.loadingIdle': 'Loading body index ({loaded} / {total} MB)…',
'search.loadingTitles': 'Loading lecture index…',
'search.loadError': 'Could not load the search index (your session may have expired). Sign in again or retry.',
'search.retry': 'Retry',
'search.groupCount': '{count}',
'search.lectureNo': 'L{n}',
'search.groupSite': 'Overview',
Expand Down
3 changes: 3 additions & 0 deletions site/docs/.vitepress/i18n/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ export const zhCN = {
'search.metaCountTime': '{count} 条,{ms} ms',
'search.loadingBar': '正文索引载入中({loaded} / {total} MB),以下先按讲名与小节标题给出结果',
'search.loadingIdle': '正文索引载入中({loaded} / {total} MB)…',
'search.loadingTitles': '正在载入讲义索引…',
'search.loadError': '讲义索引载入失败(可能登录会话已过期或网络异常),请重新登录后重试',
'search.retry': '重试加载',
'search.groupCount': '{count} 条',
'search.lectureNo': '第{n}讲',
'search.groupSite': '站点页面',
Expand Down
36 changes: 26 additions & 10 deletions site/docs/.vitepress/theme/access/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export interface ReadableTier {
export interface AccessResult {
/** The tiers the gateway let through, in the order of `lectureAccess.tiers`. */
tiers: ReadableTier[]
/** Tiers whose `site-data.json` check encountered a transient network/5xx fault (not normal 401/403 denial). */
failedTiers?: string[]
}

export const EMPTY_ACCESS: AccessResult = { tiers: [] }
Expand All @@ -39,31 +41,45 @@ export function tierUrl(deps: Pick<AccessDeps, 'withBase'>, tier: string, file:
return deps.withBase(`${tierBasePath(tier)}/${file}`)
}

async function fetchTierJsonWithStatus(
deps: Pick<AccessDeps, 'fetch'>,
url: string,
): Promise<{ json: unknown | undefined; transientError: boolean }> {
try {
const res = await deps.fetch(url, { redirect: 'manual', credentials: 'same-origin', cache: 'no-store' })
if (res.status >= 500) return { json: undefined, transientError: true }
if (res.status !== 200) return { json: undefined, transientError: false }
return { json: (await res.json()) as unknown, transientError: false }
} catch (err) {
// Only treat network/fetch rejections as transient errors (syntax/HTML parse failure is an auth redirect body).
const isSyntax = err instanceof SyntaxError
return { json: undefined, transientError: !isSyntax }
}
}

/**
* GET a file of a tier. The answer counts only on a 200 whose body is JSON: a redirect (`redirect: 'manual'` gives an
* opaque redirect with status 0), 401 / 403, any other status, a network error and a body that is not JSON all give
* `undefined`.
*/
export async function fetchTierJson(deps: Pick<AccessDeps, 'fetch'>, url: string): Promise<unknown | undefined> {
try {
const res = await deps.fetch(url, { redirect: 'manual', credentials: 'same-origin', cache: 'no-store' })
if (res.status !== 200) return undefined
return (await res.json()) as unknown
} catch {
return undefined
}
return (await fetchTierJsonWithStatus(deps, url)).json
}

/** Ask the gateway which restricted tiers the reader may read. No restricted tier configured: no request at all. */
export async function resolveAccess(lectureAccess: LectureAccess | undefined, deps: AccessDeps): Promise<AccessResult> {
const ids = lectureAccess?.tiers ?? []
if (ids.length === 0) return EMPTY_ACCESS
const slices = await Promise.all(ids.map(async (id) => ({ id, json: await fetchTierJson(deps, tierUrl(deps, id, 'site-data.json')) })))
const slices = await Promise.all(
ids.map(async (id) => ({ id, ...(await fetchTierJsonWithStatus(deps, tierUrl(deps, id, 'site-data.json'))) })),
)
const tiers: ReadableTier[] = []
for (const { id, json } of slices) {
const failedTiers: string[] = []
for (const { id, json, transientError } of slices) {
if (isTierSlice(json) && json.tier === id) tiers.push({ id, slice: json })
else if (transientError) failedTiers.push(id)
}
return { tiers }
return failedTiers.length > 0 ? { tiers, failedTiers } : { tiers }
}

/** The nodes of the `graph.json` of each readable tier (a tier whose file does not arrive or is not an array adds nothing). */
Expand Down
42 changes: 30 additions & 12 deletions site/docs/.vitepress/theme/search/SearchHost.vue
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ const engine = new LectureSearchEngine({
conceptBadge: t('search.conceptBadge'),
loadingBar: (loaded, total) => t('search.loadingBar', { loaded, total }),
loadingIdle: (loaded, total) => t('search.loadingIdle', { loaded, total }),
loadingTitles: () => t('search.loadingTitles'),
loadError: () => t('search.loadError'),
statusLabel: (status) => {
if (status === 'completed') return t('sidebar.status.completed')
if (status === 'in_progress') return t('sidebar.status.inProgress')
Expand Down Expand Up @@ -110,12 +112,12 @@ function openSearch(): void {
// spec board 04.2: on a group or lecture page the default scope is "this group"
scope.value = currentGroupId.value ? 'group' : 'all'
isOpen.value = true
loadIndex()
loadIndex(true)
}

function loadIndex(): void {
engine.ensureLoaded(activeLocale.value, currentGroupId.value).catch(() => {
// the title index could not be fetched: the panel stays usable (empty) and the next open retries
function loadIndex(forceRetry = false): void {
engine.ensureLoaded(activeLocale.value, currentGroupId.value, { forceRetry }).catch(() => {
// Error status is surfaced cleanly via getLoadState / emptyState='error'; next open/retry will re-fetch
})
}

Expand All @@ -137,13 +139,17 @@ function openHit(hit: SearchHitView): void {
function setQuery(next: string): void {
query.value = next
activeIndex.value = 0
if (isOpen.value) loadIndex()
if (isOpen.value) loadIndex(false)
}

function setScope(next: 'all' | 'group'): void {
scope.value = next
activeIndex.value = 0
if (next === 'group') engine.prioritizeGroup(activeLocale.value, currentGroupId.value)
const st = engine.getLoadState(activeLocale.value, query.value.trim().length > 0)
if (st.phase === 'error' || st.phase === 'idle') {
loadIndex(true)
}
}

function handleDialogKeyDown(ev: KeyboardEvent): void {
Expand Down Expand Up @@ -221,13 +227,21 @@ function handleGlobalKeyDown(ev: KeyboardEvent): void {
const panelProps = computed<SearchPanelProps>(() => {
void revision.value
const hasQuery = query.value.trim().length > 0
const loadState = engine.getLoadState(activeLocale.value, hasQuery)
const groups: readonly SearchGroupSectionView[] = searchResult.value.groups
const metaText = hasQuery
? t('search.metaCountTime', { count: searchResult.value.totalHits, ms: searchResult.value.elapsedMs })
: ''
const emptyState = hasQuery
? (groups.length === 0 ? 'no-results' : null)
: 'idle'
const suppressMeta =
loadState.phase === 'loading-titles' ||
loadState.phase === 'error' ||
(groups.length === 0 && (Boolean(loadState.error) || loadState.loading))
const metaText =
hasQuery && !suppressMeta
? t('search.metaCountTime', { count: searchResult.value.totalHits, ms: searchResult.value.elapsedMs })
: ''
const emptyState: SearchPanelProps['emptyState'] = groups.length > 0
? null
: hasQuery
? 'no-results'
: 'idle'

return {
query: query.value,
Expand All @@ -237,7 +251,7 @@ const panelProps = computed<SearchPanelProps>(() => {
groups,
activeIndex: activeIndex.value,
metaText,
loadState: engine.getLoadState(activeLocale.value, hasQuery),
loadState,
emptyState,
labels: {
dialogLabel: t('search.dialogLabel'),
Expand All @@ -249,6 +263,9 @@ const panelProps = computed<SearchPanelProps>(() => {
scopeGroup: t('search.scopeGroup', { id: currentGroupId.value ?? '' }),
noResults: t('search.noResults'),
idleHint: t('search.idleHint'),
loadingTitles: t('search.loadingTitles'),
loadError: t('search.loadError'),
retry: t('search.retry'),
footerSelect: t('search.footerSelect'),
footerOpen: t('search.footerOpen'),
footerClose: t('search.footerClose'),
Expand All @@ -261,6 +278,7 @@ const panelProps = computed<SearchPanelProps>(() => {
},
onOpen: openHit,
onClose: closeSearch,
onRetry: () => loadIndex(true),
onKeyDown: handleDialogKeyDown,
}
})
Expand Down
Loading
Loading