@lumx/react 3.8.1 → 3.8.2-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,173 @@
1
+ import React from 'react';
2
+
3
+ import { mdiMagnifyMinusOutline, mdiMagnifyPlusOutline } from '@lumx/icons';
4
+ import { FlexBox, IconButton, Slides, SlideshowControls } from '@lumx/react';
5
+ import { mergeRefs } from '@lumx/react/utils/mergeRefs';
6
+
7
+ import memoize from 'lodash/memoize';
8
+ import { ImageCaption } from '../../image-block/ImageCaption';
9
+ import { CLASSNAME } from '../constants';
10
+ import type { ImagesProps, InheritedSlideShowProps, ZoomButtonProps } from '../types';
11
+ import { ImageSlide } from './ImageSlide';
12
+
13
+ export interface ImageSlideshowProps extends InheritedSlideShowProps, ZoomButtonProps, ImagesProps {
14
+ currentPaginationItemRef?: React.Ref<HTMLButtonElement>;
15
+ footerRef?: React.Ref<HTMLDivElement>;
16
+ }
17
+
18
+ /** Internal image slideshow component for ImageLightbox */
19
+ export const ImageSlideshow: React.FC<ImageSlideshowProps> = ({
20
+ activeImageIndex,
21
+ images,
22
+ slideGroupLabel,
23
+ zoomInButtonProps,
24
+ zoomOutButtonProps,
25
+ slideshowControlsProps,
26
+ currentPaginationItemRef,
27
+ footerRef,
28
+ activeImageRef,
29
+ }) => {
30
+ const {
31
+ activeIndex,
32
+ slideshowId,
33
+ setSlideshow,
34
+ slideshowSlidesId,
35
+ slidesCount,
36
+ onNextClick,
37
+ onPaginationClick,
38
+ onPreviousClick,
39
+ toggleAutoPlay,
40
+ } = SlideshowControls.useSlideshowControls({
41
+ itemsCount: images.length,
42
+ activeIndex: activeImageIndex,
43
+ });
44
+
45
+ // Image metadata (caption)
46
+ const title = images[activeIndex]?.title;
47
+ const description = images[activeIndex]?.description;
48
+ const tags = images[activeIndex]?.tags;
49
+ const metadata =
50
+ title || description || tags ? (
51
+ <ImageCaption theme="dark" as="div" title={title} description={description} tags={tags} align="center" />
52
+ ) : null;
53
+
54
+ // Slideshow controls
55
+ const slideShowControls =
56
+ slidesCount > 1 && slideshowControlsProps ? (
57
+ <SlideshowControls
58
+ theme="dark"
59
+ activeIndex={activeIndex}
60
+ slidesCount={slidesCount}
61
+ onNextClick={onNextClick}
62
+ onPreviousClick={onPreviousClick}
63
+ onPaginationClick={onPaginationClick}
64
+ {...slideshowControlsProps}
65
+ paginationItemProps={(index: number) => {
66
+ const props = slideshowControlsProps?.paginationItemProps?.(index) || {};
67
+ return {
68
+ ...props,
69
+ ref: mergeRefs(
70
+ (props as any)?.ref,
71
+ // Focus the active pagination item once on mount
72
+ activeIndex === index ? currentPaginationItemRef : undefined,
73
+ ),
74
+ };
75
+ }}
76
+ />
77
+ ) : null;
78
+
79
+ // Zoom controls
80
+ const [scale, setScale] = React.useState<number | undefined>(undefined);
81
+ const zoomEnabled = zoomInButtonProps && zoomOutButtonProps;
82
+ const onScaleChange = React.useMemo(() => {
83
+ if (!zoomEnabled) return undefined;
84
+ return (newScale: number) => {
85
+ setScale((prevScale = 1) => Math.max(1, newScale * prevScale));
86
+ };
87
+ }, [zoomEnabled]);
88
+ const zoomIn = React.useCallback(() => onScaleChange?.(1.5), [onScaleChange]);
89
+ const zoomOut = React.useCallback(() => onScaleChange?.(0.5), [onScaleChange]);
90
+ React.useEffect(() => {
91
+ // Reset scale on slide change
92
+ if (activeIndex) setScale(undefined);
93
+ }, [activeIndex]);
94
+ const zoomControls = zoomEnabled && (
95
+ <>
96
+ <IconButton
97
+ {...zoomInButtonProps}
98
+ theme="dark"
99
+ emphasis="low"
100
+ icon={mdiMagnifyPlusOutline}
101
+ onClick={zoomIn}
102
+ />
103
+ <IconButton
104
+ {...zoomOutButtonProps}
105
+ theme="dark"
106
+ emphasis="low"
107
+ isDisabled={!scale || scale <= 1}
108
+ icon={mdiMagnifyMinusOutline}
109
+ onClick={zoomOut}
110
+ />
111
+ </>
112
+ );
113
+
114
+ const getImgRef = React.useMemo(
115
+ () =>
116
+ memoize(
117
+ (index: number, isActive: boolean) => {
118
+ return mergeRefs(images?.[index].imgRef, isActive ? activeImageRef : undefined);
119
+ },
120
+ // memoize based on both arguments
121
+ (...args) => args.join(),
122
+ ),
123
+ [images, activeImageRef],
124
+ );
125
+
126
+ return (
127
+ <>
128
+ <Slides
129
+ activeIndex={activeIndex}
130
+ theme="dark"
131
+ slideGroupLabel={slideGroupLabel}
132
+ fillHeight
133
+ id={slideshowId}
134
+ ref={setSlideshow}
135
+ slidesId={slideshowSlidesId}
136
+ toggleAutoPlay={toggleAutoPlay}
137
+ >
138
+ {images.map(({ image, imgRef, ...imageProps }, index) => {
139
+ const isActive = index === activeIndex;
140
+ return (
141
+ <ImageSlide
142
+ isActive={isActive}
143
+ key={image}
144
+ image={{
145
+ ...imageProps,
146
+ image,
147
+ imgRef: getImgRef(index, isActive),
148
+ }}
149
+ scale={isActive ? scale : undefined}
150
+ onScaleChange={onScaleChange}
151
+ />
152
+ );
153
+ })}
154
+ </Slides>
155
+ {(metadata || slideShowControls || zoomControls) && (
156
+ <FlexBox
157
+ ref={footerRef}
158
+ className={`${CLASSNAME}__footer`}
159
+ orientation="vertical"
160
+ vAlign="center"
161
+ gap="big"
162
+ >
163
+ {metadata}
164
+
165
+ <FlexBox className={`${CLASSNAME}__footer-actions`} orientation="horizontal" gap="regular">
166
+ {slideShowControls}
167
+ {zoomControls}
168
+ </FlexBox>
169
+ </FlexBox>
170
+ )}
171
+ </>
172
+ );
173
+ };
@@ -0,0 +1,55 @@
1
+ import React from 'react';
2
+ import type { Point, RectSize } from '@lumx/react/utils/type';
3
+
4
+ /** Maintains the scroll position centered relative to the original scroll area's dimensions when the content scales. */
5
+ export function useAnimateScroll(scrollAreaRef: React.RefObject<HTMLDivElement>) {
6
+ return React.useMemo(() => {
7
+ let animationFrame: number | null = null;
8
+
9
+ return function animate(centerPoint?: Point, initialScrollAreaSize?: RectSize) {
10
+ const scrollArea = scrollAreaRef.current as HTMLDivElement;
11
+ if (!scrollArea) {
12
+ return;
13
+ }
14
+
15
+ // Cancel previously running animation
16
+ if (animationFrame) cancelAnimationFrame(animationFrame);
17
+
18
+ // Center on the given point or else on the scroll area visual center
19
+ const clientHeightRatio = centerPoint?.y ? centerPoint.y / scrollArea.clientHeight : 0.5;
20
+ const clientWidthRatio = centerPoint?.x ? centerPoint.x / scrollArea.clientWidth : 0.5;
21
+
22
+ const initialScrollHeight = initialScrollAreaSize?.height || scrollArea.scrollHeight;
23
+ const initialScrollWidth = initialScrollAreaSize?.width || scrollArea.scrollWidth;
24
+
25
+ const heightCenter = scrollArea.scrollTop + scrollArea.clientHeight * clientHeightRatio;
26
+ const heightRatio = heightCenter / initialScrollHeight;
27
+
28
+ const widthCenter = scrollArea.scrollLeft + scrollArea.clientWidth * clientWidthRatio;
29
+ const widthRatio = widthCenter / initialScrollWidth;
30
+
31
+ let prevScrollHeight = 0;
32
+ let prevScrollWidth = 0;
33
+
34
+ function nextFrame() {
35
+ const { scrollHeight, scrollWidth, clientHeight, clientWidth } = scrollArea;
36
+
37
+ // Scroll area stopped expanding => stop animation
38
+ if (scrollHeight === prevScrollHeight && scrollWidth === prevScrollWidth) {
39
+ animationFrame = null;
40
+ return;
41
+ }
42
+
43
+ // Compute next scroll position
44
+ const top = heightRatio * scrollHeight - clientHeight * clientHeightRatio;
45
+ const left = widthRatio * scrollWidth - clientWidth * clientWidthRatio;
46
+
47
+ scrollArea.scrollTo({ top, left });
48
+ prevScrollHeight = scrollHeight;
49
+ prevScrollWidth = scrollWidth;
50
+ animationFrame = requestAnimationFrame(nextFrame);
51
+ }
52
+ animationFrame = requestAnimationFrame(nextFrame);
53
+ };
54
+ }, [scrollAreaRef]);
55
+ }
@@ -0,0 +1,148 @@
1
+ import React from 'react';
2
+ import type { Point } from '@lumx/react/utils/type';
3
+ import type { useAnimateScroll } from './useAnimateScroll';
4
+
5
+ /**
6
+ * Listen to mouse wheel + ctrl and multi-pointer pinch to zoom
7
+ */
8
+ export function usePointerZoom(
9
+ scrollAreaRef: React.RefObject<HTMLDivElement>,
10
+ onScaleChange: ((value: number) => void) | undefined,
11
+ animateScroll: ReturnType<typeof useAnimateScroll>,
12
+ ) {
13
+ const [isPointerZooming, setPointerZooming] = React.useState(false);
14
+ React.useEffect(() => {
15
+ const scrollArea = scrollAreaRef.current as HTMLDivElement;
16
+ if (!scrollArea || !onScaleChange) {
17
+ return undefined;
18
+ }
19
+
20
+ let animationFrame: number | null;
21
+ let zoomStateTimeoutId: ReturnType<typeof setTimeout> | null;
22
+
23
+ function updateScaleOnNextFrame(newScale: number, mousePosition: Point): void {
24
+ // Cancel previously scheduled frame
25
+ if (animationFrame) cancelAnimationFrame(animationFrame);
26
+
27
+ // Cancel previously scheduled zoom state change
28
+ if (zoomStateTimeoutId) clearTimeout(zoomStateTimeoutId);
29
+
30
+ function nextFrame() {
31
+ setPointerZooming(true);
32
+ onScaleChange?.(newScale);
33
+
34
+ animationFrame = null;
35
+ // Wait a bit before indicating the pointer zooming is finished
36
+ zoomStateTimeoutId = setTimeout(() => setPointerZooming(false), 100);
37
+ }
38
+ animationFrame = requestAnimationFrame(nextFrame);
39
+
40
+ // Animate scroll in parallel (centering on the current mouse position)
41
+ animateScroll(mousePosition, {
42
+ width: scrollArea.scrollWidth,
43
+ height: scrollArea.scrollHeight,
44
+ });
45
+ }
46
+
47
+ function onWheel(event: WheelEvent) {
48
+ if (!event.ctrlKey) {
49
+ return;
50
+ }
51
+ event.preventDefault();
52
+ const newScale = Math.exp(-event.deltaY / 50);
53
+
54
+ // Update scale on next frame (focused on the mouse position)
55
+ updateScaleOnNextFrame(newScale, {
56
+ x: event.pageX,
57
+ y: event.pageY,
58
+ });
59
+ }
60
+
61
+ const activePointers: Record<PointerEvent['pointerId'], PointerEvent> = {};
62
+ let prevDistance: number | null = null;
63
+ let previousCenterPoint: Point | null = null;
64
+
65
+ function onPointerDown(event: PointerEvent) {
66
+ activePointers[event.pointerId] = event;
67
+ }
68
+ function onPointerMove(event: PointerEvent) {
69
+ // Update pointer in cache
70
+ if (activePointers[event.pointerId]) {
71
+ activePointers[event.pointerId] = event;
72
+ }
73
+
74
+ const pointers = Object.values(activePointers);
75
+
76
+ // Make sure we run computation on one of the pointer in the group
77
+ if (pointers[0].pointerId !== event.pointerId) {
78
+ return;
79
+ }
80
+
81
+ // Centered point between all pointers
82
+ const centerPoint: Point = {
83
+ x: pointers.reduce((x, { clientX }) => x + clientX, 0) / pointers.length,
84
+ y: pointers.reduce((y, { clientY }) => y + clientY, 0) / pointers.length,
85
+ };
86
+
87
+ // Movement of the center point
88
+ const deltaCenterPoint = previousCenterPoint && {
89
+ left: previousCenterPoint.x - centerPoint.x,
90
+ top: previousCenterPoint.y - centerPoint.y,
91
+ };
92
+
93
+ // Pan X & Y
94
+ if (deltaCenterPoint) {
95
+ // Apply movement of the center point to the scroll
96
+ scrollArea.scrollBy({
97
+ top: deltaCenterPoint.top / 2,
98
+ left: deltaCenterPoint.left / 2,
99
+ });
100
+ }
101
+
102
+ // Pinch to zoom
103
+ if (pointers.length === 2) {
104
+ const [pointer1, pointer2] = pointers;
105
+ const distance = Math.hypot(pointer2.clientX - pointer1.clientX, pointer2.clientY - pointer1.clientY);
106
+
107
+ if (prevDistance && deltaCenterPoint) {
108
+ const delta = prevDistance - distance;
109
+ const absDelta = Math.abs(delta);
110
+
111
+ // Zoom only if we are "pinching" more than we are moving the pointers
112
+ if (absDelta > Math.abs(deltaCenterPoint.left) && absDelta > Math.abs(deltaCenterPoint.top)) {
113
+ // Update scale on next frame (focused on the center point between the two pointers)
114
+ const newScale = Math.exp(-delta / 100);
115
+ updateScaleOnNextFrame(newScale, centerPoint);
116
+ }
117
+ }
118
+
119
+ prevDistance = distance;
120
+ }
121
+
122
+ previousCenterPoint = centerPoint;
123
+ }
124
+ function onPointerUp(event: PointerEvent) {
125
+ prevDistance = null;
126
+ previousCenterPoint = null;
127
+ delete activePointers[event.pointerId];
128
+ }
129
+
130
+ scrollArea.addEventListener('wheel', onWheel, { passive: false });
131
+ const isMultiTouch = navigator.maxTouchPoints >= 2;
132
+ if (isMultiTouch) {
133
+ scrollArea.addEventListener('pointerdown', onPointerDown);
134
+ scrollArea.addEventListener('pointermove', onPointerMove);
135
+ scrollArea.addEventListener('pointerup', onPointerUp);
136
+ }
137
+ return () => {
138
+ scrollArea.removeEventListener('wheel', onWheel);
139
+ if (isMultiTouch) {
140
+ scrollArea.removeEventListener('pointerdown', onPointerDown);
141
+ scrollArea.removeEventListener('pointermove', onPointerMove);
142
+ scrollArea.removeEventListener('pointerup', onPointerUp);
143
+ }
144
+ };
145
+ }, [animateScroll, onScaleChange, scrollAreaRef]);
146
+
147
+ return isPointerZooming;
148
+ }
@@ -0,0 +1,50 @@
1
+ import React from 'react';
2
+
3
+ import type { IconButtonProps, LightboxProps, SlideshowProps, ThumbnailProps } from '@lumx/react';
4
+ import type { HasClassName } from '@lumx/react/utils/type';
5
+ import type { ImageCaptionMetadata } from '@lumx/react/components/image-block/ImageCaption';
6
+
7
+ export type InheritedSlideShowProps = Pick<SlideshowProps, 'slideshowControlsProps' | 'slideGroupLabel'>;
8
+
9
+ export interface ZoomButtonProps {
10
+ /** Zoom in button props */
11
+ zoomInButtonProps?: IconButtonProps;
12
+ /** Zoom out button props */
13
+ zoomOutButtonProps?: IconButtonProps;
14
+ }
15
+
16
+ export type InheritedThumbnailProps = Pick<
17
+ ThumbnailProps,
18
+ 'image' | 'alt' | 'imgProps' | 'imgRef' | 'loadingPlaceholderImageRef'
19
+ >;
20
+
21
+ export type InheritedImageMetadata = Pick<ImageCaptionMetadata, 'title' | 'description' | 'tags'>;
22
+
23
+ export type ImageProps = InheritedThumbnailProps & InheritedImageMetadata;
24
+
25
+ export interface ImagesProps {
26
+ /** Index of the active image to show on open */
27
+ activeImageIndex?: number;
28
+ /** List of images to display */
29
+ images: Array<ImageProps>;
30
+ /** Ref of the active image when the lightbox is open */
31
+ activeImageRef?: React.Ref<HTMLImageElement>;
32
+ }
33
+
34
+ export type InheritedLightboxProps = Pick<
35
+ LightboxProps,
36
+ 'isOpen' | 'parentElement' | 'onClose' | 'closeButtonProps' | 'aria-label' | 'aria-labelledby'
37
+ >;
38
+
39
+ export type ForwardedProps = React.ComponentPropsWithoutRef<'div'>;
40
+
41
+ /**
42
+ * ImageLightbox component props
43
+ */
44
+ export interface ImageLightboxProps
45
+ extends HasClassName,
46
+ ZoomButtonProps,
47
+ ImagesProps,
48
+ InheritedSlideShowProps,
49
+ InheritedLightboxProps,
50
+ ForwardedProps {}
@@ -0,0 +1,130 @@
1
+ import React from 'react';
2
+
3
+ import memoize from 'lodash/memoize';
4
+
5
+ import { startViewTransition } from '@lumx/react/utils/DOM/startViewTransition';
6
+ import { findImage } from '@lumx/react/utils/DOM/findImage';
7
+
8
+ import type { ImageLightboxProps } from './types';
9
+ import { CLASSNAME } from './constants';
10
+
11
+ /** Subset of the ImageLightboxProps managed by the useImageLightbox hook */
12
+ type ManagedProps = Pick<
13
+ ImageLightboxProps,
14
+ 'isOpen' | 'images' | 'parentElement' | 'activeImageRef' | 'onClose' | 'activeImageIndex'
15
+ >;
16
+
17
+ const EMPTY_PROPS: ManagedProps = { isOpen: false, images: [], parentElement: React.createRef() };
18
+
19
+ type TriggerOptions = Pick<ImageLightboxProps, 'activeImageIndex'>;
20
+
21
+ /**
22
+ * Set up an ImageLightbox with images and triggers.
23
+ *
24
+ * - Associate a trigger with the lightbox to properly focus the trigger on close
25
+ * - Associate a trigger with an image to display on open
26
+ * - Automatically provide a view transition between an image trigger and the displayed image on open & close
27
+ *
28
+ * @param initialProps Images to display in the image lightbox
29
+ */
30
+ export function useImageLightbox<P extends Partial<ImageLightboxProps>>(
31
+ initialProps: P,
32
+ ): {
33
+ /**
34
+ * Generates trigger props
35
+ * @param index Provide an index to choose which image to display when the image lightbox opens.
36
+ * */
37
+ getTriggerProps: (options?: TriggerOptions) => { onClick: React.MouseEventHandler; ref: React.Ref<any> };
38
+ /** Props to forward to the ImageLightbox */
39
+ imageLightboxProps: ManagedProps & P;
40
+ } {
41
+ const { images = [], ...otherProps } = initialProps;
42
+
43
+ const imagesPropsRef = React.useRef(images);
44
+ React.useEffect(() => {
45
+ imagesPropsRef.current = images.map((props) => ({ imgRef: React.createRef(), ...props }));
46
+ }, [images]);
47
+
48
+ const currentImageRef = React.useRef<HTMLImageElement>(null);
49
+ const [imageLightboxProps, setImageLightboxProps] = React.useState(
50
+ () => ({ ...EMPTY_PROPS, ...otherProps }) as ManagedProps & P,
51
+ );
52
+
53
+ const getTriggerProps = React.useMemo(() => {
54
+ const triggerImageRefs: Record<number, React.RefObject<HTMLImageElement>> = {};
55
+
56
+ async function close() {
57
+ const currentImage = currentImageRef.current;
58
+ if (!currentImage) {
59
+ return;
60
+ }
61
+ const currentIndex = imagesPropsRef.current.findIndex(
62
+ ({ imgRef }) => (imgRef as any)?.current === currentImage,
63
+ );
64
+
65
+ await startViewTransition({
66
+ changes() {
67
+ // Close lightbox
68
+ setImageLightboxProps((prevProps) => ({ ...prevProps, isOpen: false }));
69
+ },
70
+ // Morph from the image in lightbox to the image in trigger
71
+ viewTransitionName: {
72
+ source: currentImageRef,
73
+ target: triggerImageRefs[currentIndex],
74
+ name: CLASSNAME,
75
+ },
76
+ });
77
+ }
78
+
79
+ async function open(triggerElement: HTMLElement, { activeImageIndex }: TriggerOptions = {}) {
80
+ // If we find an image inside the trigger, animate it in transition with the opening image
81
+ const triggerImage = triggerImageRefs[activeImageIndex as any]?.current || findImage(triggerElement);
82
+
83
+ // Inject the trigger image as loading placeholder for better loading state
84
+ const imagesWithFallbackSize = imagesPropsRef.current.map((image, idx) => {
85
+ if (triggerImage && idx === activeImageIndex && !image.loadingPlaceholderImageRef) {
86
+ return { ...image, loadingPlaceholderImageRef: { current: triggerImage } };
87
+ }
88
+ return image;
89
+ });
90
+
91
+ await startViewTransition({
92
+ changes: () => {
93
+ // Open lightbox with setup props
94
+ setImageLightboxProps((prevProps) => ({
95
+ ...prevProps,
96
+ activeImageRef: currentImageRef,
97
+ parentElement: { current: triggerElement },
98
+ isOpen: true,
99
+ onClose: () => {
100
+ close();
101
+ prevProps?.onClose?.();
102
+ },
103
+ images: imagesWithFallbackSize,
104
+ activeImageIndex: activeImageIndex || 0,
105
+ }));
106
+ },
107
+ // Morph from the image in trigger to the image in lightbox
108
+ viewTransitionName: {
109
+ source: triggerImage,
110
+ target: currentImageRef,
111
+ name: CLASSNAME,
112
+ },
113
+ });
114
+ }
115
+
116
+ return memoize((options?: TriggerOptions) => ({
117
+ ref(element: HTMLElement | null) {
118
+ // Track trigger image ref if any
119
+ if (options?.activeImageIndex !== undefined && element) {
120
+ triggerImageRefs[options.activeImageIndex] = { current: findImage(element) };
121
+ }
122
+ },
123
+ onClick(e: React.MouseEvent) {
124
+ open(e.target as HTMLElement, options);
125
+ },
126
+ }));
127
+ }, []);
128
+
129
+ return { getTriggerProps, imageLightboxProps };
130
+ }
@@ -1,6 +1,7 @@
1
1
  import { CSSProperties, useEffect, useMemo, useState } from 'react';
