Skip to content

Commit

Permalink
fix(Table): fix sticky Table when no offset is given
Browse files Browse the repository at this point in the history
  • Loading branch information
tujoworker committed May 31, 2022
1 parent d1da715 commit 888564d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
11 changes: 6 additions & 5 deletions packages/dnb-eufemia/src/components/table/TableStickyHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const useStickyHeader = ({
let tdElem: HTMLTableCellElement
let thHeight = 80
let tdHeight = 64
let offsetTop = 0
let offsetTopPx = 0

try {
trElem = tableElem.querySelector(
Expand All @@ -61,13 +61,14 @@ export const useStickyHeader = ({
thElem = getThElement(tableElem)
tdElem = getTdElement(tableElem)

offsetTop = parseFloat(String(stickyOffset))
offsetTopPx = parseFloat(String(stickyOffset || '0'))

if (offsetTop > 0) {
if (offsetTopPx > 0) {
if (String(stickyOffset).includes('em')) {
offsetTopPx = Math.round(offsetTopPx * 16)
trElem.style.top = String(stickyOffset)
} else {
trElem.style.top = `${offsetTop / 16}rem`
trElem.style.top = `${offsetTopPx / 16}rem`
}
}

Expand All @@ -81,7 +82,7 @@ export const useStickyHeader = ({
stickyWarning(e)
}

const marginTop = thHeight + tdHeight + offsetTop
const marginTop = thHeight + tdHeight + offsetTopPx

intersectionObserver.current = new IntersectionObserver(
(entries) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,24 @@ describe('useStickyHeader', () => {
expect(getTrClasses()).toEqual(['dnb-tr', 'sticky'])
})

it('should use default stickyOffset when not given', () => {
render(
<Table sticky>
<BasicTable sticky />
</Table>
)

expect(screen.queryByRole('table').querySelector('tr').style.top).toBe(
''
)
expect(window.IntersectionObserver).toHaveBeenCalledTimes(1)
expect(window.IntersectionObserver).toHaveBeenCalledWith(
expect.any(Function),
// Formula: thHeight + tdHeight + offsetTopPx = -(sum)px
{ rootMargin: '-144px 0px 0px 0px' }
)
})

it('should support stickyOffset', () => {
const getTrElem = () => screen.queryByRole('table').querySelector('tr')

Expand All @@ -98,6 +116,12 @@ describe('useStickyHeader', () => {
)

expect(getTrElem().style.top).toEqual('4rem')
expect(window.IntersectionObserver).toHaveBeenCalledTimes(1)
expect(window.IntersectionObserver).toHaveBeenNthCalledWith(
1,
expect.any(Function),
{ rootMargin: '-208px 0px 0px 0px' }
)

// provide pixels
rerender(
Expand All @@ -107,6 +131,12 @@ describe('useStickyHeader', () => {
)

expect(getTrElem().style.top).toEqual('4rem')
expect(window.IntersectionObserver).toHaveBeenCalledTimes(2)
expect(window.IntersectionObserver).toHaveBeenNthCalledWith(
2,
expect.any(Function),
{ rootMargin: '-208px 0px 0px 0px' }
)
})
})

Expand Down

0 comments on commit 888564d

Please sign in to comment.