mirror of
https://github.com/carbon-design-system/carbon-components-svelte.git
synced 2025-09-14 18:01:06 +00:00
69 lines
1.5 KiB
Svelte
69 lines
1.5 KiB
Svelte
<script>
|
|
/**
|
|
* Set the selected index of the switch item
|
|
* @type {number} [selectedIndex=0]
|
|
*/
|
|
export let selectedIndex = 0;
|
|
|
|
/**
|
|
* Set to `true` to enable the light variant
|
|
* @type {boolean} [light=false]
|
|
*/
|
|
export let light = false;
|
|
|
|
import { afterUpdate, createEventDispatcher, setContext } from "svelte";
|
|
import { writable } from "svelte/store";
|
|
|
|
const dispatch = createEventDispatcher();
|
|
const currentId = writable(null);
|
|
|
|
$: currentIndex = -1;
|
|
$: switches = [];
|
|
$: if (switches[currentIndex]) {
|
|
dispatch("change", currentIndex);
|
|
currentId.set(switches[currentIndex].id);
|
|
}
|
|
|
|
setContext("ContentSwitcher", {
|
|
currentId,
|
|
add: ({ id, text, selected }) => {
|
|
if (selected) {
|
|
selectedIndex = switches.length;
|
|
}
|
|
|
|
switches = [...switches, { id, text, selected }];
|
|
},
|
|
update: (id) => {
|
|
selectedIndex = switches.map(({ id }) => id).indexOf(id);
|
|
},
|
|
change: (direction) => {
|
|
let index = currentIndex + direction;
|
|
|
|
if (index < 0) {
|
|
index = switches.length - 1;
|
|
} else if (index >= switches.length) {
|
|
index = 0;
|
|
}
|
|
|
|
selectedIndex = index;
|
|
},
|
|
});
|
|
|
|
afterUpdate(() => {
|
|
if (selectedIndex !== currentIndex) {
|
|
currentIndex = selectedIndex;
|
|
}
|
|
});
|
|
</script>
|
|
|
|
<div
|
|
role="tablist"
|
|
class:bx--content-switcher="{true}"
|
|
class:bx--content-switcher--light="{light}"
|
|
{...$$restProps}
|
|
on:click
|
|
on:mouseover
|
|
on:mouseenter
|
|
on:mouseleave>
|
|
<slot />
|
|
</div>
|