From 47d143abce7da80610a242d04f0ae6ce9f0d0cb7 Mon Sep 17 00:00:00 2001 From: LunaStev Date: Mon, 12 Oct 2026 21:37:34 +0900 Subject: [PATCH] feat: strengthen documentation loading and link validation --- .github/workflows/frontend-editor-ci.yml | 4 +- docs/document-authoring.md | 22 +++++++ frontend/package.json | 3 +- frontend/src/components/MarkdownContent.vue | 6 +- frontend/src/i18n/index.ts | 6 ++ frontend/src/pages/DocsPage.vue | 65 +++++++++++--------- frontend/src/services/documentLinks.ts | 40 ++++++++++++ frontend/src/services/documentLoader.ts | 50 +++++++++++++++ frontend/src/services/documentMarkdown.ts | 9 ++- frontend/src/ui/service-pages.css | 4 ++ frontend/tests/document-links.test.ts | 25 ++++++++ frontend/tests/document-loader.test.ts | 67 +++++++++++++++++++++ frontend/tests/document-markdown.test.ts | 8 +++ frontend/tools/check-document-links.ts | 26 ++++++++ 14 files changed, 303 insertions(+), 32 deletions(-) create mode 100644 frontend/src/services/documentLinks.ts create mode 100644 frontend/src/services/documentLoader.ts create mode 100644 frontend/tests/document-links.test.ts create mode 100644 frontend/tests/document-loader.test.ts create mode 100644 frontend/tools/check-document-links.ts diff --git a/.github/workflows/frontend-editor-ci.yml b/.github/workflows/frontend-editor-ci.yml index d8ff01b..d25b70b 100644 --- a/.github/workflows/frontend-editor-ci.yml +++ b/.github/workflows/frontend-editor-ci.yml @@ -100,7 +100,9 @@ jobs: - name: Run frontend documentation tests working-directory: frontend - run: npm run test:docs + run: | + npm run test:docs + npm run check:doc-links - name: Run frontend toolchain tests working-directory: frontend diff --git a/docs/document-authoring.md b/docs/document-authoring.md index 16ab0b4..47a301f 100644 --- a/docs/document-authoring.md +++ b/docs/document-authoring.md @@ -191,3 +191,25 @@ The live test uses the running local service at `http://localhost:8080` unless `PLAYGROUND_URL` selects another instance. The document checker also rejects unregistered playground fences and cases that require file fixtures or have `check`/`reject` modes. Add new examples only after the live test passes. + + +## Documentation links and heading IDs + +Use `/docs/{locale}/{path}` for documentation links. Heading fragments follow the +rendered GitHub-style Markdown IDs, including Unicode titles, inline formatting, +and duplicate-heading suffixes. A link to an untranslated page resolves to the +English page, so its fragment must exist in that English page. Retired paths are +resolved through `wavedoc/redirects.json`. + +Before committing link or heading changes, run: + +```shell +cd frontend +npm run check:doc-links +npm run test:docs +``` + +CI checks every official document without fetching external URLs. The checker +validates document paths, reference links, heading fragments, locale support, +redirects, and English fallback. Links to `.md` files are rejected because the +platform serves documentation URLs rather than Markdown source-file URLs. diff --git a/frontend/package.json b/frontend/package.json index df731eb..8167c6e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -8,7 +8,8 @@ "build": "vue-tsc --noEmit && vite build", "preview": "vite preview", "typecheck": "vue-tsc --noEmit", - "test:docs": "node --experimental-strip-types --test tests/document-navigation.test.ts tests/document-markdown.test.ts", + "test:docs": "node --experimental-strip-types --test tests/document-navigation.test.ts tests/document-markdown.test.ts tests/document-loader.test.ts tests/document-links.test.ts", + "check:doc-links": "node --experimental-strip-types tools/check-document-links.ts", "test:seo": "node --experimental-strip-types --test tests/seo-image.test.ts", "test:toolchains": "node --experimental-strip-types --test tests/toolchains.test.ts", "test:syntax": "node --experimental-strip-types --test tests/wave-syntax.test.ts", diff --git a/frontend/src/components/MarkdownContent.vue b/frontend/src/components/MarkdownContent.vue index 184e7c5..8a9c82c 100644 --- a/frontend/src/components/MarkdownContent.vue +++ b/frontend/src/components/MarkdownContent.vue @@ -4,11 +4,12 @@ import { computed, nextTick, onMounted, ref, shallowRef, useId, watch } from 'vu import { grammarForLanguage, normalizeFenceLanguage, Prism } from './source/syntax' import { highlightWave } from '../services/waveSyntax' -import { renderDocumentMarkdown, type DocumentExample } from '../services/documentMarkdown' +import { renderDocumentMarkdown, type DocumentExample, type DocumentHeading } from '../services/documentMarkdown' import WavePlayground from './WavePlayground.vue' defineOptions({ inheritAttrs: false }) const props = defineProps<{ source: string; repository?: string; path?: string; reference?: string; runnable?: boolean }>() +const emit = defineEmits<{ headings: [items: DocumentHeading[]] }>() const article = ref(null) const slotPrefix = `wave-example-${useId()}` const targets = shallowRef>([]) @@ -72,6 +73,9 @@ async function mountExamples() { targets.value = [] await nextTick() if (current !== generation || !article.value) return + emit('headings', Array.from(article.value.querySelectorAll('h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]')).map(element => ({ + anchor: element.id, level: Number(element.tagName.slice(1)), text: element.textContent ?? '', + }))) const placeholders = Array.from(article.value.querySelectorAll('[data-wave-playground]')) targets.value = result.slots.flatMap((example, index) => { const element = placeholders.find(item => item.dataset.wavePlayground === `${slotPrefix}-${index}`) diff --git a/frontend/src/i18n/index.ts b/frontend/src/i18n/index.ts index e62548a..228419f 100644 --- a/frontend/src/i18n/index.ts +++ b/frontend/src/i18n/index.ts @@ -305,6 +305,9 @@ const messages: Record> = { 'docs.previous': 'Previous', 'docs.next': 'Next', 'docs.noResults': 'No documents match this search.', + 'docs.notFound': 'Document not found', + 'docs.notFoundHelp': 'This document does not exist or is no longer published. Browse the documentation to find another page.', + 'docs.unavailable': 'Documentation could not be loaded. Please try again.', 'docs.languageSelector': 'Documentation language', 'docs.projectSelector': 'Documentation project', 'docs.whaleLead': 'Whale guides and reference documentation.', @@ -1083,6 +1086,9 @@ const messages: Record> = { 'docs.previous': '이전 문서', 'docs.next': '다음 문서', 'docs.noResults': '검색 조건과 일치하는 문서가 없습니다.', + 'docs.notFound': '문서를 찾을 수 없습니다', + 'docs.notFoundHelp': '존재하지 않거나 더 이상 게시되지 않은 문서입니다. 문서 목록에서 다른 페이지를 찾아보세요.', + 'docs.unavailable': '문서를 불러오지 못했습니다. 다시 시도해 주세요.', 'docs.languageSelector': '문서 언어', 'docs.projectSelector': '문서 프로젝트', 'docs.whaleLead': 'Whale 안내와 참조 문서입니다.', diff --git a/frontend/src/pages/DocsPage.vue b/frontend/src/pages/DocsPage.vue index 768ad00..46a4f76 100644 --- a/frontend/src/pages/DocsPage.vue +++ b/frontend/src/pages/DocsPage.vue @@ -8,6 +8,8 @@ import DocumentationTree from '../components/docs/DocumentationTree.vue' import { useI18n } from '../i18n' import { documentLocales, isDocumentLocale, saveDocumentLocale } from '../services/documentLocale' import { documentationCatalog, documentationPath, documentationProject, projectDocuments } from '../services/documentNavigation' +import { createDocumentLoader } from '../services/documentLoader' +import type { DocumentHeading } from '../services/documentMarkdown' import { HTTPError, getDocument, getDocuments, type DocumentLocale, type DocumentSummary, type DocumentView } from '../services/http' import { applyPageSEO } from '../services/seo' import UiInlineState from '../ui/UiInlineState.vue' @@ -24,7 +26,12 @@ const article = ref(null) const mobileNavigation = ref(null) const activeHeading = ref('') const loading = ref(true) -const failed = ref(false) +const failure = ref<'not-found' | 'unavailable' | null>(null) +const failed = computed(() => failure.value !== null) +const headings = ref([]) +const isNotFound = (error: unknown) => error instanceof HTTPError && error.status === 404 +const documentLoader = createDocumentLoader({ list: getDocuments, get: getDocument, isNotFound }) +let restoreAnchor = false const showingEnglishFallback = ref(false) const hasEnglishFallbackItems = computed(() => docLocale.value !== 'en' && documents.value.some(item => item.locale === 'en')) @@ -53,7 +60,6 @@ const groups = computed(() => { for (const item of filtered.value) result.set(item.group, [...(result.get(item.group) ?? []), item]) return Array.from(result, ([id, items]) => ({ id, title: groupName(id), items })) }) -const headings = computed(() => document.value?.blocks.filter((block) => block.kind === 'heading' && block.anchor) ?? []) const currentIndex = computed(() => documents.value.findIndex((item) => item.path === currentPath.value)) const previous = computed(() => currentIndex.value > 0 ? documents.value[currentIndex.value - 1] : null) const next = computed(() => currentIndex.value >= 0 && currentIndex.value < documents.value.length - 1 ? documents.value[currentIndex.value + 1] : null) @@ -68,38 +74,27 @@ function groupName(group: string) { } let loadGeneration = 0 -async function load() { +async function load(fresh = false) { const generation = ++loadGeneration const requestedLocale = docLocale.value const path = currentPath.value const selectedProject = project.value loading.value = true document.value = null - failed.value = false + failure.value = null + headings.value = [] + restoreAnchor = true showingEnglishFallback.value = false try { saveDocumentLocale(requestedLocale) - const [translated, english] = await Promise.all([ - getDocuments(requestedLocale), requestedLocale === 'en' ? Promise.resolve([]) : getDocuments('en'), - ]) - let loadedDocument: DocumentView | null = null - let fallback = false - if (path) { - try { - loadedDocument = await getDocument(path, requestedLocale) - } catch (error) { - if (requestedLocale === 'en' || !(error instanceof HTTPError) || error.status !== 404) throw error - loadedDocument = await getDocument(path, 'en') - fallback = true - } - } + const result = await documentLoader.load(path, requestedLocale, fresh) if (generation !== loadGeneration) return - documents.value = projectDocuments(translated, english, selectedProject) - document.value = loadedDocument - showingEnglishFallback.value = fallback - } catch { + documents.value = projectDocuments(result.translated, result.english, selectedProject) + document.value = result.document + showingEnglishFallback.value = result.englishFallback + } catch (error) { if (generation !== loadGeneration) return - failed.value = true + failure.value = isNotFound(error) ? 'not-found' : 'unavailable' document.value = null } finally { if (generation === loadGeneration) loading.value = false @@ -131,6 +126,19 @@ function onScroll() { onMounted(() => window.addEventListener('scroll', onScroll, { passive: true })) onBeforeUnmount(() => { window.removeEventListener('scroll', onScroll); cancelAnimationFrame(scrollFrame) }) watch([document, readingMode], async () => { await nextTick(); updateActiveHeading() }) +async function onHeadings(items: DocumentHeading[]) { + const loaded = document.value + headings.value = items.filter(item => item.level >= 2 && item.level <= 4) + await nextTick() + if (loaded !== document.value) return + if (restoreAnchor) { + restoreAnchor = false + let anchor = '' + try { anchor = decodeURIComponent(route.hash.slice(1)) } catch { /* Ignore malformed fragments. */ } + if (anchor) Array.from(article.value?.querySelectorAll('[id]') ?? []).find(element => element.id === anchor)?.scrollIntoView({ block: 'start' }) + } + updateActiveHeading() +} function changeDocumentLocale(event: Event) { const value = (event.target as HTMLSelectElement).value @@ -143,8 +151,8 @@ function changeDocumentLocale(event: Event) { watchEffect(() => { if (!document.value) { applyPageSEO({ - title: failed.value ? 'Page not found · Wave' : `${projectName.value} Documentation · Wave`, - description: failed.value ? 'The requested document could not be loaded.' : project.value === 'stdlib' ? t('docs.stdlibLead') : project.value === 'whale' ? t('docs.whaleLead') : t('docs.lead'), + title: failed.value ? `${t(failure.value === 'not-found' ? 'docs.notFound' : 'docs.unavailable')} · Wave` : `${projectName.value} Documentation · Wave`, + description: failed.value ? t(failure.value === 'not-found' ? 'docs.notFoundHelp' : 'docs.unavailable') : project.value === 'stdlib' ? t('docs.stdlibLead') : project.value === 'whale' ? t('docs.whaleLead') : t('docs.lead'), locale: docLocale.value, path: route.path, noIndex: failed.value, schema: { '@type': 'CollectionPage' }, alternates: !currentPath.value ? [...documentLocales.map((item) => ({ locale: item.id, path: documentationCatalog(item.id, project.value) })), { locale: 'x-default', path: documentationCatalog('en', project.value) }] : [], @@ -196,7 +204,10 @@ watchEffect(() => {
-
+
+

{{ t('docs.notFound') }}

{{ t('docs.notFoundHelp') }}

{{ t('docs.browse') }} +
+