2
2
  import { AspectRatio } from '@lumx/react/components';
3
3
  import { ThumbnailProps } from '@lumx/react/components/thumbnail/Thumbnail';
4
+ import { RectSize } from '@lumx/react/utils/type';
4
5
 
5
6
  // Calculate shift to center the focus point in the container.
6
7
  export function shiftPosition({
@@ -24,8 +25,6 @@ export function shiftPosition({
24
25
  return Math.floor(Math.max(Math.min(shift, 1), 0) * 100);
25
26
  }
26
27
 
27
- type Size = { width: number; height: number };
28
-
29
28
  // Compute CSS properties to apply the focus point.
30
29
  export const useFocusPointStyle = (
31
30
  { image, aspectRatio, focusPoint, imgProps: { width, height } = {} }: ThumbnailProps,
@@ -33,7 +32,7 @@ export const useFocusPointStyle = (
33
32
  isLoaded: boolean,
34
33
  ): CSSProperties => {
35
34
  // Get natural image size from imgProps or img element.
36
- const imageSize: Size | undefined = useMemo(() => {
35
+ const imageSize: RectSize | undefined = useMemo(() => {
37
36
  // Focus point is not applicable => exit early
38
37
  if (!image || aspectRatio === AspectRatio.original || (!focusPoint?.x && !focusPoint?.y)) return undefined;
39
38
  if (typeof width === 'number' && typeof height === 'number') return { width, height };
@@ -42,7 +41,7 @@ export const useFocusPointStyle = (
42
41
  }, [aspectRatio, element, focusPoint?.x, focusPoint?.y, height, image, isLoaded, width]);
43
42
 
44
43
  // Get container size (dependant on imageSize).
45
- const [containerSize, setContainerSize] = useState<Size | undefined>(undefined);
44
+ const [containerSize, setContainerSize] = useState<RectSize | undefined>(undefined);
46
45
  useEffect(
47
46
  function updateContainerSize() {
48
47
  const cWidth = element?.offsetWidth;
@@ -0,0 +1,32 @@
1
+ import React from 'react';
2
+
3
+ import throttle from 'lodash/throttle';
4
+ import { RectSize } from '@lumx/react/utils/type';
5
+
6
+ /**
7
+ * Observe element size (only works if it's size depends on the window size).
8
+ *
9
+ * (Not using ResizeObserver for better browser backward compat)
10
+ *
11
+ * @param elementRef Element to observe
12
+ * @return the size and a manual update callback
13
+ */
14
+ export function useElementSizeDependentOfWindowSize(
15
+ elementRef: React.RefObject<HTMLElement>,
16
+ ): [RectSize | null, () => void] {
17
+ const [size, setSize] = React.useState<null | RectSize>(null);
18
+ const updateSize = React.useMemo(
19
+ () =>
20
+ throttle(() => {
21
+ const newSize = elementRef.current?.getBoundingClientRect();
22
+ if (newSize) setSize(newSize);
23
+ }, 10),
24
+ [elementRef],
25
+ );
26
+ React.useEffect(() => {
27
+ updateSize();
28
+ window.addEventListener('resize', updateSize);
29
+ return () => window.removeEventListener('resize', updateSize);
30
+ }, [updateSize]);
31
+ return [size, updateSize];
32
+ }
@@ -0,0 +1,17 @@
1
+ import React from 'react';
2
+ import { RectSize } from '@lumx/react/utils/type';
3
+
4
+ /** Get natural image size after load. */
5
+ export function useImageSize(imgRef: React.RefObject<HTMLImageElement>, getInitialSize?: () => RectSize | null) {
6
+ const [imageSize, setImageSize] = React.useState<null | RectSize>(getInitialSize || null);
7
+ React.useEffect(() => {
8
+ const { current: img } = imgRef;
9
+ if (!img) {
10
+ return undefined;
11
+ }
12
+ const onLoad = () => setImageSize({ width: img.naturalWidth, height: img.naturalHeight });
13
+ img.addEventListener('load', onLoad);
14
+ return () => img.removeEventListener('load', onLoad);
15
+ }, [imgRef]);
16
+ return imageSize;
17
+ }
package/src/index.ts CHANGED
@@ -25,6 +25,7 @@ export * from './components/grid';
25
25
  export * from './components/grid-column';
26
26
  export * from './components/icon';
27
27
  export * from './components/image-block';
28
+ export * from './components/image-lightbox';
28
29
  export * from './components/inline-list';
29
30
  export * from './components/input-helper';
30
31
  export * from './components/input-label';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * File generated when storybook is started. Do not edit directly!
3
+ */
4
+ export default { title: 'LumX components/image-lightbox/ImageLightbox Demos' };
5
+
6
+ export { App as Default } from './default';
@@ -0,0 +1,3 @@
1
+ /** Find image in element including the element */
2
+ export const findImage = (element: HTMLElement | null): HTMLImageElement | null =>
3
+ element?.matches('img') ? (element as HTMLImageElement) : element?.querySelector('img') || null;