Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
171 changes: 171 additions & 0 deletions components/src/Table/ColumnFilter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
// Copyright The Perses Authors
// Licensed 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 { Box, ButtonBase, Typography, useTheme } from '@mui/material';
import { ReactElement, useMemo, useRef, useState } from 'react';
import { ColumnFilterDropdown } from './ColumnFilterDropDown';
import { TableColumnConfig } from './model/table-model';
import { FilterColumns } from './TableFilters';

interface Props<TableData> extends FilterColumns {
id: string;
width?: number | 'auto';
filters: Array<string | number>;
borderRight: string;
column: TableColumnConfig<TableData>;
columnUniqueValues: Record<string, Array<string | number>>;
openFilterColumn?: string;
setOpenFilterColumn: (columnId?: string) => void;
}

export function ColumnFilter<TableData>({
id,
width,
filters,
column,
setColumnFilters,
columnFilters,
borderRight,
columnUniqueValues,
openFilterColumn,
setOpenFilterColumn,
}: Props<TableData>): ReactElement {
const theme = useTheme();
const dropdownId = id.concat('-dropdown');

const [filterAnchorEl, setFilterAnchorEl] = useState<{ [key: string]: HTMLElement | undefined }>({});
const [calculatedWidth, setCalculatedWidth] = useState<string>('0px');

const handleFilterClick = (event: React.MouseEvent<HTMLButtonElement>, columnId: string): void => {
event.preventDefault();
event.stopPropagation();
setFilterAnchorEl({ ...filterAnchorEl, [columnId]: event.currentTarget });
setOpenFilterColumn(columnId);
};

const handleFilterClose = (): void => {
setFilterAnchorEl({});
setOpenFilterColumn(undefined);
};

const updateColumnFilter = (columnId: string, values: Array<string | number>): void => {
const newFilters = columnFilters.filter((f) => f.id !== columnId);
if (values.length) {
newFilters.push({ id: columnId, value: values });
}
setColumnFilters(newFilters);
};

const mainContainerRef = useRef<HTMLDivElement>(null);
const [mainContainerDimension, setMainContainerDimension] = useState<{ width: number; height: number }>({
width: 0,
height: 0,
});

const observeDimensionChanges = (htmlElements: ResizeObserverEntry[]): void => {
if (htmlElements?.length) {
const targetElement = htmlElements[0]?.target as HTMLElement;
const width = targetElement.offsetWidth;
const height = targetElement.offsetHeight;
setMainContainerDimension({ width, height });
}
};

/**
* Width is taken from the optional column.width. Therefore, it could be possibly undefined
* To handle this, we need the actual width of the container to adjust the width of the dropdown. They need to be perfectly aligned
* Also, using an observer is necessary due to the effects of the toggle view mode which changes the table dimension
*/
const observer = useRef(new ResizeObserver(observeDimensionChanges));
if (mainContainerRef.current) {
observer.current.observe(mainContainerRef.current);
}

useMemo(() => {
if (width !== undefined) {
setCalculatedWidth(typeof width === 'number' ? `${width}px` : width);
} else if (mainContainerDimension) {
setCalculatedWidth(`${mainContainerDimension.width}px`);
}
}, [width, mainContainerDimension]);

return (
<Box
key={id}
data-testid={id}
ref={mainContainerRef}
sx={{
padding: '8px',
borderRight: borderRight,
width: width,
minWidth: width,
maxWidth: width,
display: 'flex',
alignItems: 'center',
position: 'relative',
boxSizing: 'border-box',
flex: typeof width === 'number' ? 'none' : '1 1 auto',
}}
>
<Typography
variant="body2"
color="text.secondary"
noWrap
component="span"
sx={{
mr: 1,
flex: 1,
fontSize: '12px',
minWidth: '100px',
}}
>
{filters.length ? `${filters.length} items` : 'All'}
</Typography>

<ButtonBase
onClick={(e) => handleFilterClick(e, column.accessorKey as string)}
sx={{
border: '1px solid',
borderColor: 'divider',
backgroundColor: 'background.paper',
fontSize: '12px',
color: filters.length ? 'primary.main' : 'text.secondary',
px: 1,
py: 0.5,
borderRadius: 1,
minWidth: '20px',
height: '24px',
flexShrink: 0,
transition: (theme) => theme.transitions.create('all', { duration: 200 }),
'&:hover': {
backgroundColor: 'action.hover',
},
}}
>
</ButtonBase>

{openFilterColumn === column.accessorKey && (
<ColumnFilterDropdown
id={dropdownId}
width={calculatedWidth}
allValues={columnUniqueValues[column.accessorKey as string] || []}
selectedValues={filters}
onFilterChange={(values) => updateColumnFilter(column.accessorKey as string, values)}
theme={theme}
handleFilterClose={handleFilterClose}
/>
)}
</Box>
);
}
140 changes: 140 additions & 0 deletions components/src/Table/ColumnFilterDropDown.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// Copyright The Perses Authors
// Licensed 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 { ReactElement } from 'react';
import { Box, Checkbox, Divider, FormControlLabel, Theme, Typography, ClickAwayListener } from '@mui/material';

