이름: solution/front → solution/frontend
`backend` 옆에 `front` 가 있을 이유가 없었다. negosium 의 negodata/front 를 그대로 베꼈고 그게 왜 front 인지는 따져보지 않았다 — 근거 없이 들여온 이름이라 바로잡는다. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019uYhHQdssRubirPirrdJJC
This commit is contained in:
1 parent
06f6438d9b
commit
c85c577349
480 files changed
+22
-22
No files matched your search
@@ -0,0 +1,224 @@
|
||||
/**
|
||||
* 드래그 카로셀 — 마우스로 잡아끌어 넘기는 슬라이더.
|
||||
*
|
||||
* ★ 캔버스의 photos.carousel 은 `overflow-x-auto + snap` 이라 데스크톱 마우스로는 못 끈다
|
||||
* (트랙패드 스크롤만 먹는다). 쇼케이스는 커서로 끌어야 하므로 여기서 따로 만든다.
|
||||
*
|
||||
* ★ 애니메이션 라이브러리(motion)의 drag 를 쓰지 않는다.
|
||||
* 그쪽은 제스처 처리를 requestAnimationFrame 프레임 루프에 태우는데, **탭이 백그라운드면
|
||||
* rAF 가 멈춰서 드래그가 아예 동작하지 않는다.** 자동화 브라우저(hidden 탭)에서 검증이
|
||||
* 불가능해지는 것도 같은 이유다. 여기서는 pointermove 에서 transform 을 직접 쓰고,
|
||||
* 놓았을 때의 스냅만 CSS transition 에 맡긴다 — rAF 없이도 돈다.
|
||||
*/
|
||||
import {useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent, type ReactNode} from 'react';
|
||||
import {ChevronLeft, ChevronRight} from 'lucide-react';
|
||||
import {cn} from '@/lib/utils';
|
||||
|
||||
interface DragCarouselProps {
|
||||
slides: ReactNode[];
|
||||
index: number;
|
||||
onIndexChange: (next: number) => void;
|
||||
/** 아래 점 네비게이션. 슬라이드가 아주 많으면 끈다. */
|
||||
showDots?: boolean;
|
||||
label?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** 이만큼 끌면 넘긴다(컨테이너 너비 대비). 너무 작으면 살짝 흔들려도 넘어간다. */
|
||||
const DRAG_RATIO = 0.2;
|
||||
/** 짧게 튕겨도 넘어가게 하는 속도 임계(px/ms). */
|
||||
const FLICK_VELOCITY = 0.5;
|
||||
/** 양 끝에서 더 끌 때의 저항. 1 이면 끝에서도 그냥 끌려서 경계가 안 느껴진다. */
|
||||
const EDGE_RESISTANCE = 0.35;
|
||||
const SNAP_MS = 320;
|
||||
|
||||
export function DragCarousel({
|
||||
slides,
|
||||
index,
|
||||
onIndexChange,
|
||||
showDots = true,
|
||||
label,
|
||||
className,
|
||||
}: DragCarouselProps) {
|
||||
const viewportRef = useRef<HTMLDivElement>(null);
|
||||
const trackRef = useRef<HTMLDivElement>(null);
|
||||
const [width, setWidth] = useState(0);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const drag = useRef({startX: 0, startTime: 0, dx: 0, active: false});
|
||||
const count = slides.length;
|
||||
|
||||
// 너비는 창 크기·패널 접힘에 따라 바뀐다 — 측정값을 붙들고 있으면 슬라이드가 어긋난다.
|
||||
useEffect(() => {
|
||||
const el = viewportRef.current;
|
||||
if (!el) return;
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
const w = entries[0]?.contentRect.width;
|
||||
if (typeof w === 'number') setWidth(w);
|
||||
});
|
||||
ro.observe(el);
|
||||
setWidth(el.getBoundingClientRect().width);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
|
||||
/** 트랙 위치를 직접 쓴다. 드래그 중에는 transition 을 꺼야 손가락을 따라온다. */
|
||||
const paint = useCallback((offsetPx: number, animated: boolean) => {
|
||||
const track = trackRef.current;
|
||||
if (!track) return;
|
||||
track.style.transition = animated ? `transform ${SNAP_MS}ms cubic-bezier(0.22, 1, 0.36, 1)` : 'none';
|
||||
track.style.transform = `translate3d(${offsetPx}px, 0, 0)`;
|
||||
}, []);
|
||||
|
||||
// index / width 가 바뀌면(바깥 목록 클릭 포함) 제자리로 스냅.
|
||||
useEffect(() => {
|
||||
paint(-index * width, true);
|
||||
}, [index, width, paint]);
|
||||
|
||||
const settle = useCallback(
|
||||
(next: number) => {
|
||||
const clamped = Math.max(0, Math.min(count - 1, next));
|
||||
// ★ 클램프돼서 index 가 그대로면 부모가 리렌더되지 않는다 —
|
||||
// 그러면 끌어당긴 자리에 트랙이 멈춰 버리므로 여기서 직접 되돌린다.
|
||||
paint(-clamped * width, true);
|
||||
if (clamped !== index) onIndexChange(clamped);
|
||||
},
|
||||
[count, index, onIndexChange, paint, width],
|
||||
);
|
||||
|
||||
const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
if (count < 2 || e.button !== 0) return;
|
||||
drag.current = {startX: e.clientX, startTime: e.timeStamp, dx: 0, active: true};
|
||||
setDragging(true);
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
};
|
||||
|
||||
const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
if (!drag.current.active) return;
|
||||
let dx = e.clientX - drag.current.startX;
|
||||
// 양 끝을 넘어가면 저항을 준다 — 끝이라는 게 손에 느껴져야 한다.
|
||||
const atStart = index === 0 && dx > 0;
|
||||
const atEnd = index === count - 1 && dx < 0;
|
||||
if (atStart || atEnd) dx *= EDGE_RESISTANCE;
|
||||
drag.current.dx = dx;
|
||||
paint(-index * width + dx, false);
|
||||
};
|
||||
|
||||
const endDrag = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
if (!drag.current.active) return;
|
||||
const {dx, startTime} = drag.current;
|
||||
drag.current.active = false;
|
||||
setDragging(false);
|
||||
if (e.currentTarget.hasPointerCapture(e.pointerId)) {
|
||||
e.currentTarget.releasePointerCapture(e.pointerId);
|
||||
}
|
||||
|
||||
const elapsed = Math.max(1, e.timeStamp - startTime);
|
||||
const velocity = dx / elapsed; // px/ms
|
||||
const threshold = width * DRAG_RATIO;
|
||||
|
||||
if (dx < -threshold || velocity < -FLICK_VELOCITY) settle(index + 1);
|
||||
else if (dx > threshold || velocity > FLICK_VELOCITY) settle(index - 1);
|
||||
else settle(index);
|
||||
};
|
||||
|
||||
if (count === 0) return null;
|
||||
|
||||
return (
|
||||
<div className={cn('flex flex-col gap-3', className)}>
|
||||
<div
|
||||
ref={viewportRef}
|
||||
className="relative overflow-hidden"
|
||||
role="group"
|
||||
aria-roledescription="carousel"
|
||||
aria-label={label}
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'ArrowRight') settle(index + 1);
|
||||
if (e.key === 'ArrowLeft') settle(index - 1);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={trackRef}
|
||||
onPointerDown={onPointerDown}
|
||||
onPointerMove={onPointerMove}
|
||||
onPointerUp={endDrag}
|
||||
onPointerCancel={endDrag}
|
||||
className={cn(
|
||||
'flex touch-pan-y',
|
||||
count > 1 && (dragging ? 'cursor-grabbing' : 'cursor-grab'),
|
||||
)}
|
||||
>
|
||||
{slides.map((slide, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="shrink-0 grow-0"
|
||||
style={{width: width || '100%'}}
|
||||
aria-hidden={i !== index}
|
||||
>
|
||||
{/* 드래그 중 내부 이미지가 잡히면 브라우저 기본 이미지 드래그와 싸운다. */}
|
||||
<div className={cn('[&_img]:select-none', dragging && 'select-none [&_*]:pointer-events-none')}>
|
||||
{slide}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{count > 1 && (
|
||||
<>
|
||||
<CarouselArrow side="left" disabled={index === 0} onClick={() => settle(index - 1)} />
|
||||
<CarouselArrow
|
||||
side="right"
|
||||
disabled={index === count - 1}
|
||||
onClick={() => settle(index + 1)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showDots && count > 1 && (
|
||||
<div className="flex items-center justify-center gap-1.5">
|
||||
{slides.map((_, i) => (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
aria-label={`${i + 1}번째로 이동`}
|
||||
aria-current={i === index}
|
||||
onClick={() => settle(i)}
|
||||
className={cn(
|
||||
'h-1.5 cursor-pointer rounded-full transition-all',
|
||||
i === index ? 'w-5 bg-foreground' : 'w-1.5 bg-border hover:bg-muted-foreground',
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CarouselArrow({
|
||||
side,
|
||||
disabled,
|
||||
onClick,
|
||||
}: {
|
||||
side: 'left' | 'right';
|
||||
disabled: boolean;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
const Icon = side === 'left' ? ChevronLeft : ChevronRight;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
aria-label={side === 'left' ? '이전' : '다음'}
|
||||
className={cn(
|
||||
'absolute top-1/2 z-20 -translate-y-1/2 rounded-full border border-border bg-card/90 p-1.5 shadow-sm backdrop-blur-sm transition',
|
||||
'disabled:pointer-events-none disabled:opacity-0',
|
||||
'cursor-pointer hover:bg-card',
|
||||
side === 'left' ? 'left-2' : 'right-2',
|
||||
)}
|
||||
>
|
||||
<Icon className="size-4" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user