|
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 2 | +import { getBoundedPosition } from './getBoundedPosition'; |
| 3 | + |
| 4 | +describe('getBoundedPosition', () => { |
| 5 | + beforeEach(() => { |
| 6 | + vi.stubGlobal('window', { innerWidth: 1024, innerHeight: 768 }); |
| 7 | + }); |
| 8 | + |
| 9 | + afterEach(() => { |
| 10 | + vi.unstubAllGlobals(); |
| 11 | + vi.clearAllMocks(); |
| 12 | + }); |
| 13 | + |
| 14 | + it('returns the position if the window is undefined', () => { |
| 15 | + vi.stubGlobal('window', undefined); |
| 16 | + const position = getBoundedPosition({ |
| 17 | + draggableRef: { current: null }, |
| 18 | + position: { x: 100, y: 100 }, |
| 19 | + }); |
| 20 | + expect(position).toEqual({ x: 100, y: 100 }); |
| 21 | + }); |
| 22 | + |
| 23 | + it('returns the position if the draggableRef is null', () => { |
| 24 | + const position = getBoundedPosition({ |
| 25 | + draggableRef: { current: null }, |
| 26 | + position: { x: 100, y: 100 }, |
| 27 | + }); |
| 28 | + expect(position).toEqual({ x: 100, y: 100 }); |
| 29 | + }); |
| 30 | + |
| 31 | + it('bounds position within viewport considering minGapToEdge', () => { |
| 32 | + const mockElement = { |
| 33 | + getBoundingClientRect: () => ({ |
| 34 | + width: 100, |
| 35 | + height: 50, |
| 36 | + }), |
| 37 | + }; |
| 38 | + |
| 39 | + const cases = [ |
| 40 | + // Test left boundary |
| 41 | + { |
| 42 | + input: { x: -5, y: 100 }, |
| 43 | + expected: { x: 10, y: 100 }, |
| 44 | + }, |
| 45 | + // Test right boundary |
| 46 | + { |
| 47 | + input: { x: 1000, y: 100 }, |
| 48 | + expected: { x: 914, y: 100 }, // 1024 - 100 - 10 |
| 49 | + }, |
| 50 | + // Test top boundary |
| 51 | + { |
| 52 | + input: { x: 100, y: -5 }, |
| 53 | + expected: { x: 100, y: 10 }, |
| 54 | + }, |
| 55 | + // Test bottom boundary |
| 56 | + { |
| 57 | + input: { x: 100, y: 800 }, |
| 58 | + expected: { x: 100, y: 708 }, // 768 - 50 - 10 |
| 59 | + }, |
| 60 | + ]; |
| 61 | + |
| 62 | + for (const { input, expected } of cases) { |
| 63 | + const position = getBoundedPosition({ |
| 64 | + draggableRef: { current: mockElement as HTMLDivElement }, |
| 65 | + position: input, |
| 66 | + }); |
| 67 | + expect(position).toEqual(expected); |
| 68 | + } |
| 69 | + }); |
| 70 | + |
| 71 | + it('respects custom minGapToEdge', () => { |
| 72 | + const mockElement = { |
| 73 | + getBoundingClientRect: () => ({ |
| 74 | + width: 100, |
| 75 | + height: 50, |
| 76 | + }), |
| 77 | + }; |
| 78 | + |
| 79 | + const position = getBoundedPosition({ |
| 80 | + draggableRef: { current: mockElement as HTMLDivElement }, |
| 81 | + position: { x: -10, y: -10 }, |
| 82 | + minGapToEdge: 20, |
| 83 | + }); |
| 84 | + |
| 85 | + expect(position).toEqual({ x: 20, y: 20 }); |
| 86 | + }); |
| 87 | +}); |
0 commit comments