interface Props {
id: string;
allValues: Array<string | number>;
selectedValues: Array<string | number>;
onFilterChange: (values: Array<string | number>) => void;
handleFilterClose: () => void;
theme: Theme;
width: string;
}

export const ColumnFilterDropdown = ({
id,
allValues,
selectedValues,
onFilterChange,
handleFilterClose,
theme,
width,
}: Props): ReactElement => {
const values = [...new Set(allValues)].filter((v) => v !== null).sort();

if (!values.length) {
return (
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should render this dropdown inside a Portal, this will avoid the clipping. The table plugin uses it's own implementation which also has this issue. But fixing it here will make it consistent for both logs and table plugins.

<ClickAwayListener onClickAway={handleFilterClose}>
<Box
sx={{
position: 'absolute',
top: '100%',
left: 0,
zIndex: 9999,
Copy link
Copy Markdown
Contributor

@jgbernalp jgbernalp Feb 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
zIndex: 9999,
zIndex: 1000,

This will make it above other elements but below the sticky header, when using the Portal

Copy link
Copy Markdown
Contributor Author

@shahrokni shahrokni Feb 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const [filterAnchorEl, setFilterAnchorEl] = useState<{ [key: string]: HTMLElement | undefined }>({});

I was checking your comment when I realized there is no usage of this sate in the code. This is coming from the original code. Even in the original code this line has no usage! Am I mistaken, is there any usage that I am missing?! filterAnchorEl is never used for any kind of calculations. I think, the dropdown used to be a popover. Later changed, and this line became obsolete. I am not sure though.

Update

OK, a bit of this a bit of that! I guess the original idea was to use an anchor and MUI popover.
Looks nice!

⚠️ IMPORTANRT: Popover is a kind of modal. It covers the entire page, so elements beneath the Popover could not be reached as long as the Popover is not closed.

image

marginTop: '4px',
}}
>
<Box
data-filter-dropdown
data-testid={id}
sx={{
width: width,
padding: 10,
backgroundColor: theme.palette.background.paper,
border: `1px solid ${theme.palette.divider}`,
boxShadow: theme.shadows[4],
}}
>
<Typography sx={{ color: theme.palette.text.secondary, fontSize: 14 }}>No values found</Typography>
</Box>
</Box>
</ClickAwayListener>
);
}

return (
<ClickAwayListener onClickAway={handleFilterClose}>
<Box
sx={{
position: 'absolute',
top: '100%',
left: 0,
zIndex: 9999,
marginTop: '4px',
}}
>
<Box
data-filter-dropdown
data-testid={id}
sx={{
width: width,
padding: '10px',
backgroundColor: theme.palette.background.paper,
border: `1px solid ${theme.palette.divider}`,
boxShadow: theme.shadows[4],
maxHeight: 250,
overflowY: 'auto',
}}
>
<Box style={{ marginBottom: 8, fontSize: 14, fontWeight: 'bold' }}>
<FormControlLabel
control={
<Checkbox
checked={selectedValues.length === values.length && values.length > 0}
onChange={(e) => onFilterChange(e.target.checked ? values : [])}
indeterminate={selectedValues.length > 0 && selectedValues.length < values.length}
/>
}
label={<Typography sx={{ color: 'text.primary' }}>Select All ({values.length})</Typography>}
/>
</Box>
<Divider sx={{ my: 1 }} />
{values.map((value, index) => (
<Box key={`value-${index}`} style={{ marginBottom: 4 }}>
<FormControlLabel
sx={{
display: 'flex',
alignItems: 'center',
padding: '2px 0',
borderRadius: '4px',
cursor: 'pointer',
}}
control={
<Checkbox
size="small"
checked={selectedValues.includes(value)}
onChange={(e) => {
if (e.target.checked) {
onFilterChange([...selectedValues, value]);
} else {
onFilterChange(selectedValues.filter((v) => v !== value));
}
}}
/>
}
label={
<Typography variant="body2" sx={{ color: 'text.primary', fontSize: 14 }}>
{!value && value !== 0 ? '(empty)' : String(value)}
</Typography>
}
/>
</Box>
))}
</Box>
</Box>
</ClickAwayListener>
);
};
Loading