@appica/ui-react 1.3.1 → 1.4.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.
@@ -22,7 +22,19 @@ type CarouselApi = EmblaCarouselType
22
22
  type CarouselOptions = EmblaOptionsType
23
23
  type CarouselPlugin = EmblaPluginType
24
24
 
25
- type CarouselAutoplayOptions = AutoplayOptionsType & { resumeAfter?: number }
25
+ type CarouselAutoplayOptions = AutoplayOptionsType & {
26
+ resumeAfter?: number
27
+ /**
28
+ * Pause while the pointer is over the carousel. Turn it off only beside a `CarouselPlayToggle`.
29
+ * @default true
30
+ */
31
+ pauseOnHover?: boolean
32
+ /**
33
+ * Pause while keyboard focus is inside the carousel. Turn it off only beside a `CarouselPlayToggle`.
34
+ * @default true
35
+ */
36
+ pauseOnFocus?: boolean
37
+ }
26
38
  type CarouselAutoScrollOptions = AutoScrollOptionsType & { resumeAfter?: number }
27
39
  type CarouselAutoHeightOptions = AutoHeightOptionsType
28
40
  type CarouselFadeOptions = FadeOptionsType
@@ -52,12 +64,19 @@ interface CarouselContextValue {
52
64
  subscribeScrollProgress: (onChange: () => void) => () => void
53
65
  getScrollProgress: () => number
54
66
  autoplay: CarouselAutoplayState | null
67
+ /** Whether Autoplay or Auto Scroll stays stopped until `play()`: paused by the user, or stopped for good by a drag. */
68
+ paused: boolean
69
+ /** Stop Autoplay or Auto Scroll until `play()`. Hover, focus, `resumeAfter`, drags and the wheel don't restart it. */
70
+ pause: () => void
71
+ /** Restart Autoplay or Auto Scroll on a fresh timer, even while hovered or focused. */
72
+ play: () => void
55
73
  scrollPrev: () => void
56
74
  scrollNext: () => void
57
75
  scrollTo: (index: number) => void
58
76
  }
59
77
 
60
78
  const CarouselContext = React.createContext<CarouselContextValue | null>(null)
79
+ const CarouselRotationContext = React.createContext(false)
61
80
 
