Skip to content

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

32.6 KB
Raw Blame
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import {
  Check,
  ChevronDown,
  ChevronUp,
  Eraser,
  Eye,
  EyeOff,
  Lock,
  Paintbrush,
  Plus,
  RotateCcw,
  Rows3,
  Columns3,
  Search,
  SlidersHorizontal,
  Star,
  Trash2,
  Unlock,
  X,
} from 'lucide-react';
import { BrushPresetId, CspBrush } from '../types/editor';
import {
  QuickBrushPanelOrientation,
  QuickBrushPanelState,
  QuickBrushPreviewStyle,
  QuickBrushTileSize,
} from '../types/workspace';
import { ALL_BUILTIN_BRUSHES, ALL_BUILTIN_BRUSH_SECTIONS } from '../utils/presetBrushes';
import { ERASER_PRESET_ID, migrateLegacyPresetId } from '../utils/brushPresetManager';
import {
  uiStoreActions,
  useToolStore,
  useUiStore,
  useWorkspaceStore,
  workspaceStoreActions,
} from '../stores';
import { resolveAppearanceTokens } from '../utils/themeEngine';
import { getCategoryAccentStyle, resolveQuickBrush } from '../utils/quickBrushUtils';
import { isImeComposing, useI18n } from '../i18n';

export interface QuickBrushPanelSettingsProps {
  anchorRef: React.RefObject<HTMLElement | null>;
  initialTab?: 'settings' | 'brushes';
  customBrushes: CspBrush[];
  onClose: () => void;
}

const POPOVER_WIDTH = 286;
const POPOVER_EST_HEIGHT = 430;

