@appica/ui-react 1.2.0 → 1.3.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.
Files changed (172) hide show
  1. package/CHANGELOG.md +61 -15
  2. package/agent-rules.md +2 -0
  3. package/appica.css +1 -1
  4. package/dist/components/alert-dialog/alert-dialog.js +1 -1
  5. package/dist/components/alert-dialog/alert-dialog.js.map +1 -1
  6. package/dist/components/autocomplete/autocomplete.d.ts.map +1 -1
  7. package/dist/components/autocomplete/autocomplete.js +3 -7
  8. package/dist/components/autocomplete/autocomplete.js.map +1 -1
  9. package/dist/components/badge/badge.js +1 -1
  10. package/dist/components/badge/badge.js.map +1 -1
  11. package/dist/components/breadcrumb/breadcrumb.js +2 -2
  12. package/dist/components/breadcrumb/breadcrumb.js.map +1 -1
  13. package/dist/components/button/button-variants.js +1 -1
  14. package/dist/components/button/button-variants.js.map +1 -1
  15. package/dist/components/calendar/calendar.js +1 -1
  16. package/dist/components/calendar/calendar.js.map +1 -1
  17. package/dist/components/carousel/carousel.d.ts +2 -10
  18. package/dist/components/carousel/carousel.d.ts.map +1 -1
  19. package/dist/components/carousel/carousel.js +153 -33
  20. package/dist/components/carousel/carousel.js.map +1 -1
  21. package/dist/components/color-area/color-area.d.ts.map +1 -1
  22. package/dist/components/color-area/color-area.js +1 -0
  23. package/dist/components/color-area/color-area.js.map +1 -1
  24. package/dist/components/color-slider/color-slider.d.ts.map +1 -1
  25. package/dist/components/color-slider/color-slider.js +1 -0
  26. package/dist/components/color-slider/color-slider.js.map +1 -1
  27. package/dist/components/color-swatch-picker/color-swatch-picker.js +1 -1
  28. package/dist/components/color-swatch-picker/color-swatch-picker.js.map +1 -1
  29. package/dist/components/combobox/combobox.d.ts +5 -4
  30. package/dist/components/combobox/combobox.d.ts.map +1 -1
  31. package/dist/components/combobox/combobox.js +5 -8
  32. package/dist/components/combobox/combobox.js.map +1 -1
  33. package/dist/components/compare-slider/compare-slider.d.ts +50 -0
  34. package/dist/components/compare-slider/compare-slider.d.ts.map +1 -0
  35. package/dist/components/compare-slider/compare-slider.js +321 -0
  36. package/dist/components/compare-slider/compare-slider.js.map +1 -0
  37. package/dist/components/context-menu/context-menu.js +1 -1
  38. package/dist/components/context-menu/context-menu.js.map +1 -1
  39. package/dist/components/copy-button/copy-button.d.ts +2 -2
  40. package/dist/components/copy-button/copy-button.d.ts.map +1 -1
  41. package/dist/components/copy-button/copy-button.js +49 -46
  42. package/dist/components/copy-button/copy-button.js.map +1 -1
  43. package/dist/components/date-field/date-field.d.ts.map +1 -1
  44. package/dist/components/date-field/date-field.js +7 -0
  45. package/dist/components/date-field/date-field.js.map +1 -1
  46. package/dist/components/date-picker/date-picker.d.ts +10 -0
  47. package/dist/components/date-picker/date-picker.d.ts.map +1 -1
  48. package/dist/components/date-picker/date-picker.js +14 -0
  49. package/dist/components/date-picker/date-picker.js.map +1 -1
  50. package/dist/components/dialog/dialog.js +1 -1
  51. package/dist/components/dialog/dialog.js.map +1 -1
  52. package/dist/components/dropdown-menu/dropdown-menu.d.ts +13 -2
  53. package/dist/components/dropdown-menu/dropdown-menu.d.ts.map +1 -1
  54. package/dist/components/dropdown-menu/dropdown-menu.js +109 -4
  55. package/dist/components/dropdown-menu/dropdown-menu.js.map +1 -1
  56. package/dist/components/field/field.d.ts.map +1 -1
  57. package/dist/components/field/field.js +1 -0
  58. package/dist/components/field/field.js.map +1 -1
  59. package/dist/components/loader/loader.d.ts +1 -1
  60. package/dist/components/loader/loader.d.ts.map +1 -1
  61. package/dist/components/loader/loader.js +7 -5
  62. package/dist/components/loader/loader.js.map +1 -1
  63. package/dist/components/navigation/navigation-link-variants.js +1 -1
  64. package/dist/components/navigation/navigation-link-variants.js.map +1 -1
  65. package/dist/components/navigation-menu/navigation-menu.js +1 -1
  66. package/dist/components/navigation-menu/navigation-menu.js.map +1 -1
  67. package/dist/components/number-field/number-field.d.ts +1 -1
  68. package/dist/components/number-field/number-field.d.ts.map +1 -1
  69. package/dist/components/number-field/number-field.js +7 -0
  70. package/dist/components/number-field/number-field.js.map +1 -1
  71. package/dist/components/pagination/pagination.d.ts.map +1 -1
  72. package/dist/components/pagination/pagination.js +1 -2
  73. package/dist/components/pagination/pagination.js.map +1 -1
  74. package/dist/components/popover/popover.js +1 -1
  75. package/dist/components/popover/popover.js.map +1 -1
  76. package/dist/components/preview-card/preview-card.js +1 -1
  77. package/dist/components/preview-card/preview-card.js.map +1 -1
  78. package/dist/components/select/select.js +2 -2
  79. package/dist/components/select/select.js.map +1 -1
  80. package/dist/components/slider/slider.d.ts.map +1 -1
  81. package/dist/components/slider/slider.js +2 -1
  82. package/dist/components/slider/slider.js.map +1 -1
  83. package/dist/components/sparkline/sparkline.d.ts.map +1 -1
  84. package/dist/components/sparkline/sparkline.js +1 -0
  85. package/dist/components/sparkline/sparkline.js.map +1 -1
  86. package/dist/components/spinner/spinner.d.ts +1 -1
  87. package/dist/components/spinner/spinner.d.ts.map +1 -1
  88. package/dist/components/spinner/spinner.js +7 -5
  89. package/dist/components/spinner/spinner.js.map +1 -1
  90. package/dist/components/tabs/tabs.js +1 -1
  91. package/dist/components/tabs/tabs.js.map +1 -1
  92. package/dist/components/thumbnail/thumbnail.d.ts +6 -1
  93. package/dist/components/thumbnail/thumbnail.d.ts.map +1 -1
  94. package/dist/components/thumbnail/thumbnail.js +2 -0
  95. package/dist/components/thumbnail/thumbnail.js.map +1 -1
  96. package/dist/components/time-field/time-field.d.ts.map +1 -1
  97. package/dist/components/time-field/time-field.js +7 -0
  98. package/dist/components/time-field/time-field.js.map +1 -1
  99. package/dist/components/tooltip/tooltip.js +1 -1
  100. package/dist/components/tooltip/tooltip.js.map +1 -1
  101. package/dist/hooks/use-media-query.d.ts +0 -4
  102. package/dist/hooks/use-media-query.d.ts.map +1 -1
  103. package/dist/hooks/use-media-query.js.map +1 -1
  104. package/dist/index.d.ts +1 -0
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +3 -2
  107. package/dist/index.js.map +1 -1
  108. package/dist/internal/utils.d.ts.map +1 -1
  109. package/dist/internal/utils.js +2 -1
  110. package/dist/internal/utils.js.map +1 -1
  111. package/package.json +28 -23
  112. package/src/components/alert-dialog/alert-dialog.tsx +1 -1
  113. package/src/components/autocomplete/autocomplete.test.tsx +33 -0
  114. package/src/components/autocomplete/autocomplete.tsx +3 -7
  115. package/src/components/badge/badge.tsx +1 -1
  116. package/src/components/breadcrumb/breadcrumb.test.tsx +57 -2
  117. package/src/components/breadcrumb/breadcrumb.tsx +2 -2
  118. package/src/components/button/button-variants.ts +1 -1
  119. package/src/components/calendar/calendar.tsx +1 -1
  120. package/src/components/carousel/carousel.test.tsx +526 -12
  121. package/src/components/carousel/carousel.tsx +173 -42
  122. package/src/components/chip/chip.test.tsx +4 -5
  123. package/src/components/color-area/color-area.test.tsx +5 -0
  124. package/src/components/color-area/color-area.tsx +1 -0
  125. package/src/components/color-slider/color-slider.test.tsx +5 -0
  126. package/src/components/color-slider/color-slider.tsx +1 -0
  127. package/src/components/color-swatch-picker/color-swatch-picker.tsx +1 -1
  128. package/src/components/combobox/combobox.test.tsx +66 -0
  129. package/src/components/combobox/combobox.tsx +14 -11
  130. package/src/components/compare-slider/compare-slider.test.tsx +261 -0
  131. package/src/components/compare-slider/compare-slider.tsx +397 -0
  132. package/src/components/context-menu/context-menu.test.tsx +2 -1
  133. package/src/components/context-menu/context-menu.tsx +1 -1
  134. package/src/components/copy-button/copy-button.test.tsx +68 -3
  135. package/src/components/copy-button/copy-button.tsx +49 -43
  136. package/src/components/date-field/date-field.test.tsx +82 -0
  137. package/src/components/date-field/date-field.tsx +7 -0
  138. package/src/components/date-picker/date-picker.test.tsx +70 -0
  139. package/src/components/date-picker/date-picker.tsx +26 -0
  140. package/src/components/dialog/dialog.tsx +1 -1
  141. package/src/components/dropdown-menu/dropdown-menu.test.tsx +190 -1
  142. package/src/components/dropdown-menu/dropdown-menu.tsx +129 -3
  143. package/src/components/field/field.test.tsx +34 -0
  144. package/src/components/field/field.tsx +1 -0
  145. package/src/components/loader/loader.test.tsx +17 -4
  146. package/src/components/loader/loader.tsx +2 -2
  147. package/src/components/navigation/navigation-link-variants.ts +1 -1
  148. package/src/components/navigation-menu/navigation-menu.tsx +2 -2
  149. package/src/components/number-field/number-field.test.tsx +59 -0
  150. package/src/components/number-field/number-field.tsx +8 -0
  151. package/src/components/pagination/pagination.test.tsx +83 -0
  152. package/src/components/pagination/pagination.tsx +1 -2
  153. package/src/components/popover/popover.tsx +1 -1
  154. package/src/components/preview-card/preview-card.tsx +1 -1
  155. package/src/components/select/select.tsx +2 -2
  156. package/src/components/slider/slider.test.tsx +5 -0
  157. package/src/components/slider/slider.tsx +2 -1
  158. package/src/components/sparkline/sparkline.test.tsx +16 -0
  159. package/src/components/sparkline/sparkline.tsx +1 -0
  160. package/src/components/spinner/spinner.test.tsx +17 -4
  161. package/src/components/spinner/spinner.tsx +2 -2
  162. package/src/components/tabs/tabs.tsx +1 -1
  163. package/src/components/thumbnail/thumbnail.test.tsx +8 -0
  164. package/src/components/thumbnail/thumbnail.tsx +7 -0
  165. package/src/components/time-field/time-field.test.tsx +64 -0
  166. package/src/components/time-field/time-field.tsx +7 -0
  167. package/src/components/tooltip/tooltip.tsx +1 -1
  168. package/src/hooks/use-media-query.ts +0 -4
  169. package/src/index.ts +1 -0
  170. package/src/internal/utils.test.tsx +8 -1
  171. package/src/internal/utils.ts +4 -1
  172. package/styles.css +4 -0
