diff --git a/.changeset/neat-chefs-kiss.md b/.changeset/neat-chefs-kiss.md new file mode 100644 index 00000000..de0a1623 --- /dev/null +++ b/.changeset/neat-chefs-kiss.md @@ -0,0 +1,5 @@ +--- +'nuka-carousel': patch +--- + +Prevent divide by zero errors in measurements diff --git a/packages/nuka/src/hooks/use-measurement.test.tsx b/packages/nuka/src/hooks/use-measurement.test.tsx index 25e9a63e..44290577 100644 --- a/packages/nuka/src/hooks/use-measurement.test.tsx +++ b/packages/nuka/src/hooks/use-measurement.test.tsx @@ -22,6 +22,78 @@ describe('useMeasurement', () => { expect(scrollOffset).toEqual([]); }); + it('should return default values if offsetWidth is 0', () => { + const element = { + current: { + scrollWidth: 0, + offsetWidth: 0, + querySelector: () => ({ + children: [], + }), + }, + } as any; + + const { result } = renderHook(() => + useMeasurement({ + element, + scrollDistance: 'screen', + }), + ); + + const { totalPages, scrollOffset } = result.current; + + expect(totalPages).toBe(0); + expect(scrollOffset).toEqual([]); + }); + + it('should return default values if scrollDistance is 0', () => { + const element = { + current: { + scrollWidth: 1000, + offsetWidth: 500, + querySelector: () => ({ + children: [], + }), + }, + } as any; + + const { result } = renderHook(() => + useMeasurement({ + element, + scrollDistance: 0, + }), + ); + + const { totalPages, scrollOffset } = result.current; + + expect(totalPages).toBe(0); + expect(scrollOffset).toEqual([]); + }); + + it('should return default values if scrollDistance is < 0', () => { + const element = { + current: { + scrollWidth: 1000, + offsetWidth: 500, + querySelector: () => ({ + children: [], + }), + }, + } as any; + + const { result } = renderHook(() => + useMeasurement({ + element, + scrollDistance: -1, + }), + ); + + const { totalPages, scrollOffset } = result.current; + + expect(totalPages).toBe(0); + expect(scrollOffset).toEqual([]); + }); + it('should return measurements for screen', () => { const element = { current: { diff --git a/packages/nuka/src/hooks/use-measurement.tsx b/packages/nuka/src/hooks/use-measurement.tsx index a4ae89b3..6b3b7ef2 100644 --- a/packages/nuka/src/hooks/use-measurement.tsx +++ b/packages/nuka/src/hooks/use-measurement.tsx @@ -25,6 +25,8 @@ export function useMeasurement({ element, scrollDistance }: MeasurementProps) { const visibleWidth = container.offsetWidth; const remainder = scrollWidth - visibleWidth; + if (visibleWidth === 0) return; + switch (scrollDistance) { case 'screen': { const pageCount = Math.round(scrollWidth / visibleWidth); @@ -55,7 +57,7 @@ export function useMeasurement({ element, scrollDistance }: MeasurementProps) { break; } default: { - if (typeof scrollDistance === 'number') { + if (typeof scrollDistance === 'number' && scrollDistance > 0) { // find the number of pages required to scroll all the slides // to the end of the container const pageCount = Math.ceil(remainder / scrollDistance) + 1;