'use client'; import { ApiClientModalProvider, useApiClientModal } from '@scalar/api-client-react'; import { useEffect, useImperativeHandle, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import { useOpenAPIOperationContext } from './OpenAPIOperationContext'; import { useEventCallback } from 'usehooks-ts'; /** * Button which launches the Scalar API Client */ export function ScalarApiButton({ method, path, specUrl, }: { method: string; path: string; specUrl: string; }) { const [isOpen, setIsOpen] = useState(false); const controllerRef = useRef(null); return (
{isOpen && createPortal( , document.body, )}
); } function ScalarModal(props: { method: string; path: string; specUrl: string; controllerRef: React.Ref; }) { return ( ); } type ScalarModalControllerRef = { openClient: (() => void) | undefined; }; function ScalarModalController(props: { method: string; path: string; controllerRef: React.Ref; }) { const client = useApiClientModal(); const openClient = client?.open; useImperativeHandle( props.controllerRef, () => ({ openClient: openClient ? () => openClient() : undefined }), [openClient], ); // Open the client when the component is mounted. const { onOpenClient } = useOpenAPIOperationContext(); const trackOpening = useEventCallback(() => { onOpenClient({ method: props.method, path: props.path }); }); useEffect(() => { if (openClient) { openClient(); trackOpening(); } }, [openClient]); return null; }