Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

13.7 KB
Raw Blame
/**
 * Shared Plugin / Skill catalog shell. Settings intercepts tab navigation via
 * `onSelectTab` to keep the embedded catalog inside Settings.
 */

import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Info, Search, TriangleAlert, X } from 'lucide-react';

import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { SegmentedControl } from '@/components/ui/segmented-control';
import { cn } from '@/lib/utils';
import { PluginDevicePicker, type CatalogDeviceControl } from './PluginDevicePicker';
import './plugin-motion.css';

interface PluginManagementLayoutProps {
  activeTab: 'plugins' | 'skills';
  children: ReactNode;
  query?: string;
  onQueryChange?: (query: string) => void;
  searchPlaceholder?: string;
  clearSearchLabel?: string;
  headerActions?: ReactNode;
  showPrimaryTabs?: boolean;
  embedded?: boolean;
  onSelectTab?: (tab: 'plugins' | 'skills') => void;
}

interface PluginManagementHeaderProps {
  activeTab: 'plugins' | 'skills';
  children?: ReactNode;
  query?: string;
  onQueryChange?: (query: string) => void;
  searchPlaceholder?: string;
  clearSearchLabel?: string;
  showPrimaryTabs?: boolean;
  onSelectTab?: (tab: 'plugins' | 'skills') => void;
}

interface PluginManagementPageProps {
  children: ReactNode;
  className?: string;
}

/**
 * Plugin / Skill 是同一个管理页面的两个一级 Tab。宽度和水平留白只能在
 * 这个 Frame 中定义,避免两个页面各自调整后再次漂移。
 */
export const PLUGIN_MANAGEMENT_FRAME_CLASS = 'mx-auto w-full max-w-[920px] px-8 lg:px-12';

/**
 * Catalog cards respond to the width of their own content area rather than the
 * outer window. This matters when app sidebars leave a narrow main pane even
 * though viewport breakpoints such as `sm` / `md` still match.
 */
export const PLUGIN_MANAGEMENT_CARD_GRID_CLASS =
  'grid grid-cols-[repeat(auto-fit,minmax(min(100%,22.5rem),1fr))] gap-3';

export const PLUGIN_MANAGEMENT_CONTENT_CONTAINER_CLASS = 'plugin-management-content-frame';

/**
 * Installed cards keep the two-column catalog track even when only one card is
 * present, so a lone installed plugin does not stretch across the whole page.
 * The plugin catalog container collapses this to one column at narrow widths.
 */
export const PLUGIN_INSTALLED_CARD_GRID_CLASS = 'plugin-installed-card-grid grid grid-cols-2 gap-3';

const PLUGIN_MANAGEMENT_STACKED_MAX_WIDTH = 720;

export function PluginManagementLayout({
  activeTab,
  children,
  query,
  onQueryChange,
  searchPlaceholder,
  clearSearchLabel,
  headerActions,
  showPrimaryTabs = true,
  embedded = false,
  onSelectTab,
}: PluginManagementLayoutProps) {
  return (
    <div
      className={cn(
        'app-wallpaper-surface plugin-management-layout-root plugin-motion-root flex h-full min-h-0 w-full flex-col',
        embedded ? 'bg-transparent' : 'bg-[var(--surface)]',
      )}
    >
      <PluginManagementHeader
        activeTab={activeTab}
        query={query}
        onQueryChange={onQueryChange}
        searchPlaceholder={searchPlaceholder}
        clearSearchLabel={clearSearchLabel}
        showPrimaryTabs={showPrimaryTabs}
        onSelectTab={onSelectTab}
      >
        {headerActions}
      </PluginManagementHeader>
      <div className="flex min-h-0 flex-1 flex-col">{children}</div>
    </div>
  );
}

