mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-25 05:07:05 +00:00
feat(web): open Markdown images in fullscreen preview (#2395)
This commit is contained in:
@@ -95,6 +95,8 @@ Local images are read through the authenticated session file API. The referenced
|
||||
|
||||
Reachable HTTP(S) images load directly in the browser. The 10 MiB session-file limit applies to local images, not remote image URLs.
|
||||
|
||||
In Web/PWA, successfully loaded Markdown images can be clicked, tapped, or opened from the keyboard to launch the same zoomable fullscreen viewer used by `display_image`. Images keep their inline presentation and `no-referrer` behavior. Loading and failed-image fallbacks do not open a viewer.
|
||||
|
||||
#### Using display_image
|
||||
|
||||
Use the available HAPI `display_image` tool with an absolute filesystem path when:
|
||||
|
||||
@@ -2,16 +2,18 @@ import ReactDOM from 'react-dom/client'
|
||||
import type { ApiClient } from '../src/api/client'
|
||||
import { MarkdownRenderer } from '../src/components/MarkdownRenderer'
|
||||
import { HappyChatProvider, type HappyChatContextValue } from '../src/components/AssistantChat/context'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '../src/components/ui/dialog'
|
||||
import { I18nProvider } from '../src/lib/i18n-context'
|
||||
import '../src/index.css'
|
||||
|
||||
const SVG_CONTENT = '<svg xmlns="http://www.w3.org/2000/svg" width="480" height="160"><rect width="480" height="160" rx="20" fill="#0f766e"/><text x="24" y="92" fill="white" font-family="Arial" font-size="32">chat local image</text></svg>'
|
||||
const SVG_BASE64 = btoa(SVG_CONTENT)
|
||||
const REMOTE_IMAGE_URL = new URL('/favicon.ico', window.location.origin).href
|
||||
const CONTENT = `# Chat Markdown image fixture
|
||||
|
||||

|
||||
[](report.md)
|
||||
|
||||

|
||||

|
||||
|
||||
`
|
||||
|
||||
@@ -45,6 +47,21 @@ ReactDOM.createRoot(root).render(
|
||||
<I18nProvider>
|
||||
<HappyChatProvider value={chatValue}>
|
||||
<MarkdownRenderer content={CONTENT} />
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<button type="button" className="mt-6 rounded-md border border-white/20 px-3 py-2">
|
||||
Open tool detail
|
||||
</button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-h-56 overflow-auto" aria-describedby={undefined}>
|
||||
<DialogHeader className="text-left">
|
||||
<DialogTitle>Tool detail</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="max-h-24 overflow-auto">
|
||||
<MarkdownRenderer content="" />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</HappyChatProvider>
|
||||
</I18nProvider>
|
||||
)
|
||||
|
||||
@@ -1,16 +1,92 @@
|
||||
import { mkdir } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { expect, test } from '@playwright/test'
|
||||
|
||||
test('renders local chat Markdown images through the session API', async ({ page }) => {
|
||||
async function capture(page: import('@playwright/test').Page, fileName: string) {
|
||||
const directory = process.env.HAPI_SCREENSHOT_DIR
|
||||
if (!directory) return
|
||||
await mkdir(directory, { recursive: true })
|
||||
await page.screenshot({ path: join(directory, fileName), fullPage: true })
|
||||
}
|
||||
|
||||
test('renders and previews local and remote chat Markdown images', async ({ page }) => {
|
||||
await page.goto('/e2e-fixtures/chat-markdown-images.html')
|
||||
|
||||
const localImage = page.locator('img[alt="Local chart"]')
|
||||
await expect(localImage).toHaveCount(1)
|
||||
await expect(localImage).toHaveAttribute('src', /^data:image\/svg\+xml;base64,/)
|
||||
const localTrigger = page.getByRole('button', { name: /Local chart/i })
|
||||
await expect(localTrigger).toBeEnabled()
|
||||
await expect(localTrigger.locator('xpath=ancestor::a')).toHaveCount(0)
|
||||
await capture(page, 'markdown-image-inline.png')
|
||||
|
||||
await localTrigger.click()
|
||||
const localDialog = page.getByRole('dialog', { name: 'Local chart' })
|
||||
await expect(localDialog).toBeVisible()
|
||||
await expect(localDialog.getByRole('img', { name: 'Local chart' }))
|
||||
.toHaveAttribute('src', /^data:image\/svg\+xml;base64,/)
|
||||
await capture(page, 'markdown-image-fullscreen.png')
|
||||
await localDialog.getByTitle('Close', { exact: true }).click()
|
||||
await expect(localTrigger).toBeFocused()
|
||||
|
||||
const remoteImage = page.locator('img[alt="Remote chart"]')
|
||||
await expect(remoteImage).toHaveCount(1)
|
||||
await expect(remoteImage).toHaveAttribute('src', 'https://example.com/chart.png')
|
||||
await expect(remoteImage).toHaveAttribute('src', /\/favicon\.ico$/)
|
||||
await expect(remoteImage).toHaveAttribute('loading', 'lazy')
|
||||
await expect(remoteImage).toHaveAttribute('referrerpolicy', 'no-referrer')
|
||||
const remoteTrigger = page.getByRole('button', { name: /Remote chart/i })
|
||||
await expect(remoteTrigger).toBeEnabled()
|
||||
await remoteTrigger.click()
|
||||
await expect(page.getByRole('dialog', { name: 'Remote chart' })
|
||||
.getByRole('img', { name: 'Remote chart' }))
|
||||
.toHaveAttribute('referrerpolicy', 'no-referrer')
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(remoteTrigger).toBeFocused()
|
||||
|
||||
const blockedImage = page.locator('[data-hapi-markdown-image-fallback="true"][aria-label="Blocked chart"]')
|
||||
await expect(blockedImage).toHaveCount(1)
|
||||
await expect(page.getByRole('button', { name: /Blocked chart/i })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('portals Markdown image previews above tool detail dialogs', async ({ page }) => {
|
||||
await page.goto('/e2e-fixtures/chat-markdown-images.html')
|
||||
await page.getByRole('button', { name: 'Open tool detail' }).click()
|
||||
const toolDialog = page.getByRole('dialog', { name: 'Tool detail' })
|
||||
await expect(toolDialog).toBeVisible()
|
||||
|
||||
const trigger = toolDialog.getByRole('button', { name: /Dialog chart/i })
|
||||
await expect(trigger).toBeEnabled()
|
||||
await trigger.click()
|
||||
|
||||
const preview = page.getByRole('dialog', { name: 'Dialog chart' })
|
||||
await expect(preview).toBeVisible()
|
||||
await expect(preview.getByTitle('Close', { exact: true })).toBeFocused()
|
||||
const viewport = page.viewportSize()
|
||||
const box = await preview.boundingBox()
|
||||
expect(viewport).not.toBeNull()
|
||||
expect(box).not.toBeNull()
|
||||
expect(box!.x).toBeCloseTo(0, 0)
|
||||
expect(box!.y).toBeCloseTo(0, 0)
|
||||
expect(box!.width).toBeCloseTo(viewport!.width, 0)
|
||||
expect(box!.height).toBeCloseTo(viewport!.height, 0)
|
||||
|
||||
await preview.getByTitle('Zoom in', { exact: true }).click()
|
||||
await expect(preview).toBeVisible()
|
||||
await capture(page, 'markdown-image-tool-dialog.png')
|
||||
await preview.getByTitle('Close', { exact: true }).click()
|
||||
await expect(toolDialog).toBeVisible()
|
||||
await expect(trigger).toBeFocused()
|
||||
})
|
||||
|
||||
test.describe('mobile Markdown image previews', () => {
|
||||
test.use({ viewport: { width: 390, height: 844 }, hasTouch: true })
|
||||
|
||||
test('opens Markdown image previews from a mobile viewport', async ({ page }) => {
|
||||
await page.goto('/e2e-fixtures/chat-markdown-images.html')
|
||||
const trigger = page.getByRole('button', { name: /Local chart/i })
|
||||
await expect(trigger).toBeEnabled()
|
||||
await trigger.tap()
|
||||
await expect(page.getByRole('dialog', { name: 'Local chart' })).toBeVisible()
|
||||
await capture(page, 'markdown-image-fullscreen-mobile.png')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ComponentProps, ReactNode } from 'react'
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { I18nProvider } from '@/lib/i18n-context'
|
||||
|
||||
@@ -115,7 +115,8 @@ describe('AttachmentItem', () => {
|
||||
|
||||
const dialog = screen.getByRole('dialog', { name: 'zoom-me.png' })
|
||||
expect(dialog).toBeInTheDocument()
|
||||
expect(screen.getAllByRole('img', { name: 'zoom-me.png' })).toHaveLength(2)
|
||||
expect(within(dialog).getByRole('img', { name: 'zoom-me.png' })).toBeInTheDocument()
|
||||
expect(document.querySelectorAll('img[alt="zoom-me.png"]')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('keeps non-image attachments in the filename chip layout', () => {
|
||||
|
||||
@@ -95,7 +95,7 @@ describe('sortable composer image preview with the real attachment runtime', ()
|
||||
expect(screen.getByRole('dialog', { name: 'first.png' })).toBe(dialog)
|
||||
expect(within(dialog).getByTitle('Reset zoom')).toHaveTextContent('125%')
|
||||
const second = container.querySelector('[data-hapi-composer-attachment-id="second.txt"]')!
|
||||
await act(async () => fireEvent.click(within(second as HTMLElement).getByRole('button', { name: 'Remove attachment' })))
|
||||
await act(async () => fireEvent.click(within(second as HTMLElement).getByRole('button', { name: 'Remove attachment', hidden: true })))
|
||||
expect(screen.getByRole('dialog', { name: 'first.png' })).toBe(dialog)
|
||||
expect(within(dialog).getByTitle('Reset zoom')).toHaveTextContent('125%')
|
||||
expect(screen.queryByTestId('attachment-drag-handle')).not.toBeInTheDocument()
|
||||
@@ -118,10 +118,10 @@ describe('sortable composer image preview with the real attachment runtime', ()
|
||||
const { rerender, runtimeRef } = await setup()
|
||||
rerender(<Harness runtimeRef={runtimeRef} disabled />)
|
||||
expect(screen.getByRole('dialog', { name: 'first.png' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Reorder attachment first.png' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Reorder attachment first.png', hidden: true })).not.toBeInTheDocument()
|
||||
rerender(<Harness runtimeRef={runtimeRef} />)
|
||||
expect(screen.getByRole('dialog', { name: 'first.png' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Reorder attachment first.png' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Reorder attachment first.png', hidden: true })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('preserves the viewer across reordering and uses the latest keyboard callback', async () => {
|
||||
|
||||
@@ -12,6 +12,58 @@ function renderGallery() {
|
||||
}
|
||||
|
||||
describe('ImagePreview gallery navigation', () => {
|
||||
it('gates preview activation and forwards thumbnail loading behavior', () => {
|
||||
const onThumbnailLoad = vi.fn()
|
||||
const onThumbnailError = vi.fn()
|
||||
const { rerender } = render(
|
||||
<ImagePreview
|
||||
src="/gated.png"
|
||||
fileName="gated.png"
|
||||
label="Gated image"
|
||||
disabled
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer"
|
||||
thumbnailProps={{ title: 'Image source title' }}
|
||||
onThumbnailLoad={onThumbnailLoad}
|
||||
onThumbnailError={onThumbnailError}
|
||||
/>
|
||||
)
|
||||
|
||||
const disabledTrigger = screen.getByRole('button', { name: /gated image/i })
|
||||
expect(disabledTrigger).toBeDisabled()
|
||||
expect(disabledTrigger).toHaveAttribute('title', 'Loading image')
|
||||
fireEvent.click(disabledTrigger)
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
|
||||
const thumbnail = within(disabledTrigger).getByRole('img', { name: 'Gated image' })
|
||||
expect(thumbnail).toHaveAttribute('loading', 'lazy')
|
||||
expect(thumbnail).toHaveAttribute('referrerpolicy', 'no-referrer')
|
||||
expect(thumbnail).toHaveAttribute('title', 'Image source title')
|
||||
fireEvent.load(thumbnail)
|
||||
fireEvent.error(thumbnail)
|
||||
expect(onThumbnailLoad).toHaveBeenCalledTimes(1)
|
||||
expect(onThumbnailError).toHaveBeenCalledTimes(1)
|
||||
|
||||
rerender(
|
||||
<ImagePreview
|
||||
src="/gated.png"
|
||||
fileName="gated.png"
|
||||
label="Gated image"
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer"
|
||||
thumbnailProps={{ title: 'Image source title' }}
|
||||
onThumbnailLoad={onThumbnailLoad}
|
||||
onThumbnailError={onThumbnailError}
|
||||
/>
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /gated image/i }))
|
||||
const dialog = screen.getByRole('dialog', { name: 'Gated image' })
|
||||
expect(document.body.querySelector('[data-image-preview-viewer]')).toBe(dialog)
|
||||
expect(within(dialog).getByRole('img', { name: 'Gated image' }))
|
||||
.toHaveAttribute('referrerpolicy', 'no-referrer')
|
||||
})
|
||||
|
||||
it.each(['mouse', 'touch', 'pen'])('keeps %s preview gestures out of the surrounding attachment drag handler', (pointerType) => {
|
||||
const onAttachmentPointerDown = vi.fn()
|
||||
render(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState, type CSSProperties, type MouseEvent, type PointerEvent, type ReactNode, type SyntheticEvent, type WheelEvent } from 'react'
|
||||
import { useCallback, useEffect, useRef, useState, type ComponentPropsWithoutRef, type CSSProperties, type MouseEvent, type PointerEvent, type ReactNode, type SyntheticEvent, type WheelEvent } from 'react'
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog'
|
||||
import { useRouter } from '@tanstack/react-router'
|
||||
import { ArrowLeftIcon, ArrowRightIcon, CloseIcon, MinusIcon, PlusIcon } from '@/components/icons'
|
||||
import { formatFileSize } from '@/lib/file-metadata'
|
||||
@@ -27,6 +28,11 @@ type ImageDimensions = {
|
||||
height: number
|
||||
}
|
||||
|
||||
type ImagePreviewThumbnailProps = Omit<
|
||||
ComponentPropsWithoutRef<'img'>,
|
||||
'src' | 'alt' | 'className' | 'style' | 'draggable' | 'loading' | 'referrerPolicy' | 'onLoad' | 'onError'
|
||||
>
|
||||
|
||||
function getPointDistance(a: ImagePoint, b: ImagePoint): number {
|
||||
return Math.hypot(a.x - b.x, a.y - b.y)
|
||||
}
|
||||
@@ -54,6 +60,12 @@ export function ImagePreview(props: {
|
||||
caption?: ReactNode
|
||||
galleryId?: string
|
||||
fileSize?: number
|
||||
disabled?: boolean
|
||||
loading?: ComponentPropsWithoutRef<'img'>['loading']
|
||||
referrerPolicy?: ComponentPropsWithoutRef<'img'>['referrerPolicy']
|
||||
thumbnailProps?: ImagePreviewThumbnailProps
|
||||
onThumbnailLoad?: (event: SyntheticEvent<HTMLImageElement>) => void
|
||||
onThumbnailError?: (event: SyntheticEvent<HTMLImageElement>) => void
|
||||
onTriggerPointerDown?: (event: PointerEvent<HTMLButtonElement>) => void
|
||||
onTriggerContextMenu?: (event: MouseEvent<HTMLButtonElement>) => void
|
||||
onTriggerClick?: (event: MouseEvent<HTMLButtonElement>) => void
|
||||
@@ -65,6 +77,7 @@ export function ImagePreview(props: {
|
||||
const [imageDimensions, setImageDimensions] = useState<ImageDimensions | null>(null)
|
||||
const [scale, setScale] = useState(1)
|
||||
const [offset, setOffset] = useState({ x: 0, y: 0 })
|
||||
const triggerRef = useRef<HTMLButtonElement | null>(null)
|
||||
const scaleRef = useRef(scale)
|
||||
const offsetRef = useRef(offset)
|
||||
const activePointersRef = useRef(new Map<number, ImagePoint>())
|
||||
@@ -81,7 +94,7 @@ export function ImagePreview(props: {
|
||||
event.stopPropagation()
|
||||
const galleryId = props.galleryId ?? ''
|
||||
const triggers = Array.from(document.querySelectorAll<HTMLButtonElement>('[data-image-preview-trigger]'))
|
||||
.filter((trigger) => (trigger.dataset.imagePreviewGallery ?? '') === galleryId)
|
||||
.filter((trigger) => !trigger.disabled && (trigger.dataset.imagePreviewGallery ?? '') === galleryId)
|
||||
const images = triggers.flatMap((trigger): PreviewImage[] => {
|
||||
const image = trigger.querySelector('img')
|
||||
if (!image) return []
|
||||
@@ -104,10 +117,11 @@ export function ImagePreview(props: {
|
||||
}, [props.onTriggerPointerDown, stopEvent])
|
||||
|
||||
const handleTriggerClick = useCallback((event: MouseEvent<HTMLButtonElement>) => {
|
||||
if (props.disabled) return
|
||||
props.onTriggerClick?.(event)
|
||||
if (event.defaultPrevented) return
|
||||
openViewer(event)
|
||||
}, [openViewer, props.onTriggerClick])
|
||||
}, [openViewer, props.disabled, props.onTriggerClick])
|
||||
|
||||
const updateScale = useCallback((next: number | ((current: number) => number)) => {
|
||||
setScale((current) => {
|
||||
@@ -315,12 +329,14 @@ export function ImagePreview(props: {
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
onPointerDown={handleTriggerPointerDown}
|
||||
onMouseDown={stopEvent}
|
||||
onTouchStart={stopEvent}
|
||||
onContextMenu={props.onTriggerContextMenu}
|
||||
onClick={handleTriggerClick}
|
||||
disabled={props.disabled}
|
||||
data-image-preview-trigger=""
|
||||
data-image-preview-file-name={props.fileName}
|
||||
data-image-preview-label={props.label}
|
||||
@@ -330,28 +346,47 @@ export function ImagePreview(props: {
|
||||
// Otherwise it can escape the chat viewport and make the app
|
||||
// root scroll when history navigation calls scrollIntoView.
|
||||
className={`relative ${props.buttonClassName ?? 'group flex min-h-[18rem] w-full items-center justify-center overflow-auto rounded-md border border-[var(--app-border)] bg-[var(--app-code-bg)] p-3 text-left'}`}
|
||||
title="Click to zoom"
|
||||
title={props.disabled ? 'Loading image' : 'Click to zoom'}
|
||||
>
|
||||
<img
|
||||
{...props.thumbnailProps}
|
||||
src={props.src}
|
||||
alt={props.label}
|
||||
loading={props.loading}
|
||||
referrerPolicy={props.referrerPolicy}
|
||||
className={props.imageClassName ?? 'max-h-[calc(100vh-14rem)] max-w-full object-contain transition-transform group-hover:scale-[1.01]'}
|
||||
style={props.imageStyle}
|
||||
draggable={false}
|
||||
onLoad={props.onThumbnailLoad}
|
||||
onError={props.onThumbnailError}
|
||||
/>
|
||||
{props.caption}
|
||||
<span className="sr-only">{props.fileName}</span>
|
||||
</button>
|
||||
|
||||
{viewerOpen ? (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex flex-col bg-black/90 text-white"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
<DialogPrimitive.Root
|
||||
open={viewerOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) closeViewer()
|
||||
}}
|
||||
>
|
||||
<DialogPrimitive.Portal>
|
||||
<DialogPrimitive.Content
|
||||
className="pointer-events-auto fixed inset-0 z-[60] flex flex-col bg-black/90 text-white"
|
||||
aria-label={activePreview.label}
|
||||
aria-describedby={undefined}
|
||||
data-image-preview-viewer=""
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault()
|
||||
triggerRef.current?.focus()
|
||||
}}
|
||||
// Keep preview gestures from starting an ancestor's attachment drag.
|
||||
onPointerDown={stopEvent}
|
||||
// Portaled DOM events still follow React's logical tree. Stop
|
||||
// clicks so viewer controls cannot activate an enclosing link.
|
||||
onClick={stopEvent}
|
||||
>
|
||||
<DialogPrimitive.Title className="sr-only">{activePreview.label}</DialogPrimitive.Title>
|
||||
<div className="flex shrink-0 items-center gap-2 border-b border-white/10 bg-black/50 px-3 pb-2 pt-[calc(env(safe-area-inset-top)+0.5rem)] max-sm:gap-1">
|
||||
<button
|
||||
type="button"
|
||||
@@ -444,6 +479,7 @@ export function ImagePreview(props: {
|
||||
src={activePreview.src}
|
||||
alt={activePreview.label}
|
||||
draggable={false}
|
||||
referrerPolicy={props.referrerPolicy}
|
||||
onLoad={(event) => {
|
||||
const { naturalWidth, naturalHeight } = event.currentTarget
|
||||
if (naturalWidth > 0 && naturalHeight > 0) {
|
||||
@@ -472,8 +508,9 @@ export function ImagePreview(props: {
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPrimitive.Portal>
|
||||
</DialogPrimitive.Root>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ const listSessionDirectory = vi.hoisted(() => vi.fn(async () => ({
|
||||
|
||||
vi.mock('@tanstack/react-router', () => ({
|
||||
useNavigate: () => vi.fn(),
|
||||
useRouter: () => undefined,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/app-context', () => ({
|
||||
@@ -31,12 +32,12 @@ const markdown = [
|
||||
'',
|
||||
].join('\n\n')
|
||||
|
||||
function renderPreview(filePath: string, workspacePath: string | null = null, fileSearch = {}) {
|
||||
function renderPreview(filePath: string, workspacePath: string | null = null, fileSearch = {}, content = markdown) {
|
||||
return render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<I18nProvider>
|
||||
<MarkdownRenderer
|
||||
content={markdown}
|
||||
content={content}
|
||||
standalone
|
||||
sessionId="session-1"
|
||||
filePath={filePath}
|
||||
@@ -49,6 +50,20 @@ function renderPreview(filePath: string, workspacePath: string | null = null, fi
|
||||
}
|
||||
|
||||
describe('MarkdownRenderer standalone file base', () => {
|
||||
it('keeps anchors around standalone local file-preview images', async () => {
|
||||
renderPreview(
|
||||
'docs/notes-01.md',
|
||||
null,
|
||||
{},
|
||||
'[](error-notes.md)',
|
||||
)
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('img', { name: 'Linked local' })).toBeInTheDocument())
|
||||
const link = screen.getByRole('img', { name: 'Linked local' }).closest('a')
|
||||
expect(link).not.toBeNull()
|
||||
expect(link?.getAttribute('href')).toMatch(/\/sessions\/session-1\/file\?/)
|
||||
})
|
||||
|
||||
it('resolves relative links and images against the Markdown file directory', async () => {
|
||||
renderPreview('docs/notes-01.md', null, { tab: 'directories' })
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import type { ApiClient } from '@/api/client'
|
||||
import { MarkdownRenderer } from '@/components/MarkdownRenderer'
|
||||
import { HappyChatProvider, type HappyChatContextValue } from '@/components/AssistantChat/context'
|
||||
@@ -24,12 +24,19 @@ function chatValue(api: ApiClient, metadataPath: string | null = '/home/ada/codi
|
||||
}
|
||||
}
|
||||
|
||||
function renderImage(props: { src: string; alt: string; api?: ApiClient; metadataPath?: string | null }) {
|
||||
function renderImage(props: {
|
||||
src: string
|
||||
alt: string
|
||||
api?: ApiClient
|
||||
metadataPath?: string | null
|
||||
onLoad?: React.ReactEventHandler<HTMLImageElement>
|
||||
onError?: React.ReactEventHandler<HTMLImageElement>
|
||||
}) {
|
||||
const api = props.api ?? ({ readSessionFile: vi.fn() } as unknown as ApiClient)
|
||||
return render(
|
||||
<I18nProvider>
|
||||
<HappyChatProvider value={chatValue(api, props.metadataPath)}>
|
||||
<ChatMarkdownImage src={props.src} alt={props.alt} />
|
||||
<ChatMarkdownImage src={props.src} alt={props.alt} onLoad={props.onLoad} onError={props.onError} />
|
||||
</HappyChatProvider>
|
||||
</I18nProvider>
|
||||
)
|
||||
@@ -51,6 +58,27 @@ describe('ChatMarkdownImage', () => {
|
||||
expect(readSessionFile).toHaveBeenCalledWith('session-1', 'images/chart.png', MAX_MARKDOWN_IMAGE_BYTES)
|
||||
})
|
||||
|
||||
it('wraps a local image in the shared preview trigger while it loads', async () => {
|
||||
const readSessionFile = vi.fn(async () => ({
|
||||
success: true,
|
||||
content: encodeBase64('png-bytes'),
|
||||
size: 9,
|
||||
}))
|
||||
const api = { readSessionFile } as unknown as ApiClient
|
||||
|
||||
renderImage({ src: 'images/chart.png', alt: 'Chart', api })
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('img', { name: 'Chart' }).tagName).toBe('IMG'))
|
||||
const image = screen.getByRole('img', { name: 'Chart' })
|
||||
const trigger = screen.getByRole('button', { name: /chart/i })
|
||||
expect(trigger).toBeDisabled()
|
||||
expect(trigger).toHaveAttribute('title', 'Loading image')
|
||||
expect(trigger).toHaveAttribute('data-image-preview-file-name', 'chart.png')
|
||||
expect(trigger).toHaveAttribute('data-image-preview-file-size', '9')
|
||||
expect(image).toHaveAttribute('src', 'data:image/png;base64,cG5nLWJ5dGVz')
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders a relative workspace image through the conversation Markdown renderer', async () => {
|
||||
const readSessionFile = vi.fn(async () => ({
|
||||
success: true,
|
||||
@@ -71,6 +99,87 @@ describe('ChatMarkdownImage', () => {
|
||||
expect(readSessionFile).toHaveBeenCalledWith('session-1', 'images/chart.png', MAX_MARKDOWN_IMAGE_BYTES)
|
||||
})
|
||||
|
||||
it('does not nest the image preview trigger inside a Markdown link', async () => {
|
||||
const readSessionFile = vi.fn(async () => ({
|
||||
success: true,
|
||||
content: encodeBase64('png-bytes'),
|
||||
size: 9,
|
||||
}))
|
||||
const api = { readSessionFile } as unknown as ApiClient
|
||||
|
||||
render(
|
||||
<I18nProvider>
|
||||
<HappyChatProvider value={chatValue(api)}>
|
||||
<MarkdownRenderer content={'[](report.md)'} />
|
||||
</HappyChatProvider>
|
||||
</I18nProvider>
|
||||
)
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('img', { name: 'Linked chart' }).tagName).toBe('IMG'))
|
||||
const trigger = screen.getByRole('button', { name: /linked chart/i })
|
||||
expect(trigger.closest('a')).toBeNull()
|
||||
|
||||
fireEvent.load(screen.getByRole('img', { name: 'Linked chart' }))
|
||||
fireEvent.click(trigger)
|
||||
const dialog = screen.getByRole('dialog', { name: 'Linked chart' })
|
||||
fireEvent.click(within(dialog).getByTitle('Zoom in', { exact: true }))
|
||||
expect(screen.getByRole('dialog', { name: 'Linked chart' })).toBeInTheDocument()
|
||||
fireEvent.click(within(dialog).getByTitle('Close', { exact: true }))
|
||||
expect(screen.queryByRole('dialog', { name: 'Linked chart' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('preserves text navigation in mixed image and text links', async () => {
|
||||
const readSessionFile = vi.fn(async () => ({
|
||||
success: true,
|
||||
content: encodeBase64('png-bytes'),
|
||||
size: 9,
|
||||
}))
|
||||
const api = { readSessionFile } as unknown as ApiClient
|
||||
|
||||
render(
|
||||
<I18nProvider>
|
||||
<HappyChatProvider value={chatValue(api)}>
|
||||
<MarkdownRenderer content={'[ Open report](report.md)'} />
|
||||
</HappyChatProvider>
|
||||
</I18nProvider>
|
||||
)
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('img', { name: 'Linked chart' }).tagName).toBe('IMG'))
|
||||
const trigger = screen.getByRole('button', { name: /linked chart/i })
|
||||
const reportLink = screen.getByText('Open report').closest('a')
|
||||
expect(trigger.closest('a')).toBeNull()
|
||||
expect(reportLink).not.toBeNull()
|
||||
expect(reportLink).toHaveAttribute('href', '/sessions/session-1/file?path=cmVwb3J0Lm1k&origin=chat')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['strong', '[** Open report**](report.md)', 'STRONG'],
|
||||
['emphasis', '[* Open report*](report.md)', 'EM'],
|
||||
])('preserves text navigation inside %s wrappers', async (_name, content, wrapperTag) => {
|
||||
const readSessionFile = vi.fn(async () => ({
|
||||
success: true,
|
||||
content: encodeBase64('png-bytes'),
|
||||
size: 9,
|
||||
}))
|
||||
const api = { readSessionFile } as unknown as ApiClient
|
||||
|
||||
render(
|
||||
<I18nProvider>
|
||||
<HappyChatProvider value={chatValue(api)}>
|
||||
<MarkdownRenderer content={content} />
|
||||
</HappyChatProvider>
|
||||
</I18nProvider>
|
||||
)
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('img', { name: 'Nested chart' }).tagName).toBe('IMG'))
|
||||
const trigger = screen.getByRole('button', { name: /nested chart/i })
|
||||
const reportText = screen.getByText('Open report')
|
||||
const reportLink = reportText.closest('a')
|
||||
expect(trigger.closest('a')).toBeNull()
|
||||
expect(reportLink).not.toBeNull()
|
||||
expect(reportLink?.querySelector(wrapperTag)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('loads reachable HTTPS images directly without reading a session file', () => {
|
||||
const readSessionFile = vi.fn()
|
||||
const api = { readSessionFile } as unknown as ApiClient
|
||||
@@ -81,13 +190,38 @@ describe('ChatMarkdownImage', () => {
|
||||
expect(readSessionFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens a successfully loaded remote image in the shared fullscreen preview', async () => {
|
||||
const readSessionFile = vi.fn()
|
||||
const api = { readSessionFile } as unknown as ApiClient
|
||||
|
||||
renderImage({ src: 'https://example.com/chart.png', alt: 'Remote chart', api })
|
||||
|
||||
const image = screen.getByRole('img', { name: 'Remote chart' })
|
||||
const trigger = screen.getByRole('button', { name: /remote chart/i })
|
||||
expect(trigger).toBeDisabled()
|
||||
expect(image).toHaveAttribute('referrerpolicy', 'no-referrer')
|
||||
|
||||
fireEvent.load(image)
|
||||
expect(trigger).toBeEnabled()
|
||||
fireEvent.click(trigger)
|
||||
|
||||
const dialog = screen.getByRole('dialog', { name: 'Remote chart' })
|
||||
expect(within(dialog).getByRole('img', { name: 'Remote chart' }))
|
||||
.toHaveAttribute('referrerpolicy', 'no-referrer')
|
||||
expect(dialog).toHaveTextContent('chart.png')
|
||||
expect(readSessionFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows a fallback when a remote image fails to load', async () => {
|
||||
renderImage({ src: 'https://example.com/missing.png', alt: 'Missing remote' })
|
||||
const onError = vi.fn()
|
||||
renderImage({ src: 'https://example.com/missing.png', alt: 'Missing remote', onError })
|
||||
|
||||
const image = screen.getByRole('img', { name: 'Missing remote' })
|
||||
fireEvent.error(image)
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('img', { name: 'Missing remote' })).toHaveAttribute('data-hapi-markdown-image-fallback', 'true'))
|
||||
expect(onError).toHaveBeenCalledTimes(1)
|
||||
expect(screen.queryByRole('button', { name: /missing remote/i })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState, type ComponentPropsWithoutRef } from 'react'
|
||||
import { useOptionalHappyChatContext } from '@/components/AssistantChat/context'
|
||||
import { ImagePreview } from '@/components/ImagePreview'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
getMarkdownImageMimeType,
|
||||
@@ -10,6 +11,14 @@ import {
|
||||
|
||||
type ChatMarkdownImageTarget = Extract<MarkdownAssetTarget, { kind: 'local' | 'remote' | 'inert' }>
|
||||
|
||||
type MarkdownImageState = {
|
||||
key: string
|
||||
dataUrl: string | null
|
||||
fileSize?: number
|
||||
failed: boolean
|
||||
loaded: boolean
|
||||
}
|
||||
|
||||
function resolveChatMarkdownImage(src: string, workspacePath: string | null | undefined): ChatMarkdownImageTarget {
|
||||
const target = resolveMarkdownFileImage('.hapi-chat-message.md', src, { workspacePath })
|
||||
if (target.kind === 'local' || target.kind === 'remote') return target
|
||||
@@ -43,8 +52,24 @@ function markdownImageLoading(props: { label?: string; className?: string }) {
|
||||
)
|
||||
}
|
||||
|
||||
function markdownImageFileName(source: ChatMarkdownImageTarget, src: string, alt?: string): string {
|
||||
const candidate = source.kind === 'local'
|
||||
? source.path
|
||||
: source.kind === 'remote'
|
||||
? source.href
|
||||
: src
|
||||
const withoutMeta = candidate.split(/[?#]/, 1)[0] ?? candidate
|
||||
const normalized = withoutMeta.replaceAll('\\', '/')
|
||||
const basename = normalized.slice(normalized.lastIndexOf('/') + 1)
|
||||
try {
|
||||
return decodeURIComponent(basename) || alt?.trim() || 'Image'
|
||||
} catch {
|
||||
return basename || alt?.trim() || 'Image'
|
||||
}
|
||||
}
|
||||
|
||||
export function ChatMarkdownImage(props: ComponentPropsWithoutRef<'img'>) {
|
||||
const { src, alt, onError, className, ...imageProps } = props
|
||||
const { src, alt, onLoad, onError, className, ...imageProps } = props
|
||||
const chat = useOptionalHappyChatContext()
|
||||
const workspacePath = chat?.metadata?.path ?? null
|
||||
const source = typeof src === 'string'
|
||||
@@ -54,37 +79,40 @@ export function ChatMarkdownImage(props: ComponentPropsWithoutRef<'img'>) {
|
||||
const sourceKey = source.kind === 'local' ? source.path : source.href
|
||||
const api = chat?.api
|
||||
const sessionId = chat?.sessionId
|
||||
const [state, setState] = useState<{ key: string; dataUrl: string | null; failed: boolean }>(() => ({
|
||||
const [state, setState] = useState<MarkdownImageState>(() => ({
|
||||
key: sourceKey,
|
||||
dataUrl: null,
|
||||
failed: source.kind === 'inert' || (source.kind === 'local' && (!api || !sessionId)),
|
||||
loaded: false,
|
||||
}))
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
if (!localPath || !api || !sessionId) {
|
||||
setState({ key: sourceKey, dataUrl: null, failed: source.kind !== 'remote' })
|
||||
setState({ key: sourceKey, dataUrl: null, failed: source.kind !== 'remote', loaded: false })
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}
|
||||
|
||||
setState({ key: sourceKey, dataUrl: null, failed: false })
|
||||
setState({ key: sourceKey, dataUrl: null, failed: false, loaded: false })
|
||||
void api.readSessionFile(sessionId, localPath, MAX_MARKDOWN_IMAGE_BYTES).then((result) => {
|
||||
if (!active) return
|
||||
const mimeType = getMarkdownImageMimeType(localPath)
|
||||
const tooLarge = result.size !== undefined && result.size > MAX_MARKDOWN_IMAGE_BYTES
|
||||
if (!result.success || !result.content || !mimeType || tooLarge) {
|
||||
setState({ key: sourceKey, dataUrl: null, failed: true })
|
||||
setState({ key: sourceKey, dataUrl: null, failed: true, loaded: false })
|
||||
return
|
||||
}
|
||||
setState({
|
||||
key: sourceKey,
|
||||
dataUrl: `data:${mimeType};base64,${result.content}`,
|
||||
fileSize: result.size,
|
||||
failed: false,
|
||||
loaded: false,
|
||||
})
|
||||
}).catch(() => {
|
||||
if (active) setState({ key: sourceKey, dataUrl: null, failed: true })
|
||||
if (active) setState({ key: sourceKey, dataUrl: null, failed: true, loaded: false })
|
||||
})
|
||||
|
||||
return () => {
|
||||
@@ -105,17 +133,32 @@ export function ChatMarkdownImage(props: ComponentPropsWithoutRef<'img'>) {
|
||||
return markdownImageFallback({ label: alt, source: typeof src === 'string' ? src : '', className })
|
||||
}
|
||||
|
||||
const fileName = markdownImageFileName(source, typeof src === 'string' ? src : '', alt)
|
||||
const label = alt?.trim() || fileName
|
||||
|
||||
return (
|
||||
<img
|
||||
{...imageProps}
|
||||
<ImagePreview
|
||||
src={resolvedSrc}
|
||||
alt={alt}
|
||||
fileName={fileName}
|
||||
label={label}
|
||||
fileSize={state.fileSize}
|
||||
galleryId="chat-markdown-images"
|
||||
disabled={!state.loaded}
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer"
|
||||
className={cn('aui-md-img my-3 max-w-full rounded-xl', className)}
|
||||
onError={(event) => {
|
||||
thumbnailProps={imageProps}
|
||||
imageStyle={imageProps.style}
|
||||
buttonClassName="my-3 inline-block max-w-full cursor-zoom-in rounded-xl text-left disabled:cursor-default"
|
||||
imageClassName={cn('aui-md-img block max-w-full rounded-xl', className)}
|
||||
onThumbnailLoad={(event) => {
|
||||
onLoad?.(event)
|
||||
setState((current) => current.key === sourceKey
|
||||
? { ...current, loaded: true }
|
||||
: current)
|
||||
}}
|
||||
onThumbnailError={(event) => {
|
||||
onError?.(event)
|
||||
setState({ key: sourceKey, dataUrl: null, failed: true })
|
||||
setState({ key: sourceKey, dataUrl: null, failed: true, loaded: false })
|
||||
}}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import '@assistant-ui/react-markdown/styles/dot.css'
|
||||
|
||||
import type { ComponentPropsWithoutRef, ComponentType, MouseEvent, ReactNode } from 'react'
|
||||
import { useState, useCallback, useEffect, useMemo, createContext, useContext } from 'react'
|
||||
import { Children, Fragment, cloneElement, isValidElement, useState, useCallback, useEffect, useMemo, createContext, useContext } from 'react'
|
||||
import {
|
||||
MarkdownTextPrimitive,
|
||||
unstable_memoizeMarkdownComponents as memoizeMarkdownComponents,
|
||||
@@ -56,12 +56,13 @@ import type { MarkdownTextPrimitiveProps } from '@assistant-ui/react-markdown'
|
||||
// Session file being previewed; relative links/images resolve against its directory.
|
||||
// fileSearch carries the preview's browsing context (origin/tab/query) so Back still returns to it.
|
||||
export type MarkdownFileSearch = { origin?: 'chat'; tab?: 'changes' | 'directories'; query?: string }
|
||||
export const MarkdownFileBaseContext = createContext<{
|
||||
export type MarkdownFileBaseValue = {
|
||||
sessionId: string
|
||||
filePath: string
|
||||
workspacePath: string | null
|
||||
fileSearch: MarkdownFileSearch
|
||||
} | null>(null)
|
||||
}
|
||||
export const MarkdownFileBaseContext = createContext<MarkdownFileBaseValue | null>(null)
|
||||
|
||||
// ── Plugin array ────────────────────────────────────────────────────────────
|
||||
// Order: remarkGfm → remarkRepairTables → remarkCjkFriendly → remarkLatexBracketMath → remarkNonHttpsAutolink → remarkStripCjkAutolink → remarkMath → remarkDisableIndentedCode → remarkSessionPathLinks → remarkFilePathLinks
|
||||
@@ -598,6 +599,76 @@ function InertMarkdownHref(props: { href: string; children?: ReactNode; classNam
|
||||
)
|
||||
}
|
||||
|
||||
type LinkChildSegment = {
|
||||
interactiveImage: boolean
|
||||
children: ReactNode[]
|
||||
}
|
||||
|
||||
type SplitLinkNode = {
|
||||
interactiveImage: boolean
|
||||
node: ReactNode
|
||||
}
|
||||
|
||||
function splitInteractiveImageNodes(child: ReactNode, fileBase: MarkdownFileBaseValue | null): SplitLinkNode[] {
|
||||
if (!isValidElement<{ children?: ReactNode; src?: unknown }>(child)) {
|
||||
return [{ interactiveImage: false, node: child }]
|
||||
}
|
||||
|
||||
const src = typeof child.props.src === 'string' ? child.props.src : null
|
||||
if (src) {
|
||||
const standalonePath = fileBase
|
||||
? resolveMarkdownRelativePath(fileBase.filePath, src, fileBase.workspacePath)
|
||||
: null
|
||||
return [{ interactiveImage: !standalonePath, node: child }]
|
||||
}
|
||||
|
||||
const nestedChildren = Children.toArray(child.props.children)
|
||||
if (nestedChildren.length === 0) {
|
||||
return [{ interactiveImage: false, node: child }]
|
||||
}
|
||||
const nested = nestedChildren.flatMap((nestedChild) => splitInteractiveImageNodes(nestedChild, fileBase))
|
||||
if (!nested.some((segment) => segment.interactiveImage)) {
|
||||
return [{ interactiveImage: false, node: child }]
|
||||
}
|
||||
|
||||
return nested.map((segment, index) => ({
|
||||
interactiveImage: segment.interactiveImage,
|
||||
node: cloneElement(
|
||||
child,
|
||||
{ key: `${String(child.key ?? 'node')}-${index}` },
|
||||
segment.node,
|
||||
),
|
||||
}))
|
||||
}
|
||||
|
||||
function renderSplitInteractiveImageLink(
|
||||
children: ReactNode,
|
||||
fileBase: MarkdownFileBaseValue | null,
|
||||
renderAnchor: (children: ReactNode, key: string) => ReactNode,
|
||||
): ReactNode | null {
|
||||
const segments: LinkChildSegment[] = []
|
||||
const splitNodes = Children.toArray(children).flatMap((child) => splitInteractiveImageNodes(child, fileBase))
|
||||
for (const splitNode of splitNodes) {
|
||||
if (splitNode.interactiveImage) {
|
||||
segments.push({ interactiveImage: true, children: [splitNode.node] })
|
||||
continue
|
||||
}
|
||||
const previous = segments.at(-1)
|
||||
if (previous && !previous.interactiveImage) previous.children.push(splitNode.node)
|
||||
else segments.push({ interactiveImage: false, children: [splitNode.node] })
|
||||
}
|
||||
|
||||
if (!segments.some((segment) => segment.interactiveImage)) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
{segments.map((segment, index) => segment.interactiveImage
|
||||
? <Fragment key={`image-${index}`}>{segment.children}</Fragment>
|
||||
: renderAnchor(segment.children, `link-${index}`))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function A(props: ComponentPropsWithoutRef<'a'>) {
|
||||
const chat = useOptionalHappyChatContext()
|
||||
// useContext must be called unconditionally before any early return so that
|
||||
@@ -622,10 +693,30 @@ function A(props: ComponentPropsWithoutRef<'a'>) {
|
||||
if (!chat) {
|
||||
return <>{props.children}</>
|
||||
}
|
||||
const split = renderSplitInteractiveImageLink(
|
||||
props.children,
|
||||
fileBase,
|
||||
(children, key) => (
|
||||
<FilePathAnchor key={key} {...props} filePath={filePath} sessionId={chat.sessionId}>
|
||||
{children}
|
||||
</FilePathAnchor>
|
||||
),
|
||||
)
|
||||
if (split) return split
|
||||
return <FilePathAnchor {...props} filePath={filePath} sessionId={chat.sessionId} />
|
||||
}
|
||||
|
||||
if (targetSessionId) {
|
||||
const split = renderSplitInteractiveImageLink(
|
||||
props.children,
|
||||
fileBase,
|
||||
(children, key) => (
|
||||
<SessionPathAnchor key={key} {...props} targetSessionId={targetSessionId}>
|
||||
{children}
|
||||
</SessionPathAnchor>
|
||||
),
|
||||
)
|
||||
if (split) return split
|
||||
return <SessionPathAnchor {...props} targetSessionId={targetSessionId} />
|
||||
}
|
||||
|
||||
@@ -633,6 +724,22 @@ function A(props: ComponentPropsWithoutRef<'a'>) {
|
||||
? resolveMarkdownRelativePath(fileBase.filePath, props.href, fileBase.workspacePath)
|
||||
: null
|
||||
if (fileBase && relativeFilePath) {
|
||||
const split = renderSplitInteractiveImageLink(
|
||||
props.children,
|
||||
fileBase,
|
||||
(children, key) => (
|
||||
<FilePathAnchor
|
||||
key={key}
|
||||
{...props}
|
||||
filePath={relativeFilePath}
|
||||
sessionId={fileBase.sessionId}
|
||||
fileSearch={fileBase.fileSearch}
|
||||
>
|
||||
{children}
|
||||
</FilePathAnchor>
|
||||
),
|
||||
)
|
||||
if (split) return split
|
||||
return (
|
||||
<FilePathAnchor
|
||||
{...props}
|
||||
@@ -681,6 +788,16 @@ function A(props: ComponentPropsWithoutRef<'a'>) {
|
||||
if (!chat) {
|
||||
return <InertMarkdownHref href={href ?? windowsPathFromHref ?? ''} className={props.className}>{props.children}</InertMarkdownHref>
|
||||
}
|
||||
const split = renderSplitInteractiveImageLink(
|
||||
props.children,
|
||||
fileBase,
|
||||
(children, key) => (
|
||||
<FilePathAnchor key={key} {...props} filePath={decision.path} sessionId={chat.sessionId}>
|
||||
{children}
|
||||
</FilePathAnchor>
|
||||
),
|
||||
)
|
||||
if (split) return split
|
||||
return <FilePathAnchor {...props} filePath={decision.path} sessionId={chat.sessionId} />
|
||||
}
|
||||
if (decision.action === 'inert') {
|
||||
@@ -744,6 +861,25 @@ function A(props: ComponentPropsWithoutRef<'a'>) {
|
||||
ctx?.openUri(url, scheme)
|
||||
}
|
||||
|
||||
const split = renderSplitInteractiveImageLink(
|
||||
props.children,
|
||||
fileBase,
|
||||
(children, key) => (
|
||||
<a
|
||||
key={key}
|
||||
{...rest}
|
||||
href={domHref}
|
||||
target={target}
|
||||
rel={effectiveRel}
|
||||
onClick={handleClick}
|
||||
className={cn('aui-md-a font-medium text-[var(--app-link)] underline decoration-[color:var(--app-link-muted)] underline-offset-3', props.className)}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
)
|
||||
if (split) return split
|
||||
|
||||
return (
|
||||
<a
|
||||
{...rest}
|
||||
|
||||
Reference in New Issue
Block a user