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.

10.0 KB
Raw Blame
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { frameSteps, useMotionValue, useMotionValueEvent, useReducedMotion, useSpring, useVelocity } from 'framer-motion'
import { playDialTickSound } from '../lib/soundEffects'

import './WakeSlider.css'

const SETTLE = 9.23
const FULL_SPEED = 320
const MIN_REACH = 1.5
const FLAT = 0.002

const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))
const smoothstep = (s: number) => s * s * (3 - 2 * s)
const toPct = (v: number, min: number, max: number) => (max > min ? ((v - min) / (max - min)) * 100 : 0)
const snap = (v: number, min: number, max: number, step: number) => {
  if (!(max > min)) return min
  if (!(step > 0)) return clamp(v, min, max)
  const lastWhole = min + Math.floor(+((max - min) / step).toFixed(6)) * step
  const grid = clamp(Math.round((v - min) / step) * step + min, min, lastWhole)
  return +(lastWhole < max && Math.abs(v - max) <= Math.abs(v - grid) ? max : grid).toFixed(6)
}

export interface WakeSliderProps {
  value?: number
  defaultValue?: number
  onChange?: (val: number) => void
  onRelease?: (val: number) => void
  onStart?: () => void
  min?: number
  max?: number
  step?: number
  bars?: number
  height?: number
  restHeight?: number
  gap?: number
  fillColor?: string
  trackColor?: string
  crestColor?: string
  sensitivity?: number
  reach?: number
  skew?: number
  glide?: number
  smoothing?: number
  showValue?: boolean
  formatValue?: (val: number) => string
  disabled?: boolean
  ariaLabel?: string
  className?: string
}

