mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(markdown): address inline image review feedback
Keep the leading slash when resolving relative paths against an absolute markdown file, retry an inline image when its source changes after a load failure, and render linked markdown images without a nested expand button.
This commit is contained in:
1 parent
458f26134b
commit
f488b8762d
7 files changed
+118
-22
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { render, screen, fireEvent, within } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { MessagePart } from './MessagePart'
|
||||
@@ -175,6 +175,22 @@ describe('MessagePart', () => {
|
||||
|
||||
expect(container.querySelector('img')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders a linked image without a nested expand button', () => {
|
||||
renderWithProviders(
|
||||
<MessagePart part={textPart('[](https://example.com)')} />,
|
||||
)
|
||||
|
||||
const link = screen.getByRole('link')
|
||||
expect(within(link).getByAltText('logo')).toHaveAttribute('src', 'https://example.com/a.png')
|
||||
expect(within(link).queryByRole('button')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders an expand button for an unlinked image', () => {
|
||||
renderWithProviders(<MessagePart part={textPart('')} />)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Expand image: logo' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('reasoning', () => {
|
||||
|
||||
@@ -22,4 +22,33 @@ describe('InlineImage', () => {
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('shot.png')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('retries a new source after an image failure', () => {
|
||||
const { rerender } = render(<InlineImage src="broken" alt="shot.png" />)
|
||||
|
||||
fireEvent.error(screen.getByAltText('shot.png'))
|
||||
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('shot.png')).toBeInTheDocument()
|
||||
|
||||
rerender(<InlineImage src="data:image/png;base64,aGVsbG8=" alt="shot.png" />)
|
||||
|
||||
expect(screen.getByAltText('shot.png')).toHaveAttribute('src', 'data:image/png;base64,aGVsbG8=')
|
||||
expect(screen.getByRole('button', { name: 'Expand image: shot.png' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders only the image without an expand button when not expandable', () => {
|
||||
render(<InlineImage src="data:image/png;base64,aGVsbG8=" alt="shot.png" expandable={false} />)
|
||||
|
||||
expect(screen.getByAltText('shot.png')).toHaveAttribute('src', 'data:image/png;base64,aGVsbG8=')
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('falls back to the alt text for a non-expandable image that fails to load', () => {
|
||||
render(<InlineImage src="broken" alt="shot.png" expandable={false} />)
|
||||
|
||||
fireEvent.error(screen.getByAltText('shot.png'))
|
||||
|
||||
expect(screen.getByText('shot.png')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -3,17 +3,46 @@ import { cn } from '@/lib/utils'
|
||||
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
|
||||
|
||||
/**
|
||||
* Renders an image as a bounded thumbnail button that opens a full-size preview dialog.
|
||||
* Falls back to a muted alt-text span (or nothing) when the image fails to load.
|
||||
* Renders an image as a bounded thumbnail that opens a full-size preview dialog when expandable.
|
||||
* Falls back to a muted alt-text span (or nothing) when the image fails to load, retrying when the source changes.
|
||||
*/
|
||||
export function InlineImage({ src, alt, className }: { src: string; alt?: string; className?: string }) {
|
||||
export function InlineImage({
|
||||
src,
|
||||
alt,
|
||||
className,
|
||||
expandable = true,
|
||||
}: {
|
||||
src: string
|
||||
alt?: string
|
||||
className?: string
|
||||
expandable?: boolean
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [failed, setFailed] = useState(false)
|
||||
const [failedSrc, setFailedSrc] = useState<string | null>(null)
|
||||
const failed = failedSrc === src
|
||||
|
||||
if (failed) {
|
||||
return alt ? <span className="text-xs text-muted-foreground">{alt}</span> : null
|
||||
}
|
||||
|
||||
const image = (
|
||||
<img
|
||||
src={src}
|
||||
alt={alt ?? ''}
|
||||
loading="lazy"
|
||||
onError={() => setFailedSrc(src)}
|
||||
className={cn(
|
||||
'max-w-full max-h-80 rounded-lg border border-border object-contain',
|
||||
expandable && 'cursor-zoom-in',
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!expandable) {
|
||||
return image
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
@@ -22,16 +51,7 @@ export function InlineImage({ src, alt, className }: { src: string; alt?: string
|
||||
onClick={() => setOpen(true)}
|
||||
className="inline-flex"
|
||||
>
|
||||
<img
|
||||
src={src}
|
||||
alt={alt ?? ''}
|
||||
loading="lazy"
|
||||
onError={() => setFailed(true)}
|
||||
className={cn(
|
||||
'max-w-full max-h-80 rounded-lg border border-border object-contain cursor-zoom-in',
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
{image}
|
||||
</button>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="w-auto max-w-none p-2">
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ComponentPropsWithoutRef } from 'react'
|
||||
import type { ExtraProps } from 'react-markdown'
|
||||
import { InlineImage } from '@/components/ui/inline-image'
|
||||
import { useIsInsideMarkdownLink } from '@/components/ui/markdown-link'
|
||||
import { getFileApiUrl } from '@/api/files'
|
||||
import { getLocalLinkPath } from '@/lib/markdownLinks'
|
||||
|
||||
@@ -14,6 +15,8 @@ type MarkdownImageProps = ComponentPropsWithoutRef<'img'> & ExtraProps & {
|
||||
* `data:image/*` URIs, is rendered unchanged.
|
||||
*/
|
||||
export function MarkdownImage({ src, alt, resolveLocalPath }: MarkdownImageProps) {
|
||||
const insideLink = useIsInsideMarkdownLink()
|
||||
|
||||
if (typeof src !== 'string' || src === '') {
|
||||
return null
|
||||
}
|
||||
@@ -30,5 +33,5 @@ export function MarkdownImage({ src, alt, resolveLocalPath }: MarkdownImageProps
|
||||
}
|
||||
}
|
||||
|
||||
return <InlineImage src={imageSrc} alt={alt} />
|
||||
return <InlineImage src={imageSrc} alt={alt} expandable={!insideLink} />
|
||||
}
|
||||
@@ -1,7 +1,15 @@
|
||||
import { createContext, useContext } from 'react'
|
||||
import type { ComponentPropsWithoutRef } from 'react'
|
||||
import type { ExtraProps } from 'react-markdown'
|
||||
import { getLocalLinkPath, isExternalLink } from '@/lib/markdownLinks'
|
||||
|
||||
const MarkdownLinkContext = createContext(false)
|
||||
|
||||
/** Returns whether the current subtree is rendered inside a markdown link. */
|
||||
export function useIsInsideMarkdownLink(): boolean {
|
||||
return useContext(MarkdownLinkContext)
|
||||
}
|
||||
|
||||
type MarkdownLinkProps = ComponentPropsWithoutRef<'a'> & ExtraProps & {
|
||||
onOpenLocalPath?: (linkPath: string) => void
|
||||
}
|
||||
@@ -13,6 +21,7 @@ type MarkdownLinkProps = ComponentPropsWithoutRef<'a'> & ExtraProps & {
|
||||
export function MarkdownLink({ href, children, onOpenLocalPath, ...rest }: MarkdownLinkProps) {
|
||||
delete (rest as Record<string, unknown>).node
|
||||
const localPath = onOpenLocalPath ? getLocalLinkPath(href) : null
|
||||
const wrappedChildren = <MarkdownLinkContext.Provider value={true}>{children}</MarkdownLinkContext.Provider>
|
||||
|
||||
if (localPath && onOpenLocalPath) {
|
||||
return (
|
||||
@@ -24,14 +33,14 @@ export function MarkdownLink({ href, children, onOpenLocalPath, ...rest }: Markd
|
||||
onOpenLocalPath(localPath)
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
{wrappedChildren}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
if (isExternalLink(href)) {
|
||||
return <a href={href} target="_blank" rel="noopener noreferrer" {...rest}>{children}</a>
|
||||
return <a href={href} target="_blank" rel="noopener noreferrer" {...rest}>{wrappedChildren}</a>
|
||||
}
|
||||
|
||||
return <a href={href} {...rest}>{children}</a>
|
||||
return <a href={href} {...rest}>{wrappedChildren}</a>
|
||||
}
|
||||
@@ -42,6 +42,18 @@ describe('resolvePathFromFile', () => {
|
||||
it('returns absolute paths unchanged', () => {
|
||||
expect(resolvePathFromFile(FROM, '/workspace/repos/app/report.html')).toBe('/workspace/repos/app/report.html')
|
||||
})
|
||||
|
||||
it('resolves relative links against an absolute base file keeping the leading slash', () => {
|
||||
expect(resolvePathFromFile('/workspace/docs/README.md', 'img.png')).toBe('/workspace/docs/img.png')
|
||||
expect(resolvePathFromFile('/workspace/docs/README.md', './img.png')).toBe('/workspace/docs/img.png')
|
||||
expect(resolvePathFromFile('/workspace/docs/README.md', 'sub/img.png')).toBe('/workspace/docs/sub/img.png')
|
||||
})
|
||||
|
||||
it('applies parent segments against an absolute base without climbing above root', () => {
|
||||
expect(resolvePathFromFile('/workspace/docs/README.md', '../img.png')).toBe('/workspace/img.png')
|
||||
expect(resolvePathFromFile('/a/index.md', '../../x.md')).toBe('/x.md')
|
||||
expect(resolvePathFromFile('/a/index.md', '..')).toBe('/')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getWorkspaceFilePath', () => {
|
||||
|
||||
@@ -19,24 +19,31 @@ export function getLocalLinkPath(href: string | undefined): string | 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.
|
||||
* Absolute link paths are returned unchanged for the files API to validate. Leading parent segments
|
||||
* are kept for relative bases, while an absolute base keeps its leading slash and never climbs above root.
|
||||
*/
|
||||
export function resolvePathFromFile(fromFilePath: string, linkPath: string): string | null {
|
||||
if (linkPath.startsWith('/')) {
|
||||
return linkPath
|
||||
}
|
||||
|
||||
const isAbsolute = fromFilePath.startsWith('/')
|
||||
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] !== '..') {
|
||||
if (segment !== '..') {
|
||||
segments.push(segment)
|
||||
} else if (segments.length === 0) {
|
||||
if (!isAbsolute) segments.push(segment)
|
||||
} else if (isAbsolute || segments[segments.length - 1] !== '..') {
|
||||
segments.pop()
|
||||
} else {
|
||||
segments.push(segment)
|
||||
}
|
||||
}
|
||||
|
||||
return segments.join('/') || null
|
||||
const resolved = segments.join('/')
|
||||
return isAbsolute ? `/${resolved}` : resolved || null
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user