export const QuickBrushPanelSettings: React.FC<QuickBrushPanelSettingsProps> = React.memo(
  ({ anchorRef, initialTab = 'settings', customBrushes, onClose }) => {
    const { t, td } = useI18n();
    const config = useWorkspaceStore((s) => s.quickBrushPanel);
    const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
    const activePresetId = useToolStore((s) => s.activePresetId);
    const activeTool = useToolStore((s) => s.tool);
    const appearance = useUiStore((s) => s.appSettings.appearance);
    const isLightScheme = useMemo(
      () => resolveAppearanceTokens(appearance).colorScheme === 'light',
      [appearance]
    );

    const [activeTab, setActiveTab] = useState<'settings' | 'brushes'>(initialTab);
    const [searchQuery, setSearchQuery] = useState('');
    const popoverRef = useRef<HTMLDivElement>(null);

    const computePos = (): { top: number; left: number } => {
      if (typeof window === 'undefined') return { top: 64, left: 64 };
      const rect = anchorRef.current?.getBoundingClientRect();
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      const pad = 10;

      if (!rect) {
        return {
          left: Math.max(pad, Math.round((vw - POPOVER_WIDTH) / 2)),
          top: Math.max(44, Math.round((vh - POPOVER_EST_HEIGHT) / 2)),
        };
      }

      // Prefer opening to the left if anchor is on the right half of viewport, else to the right
      let left =
        rect.left > vw / 2 ? rect.left - POPOVER_WIDTH - 10 : rect.right + 10;
      if (left < pad) left = rect.right + 10;
      if (left + POPOVER_WIDTH > vw - pad) left = vw - POPOVER_WIDTH - pad;
      left = Math.max(pad, left);

      let top = rect.top - 40;
      if (top + POPOVER_EST_HEIGHT > vh - pad) {
        top = vh - POPOVER_EST_HEIGHT - pad;
      }
      top = Math.max(42, top);

      return { top: Math.round(top), left: Math.round(left) };
    };

    const [pos, setPos] = useState<{ top: number; left: number }>(() => computePos());

    useEffect(() => {
      setPos(computePos());
      const handleOutside = (e: MouseEvent) => {
        const target = e.target as Node;
        if (
          popoverRef.current?.contains(target) ||
          anchorRef.current?.contains(target)
        ) {
          return;
        }
        onClose();
      };
      const handleKey = (e: KeyboardEvent) => {
        if (isImeComposing(e)) return;
        if (e.key === 'Escape') {
          e.stopPropagation();
          onClose();
        }
      };
      const handleResize = () => setPos(computePos());

      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);
      };
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [onClose]);

    const pinnedSet = useMemo(
      () => new Set(config.brushIds.map((id) => migrateLegacyPresetId(id))),
      [config.brushIds]
    );

    const currentActiveId: BrushPresetId =
      activeTool === 'eraser' ? ERASER_PRESET_ID : migrateLegacyPresetId(activePresetId);
    const isCurrentPinned = pinnedSet.has(currentActiveId);

    const pinnedEntries = useMemo(
      () =>
        config.brushIds
          .map((id) => resolveQuickBrush(id, customBrushes))
          .filter((b): b is NonNullable<typeof b> => b !== null),
      [config.brushIds, customBrushes]
    );

    const normalizedQuery = searchQuery.trim().toLowerCase();

    const filteredBuiltinSections = useMemo(() => {
      return ALL_BUILTIN_BRUSH_SECTIONS.map((sec) => ({
        ...sec,
        brushes: ALL_BUILTIN_BRUSHES.filter(
          (b) =>
            b.category === sec.id &&
            (!normalizedQuery ||
              b.name.toLowerCase().includes(normalizedQuery) ||
              td(b.name).toLowerCase().includes(normalizedQuery) ||
              sec.label.toLowerCase().includes(normalizedQuery) ||
              td(sec.label).toLowerCase().includes(normalizedQuery))
        ),
      })).filter((s) => s.brushes.length > 0);
    }, [normalizedQuery, td]);

    const filteredCustomBrushes = useMemo(() => {
      if (!normalizedQuery) return customBrushes;
      return customBrushes.filter((b) =>
        b.name.toLowerCase().includes(normalizedQuery)
      );
    }, [customBrushes, normalizedQuery]);

    const update = (patch: Partial<Omit<QuickBrushPanelState, 'brushIds'>>) => {
      workspaceStoreActions.updateQuickBrushPanelSettings(patch);
    };

    const handleToggleBrush = (id: BrushPresetId, name: string) => {
      const added = workspaceStoreActions.toggleQuickBrush(id);
      const displayName = td(name);
      uiStoreActions.showToast(
        added
          ? t('Added "{name}" to Quick Brushes', { name: displayName })
          : t('Removed "{name}" from Quick Brushes', { name: displayName })
      );
    };

    const content = (
      <div
        ref={popoverRef}
        data-testid="quick-brush-settings-popover"
        role="dialog"
        aria-label={t('Quick-Access Brush Panel Settings')}
        onPointerDown={(e) => e.stopPropagation()}
        onWheel={(e) => e.stopPropagation()}
        style={{
          position: 'fixed',
          top: pos.top,
          left: pos.left,
          width: POPOVER_WIDTH,
          zIndex: 1000,
        }}
        className="rounded-ui-lg bg-ui-elevated border border-ui-default shadow-ui-popover text-ui-primary text-[11px] flex flex-col max-h-[calc(100vh-56px)] select-none overflow-hidden"
      >
        {/* Header */}
        <div className="h-8 px-2.5 flex items-center justify-between bg-ui-header border-b border-ui-subtle shrink-0">
          <div className="flex items-center gap-1.5 font-medium text-ui-primary">
            <SlidersHorizontal className="w-3.5 h-3.5 text-ui-accent" />
            <span>{t('Quick Brush Panel')}</span>
          </div>
          <button
            type="button"
            onClick={onClose}
            aria-label={t('Close Quick Brush Settings')}
            className="w-5 h-5 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.5 h-3.5" />
          </button>
        </div>

        {/* Tabs */}
        <div className="grid grid-cols-2 gap-1 p-1.5 bg-ui-header border-b border-ui-subtle shrink-0">
          <button
            type="button"
            data-testid="quick-brush-tab-settings"
            onClick={() => setActiveTab('settings')}
            className={`relative h-6 rounded-ui-sm text-[11px] font-medium flex items-center justify-center gap-1.5 transition-colors cursor-pointer border ${
              activeTab === 'settings'
                ? 'bg-ui-control text-ui-primary border-ui-default'
                : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border-transparent'
            }`}
          >
            <SlidersHorizontal className="w-3 h-3" />
            <span>{t('Panel Settings')}</span>
            {activeTab === 'settings' && (
              <span className="absolute bottom-0 left-2 right-2 h-[2px] bg-ui-accent rounded-full" />
            )}
          </button>
          <button
            type="button"
            data-testid="quick-brush-tab-brushes"
            onClick={() => setActiveTab('brushes')}
            className={`relative h-6 rounded-ui-sm text-[11px] font-medium flex items-center justify-center gap-1.5 transition-colors cursor-pointer border ${
              activeTab === 'brushes'
                ? 'bg-ui-control text-ui-primary border-ui-default'
                : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border-transparent'
            }`}
          >
            <Star className="w-3 h-3" />
            <span className="tabular-nums">{t('Brushes ({count})', { count: pinnedEntries.length })}</span>
            {activeTab === 'brushes' && (
              <span className="absolute bottom-0 left-2 right-2 h-[2px] bg-ui-accent rounded-full" />
            )}
          </button>
        </div>

        {/* Body */}
        {activeTab === 'settings' ? (
          <div className="p-2.5 space-y-3 overflow-y-auto min-h-0">
            {/* Orientation */}
            <div className="space-y-1">
              <div className="text-[10px] uppercase tracking-wider text-ui-muted">{t('Orientation')}</div>
              <div className="grid grid-cols-2 gap-1">
                {(
                  [
                    { id: 'vertical', label: 'Vertical', icon: <Columns3 className="w-3.5 h-3.5" /> },
                    { id: 'horizontal', label: 'Horizontal', icon: <Rows3 className="w-3.5 h-3.5" /> },
                  ] as Array<{ id: QuickBrushPanelOrientation; label: string; icon: React.ReactNode }>
                ).map((opt) => {
                  const active = config.orientation === opt.id;
                  return (
                    <button
                      key={opt.id}
                      type="button"
                      data-testid={`quick-brush-orient-${opt.id}`}
                      onClick={() => update({ orientation: opt.id })}
                      className={`h-7 px-2 rounded-ui-sm flex items-center justify-center gap-1.5 transition-colors cursor-pointer border ${
                        active
                          ? 'bg-ui-control-active text-ui-primary border-ui-accent-border font-medium'
                          : 'bg-ui-input text-ui-secondary border-ui-subtle hover:bg-ui-control-hover hover:text-ui-primary'
                      }`}
                    >
                      {opt.icon}
                      <span>{t(opt.label)}</span>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Tile Size & Columns/Rows */}
            <div className="grid grid-cols-2 gap-2">
              <div className="space-y-1">
                <div className="text-[10px] uppercase tracking-wider text-ui-muted">{t('Tile Size')}</div>
                <div className="grid grid-cols-3 gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                  {(
                    [
                      { id: 'compact', label: 'S' },
                      { id: 'medium', label: 'M' },
                      { id: 'large', label: 'L' },
                    ] as Array<{ id: QuickBrushTileSize; label: string }>
                  ).map((sz) => (
                    <button
                      key={sz.id}
                      type="button"
                      data-testid={`quick-brush-size-${sz.id}`}
                      onClick={() => update({ tileSize: sz.id })}
                      className={`h-6 rounded-ui-xs text-[10px] font-medium transition-colors cursor-pointer ${
                        config.tileSize === sz.id
                          ? 'bg-ui-control-active text-ui-primary'
                          : 'text-ui-muted hover:text-ui-primary'
                      }`}
                    >
                      {sz.label}
                    </button>
                  ))}
                </div>
              </div>

              <div className="space-y-1">
                <div className="text-[10px] uppercase tracking-wider text-ui-muted">
                  {config.orientation === 'vertical' ? t('Columns') : t('Rows')}
                </div>
                <div className="grid grid-cols-2 gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                  {([1, 2] as const).map((n) => (
                    <button
                      key={n}
                      type="button"
                      data-testid={`quick-brush-cols-${n}`}
                      onClick={() => update({ columns: n })}
                      className={`h-6 rounded-ui-xs text-[10px] font-medium tabular-nums transition-colors cursor-pointer ${
                        config.columns === n
                          ? 'bg-ui-control-active text-ui-primary'
                          : 'text-ui-muted hover:text-ui-primary'
                      }`}
                    >
                      {n}
                    </button>
                  ))}
                </div>
              </div>
            </div>

            {/* Preview Style */}
            <div className="space-y-1">
              <div className="text-[10px] uppercase tracking-wider text-ui-muted">{t('Preview Style')}</div>
              <div className="grid grid-cols-2 gap-1 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                {(
                  [
                    { id: 'tip', label: 'Brush Tip' },
                    { id: 'stroke', label: 'Stroke Curve' },
                  ] as Array<{ id: QuickBrushPreviewStyle; label: string }>
                ).map((st) => (
                  <button
                    key={st.id}
                    type="button"
                    data-testid={`quick-brush-preview-${st.id}`}
                    onClick={() => update({ previewStyle: st.id })}
                    className={`h-6 rounded-ui-xs text-[10px] font-medium transition-colors cursor-pointer ${
                      config.previewStyle === st.id
                        ? 'bg-ui-control-active text-ui-primary'
                        : 'text-ui-muted hover:text-ui-primary'
                    }`}
                  >
                    {t(st.label)}
                  </button>
                ))}
              </div>
            </div>

            {/* Opacity Slider */}
            <div className="space-y-1">
              <div className="flex items-center justify-between text-[10px]">
                <span className="uppercase tracking-wider text-ui-muted">{t('Panel Opacity')}</span>
                <span className="font-ui-mono tabular-nums text-ui-primary">
                  {Math.round(config.opacity * 100)}%
                </span>
              </div>
              <input
                type="range"
                data-testid="quick-brush-opacity-slider"
                min={40}
                max={100}
                step={5}
                value={Math.round(config.opacity * 100)}
                onChange={(e) => update({ opacity: Number(e.target.value) / 100 })}
                className="w-full"
              />
            </div>

            {/* Panel Title Input */}
            <div className="space-y-1">
              <div className="text-[10px] uppercase tracking-wider text-ui-muted">{t('Panel Label')}</div>
              <input
                type="text"
                data-testid="quick-brush-title-input"
                value={config.title}
                maxLength={28}
                placeholder={t('Favorites')}
                onChange={(e) => update({ title: e.target.value })}
                className="w-full h-7 px-2 rounded-ui-sm bg-ui-input border border-ui-subtle text-[11px] text-ui-primary placeholder:text-ui-muted"
              />
            </div>

            {/* Toggles */}
            <div className="space-y-1.5 pt-0.5 border-t border-ui-subtle">
              <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">
                <span className="text-ui-secondary">{t('Show brush names')}</span>
                <input
                  type="checkbox"
                  data-testid="quick-brush-toggle-names"
                  checked={config.showNames}
                  onChange={(e) => update({ showNames: e.target.checked })}
                />
              </label>

              <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">
                <span className="text-ui-secondary">{t('Category color accents')}</span>
                <input
                  type="checkbox"
                  data-testid="quick-brush-toggle-colors"
                  checked={config.showCategoryColors}
                  onChange={(e) => update({ showCategoryColors: e.target.checked })}
                />
              </label>

              <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">
                <span className="text-ui-secondary">{t('Show panel label (horizontal)')}</span>
                <input
                  type="checkbox"
                  data-testid="quick-brush-toggle-title"
                  checked={config.showTitle}
                  onChange={(e) => update({ showTitle: e.target.checked })}
                />
              </label>

              <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">
                <div>
                  <div className="text-ui-secondary">{t('Keep visible when UI hidden (Tab)')}</div>
                  <div className="text-[9px] text-ui-muted">
                    {t('Stay on canvas when all palettes are hidden')}
                  </div>
                </div>
                <input
                  type="checkbox"
                  data-testid="quick-brush-toggle-keep-visible"
                  checked={config.keepVisibleWhenPalettesHidden}
                  onChange={(e) => update({ keepVisibleWhenPalettesHidden: e.target.checked })}
                />
              </label>

              <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">
                <span className="text-ui-secondary">{t('Show Hide/Show UI button on bar')}</span>
                <input
                  type="checkbox"
                  data-testid="quick-brush-toggle-hide-ui-btn"
                  checked={config.showHideUiButton}
                  onChange={(e) => update({ showHideUiButton: e.target.checked })}
                />
              </label>

              <label className="flex items-center justify-between gap-2 py-0.5 cursor-pointer">
                <span className="text-ui-secondary flex items-center gap-1.5">
                  {config.locked ? (
                    <Lock className="w-3 h-3 text-ui-accent" />
                  ) : (
                    <Unlock className="w-3 h-3 text-ui-muted" />
                  )}
                  <span>{t('Lock position & brush list')}</span>
                </span>
                <input
                  type="checkbox"
                  data-testid="quick-brush-toggle-lock"
                  checked={config.locked}
                  onChange={(e) => update({ locked: e.target.checked })}
                />
              </label>
            </div>

            {/* Footer quick actions */}
            <div className="pt-2 border-t border-ui-subtle space-y-1.5">
              <button
                type="button"
                data-testid="quick-brush-toggle-all-ui-btn"
                onClick={() => workspaceStoreActions.togglePalettesHidden()}
                className="w-full h-7 px-2 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-primary flex items-center justify-between cursor-pointer transition-colors"
              >
                <span className="flex items-center gap-1.5">
                  {palettesHidden ? (
                    <Eye className="w-3.5 h-3.5 text-ui-accent" />
                  ) : (
                    <EyeOff className="w-3.5 h-3.5 text-ui-accent" />
                  )}
                  <span>{palettesHidden ? t('Show All Palettes') : t('Hide All Other Palettes')}</span>
                </span>
                <span className="text-[10px] font-ui-mono text-ui-muted">Tab</span>
              </button>

              <div className="grid grid-cols-2 gap-1">
                <button
                  type="button"
                  data-testid="quick-brush-reset-pos-btn"
                  onClick={() => workspaceStoreActions.setQuickBrushPanelPosition(null, true)}
                  className="h-6 px-2 rounded-ui-sm bg-ui-input hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary text-[10px] cursor-pointer transition-colors"
                >
                  {t('Snap to Edge')}
                </button>
                <button
                  type="button"
                  data-testid="quick-brush-reset-all-btn"
                  onClick={() => {
                    workspaceStoreActions.resetQuickBrushPanel();
                    uiStoreActions.showToast(t('Quick Brush Panel reset to defaults'));
                  }}
                  className="h-6 px-2 rounded-ui-sm bg-ui-input hover:bg-ui-control-hover border border-ui-subtle text-ui-warning text-[10px] flex items-center justify-center gap-1 cursor-pointer transition-colors"
                >
                  <RotateCcw className="w-3 h-3" />
                  <span>{t('Reset Panel')}</span>
                </button>
              </div>
            </div>
          </div>
        ) : (
          <div className="p-2.5 flex flex-col gap-2 min-h-0 overflow-hidden">
            {/* Quick Add Active Brush / Eraser */}
            <div className="grid grid-cols-2 gap-1 shrink-0">
              <button
                type="button"
                disabled={isCurrentPinned}
                onClick={() => {
                  const resolved = resolveQuickBrush(currentActiveId, customBrushes);
                  const added = workspaceStoreActions.addQuickBrush(currentActiveId);
                  if (added) {
                    uiStoreActions.showToast(
                      t('Added "{name}" to Quick Brushes', {
                        name: resolved ? td(resolved.name) : t('Brush'),
                      })
                    );
                  }
                }}
                className="h-6 px-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle disabled:opacity-40 disabled:cursor-not-allowed text-[10px] text-ui-primary flex items-center justify-center gap-1 cursor-pointer"
              >
                <Plus className="w-3 h-3 text-ui-accent" />
                <span className="truncate">
                  {isCurrentPinned ? t('Active Pinned') : t('Add Active')}
                </span>
              </button>

              <button
                type="button"
                onClick={() => handleToggleBrush(ERASER_PRESET_ID, 'Eraser')}
                className={`h-6 px-1.5 rounded-ui-sm text-[10px] flex items-center justify-center gap-1 cursor-pointer border ${
                  pinnedSet.has(ERASER_PRESET_ID)
                    ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'
                    : 'bg-ui-input hover:bg-ui-control-hover border-ui-subtle text-ui-secondary hover:text-ui-primary'
                }`}
              >
                <Eraser className="w-3 h-3" />
                <span>{pinnedSet.has(ERASER_PRESET_ID) ? t('Eraser Pinned') : t('+ Pin Eraser')}</span>
              </button>
            </div>

            {/* Pinned Order Management */}
            <div className="space-y-1 shrink-0">
              <div className="flex items-center justify-between text-[10px] text-ui-muted">
                <span className="uppercase tracking-wider tabular-nums">
                  {t('Pinned ({count})', { count: pinnedEntries.length })}
                </span>
                <div className="flex items-center gap-1.5">
                  {pinnedEntries.length > 0 && (
                    <button
                      type="button"
                      onClick={() => workspaceStoreActions.clearQuickBrushes()}
                      className="hover:text-ui-danger cursor-pointer"
                      title={t('Clear all pinned brushes')}
                    >
                      {t('Clear')}
                    </button>
                  )}
                </div>
              </div>

              {pinnedEntries.length === 0 ? (
                <div className="px-2 py-2 rounded-ui-sm bg-ui-input border border-ui-subtle text-center text-[10px] text-ui-muted">
                  {t('No brushes pinned yet. Pick any brush below or click the star in Sub Tool.')}
                </div>
              ) : (
                <div className="max-h-28 overflow-y-auto space-y-0.5 pr-0.5">
                  {pinnedEntries.map((brush, idx) => {
                    const accent = getCategoryAccentStyle(brush.category);
                    return (
                      <div
                        key={brush.id}
                        className="flex items-center justify-between gap-1 px-1.5 py-1 rounded-ui-xs bg-ui-input border border-ui-subtle"
                      >
                        <div className="flex items-center gap-1.5 min-w-0">
                          <span
                            className="w-1 h-3 rounded-full shrink-0"
                            style={{ backgroundColor: accent.barColor || 'var(--ui-border-strong)' }}
                          />
                          <span className="truncate text-[11px] text-ui-primary">
                            {td(brush.name, 'brushName')}
                          </span>
                        </div>
                        <div className="flex items-center gap-0.5 shrink-0">
                          <button
                            type="button"
                            disabled={idx === 0}
                            onClick={() => workspaceStoreActions.moveQuickBrush(brush.id, -1)}
                            title={t('Move earlier')}
                            className="p-0.5 text-ui-muted hover:text-ui-primary disabled:opacity-25 cursor-pointer"
                          >
                            <ChevronUp className="w-3 h-3" />
                          </button>
                          <button
                            type="button"
                            disabled={idx === pinnedEntries.length - 1}
                            onClick={() => workspaceStoreActions.moveQuickBrush(brush.id, 1)}
                            title={t('Move later')}
                            className="p-0.5 text-ui-muted hover:text-ui-primary disabled:opacity-25 cursor-pointer"
                          >
                            <ChevronDown className="w-3 h-3" />
                          </button>
                          <button
                            type="button"
                            onClick={() => workspaceStoreActions.removeQuickBrush(brush.id)}
                            title={t('Remove from Quick Brushes')}
                            className="p-0.5 text-ui-muted hover:text-ui-danger cursor-pointer"
                          >
                            <Trash2 className="w-3 h-3" />
                          </button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>

            {/* Search & Add Brushes Catalog */}
            <div className="relative shrink-0 pt-1 border-t border-ui-subtle">
              <Search className="w-3 h-3 text-ui-muted absolute left-2 top-1/2 -translate-y-1/2 mt-0.5 pointer-events-none" />
              <input
                type="text"
                data-testid="quick-brush-search-input"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder={t('Search brushes to add...')}
                className="w-full h-6 pl-6 pr-2 rounded-ui-sm bg-ui-input border border-ui-subtle text-[10px] text-ui-primary placeholder:text-ui-muted"
              />
            </div>

            <div className="flex-1 min-h-0 max-h-44 overflow-y-auto space-y-2 pr-0.5">
              {filteredBuiltinSections.map((sec) => (
                <div key={sec.id} className="space-y-0.5">
                  <div className="text-[9px] uppercase tracking-wider text-ui-muted px-1">
                    {td(sec.label)}
                  </div>
                  {sec.brushes.map((b) => {
                    const isPinned = pinnedSet.has(b.id);
                    return (
                      <button
                        key={b.id}
                        type="button"
                        data-testid={`quick-brush-catalog-toggle-${b.id}`}
                        onClick={() => handleToggleBrush(b.id, b.name)}
                        className={`w-full flex items-center justify-between gap-2 px-1.5 py-1 rounded-ui-xs text-left transition-colors cursor-pointer ${
                          isPinned
                            ? 'bg-ui-control-active text-ui-primary'
                            : 'bg-ui-input text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'
                        }`}
                      >
                        <span className="flex items-center gap-1.5 min-w-0">
                          <Paintbrush className="w-3 h-3 shrink-0 opacity-75" />
                          <span className="truncate text-[10px]">{td(b.name, 'brushName')}</span>
                        </span>
                        {isPinned ? (
                          <Check className="w-3 h-3 text-ui-accent shrink-0" />
                        ) : (
                          <Plus className="w-3 h-3 text-ui-muted shrink-0" />
                        )}
                      </button>
                    );
                  })}
                </div>
              ))}

              {filteredCustomBrushes.length > 0 && (
                <div className="space-y-0.5">
                  <div className="text-[9px] uppercase tracking-wider text-ui-muted px-1">
                    {t('Imported / Custom')}
                  </div>
                  {filteredCustomBrushes.map((b) => {
                    const isPinned = pinnedSet.has(b.id);
                    return (
                      <button
                        key={b.id}
                        type="button"
                        data-testid={`quick-brush-catalog-toggle-${b.id}`}
                        onClick={() => handleToggleBrush(b.id, b.name)}
                        className={`w-full flex items-center justify-between gap-2 px-1.5 py-1 rounded-ui-xs text-left transition-colors cursor-pointer ${
                          isPinned
                            ? 'bg-ui-control-active text-ui-primary'
                            : 'bg-ui-input text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'
                        }`}
                      >
                        <span className="flex items-center gap-1.5 min-w-0">
                          {b.tipDataUrl ? (
                            <img
                              src={b.tipDataUrl}
                              alt=""
                              className={`w-3 h-3 object-contain shrink-0 ${
                                b.isColorTip
                                  ? ''
                                  : isLightScheme
                                    ? 'invert'
                                    : 'brightness-125'
                              }`}
                            />
                          ) : (
                            <Paintbrush className="w-3 h-3 shrink-0 opacity-75" />
                          )}
                          <span className="truncate text-[10px]">{td(b.name, 'brushName')}</span>
                        </span>
                        {isPinned ? (
                          <Check className="w-3 h-3 text-ui-accent shrink-0" />
                        ) : (
                          <Plus className="w-3 h-3 text-ui-muted shrink-0" />
                        )}
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    );

    return typeof document !== 'undefined' ? createPortal(content, document.body) : content;
  }
);

QuickBrushPanelSettings.displayName = 'QuickBrushPanelSettings';