-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathindex.tsx
400 lines (362 loc) · 11.6 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import { useEffect, useState, useCallback, useRef } from 'react'
import * as React from 'react'
import { animated, useSpring } from 'react-spring'
import styled, { css } from 'styled-components'
import { useDebounceAnimationState } from '../../foundation/hooks'
import { passiveEvents, isEdge } from '../../foundation/support'
import { useIsomorphicLayoutEffect } from '../../hooks'
import CarouselButton, { Direction } from '../CarouselButton'
export const GRADIENT_WIDTH = 72
/**
* カルーセル系のスクロール量の定数
*
* @example
* const scrollAmount = containerElm.clientWidth * SCROLL_AMOUNT_COEF
*/
export const SCROLL_AMOUNT_COEF = 0.75
interface ScrollProps {
align?: 'center' | 'left' | 'right'
offset?: number
}
export interface CarouselBaseAppearanceProps {
buttonOffset?: number
buttonPadding?: number
bottomOffset?: number
defaultScroll?: ScrollProps
}
export type CarouselGradientProps =
| { hasGradient?: false }
| {
hasGradient: true
fadeInGradient?: boolean
}
type CarouselAppearanceProps = CarouselBaseAppearanceProps &
CarouselGradientProps
type Props = CarouselAppearanceProps & {
onScroll?: (left: number) => void
onResize?: (width: number) => void
children: React.ReactNode
centerItems?: boolean
onScrollStateChange?: (canScroll: boolean) => void
scrollAmountCoef?: number
}
export interface CarouselHandlerRef {
resetScroll(): void
}
export default function Carousel({
buttonOffset = 0,
buttonPadding = 16,
bottomOffset = 0,
defaultScroll: { align = 'left', offset: scrollOffset = 0 } = {},
onScroll,
onResize,
children,
centerItems,
onScrollStateChange,
scrollAmountCoef = SCROLL_AMOUNT_COEF,
...options
}: Props) {
// スクロール位置を保存する
// アニメーション中の場合は、アニメーション終了時のスクロール位置が保存される
const [scrollLeft, setScrollLeft] = useDebounceAnimationState(0)
// アニメーション中かどうか
const animation = useRef(false)
// スクロール可能な領域を保存する
const [maxScrollLeft, setMaxScrollLeft] = useState(0)
// 左右のボタンの表示状態を保存する
const [leftShow, setLeftShow] = useState(false)
const [rightShow, setRightShow] = useState(false)
// const [props, set, stop] = useSpring(() => ({
// scroll: 0
// }))
const [styles, set] = useSpring(() => ({ scroll: 0 }))
const ref = useRef<HTMLDivElement>(null)
const visibleAreaRef = useRef<HTMLDivElement>(null)
const innerRef = useRef<HTMLUListElement>(null)
const handleRight = useCallback(() => {
if (visibleAreaRef.current === null) {
return
}
const { clientWidth } = visibleAreaRef.current
// スクロール領域を超えないように、アニメーションを開始
// アニメーション中にアニメーションが開始されたときに、アニメーション終了予定の位置から再度計算するようにする
const scroll = Math.min(
scrollLeft + clientWidth * scrollAmountCoef,
maxScrollLeft
)
setScrollLeft(scroll, true)
void set({
scroll,
from: { scroll: scrollLeft },
reset: !animation.current,
})
animation.current = true
}, [
animation,
maxScrollLeft,
scrollLeft,
set,
scrollAmountCoef,
setScrollLeft,
])
const handleLeft = useCallback(() => {
if (visibleAreaRef.current === null) {
return
}
const { clientWidth } = visibleAreaRef.current
const scroll = Math.max(scrollLeft - clientWidth * scrollAmountCoef, 0)
setScrollLeft(scroll, true)
void set({
scroll,
from: { scroll: scrollLeft },
reset: !animation.current,
})
animation.current = true
}, [animation, scrollLeft, set, scrollAmountCoef, setScrollLeft])
// スクロール可能な場合にボタンを表示する
// scrollLeftが変化したときに処理する (アニメーション開始時 & 手動スクロール時)
useEffect(() => {
const newLeftShow = scrollLeft > 0
const newRightShow = scrollLeft < maxScrollLeft && maxScrollLeft > 0
if (newLeftShow !== leftShow || newRightShow !== rightShow) {
setLeftShow(newLeftShow)
setRightShow(newRightShow)
onScrollStateChange?.(newLeftShow || newRightShow)
}
}, [leftShow, maxScrollLeft, onScrollStateChange, rightShow, scrollLeft])
const handleScroll = useCallback(() => {
if (ref.current === null) {
return
}
// 手動でスクロールが開始されたときにアニメーションを中断
if (animation.current) {
styles.scroll.stop()
animation.current = false
}
// スクロール位置を保存 (アニメーションの基準になる)
const manualScrollLeft = ref.current.scrollLeft
// 過剰にsetStateが走らないようにdebounceする
setScrollLeft(manualScrollLeft)
}, [animation, setScrollLeft, styles])
// リサイズが起きたときに、アニメーション用のスクロール領域 & ボタンの表示状態 を再計算する
const handleResize = useCallback(() => {
if (ref.current === null) {
return
}
const { clientWidth, scrollWidth } = ref.current
const newMaxScrollLeft = scrollWidth - clientWidth
setMaxScrollLeft(newMaxScrollLeft)
if (onResize) {
onResize(clientWidth)
}
}, [onResize])
useIsomorphicLayoutEffect(() => {
const elm = ref.current
const innerElm = innerRef.current
if (elm === null || innerElm === null) {
return
}
elm.addEventListener(
'wheel',
handleScroll,
passiveEvents() && { passive: true }
)
const resizeObserver = new ResizeObserver(handleResize)
resizeObserver.observe(elm)
const resizeObserverInner = new ResizeObserver(handleResize)
resizeObserverInner.observe(innerElm)
return () => {
elm.removeEventListener('wheel', handleScroll)
resizeObserver.disconnect()
resizeObserverInner.disconnect()
}
}, [handleResize, handleScroll])
// 初期スクロールを行う
useIsomorphicLayoutEffect(() => {
if (align !== 'left' || scrollOffset !== 0) {
const scroll = ref.current
if (scroll !== null) {
const scrollLength = Math.max(
0,
Math.min(
align === 'left' && scrollOffset > 0
? scrollOffset
: align === 'center'
? maxScrollLeft / 2 + scrollOffset
: align === 'right' && scrollOffset <= maxScrollLeft
? maxScrollLeft - scrollOffset / 2
: 0,
maxScrollLeft
)
)
scroll.scrollLeft = scrollLength
setScrollLeft(scrollLength, true)
}
}
}, [ref.current])
const handleScrollMove = useCallback(() => {
if (ref.current === null) {
return
}
if (onScroll) {
onScroll(ref.current.scrollLeft)
}
}, [onScroll])
const [disableGradient, setDisableGradient] = useState(false)
useIsomorphicLayoutEffect(() => {
if (isEdge()) {
setDisableGradient(true)
}
}, [])
// NOTE: Edgeではmaskを使うと要素のレンダリングがバグる(場合によっては画像が表示されない)のでグラデーションを無効にする
if (!disableGradient && options.hasGradient === true) {
const fadeInGradient = options.fadeInGradient ?? false
const overflowGradient = !fadeInGradient
return (
<Container ref={visibleAreaRef}>
<GradientContainer fadeInGradient={fadeInGradient}>
<RightGradient>
<LeftGradient show={overflowGradient || scrollLeft > 0}>
<ScrollArea
ref={ref}
scrollLeft={styles.scroll}
onScroll={handleScrollMove}
>
<CarouselContainer ref={innerRef} centerItems={centerItems}>
{children}
</CarouselContainer>
</ScrollArea>
</LeftGradient>
</RightGradient>
</GradientContainer>
<ButtonsContainer>
<CarouselButton
direction={Direction.Left}
show={leftShow}
offset={buttonOffset}
bottomOffset={bottomOffset}
padding={buttonPadding}
gradient={overflowGradient}
onClick={handleLeft}
/>
<CarouselButton
direction={Direction.Right}
show={rightShow}
offset={buttonOffset}
bottomOffset={bottomOffset}
padding={buttonPadding}
gradient
onClick={handleRight}
/>
</ButtonsContainer>
</Container>
)
}
return (
<Container ref={visibleAreaRef}>
<ScrollArea
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
ref={ref}
scrollLeft={styles.scroll}
onScroll={handleScrollMove}
>
<CarouselContainer ref={innerRef} centerItems={centerItems}>
{children}
</CarouselContainer>
</ScrollArea>
<ButtonsContainer>
<CarouselButton
direction={Direction.Left}
show={leftShow}
offset={buttonOffset}
bottomOffset={bottomOffset}
padding={buttonPadding}
onClick={handleLeft}
/>
<CarouselButton
direction={Direction.Right}
show={rightShow}
offset={buttonOffset}
bottomOffset={bottomOffset}
padding={buttonPadding}
onClick={handleRight}
/>
</ButtonsContainer>
</Container>
)
}
const CarouselContainer = styled.ul<{ centerItems?: boolean }>`
vertical-align: top;
overflow: hidden;
list-style: none;
padding: 0;
/* 最小幅を100%にして親要素にぴったりくっつけることで子要素で要素を均等に割り付けるなどを出来るようにしてある */
min-width: 100%;
box-sizing: border-box;
${({ centerItems = false }) =>
centerItems
? css`
display: flex;
width: max-content;
margin: 0 auto;
`
: css`
display: inline-flex;
margin: 0;
`}
`
const ButtonsContainer = styled.div`
opacity: 0;
transition: 0.4s opacity;
`
const Container = styled.div`
&:hover ${ButtonsContainer} {
opacity: 1;
}
/* CarouselButtonの中にz-index:1があるのでここでコンテキストを切る */
position: relative;
z-index: 0;
`
const ScrollArea = styled(animated.div)`
overflow-x: auto;
padding: 0;
margin: 0;
&::-webkit-scrollbar {
display: none;
}
scrollbar-width: none;
`
const GradientContainer = styled.div<{ fadeInGradient: boolean }>`
/* NOTE: LeftGradientがはみ出るためhidden */
overflow: hidden;
${(p) =>
!p.fadeInGradient &&
css`
margin-left: ${-GRADIENT_WIDTH}px;
${CarouselContainer} {
padding-left: ${GRADIENT_WIDTH}px;
}
`}
margin-right: ${-GRADIENT_WIDTH}px;
/* stylelint-disable-next-line no-duplicate-selectors */
${CarouselContainer} {
padding-right: ${GRADIENT_WIDTH}px;
}
`
const RightGradient = styled.div`
mask-image: linear-gradient(
to right,
#000 calc(100% - ${GRADIENT_WIDTH}px),
transparent
);
`
const LeftGradient = styled.div<{ show: boolean }>`
/* NOTE: mask-position が left → negative px の時、right → abs(negative px) の位置に表示されるため */
margin-right: ${-GRADIENT_WIDTH}px;
padding-right: ${GRADIENT_WIDTH}px;
/* NOTE: mask-position に transition をつけたいが vender prefixes 対策で all につける */
transition: 0.2s all ease-in;
mask: linear-gradient(to right, transparent, #000 ${GRADIENT_WIDTH}px)
${(p) => (p.show ? 0 : -GRADIENT_WIDTH)}px 0;
`