Skip to content

Commit

Permalink
feat(SLB-354): improve error handling and allow image source alteration
Browse files Browse the repository at this point in the history
  • Loading branch information
pmelab committed Aug 14, 2024
1 parent bcc79e3 commit 5121f15
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 18 deletions.
13 changes: 9 additions & 4 deletions packages/npm/@amazeelabs/image/src/client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
createContext,
forwardRef,
PropsWithChildren,
useContext,
useEffect,
useRef,
} from 'react';
Expand Down Expand Up @@ -56,11 +57,13 @@ export const Image = forwardRef(function Image(
{ focus, ...props }: ImageProps,
ref,
) {
const alterSrc = useContext(ImageSettingsContext).alterSrc;
const imageRef = useRef<HTMLImageElement | null>(null);
useEffect(() => {
const r = imageRef || ref;
if (r.current && props.src) {
imageDimensions(props.src)
const url = alterSrc ? alterSrc(props.src) : props.src;
imageDimensions(url)
.then((source) => {
if (!r.current || !source) {
return;
Expand All @@ -70,7 +73,7 @@ export const Image = forwardRef(function Image(
props.width,
props.height,
);
r.current.style.backgroundImage = `url(${props.src})`;
r.current.style.backgroundImage = `url(${url})`;
r.current.style.backgroundSize = 'cover';
r.current.style.maxWidth = '100%';

Expand All @@ -84,8 +87,10 @@ export const Image = forwardRef(function Image(
r.current.src = sizerImage(target.width, target.height);
return;
})
.catch((error) => console.error(error));
.catch((error) => {
throw error;
});
}
}, [imageRef, ref, focus, props.width, props.height, props.src]);
}, [imageRef, ref, focus, props.width, props.height, props.src, alterSrc]);
return <img ref={imageRef || ref} {...props} />;
});
1 change: 1 addition & 0 deletions packages/npm/@amazeelabs/image/src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export type ImageSettings = {
staticDir: string;
outputDir: string;
outputPath: string;
alterSrc?: (src: string) => string;
};
export const defaultImageSettings = {
outputDir: 'dist/public',
Expand Down
21 changes: 13 additions & 8 deletions packages/npm/@amazeelabs/image/src/server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { imageDimensionsFromData } from 'image-dimensions';
import { cache, PropsWithChildren } from 'react';
import sharp from 'sharp';

import { ImageSettings as ClientImageSettings } from './client.js';
import {
calculateFocusExtraction,
defaultImageSettings,
Expand All @@ -21,19 +20,25 @@ import {
inferTargetDimensions,
} from './lib.js';

async function prepareFile(url: string) {
async function prepareFile(src: string) {
const alterSrc = getSettings().alterSrc;
const url = alterSrc ? alterSrc(src) : src;
if (url.match(/https?:\/\//)) {
const dir = await mkdtemp(`${tmpdir}${sep}`);
const tmpFileName = `${dir}/${createHash('md5').update(url).digest('hex')}`;
try {
const fd = await open(tmpFileName);
await fd.close();
} catch (err) {
const result = await fetch(url);
const fileStream = createWriteStream(tmpFileName, { flags: 'wx' });
if (result.body) {
await finished(Readable.fromWeb(result.body as any).pipe(fileStream));
} else {
try {
const result = await fetch(url);
const fileStream = createWriteStream(tmpFileName, { flags: 'wx' });
if (result.body) {
await finished(Readable.fromWeb(result.body as any).pipe(fileStream));
} else {
throw `Unable to download ${url}.`;
}
} catch (err) {
throw `Unable to download ${url}.`;
}
}
Expand Down Expand Up @@ -139,7 +144,7 @@ export function ImageSettings({
...settings
}: PropsWithChildren<Partial<ImageSettingsType>>) {
setSettings({ ...defaultImageSettings, ...settings });
return <ClientImageSettings {...settings}>{children}</ClientImageSettings>;
return <>{children}</>;
}

export async function Image({
Expand Down
1 change: 1 addition & 0 deletions packages/npm/@amazeelabs/image/test/image.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ test('client', async ({ page }) => {
throw error;
});
await page.goto('http://localhost:8080/client');
await page.waitForTimeout(1000);
// await expect(page).toHaveScreenshot({
// fullPage: true,
// });
Expand Down
13 changes: 13 additions & 0 deletions packages/npm/@amazeelabs/image/test/src/client-settings.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use client';

import { PropsWithChildren } from 'react';

import { ImageSettings } from '../../src/client.js';

export function ClientImageSettings({ children }: PropsWithChildren<{}>) {
return (
<ImageSettings alterSrc={(src) => src.replace('9999', '8889')}>
{children}
</ImageSettings>
);
}
11 changes: 7 additions & 4 deletions packages/npm/@amazeelabs/image/test/src/pages/client.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Image, ImageSettings } from '../../../src/client.js';
import React from 'react';

import { Image } from '../../../src/client.js';
import { ClientImageSettings } from '../client-settings';

export default function Index() {
return (
<ImageSettings>
<ClientImageSettings>
<h2>No transformation</h2>
<Image src="/goats.jpg" width={500} />
<h2>Scale width</h2>
Expand All @@ -18,7 +21,7 @@ export default function Index() {
<h2>Landscape with manual focus</h2>
<Image src="/goats.jpg" width={300} height={100} focus={[380, 140]} />
<h2>Remote file</h2>
<Image src="http://localhost:8889/goats.jpg" width={500} />
</ImageSettings>
<Image src="http://localhost:9999/goats.jpg" width={500} />
</ClientImageSettings>
);
}
8 changes: 6 additions & 2 deletions packages/npm/@amazeelabs/image/test/src/pages/server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import { Image, ImageSettings } from '../../../src/server.js';

export default function Index() {
return (
<ImageSettings outputDir="dist/public/images" outputPath="/images">
<ImageSettings
outputDir="dist/public/images"
outputPath="/images"
alterSrc={(src) => src.replace('9999', '8889')}
>
<h2>Scale width</h2>
<Image src="/goats.jpg" width={200} />
<h2>Crop</h2>
Expand All @@ -16,7 +20,7 @@ export default function Index() {
<h2>Landscape with manual focus</h2>
<Image src="/goats.jpg" width={300} height={100} focus={[380, 140]} />
<h2>Remote file</h2>
<Image src="http://localhost:8889/goats.jpg" width={500} />
<Image src="http://localhost:9999/goats.jpg" width={500} />
</ImageSettings>
);
}

0 comments on commit 5121f15

Please sign in to comment.