docs(tabs): add dynamic example

This commit is contained in:
Eric Liu 2020-11-30 11:31:48 -08:00
commit 45dfbb26cf
2 changed files with 61 additions and 12 deletions

View file

@ -1,5 +1,12 @@
<script>
import { Button, Tabs, Tab, TabContent } from "carbon-components-svelte";
import {
ButtonSet,
Button,
Tabs,
Tab,
TabContent,
} from "carbon-components-svelte";
import { afterUpdate } from "svelte";
let tabs = [
{ title: "blue", visible: true },
@ -7,17 +14,23 @@
{ title: "red", visible: true },
];
const toggleTab = (title) => {
for (const i in tabs) {
if (tabs[i].title === title) {
tabs[i].visible = !tabs[i].visible;
}
}
};
let selected = 0;
afterUpdate(() => {
// if the selected tab is not visible
// reset the index to the next visible tab
if (tabs[selected].visible === false) {
selected = tabs.filter((tab) => tab.visible).length - 1;
}
});
</script>
<style>
div {
margin: var(--cds-layout-02) 0;
}
</style>
{#key tabs}
<Tabs bind:selected>
{#each tabs as tab (tab.title)}
@ -37,6 +50,34 @@
<p>Selected index: {selected}</p>
{#each tabs as { title } (title)}
<Button on:click="{() => toggleTab(title)}">Toggle {title} tab</Button>
{/each}
<div>
<ButtonSet>
{#each tabs as { title } (title)}
<Button
kind="tertiary"
size="small"
on:click="{() => {
tabs = tabs.map((tab) => ({
...tab,
visible: tab.title === title ? !tab.visible : tab.visible,
}));
}}"
>
Toggle
{title}
tab
</Button>
{/each}
</ButtonSet>
</div>
<div>
<Button
size="small"
on:click="{() => {
selected = 1;
}}"
>
Set selected to 1
</Button>
</div>