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, { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { LayoutGrid, Trash2, Plus, Copy, X } from 'lucide-react';
import { CanvasColorMode } from '../types/editor';
import {
  useToolStore,
  toolStoreActions,
  useColorSetsStore,
  colorSetsStoreActions,
  SWATCH_COLUMN_OPTIONS,
  SwatchColumnCount,
  uiStoreActions,
} from '../stores';
import { isImeComposing, useI18n } from '../i18n';

export interface ColorHistoryPanelProps {
  colorMode?: CanvasColorMode;
  containerWidth?: number;
}

const ACTIVE_SWATCH_SHADOW = 'inset 0 0 0 1.5px #ffffff, inset 0 0 0 2.5px #111111';

function getSwatchHeightClass(columns: SwatchColumnCount): string {
  if (columns >= 5) return 'aspect-square min-h-[16px] max-h-[34px]';
  if (columns >= 3) return 'h-7';
  return 'h-6';
}

function clampPopoverPosition(
  anchorX: number,
  anchorY: number,
  menuWidth: number,
  menuHeight: number
): { left: number; top: number } {
  if (typeof window === 'undefined') return { left: anchorX, top: anchorY };
  const pad = 8;
  const left = Math.max(pad, Math.min(window.innerWidth - menuWidth - pad, anchorX));
  const top = Math.max(pad, Math.min(window.innerHeight - menuHeight - pad, anchorY));
  return { left, top };
}

export const ColorHistoryPanel: React.FC<ColorHistoryPanelProps> = React.memo(
  ({ colorMode = 'color', containerWidth = 224 }) => {
    const { t, td } = useI18n();
    const recentColors = useToolStore((s) => s.recentColors);
    const primaryColor = useToolStore((s) => s.primaryColor);
    const columns = useColorSetsStore((s) => s.historyColumns);
    const activeSetName = useColorSetsStore(
      (s) => s.sets.find((set) => set.id === s.activeSetId)?.name ?? s.sets[0]?.name ?? 'Color Set'
    );
    const activeSetDisplayName = td(activeSetName);

    const isNarrow = containerWidth < 132;
    const [hoveredHex, setHoveredHex] = useState<string | null>(null);
    const [contextMenu, setContextMenu] = useState<{
      hex: string;
      left: number;
      top: number;
    } | null>(null);
    const contextMenuRef = useRef<HTMLDivElement | null>(null);

    useEffect(() => {
      if (!contextMenu) return;
      const onPointerDown = (e: MouseEvent) => {
        if (contextMenuRef.current?.contains(e.target as Node)) return;
        setContextMenu(null);
      };
      const onKeyDown = (e: KeyboardEvent) => {
        if (isImeComposing(e)) return;
        if (e.key === 'Escape') setContextMenu(null);
      };
      window.addEventListener('mousedown', onPointerDown);
      window.addEventListener('keydown', onKeyDown);
      return () => {
        window.removeEventListener('mousedown', onPointerDown);
        window.removeEventListener('keydown', onKeyDown);
      };
    }, [contextMenu]);

    const handleAddToActiveSet = useCallback(
      (hex: string) => {
        const added = colorSetsStoreActions.addSwatch(hex);
        if (added) {
          uiStoreActions.showToast(
            t('Added {hex} to "{set}"', {
              hex: added.hex.toUpperCase(),
              set: activeSetDisplayName,
            })
          );
        }
        setContextMenu(null);
      },
      [activeSetDisplayName, t]
    );

    const handleCopyHex = useCallback(
      (hex: string) => {
        try {
          void navigator.clipboard?.writeText(hex.toUpperCase());
        } catch {
          // Ignore clipboard errors
        }
        uiStoreActions.showToast(t('Copied {hex}', { hex: hex.toUpperCase() }));
        setContextMenu(null);
      },
      [t]
    );

    const normalizedPrimary = primaryColor.toLowerCase();
    const swatchHeightClass = getSwatchHeightClass(columns);
    const footerColor = hoveredHex ?? recentColors[0] ?? null;

    return (
      <div
        data-testid="color-history-panel"
        className="flex flex-col h-full w-full min-h-0 select-none bg-ui-panel text-ui-primary overflow-hidden"
      >
        {/* Compact Toolbar: Count + Independent Columns (1..8) + Clear History */}
        <div className="h-7 px-1.5 flex items-center justify-between gap-1 shrink-0 bg-ui-header border-b border-ui-subtle">
          <div className="flex items-center gap-1 min-w-0">
            {!isNarrow && (
              <span
                data-testid="color-history-count"
                className="text-[10px] font-ui-mono tabular-nums text-ui-muted truncate px-0.5"
              >
                {recentColors.length}
              </span>
            )}
          </div>

          <div className="flex items-center gap-1 shrink-0">
            <label
              className="flex items-center gap-1 shrink-0 text-ui-muted"
              title={t('Swatches per row (1–8)')}
            >
              {!isNarrow && <LayoutGrid className="w-2.5 h-2.5 text-ui-icon-muted shrink-0" />}
              <select
                data-testid="color-history-columns-select"
                aria-label={t('Color History columns')}
                value={columns}
                onChange={(e) =>
                  colorSetsStoreActions.setHistoryColumns(
                    Number(e.target.value) as SwatchColumnCount
                  )
                }
                className="h-5 bg-ui-input text-ui-primary border border-ui-subtle hover:border-ui-default font-ui-mono tabular-nums text-[10px] px-1 rounded-ui-xs cursor-pointer"
              >
                {SWATCH_COLUMN_OPTIONS.map((n) => (
                  <option key={n} value={n} className="bg-ui-elevated text-ui-primary">
                    {n}
                  </option>
                ))}
              </select>
            </label>

            <button
              type="button"
              data-testid="color-history-clear-btn"
              disabled={recentColors.length === 0}
              onClick={() => toolStoreActions.clearRecentColors()}
              title={t('Clear Color History')}
              aria-label={t('Clear Color History')}
              className={`w-5 h-5 rounded-ui-xs flex items-center justify-center shrink-0 transition-colors ${
                recentColors.length === 0
                  ? 'text-ui-disabled cursor-not-allowed'
                  : 'text-ui-icon-muted hover:text-ui-danger hover:bg-ui-control-hover cursor-pointer'
              }`}
            >
              <Trash2 className="w-3 h-3" />
            </button>
          </div>
        </div>

        {/* Swatch Grid */}
        <div
          className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-1.5"
          onMouseLeave={() => setHoveredHex(null)}
        >
          {recentColors.length === 0 ? (
            <div className="h-full min-h-[64px] flex items-center justify-center px-2 text-center text-[11px] text-ui-muted">
              {t('No recent colors')}
            </div>
          ) : (
            <div
              data-testid="color-history-grid"
              data-columns={columns}
              style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
              className="grid w-full border-t border-l border-ui-subtle"
            >
              {recentColors.map((hex, idx) => {
                const isActive = hex.toLowerCase() === normalizedPrimary;
                return (
                  <div
                    key={`${hex}-${idx}`}
                    className="group relative w-full"
                    onMouseEnter={() => setHoveredHex(hex)}
                  >
                    <button
                      type="button"
                      data-testid={`color-history-swatch-${idx}`}
                      data-hex={hex}
                      data-active={isActive ? 'true' : undefined}
                      aria-label={t('Recent color {color}', { color: hex.toUpperCase() })}
                      aria-pressed={isActive}
                      title={t(
                        '{hex} — Click: Primary · Middle: Secondary · Right-click: Add to "{set}"',
                        { hex: hex.toUpperCase(), set: activeSetDisplayName }
                      )}
                      onClick={() => toolStoreActions.setPrimaryColor(hex, false, colorMode)}
                      onAuxClick={(e) => {
                        if (e.button === 1) {
                          e.preventDefault();
                          toolStoreActions.setSecondaryColor(hex, false, colorMode);
                        }
                      }}
                      onContextMenu={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        const pos = clampPopoverPosition(e.clientX, e.clientY, 184, 152);
                        setContextMenu({ hex, left: pos.left, top: pos.top });
                      }}
                      style={{
                        backgroundColor: hex,
                        boxShadow: isActive ? ACTIVE_SWATCH_SHADOW : undefined,
                      }}
                      className={`block w-full ${swatchHeightClass} border-r border-b border-ui-subtle cursor-pointer focus:outline-none focus-visible:z-20 focus-visible:ring-1 focus-visible:ring-ui-focus ${
                        isActive ? 'relative z-10' : 'hover:relative hover:z-10'
                      }`}
                    />

                    {/* In wide 1–2 col strips, surface a subtle hover quick-add icon */}
                    {columns <= 2 && containerWidth >= 112 && (
                      <button
                        type="button"
                        data-testid={`color-history-quick-add-${idx}`}
                        onClick={(e) => {
                          e.stopPropagation();
                          handleAddToActiveSet(hex);
                        }}
                        title={t('Add {hex} to "{set}"', {
                          hex: hex.toUpperCase(),
                          set: activeSetDisplayName,
                        })}
                        aria-label={t('Add {hex} to {set}', {
                          hex: hex.toUpperCase(),
                          set: activeSetDisplayName,
                        })}
                        className="opacity-0 group-hover:opacity-100 focus:opacity-100 absolute right-1 top-1/2 -translate-y-1/2 z-20 w-4 h-4 rounded-ui-xs flex items-center justify-center bg-ui-elevated/90 border border-ui-default text-ui-primary hover:bg-ui-control-active cursor-pointer transition-opacity"
                      >
                        <Plus className="w-2.5 h-2.5" />
                      </button>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Slim Readout & 1-Click Save to Active Color Set Footer */}
        {footerColor && !isNarrow && (
          <div className="h-6 px-1.5 flex items-center justify-between gap-1 shrink-0 bg-ui-header border-t border-ui-subtle">
            <div className="flex items-center gap-1.5 min-w-0">
              <span
                className="w-2.5 h-2.5 rounded-[2px] border border-ui-strong shrink-0"
                style={{ backgroundColor: footerColor }}
              />
              <span className="text-[10px] font-ui-mono tabular-nums text-ui-secondary uppercase truncate">
                {footerColor}
              </span>
            </div>

            <button
              type="button"
              data-testid="color-history-add-to-set-btn"
              onClick={() => handleAddToActiveSet(footerColor)}
              title={t('Add {hex} to "{set}"', {
                hex: footerColor.toUpperCase(),
                set: activeSetDisplayName,
              })}
              className="h-4.5 px-1.5 rounded-ui-xs flex items-center gap-0.5 text-[10px] bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary cursor-pointer transition-colors shrink-0"
            >
              <Plus className="w-2.5 h-2.5" />
              <span>{t('Set')}</span>
            </button>
          </div>
        )}

        {/* Portaled Swatch Context Menu */}
        {contextMenu &&
          typeof document !== 'undefined' &&
          createPortal(
            <div
              ref={contextMenuRef}
              data-testid="color-history-context-menu"
              style={{
                position: 'fixed',
                left: contextMenu.left,
                top: contextMenu.top,
              }}
              className="w-48 rounded-ui-md shadow-ui-popover p-1 z-[1000] text-[11px] bg-ui-elevated border border-ui-default text-ui-primary"
            >
              <div className="px-2 py-0.5 flex items-center gap-1.5 text-[10px] text-ui-muted">
                <span
                  className="w-2.5 h-2.5 rounded-[2px] border border-ui-strong shrink-0"
                  style={{ backgroundColor: contextMenu.hex }}
                />
                <span className="font-ui-mono tabular-nums uppercase truncate">
                  {contextMenu.hex}
                </span>
              </div>
              <div className="my-0.5 border-t border-ui-subtle" />

              <button
                type="button"
                data-testid="history-ctx-add-to-set"
                onClick={() => handleAddToActiveSet(contextMenu.hex)}
                className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
              >
                <Plus className="w-3 h-3 text-ui-accent shrink-0" />
                <span className="truncate">
                  {t('Add to "{set}"', { set: activeSetDisplayName })}
                </span>
              </button>

              <button
                type="button"
                data-testid="history-ctx-set-secondary"
                onClick={() => {
                  toolStoreActions.setSecondaryColor(contextMenu.hex, false, colorMode);
                  setContextMenu(null);
                }}
                className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
              >
                <span>{t('Set Secondary Color')}</span>
              </button>

              <button
                type="button"
                data-testid="history-ctx-copy"
                onClick={() => handleCopyHex(contextMenu.hex)}
                className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
              >
                <Copy className="w-3 h-3 text-ui-icon-muted" />
                <span>{t('Copy Hex')}</span>
              </button>

              <div className="my-0.5 border-t border-ui-subtle" />

              <button
                type="button"
                data-testid="history-ctx-remove"
                onClick={() => {
                  toolStoreActions.removeRecentColor(contextMenu.hex);
                  setContextMenu(null);
                }}
                className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-danger/15 text-ui-danger cursor-pointer text-left"
              >
                <X className="w-3 h-3" />
                <span>{t('Remove from History')}</span>
              </button>
            </div>,
            document.body
          )}
      </div>
    );
  }
);

ColorHistoryPanel.displayName = 'ColorHistoryPanel';