@consumidor-positivo/aurora 1.3.3 → 2.0.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 (43) hide show
  1. package/README.md +1 -22
  2. package/astro/Accordion/index.astro +79 -0
  3. package/astro/Breadcrumb/index.astro +124 -0
  4. package/astro/Carousel/Item/index.astro +17 -0
  5. package/astro/Carousel/Root/index.astro +332 -0
  6. package/astro/Pagination/index.astro +296 -0
  7. package/dist/components/Accordion/index.d.ts +23 -0
  8. package/dist/components/Accordion/index.es.js +85 -0
  9. package/dist/components/Accordion/index.es.js.map +1 -0
  10. package/dist/components/Accordion/styles.css +1 -0
  11. package/dist/components/Breadcrumb/index.d.ts +10 -0
  12. package/dist/components/Breadcrumb/index.es.js +112 -0
  13. package/dist/components/Breadcrumb/index.es.js.map +1 -0
  14. package/dist/components/Breadcrumb/styles.css +1 -0
  15. package/dist/components/Carousel/Item/index.d.ts +10 -0
  16. package/dist/components/Carousel/Item/index.es.js +16 -0
  17. package/dist/components/Carousel/Item/index.es.js.map +1 -0
  18. package/dist/components/Carousel/Root/hooks.d.ts +33 -0
  19. package/dist/components/Carousel/Root/index.d.ts +20 -0
  20. package/dist/components/Carousel/Root/index.es.js +256 -0
  21. package/dist/components/Carousel/Root/index.es.js.map +1 -0
  22. package/dist/components/Carousel/index.d.ts +10 -0
  23. package/dist/components/Carousel/index.es.js +14 -0
  24. package/dist/components/Carousel/index.es.js.map +1 -0
  25. package/dist/components/Carousel/styles.css +1 -1
  26. package/dist/components/Header/styles.css +1 -1
  27. package/dist/components/Pagination/index.d.ts +14 -0
  28. package/dist/components/Pagination/index.es.js +141 -0
  29. package/dist/components/Pagination/index.es.js.map +1 -0
  30. package/dist/components/Pagination/styles.css +1 -0
  31. package/dist/main.d.ts +4 -1
  32. package/dist/main.es.js +7 -1
  33. package/dist/main.es.js.map +1 -1
  34. package/package.json +2 -4
  35. package/dist/components/Prototype/Carousel/Pagination.d.ts +0 -7
  36. package/dist/components/Prototype/Carousel/Scrollbar.d.ts +0 -6
  37. package/dist/components/Prototype/Carousel/helpers.d.ts +0 -1
  38. package/dist/components/Prototype/Carousel/index.d.ts +0 -2
  39. package/dist/components/Prototype/Carousel/index.es.js +0 -469
  40. package/dist/components/Prototype/Carousel/index.es.js.map +0 -1
  41. package/dist/components/Prototype/Carousel/types.d.ts +0 -7
  42. package/dist/components/Prototype/Carousel/useCarousel.d.ts +0 -20
  43. package/dist/components/Prototype/Carousel/useCarouselDrag.d.ts +0 -9
package/README.md CHANGED
@@ -42,27 +42,6 @@ Cada componente visual é publicado em **dois formatos**: **React**, para as apl
42
42
  npm install @consumidor-positivo/aurora
