carbon-design-system / carbon-components-svelte

Svelte implementation of the Carbon Design System
https://svelte.carbondesignsystem.com
Apache License 2.0
2.7k stars 261 forks source link

SideNavLinks recipe? #963

Open ricardo-valero opened 2 years ago

ricardo-valero commented 2 years ago

This is definitely not perfect, but it's what I've been using in my svelte kit project, I thought it'd be nice to add something like it to the recipes.

// SideNavLinks.svelte
<script context="module" lang="ts">
    export type SideNavLinkType = {
        icon?: any
        href?: string
        text?: string
        links?: SideNavLinkType[]
        isDivider?: boolean
    }
</script>

<script lang="ts">
    import { SideNavDivider, SideNavLink, SideNavMenu } from 'carbon-components-svelte'
    export let links: SideNavLinkType[]
    export let currentPage: string
</script>

{#each links as link}
    {#if link.isDivider}
        <SideNavDivider />
    {:else if link.links}
        <SideNavMenu text={link.text}>
            <svelte:self {...link} {currentPage} />
        </SideNavMenu>
    {:else}
        <SideNavLink {...link} isSelected={currentPage === link.href} />
    {/if}
{/each}

Example with Svelte Kit

<script>
    import { page } from '$app/stores'
    import { SideNav, SideNavItems } from 'carbon-components-svelte'
    import { Box20, Laptop20, Product20, Tools20, User20 } from 'carbon-icons-svelte'
    import SideNavLinks from './SideNavLinks.svelte'
    let isSideNavOpen
    const sideNavLinks = [
        { text: 'Repack', href: '/repack' },
        { isDivider: true },
        {
            text: 'Catalog',
            links: [
                { text: 'Product', href: '/catalog/product', icon: Product20 },
                { text: 'Box', href: '/catalog/box', icon: Box20 },
                { text: 'User', href: '/catalog/user', icon: User20 },
                {
                    text: 'More',
                    links: [
                        { text: 'Station', href: '/catalog/station', icon: Laptop20 },
                        { text: 'Tool', href: '/catalog/tool', icon: Tools20 }
                    ]
                }
            ]
        }
    ]
</script>

<SideNav bind:isOpen={isSideNavOpen}>
    <SideNavItems>
        <SideNavLinks links={sideNavLinks} currentPage={$page.url.pathname} />
    </SideNavItems>
</SideNav>
image
metonym commented 2 years ago

Interesting – I think a recursive side nav links example would be very useful. Feel free to submit a PR.