Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { StringRequest } from "@shared/proto/cline/common"
import DOMPurify from "dompurify"
import React from "react"
import ChatErrorBoundary from "@/components/chat/ChatErrorBoundary"
import { WebServiceClient } from "@/services/grpc-client"
import { checkIfImageUrl, formatUrlForOpening, getSafeHostname } from "./utils/mcpRichUtil"
interface ImagePreviewProps {
url: string
}
// Use a class component to ensure complete isolation between instances
class ImagePreview extends React.Component<
ImagePreviewProps,
{
loading: boolean
error: string | null
fetchStartTime: number
}
> {
private imgRef = React.createRef<HTMLImageElement>()
private timeoutId: NodeJS.Timeout | null = null
private heartbeatId: NodeJS.Timeout | null = null
constructor(props: ImagePreviewProps) {
super(props)
this.state = {
loading: true,
error: null,
fetchStartTime: Date.now(),
}
}
// Track aspect ratio for proper display
private aspectRatio: number = 1
componentDidMount() {
// Set up a timeout to handle cases where the image never loads or errors
this.timeoutId = setTimeout(() => {
console.log(`Image load timeout for ${this.props.url}`)
if (this.state.loading) {
this.setState({
loading: false,
error: `Timeout loading image: ${this.props.url}`,
})
}
}, 15000)
// Set up a heartbeat to update the UI with elapsed time
this.heartbeatId = setInterval(() => {
if (this.state.loading) {
this.forceUpdate() // Just update the component to show new elapsed time
}
}, 1000)
// First, check the content type to verify it's actually an image
this.checkContentType(this.props.url)
}
// Check if the URL is an image using content type verification
checkContentType(url: string) {
// Always verify content type, even for URLs that look like images by extension
checkIfImageUrl(url)
.then((isImage) => {
if (isImage) {
console.log(`URL is confirmed as image: ${url}`)
this.loadImage(url)
} else {
console.log(`URL is not an image: ${url}`)
this.handleImageError()
}
})
.catch((error) => {
console.log(`Error checking if URL is an image: ${error}`)
// Don't fallback to direct image loading on error
// Instead, report the error so the URL can be handled as a non-image
this.handleImageError()
})
}
// Load the image after content type check or as fallback
loadImage(url: string) {
const isSvg = /\.svg(\?.*)?$/i.test(url)
// For SVG files, we don't need to calculate aspect ratio as they're vector-based
if (isSvg) {
console.log(`SVG image detected, skipping aspect ratio calculation: ${url}`)
// Default aspect ratio for SVGs
this.aspectRatio = 1
this.handleImageLoad()
return
}
// Create a test image to check if the URL loads and get dimensions
const testImg = new Image()
testImg.onload = () => {
console.log(`Test image loaded successfully: ${url}`)
// Calculate aspect ratio for proper display
if (testImg.width > 0 && testImg.height > 0) {
this.aspectRatio = testImg.width / testImg.height
}
this.handleImageLoad()
}
testImg.onerror = () => {
console.log(`Test image failed to load: ${url}`)
this.handleImageError()
}
// Force CORS mode to be anonymous to avoid CORS issues
testImg.crossOrigin = "anonymous"
}
componentWillUnmount() {
this.cleanup()
}
private cleanup() {
if (this.timeoutId) {
clearTimeout(this.timeoutId)
this.timeoutId = null
}
if (this.heartbeatId) {
clearInterval(this.heartbeatId)
this.heartbeatId = null
}
}
// Handle image load event
handleImageLoad = () => {
console.log(`Image loaded successfully: ${this.props.url}`)
this.setState({ loading: false })
this.cleanup()
}
// Handle image error event
handleImageError = () => {
console.log(`Image failed to load: ${this.props.url}`)
this.setState({
loading: false,
error: `Failed to load image: ${this.props.url}`,
})
this.cleanup()
}
render() {
const { url } = this.props
const { loading, error, fetchStartTime } = this.state
// Calculate elapsed time for loading state
const elapsedSeconds = loading ? Math.floor((Date.now() - fetchStartTime) / 1000) : 0
// Fallback display while loading
if (loading) {
return (
<div
className="image-preview-loading"
style={{
padding: "12px",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))",
borderRadius: "4px",
height: "128px",
maxWidth: "512px",
}}>
<div style={{ display: "flex", alignItems: "center", marginBottom: "8px" }}>
<div
className="loading-spinner"
style={{
marginRight: "8px",
width: "16px",
height: "16px",
border: "2px solid rgba(127, 127, 127, 0.3)",
borderTopColor: "var(--vscode-textLink-foreground, #3794ff)",
borderRadius: "50%",
animation: "spin 1s linear infinite",
}}
/>
<style>
{`
@keyframes spin {
to { transform: rotate(360deg); }
}
`}
</style>
Loading image from {getSafeHostname(url)}...
</div>
{elapsedSeconds > 3 && (
<div style={{ fontSize: "11px", color: "var(--vscode-descriptionForeground)" }}>
{elapsedSeconds > 60
? `Waiting for ${Math.floor(elapsedSeconds / 60)}m ${elapsedSeconds % 60}s...`
: `Waiting for ${elapsedSeconds}s...`}
</div>
)}
{/* Hidden image that we'll use to detect load/error events */}
{/\.svg(\?.*)?$/i.test(url) ? (
<object
data={DOMPurify.sanitize(url)}
onError={this.handleImageError}
onLoad={this.handleImageLoad}
style={{ display: "none" }}
type="image/svg+xml"
/>
) : (
<img
alt=""
onError={this.handleImageError}
onLoad={this.handleImageLoad}
ref={this.imgRef}
src={DOMPurify.sanitize(url)}
style={{ display: "none" }}
/>
)}
</div>
)
}
// Handle error state
if (error) {
return (
<div
className="image-preview-error"
onClick={async () => {
try {
await WebServiceClient.openInBrowser(
StringRequest.create({
value: DOMPurify.sanitize(url),
}),
)
} catch (err) {
console.error("Error opening URL in browser:", err)
}
}}
style={{
padding: "12px",
border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))",
borderRadius: "4px",
color: "var(--vscode-errorForeground)",
}}>
<div style={{ fontWeight: "bold" }}>Failed to load image</div>
<div style={{ fontSize: "12px", marginTop: "4px" }}>{getSafeHostname(url)}</div>
<div style={{ fontSize: "11px", marginTop: "8px", color: "var(--vscode-textLink-foreground)" }}>
Click to open in browser
</div>
</div>
)
}
// Render the image
return (
<div
className="image-preview"
onClick={async () => {
try {
await WebServiceClient.openInBrowser(
StringRequest.create({
value: DOMPurify.sanitize(formatUrlForOpening(url)),
}),
)
} catch (err) {
console.error("Error opening URL in browser:", err)
}
}}
style={{
margin: "10px 0",
maxWidth: "100%",
cursor: "pointer",
}}>
{/\.svg(\?.*)?$/i.test(url) ? (
// Special handling for SVG images
<object
aria-label={`SVG from ${getSafeHostname(url)}`}
data={DOMPurify.sanitize(url)}
style={{
width: "85%",
height: "auto",
borderRadius: "4px",
}}
type="image/svg+xml">
{/* Fallback if object tag fails */}
<img
alt={`SVG from ${getSafeHostname(url)}`}
src={DOMPurify.sanitize(url)}
style={{
width: "85%",
height: "auto",
borderRadius: "4px",
}}
/>
</object>
) : (
<img
alt={`Image from ${getSafeHostname(url)}`}
loading="eager"
onLoad={(e) => {
// Double-check aspect ratio from the actual loaded image
const img = e.currentTarget
if (img.naturalWidth > 0 && img.naturalHeight > 0) {
const newAspectRatio = img.naturalWidth / img.naturalHeight
// Update object-fit based on actual aspect ratio
// Use contain only for very extreme aspect ratios, otherwise use cover
if (newAspectRatio > 3 || newAspectRatio < 0.33) {
img.style.objectFit = "contain"
} else {
img.style.objectFit = "cover"
}
}
}}
src={DOMPurify.sanitize(url)}
style={{
width: "85%",
height: "auto",
borderRadius: "4px",
// Use contain only for very extreme aspect ratios, otherwise use cover
objectFit: this.aspectRatio > 3 || this.aspectRatio < 0.33 ? "contain" : "cover",
}}
/>
)}
</div>
)
}
}
// Create a wrapper component that memoizes the ImagePreview to prevent unnecessary re-renders
const MemoizedImagePreview = React.memo(
(props: ImagePreviewProps) => <ImagePreview {...props} />,
(prevProps, nextProps) => prevProps.url === nextProps.url, // Only re-render if URL changes
)
// Wrap the ImagePreview component with an error boundary
const ImagePreviewWithErrorBoundary: React.FC<ImagePreviewProps> = (props) => {
return (
<ChatErrorBoundary errorTitle="Something went wrong displaying this image">
<MemoizedImagePreview {...props} />
</ChatErrorBoundary>
)
}
export default ImagePreviewWithErrorBoundary
|