Skip to content

Commit ace7d93

Browse files
authoredFeb 25, 2025··
fix(virtual-core): fixes center alignment option for scrollToOffset (#935)
Fixes #931
1 parent 9b6a9aa commit ace7d93

File tree

1 file changed

+20
-28
lines changed

1 file changed

+20
-28
lines changed
 

‎packages/virtual-core/src/index.ts

+20-28
Original file line numberDiff line numberDiff line change
@@ -879,17 +879,23 @@ export class Virtualizer<
879879
)
880880
}
881881

882-
getOffsetForAlignment = (toOffset: number, align: ScrollAlignment) => {
882+
getOffsetForAlignment = (
883+
toOffset: number,
884+
align: ScrollAlignment,
885+
itemSize = 0,
886+
) => {
883887
const size = this.getSize()
884888
const scrollOffset = this.getScrollOffset()
885889

886890
if (align === 'auto') {
887-
if (toOffset >= scrollOffset + size) {
888-
align = 'end'
889-
}
891+
align = toOffset >= scrollOffset + size ? 'end' : 'start'
890892
}
891893

892-
if (align === 'end') {
894+
if (align === 'center') {
895+
// When aligning to a particular item (e.g. with scrollToIndex),
896+
// adjust offset by the size of the item to center on the item
897+
toOffset += (itemSize - size) / 2
898+
} else if (align === 'end') {
893899
toOffset -= size
894900
}
895901

@@ -928,29 +934,15 @@ export class Virtualizer<
928934
}
929935
}
930936

931-
const centerOffset =
932-
item.start - this.options.scrollPaddingStart + (item.size - size) / 2
933-
934-
switch (align) {
935-
case 'center':
936-
return [this.getOffsetForAlignment(centerOffset, align), align] as const
937-
case 'end':
938-
return [
939-
this.getOffsetForAlignment(
940-
item.end + this.options.scrollPaddingEnd,
941-
align,
942-
),
943-
align,
944-
] as const
945-
default:
946-
return [
947-
this.getOffsetForAlignment(
948-
item.start - this.options.scrollPaddingStart,
949-
align,
950-
),
951-
align,
952-
] as const
953-
}
937+
const toOffset =
938+
align === 'end'
939+
? item.end + this.options.scrollPaddingEnd
940+
: item.start - this.options.scrollPaddingStart
941+
942+
return [
943+
this.getOffsetForAlignment(toOffset, align, item.size),
944+
align,
945+
] as const
954946
}
955947

956948
private isDynamicMode = () => this.elementsCache.size > 0

0 commit comments

Comments
 (0)
Please sign in to comment.