diff --git a/CLAUDE.md b/CLAUDE.md index d45bc03..312174c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,11 +12,13 @@ DocView (`docview` / `mdv`) — Node.js CLI tool that serves a local directory a npm run dev # Vite dev server with HMR npm run build # tsc + vite build → dist/ npm run serve # Build then launch server.mjs +npm run test:unit # node:test suites (tests/*.test.mjs) for server/CLI behavior +npm run check:contrast # Theme color contrast check npm run test:e2e # Playwright E2E tests (requires Chromium) npx playwright test tests/core.spec.ts --headed # Run single test file with browser visible ``` -Tests expect the server on port 4000 — Playwright config auto-starts `node server.mjs /tmp/md-test-docs --port 4000`. +E2E tests run against the built `dist/` (run `npm run build` first). Playwright config auto-starts DocView on port 4001 (`--allow-private-remote`) and 4002 (default security), both serving `/tmp/md-test-docs` (fixtures written by `tests/setup.ts`), plus a mock remote server on 4090. Outside CI it reuses servers already listening on those ports — stop stale ones after changing `server.mjs`. No linter/formatter configured; TypeScript strict mode is the quality gate. diff --git a/server.mjs b/server.mjs index 5b0caba..b400502 100644 --- a/server.mjs +++ b/server.mjs @@ -153,12 +153,16 @@ const ENCODING_MAP = { 'koi8-r': 'koi8-r', }; +function hasUtf8Bom(buf) { + return buf[0] === 0xEF && buf[1] === 0xBB && buf[2] === 0xBF; +} + /** * Detect encoding from a buffer and return a TextDecoder-compatible label. */ function detectEncoding(buf) { // BOM detection - if (buf[0] === 0xEF && buf[1] === 0xBB && buf[2] === 0xBF) return 'utf-8'; + if (hasUtf8Bom(buf)) return 'utf-8'; if (buf[0] === 0xFF && buf[1] === 0xFE) return 'utf-16le'; if (buf[0] === 0xFE && buf[1] === 0xFF) return 'utf-16be'; @@ -174,7 +178,9 @@ function detectEncoding(buf) { async function readFileText(filePath) { const buf = await readFile(filePath); const encoding = detectEncoding(buf); - if (encoding === 'utf-8') return buf.toString('utf-8'); + // Drop a UTF-8 BOM like TextDecoder does for the other encodings: kept, it + // defeats `^` anchors on line 1 in search and leaks into the first CSV header. + if (encoding === 'utf-8') return buf.toString('utf-8', hasUtf8Bom(buf) ? 3 : 0); const decoder = new TextDecoder(encoding); return decoder.decode(buf); } @@ -193,7 +199,7 @@ async function createTextReadStream(filePath) { const { bytesRead } = await fh.read(sample, 0, 4096, 0); const encoding = detectEncoding(sample.subarray(0, bytesRead)); if (encoding === 'utf-8') { - return createReadStream(filePath, { encoding: 'utf-8' }); + return createReadStream(filePath, { encoding: 'utf-8', start: hasUtf8Bom(sample) ? 3 : 0 }); } // Non-UTF-8: read full file, decode, return as stream const buf = await readFile(filePath); diff --git a/src/chunked-table.ts b/src/chunked-table.ts index 7b91329..505afc2 100644 --- a/src/chunked-table.ts +++ b/src/chunked-table.ts @@ -33,6 +33,11 @@ interface SearchResult { const PAGE_SIZE = 1000; const SEARCH_DEBOUNCE_MS = 300; +/** Enter/Escape that commit or cancel an IME conversion (Safari: keyCode 229). */ +function isImeKey(e: KeyboardEvent): boolean { + return e.isComposing || e.keyCode === 229; +} + // --- Shared HTML helpers --- function esc(s: string): string { @@ -650,6 +655,7 @@ export class ChunkedTable { } }; input.addEventListener('keydown', (e) => { + if (isImeKey(e)) return; if (e.key === 'Enter') { e.preventDefault(); onSubmit(); } }); input.addEventListener('change', onSubmit); @@ -658,6 +664,7 @@ export class ChunkedTable { // Row-jump input ("行へ移動") this.container.querySelectorAll('.chunk-row-jump-input').forEach((input) => { input.addEventListener('keydown', (e) => { + if (isImeKey(e)) return; if (e.key === 'Enter') { e.preventDefault(); void this.jumpToRow(input); } }); }); @@ -683,6 +690,7 @@ export class ChunkedTable { }, SEARCH_DEBOUNCE_MS); }); searchInput.addEventListener('keydown', (e) => { + if (isImeKey(e)) return; if (e.key === 'Escape') { searchInput.value = ''; this.executeSearch(''); diff --git a/src/find-bar.ts b/src/find-bar.ts index 15e7d89..37ed005 100644 --- a/src/find-bar.ts +++ b/src/find-bar.ts @@ -28,6 +28,9 @@ export class FindBar { // Events this.input.addEventListener('input', () => this.search()); this.input.addEventListener('keydown', (e) => { + // Enter/Escape that commit or cancel an IME conversion are not ours (Safari + // reports the committing Enter with isComposing=false but keyCode 229). + if (e.isComposing || e.keyCode === 229) return; if (e.key === 'Enter' && e.shiftKey) { e.preventDefault(); this.prev(); } else if (e.key === 'Enter') { e.preventDefault(); this.next(); } else if (e.key === 'Escape') { this.close(); } @@ -35,6 +38,11 @@ export class FindBar { this.bar.querySelector('.find-next')!.addEventListener('click', () => this.next()); this.bar.querySelector('.find-prev')!.addEventListener('click', () => this.prev()); this.bar.querySelector('.find-close')!.addEventListener('click', () => this.close()); + // Hidden Tree/Source halves are excluded from matches, so re-run the query + // once a toggle (whose own listener has already swapped views) reveals the other. + viewer.addEventListener('click', (e) => { + if (this.isOpen && this.input.value && (e.target as Element | null)?.closest('.json-toggle-btn')) this.search(); + }); // Insert into viewer's parent viewer.parentElement!.insertBefore(this.bar, viewer); @@ -92,24 +100,27 @@ export class FindBar { private findAllMatches(query: string): Range[] { const ranges: Range[] = []; - const lowerQuery = query.toLowerCase(); - const walker = document.createTreeWalker(this.viewer, NodeFilter.SHOW_TEXT); + // Case-insensitive matching on the original text: indices from a + // lower-cased copy drift when lower-casing changes length (e.g. "İ"). + const pattern = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'giu'); + // Skip the inactive half of a Tree/Source toggle: every view renders both, + // so counting the hidden copy doubles the total and next/prev land on + // invisible text. + const walker = document.createTreeWalker(this.viewer, NodeFilter.SHOW_TEXT, { + acceptNode: (node) => { + const view = node.parentElement?.closest('.json-view-tree, .json-view-source'); + return view?.style.display === 'none' ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT; + }, + }); let node: Text | null; while ((node = walker.nextNode() as Text | null)) { const text = node.textContent || ''; - const lowerText = text.toLowerCase(); - let startPos = 0; - - while (startPos < text.length) { - const idx = lowerText.indexOf(lowerQuery, startPos); - if (idx === -1) break; - + for (const match of text.matchAll(pattern)) { const range = document.createRange(); - range.setStart(node, idx); - range.setEnd(node, idx + query.length); + range.setStart(node, match.index); + range.setEnd(node, match.index + match[0].length); ranges.push(range); - startPos = idx + query.length; } } return ranges; diff --git a/src/main.ts b/src/main.ts index 1cee2ad..28ef7ee 100644 --- a/src/main.ts +++ b/src/main.ts @@ -476,10 +476,16 @@ function toggleAllCodeBlocks() { } // --- Scroll position memory (#7) --- +// While the loading skeleton is shown, scrollTop has been clamped to 0 and is +// not the reader's position; recording it would erase the one to restore. +function isShowingLoadingSkeleton(target: HTMLElement): boolean { + return Boolean(target.firstElementChild?.classList.contains('loading-skeleton')); +} + function saveScrollPosition(pane: PaneId = 'left') { const path = getPanePath(pane); const target = getPaneViewer(pane); - if (path && target) { + if (path && target && !isShowingLoadingSkeleton(target)) { getPaneScrollMap(pane).set(path, target.scrollTop); } } @@ -515,7 +521,7 @@ function handlePaneScroll(pane: PaneId) { if (!target) return; const path = getPanePath(pane); - if (path) getPaneScrollMap(pane).set(path, target.scrollTop); + if (path && !isShowingLoadingSkeleton(target)) getPaneScrollMap(pane).set(path, target.scrollTop); const scrollHeight = target.scrollHeight - target.clientHeight; const pct = scrollHeight > 0 ? (target.scrollTop / scrollHeight) * 100 : 0; @@ -846,8 +852,10 @@ function interceptRelativeLinks(currentPath: string, target: HTMLElement = viewe if (!href) return; if (href.startsWith('#')) { // Shared DocView links are application routes, handled by hashchange. + // Require a `key=` pair: heading ids such as `#file` or `#album` are + // in-page anchors, and generated ids never contain `=`. const params = new URLSearchParams(href.slice(1)); - if (params.has('file') || params.has('album') || params.has('compare')) return; + if (href.includes('=') && (params.has('file') || params.has('album') || params.has('compare'))) return; a.addEventListener('click', (e) => { if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; e.preventDefault(); @@ -955,7 +963,10 @@ function renderContent(content: string, path: string, target: HTMLElement = view renderHighlighted(content, path, target); } } else if (path.endsWith('.yaml') || path.endsWith('.yml')) { - const treeHtml = renderYamlTree(content, secretSafe ? maskSecretValue : undefined); + // Build the tree from the masked document too: an alias (`other: *pw`) + // would otherwise resolve to the secret behind a masked anchor. + const treeSource = secretSafe ? maskYamlSecrets(content, { maskKeys: false }) : content; + const treeHtml = renderYamlTree(treeSource, secretSafe ? maskSecretValue : undefined); if (treeHtml) { const highlighted = hljs.highlight(secretSafe ? maskYamlSecrets(content) : content, { language: 'yaml' }).value; target.innerHTML = ` @@ -1259,7 +1270,11 @@ async function renderImage(path: string) { if (path.toLowerCase().endsWith('.svg')) { try { const res = await fetch(url); - if (!res.ok) return; + if (seq !== leftLoadSeq) return; + if (!res.ok) { + showError(`Failed to load: ${path} (${res.status})`); + return; + } const svgText = await res.text(); if (seq !== leftLoadSeq) return; const cleanSvg = DOMPurify.sanitize(svgText, { USE_PROFILES: { html: true, svg: true, svgFilters: true }, ADD_TAGS: ['use', 'foreignObject'] }); @@ -1272,7 +1287,9 @@ async function renderImage(path: string) { } initImageZoom(viewer); imageMetaPanel.mount(path); - } catch { /* ignore */ } + } catch { + if (seq === leftLoadSeq) showError(`Connection error loading: ${path}`); + } return; } viewer.innerHTML = `
${escapeHtml(path)}

