forked from solidjs/solid-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtab-code-blocks.tsx
More file actions
90 lines (78 loc) · 2.06 KB
/
tab-code-blocks.tsx
File metadata and controls
90 lines (78 loc) · 2.06 KB
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
import { Index, JSX, createSignal, onMount } from "solid-js";
// Check if children are elements
const isArrayOfElements = (arr: any[]): arr is Element[] => {
return arr.every((item) => item instanceof Element);
};
/**
* This is a code blocks component that can be used to divide code blocks into seperate tabs. Here's an example of how to use it in JSX and mdx:
* @example
* //jsx
* <TabsCodeBlocks>
* <div id="npm">
* <pre>
* <code>npm install</code>
* </pre>
* </div>
* ...
* </TabsCodeBlocks>
*
* @example
* //jsx
* <TabsCodeBlocks>
* <div id="npm">
* \```bash frame="none"
* npm install
* \```
* </div>
* <div id="yarn">
* \```bash frame="none"
* yarn install
* \```
* </div>
* ...
* </TabsCodeBlocks>
*/
type Props = { children: JSX.Element };
export const TabsCodeBlocks = (props: Props) => {
const [tabs, setTabs] = createSignal<Element[]>();
const [activeTab, setActiveTab] = createSignal(0);
onMount(() => {
let children = props.children;
// Check if children are an array
if (!Array.isArray(children))
throw new Error("TabsCodeBlocks children must be an array");
if (!isArrayOfElements(children))
throw new Error("TabsCodeBlocks children must be an array of elements");
// Check if all elements have ids
const allElementsHaveIds = children.every((child) => "id" in child);
if (!allElementsHaveIds)
throw new Error("All TabsCodeBlocks children must have an id");
setTabs(children);
});
return (
<div>
<nav class="mb-2 border-b-2 border-slate-800">
<Index each={tabs()}>
{(tab, idx) => (
<button
classList={{
"font-bold dark:text-slate-300 text-blue-500 border-b-2 border-blue-400":
activeTab() === idx,
"px-5 py-1 relative top-0.5 transition-colors duration-300":
true,
}}
onclick={() => setActiveTab(idx)}
>
{tab().id}
</button>
)}
</Index>
</nav>
<Index each={tabs()}>
{(tab, idx) => (
<div classList={{ hidden: activeTab() !== idx }}>{tab()}</div>
)}
</Index>
</div>
);
};