Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/frontend-editor-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions docs/document-authoring.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
3 changes: 2 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
6 changes: 5 additions & 1 deletion frontend/src/components/MarkdownContent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement | null>(null)
const slotPrefix = `wave-example-${useId()}`
const targets = shallowRef<Array<{ element: HTMLElement; example: DocumentExample }>>([])
Expand Down Expand Up @@ -72,6 +73,9 @@ async function mountExamples() {
targets.value = []
await nextTick()
if (current !== generation || !article.value) return
emit('headings', Array.from(article.value.querySelectorAll<HTMLElement>('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<HTMLElement>('[data-wave-playground]'))
targets.value = result.slots.flatMap((example, index) => {
const element = placeholders.find(item => item.dataset.wavePlayground === `${slotPrefix}-${index}`)
Expand Down
6 changes: 6 additions & 0 deletions frontend/src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,9 @@ const messages: Record<Locale, Record<string, string>> = {
'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.',
Expand Down Expand Up @@ -1083,6 +1086,9 @@ const messages: Record<Locale, Record<string, string>> = {
'docs.previous': '이전 문서',
'docs.next': '다음 문서',
'docs.noResults': '검색 조건과 일치하는 문서가 없습니다.',
'docs.notFound': '문서를 찾을 수 없습니다',
'docs.notFoundHelp': '존재하지 않거나 더 이상 게시되지 않은 문서입니다. 문서 목록에서 다른 페이지를 찾아보세요.',
'docs.unavailable': '문서를 불러오지 못했습니다. 다시 시도해 주세요.',
'docs.languageSelector': '문서 언어',
'docs.projectSelector': '문서 프로젝트',
'docs.whaleLead': 'Whale 안내와 참조 문서입니다.',
Expand Down
65 changes: 38 additions & 27 deletions frontend/src/pages/DocsPage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -24,7 +26,12 @@ const article = ref<HTMLElement | null>(null)
const mobileNavigation = ref<HTMLDetailsElement | null>(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<DocumentHeading[]>([])
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'))

Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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<HTMLElement>('[id]') ?? []).find(element => element.id === anchor)?.scrollIntoView({ block: 'start' })
}
updateActiveHeading()
}

function changeDocumentLocale(event: Event) {
const value = (event.target as HTMLSelectElement).value
Expand All @@ -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) }] : [],
Expand Down Expand Up @@ -196,7 +204,10 @@ watchEffect(() => {
</header>

<div v-if="loading" class="docs-width docs-loading"><UiSkeletonRows :rows="8" /></div>
<div v-else-if="failed" class="docs-width docs-loading"><UiInlineState :message="t('common.loadError')" :action="t('common.retry')" @action="load" /></div>
<div v-else-if="failure === 'not-found'" class="docs-width docs-error-page">
<h1>{{ t('docs.notFound') }}</h1><p>{{ t('docs.notFoundHelp') }}</p><RouterLink :to="catalogBase">{{ t('docs.browse') }}</RouterLink>
</div>
<div v-else-if="failed" class="docs-width docs-loading"><UiInlineState :message="t('docs.unavailable')" :action="t('common.retry')" @action="load(true)" /></div>

<div v-else class="docs-width docs-reader-layout" :class="{ 'docs-catalog-layout': !document }">
<aside class="docs-tree docs-tree-desktop">
Expand All @@ -222,7 +233,7 @@ watchEffect(() => {
<summary>{{ t('docs.contents') }}<ChevronRight :size="14" aria-hidden="true" /></summary>
<nav :aria-label="t('docs.contents')"><a v-for="heading in headings" :key="heading.anchor" :href="`#${heading.anchor}`" :class="`level-${heading.level}`">{{ heading.text }}</a></nav>
</details>
<div class="document-content"><MarkdownContent :source="document.markdown" runnable /></div>
<div class="document-content"><MarkdownContent :source="document.markdown" runnable @headings="onHeadings" /></div>
<nav class="document-pagination" :aria-label="t('docs.navigation')">
<RouterLink v-if="previous" :to="`${docBase}/${previous.path}`"><small><ArrowLeft :size="14" aria-hidden="true" />{{ t('docs.previous') }}</small><span>{{ previous.title }}</span></RouterLink><span v-else />
<RouterLink v-if="next" :to="`${docBase}/${next.path}`"><small>{{ t('docs.next') }}<ArrowRight :size="14" aria-hidden="true" /></small><span>{{ next.title }}</span></RouterLink>
Expand Down
40 changes: 40 additions & 0 deletions frontend/src/services/documentLinks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
export type DocumentLinkEntry = { locale: string; path: string; anchors: Set<string>; links: string[] }

// Validate local documentation URLs only; no external network access is needed.
export function validateDocumentLinks(entries: DocumentLinkEntry[], locales: Set<string>, redirects: Record<string, string>) {
const documents = new Map<string, DocumentLinkEntry>()
const failures: string[] = []
for (const entry of entries) {
const key = `${entry.locale}/${entry.path}`
if (documents.has(key)) failures.push(`${key}: duplicate document path`)
documents.set(key, entry)
}
for (const entry of entries) {
for (const href of entry.links) {
const markdownFile = !href.startsWith('/') && /^(?![a-z]+:).*\.md(?:[#?]|$)/i.test(href)
if (!href.startsWith('#') && !href.startsWith('/docs/') && !markdownFile) continue
const prefix = `${entry.locale}/${entry.path}: ${href}`
try {
const url = new URL(href, `https://documentation.invalid/docs/${entry.locale}/${entry.path}`)
const parts = decodeURIComponent(url.pathname).split('/').filter(Boolean)
if (parts[0] !== 'docs') { failures.push(`${prefix}: target is outside documentation`); continue }
const locale = parts[1]
if (!locales.has(locale)) { failures.push(`${prefix}: unsupported locale`); continue }
let path = parts.slice(2).join('/')
if (/\.md$/i.test(path)) { failures.push(`${prefix}: use a /docs/ URL instead of a Markdown file link`); continue }
path = redirects[path] ?? path
const anchor = decodeURIComponent(url.hash.slice(1))
if (['', 'stdlib', 'whale'].includes(path)) {
if (anchor) failures.push(`${prefix}: catalogue anchors are not supported`)
continue
}
const target = documents.get(`${locale}/${path}`) ?? documents.get(`en/${path}`)
if (!target) failures.push(`${prefix}: document not found`)
else if (anchor && !target.anchors.has(anchor)) failures.push(`${prefix}: heading not found`)
} catch {
failures.push(`${prefix}: invalid URL or fragment encoding`)
}
}
}
return failures
}
50 changes: 50 additions & 0 deletions frontend/src/services/documentLoader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { DocumentLocale, DocumentSummary, DocumentView } from './http.ts'

type Transport = {
list: (locale: DocumentLocale) => Promise<DocumentSummary[]>
get: (path: string, locale: DocumentLocale) => Promise<DocumentView>
isNotFound: (error: unknown) => boolean
}

// Only successful public catalogues are cached. Locale keys are bounded by the
// supported registry; errors never prevent the next request from retrying.
export function createDocumentLoader(transport: Transport, now = Date.now) {
const catalogs = new Map<DocumentLocale, {
value?: DocumentSummary[]
expires: number
pending?: Promise<DocumentSummary[]>
}>()
function catalog(locale: DocumentLocale, fresh: boolean) {
const previous = catalogs.get(locale)
if (previous?.pending) return previous.pending
if (!fresh && previous?.value && previous.expires > now()) return Promise.resolve(previous.value)
const entry: { value?: DocumentSummary[]; expires: number; pending?: Promise<DocumentSummary[]> } = { expires: 0 }
entry.pending = Promise.resolve().then(() => transport.list(locale)).then(items => {
entry.value = items
entry.expires = now() + 60_000
return items
}).catch(error => {
catalogs.delete(locale)
throw error
}).finally(() => { entry.pending = undefined })
catalogs.set(locale, entry)
return entry.pending
}
async function detail(path: string, locale: DocumentLocale) {
if (!path) return { document: null, englishFallback: false }
try {
return { document: await transport.get(path, locale), englishFallback: false }
} catch (error) {
if (locale === 'en' || !transport.isNotFound(error)) throw error
return { document: await transport.get(path, 'en'), englishFallback: true }
}
}
return {
async load(path: string, locale: DocumentLocale, fresh = false) {
const [translated, english, result] = await Promise.all([
catalog(locale, fresh), locale === 'en' ? Promise.resolve([]) : catalog('en', fresh), detail(path, locale),
])
return { ...result, translated, english }
},
}
}
9 changes: 7 additions & 2 deletions frontend/src/services/documentMarkdown.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Marked, Renderer, type Token, type Tokens } from 'marked'
import { gfmHeadingId } from 'marked-gfm-heading-id'
import { getHeadingList, gfmHeadingId } from 'marked-gfm-heading-id'
import manifest from '../../../wavedoc/examples.json' with { type: 'json' }

export type DocumentHeading = { anchor: string; level: number; text: string }
export type DocumentExample = { source: string; stdin?: string }
type ExampleMetadata = { id: string; stdin?: string }
const examples = new Map<string, ExampleMetadata>(manifest.map(item => [item.id, item]))
Expand All @@ -13,6 +14,7 @@ export function renderDocumentMarkdown(source: string, options: {
renderCode: (text: string, language?: string) => string
}) {
const slots: DocumentExample[] = []
const links: string[] = []
const ids = new WeakMap<Tokens.Code, string>()
// Only an immediately preceding marker supplies metadata. Visit nested lists
// and quotes as well, while keeping the full document in a single parse so
Expand Down Expand Up @@ -44,7 +46,10 @@ export function renderDocumentMarkdown(source: string, options: {
}
const parser = new Marked(gfmHeadingId(), {
async: false, gfm: true, breaks: false, renderer,
walkTokens(token) { if (token.type === 'link') links.push(token.href) },
hooks: { processAllTokens(tokens) { annotate(tokens); return tokens } },
})
return { html: parser.parse(source) as string, slots }
const html = parser.parse(source) as string
const headings: DocumentHeading[] = getHeadingList().map(({ id, level, raw }) => ({ anchor: id, level, text: raw }))
return { html, slots, headings, links }
}
4 changes: 4 additions & 0 deletions frontend/src/ui/service-pages.css
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,10 @@
.docs-search input { min-width: 0; width: 100%; padding: 6px 0; border: 0; outline: 0; background: transparent; color: var(--wave-text); font-size: 13px; }
.docs-search input::placeholder { color: var(--wave-text-muted); }
.docs-loading { padding: 32px 0; }
.docs-error-page { padding: 48px 0 72px; }
.docs-error-page h1 { font-size: 28px; }
.docs-error-page p { color: var(--wave-text-secondary); }
.docs-error-page a { color: var(--wave-accent); }
.docs-reader-layout { display: grid; grid-template-columns: 258px minmax(0, 1fr) 216px; align-items: start; column-gap: 36px; }
.docs-catalog-layout { grid-template-columns: 258px minmax(0, 1fr); }
.docs-tree, .docs-toc { position: sticky; top: 24px; max-height: calc(100dvh - 48px); overflow-y: auto; scrollbar-width: thin; }
Expand Down
Loading
Loading