feat(markdown): claim local .md links and navigate headings across files (#363)
Markdown surfaces the plugin draws (editor preview, side-chat transcript, changes reading pane, task note) now open local markdown links in the sidebar and follow same-page / cross-file heading anchors. The host renderer decides what a local destination even is: without a `MarkdownDelegateProvider.openFile` a local link renders as plain text (there is no `a[href]` to intercept), and `parseFileLink` accepts a fragment only in the line grammar (`#L24`), so a heading fragment makes the whole destination unparseable. So the claim is scoped by the provider (one per surface) and a SOURCE pass carries a heading fragment past the parser as `%23` — the same shape markdown-images.ts already uses for relative image destinations. Destinations the plugin does not claim (non-markdown, remote, queried) keep rendering exactly as they do today. - `markdown-navigation.ts`: pure link judge + GitHub heading slugs (Chinese kept, duplicates `-1`, authored ids reserved first), collapsed-anchor hiding, the source rewrite, the jump that scrolls the surface's OWN scroller (never `window`/`scrollIntoView`), and the session+path keyed pending fragment table. - `use-markdown-surface.ts`: one hook per surface — the container callback ref (DOM pass + mutation re-runs + pending fragment) and the delegate's `openFile`.
This commit is contained in:
1 parent
58d7f7128a
commit
cfe84c99b3
14 files changed
+1351
-41
No files matched your search
@@ -21,6 +21,7 @@ import DOMPurify from 'dompurify'
|
||||
import { MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { markdownTextProps, type MarkdownCopyLabels } from './markdown-labels.tsx'
|
||||
import { resolveLocalMediaDest, rewriteLocalImageUrls } from './markdown-images.ts'
|
||||
import { rewriteLocalMarkdownLinks } from './markdown-navigation.ts'
|
||||
import {
|
||||
analyzeHtmlSegment,
|
||||
type AnalyzedMarkdownHtml,
|
||||
@@ -299,7 +300,14 @@ export function MarkdownDocument({ info, media, codeLabels }: MarkdownDocumentPr
|
||||
// stance), so rewrite local ones into /sidebar/file media URLs first —
|
||||
// the same trust fence the sanitized HTML leaves below go through.
|
||||
// Idempotent: already-absolute media URLs pass through untouched.
|
||||
const text = rewriteLocalImageUrls(raw, media.scope, media.path, media.baseUrl)
|
||||
// The link pass follows (it must see the media URLs already in place):
|
||||
// it carries a heading fragment past the host parser and keeps every
|
||||
// local destination the plugin does not claim inert.
|
||||
const text = rewriteLocalMarkdownLinks(
|
||||
rewriteLocalImageUrls(raw, media.scope, media.path, media.baseUrl),
|
||||
media.path,
|
||||
media.scope.cwd,
|
||||
)
|
||||
return {
|
||||
kind: 'markdown',
|
||||
text,
|
||||
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
IconStopFillRegular,
|
||||
MarkdownText,
|
||||
Menu,
|
||||
MarkdownDelegateProvider,
|
||||
ReadBlock,
|
||||
StateDot,
|
||||
TerminalBlock,
|
||||
@@ -51,6 +52,7 @@ import {
|
||||
type TerminalBlockLabels,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { markdownTextProps } from './markdown-labels.tsx'
|
||||
import { useMarkdownSurface } from './use-markdown-surface.ts'
|
||||
import { IconHistoryOutline16, IconSaveOutline16 } from './icons.tsx'
|
||||
import type { Context, SidebarHistoryEntry, SidebarSessionEvent } from '../context-types.ts'
|
||||
import {
|
||||
@@ -366,19 +368,21 @@ function toolLeading(name: string, failed: boolean): React.ReactNode {
|
||||
}
|
||||
}
|
||||
|
||||
/** One row renderer (React keys ride the source event seq). */
|
||||
function renderRow(row: SidechatTranscriptRow, labels: RowLabels): React.ReactNode {
|
||||
/** One row renderer (React keys ride the source event seq). `rewrite` is the
|
||||
* surface's markdown link pass — the rows are model prose, so a relative link
|
||||
* resolves against the session cwd (see use-markdown-surface). */
|
||||
function renderRow(row: SidechatTranscriptRow, labels: RowLabels, rewrite: (text: string) => string): React.ReactNode {
|
||||
switch (row.kind) {
|
||||
case 'user':
|
||||
return (
|
||||
<div key={`${row.kind}:${row.seq}`} className={css.sidechatUser}>
|
||||
<MarkdownText {...markdownTextProps(row.text, labels)} />
|
||||
<MarkdownText {...markdownTextProps(rewrite(row.text), labels)} />
|
||||
</div>
|
||||
)
|
||||
case 'assistant':
|
||||
return (
|
||||
<div key={`${row.kind}:${row.seq}`} className={css.sidechatAssistant}>
|
||||
<MarkdownText {...markdownTextProps(row.text, labels)} />
|
||||
<MarkdownText {...markdownTextProps(rewrite(row.text), labels)} />
|
||||
</div>
|
||||
)
|
||||
case 'reasoning':
|
||||
@@ -531,6 +535,18 @@ export function SideChatView(props: {
|
||||
const prevRowsRef = useRef<SidechatTranscriptRow[]>([])
|
||||
const controllerRef = useRef<AbortController | null>(null)
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null)
|
||||
/** Heading slugs, anchor jumps and `.md` link claiming for the transcript (a
|
||||
* prose surface: it renders no file of its own, so a relative link target
|
||||
* resolves against the session cwd). */
|
||||
const { surfaceRef: chatSurfaceRef, openFile: openChatFile, rewrite: rewriteChatText } = useMarkdownSurface({
|
||||
ctx,
|
||||
sessionId: scope.sessionId,
|
||||
cwd: scope.cwd,
|
||||
})
|
||||
const transcriptRef = useCallback((element: HTMLDivElement | null) => {
|
||||
scrollRef.current = element
|
||||
chatSurfaceRef(element)
|
||||
}, [chatSurfaceRef])
|
||||
const composerRef = useRef<HTMLTextAreaElement | null>(null)
|
||||
|
||||
const summary = threadId === undefined ? undefined : list.byId[threadId]
|
||||
@@ -980,8 +996,13 @@ export function SideChatView(props: {
|
||||
&& <div className={css.sidechatHint}>{t('sideChatPendingDrop')}</div>}
|
||||
{saved && <div className={css.sidechatHint}>{t('sideChatSaved')}</div>}
|
||||
{error !== null && <div className={css.sidechatError}>{t('sideChatError', { message: error })}</div>}
|
||||
<div ref={scrollRef} className={css.sidechatScroll}>
|
||||
{rows.map(row => renderRow(row, rowLabels))}
|
||||
<div ref={transcriptRef} className={css.sidechatScroll}>
|
||||
{/* The host delegate is what makes a local markdown link in a row
|
||||
clickable at all (see use-markdown-surface), scoped to this
|
||||
transcript so nothing outside it is claimed. */}
|
||||
<MarkdownDelegateProvider openFile={openChatFile}>
|
||||
{rows.map(row => renderRow(row, rowLabels, rewriteChatText))}
|
||||
</MarkdownDelegateProvider>
|
||||
</div>
|
||||
{running && (
|
||||
<div className={css.sidechatStatus}>
|
||||
|
||||
@@ -433,6 +433,7 @@ export function SubagentView(props: {
|
||||
rootId={rootId}
|
||||
task={task}
|
||||
members={teamMembers}
|
||||
ctx={ctx}
|
||||
onClose={closePopover}
|
||||
anchor={popover.anchor}
|
||||
/>
|
||||
|
||||
+29
-13
@@ -22,11 +22,12 @@ import { useEffect, useId, useRef, useState, type ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
Button, IconCheckOutlineRegular, IconEditOutlineRegular,
|
||||
IconRefreshOutlineRegular, IconTrashOutlineRegular, Input, MarkdownText, Pill, StateDot, Tag,
|
||||
IconRefreshOutlineRegular, IconTrashOutlineRegular, Input, MarkdownDelegateProvider, MarkdownText, Pill, StateDot, Tag,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { SidebarTeamTaskView } from '../context-types.ts'
|
||||
import type { Context, SidebarTeamTaskView } from '../context-types.ts'
|
||||
import { api } from './api.ts'
|
||||
import { markdownTextProps } from './markdown-labels.tsx'
|
||||
import { useMarkdownSurface } from './use-markdown-surface.ts'
|
||||
import { FloatingWindow } from './FloatingWindow.tsx'
|
||||
import { taskBlocked, taskDotState, taskStatusLabel, taskTone } from './tasks-shared.tsx'
|
||||
import type { TeamMemberRow } from './team-projection.ts'
|
||||
@@ -100,14 +101,22 @@ function OwnerPicker(props: {
|
||||
* The read-only body: the owner line and the markdown description. The status
|
||||
* and the owner NAME live in the window's own head row (see `TaskWindow`); this
|
||||
* body carries the editable owner picker beside the prose it belongs to.
|
||||
*
|
||||
* The description is a markdown SURFACE like every other one the plugin draws:
|
||||
* heading slugs, in-note anchor jumps and `.md` link claiming. It renders no
|
||||
* file of its own, so a relative link target resolves against the session cwd
|
||||
* (`sessionId` is the team root the window was opened for).
|
||||
*/
|
||||
function TaskViewBody(props: {
|
||||
task: SidebarTeamTaskView
|
||||
teammates: readonly TeamMemberRow[]
|
||||
busy: boolean
|
||||
ctx: Context
|
||||
sessionId: string
|
||||
onReassign(owner: string): void
|
||||
}): ReactNode {
|
||||
const { task } = props
|
||||
const surface = useMarkdownSurface({ ctx: props.ctx, sessionId: props.sessionId })
|
||||
const body = task.description.trim()
|
||||
return (
|
||||
<>
|
||||
@@ -121,19 +130,21 @@ function TaskViewBody(props: {
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className={css.taskMarkdown} data-task-description>
|
||||
<div className={css.taskMarkdown} data-task-description ref={surface.surfaceRef}>
|
||||
{body === ''
|
||||
? <div className={css.popHint}>{t('teamTaskNoDescription')}</div>
|
||||
: (
|
||||
<MarkdownText
|
||||
{...markdownTextProps(body, {
|
||||
copyLabel: t('copy'),
|
||||
copiedLabel: t('copied'),
|
||||
codeLabel: t('codeBlockTitle'),
|
||||
wrapLabel: t('codeBlockWrap'),
|
||||
unwrapLabel: t('codeBlockUnwrap'),
|
||||
})}
|
||||
/>
|
||||
<MarkdownDelegateProvider openFile={surface.openFile}>
|
||||
<MarkdownText
|
||||
{...markdownTextProps(surface.rewrite(body), {
|
||||
copyLabel: t('copy'),
|
||||
copiedLabel: t('copied'),
|
||||
codeLabel: t('codeBlockTitle'),
|
||||
wrapLabel: t('codeBlockWrap'),
|
||||
unwrapLabel: t('codeBlockUnwrap'),
|
||||
})}
|
||||
/>
|
||||
</MarkdownDelegateProvider>
|
||||
)}
|
||||
</div>
|
||||
<div className={css.taskField}>
|
||||
@@ -204,6 +215,9 @@ export interface TaskWindowProps {
|
||||
/** The task under view/edit; undefined = create mode. */
|
||||
task: SidebarTeamTaskView | undefined
|
||||
members: readonly TeamMemberRow[]
|
||||
/** Client context: the description's markdown surface opens a claimed `.md`
|
||||
* link through the plugin's own file path. */
|
||||
ctx: Context
|
||||
/** Where the window first appears (the row that opened it). */
|
||||
anchor?: HTMLElement | null
|
||||
/** Close the window (the caller's popover state). */
|
||||
@@ -216,7 +230,7 @@ export interface TaskWindowProps {
|
||||
* one component.
|
||||
*/
|
||||
export function TaskWindow(props: TaskWindowProps): ReactNode {
|
||||
const { rootId, task, members, onClose } = props
|
||||
const { rootId, task, members, ctx, onClose } = props
|
||||
const creating = task === undefined
|
||||
const [editing, setEditing] = useState(creating)
|
||||
const [subject, setSubject] = useState(task?.subject ?? '')
|
||||
@@ -465,6 +479,8 @@ export function TaskWindow(props: TaskWindowProps): ReactNode {
|
||||
task={task}
|
||||
teammates={teammates}
|
||||
busy={busy}
|
||||
ctx={ctx}
|
||||
sessionId={rootId}
|
||||
onReassign={reassign}
|
||||
/>
|
||||
)}
|
||||
|
||||
+41
-10
@@ -20,7 +20,7 @@ import { EditorState } from '@codemirror/state'
|
||||
import { EditorView as CodeMirrorView, keymap, lineNumbers } from '@codemirror/view'
|
||||
import { defaultKeymap, history, historyKeymap } from '@codemirror/commands'
|
||||
import { openSearchPanel } from '@codemirror/search'
|
||||
import { IconCheckOutlineRegular, IconSearchOutlineRegular, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { IconCheckOutlineRegular, IconSearchOutlineRegular, MarkdownDelegateProvider, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { markdownTextProps } from './markdown-labels.tsx'
|
||||
import {
|
||||
applyGitLineKinds,
|
||||
@@ -32,6 +32,7 @@ import { api, htmlUrl, SidebarApiError } from './api.ts'
|
||||
import { hostTransportBase } from './desktop-env.ts'
|
||||
import { markdownPreviewSource } from './markdown-frontmatter.ts'
|
||||
import { rewriteLocalImageUrls } from './markdown-images.ts'
|
||||
import { rewriteLocalMarkdownLinks } from './markdown-navigation.ts'
|
||||
import { languageForPath } from './lang.ts'
|
||||
import { cmSurfaceTheme, CmThemeCompartment } from './cm-themes.ts'
|
||||
import { cmSearchExtensions, CmSearchPhrases } from './cm-search.ts'
|
||||
@@ -42,6 +43,7 @@ import { useSelectionPopup } from './selection-popup.ts'
|
||||
import { buildSelectionInsert, linesOfSelection } from './selection-payload.ts'
|
||||
import { analyzeMarkdownHtml } from './markdown-html.ts'
|
||||
import { LazyMermaidMarkdown, MarkdownDocument, type MarkdownHtmlMedia } from './MarkdownHtml.tsx'
|
||||
import { useMarkdownSurface } from './use-markdown-surface.ts'
|
||||
import { MdToc } from './md-toc.tsx'
|
||||
import { splitMermaidBlocks } from './mermaid-blocks.ts'
|
||||
import { localeSignature, t } from './locales.ts'
|
||||
@@ -92,7 +94,24 @@ export function TextEditor(props: FileViewerProps) {
|
||||
/** The app's resolved color scheme; the editor re-themes in place on flips. */
|
||||
const [dark, setDark] = useState(() => isDarkScheme())
|
||||
/** The markdown preview container (selection-containment + line lookup). */
|
||||
const mdRef = useRef<HTMLDivElement>(null)
|
||||
const mdRef = useRef<HTMLDivElement | null>(null)
|
||||
/** Heading slugs, anchor jumps and `.md` link claiming for the preview (the
|
||||
* delegate provider wrapped around the markdown is its claim boundary — see
|
||||
* use-markdown-surface). */
|
||||
const { surfaceRef: markdownSurfaceRef, openFile: openSurfaceFile } = useMarkdownSurface({
|
||||
ctx,
|
||||
sessionId: scope.sessionId,
|
||||
cwd: scope.cwd,
|
||||
path,
|
||||
})
|
||||
/** One ref callback for the preview container: the selection/scroll code
|
||||
* above keeps its object ref, the surface installer gets the same element.
|
||||
* A stable identity matters — a fresh callback on every render would make
|
||||
* React re-attach (and re-scan) on every render. */
|
||||
const previewRef = useCallback((element: HTMLDivElement | null) => {
|
||||
mdRef.current = element
|
||||
markdownSurfaceRef(element)
|
||||
}, [markdownSurfaceRef])
|
||||
const markdown = viewerId === 'markdown'
|
||||
const html = viewerId === 'html'
|
||||
/** The uncommitted-change gutter (issue #212): the `code` viewer only,
|
||||
@@ -497,9 +516,16 @@ export function TextEditor(props: FileViewerProps) {
|
||||
}, [mode, previewMdText])
|
||||
|
||||
/** The preview source with local image destinations rewritten to absolute
|
||||
* media URLs (see {@link rewriteLocalImageUrls}). */
|
||||
* media URLs (see {@link rewriteLocalImageUrls}) and the local link
|
||||
* destinations prepared for the host delegate (see
|
||||
* {@link rewriteLocalMarkdownLinks}; the split renderer runs the same two
|
||||
* passes per markdown run, and both are idempotent). */
|
||||
const previewText = markdown
|
||||
? rewriteLocalImageUrls(previewMdText, scope, path, hostTransportBase())
|
||||
? rewriteLocalMarkdownLinks(
|
||||
rewriteLocalImageUrls(previewMdText, scope, path, hostTransportBase()),
|
||||
path,
|
||||
scope.cwd,
|
||||
)
|
||||
: previewMdText
|
||||
/** md/mermaid block split for the preview (mermaid fences lift out). Split
|
||||
* only in preview mode: edit-mode keystrokes must not re-scan the source. */
|
||||
@@ -687,7 +713,7 @@ export function TextEditor(props: FileViewerProps) {
|
||||
{markdown && mode === 'preview' && (
|
||||
<div
|
||||
className={css.editorMd}
|
||||
ref={mdRef}
|
||||
ref={previewRef}
|
||||
onMouseUp={handlePreviewMouseUp}
|
||||
onScroll={(event) => {
|
||||
const el = event.currentTarget
|
||||
@@ -736,11 +762,16 @@ export function TextEditor(props: FileViewerProps) {
|
||||
(sticky, zero-height — first child so it pins from the very
|
||||
top) once the document has enough headings. */}
|
||||
<MdToc />
|
||||
{htmlInfo !== null
|
||||
? <MarkdownDocument info={htmlInfo} media={htmlMedia} codeLabels={codeLabels} />
|
||||
: hasMermaid
|
||||
? <LazyMermaidMarkdown text={previewText} codeLabels={codeLabels} />
|
||||
: <MarkdownText {...markdownTextProps(previewText, codeLabels)} />}
|
||||
{/* The host delegate makes the preview's local markdown links
|
||||
clickable at all (without it the renderer degrades them to plain
|
||||
text) and routes them through this surface's own open path. */}
|
||||
<MarkdownDelegateProvider openFile={openSurfaceFile}>
|
||||
{htmlInfo !== null
|
||||
? <MarkdownDocument info={htmlInfo} media={htmlMedia} codeLabels={codeLabels} />
|
||||
: hasMermaid
|
||||
? <LazyMermaidMarkdown text={previewText} codeLabels={codeLabels} />
|
||||
: <MarkdownText {...markdownTextProps(previewText, codeLabels)} />}
|
||||
</MarkdownDelegateProvider>
|
||||
</div>
|
||||
)}
|
||||
{html && mode === 'preview' && (
|
||||
|
||||
@@ -247,6 +247,7 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen
|
||||
<DiffPane
|
||||
key={previewKey(previewTarget)}
|
||||
target={previewTarget}
|
||||
ctx={ctx}
|
||||
scope={scope}
|
||||
height={paneHeight}
|
||||
onHeightCommit={(height) => { setPaneHeight(height); patchMeta({ previewH: height }) }}
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
* git targets can expand into a dedicated diff tab via the shell.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent } from 'react'
|
||||
import { IconCloseOutlineRegular, IconRefreshOutlineRegular, IconRightUpOutlineRegular, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { IconCloseOutlineRegular, IconRefreshOutlineRegular, IconRightUpOutlineRegular, MarkdownDelegateProvider, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { Context } from '../../context-types.ts'
|
||||
import type { SessionScope } from '../api.ts'
|
||||
import { htmlUrl } from '../api.ts'
|
||||
import { hostTransportBase } from '../desktop-env.ts'
|
||||
@@ -28,6 +29,7 @@ import { parseReadContent, parseReadLines, type FileOp } from './ops.ts'
|
||||
import { redactText } from '../redact.ts'
|
||||
import { rewriteLocalImageUrls } from '../markdown-images.ts'
|
||||
import { markdownTextProps } from '../markdown-labels.tsx'
|
||||
import { useMarkdownSurface } from '../use-markdown-surface.ts'
|
||||
import { splitMermaidBlocks } from '../mermaid-blocks.ts'
|
||||
import { LazyMermaidMarkdown } from '../mermaid-lazy.tsx'
|
||||
import { createFrameBatcher } from '../frame-batcher.ts'
|
||||
@@ -108,8 +110,12 @@ function PaneToggle(props: { on: boolean; label: string; title?: string; onClick
|
||||
* the caller). Mermaid fences render through the same chunk-resident
|
||||
* renderer the editor preview uses (one MarkdownText pass with the fences
|
||||
* lifted out); the plain path stays byte-for-byte for documents without
|
||||
* any. */
|
||||
function MdReadingView(props: { text: string }) {
|
||||
* any.
|
||||
*
|
||||
* The body is also a markdown SURFACE: heading slugs, anchor jumps and `.md`
|
||||
* link claiming, with relative targets resolved against the previewed file's
|
||||
* own directory (see use-markdown-surface). */
|
||||
function MdReadingView(props: { text: string; ctx: Context; scope: SessionScope; path: string }) {
|
||||
const codeLabels = {
|
||||
copyLabel: t('copy'),
|
||||
copiedLabel: t('copied'),
|
||||
@@ -117,13 +123,24 @@ function MdReadingView(props: { text: string }) {
|
||||
wrapLabel: t('codeBlockWrap'),
|
||||
unwrapLabel: t('codeBlockUnwrap'),
|
||||
}
|
||||
const hasMermaid = splitMermaidBlocks(props.text).some((block) => block.kind === 'mermaid')
|
||||
const surface = useMarkdownSurface({
|
||||
ctx: props.ctx,
|
||||
sessionId: props.scope.sessionId,
|
||||
cwd: props.scope.cwd,
|
||||
path: props.path,
|
||||
})
|
||||
// The caller already rewrote local IMAGE destinations; this pass is the link
|
||||
// half (and is idempotent, so the two can be composed in either order).
|
||||
const text = surface.rewrite(props.text)
|
||||
const hasMermaid = splitMermaidBlocks(text).some((block) => block.kind === 'mermaid')
|
||||
return (
|
||||
<div className={css.paneBody}>
|
||||
<div className={css.paneBody} ref={surface.surfaceRef}>
|
||||
<div className={css.mdBody}>
|
||||
{hasMermaid
|
||||
? <LazyMermaidMarkdown text={props.text} codeLabels={codeLabels} />
|
||||
: <MarkdownText {...markdownTextProps(props.text, codeLabels)} />}
|
||||
<MarkdownDelegateProvider openFile={surface.openFile}>
|
||||
{hasMermaid
|
||||
? <LazyMermaidMarkdown text={text} codeLabels={codeLabels} />
|
||||
: <MarkdownText {...markdownTextProps(text, codeLabels)} />}
|
||||
</MarkdownDelegateProvider>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -149,6 +166,7 @@ export function diffTabOf(ref: SidebarDiffRef): SidebarTab {
|
||||
|
||||
export interface DiffPaneProps {
|
||||
target: ChangesPreview
|
||||
ctx: Context
|
||||
scope: SessionScope
|
||||
/** The persisted pane height (px); drag commits a new one upwards. */
|
||||
height: number
|
||||
@@ -158,7 +176,7 @@ export interface DiffPaneProps {
|
||||
onExpand: () => void
|
||||
}
|
||||
|
||||
export function DiffPane({ target, scope, height, onHeightCommit, onClose, onExpand }: DiffPaneProps) {
|
||||
export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose, onExpand }: DiffPaneProps) {
|
||||
// ── Git target loading (the shared loader: staged-side fallback, the
|
||||
// untracked full-addition fallback, refresh by tick, fold cache). ─────
|
||||
const gitRef = target.kind === 'git' ? target.ref : null
|
||||
@@ -419,7 +437,7 @@ export function DiffPane({ target, scope, height, onHeightCommit, onClose, onExp
|
||||
</div>
|
||||
)
|
||||
: target.kind === 'op' && mdOp && reading && readingText !== ''
|
||||
? <MdReadingView text={readingText} />
|
||||
? <MdReadingView text={readingText} ctx={ctx} scope={scope} path={target.kind === 'op' ? target.path : ''} />
|
||||
: target.kind === 'op' && op !== null && op.isError
|
||||
? (
|
||||
<div className={css.paneBody}>
|
||||
|
||||
@@ -28,8 +28,10 @@ function isRemoteUrl(dest: string): boolean {
|
||||
* (POSIX `/`), its Windows drive (`C:\`), or its UNC `\\server\share`
|
||||
* prefix. The host's `requireAbsolute` (`path.resolve`) normalizes anyway,
|
||||
* but producing a canonical path here keeps the `/sidebar/file` URL clean.
|
||||
* Shared with the markdown navigation resolver (`markdown-navigation.ts`),
|
||||
* which canonicalizes a claimed link target the same way.
|
||||
*/
|
||||
function normalizeLocalPath(path: string): string {
|
||||
export function normalizeLocalPath(path: string): string {
|
||||
const drive = /^([A-Za-z]:)[\\/]/.exec(path)?.[1]
|
||||
const body = drive !== undefined ? path.slice(drive.length) : path
|
||||
const parts = body.split(/[\\/]+/).filter((segment) => segment !== '' && segment !== '.')
|
||||
|
||||
@@ -0,0 +1,456 @@
|
||||
/**
|
||||
* Cross-file / anchor navigation for the markdown the PLUGIN draws (the editor
|
||||
* preview, the side-chat transcript, the changes reading pane, a task note).
|
||||
*
|
||||
* THE HOST CONTRACT this module works against (DSH 0.2.0-rc.1,
|
||||
* `@deepseek-ai/dsh-client-ui-primitives`): `MarkdownText` renders a local
|
||||
* destination as a clickable file link ONLY when a surrounding
|
||||
* `MarkdownDelegateProvider` supplies `openFile` — otherwise the link is plain
|
||||
* text, and there is no `a[href]` for a click listener to intercept. Worse for
|
||||
* us, its `parseFileLink` accepts a fragment ONLY in the line grammar
|
||||
* (`#L24` / `#L24-L30`); a heading fragment (`./other.md#标题`) makes the whole
|
||||
* destination invalid, so the link would render as inert prose. That is why
|
||||
* this module owns a SOURCE rewrite as well as a DOM pass — the same shape
|
||||
* `markdown-images.ts` already has (images are rewritten into absolute
|
||||
* `/sidebar/file` URLs because the renderer refuses relative ones):
|
||||
*
|
||||
* - {@link rewriteLocalMarkdownLinks} (source, before rendering): a claimed
|
||||
* link's non-line fragment is carried past the host parser as `%23` (an
|
||||
* encoded `#`, decoded back by the host into the path it hands `openFile`);
|
||||
* a local destination the plugin does NOT claim gets a `?` appended, which
|
||||
* `parseFileLink` refuses — the link keeps rendering as plain text instead of
|
||||
* becoming a file-mention button that would do nothing.
|
||||
* - {@link markdownAnchorTarget} (pure judge): turns either shape back into
|
||||
* "same document fragment" / "file to open" / "not ours".
|
||||
* - {@link assignHeadingIds} + {@link hideEmptyAnchors} (DOM, after rendering):
|
||||
* GitHub-style heading slugs (the renderer ships bare `h1..h6`), and the
|
||||
* explicit `<a id="x"></a>` anchors collapsed without losing their id.
|
||||
*
|
||||
* Relative targets resolve against the RENDERED DOCUMENT's own directory (a
|
||||
* link in `/ws/docs/README.md` is relative to `/ws/docs`), falling back to the
|
||||
* session cwd for prose surfaces that render no file at all.
|
||||
*
|
||||
* Cross-file fragments travel through {@link rememberMarkdownAnchor}: the click
|
||||
* happens on the SOURCE document's surface while the jump belongs to the TARGET
|
||||
* document, which does not exist yet — so the fragment is parked by session +
|
||||
* absolute path and taken by the target's own surface once it mounts. The
|
||||
* host's routing is untouched.
|
||||
*/
|
||||
import { normalizeLocalPath } from './markdown-images.ts'
|
||||
import { isAbsolutePath } from './paths.ts'
|
||||
|
||||
/** Vertical breathing room above a jumped-to heading (px). */
|
||||
const SCROLL_TOP_PADDING = 8
|
||||
|
||||
/** How long a parked cross-file fragment stays eligible (ms). A click whose
|
||||
* open never lands must not make an unrelated later open of the same file
|
||||
* jump; the newest click for a key always replaces the previous one. */
|
||||
const PENDING_TTL_MS = 15_000
|
||||
|
||||
/** The fragment separator this module writes into a source destination
|
||||
* (`%23` = an encoded `#`) so a heading fragment survives the host's parser. */
|
||||
const ENCODED_HASH = '%23'
|
||||
|
||||
/** What a clicked link inside a plugin markdown surface resolves to. */
|
||||
export type MarkdownAnchorTarget =
|
||||
| {
|
||||
/** A fragment of the SAME document: scroll the preview's own scroller. */
|
||||
kind: 'same-page'
|
||||
/** The percent-decoded fragment (`''` for a bare `#` — the document top). */
|
||||
fragment: string
|
||||
}
|
||||
| {
|
||||
/** A markdown file to open in the sidebar. */
|
||||
kind: 'file'
|
||||
/** Absolute target path (`.`/`..` collapsed), or the cwd-relative spelling
|
||||
* when the surface has no base to resolve against. */
|
||||
path: string
|
||||
/** The percent-decoded fragment to land on once the file has rendered. */
|
||||
fragment: string
|
||||
}
|
||||
|
||||
/** A URL scheme (`https:`, `mailto:`, `data:`). */
|
||||
const SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i
|
||||
/** A Windows drive prefix: `C:\x.md` matches {@link SCHEME_RE} but is a path. */
|
||||
const DRIVE_RE = /^[A-Za-z]:[\\/]/
|
||||
/** The extensions a markdown link may claim (this batch claims markdown only —
|
||||
* a `.txt`/`.png`/`.ts` link keeps the browser's own behavior). */
|
||||
const MARKDOWN_EXT_RE = /\.(?:md|markdown)$/i
|
||||
/** The host's own fragment grammar for a line destination (`#L24`, `#L24-L30`). */
|
||||
const HOST_LINE_FRAGMENT_RE = /^L[1-9]\d*(?:-L[1-9]\d*)?$/
|
||||
|
||||
/** Whether a fragment is the host's line destination rather than an anchor. */
|
||||
export function isHostLineFragment(fragment: string): boolean {
|
||||
return HOST_LINE_FRAGMENT_RE.test(fragment)
|
||||
}
|
||||
|
||||
/** Percent-decode one URL piece, tolerating a malformed escape (a literal `%`). */
|
||||
function decodePercent(value: string): string {
|
||||
try {
|
||||
return decodeURIComponent(value)
|
||||
} catch {
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
/** The directory part of a path, trailing separator included (`''` when none). */
|
||||
function directoryOf(path: string): string {
|
||||
const at = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))
|
||||
return at === -1 ? '' : path.slice(0, at + 1)
|
||||
}
|
||||
|
||||
/** Join a directory and a relative path with `/` (normalized by the caller). */
|
||||
function joinPath(directory: string, relative: string): string {
|
||||
if (directory === '') return relative
|
||||
return `${directory.replace(/[\\/]+$/, '')}/${relative}`
|
||||
}
|
||||
|
||||
/** One destination's fragment separator: its offset and its length. */
|
||||
interface FragmentSeparator {
|
||||
at: number
|
||||
length: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a destination's fragment separator — a literal `#` (as authored, or as
|
||||
* the host hands a decoded destination back to `openFile`) or the encoded
|
||||
* `%23` this module writes into the source. Returns null when there is none.
|
||||
*/
|
||||
function separatorOf(destination: string): FragmentSeparator | null {
|
||||
const literal = destination.indexOf('#')
|
||||
const encoded = destination.indexOf(ENCODED_HASH)
|
||||
if (literal === -1 && encoded === -1) return null
|
||||
if (literal === -1) return { at: encoded, length: ENCODED_HASH.length }
|
||||
if (encoded === -1 || literal < encoded) return { at: literal, length: 1 }
|
||||
return { at: encoded, length: ENCODED_HASH.length }
|
||||
}
|
||||
|
||||
/**
|
||||
* The GitHub heading slug of one heading's text: trimmed, lower-cased,
|
||||
* punctuation and symbols dropped (`-` and `_` survive — GitHub's own slugger
|
||||
* keeps both), whitespace runs collapsed to a single dash, and every letter,
|
||||
* digit and combining mark of ANY script kept — so a Chinese heading keeps its
|
||||
* own text as its id, exactly like GitHub does.
|
||||
* @param text - the heading's rendered text.
|
||||
* @returns the slug (`''` for a heading with no letters or digits at all).
|
||||
*/
|
||||
export function githubHeadingSlug(text: string): string {
|
||||
return text
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^\p{L}\p{N}\p{M}\s_-]/gu, '')
|
||||
.trim()
|
||||
.replace(/\s+/g, '-')
|
||||
}
|
||||
|
||||
/**
|
||||
* Give every heading under `root` a slug `id`, in document order, `-1`/`-2`
|
||||
* suffixed on repeats. Authored ids are kept AND reserved first, so a generated
|
||||
* slug can never collide with an explicit anchor later in the document; a
|
||||
* heading whose text carries no letters or digits is left alone (an empty id
|
||||
* resolves nothing). Idempotent: a second pass over the same tree — the
|
||||
* mutation re-runs the surface installer depends on — changes nothing.
|
||||
* @param root - the surface container (React owns the tree; ids live outside
|
||||
* React's props, so React never removes them).
|
||||
*/
|
||||
export function assignHeadingIds(root: ParentNode): void {
|
||||
const headings = [...root.querySelectorAll<HTMLElement>('h1, h2, h3, h4, h5, h6')]
|
||||
const taken = new Set<string>()
|
||||
for (const heading of headings) {
|
||||
if (heading.id !== '') taken.add(heading.id)
|
||||
}
|
||||
for (const heading of headings) {
|
||||
if (heading.id !== '') continue
|
||||
const base = githubHeadingSlug(heading.textContent ?? '')
|
||||
if (base === '') continue
|
||||
let id = base
|
||||
for (let suffix = 1; taken.has(id); suffix += 1) id = `${base}-${suffix}`
|
||||
heading.id = id
|
||||
taken.add(id)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapse the explicit anchors GitHub-style READMEs carry (`<a id="x"></a>`):
|
||||
* an `<a>` with an id, no child elements and no text is marked `hidden` — out
|
||||
* of the way visually, still in the DOM, so `#x` deep links (and the jump
|
||||
* helper below) still resolve. Anchors with any content are untouched.
|
||||
* @param root - the surface container.
|
||||
*/
|
||||
export function hideEmptyAnchors(root: ParentNode): void {
|
||||
for (const anchor of root.querySelectorAll<HTMLAnchorElement>('a[id]')) {
|
||||
if (anchor.children.length > 0) continue
|
||||
if ((anchor.textContent ?? '').trim() !== '') continue
|
||||
anchor.hidden = true
|
||||
}
|
||||
}
|
||||
|
||||
/** One post-render pass: heading ids plus empty-anchor collapsing. */
|
||||
export function prepareMarkdownAnchors(root: ParentNode): void {
|
||||
assignHeadingIds(root)
|
||||
hideEmptyAnchors(root)
|
||||
}
|
||||
|
||||
/**
|
||||
* The pure link judge: what a destination inside a plugin markdown surface
|
||||
* means, or null to leave it entirely alone.
|
||||
*
|
||||
* Fed either shape the pipeline produces — a destination as authored (the
|
||||
* source rewriter's input) or the decoded destination the host hands
|
||||
* `openFile` (where this module's `%23` has already become a `#`).
|
||||
* @param destination - the link destination (a raw `href`-style string).
|
||||
* @param docPath - the absolute path of the markdown document being rendered;
|
||||
* relative targets resolve against its directory. Absent for prose surfaces.
|
||||
* @param cwd - the session workspace root, the base for prose surfaces.
|
||||
* @returns the resolved target, or null for every link the plugin does not own.
|
||||
*/
|
||||
export function markdownAnchorTarget(
|
||||
destination: string,
|
||||
docPath: string | undefined,
|
||||
cwd: string | undefined,
|
||||
): MarkdownAnchorTarget | null {
|
||||
const raw = destination.trim()
|
||||
if (raw === '') return null
|
||||
const separator = separatorOf(raw)
|
||||
const pathPart = separator === null ? raw : raw.slice(0, separator.at)
|
||||
const fragment = separator === null ? '' : decodePercent(raw.slice(separator.at + separator.length))
|
||||
// `#标题` / `#` — the document's own fragment.
|
||||
if (pathPart === '') return { kind: 'same-page', fragment }
|
||||
// `https://…`, `mailto:…`, `data:…` — never ours (a drive letter is a path).
|
||||
if (SCHEME_RE.test(pathPart) && !DRIVE_RE.test(pathPart)) return null
|
||||
// `//host/x.md` — a scheme-relative URL, i.e. remote too.
|
||||
if (pathPart.startsWith('//')) return null
|
||||
const path = decodePercent(pathPart)
|
||||
if (!MARKDOWN_EXT_RE.test(path)) return null
|
||||
return { kind: 'file', path: resolveTargetPath(path, docPath, cwd), fragment }
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a claimed markdown destination against the document that authored it.
|
||||
* Absolute paths (POSIX, drive, UNC) are normalized in place; a relative path
|
||||
* joins the document's own directory (or the session cwd); with neither base
|
||||
* known the relative spelling is handed on untouched for the opener to resolve
|
||||
* against the session cwd.
|
||||
*/
|
||||
function resolveTargetPath(path: string, docPath: string | undefined, cwd: string | undefined): string {
|
||||
if (isAbsolutePath(path)) return normalizeLocalPath(path)
|
||||
const directory = docPath !== undefined && docPath !== '' ? directoryOf(docPath) : (cwd ?? '')
|
||||
if (directory === '') return path.replace(/^(?:\.\/)+/, '').replace(/\\/g, '/')
|
||||
return normalizeLocalPath(joinPath(directory, path))
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a destination's path part is a LOCAL path the host would otherwise
|
||||
* turn into a clickable file link (once a surface provides `openFile`). Remote
|
||||
* URLs, scheme-relative URLs and anything already carrying a query (which
|
||||
* `parseFileLink` refuses on its own) are excluded.
|
||||
*/
|
||||
function isLocalDestination(pathPart: string): boolean {
|
||||
if (pathPart === '' || pathPart.includes('?')) return false
|
||||
if (pathPart.startsWith('//')) return false
|
||||
if (SCHEME_RE.test(pathPart) && !DRIVE_RE.test(pathPart)) return false
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite ONE destination for the host renderer (see the module comment).
|
||||
* Idempotent: an already-rewritten `%23` destination, a line destination and a
|
||||
* fragment-less link all come back untouched.
|
||||
*/
|
||||
function rewriteDestination(destination: string, docPath: string | undefined, cwd: string | undefined): string {
|
||||
const separator = separatorOf(destination)
|
||||
const pathPart = separator === null ? destination : destination.slice(0, separator.at)
|
||||
const fragment = separator === null ? '' : destination.slice(separator.at + separator.length)
|
||||
if (markdownAnchorTarget(destination, docPath, cwd) === null) {
|
||||
// Not ours: a remote link keeps its own anchor; a local one is pinned back
|
||||
// to plain text (`parseFileLink` refuses a destination carrying a query),
|
||||
// so the surface's delegate never offers an action it would not serve.
|
||||
if (!isLocalDestination(pathPart)) return destination
|
||||
const rest = separator === null ? '' : destination.slice(separator.at)
|
||||
return `${pathPart}?${rest}`
|
||||
}
|
||||
// Claimed. Nothing to carry without a fragment, `%23` is already ours, and a
|
||||
// line destination belongs to the host's own grammar.
|
||||
if (separator === null || separator.length === ENCODED_HASH.length) return destination
|
||||
if (isHostLineFragment(fragment)) return destination
|
||||
return `${pathPart}${ENCODED_HASH}${fragment}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the host renderer able to SERVE the local links of one markdown text:
|
||||
* a claimed `.md`/`.markdown` destination gets its heading fragment carried as
|
||||
* `%23`, and every other local destination gets the `?` that keeps it inert.
|
||||
*
|
||||
* Code spans and fenced blocks are masked first, so documentation that
|
||||
* demonstrates `[x](./a.md#标题)` is not mutated. Image destinations are left
|
||||
* to `rewriteLocalImageUrls` (which must run FIRST: it rewrites the definitions
|
||||
* an image uses into absolute media URLs, which this pass then ignores).
|
||||
* @param text - the markdown source about to be rendered.
|
||||
* @param docPath - the rendered document's absolute path (relative-link base).
|
||||
* @param cwd - the session workspace root, the base for prose surfaces.
|
||||
* @returns the markdown with local link destinations rewritten in place.
|
||||
*/
|
||||
export function rewriteLocalMarkdownLinks(
|
||||
text: string,
|
||||
docPath: string | undefined,
|
||||
cwd: string | undefined,
|
||||
): string {
|
||||
const masks: string[] = []
|
||||
const masked = text
|
||||
.replace(/```[\s\S]*?```/g, (block) => { masks.push(block); return `\u0000${masks.length - 1}\u0000` })
|
||||
.replace(/`[^`\n]*`/g, (span) => { masks.push(span); return `\u0000${masks.length - 1}\u0000` })
|
||||
|
||||
const links = masked
|
||||
// Inline links. The negative lookbehind keeps IMAGE destinations out, and
|
||||
// the label may hold ONE nested bracket pair — `[](./x.md)`
|
||||
// is a README staple, and matching only up to the inner `]` would read the
|
||||
// badge's own destination as the link's. The label is re-emitted verbatim,
|
||||
// so nested content keeps whatever the image pass gave it.
|
||||
.replace(
|
||||
/(?<!!)\[((?:[^[\]]|\[[^\]]*\])*)\]\(([^)\s]+)((?:\s+"[^"]*")?)\)/g,
|
||||
(_match, label: string, destination: string, title: string) =>
|
||||
`[${label}](${rewriteDestination(destination, docPath, cwd)}${title})`,
|
||||
)
|
||||
// Reference definitions. Every local one is fair game: a definition an
|
||||
// image uses was already turned into an absolute media URL by the image
|
||||
// pass, and an absolute http(s) URL is never touched here.
|
||||
.replace(
|
||||
/^(\s*\[([^\]]+)\]:\s*)(<[^>]+>|[^\s]+)/gm,
|
||||
(_match, head: string, _label: string, destination: string) => {
|
||||
// A `<…>` destination keeps its brackets: they are what lets the path
|
||||
// carry a space, and dropping them would truncate the link.
|
||||
const bracketed = destination.startsWith('<') && destination.endsWith('>')
|
||||
const inner = bracketed ? destination.slice(1, -1) : destination
|
||||
const rewritten = rewriteDestination(inner, docPath, cwd)
|
||||
return `${head}${bracketed ? `<${rewritten}>` : rewritten}`
|
||||
},
|
||||
)
|
||||
|
||||
// eslint-disable-next-line no-control-regex -- NUL is the deliberate mask sentinel (cannot appear in source markdown)
|
||||
return links.replace(/\u0000(\d+)\u0000/g, (_m, index: string) => masks[Number(index)] ?? '')
|
||||
}
|
||||
|
||||
/**
|
||||
* The element a fragment names, or null. Both the fragment as written and its
|
||||
* slug form are tried, so `#Some Heading` and `#some-heading` both land. The
|
||||
* scan is a linear walk over `[id]` rather than a selector: ids come from
|
||||
* arbitrary markdown text and need no CSS escaping this way.
|
||||
* @param root - the surface container.
|
||||
* @param fragment - the percent-decoded fragment.
|
||||
*/
|
||||
export function findAnchorTarget(root: ParentNode, fragment: string): HTMLElement | null {
|
||||
const wanted = new Set([fragment, githubHeadingSlug(fragment)])
|
||||
wanted.delete('')
|
||||
if (wanted.size === 0) return null
|
||||
for (const element of root.querySelectorAll<HTMLElement>('[id]')) {
|
||||
if (wanted.has(element.id)) return element
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Whether an element can scroll its own content right now. */
|
||||
function isScrollable(element: HTMLElement): boolean {
|
||||
const overflowY = window.getComputedStyle(element).overflowY
|
||||
return (overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay')
|
||||
&& element.scrollHeight > element.clientHeight
|
||||
}
|
||||
|
||||
/**
|
||||
* The scroller a jump writes to: the nearest scrollable ancestor of the surface
|
||||
* container — the preview's own scroll box — falling back to the container
|
||||
* itself. Never `window.scrollTo` (nor `scrollIntoView`, which walks every
|
||||
* scrollable ancestor and would drag the whole sidebar).
|
||||
*/
|
||||
function scrollHostFor(container: HTMLElement): HTMLElement {
|
||||
for (let node: HTMLElement | null = container; node !== null; node = node.parentElement) {
|
||||
if (isScrollable(node)) return node
|
||||
}
|
||||
return container
|
||||
}
|
||||
|
||||
/**
|
||||
* A `hidden` element has no layout box, so measuring it would report the
|
||||
* viewport origin: resolve a hidden explicit anchor through its nearest visible
|
||||
* ancestor, which is exactly where the id sits in the flow.
|
||||
*/
|
||||
function visibleAncestorOf(target: HTMLElement): HTMLElement {
|
||||
let node = target
|
||||
while (node.hidden && node.parentElement !== null) node = node.parentElement
|
||||
return node
|
||||
}
|
||||
|
||||
/**
|
||||
* Scroll one element to the top of the surface's own scroller (the measured box
|
||||
* of `container`, so nothing outside it moves).
|
||||
* @param container - the surface container.
|
||||
* @param target - the element to reveal.
|
||||
*/
|
||||
export function scrollAnchorIntoView(container: HTMLElement, target: HTMLElement): void {
|
||||
const scroller = scrollHostFor(container)
|
||||
const box = visibleAncestorOf(target)
|
||||
const offset = box.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop
|
||||
scroller.scrollTop = Math.max(0, offset - SCROLL_TOP_PADDING)
|
||||
}
|
||||
|
||||
/**
|
||||
* Land `fragment` inside `container`: open a collapsed `<details>` ancestor
|
||||
* (the same courtesy the preview's own outline pays) and scroll the surface's
|
||||
* own scroller. A missing target is a silent no-op — a stale link must neither
|
||||
* throw nor move the reader.
|
||||
* @returns whether the document actually carries the fragment.
|
||||
*/
|
||||
export function jumpToFragment(container: HTMLElement, fragment: string): boolean {
|
||||
// A bare `#` link means "back to the top" (READMEs use it as such).
|
||||
if (fragment === '') {
|
||||
scrollHostFor(container).scrollTop = 0
|
||||
return true
|
||||
}
|
||||
const target = findAnchorTarget(container, fragment)
|
||||
if (target === null) return false
|
||||
target.closest('details:not([open])')?.setAttribute('open', '')
|
||||
scrollAnchorIntoView(container, target)
|
||||
return true
|
||||
}
|
||||
|
||||
/** The pending cross-file fragments, keyed by session + absolute target path. */
|
||||
const pendingAnchors = new Map<string, { fragment: string; at: number }>()
|
||||
|
||||
/** The lookup key of one document: session + its path, separator- and
|
||||
* traversal-normalized so the two spellings a surface and the editor hold
|
||||
* (`/p/a.md` vs `\p\a.md`, cwd-relative vs absolute) meet. */
|
||||
function anchorKey(sessionId: string, cwd: string | undefined, path: string): string {
|
||||
const absolute = isAbsolutePath(path) ? path : joinPath(cwd ?? '', path)
|
||||
return `${sessionId}::${normalizeLocalPath(absolute).replace(/\\/g, '/')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Park the fragment a cross-file link wants to land on, for the target
|
||||
* document's own surface to take once it mounts.
|
||||
* @param sessionId - the session both documents live in.
|
||||
* @param cwd - that session's workspace root (path resolution).
|
||||
* @param path - the target file (absolute, or cwd-relative).
|
||||
* @param fragment - the decoded fragment (`''` parks nothing).
|
||||
*/
|
||||
export function rememberMarkdownAnchor(
|
||||
sessionId: string,
|
||||
cwd: string | undefined,
|
||||
path: string,
|
||||
fragment: string,
|
||||
): void {
|
||||
if (fragment === '') return
|
||||
pendingAnchors.set(anchorKey(sessionId, cwd, path), { fragment, at: Date.now() })
|
||||
}
|
||||
|
||||
/**
|
||||
* Take (and clear) the fragment parked for one document. The entry is always
|
||||
* consumed — a surface that takes it and finds no such heading does not leave
|
||||
* it behind for a later, unrelated open.
|
||||
* @returns the fragment, or null when nothing (fresh) is parked.
|
||||
*/
|
||||
export function takeMarkdownAnchor(sessionId: string, cwd: string | undefined, path: string): string | null {
|
||||
const key = anchorKey(sessionId, cwd, path)
|
||||
const entry = pendingAnchors.get(key)
|
||||
if (entry === undefined) return null
|
||||
pendingAnchors.delete(key)
|
||||
return Date.now() - entry.at > PENDING_TTL_MS ? null : entry.fragment
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* React glue for ONE plugin-drawn markdown surface (the container that holds
|
||||
* the rendered markdown). It returns three things the caller wires up:
|
||||
*
|
||||
* - `surfaceRef`: a CALLBACK REF for that container. The installer behind it
|
||||
* runs the DOM pass from `markdown-navigation.ts` (heading slugs + collapsed
|
||||
* explicit anchors) on mount and after every content mutation — the pattern
|
||||
* the raw-HTML preview pass already uses, which keeps late content (the lazy
|
||||
* mermaid chunk, shiki highlighting) covered and makes the pass self-healing
|
||||
* when React re-renders a subtree it owns — and then applies the cross-file
|
||||
* fragment parked for this document. A callback ref (not a `RefObject`)
|
||||
* because the container mounts and unmounts with its host — the preview
|
||||
* container disappears on every preview→edit flip — and only a ref callback
|
||||
* fires on both edges (React 18 hands it `null` on unmount, which is where
|
||||
* the observer is torn down). Its identity is keyed on (session, path) alone,
|
||||
* so an ordinary re-render never detaches anything.
|
||||
* - `openFile`: the host delegate's file handler. The host renderer only makes
|
||||
* a local markdown link clickable when a `MarkdownDelegateProvider` supplies
|
||||
* this, which is why every caller wraps its markdown in that provider with
|
||||
* `openFile={surface.openFile}`: the provider's scope IS the claim boundary,
|
||||
* and a link rendered outside it (the host's chat prose, any other panel) is
|
||||
* never seen by this plugin.
|
||||
* - `rewrite`: the source-side pass (`rewriteLocalMarkdownLinks`) that runs
|
||||
* BEFORE rendering, so a heading fragment survives the host's parser and a
|
||||
* link the plugin does not claim stays inert prose.
|
||||
*/
|
||||
import { useCallback, useRef } from 'react'
|
||||
import type { Context } from '../context-types.ts'
|
||||
import {
|
||||
jumpToFragment,
|
||||
markdownAnchorTarget,
|
||||
prepareMarkdownAnchors,
|
||||
rememberMarkdownAnchor,
|
||||
rewriteLocalMarkdownLinks,
|
||||
takeMarkdownAnchor,
|
||||
} from './markdown-navigation.ts'
|
||||
import { openSidebarFile } from './sidebar-file.ts'
|
||||
|
||||
/** The DOM marker the installer puts on the container it owns (the claim
|
||||
* boundary is the provider scope; this makes the surface inspectable in a
|
||||
* browser and pointable from a spec). */
|
||||
export const MARKDOWN_SURFACE_ATTR = 'data-dsh-md-surface'
|
||||
|
||||
export interface MarkdownSurfaceOptions {
|
||||
/** Client context: the open goes through `openSidebarFile`, the plugin's own
|
||||
* claim-aware editor path (same entry point the file tree and the chat
|
||||
* mentions use). */
|
||||
ctx: Context
|
||||
/** The session the markdown renders in — the open scope and the key of the
|
||||
* pending-fragment table. */
|
||||
sessionId: string
|
||||
/** The session workspace root, when the caller has a scope. Read live at
|
||||
* click time (a session's cwd may land after the tab does). */
|
||||
cwd?: string
|
||||
/** The rendered file's absolute path: relative targets resolve against its
|
||||
* directory. Prose surfaces (transcript, task note) omit it — their
|
||||
* relative targets resolve against the session cwd instead. */
|
||||
path?: string
|
||||
}
|
||||
|
||||
/** What a surface wires into its markup. */
|
||||
export interface MarkdownSurfaceBinding {
|
||||
/** Callback ref for the container that holds the rendered markdown. */
|
||||
surfaceRef: (element: HTMLElement | null) => void
|
||||
/** `MarkdownDelegateProvider.openFile` for this surface. */
|
||||
openFile: (destination: string, options?: { line?: number }) => void
|
||||
/** Rewrite one markdown text before rendering it in this surface. */
|
||||
rewrite: (text: string) => string
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire one plugin markdown surface.
|
||||
* @param opts - the surface's context, session and rendered document path.
|
||||
* @returns the container ref, the delegate handler and the source rewrite.
|
||||
*/
|
||||
export function useMarkdownSurface(opts: MarkdownSurfaceOptions): MarkdownSurfaceBinding {
|
||||
const { ctx, sessionId, cwd, path } = opts
|
||||
const containerRef = useRef<HTMLElement | null>(null)
|
||||
const detachRef = useRef<(() => void) | null>(null)
|
||||
|
||||
/** The session workspace root: the caller's scope when it has one, else the
|
||||
* session summary (a stripped-down host or a bare spec context may have no
|
||||
* session list at all — the opener then resolves against its own cwd). */
|
||||
const resolveCwd = useCallback(
|
||||
(): string | undefined => cwd ?? ctx.sessions?.list?.getSnapshot?.()?.byId?.[sessionId]?.cwd,
|
||||
[ctx, sessionId, cwd],
|
||||
)
|
||||
|
||||
const surfaceRef = useCallback((element: HTMLElement | null): void => {
|
||||
detachRef.current?.()
|
||||
detachRef.current = null
|
||||
containerRef.current = element
|
||||
if (element === null) return
|
||||
detachRef.current = attachMarkdownSurface(element, sessionId, path, resolveCwd)
|
||||
}, [sessionId, path, resolveCwd])
|
||||
|
||||
const openFile = useCallback((destination: string, options?: { line?: number }): void => {
|
||||
const target = markdownAnchorTarget(destination, path, resolveCwd())
|
||||
if (target === null) return
|
||||
if (target.kind === 'same-page') {
|
||||
const container = containerRef.current
|
||||
if (container !== null) jumpToFragment(container, target.fragment)
|
||||
return
|
||||
}
|
||||
// `#L24` arrives as the host's own line option (never as an anchor); a
|
||||
// heading fragment parks a jump for the document about to open.
|
||||
if (options?.line === undefined && target.fragment !== '') {
|
||||
rememberMarkdownAnchor(sessionId, resolveCwd(), target.path, target.fragment)
|
||||
}
|
||||
try {
|
||||
openSidebarFile(ctx, sessionId, target.path)
|
||||
} catch (error) {
|
||||
// A failed open leaves the reader where they are (the link was claimed);
|
||||
// the parked fragment expires on its own.
|
||||
console.error('[dsh-better-sidebar] markdown file link open failed', error)
|
||||
}
|
||||
}, [ctx, sessionId, path, resolveCwd])
|
||||
|
||||
const rewrite = useCallback(
|
||||
(text: string): string => rewriteLocalMarkdownLinks(text, path, resolveCwd()),
|
||||
[path, resolveCwd],
|
||||
)
|
||||
|
||||
return { surfaceRef, openFile, rewrite }
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the post-render half on one container: the DOM pass, its mutation
|
||||
* re-runs, and the pending cross-file fragment.
|
||||
* @returns the disposer (observer + marker).
|
||||
*/
|
||||
function attachMarkdownSurface(
|
||||
container: HTMLElement,
|
||||
sessionId: string,
|
||||
path: string | undefined,
|
||||
resolveCwd: () => string | undefined,
|
||||
): () => void {
|
||||
container.setAttribute(MARKDOWN_SURFACE_ATTR, '')
|
||||
prepareMarkdownAnchors(container)
|
||||
|
||||
/** The fragment this surface still owes the reader (taken once, then carried
|
||||
* here until the heading actually renders — the content may arrive a beat
|
||||
* after the container does). */
|
||||
let pending: string | null = path === undefined || path === '' ? null : takeMarkdownAnchor(sessionId, resolveCwd(), path)
|
||||
const applyPending = (): void => {
|
||||
if (pending !== null && jumpToFragment(container, pending)) pending = null
|
||||
}
|
||||
// After the commit that mounted this container: the host's layout effects
|
||||
// (the preview's remembered-scroll restore) run first, so this is the last
|
||||
// write to the scroller.
|
||||
if (pending !== null) queueMicrotask(applyPending)
|
||||
|
||||
let scheduled = false
|
||||
const observer = new MutationObserver(() => {
|
||||
if (scheduled) return
|
||||
scheduled = true
|
||||
queueMicrotask(() => {
|
||||
scheduled = false
|
||||
prepareMarkdownAnchors(container)
|
||||
applyPending()
|
||||
})
|
||||
})
|
||||
observer.observe(container, { childList: true, subtree: true })
|
||||
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
container.removeAttribute(MARKDOWN_SURFACE_ATTR)
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { act } from 'react-dom/test-utils'
|
||||
import { DiffPane } from '../src/client/changes/DiffPane.tsx'
|
||||
import { DiffTab } from '../src/client/DiffTab.tsx'
|
||||
import { api } from '../src/client/api.ts'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
import type { SessionScope } from '../src/client/api.ts'
|
||||
import type { SidebarDiffRef } from '../src/client/state.ts'
|
||||
|
||||
@@ -69,6 +70,7 @@ describe('useGitDiffTarget through the inline preview pane (DiffPane)', () => {
|
||||
act(() => {
|
||||
root.render(createElement(DiffPane, {
|
||||
target: { kind: 'git', ref: worktree },
|
||||
ctx: {} as Context,
|
||||
scope: SCOPE,
|
||||
height: 300,
|
||||
onHeightCommit: () => {},
|
||||
@@ -101,6 +103,7 @@ describe('useGitDiffTarget through the inline preview pane (DiffPane)', () => {
|
||||
act(() => {
|
||||
root.render(createElement(DiffPane, {
|
||||
target: { kind: 'git', ref: worktree },
|
||||
ctx: {} as Context,
|
||||
scope: SCOPE,
|
||||
height: 300,
|
||||
onHeightCommit: () => {},
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
/**
|
||||
* The pure half of markdown anchor navigation (`src/client/markdown-navigation.ts`):
|
||||
* GitHub heading slugs, the link-claim judge, the SOURCE rewrite that carries a
|
||||
* heading fragment past the host's `parseFileLink`, and the cross-file fragment
|
||||
* table. The DOM half — ids on real rendered markdown, the host delegate's
|
||||
* click path, in-preview scrolling — lives in tests/markdown-surface.spec.tsx,
|
||||
* which renders the REAL TextEditor (and therefore the real host `MarkdownText`).
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
githubHeadingSlug,
|
||||
isHostLineFragment,
|
||||
markdownAnchorTarget,
|
||||
rememberMarkdownAnchor,
|
||||
rewriteLocalMarkdownLinks,
|
||||
takeMarkdownAnchor,
|
||||
type MarkdownAnchorTarget,
|
||||
} from '../src/client/markdown-navigation.ts'
|
||||
|
||||
const DOC = '/ws/docs/README.md'
|
||||
const CWD = '/ws'
|
||||
|
||||
/** The judged FILE target, failing loudly when the link was not claimed. The
|
||||
* base is an object rather than two defaulted parameters: `undefined` is one
|
||||
* of the cases under test ("no document, no cwd"), and a defaulted parameter
|
||||
* cannot express it. */
|
||||
function fileTarget(
|
||||
destination: string,
|
||||
base: { docPath?: string; cwd?: string } = { docPath: DOC, cwd: CWD },
|
||||
): { path: string; fragment: string } {
|
||||
const target: MarkdownAnchorTarget | null = markdownAnchorTarget(destination, base.docPath, base.cwd)
|
||||
if (target === null || target.kind !== 'file') throw new Error(`not claimed as a file link: ${destination}`)
|
||||
return { path: target.path, fragment: target.fragment }
|
||||
}
|
||||
|
||||
describe('githubHeadingSlug', () => {
|
||||
it('lower-cases, drops punctuation and collapses whitespace runs to one dash', () => {
|
||||
expect(githubHeadingSlug('Hello, World!')).toBe('hello-world')
|
||||
expect(githubHeadingSlug(' Mixed CASE ')).toBe('mixed-case')
|
||||
expect(githubHeadingSlug('API 参考 (v2)')).toBe('api-参考-v2')
|
||||
expect(githubHeadingSlug('`code` & "quotes"')).toBe('code-quotes')
|
||||
expect(githubHeadingSlug('Trailing punctuation:')).toBe('trailing-punctuation')
|
||||
})
|
||||
|
||||
it('keeps Chinese text as its own id, like GitHub does', () => {
|
||||
expect(githubHeadingSlug('中文标题')).toBe('中文标题')
|
||||
expect(githubHeadingSlug('已核实的事实')).toBe('已核实的事实')
|
||||
// The full-width colon is punctuation: it goes, the text stays.
|
||||
expect(githubHeadingSlug('认领文件链接:在侧栏打开')).toBe('认领文件链接在侧栏打开')
|
||||
})
|
||||
|
||||
it('keeps the dash and underscore GitHub keeps, and drops symbols', () => {
|
||||
expect(githubHeadingSlug('Foo-Bar_Baz')).toBe('foo-bar_baz')
|
||||
expect(githubHeadingSlug('C++ / C#')).toBe('c-c')
|
||||
expect(githubHeadingSlug('🎉 Party')).toBe('party')
|
||||
})
|
||||
|
||||
it('yields an empty slug for text with nothing to keep', () => {
|
||||
expect(githubHeadingSlug('!!!')).toBe('')
|
||||
expect(githubHeadingSlug(' ')).toBe('')
|
||||
expect(githubHeadingSlug('')).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isHostLineFragment', () => {
|
||||
it('recognizes the line grammar the host parses itself', () => {
|
||||
expect(isHostLineFragment('L24')).toBe(true)
|
||||
expect(isHostLineFragment('L24-L30')).toBe(true)
|
||||
// The host's own regex does not validate the range order either, so a
|
||||
// reversed range stays the host's business — this predicate mirrors the
|
||||
// host grammar exactly, no more.
|
||||
expect(isHostLineFragment('L24-L3')).toBe(true)
|
||||
expect(isHostLineFragment('l24')).toBe(false)
|
||||
expect(isHostLineFragment('L0')).toBe(false)
|
||||
expect(isHostLineFragment('标题')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('markdownAnchorTarget', () => {
|
||||
it('claims a relative .md link against the DOCUMENT directory, not the cwd', () => {
|
||||
// The whole point of the base rule: the link lives in /ws/docs, so its
|
||||
// sibling is /ws/docs/other.md — NOT /ws/other.md.
|
||||
expect(fileTarget('./other.md')).toEqual({ path: '/ws/docs/other.md', fragment: '' })
|
||||
expect(fileTarget('other.md')).toEqual({ path: '/ws/docs/other.md', fragment: '' })
|
||||
})
|
||||
|
||||
it('collapses . and .. segments and accepts both markdown extensions', () => {
|
||||
expect(fileTarget('../a/b.markdown')).toEqual({ path: '/ws/a/b.markdown', fragment: '' })
|
||||
expect(fileTarget('./deep/./x/../y.md')).toEqual({ path: '/ws/docs/deep/y.md', fragment: '' })
|
||||
// The extension check is case-insensitive; other markdown-ish extensions
|
||||
// are NOT claimed this batch.
|
||||
expect(fileTarget('./OTHER.MD').path).toBe('/ws/docs/OTHER.MD')
|
||||
expect(markdownAnchorTarget('./other.mdx', DOC, CWD)).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps a fragment through the claim, percent-decoded — both spellings', () => {
|
||||
// As authored (a literal `#`) and as the host hands it back after decoding
|
||||
// this module's `%23` carrier.
|
||||
expect(fileTarget('./other.md#中文标题')).toEqual({ path: '/ws/docs/other.md', fragment: '中文标题' })
|
||||
expect(fileTarget('./other.md%23中文标题')).toEqual({ path: '/ws/docs/other.md', fragment: '中文标题' })
|
||||
expect(fileTarget('./other.md#%E6%A0%87%E9%A2%98')).toEqual({ path: '/ws/docs/other.md', fragment: '标题' })
|
||||
expect(fileTarget('./a%20b.md').path).toBe('/ws/docs/a b.md')
|
||||
// The host's own line destination is claimed as a FILE (the line rides the
|
||||
// host's `options.line`; it is not an anchor).
|
||||
expect(fileTarget('./other.md#L24')).toEqual({ path: '/ws/docs/other.md', fragment: 'L24' })
|
||||
})
|
||||
|
||||
it('keeps an absolute path absolute (POSIX, drive letter, UNC)', () => {
|
||||
expect(fileTarget('/abs/x.md').path).toBe('/abs/x.md')
|
||||
// A drive-letter path LOOKS like a scheme (`C:`); it must stay a path.
|
||||
expect(fileTarget('C:\\docs\\x.md').path).toBe('C:\\docs\\x.md')
|
||||
expect(fileTarget('\\\\server\\share\\x.md').path).toBe('\\\\server\\share\\x.md')
|
||||
expect(fileTarget('/ws/docs/README.md#top')).toEqual({ path: '/ws/docs/README.md', fragment: 'top' })
|
||||
})
|
||||
|
||||
it('resolves against the session cwd when the surface renders no file', () => {
|
||||
expect(fileTarget('./other.md', { cwd: CWD }).path).toBe('/ws/other.md')
|
||||
// With no base at all the relative spelling passes through for the opener
|
||||
// (which resolves it against the session cwd itself).
|
||||
expect(fileTarget('docs/other.md', {}).path).toBe('docs/other.md')
|
||||
})
|
||||
|
||||
it('reads a bare fragment as the same document — decoded, and permissive', () => {
|
||||
expect(markdownAnchorTarget('#标题', DOC, CWD)).toEqual({ kind: 'same-page', fragment: '标题' })
|
||||
// `#` alone is "back to the top".
|
||||
expect(markdownAnchorTarget('#', DOC, CWD)).toEqual({ kind: 'same-page', fragment: '' })
|
||||
// A fragment with a space still names the heading whose slug it is.
|
||||
expect(markdownAnchorTarget('#Some Heading', DOC, CWD)).toEqual({ kind: 'same-page', fragment: 'Some Heading' })
|
||||
// …and the encoded carrier the rewriter writes reads the same way.
|
||||
expect(markdownAnchorTarget('%23标题', DOC, CWD)).toEqual({ kind: 'same-page', fragment: '标题' })
|
||||
})
|
||||
|
||||
it('never claims remote links (http, https, mailto, protocol-relative)', () => {
|
||||
for (const destination of [
|
||||
'https://example.com/x.md',
|
||||
'http://example.com/x.md#a',
|
||||
'HTTPS://Example.com/X.MD',
|
||||
'mailto:me@example.com',
|
||||
'data:text/markdown,#x',
|
||||
'//example.com/x.md',
|
||||
]) {
|
||||
expect(markdownAnchorTarget(destination, DOC, CWD), destination).toBeNull()
|
||||
}
|
||||
// The one that IS claimed, for contrast: the DOM would have resolved both
|
||||
// of these against the GUI origin, which is why the raw destination is
|
||||
// judged and why a query kills the claim.
|
||||
expect(fileTarget('other.md').path).toBe('/ws/docs/other.md')
|
||||
})
|
||||
|
||||
it('leaves every other extension and unusable destination alone', () => {
|
||||
expect(markdownAnchorTarget('./notes.txt', DOC, CWD)).toBeNull()
|
||||
expect(markdownAnchorTarget('./image.png', DOC, CWD)).toBeNull()
|
||||
expect(markdownAnchorTarget('./src/a.ts', DOC, CWD)).toBeNull()
|
||||
expect(markdownAnchorTarget('./other.md?raw=1', DOC, CWD)).toBeNull()
|
||||
expect(markdownAnchorTarget('', DOC, CWD)).toBeNull()
|
||||
expect(markdownAnchorTarget(' ', DOC, CWD)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('rewriteLocalMarkdownLinks', () => {
|
||||
it('carries a heading fragment past the host parser as an encoded `#`', () => {
|
||||
expect(rewriteLocalMarkdownLinks('[x](./other.md#标题)', DOC, CWD)).toBe('[x](./other.md%23标题)')
|
||||
expect(rewriteLocalMarkdownLinks('[x](./other.md#)', DOC, CWD)).toBe('[x](./other.md%23)')
|
||||
expect(rewriteLocalMarkdownLinks('[x](#标题)', DOC, CWD)).toBe('[x](%23标题)')
|
||||
// The link label is untouched, titles survive, and the SAME destination the
|
||||
// judge accepts is the one the rewriter leaves alone.
|
||||
expect(rewriteLocalMarkdownLinks('[x](./other.md#标题 "title")', DOC, CWD)).toBe('[x](./other.md%23标题 "title")')
|
||||
expect(rewriteLocalMarkdownLinks('[x](./other.md#L24)', DOC, CWD)).toBe('[x](./other.md#L24)')
|
||||
expect(rewriteLocalMarkdownLinks('[x](./other.md)', DOC, CWD)).toBe('[x](./other.md)')
|
||||
})
|
||||
|
||||
it('keeps every destination the plugin does not claim inert', () => {
|
||||
// `parseFileLink` refuses a destination carrying a query, so the appended
|
||||
// `?` is what stops a non-markdown local path from becoming a file-mention
|
||||
// button the plugin would not serve.
|
||||
expect(rewriteLocalMarkdownLinks('[x](./notes.txt)', DOC, CWD)).toBe('[x](./notes.txt?)')
|
||||
expect(rewriteLocalMarkdownLinks('[x](./notes.txt#anchor)', DOC, CWD)).toBe('[x](./notes.txt?#anchor)')
|
||||
expect(rewriteLocalMarkdownLinks('[x](../src/a.ts#L3)', DOC, CWD)).toBe('[x](../src/a.ts?#L3)')
|
||||
// Remote links keep their own anchor, query and all.
|
||||
expect(rewriteLocalMarkdownLinks('[x](https://e.com/a.md#top)', DOC, CWD)).toBe('[x](https://e.com/a.md#top)')
|
||||
expect(rewriteLocalMarkdownLinks('[x](mailto:me@e.com)', DOC, CWD)).toBe('[x](mailto:me@e.com)')
|
||||
expect(rewriteLocalMarkdownLinks('[x](//e.com/a.md)', DOC, CWD)).toBe('[x](//e.com/a.md)')
|
||||
// An already-queried destination is inert on its own.
|
||||
expect(rewriteLocalMarkdownLinks('[x](./a.md?raw=1)', DOC, CWD)).toBe('[x](./a.md?raw=1)')
|
||||
})
|
||||
|
||||
it('leaves images to the image pass and code spans alone', () => {
|
||||
expect(rewriteLocalMarkdownLinks('', DOC, CWD)).toBe('')
|
||||
expect(rewriteLocalMarkdownLinks('`[x](./other.md#标题)`', DOC, CWD)).toBe('`[x](./other.md#标题)`')
|
||||
expect(rewriteLocalMarkdownLinks('```\n[x](./other.md#标题)\n```', DOC, CWD)).toBe('```\n[x](./other.md#标题)\n```')
|
||||
// An image nested in a link label keeps its own destination.
|
||||
expect(rewriteLocalMarkdownLinks('[](./other.md#x)', DOC, CWD))
|
||||
.toBe('[](./other.md%23x)')
|
||||
})
|
||||
|
||||
it('rewrites reference definitions, brackets included', () => {
|
||||
expect(rewriteLocalMarkdownLinks('[id]: ./other.md#标题', DOC, CWD)).toBe('[id]: ./other.md%23标题')
|
||||
expect(rewriteLocalMarkdownLinks('[id]: <./a b.md#标题>', DOC, CWD)).toBe('[id]: <./a b.md%23标题>')
|
||||
expect(rewriteLocalMarkdownLinks('[id]: ./notes.txt', DOC, CWD)).toBe('[id]: ./notes.txt?')
|
||||
// An image-used definition was already turned into a media URL by the
|
||||
// image pass (which runs first) — never touched here.
|
||||
expect(rewriteLocalMarkdownLinks('[id]: http://gui/sidebar/file?path=%2Fx.png', DOC, CWD))
|
||||
.toBe('[id]: http://gui/sidebar/file?path=%2Fx.png')
|
||||
})
|
||||
|
||||
it('is idempotent: a second pass over its own output changes nothing', () => {
|
||||
const once = rewriteLocalMarkdownLinks('[a](./other.md#标题) [b](./notes.txt) [c](#x) [d](./other.md#L3)', DOC, CWD)
|
||||
expect(rewriteLocalMarkdownLinks(once, DOC, CWD)).toBe(once)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the cross-file fragment table', () => {
|
||||
afterEach(() => { vi.useRealTimers() })
|
||||
|
||||
it('hands a parked fragment to the target document exactly once', () => {
|
||||
rememberMarkdownAnchor('s1', '/ws', '/ws/docs/other.md', '标题')
|
||||
expect(takeMarkdownAnchor('s1', '/ws', '/ws/docs/other.md')).toBe('标题')
|
||||
// Consumed AND cleared: a second mount of the same document must not jump
|
||||
// again.
|
||||
expect(takeMarkdownAnchor('s1', '/ws', '/ws/docs/other.md')).toBeNull()
|
||||
})
|
||||
|
||||
it('keys on session + path, matching the two spellings the surfaces hold', () => {
|
||||
// The click side has an absolute path; an editor tab opened from the chat
|
||||
// may hold the cwd-relative one (or a Windows separator). Both must meet.
|
||||
rememberMarkdownAnchor('s1', '/ws', 'docs/other.md', 'frag')
|
||||
expect(takeMarkdownAnchor('s1', '/ws', '/ws/docs/other.md')).toBe('frag')
|
||||
rememberMarkdownAnchor('s1', '/ws', '/ws/docs/other.md', 'frag')
|
||||
expect(takeMarkdownAnchor('s1', '/ws', 'docs\\other.md')).toBe('frag')
|
||||
// A different session, or a different file, is a miss.
|
||||
rememberMarkdownAnchor('s1', '/ws', '/ws/docs/other.md', 'frag')
|
||||
expect(takeMarkdownAnchor('s2', '/ws', '/ws/docs/other.md')).toBeNull()
|
||||
expect(takeMarkdownAnchor('s1', '/ws', '/ws/docs/third.md')).toBeNull()
|
||||
})
|
||||
|
||||
it('never parks an empty fragment, and expires a stale one', () => {
|
||||
// Distinct keys per case: the table is module state shared by the file.
|
||||
rememberMarkdownAnchor('s1', '/ws', '/ws/docs/empty.md', '')
|
||||
expect(takeMarkdownAnchor('s1', '/ws', '/ws/docs/empty.md')).toBeNull()
|
||||
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'))
|
||||
rememberMarkdownAnchor('s1', '/ws', '/ws/docs/stale.md', 'frag')
|
||||
vi.setSystemTime(new Date('2026-01-01T00:01:00Z'))
|
||||
// An open that never landed must not make a later, unrelated open jump.
|
||||
expect(takeMarkdownAnchor('s1', '/ws', '/ws/docs/stale.md')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,335 @@
|
||||
/**
|
||||
* The DOM half of markdown cross-file / anchor navigation, rendered through the
|
||||
* REAL TextEditor (and therefore the real host `MarkdownText`): heading slugs
|
||||
* on rendered headings, the host delegate that makes a claimed local link
|
||||
* clickable at all, the DECODED `%23` fragment carrier, same-page scrolling in
|
||||
* the preview's own container, and the parked cross-file fragment landing once
|
||||
* the target document renders.
|
||||
*
|
||||
* Why the delegate is the mechanism (and not a click listener on the
|
||||
* container): the host renderer gives a local destination a clickable element
|
||||
* ONLY when a surrounding `MarkdownDelegateProvider` supplies `openFile` —
|
||||
* otherwise the link is inert prose, and a heading fragment makes the whole
|
||||
* destination unparseable for the renderer. Both halves are asserted here,
|
||||
* including the boundary: the same markdown rendered OUTSIDE the plugin's
|
||||
* surface stays inert.
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createElement } from 'react'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { renderRoot, setupReactAct } from './test-utils.ts'
|
||||
import { TextEditor } from '../src/client/TextEditor.tsx'
|
||||
import { attachLocale } from '../src/client/locales.ts'
|
||||
import { createSidebarStore, allLeaves } from '../src/client/state.ts'
|
||||
import { createBetterSidebarService, type FileViewerProps } from '../src/client/service.ts'
|
||||
import { hideEmptyAnchors, jumpToFragment } from '../src/client/markdown-navigation.ts'
|
||||
import { MARKDOWN_SURFACE_ATTR } from '../src/client/use-markdown-surface.ts'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
|
||||
setupReactAct()
|
||||
|
||||
/** Minimal structural fake of the DSH LocaleService face the sidebar uses. */
|
||||
class FakeLocale {
|
||||
active: string = 'en'
|
||||
getSnapshot(): { active: string } {
|
||||
return { active: this.active }
|
||||
}
|
||||
subscribe(_fn: () => void): () => void {
|
||||
return () => {}
|
||||
}
|
||||
}
|
||||
|
||||
const SESSION = 's1'
|
||||
|
||||
interface Mounted {
|
||||
container: HTMLDivElement
|
||||
/** Every editor tab the sidebar currently holds (path-typed ones last). */
|
||||
tabs: () => { type: string; path?: string }[]
|
||||
unmount: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount the real TextEditor on one markdown file, backed by the plugin's own
|
||||
* sidebar service — so a claimed link's open is observed the way the app
|
||||
* observes it (a tab landing in the store), not through a stub.
|
||||
*/
|
||||
function mountEditor(content: string, path: string): Mounted {
|
||||
attachLocale(new FakeLocale())
|
||||
const store = createSidebarStore()
|
||||
const service = createBetterSidebarService(store)
|
||||
// openTab refuses a type nobody registered.
|
||||
service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab) => tab.path, component: () => null })
|
||||
store.setSession(SESSION)
|
||||
const ctx = {
|
||||
betterSidebar: service,
|
||||
get: (name: string) => name === 'betterSidebar' ? service : undefined,
|
||||
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: { [SESSION]: { cwd: '/p' } } }) } },
|
||||
} as unknown as Context
|
||||
const props: FileViewerProps = {
|
||||
ctx,
|
||||
store,
|
||||
scope: { sessionId: SESSION, cwd: '/p' },
|
||||
path,
|
||||
title: path.slice(path.lastIndexOf('/') + 1),
|
||||
viewerId: 'markdown',
|
||||
content,
|
||||
}
|
||||
const mounted = renderRoot(createElement(TextEditor, props))
|
||||
return {
|
||||
container: mounted.container,
|
||||
tabs: () => allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs),
|
||||
unmount: mounted.unmount,
|
||||
}
|
||||
}
|
||||
|
||||
/** The plugin's markdown surface container inside a mounted editor. */
|
||||
function surfaceOf(container: HTMLElement): HTMLElement {
|
||||
const surface = container.querySelector<HTMLElement>(`[${MARKDOWN_SURFACE_ATTR}]`)
|
||||
if (surface === null) throw new Error('markdown surface container not found')
|
||||
return surface
|
||||
}
|
||||
|
||||
/** The host-rendered file link whose destination is `title`, or null. */
|
||||
function fileLink(surface: HTMLElement, title: string): HTMLButtonElement | null {
|
||||
return [...surface.querySelectorAll('button')].find(button => button.title === title) ?? null
|
||||
}
|
||||
|
||||
/** Pin one element's measured top edge (jsdom has no layout). */
|
||||
function stubRectTop(element: Element, top: number): void {
|
||||
element.getBoundingClientRect = (): DOMRect => ({
|
||||
top, bottom: top, left: 0, right: 0, width: 0, height: 0, x: 0, y: top,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect
|
||||
}
|
||||
|
||||
/** Observe every write to an element's scrollTop (jsdom accepts the write but
|
||||
* has no layout to derive one from). */
|
||||
function watchScrollTop(element: HTMLElement): () => number {
|
||||
let value = 0
|
||||
Object.defineProperty(element, 'scrollTop', {
|
||||
configurable: true,
|
||||
get: () => value,
|
||||
set: (next: number) => { value = next },
|
||||
})
|
||||
return () => value
|
||||
}
|
||||
|
||||
/** Click one element the way a reader would. */
|
||||
function click(element: HTMLElement): void {
|
||||
act(() => { element.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })) })
|
||||
}
|
||||
|
||||
/** Flush the microtasks the surface installer queues (pending anchor, pass). */
|
||||
async function flushMicrotasks(): Promise<void> {
|
||||
await act(async () => { await new Promise(resolve => { setTimeout(resolve, 0) }) })
|
||||
}
|
||||
|
||||
/** `scrollIntoView` is absent in jsdom; a spy proves the jump never uses it
|
||||
* (it would drag every scrollable ancestor, i.e. the whole sidebar). */
|
||||
const scrollIntoView = vi.fn()
|
||||
const scrollTo = vi.fn()
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(Element.prototype, 'scrollIntoView', { configurable: true, writable: true, value: scrollIntoView })
|
||||
window.scrollTo = scrollTo as unknown as typeof window.scrollTo
|
||||
})
|
||||
afterEach(() => {
|
||||
scrollIntoView.mockClear()
|
||||
scrollTo.mockClear()
|
||||
attachLocale(undefined)
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
describe('the markdown preview surface', () => {
|
||||
it('slugs rendered headings like GitHub, keeps authored ids, and reserves them first', () => {
|
||||
const mounted = mountEditor([
|
||||
'## Hello, World!',
|
||||
'',
|
||||
'## Hello, World!',
|
||||
'',
|
||||
'### 中文标题',
|
||||
'',
|
||||
'<h2 id="custom">Authored</h2>',
|
||||
'',
|
||||
'<a id="anchor"></a>',
|
||||
'',
|
||||
'## custom',
|
||||
'',
|
||||
].join('\n'), '/p/docs/README.md')
|
||||
const surface = surfaceOf(mounted.container)
|
||||
const ids = [...surface.querySelectorAll('h2, h3')].map(heading => heading.id)
|
||||
// The host renders bare `h1..h6` (no ids) — every id below is the plugin's.
|
||||
expect(ids).toEqual(['hello-world', 'hello-world-1', '中文标题', 'custom', 'custom-1'])
|
||||
// The authored id is kept AND reserved: the later heading with the same
|
||||
// slug gets the suffix instead of stealing it.
|
||||
expect(surface.querySelector('h2#custom')?.textContent).toBe('Authored')
|
||||
mounted.unmount()
|
||||
})
|
||||
|
||||
it('collapses an explicit empty anchor without losing its id, and deep links still land', async () => {
|
||||
const mounted = mountEditor('intro <a id="hidden-anchor"></a> tail\n\n[jump](#hidden-anchor)\n', '/p/docs/README.md')
|
||||
const surface = surfaceOf(mounted.container)
|
||||
// The raw-HTML pass ran before the surface pass observed the tree.
|
||||
await flushMicrotasks()
|
||||
const hidden = surface.querySelector<HTMLAnchorElement>('a#hidden-anchor')
|
||||
expect(hidden?.hidden).toBe(true)
|
||||
// …and the id is still there, so `#hidden-anchor` keeps resolving: the jump
|
||||
// measures the nearest VISIBLE ancestor (a hidden box has no position).
|
||||
expect(hidden?.id).toBe('hidden-anchor')
|
||||
const scrollTop = watchScrollTop(surface)
|
||||
stubRectTop(surface, 0)
|
||||
stubRectTop(hidden!.parentElement!, 260)
|
||||
click(fileLink(surface, '#hidden-anchor')!)
|
||||
expect(scrollTop()).toBe(252)
|
||||
mounted.unmount()
|
||||
})
|
||||
|
||||
it('renders a claimed .md link as the host file link and opens the DOCUMENT-relative target', () => {
|
||||
const mounted = mountEditor('See [other](./other.md) and [abs](/p/docs/third.md).\n', '/p/docs/README.md')
|
||||
const surface = surfaceOf(mounted.container)
|
||||
const link = fileLink(surface, './other.md')
|
||||
expect(link).not.toBeNull()
|
||||
// The claim is the host's file link, not an anchor: nothing here navigates
|
||||
// the page away (the host renders a button).
|
||||
expect(link?.closest('a')).toBeNull()
|
||||
click(link!)
|
||||
// `/p/docs/other.md`, NOT `/p/other.md`: the base is the rendered document.
|
||||
expect(mounted.tabs().map(tab => tab.path)).toEqual(['/p/docs/other.md'])
|
||||
click(fileLink(surface, '/p/docs/third.md')!)
|
||||
expect(mounted.tabs().map(tab => tab.path)).toEqual(['/p/docs/other.md', '/p/docs/third.md'])
|
||||
mounted.unmount()
|
||||
})
|
||||
|
||||
it('keeps remote links as links and non-markdown local links as inert text', () => {
|
||||
const mounted = mountEditor([
|
||||
'[site](https://example.com/a.md)',
|
||||
'',
|
||||
'[notes](./notes.txt)',
|
||||
'',
|
||||
'[image](./pic.png)',
|
||||
'',
|
||||
'[dir](./docs)',
|
||||
'',
|
||||
].join('\n'), '/p/docs/README.md')
|
||||
const surface = surfaceOf(mounted.container)
|
||||
// http(s) keeps today's behavior verbatim: a real anchor to the destination.
|
||||
const external = surface.querySelector<HTMLAnchorElement>('a[href="https://example.com/a.md"]')
|
||||
expect(external).not.toBeNull()
|
||||
// Everything the plugin does not claim stays what it renders as today —
|
||||
// plain text — instead of a file-mention button that would do nothing.
|
||||
for (const label of ['notes', 'image', 'dir']) {
|
||||
expect(surface.textContent, label).toContain(label)
|
||||
}
|
||||
for (const destination of ['./notes.txt', './pic.png', './docs']) {
|
||||
expect(fileLink(surface, destination), destination).toBeNull()
|
||||
}
|
||||
// …and no link of the document produced a tab.
|
||||
click(surface)
|
||||
expect(mounted.tabs()).toEqual([])
|
||||
mounted.unmount()
|
||||
})
|
||||
|
||||
it('scopes the claim to the plugin surface: the same markdown elsewhere stays inert', () => {
|
||||
const bare = renderRoot(createElement(MarkdownText, {
|
||||
text: '[other](./other.md)\n',
|
||||
labels: { code: { copyLabel: 'c', copiedLabel: 'C' }, footnotes: '' },
|
||||
}))
|
||||
// No provider, no claim: the host renders the local destination as text
|
||||
// (this is exactly why the plugin has to wrap its own surfaces).
|
||||
expect(bare.container.querySelector('button')).toBeNull()
|
||||
expect(bare.container.querySelector('a')).toBeNull()
|
||||
expect(bare.container.textContent).toContain('other')
|
||||
bare.unmount()
|
||||
})
|
||||
|
||||
it('scrolls the preview container itself for a same-page fragment', () => {
|
||||
const mounted = mountEditor('[jump](#目标标题)\n\n## 目标标题\n', '/p/docs/README.md')
|
||||
const surface = surfaceOf(mounted.container)
|
||||
const heading = surface.querySelector<HTMLElement>('h2#目标标题')!
|
||||
const scrollTop = watchScrollTop(surface)
|
||||
stubRectTop(heading, 120)
|
||||
// The link is a host file link whose destination the delegate decodes back
|
||||
// into a same-document fragment.
|
||||
const link = fileLink(surface, '#目标标题')
|
||||
expect(link).not.toBeNull()
|
||||
click(link!)
|
||||
expect(scrollTop()).toBe(112) // 120 - the 8px padding
|
||||
// Never the window, never scrollIntoView (that would scroll every ancestor).
|
||||
expect(scrollTo).not.toHaveBeenCalled()
|
||||
expect(scrollIntoView).not.toHaveBeenCalled()
|
||||
// A same-page jump opens nothing.
|
||||
expect(mounted.tabs()).toEqual([])
|
||||
mounted.unmount()
|
||||
})
|
||||
|
||||
it('ignores a fragment the document does not carry', () => {
|
||||
const mounted = mountEditor('[jump](#missing)\n\n## Present\n', '/p/docs/README.md')
|
||||
const surface = surfaceOf(mounted.container)
|
||||
const scrollTop = watchScrollTop(surface)
|
||||
click(fileLink(surface, '#missing')!)
|
||||
expect(scrollTop()).toBe(0)
|
||||
expect(scrollTo).not.toHaveBeenCalled()
|
||||
expect(mounted.tabs()).toEqual([])
|
||||
mounted.unmount()
|
||||
})
|
||||
|
||||
it('opens a cross-file target and lands the parked fragment once that file renders', async () => {
|
||||
// The link's fragment cannot reach the host parser as authored — this is
|
||||
// the `%23` carrier, end to end: rewrite → host decode → delegate → park.
|
||||
const source = mountEditor('[jump](./other.md#目标标题)\n', '/p/docs/README.md')
|
||||
const link = fileLink(surfaceOf(source.container), './other.md#目标标题')
|
||||
expect(link).not.toBeNull()
|
||||
click(link!)
|
||||
expect(source.tabs().map(tab => tab.path)).toEqual(['/p/docs/other.md'])
|
||||
source.unmount()
|
||||
|
||||
// The target document renders in its own editor (same session, same path
|
||||
// spelling the open used) and takes the parked fragment.
|
||||
const target = mountEditor('## 目标标题\n', '/p/docs/other.md')
|
||||
const targetSurface = surfaceOf(target.container)
|
||||
const scrollTop = watchScrollTop(targetSurface)
|
||||
const heading = targetSurface.querySelector<HTMLElement>('h2#目标标题')!
|
||||
stubRectTop(heading, 200)
|
||||
await flushMicrotasks()
|
||||
expect(scrollTop()).toBe(192)
|
||||
expect(scrollTo).not.toHaveBeenCalled()
|
||||
expect(scrollIntoView).not.toHaveBeenCalled()
|
||||
target.unmount()
|
||||
|
||||
// Consumed: a later mount of the same document does not jump again.
|
||||
const again = mountEditor('## 目标标题\n', '/p/docs/other.md')
|
||||
const againSurface = surfaceOf(again.container)
|
||||
const againScrollTop = watchScrollTop(againSurface)
|
||||
stubRectTop(againSurface.querySelector<HTMLElement>('h2#目标标题')!, 200)
|
||||
await flushMicrotasks()
|
||||
expect(againScrollTop()).toBe(0)
|
||||
again.unmount()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the document pass', () => {
|
||||
it('measures a collapsed anchor through its nearest visible ancestor', () => {
|
||||
const root = document.createElement('div')
|
||||
root.innerHTML = '<p id="wrapper"><a id="empty"></a></p>'
|
||||
hideEmptyAnchors(root)
|
||||
const empty = root.querySelector<HTMLElement>('a#empty')!
|
||||
expect(empty.hidden).toBe(true)
|
||||
// A hidden element has no box of its own: the paragraph carries the
|
||||
// position, and that is what the jump must measure.
|
||||
stubRectTop(root, 0)
|
||||
stubRectTop(empty, 0)
|
||||
stubRectTop(root.querySelector<HTMLElement>('p#wrapper')!, 300)
|
||||
const scrollTop = watchScrollTop(root)
|
||||
expect(jumpToFragment(root, 'empty')).toBe(true)
|
||||
expect(scrollTop()).toBe(292)
|
||||
})
|
||||
|
||||
it('opens a collapsed details block a fragment lives in', () => {
|
||||
const root = document.createElement('div')
|
||||
root.innerHTML = '<details><summary>more</summary><h2 id="deep">Deep</h2></details>'
|
||||
stubRectTop(root, 0)
|
||||
expect(jumpToFragment(root, 'deep')).toBe(true)
|
||||
expect(root.querySelector('details')?.hasAttribute('open')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -119,6 +119,7 @@ describe('changes tab HTML render preview sandbox', () => {
|
||||
op: { callId: 'c1', kind: 'read' as const, path, time: 0, running: false, isError: false, read: '<content>1: <html><body>hi</body></html></content>' },
|
||||
},
|
||||
scope: { sessionId: 's1', cwd: '/p' },
|
||||
ctx: CTX,
|
||||
height: 300,
|
||||
onHeightCommit: () => {},
|
||||
onClose: () => {},
|
||||
|
||||
Reference in new issue
Block a user