@lumx/react 3.7.6-alpha.8 → 3.7.6-test.0

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.
Files changed (31) hide show
  1. package/index.d.ts +1 -63
  2. package/index.js +551 -1286
  3. package/index.js.map +1 -1
  4. package/package.json +3 -3
  5. package/src/components/heading/Heading.test.tsx +3 -1
  6. package/src/components/heading/Heading.tsx +3 -2
  7. package/src/components/image-block/ImageBlock.stories.tsx +74 -63
  8. package/src/components/image-block/ImageBlock.tsx +1 -0
  9. package/src/components/image-block/ImageCaption.tsx +7 -7
  10. package/src/components/thumbnail/useFocusPointStyle.tsx +4 -3
  11. package/src/hooks/useOnResize.ts +41 -0
  12. package/src/index.ts +0 -1
  13. package/src/utils/type.ts +0 -15
  14. package/src/components/image-lightbox/ImageLightbox.stories.tsx +0 -165
  15. package/src/components/image-lightbox/ImageLightbox.test.tsx +0 -252
  16. package/src/components/image-lightbox/ImageLightbox.tsx +0 -72
  17. package/src/components/image-lightbox/constants.ts +0 -11
  18. package/src/components/image-lightbox/index.ts +0 -2
  19. package/src/components/image-lightbox/internal/ImageSlide.tsx +0 -106
  20. package/src/components/image-lightbox/internal/ImageSlideshow.tsx +0 -173
  21. package/src/components/image-lightbox/internal/useAnimateScroll.ts +0 -55
  22. package/src/components/image-lightbox/internal/usePointerZoom.ts +0 -148
  23. package/src/components/image-lightbox/types.ts +0 -47
  24. package/src/components/image-lightbox/useImageLightbox.tsx +0 -135
  25. package/src/hooks/useElementSizeDependentOfWindowSize.ts +0 -32
  26. package/src/hooks/useImageSize.ts +0 -17
  27. package/src/stories/generated/ImageLightbox/Demos.stories.tsx +0 -6
  28. package/src/utils/findImage.tsx +0 -3
  29. package/src/utils/getPrefersReducedMotion.ts +0 -6
  30. package/src/utils/startViewTransition.ts +0 -54
  31. package/src/utils/unref.ts +0 -6