@@ -0,0 +1,261 @@
1
+ import * as React from 'react'
2
+ import { act, fireEvent, render, screen, within } from '@testing-library/react'
3
+ import userEvent from '@testing-library/user-event'
4
+ import { afterEach, describe, expect, it, vi } from 'vitest'
5
+ import { axe } from 'vitest-axe'
6
+ import { CompareSlider, type CompareSliderProps } from './compare-slider'
7
+ import { DirectionProvider } from '../../providers/direction-provider'
8
+
9
+ const RECT = { x: 0, y: 0, top: 0, left: 0, right: 200, bottom: 100, width: 200, height: 100 }
10
+
11
+ function stubSize() {
12
+ vi.spyOn(HTMLDivElement.prototype, 'getBoundingClientRect').mockImplementation(
13
+ () => ({ ...RECT, toJSON: () => RECT }) as DOMRect,
14
+ )
15
+ }
16
+
17
+ class MockIntersectionObserver {
18
+ static instances: MockIntersectionObserver[] = []
19
+ callback: IntersectionObserverCallback
20
+ constructor(callback: IntersectionObserverCallback) {
21
+ this.callback = callback
22
+ MockIntersectionObserver.instances.push(this)
23
+ }
24
+ observe = () => {}
25
+ unobserve = () => {}
26
+ disconnect = () => {}
27
+ takeRecords = () => []
28
+ }
29
+
30
+ function renderSlider(props: Partial<CompareSliderProps> = {}) {
31
+ return render(
32
+ <CompareSlider
33
+ data-testid="root"
34
+ aria-label="Compare the sketch with the room"
35
+ before={<img alt="Sketch" src="/sketch.png" />}
36
+ after={<img alt="Room" src="/room.jpg" />}
37
+ {...props}
38
+ />,
39
+ )
40
+ }
41
+
42
+ const slider = () => screen.getByRole('slider') as HTMLInputElement
43
+ const root = () => screen.getByTestId('root')
44
+ const layer = (side: 'before' | 'after') => root().querySelector(`[data-slot="compare-slider-${side}"]`) as HTMLElement
45
+
46
+ afterEach(() => {
47
+ vi.restoreAllMocks()
48
+ vi.unstubAllGlobals()
49
+ MockIntersectionObserver.instances = []
50
+ })
51
+
52
+ describe('CompareSlider', () => {
53
+ it('renders both layers around a labeled slider set to 50', () => {
54
+ renderSlider()
55
+ expect(screen.getByRole('img', { name: 'Sketch' })).toBeInTheDocument()
56
+ expect(screen.getByRole('img', { name: 'Room' })).toBeInTheDocument()
57
+ expect(slider()).toHaveAccessibleName('Compare the sketch with the room')
58
+ expect(slider()).toHaveValue('50')
59
+ expect(root()).toHaveAttribute('data-orientation', 'horizontal')
60
+ })
61
+
62
+ it('clips each layer to its side of the divider, starting at defaultValue', () => {
63
+ renderSlider({ defaultValue: 30 })
64
+ expect(slider()).toHaveValue('30')
65
+ expect(layer('before').style.clipPath).toBe('inset(0 70% 0 0)')
66
+ expect(layer('after').style.clipPath).toBe('inset(0 0 0 30%)')
67
+ })
68
+
69
+ it('puts before on the right in a right-to-left layout', () => {
70
+ render(
71
+ <DirectionProvider dir="rtl">
72
+ <CompareSlider data-testid="root" aria-label="Compare" defaultValue={30} before="Before" after="After" />
73
+ </DirectionProvider>,
74
+ )
75
+ expect(layer('before').style.clipPath).toBe('inset(0 0 0 70%)')
76
+ expect(layer('after').style.clipPath).toBe('inset(0 30% 0 0)')
77
+ })
78
+
79
+ it('stacks before above after when vertical', () => {
80
+ renderSlider({ orientation: 'vertical', defaultValue: 30 })
81
+ expect(root()).toHaveAttribute('data-orientation', 'vertical')
82
+ expect(slider()).toHaveAttribute('aria-orientation', 'vertical')
83
+ expect(layer('before').style.clipPath).toBe('inset(0 0 70% 0)')
84
+ expect(layer('after').style.clipPath).toBe('inset(30% 0 0 0)')
85
+ })
86
+
87
+ it('moves the divider to a mouse press, follows the drag and commits on release', async () => {
88
+ stubSize()
89
+ const onValueChange = vi.fn()
90
+ const onValueCommitted = vi.fn()
91
+ const user = userEvent.setup()
92
+ renderSlider({ onValueChange, onValueCommitted })
93
+
94
+ await user.pointer([
95
+ { keys: '[MouseLeft>]', target: root(), coords: { clientX: 50, clientY: 50 } },
96
+ { target: root(), coords: { clientX: 150, clientY: 50 } },
97
+ ])
98
+ expect(onValueChange).toHaveBeenNthCalledWith(1, 25)
99
+ expect(slider()).toHaveValue('75')
100
+ expect(root()).toHaveAttribute('data-dragging')
101
+ expect(onValueCommitted).not.toHaveBeenCalled()
102
+
103
+ await user.pointer({ keys: '[/MouseLeft]', target: root() })
104
+ expect(onValueCommitted).toHaveBeenCalledExactlyOnceWith(75)
105
+ expect(root()).not.toHaveAttribute('data-dragging')
106
+ })
107
+
108
+ it('leaves a touch swipe across the axis to the page, and follows one along it', async () => {
109
+ stubSize()
110
+ const user = userEvent.setup()
111
+ renderSlider()
112
+
113
+ await user.pointer([
114
+ { keys: '[TouchA>]', target: root(), coords: { clientX: 100, clientY: 10 } },
115
+ { pointerName: 'TouchA', target: root(), coords: { clientX: 104, clientY: 60 } },
116
+ { keys: '[/TouchA]', target: root() },
117
+ ])
118
+ expect(slider()).toHaveValue('50')
119
+
120
+ await user.pointer([
121
+ { keys: '[TouchA>]', target: root(), coords: { clientX: 100, clientY: 50 } },
122
+ { pointerName: 'TouchA', target: root(), coords: { clientX: 60, clientY: 52 } },
123
+ { pointerName: 'TouchA', target: root(), coords: { clientX: 40, clientY: 52 } },
124
+ { keys: '[/TouchA]', target: root() },
125
+ ])
126
+ expect(slider()).toHaveValue('20')
127
+ })
128
+
129
+ it('moves the divider to a tap, but not to a touch the page takes over for scrolling', async () => {
130
+ stubSize()
131
+ const onValueCommitted = vi.fn()
132
+ const user = userEvent.setup()
133
+ renderSlider({ onValueCommitted })
134
+
135
+ await user.pointer({ keys: '[TouchA]', target: root(), coords: { clientX: 40, clientY: 50 } })
136
+ expect(slider()).toHaveValue('20')
137
+ expect(onValueCommitted).toHaveBeenCalledExactlyOnceWith(20)
138
+
139
+ fireEvent.pointerDown(root(), { pointerType: 'touch', pointerId: 2, clientX: 150, clientY: 50 })
140
+ expect(root()).toHaveAttribute('data-dragging')
141
+ fireEvent.pointerCancel(root(), { pointerType: 'touch', pointerId: 2, clientX: 150, clientY: 50 })
142
+ expect(root()).not.toHaveAttribute('data-dragging')
143
+ expect(slider()).toHaveValue('20')
144
+ expect(onValueCommitted).toHaveBeenCalledTimes(1)
145
+ })
146
+
147
+ it('steps with the arrow keys, by 10 with Shift, and jumps to the ends with Home and End', async () => {
148
+ const onValueCommitted = vi.fn()
149
+ const user = userEvent.setup()
150
+ renderSlider({ onValueCommitted })
151
+
152
+ slider().focus()
153
+ await user.keyboard('{ArrowRight}')
154
+ expect(slider()).toHaveValue('51')
155
+ expect(onValueCommitted).toHaveBeenLastCalledWith(51)
156
+ await user.keyboard('{Shift>}{ArrowLeft}{/Shift}')
157
+ expect(slider()).toHaveValue('41')
158
+ await user.keyboard('{Home}')
159
+ expect(slider()).toHaveValue('0')
160
+ await user.keyboard('{End}')
161
+ expect(slider()).toHaveValue('100')
162
+ })
163
+
164
+ it('moves the divider the way the arrow points, in RTL and when vertical', async () => {
165
+ const user = userEvent.setup()
166
+ const { unmount } = render(
167
+ <DirectionProvider dir="rtl">
168
+ <CompareSlider aria-label="Compare" before="Before" after="After" />
169
+ </DirectionProvider>,
170
+ )
171
+ slider().focus()
172
+ await user.keyboard('{ArrowLeft}')
173
+ expect(slider()).toHaveValue('51')
174
+ unmount()
175
+
176
+ renderSlider({ orientation: 'vertical' })
177
+ slider().focus()
178
+ await user.keyboard('{ArrowDown}')
179
+ expect(slider()).toHaveValue('51')
180
+ await user.keyboard('{ArrowUp}{ArrowUp}')
181
+ expect(slider()).toHaveValue('49')
182
+ })
183
+
184
+ it('reports changes but holds its position while controlled', async () => {
185
+ const onValueChange = vi.fn()
186
+ const user = userEvent.setup()
187
+ const { rerender } = renderSlider({ value: 20, onValueChange })
188
+
189
+ slider().focus()
190
+ await user.keyboard('{ArrowRight}')
191
+ expect(onValueChange).toHaveBeenCalledWith(21)
192
+ expect(slider()).toHaveValue('20')
193
+
194
+ rerender(<CompareSlider aria-label="Compare" value={60} before="Before" after="After" />)
195
+ expect(slider()).toHaveValue('60')
196
+ })
197
+
198
+ it('draws a double arrow that follows orientation, and takes a replacement icon', () => {
199
+ const handlePath = () => root().querySelector('[data-slot="compare-slider-handle"] path')?.getAttribute('d')
200
+ const { rerender } = renderSlider()
201
+ const horizontal = handlePath()
202
+ rerender(<CompareSlider data-testid="root" orientation="vertical" before="Before" after="After" />)
203
+ expect(handlePath()).not.toBe(horizontal)
204
+
205
+ rerender(
206
+ <CompareSlider data-testid="root" icon={<svg data-testid="custom-icon" />} before="Before" after="After" />,
207
+ )
208
+ expect(screen.getByTestId('custom-icon')).toBeInTheDocument()
209
+ expect(root().querySelectorAll('[data-slot="compare-slider-handle"] svg')).toHaveLength(1)
210
+ })
211
+
212
+ it('pins each label inside its own layer, so it clips with that side', () => {
213
+ const { rerender } = renderSlider({ beforeLabel: 'Drawing', afterLabel: 'Photo' })
214
+ expect(within(layer('before')).getByText('Drawing')).toHaveAttribute('data-slot', 'compare-slider-label')
215
+ expect(within(layer('after')).getByText('Photo')).toHaveAttribute('data-slot', 'compare-slider-label')
216
+
217
+ rerender(<CompareSlider data-testid="root" before="Before" after="After" />)
218
+ expect(root().querySelector('[data-slot="compare-slider-label"]')).toBeNull()
219
+ })
220
+
221
+ it('opens on before alone with reveal, then moves to defaultValue once in view', () => {
222
+ vi.stubGlobal('IntersectionObserver', MockIntersectionObserver)
223
+ renderSlider({ reveal: true, defaultValue: 40 })
224
+ expect(slider()).toHaveValue('100')
225
+ expect(layer('after').style.clipPath).toBe('inset(0 0 0 100%)')
226
+
227
+ act(() => {
228
+ MockIntersectionObserver.instances[0]!.callback(
229
+ [{ isIntersecting: true } as IntersectionObserverEntry],
230
+ MockIntersectionObserver.instances[0] as unknown as IntersectionObserver,
231
+ )
232
+ })
233
+ expect(slider()).toHaveValue('40')
234
+ })
235
+
236
+ it('ignores presses and keys while disabled', async () => {
237
+ stubSize()
238
+ const onValueChange = vi.fn()
239
+ const user = userEvent.setup()
240
+ renderSlider({ disabled: true, onValueChange })
241
+
242
+ expect(slider()).toBeDisabled()
243
+ expect(root()).toHaveAttribute('data-disabled')
244
+ await user.pointer({ keys: '[MouseLeft]', target: root(), coords: { clientX: 20, clientY: 50 } })
245
+ expect(onValueChange).not.toHaveBeenCalled()
246
+ expect(slider()).toHaveValue('50')
247
+ })
248
+
249
+ it('claims drags along its own axis from a surrounding Drawer', () => {
250
+ const { unmount } = renderSlider()
251
+ expect(root()).toHaveAttribute('data-base-ui-swipe-ignore', 'x')
252
+ unmount()
253
+ renderSlider({ orientation: 'vertical' })
254
+ expect(root()).toHaveAttribute('data-base-ui-swipe-ignore', 'y')
255
+ })
256
+
257
+ it('has no accessibility violations', async () => {
258
+ const { container } = renderSlider({ beforeLabel: 'Drawing', afterLabel: 'Photo' })
259
+ expect(await axe(container)).toHaveNoViolations()
260
+ })
261
+ })
@@ -0,0 +1,397 @@
1
+ 'use client'
2
+
3
+ import * as React from 'react'
4
+ import { useDirection } from '../../hooks/use-direction'
5
+ import { cn } from '../../internal/utils'
6
+
7
+ type CompareSliderOrientation = 'horizontal' | 'vertical'
8
+ type CompareSliderLabelPosition = 'top' | 'bottom'
9
+ type LabelCorner = `${CompareSliderLabelPosition}-${'start' | 'end'}`
10
+
11
+ /** How far a touch travels before it counts as a drag rather than a scroll, in pixels. */
12
+ const DRAG_THRESHOLD = 6
13
+ const STEP = 1
14
+ const PAGE_STEP = 10
15
+
16
+ const ROOT_ORIENTATION: Record<CompareSliderOrientation, string> = {
17
+ horizontal: 'cursor-ew-resize touch-pan-y',
18
+ vertical: 'cursor-ns-resize touch-pan-x',
19
+ }
20
+
21
+ const DIVIDER_ORIENTATION: Record<CompareSliderOrientation, string> = {
22
+ horizontal: 'inset-y-0 w-0.5 ltr:-translate-x-1/2 rtl:translate-x-1/2',
23
+ vertical: 'inset-x-0 h-0.5 -translate-y-1/2',
24
+ }
25
+
26
+ const HANDLE_ORIENTATION: Record<CompareSliderOrientation, string> = {
27
+ horizontal: 'top-1/2 -translate-y-1/2 ltr:-translate-x-1/2 rtl:translate-x-1/2',
28
+ vertical: 'inset-s-1/2 -translate-y-1/2 ltr:-translate-x-1/2 rtl:translate-x-1/2',
29
+ }
30
+
31
+ const POSITION_TRANSITION: Record<CompareSliderOrientation, string> = {
32
+ horizontal: 'transition-[inset-inline-start]',
33
+ vertical: 'transition-[top]',
34
+ }
35
+
36
+ const REVEAL_TIMING = 'duration-1000 ease-out motion-reduce:transition-none'
37
+
38
+ const PRESS_TIMING =
39
+ 'transition duration-250 ease-spring group-data-dragging/compare-slider:duration-100 group-data-dragging/compare-slider:ease-in-out motion-reduce:transition-none'
40
+
41
+ const LAYER_CLASSES = 'relative col-start-1 row-start-1 min-h-0 min-w-0 [&>img]:size-full [&>img]:object-cover'
42
+
43
+ const LABEL_CLASSES =
44
+ 'border-border bg-background text-foreground-intense absolute flex h-7 items-center rounded-full border px-3 text-sm whitespace-nowrap'
45
+
46
+ const LABEL_CORNER: Record<LabelCorner, string> = {
47
+ 'top-start': 'top-3 inset-s-3',
48
+ 'top-end': 'top-3 inset-e-3',
49
+ 'bottom-start': 'bottom-3 inset-s-3',
50
+ 'bottom-end': 'bottom-3 inset-e-3',
51
+ }
52
+
53
+ interface CompareSliderProps extends Omit<
54
+ React.ComponentPropsWithoutRef<'div'>,
55
+ 'children' | 'defaultValue' | 'onChange'
56
+ > {
57
+ /** Layer on the start side of the divider, or above it when vertical. */
58
+ before: React.ReactNode
59
+ /** Layer on the end side of the divider, or below it when vertical. */
60
+ after: React.ReactNode
61
+ /** Divider position as a percentage of the way from the start edge (the top when vertical). Pass it to control the component. */
62
+ value?: number
63
+ /**
64
+ * Divider position on first render, as a percentage of the way from the start edge, when the component is uncontrolled.
65
+ * @default 50
66
+ */
67
+ defaultValue?: number
68
+ /** Fires on every change, including each frame of a drag. */
69
+ onValueChange?: (value: number) => void
70
+ /** Fires once a drag ends or a key press settles, with the position landed on. */
71
+ onValueCommitted?: (value: number) => void
72
+ /**
73
+ * Axis the divider travels along. Vertical stacks `before` above `after`.
74
+ * @default 'horizontal'
75
+ */
76
+ orientation?: CompareSliderOrientation
77
+ /** Caption in a corner of the `before` layer, clipped with it as the divider passes. */
78
+ beforeLabel?: React.ReactNode
79
+ /** Caption in a corner of the `after` layer, clipped with it as the divider passes. */
80
+ afterLabel?: React.ReactNode
81
+ /**
82
+ * Edge the labels sit along. A vertical slider ignores it and puts each label at its own end.
83
+ * @default 'bottom'
84
+ */
85
+ labelPosition?: CompareSliderLabelPosition
86
+ /** Icon on the handle. Defaults to a double arrow that follows `orientation`. */
87
+ icon?: React.ReactNode
88
+ /**
89
+ * Open on `before` alone and wipe the divider in to `defaultValue` the first time the slider scrolls into view. Uncontrolled only.
90
+ * @default false
91
+ */
92
+ reveal?: boolean
93
+ /**
94
+ * Prevent moving the divider.
95
+ * @default false
96
+ */
97
+ disabled?: boolean
98
+ }
99
+
100
+ function clamp(value: number): number {
101
+ return Math.min(100, Math.max(0, value))
102
+ }
103
+
104
+ /** Clips each layer to its side of the divider, so a transparent layer never shows the other through it. */
105
+ function layerClips(position: number, vertical: boolean, rtl: boolean): [before: string, after: string] {
106
+ const rest = 100 - position
107
+ if (vertical) return [`inset(0 0 ${rest}% 0)`, `inset(${position}% 0 0 0)`]
108
+ return rtl
109
+ ? [`inset(0 0 0 ${rest}%)`, `inset(0 ${position}% 0 0)`]
110
+ : [`inset(0 ${rest}% 0 0)`, `inset(0 0 0 ${position}%)`]
111
+ }
112
+
113
+ function CompareSlider({
114
+ before,
115
+ after,
116
+ value,
117
+ defaultValue = 50,
118
+ onValueChange,
119
+ onValueCommitted,
120
+ orientation = 'horizontal',
121
+ beforeLabel,
122
+ afterLabel,
123
+ labelPosition = 'bottom',
124
+ icon,
125
+ reveal = false,
126
+ disabled = false,
127
+ className,
128
+ 'aria-label': ariaLabel,
129
+ 'aria-labelledby': ariaLabelledBy,
130
+ ...props
131
+ }: CompareSliderProps) {
132
+ const rtl = useDirection() === 'rtl'
133
+ const vertical = orientation === 'vertical'
134
+ const controlled = value !== undefined
135
+
136
+ const rootRef = React.useRef<HTMLDivElement>(null)
137
+ const inputRef = React.useRef<HTMLInputElement>(null)
138
+ const gestureRef = React.useRef<{ x: number; y: number; tracking: boolean } | null>(null)
139
+
140
+ const [uncontrolled, setUncontrolled] = React.useState(() => clamp(defaultValue))
141
+ const [seen, setSeen] = React.useState(!reveal)
142
+ const [touched, setTouched] = React.useState(false)
143
+ const [dragging, setDragging] = React.useState(false)
144
+
145
+ const position = controlled ? clamp(value) : reveal && !seen && !touched ? 100 : uncontrolled
146
+ const revealing = reveal && !controlled && !touched
147
+
148
+ const latestRef = React.useRef(position)
149
+ latestRef.current = position
150
+
151
+ React.useEffect(() => {
152
+ if (!reveal || seen) return
153
+ const node = rootRef.current
154
+ if (!node || typeof IntersectionObserver === 'undefined') {
155
+ setSeen(true)
156
+ return
157
+ }
158
+ const observer = new IntersectionObserver(
159
+ ([entry]) => {
160
+ if (entry?.isIntersecting) setSeen(true)
161
+ },
162
+ { threshold: 0.4 },
163
+ )
164
+ observer.observe(node)
165
+ return () => observer.disconnect()
166
+ }, [reveal, seen])
167
+
168
+ const update = (next: number) => {
169
+ const clamped = clamp(next)
170
+ setTouched(true)
171
+ if (clamped === latestRef.current) return
172
+ latestRef.current = clamped
173
+ if (!controlled) setUncontrolled(clamped)
174
+ onValueChange?.(clamped)
175
+ }
176
+
177
+ const placeAt = (clientX: number, clientY: number) => {
178
+ const rect = rootRef.current?.getBoundingClientRect()
179
+ if (!rect?.width || !rect.height) return
180
+ const ratio = vertical ? (clientY - rect.top) / rect.height : (clientX - rect.left) / rect.width
181
+ update((!vertical && rtl ? 1 - ratio : ratio) * 100)
182
+ }
183
+
184
+ const capture = (event: React.PointerEvent<HTMLDivElement>) => {
185
+ try {
186
+ // Capture last: it throws when the pointer is already gone, by which point the
187
+ // press has been applied and a failure only costs tracking outside the element.
188
+ event.currentTarget.setPointerCapture(event.pointerId)
189
+ } catch {}
190
+ }
191
+
192
+ const handlePointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
193
+ if (disabled || (event.pointerType === 'mouse' && event.button !== 0)) return
194
+ const mouse = event.pointerType === 'mouse'
195
+ gestureRef.current = { x: event.clientX, y: event.clientY, tracking: mouse }
196
+ setDragging(true)
197
+ if (!mouse) return
198
+ placeAt(event.clientX, event.clientY)
199
+ inputRef.current?.focus({ preventScroll: true })
200
+ capture(event)
201
+ }
202
+
203
+ const handlePointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
204
+ const gesture = gestureRef.current
205
+ if (!gesture) return
206
+ if (!gesture.tracking) {
207
+ const dx = Math.abs(event.clientX - gesture.x)
208
+ const dy = Math.abs(event.clientY - gesture.y)
209
+ if (dx < DRAG_THRESHOLD && dy < DRAG_THRESHOLD) return
210
+ if (vertical ? dx > dy : dy > dx) {
211
+ gestureRef.current = null
212
+ setDragging(false)
213
+ return
214
+ }
215
+ gesture.tracking = true
216
+ capture(event)
217
+ }
218
+ placeAt(event.clientX, event.clientY)
219
+ }
220
+
221
+ const endDrag = (event: React.PointerEvent<HTMLDivElement>) => {
222
+ const gesture = gestureRef.current
223
+ gestureRef.current = null
224
+ if (!gesture) return
225
+ setDragging(false)
226
+ if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {
227
+ event.currentTarget.releasePointerCapture(event.pointerId)
228
+ }
229
+ if (!gesture.tracking) {
230
+ if (event.type !== 'pointerup') return
231
+ placeAt(event.clientX, event.clientY)
232
+ inputRef.current?.focus({ preventScroll: true })
233
+ }
234
+ onValueCommitted?.(latestRef.current)
235
+ }
236
+
237
+ const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
238
+ if (disabled) return
239
+ const step = event.shiftKey ? PAGE_STEP : STEP
240
+ const across = !vertical && rtl ? -1 : 1
241
+ const deltas: Record<string, number | undefined> = {
242
+ ArrowLeft: -across * step,
243
+ ArrowRight: across * step,
244
+ ArrowUp: vertical ? -step : step,
245
+ ArrowDown: vertical ? step : -step,
246
+ PageUp: vertical ? -PAGE_STEP : PAGE_STEP,
247
+ PageDown: vertical ? PAGE_STEP : -PAGE_STEP,
248
+ }
249
+ const next =
250
+ event.key === 'Home' ? 0 : event.key === 'End' ? 100 : latestRef.current + (deltas[event.key] ?? Number.NaN)
251
+ if (Number.isNaN(next)) return
252
+ event.preventDefault()
253
+ update(next)
254
+ onValueCommitted?.(latestRef.current)
255
+ }
256
+
257
+ const [beforeClip, afterClip] = layerClips(position, vertical, rtl)
258
+ const offset = { [vertical ? 'top' : 'insetInlineStart']: `${position}%` }
259
+ const positionTransition = revealing && cn(POSITION_TRANSITION[orientation], REVEAL_TIMING)
260
+ const clipTransition = revealing && `transition-[clip-path] ${REVEAL_TIMING}`
261
+ const beforeCorner: LabelCorner = vertical ? 'top-start' : `${labelPosition}-start`
262
+ const afterCorner: LabelCorner = vertical ? 'bottom-start' : `${labelPosition}-end`
263
+
264
+ return (
265
+ <div
266
+ ref={rootRef}
267
+ data-base-ui-swipe-ignore={vertical ? 'y' : 'x'}
268
+ {...props}
269
+ data-slot="compare-slider"
270
+ data-orientation={orientation}
271
+ data-dragging={dragging ? '' : undefined}
272
+ data-disabled={disabled ? '' : undefined}
273
+ className={cn(
274
+ 'group/compare-slider relative isolate rounded-2xl select-none',
275
+ disabled ? 'cursor-default' : ROOT_ORIENTATION[orientation],
276
+ className,
277
+ )}
278
+ onPointerDown={handlePointerDown}
279
+ onPointerMove={handlePointerMove}
280
+ onPointerUp={endDrag}
281
+ onPointerCancel={endDrag}
282
+ >
283
+ <div
284
+ data-slot="compare-slider-viewport"
285
+ className="bg-background-muted pointer-events-none grid size-full overflow-hidden rounded-[inherit]"
286
+ >
287
+ <div
288
+ data-slot="compare-slider-before"
289
+ className={cn(LAYER_CLASSES, clipTransition)}
290
+ style={{ clipPath: beforeClip }}
291
+ >
292
+ {before}
293
+ {beforeLabel ? (
294
+ <span data-slot="compare-slider-label" className={cn(LABEL_CLASSES, LABEL_CORNER[beforeCorner])}>
295
+ {beforeLabel}
296
+ </span>
297
+ ) : null}
298
+ </div>
299
+ <div
300
+ data-slot="compare-slider-after"
301
+ className={cn(LAYER_CLASSES, clipTransition)}
302
+ style={{ clipPath: afterClip }}
303
+ >
304
+ {after}
305
+ {afterLabel ? (
306
+ <span data-slot="compare-slider-label" className={cn(LABEL_CLASSES, LABEL_CORNER[afterCorner])}>
307
+ {afterLabel}
308
+ </span>
309
+ ) : null}
310
+ </div>
311
+ <div
312
+ data-slot="compare-slider-divider"
313
+ aria-hidden="true"
314
+ className={cn(
315
+ 'light absolute bg-white shadow-md shadow-black/20',
316
+ DIVIDER_ORIENTATION[orientation],
317
+ positionTransition,
318
+ )}
319
+ style={offset}
320
+ />
321
+ </div>
322
+
323
+ <input
324
+ ref={inputRef}
325
+ type="range"
326
+ className="sr-only"
327
+ min={0}
328
+ max={100}
329
+ value={Math.round(position)}
330
+ disabled={disabled}
331
+ aria-label={ariaLabelledBy ? undefined : (ariaLabel ?? 'Divider position')}
332
+ aria-labelledby={ariaLabelledBy}
333
+ aria-orientation={orientation}
334
+ onKeyDown={handleKeyDown}
335
+ onChange={(event) => update(Number(event.target.value))}
336
+ />
337
+
338
+ <span
339
+ data-slot="compare-slider-handle"
340
+ aria-hidden="true"
341
+ className={cn(
342
+ 'light bg-background text-foreground-intense outline-ring pointer-events-none absolute grid size-11 place-items-center rounded-full shadow-lg shadow-black/25',
343
+ "[&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-5",
344
+ 'group-has-focus-visible/compare-slider:outline-2 group-has-focus-visible/compare-slider:outline-offset-2',
345
+ 'group-data-disabled/compare-slider:bg-background/60 group-data-disabled/compare-slider:*:opacity-disabled group-data-disabled/compare-slider:shadow-none group-data-disabled/compare-slider:backdrop-blur-md',
346
+ 'transform-gpu group-data-dragging/compare-slider:translate-y-[calc(-50%+1px)] group-data-dragging/compare-slider:scale-[0.97]',
347
+ HANDLE_ORIENTATION[orientation],
348
+ revealing ? positionTransition : PRESS_TIMING,
349
+ )}
350
+ style={offset}
351
+ >
352
+ {icon ?? (vertical ? <ArrowsVerticalIcon /> : <ArrowsHorizontalIcon />)}
353
+ </span>
354
+ </div>
355
+ )
356
+ }
357
+
358
+ interface IconProps extends React.SVGProps<SVGSVGElement> {}
359
+
360
+ function ArrowsHorizontalIcon(props: IconProps) {
361
+ return (
362
+ <svg
363
+ xmlns="http://www.w3.org/2000/svg"
364
+ viewBox="0 0 24 24"
365
+ fill="none"
366
+ stroke="currentColor"
367
+ strokeWidth="1.5"
368
+ strokeLinecap="round"
369
+ strokeLinejoin="round"
370
+ aria-hidden="true"
371
+ {...props}
372
+ >
373
+ <path d="m7 8-4 4m0 0 4 4m-4-4h18m-4-4 4 4m0 0-4 4" />
374
+ </svg>
375
+ )
376
+ }
377
+
378
+ function ArrowsVerticalIcon(props: IconProps) {
379
+ return (
380
+ <svg
381
+ xmlns="http://www.w3.org/2000/svg"
382
+ viewBox="0 0 24 24"
383
+ fill="none"
384
+ stroke="currentColor"
385
+ strokeWidth="1.5"
386
+ strokeLinecap="round"
387
+ strokeLinejoin="round"
388
+ aria-hidden="true"
389
+ {...props}
390
+ >
391
+ <path d="m8 7 4-4m0 0 4 4m-4-4v18m-4-4 4 4m0 0 4-4" />
392
+ </svg>
393
+ )
394
+ }
395
+
396
+ export { CompareSlider }
397
+ export type { CompareSliderProps }
@@ -146,7 +146,8 @@ describe('ContextMenu', () => {
146
146
  const user = setupUser()
147
147
  render(<BasicMenu />)
148
148
  await user.pointer({ keys: '[MouseRight]', target: screen.getByTestId('trigger') })
149
- await screen.findByRole('menuitem', { name: 'Profile' })
149
+ const menu = await screen.findByRole('menu')
150
+ await waitFor(() => expect(menu.contains(document.activeElement)).toBe(true))
150
151
  await user.keyboard('{ArrowDown}')
151
152
  await waitFor(() => {
152
153
  const profile = screen.getByRole('menuitem', { name: 'Profile' })
@@ -67,7 +67,7 @@ function popupClassName(size: ContextMenuSize, className?: string) {
67
67
  'max-h-(--available-height) bg-background border-border-overlay flex flex-col border shadow-2xl outline-none',
68
68
  POPUP_SIZE[size],
69
69
  'origin-(--transform-origin)',
70
- 'motion-safe:transition-[opacity,scale] motion-safe:duration-200 motion-safe:ease-[cubic-bezier(0.175,0.885,0.32,1.5)]',
70
+ 'motion-safe:transition-[opacity,scale] motion-safe:duration-200 motion-safe:ease-spring',
71
71
  'data-starting-style:motion-safe:scale-90 data-starting-style:motion-safe:opacity-0',
72
72
  'data-ending-style:motion-safe:scale-95 data-ending-style:motion-safe:opacity-0 data-ending-style:motion-safe:duration-100 data-ending-style:motion-safe:ease-out',
73
73
  className,