All files / src/components/features/admin/api-docs ApiDocsClient.tsx

0% Statements 0/339
100% Branches 0/0
0% Functions 0/1
0% Lines 0/339

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
'use client';

/**
 * API Documentation Client Component
 * Main component for browsing and testing API endpoints
 */

import React, { useState, useMemo, useCallback } from 'react';
import { useSearchParams, useRouter, usePathname } from 'next/navigation';
import { apiRegistry, searchEndpoints, getEndpointById } from '@/lib/api-docs/registry';
import { ApiCategory, ApiEndpoint, ApiTestRequest } from '@/types/api-docs';
import { downloadOpenAPISpec, downloadOpenAPISpecYaml } from '@/lib/api-docs/executor';
import ApiDocsSidebar from './ApiDocsSidebar';
import EndpointDetail from './EndpointDetail';
import ApiTester from './ApiTester';
import SavedRequests from './SavedRequests';
import EnvironmentSelector from './EnvironmentSelector';
import { Icon } from '@/components/ui/icons';
import { IconName } from '@/components/ui/icons/registry';

// Helper to get initial state from URL (called once during useState initialization)
function getInitialEndpoint(): ApiEndpoint | null {
  if (typeof window === 'undefined') return null;
  const params = new URLSearchParams(window.location.search);
  const endpointId = params.get('endpoint');
  if (endpointId) {
    return getEndpointById(endpointId) ?? null;
  }
  return null;
}

function getInitialCategory(): string | null {
  const endpoint = getInitialEndpoint();
  return endpoint?.category ?? null;
}

function getInitialShowTester(): boolean {
  if (typeof window === 'undefined') return false;
  const params = new URLSearchParams(window.location.search);
  return params.get('tester') === 'true';
}

