Skip to content
Merged
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
6 changes: 6 additions & 0 deletions packages/pluggableWidgets/image-web/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),

## [Unreleased]

### Fixed

- We fixed an issue where an image enlarged on click was shown smaller than the image on the page when its width was a percentage or a maximum height was set. The enlarged image now shows at its natural size, or at its size on the page when that is larger, scaled down to fit the screen.

- We fixed an issue where a height in viewport units was not applied to the image.

## [1.6.1] - 2026-08-14

### Fixed
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { cloneElement, CSSProperties, FunctionComponent, ReactNode, useCallback } from "react";
import { CSSProperties, FunctionComponent, ReactNode, useCallback, useState } from "react";
import { ImageSize, LightboxImage } from "./LightboxImage";
import { ImageContentProps, ImageUi } from "./ui";
import { DisplayAsEnum, HeightUnitEnum, OnClickTypeEnum, WidthUnitEnum } from "../../../typings/ImageProps";
import { useLightboxState } from "../../utils/lightboxState";
import { Lightbox, LightboxProps } from "../Lightbox";

import "../../ui/Image.scss";
import classNames from "classnames";

Check warning on line 9 in packages/pluggableWidgets/image-web/src/components/Image/Image.tsx

View workflow job for this annotation

GitHub Actions / Run code quality check

`classnames` import should occur before import of `react`