/** Shared top row: primary tabs, catalog search, then page-specific actions. */
export function PluginManagementHeader({
  activeTab,
  children,
  query,
  onQueryChange,
  searchPlaceholder,
  clearSearchLabel,
  showPrimaryTabs = true,
  onSelectTab,
}: PluginManagementHeaderProps) {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const frameRef = useRef<HTMLDivElement | null>(null);
  const [stacked, setStacked] = useState(false);
  const composingRef = useRef(false);
  const [compositionQuery, setCompositionQuery] = useState<string | null>(null);
  const searchable = query !== undefined && onQueryChange !== undefined;
  const searchInputId = `plugin-management-${activeTab}-search`;
  const resolvedSearchPlaceholder =
    searchPlaceholder ??
    t(activeTab === 'plugins' ? 'settings.ghosts.page.search' : 'skillhub.home.search');
  const resolvedClearSearchLabel =
    clearSearchLabel ??
    t(activeTab === 'plugins' ? 'settings.ghosts.page.clearSearch' : 'skillhub.home.clearSearch');

  useLayoutEffect(() => {
    const frame = frameRef.current;
    const root = frame?.closest('.plugin-management-layout-root');
    if (!root || typeof ResizeObserver === 'undefined') return;
    const update = (width: number) => setStacked(width <= PLUGIN_MANAGEMENT_STACKED_MAX_WIDTH);
    update(root.getBoundingClientRect().width);
    const observer = new ResizeObserver((entries) => {
      const entry = entries[0];
      update(entry?.contentRect.width ?? root.getBoundingClientRect().width);
    });
    observer.observe(root);
    return () => observer.disconnect();
  }, []);

  const tabs = showPrimaryTabs ? (
    <SegmentedControl
      key="plugin-management-tabs"
      className="plugin-motion-tabs shrink-0"
      role="tablist"
      aria-label={t('sidebar.horizontalTabbarAria')}
      style={WINDOW_NO_DRAG_STYLE}
      height={38}
      optionHeight={32}
      optionClassName="plugin-management-tab min-w-[88px] px-4 text-13"
      value={activeTab}
      onValueChange={(tab) =>
        onSelectTab
          ? onSelectTab(tab)
          : navigate(tab === 'plugins' ? '/plugins' : '/skillhub/local')
      }
      options={[
        { value: 'plugins', label: t('settings.ghosts.title') },
        { value: 'skills', label: t('skillhub.home.title') },
      ]}
    />
  ) : null;

  const tools =
    searchable || children ? (
      // 该容器 flex-1 撑满 tab 与右缘之间的整段空间;no-drag 只能标在其中的
      // 交互元素(搜索框 / 动作按钮)上,标在容器上会把中段空白也挖出拖拽区
      // (windowDrag.tsx:drag 区域是纯几何计算,与内容实际占位无关)。
      <div
        key="plugin-management-tools"
        className="plugin-management-tools flex min-w-0 flex-1 items-center justify-end gap-1.5"
      >
        {searchable ? (
          <div
            className="plugin-management-search-control flex h-9 min-w-[148px] max-w-[260px] flex-1 items-center gap-2 rounded-full border px-3 backdrop-blur-md transition-[width,background-color,border-color,box-shadow] focus-within:border-[var(--focus-ring)] focus-within:ring-2 focus-within:ring-[var(--focus-ring-soft)] motion-reduce:transition-none"
            style={{
              ...WINDOW_NO_DRAG_STYLE,
              background: 'color-mix(in srgb, var(--surface-elevated-soft) 70%, transparent)',
              borderColor: 'color-mix(in srgb, var(--border-default) 52%, transparent)',
              boxShadow:
                'inset 0 1px 0 color-mix(in srgb, var(--surface-elevated) 24%, transparent)',
            }}
          >
            <label
              htmlFor={searchInputId}
              className="plugin-management-search-trigger grid size-6 shrink-0 cursor-text place-items-center text-[var(--text-tertiary)]"
            >
              <Search size={15} strokeWidth={1.75} aria-hidden="true" />
            </label>
            <input
              id={searchInputId}
              type="text"
              inputMode="search"
              value={compositionQuery ?? query}
              onCompositionStart={(event) => {
                composingRef.current = true;
                setCompositionQuery(event.currentTarget.value);
              }}
              onCompositionEnd={(event) => {
                composingRef.current = false;
                setCompositionQuery(null);
                onQueryChange(event.currentTarget.value);
              }}
              onChange={(event) => {
                // Skill search updates router state; keep IME drafts local until committed.
                if (composingRef.current) {
                  setCompositionQuery(event.target.value);
                } else {
                  onQueryChange(event.target.value);
                }
              }}
              onKeyDown={(event) => {
                if (event.key !== 'Escape') return;
                if (composingRef.current || event.nativeEvent.isComposing) {
                  // Keep Settings from blurring the field; IME still handles Escape.
                  event.stopPropagation();
                  return;
                }
                // 认领这一下 Esc:外层(设置页)不再接着失焦或退出。
                event.preventDefault();
                // 按住不放的自动连发不算新的一下:清空后不能接着失焦。
                if (event.repeat) return;
                if (query) {
                  onQueryChange('');
                } else {
                  event.currentTarget.blur();
                }
              }}
              placeholder={resolvedSearchPlaceholder}
              aria-label={resolvedSearchPlaceholder}
              className="plugin-management-search-input min-w-0 flex-1 appearance-none border-0 bg-transparent text-13 text-[var(--text-primary)] outline-none placeholder:text-[var(--text-placeholder)]"
            />
            {query ? (
              <button
                type="button"
                onClick={() => onQueryChange('')}
                aria-label={resolvedClearSearchLabel}
                className="plugin-management-search-clear grid size-6 shrink-0 place-items-center rounded-full text-[var(--text-tertiary)] transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
              >
                <X size={13} strokeWidth={1.75} aria-hidden="true" />
              </button>
            ) : null}
          </div>
        ) : null}
        {children ? (
          <div className="flex shrink-0 items-center gap-1.5" style={WINDOW_NO_DRAG_STYLE}>
            {children}
          </div>
        ) : null}
      </div>
    ) : null;

  // Catalog scroll surfaces reserve a 12px gutter on both edges; mirror it here.
  return (
    <div className="plugin-management-header h-16 shrink-0 px-3" style={WINDOW_DRAG_STYLE}>
      <div
        ref={frameRef}
        className={cn(
          PLUGIN_MANAGEMENT_FRAME_CLASS,
          'plugin-management-header-frame flex h-full items-center gap-4',
        )}
      >
        {stacked ? tools : tabs}
        {stacked ? tabs : tools}
      </div>
    </div>
  );
}

