Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#43 scroll position #52

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 20 additions & 19 deletions VirtualList.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
// read-only, but visible to consumers via bind:start
export let start = 0;
export let end = 0;

// local state
let height_map = [];
let rows;
Expand All @@ -31,6 +30,12 @@
$: if (mounted) refresh(items, viewport_height, itemHeight);

async function refresh(items, viewport_height, itemHeight) {
const isStartOverflow = items.length < start

if (isStartOverflow) {
await scrollToIndex(items.length - 1, {behavior: 'auto'})
}

const { scrollTop } = viewport;

await tick(); // wait until the DOM is up to date
Expand Down Expand Up @@ -102,29 +107,25 @@
while (i < items.length) height_map[i++] = average_height;
bottom = remaining * average_height;

// prevent jumping if we scrolled up into unknown territory
if (start < old_start) {
await tick();

let expected_height = 0;
let actual_height = 0;

for (let i = start; i < old_start; i +=1) {
if (rows[i - start]) {
expected_height += height_map[i];
actual_height += itemHeight || rows[i - start].offsetHeight;
}
}

const d = actual_height - expected_height;
viewport.scrollTo(0, scrollTop + d);
}

// TODO if we overestimated the space these
// rows would occupy we may need to add some
// more. maybe we can just call handle_scroll again?
}

export async function scrollToIndex (index, opts) {
const {scrollTop} = viewport;
const itemsDelta = index - start;
const _itemHeight = itemHeight || average_height;
const distance = itemsDelta * _itemHeight;
opts = {
left: 0,
top: scrollTop + distance,
behavior: 'smooth',
...opts
};
viewport.scrollTo(opts);
}

// trigger initial refresh
onMount(() => {
rows = contents.getElementsByTagName('svelte-virtual-list-row');
Expand Down
Binary file added logo_svelte-virtual-list-ce.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions logo_svelte-virtual-list-ce.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.