Merge branch 'feature/global-apikey-widget'
This commit is contained in:
commit
f1335fb4d3
|
|
@ -5,6 +5,8 @@ import { usePathname } from 'next/navigation';
|
|||
import { SubsectionNav } from '@/components/shared/SubsectionNav';
|
||||
import { DocsSidebar } from '@/components/docs/layout/DocsSidebar';
|
||||
import { ThreeColumnLayout } from '@/components/layout/ThreeColumnLayout';
|
||||
import { ApiKeyWidget } from '@/components/shared/ApiKeyWidget/apikey-widget';
|
||||
import { ApiKeyProvider } from '@/components/shared/ApiKeyWidget/apikey-context';
|
||||
|
||||
/**
|
||||
* Root Documentation Layout
|
||||
|
|
@ -44,6 +46,7 @@ export default function DocsRootLayout({ children }: DocsRootLayoutProps) {
|
|||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<ApiKeyProvider>
|
||||
<div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950">
|
||||
{/* Animated gradient background (matching landing page) */}
|
||||
<div className="fixed inset-0 overflow-hidden pointer-events-none">
|
||||
|
|
@ -57,6 +60,7 @@ export default function DocsRootLayout({ children }: DocsRootLayoutProps) {
|
|||
currentPath={pathname}
|
||||
ctaText="Join Beta"
|
||||
ctaHref="/signup"
|
||||
rightSlot={<ApiKeyWidget />}
|
||||
/>
|
||||
|
||||
{/* Three-column Documentation Layout */}
|
||||
|
|
@ -71,5 +75,6 @@ export default function DocsRootLayout({ children }: DocsRootLayoutProps) {
|
|||
/>
|
||||
</div>
|
||||
</div>
|
||||
</ApiKeyProvider>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
'use client';
|
||||
|
||||
import { useApiKey } from '@/components/shared/ApiKeyWidget/apikey-context';
|
||||
/**
|
||||
* Interactive API Widget - Production Version
|
||||
*
|
||||
|
|
@ -60,6 +61,8 @@ export const InteractiveAPIWidget = ({
|
|||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const [paramValues, setParamValues] = useState<Record<string, string>>({});
|
||||
|
||||
const {apiKeyValidated, focus} = useApiKey()
|
||||
|
||||
// Load API key from localStorage and listen for changes
|
||||
useEffect(() => {
|
||||
const loadApiKey = () => {
|
||||
|
|
@ -266,7 +269,7 @@ func main() {
|
|||
|
||||
// Expand API key input in navigation
|
||||
const expandApiKey = () => {
|
||||
window.dispatchEvent(new CustomEvent('expandApiKeyInput'));
|
||||
focus();
|
||||
};
|
||||
|
||||
const isSuccess = response && response.success === true;
|
||||
|
|
@ -336,7 +339,7 @@ func main() {
|
|||
onClick={expandApiKey}
|
||||
className="text-sm text-gray-400 hover:text-white underline-offset-4 hover:underline transition-colors"
|
||||
>
|
||||
{apiKey ? 'API Key Set' : 'Enter API Key'}
|
||||
{apiKeyValidated ? 'API Key Set' : 'Enter API Key'}
|
||||
</button>
|
||||
<button
|
||||
onClick={executeRequest}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,232 @@
|
|||
'use client';
|
||||
|
||||
/**
|
||||
* API Key Context Provider
|
||||
*
|
||||
* Centralized state management for API key functionality across demo pages.
|
||||
* Provides:
|
||||
* - API key validation and storage
|
||||
* - UI state management (expanded, visibility)
|
||||
* - Focus method for external components
|
||||
* - Automatic validation of stored keys on mount
|
||||
*
|
||||
* Phase 1 of centralizing apikey functionality (previously duplicated across demo pages)
|
||||
*/
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect, useRef, useCallback } from 'react';
|
||||
import {
|
||||
validateApiKeyRequest,
|
||||
getStoredKey,
|
||||
setStoredKey,
|
||||
clearStoredKey,
|
||||
type ApiKeyContextValue,
|
||||
type ApiKeyProviderProps,
|
||||
type ApiKeyInfo,
|
||||
} from '@/lib/apikey';
|
||||
|
||||
// Create context with undefined default (will error if used outside provider)
|
||||
const ApiKeyContext = createContext<ApiKeyContextValue | undefined>(undefined);
|
||||
|
||||
/**
|
||||
* API Key Provider Component
|
||||
*
|
||||
* Wraps the application to provide global API key state and actions
|
||||
*/
|
||||
export function ApiKeyProvider({ children, onValidationSuccess }: ApiKeyProviderProps) {
|
||||
// Data State
|
||||
const [apiKey, setApiKeyState] = useState('');
|
||||
const [apiKeyValidated, setApiKeyValidated] = useState(false);
|
||||
const [apiKeyInfo, setApiKeyInfo] = useState<ApiKeyInfo | null>(null);
|
||||
const [apiKeyError, setApiKeyError] = useState('');
|
||||
const [validatingKey, setValidatingKey] = useState(false);
|
||||
const [isReady, setIsReady] = useState(false);
|
||||
|
||||
// UI State (grouped)
|
||||
const [expanded, setExpandedState] = useState(false);
|
||||
const [keyVisible, setKeyVisible] = useState(false);
|
||||
|
||||
// Refs
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
/**
|
||||
* Validate stored API key on mount
|
||||
*/
|
||||
const validateStoredApiKey = useCallback(
|
||||
async (keyToValidate: string) => {
|
||||
setValidatingKey(true);
|
||||
setApiKeyError('');
|
||||
|
||||
const result = await validateApiKeyRequest(keyToValidate);
|
||||
|
||||
if (result.success && result.keyInfo) {
|
||||
setApiKeyValidated(true);
|
||||
setApiKeyInfo(result.keyInfo);
|
||||
setApiKeyState(keyToValidate);
|
||||
|
||||
// Call optional success callback
|
||||
onValidationSuccess?.(result.keyInfo);
|
||||
} else {
|
||||
// Stored key is invalid, clear it
|
||||
clearStoredKey();
|
||||
setApiKeyError(result.error || 'Stored API key is invalid or expired');
|
||||
setApiKeyValidated(false);
|
||||
}
|
||||
|
||||
setValidatingKey(false);
|
||||
setIsReady(true);
|
||||
},
|
||||
[onValidationSuccess]
|
||||
);
|
||||
|
||||
/**
|
||||
* Initialize: check for stored API key
|
||||
*/
|
||||
useEffect(() => {
|
||||
const storedKey = getStoredKey();
|
||||
if (storedKey) {
|
||||
validateStoredApiKey(storedKey);
|
||||
} else {
|
||||
setIsReady(true);
|
||||
}
|
||||
}, [validateStoredApiKey]);
|
||||
|
||||
/**
|
||||
* Validate API key (user-triggered)
|
||||
*/
|
||||
const validateApiKey = useCallback(async () => {
|
||||
setValidatingKey(true);
|
||||
setApiKeyError('');
|
||||
|
||||
const result = await validateApiKeyRequest(apiKey);
|
||||
|
||||
if (result.success && result.keyInfo) {
|
||||
setApiKeyValidated(true);
|
||||
setApiKeyInfo(result.keyInfo);
|
||||
setStoredKey(apiKey);
|
||||
|
||||
// Collapse widget after successful validation
|
||||
setExpandedState(false);
|
||||
|
||||
// Call optional success callback
|
||||
onValidationSuccess?.(result.keyInfo);
|
||||
} else {
|
||||
setApiKeyError(result.error || 'Validation failed');
|
||||
setApiKeyValidated(false);
|
||||
}
|
||||
|
||||
setValidatingKey(false);
|
||||
}, [apiKey, onValidationSuccess]);
|
||||
|
||||
/**
|
||||
* Revoke API key
|
||||
* Optionally accepts a cleanup function for page-specific state
|
||||
*/
|
||||
const revokeApiKey = useCallback((clearPageState?: () => void) => {
|
||||
clearStoredKey();
|
||||
setApiKeyState('');
|
||||
setApiKeyValidated(false);
|
||||
setApiKeyInfo(null);
|
||||
setApiKeyError('');
|
||||
setExpandedState(true); // Expand to show input after revoke
|
||||
|
||||
// Call optional page-specific cleanup
|
||||
clearPageState?.();
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Toggle API key visibility
|
||||
*/
|
||||
const toggleKeyVisibility = useCallback(() => {
|
||||
setKeyVisible((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Set expanded state
|
||||
*/
|
||||
const setExpanded = useCallback((value: boolean) => {
|
||||
setExpandedState(value);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Set API key value
|
||||
*/
|
||||
const setApiKey = useCallback((key: string) => {
|
||||
setApiKeyState(key);
|
||||
setApiKeyError(''); // Clear error when user types
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Focus method - for external components to trigger focus
|
||||
* Expands widget, focuses input, and scrolls into view
|
||||
*/
|
||||
const focus = useCallback(() => {
|
||||
setExpandedState(true);
|
||||
|
||||
// Wait for expansion animation, then focus
|
||||
setTimeout(() => {
|
||||
inputRef.current?.focus();
|
||||
// TODO: don't need because it's always visible
|
||||
// containerRef.current?.scrollIntoView({
|
||||
// behavior: 'smooth',
|
||||
// block: 'center',
|
||||
// });
|
||||
}, 100);
|
||||
}, []);
|
||||
|
||||
const value: ApiKeyContextValue = {
|
||||
// Data State
|
||||
apiKey,
|
||||
apiKeyValidated,
|
||||
apiKeyInfo,
|
||||
apiKeyError,
|
||||
validatingKey,
|
||||
isReady,
|
||||
|
||||
// UI State
|
||||
ui: {
|
||||
expanded,
|
||||
keyVisible,
|
||||
},
|
||||
|
||||
// Actions
|
||||
setApiKey,
|
||||
validateApiKey,
|
||||
revokeApiKey,
|
||||
toggleKeyVisibility,
|
||||
setExpanded,
|
||||
|
||||
// Focus method
|
||||
focus,
|
||||
inputRef,
|
||||
containerRef,
|
||||
};
|
||||
|
||||
return (
|
||||
<ApiKeyContext.Provider value={value}>
|
||||
<div ref={containerRef}>{children}</div>
|
||||
</ApiKeyContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* useApiKey Hook
|
||||
*
|
||||
* Access API key context values and actions
|
||||
* Must be used within ApiKeyProvider
|
||||
*
|
||||
* @example
|
||||
* const { apiKey, apiKeyValidated, validateApiKey, focus } = useApiKey();
|
||||
*/
|
||||
export function useApiKey(): ApiKeyContextValue {
|
||||
const context = useContext(ApiKeyContext);
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error('useApiKey must be used within an ApiKeyProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
// Export inputRef for ApiKeyWidget to use
|
||||
export { ApiKeyContext };
|
||||
|
|
@ -0,0 +1,305 @@
|
|||
'use client';
|
||||
|
||||
/**
|
||||
* API Key Widget Component
|
||||
*
|
||||
* Global API key management widget displayed in navigation bar.
|
||||
* Features:
|
||||
* - Inline collapsed state (fits in nav rightSlot)
|
||||
* - Popup expanded state (absolute positioned dropdown)
|
||||
* - API key validation and management
|
||||
* - Click outside and Escape key to close
|
||||
* - Focus method accessible via useApiKey hook
|
||||
*
|
||||
* Usage:
|
||||
* Must be used within ApiKeyProvider context
|
||||
*/
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useApiKey } from './apikey-context';
|
||||
|
||||
export function ApiKeyWidget() {
|
||||
const {
|
||||
apiKey,
|
||||
apiKeyValidated,
|
||||
apiKeyInfo,
|
||||
apiKeyError,
|
||||
validatingKey,
|
||||
ui,
|
||||
inputRef,
|
||||
containerRef,
|
||||
setApiKey,
|
||||
validateApiKey,
|
||||
revokeApiKey,
|
||||
toggleKeyVisibility,
|
||||
setExpanded,
|
||||
} = useApiKey();
|
||||
|
||||
// const containerRef = useRef<HTMLDivElement>(null);
|
||||
// const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [isMobileContext, setIsMobileContext] = useState(false);
|
||||
|
||||
// Detect mobile context (inside mobile dropdown menu)
|
||||
useEffect(() => {
|
||||
const checkContext = () => {
|
||||
if (containerRef.current) {
|
||||
// Check if ancestor has md:hidden class (mobile menu)
|
||||
const mobileMenu = containerRef.current.closest('.md\\:hidden');
|
||||
setIsMobileContext(mobileMenu !== null);
|
||||
}
|
||||
};
|
||||
|
||||
checkContext();
|
||||
window.addEventListener('resize', checkContext);
|
||||
return () => window.removeEventListener('resize', checkContext);
|
||||
}, []);
|
||||
|
||||
// Click outside to close
|
||||
useEffect(() => {
|
||||
if (!ui.expanded) return;
|
||||
|
||||
function handleClickOutside(event: MouseEvent) {
|
||||
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
|
||||
setExpanded(false);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, [ui.expanded, setExpanded]);
|
||||
|
||||
// Escape key to close
|
||||
useEffect(() => {
|
||||
if (!ui.expanded) return;
|
||||
|
||||
function handleEscape(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') {
|
||||
setExpanded(false);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', handleEscape);
|
||||
return () => document.removeEventListener('keydown', handleEscape);
|
||||
}, [ui.expanded, setExpanded]);
|
||||
|
||||
// Handle Enter key for validation
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter' && !validatingKey) {
|
||||
validateApiKey();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Backdrop for mobile expanded state */}
|
||||
{ui.expanded && isMobileContext && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 z-40"
|
||||
onClick={() => setExpanded(false)}
|
||||
aria-label="Close API key details"
|
||||
/>
|
||||
)}
|
||||
|
||||
<div ref={containerRef} className={isMobileContext ? "relative" : "relative h-full flex items-center"}>
|
||||
{/* COLLAPSED STATE - Always rendered to maintain layout space */}
|
||||
<button
|
||||
onClick={() => setExpanded(true)}
|
||||
className={`group px-3 bg-transparent backdrop-blur-sm border-none rounded-lg hover:border-purple-500/50 transition-all flex items-center ${
|
||||
isMobileContext
|
||||
? 'w-auto max-w-full py-2.5 h-11' // Mobile: auto-width, larger touch target
|
||||
: 'py-2 h-10' // Desktop: original size
|
||||
} ${
|
||||
ui.expanded && isMobileContext ? 'opacity-50 pointer-events-none' : '' // Fade when expanded on mobile
|
||||
}`}
|
||||
aria-label="Expand API key details"
|
||||
disabled={ui.expanded}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={`w-2 h-2 rounded-full ${apiKeyValidated ? 'bg-green-400' : 'bg-gray-500'}`}
|
||||
></div>
|
||||
<span className="text-sm text-gray-300 font-medium whitespace-nowrap">
|
||||
{apiKeyValidated && apiKeyInfo
|
||||
? `${apiKeyInfo.organizationSlug} / ${apiKeyInfo.projectSlug}`
|
||||
: 'API Key'}
|
||||
</span>
|
||||
<svg
|
||||
className="w-4 h-4 text-gray-400 group-hover:text-purple-400 transition-colors"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* EXPANDED STATE - Rendered as overlay when expanded */}
|
||||
{ui.expanded && (
|
||||
<div className={`bg-slate-900/95 backdrop-blur-sm border border-slate-700 rounded-xl shadow-2xl animate-in fade-in duration-200 ${
|
||||
isMobileContext
|
||||
? 'fixed inset-x-4 top-16 p-5 z-50 max-h-[calc(100vh-6rem)] overflow-y-auto' // Mobile: fixed positioning for full-width
|
||||
: 'absolute top-0 right-0 w-96 p-5 z-50' // Desktop: absolute positioned
|
||||
}`}>
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div>
|
||||
<h3 className={`font-semibold text-white mb-1 ${isMobileContext ? 'text-base' : 'text-sm'}`}>
|
||||
{apiKeyValidated ? 'API Key Active' : 'Enter API Key'}
|
||||
</h3>
|
||||
{apiKeyValidated && apiKeyInfo && (
|
||||
<p className="text-xs text-gray-400">
|
||||
{apiKeyInfo.organizationSlug} / {apiKeyInfo.projectSlug}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setExpanded(false)}
|
||||
className={`rounded-lg bg-slate-800 hover:bg-slate-700 text-gray-400 hover:text-white flex items-center justify-center transition-colors ${
|
||||
isMobileContext ? 'w-10 h-10' : 'w-8 h-8'
|
||||
}`}
|
||||
aria-label="Minimize API key details"
|
||||
>
|
||||
<svg className={isMobileContext ? 'w-5 h-5' : 'w-4 h-4'} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M5 15l7-7 7 7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* API Key Input/Display */}
|
||||
<div className="mb-4">
|
||||
<label className="text-xs text-gray-500 mb-2 block">API Key</label>
|
||||
<div className={`flex gap-2 ${isMobileContext ? 'flex-col' : 'flex-row'}`}>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type={ui.keyVisible ? 'text' : 'password'}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Enter your API key"
|
||||
disabled={apiKeyValidated}
|
||||
className={`flex-1 px-4 bg-slate-800 border border-slate-700 rounded-lg text-gray-300 font-mono placeholder:text-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all ${
|
||||
isMobileContext ? 'py-3 text-base' : 'py-2 text-sm'
|
||||
}`}
|
||||
/>
|
||||
<button
|
||||
onClick={toggleKeyVisibility}
|
||||
className={`bg-slate-800 hover:bg-slate-700 border border-slate-700 rounded-lg text-gray-400 hover:text-white transition-colors ${
|
||||
isMobileContext ? 'px-4 py-3 w-full justify-center flex items-center gap-2' : 'px-3 py-2'
|
||||
}`}
|
||||
aria-label={ui.keyVisible ? 'Hide API key' : 'Show API key'}
|
||||
>
|
||||
{ui.keyVisible ? (
|
||||
<>
|
||||
<svg className={isMobileContext ? 'w-5 h-5' : 'w-4 h-4'} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
|
||||
/>
|
||||
</svg>
|
||||
{isMobileContext && <span className="text-sm font-medium">Hide</span>}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg className={isMobileContext ? 'w-5 h-5' : 'w-4 h-4'} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
|
||||
/>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
|
||||
/>
|
||||
</svg>
|
||||
{isMobileContext && <span className="text-sm font-medium">Show</span>}
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{apiKeyError && (
|
||||
<div className={`mb-3 bg-red-900/20 border border-red-700/50 rounded-lg ${isMobileContext ? 'p-3' : 'p-2'}`}>
|
||||
<p className="text-xs text-red-400">{apiKeyError}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2">
|
||||
{!apiKeyValidated ? (
|
||||
<button
|
||||
onClick={validateApiKey}
|
||||
disabled={validatingKey || !apiKey.trim()}
|
||||
className={`flex-1 bg-purple-600 hover:bg-purple-700 disabled:bg-slate-700 disabled:text-gray-500 disabled:cursor-not-allowed border border-purple-500 disabled:border-slate-600 rounded-lg text-white font-medium transition-colors ${
|
||||
isMobileContext ? 'px-5 py-3.5 text-base' : 'px-4 py-2 text-sm'
|
||||
}`}
|
||||
>
|
||||
{validatingKey ? (
|
||||
<span className="flex items-center justify-center gap-2">
|
||||
<svg
|
||||
className={isMobileContext ? 'animate-spin h-5 w-5' : 'animate-spin h-4 w-4'}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
></circle>
|
||||
<path
|
||||
className="opacity-75"
|
||||
fill="currentColor"
|
||||
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||
></path>
|
||||
</svg>
|
||||
Validating...
|
||||
</span>
|
||||
) : (
|
||||
'Validate Key'
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => revokeApiKey()}
|
||||
className={`flex-1 bg-red-900/20 hover:bg-red-900/30 border border-red-700/50 hover:border-red-600 rounded-lg text-red-400 font-medium transition-colors ${
|
||||
isMobileContext ? 'px-5 py-3.5 text-base' : 'px-4 py-2 text-sm'
|
||||
}`}
|
||||
>
|
||||
Revoke & Use Different Key
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Helper Text */}
|
||||
{!apiKeyValidated && (
|
||||
<p className={`mt-3 text-gray-500 text-center ${isMobileContext ? 'text-sm' : 'text-xs'}`}>
|
||||
Press Enter or click Validate to verify your API key
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -7,7 +7,6 @@
|
|||
* Features:
|
||||
* - Dark nav bar with decorative wave line
|
||||
* - Active state indicator (purple color)
|
||||
* - Optional API Key input on the right
|
||||
* - Responsive (hamburger menu on mobile)
|
||||
* - Three-column layout matching docs structure
|
||||
* - Customizable left/right slots
|
||||
|
|
@ -19,13 +18,12 @@
|
|||
* <SubsectionNav
|
||||
* items={[...]}
|
||||
* currentPath="/docs/final"
|
||||
* showApiKeyInput={true}
|
||||
* leftSlot={<Logo />}
|
||||
* rightSlot={<UserMenu />}
|
||||
* />
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useRef, ReactNode } from 'react';
|
||||
import { useState, ReactNode } from 'react';
|
||||
import { ThreeColumnLayout } from '@/components/layout/ThreeColumnLayout';
|
||||
|
||||
interface NavItem {
|
||||
|
|
@ -39,212 +37,19 @@ interface SubsectionNavProps {
|
|||
ctaText?: string;
|
||||
ctaHref?: string;
|
||||
onCtaClick?: () => void;
|
||||
showApiKeyInput?: boolean;
|
||||
/** Optional content for left column (w-64, hidden until lg) */
|
||||
leftSlot?: ReactNode;
|
||||
/** Optional content for right column (w-56, hidden until xl). If not provided and showApiKeyInput is true, API key input is used. */
|
||||
/** Optional content for right column (w-56, hidden until xl) */
|
||||
rightSlot?: ReactNode;
|
||||
}
|
||||
|
||||
const API_KEY_STORAGE = 'banatie_docs_api_key';
|
||||
|
||||
export const SubsectionNav = ({
|
||||
items,
|
||||
currentPath,
|
||||
showApiKeyInput = false,
|
||||
leftSlot,
|
||||
rightSlot,
|
||||
}: SubsectionNavProps) => {
|
||||
export const SubsectionNav = ({ items, currentPath, leftSlot, rightSlot }: SubsectionNavProps) => {
|
||||
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [isApiKeyExpanded, setIsApiKeyExpanded] = useState(false);
|
||||
const [keyVisible, setKeyVisible] = useState(false);
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const isActive = (href: string) => currentPath.startsWith(href);
|
||||
|
||||
// Load API key from localStorage
|
||||
useEffect(() => {
|
||||
if (showApiKeyInput) {
|
||||
const stored = localStorage.getItem(API_KEY_STORAGE);
|
||||
if (stored) setApiKey(stored);
|
||||
}
|
||||
}, [showApiKeyInput]);
|
||||
|
||||
// Handle API key changes
|
||||
const handleApiKeyChange = (value: string) => {
|
||||
setApiKey(value);
|
||||
if (value) {
|
||||
localStorage.setItem(API_KEY_STORAGE, value);
|
||||
} else {
|
||||
localStorage.removeItem(API_KEY_STORAGE);
|
||||
}
|
||||
|
||||
// Dispatch event to notify widgets
|
||||
window.dispatchEvent(new CustomEvent('apiKeyChanged', { detail: value }));
|
||||
};
|
||||
|
||||
// Handle clear API key
|
||||
const handleClear = () => {
|
||||
setApiKey('');
|
||||
localStorage.removeItem(API_KEY_STORAGE);
|
||||
window.dispatchEvent(new CustomEvent('apiKeyChanged', { detail: '' }));
|
||||
};
|
||||
|
||||
// Close dropdown when clicking outside
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||
setIsApiKeyExpanded(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isApiKeyExpanded) {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
};
|
||||
}, [isApiKeyExpanded]);
|
||||
|
||||
// Listen for custom event to expand API key from widgets
|
||||
useEffect(() => {
|
||||
const handleExpandApiKey = () => {
|
||||
setIsApiKeyExpanded(true);
|
||||
// Scroll to top to show nav
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
};
|
||||
|
||||
window.addEventListener('expandApiKeyInput', handleExpandApiKey);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('expandApiKeyInput', handleExpandApiKey);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Desktop API Key Input Component
|
||||
const apiKeyComponent = showApiKeyInput && (
|
||||
<div className="hidden md:block relative" ref={dropdownRef}>
|
||||
<button
|
||||
onClick={() => setIsApiKeyExpanded(!isApiKeyExpanded)}
|
||||
className="flex items-center gap-2 px-3 py-1.5 bg-slate-800/50 hover:bg-slate-800 border border-purple-500/30 hover:border-purple-500/50 rounded-lg transition-all"
|
||||
aria-label="Toggle API key input"
|
||||
>
|
||||
<div
|
||||
className={`w-2 h-2 rounded-full transition-colors ${
|
||||
apiKey ? 'bg-green-400' : 'bg-amber-400'
|
||||
}`}
|
||||
></div>
|
||||
<span className="text-xs text-gray-300 font-medium">
|
||||
🔑 {apiKey ? 'API Key Set' : 'API Key'}
|
||||
</span>
|
||||
<svg
|
||||
className={`w-3 h-3 text-gray-400 transition-transform ${
|
||||
isApiKeyExpanded ? 'rotate-180' : ''
|
||||
}`}
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 9l-7 7-7-7"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{/* Dropdown Card */}
|
||||
{isApiKeyExpanded && (
|
||||
<div className="absolute top-full right-0 mt-2 w-80 p-4 bg-slate-900/95 backdrop-blur-sm border border-purple-500/30 rounded-xl shadow-2xl z-50 animate-fade-in">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-white mb-1">API Key</h3>
|
||||
<p className="text-xs text-gray-400">
|
||||
Enter once, use across all examples
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setIsApiKeyExpanded(false)}
|
||||
className="w-8 h-8 rounded-lg bg-slate-800 hover:bg-slate-700 text-gray-400 hover:text-white flex items-center justify-center transition-colors"
|
||||
aria-label="Close API key input"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
<label className="text-xs text-gray-500 mb-1 block">Your API Key</label>
|
||||
<div className="flex gap-2 mb-2">
|
||||
<input
|
||||
type={keyVisible ? 'text' : 'password'}
|
||||
value={apiKey}
|
||||
onChange={(e) => handleApiKeyChange(e.target.value)}
|
||||
placeholder="Enter your API key"
|
||||
className="flex-1 px-3 py-2 bg-slate-800 border border-slate-700 focus:border-purple-500 focus:ring-1 focus:ring-purple-500 rounded-lg text-sm text-gray-300 font-mono placeholder-gray-500 focus:outline-none transition-colors"
|
||||
/>
|
||||
<button
|
||||
onClick={() => setKeyVisible(!keyVisible)}
|
||||
className="px-3 py-2 bg-slate-800 hover:bg-slate-700 border border-slate-700 rounded-lg text-gray-400 hover:text-white transition-colors"
|
||||
aria-label={keyVisible ? 'Hide API key' : 'Show API key'}
|
||||
>
|
||||
{keyVisible ? (
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
|
||||
/>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{apiKey && (
|
||||
<button
|
||||
onClick={handleClear}
|
||||
className="w-full px-3 py-2 bg-red-900/20 hover:bg-red-900/30 border border-red-700/50 hover:border-red-600 rounded-lg text-red-400 text-xs font-medium transition-colors"
|
||||
>
|
||||
Clear API Key
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-gray-500">
|
||||
<p>Stored locally in your browser</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<nav className="sticky top-0 z-40 bg-slate-950/80 backdrop-blur-sm border-b border-white/10">
|
||||
<nav className="sticky top-0 z-40 bg-slate-950/80 backdrop-blur-sm border-b border-white/10 relative">
|
||||
{/* Three-Column Layout */}
|
||||
<ThreeColumnLayout
|
||||
left={leftSlot}
|
||||
|
|
@ -277,12 +82,7 @@ export const SubsectionNav = ({
|
|||
className="p-2 text-gray-400 hover:text-white transition-colors"
|
||||
aria-label="Toggle menu"
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
{mobileMenuOpen ? (
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
|
|
@ -304,9 +104,15 @@ export const SubsectionNav = ({
|
|||
</div>
|
||||
</div>
|
||||
}
|
||||
right={rightSlot || apiKeyComponent}
|
||||
/>
|
||||
|
||||
{/* Right Slot - Absolutely Positioned */}
|
||||
{rightSlot && (
|
||||
<div className="absolute top-0 right-0 h-12 flex items-center pr-0 hidden xl:flex">
|
||||
{rightSlot}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Decorative Wave Line */}
|
||||
<div className="absolute bottom-0 left-0 right-0 h-px overflow-hidden">
|
||||
<svg
|
||||
|
|
@ -335,7 +141,20 @@ export const SubsectionNav = ({
|
|||
{/* Mobile Menu Overlay */}
|
||||
{mobileMenuOpen && (
|
||||
<div className="md:hidden border-t border-white/10 bg-slate-900/95 backdrop-blur-sm">
|
||||
<div className="px-6 py-4 space-y-2">
|
||||
<div className="px-6 py-4">
|
||||
{/* ApiKeyWidget - Mobile */}
|
||||
{rightSlot && (
|
||||
<>
|
||||
<div className="flex justify-end mb-3">
|
||||
{rightSlot}
|
||||
</div>
|
||||
{/* Visual separator */}
|
||||
<div className="border-t border-white/10 mb-3" />
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Navigation items */}
|
||||
<div className="space-y-2">
|
||||
{items.map((item) => {
|
||||
const active = isActive(item.href);
|
||||
return (
|
||||
|
|
@ -352,65 +171,7 @@ export const SubsectionNav = ({
|
|||
</a>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* API Key Input in Mobile Menu */}
|
||||
{showApiKeyInput && (
|
||||
<div className="pt-4 mt-4 border-t border-white/10">
|
||||
<h4 className="text-xs font-semibold text-white mb-2">API Key</h4>
|
||||
<p className="text-xs text-gray-400 mb-3">
|
||||
Enter once, use across all examples
|
||||
</p>
|
||||
<div className="flex gap-2 mb-2">
|
||||
<input
|
||||
type={keyVisible ? 'text' : 'password'}
|
||||
value={apiKey}
|
||||
onChange={(e) => handleApiKeyChange(e.target.value)}
|
||||
placeholder="Enter your API key"
|
||||
className="flex-1 px-3 py-2 bg-slate-800 border border-slate-700 focus:border-purple-500 focus:ring-1 focus:ring-purple-500 rounded-lg text-sm text-gray-300 font-mono placeholder-gray-500 focus:outline-none transition-colors"
|
||||
/>
|
||||
<button
|
||||
onClick={() => setKeyVisible(!keyVisible)}
|
||||
className="px-3 py-2 bg-slate-800 hover:bg-slate-700 border border-slate-700 rounded-lg text-gray-400 hover:text-white transition-colors"
|
||||
aria-label={keyVisible ? 'Hide API key' : 'Show API key'}
|
||||
>
|
||||
{keyVisible ? (
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
|
||||
/>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
{apiKey && (
|
||||
<button
|
||||
onClick={handleClear}
|
||||
className="w-full px-3 py-2 bg-red-900/20 hover:bg-red-900/30 border border-red-700/50 hover:border-red-600 rounded-lg text-red-400 text-xs font-medium transition-colors"
|
||||
>
|
||||
Clear API Key
|
||||
</button>
|
||||
)}
|
||||
<p className="text-xs text-gray-500 mt-2">Stored locally in your browser</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,26 @@
|
|||
/**
|
||||
* API Key Management Constants
|
||||
*
|
||||
* Centralized constants for API key functionality across demo pages
|
||||
*/
|
||||
|
||||
/**
|
||||
* LocalStorage key for persisting API keys
|
||||
*/
|
||||
export const API_KEY_STORAGE_KEY = 'banatie_demo_api_key';
|
||||
|
||||
/**
|
||||
* Base URL for API requests
|
||||
* Uses environment variable or falls back to localhost
|
||||
*/
|
||||
export const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
|
||||
|
||||
/**
|
||||
* API endpoints
|
||||
*/
|
||||
export const API_ENDPOINTS = {
|
||||
INFO: '/api/info',
|
||||
TEXT_TO_IMAGE: '/api/text-to-image',
|
||||
UPLOAD: '/api/upload',
|
||||
IMAGES_GENERATED: '/api/images/generated',
|
||||
} as const;
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
/**
|
||||
* API Key Management Library
|
||||
*
|
||||
* Centralized utilities for API key validation, storage, and management
|
||||
* Used across demo pages and components
|
||||
*/
|
||||
|
||||
// Constants
|
||||
export { API_KEY_STORAGE_KEY, API_BASE_URL, API_ENDPOINTS } from './constants';
|
||||
|
||||
// Types
|
||||
export type {
|
||||
ApiKeyInfo,
|
||||
ApiInfoResponse,
|
||||
ValidationResult,
|
||||
ApiKeyContextValue,
|
||||
ApiKeyProviderProps,
|
||||
} from './types';
|
||||
|
||||
// Validation utilities
|
||||
export { validateApiKeyRequest, parseKeyInfo } from './validation';
|
||||
|
||||
// Storage utilities
|
||||
export { getStoredKey, setStoredKey, clearStoredKey } from './storage';
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
/**
|
||||
* API Key Storage Utilities
|
||||
*
|
||||
* localStorage utilities for persisting API keys
|
||||
*/
|
||||
|
||||
import { API_KEY_STORAGE_KEY } from './constants';
|
||||
|
||||
/**
|
||||
* Check if localStorage is available (browser environment)
|
||||
*/
|
||||
function isLocalStorageAvailable(): boolean {
|
||||
try {
|
||||
return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get stored API key from localStorage
|
||||
*
|
||||
* @returns The stored API key or null if not found
|
||||
*/
|
||||
export function getStoredKey(): string | null {
|
||||
if (!isLocalStorageAvailable()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return localStorage.getItem(API_KEY_STORAGE_KEY);
|
||||
} catch (error) {
|
||||
console.error('Error reading API key from localStorage:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save API key to localStorage
|
||||
*
|
||||
* @param apiKey - The API key to store
|
||||
*/
|
||||
export function setStoredKey(apiKey: string): void {
|
||||
if (!isLocalStorageAvailable()) {
|
||||
console.warn('localStorage is not available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
localStorage.setItem(API_KEY_STORAGE_KEY, apiKey);
|
||||
} catch (error) {
|
||||
console.error('Error saving API key to localStorage:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove API key from localStorage
|
||||
*/
|
||||
export function clearStoredKey(): void {
|
||||
if (!isLocalStorageAvailable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
localStorage.removeItem(API_KEY_STORAGE_KEY);
|
||||
} catch (error) {
|
||||
console.error('Error removing API key from localStorage:', error);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
/**
|
||||
* API Key Management Types
|
||||
*
|
||||
* TypeScript interfaces and types for API key functionality
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
|
||||
/**
|
||||
* Information about an API key extracted from validation response
|
||||
*/
|
||||
export interface ApiKeyInfo {
|
||||
organizationSlug?: string;
|
||||
projectSlug?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from API info endpoint
|
||||
*/
|
||||
export interface ApiInfoResponse {
|
||||
message?: string;
|
||||
keyInfo?: {
|
||||
organizationSlug?: string;
|
||||
organizationId?: string;
|
||||
projectSlug?: string;
|
||||
projectId?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of API key validation
|
||||
*/
|
||||
export interface ValidationResult {
|
||||
success: boolean;
|
||||
keyInfo?: ApiKeyInfo;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Context value for API Key Provider
|
||||
*/
|
||||
export interface ApiKeyContextValue {
|
||||
// Data State
|
||||
apiKey: string;
|
||||
apiKeyValidated: boolean;
|
||||
apiKeyInfo: ApiKeyInfo | null;
|
||||
apiKeyError: string;
|
||||
validatingKey: boolean;
|
||||
isReady: boolean; // true when initial validation complete
|
||||
|
||||
// UI State (grouped)
|
||||
ui: {
|
||||
expanded: boolean;
|
||||
keyVisible: boolean;
|
||||
};
|
||||
|
||||
// Actions
|
||||
setApiKey: (key: string) => void;
|
||||
validateApiKey: () => Promise<void>;
|
||||
revokeApiKey: (clearPageState?: () => void) => void;
|
||||
toggleKeyVisibility: () => void;
|
||||
setExpanded: (expanded: boolean) => void;
|
||||
|
||||
// Focus method for external components
|
||||
focus: () => void;
|
||||
inputRef: React.Ref<HTMLInputElement>;
|
||||
containerRef: React.Ref<HTMLInputElement>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Props for ApiKeyProvider component
|
||||
*/
|
||||
export interface ApiKeyProviderProps {
|
||||
children: React.ReactNode;
|
||||
onValidationSuccess?: (keyInfo: ApiKeyInfo) => void;
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
/**
|
||||
* API Key Validation Logic
|
||||
*
|
||||
* Core validation functions for API key management
|
||||
*/
|
||||
|
||||
import { API_BASE_URL, API_ENDPOINTS } from './constants';
|
||||
import type { ApiKeyInfo, ApiInfoResponse, ValidationResult } from './types';
|
||||
|
||||
/**
|
||||
* Parse API key info from API response
|
||||
* Handles various response formats (organizationSlug vs organizationId)
|
||||
*/
|
||||
export function parseKeyInfo(data: ApiInfoResponse): ApiKeyInfo {
|
||||
if (data.keyInfo) {
|
||||
return {
|
||||
organizationSlug: data.keyInfo.organizationSlug || data.keyInfo.organizationId || 'Unknown',
|
||||
projectSlug: data.keyInfo.projectSlug || data.keyInfo.projectId || 'Unknown',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
organizationSlug: 'Unknown',
|
||||
projectSlug: 'Unknown',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate API key by making request to /api/info endpoint
|
||||
*
|
||||
* @param apiKey - The API key to validate
|
||||
* @returns ValidationResult with success status, keyInfo, or error
|
||||
*/
|
||||
export async function validateApiKeyRequest(apiKey: string): Promise<ValidationResult> {
|
||||
if (!apiKey.trim()) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Please enter an API key',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}${API_ENDPOINTS.INFO}`, {
|
||||
headers: {
|
||||
'X-API-Key': apiKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data: ApiInfoResponse = await response.json();
|
||||
const keyInfo = parseKeyInfo(data);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
keyInfo,
|
||||
};
|
||||
} else {
|
||||
// Try to parse error message from response
|
||||
try {
|
||||
const error = await response.json();
|
||||
return {
|
||||
success: false,
|
||||
error: error.message || 'Invalid API key',
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
success: false,
|
||||
error: response.status === 401 ? 'Invalid API key' : `Request failed with status ${response.status}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('API key validation error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: 'Failed to validate API key. Please check your connection.',
|
||||
};
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue