improved sticky folders

This commit is contained in:
vcoppe committed 2026-10-17 16:39:41 +02:00
1 parent 593b43e433
commit 970cf7d1e1
8 files changed
+180 -54

No files matched your search

@@ -1,18 +1,26 @@
<script lang="ts">
import { setContext, type Snippet } from 'svelte';
import { CollapsibleTreeState } from './utils.svelte';
import { getContext, setContext, type Snippet } from 'svelte';
import { CollapsibleTreeState, StuckRows } from './utils.svelte';
import { stickyKey, type StickyLevel } from './sticky';
const {
defaultState = 'open',
side = 'right',
nohover = false,
slotInsideTrigger = true,
sticky = false,
children,
}: {
defaultState?: 'open' | 'closed';
side?: 'left' | 'right';
nohover?: boolean;
slotInsideTrigger?: boolean;
/**
* The rows of the nodes stick to the top of the scrolled area while some of the content of
* their node is in view, each under the rows of the nodes it is in. A tree in a tree is
* like its node.
*/
sticky?: boolean;
children: Snippet;
} = $props();
@@ -23,6 +31,15 @@
setContext('collapsible-tree-nohover', nohover);
setContext('collapsible-tree-parent-id', 'root');
setContext('collapsible-tree-slot-inside-trigger', slotInsideTrigger);
setContext<StickyLevel>(
stickyKey,
getContext<StickyLevel | undefined>(stickyKey) ?? {
enabled: sticky,
top: 0,
depth: 0,
stuckRows: new StuckRows(),
}
);
</script>
{@render children()}
@@ -5,37 +5,58 @@
import { getContext, setContext, type Snippet } from 'svelte';
import type { ClassValue } from 'svelte/elements';
import type { CollapsibleTreeState } from './utils.svelte';
import { stickyKey, stickyZIndex, trackStuck, type StickyLevel } from './sticky';
const props: {
id: string | number;
class?: ClassValue;
trigger: Snippet;
/** Classes and style of the trigger row (when the trigger holds the content), to make it stick. */
triggerClass?: ClassValue;
triggerStyle?: string;
/** Gets whether the node is open, for contents that are only worth building then. */
content: Snippet<[boolean]>;
} = $props();
let state = getContext<CollapsibleTreeState>('collapsible-tree-state');
let treeState = getContext<CollapsibleTreeState>('collapsible-tree-state');
let side = getContext<'left' | 'right'>('collapsible-tree-side');
let nohover = getContext<boolean>('collapsible-tree-nohover');
let slotInsideTrigger = getContext<boolean>('collapsible-tree-slot-inside-trigger');
let parentId = getContext<string>('collapsible-tree-parent-id');
// where the row sticks, under the rows of the nodes this one is in
let level = getContext<StickyLevel>(stickyKey);
let fullId = `${parentId}.${props.id}`;
setContext('collapsible-tree-parent-id', fullId);
let open = state.get(fullId);
let open = treeState.get(fullId);
// the rows of the nodes in this one stick under this row, whatever its height
let rowHeight = $state(0);
setContext<StickyLevel>(stickyKey, {
get enabled() {
return level.enabled;
},
get top() {
return level.top + rowHeight;
},
get depth() {
return level.depth + 1;
},
get stuckRows() {
return level.stuckRows;
},
});
// the row is on top of the content that goes under it
let stuck = $state(false);
// only the deepest row that is stuck has a border: the rows above it run into it
let bordered = $derived(stuck && level.stuckRows.deepest === level.depth);
export function openNode() {
open.current = true;
}
</script>
<Collapsible.Root bind:open={open.current} class={props.class}>
{#snippet row()}
{#if slotInsideTrigger}
<Collapsible.Trigger class={['w-full', props.triggerClass]} style={props.triggerStyle}>
<Collapsible.Trigger class="w-full">
<Button
variant="ghost"
size="icon"
@@ -91,6 +112,35 @@
{/if}
</Button>
{/if}
{/snippet}
<Collapsible.Root bind:open={open.current} class={props.class}>
{#if level.enabled}
<!-- sticks while some of the content of the node is in view, with a border when it does -->
<div
class={['sticky bg-background', bordered && 'border-b']}
style="top: {level.top}px; z-index: {stickyZIndex(level.depth)}"
bind:clientHeight={rowHeight}
{@attach (row) => {
const stop = trackStuck(
row,
() => level.top,
(value) => {
stuck = value;
level.stuckRows.set(fullId, level.depth, value);
}
);
return () => {
stop?.();
level.stuckRows.set(fullId, level.depth, false);
};
}}
>
{@render row()}
</div>
{:else}
{@render row()}
{/if}
<Collapsible.Content>
{@render props.content(open.current)}
</Collapsible.Content>
@@ -0,0 +1,79 @@
import type { StuckRows } from './utils.svelte';
/**
* Where the row of a node of a sticky tree sticks: under the rows of the nodes it is in, which stay
* in view as long as some of their content can be seen.
*/
export type StickyLevel = {
/** Whether the rows stick. */
readonly enabled: boolean;
/** How far from the top of the scrolled area the rows of this level stick. */
readonly top: number;
/** How many nodes the rows of this level are in. */
readonly depth: number;
/** Which rows of the tree are stuck. */
readonly stuckRows: StuckRows;
};
/** The key of the context that holds the `StickyLevel`. */
export const stickyKey = 'collapsible-tree-sticky';
/** The rows of the outer levels are above the ones of the inner levels. */
export function stickyZIndex(depth: number): number {
return Math.max(100 - depth, 1);
}
/** The first ancestor that scrolls (or clips), which a sticky row sticks to. */
function scrollParent(node: HTMLElement): HTMLElement | null {
for (let parent = node.parentElement; parent; parent = parent.parentElement) {
if (getComputedStyle(parent).overflowY !== 'visible') {
return parent;
}
}
return null;
}
/**
* Tells whether a sticky row is stuck, and in view: it is held at `top()` from the top of the
* scrolled area, further down than the beginning of the node it is in. A row that is on its way out
* with the end of its node (pushed up under the row of the node above) is not.
*/
export function trackStuck(
row: HTMLElement,
top: () => number,
onChange: (stuck: boolean) => void
) {
const node = row.parentElement;
const scroller = scrollParent(row);
if (!node || !scroller) {
return;
}
let stuck = false;
let frame = 0;
const check = () => {
frame = 0;
const rowTop = row.getBoundingClientRect().top;
const held = scroller.getBoundingClientRect().top + scroller.clientTop + top();
const now =
rowTop - node.getBoundingClientRect().top > 0.5 && Math.abs(rowTop - held) < 0.5;
if (now !== stuck) {
stuck = now;
onChange(stuck);
}
};
const schedule = () => {
if (!frame) {
frame = requestAnimationFrame(check);
}
};
scroller.addEventListener('scroll', schedule, { passive: true });
// the node changes when it is opened or closed, or its content does
const observer = new ResizeObserver(schedule);
observer.observe(node);
schedule();
return () => {
scroller.removeEventListener('scroll', schedule);
observer.disconnect();
cancelAnimationFrame(frame);
};
}
@@ -29,3 +29,24 @@ export class CollapsibleTreeState {
return this._open[id];
}
}
/**
* The rows of a sticky tree that are stuck, by node, with how deep they are: only the deepest one
* gets the border that shows where the rows end.
*/
export class StuckRows {
private rows: Record<string, number> = $state({});
set(id: string, depth: number, stuck: boolean) {
if (stuck) {
this.rows[id] = depth;
} else if (id in this.rows) {
delete this.rows[id];
}
}
/** The depth of the deepest row that is stuck, -1 if none is. */
get deepest(): number {
return Math.max(-1, ...Object.values(this.rows));
}
}