export function WakeSlider({
  value: valueProp,
  defaultValue = 50,
  onChange,
  onRelease,
  onStart,
  min = 0,
  max = 100,
  step = 1,
  bars = 32,
  height = 56,
  restHeight = 12,
  gap = 4,
  fillColor = '#f5f5f5',
  trackColor = '#27272a',
  crestColor = '',
  sensitivity = 1,
  reach = 6,
  skew = 0.6,
  glide = 0.3,
  smoothing = 100,
  showValue = false,
  formatValue,
  disabled = false,
  ariaLabel = 'Value',
  className = ''
}: WakeSliderProps) {
  const [inner, setInner] = useState(defaultValue)
  const value = clamp(valueProp ?? inner, min, max)
  const pct = toPct(value, min, max)
  const reduce = useReducedMotion()
  const format = formatValue ?? String
  const rest = Math.min(restHeight, height - 1) / height

  const rootRef = useRef<HTMLDivElement>(null)
  const trackRef = useRef<HTMLDivElement>(null)
  const handleRef = useRef<HTMLButtonElement>(null)
  const barEls = useRef<(HTMLSpanElement | null)[]>([])
  const crestEls = useRef<(HTMLSpanElement | null)[]>([])
  const pointerId = useRef<number | null>(null)
  const pendingX = useRef<number | null>(null)
  const lastAmp = useRef(0)
  const latest = useRef(value)
  latest.current = value

  const target = useMotionValue(pct)
  const w0 = SETTLE / glide
  const head = useSpring(target, { stiffness: w0 * w0, damping: 2 * w0, mass: 1 })
  const rawSpeed = useVelocity(head)
  const wv = 2000 / smoothing
  const speed = useSpring(rawSpeed, { stiffness: wv * wv, damping: 2.5 * wv, mass: 1 })

  // While dragging, the pointer drives `target` directly (see flushDrag); the
  // snapped value only takes over again on release.
  useEffect(() => {
    if (pointerId.current === null) target.set(pct)
  }, [pct, target])

  const paint = (force = false) => {
    // Under the finger the fill tracks the pointer 1:1; the spring only drives
    // the wake (and glides between values for clicks, keys and the release).
    const h = ((reduce || pointerId.current !== null ? target.get() : head.get()) / 100) * (bars - 1)
    const v = reduce ? 0 : speed.get()
    const amp = smoothstep(clamp((Math.abs(v) * sensitivity) / FULL_SPEED, 0, 1))
    const dir = Math.sign(v) || 1
    const r = MIN_REACH + (reach - MIN_REACH) * amp
    const behind = r * (1 + skew)
    const ahead = r * (1 - 0.5 * skew)
    const lit = Math.round(h)
    const flat = !force && amp < FLAT && lastAmp.current < FLAT
    for (let i = 0; i < bars; i++) {
      const el = barEls.current[i]
      if (!el) continue
      const on = i <= lit ? 'true' : 'false'
      if (el.dataset.on !== on) el.dataset.on = on
      if (flat) continue
      const d = i - h
      const R = d * dir < 0 ? behind : ahead
      const lift = Math.abs(d) < R ? amp * Math.cos((Math.PI * d) / (2 * R)) ** 2 : 0
      el.style.transform = `scaleY(${rest + lift * (1 - rest)})`
      const crest = crestEls.current[i]
      if (crest) crest.style.opacity = String(lift)
    }
    lastAmp.current = amp
  }
  const paintRef = useRef(paint)
  paintRef.current = paint
  const run = useCallback(() => paintRef.current(), [])
  // NOTE: the reference implementation targets `motion` v12 (`frame.render(...)`).
  // This repo runs framer-motion v11, where the same render-step scheduler lives at
  // `frameSteps.render.schedule(callback, keepAlive, immediate)`.
  const schedule = useCallback(() => frameSteps.render.schedule(run, false, true), [run])
  useMotionValueEvent(head, 'change', schedule)
  useMotionValueEvent(speed, 'change', schedule)
  useLayoutEffect(() => {
    paintRef.current(true)
  })

  // One tick per detent: every value step, but never more than one per bar,
  // so fine-grained sliders don't buzz.
  const detents = Math.max(1, Math.min(bars - 1, Math.round((max - min) / (step > 0 ? step : 1))))
  const detentOf = (v: number) => Math.round((toPct(v, min, max) / 100) * detents)

  const commit = (next: number) => {
    const clean = snap(next, min, max, step)
    if (clean === latest.current) return
    if (detentOf(clean) !== detentOf(latest.current)) playDialTickSound()
    latest.current = clean
    if (valueProp === undefined) setInner(clean)
    onChange?.(clean)
  }
  const commitFromX = (x: number) => {
    const track = trackRef.current
    if (!track) return
    const rect = track.getBoundingClientRect()
    if (!rect.width) return
    let ratio = clamp((x - rect.left) / rect.width, 0, 1)
    if (getComputedStyle(track).direction === 'rtl') ratio = 1 - ratio
    target.set(ratio * 100)
    schedule()
    commit(min + ratio * (max - min))
  }
  // Pointer moves can arrive far faster than the screen refreshes (1000 Hz
  // mice); handle only the latest one, once per frame.
  const flushDrag = useCallback(() => {
    const x = pendingX.current
    pendingX.current = null
    if (x !== null && pointerId.current !== null) commitRef.current(x)
  }, [])
  const commitRef = useRef(commitFromX)
  commitRef.current = commitFromX
  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
    if (disabled || pointerId.current !== null) return
    pointerId.current = e.pointerId
    try {
      e.currentTarget.setPointerCapture(e.pointerId)
    } catch {}
    rootRef.current?.removeAttribute('data-instant')
    handleRef.current?.focus({ preventScroll: true })
    onStart?.()
    commitFromX(e.clientX)
  }
  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
    if (e.pointerId !== pointerId.current) return
    pendingX.current = e.clientX
    frameSteps.update.schedule(flushDrag)
  }
  const endDrag = (e: React.PointerEvent<HTMLDivElement>) => {
    if (e.pointerId !== pointerId.current) return
    try {
      e.currentTarget.releasePointerCapture(e.pointerId)
    } catch {}
    if (pendingX.current !== null) {
      commitFromX(pendingX.current)
      pendingX.current = null
    }
    pointerId.current = null
    // Hand the fill back to the spring from where the finger left it, then
    // let it settle into the snapped value.
    head.jump(target.get())
    target.set(toPct(latest.current, min, max))
    onRelease?.(latest.current)
  }
  const onKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {
    if (disabled) return
    const jumps: Record<string, number> = {
      ArrowRight: value + step,
      ArrowUp: value + step,
      ArrowLeft: value - step,
      ArrowDown: value - step,
      PageUp: value + step * 10,
      PageDown: value - step * 10,
      Home: min,
      End: max
    }
    if (!(e.key in jumps)) return
    e.preventDefault()
    const clean = snap(jumps[e.key], min, max, step)
    const p = toPct(clean, min, max)
    rootRef.current?.setAttribute('data-instant', 'true')
    head.jump(p)
    speed.jump(0)
    target.jump(p)
    commit(clean)
    onRelease?.(clean)
  }

  const barNodes = useMemo(() => {
    barEls.current.length = bars
    crestEls.current.length = bars
    return Array.from({ length: bars }, (_, i) => (
      <span
        key={i}
        ref={(el) => {
          barEls.current[i] = el
        }}
        className="wake-slider__bar"
      >
        {crestColor ? (
          <span
            ref={(el) => {
              crestEls.current[i] = el
            }}
            className="wake-slider__crest"
          />
        ) : null}
      </span>
    ))
  }, [bars, crestColor])

  return (
    <div
      ref={rootRef}
      className={`wake-slider${className ? ` ${className}` : ''}`}
      aria-disabled={disabled || undefined}
      style={
        {
          '--ws-fill': fillColor,
          '--ws-track': trackColor,
          '--ws-crest': crestColor || fillColor,
          '--ws-height': `${height}px`,
          '--ws-gap': `${gap}px`,
          '--ws-rest': rest
        } as React.CSSProperties
      }
    >
      <div
        ref={trackRef}
        className="wake-slider__track"
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={endDrag}
        onPointerCancel={endDrag}
        onLostPointerCapture={endDrag}
      >
        {barNodes}
        <button
          ref={handleRef}
          type="button"
          role="slider"
          className="wake-slider__handle"
          tabIndex={disabled ? -1 : 0}
          aria-label={ariaLabel}
          aria-valuemin={min}
          aria-valuemax={max}
          aria-valuenow={value}
          aria-valuetext={format(value)}
          aria-disabled={disabled || undefined}
          onKeyDown={onKeyDown}
        />
      </div>
      {showValue ? (
        <span className="wake-slider__value" aria-hidden="true">
          {format(value)}
        </span>
      ) : null}
    </div>
  )
}

export default WakeSlider