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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
12 changes: 9 additions & 3 deletions server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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);
}
Expand All @@ -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);
Expand Down
8 changes: 8 additions & 0 deletions src/chunked-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
Expand All @@ -658,6 +664,7 @@ export class ChunkedTable {
// Row-jump input ("行へ移動")
this.container.querySelectorAll<HTMLInputElement>('.chunk-row-jump-input').forEach((input) => {
input.addEventListener('keydown', (e) => {
if (isImeKey(e)) return;
if (e.key === 'Enter') { e.preventDefault(); void this.jumpToRow(input); }
});
});
Expand All @@ -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('');
Expand Down
35 changes: 23 additions & 12 deletions src/find-bar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,21 @@ 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(); }
});
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);
Expand Down Expand Up @@ -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<HTMLElement>('.json-view-tree, .json-view-source');
return view?.style.display === 'none' ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT;
Comment thread
simota marked this conversation as resolved.
Resolved
},
});

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;
Expand Down
54 changes: 42 additions & 12 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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 = `
Expand Down Expand Up @@ -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'] });
Expand All @@ -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 = `<div class="image-view"><img src="${url}" alt="${escapeHtml(path)}" /><p class="image-caption">${escapeHtml(path)}</p></div>`;
Expand Down Expand Up @@ -2222,8 +2239,8 @@ async function loadFullFile(path: string, seq: number) {
}

// Error UX (#11)
function showError(message: string) {
viewer.innerHTML = `<div class="error-banner"><p>${escapeHtml(message)}</p><button class="error-btn" onclick="location.reload()">Reload</button></div>`;
function showError(message: string, target: HTMLElement = viewer) {
target.innerHTML = `<div class="error-banner"><p>${escapeHtml(message)}</p><button class="error-btn" onclick="location.reload()">Reload</button></div>`;
}

async function reloadCurrentFile() {
Expand Down Expand Up @@ -2375,6 +2392,7 @@ img{max-width:100%}h1,h2,h3{color:#1a1c2e}</style></head>
}

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) {
Expand Down Expand Up @@ -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 = `<div class="image-view"><div class="svg-container">${cleanSvg}</div></div>`;
} catch { /* ignore */ }
} catch {
if (isCurrent()) showError(`Connection error loading: ${path}`, target);
}
} else {
target.innerHTML = `<div class="image-view"><img src="${url}" alt="${escapeHtml(path)}" /></div>`;
}
Expand Down Expand Up @@ -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 ---
Expand Down
38 changes: 35 additions & 3 deletions src/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof md.block.ruler.at>[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 };

Expand Down Expand Up @@ -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;
Expand Down
15 changes: 11 additions & 4 deletions src/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 3 additions & 0 deletions src/url-bar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down
11 changes: 8 additions & 3 deletions src/yaml-tree.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -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);
},
});
Expand Down
Loading
Loading