62
81
  function useCarousel(): CarouselContextValue {
63
82
  const ctx = React.useContext(CarouselContext)
@@ -75,6 +94,11 @@ const CAROUSEL_ACCESSIBILITY_VIEWPORT: CarouselAccessibilityOptions = {
75
94
  carouselAriaRoleDescription: '',
76
95
  }
77
96
 
97
+ // Browsers match :focus-visible for keyboard focus, not for focus from a mouse or touch press.
98
+ function hasKeyboardFocus(node: EventTarget | null): boolean {
99
+ return node instanceof Element && node.matches(':focus-visible')
100
+ }
101
+
78
102
  function getShownSlides(api: CarouselApi): Set<number> {
79
103
  const { options, scrollSnapList } = api.internalEngine()
80
104
  if (!options.active) return new Set(api.slideNodes().keys())
@@ -185,7 +209,7 @@ interface CarouselProps extends Omit<React.ComponentPropsWithoutRef<'div'>, 'onS
185
209
  duration?: number
186
210
  /** Escape hatch: a raw Embla options object, merged last so it wins over the flat props. */
187
211
  options?: CarouselOptions
188
- /** Enable the Autoplay plugin. It pauses while hovered or focused and stays off under reduced motion. `resumeAfter` (ms) restarts the timer after user interaction. */
212
+ /** Enable the Autoplay plugin. It pauses while hovered or while keyboard focus is inside, unless `pauseOnHover` or `pauseOnFocus` is `false`, and stays off under reduced motion. `resumeAfter` (ms) restarts the timer after user interaction. */
189
213
  autoplay?: boolean | CarouselAutoplayOptions
190
214
  /** Enable continuous Auto Scroll. Mutually exclusive with `autoplay`; paused under reduced motion. */
191
215
  autoScroll?: boolean | CarouselAutoScrollOptions
@@ -278,6 +302,8 @@ function Carousel({
278
302
  (typeof autoplay === 'object' && typeof autoplay.resumeAfter === 'number' && autoplay.resumeAfter) ||
279
303
  (typeof autoScroll === 'object' && typeof autoScroll.resumeAfter === 'number' && autoScroll.resumeAfter) ||
280
304
  0
305
+ const pauseOnHover = typeof autoplay !== 'object' || autoplay.pauseOnHover !== false
306
+ const pauseOnFocus = typeof autoplay !== 'object' || autoplay.pauseOnFocus !== false
281
307
 
282
308
  const plugins = React.useMemo<CarouselPlugin[]>(() => {
283
309
  const list: CarouselPlugin[] = []
@@ -289,7 +315,7 @@ function Carousel({
289
315
  }
290
316
  if (autoplay) {
291
317
  const opts = typeof autoplay === 'object' ? autoplay : undefined
292
- const { resumeAfter, ...emblaOpts } = opts ?? {}
318
+ const { resumeAfter, pauseOnHover: _pauseOnHover, pauseOnFocus: _pauseOnFocus, ...emblaOpts } = opts ?? {}
293
319
  const autoResume = typeof resumeAfter === 'number' && resumeAfter > 0
294
320
  list.push(Autoplay(autoResume ? { ...emblaOpts, defaultInteraction: false } : emblaOpts))
295
321
  } else if (autoScroll && !reducedMotion) {
@@ -387,6 +413,21 @@ function Carousel({
387
413
  canScrollNext: false,
388
414
  })
389
415
  const [autoplayState, setAutoplayState] = React.useState<CarouselAutoplayState | null>(null)
416
+ const [paused, setPausedState] = React.useState(false)
417
+ const pausedRef = React.useRef(false)
418
+ const setPaused = React.useCallback((next: boolean) => {
419
+ pausedRef.current = next
420
+ setPausedState(next)
421
+ }, [])
422
+ const rotationRef = React.useRef<{ pause: () => void; play: () => void } | null>(null)
423
+ const pause = React.useCallback(() => {
424
+ setPaused(true)
425
+ rotationRef.current?.pause()
426
+ }, [setPaused])
427
+ const play = React.useCallback(() => {
428
+ setPaused(false)
429
+ rotationRef.current?.play()
430
+ }, [setPaused])
390
431
 
391
432
  const scrollProgressRef = React.useRef(0)
392
433
  const scrollListenersRef = React.useRef<Set<() => void>>(new Set())
@@ -464,12 +505,11 @@ function Carousel({
464
505
  resumeTimer = undefined
465
506
  }
466
507
  }
467
- const scheduleResume = (play: () => void) => {
468
- if (resumeAfter <= 0) return
508
+ const scheduleResume = (restart: () => void) => {
469
509
  clearResumeTimer()
470
510
  resumeTimer = setTimeout(() => {
471
511
  resumeTimer = undefined
472
- play()
512
+ restart()
473
513
  }, resumeAfter)
474
514
  }
475
515
 
@@ -479,13 +519,23 @@ function Carousel({
479
519
  // Rotation that hover or focus stopped, owed a restart once both have left.
480
520
  let held = false
481
521
  const playAutoplay = () => {
522
+ if (pausedRef.current) return
482
523
  if (hovered || focused) held = true
483
524
  else emblaApi.plugins().autoplay?.play()
484
525
  }
485
526
  const interruptAutoplay = () => {
486
527
  held = false
487
528
  emblaApi.plugins().autoplay?.stop()
488
- scheduleResume(playAutoplay)
529
+ if (resumeAfter > 0) scheduleResume(playAutoplay)
530
+ else setPaused(true)
531
+ }
532
+ const playAutoScroll = () => {
533
+ if (!pausedRef.current) emblaApi.plugins().autoScroll?.play()
534
+ }
535
+ const interruptAutoScroll = () => {
536
+ emblaApi.plugins().autoScroll?.stop()
537
+ if (resumeAfter > 0) scheduleResume(playAutoScroll)
538
+ else setPaused(true)
489
539
  }
490
540
 
491
541
  let cleanupAutoplay: (() => void) | undefined
@@ -500,14 +550,17 @@ function Carousel({
500
550
  const onPlay = () => {
501
551
  held = false
502
552
  clearResumeTimer()
553
+ if (pausedRef.current) setPaused(false)
503
554
  setAutoplayState((s) => (s ? { ...s, isPlaying: true } : s))
504
555
  }
505
556
  const onStop = () => setAutoplayState((s) => (s ? { ...s, isPlaying: false } : s))
506
557
  const onTimerSet = () => setAutoplayState((s) => (s ? { ...s, cycleId: s.cycleId + 1, isPlaying: true } : s))
507
558
  const onTimerStopped = () => setAutoplayState((s) => (s ? { ...s, isPlaying: false } : s))
508
559
  const resetOnSelect = () => autoplayPlugin.reset()
560
+ const stopsOnPress = autoplayPlugin.options.defaultInteraction !== false
509
561
  const onUserStop = () => {
510
562
  held = false
563
+ if (stopsOnPress && !reducedMotion) setPaused(true)
511
564
  }
512
565
  const onInteraction = (_api: CarouselApi, event: { detail: { interaction: string } }) => {
513
566
  if (event.detail.interaction === 'pointerdown' || event.detail.interaction === 'slidefocus') {
@@ -530,9 +583,10 @@ function Carousel({
530
583
  hovered = false
531
584
  release()
532
585
  }
533
- const onFocusIn = () => {
534
- focused = true
535
- hold()
586
+ const onFocusIn = (event: FocusEvent) => {
587
+ focused = hasKeyboardFocus(event.target)
588
+ if (focused) hold()
589
+ else release()
536
590
  }
537
591
  const onFocusOut = (event: FocusEvent) => {
538
592
  if (event.relatedTarget instanceof Node && root?.contains(event.relatedTarget)) return
@@ -547,17 +601,33 @@ function Carousel({
547
601
  emblaApi.on('pointerdown', onUserStop)
548
602
  emblaApi.on('slidefocus', onUserStop)
549
603
  if (resumeAfter > 0) emblaApi.on('autoplay:interaction', onInteraction)
550
- root?.addEventListener('pointerenter', onPointerEnter)
551
- root?.addEventListener('pointerleave', onPointerLeave)
552
- root?.addEventListener('focusin', onFocusIn)
553
- root?.addEventListener('focusout', onFocusOut)
604
+ if (pauseOnHover) {
605
+ root?.addEventListener('pointerenter', onPointerEnter)
606
+ root?.addEventListener('pointerleave', onPointerLeave)
607
+ }
608
+ if (pauseOnFocus) {
609
+ root?.addEventListener('focusin', onFocusIn)
610
+ root?.addEventListener('focusout', onFocusOut)
611
+ }
554
612
  if (autoplayEnabled && !reducedMotion) {
555
- hovered = !!root?.matches(':hover')
556
- focused = !!root?.contains(document.activeElement)
613
+ hovered = pauseOnHover && !!root?.matches(':hover')
614
+ focused = pauseOnFocus && !!root?.contains(document.activeElement) && hasKeyboardFocus(document.activeElement)
557
615
  playAutoplay()
558
616
  } else {
559
617
  autoplayPlugin.stop()
560
618
  }
619
+ rotationRef.current = {
620
+ pause: () => {
621
+ held = false
622
+ clearResumeTimer()
623
+ emblaApi.plugins().autoplay?.stop()
624
+ },
625
+ play: () => {
626
+ held = false
627
+ clearResumeTimer()
628
+ if (!reducedMotion) emblaApi.plugins().autoplay?.play()
629
+ },
630
+ }
561
631
  cleanupAutoplay = () => {
562
632
  emblaApi.off('autoplay:play', onPlay)
563
633
  emblaApi.off('autoplay:stop', onStop)
@@ -578,16 +648,38 @@ function Carousel({
578
648
 
579
649
  let cleanupAutoScroll: (() => void) | undefined
580
650
  if (autoScrollPlugin && autoScrollEnabled && !autoplayEnabled) {
581
- autoScrollPlugin.play()
651
+ playAutoScroll()
652
+ const onPlay = () => {
653
+ if (pausedRef.current) setPaused(false)
654
+ }
655
+ const stopsOnPress = autoScrollPlugin.options.defaultInteraction !== false
656
+ const onUserStop = () => {
657
+ if (stopsOnPress) setPaused(true)
658
+ }
582
659
  const onInteraction = (_api: CarouselApi, event: { detail: { interaction: string } }) => {
583
660
  if (event.detail.interaction === 'pointerdown' || event.detail.interaction === 'slidefocus') {
584
- autoScrollPlugin.stop()
585
- scheduleResume(() => emblaApi.plugins().autoScroll?.play())
661
+ interruptAutoScroll()
586
662
  }
587
663
  }
588
- if (resumeAfter > 0) {
589
- emblaApi.on('autoscroll:interaction', onInteraction)
590
- cleanupAutoScroll = () => emblaApi.off('autoscroll:interaction', onInteraction)
664
+ emblaApi.on('autoscroll:play', onPlay)
665
+ emblaApi.on('pointerdown', onUserStop)
666
+ emblaApi.on('slidefocus', onUserStop)
667
+ if (resumeAfter > 0) emblaApi.on('autoscroll:interaction', onInteraction)
668
+ rotationRef.current = {
669
+ pause: () => {
670
+ clearResumeTimer()
671
+ emblaApi.plugins().autoScroll?.stop()
672
+ },
673
+ play: () => {
674
+ clearResumeTimer()
675
+ emblaApi.plugins().autoScroll?.play()
676
+ },
677
+ }
678
+ cleanupAutoScroll = () => {
679
+ emblaApi.off('autoscroll:play', onPlay)
680
+ emblaApi.off('pointerdown', onUserStop)
681
+ emblaApi.off('slidefocus', onUserStop)
682
+ if (resumeAfter > 0) emblaApi.off('autoscroll:interaction', onInteraction)
591
683
  }
592
684
  }
593
685
 
@@ -602,8 +694,7 @@ function Carousel({
602
694
  if (autoplayPlugin?.isPlaying() || held) {
603
695
  interruptAutoplay()
604
696
  } else if (autoScrollPlugin?.isPlaying()) {
605
- autoScrollPlugin.stop()
606
- scheduleResume(() => emblaApi.plugins().autoScroll?.play())
697
+ interruptAutoScroll()
607
698
  }
608
699
  }
609
700
  viewport.addEventListener('wheel', onWheel, { passive: true })
@@ -619,8 +710,18 @@ function Carousel({
619
710
  cleanupAutoScroll?.()
620
711
  cleanupWheel?.()
621
712
  clearResumeTimer()
713
+ rotationRef.current = null
622
714
  }
623
- }, [emblaApi, autoplayEnabled, autoScrollEnabled, resumeAfterMs, reducedMotion])
715
+ }, [
716
+ emblaApi,
717
+ autoplayEnabled,
718
+ autoScrollEnabled,
719
+ resumeAfterMs,
720
+ reducedMotion,
721
+ pauseOnHover,
722
+ pauseOnFocus,
723
+ setPaused,
724
+ ])
624
725
 
625
726
  const scrollPrev = React.useCallback(() => emblaApi?.goToPrev(), [emblaApi])
626
727
  const scrollNext = React.useCallback(() => emblaApi?.goToNext(), [emblaApi])
@@ -644,6 +745,9 @@ function Carousel({
644
745
  subscribeScrollProgress,
645
746
  getScrollProgress,
646
747
  autoplay: autoplayState,
748
+ paused,
749
+ pause,
750
+ play,
647
751
  scrollPrev,
648
752
  scrollNext,
649
753
  scrollTo,
@@ -661,6 +765,9 @@ function Carousel({
661
765
  subscribeScrollProgress,
662
766
  getScrollProgress,
663
767
  autoplayState,
768
+ paused,
769
+ pause,
770
+ play,
664
771
  scrollPrev,
665
772
  scrollNext,
666
773
  scrollTo,
@@ -669,17 +776,19 @@ function Carousel({
669
776
 
670
777
  return (
671
778
  <CarouselContext.Provider value={contextValue}>
672
- <div
673
- data-slot="carousel"
674
- data-orientation={orientation}
675
- role={rootProps['aria-label'] || rootProps['aria-labelledby'] ? 'region' : 'group'}
676
- aria-roledescription="carousel"
677
- className={cn('relative', className)}
678
- {...rootProps}
679
- ref={composedRootRef}
680
- >
681
- {children}
682
- </div>
779
+ <CarouselRotationContext.Provider value={autoplayEnabled || autoScrollEnabled}>
780
+ <div
781
+ data-slot="carousel"
782
+ data-orientation={orientation}
783
+ role={rootProps['aria-label'] || rootProps['aria-labelledby'] ? 'region' : 'group'}
784
+ aria-roledescription="carousel"
785
+ className={cn('relative', className)}
786
+ {...rootProps}
787
+ ref={composedRootRef}
788
+ >
789
+ {children}
790
+ </div>
791
+ </CarouselRotationContext.Provider>
683
792
  </CarouselContext.Provider>
684
793
  )
685
794
  }
@@ -1080,6 +1189,41 @@ function CarouselNext({ className, position = 'inside', disabled: disabledProp,
1080
1189
  )
1081
1190
  }
1082
1191
 
1192
+ type CarouselPlayToggleState = { paused: boolean }
1193
+
1194
+ type CarouselPlayToggleProps = useRender.ComponentProps<'button', CarouselPlayToggleState>
1195
+
1196
+ function CarouselPlayToggle({ className, render, ...props }: CarouselPlayToggleProps) {
1197
+ const { reducedMotion, paused, pause, play } = useCarousel()
1198
+ const rotates = React.useContext(CarouselRotationContext)
1199
+ const state: CarouselPlayToggleState = { paused }
1200
+
1201
+ const trigger = useRender({
1202
+ defaultTagName: 'button',
1203
+ render,
1204
+ state,
1205
+ props: mergeProps<'button'>(
1206
+ {
1207
+ type: 'button',
1208
+ 'data-slot': 'carousel-play-toggle',
1209
+ 'data-paused': paused || undefined,
1210
+ 'aria-pressed': paused,
1211
+ 'aria-label': 'Pause slides',
1212
+ onClick: paused ? play : pause,
1213
+ } as unknown as React.ButtonHTMLAttributes<HTMLButtonElement>,
1214
+ props,
1215
+ ),
1216
+ })
1217
+
1218
+ if (!rotates || reducedMotion) return null
1219
+
1220
+ return (
1221
+ <div data-slot="carousel-play-toggle-positioner" className={cn('motion-reduce:hidden', className)}>
1222
+ {trigger}
1223
+ </div>
1224
+ )
1225
+ }
1226
+
1083
1227
  interface CarouselPaginationProps extends React.ComponentPropsWithoutRef<'div'> {
1084
1228
  /**
1085
1229
  * Lay the bullets out in a row or a column.
@@ -1429,6 +1573,7 @@ export {
1429
1573
  CarouselThumb,
1430
1574
  CarouselPrev,
1431
1575
  CarouselNext,
1576
+ CarouselPlayToggle,
1432
1577
  CarouselPagination,
1433
1578
  CarouselProgress,
1434
1579
  useCarousel,
@@ -1442,6 +1587,7 @@ export type {
1442
1587
  CarouselThumbProps,
1443
1588
  CarouselPrevProps,
1444
1589
  CarouselNextProps,
1590
+ CarouselPlayToggleProps,
1445
1591
  CarouselPaginationProps,
1446
1592
  CarouselProgressProps,
1447
1593
  CarouselApi,