Skip to content

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

12.6 KB
Raw Blame
import React, { useMemo, useRef, useState } from 'react';
import { ChevronDown, ChevronUp, Eraser, Paintbrush, Redo2, Undo2 } from 'lucide-react';
import { isPaintTool } from '../../types/editor';
import { FocusHudPoint } from '../../types/workspace';
import { ALL_BUILTIN_BRUSHES } from '../../utils/presetBrushes';
import { DEFAULT_BRUSH_PRESET_ID, migrateLegacyPresetId } from '../../utils/brushPresetManager';
import { toolStoreActions, useToolStore } from '../../stores';
import { ScrubSlider } from '../ui';
import { WorkspaceCommandHandlers } from '../CommandBar';
import { FocusGripDots, getFocusHudSurfaceStyle, useFocusHudDrag } from './focusHudUtils';
import { useI18n } from '../../i18n';

export interface FocusBrushSlidersHudProps {
  commandHandlers: WorkspaceCommandHandlers;
  leftHandedMode: boolean;
  floatingOpacity: number;
  isAutoFaded: boolean;
  customPosition?: FocusHudPoint;
}

export const FocusBrushSlidersHud: React.FC<FocusBrushSlidersHudProps> = React.memo(
  ({ commandHandlers, leftHandedMode, floatingOpacity, isAutoFaded, customPosition }) => {
    const { t, td } = useI18n();
    const tool = useToolStore((s) => s.tool);
    const lastPaintTool = useToolStore((s) => s.lastPaintTool);
    const brushSettings = useToolStore((s) => s.brushSettings);
    const activePresetId = useToolStore((s) => s.activePresetId);
    const fillSettings = useToolStore((s) => s.fillSettings);
    const liquifySettings = useToolStore((s) => s.liquifySettings);
    const retouchSettings = useToolStore((s) => s.retouchSettings);

    const [collapsed, setCollapsed] = useState(false);
    const cardRef = useRef<HTMLDivElement>(null);

    const { isDragging, handleStartDrag, handleResetWidgetPosition } = useFocusHudDrag(
      'brushSliders',
      cardRef,
      customPosition
    );

    const isEraser = tool === 'eraser';
    const isLiquify = tool === 'liquify';
    const isRetouch = tool === 'retouch';
    const isPaintUnfilled = tool === 'fill' && fillSettings.method === 'paint-unfilled';
    const usesStrength = isLiquify || isRetouch;

    const minSize = isLiquify ? 5 : isRetouch || isPaintUnfilled ? 2 : 0.5;
    const maxSize = isLiquify ? 500 : isRetouch || isPaintUnfilled ? 300 : 500;
    const defaultSize = isLiquify ? 80 : isRetouch ? 40 : isPaintUnfilled ? 24 : 12;

    const currentSize = isLiquify
      ? (liquifySettings.size ?? 80)
      : isRetouch
        ? (retouchSettings.size ?? 40)
        : isPaintUnfilled
          ? (fillSettings.brushSize ?? 24)
          : (brushSettings.size ?? 12);

    const currentOpacityPct = isLiquify
      ? Math.round(liquifySettings.strength ?? 50)
      : isRetouch
        ? Math.round(retouchSettings.strength ?? 50)
        : isPaintUnfilled
          ? Math.round((fillSettings.opacity ?? 1) * 100)
          : Math.round((brushSettings.opacity ?? 1) * 100);

    const currentFlowPct = Math.round(
      (brushSettings.flow ?? brushSettings.brushDensity ?? 1) * 100
    );

    const activeLabel = useMemo(() => {
      if (isEraser) return t('Eraser');
      if (isLiquify) return t('Liquify');
      if (isRetouch) return t('Retouch');
      if (brushSettings.brushName?.trim()) return td(brushSettings.brushName.trim());
      const normalized = migrateLegacyPresetId(
        brushSettings.preset || activePresetId || DEFAULT_BRUSH_PRESET_ID
      );
      const builtin = ALL_BUILTIN_BRUSHES.find((b) => b.id === normalized);
      return builtin?.name ? td(builtin.name) : t('Brush');
    }, [
      activePresetId,
      brushSettings.brushName,
      brushSettings.preset,
      isEraser,
      isLiquify,
      isRetouch,
      t,
      td,
    ]);

    const handleSizeChange = (nextSize: number) => {
      if (isLiquify) {
        toolStoreActions.updateLiquifySettings({ size: Math.round(nextSize) });
      } else if (isRetouch) {
        toolStoreActions.updateRetouchSettings({ size: Math.round(nextSize) });
      } else if (isPaintUnfilled) {
        toolStoreActions.updateFillSettings({ brushSize: Math.round(nextSize) });
      } else {
        toolStoreActions.updateBrushSettings({ size: nextSize });
      }
    };

    const handleOpacityChange = (nextPct: number) => {
      if (isLiquify) {
        toolStoreActions.updateLiquifySettings({ strength: Math.round(nextPct) });
      } else if (isRetouch) {
        toolStoreActions.updateRetouchSettings({ strength: Math.round(nextPct) });
      } else if (isPaintUnfilled) {
        toolStoreActions.updateFillSettings({ opacity: Math.round(nextPct) / 100 });
      } else {
        toolStoreActions.updateBrushSettings({ opacity: Math.round(nextPct) / 100 });
      }
    };

    const handleFlowChange = (nextPct: number) => {
      const ratio = Math.round(nextPct) / 100;
      toolStoreActions.updateBrushSettings({ flow: ratio, brushDensity: ratio });
    };

    const isFixed = Boolean(customPosition);
    const anchorSide = isFixed ? 'custom' : leftHandedMode ? 'right' : 'left';
    const anchorClass = isFixed
      ? ''
      : leftHandedMode
        ? 'absolute bottom-3 right-3'
        : 'absolute bottom-3 left-3';

    const surfaceStyle = getFocusHudSurfaceStyle(
      floatingOpacity,
      isAutoFaded,
      isFixed
        ? {
            position: 'fixed',
            left: customPosition!.x,
            top: customPosition!.y,
            zIndex: isDragging ? 49 : 42,
          }
        : { zIndex: 42 }
    );

    const paintActive = isPaintTool(tool);

    return (
      <section
        ref={cardRef}
        role="region"
        aria-label={t('Focus Brush Controls')}
        data-testid="focus-brush-sliders-hud"
        data-anchor-side={anchorSide}
        data-collapsed={String(collapsed)}
        data-hud-blur={floatingOpacity < 0.98 ? 'true' : 'false'}
        data-auto-faded={String(isAutoFaded)}
        onPointerDown={(e) => e.stopPropagation()}
        onWheel={(e) => e.stopPropagation()}
        style={surfaceStyle}
        className={`${anchorClass} w-[204px] rounded-ui-lg border shadow-ui-floating text-ui-primary transition-[opacity,border-color,box-shadow] duration-150 select-none ui-icon-stroke ${
          isDragging ? 'border-ui-strong shadow-ui-popover' : 'border-ui-default'
        }`}
      >
        {/* Draggable Micro Header */}
        <div
          data-testid="focus-brush-hud-drag-handle"
          onPointerDown={handleStartDrag}
          onDoubleClick={handleResetWidgetPosition}
          title={t('Drag to move Brush Controls · Double-click to snap back')}
          className="group h-6 px-2 flex items-center justify-between gap-1.5 cursor-grab active:cursor-grabbing border-b border-ui-subtle"
        >
          <div className="flex items-center gap-1.5 min-w-0">
            <FocusGripDots orientation="horizontal" />
            <span className="text-[10.5px] font-medium text-ui-secondary truncate">
              {activeLabel}
            </span>
          </div>

          <button
            type="button"
            data-testid="focus-brush-hud-collapse-btn"
            onClick={() => setCollapsed((v) => !v)}
            aria-label={collapsed ? t('Expand Brush Controls') : t('Collapse Brush Controls')}
            aria-expanded={!collapsed}
            title={collapsed ? t('Expand Brush Controls') : t('Collapse Brush Controls')}
            className="w-4 h-4 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer shrink-0"
          >
            {collapsed ? (
              <ChevronUp className="w-3 h-3" />
            ) : (
              <ChevronDown className="w-3 h-3" />
            )}
          </button>
        </div>

        {/* Compact ScrubSliders + Quick Undo/Redo/Brush/Eraser Strip */}
        {!collapsed && (
          <div className="p-2 space-y-1.5">
            <ScrubSlider
              data-testid="focus-brush-size-slider"
              label={t('Size')}
              aria-label={t('Brush Size')}
              size="xs"
              variant="size"
              logarithmic
              min={minSize}
              max={maxSize}
              step={minSize < 1 ? 0.5 : 1}
              defaultValue={defaultSize}
              unit="px"
              formatValue={(v) => `${v < 10 ? v.toFixed(1) : Math.round(v)}px`}
              value={currentSize}
              onChange={handleSizeChange}
            />

            <ScrubSlider
              data-testid="focus-brush-opacity-slider"
              label={usesStrength ? t('Strength') : t('Opacity')}
              aria-label={usesStrength ? t('Tool Strength') : t('Brush Opacity')}
              size="xs"
              variant="opacity"
              min={1}
              max={100}
              step={1}
              defaultValue={usesStrength ? 50 : 100}
              unit="%"
              value={currentOpacityPct}
              onChange={handleOpacityChange}
            />

            <ScrubSlider
              data-testid="focus-brush-flow-slider"
              label={t('Flow / Ink')}
              aria-label={t('Brush Flow')}
              size="xs"
              variant="opacity"
              min={1}
              max={100}
              step={1}
              defaultValue={100}
              unit="%"
              disabled={usesStrength || isPaintUnfilled}
              value={currentFlowPct}
              onChange={handleFlowChange}
            />

            {/* Micro Action Footer: Undo / Redo / Brush / Eraser */}
            <div className="pt-1.5 mt-1 border-t border-ui-subtle grid grid-cols-4 gap-1">
              <button
                type="button"
                data-testid="focus-hud-undo-btn"
                disabled={!commandHandlers.canUndo}
                onClick={() => commandHandlers.onUndo()}
                title={t('Undo (Ctrl+Z)')}
                aria-label={t('Undo')}
                className={`h-6 rounded-ui-xs border flex items-center justify-center transition-colors ${
                  commandHandlers.canUndo
                    ? 'bg-ui-control border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer'
                    : 'bg-ui-input border-ui-subtle text-ui-disabled opacity-40 cursor-not-allowed'
                }`}
              >
                <Undo2 className="w-3.5 h-3.5" />
              </button>

              <button
                type="button"
                data-testid="focus-hud-redo-btn"
                disabled={!commandHandlers.canRedo}
                onClick={() => commandHandlers.onRedo()}
                title={t('Redo (Ctrl+Y)')}
                aria-label={t('Redo')}
                className={`h-6 rounded-ui-xs border flex items-center justify-center transition-colors ${
                  commandHandlers.canRedo
                    ? 'bg-ui-control border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer'
                    : 'bg-ui-input border-ui-subtle text-ui-disabled opacity-40 cursor-not-allowed'
                }`}
              >
                <Redo2 className="w-3.5 h-3.5" />
              </button>

              <button
                type="button"
                data-testid="focus-hud-brush-btn"
                aria-pressed={paintActive}
                onClick={() => toolStoreActions.selectTool(lastPaintTool || 'brush')}
                title={t('Brush (B)')}
                aria-label={t('Brush Tool')}
                className={`h-6 rounded-ui-xs border flex items-center justify-center transition-colors cursor-pointer ${
                  paintActive
                    ? 'bg-ui-control-active border-ui-accent-border text-ui-accent'
                    : 'bg-ui-control border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                <Paintbrush className="w-3.5 h-3.5" />
              </button>

              <button
                type="button"
                data-testid="focus-hud-eraser-btn"
                aria-pressed={isEraser}
                onClick={() => toolStoreActions.selectTool('eraser')}
                title={t('Eraser (E)')}
                aria-label={t('Eraser Tool')}
                className={`h-6 rounded-ui-xs border flex items-center justify-center transition-colors cursor-pointer ${
                  isEraser
                    ? 'bg-ui-control-active border-ui-accent-border text-ui-accent'
                    : 'bg-ui-control border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                <Eraser className="w-3.5 h-3.5" />
              </button>
            </div>
          </div>
        )}
      </section>
    );
  }
);
FocusBrushSlidersHud.displayName = 'FocusBrushSlidersHud';