Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(view-data): Add image content type check for URLs in view data page #255

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 48 additions & 43 deletions src/components/Points/PointImage.jsx
Original file line number Diff line number Diff line change
@@ -1,54 +1,59 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Box, CardMedia, Modal, Typography } from '@mui/material';

function PointImage({ data, sx }) {
const [fullScreenImg, setFullScreenImg] = useState(null);
const renderImages = () => {
const images = [];

function isImgUrl(string) {
let url;
try {
url = new URL(string);
} catch (_) {
return false;
}
if (url) {
return /\.(jpg|jpeg|png|webp|gif|svg)$/.test(url.pathname);
}
return false;
}
const [imageUrls, setImageUrls] = useState([]);

// Loop through the object's properties
for (const key in data) {
if (typeof data[key] == 'string') {
// Check if the value is an image URL
if (isImgUrl(data[key])) {
images.push(
<CardMedia
component="img"
sx={{
width: 150,
margin: 'auto',
padding: 1,
wordWrap: 'break-word',
p: 1,
border: '1px solid #ccc',
borderRadius: '5px',
...sx,
}}
key={key}
image={data[key]}
alt={data[key]}
onClick={() => setFullScreenImg(data[key])}
/>
);
useEffect(() => {
const fetchImageUrls = async () => {
const urlChecks = Object.keys(data).map(async (key) => {
if (typeof data[key] === 'string') {
try {
const url = new URL(data[key]);
if (/\.(jpg|jpeg|png|webp|gif|svg)$/.test(url.pathname)) {
return { key, url: data[key] };
}
const response = await fetch(url, { method: 'HEAD' });
const contentType = response.headers.get('content-type');
if (contentType && contentType.startsWith('image/')) {
return { key, url: data[key] };
}
} catch (_) {
// Ignore invalid URLs
}
}
}
}
return null;
});

const urls = (await Promise.all(urlChecks)).filter(Boolean);
setImageUrls(urls);
};

return images;
fetchImageUrls();
}, [data]);

const renderImages = () => {
return imageUrls.map(({ key, url }) => (
<CardMedia
component="img"
sx={{
width: 150,
margin: 'auto',
padding: 1,
wordWrap: 'break-word',
p: 1,
border: '1px solid #ccc',
borderRadius: '5px',
...sx,
}}
key={key}
image={url}
alt={url}
onClick={() => setFullScreenImg(url)}
/>
));
};

const images = renderImages();
Expand Down
Loading