Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

как упростить filterOptions, ток чтобы я могла использовать для другого набора колонок и…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-7-sonnet-20250219-thinking-32k’s answer.
  1. User

    как упростить filterOptions, ток чтобы я могла использовать для другого набора колонок и их фильтров

    import { MenuContent, MenuRoot, MenuTrigger } from '@/components/ui/menu' import { Tooltip } from '@/components/ui/tooltip' import { setSelectedTasks } from '@/store/shiftDailyTasksSlice' import { Box, Checkbox, Flex, Icon, MenuItem, Separator, Table, Text, useDisclosure, } from '@chakra-ui/react' import React, { useRef, useState } from 'react' import { RiArrowRightSLine, RiCheckboxMultipleBlankFill, RiEqualLine, RiFilter3Line, } from 'react-icons/ri' import { PiGreaterThanBold, PiGreaterThanOrEqualBold, PiLessThanBold, PiLessThanOrEqualBold, } from 'react-icons/pi' import { useDispatch } from 'react-redux'

    const filterOptions = { staff: { operators: [ { value: 'exact', label: 'Равно', icon: RiEqualLine, filterType: 'input', }, { value: 'in', label: 'Выбрать несколько', icon: RiCheckboxMultipleBlankFill, filterType: 'checkbox', }, ], }, machines: { operators: [ { value: 'exact', label: 'Равно', icon: RiEqualLine, filterType: 'input', }, { value: 'in', label: 'Выбрать несколько', icon: RiCheckboxMultipleBlankFill, filterType: 'checkbox', }, ], }, time_start: { operators: [ { value: 'exact', label: 'Равно', icon: RiEqualLine }, { value: 'in', label: 'Выбрать несколько', icon: RiCheckboxMultipleBlankFill, filterType: 'checkbox', }, { value: 'gt', label: 'Больше чем', icon: PiGreaterThanBold, filterType: 'input', }, { value: 'lt', label: 'Меньше чем', icon: PiLessThanBold, filterType: 'input', }, { value: 'gte', label: 'Больше или равно', icon: PiGreaterThanOrEqualBold, filterType: 'input', }, { value: 'lte', label: 'Меньше или равно', icon: PiLessThanOrEqualBold, filterType: 'input', }, ], }, time_end: { operators: [ { value: 'exact', label: 'Равно', icon: RiEqualLine, filterType: 'input', }, { value: 'in', label: 'Выбрать несколько', icon: RiCheckboxMultipleBlankFill, filterType: 'checkbox', }, { value: 'gt', label: 'Больше чем', icon: PiGreaterThanBold, filterType: 'input', }, { value: 'lt', label: 'Меньше чем', icon: PiLessThanBold, filterType: 'input', }, { value: 'gte', label: 'Больше или равно', icon: PiGreaterThanOrEqualBold, filterType: 'input', }, { value: 'lte', label: 'Меньше или равно', icon: PiLessThanOrEqualBold, filterType: 'input', }, ], }, status: { operators: [ { value: 'exact', label: 'Равно', icon: RiEqualLine, filterType: 'input', }, { value: 'in', label: 'Выбрать несколько', icon: RiCheckboxMultipleBlankFill, filterType: 'checkbox', }, ], }, created_at: { operators: [ { value: 'exact', label: 'Равно', icon: RiEqualLine, filterType: 'input', }, { value: 'in', label: 'Выбрать несколько', icon: RiCheckboxMultipleBlankFill, filterType: 'checkbox', }, { value: 'gt', label: 'Больше чем', icon: PiGreaterThanBold, filterType: 'input', }, { value: 'lt', label: 'Меньше чем', icon: PiLessThanBold, filterType: 'input', }, { value: 'gte', label: 'Больше или равно', icon: PiGreaterThanOrEqualBold, filterType: 'input', }, { value: 'lte', label: 'Меньше или равно', icon: PiLessThanOrEqualBold, filterType: 'input', }, ], }, }

    const TableHeader = ({ column, selectedRows, allIds }) => { const filterMenu = useDisclosure() const [subMenuOpen, setSubMenuOpen] = useState() const dispatch = useDispatch() const ref = useRef(null)

    if (column.id === 'selection') {
        const allSelected = selectedRows?.length === allIds?.length
        const indeterminate = selectedRows?.length > 0 && !allSelected
    
        return (
            <Table.ColumnHeader
                p='0px'
                width={column.width}
                borderInlineEndWidth='0px'
                borderRight='1px solid #E8EFFA'
            >
                <Flex direction='column'>
                    <Box p='0px 8px 0px 12px'>
                        <Checkbox.Root
                            checked={
                                indeterminate ? 'indeterminate' : allSelected
                            }
                            onCheckedChange={e => {
                                if (e.checked) {
                                    dispatch(setSelectedTasks([...allIds]))
                                } else {
                                    dispatch(setSelectedTasks([]))
                                }
                            }}
                            cursor='pointer'
                        >
                            <Checkbox.HiddenInput />
                            <Checkbox.Control />
                        </Checkbox.Root>
                    </Box>
                </Flex>
            </Table.ColumnHeader>
        )
    }
    
    const columnFilterOptions = filterOptions[column.filterName] || null
    return (
        <Table.ColumnHeader
            color='bia.black.700'
            textStyle='bia.table'
            p='0px'
            width={column.width}
            borderInlineEndWidth='0px'
            borderRight='1px solid #E8EFFA'
        >
            <Flex direction='column'>
                <Box p='0px 8px 0px 12px'>
                    <Text>{column.Header}</Text>
                </Box>
                <Separator borderColor='bia.neutral.500' />
                <Box p='0px 8px 0px 12px'>
                    {columnFilterOptions && (
                        <MenuRoot
                            closeOnSelect={false}
                            onOpenChange={details => {
                                if (!details.open) {
                                    filterMenu.onClose()
                                    setSubMenuOpen(null)
                                }
                            }}
                            positioning={{
                                getAnchorRect() {
                                    return ref.current
                                        ? ref.current.getBoundingClientRect()
                                        : null
                                },
                            }}
                            open={filterMenu.open}
                            variant='bia.filterMenu'
                        >
                            <Tooltip
                                content={'Фильтры'}
                                openDelay={0}
                            >
                                <MenuTrigger
                                    w='24px'
                                    h='24px'
                                    borderRadius='4px'
                                    border='2px solid transparent'
                                    _focusVisible={{
                                        outline: '2px solid #FFCCD2',
                                        outlineOffset: '0',
                                    }}
                                    onClick={filterMenu.onOpen}
                                    variant='outline'
                                    ref={ref}
                                >
                                    <Icon
                                        as={RiFilter3Line}
                                        width='20px'
                                        height='20px'
                                        fill={
                                            filterMenu.open
                                                ? 'bia.red.800'
                                                : 'bia.black.800'
                                        }
                                    />
                                </MenuTrigger>
                            </Tooltip>
                            <MenuContent p='0'>
                                <Flex direction='column'>
                                    {columnFilterOptions.operators.map(
                                        filter => (
                                            <MenuItem
                                                key={filter.value}
                                                justifyContent='space-between'
                                            >
                                                <Flex
                                                    alignItems='center'
                                                    gap='8px'
                                                >
                                                    <Icon
                                                        width='20px'
                                                        height='20px'
                                                        color='#2B2D35'
                                                        as={filter.icon}
                                                    />
                                                    <Text
                                                        fontSize='14px'
                                                        lineHeight='24px'
                                                    >
                                                        {filter.label}
                                                    </Text>
                                                </Flex>
                                                <Icon
                                                    width='20px'
                                                    height='20px'
                                                    color='#2B2D35'
                                                    as={RiArrowRightSLine}
                                                />
                                            </MenuItem>
                                        )
                                    )}
                                </Flex>
                            </MenuContent>
                        </MenuRoot>
                    )}
                </Box>
            </Flex>
        </Table.ColumnHeader>
    )
    

    }

    export default TableHeader

  2. Assistant

    Ниже — одна из самых простых стратегий «раздуть» filterOptions до гибкого и полностью переиспользуемого генератора.

    1. Описываем единый справочник всех возможных операторов (value + label + icon + filterType).
    2. Готовим «пресеты» для разных типов данных: text, number, date, enum и т. д.
    3. Функцией buildFilterOptions по списку колонок собираем final-конфиг прямо в компоненте таблицы или в общем хелпере.

    Итог — чтобы «добавить ещё одну таблицу», вам достаточно передать в buildFilterOptions массив её колонок.

    // filters.ts
    import {
      RiEqualLine,
      RiCheckboxMultipleBlankFill,
    } from 'react-icons/ri'
    import {
      PiGreaterThanBold,
      PiGreaterThanOrEqualBold,
      PiLessThanBold,
      PiLessThanOrEqualBold,
    } from 'react-icons/pi'
    
    /* 1. Единый справочник операторов */
    const OPERATORS = {
      exact: { value: 'exact', label: 'Равно',           icon: RiEqualLine,              filterType: 'input'    },
      in:    { value: 'in',    label: 'Выбрать несколько', icon: RiCheckboxMultipleBlankFill, filterType: 'checkbox' },
      gt:    { value: 'gt',    label: 'Больше чем',      icon: PiGreaterThanBold,        filterType: 'input'    },
      lt:    { value: 'lt',    label: 'Меньше чем',      icon: PiLessThanBold,           filterType: 'input'    },
      gte:   { value: 'gte',   label: 'Больше или равно', icon: PiGreaterThanOrEqualBold, filterType: 'input'    },
      lte:   { value: 'lte',   label: 'Меньше или равно', icon: PiLessThanOrEqualBold,   filterType: 'input'    },
    } as const
    
    /* 2. Пресеты для типов */
    const PRESETS = {
      text:   ['exact', 'in'],
      enum:   ['exact', 'in'],
      number: ['exact', 'in', 'gt', 'lt', 'gte', 'lte'],
      date:   ['exact', 'in', 'gt', 'lt', 'gte', 'lte'],
    } as const
    
    /* 3. Генератор */
    export type ColumnDef = { filterName: string; type: keyof typeof PRESETS }
    
    export const buildFilterOptions = (cols: ColumnDef[]) =>
      cols.reduce<Record<string, { operators: typeof OPERATORS[keyof typeof OPERATORS][] }>>(
        (acc, { filterName, type }) => {
          acc[filterName] = {
            operators: PRESETS[type].map(key => OPERATORS[key]),
          }
          return acc
        },
        {},
      )
    

    Использование в вашем TableHeader

    // любая таблица описывает ОДИН раз свои колонки
    const columnsMeta = [
      { filterName: 'staff',      type: 'text' },
      { filterName: 'machines',   type: 'text' },
      { filterName: 'time_start', type: 'date' },
      { filterName: 'time_end',   type: 'date' },
      { filterName: 'status',     type: 'enum' },
      { filterName: 'created_at', type: 'date' },
    ] as const
    
    // мемоизируем, чтобы не пересоздавать на каждом рендере
    const filterOptions = useMemo(() => buildFilterOptions(columnsMeta), [])
    

    Дальше TableHeader остается прежним:

    const columnFilterOptions = filterOptions[column.filterName]
    

    Как добавить ещё одну таблицу?

    1. Создаёте новый массив columnsMeta₂.
    2. Вызываете buildFilterOptions(columnsMeta₂).
    3. Передаёте результат в свои TableHeader.

    Преимущества

    • Один источник правды для иконок, надписей и filterType.
    • Пресеты вы меняете в одном месте (добавили, скажем, «startsWith» — разом у всех текстовых колонок).
    • Лаконичные колонки: описываете только имя фильтра и тип данных.

    Если нужно точечно «перебить» пресет для конкретной колонки, можно добавить overrides:

    export const buildFilterOptions = (cols, overrides = {}) =>
      cols.reduce((acc, { filterName, type }) => {
        const base = PRESETS[type].map(k => OPERATORS[k])
        acc[filterName] = overrides[filterName]
          ? { operators: overrides[filterName] }
          : { operators: base }
        return acc
      }, {})
    

    Теперь колонка status может получить свой кастомный набор операторов, передав его в overrides.

  3. User

    а если набор колонок будет такой machine_state_info: exact, in / produced_semiproducts_name: exact, in / produced_semiproducts_count: exact, in, gt, lt, gte, lte

  4. Assistant

    Ничего «дописывать руками» в самом конфиге больше не нужно — достаточно передать новый массив колонок (и при желании — overrides).

    Ниже показаны сразу оба варианта:
    • «чистый» — когда вас полностью устраивают пресеты text/number;
    • «точечный» — как перебить пресет через overrides, если вдруг для конкретной колонки нужен особый набор.

    // TableX.tsx  (новая таблица с вашими колонками)
    import { useMemo } from 'react'
    import { buildFilterOptions } from '@/utils/filters'   // генератор из предыдущего ответа
    
    /* --------------------------------------------------------------------------------
     * 1. ОПИСЫВАЕМ КОЛОНКИ
     *    Только name + тип (text / number / date / enum …)
     * --------------------------------------------------------------------------------*/
    const columnsMeta = [
      { filterName: 'machine_state_info',        type: 'text'   }, // exact, in
      { filterName: 'produced_semiproducts_name',type: 'text'   }, // exact, in
      { filterName: 'produced_semiproducts_count',type: 'number'}, // exact, in, gt, lt, gte, lte
    ] as const
    
    /* --------------------------------------------------------------------------------
     * 2-а. ПРОСТО строим конфиг, если устраивают пресеты
     * --------------------------------------------------------------------------------*/
    const filterOptions = useMemo(
      () => buildFilterOptions(columnsMeta),             // ← вот и всё 😉
      []
    )
    
    /* --------------------------------------------------------------------------------
     * 2-б. (опционально) Хотите переопределить конкретную колонку?
     *      Например, для produced_semiproducts_name оставить только exact
     * --------------------------------------------------------------------------------*/
    const filterOptionsWithOverrides = useMemo(
      () =>
        buildFilterOptions(
          columnsMeta,
          {
            produced_semiproducts_name: ['exact'],        // override
          }
        ),
      []
    )
    
    /* --------------------------------------------------------------------------------
     * 3. Передаём в Header / Table
     * --------------------------------------------------------------------------------*/
    <Table columns={columns} filterOptions={filterOptions} />
    

    Функция-генератор (filters.ts) уже умеет принимать overrides — если в неё не передавать второй аргумент, берётся чистый пресет:

    export const buildFilterOptions = (
      cols: ColumnDef[],
      overrides: Record<string, (keyof typeof OPERATORS)[]> = {}
    ) =>
      cols.reduce<Record<string, { operators: OperatorConf[] }>>((acc, { filterName, type }) => {
        const baseList      = PRESETS[type].map(k => OPERATORS[k])
        const overrideList  = overrides[filterName]?.map(k => OPERATORS[k])
        acc[filterName] = { operators: overrideList ?? baseList }
        return acc
      }, {})
    

    Таким образом для вашего нового набора колонок:

    machine_state_info → text-preset → ['exact', 'in']
    produced_semiproducts_name → text-preset → ['exact', 'in']
    produced_semiproducts_count → number-preset → ['exact', 'in', 'gt', 'lt', 'gte', 'lte']

    Никакого дублирования и километровых объектов вручную ✨

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.