43
43
  ```
44
44
 
45
- ### Componentes Opcionais
46
-
47
- Alguns componentes requerem dependências adicionais que não são instaladas por padrão para evitar aumentar o bundle desnecessariamente.
48
-
49
- #### Carousel
50
-
51
- O componente Carousel requer a instalação do `react-snap-carousel`:
52
-
53
- ```bash
54
- npm install react-snap-carousel
55
- ```
56
-
57
- ```tsx
58
- import { Carousel } from '@consumidor-positivo/aurora'
59
-
60
- // Agora você pode usar o Carousel
61
- <Carousel items={items} />
62
- ```
63
-
64
- > **Nota:** Se você tentar usar o Carousel sem instalar o `react-snap-carousel`, receberá um erro de dependência em tempo de execução.
65
-
66
45
  ## Dois formatos: React e Astro
67
46
 
68
47
  O caminho do import decide qual versão você usa.
@@ -89,7 +68,7 @@ import Text from '@consumidor-positivo/aurora/astro/Text/index.astro'
89
68
 
90
69
  A versão Astro renderiza em build time, sem ilha e sem React no bundle, e tem as mesmas props visuais da React. Como o Astro não tem prop de função, os callbacks viram atributos e eventos: `data-au-modal-toggle` e `data-au-drawer-toggle` abrem Modal e Drawer, e os componentes emitem eventos `au:*` (`au:tabchange`, `au:modalopen`...). Uma página feita só com componentes Astro importa o reset uma vez, pelo `global.css`.
91
70
 
92
- Todo componente visual tem as duas versões. Ficam só em React os utilitários (`Transition`, `IsMobile`, `misc/*`) e o `Prototype/Carousel`. A referência completa está em [docs/astro.md](docs/astro.md) e na página "Componentes Astro" do Storybook.
71
+ Todo componente visual tem as duas versões. Ficam só em React os utilitários (`Transition`, `IsMobile`, `misc/*`). A referência completa está em [docs/astro.md](docs/astro.md) e na página "Componentes Astro" do Storybook.
93
72
 
94
73
  ## Desenvolvimento
95
74
 
@@ -0,0 +1,79 @@
1
+ ---
2
+ import type { HTMLAttributes } from 'astro/types'
3
+ import IconMinusCircle from '../icons/default/IconMinusCircle.astro'
4
+ import IconPlusCircle from '../icons/default/IconPlusCircle.astro'
5
+ import '../../dist/components/Accordion/styles.css'
6
+
7
+ /**
8
+ * Same markup as the React `Accordion`. `open` is the initial state (the React
9
+ * `defaultOpen`; there is no controlled mode) and the inline controller
10
+ * toggles the accordion on every header click, emitting `au:accordiontoggle`
11
+ * (`detail.open`) from the root in place of `onToggle`. The header and panel
12
+ * ids are generated per render, as React generates its own. Every other HTML
13
+ * attribute lands on the root `div`.
14
+ */
15
+ export type Props = HTMLAttributes<'div'> & {
16
+ /** Text shown in the header. */
17
+ label: string
18
+ /** Figma "Type". Keep one type per group. */
19
+ variant?: 'container' | 'row'
20
+ /** Initial state. */
21
+ open?: boolean
22
+ }
23
+
24
+ const {
25
+ label,
26
+ variant = 'container',
27
+ open = false,
28
+ class: className,
29
+ ...rest
30
+ } = Astro.props
31
+
32
+ const uid = crypto.randomUUID().slice(0, 8)
33
+ const headerId = `au-accordion-header-${uid}`
34
+ const panelId = `au-accordion-panel-${uid}`
35
+ ---
36
+
37
+ <div
38
+ class:list={['au-accordion', `au-accordion--${variant}`, open && 'au-accordion--open', className]}
39
+ data-element="au-accordion"
40
+ {...rest}>
41
+ <button
42
+ type="button"
43
+ id={headerId}
44
+ class="au-accordion__header"
45
+ aria-expanded={open ? 'true' : 'false'}
46
+ aria-controls={panelId}>
47
+ <span class="au-accordion__label">{label}</span>
48
+ <span class="au-accordion__icon au-accordion__icon--closed" aria-hidden="true"><IconPlusCircle /></span>
49
+ <span class="au-accordion__icon au-accordion__icon--open" aria-hidden="true"><IconMinusCircle /></span>
50
+ </button>
51
+ <div id={panelId} class="au-accordion__panel" role="region" aria-labelledby={headerId}>
52
+ <div class="au-accordion__panel-body">
53
+ <div class="au-accordion__panel-content"><slot /></div>
54
+ </div>
55
+ </div>
56
+ </div>
57
+
58
+ <script>
59
+ import { elementController } from '@consumidor-positivo/aurora/astro/runtime'
60
+
61
+ const OPEN_CLASS = 'au-accordion--open'
62
+
63
+ elementController('au-accordion', ({ root, query, on, emit }) => {
64
+ const header = query<HTMLButtonElement>('.au-accordion__header')
65
+ if (!header) return
66
+
67
+ on('click', (event) => {
68
+ const target = event.target as Element | null
69
+ // A nested accordion handles its own header.
70
+ if (target?.closest('.au-accordion') !== root) return
71
+ if (!target?.closest('.au-accordion__header')) return
72
+
73
+ const open = !root.classList.contains(OPEN_CLASS)
74
+ root.classList.toggle(OPEN_CLASS, open)
75
+ header.setAttribute('aria-expanded', String(open))
76
+ emit('au:accordiontoggle', { open })
77
+ })
78
+ })
79
+ </script>
@@ -0,0 +1,124 @@
1
+ ---
2
+ import type { HTMLAttributes } from 'astro/types'
3
+ import LinkButton from '../LinkButton/index.astro'
4
+ import IconChevronLeft from '../icons/default/IconChevronLeft.astro'
5
+ import IconMoreHorizontal from '../icons/default/IconMoreHorizontal.astro'
6
+ import '../../dist/components/Breadcrumb/styles.css'
7
+
8
+ export type BreadcrumbItem = {
9
+ label: string
10
+ /** Omit on the current page (the last item), which is not a link. */
11
+ href?: string
12
+ }
13
+
14
+ /**
15
+ * Same props and markup as the React `Breadcrumb`: the full trail above the
16
+ * medium breakpoint and the link to the parent page below it, both in the
17
+ * HTML and switched by CSS. With five levels or more the middle ones collapse
18
+ * behind the ellipsis button; the inline controller opens and closes its
19
+ * list (click, outside click and Escape), as the React state does. The menu
20
+ * id is generated per render, as React generates its own. Every other HTML
21
+ * attribute lands on the `<nav>`.
22
+ */
23
+ export type Props = HTMLAttributes<'nav'> & {
24
+ /** The trail, from the root to the current page. */
25
+ items: BreadcrumbItem[]
26
+ }
27
+
28
+ const { items, class: className, ...rest } = Astro.props
29
+
30
+ const MIN_ITEMS_TO_COLLAPSE = 5
31
+
32
+ const lastIndex = items.length - 1
33
+ const current = items[lastIndex]
34
+ const parent = items.length > 1 ? items[lastIndex - 1] : undefined
35
+ const shouldCollapse = items.length >= MIN_ITEMS_TO_COLLAPSE
36
+ const hiddenItems = shouldCollapse ? items.slice(1, lastIndex - 1) : []
37
+ const visibleItems = shouldCollapse ? [items[0], parent!] : items.slice(0, lastIndex)
38
+ const menuId = `au-breadcrumb-menu-${crypto.randomUUID().slice(0, 8)}`
39
+ ---
40
+
41
+ <nav class:list={['au-breadcrumb', className]} aria-label="Breadcrumb" data-element="au-breadcrumb" {...rest}>
42
+ <ol class="au-breadcrumb__list">
43
+ {
44
+ visibleItems.map((item, index) => (
45
+ <Fragment>
46
+ {index === 1 && shouldCollapse && (
47
+ <li class="au-breadcrumb__item au-breadcrumb__item--collapse">
48
+ <button
49
+ type="button"
50
+ class="au-breadcrumb__ellipsis"
51
+ aria-label="Mostrar níveis ocultos"
52
+ aria-expanded="false"
53
+ aria-haspopup="true"
54
+ aria-controls={menuId}>
55
+ <IconMoreHorizontal />
56
+ </button>
57
+ <ul id={menuId} class="au-breadcrumb__menu" hidden>
58
+ {hiddenItems.map((hidden) => (
59
+ <li class="au-breadcrumb__menu-item">
60
+ <a class="au-breadcrumb__menu-link" href={hidden.href}>{hidden.label}</a>
61
+ </li>
62
+ ))}
63
+ </ul>
64
+ </li>
65
+ )}
66
+ <li class="au-breadcrumb__item">
67
+ {item.href ? (
68
+ <LinkButton as="a" href={item.href} size="small">{item.label}</LinkButton>
69
+ ) : (
70
+ <span class="au-breadcrumb__text">{item.label}</span>
71
+ )}
72
+ </li>
73
+ </Fragment>
74
+ ))
75
+ }
76
+ <li class="au-breadcrumb__item au-breadcrumb__item--current">
77
+ <span class="au-breadcrumb__current" aria-current="page" title={current.label}>{current.label}</span>
78
+ </li>
79
+ </ol>
80
+
81
+ {
82
+ parent?.href && (
83
+ <LinkButton as="a" href={parent.href} size="small" class="au-breadcrumb__back">
84
+ <IconChevronLeft slot="icon-left" />{parent.label}
85
+ </LinkButton>
86
+ )
87
+ }
88
+ </nav>
89
+
90
+ <script>
91
+ import { elementController } from '@consumidor-positivo/aurora/astro/runtime'
92
+
93
+ const OPEN_CLASS = 'au-breadcrumb__ellipsis--open'
94
+
95
+ elementController('au-breadcrumb', ({ query, on }) => {
96
+ const collapse = query<HTMLElement>('.au-breadcrumb__item--collapse')
97
+ const button = query<HTMLButtonElement>('.au-breadcrumb__ellipsis')
98
+ const menu = query<HTMLElement>('.au-breadcrumb__menu')
99
+ if (!collapse || !button || !menu) return
100
+
101
+ function toggle(isOpen: boolean) {
102
+ button!.classList.toggle(OPEN_CLASS, isOpen)
103
+ button!.setAttribute('aria-expanded', String(isOpen))
104
+ menu!.hidden = !isOpen
105
+ }
106
+
107
+ const isOpen = () => !menu!.hidden
108
+
109
+ on('click', (event) => {
110
+ if ((event.target as Element | null)?.closest('.au-breadcrumb__ellipsis')) {
111
+ toggle(!isOpen())
112
+ }
113
+ })
114
+
115
+ on('global:click', (event) => {
116
+ if (!isOpen() || collapse!.contains(event.target as Node)) return
117
+ toggle(false)
118
+ })
119
+
120
+ on('global:keydown', (event) => {
121
+ if (event.key === 'Escape' && isOpen()) toggle(false)
122
+ })
123
+ })
124
+ </script>
@@ -0,0 +1,17 @@
1
+ ---
2
+ import type { HTMLAttributes } from 'astro/types'
3
+ import '../../../dist/components/Carousel/styles.css'
4
+
5
+ /**
6
+ * Same markup as the React `Carousel.Item`: one slide, `role="group"` with
7
+ * `aria-roledescription="slide"`. Every HTML attribute lands on the slide,
8
+ * so a `data-*` can anchor the app's own visibility tracking.
9
+ */
10
+ export type Props = HTMLAttributes<'div'>
11
+
12
+ const { class: className, ...rest } = Astro.props
13
+ ---
14
+
15
+ <div class:list={['au-carousel__item', className]} role="group" aria-roledescription="slide" {...rest}>
16
+ <slot />
17
+ </div>
@@ -0,0 +1,332 @@
1
+ ---
2
+ import type { HTMLAttributes } from 'astro/types'
3
+ import Button from '../../Button/index.astro'
4
+ import IconChevronLeft from '../../icons/default/IconChevronLeft.astro'
5
+ import IconChevronRight from '../../icons/default/IconChevronRight.astro'
6
+ import '../../../dist/components/Carousel/styles.css'
7
+
8
+ export type CarouselNavigation = 'text' | 'pin' | 'only-pin'
9
+
10
+ export type CarouselItemsPerView = number | { mobile?: number; desktop?: number }
11
+
12
+ /**
13
+ * Same markup as the React `Carousel.Root`; the slides come through the
14
+ * default slot as `Carousel/Item`. The number of pages depends on layout, so
15
+ * the HTML ships the navigation hidden with "Página 1 de 1" and the inline
16
+ * controller measures the rail, fills the position text and the pins, keeps
17
+ * them in step with the scroll and emits `au:carouselchange`
18
+ * (`detail.page`, from 1, and `detail.pageCount`) in place of
19
+ * `onPageChange`. React does the same on its first render, so both show the
20
+ * navigation only after measuring. `data-page-label` on the root is
21
+ * controller wiring. Other HTML attributes land on the root `<div>`.
22
+ */
23
+ export type Props = Omit<HTMLAttributes<'div'>, 'draggable' | 'style'> & {
24
+ /**
25
+ * How the position is shown (Figma: Type). `text` writes "Página 1 de 2"
26
+ * between the arrows; `pin` replaces it with dots; `only-pin` has no arrows.
27
+ */
28
+ navigation?: CarouselNavigation
29
+ /** White arrows, text and pins for dark backgrounds (Figma: Negative). */
30
+ negative?: boolean
31
+ /** Word before "1 de 2" in the position text and in the pins' labels. */
32
+ pageLabel?: string
33
+ /** Accessible name of the carousel region. */
34
+ label?: string
35
+ /** Space between slides, in px. */
36
+ gap?: number
37
+ /**
38
+ * Width of each slide as a share of the rail: `3` fits three, `1.4` fits
39
+ * one and lets the next peek. A `{ mobile, desktop }` pair switches at the
40
+ * medium breakpoint. Without it, slides keep their own width.
41
+ */
42
+ itemsPerView?: CarouselItemsPerView
43
+ /** Mouse drag on the rail. Touch always scrolls natively. */
44
+ draggable?: boolean
45
+ }
46
+
47
+ const {
48
+ navigation = 'text',
49
+ negative = false,
50
+ pageLabel = 'Página',
51
+ label = 'Carrossel',
52
+ gap = 16,
53
+ itemsPerView,
54
+ draggable = true,
55
+ class: className,
56
+ ...rest
57
+ } = Astro.props
58
+
59
+ const hasArrows = navigation !== 'only-pin'
60
+ const hasPins = navigation !== 'text'
61
+ const status = [pageLabel.trim(), '1 de 1'].filter(Boolean).join(' ')
62
+
63
+ const { mobile, desktop } =
64
+ typeof itemsPerView === 'number'
65
+ ? { mobile: itemsPerView, desktop: undefined }
66
+ : (itemsPerView ?? {})
67
+
68
+ // Written as React serializes its `style` object.
69
+ const style = [
70
+ `--au-carousel-gap: ${gap}px;`,
71
+ mobile !== undefined && `--au-carousel-items: ${mobile};`,
72
+ desktop !== undefined && `--au-carousel-items-desktop: ${desktop};`,
73
+ ]
74
+ .filter(Boolean)
75
+ .join(' ')
76
+ ---
77
+
78
+ <div
79
+ class:list={[
80
+ 'au-carousel',
81
+ `au-carousel--navigation-${navigation}`,
82
+ negative && 'au-carousel--negative',
83
+ draggable && 'au-carousel--draggable',
84
+ itemsPerView !== undefined && 'au-carousel--items-per-view',
85
+ className,
86
+ ]}
87
+ role="region"
88
+ aria-roledescription="carrossel"
89
+ aria-label={label}
90
+ style={style}
91
+ data-element="au-carousel"
92
+ data-page-label={pageLabel}
93
+ {...rest}>
94
+ <div class="au-carousel__rail"><slot /></div>
95
+
96
+ <div class="au-carousel__nav" hidden>
97
+ {
98
+ hasArrows && (
99
+ <Button
100
+ class="au-carousel__arrow au-carousel__arrow--previous"
101
+ type="outlined"
102
+ round
103
+ negative={negative}
104
+ disabled
105
+ aria-label="Anterior">
106
+ <IconChevronLeft />
107
+ </Button>
108
+ )
109
+ }
110
+
111
+ <span class:list={['au-carousel__status', hasPins && 'au-carousel__status--hidden']} aria-live="polite" aria-atomic="true">{status}</span>
112
+
113
+ {hasPins && <div class="au-carousel__pins" />}
114
+
115
+ {
116
+ hasArrows && (
117
+ <Button
118
+ class="au-carousel__arrow au-carousel__arrow--next"
119
+ type="outlined"
120
+ round
121
+ negative={negative}
122
+ disabled
123
+ aria-label="Próximo">
124
+ <IconChevronRight />
125
+ </Button>
126
+ )
127
+ }
128
+ </div>
129
+ </div>
130
+
131
+ <script>
132
+ import { elementController } from '@consumidor-positivo/aurora/astro/runtime'
133
+
134
+ /** Pointer travel, in px, before a mouse press becomes a drag (a click below it still reaches the slide). */
135
+ const DRAG_THRESHOLD = 5
136
+ const DRAGGING_CLASS = 'au-carousel__rail--dragging'
137
+
138
+ /**
139
+ * Groups the slides into pages. A page starts at a slide and holds every
140
+ * following slide that still fits, whole, in the rail's visible width.
141
+ * Returns the scroll position of each page (the `offsetLeft` of its first
142
+ * slide, which is also where CSS snaps). The rail is `position: relative`,
143
+ * so `offsetLeft` is measured from the rail itself.
144
+ */
145
+ function getPageStarts(rail: HTMLElement): number[] {
146
+ const slides = Array.from(rail.children) as HTMLElement[]
147
+ const viewport = rail.clientWidth
148
+ const starts: number[] = []
149
+ let index = 0
150
+
151
+ while (index < slides.length) {
152
+ const start = slides[index].offsetLeft
153
+ starts.push(start)
154
+ let next = index + 1
155
+ while (
156
+ next < slides.length &&
157
+ slides[next].offsetLeft + slides[next].offsetWidth <= start + viewport + 1
158
+ ) {
159
+ next += 1
160
+ }
161
+ index = next
162
+ }
163
+
164
+ return starts
165
+ }
166
+
167
+ /**
168
+ * The page the rail is scrolled to: the one whose start is nearest to
169
+ * `scrollLeft`, or the last page once the rail cannot scroll any further
170
+ * (its start may lie past the maximum scroll, where the browser clamps it).
171
+ */
172
+ function getActivePage(rail: HTMLElement, starts: number[]): number {
173
+ if (starts.length === 0) return 0
174
+
175
+ const { scrollLeft } = rail
176
+ const maxScroll = rail.scrollWidth - rail.clientWidth
177
+ if (scrollLeft >= maxScroll - 1) return starts.length - 1
178
+
179
+ let nearest = 0
180
+ starts.forEach((start, index) => {
181
+ if (Math.abs(start - scrollLeft) < Math.abs(starts[nearest] - scrollLeft)) {
182
+ nearest = index
183
+ }
184
+ })
185
+ return nearest
186
+ }
187
+
188
+ elementController('au-carousel', ({ root, query, on, emit }) => {
189
+ const rail = query<HTMLElement>('.au-carousel__rail')
190
+ const nav = query<HTMLElement>('.au-carousel__nav')
191
+ const status = query<HTMLElement>('.au-carousel__status')
192
+ const pins = query<HTMLElement>('.au-carousel__pins')
193
+ const previous = query<HTMLButtonElement>('.au-carousel__arrow--previous')
194
+ const next = query<HTMLButtonElement>('.au-carousel__arrow--next')
195
+ if (!rail || !nav || !status) return
196
+
197
+ const pageLabel = (root.dataset.pageLabel ?? 'Página').trim()
198
+ const pinLabel = pageLabel || 'Página'
199
+ const draggable = root.classList.contains('au-carousel--draggable')
200
+ let starts: number[] = []
201
+ let page = 0
202
+
203
+ function setArrow(button: HTMLButtonElement | null, disabled: boolean) {
204
+ if (!button) return
205
+ button.disabled = disabled
206
+ button.classList.toggle('au-btn--disabled', disabled)
207
+ }
208
+
209
+ function pin(index: number) {
210
+ const button = document.createElement('button')
211
+ button.type = 'button'
212
+ button.className = 'au-carousel__pin'
213
+ if (index === page) {
214
+ button.classList.add('au-carousel__pin--active')
215
+ button.setAttribute('aria-current', 'true')
216
+ }
217
+ button.setAttribute('aria-label', `${pinLabel} ${index + 1}`)
218
+ return button
219
+ }
220
+
221
+ function render() {
222
+ const total = Math.max(starts.length, 1)
223
+ nav!.hidden = starts.length <= 1
224
+ status!.textContent = [pageLabel, `${page + 1} de ${total}`].filter(Boolean).join(' ')
225
+ setArrow(previous, page === 0)
226
+ setArrow(next, page >= total - 1)
227
+ pins?.replaceChildren(...Array.from({ length: total }, (_, index) => pin(index)))
228
+ }
229
+
230
+ function setActive(target: number) {
231
+ if (target === page) return
232
+ page = target
233
+ render()
234
+ emit('au:carouselchange', { page: page + 1, pageCount: starts.length })
235
+ }
236
+
237
+ function measure() {
238
+ starts = getPageStarts(rail!)
239
+ const active = getActivePage(rail!, starts)
240
+ if (active === page) render()
241
+ else setActive(active)
242
+ }
243
+
244
+ function goTo(target: number) {
245
+ if (target < 0 || target >= starts.length) return
246
+ rail!.scrollTo({ left: starts[target] })
247
+ }
248
+
249
+ let frame = 0
250
+ rail.addEventListener(
251
+ 'scroll',
252
+ () => {
253
+ cancelAnimationFrame(frame)
254
+ frame = requestAnimationFrame(() => setActive(getActivePage(rail!, starts)))
255
+ },
256
+ { passive: true },
257
+ )
258
+
259
+ const resizeObserver =
260
+ typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : undefined
261
+
262
+ function observeSlides() {
263
+ resizeObserver?.disconnect()
264
+ resizeObserver?.observe(rail!)
265
+ Array.from(rail!.children).forEach((slide) => resizeObserver?.observe(slide))
266
+ }
267
+
268
+ new MutationObserver(() => {
269
+ observeSlides()
270
+ measure()
271
+ }).observe(rail, { childList: true })
272
+
273
+ measure()
274
+ observeSlides()
275
+
276
+ on('click', (event) => {
277
+ const target = event.target as Element | null
278
+ if (target?.closest('.au-carousel__arrow--previous')) return goTo(page - 1)
279
+ if (target?.closest('.au-carousel__arrow--next')) return goTo(page + 1)
280
+ const dot = target?.closest<HTMLButtonElement>('.au-carousel__pin')
281
+ if (dot) goTo(Array.from(pins!.children).indexOf(dot))
282
+ })
283
+
284
+ let drag: { startX: number; scrollLeft: number; page: number; moved: boolean } | null = null
285
+
286
+ function suppressClick(event: Event) {
287
+ event.stopPropagation()
288
+ event.preventDefault()
289
+ }
290
+
291
+ on('pointerdown', (event) => {
292
+ if (!draggable || event.pointerType !== 'mouse' || event.button !== 0) return
293
+ if (!rail!.contains(event.target as Node)) return
294
+ drag = { startX: event.clientX, scrollLeft: rail!.scrollLeft, page, moved: false }
295
+ rail!.setPointerCapture(event.pointerId)
296
+ })
297
+
298
+ on('pointermove', (event) => {
299
+ if (!drag) return
300
+ const delta = event.clientX - drag.startX
301
+ if (!drag.moved) {
302
+ if (Math.abs(delta) < DRAG_THRESHOLD) return
303
+ drag.moved = true
304
+ rail!.classList.add(DRAGGING_CLASS)
305
+ }
306
+ rail!.scrollLeft = drag.scrollLeft - delta
307
+ })
308
+
309
+ function endDrag(event: PointerEvent) {
310
+ if (!drag) return
311
+ const { moved, page: from, startX } = drag
312
+ drag = null
313
+ if (rail!.hasPointerCapture(event.pointerId)) {
314
+ rail!.releasePointerCapture(event.pointerId)
315
+ }
316
+ if (!moved) return
317
+
318
+ rail!.classList.remove(DRAGGING_CLASS)
319
+ const direction = event.clientX < startX ? 1 : -1
320
+ const nearest = getActivePage(rail!, starts)
321
+ goTo(nearest === from ? from + direction : nearest)
322
+
323
+ // The click that ends a drag must not reach the slide. It fires in the
324
+ // same task as `pointerup`, so the listener is gone by the next one.
325
+ rail!.addEventListener('click', suppressClick, { capture: true, once: true })
326
+ setTimeout(() => rail!.removeEventListener('click', suppressClick, { capture: true }))
327
+ }
328
+
329
+ on('pointerup', endDrag)
330
+ on('pointercancel', endDrag)
331
+ })
332
+ </script>