export default function ApiDocsClient() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  // Initialize state from URL params using lazy initialization
  const [selectedCategory, setSelectedCategory] = useState<string | null>(getInitialCategory);
  const [selectedEndpoint, setSelectedEndpoint] = useState<ApiEndpoint | null>(getInitialEndpoint);
  const [searchQuery, setSearchQuery] = useState('');
  const [showTester, setShowTester] = useState(getInitialShowTester);
  const [showSavedRequests, setShowSavedRequests] = useState(false);
  const [showExportMenu, setShowExportMenu] = useState(false);

  // Update URL when endpoint changes
  const updateUrl = useCallback((endpointId: string | null, tester: boolean = false) => {
    const params = new URLSearchParams(searchParams.toString());
    if (endpointId) {
      params.set('endpoint', endpointId);
      if (tester) {
        params.set('tester', 'true');
      } else {
        params.delete('tester');
      }
    } else {
      params.delete('endpoint');
      params.delete('tester');
    }
    const newUrl = params.toString() ? `${pathname}?${params.toString()}` : pathname;
    router.replace(newUrl, { scroll: false });
  }, [pathname, router, searchParams]);

  // Filter endpoints based on search
  const filteredCategories = useMemo(() => {
    if (!searchQuery.trim()) {
      return apiRegistry.categories;
    }

    const matchingEndpoints = searchEndpoints(searchQuery);
    const matchingCategoryIds = new Set(matchingEndpoints.map((e) => e.category));

    return apiRegistry.categories
      .filter((cat) => matchingCategoryIds.has(cat.id))
      .map((cat) => ({
        ...cat,
        endpoints: cat.endpoints.filter((e) =>
          matchingEndpoints.some((m) => m.id === e.id)
        )}));
  }, [searchQuery]);

  const handleSelectEndpoint = (endpoint: ApiEndpoint) => {
    setSelectedEndpoint(endpoint);
    setSelectedCategory(endpoint.category);
    setShowTester(false);
    updateUrl(endpoint.id, false);
  };

  const handleTestEndpoint = (endpoint: ApiEndpoint) => {
    setSelectedEndpoint(endpoint);
    setShowTester(true);
    updateUrl(endpoint.id, true);
  };

  const handleCloseTester = () => {
    setShowTester(false);
    if (selectedEndpoint) {
      updateUrl(selectedEndpoint.id, false);
    }
  };

  const handleLoadSavedRequest = (request: ApiTestRequest) => {
    // Find the endpoint in the registry
    const endpoint = getEndpointById(request.endpoint.id);
    if (endpoint) {
      setSelectedEndpoint(endpoint);
      setSelectedCategory(endpoint.category);
      setShowTester(true);
      setShowSavedRequests(false);
      updateUrl(endpoint.id, true);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      {/* Header */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 sticky top-0 z-10">
        <div className="max-w-[1400px] mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
                {apiRegistry.title}
              </h1>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                {apiRegistry.description} &bull; v{apiRegistry.version}
              </p>
            </div>
            <div className="flex items-center gap-4">
              <div className="relative">
                <input
                  type="text"
                  placeholder="Search endpoints..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-64 px-4 py-2 pl-10 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent placeholder-gray-400 dark:placeholder-gray-500"
                />
                <Icon name="search" size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500" />
              </div>

              {/* Saved Requests Button */}
              <button
                onClick={() => setShowSavedRequests(!showSavedRequests)}
                className={`p-2 rounded-lg border transition-colors ${
                  showSavedRequests
                    ? 'bg-indigo-100 dark:bg-indigo-900/50 border-indigo-300 dark:border-indigo-700 text-indigo-600 dark:text-indigo-400'
                    : 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700'
                }`}
                title="Saved Requests"
              >
                <Icon name="bookmark" size={20} />
              </button>

              {/* Export Menu */}
              <div className="relative">
                <button
                  onClick={() => setShowExportMenu(!showExportMenu)}
                  className="p-2 rounded-lg border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                  title="Export OpenAPI Spec"
                >
                  <Icon name="file-download" size={20} />
                </button>
                {showExportMenu && (
                  <>
                    <div className="fixed inset-0 z-40" onClick={() => setShowExportMenu(false)} />
                    <div className="absolute right-0 top-full mt-2 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 z-50">
                      <div className="p-2">
                        <button
                          onClick={() => {
                            downloadOpenAPISpec();
                            setShowExportMenu(false);
                          }}
                          className="w-full px-3 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
                        >
                          Export as JSON
                        </button>
                        <button
                          onClick={() => {
                            downloadOpenAPISpecYaml();
                            setShowExportMenu(false);
                          }}
                          className="w-full px-3 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
                        >
                          Export as YAML
                        </button>
                      </div>
                    </div>
                  </>
                )}
              </div>

              {/* Environment Selector */}
              <EnvironmentSelector />

              <span className="text-sm text-gray-500 dark:text-gray-400">
                {apiRegistry.categories.reduce(
                  (acc, cat) => acc + cat.endpoints.length,
                  0
                )}{' '}
                endpoints
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-[1400px] mx-auto px-4 py-6">
        <div className="flex gap-6">
          {/* Sidebar */}
          <div className="w-72 flex-shrink-0 space-y-4">
            <ApiDocsSidebar
              categories={filteredCategories}
              selectedCategory={selectedCategory}
              selectedEndpoint={selectedEndpoint}
              onSelectCategory={setSelectedCategory}
              onSelectEndpoint={handleSelectEndpoint}
            />
            {/* Saved Requests Panel */}
            {showSavedRequests && (
              <SavedRequests onLoadRequest={handleLoadSavedRequest} />
            )}
          </div>

          {/* Content Area */}
          <div className="flex-1 min-w-0">
            {selectedEndpoint ? (
              showTester ? (
                <ApiTester
                  endpoint={selectedEndpoint}
                  onClose={handleCloseTester}
                />
              ) : (
                <EndpointDetail
                  endpoint={selectedEndpoint}
                  onTest={() => handleTestEndpoint(selectedEndpoint)}
                />
              )
            ) : (
              <WelcomeView
                categories={apiRegistry.categories}
                onSelectCategory={(cat) => {
                  setSelectedCategory(cat.id);
                  if (cat.endpoints.length > 0) {
                    const firstEndpoint = cat.endpoints[0];
                    setSelectedEndpoint(firstEndpoint);
                    updateUrl(firstEndpoint.id, false);
                  }
                }}
              />
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// Welcome view when no endpoint is selected
function WelcomeView({
  categories,
  onSelectCategory}: {
  categories: ApiCategory[];
  onSelectCategory: (cat: ApiCategory) => void;
}) {
  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-8">
      <div className="text-center mb-8">
        <div className="inline-flex items-center justify-center w-16 h-16 bg-indigo-100 dark:bg-indigo-900/50 rounded-full mb-4">
          <Icon name="file-text" size={32} className="text-indigo-600 dark:text-indigo-400" />
        </div>
        <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">
          Welcome to the API Documentation
        </h2>
        <p className="text-gray-600 dark:text-gray-400 mt-2 max-w-md mx-auto">
          Select an endpoint from the sidebar to view documentation, or choose
          a category below to get started.
        </p>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        {categories.map((category) => (
          <button
            key={category.id}
            onClick={() => onSelectCategory(category)}
            className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-200 dark:border-gray-600 hover:border-indigo-300 dark:hover:border-indigo-500 hover:bg-indigo-50 dark:hover:bg-indigo-900/30 transition-colors text-left"
          >
            <CategoryIcon icon={category.icon} />
            <h3 className="font-medium text-gray-900 dark:text-gray-100 mt-2">{category.name}</h3>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
              {category.endpoints.length} endpoint
              {category.endpoints.length !== 1 ? 's' : ''}
            </p>
          </button>
        ))}
      </div>
    </div>
  );
}

// Icon mapping for API categories
const CATEGORY_ICON_MAP: Record<string, IconName> = {
  'lock': 'lock-outline',
  'box': 'package',
  'folder': 'folder',
  'shopping-cart': 'shopping-cart',
  'package': 'package',
  'user': 'user',
  'star': 'star-outline',
  'heart': 'heart',
  'credit-card': 'credit-card',
  'tag': 'tag',
  'award': 'award',
  'users': 'users',
  'file-text': 'file-text',
  'columns': 'columns',
  'settings': 'settings',
  'code': 'code',
  'support': 'support',
  'home': 'home',
  'chat-bubble': 'chat-bubble',
  'cpu': 'cpu',
  'image': 'image',
  'clipboard-list': 'clipboard-list',
  'ticket': 'ticket'};

function CategoryIcon({ icon }: { icon?: string }) {
  const iconName = CATEGORY_ICON_MAP[icon || ''] || 'package';
  return <Icon name={iconName} size={20} className="text-indigo-600 dark:text-indigo-400" />;
}