refactor: add CodeExample component

This commit is contained in:
moonrailgun 2024-10-09 23:55:01 +08:00
parent 6474cefd89
commit 29f184c15d
2 changed files with 51 additions and 15 deletions

View File

@ -0,0 +1,37 @@
import React from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';
import { CodeBlock } from './CodeBlock';
interface CodeExampleItem {
label: string;
code?: string;
element?: React.ReactNode;
}
interface CodeExampleProps {
className?: string;
example: Record<string, CodeExampleItem>;
}
export const CodeExample: React.FC<CodeExampleProps> = React.memo((props) => {
const keys = Object.keys(props.example);
return (
<Tabs className={props.className} defaultValue={keys[0]}>
<TabsList>
{keys.map((key) => (
<TabsTrigger key={key} value={key}>
{props.example[key].label}
</TabsTrigger>
))}
</TabsList>
{keys.map((key) => (
<TabsContent key={key} value={key}>
{props.example[key].element ?? (
<CodeBlock code={props.example[key].code ?? ''} />
)}
</TabsContent>
))}
</Tabs>
);
});
CodeExample.displayName = 'CodeExample';

View File

@ -1,8 +1,7 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card'; import { Card, CardContent, CardHeader } from '@/components/ui/card';
import React from 'react'; import React from 'react';
import { CodeBlock } from '../CodeBlock';
import { useTranslation } from '@i18next-toolkit/react'; import { useTranslation } from '@i18next-toolkit/react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs'; import { CodeExample } from '../CodeExample';
export const FeedApiGuide: React.FC<{ channelId: string }> = React.memo( export const FeedApiGuide: React.FC<{ channelId: string }> = React.memo(
(props) => { (props) => {
@ -11,21 +10,21 @@ export const FeedApiGuide: React.FC<{ channelId: string }> = React.memo(
return ( return (
<Card className="w-full overflow-hidden"> <Card className="w-full overflow-hidden">
<CardHeader> <CardHeader>
<div>{t('You can send any message into this channel with:')}</div> <div>{t('You can send a message to this channel with:')}</div>
</CardHeader> </CardHeader>
<CardContent className="flex w-full flex-col gap-5 overflow-hidden"> <CardContent className="flex w-full flex-col gap-5 overflow-hidden">
<Tabs defaultValue="curl"> <CodeExample
<TabsList> example={{
<TabsTrigger value="curl">curl</TabsTrigger> curl: {
<TabsTrigger value="fetch">fetch</TabsTrigger> label: 'curl',
</TabsList> code: generateCurlCode(props.channelId),
<TabsContent value="curl"> },
<CodeBlock code={generateCurlCode(props.channelId)} /> fetch: {
</TabsContent> label: 'fetch',
<TabsContent value="fetch"> code: generateFetchCode(props.channelId),
<CodeBlock code={generateFetchCode(props.channelId)} /> },
</TabsContent> }}
</Tabs> />
<div className="pl-2 font-bold">{t('OR')}</div> <div className="pl-2 font-bold">{t('OR')}</div>