Skip to content

Commit

Permalink
toc is active
Browse files Browse the repository at this point in the history
  • Loading branch information
TGlide committed Nov 8, 2023
1 parent a86565e commit c761856
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/tricky-coins-jog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@melt-ui/svelte': minor
---

TOC: isActive helper
11 changes: 11 additions & 0 deletions src/docs/data/builders/table-of-contents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ const builder: APISchema = {
description: 'A writable store that lists all the headings within the specified container.',
},
],
helpers: [
{
name: 'isActive',
type: '(headingId: string) => boolean',
description: 'Returns whether the heading with the given id is currently active.',
},
],
};

const item = elementSchema('item', {
Expand All @@ -94,6 +101,10 @@ const item = elementSchema('item', {
name: 'data-id',
value: 'The id of the heading element the item links to.',
},
{
name: 'data-active',
value: 'Whether the item is currently active.',
},
],
events: tableOfContentsEvents['item'],
});
Expand Down
13 changes: 12 additions & 1 deletion src/lib/builders/table-of-contents/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { Defaults } from '$lib/internal/types';

import { dequal } from 'dequal';
import { onMount } from 'svelte';
import { get, writable, type Writable } from 'svelte/store';
import { derived, get, writable, type Writable } from 'svelte/store';

import type {
CreateTableOfContentsArgs,
Expand Down Expand Up @@ -378,6 +378,14 @@ export function createTableOfContents(args: CreateTableOfContentsArgs) {
},
});

// Helpers
const isActive = derived(activeHeadingIdxs, ($activeHeadingIdxs) => {
return (headingId: string) => {
const idx = headingsList.findIndex((heading) => heading.id === headingId);
return $activeHeadingIdxs.includes(idx);
};
});

return {
elements: {
item,
Expand All @@ -386,5 +394,8 @@ export function createTableOfContents(args: CreateTableOfContentsArgs) {
activeHeadingIdxs,
headingsTree,
},
helpers: {
isActive,
},
};
}

0 comments on commit c761856

Please sign in to comment.