Getting Started
Components
Special Effects
Animations
Text Animations
Backgrounds
An interactive file tree component with expandable folders, selectable files, and smooth animations.
motion-sv
file-tree.svelte
<script lang="ts"> import { Tree, Folder, File, CollapseButton, type TreeViewElement, } from "$lib/components/magic/file-tree/index.js";
const ELEMENTS: TreeViewElement[] = [ { id: "1", name: "src", children: [ { id: "2", name: "lib", children: [ { id: "3", name: "index.ts" }, { id: "4", name: "utils.ts" }, ], }, { id: "5", name: "routes", children: [ { id: "6", name: "+page.svelte" }, { id: "7", name: "+layout.svelte" }, ], }, ], }, { id: "8", name: "package.json", }, { id: "9", name: "README.md", }, ];</script>
<div class="bg-background relative mx-auto flex h-80 w-70 flex-col items-center justify-center overflow-hidden rounded-lg border md:m-6 md:mx-auto"> <Tree class="bg-background mx-auto overflow-hidden rounded-md p-4" initialSelectedId="7" initialExpandedItems={["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]} elements={ELEMENTS} > <Folder element="src" value="1"> <Folder value="2" element="app"> <File value="3"> <p>layout.tsx</p> </File> <File value="4"> <p>page.tsx</p> </File> </Folder> <Folder value="5" element="components"> <Folder value="6" element="ui"> <File value="7"> <p>button.tsx</p> </File> </Folder> <File value="8"> <p>header.tsx</p> </File> <File value="9"> <p>footer.tsx</p> </File> </Folder> <Folder value="10" element="lib"> <File value="11"> <p>utils.ts</p> </File> </Folder> </Folder> </Tree></div>Installation
pnpm dlx shadcn-svelte@latest add https://sv-animations.vercel.app/r/file-tree.json
Install dependencies
Install the required packages for this component:
pnpm add motion-sv
Copy the Source Code
Copy and paste the following code into your project:
file-tree.svelte
<script lang="ts" module> export type TreeViewElement = { id: string; name: string; isSelectable?: boolean; children?: TreeViewElement[]; };</script>
<script lang="ts"> import { setContext, untrack } from "svelte"; import { cn } from "#lib/utils.js"; import type { Snippet } from "svelte"; import type { ClassValue, HTMLAttributes } from "svelte/elements";
interface TreeProps extends HTMLAttributes<HTMLDivElement> { /** * Initial selected item ID */ initialSelectedId?: string; /** * Initial expanded items */ initialExpandedItems?: string[]; /** * Tree elements data */ elements?: TreeViewElement[]; /** * Show indicator line */ indicator?: boolean; /** * Open folder icon */ openIcon?: Snippet; /** * Close folder icon */ closeIcon?: Snippet; /** * Text direction */ dir?: "rtl" | "ltr"; /** * Children content */ children: Snippet; /** * Additional CSS classes */ class?: ClassValue; }
let { initialSelectedId, initialExpandedItems = [], elements, indicator = true, openIcon, closeIcon, dir = "ltr", children, class: className, ...props }: TreeProps = $props();
let selectedId = $state(untrack(() => initialSelectedId)); let expandedItems = $state<string[]>(untrack(() => initialExpandedItems));
const selectItem = (id: string) => { selectedId = id; };
const handleExpand = (id: string) => { if (expandedItems.includes(id)) { expandedItems = expandedItems.filter((item) => item !== id); } else { expandedItems = [...expandedItems, id]; } };
const setExpandedItems = (items: string[]) => { expandedItems = items; };
let direction: "rtl" | "ltr" = $derived(dir === "rtl" ? "rtl" : "ltr");
setContext("tree", { selectedId: () => selectedId, expandedItems: () => expandedItems, handleExpand, selectItem, setExpandedItems, get indicator() { return indicator; }, get openIcon() { return openIcon; }, get closeIcon() { return closeIcon; }, get direction() { return direction; }, });</script>
<div class={cn("size-full", className)} {...props}> <div class="relative h-full overflow-auto px-2" dir={direction}> <div class="flex flex-col gap-1"> {@render children()} </div> </div></div> folder.svelte
<script lang="ts"> import { getContext } from "svelte"; import { cn } from "#lib/utils.js"; import { motion, AnimatePresence } from "motion-sv"; import type { Snippet } from "svelte"; import type { ClassValue, HTMLAttributes } from "svelte/elements";
interface FolderProps extends HTMLAttributes<HTMLDivElement> { /** * Folder name/label */ element: string; /** * Unique value for this folder */ value: string; /** * Whether the folder is selectable */ isSelectable?: boolean; /** * Whether the folder is selected */ isSelect?: boolean; /** * Children content */ children: Snippet; /** * Additional CSS classes */ class?: ClassValue; }
let { element, value, isSelectable = true, isSelect, children, class: className, ...props }: FolderProps = $props();
const context = getContext<{ selectedId: () => string | undefined; expandedItems: () => string[]; handleExpand: (id: string) => void; selectItem: (id: string) => void; setExpandedItems: (items: string[]) => void; indicator: boolean; openIcon?: Snippet; closeIcon?: Snippet; direction: "rtl" | "ltr"; }>("tree");
const isExpanded = $derived(context.expandedItems().includes(value)); const isSelected = $derived(isSelect ?? context.selectedId() === value);
// Default folder icons (SVG) const defaultOpenIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/><path d="M2 10h20"/></svg>`; const defaultCloseIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/></svg>`;</script>
<div class="relative h-full overflow-hidden" {...props}> <button type="button" class={cn("flex w-full items-center gap-1 rounded-md text-left text-sm", className, { "bg-muted rounded-md": isSelected && isSelectable, "cursor-pointer": isSelectable, "cursor-not-allowed opacity-50": !isSelectable, })} disabled={!isSelectable} onclick={() => context.handleExpand(value)} > <span class="size-4"> {#if context.openIcon && isExpanded} {@render context.openIcon()} {:else if context.closeIcon && !isExpanded} {@render context.closeIcon()} {:else} {@html isExpanded ? defaultOpenIcon : defaultCloseIcon} {/if} </span> <span>{element}</span> </button>
<AnimatePresence mode="popLayout"> {#if isExpanded} <motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: "auto", opacity: 1 }} exit={{ height: 0, opacity: 0 }} transition={{ duration: 0.2, ease: "easeInOut" }} class="relative overflow-hidden text-sm" > {#if element && context.indicator} <div dir={context.direction} class="bg-muted absolute left-1.5 h-full w-px rounded-md py-3 duration-300 ease-in-out hover:bg-slate-300 rtl:right-1.5" aria-hidden="true" ></div> {/if} <div class="ml-5 flex flex-col gap-1 py-1 rtl:mr-5" dir={context.direction}> {@render children()} </div> </motion.div> {/if} </AnimatePresence></div> file.svelte
<script lang="ts"> import { getContext } from "svelte"; import { cn } from "#lib/utils.js"; import type { Snippet } from "svelte"; import type { ClassValue, HTMLButtonAttributes } from "svelte/elements";
interface FileProps extends HTMLButtonAttributes { value: string; isSelectable?: boolean; isSelect?: boolean; fileIcon?: Snippet; children: Snippet; class?: ClassValue; }
let { value, isSelectable = true, isSelect, fileIcon, children, class: className, ...props }: FileProps = $props();
const context = getContext<{ selectedId: () => string | undefined; expandedItems: () => string[]; handleExpand: (id: string) => void; selectItem: (id: string) => void; setExpandedItems: (items: string[]) => void; indicator: boolean; openIcon?: Snippet; closeIcon?: Snippet; direction: "rtl" | "ltr"; }>("tree");
const isSelected = $derived(isSelect ?? context.selectedId() === value);
// Default file icon (SVG) const defaultFileIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/></svg>`;</script>
<button type="button" disabled={!isSelectable} class={cn( "flex w-fit items-center gap-1 rounded-md pr-1 text-sm duration-200 ease-in-out rtl:pr-0 rtl:pl-1", { "bg-muted": isSelected && isSelectable, }, isSelectable ? "cursor-pointer" : "cursor-not-allowed opacity-50", context.direction === "rtl" ? "rtl" : "ltr", className )} onclick={() => context.selectItem(value)} {...props}> <span class="size-4"> {#if fileIcon} {@render fileIcon()} {:else} {@html defaultFileIcon} {/if} </span> {@render children()}</button> collapse-button.svelte
<script lang="ts"> import { getContext, onMount } from "svelte"; import { cn } from "#lib/utils.js"; import type { Snippet } from "svelte"; import type { ClassValue, HTMLButtonAttributes } from "svelte/elements"; import type { TreeViewElement } from "./file-tree.svelte";
interface CollapseButtonProps extends HTMLButtonAttributes { /** * Tree elements to expand/collapse */ elements: TreeViewElement[]; /** * Whether to expand all on mount */ expandAll?: boolean; /** * Children content */ children: Snippet; /** * Additional CSS classes */ class?: ClassValue; }
let { elements, expandAll = false, children, class: className, ...props }: CollapseButtonProps = $props();
const context = getContext<{ selectedId: () => string | undefined; expandedItems: () => string[]; handleExpand: (id: string) => void; selectItem: (id: string) => void; setExpandedItems: (items: string[]) => void; indicator: boolean; openIcon?: Snippet; closeIcon?: Snippet; direction: "rtl" | "ltr"; }>("tree");
const expendAllTree = (elements: TreeViewElement[]) => { const expandTree = (element: TreeViewElement) => { const isSelectable = element.isSelectable ?? true; if (isSelectable && element.children && element.children.length > 0) { const currentExpanded = context.expandedItems(); if (!currentExpanded.includes(element.id)) { context.setExpandedItems([...currentExpanded, element.id]); } element.children.forEach(expandTree); } };
elements.forEach(expandTree); };
const closeAll = () => { context.setExpandedItems([]); };
onMount(() => { if (expandAll) { expendAllTree(elements); } });
const handleClick = () => { const currentExpanded = context.expandedItems(); if (currentExpanded && currentExpanded.length > 0) { closeAll(); } else { expendAllTree(elements); } };</script>
<button type="button" class={cn("hover:bg-muted absolute right-2 bottom-1 h-8 w-fit rounded-md p-1", className)} onclick={handleClick} {...props}> {@render children()} <span class="sr-only">Toggle</span></button> index.ts
import Tree from "./file-tree.svelte";import Folder from "./folder.svelte";import File from "./file.svelte";import CollapseButton from "./collapse-button.svelte";import type { TreeViewElement } from "./file-tree.svelte";
export { Tree, Folder, File, CollapseButton };export type { TreeViewElement };Folder Structure
Folder Structure
src/└── lib/ └── components/ └── magic/ └── file-tree/ ├── file-tree.svelte ├── folder.svelte ├── file.svelte ├── collapse-button.svelte └── index.tsInstall and integrate the Svelte component documented below.https://sv-animations.vercel.app/magic/docs/components/file-tree/llms.txt
Follow the guide's installation and usage instructions.Match the project's existing structure, imports, and styles.Keep changes scoped to the component and verify it works.Reply with a short bullet list of completed changes.Usage
<script lang="ts"> import { File, Folder, Tree, type TreeViewElement } from "#lib/components/magic/file-tree/index.js";
const elements: TreeViewElement[] = [ { id: "src", name: "src", children: [{ id: "page", name: "+page.svelte" }], }, ];</script>
<Tree {elements} initialExpandedItems={["src"]}> <Folder value="src" element="src"> <File value="page">+page.svelte</File> </Folder></Tree>Props
Tree
The root tree container component.
| Name | Type | Default | Description |
|---|---|---|---|
initialSelectedId | string | undefined | Initial selected item ID |
initialExpandedItems | string[] | [] | Initial expanded items |
elements | TreeViewElement[] | undefined | Tree elements data |
indicator | boolean | true | Show indicator line |
dir | 'rtl' | 'ltr' | 'ltr' | Text direction |
class | ClassValue | "" | Additional CSS classes |
Folder
A folder component that can contain files and other folders.
| Name | Type | Default | Description |
|---|---|---|---|
element | string | required | Folder name/label |
value | string | required | Unique value for this folder |
isSelectable | boolean | true | Whether the folder is selectable |
class | ClassValue | "" | Additional CSS classes |
File
A file component that can be selected.
| Name | Type | Default | Description |
|---|---|---|---|
value | string | required | Unique value for this file |
isSelectable | boolean | true | Whether the file is selectable |
class | ClassValue | "" | Additional CSS classes |
Collapse Button
A button to expand or collapse all folders.
| Name | Type | Default | Description |
|---|---|---|---|
elements | TreeViewElement[] | required | Tree elements to expand/collapse |
expandAll | boolean | false | Whether to expand all on mount |
class | ClassValue | "" | Additional CSS classes |