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

[ui-storagebrowser] add useWindowSize hook to get window size #3930

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
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

import React, { useMemo, useState, useCallback, useEffect } from 'react';
import React, { useMemo, useState, useCallback, useRef } from 'react';
import { ColumnProps } from 'antd/lib/table';
import { Input, Tooltip } from 'antd';

Expand Down Expand Up @@ -53,6 +53,7 @@ import DragAndDrop from '../../../reactComponents/DragAndDrop/DragAndDrop';
import UUID from '../../../utils/string/UUID';
import { UploadItem } from '../../../utils/hooks/useFileUpload/util';
import FileUploadQueue from '../../../reactComponents/FileUploadQueue/FileUploadQueue';
import { useWindowSize } from '../../../utils/hooks/useWindowSize/useWindowSize';
import LoadingErrorWrapper from '../../../reactComponents/LoadingErrorWrapper/LoadingErrorWrapper';

interface StorageDirectoryPageProps {
Expand All @@ -78,7 +79,6 @@ const StorageDirectoryPage = ({
...restProps
}: StorageDirectoryPageProps): JSX.Element => {
const [loadingFiles, setLoadingFiles] = useState<boolean>(false);
const [tableHeight, setTableHeight] = useState<number>(100);
const [selectedFiles, setSelectedFiles] = useState<StorageDirectoryTableData[]>([]);
const [filesToUpload, setFilesToUpload] = useState<UploadItem[]>([]);
const [polling, setPolling] = useState<boolean>(false);
Expand Down Expand Up @@ -233,28 +233,10 @@ const StorageDirectoryPage = ({
setFilesToUpload(prevFiles => [...prevFiles, ...newUploadItems]);
};

useEffect(() => {
//TODO: handle table resize
const calculateTableHeight = () => {
const windowHeight = window.innerHeight;
// TODO: move 450 to dynamic based on table header height, tab nav and some header.
const tableHeightFix = windowHeight - 450;
return tableHeightFix;
};

const handleWindowResize = () => {
const tableHeight = calculateTableHeight();
setTableHeight(tableHeight);
};

handleWindowResize(); // Calculate initial scroll height

window.addEventListener('resize', handleWindowResize);

return () => {
window.removeEventListener('resize', handleWindowResize);
};
}, []);
const tableRef = useRef<HTMLDivElement>(null);
const { size, offset } = useWindowSize(tableRef);
// 40px for table header, 64px for pagination
const tableBodyHeight = Math.max(size.height - (offset.top + 64 + 40), 100);

const locale = {
emptyText: t('Folder is empty')
Expand Down Expand Up @@ -308,25 +290,27 @@ const StorageDirectoryPage = ({
loading={(loadingFiles || listDirectoryLoading) && !polling}
errors={errorConfig}
>
<Table
className={className}
columns={getColumns(tableData[0] ?? {})}
dataSource={tableData}
onRow={onRowClicked}
pagination={false}
rowClassName={rowClassName}
rowKey={r => `${r.path}_${r.type}_${r.mtime}`}
rowSelection={{
hideSelectAll: !tableData.length,
columnWidth: 36,
type: 'checkbox',
...rowSelection
}}
scroll={{ y: tableHeight }}
data-testid={testId}
locale={locale}
{...restProps}
/>
<div ref={tableRef}>
<Table
className={className}
columns={getColumns(tableData[0] ?? {})}
dataSource={tableData}
onRow={onRowClicked}
pagination={false}
rowClassName={rowClassName}
rowKey={r => `${r.path}_${r.type}_${r.mtime}`}
rowSelection={{
hideSelectAll: !tableData.length,
columnWidth: 36,
type: 'checkbox',
...rowSelection
}}
scroll={{ y: tableBodyHeight }}
data-testid={`${testId}`}
locale={locale}
{...restProps}
/>
</div>

{filesData?.page && filesData?.page?.total_pages > 0 && (
<Pagination
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// Licensed to Cloudera, Inc. under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { renderHook, act } from '@testing-library/react';
import { useWindowSize } from './useWindowSize';

describe('useWindowSize', () => {
const mockGetBoundingClientRect = jest.fn();

beforeAll(() => {
global.HTMLElement.prototype.getBoundingClientRect = mockGetBoundingClientRect;
});

beforeEach(() => {
mockGetBoundingClientRect.mockClear();
});

it('should handle missing ref gracefully', () => {
Object.defineProperty(window, 'innerWidth', {
writable: true,
value: 800
});
Object.defineProperty(window, 'innerHeight', {
writable: true,
value: 600
});

const { result } = renderHook(() => useWindowSize());

expect(result.current.size).toEqual({ width: 800, height: 600 });
expect(result.current.offset).toEqual({ top: 0, left: 0 });
});

it('should initialize size and offset correctly', () => {
Object.defineProperty(window, 'innerWidth', {
writable: true,
value: 800
});
Object.defineProperty(window, 'innerHeight', {
writable: true,
value: 600
});

mockGetBoundingClientRect.mockReturnValue({
top: 50,
left: 100,
width: 200,
height: 100,
right: 300,
bottom: 150
});

const mockRef = {
current: document.createElement('div')
};

const { result } = renderHook(() => useWindowSize(mockRef));

expect(result.current.size).toEqual({ width: 800, height: 600 });
expect(result.current.offset).toEqual({ top: 50, left: 100 });
});

it('should update size and offset on window resize', () => {
Object.defineProperty(window, 'innerWidth', {
writable: true,
value: 800
});
Object.defineProperty(window, 'innerHeight', {
writable: true,
value: 600
});
mockGetBoundingClientRect.mockReturnValue({
top: 50,
left: 100,
width: 200,
height: 100,
right: 300,
bottom: 150
});

const mockRef = {
current: document.createElement('div')
};

const { result } = renderHook(() => useWindowSize(mockRef));

expect(result.current.size).toEqual({ width: 800, height: 600 });
expect(result.current.offset).toEqual({ top: 50, left: 100 });

mockGetBoundingClientRect.mockReturnValue({
top: 60,
left: 120,
width: 200,
height: 100,
right: 320,
bottom: 160
});

act(() => {
Object.defineProperty(window, 'innerWidth', {
writable: true,
value: 1024
});
Object.defineProperty(window, 'innerHeight', {
writable: true,
value: 768
});
window.dispatchEvent(new Event('resize'));
});

expect(result.current.size).toEqual({ width: 1024, height: 768 });
expect(result.current.offset).toEqual({ top: 60, left: 120 });
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Licensed to Cloudera, Inc. under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { useLayoutEffect, useState } from 'react';

interface WindowSize {
width: number;
height: number;
}

interface WindowOffset {
top: number;
left: number;
}

export const useWindowSize = (
ref?: React.RefObject<HTMLElement>
): {
size: WindowSize;
offset: WindowOffset;
} => {
const [size, setSize] = useState<WindowSize>({
width: window.innerWidth,
height: window.innerHeight
});

const [offset, setOffset] = useState<WindowOffset>({
top: 0,
left: 0
});

const handleResize = () => {
setSize({
width: window.innerWidth,
height: window.innerHeight
});

if (ref?.current) {
const rect = ref.current.getBoundingClientRect();
setOffset({
top: rect.top + window.scrollY,
left: rect.left + window.scrollX
});
}
};

useLayoutEffect(() => {
handleResize();

window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [ref]);

return { size, offset };
};