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

Attempt to adjust image comparison size based on the images aspect ratio #74

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
4 changes: 4 additions & 0 deletions content/redesigning-my-website.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ to keep gradients in titles while using the dark theme only. They look better wi
Here's a quick comparison:

<ImageComparison
fitStrategy={'taller'}
position={0.35}
description={
'Toolbar before (left) and now (right). Slide over the image to view the differences'
Expand Down Expand Up @@ -147,6 +148,7 @@ interactive than before and they don't need to go to the contact site and fill u
Here's the comparison:

<ImageComparison
fitStrategy={'taller'}
position={0.4}
description={
'Blog before (left) and now (right). Slide over the image to view the differences'
Expand All @@ -157,6 +159,7 @@ Here's the comparison:
</ImageComparison>

<ImageComparison
fitStrategy={'taller'}
position={0.4}
description={
'Blog footer before (left) and now (right). Slide over the image to view the differences'
Expand All @@ -177,6 +180,7 @@ website.
Comparison:

<ImageComparison
fitStrategy={'taller'}
position={0.3}
description={
'Footer before (left) and now (right). Slide over the image to view the differences'
Expand Down
96 changes: 91 additions & 5 deletions src/components/ui/blog/mdx/image-comparison.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
'use client';

import {
Children,
cloneElement,
useRef,
useEffect,
useState,
type ComponentProps,
type PropsWithChildren,
type ReactElement,
type ReactNode,
type Ref,
} from 'react';
import {
ReactCompareSlider,
ReactCompareSliderHandle,
useReactCompareSliderRef,
} from 'react-compare-slider';

import cx from '@/utils/cx';
Expand All @@ -15,9 +24,11 @@ interface ImageComparisonProps
extends PropsWithChildren,
Omit<ComponentProps<typeof ReactCompareSlider>, 'itemOne' | 'itemTwo'> {
description?: string;
fitStrategy?: 'taller' | 'wider';
}

const Handle = (props: { portrait?: boolean }) => {
const Handle = (props: { portrait?: boolean; disabled?: boolean }) => {
if (props.disabled) return null;
return (
<ReactCompareSliderHandle
portrait={props.portrait}
Expand Down Expand Up @@ -51,21 +62,96 @@ const getChildrenArray = (
typeof it !== 'boolean',
) as Array<Exclude<ReactNode, string | number | boolean>>;

const addRefToElement = (
element: ReactNode | null | undefined,
ref: Ref<HTMLImageElement>,
onLoad?: () => void,
) => {
if (!element) return null;
try {
return cloneElement(element as ReactElement, { ref, onLoad });
} catch (e) {
return null;
}
};

const gcd = (w: number, h: number): number => {
if (h === 0) return w;
return gcd(h, w % h);
};

export const ImageComparison = (props: ImageComparisonProps) => {
const { children: childrenFromProps, description, ...otherProps } = props;
const {
children: childrenFromProps,
description,
fitStrategy,
...otherProps
} = props;

const reactCompareSliderRef = useReactCompareSliderRef();
const itemOneRef = useRef<HTMLImageElement>(null);
const itemTwoRef = useRef<HTMLImageElement>(null);

const [itemOneLoaded, setItemOneLoaded] = useState(false);
const [itemTwoLoaded, setItemTwoLoaded] = useState(false);
const [componentReady, setComponentReady] = useState(false);

const children = getChildrenArray(childrenFromProps);

useEffect(() => {
const rootContainer = reactCompareSliderRef.current.rootContainer;
const itemOne = itemOneRef.current;
const itemTwo = itemTwoRef.current;

if (!rootContainer || !itemOne || !itemTwo) {
return;
}

if (typeof fitStrategy === 'undefined') {
rootContainer.style.aspectRatio = 'auto';
setComponentReady(true);
return;
}

if (!itemOneLoaded && !itemTwoLoaded) return;

const itemOneAspectRatio = itemOne.naturalHeight / itemOne.naturalWidth;
const itemTwoAspectRatio = itemTwo.naturalHeight / itemTwo.naturalWidth;

const aspectRatio =
fitStrategy === 'taller'
? Math.max(itemOneAspectRatio, itemTwoAspectRatio)
: Math.min(itemOneAspectRatio, itemTwoAspectRatio);

const w = rootContainer.getBoundingClientRect().width;
const h = rootContainer.getBoundingClientRect().width * aspectRatio;
const r = gcd(w, h);
rootContainer.style.aspectRatio = `${w / r} / ${h / r}`;
setComponentReady(true);
}, [fitStrategy, reactCompareSliderRef, itemOneLoaded, itemTwoLoaded]);

return (
<figure className={'image-comparison'}>
<ReactCompareSlider
{...otherProps}
ref={reactCompareSliderRef}
position={(otherProps.position || 0.5) * 100}
handle={<Handle portrait={otherProps.portrait} />}
itemOne={children[0]}
itemTwo={children[1]}
handle={
<Handle portrait={otherProps.portrait} disabled={!componentReady} />
}
itemOne={addRefToElement(children[0], itemOneRef, () => {
setItemOneLoaded(true);
})}
itemTwo={addRefToElement(children[1], itemTwoRef, () => {
setItemTwoLoaded(true);
})}
className={cx(
'border border-divider rounded-2',
'[&_img]:object-contain [&_img]:h-full [&_img]:bg-background',
!componentReady ? 'cursor-not-allowed' : '',
)}
transition={'.25s ease-in-out'}
disabled={!componentReady}
changePositionOnHover
/>
<figcaption>{description}</figcaption>
Expand Down