Skip to content

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

15.1 KB
Raw Blame
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { Check, ChevronLeft, ChevronRight, Plus, RotateCcw, X } from 'lucide-react';
import { COMMAND_CATALOG, CommandActionId, FocusHudPoint } from '../../types/workspace';
import { useToolStore, useWorkspaceStore, workspaceStoreActions } from '../../stores';
import {
  WorkspaceCommandHandlers,
  executeWorkspaceCommand,
  isCommandActive,
  isCommandDisabled,
  renderCommandIcon,
} from '../CommandBar';
import { FocusGripDots, getFocusHudSurfaceStyle, useFocusHudDrag } from './focusHudUtils';
import { isImeComposing, useI18n } from '../../i18n';

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

const POPOVER_WIDTH = 256;
const POPOVER_EST_HEIGHT = 336;

export const FocusQuickActionDock: React.FC<FocusQuickActionDockProps> = React.memo(
  ({ commandHandlers, floatingOpacity, isAutoFaded, customPosition }) => {
    const { t, td } = useI18n();
    const quickActionIds = useWorkspaceStore((s) => s.focusHud.quickActionIds);
    const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
    const quickBrushVisible = useWorkspaceStore((s) => s.quickBrushPanel.visible);
    const activeTool = useToolStore((s) => s.tool);

    const [customizeOpen, setCustomizeOpen] = useState(false);
    const [popoverPos, setPopoverPos] = useState<{ top: number; left: number }>({
      top: 120,
      left: 120,
    });

    const dockRef = useRef<HTMLDivElement>(null);
    const customizeBtnRef = useRef<HTMLButtonElement>(null);
    const popoverRef = useRef<HTMLDivElement>(null);

    const handleDragStartExtra = useCallback(() => {
      setCustomizeOpen(false);
    }, []);

    const { isDragging, handleStartDrag, handleResetWidgetPosition } = useFocusHudDrag(
      'quickActionDock',
      dockRef,
      customPosition,
      handleDragStartExtra
    );

    const catalogById = useMemo(
      () => new Map(COMMAND_CATALOG.map((entry) => [entry.id, entry])),
      []
    );

    const computePopoverPos = useCallback(() => {
      if (typeof window === 'undefined') return { top: 120, left: 120 };
      const btn = customizeBtnRef.current ?? dockRef.current;
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      const pad = 10;
      if (!btn) {
        return {
          left: Math.max(pad, Math.round((vw - POPOVER_WIDTH) / 2)),
          top: Math.max(pad, vh - POPOVER_EST_HEIGHT - 56),
        };
      }
      const rect = btn.getBoundingClientRect();
      const left = Math.max(
        pad,
        Math.min(vw - POPOVER_WIDTH - pad, Math.round(rect.right - POPOVER_WIDTH))
      );
      let top = Math.round(rect.top - POPOVER_EST_HEIGHT - 8);
      if (top < pad) {
        top = Math.min(vh - POPOVER_EST_HEIGHT - pad, Math.round(rect.bottom + 8));
      }
      top = Math.max(pad, top);
      return { top, left };
    }, []);

    useEffect(() => {
      if (!customizeOpen) return;
      const handleOutside = (e: MouseEvent) => {
        const target = e.target as Node;
        if (
          customizeBtnRef.current?.contains(target) ||
          popoverRef.current?.contains(target)
        ) {
          return;
        }
        setCustomizeOpen(false);
      };
      const handleKey = (e: KeyboardEvent) => {
        if (isImeComposing(e)) return;
        if (e.key === 'Escape') {
          e.stopPropagation();
          setCustomizeOpen(false);
        }
      };
      const handleResize = () => setPopoverPos(computePopoverPos());
      window.addEventListener('mousedown', handleOutside);
      window.addEventListener('keydown', handleKey);
      window.addEventListener('resize', handleResize);
      return () => {
        window.removeEventListener('mousedown', handleOutside);
        window.removeEventListener('keydown', handleKey);
        window.removeEventListener('resize', handleResize);
      };
    }, [computePopoverPos, customizeOpen]);

    const isFixed = Boolean(customPosition);
    const anchorClass = isFixed ? '' : 'absolute bottom-3 left-1/2 -translate-x-1/2';
    const effectiveAutoFade = isAutoFaded && !customizeOpen;

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

    const toggleAction = (id: CommandActionId) => {
      workspaceStoreActions.toggleFocusQuickAction(id);
    };

    return (
      <>
        <div
          ref={dockRef}
          role="toolbar"
          aria-label={t('Focus Quick Actions')}
          data-testid="focus-quick-action-dock"
          data-anchor-side={isFixed ? 'custom' : 'bottom-center'}
          data-hud-blur={floatingOpacity < 0.98 ? 'true' : 'false'}
          data-auto-faded={String(effectiveAutoFade)}
          onPointerDown={(e) => e.stopPropagation()}
          onWheel={(e) => e.stopPropagation()}
          style={surfaceStyle}
          className={`${anchorClass} h-9 px-1.5 rounded-full border shadow-ui-floating text-ui-primary flex items-center gap-0.5 max-w-[calc(100vw-32px)] transition-[opacity,border-color,box-shadow] duration-150 select-none ui-icon-stroke ${
            isDragging ? 'border-ui-strong shadow-ui-popover' : 'border-ui-default'
          }`}
        >
          {/* Left Vertical Drag Grip */}
          <div
            data-testid="focus-quick-action-drag-handle"
            onPointerDown={handleStartDrag}
            onDoubleClick={handleResetWidgetPosition}
            title={t('Drag to move Quick Action Dock · Double-click to recenter')}
            className="group h-full px-1 flex items-center justify-center cursor-grab active:cursor-grabbing shrink-0"
          >
            <FocusGripDots orientation="vertical" />
          </div>

          <span aria-hidden="true" className="h-4 w-px bg-ui-subtle shrink-0 mr-0.5" />

          {/* Customizable Action Capsule Buttons */}
          <div className="flex items-center gap-0.5 overflow-x-auto no-scrollbar">
            {quickActionIds.map((cmdId) => {
              const entry = catalogById.get(cmdId);
              if (!entry) return null;
              const disabled = isCommandDisabled(cmdId, commandHandlers);
              const active = isCommandActive(
                cmdId,
                commandHandlers,
                palettesHidden,
                quickBrushVisible,
                activeTool
              );
              const label = td(entry.label);
              return (
                <button
                  key={cmdId}
                  type="button"
                  data-testid={`focus-quick-action-${cmdId}`}
                  disabled={disabled}
                  onClick={() => executeWorkspaceCommand(cmdId, commandHandlers)}
                  title={`${label}${entry.shortcut ? ` (${entry.shortcut})` : ''}`}
                  aria-label={label}
                  aria-pressed={active || undefined}
                  className={`w-7 h-7 rounded-full flex items-center justify-center transition-colors shrink-0 ${
                    disabled
                      ? 'opacity-35 cursor-not-allowed text-ui-disabled'
                      : active
                        ? 'bg-ui-control-active text-ui-accent border border-ui-accent-border cursor-pointer'
                        : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover border border-transparent cursor-pointer'
                  }`}
                >
                  {renderCommandIcon(cmdId, palettesHidden)}
                </button>
              );
            })}
          </div>

          <span aria-hidden="true" className="h-4 w-px bg-ui-subtle shrink-0 mx-0.5" />

          {/* Inline Customize (+) Popover Trigger */}
          <button
            ref={customizeBtnRef}
            type="button"
            data-testid="focus-quick-action-customize-btn"
            aria-label={t('Customize Quick Action Dock')}
            aria-expanded={customizeOpen}
            title={t('Customize Quick Actions')}
            onClick={() => {
              setCustomizeOpen((prev) => {
                if (!prev) {
                  setPopoverPos(computePopoverPos());
                  return true;
                }
                return false;
              });
            }}
            className={`w-6 h-6 rounded-full flex items-center justify-center transition-colors shrink-0 cursor-pointer ${
              customizeOpen
                ? 'bg-ui-control-active text-ui-accent'
                : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
            }`}
          >
            <Plus className="w-3.5 h-3.5" />
          </button>
        </div>

        {/* Inline Customize Popover */}
        {customizeOpen &&
          typeof document !== 'undefined' &&
          createPortal(
            <div
              ref={popoverRef}
              role="dialog"
              aria-label={t('Customize Focus Quick Actions')}
              data-testid="focus-quick-action-customize-popover"
              onPointerDown={(e) => e.stopPropagation()}
              onWheel={(e) => e.stopPropagation()}
              style={{
                position: 'fixed',
                top: popoverPos.top,
                left: popoverPos.left,
                width: POPOVER_WIDTH,
                zIndex: 1000,
              }}
              className="rounded-ui-md bg-ui-elevated border border-ui-default shadow-ui-popover p-2 text-[11px] text-ui-primary select-none"
            >
              <div className="flex items-center justify-between pb-1.5 mb-1.5 border-b border-ui-subtle">
                <span className="font-medium text-xs">{t('Quick Action Dock')}</span>
                <div className="flex items-center gap-1.5">
                  <button
                    type="button"
                    data-testid="focus-quick-action-reset-btn"
                    onClick={() => workspaceStoreActions.resetFocusQuickActions()}
                    title={t('Reset to default focus actions')}
                    className="text-[10px] text-ui-muted hover:text-ui-primary flex items-center gap-0.5 cursor-pointer"
                  >
                    <RotateCcw className="w-2.5 h-2.5" />
                    <span>{t('Reset')}</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setCustomizeOpen(false)}
                    aria-label={t('Close customize popover')}
                    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 cursor-pointer"
                  >
                    <X className="w-3 h-3" />
                  </button>
                </div>
              </div>

              {/* Active Pinned Order */}
              {quickActionIds.length > 0 && (
                <div className="mb-2 space-y-0.5 max-h-28 overflow-y-auto">
                  <div className="text-[9.5px] uppercase tracking-wider text-ui-muted px-1 mb-0.5 tabular-nums">
                    {t('Active ({count})', { count: quickActionIds.length })}
                  </div>
                  {quickActionIds.map((cid, idx) => {
                    const entry = catalogById.get(cid);
                    if (!entry) return null;
                    return (
                      <div
                        key={cid}
                        className="flex items-center justify-between gap-1 px-1.5 py-0.5 rounded-ui-xs bg-ui-input border border-ui-subtle"
                      >
                        <div className="flex items-center gap-1.5 min-w-0">
                          {renderCommandIcon(cid, palettesHidden)}
                          <span className="truncate text-[10.5px]">{td(entry.label)}</span>
                        </div>
                        <div className="flex items-center gap-0.5 shrink-0">
                          <button
                            type="button"
                            disabled={idx === 0}
                            onClick={() => workspaceStoreActions.moveFocusQuickAction(cid, -1)}
                            title={t('Move left')}
                            className="p-0.5 text-ui-muted hover:text-ui-primary disabled:opacity-25 cursor-pointer"
                          >
                            <ChevronLeft className="w-3 h-3" />
                          </button>
                          <button
                            type="button"
                            disabled={idx === quickActionIds.length - 1}
                            onClick={() => workspaceStoreActions.moveFocusQuickAction(cid, 1)}
                            title={t('Move right')}
                            className="p-0.5 text-ui-muted hover:text-ui-primary disabled:opacity-25 cursor-pointer"
                          >
                            <ChevronRight className="w-3 h-3" />
                          </button>
                          <button
                            type="button"
                            onClick={() => toggleAction(cid)}
                            title={t('Remove')}
                            className="p-0.5 text-ui-muted hover:text-ui-danger cursor-pointer"
                          >
                            <X className="w-3 h-3" />
                          </button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}

              {/* All COMMAND_CATALOG Entries */}
              <div className="text-[9.5px] uppercase tracking-wider text-ui-muted px-1 mb-0.5">
                {t('Available Commands')}
              </div>
              <div className="max-h-40 overflow-y-auto space-y-0.5">
                {COMMAND_CATALOG.map((entry) => {
                  const pinned = quickActionIds.includes(entry.id);
                  return (
                    <button
                      key={entry.id}
                      type="button"
                      data-testid={`focus-quick-action-opt-${entry.id}`}
                      onClick={() => toggleAction(entry.id)}
                      className={`w-full flex items-center justify-between gap-2 px-1.5 py-1 rounded-ui-xs text-left transition-colors cursor-pointer ${
                        pinned
                          ? 'bg-ui-control-active text-ui-primary'
                          : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                      }`}
                    >
                      <span className="flex items-center gap-1.5 min-w-0">
                        {renderCommandIcon(entry.id, palettesHidden)}
                        <span className="truncate text-[10.5px]">{td(entry.label)}</span>
                      </span>
                      {pinned && <Check className="w-3 h-3 text-ui-accent shrink-0" />}
                    </button>
                  );
                })}
              </div>
            </div>,
            document.body
          )}
      </>
    );
  }
);
FocusQuickActionDock.displayName = 'FocusQuickActionDock';