${escapeHtml(path)}

`; @@ -2222,8 +2239,8 @@ async function loadFullFile(path: string, seq: number) { } // Error UX (#11) -function showError(message: string) { - viewer.innerHTML = `

${escapeHtml(message)}

`; +function showError(message: string, target: HTMLElement = viewer) { + target.innerHTML = `

${escapeHtml(message)}

`; } async function reloadCurrentFile() { @@ -2375,6 +2392,7 @@ img{max-width:100%}h1,h2,h3{color:#1a1c2e} } function handleKeyboard(e: KeyboardEvent) { + if (e.isComposing || e.keyCode === 229) return; // keys driving an IME conversion if (helpModal.isOpen) return; const openPaneFindBar = [findBar, splitFindBar].find((bar) => bar?.active); if (openPaneFindBar) { @@ -2790,12 +2808,18 @@ async function loadIntoSplit(path: string) { if (path.toLowerCase().endsWith('.svg')) { try { const res = await fetch(url); - if (!res.ok || !isCurrent()) return; + if (!isCurrent()) return; + if (!res.ok) { + showError(`Failed to load: ${path} (${res.status})`, target); + return; + } const svgText = await res.text(); if (!isCurrent()) return; const cleanSvg = DOMPurify.sanitize(svgText, { USE_PROFILES: { html: true, svg: true, svgFilters: true }, ADD_TAGS: ['use', 'foreignObject'] }); target.innerHTML = `
${cleanSvg}
`; - } catch { /* ignore */ } + } catch { + if (isCurrent()) showError(`Connection error loading: ${path}`, target); + } } else { target.innerHTML = `
${escapeHtml(path)}
`; } @@ -2823,13 +2847,19 @@ async function loadIntoSplit(path: string) { try { const res = await fetch(`/api/file?path=${encodeURIComponent(path)}`); - if (!res.ok) return; + if (!isCurrent()) return; + if (!res.ok) { + showError(`Failed to load: ${path} (${res.status})`, target); + return; + } const content = await res.text(); if (!isCurrent()) return; renderContent(content, path, target); initImageZoom(target); if (syncSplitScroll) requestAnimationFrame(() => { if (isCurrent()) syncScrollFrom('left'); }); - } catch { /* ignore */ } + } catch { + if (isCurrent()) showError(`Connection error loading: ${path}`, target); + } } // --- Init --- diff --git a/src/markdown.ts b/src/markdown.ts index bba0112..743d2af 100644 --- a/src/markdown.ts +++ b/src/markdown.ts @@ -1856,6 +1856,30 @@ md.use(frontmatter, () => { // silently consume front matter }); +// The plugin auto-closes an unterminated block at end of file, so a document +// that merely starts with a `---` horizontal rule would render as an empty +// page. Only treat it as front matter when a closing fence exists. +{ + type BlockRule = Parameters[1]; + // Look the rule up by its registered name: function names do not survive minification. + const rules = (md.block.ruler as unknown as { __rules__: { name: string; fn: BlockRule }[] }).__rules__; + const frontMatterRule = rules.find((rule) => rule.name === 'front_matter')?.fn; + if (frontMatterRule) { + md.block.ruler.at('front_matter', (state, startLine, endLine, silent) => { + if (startLine !== 0 || state.src.charCodeAt(0) !== 0x2D /* - */) return false; + const lineText = (line: number) => state.src.slice(state.bMarks[line] + state.tShift[line], state.eMarks[line]); + const openLength = /^-*/.exec(lineText(0))![0].length; + let closed = false; + for (let line = 1; line < endLine && !closed; line++) { + const text = lineText(line); + const fence = /^(-+)[ \t]*$/.exec(text); + closed = text === '...' || (!!fence && fence[1].length >= openLength && state.sCount[line] - state.blkIndent < 4); + } + return closed && frontMatterRule(state, startLine, endLine, silent); + }, { alt: ['paragraph', 'reference', 'blockquote', 'list'] }); + } +} + type QiitaArticleMeta = { title: string; tags: string[] }; type MarkdownRenderEnv = { qiita: boolean; qiitaArticle?: QiitaArticleMeta }; @@ -1888,10 +1912,18 @@ function wikiLinkPlugin(mdi: MarkdownIt) { const pos = state.pos; if (src.charCodeAt(pos) !== 0x5B || src.charCodeAt(pos + 1) !== 0x5B) return false; // [[ const closeIdx = src.indexOf(']]', pos + 2); - if (closeIdx === -1) return false; - if (silent) return true; - + // Stay inside the current inline range, and leave bracketed text such as + // `[[y](url) z]]` to the link rule — a wiki target never contains brackets. + if (closeIdx === -1 || closeIdx + 2 > state.posMax) return false; const content = src.slice(pos + 2, closeIdx); + if (/[[\]\n]/.test(content)) return false; + // Silent mode (link-label scanning) must still consume the token, or + // markdown-it aborts the whole render with "didn't increment state.pos". + if (silent) { + state.pos = closeIdx + 2; + return true; + } + const pipeIdx = content.indexOf('|'); const target = pipeIdx >= 0 ? content.slice(0, pipeIdx).trim() : content.trim(); const display = pipeIdx >= 0 ? content.slice(pipeIdx + 1).trim() : target; diff --git a/src/search.ts b/src/search.ts index 0cfb815..0aa2f1a 100644 --- a/src/search.ts +++ b/src/search.ts @@ -115,12 +115,19 @@ export class SearchModal { this.debounceTimer = setTimeout(() => this.search(), this.mode === 'fulltext' ? 300 : 50); }); + // A lone Shift tap toggles mode (backward compat). Toggle on release, and + // only when no other key was pressed meanwhile, so typing capitals does not. + let shiftAlone = false; + this.input.addEventListener('keyup', (e) => { + if (e.key === 'Shift' && shiftAlone) this.switchMode(this.mode === 'files' ? 'fulltext' : 'files'); + shiftAlone = false; + }); this.input.addEventListener('keydown', (e) => { + shiftAlone = e.key === 'Shift' && !e.repeat && !e.isComposing; + // Enter/Escape that commit or cancel an IME conversion are not ours (Safari + // reports the committing Enter with isComposing=false but keyCode 229). + if (e.isComposing || e.keyCode === 229) return; if (e.key === 'Escape') this.close(); - // Shift key toggles mode (backward compat) - if (e.key === 'Shift') { - this.switchMode(this.mode === 'files' ? 'fulltext' : 'files'); - } if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); this.navigate(e.key === 'ArrowDown' ? 1 : -1); diff --git a/src/url-bar.ts b/src/url-bar.ts index 1de74b3..570fd7d 100644 --- a/src/url-bar.ts +++ b/src/url-bar.ts @@ -132,6 +132,9 @@ export class UrlBar { }); this.input.addEventListener('keydown', (e) => { + // Enter/Escape that commit or cancel an IME conversion are not ours (Safari + // reports the committing Enter with isComposing=false but keyCode 229). + if (e.isComposing || e.keyCode === 229) return; if (e.key === 'Escape') { e.preventDefault(); this.close(); return; } if (e.key === 'Enter') { e.preventDefault(); void this.submit(); return; } if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { diff --git a/src/yaml-tree.ts b/src/yaml-tree.ts index 576893d..af2b8a1 100644 --- a/src/yaml-tree.ts +++ b/src/yaml-tree.ts @@ -1,8 +1,12 @@ import { parse, parseDocument, visit, isScalar } from 'yaml'; import { isLikelySecretKey, maskSecrets, REDACTED, type SecretMasker } from './secret-mask'; -/** Mask block values too; a line-based assignment matcher cannot see them. */ -export function maskYamlSecrets(content: string): string { +/** + * Mask block values too; a line-based assignment matcher cannot see them. + * `maskKeys: false` leaves mapping keys intact so the result still parses + * (two hash-like keys would otherwise both become `[REDACTED]` and collide). + */ +export function maskYamlSecrets(content: string, { maskKeys = true } = {}): string { try { const doc = parseDocument(content); if (doc.errors.length) return maskSecrets(content); @@ -17,7 +21,8 @@ export function maskYamlSecrets(content: string): string { pair.value = replacement; } }, - Scalar(_key, node) { + Scalar(key, node) { + if (!maskKeys && key === 'key') return; if (typeof node.value === 'string') node.value = maskSecrets(node.value); }, }); diff --git a/tests/frontend-audit.spec.ts b/tests/frontend-audit.spec.ts new file mode 100644 index 0000000..2ad1e74 --- /dev/null +++ b/tests/frontend-audit.spec.ts @@ -0,0 +1,183 @@ +import { test, expect, type Page } from '@playwright/test'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const DIR = '/tmp/md-test-docs'; + +/** + * Regression suite for the frontend audit batch: + * - markdown: wiki link inside a link label, unterminated leading `---` + * - routing: heading anchors named like app routes (#file, #album) + * - scroll memory across SSE live reload + * - find bar: hidden Tree/Source copy, case folding that changes length + * - search modal: Shift while typing, IME composition keys + * - failed SVG load, YAML alias masking, UTF-8 BOM in JSONL/CSV + */ + +async function openHash(page: Page, file: string, query = '') { + await page.goto(`/${query}#file=${encodeURIComponent(file)}`); +} + +test.describe('Frontend audit regressions', () => { + test('a wiki link inside a link label does not abort rendering', async ({ page }) => { + await openHash(page, 'audit-wiki-label.md'); + await expect(page.locator('#viewer h1')).toContainText('After Wiki'); + await expect(page.locator('#viewer a[href="http://example.com"]')).toHaveText('y'); + await expect(page.locator('#viewer .error-banner')).toHaveCount(0); + }); + + test('a leading --- without a closing fence is a rule, not front matter', async ({ page }) => { + await openHash(page, 'audit-unclosed-fm.md'); + await expect(page.locator('#viewer h1')).toContainText('Unclosed Title'); + await expect(page.locator('#viewer .markdown-body')).toContainText('Body paragraph should render.'); + await expect(page.locator('#viewer .markdown-body hr')).toHaveCount(1); + }); + + test('closed front matter is still hidden', async ({ page }) => { + await openHash(page, 'audit-closed-fm.md'); + await expect(page.locator('#viewer h1')).toContainText('Closed Title'); + await expect(page.locator('#viewer .markdown-body')).not.toContainText('title: meta'); + }); + + test('a heading anchor named #file scrolls in-page instead of routing', async ({ page }) => { + await openHash(page, 'audit-heading-route.md'); + await expect(page.locator('#viewer h1')).toContainText('Heading Route'); + await page.locator('#viewer a', { hasText: 'go to file section' }).click(); + await expect(page.locator('#viewer h2#file')).toBeInViewport(); + expect(new URLSearchParams(new URL(page.url()).hash.slice(1)).get('file')).toBe('audit-heading-route.md'); + }); + + test('live reload keeps the scroll position of the open file', async ({ page }) => { + const file = join(DIR, 'audit-scroll.md'); + const original = readFileSync(file, 'utf-8'); + const sseConnected = page.waitForResponse((res) => res.url().includes('/api/watch')); + await openHash(page, 'audit-scroll.md'); + await expect(page.locator('#viewer h1')).toContainText('Scroll Memory'); + await sseConnected; + + const viewer = page.locator('#viewer'); + await viewer.evaluate((el) => { el.scrollTop = 3000; }); + await expect.poll(() => viewer.evaluate((el) => el.scrollTop)).toBe(3000); + + // Hold the reload response for a few frames so the loading skeleton is + // laid out (on a fast loopback the fetch can beat the next frame). + await page.route(/\/api\/file\?path=audit-scroll\.md$/, async (route) => { + await new Promise((resolve) => setTimeout(resolve, 300)); + await route.continue(); + }); + try { + // Editors often save twice in a row: the second reload starts while the + // first one's skeleton is still on screen. + writeFileSync(file, original + '\nFirst save.\n'); + await page.waitForTimeout(150); + writeFileSync(file, original + '\nEdited marker paragraph.\n'); + await expect(page.locator('#viewer')).toContainText('Edited marker paragraph.', { timeout: 15000 }); + await expect.poll(() => viewer.evaluate((el) => el.scrollTop)).toBe(3000); + } finally { + writeFileSync(file, original); + } + }); + + test('find bar counts only the visible Tree/Source view', async ({ page }) => { + await openHash(page, 'audit-find.yaml'); + await expect(page.locator('#viewer .json-view-tree')).toContainText('zqfindtoken'); + await page.locator('#viewer').click(); + await page.keyboard.press('/'); + await page.locator('.find-input').fill('zqfindtoken'); + await expect(page.locator('.find-info')).toHaveText('1/1'); + + // Switching views with the bar open re-runs the query on the shown half. + await page.locator('#viewer .json-toggle-btn[data-view="source"]').click(); + await expect.poll(() => page.evaluate(() => { + const [range] = [...(CSS.highlights.get('find-current') ?? [])] as Range[]; + return range?.startContainer.parentElement?.closest('.json-view-source, .json-view-tree')?.className ?? null; + })).toBe('json-view-source'); + await expect(page.locator('.find-info')).toHaveText('1/1'); + }); + + test('find bar ranges stay aligned after characters whose lower case is longer', async ({ page }) => { + await openHash(page, 'audit-find-length.md'); + await expect(page.locator('#viewer h1')).toContainText('Find'); + await page.locator('#viewer').click(); + await page.keyboard.press('/'); + await page.locator('.find-input').fill('end'); + await expect(page.locator('.find-info')).toHaveText('1/1'); + const current = await page.evaluate(() => { + const ranges = CSS.highlights.get('find-current'); + return ranges ? [...ranges].map((r) => r.toString()) : []; + }); + expect(current).toEqual(['end']); + }); + + test('Shift while typing keeps the search mode; a lone Shift tap still toggles it', async ({ page }) => { + await page.goto('/'); + await page.waitForSelector('.filetree-item'); + await page.keyboard.press('Meta+p'); + await page.waitForSelector('.search-overlay'); + const tabFiles = page.locator('.search-tab', { hasText: 'Files' }); + const tabFulltext = page.locator('.search-tab', { hasText: 'Full text' }); + await expect(tabFiles).toHaveAttribute('aria-selected', 'true'); + + // Typing a capital: Shift is held while another key is pressed. + await page.keyboard.down('Shift'); + await page.keyboard.press('KeyO'); + await page.keyboard.up('Shift'); + await page.keyboard.type('ther'); + await expect(page.locator('.search-overlay input')).toHaveValue('Other'); + await expect(tabFiles).toHaveAttribute('aria-selected', 'true'); + + await page.keyboard.press('Shift'); + await expect(tabFulltext).toHaveAttribute('aria-selected', 'true'); + }); + + test('Escape and Enter during IME composition do not act on the search modal', async ({ page }) => { + await page.goto('/'); + await page.waitForSelector('.filetree-item'); + await page.keyboard.press('Meta+p'); + const input = page.locator('.search-overlay input'); + await input.fill('README'); + await expect(page.locator('.search-item').first()).toBeVisible(); + for (const key of ['Escape', 'Enter']) { + await input.dispatchEvent('keydown', { key, isComposing: true, bubbles: true }); + } + await expect(page.locator('.search-overlay')).toBeVisible(); + expect(new URL(page.url()).hash).not.toContain('README'); + }); + + test('a failed SVG load replaces the previous document with an error', async ({ page }) => { + await openHash(page, 'audit-find-length.md'); + await expect(page.locator('#viewer h1')).toContainText('Find'); + await page.evaluate(() => { location.hash = '#file=missing-audit.svg'; }); + await expect(page.locator('#viewer .error-banner')).toContainText('missing-audit.svg'); + await expect(page.locator('#viewer h1')).toHaveCount(0); + }); + + test('secret-safe YAML tree does not resolve aliases to masked secrets', async ({ page }) => { + await openHash(page, 'audit-secret-alias.yaml', '?secretSafe=1'); + await expect(page.locator('#viewer .json-view-tree')).toContainText('other'); + await expect(page.locator('#viewer')).not.toContainText('hunter2-alias'); + await expect(page.locator('#viewer .json-view-tree')).toContainText('[REDACTED]'); + }); + + test('secret-safe YAML tree keeps mapping keys (no collision on hash-like keys)', async ({ page }) => { + await openHash(page, 'audit-secret-hashkeys.yaml', '?secretSafe=1'); + const tree = page.locator('#viewer .json-view-tree'); + await expect(tree).toContainText('d41d8cd98f00b204e9800998ecf8427e'); + await expect(tree).toContainText('9e107d9d372bb6826bd81d3542a419d6'); + }); + + test('UTF-8 BOM is stripped from text and record responses', async ({ request }) => { + const full = await request.get('/api/file?path=audit-bom.csv'); + expect((await full.text()).startsWith('id,name')).toBe(true); + const records = await request.get('/api/file?path=audit-bom.csv&offset=0&limit=10&records=1'); + expect((await records.text()).split('\n')[0]).toBe('id,name'); + const lines = await request.get('/api/file?path=audit-bom.jsonl&offset=0&limit=1'); + expect(JSON.parse(await lines.text())).toEqual({ a: 1 }); + }); + + test('UTF-8 BOM does not hide the first line from anchored regex search', async ({ request }) => { + const res = await request.get('/api/search?regex=1&q=' + encodeURIComponent('^id,name$')); + const results = await res.json() as { path: string; line: number }[]; + expect(results).toContainEqual(expect.objectContaining({ path: 'audit-bom.csv', line: 1 })); + }); +}); diff --git a/tests/setup.ts b/tests/setup.ts index 8871749..472be57 100644 --- a/tests/setup.ts +++ b/tests/setup.ts @@ -423,6 +423,28 @@ flowchart TD 'Evil: [[javascript:alert(1)]] and [[data:text/html;base64,PHNjcmlwdD4=]]', ].join('\n') + '\n'); + // Frontend audit fixtures (frontend-audit.spec.ts). + write('audit-wiki-label.md', 'Bounded: [x [[y](http://example.com) z]] tail\n\n# After Wiki\n'); + write('audit-unclosed-fm.md', '---\n# Unclosed Title\n\nBody paragraph should render.\n'); + write('audit-closed-fm.md', '---\ntitle: meta\n---\n# Closed Title\n'); + write('audit-heading-route.md', [ + '# Heading Route', + '', + '[go to file section](#file)', + '', + ...Array.from({ length: 120 }, (_, i) => `Filler paragraph ${i + 1}.\n`), + '## File', + '', + 'File section body.', + ].join('\n') + '\n'); + write('audit-scroll.md', '# Scroll Memory\n\n' + Array.from({ length: 300 }, (_, i) => `Paragraph ${i + 1}.\n`).join('\n')); + write('audit-find.yaml', 'greeting: zqfindtoken\n'); + write('audit-find-length.md', '# Find\n\nİstanbul İstanbul end\n'); + write('audit-secret-alias.yaml', 'password: &pw hunter2-alias\nother: *pw\n'); + write('audit-secret-hashkeys.yaml', 'checksums:\n d41d8cd98f00b204e9800998ecf8427e: a.txt\n 9e107d9d372bb6826bd81d3542a419d6: b.txt\n'); + write('audit-bom.jsonl', '{"a":1}\n{"a":2}\n'); + write('audit-bom.csv', 'id,name\n1,alpha\n'); + // mtime filter fixtures (filetree-mtime-filter.spec.ts). // archived-old.md: backdated ~400 days → excluded by every preset except "すべて". // edited-yesterday.md: dated to yesterday noon → excluded by "今日" but included