Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

25.8 KB
Raw Blame
import React, {
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';
import type { SliderStyle } from '../../types/appearance';
import { useUiStore } from '../../stores';
import { acquireWorkspaceInteractionLock } from '../../utils/workspacePointerGuard';
import {
  clampNumber,
  computePageStep,
  formatNumericValue,
  getStepDecimals,
  parseNumericInput,
  quantizeValue,
  ratioToValue,
  roundToDecimals,
  valueToRatio,
} from './sliderMath';
import { isImeComposing, useI18n } from '../../i18n';

export type ScrubSliderVariant = 'default' | 'opacity' | 'size' | 'hue';
export type ScrubSliderSize = 'xs' | 'sm' | 'md';

export interface ScrubSliderHandle {
  /**
   * Synchronizes the visual fill, needle/thumb, readout text, and ARIA value attributes
   * directly in the DOM with zero React re-renders (for 60-240Hz camera/zoom streams).
   */
  setLiveValue: (value: number) => void;
}

export interface ScrubSliderProps {
  label?: string;
  value: number;
  min: number;
  max: number;
  step?: number;
  /** Optional fine step used when holding Shift (defaults to `step` with 0.1x travel speed). */
  fineStep?: number;
  /** Default value restored on double-click or Alt+click. */
  defaultValue?: number;
  /** Unit suffix appended to numeric readout (e.g. 'px', '%', '°', 'mm'). */
  unit?: string;
  /** Custom display formatter for the numeric readout. */
  formatValue?: (value: number) => string;
  /** Custom parser when committing an inline edited value. */
  parseValue?: (raw: string) => number | null;
  /** Track visual variant. */
  variant?: ScrubSliderVariant;
  /** Per-instance override for global `appearance.sliderStyle`. */
  sliderStyle?: SliderStyle;
  /** Compact height scale ('xs' = 20px, 'sm' = --ui-control-height, 'md' = comfortable). */
  size?: ScrubSliderSize;
  /** Logarithmic value mapping (ideal for brush size and zoom). */
  logarithmic?: boolean;
  /** Hide visible label text while keeping aria-label accessibility. */
  hideLabel?: boolean;
  /** Hide visible numeric readout (e.g. when paired with an external readout). */
  hideValue?: boolean;
  /** Allow clicking numeric readout to enter exact values inline (default: true). */
  allowInlineEdit?: boolean;
  disabled?: boolean;
  onChange: (value: number) => void;
  /** Optional commit callback fired on pointerup, inline edit commit, reset, or keyboard commit. */
  onCommit?: (value: number) => void;
  /** Imperative ref for zero-rerender DOM updates. */
  liveRef?: React.Ref<ScrubSliderHandle>;
  className?: string;
  'aria-label'?: string;
  'data-testid'?: string;
  title?: string;
}

const FINE_PRECISION_SCALE = 0.1;

const HUE_GRADIENT =
  'linear-gradient(90deg, #e5484d 0%, #f5c43d 17%, #4cc38a 33%, #2ec4d6 50%, #3b82f6 67%, #a855f7 83%, #e5484d 100%)';

const SCRUBBER_HEIGHT_CLASSES: Record<ScrubSliderSize, string> = {
  xs: 'h-5',
  sm: 'h-[var(--ui-control-height)]',
  md: 'h-7',
};

const ScrubberSizeRampSvg: React.FC<{
  fillColor: string;
  className?: string;
}> = React.memo(({ fillColor, className = '' }) => (
  <svg
    viewBox="0 0 100 24"
    preserveAspectRatio="none"
    aria-hidden="true"
    className={`w-full h-full block pointer-events-none ${className}`}
  >
    <path d="M 0 11.4 L 100 3.5 L 100 20.5 L 0 12.6 Z" fill={fillColor} />
  </svg>
));
ScrubberSizeRampSvg.displayName = 'ScrubberSizeRampSvg';

const ScrubSliderInner: React.FC<ScrubSliderProps> = ({
  label,
  value,
  min,
  max,
  step = 1,
  fineStep,
  defaultValue,
  unit = '',
  formatValue,
  parseValue,
  variant = 'default',
  sliderStyle: sliderStyleProp,
  size = 'sm',
  logarithmic = false,
  hideLabel = false,
  hideValue = false,
  allowInlineEdit = true,
  disabled = false,
  onChange,
  onCommit,
  liveRef,
  className = '',
  'aria-label': ariaLabel,
  'data-testid': dataTestId,
  title,
}) => {
  const { t } = useI18n();
  const globalSliderStyle = useUiStore((s) => s.appSettings.appearance.sliderStyle);
  const effectiveStyle: SliderStyle = sliderStyleProp ?? globalSliderStyle ?? 'scrubber';

  const clampedValue = clampNumber(value, min, max);
  const ratio = valueToRatio(clampedValue, min, max, logarithmic);
  const pct = ratio * 100;

  const [isDragging, setIsDragging] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [draftText, setDraftText] = useState('');

  const sliderElRef = useRef<HTMLDivElement>(null);
  const trackElRef = useRef<HTMLDivElement>(null);
  const fillElRef = useRef<HTMLDivElement>(null);
  const needleElRef = useRef<HTMLDivElement>(null);
  const readoutElRef = useRef<HTMLSpanElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const liveValueRef = useRef<number>(clampedValue);
  liveValueRef.current = clampedValue;

  const isEditingRef = useRef(false);
  isEditingRef.current = isEditing;

  const editCancelledRef = useRef(false);

  const dragRef = useRef<{
    active: boolean;
    pointerId: number | null;
    width: number;
    lastClientX: number;
    ratio: number;
    latestValue: number;
    captured: boolean;
    releaseGuard: (() => void) | null;
  }>({
    active: false,
    pointerId: null,
    width: 1,
    lastClientX: 0,
    ratio,
    latestValue: clampedValue,
    captured: false,
    releaseGuard: null,
  });

  useEffect(() => {
    return () => {
      dragRef.current.releaseGuard?.();
      dragRef.current.releaseGuard = null;
    };
  }, []);

  const formatDisplay = useCallback(
    (v: number): string => (formatValue ? formatValue(v) : formatNumericValue(v, step, unit)),
    [formatValue, step, unit]
  );

  const formattedValue = formatDisplay(clampedValue);

  const syncLiveDom = useCallback(
    (nextVal: number) => {
      const safeVal = clampNumber(nextVal, min, max);
      liveValueRef.current = safeVal;
      const nextRatio = valueToRatio(safeVal, min, max, logarithmic);
      const nextPct = nextRatio * 100;

      if (fillElRef.current) {
        if (variant === 'size') {
          fillElRef.current.style.clipPath = `inset(0 ${100 - nextPct}% 0 0)`;
        } else {
          fillElRef.current.style.width = `${nextPct}%`;
        }
      }
      if (needleElRef.current) {
        needleElRef.current.style.left =
          effectiveStyle === 'scrubber'
            ? `clamp(1px, ${nextPct}%, calc(100% - 1px))`
            : `${nextPct}%`;
      }
      if (readoutElRef.current && !isEditingRef.current) {
        readoutElRef.current.textContent = formatDisplay(safeVal);
      }
      if (sliderElRef.current) {
        sliderElRef.current.setAttribute('aria-valuenow', String(safeVal));
        sliderElRef.current.setAttribute('aria-valuetext', formatDisplay(safeVal));
      }
    },
    [effectiveStyle, formatDisplay, logarithmic, max, min, variant]
  );

  useImperativeHandle(
    liveRef,
    () => ({
      setLiveValue: syncLiveDom,
    }),
    [syncLiveDom]
  );

  const emitValue = useCallback(
    (nextVal: number, commit = false) => {
      const clamped = clampNumber(nextVal, min, max);
      liveValueRef.current = clamped;
      dragRef.current.latestValue = clamped;
      onChange(clamped);
      if (commit) {
        onCommit?.(clamped);
      }
    },
    [max, min, onChange, onCommit]
  );

  const handleResetToDefault = useCallback(() => {
    if (disabled || defaultValue === undefined) return;
    const resetVal = quantizeValue(defaultValue, min, max, step);
    syncLiveDom(resetVal);
    emitValue(resetVal, true);
  }, [defaultValue, disabled, emitValue, max, min, step, syncLiveDom]);

  const startInlineEdit = useCallback(
    (e?: React.SyntheticEvent) => {
      if (disabled || !allowInlineEdit) return;
      e?.stopPropagation();
      editCancelledRef.current = false;
      const decimals = getStepDecimals(fineStep ?? step);
      const editableNum = roundToDecimals(liveValueRef.current, decimals);
      setDraftText(Object.is(editableNum, -0) ? '0' : String(editableNum));
      setIsEditing(true);
    },
    [allowInlineEdit, disabled, fineStep, step]
  );

  useEffect(() => {
    if (!isEditing) return;
    const input = inputRef.current;
    if (input) {
      input.focus?.();
      input.select?.();
    }
  }, [isEditing]);

  const commitInlineEdit = useCallback(() => {
    if (!isEditingRef.current) return;
    setIsEditing(false);
    if (editCancelledRef.current) {
      editCancelledRef.current = false;
      return;
    }
    const parsed = parseValue ? parseValue(draftText) : parseNumericInput(draftText);
    if (parsed !== null && Number.isFinite(parsed)) {
      const targetStep = fineStep !== undefined ? fineStep : step;
      const next = quantizeValue(parsed, min, max, targetStep);
      syncLiveDom(next);
      emitValue(next, true);
    }
  }, [draftText, emitValue, fineStep, max, min, parseValue, step, syncLiveDom]);

  const cancelInlineEdit = useCallback(() => {
    editCancelledRef.current = true;
    setIsEditing(false);
    sliderElRef.current?.focus?.();
  }, []);

  const handleTrackPointerDown = useCallback(
    (e: React.PointerEvent<HTMLDivElement>) => {
      if (disabled || isEditingRef.current || e.button !== 0) return;
      const target = e.target as HTMLElement | null;
      if (target?.closest?.('[data-scrub-readout="true"], input')) return;

      e.preventDefault();
      e.stopPropagation();

      if (e.altKey && defaultValue !== undefined) {
        handleResetToDefault();
        return;
      }

      const measureEl = trackElRef.current ?? e.currentTarget;
      const rect = measureEl.getBoundingClientRect();
      const width = Math.max(1, rect.width || measureEl.clientWidth || 100);
      const currentRatio = valueToRatio(liveValueRef.current, min, max, logarithmic);

      let initialRatio = currentRatio;
      let nextVal = liveValueRef.current;

      if (!e.shiftKey) {
        initialRatio = clampNumber((e.clientX - rect.left) / width, 0, 1);
        nextVal = quantizeValue(
          ratioToValue(initialRatio, min, max, logarithmic),
          min,
          max,
          step
        );
      }

      let captured = false;
      try {
        if (typeof e.currentTarget.setPointerCapture === 'function') {
          e.currentTarget.setPointerCapture(e.pointerId);
          captured = true;
        }
      } catch {
        captured = false;
      }

      dragRef.current.releaseGuard?.();
      dragRef.current = {
        active: true,
        pointerId: e.pointerId,
        width,
        lastClientX: e.clientX,
        ratio: initialRatio,
        latestValue: nextVal,
        captured,
        releaseGuard: acquireWorkspaceInteractionLock('scrub-slider'),
      };

      setIsDragging(true);
      e.currentTarget.focus?.();

      if (!e.shiftKey && nextVal !== liveValueRef.current) {
        syncLiveDom(nextVal);
        emitValue(nextVal, false);
      }
    },
    [
      defaultValue,
      disabled,
      emitValue,
      handleResetToDefault,
      logarithmic,
      max,
      min,
      step,
      syncLiveDom,
    ]
  );

  const handleTrackPointerMove = useCallback(
    (e: React.PointerEvent<HTMLDivElement>) => {
      const drag = dragRef.current;
      if (!drag.active) return;
      e.stopPropagation();

      const dx = e.clientX - drag.lastClientX;
      drag.lastClientX = e.clientX;
      if (dx === 0) return;

      const scale = e.shiftKey ? FINE_PRECISION_SCALE : 1;
      const nextRatio = clampNumber(drag.ratio + (dx / drag.width) * scale, 0, 1);
      drag.ratio = nextRatio;

      const activeStep = e.shiftKey && fineStep !== undefined ? fineStep : step;
      const raw = ratioToValue(nextRatio, min, max, logarithmic);
      const nextVal = quantizeValue(raw, min, max, activeStep);

      if (nextVal !== drag.latestValue) {
        drag.latestValue = nextVal;
        syncLiveDom(nextVal);
        emitValue(nextVal, false);
      }
    },
    [emitValue, fineStep, logarithmic, max, min, step, syncLiveDom]
  );

  const finishDrag = useCallback(
    (e: React.PointerEvent<HTMLDivElement>, cancelled = false) => {
      const drag = dragRef.current;
      if (!drag.active) return;
      e.stopPropagation();

      const pid = drag.pointerId;
      const finalVal = drag.latestValue;
      drag.active = false;
      drag.pointerId = null;
      drag.releaseGuard?.();
      drag.releaseGuard = null;
      setIsDragging(false);

      if (pid !== null && drag.captured) {
        try {
          if (
            typeof e.currentTarget.hasPointerCapture !== 'function' ||
            e.currentTarget.hasPointerCapture(pid)
          ) {
            e.currentTarget.releasePointerCapture?.(pid);
          }
        } catch {
          // Ignore in synthetic pointer events
        }
      }

      if (!cancelled) {
        onCommit?.(finalVal);
      }
    },
    [onCommit]
  );

  const handleDoubleClick = useCallback(
    (e: React.MouseEvent<HTMLDivElement>) => {
      const target = e.target as HTMLElement | null;
      if (target?.closest?.('[data-scrub-readout="true"], input')) return;
      if (defaultValue === undefined || disabled) return;
      e.preventDefault();
      e.stopPropagation();
      handleResetToDefault();
    },
    [defaultValue, disabled, handleResetToDefault]
  );

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent<HTMLDivElement>) => {
      if (disabled || isEditingRef.current) return;

      const cur = liveValueRef.current;
      const pageStep = computePageStep(min, max, step);
      const arrowStep = e.shiftKey && fineStep !== undefined ? fineStep : step;
      let next: number | null = null;

      switch (e.key) {
        case 'ArrowRight':
        case 'ArrowUp':
          next = quantizeValue(cur + arrowStep, min, max, arrowStep);
          break;
        case 'ArrowLeft':
        case 'ArrowDown':
          next = quantizeValue(cur - arrowStep, min, max, arrowStep);
          break;
        case 'PageUp':
          next = quantizeValue(cur + pageStep, min, max, step);
          break;
        case 'PageDown':
          next = quantizeValue(cur - pageStep, min, max, step);
          break;
        case 'Home':
          next = min;
          break;
        case 'End':
          next = max;
          break;
        case 'Enter':
        case 'F2':
          if (allowInlineEdit && !hideValue) {
            e.preventDefault();
            e.stopPropagation();
            startInlineEdit();
          }
          return;
        default:
          return;
      }

      if (next !== null) {
        e.preventDefault();
        e.stopPropagation();
        if (next !== cur) {
          syncLiveDom(next);
          emitValue(next, true);
        }
      }
    },
    [
      allowInlineEdit,
      disabled,
      emitValue,
      fineStep,
      hideValue,
      max,
      min,
      startInlineEdit,
      step,
      syncLiveDom,
    ]
  );

  const computedTitle =
    title ??
    (defaultValue !== undefined
      ? label
        ? t('{label}: {value} (Drag · Shift for fine · Double-click to reset)', { label, value: formattedValue })
        : t('{value} (Drag · Shift for fine · Double-click to reset)', { value: formattedValue })
      : label
        ? t('{label}: {value} (Drag · Shift for fine)', { label, value: formattedValue })
        : t('{value} (Drag · Shift for fine)', { value: formattedValue }));

  const renderReadout = (compact: boolean) => {
    if (hideValue) return null;
    if (isEditing) {
      return (
        <input
          ref={inputRef}
          type="text"
          inputMode="decimal"
          data-scrub-input="true"
          value={draftText}
          onChange={(e) => setDraftText(e.target.value)}
          onBlur={commitInlineEdit}
          onPointerDown={(e) => e.stopPropagation()}
          onClick={(e) => e.stopPropagation()}
          onKeyDown={(e) => {
            if (isImeComposing(e)) return;
            e.stopPropagation();
            if (e.key === 'Enter') {
              e.preventDefault();
              commitInlineEdit();
            } else if (e.key === 'Escape') {
              e.preventDefault();
              cancelInlineEdit();
            }
          }}
          aria-label={ariaLabel ?? (label ? t('{label} value', { label }) : t('Numeric value'))}
          className={`w-14 bg-ui-elevated text-ui-primary font-ui-mono tabular-nums text-right border border-ui-focus rounded-ui-xs px-1 py-0 select-text focus:outline-none ${
            compact ? 'text-[10px] h-4 leading-4' : 'text-[10.5px] h-[18px] leading-[18px]'
          }`}
        />
      );
    }

    return (
      <span
        ref={readoutElRef}
        data-scrub-readout="true"
        role={allowInlineEdit && !disabled ? 'button' : undefined}
        tabIndex={-1}
        onPointerDown={(e) => {
          if (allowInlineEdit && !disabled) {
            e.stopPropagation();
          }
        }}
        onClick={(e) => {
          if (allowInlineEdit && !disabled) {
            startInlineEdit(e);
          }
        }}
        title={allowInlineEdit && !disabled ? t('Click to type exact value') : undefined}
        className={`font-ui-mono tabular-nums shrink-0 rounded-ui-xs transition-colors ${
          compact ? 'text-[10px] px-1' : 'text-[10.5px] px-1 -mr-0.5'
        } ${
          disabled
            ? 'text-ui-disabled'
            : allowInlineEdit
              ? 'text-ui-primary hover:bg-ui-control-hover/85 cursor-text'
              : 'text-ui-primary'
        }`}
      >
        {formattedValue}
      </span>
    );
  };

  // =========================================================================
  // TRACK MODE (Classic Minimalist: 3px precision track + 10px machined thumb)
  // =========================================================================
  if (effectiveStyle === 'track') {
    const showHeader = (!hideLabel && Boolean(label)) || !hideValue;
    return (
      <div
        ref={sliderElRef}
        role="slider"
        tabIndex={disabled ? -1 : 0}
        data-testid={dataTestId}
        data-slider-mode="track"
        data-variant={variant}
        aria-label={ariaLabel ?? label}
        aria-valuemin={min}
        aria-valuemax={max}
        aria-valuenow={clampedValue}
        aria-valuetext={formattedValue}
        aria-disabled={disabled || undefined}
        title={computedTitle}
        onPointerDown={handleTrackPointerDown}
        onPointerMove={handleTrackPointerMove}
        onPointerUp={(e) => finishDrag(e, false)}
        onPointerCancel={(e) => finishDrag(e, true)}
        onDoubleClick={handleDoubleClick}
        onKeyDown={handleKeyDown}
        className={`group select-none touch-none focus:outline-none ${
          showHeader ? 'space-y-0.5' : ''
        } ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-ew-resize'} ${className}`}
      >
        {showHeader && (
          <div className="flex items-center justify-between gap-1.5 min-h-[15px]">
            {!hideLabel && label ? (
              <span className="text-[11px] text-ui-secondary group-hover:text-ui-primary truncate leading-tight transition-colors">
                {label}
              </span>
            ) : (
              <span />
            )}
            {renderReadout(size === 'xs')}
          </div>
        )}

        <div
          className={`relative flex items-center ${size === 'xs' ? 'h-4' : 'h-[18px]'}`}
        >
          <div
            ref={trackElRef}
            className={`relative w-full rounded-full overflow-hidden ${
              variant === 'opacity'
                ? 'h-[5px] ui-checker-alpha border border-ui-subtle'
                : variant === 'hue'
                  ? 'h-[5px] border border-ui-subtle'
                  : variant === 'size'
                    ? 'h-[8px] bg-transparent'
                    : 'h-[3px] bg-ui-control-hover'
            }`}
            style={variant === 'hue' ? { backgroundImage: HUE_GRADIENT } : undefined}
          >
            {variant === 'opacity' && (
              <div
                className="absolute inset-0 pointer-events-none"
                style={{
                  backgroundImage:
                    'linear-gradient(90deg, transparent 0%, rgba(var(--ui-accent-rgb), 0.82) 100%)',
                }}
              />
            )}

            {variant === 'size' && (
              <>
                <div className="absolute inset-0 pointer-events-none">
                  <ScrubberSizeRampSvg fillColor="var(--ui-bg-control-hover)" />
                </div>
                <div
                  ref={fillElRef}
                  className="absolute inset-0 pointer-events-none"
                  style={{ clipPath: `inset(0 ${100 - pct}% 0 0)` }}
                >
                  <ScrubberSizeRampSvg fillColor="var(--ui-accent)" />
                </div>
              </>
            )}

            {variant === 'default' && (
              <div
                ref={fillElRef}
                className="absolute inset-y-0 left-0 rounded-full bg-ui-accent/75 pointer-events-none"
                style={{ width: `${pct}%` }}
              />
            )}

            {(variant === 'opacity' || variant === 'hue') && (
              <div
                ref={fillElRef}
                className="sr-only pointer-events-none"
                style={{ width: `${pct}%` }}
              />
            )}
          </div>

          {/* 10px machined thumb */}
          <div
            ref={needleElRef}
            aria-hidden="true"
            className={`pointer-events-none absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-[10px] h-[10px] rounded-full bg-ui-accent border border-ui-panel transition-colors ${
              isDragging
                ? 'ring-2 ring-ui-focus/45'
                : 'group-focus-visible:ring-2 group-focus-visible:ring-ui-focus/55'
            }`}
            style={{ left: `${pct}%` }}
          />
        </div>
      </div>
    );
  }

  // =========================================================================
  // SCRUBBER MODE (Atelier Signature: Recessed bar + wash + 2px crisp needle)
  // =========================================================================
  return (
    <div
      ref={sliderElRef}
      role="slider"
      tabIndex={disabled ? -1 : 0}
      data-testid={dataTestId}
      data-slider-mode="scrubber"
      data-variant={variant}
      aria-label={ariaLabel ?? label}
      aria-valuemin={min}
      aria-valuemax={max}
      aria-valuenow={clampedValue}
      aria-valuetext={formattedValue}
      aria-disabled={disabled || undefined}
      title={computedTitle}
      onPointerDown={handleTrackPointerDown}
      onPointerMove={handleTrackPointerMove}
      onPointerUp={(e) => finishDrag(e, false)}
      onPointerCancel={(e) => finishDrag(e, true)}
      onDoubleClick={handleDoubleClick}
      onKeyDown={handleKeyDown}
      className={`group relative w-full ${SCRUBBER_HEIGHT_CLASSES[size]} rounded-ui-sm border overflow-hidden select-none touch-none transition-colors focus:outline-none focus-visible:border-ui-focus ${
        disabled
          ? 'bg-ui-input border-ui-subtle opacity-50 cursor-not-allowed'
          : isDragging
            ? 'bg-ui-input border-ui-focus cursor-ew-resize'
            : 'bg-ui-input border-ui-subtle hover:border-ui-default cursor-ew-resize'
      } ${className}`}
    >
      {/* Visual Track Layer */}
      <div
        ref={trackElRef}
        aria-hidden="true"
        className={`pointer-events-none absolute inset-0 overflow-hidden ${
          variant === 'opacity' ? 'ui-checker-alpha' : ''
        }`}
      >
        {variant === 'opacity' && (
          <div
            className="absolute inset-0"
            style={{
              backgroundImage:
                'linear-gradient(90deg, transparent 0%, rgba(var(--ui-accent-rgb), 0.34) 100%)',
            }}
          />
        )}

        {variant === 'hue' && (
          <div
            className="absolute inset-x-0 bottom-0 h-[3px] opacity-90"
            style={{ backgroundImage: HUE_GRADIENT }}
          />
        )}

        {variant === 'size' && (
          <div className="absolute inset-0 opacity-65">
            <ScrubberSizeRampSvg fillColor="var(--ui-border-subtle)" />
          </div>
        )}

        {/* Active Fill Wash */}
        {variant === 'size' ? (
          <div
            ref={fillElRef}
            className="absolute inset-0 pointer-events-none"
            style={{ clipPath: `inset(0 ${100 - pct}% 0 0)` }}
          >
            <ScrubberSizeRampSvg
              fillColor={isDragging ? 'var(--ui-accent-hover)' : 'var(--ui-accent-subtle)'}
            />
          </div>
        ) : (
          <div
            ref={fillElRef}
            className="absolute inset-y-0 left-0"
            style={{
              width: `${pct}%`,
              backgroundColor: isDragging
                ? 'var(--ui-accent-hover)'
                : 'var(--ui-accent-subtle)',
            }}
          />
        )}

        {/* Crisp 2px Vertical Needle Indicator */}
        <div
          ref={needleElRef}
          className={`absolute top-[2px] bottom-[2px] w-[2px] -ml-[1px] rounded-[1px] bg-ui-accent transition-opacity ${
            isDragging ? 'opacity-100' : 'opacity-80 group-hover:opacity-100'
          }`}
          style={{ left: `clamp(1px, ${pct}%, calc(100% - 1px))` }}
        />
      </div>

      {/* Foreground Label + Tabular Numeric Readout */}
      {(!hideLabel || !hideValue) && (
        <div
          className={`relative z-10 h-full flex items-center justify-between gap-1.5 ${
            size === 'xs' ? 'px-1.5' : 'px-2'
          }`}
        >
          {!hideLabel && label ? (
            <span
              className={`pointer-events-none truncate leading-none ${
                size === 'xs' ? 'text-[10px]' : 'text-[11px]'
              } ${
                disabled
                  ? 'text-ui-disabled'
                  : isDragging
                    ? 'text-ui-primary'
                    : 'text-ui-secondary group-hover:text-ui-primary'
              }`}
            >
              {label}
            </span>
          ) : (
            <span className="pointer-events-none" />
          )}
          {renderReadout(size === 'xs')}
        </div>
      )}
    </div>
  );
};

export const ScrubSlider = React.memo(ScrubSliderInner);
ScrubSlider.displayName = 'ScrubSlider';