mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
refactor(files): share markdown link handling across renderers
This commit is contained in:
1 parent
fd1e8d16ca
commit
3451a0e24d
9 files changed
+172
-112
No files matched your search
@@ -4,7 +4,8 @@ import remarkGfm from 'remark-gfm'
|
||||
import rehypeHighlight from 'rehype-highlight'
|
||||
import rehypeRaw from 'rehype-raw'
|
||||
import { markdownComponents } from './MarkdownComponents'
|
||||
import { resolveLinkedFilePath } from './resolve-link-path'
|
||||
import { MarkdownLink } from '@/components/ui/markdown-link'
|
||||
import { resolvePathFromFile } from '@/lib/markdownLinks'
|
||||
import type { Components } from 'react-markdown'
|
||||
|
||||
interface MarkdownRendererProps {
|
||||
@@ -15,8 +16,6 @@ interface MarkdownRendererProps {
|
||||
onOpenFile?: (path: string) => void
|
||||
}
|
||||
|
||||
const EXTERNAL_LINK = /^https?:\/\//i
|
||||
|
||||
interface TaskItem {
|
||||
lineIndex: number
|
||||
checked: boolean
|
||||
@@ -59,6 +58,14 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({ content, classN
|
||||
}
|
||||
}, [handleToggle, taskItems])
|
||||
|
||||
const handleOpenLocalPath = useMemo(() => {
|
||||
if (!filePath || !onOpenFile) return undefined
|
||||
return (linkPath: string) => {
|
||||
const resolvedPath = resolvePathFromFile(filePath, linkPath)
|
||||
if (resolvedPath) onOpenFile(resolvedPath)
|
||||
}
|
||||
}, [filePath, onOpenFile])
|
||||
|
||||
const components: Components = {
|
||||
...markdownComponents,
|
||||
input(props) {
|
||||
@@ -80,30 +87,7 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({ content, classN
|
||||
return <input type={type} checked={checked} disabled={disabled} {...rest} />
|
||||
},
|
||||
a(props) {
|
||||
const { href, children, ...rest } = props
|
||||
delete (rest as Record<string, unknown>).node
|
||||
|
||||
const linkedPath = href && filePath && onOpenFile ? resolveLinkedFilePath(filePath, href) : null
|
||||
if (linkedPath && onOpenFile) {
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
{...rest}
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
onOpenFile(linkedPath)
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
if (href && EXTERNAL_LINK.test(href)) {
|
||||
return <a href={href} target="_blank" rel="noopener noreferrer" {...rest}>{children}</a>
|
||||
}
|
||||
|
||||
return <a href={href} {...rest}>{children}</a>
|
||||
return <MarkdownLink {...props} onOpenLocalPath={handleOpenLocalPath} />
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { resolveLinkedFilePath } from './resolve-link-path'
|
||||
|
||||
const FROM = 'opencode-manager/ocm-link-test/index.md'
|
||||
|
||||
describe('resolveLinkedFilePath', () => {
|
||||
it('resolves sibling, dot-relative, nested, and parent links against the containing file', () => {
|
||||
expect(resolveLinkedFilePath(FROM, 'report.html')).toBe('opencode-manager/ocm-link-test/report.html')
|
||||
expect(resolveLinkedFilePath(FROM, './report.html')).toBe('opencode-manager/ocm-link-test/report.html')
|
||||
expect(resolveLinkedFilePath(FROM, 'sub/page.html')).toBe('opencode-manager/ocm-link-test/sub/page.html')
|
||||
expect(resolveLinkedFilePath(FROM, '../README.md')).toBe('opencode-manager/README.md')
|
||||
})
|
||||
|
||||
it('resolves folder links without the trailing slash', () => {
|
||||
expect(resolveLinkedFilePath(FROM, 'sub/')).toBe('opencode-manager/ocm-link-test/sub')
|
||||
expect(resolveLinkedFilePath(FROM, '..')).toBe('opencode-manager')
|
||||
})
|
||||
|
||||
it('keeps parent segments above the repos root for the files API to validate', () => {
|
||||
expect(resolveLinkedFilePath('opencode-manager/index.md', '../../notes.md')).toBe('../notes.md')
|
||||
expect(resolveLinkedFilePath('../.config/opencode/AGENTS.md', 'skills/x.md')).toBe('../.config/opencode/skills/x.md')
|
||||
})
|
||||
|
||||
it('returns absolute paths unchanged apart from query, fragment, and trailing slash', () => {
|
||||
expect(resolveLinkedFilePath(FROM, '/workspace/repos/app/report.html#top')).toBe('/workspace/repos/app/report.html')
|
||||
expect(resolveLinkedFilePath(FROM, '/workspace/repos/app/')).toBe('/workspace/repos/app')
|
||||
})
|
||||
|
||||
it('drops query and fragment and decodes encoded names', () => {
|
||||
expect(resolveLinkedFilePath(FROM, 'report.html#summary')).toBe('opencode-manager/ocm-link-test/report.html')
|
||||
expect(resolveLinkedFilePath(FROM, 'my%20report.html?x=1')).toBe('opencode-manager/ocm-link-test/my report.html')
|
||||
expect(resolveLinkedFilePath('repo/my docs/index.md', 'a.html')).toBe('repo/my docs/a.html')
|
||||
})
|
||||
|
||||
it('ignores anchors, protocol-relative URLs, and scheme links', () => {
|
||||
expect(resolveLinkedFilePath(FROM, '#section')).toBeNull()
|
||||
expect(resolveLinkedFilePath(FROM, '//example.com/a')).toBeNull()
|
||||
expect(resolveLinkedFilePath(FROM, 'https://example.com')).toBeNull()
|
||||
expect(resolveLinkedFilePath(FROM, 'mailto:a@b.c')).toBeNull()
|
||||
expect(resolveLinkedFilePath(FROM, '')).toBeNull()
|
||||
expect(resolveLinkedFilePath(FROM, '/')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for malformed percent-encoding', () => {
|
||||
expect(resolveLinkedFilePath(FROM, 'bad%zz.html')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,35 +0,0 @@
|
||||
const URL_SCHEME = /^[a-z][a-z\d+.-]*:/i
|
||||
|
||||
/**
|
||||
* Resolves a markdown link to the workspace path of the file or folder it points at.
|
||||
* Relative links resolve against the containing file; absolute paths are returned as-is for the files API to validate.
|
||||
* Returns null for anchors, protocol-relative URLs, and links with a URL scheme.
|
||||
*/
|
||||
export function resolveLinkedFilePath(fromFilePath: string, href: string): string | null {
|
||||
if (!href || href.startsWith('#') || href.startsWith('//') || URL_SCHEME.test(href)) {
|
||||
return null
|
||||
}
|
||||
|
||||
let linkPath: string
|
||||
try {
|
||||
linkPath = decodeURIComponent(href.split(/[?#]/)[0])
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
if (linkPath.startsWith('/')) {
|
||||
return linkPath.replace(/\/+$/, '') || null
|
||||
}
|
||||
|
||||
const segments = fromFilePath.split('/').filter(Boolean).slice(0, -1)
|
||||
for (const segment of linkPath.split('/')) {
|
||||
if (segment === '' || segment === '.') continue
|
||||
if (segment === '..' && segments.length > 0 && segments[segments.length - 1] !== '..') {
|
||||
segments.pop()
|
||||
} else {
|
||||
segments.push(segment)
|
||||
}
|
||||
}
|
||||
|
||||
return segments.join('/') || null
|
||||
}
|
||||
@@ -91,6 +91,23 @@ describe('MessagePart', () => {
|
||||
expect(screen.getByText('Hello, this is a text message')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens local markdown links in a text part through onFileClick and external links in a new tab', () => {
|
||||
const onFileClick = vi.fn()
|
||||
renderWithProviders(
|
||||
<MessagePart
|
||||
part={textPart('[recap](recaps/daily-overview.html)\n\n[site](https://example.com)')}
|
||||
onFileClick={onFileClick}
|
||||
/>,
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole('link', { name: 'recap' }))
|
||||
expect(onFileClick).toHaveBeenCalledWith('recaps/daily-overview.html')
|
||||
|
||||
const external = screen.getByRole('link', { name: 'site' })
|
||||
expect(external).toHaveAttribute('target', '_blank')
|
||||
expect(external).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
})
|
||||
|
||||
it('renders null for an empty text part', () => {
|
||||
const { container } = renderWithProviders(<MessagePart part={textPart(' ')} />)
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ export const MessagePart = memo(function MessagePart({ part, messageID, onFileCl
|
||||
|
||||
switch (part.type) {
|
||||
case 'text':
|
||||
return <TextPart text={part.text} />
|
||||
return <TextPart text={part.text} onFileClick={onFileClick} />
|
||||
case 'reasoning':
|
||||
if (simpleChatMode || !showReasoning) return null
|
||||
if (!part.text.trim()) return null
|
||||
|
||||
@@ -6,11 +6,13 @@ import rehypeRaw from 'rehype-raw'
|
||||
import mermaid from 'mermaid'
|
||||
import { Maximize2, X, AlertCircle } from 'lucide-react'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { MarkdownLink } from '@/components/ui/markdown-link'
|
||||
import { useTheme } from '@/hooks/useTheme'
|
||||
import 'highlight.js/styles/github-dark.css'
|
||||
|
||||
interface TextPartProps {
|
||||
text: string
|
||||
onFileClick?: (filePath: string) => void
|
||||
}
|
||||
|
||||
interface MermaidBlockProps {
|
||||
@@ -181,7 +183,7 @@ function isMermaidBlockComplete(text: string): boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
export function TextPart({ text }: TextPartProps) {
|
||||
export function TextPart({ text, onFileClick }: TextPartProps) {
|
||||
const mermaidComplete = React.useMemo(() => {
|
||||
return text ? isMermaidBlockComplete(text) : false
|
||||
}, [text])
|
||||
@@ -257,7 +259,10 @@ export function TextPart({ text }: TextPartProps) {
|
||||
<table>{children}</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
},
|
||||
a(props) {
|
||||
return <MarkdownLink {...props} onOpenLocalPath={onFileClick} />
|
||||
},
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { ComponentPropsWithoutRef } from 'react'
|
||||
import type { ExtraProps } from 'react-markdown'
|
||||
import { getLocalLinkPath, isExternalLink } from '@/lib/markdownLinks'
|
||||
|
||||
type MarkdownLinkProps = ComponentPropsWithoutRef<'a'> & ExtraProps & {
|
||||
onOpenLocalPath?: (linkPath: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a markdown link. Local file links call `onOpenLocalPath` instead of navigating the app,
|
||||
* and external http(s) links open in a new tab.
|
||||
*/
|
||||
export function MarkdownLink({ href, children, onOpenLocalPath, ...rest }: MarkdownLinkProps) {
|
||||
delete (rest as Record<string, unknown>).node
|
||||
const localPath = onOpenLocalPath ? getLocalLinkPath(href) : null
|
||||
|
||||
if (localPath && onOpenLocalPath) {
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
{...rest}
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
onOpenLocalPath(localPath)
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
if (isExternalLink(href)) {
|
||||
return <a href={href} target="_blank" rel="noopener noreferrer" {...rest}>{children}</a>
|
||||
}
|
||||
|
||||
return <a href={href} {...rest}>{children}</a>
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getLocalLinkPath, resolvePathFromFile, isExternalLink } from './markdownLinks'
|
||||
|
||||
const FROM = 'opencode-manager/ocm-link-test/index.md'
|
||||
|
||||
describe('getLocalLinkPath', () => {
|
||||
it('returns relative and absolute paths without query, fragment, or trailing slash', () => {
|
||||
expect(getLocalLinkPath('recaps/daily-overview-2026-09-29.html')).toBe('recaps/daily-overview-2026-09-29.html')
|
||||
expect(getLocalLinkPath('./report.html#top')).toBe('./report.html')
|
||||
expect(getLocalLinkPath('/workspace/repos/app/report.html?x=1')).toBe('/workspace/repos/app/report.html')
|
||||
expect(getLocalLinkPath('sub/')).toBe('sub')
|
||||
expect(getLocalLinkPath('/')).toBe('/')
|
||||
expect(getLocalLinkPath('my%20report.html')).toBe('my report.html')
|
||||
})
|
||||
|
||||
it('ignores anchors, protocol-relative URLs, scheme links, empty, and malformed encodings', () => {
|
||||
expect(getLocalLinkPath(undefined)).toBeNull()
|
||||
expect(getLocalLinkPath('')).toBeNull()
|
||||
expect(getLocalLinkPath('#section')).toBeNull()
|
||||
expect(getLocalLinkPath('//example.com/a')).toBeNull()
|
||||
expect(getLocalLinkPath('https://example.com')).toBeNull()
|
||||
expect(getLocalLinkPath('mailto:a@b.c')).toBeNull()
|
||||
expect(getLocalLinkPath('bad%zz.html')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolvePathFromFile', () => {
|
||||
it('resolves sibling, dot-relative, nested, parent, and folder links against the containing file', () => {
|
||||
expect(resolvePathFromFile(FROM, 'report.html')).toBe('opencode-manager/ocm-link-test/report.html')
|
||||
expect(resolvePathFromFile(FROM, './report.html')).toBe('opencode-manager/ocm-link-test/report.html')
|
||||
expect(resolvePathFromFile(FROM, 'sub/page.html')).toBe('opencode-manager/ocm-link-test/sub/page.html')
|
||||
expect(resolvePathFromFile(FROM, '../README.md')).toBe('opencode-manager/README.md')
|
||||
expect(resolvePathFromFile(FROM, '..')).toBe('opencode-manager')
|
||||
expect(resolvePathFromFile('repo/my docs/index.md', 'a.html')).toBe('repo/my docs/a.html')
|
||||
})
|
||||
|
||||
it('keeps parent segments above the repos root for the files API to validate', () => {
|
||||
expect(resolvePathFromFile('opencode-manager/index.md', '../../notes.md')).toBe('../notes.md')
|
||||
expect(resolvePathFromFile('../.config/opencode/AGENTS.md', 'skills/x.md')).toBe('../.config/opencode/skills/x.md')
|
||||
})
|
||||
|
||||
it('returns absolute paths unchanged', () => {
|
||||
expect(resolvePathFromFile(FROM, '/workspace/repos/app/report.html')).toBe('/workspace/repos/app/report.html')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isExternalLink', () => {
|
||||
it('detects http and https links only', () => {
|
||||
expect(isExternalLink('https://example.com')).toBe(true)
|
||||
expect(isExternalLink('http://example.com')).toBe(true)
|
||||
expect(isExternalLink('recaps/a.html')).toBe(false)
|
||||
expect(isExternalLink(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
const URL_SCHEME = /^[a-z][a-z\d+.-]*:/i
|
||||
|
||||
/**
|
||||
* Extracts the local file path a markdown link points at, decoded and without query or fragment.
|
||||
* Returns null for anchors, protocol-relative URLs, links with a URL scheme, and malformed encodings.
|
||||
*/
|
||||
export function getLocalLinkPath(href: string | undefined): string | null {
|
||||
if (!href || href.startsWith('#') || href.startsWith('//') || URL_SCHEME.test(href)) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const linkPath = decodeURIComponent(href.split(/[?#]/)[0]).replace(/(.)\/+$/, '$1')
|
||||
return linkPath || null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a local link path against the workspace path of the file that contains it.
|
||||
* Absolute paths are returned unchanged for the files API to validate; leading parent segments are kept.
|
||||
*/
|
||||
export function resolvePathFromFile(fromFilePath: string, linkPath: string): string | null {
|
||||
if (linkPath.startsWith('/')) {
|
||||
return linkPath
|
||||
}
|
||||
|
||||
const segments = fromFilePath.split('/').filter(Boolean).slice(0, -1)
|
||||
for (const segment of linkPath.split('/')) {
|
||||
if (segment === '' || segment === '.') continue
|
||||
if (segment === '..' && segments.length > 0 && segments[segments.length - 1] !== '..') {
|
||||
segments.pop()
|
||||
} else {
|
||||
segments.push(segment)
|
||||
}
|
||||
}
|
||||
|
||||
return segments.join('/') || null
|
||||
}
|
||||
|
||||
/** Returns whether a link targets an external http(s) page. */
|
||||
export function isExternalLink(href: string | undefined): boolean {
|
||||
return !!href && /^https?:\/\//i.test(href)
|
||||
}
|
||||
Reference in new issue
Block a user