Skip to content

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

10.7 KB
Raw Blame
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { ChevronDown, ChevronUp } from 'lucide-react';
import {
  clampNumber,
  formatNumericValue,
  getStepDecimals,
  parseNumericInput,
  quantizeValue,
  roundToDecimals,
} from './sliderMath';
import { isImeComposing, useI18n } from '../../i18n';

export interface PrecisionNumberInputProps {
  value: number;
  min?: number;
  max?: number;
  step?: number;
  fineStep?: number;
  defaultValue?: number;
  /** Optional prefix / label inside left edge that supports horizontal drag-to-scrub. */
  label?: string;
  /** Optional unit suffix rendered cleanly inside right edge (e.g. 'px', '%', '°'). */
  unit?: string;
  /** Pixels per step when scrubbing the label (default: 4). */
  scrubPixelsPerStep?: number;
  size?: 'xs' | 'sm' | 'md';
  disabled?: boolean;
  onChange: (value: number) => void;
  onCommit?: (value: number) => void;
  className?: string;
  'aria-label'?: string;
  'data-testid'?: string;
  title?: string;
}

const HEIGHT_CLASSES = {
  xs: 'h-5',
  sm: 'h-[var(--ui-control-height)]',
  md: 'h-7',
} as const;

const PrecisionNumberInputInner: React.FC<PrecisionNumberInputProps> = ({
  value,
  min = -Number.MAX_SAFE_INTEGER,
  max = Number.MAX_SAFE_INTEGER,
  step = 1,
  fineStep,
  defaultValue,
  label,
  unit = '',
  scrubPixelsPerStep = 4,
  size = 'sm',
  disabled = false,
  onChange,
  onCommit,
  className = '',
  'aria-label': ariaLabel,
  'data-testid': dataTestId,
  title,
}) => {
  const { t } = useI18n();
  const clamped = clampNumber(value, min, max);
  const [isFocused, setIsFocused] = useState(false);
  const [isScrubbing, setIsScrubbing] = useState(false);
  const [draft, setDraft] = useState(() => formatNumericValue(clamped, step));
  const cancelledRef = useRef(false);
  const inputRef = useRef<HTMLInputElement>(null);

  const scrubRef = useRef<{
    active: boolean;
    pointerId: number | null;
    startValue: number;
    accumulatedPx: number;
    lastClientX: number;
    latestValue: number;
  }>({
    active: false,
    pointerId: null,
    startValue: clamped,
    accumulatedPx: 0,
    lastClientX: 0,
    latestValue: clamped,
  });

  useEffect(() => {
    if (!isFocused) {
      setDraft(formatNumericValue(clamped, step));
    }
  }, [clamped, isFocused, step]);

  const applyValue = useCallback(
    (raw: number, activeStep: number, commit: boolean) => {
      const next = quantizeValue(raw, min, max, activeStep);
      setDraft(formatNumericValue(next, activeStep));
      if (next !== clamped) {
        onChange(next);
      }
      if (commit) {
        onCommit?.(next);
      }
      return next;
    },
    [clamped, max, min, onChange, onCommit]
  );

  const commitDraft = useCallback(() => {
    if (cancelledRef.current) {
      cancelledRef.current = false;
      setDraft(formatNumericValue(clamped, step));
      return;
    }
    const parsed = parseNumericInput(draft);
    if (parsed === null) {
      setDraft(formatNumericValue(clamped, step));
      return;
    }
    const effectiveStep = fineStep ?? step;
    applyValue(parsed, effectiveStep, true);
  }, [applyValue, clamped, draft, fineStep, step]);

  const stepBy = useCallback(
    (direction: 1 | -1, shiftKey: boolean) => {
      if (disabled) return;
      const delta = shiftKey ? (fineStep ?? step * 10) : step;
      const decimals = getStepDecimals(delta);
      const next = roundToDecimals(clamped + direction * delta, decimals);
      applyValue(next, delta, true);
    },
    [applyValue, clamped, disabled, fineStep, step]
  );

  const handleLabelPointerDown = useCallback(
    (e: React.PointerEvent<HTMLSpanElement>) => {
      if (disabled || e.button !== 0) return;
      e.preventDefault();
      e.stopPropagation();

      if (e.altKey && defaultValue !== undefined) {
        applyValue(defaultValue, step, true);
        return;
      }

      try {
        e.currentTarget.setPointerCapture?.(e.pointerId);
      } catch {
        // Safe in synthetic tests
      }

      scrubRef.current = {
        active: true,
        pointerId: e.pointerId,
        startValue: clamped,
        accumulatedPx: 0,
        lastClientX: e.clientX,
        latestValue: clamped,
      };
      setIsScrubbing(true);
    },
    [applyValue, clamped, defaultValue, disabled, step]
  );

  const handleLabelPointerMove = useCallback(
    (e: React.PointerEvent<HTMLSpanElement>) => {
      const scrub = scrubRef.current;
      if (!scrub.active) return;
      e.stopPropagation();

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

      const scale = e.shiftKey ? 0.1 : 1;
      scrub.accumulatedPx += dx * scale;

      const activeStep = e.shiftKey && fineStep !== undefined ? fineStep : step;
      const stepDelta = Math.trunc(scrub.accumulatedPx / Math.max(1, scrubPixelsPerStep));
      const raw = scrub.startValue + stepDelta * activeStep;
      const next = quantizeValue(raw, min, max, activeStep);

      if (next !== scrub.latestValue) {
        scrub.latestValue = next;
        setDraft(formatNumericValue(next, activeStep));
        onChange(next);
      }
    },
    [fineStep, max, min, onChange, scrubPixelsPerStep, step]
  );

  const finishScrub = useCallback(
    (e: React.PointerEvent<HTMLSpanElement>, cancelled = false) => {
      const scrub = scrubRef.current;
      if (!scrub.active) return;
      e.stopPropagation();
      const pid = scrub.pointerId;
      const finalVal = scrub.latestValue;
      scrub.active = false;
      scrub.pointerId = null;
      setIsScrubbing(false);
      if (pid !== null) {
        try {
          if (
            typeof e.currentTarget.hasPointerCapture !== 'function' ||
            e.currentTarget.hasPointerCapture(pid)
          ) {
            e.currentTarget.releasePointerCapture?.(pid);
          }
        } catch {
          // Ignore in synthetic tests
        }
      }
      if (!cancelled) {
        onCommit?.(finalVal);
      }
    },
    [onCommit]
  );

  const handleLabelDoubleClick = useCallback(
    (e: React.MouseEvent<HTMLSpanElement>) => {
      if (disabled || defaultValue === undefined) return;
      e.preventDefault();
      e.stopPropagation();
      applyValue(defaultValue, step, true);
    },
    [applyValue, defaultValue, disabled, step]
  );

  return (
    <div
      data-testid={dataTestId}
      title={title}
      className={`group relative flex items-center ${HEIGHT_CLASSES[size]} rounded-ui-sm bg-ui-input border transition-colors overflow-hidden ${
        disabled
          ? 'border-ui-subtle opacity-50'
          : isFocused || isScrubbing
            ? 'border-ui-focus'
            : 'border-ui-subtle hover:border-ui-default'
      } ${className}`}
    >
      {label && (
        <span
          data-precision-scrub-handle="true"
          onPointerDown={handleLabelPointerDown}
          onPointerMove={handleLabelPointerMove}
          onPointerUp={(e) => finishScrub(e, false)}
          onPointerCancel={(e) => finishScrub(e, true)}
          onDoubleClick={handleLabelDoubleClick}
          title={
            defaultValue !== undefined
              ? t('Drag horizontally to scrub {label} · Shift for fine · Double-click to reset', {
                  label,
                })
              : t('Drag horizontally to scrub {label} · Shift for fine', { label })
          }
          className={`h-full flex items-center pl-1.5 pr-1 text-[10px] select-none shrink-0 touch-none ${
            disabled
              ? 'text-ui-disabled cursor-not-allowed'
              : isScrubbing
                ? 'text-ui-accent cursor-ew-resize'
                : 'text-ui-muted hover:text-ui-primary cursor-ew-resize'
          }`}
        >
          {label}
        </span>
      )}

      <input
        ref={inputRef}
        type="text"
        inputMode="decimal"
        disabled={disabled}
        aria-label={ariaLabel ?? label ?? t('Numeric input')}
        value={isFocused ? draft : formatNumericValue(clamped, step)}
        onFocus={(e) => {
          cancelledRef.current = false;
          setIsFocused(true);
          setDraft(formatNumericValue(clamped, step));
          e.currentTarget.select?.();
        }}
        onChange={(e) => setDraft(e.target.value)}
        onBlur={() => {
          setIsFocused(false);
          commitDraft();
        }}
        onKeyDown={(e) => {
          e.stopPropagation();
          if (isImeComposing(e)) return;
          if (e.key === 'Enter') {
            e.preventDefault();
            commitDraft();
            inputRef.current?.blur?.();
          } else if (e.key === 'Escape') {
            e.preventDefault();
            cancelledRef.current = true;
            setDraft(formatNumericValue(clamped, step));
            inputRef.current?.blur?.();
          } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            stepBy(1, e.shiftKey);
          } else if (e.key === 'ArrowDown') {
            e.preventDefault();
            stepBy(-1, e.shiftKey);
          }
        }}
        className={`ui-no-spin flex-1 min-w-0 h-full bg-transparent text-right font-ui-mono tabular-nums text-ui-primary border-0 focus:outline-none focus:shadow-none select-text ${
          size === 'xs' ? 'text-[10px] px-1' : 'text-[11px] px-1.5'
        } ${unit ? 'pr-0.5' : ''}`}
      />

      {unit && (
        <span className="pr-1.5 text-[9.5px] font-ui-mono text-ui-muted select-none shrink-0 pointer-events-none">
          {unit}
        </span>
      )}

      {/* Subtle hover steppers */}
      {!disabled && (
        <div className="flex flex-col h-full border-l border-ui-subtle opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity shrink-0">
          <button
            type="button"
            tabIndex={-1}
            aria-label={label ? t('Increase {label}', { label }) : t('Increase value')}
            onMouseDown={(e) => e.preventDefault()}
            onClick={(e) => stepBy(1, e.shiftKey)}
            className="flex-1 w-3.5 flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
          >
            <ChevronUp className="w-2.5 h-2.5" />
          </button>
          <button
            type="button"
            tabIndex={-1}
            aria-label={label ? t('Decrease {label}', { label }) : t('Decrease value')}
            onMouseDown={(e) => e.preventDefault()}
            onClick={(e) => stepBy(-1, e.shiftKey)}
            className="flex-1 w-3.5 flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover border-t border-ui-subtle cursor-pointer"
          >
            <ChevronDown className="w-2.5 h-2.5" />
          </button>
        </div>
      )}
    </div>
  );
};

export const PrecisionNumberInput = React.memo(PrecisionNumberInputInner);
PrecisionNumberInput.displayName = 'PrecisionNumberInput';