export type ImageType = {
type: "image" | "icon" | "glyph";
Expand Down Expand Up @@ -61,6 +62,7 @@
backgroundImageContent
}) => {
const { lightboxIsOpen, openLightbox, closeLightbox } = useLightboxState();
const [sizeOnPage, setSizeOnPage] = useState<ImageSize>();

const onCloseLightbox = useCallback<LightboxProps["onClose"]>(
event => {
Expand All @@ -76,6 +78,8 @@
if (onClickType === "action") {
onClick?.();
} else if (onClickType === "enlarge") {
const { width, height } = event.currentTarget.getBoundingClientRect();
setSizeOnPage({ width, height });
openLightbox();
}
},
Expand Down Expand Up @@ -135,7 +139,17 @@
{content}
{!previewMode && lightboxIsOpen && (
<Lightbox isOpen={lightboxIsOpen} onClose={onCloseLightbox}>
{type === "image" ? cloneElement(content, { image, onClick: undefined }) : content}
{type === "image" ? (
<LightboxImage
className={classNames({ "img-thumbnail": displayAs === "thumbnail" })}
image={image}
style={style}
altText={altText}
minSize={sizeOnPage}
/>
) : (
content
)}
</Lightbox>
)}
</ImageUi.Wrapper>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import classNames from "classnames";
import { CSSProperties, ReactElement, SyntheticEvent, useCallback, useState } from "react";

export interface ImageSize {
width: number;
height: number;
}

export interface LightboxImageProps {
image: string | undefined;
className?: string;
style?: CSSProperties;
altText?: string;
/** The size of the image on the page. The enlarged image is never shown smaller than this. */
minSize?: ImageSize;
}

/**
* Style properties of the image on the page that only make sense for the box it has on the page. The enlarged
* image gets its size from `Image.scss` and `getLightboxImageWidth` instead.
*/
const PAGE_ONLY_STYLE_PROPERTIES = [
"width",
"height",
"minWidth",
"minHeight",
"maxWidth",
"maxHeight",
"aspectRatio",
"objectFit",
"objectPosition"
] as const;

export function getLightboxImageStyle(style: CSSProperties | undefined): CSSProperties | undefined {
if (!style) {
return style;
}
const rest: CSSProperties = { ...style };
for (const property of PAGE_ONLY_STYLE_PROPERTIES) {
delete rest[property];
}
return rest;
}

/**
* The enlarged image shows at its natural size, but at least at the size of the image on the page. It is scaled
* down to fit the viewport, keeping the aspect ratio of the image. Returns `undefined` when the natural size is
* large enough, so that `Image.scss` alone sizes the image.
*/
export function getLightboxImageWidth(naturalSize: ImageSize, minSize: ImageSize | undefined): string | undefined {
if (!minSize || naturalSize.width <= 0 || naturalSize.height <= 0) {
return undefined;
}
const ratio = naturalSize.width / naturalSize.height;
const width = Math.ceil(Math.max(minSize.width, minSize.height * ratio));
if (width <= naturalSize.width) {
return undefined;
}
return `min(${width}px, var(--mx-image-viewer-lightbox-max-width), calc(var(--mx-image-viewer-lightbox-max-height) * ${ratio}))`;
}

export function LightboxImage({ image, className, style, altText, minSize }: LightboxImageProps): ReactElement {
const [naturalSize, setNaturalSize] = useState<ImageSize>();

const onLoad = useCallback((event: SyntheticEvent<HTMLImageElement>) => {
const { naturalWidth, naturalHeight } = event.currentTarget;
setNaturalSize({ width: naturalWidth, height: naturalHeight });
}, []);

const width = naturalSize ? getLightboxImageWidth(naturalSize, minSize) : undefined;

return (
<img
className={classNames("mx-image-viewer-lightbox-image", className)}
src={image}
style={{ ...getLightboxImageStyle(style), width }}
alt={altText}
role="img"
onLoad={onLoad}
/>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ function getStyle(value: string | number, type: WidthUnitEnum | HeightUnitEnum):
return value;
} else if (type === "percentage") {
return value + "%";
} else if (type === "viewport") {
return value + "vh";
}

return "";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import "@testing-library/jest-dom";
import { render } from "@testing-library/react";
import { fireEvent, render } from "@testing-library/react";
import userEvent, { UserEvent } from "@testing-library/user-event";
import { forwardRef } from "react";
import { ModalProps } from "react-overlays/esm/Modal";
Expand Down Expand Up @@ -91,6 +91,24 @@ describe("Image", () => {
expect(image.asFragment()).toMatchSnapshot();
});

it("applies a height in viewport units to the image", () => {
const { getByRole } = render(<Image {...imageProps} height={30} heightUnit="viewport" />);
expect(getByRole("img")).toHaveStyle({ height: "30vh" });
});

it("applies a height in viewport units to the background image", () => {
const { container } = render(
<Image
{...imageProps}
height={30}
heightUnit="viewport"
renderAsBackground
backgroundImageContent={<div>Image content</div>}
/>
);
expect(container.querySelector(".mx-image-background")).toHaveStyle({ height: "30vh" });
});

it("renders the structure with a glyph icon", () => {
const image = render(<Image {...glyphiconProps} />);
expect(image.asFragment()).toMatchSnapshot();
Expand Down Expand Up @@ -163,6 +181,75 @@ describe("Image", () => {
expect(lightbox).toBeInTheDocument();
});

it("does not apply the sizing of the image on the page to the lightbox image", async () => {
const { getByRole, getAllByRole } = render(
<Image
{...imageProps}
onClickType="enlarge"
width={50}
widthUnit="percentage"
height={0}
heightUnit="auto"
style={{ width: "50%", height: "auto", maxHeight: "250px", minHeight: "10px", opacity: 0.9 }}
/>
);
const thumbnail = getByRole("button");
expect(thumbnail).toHaveStyle({ width: "50%", maxHeight: "250px" });

await user.click(thumbnail);

// The thumbnail has role "button"; the only image is the one in the lightbox.
const [lightboxImage] = getAllByRole("img") as HTMLImageElement[];
expect(lightboxImage.tagName).toBe("IMG");
expect(lightboxImage.style.width).toBe("");
expect(lightboxImage.style.height).toBe("");
expect(lightboxImage.style.maxHeight).toBe("");
expect(lightboxImage.style.minHeight).toBe("");
expect(lightboxImage.style.opacity).toBe("0.9");
});

it("does not apply the aspect ratio or object fit of the image on the page to the lightbox image", async () => {
const { getByRole, getAllByRole } = render(
<Image
{...imageProps}
onClickType="enlarge"
style={{ aspectRatio: "1 / 1", objectFit: "cover", objectPosition: "top" }}
/>
);
await user.click(getByRole("button"));

const [lightboxImage] = getAllByRole("img") as HTMLImageElement[];
expect(lightboxImage.style.aspectRatio).toBe("");
expect(lightboxImage.style.objectFit).toBe("");
expect(lightboxImage.style.objectPosition).toBe("");
});

it("keeps the thumbnail class and adds the lightbox image class", async () => {
const { getByRole, getAllByRole } = render(
<Image {...imageProps} onClickType="enlarge" displayAs="thumbnail" />
);
expect(getByRole("button").getAttribute("src")).toContain("thumb=true");
await user.click(getByRole("button"));

const [lightboxImage] = getAllByRole("img") as HTMLImageElement[];
expect(lightboxImage).toHaveClass("img-thumbnail", "mx-image-viewer-lightbox-image");
expect(lightboxImage.getAttribute("src")).not.toContain("thumb=true");
});

it("shows the lightbox image at least at the size of the image on the page", async () => {
const { getByRole, getAllByRole } = render(<Image {...imageProps} onClickType="enlarge" />);
const imageOnPage = getByRole("button");
jest.spyOn(imageOnPage, "getBoundingClientRect").mockReturnValue({ width: 560, height: 420 } as DOMRect);
await user.click(imageOnPage);

const [lightboxImage] = getAllByRole("img") as HTMLImageElement[];
Object.defineProperty(lightboxImage, "naturalWidth", { value: 400 });
Object.defineProperty(lightboxImage, "naturalHeight", { value: 300 });
fireEvent.load(lightboxImage);

expect(lightboxImage.getAttribute("style")).toContain("min(560px");
});

it("closes the lightbox when the user clicks on the close button after opening it", async () => {
const { container, getByRole } = render(<Image {...imageProps} onClickType="enlarge" />);
const image = getByRole("button");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { getLightboxImageStyle, getLightboxImageWidth } from "../Image/LightboxImage";

describe("getLightboxImageWidth", () => {
it("returns undefined when the natural size is at least the size on the page", () => {
expect(getLightboxImageWidth({ width: 400, height: 300 }, { width: 200, height: 150 })).toBeUndefined();
expect(getLightboxImageWidth({ width: 400, height: 300 }, { width: 400, height: 300 })).toBeUndefined();
expect(getLightboxImageWidth({ width: 400, height: 300 }, undefined)).toBeUndefined();
});

it("uses the width on the page when it is larger than the natural width", () => {
expect(getLightboxImageWidth({ width: 400, height: 300 }, { width: 560, height: 420 })).toBe(
"min(560px, var(--mx-image-viewer-lightbox-max-width), calc(var(--mx-image-viewer-lightbox-max-height) * 1.3333333333333333))"
);
});

it("uses the height on the page when the image on the page is taller than its aspect ratio", () => {
expect(getLightboxImageWidth({ width: 160, height: 120 }, { width: 200, height: 450 })).toMatch(/^min\(600px,/);
});

it("does not enlarge a cropped image whose box on the page fits inside the natural size", () => {
// aspect-ratio: 1 / 1 with object-fit: cover shows a 400x300 image at 300x300.
expect(getLightboxImageWidth({ width: 400, height: 300 }, { width: 300, height: 300 })).toBeUndefined();
});
});

describe("getLightboxImageStyle", () => {
it("removes the properties that size the image on the page and keeps the others", () => {
expect(
getLightboxImageStyle({
width: "50%",
maxHeight: "250px",
aspectRatio: "1 / 1",
objectFit: "cover",
opacity: 0.9
})
).toEqual({ opacity: 0.9 });
});
});
14 changes: 14 additions & 0 deletions packages/pluggableWidgets/image-web/src/ui/Image.scss
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

--mx-image-viewer-lightbox-max-width: 90vw;
--mx-image-viewer-lightbox-max-height: 85vh;

// Show the image at its natural size, scaled down to fit the viewport. The class selector is needed to win
// over Atlas rules with the same specificity, such as `img.img-thumbnail { max-width: 100% }`.
// `LightboxImage` sets a width when the image on the page is larger than the natural size.
.mx-image-viewer-lightbox-image {
display: block;
width: auto;
height: auto;
max-width: var(--mx-image-viewer-lightbox-max-width);
max-height: var(--mx-image-viewer-lightbox-max-height);
}
}

.mx-image-viewer.mx-image-background {
Expand Down
Loading