1280px
설치
이 명령 한 줄이면 필요한 파일과 패키지가 함께 설치돼요.
터미널터미널터미널bash
npx shadcn@latest add https://dsui.vercel.app/r/segmented-control.json파일
components/arc/segmented-control/segmented-control.module.csscomponents/arc/segmented-control/segmented-control.tsx
npm 패키지
motion@^14.2.0
- v1.1.0리퀴드 글래스 변형(variant="liquid-glass")을 더했어요.
- v1.0.0처음 공개했어요.
segmented-control.module.csssegmented-control.module.csssegmented-control.module.csscss
/* The frame can shrink below its content inside flex and grid parents; the track then scrolls inside it. */
.root { display: inline-flex; min-width: 0; max-width: 100%; flex-shrink: 1; border-radius: var(--radius-pill); background: var(--surface-muted); }
/* The track owns the stacking context so the gliding highlight passes under every label, not over earlier ones. */
.track { --fade-start: 0px; --fade-end: 0px; isolation: isolate; display: flex; min-width: 0; gap: 2px; overflow-x: auto; overscroll-behavior-x: contain; padding: 3px; border-radius: inherit; scrollbar-width: none; -webkit-mask-image: linear-gradient(to right, transparent, #000 var(--fade-start), #000 calc(100% - var(--fade-end)), transparent); mask-image: linear-gradient(to right, transparent, #000 var(--fade-start), #000 calc(100% - var(--fade-end)), transparent); }
.track::-webkit-scrollbar { display: none; }
.track[data-fade-start] { --fade-start: 20px; }
.track[data-fade-end] { --fade-end: 20px; }
/* The highlight travels and the label color follows it. An idle item lights a soft pill on hover and sinks a little on press. */
.button { position: relative; flex: 0 0 auto; min-height: var(--control-height-sm); border: 0; border-radius: var(--radius-pill); padding: 0 var(--space-4); background: transparent; color: var(--text-muted); font: inherit; font-size: var(--label-md); font-weight: var(--label-weight); white-space: nowrap; cursor: pointer; -webkit-tap-highlight-color: transparent; transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), transform var(--duration-spring) var(--ease-spring); }
@media (hover: hover) and (pointer: fine) { .button:hover:not([aria-pressed="true"]) { color: var(--foreground); background: var(--control-track-hover); } }
.button:active, .button[aria-pressed="true"] { color: var(--foreground); }
.button:active { transform: scale(.94); }
.selection { position: absolute; z-index: -1; inset: 0; border: 1px solid var(--border); border-radius: inherit; background: var(--surface); box-shadow: var(--shadow-resting); }
/* Liquid glass: the layer paints the frame and shapes the selection as a lens. */
/* In light the lens is a white pill with the resting shadow, so the chosen option reads at a glance even where the glass is quiet. */
.glass .selection { border-color: transparent; background: var(--surface); box-shadow: var(--shadow-resting); }
/* Dark keeps an ink tint instead: a white lens there would outshine the glass. The OS rule mirrors the explicit switch, as in foundation.css. */
:global(:root[data-theme="dark"]) .glass .selection, :global(:root.dark) .glass .selection { border-color: color-mix(in oklab, var(--foreground) 24%, transparent); background: color-mix(in oklab, var(--foreground) 14%, transparent); box-shadow: none; }
@media (prefers-color-scheme: dark) { :global(:root:not([data-theme="light"]):not([data-theme="dark"]):not(.light):not(.dark)) .glass .selection { border-color: color-mix(in oklab, var(--foreground) 24%, transparent); background: color-mix(in oklab, var(--foreground) 14%, transparent); box-shadow: none; } }
.glass .button { color: color-mix(in oklab, var(--foreground) 58%, transparent); }
.glass .button:hover, .glass .button[aria-pressed="true"] { color: var(--foreground); background: transparent; }
.label { position: relative; z-index: 1; display: inline-flex; align-items: center; gap: 6px; }
@media (max-width: 380px) { .button { padding: 0 10px; } }
@media (prefers-reduced-motion: reduce) { .button { transition: none; } .button:active { transform: none; } }
segmented-control.tsxsegmented-control.tsxsegmented-control.tsxtsx
"use client";
import { useEffect, useId, useLayoutEffect, useRef, type KeyboardEvent, type ReactNode } from "react";
import { LayoutGroup, motion } from "motion/react";
import { useReducedMotion } from "../lib/use-reduced-motion";
import { motionTokens } from "../lib/motion-tokens";
import styles from "./segmented-control.module.css";
import { playUiSound } from "../sound/play";
import { LiquidGlassLayer, liquidGlassHost } from "../liquid-glass/liquid-glass-layer";
export interface Segment { value: string; label: string; /** Optional content after the label, such as a badge. */ accessory?: ReactNode; }
export interface SegmentedControlProps {
options: Segment[];
value: string;
onValueChange: (value: string) => void;
label?: string;
/** Called when the pointer or focus reaches an option, before it is chosen. Use it to start loading what that option shows. */
onOptionIntent?: (value: string) => void;
className?: string;
/** `liquid-glass` draws the control as glass with the selection as a raised lens. */
variant?: "default" | "liquid-glass";
}
export default function SegmentedControl({ options, value, onValueChange, label, onOptionIntent, className, variant = "default" }: SegmentedControlProps) {
const id = useId();
const glass = variant === "liquid-glass";
const reduced = useReducedMotion();
const track = useRef<HTMLDivElement>(null);
// When the options are wider than the container, the track scrolls inside itself. Edges fade only on the side with more to see.
useLayoutEffect(() => {
const node = track.current;
if (!node) return;
const edges = () => {
const rest = node.scrollWidth - node.clientWidth - node.scrollLeft;
node.toggleAttribute("data-fade-start", node.scrollLeft > 1);
node.toggleAttribute("data-fade-end", rest > 1);
};
edges();
node.addEventListener("scroll", edges, { passive: true });
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(edges);
observer?.observe(node);
return () => { node.removeEventListener("scroll", edges); observer?.disconnect(); };
}, [options.length]);
// The selected option is always scrolled fully into view, with a little room so it clears the fade.
const first = useRef(true);
useEffect(() => {
const node = track.current;
const button = node?.querySelector<HTMLElement>('[aria-pressed="true"]');
if (!node || !button || node.scrollWidth <= node.clientWidth) { first.current = false; return; }
const room = 20, start = button.offsetLeft - room, end = button.offsetLeft + button.offsetWidth + room - node.clientWidth;
const left = node.scrollLeft > start ? start : node.scrollLeft < end ? end : node.scrollLeft;
if (left !== node.scrollLeft) node.scrollTo({ left: Math.max(0, left), behavior: first.current || reduced ? "auto" : "smooth" });
first.current = false;
}, [value, reduced]);
// Arrow keys, Home and End move the selection like a tab list; only the selected option is a tab stop.
const selectedIndex = Math.max(0, options.findIndex(option => option.value === value));
const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
const last = options.length - 1;
const target = event.key === "ArrowRight" || event.key === "ArrowDown" ? (selectedIndex === last ? 0 : selectedIndex + 1)
: event.key === "ArrowLeft" || event.key === "ArrowUp" ? (selectedIndex === 0 ? last : selectedIndex - 1)
: event.key === "Home" ? 0 : event.key === "End" ? last : -1;
if (target < 0 || !options[target]) return;
event.preventDefault();
playUiSound("tick");
onValueChange(options[target].value);
track.current?.querySelector<HTMLElement>(`[data-value="${CSS.escape(options[target].value)}"]`)?.focus({ preventScroll: true });
};
return <div className={[styles.root, glass ? `${liquidGlassHost} ${styles.glass}` : "", className].filter(Boolean).join(" ")} role="group" aria-label={label}>
{glass ? <LiquidGlassLayer preset="tabs" lens="[data-glass-lens]" /> : null}
<LayoutGroup id={id}><motion.div ref={track} layoutScroll className={styles.track}>
{options.map((option, index) => <button key={option.value} id={`${id}-${option.value}`} className={styles.button} type="button" data-value={option.value} aria-pressed={value === option.value} tabIndex={index === selectedIndex ? 0 : -1} onClick={() => { if (value !== option.value) playUiSound("tick"); onValueChange(option.value); }} onKeyDown={onKeyDown} onPointerEnter={onOptionIntent ? () => onOptionIntent(option.value) : undefined} onFocus={onOptionIntent ? () => onOptionIntent(option.value) : undefined}>
{value === option.value && <motion.span className={styles.selection} data-glass-lens="" layoutId="selection" layoutDependency={value} transition={reduced ? { duration: 0 } : motionTokens.spring.morph} aria-hidden="true" />}
<span className={styles.label}>{option.label}{option.accessory}</span>
</button>)}
</motion.div></LayoutGroup>
</div>;
}
사용된 항목
- 리퀴드 글래스컴포넌트
빛이 굴절하고 물결이 흐르는 유리 면이에요. 원하는 내용을 감싸거나 글자를 유리로 채울 수 있어요.
이 항목을 쓰는 조합
- 문의 섹션블록
문의 양식, 연락 채널, 지점 안내 중에서 고를 수 있는 연락처 섹션이에요.
- 행동 유도 섹션블록
가운데 정렬, 좌우 분할, 배너 세 가지 모양으로 행동을 유도하는 섹션이에요.
기기 프리셋과 끌어서 조절하는 손잡이가 있는 미리보기 틀이에요.
- 문서 사이드바블록
검색, 보기 범위, 접히는 분류가 있는 문서 왼쪽 메뉴예요.
- 자주 묻는 질문블록
아코디언, 분류 열, 검색 세 가지 방식으로 질문과 답을 보여 주는 섹션이에요.
- 히어로 섹션블록
가운데, 분할, 미니멀 세 가지 모양의 첫 화면 소개 섹션이에요.
- 뉴스레터 구독블록
이메일을 받아 구독을 확인해 주고 지난 호를 겹쳐 보여 주는 가입 블록이에요.
- 요금제 비교블록
월간과 연간 결제를 바꿔 가며 두 요금제의 기능을 견줘 보는 블록이에요.
- 설정 패널블록
소리, 화면 모드, 시즌 테마, 글자 크기, 움직임을 한 서랍에 모은 설정 블록이에요. 언어나 계정 같은 묶음도 더할 수 있어요.
- 단계형 설정블록
설정을 두 단계로 보여 주는 블록이에요. 처음에는 소리, 화면, 언어 같은 묶음 목록이 나오고, 하나를 고르면 그 묶음의 화면이 오른쪽에서 밀려 들어와요.
- 사이트 푸터블록
열 링크, 미니멀, 로고 세 가지 모양의 사이트 하단 영역이에요.
- 사이트 헤더블록
기본, 가운데 정렬, 메가 메뉴 세 가지 모양의 사이트 상단 내비게이션이에요.
- 통계 띠블록
핵심 숫자를 보이면 올라가듯 세어 주는 통계 영역이에요.