@@ -1,148 +0,0 @@
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
- }
@@ -1,47 +0,0 @@
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<ThumbnailProps, 'image' | 'alt' | 'imgProps' | 'imgRef'>;
17
-
18
- export type InheritedImageMetadata = Pick<ImageCaptionMetadata, 'title' | 'description' | 'tags'>;
19
-
20
- export type ImageProps = InheritedThumbnailProps & InheritedImageMetadata;
21
-
22
- export interface ImagesProps {
23
- /** Index of the active image to show on open */
24
- activeImageIndex?: number;
25
- /** List of images to display */
26
- images: Array<ImageProps>;
27
- /** Ref of the active image when the lightbox is open */
28
- activeImageRef?: React.Ref<HTMLImageElement>;
29
- }
30
-
31
- export type InheritedLightboxProps = Pick<
32
- LightboxProps,
33
- 'isOpen' | 'parentElement' | 'onClose' | 'closeButtonProps' | 'aria-label' | 'aria-labelledby'
34
- >;
35
-
36
- export type ForwardedProps = React.ComponentPropsWithoutRef<'div'>;
37
-
38
- /**
39
- * ImageLightbox component props
40
- */
41
- export interface ImageLightboxProps
42
- extends HasClassName,
43
- ZoomButtonProps,
44
- ImagesProps,
45
- InheritedSlideShowProps,
46
- InheritedLightboxProps,
47
- ForwardedProps {}
@@ -1,135 +0,0 @@
1
- import React from 'react';
2
-
3
- import memoize from 'lodash/memoize';
4
-
5
- import { startViewTransition } from '@lumx/react/utils/startViewTransition';
6
- import { findImage } from '@lumx/react/utils/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: P & ManagedProps;
40
- } {
41
- const { images = [], ...otherProps } = initialProps;
42
-
43
- const basePropsRef = React.useRef(EMPTY_PROPS as P & ManagedProps);
44
- React.useEffect(() => {
45
- basePropsRef.current = { ...EMPTY_PROPS, ...otherProps } as P & ManagedProps;
46
- }, [otherProps]);
47
-
48
- const imagesPropsRef = React.useRef(images);
49
- React.useEffect(() => {
50
- imagesPropsRef.current = images.map((props) => ({ imgRef: React.createRef(), ...props }));
51
- }, [images]);
52
-
53
- const currentImageRef = React.useRef<HTMLImageElement>(null);
54
- const [imageLightboxProps, setImageLightboxProps] = React.useState<P & ManagedProps>(basePropsRef.current);
55
-
56
- const getTriggerProps = React.useMemo(() => {
57
- const triggerImageRefs: Record<number, React.RefObject<HTMLImageElement>> = {};
58
-
59
- async function closeLightbox() {
60
- const currentImage = currentImageRef.current;
61
- if (!currentImage) {
62
- return;
63
- }
64
- const currentIndex = imagesPropsRef.current.findIndex(
65
- ({ imgRef }) => (imgRef as any)?.current === currentImage,
66
- );
67
-
68
- await startViewTransition({
69
- changes() {
70
- // Close lightbox with reset empty props
71
- setImageLightboxProps(({ parentElement }) => ({ ...basePropsRef.current, parentElement }));
72
- },
73
- // Morph from the image in lightbox to the image in trigger
74
- viewTransitionName: {
75
- source: currentImageRef,
76
- target: triggerImageRefs[currentIndex],
77
- name: CLASSNAME,
78
- },
79
- });
80
- }
81
-
82
- async function openLightbox(triggerElement: HTMLElement, { activeImageIndex }: TriggerOptions = {}) {
83
- // If we find an image inside the trigger, animate it in transition with the opening image
84
- const triggerImage = triggerImageRefs[activeImageIndex as any]?.current || findImage(triggerElement);
85
-
86
- // Inject the trigger image size as a fallback for better loading state
87
- const imagesWithFallbackSize = imagesPropsRef.current.map((image, idx) => {
88
- if (triggerImage && idx === activeImageIndex && !image.imgProps?.width && !image.imgProps?.height) {
89
- const imgProps = {
90
- ...image.imgProps,
91
- height: triggerImage.naturalHeight,
92
- width: triggerImage.naturalWidth,
93
- };
94
- return { ...image, imgProps };
95
- }
96
- return image;
97
- });
98
-
99
- await startViewTransition({
100
- changes: () => {
101
- // Open lightbox with setup props
102
- setImageLightboxProps({
103
- ...basePropsRef.current,
104
- activeImageRef: currentImageRef,
105
- parentElement: { current: triggerElement },
106
- isOpen: true,
107
- onClose: closeLightbox,
108
- images: imagesWithFallbackSize,
109
- activeImageIndex: activeImageIndex || 0,
110
- });
111
- },
112
- // Morph from the image in trigger to the image in lightbox
113
- viewTransitionName: {
114
- source: triggerImage,
115
- target: currentImageRef,
116
- name: CLASSNAME,
117
- },
118
- });
119
- }
120
-
121
- return memoize((options?: TriggerOptions) => ({
122
- ref(element: HTMLElement | null) {
123
- // Track trigger image ref if any
124
- if (options?.activeImageIndex !== undefined && element) {
125
- triggerImageRefs[options.activeImageIndex] = { current: findImage(element) };
126
- }
127
- },
128
- onClick(e: React.MouseEvent) {
129
- openLightbox(e.target as HTMLElement, options);
130
- },
131
- }));
132
- }, []);
133
-
134
- return { getTriggerProps, imageLightboxProps };
135
- }
@@ -1,32 +0,0 @@
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
- }
@@ -1,17 +0,0 @@
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
- }
@@ -1,6 +0,0 @@
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';
@@ -1,3 +0,0 @@
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;
@@ -1,6 +0,0 @@
1
- import { WINDOW } from '@lumx/react/constants';
2
-
3
- /** Check if user prefers reduced motion */
4
- export function getPrefersReducedMotion() {
5
- return WINDOW?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
6
- }
@@ -1,54 +0,0 @@
1
- import ReactDOM from 'react-dom';
2
- import { getPrefersReducedMotion } from '@lumx/react/utils/getPrefersReducedMotion';
3
- import { MaybeElementOrRef } from '@lumx/react/utils/type';
4
- import { unref } from '@lumx/react/utils/unref';
5
-
6
- function setTransitionViewName(elementRef: MaybeElementOrRef<HTMLElement>, name: string | null | undefined) {
7
- const element = unref(elementRef) as any;
8
- if (element) element.style.viewTransitionName = name;
9
- }
10
-
11
- /**
12
- * Wrapper around the `document.startViewTransition` handling browser incompatibilities, react DOM flush and
13
- * user preference.
14
- *
15
- * @param changes callback containing the changes to apply within the view transition.
16
- * @param setViewTransitionName set the `viewTransitionName` style on a `source` & `target` to morph these elements.
17
- */
18
- export async function startViewTransition({
19
- changes,
20
- viewTransitionName,
21
- }: {
22
- changes: () => void;
23
- viewTransitionName: {
24
- source: MaybeElementOrRef<HTMLElement>;
25
- target: MaybeElementOrRef<HTMLElement>;
26
- name: string;
27
- };
28
- }) {
29
- const start = (document as any)?.startViewTransition?.bind(document);
30
- const prefersReducedMotion = getPrefersReducedMotion();
31
- const { flushSync } = ReactDOM as any;
32
- if (prefersReducedMotion || !start || !flushSync || !viewTransitionName?.source || !viewTransitionName?.target) {
33
- // Skip, apply changes without a transition
34
- changes();
35
- return;
36
- }
37
-
38
- // Set transition name on source element
39
- setTransitionViewName(viewTransitionName.source, viewTransitionName.name);
40
-
41
- // Start view transition, apply changes & flush to DOM
42
- await start(() => {
43
- // Un-set transition name on source element
44
- setTransitionViewName(viewTransitionName.source, null);
45
-
46
- flushSync(changes);
47
-
48
- // Set transition name on target element
49
- setTransitionViewName(viewTransitionName.target, viewTransitionName.name);
50
- }).updateCallbackDone;
51
-
52
- // Un-set transition name on target element
53
- setTransitionViewName(viewTransitionName.target, null);
54
- }
@@ -1,6 +0,0 @@
1
- import { MaybeElementOrRef } from '@lumx/react/utils/type';
2
-
3
- export function unref(maybeElement: MaybeElementOrRef<HTMLElement>) {
4
- if (maybeElement instanceof HTMLElement) return maybeElement;
5
- return maybeElement?.current;
6
- }