/** Shared breathing room and page-enter hook for both top-level catalogs. */
export function PluginManagementPage({ children, className }: PluginManagementPageProps) {
  return (
    <div
      className={cn(
        PLUGIN_MANAGEMENT_FRAME_CLASS,
        PLUGIN_MANAGEMENT_CONTENT_CONTAINER_CLASS,
        'flex flex-col pb-16 pt-8',
        className,
      )}
    >
      {children}
    </div>
  );
}

export function CatalogTargetControls({
  computer,
  project,
  projectLabel,
}: {
  computer?: CatalogDeviceControl;
  project?: ReactNode;
  projectLabel?: string;
}) {
  const { t } = useTranslation();
  if (!computer && !project) return null;
  return (
    <div
      role="group"
      aria-label={t('settings.ghosts.scopePicker.management')}
      data-catalog-region="target"
      className="min-w-0 max-w-full"
      style={WINDOW_NO_DRAG_STYLE}
    >
      <PluginDevicePicker
        {...(computer ?? {
          selected: null,
          onSelect: () => {},
          directory: { candidates: [], target: undefined, online: true, relayOnline: false },
        })}
        projectMenu={project}
        projectLabel={projectLabel}
      />
    </div>
  );
}

export function InstalledCatalogHeader({
  title,
  count,
  controls,
}: {
  title: string;
  count?: number;
  controls?: ReactNode;
}) {
  return (
    <header
      className="mb-4 flex flex-wrap items-center justify-between gap-3"
      data-catalog-region="installed"
    >
      <div className="flex items-baseline gap-2">
        <h2 className="text-20 font-medium leading-6 text-[var(--text-primary)]">{title}</h2>
        {count !== undefined ? (
          <span className="text-13 tabular-nums text-[var(--text-tertiary)]">{count}</span>
        ) : null}
      </div>
      {controls ? (
        <div
          className="flex min-w-0 max-w-full flex-wrap items-center gap-2"
          style={WINDOW_NO_DRAG_STYLE}
        >
          {controls}
        </div>
      ) : null}
    </header>
  );
}

export function CatalogManagementNotice({
  title,
  children,
  action,
  warning = false,
  className,
}: {
  title: string;
  children: ReactNode;
  action?: ReactNode;
  warning?: boolean;
  className?: string;
}) {
  const Icon = warning ? TriangleAlert : Info;
  return (
    <div
      role="status"
      data-catalog-region="notice"
      className={cn(
        'mb-4 flex flex-wrap items-start justify-between gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3',
        className,
      )}
    >
      <div className="flex min-w-0 flex-1 basis-60 items-start gap-2.5">
        <Icon
          size={16}
          aria-hidden="true"
          className={cn(
            'mt-0.5 shrink-0',
            warning ? 'text-[var(--warning-fg)]' : 'text-[var(--text-secondary)]',
          )}
        />
        <div className="min-w-0 flex-1 [overflow-wrap:anywhere]">
          <p className="text-13 font-medium leading-5 text-[var(--text-primary)]">{title}</p>
          <div className="mt-0.5 text-13 leading-5 text-[var(--text-secondary)]">{children}</div>
        </div>
      </div>
      {action ? (
        <div className="ml-auto flex shrink-0 flex-wrap items-center gap-2">{action}</div>
      ) : null}
    </div>
  );
}