Skip to content

Commit

Permalink
Add a SingleSelectAccordion component
Browse files Browse the repository at this point in the history
Plumb in a way for it to pass data back to a containing component when one of its items is clicked on.
  • Loading branch information
aaronbrethorst committed Nov 25, 2024
1 parent 6ed5fcd commit 456adc6
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/components/containers/Accordion.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
return {
isActive,
skipAnimation,
activate: () => {
activate: (_data) => {
activeItems.update((items) => {
const newItems = new Set(items);
if (newItems.has(id)) {
Expand Down
5 changes: 4 additions & 1 deletion src/components/containers/AccordionItem.svelte
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
<script>
import { getContext } from 'svelte';
import { slide } from 'svelte/transition';
export let data = null;
const id = crypto.randomUUID();
const { registerItem } = getContext('accordion');
const { isActive, skipAnimation, activate } = registerItem(id);
function toggle() {
activate();
activate(data);
}
</script>

Expand Down
41 changes: 41 additions & 0 deletions src/components/containers/SingleSelectAccordion.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<script>
import { setContext } from 'svelte';
import { writable, derived } from 'svelte/store';
// Create a store to track the active item and data.
const activeItem = writable(null);
const activeData = writable(null);
// Create dispatch for activeChanged event
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
// Watch for changes to activeItem and dispatch event
$: {
dispatch('activeChanged', {
activeItem: $activeItem,
activeData: $activeData
});
}
// Provide context for child AccordionItems
setContext('accordion', {
registerItem: (id) => {
const isActive = derived(activeItem, ($activeItem) => $activeItem === id);
return {
isActive,
activate: (data) => {
const newId = $activeItem === id ? null : id;
activeItem.set(newId);
activeData.set(newId ? data : null);
}
};
}
});
</script>

<div
class="divide-y divide-gray-200 border-y border-gray-200 dark:divide-gray-700 dark:border-gray-700"
>
<slot />
</div>

0 comments on commit 456adc6

Please sign in to comment.