Skip to content

Commit

Permalink
Refactor image and icon loading logic
Browse files Browse the repository at this point in the history
  • Loading branch information
JeremyDolle committed Oct 9, 2024
1 parent 25b3a67 commit 26d7146
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 16 deletions.
19 changes: 15 additions & 4 deletions template/src/components/atoms/AssetByVariant/AssetByVariant.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,21 @@ function AssetByVariant({ path, extension = 'png', ...props }: Props) {
.custom<ImageSourcePropType>()
.parse(images(`./${path}.${extension}`));

const fetchedModule = z
.custom<ImageSourcePropType>()
.parse(images(`./${variant}/${path}.${extension}`));
setImage(fetchedModule ?? defaultSource);
if (variant === 'default') {
setImage(defaultSource);
return;
}

try {
const fetchedModule = z
.custom<ImageSourcePropType>()
.parse(images(`./${variant}/${path}.${extension}`));
setImage(fetchedModule);
} catch (error) {
// eslint-disable-next-line no-console
console.error(`Couldn't load the image: ${path}.${extension} for the variant ${variant}, Fallback to default`, error);
setImage(defaultSource);
}
} catch (error) {
// eslint-disable-next-line no-console
console.error(`Couldn't load the image: ${path}`, error);
Expand Down
26 changes: 14 additions & 12 deletions template/src/components/atoms/IconByVariant/IconByVariant.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,23 @@ function IconByVariant({ path, ...props }: Props) {
.object({ default: z.custom<ReactElement<SvgProps>>() })
.parse(icons(`./${path}.${EXTENSION}`));

if (variant !== 'default') {
try {
const fetchedModule = z
.object({ default: z.custom<ReactElement<SvgProps>>() })
.parse(icons(`./${variant}/${path}.${EXTENSION}`));
if (variant === 'default') {
setIcon(defaultSource.default);
return;
}

setIcon(fetchedModule.default);
} catch (error) {
// eslint-disable-next-line no-console
console.error(`Couldn't load the icon: ${path}.${EXTENSION} for the variant ${variant}, Fallback to default`, error);
setIcon(defaultSource.default);
}
} else {
try {
const fetchedModule = z
.object({ default: z.custom<ReactElement<SvgProps>>() })
.parse(icons(`./${variant}/${path}.${EXTENSION}`));

setIcon(fetchedModule.default);
} catch (error) {
// eslint-disable-next-line no-console
console.error(`Couldn't load the icon: ${path}.${EXTENSION} for the variant ${variant}, Fallback to default`, error);
setIcon(defaultSource.default);
}

} catch (error) {
// eslint-disable-next-line no-console
console.error(`Couldn't load the icon: ${path}.${EXTENSION}`, error);
Expand Down

0 comments on commit 26d7146

Please sign in to comment.