Skip to content

Edge-Drop is a clipboard shelf on the edge of your screen. Hover to open it. Drag files and images into any app, click to copy text and links. Free and open-source for Windows.

feat(filters): CSS-driven segmented filter bar with separate emoji toggle

Deepender25b1826203983f
diff --git a/src/components/EmojiCategoryBar.tsx b/src/components/EmojiCategoryBar.tsx
index fc639b0..c8e46a2 100644
--- a/src/components/EmojiCategoryBar.tsx
+++ b/src/components/EmojiCategoryBar.tsx
@@ -7,7 +7,7 @@ import { loadRecents } from '../lib/emoji/prefs'
import { useStore } from '../store/appStore'
import { playButtonClickSound } from '../lib/soundEffects'
import { useTranslation } from '../i18n'
-import RubberSegment from './RubberSegment'
+import { SegmentedControl } from './SegmentedControl'
import {
EmojiSmileIcon,
EmojiClockIcon,
@@ -34,13 +34,14 @@ export const CATEGORY_ICONS: Record<EmojiCategoryId, IconCmp> = {
}
export interface EmojiCategoryBarProps {
+ /** Which dock the bar is in. The control is the same size in both. */
isHorizontal?: boolean
className?: string
/** Hover-intent hook: warm a category's first screen before it's clicked. */
onHoverCategory?: (id: EmojiCategoryId) => void
}
-export function EmojiCategoryBar({ isHorizontal = false, className = '', onHoverCategory }: EmojiCategoryBarProps) {
+export function EmojiCategoryBar({ className = '', onHoverCategory }: EmojiCategoryBarProps) {
const { t } = useTranslation()
const category = useStore((s) => s.emojiCategory)
const setCategory = useStore((s) => s.setEmojiCategory)
@@ -64,46 +65,20 @@ export function EmojiCategoryBar({ isHorizontal = false, className = '', onHover
[setCategory]
)
- const slotSize = isHorizontal ? 28 : 24
- const trackHeight = isHorizontal ? 30 : 28
- const iconSize = isHorizontal ? 14 : 14
+ const reduceMotion = useStore((s) => !!s.settings.reduceMotion)
return (
- <div
- className={`emoji-cat-bar${className ? ` ${className}` : ''}`}
- role="tablist"
- aria-label={t('emoji.categories')}
- style={{ margin: 0 }}
- >
- <RubberSegment
+ <div className={`emoji-cat-bar${className ? ` ${className}` : ''}`} style={{ margin: 0 }}>
+ <SegmentedControl
items={shownCats.map((c) => {
const Icon = CATEGORY_ICONS[c.id]
- const label = t(c.labelKey)
- return {
- value: c.id,
- label,
- title: label,
- icon: <Icon width={iconSize} height={iconSize} />
- }
+ return { value: c.id, label: t(c.labelKey), icon: <Icon width={14} height={14} /> }
})}
value={category}
- onChange={(val) => selectCategory(val as EmojiCategoryId)}
- trackColor="#141414"
- thumbColor="#ffffff"
- textColor="rgba(255, 255, 255, 0.72)"
- activeTextColor="#000000"
- size="custom"
- height={trackHeight}
- minWidth={slotSize}
- radius={9999}
- inset={2}
- equalSlots={true}
- stretch={80}
- squash={2}
- glide={60}
- draggable={true}
- onHoverItem={onHoverCategory ? (val) => onHoverCategory(val as EmojiCategoryId) : undefined}
- aria-label={t('emoji.categories')}
+ onChange={(val) => selectCategory(val)}
+ onHoverItem={onHoverCategory}
+ ariaLabel={t('emoji.categories')}
+ reduceMotion={reduceMotion}
/>
</div>
)
diff --git a/src/components/Header.tsx b/src/components/Header.tsx
index 2054151..4ef1c3a 100644
--- a/src/components/Header.tsx
+++ b/src/components/Header.tsx
@@ -1,5 +1,5 @@
import { useStore } from '../store/appStore'
-import RubberSegment from './RubberSegment'
+import { SegmentedControl } from './SegmentedControl'
import { GearIcon, CloseIcon, InfoIcon, ClockIcon, TypeIcon, LinkIcon, ImageIcon, FilesIcon, PaletteIcon, EmojiSmileIcon } from './icons'
import { playButtonClickSound } from '../lib/soundEffects'
import { loadEmojiCatalog } from '../lib/emoji/load'
@@ -52,7 +52,7 @@ export function Header({ isHorizontal = false, itemCount, clearProps }: HeaderPr
const setEmojiOpen = useStore((s) => s.setEmojiOpen)
const FILTERS: {
- id: import('../../shared/types').TypeFilter | 'emoji'
+ id: TypeFilter
label: string
Icon: typeof ClockIcon
}[] = [
@@ -61,14 +61,9 @@ export function Header({ isHorizontal = false, itemCount, clearProps }: HeaderPr
{ id: 'links', label: t('filters.links'), Icon: LinkIcon },
{ id: 'images', label: t('filters.images'), Icon: ImageIcon },
{ id: 'files', label: t('filters.files'), Icon: FilesIcon },
- { id: 'colors', label: t('filters.colors') || 'Colors', Icon: PaletteIcon },
- { id: 'emoji', label: t('emoji.open'), Icon: EmojiSmileIcon }
+ { id: 'colors', label: t('filters.colors') || 'Colors', Icon: PaletteIcon }
]
- const activeId: (typeof FILTERS)[number]['id'] = emojiOpen ? 'emoji' : typeFilter
- const filterSlotSize = isHorizontal ? 26 : 24
- const filterTrackHeight = isHorizontal ? 30 : 28
- const filterIconSize = isHorizontal ? 14 : 13
const reduceMotion = !!settings.reduceMotion
const headerFade = `opacity ${reduceMotion ? '0.01s' : '0.16s'} ease`
@@ -106,11 +101,7 @@ export function Header({ isHorizontal = false, itemCount, clearProps }: HeaderPr
position: 'relative',
display: 'flex',
alignItems: 'center',
- background: 'transparent',
- border: 'none',
- borderRadius: 999,
- padding: 0,
- marginLeft: 0,
+ gap: 6,
maxWidth: '100%',
overflow: 'visible',
opacity: settingsOpen ? 0 : 1,
@@ -118,39 +109,39 @@ export function Header({ isHorizontal = false, itemCount, clearProps }: HeaderPr
transition: headerFade
}}
>
- <RubberSegment
+ {/* Type filters. With the emoji picker open no filter is shown as
+ selected; picking one closes the picker (setTypeFilter). */}
+ <SegmentedControl
items={FILTERS.map((f) => ({
value: f.id,
label: f.label,
- title: f.label,
- icon: <f.Icon width={filterIconSize} height={filterIconSize} />
+ icon: <f.Icon width={14} height={14} />
}))}
- value={activeId}
+ value={emojiOpen ? null : typeFilter}
onChange={(val) => {
playButtonClickSound()
- if (val === 'emoji') setEmojiOpen(true)
- else setTypeFilter(val as TypeFilter)
- }}
- onHoverItem={(val) => {
- if (val === 'emoji') void loadEmojiCatalog()
+ setTypeFilter(val)
}}
- trackColor="#141414"
- thumbColor="#ffffff"
- textColor="rgba(255, 255, 255, 0.72)"
- activeTextColor="#000000"
- size="custom"
- height={filterTrackHeight}
- minWidth={filterSlotSize}
- radius={9999}
- inset={2}
- equalSlots={true}
- stretch={80}
- squash={2}
- glide={60}
- draggable={true}
+ ariaLabel={t('filters.title') || 'Filters'}
+ reduceMotion={reduceMotion}
tabIndex={settingsOpen ? -1 : undefined}
- aria-label={t('filters.title') || 'Filters'}
/>
+ {/* Emoji is a separate view, not a filter, so it gets its own toggle. */}
+ <button
+ type="button"
+ className={`emoji-mode-btn${emojiOpen ? ' active' : ''}`}
+ aria-pressed={emojiOpen}
+ aria-label={t('emoji.open')}
+ title={t('emoji.open')}
+ tabIndex={settingsOpen ? -1 : undefined}
+ onPointerEnter={() => void loadEmojiCatalog()}
+ onClick={() => {
+ playButtonClickSound()
+ setEmojiOpen(!emojiOpen)
+ }}
+ >
+ <EmojiSmileIcon width={14} height={14} />
+ </button>
</div>
{isHorizontal ? (
<div
diff --git a/src/components/RubberSegment.tsx b/src/components/RubberSegment.tsx
deleted file mode 100644
index a4c2eef..0000000
--- a/src/components/RubberSegment.tsx
+++ /dev/null
@@ -1,493 +0,0 @@
-/**
- * RubberSegment — rubber-band elastic segmented control with momentum gliding and clip-path thumb.
- *
- * Adapted for TypeScript and Framer Motion v11.
- */
-import {
- useEffect,
- useLayoutEffect,
- useRef,
- useState,
- type ReactNode
-} from 'react'
-import {
- animate,
- motion,
- useMotionValue,
- useReducedMotion,
- useTransform,
- type MotionValue
-} from 'framer-motion'
-
-import '../styles/RubberSegment.css'
-
-const EASE_OUT = [0.23, 1, 0.32, 1] as const
-const SPRING_UI = { type: 'spring' as const, duration: 0.3, bounce: 0 }
-const SPRING_MOMENTUM = { type: 'spring' as const, duration: 0.4, bounce: 0.2 }
-const SPRING_RELAX = { type: 'spring' as const, duration: 0.16, bounce: 0 }
-const DILATE = 0.19
-const HANDOFF = 0.15
-const FLICK = 110
-const MAX_VELOCITY = 2000
-const DEADZONE = 4
-const SLOP = 10
-const RUBBER = 0.55
-
-const SIZES = {
- sm: { height: 26, font: 12, pad: 0, min: 22 },
- md: { height: 28, font: 13, pad: 0, min: 24 },
- lg: { height: 36, font: 13, pad: 14, min: 44 }
-}
-
-const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))
-const rubber = (over: number, dim: number) => (over * dim * RUBBER) / (dim + RUBBER * Math.abs(over))
-const project = (v: number, glide: number) => {
- const d = 1 - 0.1 * Math.pow(0.05, glide / 100)
- return ((v / 1000) * d) / (1 - d)
-}
-const velocityOf = (hist: [number, number][], now: number) => {
- const recent = hist.filter(([t]) => now - t <= 100)
- if (recent.length < 2) return 0
- const [t0, x0] = recent[0]
- const [t1, x1] = recent[recent.length - 1]
- return t1 - t0 >= 8 ? ((x1 - x0) / (t1 - t0)) * 1000 : 0
-}
-const nearestSlot = (slots: { l: number; r: number }[], x: number) => {
- let best = 0
- for (let i = 1; i < slots.length; i++) {
- if (Math.abs((slots[i].l + slots[i].r) / 2 - x) < Math.abs((slots[best].l + slots[best].r) / 2 - x)) best = i
- }
- return best
-}
-
-export interface RubberSegmentItem<T extends string = string> {
- value: T
- label: string
- icon?: ReactNode
- title?: string
- disabled?: boolean
-}
-
-export interface RubberSegmentProps<T extends string = string> {
- items: (RubberSegmentItem<T> | string)[]
- value?: T
- defaultValue?: T
- onChange?: (value: T, index: number) => void
- onHoverItem?: (value: T) => void
- trackColor?: string
- thumbColor?: string
- textColor?: string
- activeTextColor?: string
- size?: 'sm' | 'md' | 'lg' | 'custom'
- height?: number
- minWidth?: number
- padding?: number
- radius?: number
- inset?: number
- equalSlots?: boolean
- stretch?: number
- squash?: number
- speed?: number
- glide?: number
- draggable?: boolean
- disabled?: boolean
- className?: string
- 'aria-label'?: string
- tabIndex?: number
-}
-
-interface DragState {
- id: number
- x0: number
- slot: number
- onThumb: boolean
- live: boolean
- offset: number
- w: number
- hist: [number, number][]
-}
-
-export default function RubberSegment<T extends string = string>({
- items,
- value,
- defaultValue,
- onChange,
- onHoverItem,
- trackColor = '#141414',
- thumbColor = '#ffffff',
- textColor = 'rgba(255, 255, 255, 0.72)',
- activeTextColor = '#000000',
- size = 'md',
- height,
- minWidth,
- padding,
- radius = 9999,
- inset = 2,
- equalSlots = true,
- stretch = 80,
- squash = 2,
- speed = 1,
- glide = 60,
- draggable = true,
- disabled = false,
- className = '',
- 'aria-label': ariaLabel = 'Segmented control',
- tabIndex
-}: RubberSegmentProps<T>) {
- const list: RubberSegmentItem<T>[] = items.map((item) =>
- typeof item === 'string' ? { value: item as T, label: item } : item
- )
- const [inner, setInner] = useState<T>(() => (defaultValue ?? list[0]?.value) as T)
- const current = value !== undefined ? value : inner
- const index = Math.max(
- 0,
- list.findIndex((item) => item.value === current)
- )
- const reduce = useReducedMotion()
-
- const trackRef = useRef<HTMLDivElement | null>(null)
- const thumbRef = useRef<HTMLDivElement | null>(null)
- const itemRefs = useRef<(HTMLButtonElement | null)[]>([])
- const slots = useRef<{ l: number; r: number }[]>([])
- const box = useRef<DOMRect | null>(null)
- const committed = useRef(index)
- const handoff = useRef<number | null>(null)
- const drag = useRef<DragState | null>(null)
- const gen = useRef(0)
-
- // edgeL starts far off-canvas so the very first paint renders the thumb
- // fully clipped (invisible) instead of a full-width white flash: measured
- // slot values set in the layout effect only reach the DOM on a later frame
- // (motion values apply asynchronously), and 0/0/0 means zero clipping.
- const edgeL = useMotionValue(10000)
- const edgeR = useMotionValue(0)
- const innerW = useMotionValue(0)
- const thumbRadius = Math.max(0, radius - inset)
- const clipPath = useTransform(
- () => `inset(0px ${Math.max(0, innerW.get() - edgeR.get())}px 0px ${Math.max(0, edgeL.get())}px round ${thumbRadius}px)`
- )
-
- const t = (seconds: number) => seconds / speed
-
- const jumpTo = (i: number) => {
- const s = slots.current[i]
- if (!s) return
- if (handoff.current) clearTimeout(handoff.current)
- gen.current += 1
- edgeL.set(s.l)
- edgeR.set(s.r)
- }
-
- // Returns true when the track had real layout. Also writes the computed
- // clip straight onto the thumb element: motion values reach the DOM
- // asynchronously, so without this the first paint can show a stale clip
- // (full-white flash, or a never-appearing thumb if timing slips). The
- // string matches the motion path exactly, so framer taking over later
- // causes no visual jump.
- const measure = (): boolean => {
- const track = trackRef.current
- if (!track) return false
- const rect = track.getBoundingClientRect()
- box.current = rect
- slots.current = list.map((_, i) => {
- const el = itemRefs.current[i]
- if (!el) return { l: 0, r: 0 }
- const r = el.getBoundingClientRect()
- return { l: r.left - rect.left - inset, r: r.right - rect.left - inset }
- })
- innerW.set(rect.width - inset * 2)
- jumpTo(committed.current)
- try {
- const el = thumbRef.current
- const s = slots.current[committed.current]
- if (el && s) {
- const w = Math.max(0, rect.width - inset * 2)
- el.style.clipPath =
- `inset(0px ${Math.max(0, w - s.r)}px 0px ${Math.max(0, s.l)}px round ${thumbRadius}px)`
- }
- } catch { /* ignore */ }
- return rect.width > 0
- }
-
- const listKey = list.map((item) => item.value).join('|')
- useLayoutEffect(() => {
- const laidOut = measure()
- // Backstop: if the track had no layout yet (mounted hidden), retry on
- // frames (bounded) until it does, so the thumb can never stick hidden.
- // The ResizeObserver below is the primary path for show events.
- let tries = 0
- let raf = 0
- if (!laidOut) {
- const ensure = () => {
- if (measure()) return
- if (tries++ < 60) raf = requestAnimationFrame(ensure)
- }
- raf = requestAnimationFrame(ensure)
- }
- const observer = new ResizeObserver(() => measure())
- if (trackRef.current) observer.observe(trackRef.current)
- if (typeof document !== 'undefined' && (document as Document).fonts) {
- void (document as Document).fonts.ready.then(() => measure()).catch(() => {})
- }
- return () => {
- cancelAnimationFrame(raf)
- observer.disconnect()
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [listKey, size, inset, equalSlots, height, minWidth])
-
- useEffect(() => {
- if (!drag.current && committed.current !== index) {
- committed.current = index
- jumpTo(index)
- }
- })
-
- useEffect(
- () => () => {
- if (handoff.current) clearTimeout(handoff.current)
- edgeL.stop()
- edgeR.stop()
- },
- [edgeL, edgeR]
- )
-
- const commit = (i: number) => {
- committed.current = i
- if (i === index) return
- if (value === undefined) setInner(list[i].value)
- onChange?.(list[i].value, i)
- }
-
- const land = (to: number, v: number | null, flick: boolean, withSquash: boolean) => {
- const b = slots.current[to]
- if (!b) return
- const g = ++gen.current
- const dir = Math.sign((b.l + b.r) / 2 - (edgeL.get() + edgeR.get()) / 2) || 1
- const [lead, leadTo, trail, trailTo] = dir > 0 ? [edgeR, b.r, edgeL, b.l] : [edgeL, b.l, edgeR, b.r]
- const velocityFor = (mv: MotionValue<number>) =>
- clamp(v === null ? mv.getVelocity() : v, -MAX_VELOCITY, MAX_VELOCITY)
- animate(lead, leadTo, {
- ...(flick ? SPRING_MOMENTUM : SPRING_UI),
- duration: t(flick ? 0.4 : 0.3),
- velocity: velocityFor(lead)
- })
- const trailVelocity = velocityFor(trail)
- if (!withSquash || squash <= 0) {
- animate(trail, trailTo, { ...SPRING_UI, duration: t(0.3), velocity: trailVelocity })
- return
- }
- void animate(trail, trailTo + dir * squash, {
- ...SPRING_UI,
- duration: t(0.3),
- velocity: trailVelocity
- }).then(() => {
- if (gen.current === g) animate(trail, trailTo, { ...SPRING_RELAX, duration: t(0.16) })
- })
- }
-
- const travel = (from: number, to: number) => {
- const a = slots.current[from]
- const b = slots.current[to]
- if (!a || !b) return
- if (handoff.current) clearTimeout(handoff.current)
- gen.current += 1
- if (reduce) {
- edgeL.set(b.l)
- edgeR.set(b.r)
- return
- }
- const u = stretch / 100
- const tween = { duration: t(DILATE), ease: EASE_OUT }
- animate(edgeL, b.l + (Math.min(a.l, b.l) - b.l) * u, tween)
- animate(edgeR, b.r + (Math.max(a.r, b.r) - b.r) * u, tween)
- handoff.current = window.setTimeout(() => land(to, null, false, true), t(HANDOFF) * 1000)
- }
-
- const localX = (e: React.PointerEvent | PointerEvent) =>
- e.clientX - (box.current ? box.current.left : 0) - inset
-
- const handlePointerDown = (e: React.PointerEvent<HTMLButtonElement>, i: number) => {
- if (disabled || drag.current || e.button !== 0) return
- if (!trackRef.current) return
- box.current = trackRef.current.getBoundingClientRect()
- try {
- e.currentTarget.setPointerCapture(e.pointerId)
- } catch {}
- const x = localX(e)
- const onThumb = draggable && x >= edgeL.get() && x <= edgeR.get()
- drag.current = {
- id: e.pointerId,
- x0: x,
- slot: i,
- onThumb,
- live: false,
- offset: 0,
- w: 0,
- hist: [[e.timeStamp, x]]
- }
- if (onThumb) {
- if (handoff.current) clearTimeout(handoff.current)
- gen.current += 1
- edgeL.stop()
- edgeR.stop()
- } else if (!reduce) {
- e.currentTarget.dataset.pressed = ''
- }
- }
-
- const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
- const d = drag.current
- if (!d || e.pointerId !== d.id || !d.onThumb) return
- const x = localX(e)
- d.hist.push([e.timeStamp, x])
- if (d.hist.length > 8) d.hist.shift()
- if (!d.live) {
- if (Math.abs(x - d.x0) < DEADZONE) return
- d.live = true
- d.offset = x - edgeL.get()
- d.w = edgeR.get() - edgeL.get()
- if (trackRef.current) trackRef.current.dataset.held = ''
- }
- const width = innerW.get()
- const l = x - d.offset
- const maxL = width - d.w
- if (reduce) {
- const c = clamp(l, 0, maxL)
- edgeL.set(c)
- edgeR.set(c + d.w)
- } else if (l < 0) {
- edgeL.set(0)
- edgeR.set(d.w - rubber(-l, d.w))
- } else if (l > maxL) {
- edgeR.set(width)
- edgeL.set(maxL + rubber(l - maxL, d.w))
- } else {
- edgeL.set(l)
- edgeR.set(l + d.w)
- }
- }
-
- const release = () => {
- const d = drag.current
- if (!d) return null
- drag.current = null
- if (trackRef.current) delete trackRef.current.dataset.held
- const el = itemRefs.current[d.slot]
- if (el) delete el.dataset.pressed
- return d
- }
-
- const handlePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
- const d = drag.current
- if (!d || e.pointerId !== d.id) return
- release()
- const x = localX(e)
- if (!d.live) {
- if (Math.abs(x - d.x0) <= SLOP && d.slot !== committed.current) {
- const from = committed.current
- commit(d.slot)
- travel(from, d.slot)
- }
- return
- }
- const v = velocityOf(d.hist, e.timeStamp)
- const flick = Math.abs(v) > FLICK
- let to = nearestSlot(slots.current, (edgeL.get() + edgeR.get()) / 2 + project(v, glide))
- if (flick && to === committed.current) to = clamp(to + Math.sign(v), 0, list.length - 1)
- commit(to)
- if (reduce) jumpTo(to)
- else land(to, v, flick, flick)
- }
-
- const handlePointerCancel = (e: React.PointerEvent<HTMLDivElement>) => {
- const d = drag.current
- if (!d || e.pointerId !== d.id) return
- release()
- if (!d.live) return
- if (reduce) jumpTo(committed.current)
- else land(committed.current, null, false, false)
- }
-
- const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {
- if (disabled) return
- const last = list.length - 1
- let next: number | null = null
- if (e.key === 'ArrowRight' || e.key === 'ArrowDown') next = Math.min(last, index + 1)
- else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') next = Math.max(0, index - 1)
- else if (e.key === 'Home') next = 0
- else if (e.key === 'End') next = last
- if (next === null) return
- e.preventDefault()
- if (next === index) return
- const from = committed.current
- commit(next)
- travel(from, next)
- itemRefs.current[next]?.focus()
- }
-
- const preset = size !== 'custom' ? SIZES[size] || SIZES.md : null
- const effH = height ?? preset?.height ?? 28
- const effPad = padding ?? preset?.pad ?? 0
- const effMin = minWidth ?? preset?.min ?? 28
-
- return (
- <div
- ref={trackRef}
- role="radiogroup"
- aria-label={ariaLabel}
- aria-disabled={disabled || undefined}
- data-equal={equalSlots ? '' : undefined}
- data-draggable={draggable && !disabled ? '' : undefined}
- className={`rubber-segment${className ? ` ${className}` : ''}`}
- style={{
- '--rs-track': trackColor,
- '--rs-thumb': thumbColor,
- '--rs-ink': textColor,
- '--rs-ink-active': activeTextColor,
- '--rs-radius': `${radius}px`,
- '--rs-inset': `${inset}px`,
- '--rs-thumb-radius': `${thumbRadius}px`,
- '--rs-h': `${effH}px`,
- '--rs-font': `${preset?.font ?? 13}px`,
- '--rs-pad': `${effPad}px`,
- '--rs-min': `${effMin}px`
- } as React.CSSProperties}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
- onPointerCancel={handlePointerCancel}
- onLostPointerCapture={handlePointerCancel}
- >
- {list.map((item, i) => (
- <button
- key={item.value}
- ref={(el) => {
- itemRefs.current[i] = el
- }}
- type="button"
- role="radio"
- aria-checked={i === index}
- aria-label={item.label}
- title={item.title || item.label}
- tabIndex={tabIndex !== undefined ? tabIndex : i === index ? 0 : -1}
- disabled={disabled || !!item.disabled}
- className="rubber-segment__item"
- onPointerDown={(e) => handlePointerDown(e, i)}
- onPointerEnter={() => onHoverItem?.(item.value)}
- onKeyDown={handleKeyDown}
- >
- {item.icon}
- {effPad > 0 && item.label ? <span className="rubber-segment__label">{item.label}</span> : null}
- </button>
- ))}
- <motion.div ref={thumbRef} className="rubber-segment__thumb" aria-hidden="true" style={{ clipPath }}>
- {list.map((item) => (
- <span key={item.value} className="rubber-segment__item rubber-segment__copy">
- {item.icon}
- {effPad > 0 && item.label ? <span className="rubber-segment__label">{item.label}</span> : null}
- </span>
- ))}
- </motion.div>
- </div>
- )
-}
diff --git a/src/components/SegmentedControl.tsx b/src/components/SegmentedControl.tsx
new file mode 100644
index 0000000..d77d0e5
--- /dev/null
+++ b/src/components/SegmentedControl.tsx
@@ -0,0 +1,180 @@
+/**
+ * SegmentedControl — icon segmented control used by the shelf filter bar and
+ * the emoji category bar.
+ *
+ * Geometry is pure CSS: every slot has the same fixed width, so the thumb's
+ * position is just `--i × slot`. Nothing is measured, so it can never drift
+ * out of line with the icons.
+ *
+ * The thumb is a white pill that clips a second, black copy of the icons.
+ * The thumb slides by +i slots and the copy inside it by −i slots, both with
+ * the same spring, so the copy stays still and an icon reads black exactly
+ * where the thumb covers it. Both are CSS translate transitions, so the
+ * browser's compositor runs them with no per-frame JS.
+ *
+ * Pointer: the thumb follows the pointer from the moment it goes down (and
+ * slides along if you drag across the slots); the choice commits on release,
+ * so a press can still be cancelled by dragging back.
+ */
+import { useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent, type ReactNode } from 'react'
+
+import '../styles/SegmentedControl.css'
+
+export interface SegmentedItem<T extends string> {
+ value: T
+ label: string
+ icon: ReactNode
+}
+
+export interface SegmentedControlProps<T extends string> {
+ items: SegmentedItem<T>[]
+ /** Selected value; `null` (or a value not in `items`) shows no thumb. */
+ value: T | null
+ onChange: (value: T) => void
+ /** Pointer entered a slot (used to warm data before a click). */
+ onHoverItem?: (value: T) => void
+ ariaLabel: string
+ /** Snap instead of sliding (the app's Reduce motion setting). */
+ reduceMotion?: boolean
+ /** -1 removes every slot from the tab order (control hidden). */
+ tabIndex?: number
+ className?: string
+}
+
+export function SegmentedControl<T extends string>({
+ items,
+ value,
+ onChange,
+ onHoverItem,
+ ariaLabel,
+ reduceMotion = false,
+ tabIndex,
+ className = ''
+}: SegmentedControlProps<T>) {
+ const selected = items.findIndex((item) => item.value === value)
+ const [preview, setPreview] = useState<number | null>(null)
+
+ // With nothing selected the thumb fades out where it last was, so it
+ // slides from there (rather than from slot 0) when a slot is chosen again.
+ const lastShown = useRef(Math.max(0, selected))
+ const shown = preview ?? (selected >= 0 ? selected : lastShown.current)
+ lastShown.current = shown
+ const thumbHidden = preview === null && selected < 0
+
+ const trackRef = useRef<HTMLDivElement | null>(null)
+ const itemRefs = useRef<(HTMLButtonElement | null)[]>([])
+ // The live press lives in a ref (not state) so the release handler always
+ // sees the latest slot, even if React has not re-rendered since the move.
+ const press = useRef<{ id: number; slots: { l: number; r: number }[]; at: number } | null>(null)
+
+ const commit = (i: number) => {
+ const item = items[i]
+ if (item && i !== selected) onChange(item.value)
+ }
+
+ const slotAt = (clientX: number): number => {
+ const slots = press.current?.slots ?? []
+ for (let i = 0; i < slots.length; i++) if (clientX < slots[i].r) return i
+ return slots.length - 1
+ }
+
+ const handlePointerDown = (e: PointerEvent<HTMLButtonElement>, i: number) => {
+ if (e.button !== 0 || press.current) return
+ const track = trackRef.current
+ if (!track) return
+ press.current = {
+ id: e.pointerId,
+ slots: itemRefs.current.map((el) => {
+ const r = el?.getBoundingClientRect()
+ return { l: r?.left ?? 0, r: r?.right ?? 0 }
+ }),
+ at: i
+ }
+ try { track.setPointerCapture(e.pointerId) } catch { /* ignore */ }
+ setPreview(i)
+ }
+
+ const handlePointerMove = (e: PointerEvent<HTMLDivElement>) => {
+ if (!press.current || e.pointerId !== press.current.id) return
+ const i = slotAt(e.clientX)
+ if (i !== press.current.at) {
+ press.current.at = i
+ setPreview(i)
+ }
+ }
+
+ const handlePointerUp = (e: PointerEvent<HTMLDivElement>) => {
+ if (!press.current || e.pointerId !== press.current.id) return
+ const target = press.current.at
+ press.current = null
+ setPreview(null)
+ commit(target)
+ }
+
+ // Lost capture or cancel before release: drop the preview, keep the value.
+ const handlePointerAbort = (e: PointerEvent<HTMLDivElement>) => {
+ if (!press.current || e.pointerId !== press.current.id) return
+ press.current = null
+ setPreview(null)
+ }
+
+ const handleKeyDown = (e: KeyboardEvent<HTMLButtonElement>, i: number) => {
+ const last = items.length - 1
+ let next: number | null = null
+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') next = Math.min(last, i + 1)
+ else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') next = Math.max(0, i - 1)
+ else if (e.key === 'Home') next = 0
+ else if (e.key === 'End') next = last
+ if (next === null) return
+ e.preventDefault()
+ commit(next)
+ itemRefs.current[next]?.focus()
+ }
+
+ return (
+ <div
+ ref={trackRef}
+ role="radiogroup"
+ aria-label={ariaLabel}
+ className={`seg${reduceMotion ? ' seg--instant' : ''}${className ? ` ${className}` : ''}`}
+ data-empty={thumbHidden ? '' : undefined}
+ data-held={preview !== null ? '' : undefined}
+ style={{ '--i': shown } as CSSProperties}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ onPointerCancel={handlePointerAbort}
+ onLostPointerCapture={handlePointerAbort}
+ >
+ {items.map((item, i) => (
+ <button
+ key={item.value}
+ ref={(el) => { itemRefs.current[i] = el }}
+ type="button"
+ role="radio"
+ aria-checked={i === selected}
+ aria-label={item.label}
+ title={item.label}
+ tabIndex={tabIndex ?? (i === (selected >= 0 ? selected : 0) ? 0 : -1)}
+ className="seg__item"
+ onPointerDown={(e) => handlePointerDown(e, i)}
+ onPointerEnter={onHoverItem ? () => onHoverItem(item.value) : undefined}
+ // Keyboard activation (Enter/Space) arrives as a click with detail 0;
+ // pointer clicks are already handled on release above.
+ onClick={(e) => { if (e.detail === 0) commit(i) }}
+ onKeyDown={(e) => handleKeyDown(e, i)}
+ >
+ {item.icon}
+ </button>
+ ))}
+ <div className="seg__thumb" aria-hidden="true">
+ <div className="seg__ink">
+ {items.map((item) => (
+ <span key={item.value} className="seg__slot">{item.icon}</span>
+ ))}
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default SegmentedControl
diff --git a/src/styles/RubberSegment.css b/src/styles/RubberSegment.css
deleted file mode 100644
index a309142..0000000
--- a/src/styles/RubberSegment.css
+++ /dev/null
@@ -1,136 +0,0 @@
-/* ---- RubberSegment.css ---- */
-.rubber-segment {
- --rs-track: var(--bg-card, #141414);
- --rs-thumb: #ffffff;
- --rs-ink: rgba(255, 255, 255, 0.72);
- --rs-ink-active: #000000;
- --rs-radius: 9999px;
- --rs-inset: 2px;
- --rs-thumb-radius: 9999px;
- --rs-h: 28px;
- --rs-font: 13px;
- --rs-pad: 0px;
- --rs-min: 24px;
- --rs-idle: 1;
- --rs-hover: 1;
- --rs-ease-out: cubic-bezier(0.23, 1, 0.32, 1);
-
- position: relative;
- display: inline-grid;
- grid-auto-flow: column;
- grid-auto-columns: auto;
- align-items: center;
- vertical-align: middle;
- padding: var(--rs-inset);
- border-radius: var(--rs-radius);
- background: var(--rs-track);
- border: 1px solid rgba(255, 255, 255, 0.08);
- font-family: inherit;
- touch-action: pan-y;
- user-select: none;
- -webkit-user-select: none;
- -webkit-touch-callout: none;
- -webkit-tap-highlight-color: transparent;
- box-sizing: border-box;
-}
-
-.rubber-segment[data-equal] {
- grid-auto-columns: minmax(0, 1fr);
-}
-
-.rubber-segment[aria-disabled='true'] {
- opacity: 0.5;
- pointer-events: none;
-}
-
-.rubber-segment__item {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- height: calc(var(--rs-h) - var(--rs-inset) * 2);
- min-width: var(--rs-min);
- margin: 0;
- padding: 0 var(--rs-pad);
- border: 0;
- border-radius: var(--rs-thumb-radius);
- background: none;
- color: var(--rs-ink);
- font: inherit;
- font-size: var(--rs-font);
- font-weight: 500;
- line-height: 1;
- white-space: nowrap;
- cursor: pointer;
- outline: none;
- box-sizing: border-box;
- transition:
- color 140ms ease,
- opacity 140ms ease,
- transform 140ms var(--rs-ease-out);
-}
-
-.rubber-segment__item[aria-checked='true'] {
- cursor: default;
-}
-
-.rubber-segment[data-draggable] .rubber-segment__item[aria-checked='true'] {
- cursor: grab;
-}
-
-.rubber-segment[data-held],
-.rubber-segment[data-held] .rubber-segment__item {
- cursor: grabbing;
-}
-
-.rubber-segment__item[data-pressed] {
- transform: scale(0.94);
-}
-
-.rubber-segment__item:focus-visible {
- outline: 2px solid rgba(255, 255, 255, 0.4);
- outline-offset: 2px;
-}
-
-@media (hover: hover) and (pointer: fine) {
- .rubber-segment__item[aria-checked='false']:hover {
- color: #ffffff;
- }
-}
-
-.rubber-segment__thumb {
- position: absolute;
- inset: var(--rs-inset);
- display: grid;
- grid-auto-flow: column;
- grid-auto-columns: auto;
- align-items: center;
- background: var(--rs-thumb);
- color: var(--rs-ink-active);
- border-radius: var(--rs-thumb-radius);
- pointer-events: none;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
-}
-
-.rubber-segment[data-equal] .rubber-segment__thumb {
- grid-auto-columns: minmax(0, 1fr);
-}
-
-.rubber-segment__copy {
- color: var(--rs-ink-active);
- opacity: 1;
- cursor: default;
- display: inline-flex;
- align-items: center;
- justify-content: center;
-}
-
-.rubber-segment__label {
- display: inline-block;
- line-height: 1;
-}
-
-@media (prefers-reduced-motion: reduce) {
- .rubber-segment__item {
- transition: opacity 160ms ease;
- }
-}
diff --git a/src/styles/SegmentedControl.css b/src/styles/SegmentedControl.css
new file mode 100644
index 0000000..3a3986f
--- /dev/null
+++ b/src/styles/SegmentedControl.css
@@ -0,0 +1,156 @@
+/* ---- SegmentedControl.css ----
+ Borderless pill track in the same surface colour as the search field,
+ fixed 26px slots, 30px tall (the thumb is a 26px circle). */
+.seg {
+ --seg-slot: 26px;
+ --seg-h: 30px;
+ --seg-pad: 2px;
+ /* Spring: response 0.28s, damping 0.86, ends where it first reaches the slot. */
+ --seg-motion: 228ms linear(0, 0.006 2.3%, 0.026 4.8%, 0.059 7.5%, 0.11 10.8%, 0.195 15.3%, 0.455 28%, 0.561 33.8%, 0.648 39%, 0.722 44.3%, 0.785 49.5%, 0.84 55%, 0.886 61%, 0.925 67.5%, 0.956 74.8%, 0.979 83.3%, 0.995 94%, 1);
+
+ position: relative;
+ display: inline-grid;
+ grid-auto-flow: column;
+ grid-auto-columns: var(--seg-slot);
+ flex-shrink: 0;
+ height: var(--seg-h);
+ padding: var(--seg-pad);
+ box-sizing: border-box;
+ border-radius: 999px;
+ background: var(--bg-card, #141414);
+ touch-action: none;
+ user-select: none;
+ -webkit-user-select: none;
+ -webkit-tap-highlight-color: transparent;
+}
+
+.seg__item {
+ display: grid;
+ place-items: center;
+ width: var(--seg-slot);
+ height: 100%;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ border-radius: 999px;
+ background: none;
+ color: rgba(255, 255, 255, 0.72);
+ cursor: pointer;
+ outline: none;
+ transition: color 140ms ease;
+}
+
+.seg__item[aria-checked='true'] {
+ cursor: default;
+}
+
+@media (hover: hover) and (pointer: fine) {
+ .seg__item[aria-checked='false']:hover {
+ color: #ffffff;
+ }
+}
+
+.seg__item:focus-visible {
+ outline: 2px solid rgba(255, 255, 255, 0.4);
+ outline-offset: 2px;
+}
+
+.seg__thumb {
+ position: absolute;
+ top: var(--seg-pad);
+ left: var(--seg-pad);
+ width: var(--seg-slot);
+ height: calc(var(--seg-h) - var(--seg-pad) * 2);
+ border-radius: 999px;
+ background: #ffffff;
+ overflow: hidden;
+ pointer-events: none;
+ /* translate (not transform) so the press scale stays centred on the slot. */
+ translate: calc(var(--i) * var(--seg-slot)) 0;
+ transition:
+ translate var(--seg-motion),
+ opacity 160ms ease,
+ scale 160ms cubic-bezier(0.23, 1, 0.32, 1);
+}
+
+/* Black copy of the icons, counter-moved so it stays aligned with the slots. */
+.seg__ink {
+ position: absolute;
+ top: 0;
+ left: 0;
+ height: 100%;
+ display: grid;
+ grid-auto-flow: column;
+ grid-auto-columns: var(--seg-slot);
+ color: #000000;
+ translate: calc(var(--i) * var(--seg-slot) * -1) 0;
+ transition: translate var(--seg-motion);
+}
+
+.seg__slot {
+ display: grid;
+ place-items: center;
+}
+
+/* Pressed: the thumb gives a little, like a physical button. */
+.seg[data-held] .seg__thumb {
+ scale: 0.94;
+}
+
+.seg[data-empty] .seg__thumb {
+ opacity: 0;
+}
+
+/* Emoji view toggle that sits beside the filter control: same height,
+ surface and selected look as a segment, so the two read as one family. */
+.emoji-mode-btn {
+ display: grid;
+ place-items: center;
+ flex-shrink: 0;
+ width: 30px;
+ height: 30px;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ border-radius: 999px;
+ background: var(--bg-card, #141414);
+ color: rgba(255, 255, 255, 0.72);
+ cursor: pointer;
+ outline: none;
+ transition:
+ background-color 160ms ease,
+ color 140ms ease,
+ scale 160ms cubic-bezier(0.23, 1, 0.32, 1);
+}
+
+@media (hover: hover) and (pointer: fine) {
+ .emoji-mode-btn:hover {
+ color: #ffffff;
+ }
+}
+
+.emoji-mode-btn:active {
+ scale: 0.94;
+}
+
+.emoji-mode-btn.active {
+ background: #ffffff;
+ color: #000000;
+}
+
+.emoji-mode-btn:focus-visible {
+ outline: 2px solid rgba(255, 255, 255, 0.4);
+ outline-offset: 2px;
+}
+
+.seg--instant .seg__thumb,
+.seg--instant .seg__ink {
+ transition: none;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .seg__thumb,
+ .seg__ink {
+ transition: none;
+ }
+}
diff --git a/src/styles/emoji.css b/src/styles/emoji.css
index d6f8cb4..a28cd63 100644
--- a/src/styles/emoji.css
+++ b/src/styles/emoji.css
@@ -9,7 +9,7 @@
z-index: 1;
}
-/* Sleek Category Pill Bar (RubberSegment) */
+/* Category bar wrapper (SegmentedControl inside) */
.emoji-cat-bar {
display: flex;
align-items: center;
diff --git a/tests/filterBar.test.ts b/tests/filterBar.test.ts
new file mode 100644
index 0000000..cd7aa8e
--- /dev/null
+++ b/tests/filterBar.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from 'vitest'
+import { existsSync, readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const root = join(__dirname, '..')
+
+function read(rel: string): string {
+ return readFileSync(join(root, rel), 'utf8')
+}
+
+describe('filter bar (SegmentedControl)', () => {
+ const tsx = read('src/components/SegmentedControl.tsx')
+ const css = read('src/styles/SegmentedControl.css')
+
+ it('replaces RubberSegment everywhere', () => {
+ expect(existsSync(join(root, 'src/components/RubberSegment.tsx'))).toBe(false)
+ expect(existsSync(join(root, 'src/styles/RubberSegment.css'))).toBe(false)
+ expect(read('src/components/Header.tsx')).toContain('<SegmentedControl')
+ expect(read('src/components/EmojiCategoryBar.tsx')).toContain('<SegmentedControl')
+ })
+
+ it('has no per-frame JS: no framer-motion, no measuring loop', () => {
+ expect(tsx).not.toContain('framer-motion')
+ expect(tsx).not.toContain('requestAnimationFrame')
+ expect(tsx).not.toContain('ResizeObserver')
+ })
+
+ it('places the thumb by pure CSS geometry from the selected index', () => {
+ expect(tsx).toContain("'--i': shown")
+ expect(css).toContain('grid-auto-columns: var(--seg-slot);')
+ expect(css).toContain('translate: calc(var(--i) * var(--seg-slot)) 0;')
+ // The black icon copy moves the opposite way with the same spring, so it stays on the slots.
+ expect(css).toContain('translate: calc(var(--i) * var(--seg-slot) * -1) 0;')
+ expect(css.match(/translate var\(--seg-motion\)/g)?.length).toBe(2)
+ })
+
+ it('is borderless and uses the search field surface', () => {
+ const track = css.match(/\.seg \{([^}]*)\}/)?.[1] ?? ''
+ expect(track).toContain('background: var(--bg-card, #141414);')
+ expect(track).not.toMatch(/\bborder:/)
+ })
+
+ it('commits on release from a ref, so a fast click can never be lost', () => {
+ expect(tsx).toContain('const target = press.current.at')
+ expect(tsx).toContain('setPointerCapture')
+ expect(tsx).toContain("onClick={(e) => { if (e.detail === 0) commit(i) }}")
+ })
+
+ it('honours Reduce motion', () => {
+ expect(tsx).toContain("reduceMotion ? ' seg--instant' : ''")
+ expect(css).toMatch(/\.seg--instant \.seg__thumb,\s*\.seg--instant \.seg__ink \{\s*transition: none;/)
+ expect(read('src/components/Header.tsx')).toContain('reduceMotion={reduceMotion}')
+ })
+
+ it('header: filters exclude emoji, which is its own toggle; no thumb while the picker is open', () => {
+ const header = read('src/components/Header.tsx')
+ expect(header).not.toContain("id: 'emoji'")
+ expect(header).toContain('value={emojiOpen ? null : typeFilter}')
+ expect(header).toContain('className={`emoji-mode-btn${emojiOpen ? \' active\' : \'\'}`}')
+ expect(header).toContain('setEmojiOpen(!emojiOpen)')
+ })
+
+ it('Header renders EmojiCategoryBar centered in place of search in horizontal dock when emojiOpen', () => {
+ expect(read('src/components/Header.tsx')).toContain('<EmojiCategoryBar isHorizontal={true}')
+ })
+
+ it('EmojiPicker renders EmojiCategoryBar only in vertical dock mode and delegates horizontal to Header', () => {
+ const src = read('src/components/EmojiPicker.tsx')
+ expect(src).toContain('!isHorizontal && <EmojiCategoryBar isHorizontal={false}')
+ expect(src).not.toContain('emoji-cat-btn')
+ })
+})
diff --git a/tests/jellyFilters.test.ts b/tests/jellyFilters.test.ts
deleted file mode 100644
index d660930..0000000
--- a/tests/jellyFilters.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { readFileSync } from 'node:fs'
-import { join } from 'node:path'
-
-const root = join(__dirname, '..')
-
-function read(rel: string): string {
- return readFileSync(join(root, rel), 'utf8')
-}
-
-describe('rubber segment filter contracts (adapted to installed framer-motion v11)', () => {
- it('uses framer-motion, never the motion package', () => {
- const src = read('src/components/RubberSegment.tsx')
- expect(src).toContain("from 'framer-motion'")
- expect(src).not.toContain('motion/react')
- expect(src).not.toContain('.jump(')
- })
-
- it('animates clip-path with rubber dilation and full cleanup', () => {
- const src = read('src/components/RubberSegment.tsx')
- expect(src).toContain('clipPath')
- expect(src).toContain('useTransform')
- expect(src).toContain('ResizeObserver')
- expect(src).toContain('edgeL.stop()')
- expect(src).toContain('useReducedMotion')
- })
-
- it('Header renders RubberSegment for filters without the old sliding pill', () => {
- const src = read('src/components/Header.tsx')
- expect(src).toContain('<RubberSegment')
- expect(src).not.toContain('Sliding Pill')
- })
-
- it('Header renders EmojiCategoryBar centered in place of search in horizontal dock when emojiOpen', () => {
- const src = read('src/components/Header.tsx')
- expect(src).toContain('<EmojiCategoryBar isHorizontal={true}')
- })
-
- it('EmojiPicker renders EmojiCategoryBar only in vertical dock mode and delegates horizontal to Header', () => {
- const src = read('src/components/EmojiPicker.tsx')
- expect(src).toContain('!isHorizontal && <EmojiCategoryBar isHorizontal={false}')
- expect(src).not.toContain('emoji-cat-btn')
- })
-
- it('EmojiCategoryBar renders RubberSegment with elastic physics', () => {
- const src = read('src/components/EmojiCategoryBar.tsx')
- expect(src).toContain('<RubberSegment')
- })
-
- it('RubberSegment stylesheet exists with clean thumb layer styles', () => {
- const css = read('src/styles/RubberSegment.css')
- expect(css).toContain('.rubber-segment')
- expect(css).toContain('.rubber-segment__thumb')
- })
-})