import * as fs from 'fs'; import * as path from 'path'; import { SyntheticEvent, useState } from 'react'; import { CodeBlock } from '../components/codeblock'; import { ThemeSelector } from '../components/theme-selector'; import LANG_CATS from '../data/categories.json'; import { MainLayout } from '../layouts/main'; const SNIPPETS_DIR = path.resolve(process.cwd(), 'data', 'snippets'); const SNIPPET_IGNORE = ['node-repl', 'sql_more']; // This object will automatically be populated from data in `LANG_CATS`. Do not // touch this object manually. const __LANG_LOOKUP: Record = {}; Object.keys(LANG_CATS).forEach((category) => { LANG_CATS[category].forEach((language) => { if (!(language in __LANG_LOOKUP)) { __LANG_LOOKUP[language] = []; } __LANG_LOOKUP[language].push(category.toLowerCase()); }); }); interface Props { snippets: Record; totalCount: number; } export async function getStaticProps() { const snippets = {}; const snippetFiles = fs.readdirSync(SNIPPETS_DIR); snippetFiles.forEach((filenames) => { const language = filenames.replace('.txt', ''); const filePath = path.resolve(SNIPPETS_DIR, filenames); if (SNIPPET_IGNORE.indexOf(language) >= 0) { return; } snippets[language] = fs.readFileSync(filePath, 'utf-8'); }); return { props: { snippets, totalCount: Object.keys(snippets).length, }, }; } const Examples = ({ snippets, totalCount }: Props) => { const [theme, setTheme] = useState('atom-one-dark'); const [filter, setFilter] = useState('all'); const handleRadio = (e: SyntheticEvent) => { setFilter(e.currentTarget.value); }; return (
{Object.keys(snippets).map((language) => { const showAll = filter === 'all'; const langInFilter = __LANG_LOOKUP[language]?.includes(filter); const display = showAll || langInFilter ? 'block' : 'none'; return (
); })}
); }; export default Examples;