Skip to content

Commit

Permalink
fix: show error when image fails to load (#466)
Browse files Browse the repository at this point in the history
  • Loading branch information
DenverCoder1 authored Jun 17, 2022
1 parent 32f4118 commit 0b56a3c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
9 changes: 8 additions & 1 deletion client/src/BadgePreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@ import Form from 'react-bootstrap/esm/Form';
* Image for previewing a badge with a custom icon, or placeholder text if no image is uploaded
*/
class BadgePreview extends React.Component<{ url: string, label: string }> {
static handleError = (event: React.SyntheticEvent<HTMLImageElement>) => {
const target = event.target as HTMLImageElement;
if (!target.src.includes("critical")) {
target.src = "https://custom-icon-badges.herokuapp.com/badge/failed%20to%20load-try%20compressing%20the%20image%20to%20make%20it%20smaller-critical?logo=x-circle-fill";
}
}

render = () => {
const { url, label } = this.props;
return (
<Form.Group controlId="formFile" className="mb-3 d-flex align-items-center flex-column">
<h3>{label}</h3>
{url ? <img className="m-2" src={url} alt="badge preview" /> : <Card.Text className="text-muted m-2">Upload a file to see a preview</Card.Text>}
{url ? <img className="m-2" src={url} alt="badge preview" onError={BadgePreview.handleError} /> : <Card.Text className="text-muted m-2">Upload a file to see a preview</Card.Text>}
</Form.Group>
);
}
Expand Down
14 changes: 8 additions & 6 deletions client/src/UploadForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class UploadForm extends React.Component<{}, { slug: string, type: string, data:
slug: fileName.split(".")[0],
type: match[1],
data: match[2],
previewUrl: this.buildShieldUrl(dataUrl),
previewUrl: UploadForm.buildShieldUrl(dataUrl),
message: { type: "", content: <div /> },
});
};
Expand Down Expand Up @@ -115,15 +115,17 @@ class UploadForm extends React.Component<{}, { slug: string, type: string, data:
});
};

buildShieldUrl = (
static buildShieldUrl = (
dataUrl: string = "",
text: string = "Preview",
color: string = "#E61B23"
label: string = "badge",
message: string = "preview",
color: string = "success"
): string => {
const encodedDataUrl = encodeURIComponent(dataUrl);
const encodedText = encodeURIComponent(text);
const encodedLabel = encodeURIComponent(label);
const encodedMessage = encodeURIComponent(message);
const encodedColor = encodeURIComponent(color);
return `https://img.shields.io/badge/${encodedText}-${encodedColor}.svg?logo=${encodedDataUrl}`;
return `https://img.shields.io/badge/${encodedLabel}-${encodedMessage}-${encodedColor}.svg?logo=${encodedDataUrl}`;
};

render = () => {
Expand Down

0 comments on commit 0b56a3c

Please sign in to comment.