ヘルプを Wiki から分離 (#424) (#430)

画面上でのテストは完了.
移行にす早さが求められるので,準備ができたらマージする.

Reviewed-on: #430
Co-authored-by: miteruzo <miteruzo@naver.com>
このコミットはプルリクエスト #430 でマージされました。
このコミットが含まれているのは:
2026-10-13 12:25:11 +09:00
committed by みてるぞ
コミット e44887cf15
85個のファイルの変更、4126行の追加、764行の削除
+2
ファイルの表示
@@ -22,3 +22,5 @@ dist-ssr
*.njsproj
*.sln
*.sw?
/help
生成ファイル
+4 -43
ファイルの表示
@@ -38,6 +38,7 @@
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.3.0",
"unist-util-visit-parents": "^6.0.1",
"yaml": "^2.9.1",
"zustand": "^5.0.8"
},
"devDependencies": {
@@ -2060,9 +2061,6 @@
"arm"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2077,9 +2075,6 @@
"arm"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2094,9 +2089,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2111,9 +2103,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2128,9 +2117,6 @@
"loong64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2145,9 +2131,6 @@
"loong64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2162,9 +2145,6 @@
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2179,9 +2159,6 @@
"ppc64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2196,9 +2173,6 @@
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2213,9 +2187,6 @@
"riscv64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2230,9 +2201,6 @@
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2247,9 +2215,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2264,9 +2229,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -9114,10 +9076,9 @@
"license": "ISC"
},
"node_modules/yaml": {
"version": "2.8.3",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz",
"integrity": "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg==",
"dev": true,
"version": "2.9.1",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz",
"integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==",
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
+1
ファイルの表示
@@ -42,6 +42,7 @@
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.3.0",
"unist-util-visit-parents": "^6.0.1",
"yaml": "^2.9.1",
"zustand": "^5.0.8"
},
"devDependencies": {
+112
ファイルの表示
@@ -0,0 +1,112 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { generateHelpAssets } from './help-assets'
import type { ArticleMeta, HelpChange, HelpSearchEntry, HelpTitleIndex } from '@/lib/help'
vi.hoisted (() => {
vi.stubGlobal ('Uint8Array', Object.getPrototypeOf (new TextEncoder ().encode ('')).constructor)
})
afterAll (() => vi.unstubAllGlobals ())
const readAsset = <T,> (modules: Map<string, string>, name: string): T => {
const source = modules.get (`virtual:help/${ name }`)!
const argument = source.slice ('export default JSON.parse('.length, -1)
return JSON.parse (JSON.parse (argument))
}
describe ('Build-time Help assets', () => {
let root: string
beforeEach (async () => {
root = await mkdtemp (path.join (tmpdir (), 'btrc-help-assets-'))
})
afterEach (async () => {
await rm (root, { recursive: true, force: true })
})
const writeArticle = async (
identifier: string,
editions: Record<string, string>,
current = '2026-10-02.10',
) => {
const articleRoot = path.join (root, identifier)
const editionRoot = path.join (articleRoot, 'editions', 'ja')
await mkdir (editionRoot, { recursive: true })
await writeFile (path.join (articleRoot, 'article.yml'), [
`identifier: ${ identifier }`, 'canonical_language: ja', 'title: stale YAML title',
'languages:', ' ja:', ` current_edition: ${ current }`].join ('\n'))
await Promise.all (Object.entries (editions).map (([edition, source]) =>
writeFile (path.join (editionRoot, `${ edition }.mdx`), source)))
}
it ('generates current search and ordered published history from each edition H1', async () => {
await writeArticle ('guide', {
'2026-10-01': '# 旧ホーム\n\n過去本文',
'2026-10-02': '# ホーム\n\n最初の同日版',
'2026-10-02.2': '# ホーム\n\n第二版',
'2026-10-02.3': '# ホーム\n\n第三版',
'2026-10-02.10': '\uFEFF# 最新ホーム\r\n\r\n現在本文\r\n# 別見出し',
'2026-10-02.11': '# 未公開\n\n検索に含めない' })
const { modules } = await generateHelpAssets (root)
const articles = readAsset<Record<string, ArticleMeta>> (modules, 'articles')
expect (articles.guide.languages.ja).toEqual ({
currentEdition: '2026-10-02.10', publishedEditions: [
'2026-10-01', '2026-10-02', '2026-10-02.2', '2026-10-02.3', '2026-10-02.10'] })
expect (readAsset<Record<string, HelpSearchEntry[]>> (modules, 'search').ja).toEqual ([{
identifier: 'guide', edition: '2026-10-02.10', title: '最新ホーム',
body: '\r\n現在本文\r\n# 別見出し' }])
const changes = readAsset<Record<string, HelpChange[]>> (modules, 'changes').ja
expect (changes.map (row => [row.edition, row.title, row.pred, row.change, row.date]))
.toEqual ([
['2026-10-02.10', '最新ホーム', '2026-10-02.3', 'update', '2026-10-02'],
['2026-10-02.3', 'ホーム', '2026-10-02.2', 'update', '2026-10-02'],
['2026-10-02.2', 'ホーム', '2026-10-02', 'update', '2026-10-02'],
['2026-10-02', 'ホーム', '2026-10-01', 'update', '2026-10-02'],
['2026-10-01', '旧ホーム', null, 'new', '2026-10-01']])
const titles = readAsset<Record<string, HelpTitleIndex>> (modules, 'titles').ja
expect (titles).toEqual ({ '旧ホーム': ['guide'], 'ホーム': ['guide'],
'最新ホーム': ['guide'] })
expect (modules.get ('virtual:help/loaders')).not.toContain ('2026-10-02.11')
expect (modules.get ('virtual:help/loaders')).toContain ('2026-10-02.10.mdx?raw')
expect (modules.get ('virtual:help/search')).not.toContain ('import(')
})
it ('retains ambiguous title identifiers and normalises width and case', async () => {
await writeArticle ('alpha', { '2026-10-02': '# HOME\n本文' }, '2026-10-02')
await writeArticle ('beta', { '2026-10-02': '# Home\n本文' }, '2026-10-02')
const { modules } = await generateHelpAssets (root)
expect (readAsset<Record<string, HelpTitleIndex>> (modules, 'titles').ja.home)
.toEqual (['alpha', 'beta'])
expect (readAsset<Record<string, HelpChange[]>> (modules, 'changes').ja
.map (row => row.identifier)).toEqual (['alpha', 'beta'])
})
it ('rejects missing current files during generation', async () => {
await writeArticle ('guide', { '2026-10-02': '# ホーム' })
await expect (generateHelpAssets (root)).rejects.toThrow ('Missing current Help edition')
})
it.each (['本文\n# 遅い見出し', '# \n本文']) (
'rejects missing leading H1 at build time: %s', async source => {
await writeArticle ('guide', { '2026-10-02.10': source })
await expect (generateHelpAssets (root)).rejects.toThrow ('Missing leading Help H1')
})
it ('rejects absent canonical metadata instead of generating incomplete assets', async () => {
await writeArticle ('guide', { '2026-10-02.10': '# ホーム' })
await writeFile (path.join (root, 'guide', 'article.yml'),
'identifier: guide\nlanguages:\n ja:\n current_edition: 2026-10-02.10')
await expect (generateHelpAssets (root)).rejects.toThrow ('Invalid Help metadata')
})
it ('rejects an empty Help checkout', async () => {
await expect (generateHelpAssets (root)).rejects.toThrow ('No Help articles found')
})
})
+192
ファイルの表示
@@ -0,0 +1,192 @@
import { readFile, readdir } from 'node:fs/promises'
import path from 'node:path'
import { normalizePath as normalisePath } from 'vite'
import { parse as parseYAML } from 'yaml'
import type { Plugin } from 'vite'
type Language = { currentEdition: string; publishedEditions: string[] }
type Article = {
identifier: string
canonicalLanguage: string
languages: Record<string, Language> }
type Text = { title: string; body: string }
type SearchEntry = Text & { identifier: string; edition: string }
type Change = {
identifier: string
edition: string
title: string
pred: string | null
change: 'new' | 'update'
date: string }
type RawArticle = {
identifier: string
canonical_language: string
languages: Record<string, { current_edition: string }> }
const prefix = 'virtual:help/'
const compareEditions = (a: string, b: string): number => {
const [dateA, revisionA = '1'] = a.split ('.')
const [dateB, revisionB = '1'] = b.split ('.')
return dateA.localeCompare (dateB) || Number (revisionA) - Number (revisionB)
}
const validateEdition = (edition: string): void => {
const [date, revision = '1'] = edition.split ('.')
if (!(/^\d{4}-\d{2}-\d{2}(?:\.[1-9]\d*)?$/.test (edition))
|| new Date (date).toISOString ().slice (0, 10) !== date
|| !(Number.isSafeInteger (Number (revision))))
throw new Error (`Invalid Help edition: ${ edition }`)
}
export const generateHelpAssets = async (
root: string,
): Promise<{ modules: Map<string, string>; files: string[] }> => {
const modules = new Map<string, string> ()
const files: string[] = [root]
const articles: Record<string, Article> = Object.create (null)
const search: Record<string, SearchEntry[]> = Object.create (null)
const changes: Record<string, Change[]> = Object.create (null)
const titles: Record<string, Record<string, string[]>> = Object.create (null)
const components: string[] = []
const sources: string[] = []
const texts: string[] = []
const directories = (await readdir (root, { withFileTypes: true }))
.filter (entry => entry.isDirectory () && !(entry.name.startsWith ('.')))
.sort ((a, b) => a.name.localeCompare (b.name))
for (const directory of directories)
{
const articlePath = path.join (root, directory.name, 'article.yml')
files.push (articlePath)
const raw = parseYAML (await readFile (articlePath, 'utf8')) as RawArticle | null
if (raw == null || raw.identifier !== directory.name
|| typeof raw.canonical_language !== 'string'
|| raw.languages == null || typeof raw.languages !== 'object'
|| !(Object.hasOwn (raw.languages, raw.canonical_language)))
throw new Error (`Invalid Help metadata: ${ articlePath }`)
const article: Article = {
identifier: raw.identifier,
canonicalLanguage: raw.canonical_language,
languages: Object.create (null) }
articles[raw.identifier] = article
for (const [language, metadata] of Object.entries (raw.languages))
{
if (!(/^[a-zA-Z0-9-]+$/.test (language))
|| typeof metadata?.current_edition !== 'string')
throw new Error (`Invalid Help language: ${ articlePath }/${ language }`)
const currentEdition = metadata.current_edition
validateEdition (currentEdition)
const editionRoot = path.join (root, directory.name, 'editions', language)
files.push (editionRoot)
const editions = (await readdir (editionRoot)).filter (name => name.endsWith ('.mdx'))
.map (name => name.slice (0, -4))
editions.forEach (validateEdition)
if (!(editions.includes (currentEdition)))
throw new Error (`Missing current Help edition: ${ editionRoot }/${ currentEdition }`)
const publishedEditions = editions
.filter (edition => compareEditions (edition, currentEdition) <= 0)
.sort (compareEditions)
article.languages[language] = { currentEdition, publishedEditions }
search[language] ??= []
changes[language] ??= []
titles[language] ??= Object.create (null)
for (const [index, edition] of publishedEditions.entries ())
{
const sourcePath = path.join (editionRoot, `${ edition }.mdx`)
files.push (sourcePath)
const mdx = (await readFile (sourcePath, 'utf8')).replace (/^\uFEFF/, '')
const heading = mdx.match (/^# +([^\r\n]+)(?:\r?\n|$)/)
if (heading == null || !(heading[1].trim ()))
throw new Error (`Missing leading Help H1: ${ sourcePath }`)
const text = { title: heading[1].trim (), body: mdx.slice (heading[0].length) }
const key = JSON.stringify (`${ raw.identifier }/${ language }/${ edition }`)
const textId = `${ prefix }text/${ raw.identifier }/${ language }/${ edition }`
const componentId = JSON.stringify (normalisePath (sourcePath))
const sourceId = JSON.stringify (normalisePath (sourcePath) + '?raw')
modules.set (textId, `export default ${ JSON.stringify (text) }`)
texts.push (`${ key }: () => import(${ JSON.stringify (textId) })`)
components.push (`${ key }: () => import(${ componentId })`)
sources.push (`${ key }: () => import(${ sourceId })`)
if (edition === currentEdition)
search[language].push ({ identifier: raw.identifier, edition, ...text })
changes[language].push ({ identifier: raw.identifier, edition, title: text.title,
pred: publishedEditions[index - 1] ?? null,
change: index === 0 ? 'new' : 'update', date: edition.split ('.')[0] })
const title = text.title.trim ().normalize ('NFKC').toLowerCase ()
const identifiers = titles[language][title] ??= []
if (!(identifiers.includes (raw.identifier)))
identifiers.push (raw.identifier)
}
}
}
if (Object.keys (articles).length === 0)
throw new Error (`No Help articles found: ${ root }`)
Object.values (changes).forEach (rows => rows.sort ((a, b) =>
compareEditions (b.edition, a.edition) || a.identifier.localeCompare (b.identifier)))
for (const [name, data] of Object.entries ({ articles, search, changes, titles }))
{
modules.set (`${ prefix }${ name }`,
`export default JSON.parse(${ JSON.stringify (JSON.stringify (data)) })`)
}
modules.set (`${ prefix }loaders`, [
`export const components = { ${ components.join (',\n') } };`,
`export const sources = { ${ sources.join (',\n') } };`,
`export const texts = { ${ texts.join (',\n') } };`].join ('\n'))
return { modules, files }
}
export const helpAssets = (): Plugin => {
const state: { root: string; data?: ReturnType<typeof generateHelpAssets> } = { root: '' }
const data = () => state.data ??= generateHelpAssets (state.root)
return {
name: 'help-assets',
configResolved (config) {
state.root = path.resolve (config.root, 'help')
},
async buildStart () {
state.data = generateHelpAssets (state.root)
const generated = await data ()
generated.files.forEach (file => this.addWatchFile (file))
},
resolveId (id) {
return id.startsWith (prefix) ? `\0${ id }` : null
},
async load (id) {
if (!(id.startsWith (`\0${ prefix }`)))
return null
const source = (await data ()).modules.get (id.slice (1))
if (source == null)
throw new Error (`Unknown Help asset: ${ id.slice (1) }`)
return source
},
configureServer (server) {
server.watcher.add (state.root)
server.watcher.on ('all', (_event, file) => {
if (!(file.startsWith (state.root + path.sep)) || !(/\.(mdx|yml)$/.test (file)))
return
state.data = undefined
for (const module of server.moduleGraph.idToModuleMap.values ())
{
if (module.id?.startsWith (`\0${ prefix }`))
server.moduleGraph.invalidateModule (module)
}
server.ws.send ({ type: 'full-reload' })
})
} }
}
+56 -80
ファイルの表示
@@ -15,7 +15,6 @@ import { Toaster } from '@/components/ui/toaster'
import { apiPost, isApiError } from '@/lib/api'
import { applyClientAnimationMode,
applyClientAppearance,
type ClientAnimationMode,
fetchUserThemeSlots,
fetchUserSettings,
getClientThemeMode,
@@ -25,7 +24,6 @@ import { applyClientAnimationMode,
seedClientThemeMode } from '@/lib/settings'
import { useClientBehaviourSettings } from '@/lib/useClientBehaviourSettings'
import { UnsavedChangesGuardProvider } from '@/lib/useUnsavedChangesGuard'
import { KeyboardShortcutsProvider } from '@/lib/useKeyboardShortcuts'
import DeerjikistDetailPage from '@/pages/deerjikists/DeerjikistDetailPage'
import MaterialBasePage from '@/pages/materials/MaterialBasePage'
@@ -34,12 +32,15 @@ import MaterialHistoryPage from '@/pages/materials/MaterialHistoryPage'
import MaterialListPage from '@/pages/materials/MaterialListPage'
import MaterialNewPage from '@/pages/materials/MaterialNewPage'
import MaterialSyncSuppressionsPage from '@/pages/materials/MaterialSyncSuppressionsPage'
// import MaterialSearchPage from '@/pages/materials/MaterialSearchPage'
import MorePage from '@/pages/MorePage'
import GekanatorPage from '@/pages/GekanatorPage'
import NicoTagListPage from '@/pages/tags/NicoTagListPage'
import NotFound from '@/pages/NotFound'
import TOSPage from '@/pages/TOSPage.mdx'
import HelpDetailPage from '@/pages/help/HelpDetailPage'
import HelpChangesPage from '@/pages/help/HelpChangesPage'
import HelpDiffPage from '@/pages/help/HelpDiffPage'
import HelpListPage from '@/pages/help/HelpListPage'
import PostDetailPage from '@/pages/posts/PostDetailPage'
import PostHistoryPage from '@/pages/posts/PostHistoryPage'
import PostNewPage from '@/pages/posts/PostNewPage'
@@ -60,90 +61,62 @@ import WikiSearchPage from '@/pages/wiki/WikiSearchPage'
import type { Dispatch, FC, SetStateAction } from 'react'
import type { ClientAnimationMode } from '@/lib/settings'
import type { User } from '@/types'
const RouteTransitionWrapper = ({ animationMode, user, setUser }: {
animationMode: ClientAnimationMode
user: User | null
setUser: Dispatch<SetStateAction<User | null>> }) => {
animationMode: ClientAnimationMode
user: User | null
setUser: Dispatch<SetStateAction<User | null>> }) => {
const location = useLocation ()
const routes = (
<Routes location={location}>
<Route path="/" element={<Navigate to="/posts" replace/>}/>
<Route path="/posts" element={<PostListPage/>}/>
<Route path="/posts/new" element={<PostNewPage user={user}/>}/>
<Route path="/posts/search" element={<PostSearchPage/>}/>
<Route path="/posts/:id" element={<PostDetailRoute user={user}/>}/>
<Route path="/posts/changes" element={<PostHistoryPage/>}/>
<Route path="/tags" element={<TagListPage/>}/>
<Route path="/tags/:id" element={<TagDetailPage/>}/>
<Route path="/tags/:id/deerjikists" element={<DeerjikistDetailPage/>}/>
<Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/>
<Route path="/nico/tags" element={<NicoTagListPage user={user}/>}/>
<Route path="/tags/changes" element={<TagHistoryPage/>}/>
<Route path="/theatres/:id" element={<TheatreDetailPage user={user}/>}/>
<Route path="/materials" element={<MaterialBasePage/>}>
<Route index element={<MaterialListPage/>}/>
<Route path="changes" element={<MaterialHistoryPage/>}/>
<Route path="new" element={<MaterialNewPage/>}/>
<Route path="suppressions" element={<MaterialSyncSuppressionsPage/>}/>
<Route path=":id" element ={<MaterialDetailPage/>}/>
</Route>
<Route path="/wiki" element={<WikiSearchPage/>}/>
<Route path="/wiki/:title" element={<WikiDetailPage/>}/>
<Route path="/wiki/new" element={<WikiNewPage user={user}/>}/>
<Route path="/wiki/:id/edit" element={<WikiEditPage user={user}/>}/>
<Route path="/wiki/:id/diff" element={<WikiDiffPage/>}/>
<Route path="/wiki/changes" element={<WikiHistoryPage/>}/>
<Route path="/help" element={<HelpListPage/>}/>
<Route path="/help/changes" element={<HelpChangesPage/>}/>
<Route path="/help/:identifier/diff" element={<HelpDiffPage/>}/>
<Route path="/help/:identifier" element={<HelpDetailPage/>}/>
<Route path="/users/settings" element={<SettingPage user={user} setUser={setUser}/>}/>
<Route path="/settings" element={<Navigate to="/users/settings" replace/>}/>
<Route path="/tos" element={<TOSPage/>}/>
<Route path="/gekanator" element={<GekanatorPage user={user}/>}/>
<Route path="/more" element={<MorePage/>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>)
if (animationMode === 'off')
{
return (
<Routes location={location}>
<Route path="/" element={<Navigate to="/posts" replace/>}/>
<Route path="/posts" element={<PostListPage/>}/>
<Route path="/posts/new" element={<PostNewPage user={user}/>}/>
<Route path="/posts/search" element={<PostSearchPage/>}/>
<Route path="/posts/:id" element={<PostDetailRoute user={user}/>}/>
<Route path="/posts/changes" element={<PostHistoryPage/>}/>
<Route path="/tags" element={<TagListPage/>}/>
<Route path="/tags/:id" element={<TagDetailPage/>}/>
<Route path="/tags/:id/deerjikists" element={<DeerjikistDetailPage/>}/>
<Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/>
<Route path="/nico/tags" element={<NicoTagListPage user={user}/>}/>
<Route path="/tags/changes" element={<TagHistoryPage/>}/>
<Route path="/theatres/:id" element={<TheatreDetailPage user={user}/>}/>
<Route path="/materials" element={<MaterialBasePage/>}>
<Route index element={<MaterialListPage/>}/>
<Route path="changes" element={<MaterialHistoryPage/>}/>
<Route path="new" element={<MaterialNewPage/>}/>
<Route path="suppressions" element={<MaterialSyncSuppressionsPage/>}/>
<Route path=":id" element ={<MaterialDetailPage/>}/>
</Route>
<Route path="/wiki" element={<WikiSearchPage/>}/>
<Route path="/wiki/:title" element={<WikiDetailPage/>}/>
<Route path="/wiki/new" element={<WikiNewPage user={user}/>}/>
<Route path="/wiki/:id/edit" element={<WikiEditPage user={user}/>}/>
<Route path="/wiki/:id/diff" element={<WikiDiffPage/>}/>
<Route path="/wiki/changes" element={<WikiHistoryPage/>}/>
<Route path="/users/settings" element={<SettingPage user={user} setUser={setUser}/>}/>
<Route path="/settings" element={<Navigate to="/users/settings" replace/>}/>
<Route path="/tos" element={<TOSPage/>}/>
<Route path="/gekanator" element={<GekanatorPage user={user}/>}/>
<Route path="/more" element={<MorePage/>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>)
}
return routes
return (
<AnimatePresence mode="wait">
<Routes location={location}>
<Route path="/" element={<Navigate to="/posts" replace/>}/>
<Route path="/posts" element={<PostListPage/>}/>
<Route path="/posts/new" element={<PostNewPage user={user}/>}/>
<Route path="/posts/search" element={<PostSearchPage/>}/>
<Route path="/posts/:id" element={<PostDetailRoute user={user}/>}/>
<Route path="/posts/changes" element={<PostHistoryPage/>}/>
<Route path="/tags" element={<TagListPage/>}/>
<Route path="/tags/:id" element={<TagDetailPage/>}/>
<Route path="/tags/:id/deerjikists" element={<DeerjikistDetailPage/>}/>
<Route path="/tags/nico" element={<NicoTagListPage user={user}/>}/>
<Route path="/nico/tags" element={<NicoTagListPage user={user}/>}/>
<Route path="/tags/changes" element={<TagHistoryPage/>}/>
<Route path="/theatres/:id" element={<TheatreDetailPage user={user}/>}/>
<Route path="/materials" element={<MaterialBasePage/>}>
<Route index element={<MaterialListPage/>}/>
<Route path="changes" element={<MaterialHistoryPage/>}/>
<Route path="new" element={<MaterialNewPage/>}/>
<Route path="suppressions" element={<MaterialSyncSuppressionsPage/>}/>
<Route path=":id" element ={<MaterialDetailPage/>}/>
</Route>
<Route path="/wiki" element={<WikiSearchPage/>}/>
<Route path="/wiki/:title" element={<WikiDetailPage/>}/>
<Route path="/wiki/new" element={<WikiNewPage user={user}/>}/>
<Route path="/wiki/:id/edit" element={<WikiEditPage user={user}/>}/>
<Route path="/wiki/:id/diff" element={<WikiDiffPage/>}/>
<Route path="/wiki/changes" element={<WikiHistoryPage/>}/>
<Route path="/users/settings" element={<SettingPage user={user} setUser={setUser}/>}/>
<Route path="/settings" element={<Navigate to="/users/settings" replace/>}/>
<Route path="/tos" element={<TOSPage/>}/>
<Route path="/gekanator" element={<GekanatorPage user={user}/>}/>
<Route path="/more" element={<MorePage/>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>
{routes}
</AnimatePresence>)
}
@@ -166,9 +139,9 @@ const RoutedApp: FC = () => {
() => (
animationMode === 'off'
? { duration: 0 }
: animationMode === 'reduced'
? { duration: .08, ease: 'linear' as const }
: { duration: .2, ease: 'easeOut' as const }
: (animationMode === 'reduced'
? { duration: .08, ease: 'linear' as const }
: { duration: .2, ease: 'easeOut' as const })
),
[animationMode],
)
@@ -285,10 +258,12 @@ const RoutedApp: FC = () => {
</DialogueProvider>)
}
const router = createBrowserRouter ([{
path: '*',
element: <RoutedApp/> }])
const App: FC = () => (
<>
<RouteBlockerOverlay/>
@@ -296,4 +271,5 @@ const App: FC = () => (
<RouterProvider router={router}/>
</>)
export default App
+115 -30
ファイルの表示
@@ -20,6 +20,7 @@ import type { FC, MouseEvent } from 'react'
import type { Material, Menu, MenuVisibleItem, Tag, User } from '@/types'
type Props = { user: User | null }
type NavDensity = 'auto' | 'comfortable' | 'compact'
export const menuOutline = (
@@ -40,6 +41,9 @@ export const menuOutline = (
const materialFlg = /^\/materials\/\d+/.test (pathName)
const helpVsbl = /\/help\/((?!changes)[^\/?]+)/.test (pathName)
const helpIdentifier = pathName.split ('/')[2] ?? ''
return [
{ name: '広場', to: '/posts', subMenu: [
{ name: '一覧', to: '/posts' },
@@ -71,7 +75,7 @@ export const menuOutline = (
visible: materialFlg && Boolean (material?.tag) },
{ name: '履歴', to: `/materials/changes?material_id=${ material?.id }`,
visible: materialFlg }] },
{ name: 'Wiki', to: '/wiki/ヘルプ:ホーム', base: '/wiki', subMenu: [
{ name: 'Wiki', to: '/wiki', subMenu: [
{ name: '検索', to: '/wiki' },
{ name: '新規', to: '/wiki/new', visible: editable },
{ name: '全体履歴', to: '/wiki/changes' },
@@ -82,6 +86,13 @@ export const menuOutline = (
{ name: '履歴', to: `/wiki/changes?id=${ wikiId }`, visible: wikiPageFlg },
{ name: '編輯', to: `/wiki/${ wikiId || wikiTitle }/edit`,
visible: wikiPageFlg && editable }] },
{ name: 'ヘルプ', to: '/help/home', base: '/help', subMenu: [
{ name: '検索', to: '/help' },
{ name: '全体履歴', to: '/help/changes' },
{ component: <Separator/>, visible: helpVsbl },
{ name: '履歴',
to: `/help/changes?identifier=${ helpIdentifier }`,
visible: helpVsbl }] },
{ name: 'おたのしみ', visible: false, subMenu: [
{ name: '上映会 (β)', to: '/theatres/1' },
{ name: 'グカネータ (β)', to: '/gekanator' }] },
@@ -104,6 +115,8 @@ const TopNav: FC<Props> = ({ user }) => {
const dirRef = useRef<(-1) | 1> (1)
const itemsRef = useRef<(HTMLAnchorElement | null)[]> ([])
const navRef = useRef<HTMLDivElement | null> (null)
const layoutRef = useRef<HTMLDivElement | null> (null)
const barRef = useRef<HTMLElement | null> (null)
const measure = (idx: number) => {
const nav = navRef.current
@@ -128,6 +141,8 @@ const TopNav: FC<Props> = ({ user }) => {
width: 0,
visible: false })
const [menuOpen, setMenuOpen] = useState (false)
const [desktop, setDesktop] = useState (false)
const [density, setDensity] = useState<NavDensity> ('auto')
const [moreVsbl, setMoreVsbl] = useState (false)
const [openItemIdx, setOpenItemIdx] = useState (-1)
const [wikiId, setWikiId] = useState<number | null> (WikiIdBus.get ())
@@ -194,15 +209,81 @@ const TopNav: FC<Props> = ({ user }) => {
const dir = dirRef.current
useLayoutEffect (() => {
const raf = requestAnimationFrame (() => measure (moreVsbl ? -1 : activeIdx))
const onResize = () => requestAnimationFrame (() => measure (moreVsbl ? -1 : activeIdx))
const layout = layoutRef.current
const bar = barRef.current
const primary = bar?.querySelector<HTMLElement> ('.top-nav-primary')
if (layout == null || bar == null || primary == null)
return
addEventListener ('resize', onResize)
return () => {
cancelAnimationFrame (raf)
removeEventListener ('resize', onResize)
const userLink = bar.querySelector<HTMLElement> ('.top-nav-user-desktop')
let raf = 0
let active = true
const update = () => {
if (!(window.matchMedia ('(min-width: 768px)').matches))
{
setDesktop (false)
setDensity ('auto')
return
}
// Measure the same desktop elements while the mobile layout is active.
layout.setAttribute ('data-measuring', '')
const previousDensity = layout.getAttribute ('data-density') ?? 'auto'
const fittingDensity = (() => {
try
{
for (const candidate of ['auto', 'comfortable', 'compact'] as const)
{
layout.setAttribute ('data-density', candidate)
const style = getComputedStyle (bar)
const required = primary.getBoundingClientRect ().width
+ (userLink?.getBoundingClientRect ().width ?? 0)
+ parseFloat (style.paddingLeft) + parseFloat (style.paddingRight)
+ (userLink == null ? 0 : parseFloat (style.columnGap))
if (required <= bar.clientWidth)
return candidate
}
return null
}
finally
{
layout.setAttribute ('data-density', previousDensity)
layout.removeAttribute ('data-measuring')
}
}) ()
setDensity (fittingDensity ?? 'compact')
setDesktop (fittingDensity != null)
if (fittingDensity != null)
measure (moreVsbl ? -1 : activeIdx)
}
})
const schedule = () => {
if (!(active))
return
cancelAnimationFrame (raf)
raf = requestAnimationFrame (update)
}
const observer =
typeof ResizeObserver === 'undefined' ? null : new ResizeObserver (schedule)
observer?.observe (bar)
observer?.observe (primary)
if (userLink != null)
observer?.observe (userLink)
update ()
addEventListener ('resize', schedule)
document.fonts?.addEventListener ('loadingdone', schedule)
void document.fonts?.ready.then (schedule)
return () => {
active = false
cancelAnimationFrame (raf)
observer?.disconnect ()
removeEventListener ('resize', schedule)
document.fonts?.removeEventListener ('loadingdone', schedule)
}
}, [activeIdx, moreVsbl, desktop, density, user?.name])
useEffect (() => {
const unsubscribe = WikiIdBus.subscribe (setWikiId)
@@ -215,19 +296,22 @@ const TopNav: FC<Props> = ({ user }) => {
}, [activeIdx, location])
return (
<>
<nav className="top-nav-root px-3 flex justify-between items-center w-full">
<div className="flex items-center gap-2 h-12">
<div ref={layoutRef} className="top-nav-layout w-full min-w-0 shrink-0"
data-desktop={desktop} data-density={density}>
<nav ref={barRef}
className="top-nav-root top-nav-bar flex justify-between items-center w-full">
<div className="top-nav-primary flex shrink-0 items-center h-12">
<PrefetchLink
to="/posts"
className="top-nav-brand-link mx-4 text-xl font-bold"
className="top-nav-brand-link shrink-0 whitespace-nowrap font-bold"
onClick={() => {
scroll (0, 0)
}}>
ぼざクリ タグ広場
</PrefetchLink>
<div ref={navRef} className="relative hidden md:flex h-12 items-center">
<div ref={navRef}
className="top-nav-desktop-menu relative shrink-0 h-12 items-center">
<div aria-hidden
className={cn ('absolute inset-y-0 h-12',
'top-nav-highlight',
@@ -239,6 +323,7 @@ const TopNav: FC<Props> = ({ user }) => {
{visibleMenu.map ((item, i) => (
<motion.div
key={item.to}
className="shrink-0 whitespace-nowrap"
{...(animationsOff
? { }
: { layoutId: `menu-${ item.name }` })}
@@ -252,7 +337,7 @@ const TopNav: FC<Props> = ({ user }) => {
ref={(el: (HTMLAnchorElement | null)) => {
itemsRef.current[i] = el
}}
className={cn ('top-nav-menu-link relative z-10 flex h-full items-center px-5',
className={cn ('top-nav-menu-link relative z-10 flex h-full items-center',
(i === openItemIdx) && 'font-bold')}>
{item.name}
</PrefetchLink>
@@ -267,7 +352,8 @@ const TopNav: FC<Props> = ({ user }) => {
setMoreVsbl (true)
measure (-1)
}}
className={cn ('top-nav-menu-link relative z-10 flex h-full items-center px-5',
className={cn ('top-nav-menu-link relative z-10 flex h-full items-center',
'shrink-0 whitespace-nowrap',
(openItemIdx < 0 || moreVsbl) && 'font-bold')}>
その他 &raquo;
</PrefetchLink>
@@ -278,7 +364,8 @@ const TopNav: FC<Props> = ({ user }) => {
<button
type="button"
className="top-nav-mobile-toggle md:hidden ml-auto border-0 bg-transparent pr-4"
className="top-nav-mobile-toggle shrink-0 whitespace-nowrap
ml-auto border-0 bg-transparent pr-4"
onClick={() => {
setMenuOpen (!(menuOpen))
}}>
@@ -291,7 +378,8 @@ const TopNav: FC<Props> = ({ user }) => {
key="submenu-shell"
{...(animationsOff ? { }
: { layout: true })}
className="relative z-20 hidden md:block overflow-hidden top-nav-submenu"
className="top-nav-desktop-submenu relative z-20 shrink-0
overflow-hidden top-nav-submenu"
animate={{ height: submenuHeight }}
onMouseLeave={() => {
if (moreVsbl)
@@ -305,7 +393,8 @@ const TopNav: FC<Props> = ({ user }) => {
? (
moreMenu.map ((item, i) => (
<div key={i} className="relative h-[40px]">
<div className="absolute inset-0 flex items-center px-3">
<div className="absolute inset-0 flex items-center px-3
overflow-x-auto whitespace-nowrap">
<motion.div
transition={topNavTransition}
{...(animationsOff
@@ -315,7 +404,7 @@ const TopNav: FC<Props> = ({ user }) => {
: { initial: { x: 40, y: -40, opacity: 0 },
animate: { x: 0, y: 0, opacity: 1 },
exit: { x: 40, y: -40, opacity: 0 } }))}
className="z-10 h-full flex items-center px-3 font-bold w-28">
className="z-10 h-full flex shrink-0 items-center px-3 font-bold w-28">
<h2>{item.name}</h2>
</motion.div>
{item.subMenu
@@ -363,7 +452,8 @@ const TopNav: FC<Props> = ({ user }) => {
<div className="relative h-[40px]">
{animationsOff
? (
<div className="absolute inset-0 flex items-center px-3">
<div className="absolute inset-0 flex items-center px-3
overflow-x-auto whitespace-nowrap">
{(visibleMenu[activeIdx]?.subMenu ?? [])
.filter (item => item.visible ?? true)
.map ((item, i) => (
@@ -392,7 +482,8 @@ const TopNav: FC<Props> = ({ user }) => {
variants={{ enter: (d: -1 | 1) => ({ y: d * 24, opacity: 0 }),
centre: { y: 0, opacity: 1 },
exit: (d: -1 | 1) => ({ y: (-d) * 24, opacity: 0 }) }}
className="absolute inset-0 flex items-center px-3"
className="absolute inset-0 flex items-center px-3
overflow-x-auto whitespace-nowrap"
initial="enter"
animate="centre"
exit="exit"
@@ -432,7 +523,7 @@ const TopNav: FC<Props> = ({ user }) => {
? (
menuOpen && (
<div
className={cn ('top-nav-root top-nav-mobile-menu flex flex-col md:hidden',
className={cn ('top-nav-root top-nav-mobile-menu flex flex-col',
'items-start')}>
<Separator/>
{visibleMenu.map ((item, i) => (
@@ -476,9 +567,6 @@ const TopNav: FC<Props> = ({ user }) => {
</Fragment>))}
<PrefetchLink
to="/more"
ref={(el: (HTMLAnchorElement | null)) => {
itemsRef.current[visibleMenu.length] = el
}}
className={cn ('top-nav-mobile-row w-full min-h-[40px] flex items-center pl-8',
((openItemIdx < 0)
&& 'top-nav-mobile-active font-bold'))}>
@@ -492,7 +580,7 @@ const TopNav: FC<Props> = ({ user }) => {
{menuOpen && (
<motion.div
key="spmenu"
className={cn ('top-nav-root top-nav-mobile-menu flex flex-col md:hidden',
className={cn ('top-nav-root top-nav-mobile-menu flex flex-col',
'items-start')}
variants={{ closed: { clipPath: 'inset(0 0 100% 0)',
height: 0 },
@@ -558,9 +646,6 @@ const TopNav: FC<Props> = ({ user }) => {
</Fragment>))}
<PrefetchLink
to="/more"
ref={(el: (HTMLAnchorElement | null)) => {
itemsRef.current[visibleMenu.length] = el
}}
className={cn ('top-nav-mobile-row w-full min-h-[40px] flex items-center pl-8',
((openItemIdx < 0)
&& 'top-nav-mobile-active font-bold'))}>
@@ -570,7 +655,7 @@ const TopNav: FC<Props> = ({ user }) => {
<Separator/>
</motion.div>)}
</AnimatePresence>)}
</>)
</div>)
}
export default TopNav
+3 -3
ファイルの表示
@@ -15,8 +15,8 @@ const TopNavUser: FC<Props> = ({ user, sp }) => {
return
const className = cn ((sp
? 'md:hidden w-full min-h-[40px] flex items-center pl-8'
: 'hidden md:block ml-auto pr-4'),
? 'top-nav-user-mobile w-full min-h-[40px] flex items-center pl-8'
: 'top-nav-user-desktop shrink-0 whitespace-nowrap ml-auto'),
'font-bold text-red-600 hover:text-red-400',
'dark:text-yellow-400 dark:hover:text-yellow-200')
@@ -30,4 +30,4 @@ const TopNavUser: FC<Props> = ({ user, sp }) => {
</>)
}
export default TopNavUser
export default TopNavUser
+233 -1
ファイルの表示
@@ -197,12 +197,244 @@ body
background: var(--top-nav-root-bg-mobile);
}
.top-nav-bar
{
padding-inline: 8px;
column-gap: 4px;
}
.top-nav-primary
{
column-gap: 4px;
}
.top-nav-layout .top-nav-brand-link
{
margin-inline: 4px;
font-size: 1rem;
}
.top-nav-desktop-menu,
.top-nav-desktop-submenu,
.top-nav-user-desktop
{
display: none;
}
.top-nav-desktop-menu
{
font-size: .875rem;
}
.top-nav-desktop-menu .top-nav-menu-link
{
padding-inline: 8px;
}
.top-nav-user-desktop
{
padding-right: 4px;
font-size: .875rem;
}
.top-nav-user-mobile
{
overflow-wrap: anywhere;
}
@media (min-width: 768px)
{
.top-nav-root
.top-nav-layout .top-nav-brand-link
{
font-size: 1.125rem;
}
.top-nav-layout[data-desktop='true'] .top-nav-root
{
background: var(--top-nav-root-bg-desktop);
}
.top-nav-layout[data-desktop='true'] .top-nav-desktop-menu,
.top-nav-layout[data-measuring] .top-nav-desktop-menu
{
display: flex;
}
.top-nav-layout[data-desktop='true'] .top-nav-user-desktop,
.top-nav-layout[data-measuring] .top-nav-user-desktop,
.top-nav-layout[data-desktop='true'] .top-nav-desktop-submenu
{
display: block;
}
.top-nav-layout[data-desktop='true'] .top-nav-mobile-toggle,
.top-nav-layout[data-measuring] .top-nav-mobile-toggle,
.top-nav-layout[data-desktop='true'] .top-nav-mobile-menu,
.top-nav-layout[data-desktop='true'] .top-nav-user-mobile
{
display: none;
}
.top-nav-layout[data-measuring]
{
visibility: hidden;
}
}
@media (min-width: 1024px)
{
.top-nav-bar
{
padding-inline: 12px;
column-gap: 8px;
}
.top-nav-primary
{
column-gap: 6px;
}
.top-nav-layout .top-nav-brand-link
{
margin-inline: 8px;
font-size: 1.25rem;
}
.top-nav-desktop-menu
{
column-gap: 2px;
}
.top-nav-desktop-menu,
.top-nav-user-desktop
{
font-size: .9375rem;
}
.top-nav-desktop-menu .top-nav-menu-link
{
padding-inline: 12px;
}
.top-nav-user-desktop
{
padding-right: 8px;
}
}
@media (min-width: 1280px)
{
.top-nav-bar
{
column-gap: 12px;
}
.top-nav-primary
{
column-gap: 8px;
}
.top-nav-layout .top-nav-brand-link
{
margin-inline: 16px;
}
.top-nav-desktop-menu
{
column-gap: 4px;
}
.top-nav-desktop-menu,
.top-nav-user-desktop
{
font-size: 1rem;
}
.top-nav-desktop-menu .top-nav-menu-link
{
padding-inline: 20px;
}
.top-nav-user-desktop
{
padding-right: 16px;
}
}
.top-nav-layout[data-density='comfortable'] .top-nav-bar
{
padding-inline: 12px;
column-gap: 8px;
}
.top-nav-layout[data-density='comfortable'] .top-nav-primary
{
column-gap: 6px;
}
.top-nav-layout[data-density='comfortable'] .top-nav-brand-link
{
margin-inline: 8px;
font-size: 1.25rem;
}
.top-nav-layout[data-density='comfortable'] .top-nav-desktop-menu
{
column-gap: 2px;
}
.top-nav-layout[data-density='comfortable'] .top-nav-desktop-menu,
.top-nav-layout[data-density='comfortable'] .top-nav-user-desktop
{
font-size: .9375rem;
}
.top-nav-layout[data-density='comfortable'] .top-nav-desktop-menu .top-nav-menu-link
{
padding-inline: 12px;
}
.top-nav-layout[data-density='comfortable'] .top-nav-user-desktop
{
padding-right: 8px;
}
.top-nav-layout[data-density='compact'] .top-nav-bar
{
padding-inline: 8px;
column-gap: 4px;
}
.top-nav-layout[data-density='compact'] .top-nav-primary
{
column-gap: 4px;
}
.top-nav-layout[data-density='compact'] .top-nav-brand-link
{
margin-inline: 4px;
font-size: 1.125rem;
}
.top-nav-layout[data-density='compact'] .top-nav-desktop-menu
{
column-gap: 0;
}
.top-nav-layout[data-density='compact'] .top-nav-desktop-menu,
.top-nav-layout[data-density='compact'] .top-nav-user-desktop
{
font-size: .875rem;
}
.top-nav-layout[data-density='compact'] .top-nav-desktop-menu .top-nav-menu-link
{
padding-inline: 8px;
}
.top-nav-layout[data-density='compact'] .top-nav-user-desktop
{
padding-right: 4px;
}
.top-nav-brand-link,
+130
ファイルの表示
@@ -0,0 +1,130 @@
import { describe, expect, it } from 'vitest'
import { createHelpFixture } from '@/test/helpFixtures'
describe ('Help file catalogue', () => {
it.each ([['Éclair', 'eclair'], ['home', 'HOME'], ['e\u0301clair', 'Éclair']]) (
'compares title %s and %s equally at primary strength', (a, b) => {
const { api } = createHelpFixture ()
expect (api.compareHelpTitles (a, b)).toBe (0)
})
it ('orders distinct Latin titles in both directions', () => {
const { api } = createHelpFixture ()
expect (api.compareHelpTitles ('Apple', 'Zebra')).toBeLessThan (0)
expect (api.compareHelpTitles ('Zebra', 'Apple')).toBeGreaterThan (0)
})
it.each ([['ほーむ', 'ホーム'], ['ホーム', 'ほーむ'], ['ホーム', 'ホーム'],
['ABC', 'abc'], ['ガイド', 'がいど']]) (
'normalises search text %s and %s identically', (query, text) => {
const { api } = createHelpFixture ()
expect (api.normaliseHelpSearchText (query)).toBe (api.normaliseHelpSearchText (text))
})
it.each ([['2026-10-02', null], ['2026-10-02.2', 2],
['2026-10-02.3', 3], ['2026-10-02.10', 10]] as const) (
'separates the date and revision of %s', (edition, revision) => {
const { api } = createHelpFixture ()
expect (api.parseHelpEdition (edition)).toEqual ({ date: '2026-10-02', revision })
const date = api.helpEditionDate (edition)!
expect ([date.getFullYear (), date.getMonth (), date.getDate ()]).toEqual ([2026, 9, 2])
})
it.each (['missing', '2026-02-30', '2026-10-02.0', '2026-10-02.2.extra',
'2026-10-02.9007199254740992']) ('rejects invalid edition %s', edition => {
const { api } = createHelpFixture ()
expect (api.parseHelpEdition (edition)).toBeNull ()
expect (api.helpEditionDate (edition)).toBeNull ()
})
it ('compares numeric revision suffixes without losing the edition identifiers', () => {
const { api } = createHelpFixture ()
expect (['2026-10-02.10', '2026-10-02.3', '2026-10-02', '2026-10-02.2']
.sort (api.compareHelpEditions)).toEqual ([
'2026-10-02', '2026-10-02.2', '2026-10-02.3', '2026-10-02.10'])
})
it ('uses current_edition rather than the newest file, without YAML titles', async () => {
const { api } = createHelpFixture ()
expect ((await api.getHelpArticle ('guide'))?.languages.ja.currentEdition)
.toBe ('2026-10-02.10')
expect (await api.getHelpSearchEntries ('ja')).toEqual ([
{ identifier: 'guide', edition: '2026-10-02.10',
title: 'ホーム第十版', body: '\nタグを検索する 第十版本文' },
{ identifier: '設定 手順', edition: '2026-10-03',
title: '設定', body: '\nタグを設定する' }])
})
it ('orders published editions numerically and separates languages', async () => {
const { api } = createHelpFixture ()
expect (await api.getHelpEditions ('guide', 'ja')).toEqual ([
'2026-10-01', '2026-10-02', '2026-10-02.2', '2026-10-02.3', '2026-10-02.10'])
expect (await api.getHelpEditions ('guide', 'en')).toEqual (['2026-10-02'])
expect (await api.getHelpPublishedEditions ('guide', 'ja'))
.not.toContain ('2026-10-02.11')
})
it ('uses generated edition titles without reparsing raw sources', async () => {
const { api, raw } = createHelpFixture ()
expect (await api.getHelpEditionText ('guide', 'ja', '2026-10-01'))
.toEqual ({ title: '旧ホーム', body: '\n過去限定本文' })
raw['../../help/guide/editions/ja/2026-10-02.mdx']
.mockResolvedValue ('\uFEFF# 改題\r\n\r\n本文\r\n# 別見出し')
expect (await api.getHelpEditionText ('guide', 'ja', '2026-10-02'))
.toEqual ({ title: 'ホーム', body: '\nタグを検索する' })
expect (raw['../../help/guide/editions/ja/2026-10-02.mdx']).not.toHaveBeenCalled ()
expect ((await api.getHelpEditionSource ('guide', 'ja', '2026-10-02'))?.source)
.toBe ('\uFEFF# 改題\r\n\r\n本文\r\n# 別見出し')
})
it ('returns missing resources without substituting another edition', async () => {
const { api } = createHelpFixture ()
expect (await api.getHelpArticle ('absent')).toBeNull ()
expect (await api.getHelpEditions ('absent', 'ja')).toEqual ([])
expect (await api.getHelpEdition ('guide', 'ja', 'missing')).toBeNull ()
expect (await api.getHelpEditionText ('guide', 'fr', '2026-10-02')).toBeNull ()
})
it ('reports generated search asset failures instead of hiding articles', async () => {
const { api, loads } = createHelpFixture ()
loads.search.mockImplementationOnce (() => { throw new Error ('asset failure') })
await expect (api.getHelpSearchEntries ('ja')).rejects.toThrow ('asset failure')
})
it ('reports raw loading failures and excludes unpublished editions', async () => {
const { api, raw } = createHelpFixture ()
const loader = raw['../../help/guide/editions/ja/2026-10-02.mdx']
loader.mockRejectedValueOnce (new Error ('fixture failure'))
await expect (api.getHelpEditionSource ('guide', 'ja', '2026-10-02'))
.rejects.toThrow ('fixture failure')
expect (await api.getHelpEdition ('guide', 'ja', '2026-10-02.11')).toBeNull ()
expect (await api.getHelpEditionSource ('guide', 'ja', '2026-10-02.11')).toBeNull ()
})
it ('compares raw H1 and body lines in the requested direction', async () => {
const { api } = createHelpFixture ()
const forward = await api.getHelpDiff ('guide', 'ja', '2026-10-01', '2026-10-02.10')
expect (forward?.from.title).toBe ('旧ホーム')
expect (forward?.to.title).toBe ('ホーム第十版')
expect (forward?.lines).toEqual (expect.arrayContaining ([
{ type: 'removed', content: '# 旧ホーム\n' },
{ type: 'added', content: '# ホーム第十版\n' },
{ type: 'unchanged', content: '\n' }]))
const reverse = await api.getHelpDiff ('guide', 'ja', '2026-10-02.10', '2026-10-01')
expect (reverse?.lines).toEqual (expect.arrayContaining ([
{ type: 'added', content: '# 旧ホーム\n' },
{ type: 'removed', content: '# ホーム第十版\n' }]))
})
it.each ([['missing', 'ja', '2026-10-01', '2026-10-02.10'],
['guide', 'ja', '2026-10-01', '2026-10-02.11'],
['guide', 'en', '2026-10-01', '2026-10-02']]) (
'rejects invalid diff editions for %s/%s without reading sources',
async (id, language, from, to) => {
const { api, raw } = createHelpFixture ()
expect (await api.getHelpDiff (id, language, from, to)).toBeNull ()
Object.values (raw).forEach (load => expect (load).not.toHaveBeenCalled ())
})
})
+237
ファイルの表示
@@ -0,0 +1,237 @@
import type { ComponentType } from 'react'
type ArticleLanguage = { currentEdition: string; publishedEditions: string[] }
export type ArticleMeta = {
identifier: string
canonicalLanguage: string
languages: Record<string, ArticleLanguage> }
export type HelpEditionText = {
title: string
body: string }
export type HelpSearchEntry = HelpEditionText & {
identifier: string
edition: string }
export type HelpEditionContent = HelpEditionText & { content: ComponentType }
export type HelpEditionSource = HelpEditionText & { source: string }
export type HelpChange = Pick<HelpSearchEntry, 'identifier' | 'edition' | 'title'> & {
pred: string | null
change: 'new' | 'update'
date: string }
export type HelpTitleIndex = Record<string, string[]>
export type HelpDiffLine = {
type: 'added' | 'removed' | 'unchanged'
content: string }
export type HelpDiff = {
from: HelpEditionSource
to: HelpEditionSource
lines: HelpDiffLine[] }
export type HelpEditionIdentifier = { date: string; revision: number | null }
// Fix the locale and primary strength; ICU versions still differ from MySQL UCA 9.0.
const helpTitleCollator = new Intl.Collator ('en', {
usage: 'sort', sensitivity: 'base', ignorePunctuation: false, numeric: false })
export const compareHelpTitles = (a: string, b: string): number =>
helpTitleCollator.compare (a, b)
export const normaliseHelpSearchText = (value: string): string =>
value.normalize ('NFKC').toLowerCase ().replace (/[ァ-ヶヽヾ]/g,
character => String.fromCodePoint (character.codePointAt (0)! - 0x60))
export const parseHelpEdition = (edition: string): HelpEditionIdentifier | null => {
const matched = edition.match (/^(\d{4}-\d{2}-\d{2})(?:\.([1-9]\d*))?$/)
if (matched == null)
return null
const date = new Date (matched[1])
const revision = matched[2] == null ? null : Number (matched[2])
if (Number.isNaN (date.getTime ()) || date.toISOString ().slice (0, 10) !== matched[1]
|| (revision != null && !(Number.isSafeInteger (revision))))
return null
return { date: matched[1], revision }
}
export const compareHelpEditions = (a: string, b: string): number => {
const before = parseHelpEdition (a)
const after = parseHelpEdition (b)
if (before == null || after == null)
return a.localeCompare (b)
return before.date.localeCompare (after.date)
|| (before.revision ?? 1) - (after.revision ?? 1)
}
export const helpEditionDate = (edition: string): Date | null => {
const parsed = parseHelpEdition (edition)
return parsed == null ? null : new Date (`${ parsed.date }T00:00:00`)
}
export const getHelpArticle = async (identifier: string): Promise<ArticleMeta | null> => {
const { default: articles } = await import ('virtual:help/articles')
return Object.hasOwn (articles, identifier) ? articles[identifier] : null
}
export const getHelpEditions = async (
identifier: string,
language: string,
): Promise<string[]> => {
const article = await getHelpArticle (identifier)
return article?.languages[language]?.publishedEditions ?? []
}
export const getHelpPublishedEditions = async (
identifier: string,
language: string,
): Promise<string[]> => await getHelpEditions (identifier, language)
export const getHelpEdition = async (
identifier: string,
language: string,
edition: string,
): Promise<ComponentType | null> => {
const { components } = await import ('virtual:help/loaders')
const loader = components[`${ identifier }/${ language }/${ edition }`]
if (!(loader))
return null
return (await loader ()).default
}
export const getHelpEditionSource = async (
identifier: string,
language: string,
edition: string,
): Promise<HelpEditionSource | null> => {
const { sources } = await import ('virtual:help/loaders')
const loader = sources[`${ identifier }/${ language }/${ edition }`]
if (!(loader))
return null
const [source, text] = await Promise.all ([
loader (), getHelpEditionText (identifier, language, edition)])
return text == null ? null : { source: source.default, ...text }
}
export const getHelpEditionText = async (
identifier: string,
language: string,
edition: string,
): Promise<HelpEditionText | null> => {
const { texts } = await import ('virtual:help/loaders')
const loader = texts[`${ identifier }/${ language }/${ edition }`]
return loader == null ? null : (await loader ()).default
}
export const getHelpSearchEntries = async (
language: string,
): Promise<HelpSearchEntry[]> => {
const { default: search } = await import ('virtual:help/search')
return search[language] ?? []
}
export const getHelpEditionContent = async (
identifier: string,
language: string,
edition: string,
): Promise<HelpEditionContent | null> => {
const [content, text] = await Promise.all ([
getHelpEdition (identifier, language, edition),
getHelpEditionText (identifier, language, edition)])
return content != null && text != null ? { content, ...text } : null
}
export const getHelpChanges = async (language: string): Promise<HelpChange[]> => {
const { default: changes } = await import ('virtual:help/changes')
return changes[language] ?? []
}
export const getHelpTitleIndex = async (language: string): Promise<HelpTitleIndex> => {
const { default: titles } = await import ('virtual:help/titles')
return titles[language] ?? { }
}
const diffHelpLines = (from: string, to: string): HelpDiffLine[] => {
const before = from.match (/[^\n]*\n|[^\n]+$/g) ?? []
const after = to.match (/[^\n]*\n|[^\n]+$/g) ?? []
const lengths = Array.from ({ length: before.length + 1 },
() => new Uint32Array (after.length + 1))
for (let i = before.length - 1; i >= 0; --i)
{
for (let j = after.length - 1; j >= 0; --j)
{
lengths[i][j] =
before[i] === after[j]
? lengths[i + 1][j + 1] + 1
: Math.max (lengths[i + 1][j], lengths[i][j + 1])
}
}
const lines: HelpDiffLine[] = []
let i = 0
let j = 0
while (i < before.length || j < after.length)
{
if (i < before.length && j < after.length && before[i] === after[j])
{
lines.push ({ type: 'unchanged', content: before[i] })
++i
++j
}
else if (i < before.length
&& (j === after.length || lengths[i + 1][j] >= lengths[i][j + 1]))
{
lines.push ({ type: 'removed', content: before[i] })
++i
}
else
{
lines.push ({ type: 'added', content: after[j] })
++j
}
}
return lines
}
export const getHelpDiff = async (
identifier: string,
language: string,
from: string,
to: string,
): Promise<HelpDiff | null> => {
const editions = await getHelpPublishedEditions (identifier, language)
if (!(editions.includes (from)) || !(editions.includes (to)))
return null
const [before, after] = await Promise.all ([
getHelpEditionSource (identifier, language, from),
getHelpEditionSource (identifier, language, to)])
if (before == null || after == null)
return null
return { from: before, to: after, lines: diffHelpLines (before.source, after.source) }
}
+126
ファイルの表示
@@ -0,0 +1,126 @@
import { QueryClient } from '@tanstack/react-query'
import { fireEvent, screen, waitFor } from '@testing-library/react'
import { Route, Routes, useLocation } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import PrefetchLink from '@/components/PrefetchLink'
import * as prefetchers from '@/lib/prefetchers'
import HelpDetailPage from '@/pages/help/HelpDetailPage'
import HelpDiffPage from '@/pages/help/HelpDiffPage'
import { helpFixture } from '@/test/helpFixtures'
import { renderWithProviders } from '@/test/render'
const settings = vi.hoisted (() => ({ linkPreload: 'intent' }))
vi.mock ('@/lib/useClientBehaviourSettings', () => ({
useClientBehaviourSettings: () => settings }))
vi.mock ('@/lib/help', async () => (await import ('@/test/helpFixtures')).helpFixture.api)
const Location = () => {
const location = useLocation ()
return <output data-testid="location">{location.pathname}</output>
}
describe ('Help prefetch integration', () => {
beforeEach (() => {
helpFixture.reset ()
settings.linkPreload = 'intent'
vi.clearAllMocks ()
})
it.each (['/help', '/help?title=ホーム&text=検索&page=2', '/help/guide', '/help/changes',
'/help/guide/diff?from=2026-10-01&to=2026-10-02.10',
'/help/%E8%A8%AD%E5%AE%9A%20%E6%89%8B%E9%A0%86?edition=2026-10-03']) (
'registers a unique prefetcher for %s', path => {
const url = new URL (path, window.location.origin)
expect (prefetchers.routePrefetchers.filter (entry => entry.test (url))).toHaveLength (1)
})
it ('loads and reuses the same MDX module for repeated prefetch and display', async () => {
const { queryClient } = renderWithProviders (
<>
<PrefetchLink to="/help/guide">Help</PrefetchLink>
<Routes>
<Route path="/" element={null}/>
<Route path="/help/:identifier" element={<HelpDetailPage/>}/>
</Routes>
</>)
const loader = helpFixture.moduleLoads['../../help/guide/editions/ja/2026-10-02.10.mdx']
await Promise.all ([
prefetchers.prefetchForURL (queryClient, '/help/guide'),
prefetchers.prefetchForURL (queryClient, '/help/guide')])
expect (loader).toHaveBeenCalledTimes (1)
fireEvent.click (screen.getByRole ('link', { name: 'Help' }))
await screen.findByRole ('heading', { name: 'ホーム第十版' })
expect (loader).toHaveBeenCalledTimes (1)
})
it ('prefetches the requested identifier and edition independently', async () => {
const client = new QueryClient ()
await prefetchers.prefetchForURL (client, '/help/guide?edition=2026-10-02.3')
await prefetchers.prefetchForURL (client, `/help/${encodeURIComponent ('設定 手順')}`)
expect (helpFixture.modules['../../help/guide/editions/ja/2026-10-02.3.mdx'])
.toHaveBeenCalledTimes (1)
expect (helpFixture.modules['../../help/設定 手順/editions/ja/2026-10-03.mdx'])
.toHaveBeenCalledTimes (1)
expect (helpFixture.modules['../../help/guide/editions/en/2026-10-02.mdx'])
.not.toHaveBeenCalled ()
})
it ('loads history editions without treating changes as an article', async () => {
const article = vi.spyOn (helpFixture.api, 'getHelpArticle')
await prefetchers.prefetchForURL (new QueryClient (), '/help/changes')
expect (article).not.toHaveBeenCalledWith ('changes')
expect (helpFixture.loads.changes).toHaveBeenCalledTimes (1)
Object.values (helpFixture.raw).forEach (load => expect (load).not.toHaveBeenCalled ())
Object.values (helpFixture.modules).forEach (load => expect (load).not.toHaveBeenCalled ())
})
it ('reuses two prefetched raw editions when displaying their diff', async () => {
const path = '/help/guide/diff?from=2026-10-01&to=2026-10-02.10'
const { queryClient } = renderWithProviders (
<>
<PrefetchLink to={path}>diff</PrefetchLink>
<Routes>
<Route path="/" element={null}/>
<Route path="/help/:identifier/diff" element={<HelpDiffPage/>}/>
</Routes>
</>)
await Promise.all ([prefetchers.prefetchForURL (queryClient, path),
prefetchers.prefetchForURL (queryClient, path)])
fireEvent.click (screen.getByRole ('link', { name: 'diff' }))
expect (await screen.findByRole ('link', { name: '旧ホーム (2026-10-01)' }))
.toHaveAttribute ('href', '/help/guide?edition=2026-10-01')
expect (screen.getByText ('+ # ホーム第十版')).toBeInTheDocument ()
Object.entries (helpFixture.raw).forEach (([name, load]) => {
const expected = /\/ja\/(2026-10-01|2026-10-02\.10)\.mdx$/.test (name) ? 1 : 0
expect (load).toHaveBeenCalledTimes (expected)
})
Object.values (helpFixture.modules).forEach (load => expect (load).not.toHaveBeenCalled ())
})
it.each (['intent', 'off']) ('respects %s intent settings and still prefetches clicks',
async mode => {
settings.linkPreload = mode
const run = vi.spyOn (prefetchers, 'prefetchForURL').mockResolvedValue ()
renderWithProviders (<><Location/><PrefetchLink to="/help/guide">Help</PrefetchLink></>)
const link = screen.getByRole ('link', { name: 'Help' })
fireEvent.mouseEnter (link)
fireEvent.touchStart (link)
expect (run).toHaveBeenCalledTimes (mode === 'intent' ? 2 : 0)
fireEvent.click (link)
await waitFor (() => expect (screen.getByTestId ('location'))
.toHaveTextContent ('/help/guide'))
expect (run).toHaveBeenCalledTimes (mode === 'intent' ? 3 : 1)
})
it ('continues navigation after prefetch failure', async () => {
vi.spyOn (console, 'error').mockImplementation (() => {})
vi.spyOn (prefetchers, 'prefetchForURL').mockRejectedValue (new Error ('offline'))
renderWithProviders (<><Location/><PrefetchLink to="/help/guide">Help</PrefetchLink></>)
fireEvent.click (screen.getByRole ('link', { name: 'Help' }))
await waitFor (() => expect (screen.getByTestId ('location'))
.toHaveTextContent ('/help/guide'))
})
})
+70 -1
ファイルの表示
@@ -1,8 +1,13 @@
import { QueryClient } from '@tanstack/react-query'
import { match } from 'path-to-regexp'
import { getHelpArticle,
getHelpChanges,
getHelpDiff,
getHelpEditionContent,
getHelpSearchEntries } from '@/lib/help'
import { fetchPost, fetchPosts, fetchPostChanges } from '@/lib/posts'
import { postsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys'
import { helpKeys, postsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys'
import { fetchNicoTags, fetchTagByName, fetchTag, fetchTagChanges, fetchTags } from '@/lib/tags'
import { fetchWikiPage,
fetchWikiPageByTitle,
@@ -15,12 +20,69 @@ type Prefetcher = (qc: QueryClient, url: URL) => Promise<void>
const mPost = match<{ id: string }> ('/posts/:id')
const mWiki = match<{ title: string }> ('/wiki/:title')
const mTag = match<{ id: string }> ('/tags/:id')
const mHelp = match<{ identifier: string }> ('/help/:identifier')
const mHelpDiff = match<{ identifier: string }> ('/help/:identifier/diff')
const boolFromQuery = (value: string | null): boolean =>
['1', 'true', 'on', 'yes', ''].includes ((value ?? '').toLowerCase ())
const prefetchHelpIndex: Prefetcher = async qc => {
await qc.prefetchQuery ({
queryKey: helpKeys.index ('ja'),
queryFn: () => getHelpSearchEntries ('ja'),
staleTime: Infinity })
}
const prefetchHelpShow: Prefetcher = async (qc, url) => {
const matched = mHelp (url.pathname)
if (!(matched))
return
const { identifier } = matched.params
const language = 'ja'
const article = await qc.fetchQuery ({
queryKey: helpKeys.article (identifier),
queryFn: () => getHelpArticle (identifier),
staleTime: Infinity })
const edition = url.searchParams.get ('edition') ?? article?.languages[language]?.currentEdition
if (edition == null)
return
await qc.prefetchQuery ({
queryKey: helpKeys.edition (identifier, language, edition),
queryFn: () => getHelpEditionContent (identifier, language, edition),
staleTime: Infinity })
}
const prefetchHelpChanges: Prefetcher = async qc => {
await qc.prefetchQuery ({
queryKey: helpKeys.changes ('ja'),
queryFn: () => getHelpChanges ('ja'),
staleTime: Infinity })
}
const prefetchHelpDiff: Prefetcher = async (qc, url) => {
const matched = mHelpDiff (url.pathname)
const fromValues = url.searchParams.getAll ('from')
const toValues = url.searchParams.getAll ('to')
const [from] = fromValues
const [to] = toValues
if (!(matched) || fromValues.length !== 1 || toValues.length !== 1 || !(from) || !(to))
return
const { identifier } = matched.params
await qc.prefetchQuery ({
queryKey: helpKeys.diff (identifier, 'ja', from, to),
queryFn: () => getHelpDiff (identifier, 'ja', from, to),
staleTime: Infinity })
}
const prefetchWikiPagesIndex: Prefetcher = async (qc, url) => {
const title = url.searchParams.get ('title') ?? ''
@@ -223,6 +285,13 @@ const prefetchTagChanges: Prefetcher = async (qc, url) => {
export const routePrefetchers: { test: (u: URL) => boolean; run: Prefetcher }[] = [
{ test: u => /^\/help\/?$/.test (u.pathname), run: prefetchHelpIndex },
{ test: u => /^\/help\/changes\/?$/.test (u.pathname), run: prefetchHelpChanges },
{ test: u => Boolean (mHelpDiff (u.pathname)), run: prefetchHelpDiff },
{ test: u => {
const matched = mHelp (u.pathname)
return Boolean (matched && matched.params.identifier !== 'changes')
}, run: prefetchHelpShow },
{ test: u => ['/', '/posts', '/posts/search'].includes (u.pathname),
run: prefetchPostsIndex },
{ test: u => (!(['/posts/new', '/posts/changes', '/posts/search'].includes (u.pathname))
+11
ファイルの表示
@@ -61,3 +61,14 @@ export const wikiKeys = {
root: ['wiki'] as const,
index: (p: { title?: string }) => ['wiki', 'index', p] as const,
show: (title: string, p: { version?: string }) => ['wiki', title, p] as const }
export const helpKeys = {
root: ['help'] as const,
index: (language: string) => ['help', 'index', language] as const,
titles: (language: string) => ['help', 'titles', language] as const,
article: (identifier: string) => ['help', 'article', identifier] as const,
edition: (identifier: string, language: string, edition: string) =>
['help', 'edition', identifier, language, edition] as const,
diff: (identifier: string, language: string, from: string, to: string) =>
['help', 'diff', identifier, language, from, to] as const,
changes: (language: string) => ['help', 'changes', language] as const }
+16 -2
ファイルの表示
@@ -72,11 +72,25 @@ describe ('tags API functions', () => {
)
})
it ('returns null when tag fetches fail', async () => {
api.apiGet.mockRejectedValueOnce (new Error ('missing'))
it ('returns null for a missing named tag while retaining the ID helper contract', async () => {
api.apiGet.mockRejectedValueOnce (new Error ('missing'))
api.apiGet.mockRejectedValueOnce ({ isAxiosError: true, response: { status: 404 } })
await expect (fetchTag ('1')).resolves.toBeNull ()
await expect (fetchTagByName ('unknown')).resolves.toBeNull ()
})
it.each ([403, 500]) ('propagates named tag HTTP %s', async status => {
const error = { isAxiosError: true, response: { status } }
api.apiGet.mockRejectedValueOnce (error)
await expect (fetchTagByName ('ホーム')).rejects.toBe (error)
})
it ('propagates named tag network failures and encodes the name', async () => {
const error = new Error ('offline')
api.apiGet.mockRejectedValueOnce (error)
await expect (fetchTagByName ('名前/#%')).rejects.toBe (error)
expect (api.apiGet).toHaveBeenLastCalledWith (
`/tags/name/${ encodeURIComponent ('名前/#%') }`)
})
})
+7 -3
ファイルの表示
@@ -1,3 +1,5 @@
import { isAxiosError } from 'axios'
import { apiGet } from '@/lib/api'
import type { Deerjikist,
@@ -68,11 +70,13 @@ export const fetchExternalTag = async (id: string): Promise<Tag | null> => {
export const fetchTagByName = async (name: string): Promise<Tag | null> => {
try
{
return await apiGet (`/tags/name/${ name }`)
return await apiGet (`/tags/name/${ encodeURIComponent (name) }`)
}
catch
catch (error)
{
return null
if (isAxiosError (error) && error.response?.status === 404)
return null
throw error
}
}
+24 -17
ファイルの表示
@@ -2,9 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fetchWikiPage, fetchWikiPageByTitle, fetchWikiPages } from '@/lib/wiki'
const api = vi.hoisted (() => ({
apiGet: vi.fn (),
}))
const api = vi.hoisted (() => ({ apiGet: vi.fn () }))
vi.mock ('@/lib/api', () => api)
@@ -21,28 +19,37 @@ describe ('wiki API functions', () => {
await fetchWikiPage ('1', { version: '3' })
expect (api.apiGet).toHaveBeenNthCalledWith (
1,
'/wiki',
{ params: { title: '虹' } },
)
1,
'/wiki',
{ params: { title: '虹' } })
expect (api.apiGet).toHaveBeenNthCalledWith (
2,
'/wiki/1',
{ params: { version: '3' } },
)
2,
'/wiki/1',
{ params: { version: '3' } })
})
it ('encodes title path segments and returns null on misses', async () => {
api.apiGet.mockResolvedValueOnce ({ id: 2 })
api.apiGet.mockRejectedValueOnce (new Error ('missing'))
api.apiGet.mockRejectedValueOnce ({ isAxiosError: true, response: { status: 404 } })
await fetchWikiPageByTitle ('a/b c', { version: undefined })
await expect (fetchWikiPageByTitle ('missing', {})).resolves.toBeNull ()
await expect (fetchWikiPageByTitle ('missing', { })).resolves.toBeNull ()
expect (api.apiGet).toHaveBeenNthCalledWith (
1,
'/wiki/title/a%2Fb%20c',
{ params: { version: undefined } },
)
1,
'/wiki/title/a%2Fb%20c',
{ params: { version: undefined } })
})
it.each ([403, 500]) ('preserves HTTP %s errors', async status => {
const error = { isAxiosError: true, response: { status } }
api.apiGet.mockRejectedValueOnce (error)
await expect (fetchWikiPageByTitle ('ホーム', { })).rejects.toBe (error)
})
it ('preserves network failures for callers', async () => {
const error = new Error ('network failure')
api.apiGet.mockRejectedValueOnce (error)
await expect (fetchWikiPageByTitle ('ホーム', { })).rejects.toBe (error)
})
})
+6 -2
ファイルの表示
@@ -1,3 +1,5 @@
import { isAxiosError } from 'axios'
import { apiGet } from '@/lib/api'
import type { WikiPage } from '@/types'
@@ -21,8 +23,10 @@ export const fetchWikiPageByTitle = async (
{
return await apiGet (`/wiki/title/${ encodeURIComponent (title) }`, { params: { version } })
}
catch
catch (error)
{
return null
if (isAxiosError (error) && error.response?.status === 404)
return null
throw error
}
}
+77
ファイルの表示
@@ -0,0 +1,77 @@
import { fireEvent, screen, within } from '@testing-library/react'
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { Route, Routes } from 'react-router-dom'
import HelpDetailPage from '@/pages/help/HelpDetailPage'
import { compileMdx, transformMdx } from '@/test/compileMdx'
import { helpFixture } from '@/test/helpFixtures'
import { renderWithProviders } from '@/test/render'
const prefetch = vi.hoisted (() => vi.fn (async () => {}))
vi.hoisted (() => {
vi.stubGlobal ('Uint8Array', Object.getPrototypeOf (new TextEncoder ().encode ('')).constructor)
})
afterAll (() => vi.unstubAllGlobals ())
vi.mock ('@/lib/prefetchers', () => ({ prefetchForURL: prefetch }))
vi.mock ('@/lib/help', async () => (await import ('@/test/helpFixtures')).helpFixture.api)
const tableSource = [
'# 表のある記事', '', '| 項目 | 説明 |', '| --- | --- |',
'| [ヘルプ](/help/guide) | **強調** |', '| 通常 | 本文 |'].join ('\n')
describe ('Help MDX with the application compiler', () => {
beforeEach (() => helpFixture.reset ())
it ('compiles GFM table structure, links and emphasis', async () => {
const Content = await compileMdx (tableSource)
renderWithProviders (<Content/>)
const table = screen.getByRole ('table')
expect (table.querySelector ('thead')).not.toBeNull ()
expect (table.querySelector ('tbody')).not.toBeNull ()
expect (within (table).getAllByRole ('columnheader')).toHaveLength (2)
expect (within (table).getAllByRole ('cell')).toHaveLength (4)
expect (within (table).getByRole ('link', { name: 'ヘルプ' }))
.toHaveAttribute ('href', '/help/guide')
expect (table.querySelector ('strong')).toHaveTextContent ('強調')
})
it ('retains headings, paragraphs and lists', async () => {
const Content = await compileMdx ('# 見出し\n\n本文\n\n- 第一\n- 第二')
renderWithProviders (<Content/>)
expect (screen.getByRole ('heading', { level: 1 })).toHaveTextContent ('見出し')
expect (screen.getByText ('本文').tagName).toBe ('P')
expect (screen.getAllByRole ('listitem')).toHaveLength (2)
})
it ('keeps tables inside the Help dark-mode typography container', async () => {
const Content = await compileMdx (tableSource)
helpFixture.modules['../../help/guide/editions/ja/2026-10-02.10.mdx']
.mockResolvedValue ({ default: Content })
renderWithProviders (
<Routes><Route path="/help/:identifier" element={<HelpDetailPage/>}/></Routes>,
{ route: '/help/guide' })
const table = await screen.findByRole ('table')
expect (table.closest ('article')).toHaveClass ('prose', 'dark:prose-invert')
})
it ('preserves long cell contents when rendering a wide table', async () => {
const cell = 'wide'.repeat (100)
const Content = await compileMdx (`| 項目 |\n| --- |\n| ${ cell } |`)
renderWithProviders (<Content/>)
expect (screen.getByRole ('cell')).toHaveTextContent (cell)
})
it.each (['.mdx?raw', '.mdx?url']) ('preserves the %s transform bypass', async suffix => {
expect (await transformMdx (tableSource, suffix)).toBeNull ()
})
it ('uses the common PrefetchLink interaction for internal MDX links', async () => {
prefetch.mockClear ()
const Content = await compileMdx ('[内部リンク](/help/guide)')
renderWithProviders (<Content/>)
fireEvent.mouseEnter (screen.getByRole ('link', { name: '内部リンク' }))
expect (prefetch).toHaveBeenCalledWith (expect.anything (),
new URL ('/help/guide', window.location.origin).href)
})
})
+49 -1
ファイルの表示
@@ -1,4 +1,52 @@
import { useMemo } from 'react'
import { useLocation } from 'react-router-dom'
import PrefetchLink from '@/components/PrefetchLink'
import type { MDXComponents } from 'mdx/types'
import type { ComponentProps } from 'react'
export const useMDXComponents = (): MDXComponents => ({ })
const MDXLink = (
{ href, children, ...props }: ComponentProps<'a'>,
) => {
const location = useLocation ()
const url = useMemo (() => {
try
{
const base = new URL (location.pathname + location.search, window.location.origin)
return href ? new URL (href, base) : null
}
catch
{
return null
}
}, [href, location.pathname, location.search])
const internal = url != null
&& url.origin === window.location.origin
&& (url.protocol === 'http:' || url.protocol === 'https:')
const anchor = href?.startsWith ('#')
|| (url?.pathname === location.pathname
&& url.search === location.search && Boolean (url.hash))
const external = url != null && !(internal)
&& (url.protocol === 'http:' || url.protocol === 'https:')
if (internal && !(anchor) && props.download == null)
{
return (
<PrefetchLink to={url.pathname + url.search + url.hash} {...props}>
{children}
</PrefetchLink>)
}
return (
<a href={href}
{...props}
target={external ? props.target ?? '_blank' : props.target}
rel={props.rel ?? 'noopener noreferrer'}>
{children}
</a>)
}
export const useMDXComponents = (): MDXComponents => ({ a: MDXLink })
+55
ファイルの表示
@@ -0,0 +1,55 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import { HelmetProvider } from 'react-helmet-async'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { apiGet } from '@/lib/api'
import App from '@/App'
import { helpFixture } from '@/test/helpFixtures'
vi.hoisted (() => {
window.history.replaceState (null, '', '/help/changes')
})
vi.mock ('@/lib/help', async () => (await import ('@/test/helpFixtures')).helpFixture.api)
vi.mock ('@/lib/api', () => ({ apiGet: vi.fn (), apiPost: async () => ({}),
isApiError: () => false }))
vi.mock ('@/components/TopNav', () => ({ default: () => null }))
vi.mock ('@/components/DevModeWatermark', () => ({ default: () => null }))
vi.mock ('@/lib/useClientBehaviourSettings', () => ({
useClientBehaviourSettings: () => ({ animation: 'off', linkPreload: 'off' }) }))
describe ('Help global edition history', () => {
beforeEach (() => helpFixture.reset ())
it ('routes /help/changes to published editions in date and numeric order', async () => {
const client = new QueryClient ({ defaultOptions: { queries: { retry: false } } })
const { container } = render (
<QueryClientProvider client={client}>
<HelmetProvider><App/></HelmetProvider>
</QueryClientProvider>)
const links = await screen.findAllByRole ('link')
const editions = links.map (link => link.getAttribute ('href'))
.filter (href => href?.startsWith ('/help/') && href.includes ('edition='))
expect (editions).toEqual ([
`/help/${encodeURIComponent ('設定 手順')}?edition=2026-10-03`,
'/help/guide?edition=2026-10-02.10', '/help/guide?edition=2026-10-02.3',
'/help/guide?edition=2026-10-02.2', '/help/guide?edition=2026-10-02',
'/help/guide?edition=2026-10-01'])
expect (container).toHaveTextContent ('旧ホーム')
expect (screen.getAllByRole ('columnheader').map (cell => cell.textContent))
.toEqual (['差分', 'タイトル', '有効開始年月日'])
expect (container).not.toHaveTextContent ('未公開ホーム')
expect (container).not.toHaveTextContent ('Invalid Date')
expect (container.textContent).not.toMatch (/\d{1,2}:\d{2}/)
expect (screen.getAllByRole ('link', { name: '差分' }).map (link =>
link.getAttribute ('href'))).toEqual ([
'/help/guide/diff?from=2026-10-02.3&to=2026-10-02.10',
'/help/guide/diff?from=2026-10-02.2&to=2026-10-02.3',
'/help/guide/diff?from=2026-10-02&to=2026-10-02.2',
'/help/guide/diff?from=2026-10-01&to=2026-10-02'])
expect (apiGet).not.toHaveBeenCalled ()
expect (window.location.pathname).toBe ('/help/changes')
})
})
+119
ファイルの表示
@@ -0,0 +1,119 @@
import { useQuery } from '@tanstack/react-query'
import { useMemo } from 'react'
import { Helmet } from 'react-helmet-async'
import { useSearchParams } from 'react-router-dom'
import PrefetchLink from '@/components/PrefetchLink'
import PageTitle from '@/components/common/PageTitle'
import Pagination from '@/components/common/Pagination'
import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config'
import { getHelpChanges, helpEditionDate } from '@/lib/help'
import { helpKeys } from '@/lib/queryKeys'
import { LIST_LIMIT_OPTIONS } from '@/lib/settings'
import { dateString } from '@/lib/utils'
import type { FC } from 'react'
const HelpChangesPage: FC = () => {
const [searchParams, setSearchParams] = useSearchParams ()
const identifier = searchParams.get ('identifier') ?? ''
const pageValue = searchParams.get ('page') ?? '1'
const pageNumber = Number (pageValue)
const requestedPage =
(/^[1-9]\d*$/.test (pageValue) && Number.isSafeInteger (pageNumber))
? pageNumber : 1
const limit = LIST_LIMIT_OPTIONS.find (
value => String (value) === searchParams.get ('limit')) ?? 20
const { data: changes = [], isLoading, error } = useQuery ({
queryKey: helpKeys.changes ('ja'),
queryFn: () => getHelpChanges ('ja'),
staleTime: Infinity })
const results = useMemo (() => identifier
? changes.filter (entry => entry.identifier === identifier)
: changes, [changes, identifier])
const totalPages = Math.ceil (results.length / limit)
const page = requestedPage <= Math.max (1, totalPages) ? requestedPage : 1
const pageResults = results.slice ((page - 1) * limit, page * limit)
const handleLimit = (value: string) => {
const next = new URLSearchParams (searchParams)
next.set ('limit', value)
next.set ('page', '1')
setSearchParams (next)
}
return (
<MainArea className="min-w-0 max-w-full">
<Helmet>
<title>{`ヘルプ改定履歴 | ${ SITE_TITLE }`}</title>
</Helmet>
<div className="flex flex-wrap items-center justify-between gap-3">
<PageTitle>ヘルプ改定履歴</PageTitle>
<label className="flex items-center gap-2 text-xs text-muted-foreground">
<span>件数</span>
<select value={limit} onChange={ev => handleLimit (ev.target.value)}
className="rounded border border-border bg-background px-2 py-1 text-sm
text-foreground">
{LIST_LIMIT_OPTIONS.map (value => (
<option key={value} value={value}>{value}</option>))}
</select>
</label>
</div>
{isLoading
? <p className="mt-4">読み込み中...</p>
: (error
? <p className="mt-4 text-red-600" role="alert">{error.message}</p>
: (
<div className="mt-4">
<div className="min-w-0 max-w-full overflow-x-auto">
<table className="table-auto w-full min-w-[900px] whitespace-nowrap
border-collapse">
<thead className="border-b-2 border-black dark:border-white">
<tr>
<th className="p-2 text-left">差分</th>
<th className="p-2 text-left">タイトル</th>
<th className="p-2 text-left">有効開始年月日</th>
</tr>
</thead>
<tbody>
{pageResults.map (entry => {
const path = `/help/${ encodeURIComponent (entry.identifier) }`
const diffQuery = new URLSearchParams ({
from: entry.pred ?? '', to: entry.edition })
const diffTo = `${ path }/diff?${ diffQuery.toString () }`
const updatedAt = helpEditionDate (entry.edition)
return (
<tr key={`${ entry.identifier }/${ entry.edition }`}
className="even:bg-gray-100 text-gray-900
dark:even:bg-gray-700 dark:text-gray-100">
<td className="p-2">
{entry.pred != null && (
<PrefetchLink to={diffTo}>
差分
</PrefetchLink>)}
</td>
<td className="p-2">
<PrefetchLink to={`${ path }?edition=${ entry.edition }`}>
{entry.title}
</PrefetchLink>
</td>
<td className="p-2">
{updatedAt != null && dateString (updatedAt, 'hour')}
</td>
</tr>)
})}
</tbody>
</table>
</div>
{totalPages > 0 && <Pagination page={page} totalPages={totalPages}/>}
</div>))}
</MainArea>)
}
export default HelpChangesPage
+128
ファイルの表示
@@ -0,0 +1,128 @@
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import { Route, Routes, useLocation, useNavigate } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import HelpDetailPage from '@/pages/help/HelpDetailPage'
import { helpFixture } from '@/test/helpFixtures'
import { renderWithProviders } from '@/test/render'
import type { ReactElement } from 'react'
vi.mock ('@/lib/help', async () => (await import ('@/test/helpFixtures')).helpFixture.api)
const Navigation = () => {
const navigate = useNavigate ()
const location = useLocation ()
return (
<>
<output data-testid="location">{location.pathname}{location.search}</output>
<button onClick={() => navigate ('/help/設定%20手順')}>switch article</button>
<button onClick={() => navigate ('/help/guide?edition=2026-10-02.3')}>
switch edition
</button>
</>)
}
const renderDetail = (route = '/help/guide') => renderWithProviders (
<>
<Navigation/>
<Routes>
<Route path="/help/:identifier" element={<HelpDetailPage/>}/>
</Routes>
</>, { route })
describe ('Help details', () => {
beforeEach (() => helpFixture.reset ())
it.each (['2026-10-02', '2026-10-02.2', '2026-10-02.3', '2026-10-02.10']) (
'displays a date without inventing a time for edition %s', async edition => {
const { container } = renderDetail (`/help/guide?edition=${ edition }`)
await screen.findByRole ('heading')
expect (container).toHaveTextContent ('10月2日')
expect (container).not.toHaveTextContent ('Invalid Date')
expect (container.textContent).not.toMatch (/\d{1,2}:\d{2}/)
const revision = edition.split ('.')[1]
if (revision != null)
expect (container).toHaveTextContent (` .${ revision }`)
expect (helpFixture.modules[`../../help/guide/editions/ja/${ edition }.mdx`])
.toHaveBeenCalled ()
})
it ('displays current_edition H1 and body even when newer files exist', async () => {
renderDetail ()
expect (await screen.findByRole ('heading', { name: 'ホーム第十版' }))
.toBeInTheDocument ()
expect (screen.getByText ('タグを検索する 第十版本文')).toBeInTheDocument ()
expect (screen.queryByText ('未公開限定本文')).not.toBeInTheDocument ()
await waitFor (() => expect (document.title).toContain ('ホーム第十版 ヘルプ'))
})
it ('uses the historical H1 in both page and document titles', async () => {
renderDetail ('/help/guide?edition=2026-10-01')
expect (await screen.findByRole ('heading', { name: '旧ホーム' })).toBeInTheDocument ()
expect (screen.getByText ('過去限定本文')).toBeInTheDocument ()
await waitFor (() => expect (document.title).toContain ('旧ホーム ヘルプ'))
expect (screen.getByText ('(最古)')).toBeInTheDocument ()
expect (screen.getByRole ('link', { name: '新 >' }))
.toHaveAttribute ('href', '/help/guide?edition=2026-10-02')
})
it ('navigates .2, .3 and .10 in numeric edition order', async () => {
renderDetail ('/help/guide?edition=2026-10-02.3')
await screen.findByRole ('heading', { name: 'ホーム第三版' })
expect (screen.getByRole ('link', { name: '< 古' }))
.toHaveAttribute ('href', '/help/guide?edition=2026-10-02.2')
const next = screen.getByRole ('link', { name: '新 >' })
expect (next).toHaveAttribute ('href', '/help/guide?edition=2026-10-02.10')
fireEvent.click (next)
await screen.findByRole ('heading', { name: 'ホーム第十版' })
expect (screen.getByText ('(最新)')).toBeInTheDocument ()
expect (screen.queryByText ('第三版本文')).not.toBeInTheDocument ()
})
it.each (['/help/missing', '/help/guide?edition=missing',
'/help/guide?edition=2026-02-30', '/help/guide?edition=2026-10-02.2.extra',
'/help/guide?edition=2026-10-02.11']) (
'shows NotFound without redirecting %s', async route => {
renderDetail (route)
expect (await screen.findByText ('404')).toBeInTheDocument ()
expect (screen.getByTestId ('location')).toHaveTextContent (route)
})
it ('hides the old body and title immediately while another article loads', async () => {
let finish!: (value: { default: () => ReactElement }) => void
const pending = new Promise<{ default: () => ReactElement }> (resolve => {
finish = resolve
})
helpFixture.modules['../../help/設定 手順/editions/ja/2026-10-03.mdx']
.mockReturnValueOnce (pending)
renderDetail ()
await screen.findByRole ('heading', { name: 'ホーム第十版' })
fireEvent.click (screen.getByRole ('button', { name: 'switch article' }))
expect (screen.queryByText ('タグを検索する 第十版本文')).not.toBeInTheDocument ()
await waitFor (() => expect (document.title).not.toContain ('ホーム'))
await act (async () => finish ({ default: () => <h1>設定</h1> }))
await screen.findByRole ('heading', { name: '設定' })
await waitFor (() => expect (document.title).toContain ('設定 ヘルプ'))
})
it ('ignores a late response for the previous edition', async () => {
let finish!: (value: { default: () => ReactElement }) => void
const pending = new Promise<{ default: () => ReactElement }> (resolve => {
finish = resolve
})
const loader = helpFixture.modules['../../help/guide/editions/ja/2026-10-02.10.mdx']
loader.mockReturnValueOnce (pending)
renderDetail ()
await waitFor (() => expect (loader).toHaveBeenCalled ())
fireEvent.click (screen.getByRole ('button', { name: 'switch edition' }))
await screen.findByRole ('heading', { name: 'ホーム第三版' })
await act (async () => finish ({ default: () => <h1>遅延した旧本文</h1> }))
expect (screen.queryByText ('遅延した旧本文')).not.toBeInTheDocument ()
expect (screen.getByRole ('heading', { name: 'ホーム第三版' })).toBeInTheDocument ()
await waitFor (() => expect (document.title).toContain ('ホーム第三版 ヘルプ'))
})
})
+106
ファイルの表示
@@ -0,0 +1,106 @@
import { useQuery } from '@tanstack/react-query'
import { Helmet } from 'react-helmet-async'
import { useLocation, useParams } from 'react-router-dom'
import PrefetchLink from '@/components/PrefetchLink'
import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config'
import { getHelpArticle,
getHelpEditionContent,
helpEditionDate,
parseHelpEdition } from '@/lib/help'
import { dateString } from '@/lib/utils'
import { helpKeys } from '@/lib/queryKeys'
import NotFound from '@/pages/NotFound'
import type { FC } from 'react'
const HelpDetailPage: FC = () => {
const { identifier = '' } = useParams ()
const location = useLocation ()
// Locale 対応が入るまでは ja 固定
const language = 'ja'
const { data: article, isLoading: articleLoading } = useQuery ({
queryKey: helpKeys.article (identifier),
queryFn: () => getHelpArticle (identifier),
staleTime: Infinity })
const query = new URLSearchParams (location.search)
const requestedEdition = query.get ('edition')
const languageMeta = article?.languages[language]
const edition = requestedEdition ?? languageMeta?.currentEdition
const editionInfo = parseHelpEdition (edition ?? '')
const editionDate = helpEditionDate (edition ?? '')
const editions = languageMeta?.publishedEditions ?? []
const index = edition ? editions.indexOf (edition) : -1
const pred = index > 0 ? editions[index - 1] : undefined
const succ =
index >= 0 && index < editions.length - 1
? editions[index + 1]
: undefined
const { data: current, isSuccess, isError } = useQuery ({
enabled: edition != null && editionInfo != null && editions.includes (edition),
queryKey: helpKeys.edition (identifier, language, edition ?? ''),
queryFn: () => getHelpEditionContent (identifier, language, edition ?? ''),
staleTime: Infinity })
if (!articleLoading
&& (article == null
|| languageMeta == null
|| edition == null
|| editionInfo == null
|| !(editions.includes (edition))))
return <NotFound/>
if (isError || (isSuccess && current == null))
return <NotFound/>
const Content = current?.content
return (
<MainArea>
<Helmet>
<title>{current?.title || identifier} ヘルプ | {SITE_TITLE}</title>
</Helmet>
{requestedEdition && (
<div className="text-sm flex gap-3 items-center justify-center
border border-gray-700 rounded px-2 py-1 mb-4">
{pred
? (
<PrefetchLink
to={`/help/${ encodeURIComponent (identifier) }?edition=${ pred }`}>
&lt; 古
</PrefetchLink>)
: '(最古)'}
<span>
{editionDate != null && dateString (editionDate, 'hour')}
{editionInfo?.revision != null && ` .${ editionInfo.revision }`}
</span>
{succ
? (
<PrefetchLink
to={`/help/${ encodeURIComponent (identifier) }?edition=${ succ }`}>
新 &gt;
</PrefetchLink>)
: '(最新)'}
</div>)}
<article className="prose dark:prose-invert mx-auto p-4">
{Content ? <Content/> : <div>Loading...</div>}
</article>
</MainArea>)
}
export default HelpDetailPage
+81
ファイルの表示
@@ -0,0 +1,81 @@
import { useQuery } from '@tanstack/react-query'
import { Helmet } from 'react-helmet-async'
import { useParams, useSearchParams } from 'react-router-dom'
import PrefetchLink from '@/components/PrefetchLink'
import PageTitle from '@/components/common/PageTitle'
import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config'
import { getHelpDiff } from '@/lib/help'
import { helpKeys } from '@/lib/queryKeys'
import { cn } from '@/lib/utils'
import NotFound from '@/pages/NotFound'
import type { FC } from 'react'
const markers = { added: '+ ', removed: '- ', unchanged: ' ' }
const HelpDiffPage: FC = () => {
const { identifier = '' } = useParams ()
const [searchParams] = useSearchParams ()
const from = searchParams.get ('from') ?? ''
const to = searchParams.get ('to') ?? ''
const validParams = Boolean (identifier && from && to)
&& searchParams.getAll ('from').length === 1
&& searchParams.getAll ('to').length === 1
const { data: diff, isLoading, isError } = useQuery ({
enabled: validParams,
queryKey: helpKeys.diff (identifier, 'ja', from, to),
queryFn: () => getHelpDiff (identifier, 'ja', from, to),
staleTime: Infinity })
if (!(validParams) || isError || (!(isLoading) && diff == null))
return <NotFound/>
const title = `${ diff?.to.title ?? identifier } (${ from } → ${ to })`
const path = `/help/${ encodeURIComponent (identifier) }`
return (
<MainArea className="min-w-0 max-w-full">
<Helmet>
<title>{`ヘルプ 差分: ${ title } | ${ SITE_TITLE }`}</title>
</Helmet>
<PageTitle>{title}</PageTitle>
{diff
? (
<>
<div className="flex flex-wrap items-center gap-3">
<PrefetchLink to={`${ path }?edition=${ encodeURIComponent (from) }`}>
{diff.from.title} ({from})
</PrefetchLink>
<span>→</span>
<PrefetchLink to={`${ path }?edition=${ encodeURIComponent (to) }`}>
{diff.to.title} ({to})
</PrefetchLink>
</div>
<pre className="mt-4 overflow-x-auto whitespace-pre">
<code>
{diff.lines.map ((line, index) => {
const colour = cn (
'block text-gray-900 dark:text-gray-100',
line.type === 'added' && 'bg-green-200 dark:bg-green-800',
line.type === 'added' && 'text-green-950 dark:text-green-50',
line.type === 'removed' && 'bg-red-200 dark:bg-red-800',
line.type === 'removed' && 'text-red-950 dark:text-red-50')
return (
<span key={index} className={colour}>
{markers[line.type]}{line.content.replace (/\r?\n$/, '')}
</span>)
})}
</code>
</pre>
</>)
: <div>Loading...</div>}
</MainArea>)
}
export default HelpDiffPage
+130
ファイルの表示
@@ -0,0 +1,130 @@
import { fireEvent, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import HelpListPage from '@/pages/help/HelpListPage'
import { helpFixture } from '@/test/helpFixtures'
import { renderWithProviders } from '@/test/render'
vi.mock ('@/lib/help', async () => (await import ('@/test/helpFixtures')).helpFixture.api)
describe ('Help search', () => {
beforeEach (() => helpFixture.reset ())
it ('initially lists each current article once with encoded detail links', async () => {
renderWithProviders (<HelpListPage/>, { route: '/help' })
expect (await screen.findByRole ('link', { name: 'ホーム第十版' }))
.toHaveAttribute ('href', '/help/guide')
expect (screen.getByRole ('link', { name: '設定' }))
.toHaveAttribute ('href', `/help/${encodeURIComponent ('設定 手順')}`)
expect (screen.getByText ('2 件')).toBeInTheDocument ()
expect (screen.queryByText ('旧ホーム')).not.toBeInTheDocument ()
expect (screen.queryByText ('未公開ホーム')).not.toBeInTheDocument ()
})
it.each ([
['ホーム', '', ['ホーム第十版']],
['', '検索', ['ホーム第十版']],
['', 'タグ', ['設定', 'ホーム第十版']],
['ホーム', '設定', []],
['ホーム', '検索', ['ホーム第十版']],
['旧ホーム', '', []],
['', '過去限定本文', []]]) (
'searches title %s and body %s together', async (title, body, expected) => {
const { container } = renderWithProviders (<HelpListPage/>)
await screen.findByText ('2 件')
fireEvent.change (screen.getByRole ('textbox', { name: 'タイトル' }), {
target: { value: title } })
fireEvent.change (screen.getByRole ('textbox', { name: '内容' }), {
target: { value: body } })
fireEvent.click (screen.getByRole ('button', { name: '検索' }))
expect (Array.from (container.querySelectorAll ('tbody a'), link => link.textContent))
.toEqual (expected)
if (expected.length === 0)
expect (screen.getByText ('該当する記事がありません.')).toBeInTheDocument ()
})
it ('displays loading failures without stale results', async () => {
helpFixture.loads.search.mockImplementationOnce (() => {
throw new Error ('fixture loading failed')
})
renderWithProviders (<HelpListPage/>)
expect (await screen.findByRole ('alert')).toHaveTextContent ('fixture loading failed')
expect (screen.queryByRole ('link', { name: 'ホーム第十版' })).not.toBeInTheDocument ()
})
it ('sorts edition suffixes numerically and displays their date without a time', async () => {
const editions = ['2026-10-02', '2026-10-02.2', '2026-10-02.3', '2026-10-02.10']
helpFixture.assets.search.default.ja = editions.map ((edition, index) => ({
identifier: `article-${ index }`, edition, title: `article-${ index }`, body: '' }))
const { container } = renderWithProviders (<HelpListPage/>, { route: '/help' })
await screen.findByText ('4 件')
expect (Array.from (container.querySelectorAll ('tbody a'), link => link.textContent))
.toEqual (['article-3', 'article-2', 'article-1', 'article-0'])
const dates = Array.from (container.querySelectorAll ('tbody tr'), row =>
row.children[1].textContent)
expect (dates).toHaveLength (4)
dates.forEach (date => {
expect (date).toContain ('10月2日')
expect (date).not.toContain ('Invalid Date')
expect (date).not.toMatch (/\d{1,2}:\d{2}/)
})
})
it.each ([['ホーム', 'ほーむ', '', true], ['ほーむ', 'ホーム', '', true],
['ホーム', 'ホーム', '', true], ['ホーム', '', 'ホーム', true],
['ホーム', 'ほーむ', 'ホーム', true], ['ホーム', 'ほーむ', '不一致', false]] as const) (
'searches title %s with %s and body with %s', async (title, query, text, found) => {
const entry = { identifier: 'guide', edition: '2026-10-02.10',
title, body: 'ほーむの案内' }
helpFixture.assets.search.default.ja = [entry]
const params = new URLSearchParams ({ title: query, text })
renderWithProviders (<HelpListPage/>, { route: `/help?${ params }` })
await screen.findByText (`${ found ? 1 : 0 } 件`)
if (found)
expect (screen.getByRole ('link', { name: title })).toHaveAttribute ('href', '/help/guide')
else
expect (screen.queryByRole ('link', { name: title })).not.toBeInTheDocument ()
expect (entry).toEqual ({ identifier: 'guide', edition: '2026-10-02.10',
title, body: 'ほーむの案内' })
})
// ai_ci equality is documented by MySQL; these are not captured DB sort results.
it.each (['asc', 'desc']) ('orders different titles before identifiers in order %s',
async direction => {
helpFixture.assets.search.default.ja = [
{ identifier: 'alpha', edition: '2026-10-02', title: 'Zebra', body: '' },
{ identifier: 'beta', edition: '2026-10-02', title: 'Apple', body: '' }]
const { container } = renderWithProviders (<HelpListPage/>, {
route: `/help?order=title:${ direction }` })
await screen.findByText ('2 件')
const expected = direction === 'asc'
? ['/help/beta', '/help/alpha'] : ['/help/alpha', '/help/beta']
expect (Array.from (container.querySelectorAll ('tbody a'), link =>
link.getAttribute ('href'))).toEqual (expected)
})
it.each (['asc', 'desc']) ('uses identifier ties for MySQL ai_ci title order %s',
async direction => {
helpFixture.assets.search.default.ja = [
{ identifier: 'alpha', edition: '2026-10-02', title: 'Éclair', body: '' },
{ identifier: 'beta', edition: '2026-10-02', title: 'eclair', body: '' }]
const { container } = renderWithProviders (<HelpListPage/>, {
route: `/help?order=title:${ direction }` })
await screen.findByText ('2 件')
expect (Array.from (container.querySelectorAll ('tbody a'), link =>
link.getAttribute ('href'))).toEqual (['/help/alpha', '/help/beta'])
})
it.each (['asc', 'desc']) ('ignores title case before identifier ties in order %s',
async direction => {
helpFixture.assets.search.default.ja = [
{ identifier: 'alpha', edition: '2026-10-02', title: 'home', body: '' },
{ identifier: 'beta', edition: '2026-10-02', title: 'HOME', body: '' }]
const { container } = renderWithProviders (<HelpListPage/>, {
route: `/help?order=title:${ direction }` })
await screen.findByText ('2 件')
expect (Array.from (container.querySelectorAll ('tbody a'), link =>
link.getAttribute ('href'))).toEqual (['/help/alpha', '/help/beta'])
})
})
+212
ファイルの表示
@@ -0,0 +1,212 @@
import { useQuery } from '@tanstack/react-query'
import { useEffect, useMemo, useState } from 'react'
import { Helmet } from 'react-helmet-async'
import { useSearchParams } from 'react-router-dom'
import PrefetchLink from '@/components/PrefetchLink'
import SortHeader from '@/components/SortHeader'
import FormField from '@/components/common/FormField'
import PageTitle from '@/components/common/PageTitle'
import Pagination from '@/components/common/Pagination'
import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config'
import { compareHelpEditions,
compareHelpTitles,
getHelpSearchEntries,
helpEditionDate,
normaliseHelpSearchText } from '@/lib/help'
import { helpKeys } from '@/lib/queryKeys'
import { LIST_LIMIT_OPTIONS } from '@/lib/settings'
import { dateString, inputClass } from '@/lib/utils'
import type { FormEvent, FC } from 'react'
type SearchConditions = { title: string; text: string }
type HelpOrderField = 'title' | 'updated_at'
type HelpOrder = `${ HelpOrderField }:${ 'asc' | 'desc' }`
const defaultDirection: Record<HelpOrderField, 'asc' | 'desc'> = {
title: 'asc', updated_at: 'desc' }
const HelpSearchPage: FC = () => {
const [searchParams, setSearchParams] = useSearchParams ()
const pageValue = searchParams.get ('page') ?? '1'
const pageNumber = Number (pageValue)
const requestedPage =
(/^[1-9]\d*$/.test (pageValue) && Number.isSafeInteger (pageNumber))
? pageNumber : 1
const limit = LIST_LIMIT_OPTIONS.find (
value => String (value) === searchParams.get ('limit')) ?? 20
const requestedOrder = searchParams.get ('order') ?? 'updated_at:desc'
const order: HelpOrder =
['title:asc', 'title:desc', 'updated_at:asc', 'updated_at:desc'].includes (requestedOrder)
? requestedOrder as HelpOrder
: 'updated_at:desc'
const conditions = useMemo<SearchConditions> (() => ({
title: searchParams.get ('title') ?? '',
text: searchParams.get ('text') ?? '' }), [searchParams])
const [title, setTitle] = useState (conditions.title)
const [text, setText] = useState (conditions.text)
const { data: entries = [], isLoading: loading, error } = useQuery ({
queryKey: helpKeys.index ('ja'),
queryFn: () => getHelpSearchEntries ('ja'),
staleTime: Infinity })
useEffect (() => {
setTitle (conditions.title)
setText (conditions.text)
}, [conditions.title, conditions.text])
const results = useMemo (() => {
const titleQuery = normaliseHelpSearchText (conditions.title.trim ())
const textQuery = normaliseHelpSearchText (conditions.text.trim ())
const [field, direction] = order.split (':')
return (
entries.filter (entry => (
(!(titleQuery)
|| normaliseHelpSearchText (entry.title).includes (titleQuery))
&& (!(textQuery)
|| normaliseHelpSearchText (entry.body).includes (textQuery))))
.sort ((a, b) => {
const comparison = field === 'title'
? compareHelpTitles (a.title, b.title)
: compareHelpEditions (a.edition, b.edition)
return (direction === 'asc' ? comparison : -comparison)
|| a.identifier.localeCompare (b.identifier)
}))
}, [entries, conditions, order])
const totalPages = Math.ceil (results.length / limit)
const page = requestedPage <= Math.max (1, totalPages) ? requestedPage : 1
const pageResults = results.slice ((page - 1) * limit, page * limit)
const handleLimit = (value: string) => {
const next = new URLSearchParams (searchParams)
next.set ('limit', value)
next.set ('page', '1')
setSearchParams (next)
}
const handleSearch = (ev: FormEvent<HTMLFormElement>) => {
ev.preventDefault ()
const next = new URLSearchParams (searchParams)
if (title)
next.set ('title', title)
else
next.delete ('title')
if (text)
next.set ('text', text)
else
next.delete ('text')
next.set ('page', '1')
setSearchParams (next)
}
return (
<MainArea className="min-w-0 max-w-full">
<Helmet>
<title>{`ヘルプ | ${ SITE_TITLE }`}</title>
</Helmet>
<div className="max-w-xl">
<div className="flex flex-wrap items-center justify-between gap-3">
<PageTitle>ヘルプ検索</PageTitle>
<label className="flex items-center gap-2 text-xs text-muted-foreground">
<span>件数</span>
<select value={limit} onChange={ev => handleLimit (ev.target.value)}
className="rounded border border-border bg-background px-2 py-1 text-sm
text-foreground">
{LIST_LIMIT_OPTIONS.map (value => (
<option key={value} value={value}>{value}</option>))}
</select>
</label>
</div>
<form onSubmit={handleSearch} className="space-y-2">
<FormField label="タイトル">
{({ invalid }) => (
<input type="text"
aria-label="タイトル"
value={title}
onChange={e => setTitle (e.target.value)}
className={inputClass (invalid)}/>)}
</FormField>
<FormField label="内容">
{({ invalid }) => (
<input type="text"
aria-label="内容"
value={text}
onChange={e => setText (e.target.value)}
className={inputClass (invalid)}/>)}
</FormField>
<div className="py-3">
<button type="submit"
className="bg-blue-500 text-white px-4 py-2 rounded">
検索
</button>
</div>
</form>
</div>
{loading
? <p className="mt-4">読み込み中...</p>
: (error
? <p className="mt-4 text-red-600" role="alert">{error.message}</p>
: (
<div className="mt-4">
<p className="mb-2 text-sm" aria-live="polite">{results.length} 件</p>
<div className="min-w-0 max-w-full overflow-x-auto">
<table className="table-auto w-full min-w-[640px] whitespace-nowrap
border-collapse text-gray-900 dark:text-gray-100">
<thead className="border-b-2 border-black dark:border-white">
<tr>
<th className="p-2 text-left">
<SortHeader<HelpOrderField>
by="title"
label="タイトル"
currentOrder={order}
defaultDirection={defaultDirection}/>
</th>
<th className="p-2 text-left">
<SortHeader<HelpOrderField>
by="updated_at"
label="有効開始年月日"
currentOrder={order}
defaultDirection={defaultDirection}/>
</th>
</tr>
</thead>
<tbody>
{pageResults.map (entry => {
const updatedAt = helpEditionDate (entry.edition)
return (
<tr key={entry.identifier}
className="even:bg-gray-100 text-gray-900
dark:even:bg-gray-700 dark:text-gray-100">
<td className="p-2">
<PrefetchLink
to={`/help/${encodeURIComponent (entry.identifier)}`}>
{entry.title}
</PrefetchLink>
</td>
<td className="p-2">
{updatedAt != null && dateString (updatedAt, 'hour')}
</td>
</tr>)
})}
</tbody>
</table>
</div>
{totalPages > 0 && <Pagination page={page} totalPages={totalPages}/>}
{results.length === 0 && <p className="mt-4">該当する記事がありません.</p>}
</div>))}
</MainArea>)
}
export default HelpSearchPage
+141 -4
ファイルの表示
@@ -1,14 +1,19 @@
import { screen } from '@testing-library/react'
import { Route, Routes } from 'react-router-dom'
import { describe, expect, it, vi } from 'vitest'
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
import { Route, Routes, useLocation } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { apiPost } from '@/lib/api'
import { getHelpTitleIndex } from '@/lib/help'
import { tagsKeys, wikiKeys } from '@/lib/queryKeys'
import WikiDetailPage from '@/pages/wiki/WikiDetailPage'
import { buildTag, buildWikiPage } from '@/test/factories'
import WikiNewPage from '@/pages/wiki/WikiNewPage'
import { buildTag, buildUser, buildWikiPage } from '@/test/factories'
import { renderWithProviders } from '@/test/render'
const wikiApi = vi.hoisted (() => ({
fetchWikiPage: vi.fn (),
fetchWikiPageByTitle: vi.fn (),
fetchWikiPages: vi.fn (),
}))
const tagsApi = vi.hoisted (() => ({
@@ -22,8 +27,140 @@ const postsApi = vi.hoisted (() => ({
vi.mock ('@/lib/wiki', () => wikiApi)
vi.mock ('@/lib/tags', () => tagsApi)
vi.mock ('@/lib/posts', () => postsApi)
vi.mock ('@/lib/help', () => ({ getHelpTitleIndex: vi.fn () }))
vi.mock ('@/lib/api', async importOriginal => ({
...await importOriginal<typeof import ('@/lib/api')> (), apiPost: vi.fn () }))
vi.mock ('@/components/ui/use-toast', () => ({ toast: vi.fn () }))
vi.mock ('react-markdown-editor-lite', () => ({
default: ({ value, onChange }: {
value: string
onChange: (event: { text: string }) => void }) => (
<textarea aria-label="本文エディタ" value={value}
onChange={event => onChange ({ text: event.target.value })}/>) }))
const Location = () => {
const location = useLocation ()
return <output data-testid="location">{location.pathname}{location.search}</output>
}
describe ('WikiDetailPage', () => {
beforeEach (() => {
wikiApi.fetchWikiPageByTitle.mockReset ().mockResolvedValue (null)
wikiApi.fetchWikiPages.mockReset ().mockResolvedValue ([])
tagsApi.fetchTagByName.mockReset ().mockResolvedValue (null)
postsApi.fetchPosts.mockReset ().mockResolvedValue ({ posts: [], count: 0 })
vi.mocked (getHelpTitleIndex).mockReset ().mockResolvedValue ({ })
vi.mocked (apiPost).mockReset ()
})
it ('offers creation for an existing tag after the Help lookup completes', async () => {
let finish!: (index: Record<string, string[]>) => void
const pending = new Promise<Record<string, string[]>> (resolve => {
finish = resolve
})
vi.mocked (getHelpTitleIndex).mockReturnValueOnce (pending)
tagsApi.fetchTagByName.mockResolvedValue (buildTag ({ name: '既存タグ', hasWiki: false }))
renderWithProviders (
<Routes><Route path="/wiki/:title" element={<WikiDetailPage/>}/></Routes>,
{ route: `/wiki/${ encodeURIComponent ('既存タグ') }` })
await waitFor (() => expect (getHelpTitleIndex).toHaveBeenCalled ())
expect (screen.queryByText ('404')).not.toBeInTheDocument ()
expect (screen.queryByRole ('link', { name: '新規作成してください' }))
.not.toBeInTheDocument ()
await act (async () => finish ({ }))
expect (await screen.findByRole ('link', { name: '新規作成してください' }))
.toHaveAttribute ('href', `/wiki/new?title=${ encodeURIComponent ('既存タグ') }`)
})
it ('creates a tag description through the existing form and displays its content', async () => {
const page = buildWikiPage ({ title: '既存タグ', body: '説明文',
resourceType: 'tag_description' })
tagsApi.fetchTagByName.mockResolvedValue (buildTag ({ name: page.title, hasWiki: false }))
vi.mocked (apiPost).mockResolvedValueOnce (page)
const path = `/wiki/${ encodeURIComponent (page.title) }`
const { container, queryClient } = renderWithProviders (
<>
<Location/>
<Routes>
<Route path="/wiki/new" element={<WikiNewPage user={buildUser ({ role: 'member' })}/>}/>
<Route path="/wiki/:title" element={<WikiDetailPage/>}/>
</Routes>
</>, { route: path })
fireEvent.click (await screen.findByRole ('link', { name: '新規作成してください' }))
await screen.findByRole ('heading', { name: '新規 Wiki ページ' })
expect (queryClient.getQueryData (wikiKeys.show (page.title, { }))).toBeNull ()
queryClient.setQueryData (wikiKeys.index ({ }), [])
wikiApi.fetchWikiPageByTitle.mockResolvedValue (page)
wikiApi.fetchWikiPages.mockResolvedValue ([page])
tagsApi.fetchTagByName.mockResolvedValue (buildTag ({ name: page.title, hasWiki: true }))
expect (screen.getAllByRole ('textbox')[0]).toHaveValue (page.title)
fireEvent.change (screen.getByRole ('textbox', { name: '本文エディタ' }), {
target: { value: page.body } })
fireEvent.click (screen.getByRole ('button', { name: '追加' }))
await screen.findByRole ('heading', { name: page.title })
expect (screen.getByTestId ('location')).toHaveTextContent (path)
expect (screen.queryByRole ('textbox', { name: '本文エディタ' })).not.toBeInTheDocument ()
expect (within (container.querySelector ('article')!).getByText (page.body))
.toBeInTheDocument ()
const form = vi.mocked (apiPost).mock.calls[0][1] as FormData
expect (form.get ('title')).toBe (page.title)
expect (form.get ('body')).toBe (page.body)
expect (apiPost).toHaveBeenCalledWith ('/wiki', form,
{ headers: { 'Content-Type': 'multipart/form-data' } })
expect (screen.queryByText ('404')).not.toBeInTheDocument ()
expect (queryClient.getQueryData (wikiKeys.show (page.title, { }))).toEqual (page)
await waitFor (() => expect (queryClient.getQueryData (wikiKeys.index ({ })))
.toEqual ([page]))
await waitFor (() => expect (queryClient.getQueryData (tagsKeys.show (page.title)))
.toMatchObject ({ hasWiki: true }))
expect (getHelpTitleIndex).toHaveBeenCalledTimes (1)
})
it ('keeps failed saves on the form without changing cached Wiki or tag state', async () => {
const title = '既存タグ'
const tag = buildTag ({ name: title, hasWiki: false })
const path = `/wiki/new?title=${ encodeURIComponent (title) }`
vi.mocked (apiPost).mockRejectedValueOnce (new Error ('save failed'))
const { queryClient } = renderWithProviders (
<><Location/><WikiNewPage user={buildUser ({ role: 'member' })}/></>, { route: path })
queryClient.setQueryData (wikiKeys.show (title, { }), null)
queryClient.setQueryData (wikiKeys.index ({ }), [])
queryClient.setQueryData (tagsKeys.show (title), tag)
fireEvent.change (screen.getByRole ('textbox', { name: '本文エディタ' }), {
target: { value: '保存しない本文' } })
await act (async () => fireEvent.click (screen.getByRole ('button', { name: '追加' })))
expect (apiPost).toHaveBeenCalledTimes (1)
expect (screen.getByTestId ('location')).toHaveTextContent (path)
expect (screen.getByRole ('heading', { name: '新規 Wiki ページ' })).toBeInTheDocument ()
expect (queryClient.getQueryData (wikiKeys.show (title, { }))).toBeNull ()
expect (queryClient.getQueryData (tagsKeys.show (title))).toEqual (tag)
expect (queryClient.getQueryState (wikiKeys.index ({ }))?.isInvalidated).toBe (false)
})
it ('shows NotFound when neither a tag nor a Help title exists', async () => {
renderWithProviders (
<Routes><Route path="/wiki/:title" element={<WikiDetailPage/>}/></Routes>,
{ route: '/wiki/missing' })
expect (await screen.findByText ('404')).toBeInTheDocument ()
expect (screen.queryByRole ('link', { name: '新規作成してください' }))
.not.toBeInTheDocument ()
})
it.each (['403', '500', 'offline']) ('keeps Wiki error %s distinct from missing content',
async message => {
wikiApi.fetchWikiPageByTitle.mockRejectedValue (new Error (message))
tagsApi.fetchTagByName.mockResolvedValue (buildTag ({ name: '既存タグ' }))
renderWithProviders (
<Routes><Route path="/wiki/:title" element={<WikiDetailPage/>}/></Routes>,
{ route: `/wiki/${ encodeURIComponent ('既存タグ') }` })
expect (await screen.findByRole ('alert')).toHaveTextContent (message)
expect (getHelpTitleIndex).not.toHaveBeenCalled ()
expect (screen.queryByRole ('link', { name: '新規作成してください' }))
.not.toBeInTheDocument ()
})
it ('renders deprecated state outside the wiki title link', async () => {
wikiApi.fetchWikiPageByTitle.mockResolvedValueOnce (buildWikiPage ({
title: '旧タグ',
+44 -7
ファイルの表示
@@ -1,5 +1,3 @@
import type { FC } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useEffect, useMemo } from 'react'
import { Helmet } from 'react-helmet-async'
@@ -13,10 +11,14 @@ import TabGroup, { Tab } from '@/components/common/TabGroup'
import MainArea from '@/components/layout/MainArea'
import { SITE_TITLE } from '@/config'
import { WikiIdBus } from '@/lib/eventBus/WikiIdBus'
import { getHelpTitleIndex } from '@/lib/help'
import { fetchPosts } from '@/lib/posts'
import { postsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys'
import { helpKeys, postsKeys, tagsKeys, wikiKeys } from '@/lib/queryKeys'
import { fetchTagByName } from '@/lib/tags'
import { fetchWikiPage, fetchWikiPageByTitle } from '@/lib/wiki'
import NotFound from '@/pages/NotFound'
import type { FC } from 'react'
import type { Tag } from '@/types'
@@ -33,15 +35,33 @@ const WikiDetailPage: FC = () => {
const query = new URLSearchParams (location.search)
const version = query.get ('version') || undefined
const { data: wikiPage, isLoading: loading } = useQuery ({
const { data: wikiPage, isLoading: loading, isSuccess, isFetching, error } = useQuery ({
enabled: Boolean (title) && !(/^\d+$/.test (title)),
queryKey: wikiKeys.show (title, { version }),
queryFn: () => fetchWikiPageByTitle (title, { version }) })
const missingWiki = isSuccess && !(isFetching) && wikiPage == null
const { data: titleIndex, isPending: lookupPending,
isFetching: lookupFetching, error: lookupError } = useQuery ({
enabled: missingWiki,
queryKey: helpKeys.titles ('ja'),
queryFn: () => getHelpTitleIndex ('ja'),
staleTime: Infinity })
const lookupTitle = title.trim ().normalize ('NFKC').toLowerCase ().replace (/^ヘルプ:/, '')
const identifiers = useMemo (() => (
(titleIndex != null && Object.hasOwn (titleIndex, lookupTitle))
? titleIndex[lookupTitle] : []), [titleIndex, lookupTitle])
useEffect (() => {
if (missingWiki && !(lookupFetching) && lookupError == null && identifiers.length === 1)
navigate (`/help/${ encodeURIComponent (identifiers[0]) }`, { replace: true })
}, [missingWiki, lookupFetching, lookupError, identifiers, navigate])
const effectiveTitle = wikiPage?.title ?? title
const deprecated = wikiPage?.deprecatedAt != null
const { data: tag } = useQuery ({
const { data: tag, isPending: tagPending,
isFetching: tagFetching, error: tagError } = useQuery ({
enabled: Boolean (effectiveTitle),
queryKey: tagsKeys.show (effectiveTitle),
queryFn: () => fetchTagByName (effectiveTitle) })
@@ -73,19 +93,36 @@ const WikiDetailPage: FC = () => {
if (!(/^\d+$/.test (title)))
return
let active = true
void (async () => {
try
{
const data = await fetchWikiPage (title, { })
navigate (`/wiki/${ encodeURIComponent(data.title) }`, { replace: true })
if (active)
navigate (`/wiki/${ encodeURIComponent (data.title) }`, { replace: true })
}
catch
{
;
}
}) ()
return () => {
active = false
}
}, [title, navigate])
const displayError = error ?? (missingWiki ? lookupError ?? tagError : null)
if (displayError != null)
return <MainArea><p role="alert">{displayError.message}</p></MainArea>
const waiting = loading || (isFetching && wikiPage == null)
|| (missingWiki && (lookupPending || lookupFetching || tagPending
|| (tagFetching && tag == null) || identifiers.length === 1))
if (missingWiki && !(waiting) && (tag == null || version != null))
return <NotFound/>
return (
<MainArea>
<Helmet>
@@ -119,7 +156,7 @@ const WikiDetailPage: FC = () => {
{...(version && { to: `/wiki/${ encodeURIComponent (title) }` })}/>
{deprecated && <span>(廃止)</span>}
</h1>
{loading ? <div>Loading...</div> : <WikiBody title={title} body={wikiPage?.body}/>}
{waiting ? <div>Loading...</div> : <WikiBody title={title} body={wikiPage?.body}/>}
{(!(version) && posts.length > 0) && (
<div className="not-prose">
+144
ファイルの表示
@@ -0,0 +1,144 @@
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import { Route, Routes, useLocation, useNavigate } from 'react-router-dom'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { apiGet } from '@/lib/api'
import * as help from '@/lib/help'
import HelpDetailPage from '@/pages/help/HelpDetailPage'
import WikiDetailPage from '@/pages/wiki/WikiDetailPage'
import { buildWikiPage } from '@/test/factories'
import { helpFixture } from '@/test/helpFixtures'
import { renderWithProviders } from '@/test/render'
vi.mock ('@/lib/api', () => ({ apiGet: vi.fn () }))
vi.mock ('@/lib/help', async () => (await import ('@/test/helpFixtures')).helpFixture.api)
vi.mock ('@/lib/tags', () => ({ fetchTagByName: async () => null }))
vi.mock ('@/lib/posts', () => ({ fetchPosts: async () => ({ posts: [], count: 0 }) }))
const Location = () => {
const location = useLocation ()
const navigate = useNavigate ()
return (
<>
<output data-testid="location">{location.pathname}{location.search}</output>
<button onClick={() => navigate (`/wiki/${ encodeURIComponent ('該当なし') }`)}>
switch title
</button>
</>)
}
const renderWiki = (title: string) => {
const route = `/wiki/${encodeURIComponent (title)}`
const { queryClient } = renderWithProviders (
<>
<Location/>
<Routes>
<Route path="/wiki/:title" element={<WikiDetailPage/>}/>
<Route path="/help/:identifier" element={<HelpDetailPage/>}/>
<Route path="/404" element={<div>unexpected redirect</div>}/>
</Routes>
</>, { route })
return { route, queryClient }
}
describe ('Legacy Wiki to Help compatibility', () => {
beforeEach (() => {
helpFixture.reset ()
vi.mocked (apiGet).mockReset ()
vi.mocked (apiGet).mockImplementation (async path => {
if (path === '/wiki')
return []
throw { isAxiosError: true, response: { status: 404 } }
})
})
it ('keeps a successful Wiki result even when Help has the same title', async () => {
vi.mocked (apiGet).mockResolvedValueOnce (buildWikiPage ({
title: 'ホーム', body: 'Wiki の現行本文' }))
const { route } = renderWiki ('ホーム')
await screen.findByText ('Wiki の現行本文')
expect (screen.getByTestId ('location')).toHaveTextContent (route)
expect (screen.queryByText ('タグを検索する')).not.toBeInTheDocument ()
expect (helpFixture.loads.titles).not.toHaveBeenCalled ()
})
it.each (['ホーム', 'ヘルプ:ホーム', '旧ホーム', 'ヘルプ:旧ホーム', 'ホーム第十版']) (
'redirects a unique current or historical Japanese title: %s', async title => {
renderWiki (title)
await waitFor (() => {
expect (screen.getByTestId ('location')).toHaveTextContent ('/help/guide')
})
expect (await screen.findByRole ('heading', { name: 'ホーム第十版' }))
.toBeInTheDocument ()
Object.values (helpFixture.raw).forEach (load => expect (load).not.toHaveBeenCalled ())
expect (apiGet).toHaveBeenCalledWith (
`/wiki/title/${encodeURIComponent (title)}`, expect.anything ())
})
it ('keeps the original URL and displays NotFound when no title matches', async () => {
const { route, queryClient } = renderWiki ('該当なし')
await screen.findByText ('404')
await waitFor (() => {
expect (helpFixture.loads.titles).toHaveBeenCalled ()
expect (queryClient.isFetching ()).toBe (0)
})
expect (screen.getByTestId ('location')).toHaveTextContent (route)
expect (screen.queryByText ('unexpected redirect')).not.toBeInTheDocument ()
})
it ('does not choose between articles with the same title', async () => {
helpFixture.assets.titles.default.ja['ホーム'] = ['guide', '設定 手順']
const { route, queryClient } = renderWiki ('ホーム')
await screen.findByText ('404')
await waitFor (() => {
expect (helpFixture.loads.titles).toHaveBeenCalled ()
expect (queryClient.isFetching ()).toBe (0)
})
expect (screen.getByTestId ('location')).toHaveTextContent (route)
})
it ('waits for title lookup and does not redirect a later Wiki URL using an old title',
async () => {
let finish!: (index: Record<string, string[]>) => void
const pending = new Promise<Record<string, string[]>> (resolve => {
finish = resolve
})
const lookup = vi.spyOn (help, 'getHelpTitleIndex').mockReturnValueOnce (pending)
renderWiki ('ホーム')
await waitFor (() => expect (lookup).toHaveBeenCalled ())
expect (screen.queryByText ('404')).not.toBeInTheDocument ()
fireEvent.click (screen.getByRole ('button', { name: 'switch title' }))
await waitFor (() => expect (apiGet).toHaveBeenCalledWith (
`/wiki/title/${ encodeURIComponent ('該当なし') }`, expect.anything ()))
await act (async () => finish ({ 'ホーム': ['guide'] }))
await screen.findByText ('404')
expect (screen.getByTestId ('location'))
.toHaveTextContent (`/wiki/${ encodeURIComponent ('該当なし') }`)
})
it ('does not treat a Wiki network failure as a missing Wiki', async () => {
vi.mocked (apiGet).mockRejectedValueOnce (new Error ('offline'))
const { route } = renderWiki ('ホーム')
expect (await screen.findByRole ('alert')).toHaveTextContent ('offline')
expect (screen.getByTestId ('location')).toHaveTextContent (route)
expect (helpFixture.loads.titles).not.toHaveBeenCalled ()
expect (screen.queryByText ('404')).not.toBeInTheDocument ()
expect (screen.queryByRole ('link', { name: '新規作成してください' }))
.not.toBeInTheDocument ()
})
it.each ([403, 500]) ('does not redirect HTTP %s to Help', async status => {
vi.mocked (apiGet).mockRejectedValueOnce ({ isAxiosError: true, response: { status } })
const { route, queryClient } = renderWiki ('ホーム')
await waitFor (() => {
expect (apiGet).toHaveBeenCalled ()
expect (queryClient.isFetching ()).toBe (0)
})
expect (screen.getByTestId ('location')).toHaveTextContent (route)
expect (screen.queryByText ('タグを検索する')).not.toBeInTheDocument ()
expect (helpFixture.loads.titles).not.toHaveBeenCalled ()
})
})
+11 -4
ファイルの表示
@@ -1,10 +1,10 @@
import type { FC } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import MarkdownIt from 'markdown-it'
import { useState } from 'react'
import { Helmet } from 'react-helmet-async'
import MdEditor from 'react-markdown-editor-lite'
import { useLocation, useNavigate } from 'react-router-dom'
import 'react-markdown-editor-lite/lib/index.css'
import FieldError from '@/components/common/FieldError'
import FormField from '@/components/common/FormField'
@@ -12,12 +12,13 @@ import MainArea from '@/components/layout/MainArea'
import { toast } from '@/components/ui/use-toast'
import { SITE_TITLE } from '@/config'
import { apiPost } from '@/lib/api'
import { tagsKeys, wikiKeys } from '@/lib/queryKeys'
import { canEditContent } from '@/lib/users'
import { inputClass } from '@/lib/utils'
import { useValidationErrors } from '@/lib/useValidationErrors'
import Forbidden from '@/pages/Forbidden'
import 'react-markdown-editor-lite/lib/index.css'
import type { FC } from 'react'
import type { User, WikiPage } from '@/types'
@@ -38,6 +39,7 @@ const WikiNewPage: FC<Props> = ({ user }) => {
const location = useLocation ()
const navigate = useNavigate ()
const qc = useQueryClient ()
const query = new URLSearchParams (location.search)
const titleQuery = query.get ('title') ?? ''
@@ -58,8 +60,13 @@ const WikiNewPage: FC<Props> = ({ user }) => {
{
const data = await apiPost<WikiPage> ('/wiki', formData,
{ headers: { 'Content-Type': 'multipart/form-data' } })
await qc.cancelQueries ({ queryKey: wikiKeys.root })
qc.setQueryData (wikiKeys.show (data.title, { }), data)
await Promise.all ([
qc.invalidateQueries ({ queryKey: wikiKeys.root }),
qc.invalidateQueries ({ queryKey: tagsKeys.root })])
toast ({ title: '投稿成功!' })
navigate (`/wiki/${ data.title }`)
navigate (`/wiki/${ encodeURIComponent (data.title) }`)
}
catch (e)
{
+33 -37
ファイルの表示
@@ -1,62 +1,58 @@
import { fireEvent, screen, waitFor } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { apiGet } from '@/lib/api'
import WikiSearchPage from '@/pages/wiki/WikiSearchPage'
import { buildWikiPage } from '@/test/factories'
import { renderWithProviders } from '@/test/render'
const api = vi.hoisted (() => ({
apiGet: vi.fn (),
}))
vi.mock ('@/lib/api', () => ({ apiGet: vi.fn () }))
vi.mock ('@/lib/api', () => api)
describe ('WikiSearchPage', () => {
describe ('Wiki resource identity', () => {
beforeEach (() => vi.mocked (apiGet).mockReset ())
it ('loads initial wiki pages and renders links', async () => {
api.apiGet.mockResolvedValueOnce ([buildWikiPage ({ title: '虹夏' })])
vi.mocked (apiGet).mockResolvedValueOnce ([buildWikiPage ({ title: '虹夏' })])
renderWithProviders (<WikiSearchPage/>)
expect (await screen.findByRole ('link', { name: '虹夏' })).toHaveAttribute (
'href',
'/wiki/%E8%99%B9%E5%A4%8F',
)
expect (api.apiGet).toHaveBeenCalledWith ('/wiki', { params: { title: '' } })
expect (await screen.findByRole ('link', { name: '虹夏' }))
.toHaveAttribute ('href', '/wiki/%E8%99%B9%E5%A4%8F')
expect (apiGet).toHaveBeenCalledWith ('/wiki', { params: { title: '' } })
})
it ('searches by title on submit', async () => {
api.apiGet
.mockResolvedValueOnce ([])
.mockResolvedValueOnce ([buildWikiPage ({ title: '検索結果' })])
vi.mocked (apiGet).mockResolvedValueOnce ([])
.mockResolvedValueOnce ([buildWikiPage ({ title: '検索結果' })])
renderWithProviders (<WikiSearchPage/>)
await waitFor (() => expect (apiGet).toHaveBeenCalledTimes (1))
fireEvent.change (screen.getAllByRole ('textbox')[0], { target: { value: '検索' } })
fireEvent.click (screen.getByRole ('button', { name: '検索' }))
await waitFor (() => {
expect (api.apiGet).toHaveBeenLastCalledWith (
'/wiki',
{ params: { title: '検索' } },
)
})
await waitFor (() => expect (apiGet).toHaveBeenLastCalledWith (
'/wiki', { params: { title: '検索' } }))
expect (await screen.findByRole ('link', { name: '検索結果' })).toBeInTheDocument ()
})
it ('marks deprecated wiki tags in the result title', async () => {
api.apiGet.mockResolvedValueOnce ([
buildWikiPage ({
title: '旧タグ',
deprecatedAt: '2026-06-01T00:00:00.000Z',
}),
])
vi.mocked (apiGet).mockResolvedValueOnce ([buildWikiPage ({
title: '旧タグ', deprecatedAt: '2026-06-01T00:00:00.000Z' })])
renderWithProviders (<WikiSearchPage/>)
expect (await screen.findByRole ('link', { name: '旧タグ' })).toBeInTheDocument ()
expect (screen.getByText ('(廃止)').closest ('a')).toBeNull ()
})
it ('renders colliding description and group IDs with stable distinct keys', async () => {
const errors = vi.spyOn (console, 'error').mockImplementation (() => {})
const description = buildWikiPage ({ id: 51, title: '説明', resourceType: 'tag_description' })
const group = buildWikiPage ({ id: 51, title: 'タググループ:一覧', resourceType: 'tag_group' })
vi.mocked (apiGet).mockResolvedValue ([description, group])
renderWithProviders (<WikiSearchPage/>)
const link = await screen.findByRole ('link', { name: '旧タグ' })
const marker = screen.getByText ('(廃止)')
expect (link).toBeInTheDocument ()
expect (marker.closest ('a')).toBeNull ()
await screen.findByRole ('link', { name: '説明' })
expect (screen.getByRole ('link', { name: 'タググループ:一覧' }))
.toHaveAttribute ('href', `/wiki/${ encodeURIComponent (group.title) }`)
await waitFor (() => {
expect (errors.mock.calls.some (args => args.some (value =>
String (value).includes ('same key')))).toBe (false)
})
})
})
+2 -1
ファイルの表示
@@ -81,7 +81,8 @@ const WikiSearchPage: FC = () => {
</thead>
<tbody>
{results.map (page => (
<tr key={page.id} className="even:bg-gray-100 dark:even:bg-gray-700">
<tr key={`${ page.resourceType }:${ page.id }`}
className="even:bg-gray-100 dark:even:bg-gray-700">
<td className="p-2">
<PrefetchLink to={`/wiki/${ encodeURIComponent (page.title) }`}>
{page.title}
+37
ファイルの表示
@@ -0,0 +1,37 @@
import * as jsxRuntime from 'react/jsx-runtime'
import { ModuleKind, ScriptTarget, transpileModule } from 'typescript'
import { useMDXComponents } from '@/mdx-components'
import viteConfig from '../../vite.config'
import type { ComponentType } from 'react'
type Transform = (source: string, id: string) => Promise<{ code: string } | null>
export const transformMdx = async (source: string, suffix = '.mdx') => {
const plugins = viteConfig.plugins?.flat () as { name: string; transform: Transform }[]
const plugin = plugins.find (entry => entry.name === '@mdx-js/rollup')
if (plugin == null)
throw new Error ('The application MDX compiler is not registered')
return plugin.transform.call (plugin, source, `/test/help-table${suffix}`)
}
export const compileMdx = async (source: string): Promise<ComponentType> => {
const result = await transformMdx (source)
if (result == null)
throw new Error ('MDX was not compiled')
const code = transpileModule (result.code, {
compilerOptions: { module: ModuleKind.CommonJS, target: ScriptTarget.ES2022 } }).outputText
const exports = { } as { default: ComponentType }
const requireFixture = (name: string) => {
if (name === 'react/jsx-runtime')
return jsxRuntime
if (name === '@/mdx-components')
return { useMDXComponents }
throw new Error (`Unexpected MDX dependency: ${name}`)
}
new Function ('require', 'exports', code) (requireFixture, exports)
return exports.default
}
+1
ファイルの表示
@@ -59,6 +59,7 @@ export const buildUser = (overrides: Partial<User> = {}): User => ({
})
export const buildWikiPage = (overrides: Partial<WikiPage> = {}): WikiPage => ({
resourceType: 'tag_description',
id: 1,
title: 'テストWiki',
deprecatedAt: null,
+126
ファイルの表示
@@ -0,0 +1,126 @@
import { createElement } from 'react'
import { ModuleKind, ScriptTarget, transpileModule } from 'typescript'
import { vi } from 'vitest'
import source from '@/lib/help.ts?raw'
import type { ComponentType } from 'react'
import type * as Help from '@/lib/help'
export const editionRows = [
['guide', 'ja', '2026-10-01', '旧ホーム', '過去限定本文'],
['guide', 'ja', '2026-10-02', 'ホーム', 'タグを検索する'],
['guide', 'ja', '2026-10-02.2', 'ホーム第二版', '第二版本文'],
['guide', 'ja', '2026-10-02.3', 'ホーム第三版', '第三版本文'],
['guide', 'ja', '2026-10-02.10', 'ホーム第十版', 'タグを検索する 第十版本文'],
['guide', 'ja', '2026-10-02.11', '未公開ホーム', '未公開限定本文'],
['guide', 'en', '2026-10-02', 'Home', 'English body'],
['設定 手順', 'ja', '2026-10-03', '設定', 'タグを設定する']] as const
const compiled = transpileModule (source, {
compilerOptions: { module: ModuleKind.CommonJS, target: ScriptTarget.ES2022 } }).outputText
// Supply generated virtual modules, executing the actual runtime Help module.
export const createHelpFixture = () => {
const articles: Record<string, Help.ArticleMeta> = {
guide: { identifier: 'guide', canonicalLanguage: 'ja', languages: {
ja: { currentEdition: '2026-10-02.10', publishedEditions: [
'2026-10-01', '2026-10-02', '2026-10-02.2', '2026-10-02.3', '2026-10-02.10'] },
en: { currentEdition: '2026-10-02', publishedEditions: ['2026-10-02'] } } },
'設定 手順': { identifier: '設定 手順', canonicalLanguage: 'ja', languages: {
ja: { currentEdition: '2026-10-03', publishedEditions: ['2026-10-03'] } } } }
const published = editionRows.filter (([id, language, edition]) =>
articles[id].languages[language].publishedEditions.includes (edition))
const raw = Object.fromEntries (editionRows.map (([id, language, edition, title, body]) => [
`../../help/${id}/editions/${language}/${edition}.mdx`,
vi.fn (async () => `# ${title}\n\n${body}`)]))
const moduleLoads = Object.fromEntries (published.map (([id, language, edition, title, body]) => [
`../../help/${id}/editions/${language}/${edition}.mdx`,
vi.fn (async (): Promise<{ default: ComponentType }> => ({
default: () => createElement ('div', null,
createElement ('h1', null, title), createElement ('p', null, body)) }))]))
// Dynamic imports reuse a module namespace even when called more than once.
const caches: Record<string, { promise?: Promise<{ default: ComponentType }> }> = { }
const modules = Object.fromEntries (Object.entries (moduleLoads).map (([path, load]) => {
caches[path] = { }
return [path, vi.fn (() => caches[path].promise ??= load ())]
}))
const texts = Object.fromEntries (published.map (([id, language, edition, title, body]) => [
`${ id }/${ language }/${ edition }`,
vi.fn (async () => ({ default: { title, body: `\n${ body }` } }))]))
const components = Object.fromEntries (published.map (([id, language, edition]) => [
`${ id }/${ language }/${ edition }`,
modules[`../../help/${ id }/editions/${ language }/${ edition }.mdx`]]))
const sources = Object.fromEntries (published.map (([id, language, edition]) => [
`${ id }/${ language }/${ edition }`,
async () => ({ default: await raw[
`../../help/${ id }/editions/${ language }/${ edition }.mdx`] () })]))
const search: Record<string, Help.HelpSearchEntry[]> = { }
const changes: Record<string, Help.HelpChange[]> = { }
const titles: Record<string, Help.HelpTitleIndex> = { }
published.forEach (([id, language, edition, title, body]) => {
const editions = articles[id].languages[language].publishedEditions
const index = editions.indexOf (edition)
const searchRows = search[language] ??= []
if (articles[id].languages[language].currentEdition === edition)
searchRows.push ({ identifier: id, edition, title, body: `\n${ body }` })
const rows = changes[language] ??= []
rows.push ({ identifier: id, edition, title,
pred: editions[index - 1] ?? null,
change: index === 0 ? 'new' : 'update', date: edition.split ('.')[0] })
const lookup = (titles[language] ??= { })
const identifiers = lookup[title.trim ().normalize ('NFKC').toLowerCase ()] ??= []
if (!(identifiers.includes (id)))
identifiers.push (id)
})
Object.values (changes).forEach (rows => rows.sort ((a, b) => {
const [dateA, revisionA = '1'] = a.edition.split ('.')
const [dateB, revisionB = '1'] = b.edition.split ('.')
return dateB.localeCompare (dateA) || Number (revisionB) - Number (revisionA)
|| a.identifier.localeCompare (b.identifier)
}))
const assets = {
articles: { default: articles }, search: { default: search },
changes: { default: changes }, titles: { default: titles } }
const snapshot = JSON.stringify (assets)
const loaders = { components, sources, texts }
const loads = {
articles: vi.fn (() => assets.articles), search: vi.fn (() => assets.search),
changes: vi.fn (() => assets.changes), titles: vi.fn (() => assets.titles),
loaders: vi.fn (() => loaders) }
const api = { } as typeof Help
const requireFixture = (name: string) => {
const key = name.replace ('virtual:help/', '') as keyof typeof loads
if (Object.hasOwn (loads, key))
return loads[key] ()
throw new Error (`Unexpected Help dependency: ${name}`)
}
new Function ('require', 'exports', compiled) (requireFixture, api)
const reset = () => {
Object.assign (assets, JSON.parse (snapshot))
editionRows.forEach (([id, language, edition, title, body]) => {
const path = `../../help/${ id }/editions/${ language }/${ edition }.mdx`
raw[path].mockReset ().mockResolvedValue (`# ${ title }\n\n${ body }`)
})
published.forEach (([id, language, edition, title, body]) => {
const path = `../../help/${ id }/editions/${ language }/${ edition }.mdx`
caches[path].promise = undefined
moduleLoads[path].mockClear ()
modules[path].mockReset ().mockImplementation (() =>
caches[path].promise ??= moduleLoads[path] ())
texts[`${ id }/${ language }/${ edition }`].mockReset ().mockResolvedValue ({
default: { title, body: `\n${ body }` } })
})
loads.articles.mockReset ().mockImplementation (() => assets.articles)
loads.search.mockReset ().mockImplementation (() => assets.search)
loads.changes.mockReset ().mockImplementation (() => assets.changes)
loads.titles.mockReset ().mockImplementation (() => assets.titles)
loads.loaders.mockReset ().mockImplementation (() => loaders)
}
return { api, assets, loads, raw, modules, moduleLoads, texts, reset }
}
export const helpFixture = createHelpFixture ()
+1
ファイルの表示
@@ -452,6 +452,7 @@ export type ViewFlagBehavior = typeof ViewFlagBehavior[keyof typeof ViewFlagBeha
export type WikiPage = {
id: number
resourceType: 'tag_description' | 'tag_group'
title: string
deprecatedAt: string | null
createdUserId: number
ベンダーファイル
+28
ファイルの表示
@@ -1 +1,29 @@
/// <reference types="vite/client" />
declare module 'virtual:help/articles' {
const articles: Record<string, import ('./lib/help').ArticleMeta>
export default articles
}
declare module 'virtual:help/search' {
const search: Record<string, import ('./lib/help').HelpSearchEntry[]>
export default search
}
declare module 'virtual:help/changes' {
const changes: Record<string, import ('./lib/help').HelpChange[]>
export default changes
}
declare module 'virtual:help/titles' {
const titles: Record<string, import ('./lib/help').HelpTitleIndex>
export default titles
}
declare module 'virtual:help/loaders' {
export const components: Record<string,
() => Promise<{ default: import ('react').ComponentType }>>
export const sources: Record<string, () => Promise<{ default: string }>>
export const texts: Record<string,
() => Promise<{ default: import ('./lib/help').HelpEditionText }>>
}
+18 -2
ファイルの表示
@@ -1,12 +1,28 @@
import mdx from '@mdx-js/rollup'
import react from '@vitejs/plugin-react'
import path from 'path'
import remarkGFM from 'remark-gfm'
import { defineConfig } from 'vite'
import { helpAssets } from './scripts/help-assets'
const mdxPlugin = mdx ({ providerImportSource: '@/mdx-components',
remarkPlugins: [remarkGFM] })
const originalTransform = mdxPlugin.transform
if (typeof originalTransform === 'function')
{
mdxPlugin.transform =
function (code, id)
{
return (/[?&](raw|url)(?:&|$)/.test (id)
? null
: originalTransform.call (this, code, id))
}
}
// https://vite.dev/config/
export default defineConfig ({
plugins: [mdx ({ providerImportSource: '@/mdx-components' }), react ()],
plugins: [helpAssets (), mdxPlugin, react ()],
resolve: { alias: { '@': path.resolve (__dirname, './src') } },
server: { host: true,
port: 5173,