break-word обрезает строку по словам, как обрезать по символам
- User
break-word обрезает строку по словам, как обрезать по символам
- Assistant
В CSS за «деление строки» отвечают сразу несколько свойств.
Если нужно переносить/«ломать» строку по любому символу, а не только по пробелам, используйте одно из двух:/* классический способ */ .element { word-break: break-all; /* разрешает перенос в любой точке */ } /* более новый, «мягкий» вариант (рекомендован спецификацией) */ .element { overflow-wrap: anywhere; /* переносим где угодно, но только при необходимости */ }Разница:
•
word-break: break-all— жёстко разрешает перенос между любыми символами, даже если место ещё не закончилось;
•overflow-wrap: anywhere— старается сначала переносить по словам, а к «символьному» переносу прибегает, только когда содержимое не помещается.Оба варианта, в отличие от
overflow-wrap: break-word(word-wrap: break-word), не требуют пробела между словами и плюнут перенос в любом месте строки. - User
есть компонент fixed table: import React, { ReactElement, ReactNode } from 'react'; import { ItemProps, TableVirtuoso } from 'react-virtuoso'; import './FixedTable.css'; import { Box, TableFooter, TableRowProps } from '@mui/material'; import { observer } from 'mobx-react-lite'; import { TableRow, parserSx, CircularProgress, TableCell } from 'sigur-ui-kit'; import { useTranslation } from 'react-i18next'; import { ElementWithId } from '../../../features'; import { useClasses } from './FixedTable.style'; import { TableEmptyPlaceholder } from './TableEmptyPlaceholder';
export interface TableItemProps extends TableRowProps { hideSelect?: boolean; }
interface FixedTableProps { data: T[]; renderRow: (index: number, element: T) => ReactNode; Header?: ReactNode; loadMore?: () => Promise; rowProps?: (data: T) => TableItemProps; selected?: Map<number, T>; isSelectAll?: boolean; currentScrollPosition?: number; hasMore?: boolean; itemHeight?: number; overscan?: number; isLoading?: boolean; emptyText: string; withFilter?: boolean; showEmpty?: boolean; HeaderChildren?: ReactNode; }
export const FixedTable = (<T extends ElementWithId, >(props: FixedTableProps): ReactElement => { const { data, renderRow, Header = null, loadMore = (): Promise => Promise.resolve(), rowProps, selected, hasMore = false, itemHeight, overscan = 1000, isSelectAll, isLoading, emptyText, withFilter, showEmpty = true, HeaderChildren } = props; const classes = useClasses(); const { t } = useTranslation(); const rowCount = hasMore ? data.length + 1 : data.length; // useEffect(() => { // if (!tableRef.current) { // return; // } // // tableRef.current.scrollTo({ // top: currentScrollPosition, // }); // }); // // const handleScrollerRef = useCallback((ref: HTMLElement | Window | null): void => { // scrollerRef.current = ref; // }, []);
return ( <Box sx={ classes.parent } > <TableVirtuoso data={ data } fixedHeaderContent={ (): ReactNode => Header } className='table-container' overscan={ { main: overscan, reverse: overscan } } components={ { TableFoot: React.forwardRef(({ style }, ref): ReactElement => { if (!hasMore || !data.length) { return (<></>); } return ( <TableFooter ref={ ref } sx={ classes.loaderRow } key={ data.length } > <TableRow> <TableCell colSpan={ 100 } > <CircularProgress color='secondary' sx={ parserSx(classes.loader, style) } /> </TableCell> </TableRow> </TableFooter> ); }), TableRow: observer( (itemProps: ItemProps<T>): ReactElement => { const { hideSelect, sx, ...renderProps } = rowProps?.(itemProps.item) || {}; const isSelected = (!hideSelect && isSelectAll) ? !selected?.has(itemProps.item['id']) : !!selected?.has(itemProps.item['id']); return ( <TableRow sx={ parserSx( itemProps.style, isSelected ? classes.selectedTableRow : classes.tableRow, sx ) } { ...itemProps } { ...renderProps } /> ); } ) } } fixedFooterContent={ () => false } width='100%' atBottomThreshold={ 10 } atBottomStateChange={ (isBot): void => { if (isBot && hasMore) { loadMore(); } } } totalCount={ rowCount } itemContent={ renderRow } fixedItemHeight={ itemHeight } /> <TableEmptyPlaceholder isLoading={ !!isLoading } isEmpty={ showEmpty && !data.length } emptyText={ !withFilter ? emptyText : t('No search results') } /> { HeaderChildren } </Box> );}); в который в tablerow загружается кастомный компонент
import React, { ReactElement, useEffect } from 'react'; import { parserSx, TableCell } from 'sigur-ui-kit'; import { useTranslation } from 'react-i18next'; import { observer } from 'mobx-react-lite'; import { DateUtils, Schedule, Tag } from '../../../../features'; import { useHoverParent, useLoader } from '../../../../hooks'; import { TableCheckboxCell, TableEditTagsCell, TagsCell } from '../../../Common'; import { TypographyOverflow } from '../../../../components/custom'; import { useClasses } from './SchedulesTableRow.style';
interface SchedulesTableRowProps { schedule: Schedule; isSelected?: boolean; handleChangeSelect: (schedule: Schedule) => void; updateAllTags?: (tags: Tag[], unAssignTagIds?: Tag[], assignTagIds?: Tag[], id?: number) => Promise; loadAssignedTags?: (id: number) => Promise; mapOfAllTags?: Map<number, Tag>; mapOfAssignedTagIds?: Map<number, number[]>; }
export const SchedulesTableRow = observer( (props: SchedulesTableRowProps): ReactElement => { const { schedule, isSelected, handleChangeSelect, updateAllTags, loadAssignedTags, mapOfAllTags, mapOfAssignedTagIds } = props;
const { isHovered, hoverRef } = useHoverParent(); const classes = useClasses(); const { t } = useTranslation(); const { byPromise, isLoading } = useLoader(); useEffect(() => { if (loadAssignedTags && !mapOfAssignedTagIds?.get(schedule.id)) { byPromise(loadAssignedTags(schedule.id)); } }, [byPromise, loadAssignedTags, mapOfAssignedTagIds, schedule.id]); const date = schedule.start.getValue(); return ( <> <TableCheckboxCell sx={ parserSx(classes.cell, classes.checkboxCell) } handleChange={ () => handleChangeSelect(schedule) } isSelected={ isSelected } /> <TableCell ref={ hoverRef } sx={ parserSx(classes.cell, classes.nameCell) } > <TypographyOverflow variant='body2' fontWeight={ 500 } > { schedule.id === -1 ? t('Always (default schedule)') : schedule.name } </TypographyOverflow> </TableCell> <TableCell sx={ parserSx(classes.cell) } > <TypographyOverflow variant='body2' > { date && DateUtils.parseToDateString(date, '.') } </TypographyOverflow> </TableCell> <TagsCell sx={ classes.cell } entityId={ schedule.id } mapOfAssignedTagIds={ mapOfAssignedTagIds } mapOfAllTags={ mapOfAllTags } isLoading={ isLoading } /> <TableEditTagsCell sx={ parserSx(classes.cell, classes.smallCell) } allTags={ Array.from(mapOfAllTags?.values() || []) } mapOfAllTags={ mapOfAllTags } mapOfAssignedTagIds={ mapOfAssignedTagIds } entityId={ schedule.id } updateAllTags={ updateAllTags } assignPermission='SCHEDULER_TAG_ASSIGN' editPermission='SCHEDULER_TAG_CREATE_UPDATE_DELETE' isHovered={ isHovered } /> </> ); });необходимо при нажатии на TableEditTagsCell переводить tablerow в фокусное состояние
при этом код TableEditTagsCell: import { MouseEvent, ReactElement, ReactNode, useCallback, useEffect, useMemo, useState } from 'react'; import { Box, MenuItem, Popover, SxProps, Theme, Typography } from '@mui/material'; import { useTranslation } from 'react-i18next'; import { IconButton, parserSx, TableCell, TextField } from 'sigur-ui-kit'; import { observer } from 'mobx-react-lite'; import { ReactComponent as FavoritesIcon } from '../../../assets/svg/favorites.svg'; import { ReactComponent as EmptyFavoritesIcon } from '../../../assets/svg/empty_favorites.svg'; import { ReactComponent as PlusIcon } from '../../../assets/svg/add.svg'; import { ReactComponent as CloseIcon } from '../../../assets/svg/close.svg'; import { ReactComponent as SaveIcon } from '../../../assets/svg/ok.svg'; import { WithPermission } from '../../../components/custom'; import { RolePermission, Tag } from '../../../features'; import { profileStore } from '../../../stores'; import { useDeleteModal } from '../../../hooks'; import { useClasses } from './TableEditTagsCell.style'; import { TagRow } from './TagRow';
interface TableEditTagsCellProps { updateAllTags?: (tags: Tag[], unAssignTagIds?: Tag[], assignTagIds?: Tag[], id?: number) => Promise; entityId?: number; icon?: ReactNode; withCheckbox?: boolean; isHovered?: boolean; editPermission: keyof RolePermission; assignPermission: keyof RolePermission; getTag?: () => Promise<Tag[]>; mapOfAllTags?: Map<number, Tag>; mapOfAssignedTagIds?: Map<number, number[]>; allTags?: Tag[]; sx?: SxProps; iconSx?: SxProps; }
interface TagWithCheck { tag: Tag; checked: boolean; }
export const TableEditTagsCell = observer((props: TableEditTagsCellProps): ReactElement => { const { mapOfAllTags, icon, withCheckbox = true, assignPermission, editPermission, isHovered, entityId, updateAllTags, mapOfAssignedTagIds, allTags: tagsWithSystem, sx, iconSx } = props;
const allTags = useMemo(() => tagsWithSystem?.filter(({ id }) => id !== -1), [tagsWithSystem]); const [isEdit, setIsEdit] = useState<boolean>(false); const [onEdit, setOnEdit] = useState<string>(''); const [newValue, setNewValue] = useState<string>(''); const [baseTags, setBaseTags] = useState<TagWithCheck[]>(); const [tags, setTags] = useState<TagWithCheck[]>(); const [tagsOfCurrentEntity, setTagsOfCurrentEntity] = useState<Tag[]>(); const openDeleteModal = useDeleteModal(); const classes = useClasses(); const { t } = useTranslation(); const { validatePermission } = profileStore; const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null); const handleClose = useCallback((): void => { setAnchorEl(null); }, []); const openMenu = useCallback((e: MouseEvent<HTMLElement>): void => { e.stopPropagation(); setAnchorEl(e.currentTarget); }, []); const handleEditable = useCallback((tag?: Tag): void => { if (!!tag) { setOnEdit(tag.name); setIsEdit(true); } else { setOnEdit(''); setIsEdit(false); } }, []); const editable = useMemo(() => validatePermission([editPermission]), [editPermission, validatePermission]); const updateStateWithTags = (tag: Tag, index: number, checked?: boolean): void => { setTags(prev => { if (!prev) { return; } const copy = [...prev]; const pointer = copy[index]; if (pointer) { pointer.tag = tag; pointer.checked = checked !== undefined ? checked : pointer.checked; } return copy; }); }; const handleDeleteTag = useCallback((index: number): void => { openDeleteModal({ onSubmit: (): Promise<void> => Promise.resolve().then(() => { setTags(prev => { if (!prev) { return; } const copy = [...prev]; copy.splice(index, 1); return copy; }); }), title: t('Delete list?'), }); }, [openDeleteModal, t]); const handleAddTag = (tag: Tag): void => { setTags(prev => { if (!prev) { return; } return [...prev, { tag: tag, checked: false }]; }); }; const checkForRowDuplicates = useCallback((tagName: string, rowIndex: number): boolean => { return !!tags?.some((value, index) => value.tag.name === tagName && index !== rowIndex); }, [tags]); const onClosePopover = useCallback((e: MouseEvent): void => { e.stopPropagation(); if (tags) { if (!entityId) { updateAllTags?.(tags.map(tag => tag.tag)); } else { let assigTagIds: Tag[] = []; let unAssigTagIds: Tag[] = []; tags.forEach(tag => { if (tag.checked) { if (tag.tag.id < 0) { // new tags assigTagIds.push(tag.tag); } else { // without new tags const baseChecked = baseTags?.filter(baseTag => baseTag.tag.id === tag.tag.id); if (baseChecked && baseChecked[0]?.checked !== tag.checked) { assigTagIds.push(tag.tag); } } } else { if (tag.tag.id < 0) { // new tags unAssigTagIds.push(tag.tag); } else { // without new tags const baseChecked = baseTags?.filter(baseTag => baseTag.tag.id === tag.tag.id); if (baseChecked && baseChecked[0]?.checked !== tag.checked) { unAssigTagIds.push(tag.tag); } } } }); updateAllTags?.(tags.map(tag => tag.tag), unAssigTagIds, assigTagIds, entityId); } } setIsEdit(false); setOnEdit(''); handleClose(); }, [baseTags, entityId, handleClose, tags, updateAllTags]); useEffect(() => { if (entityId === undefined) { const baseAllTagsWithCheck = allTags?.map(tag => { return { tag, checked: false }; }); setBaseTags(baseAllTagsWithCheck); setTags(baseAllTagsWithCheck); return; } const baseAllTagsWithCheck = allTags?.map(tag => { return { tag, checked: !!mapOfAssignedTagIds?.get(entityId)?.some(id => id === tag.id) }; }); const allTagsWithCheck = allTags?.map(tag => { return { tag, checked: !!mapOfAssignedTagIds?.get(entityId)?.some(id => id === tag.id) }; }); if (entityId) { const arrayOfTagsCurrentEntity = mapOfAssignedTagIds?.get(entityId)?.reduce((acc: Tag[], cur: number): Tag[] => { const tag = mapOfAllTags?.get(cur); if (tag) { acc.push(tag); } return acc; }, []); setTagsOfCurrentEntity(arrayOfTagsCurrentEntity); } setBaseTags(baseAllTagsWithCheck); setTags(allTagsWithCheck); }, [allTags, entityId, mapOfAllTags, mapOfAssignedTagIds]); return ( <TableCell sx={ parserSx(classes.wrap, sx) } > <WithPermission permission={ [assignPermission, editPermission] }> <Box sx={ iconSx } onClick={ !!icon ? openMenu : undefined } > { icon || ( <IconButton onClick={ openMenu } sx={ classes.icon } disableRipple > { (isHovered) && ( tagsOfCurrentEntity?.length ? <FavoritesIcon/> : <EmptyFavoritesIcon/> ) } </IconButton> ) } </Box> <Popover anchorEl={ anchorEl } open={ Boolean(anchorEl) } onClose={ onClosePopover } sx={ classes.menu } onClick={ (e): void => e.stopPropagation() } > <WithPermission permission={ editPermission }> <MenuItem onClick={ (e): void => { e.stopPropagation(); setIsEdit(true); } } sx={ classes.addMenuItem } disableRipple > { isEdit && !onEdit ? ( <> <TextField color='primary' size='small' disabled={ !isEdit } sx={ parserSx(classes.listName, classes.editable) } value={ newValue } onChange={ (e): void => setNewValue(e.target.value) } onClick={ (e): void => e.stopPropagation() } autoFocus /> <Box> <IconButton size='small' disableRipple onClick={ (e): void => { if (newValue === '') { return; } e.stopPropagation(); if (tags?.map(item => item.tag.name).some(value => value === newValue)) { return; } handleAddTag(new Tag({ id: -1 * Math.random(), name: newValue })); setNewValue(''); setIsEdit(false); } } sx={ classes.icon } > <SaveIcon/> </IconButton> <IconButton size='small' disableRipple onClick={ (e): void => { e.stopPropagation(); setNewValue(''); setIsEdit(false); } } sx={ classes.icon } > <CloseIcon/> </IconButton> </Box> </> ) : ( <> <PlusIcon /> <Typography variant='body2' > { t('Create a new list') } </Typography> </> ) } </MenuItem> </WithPermission> { tags?.map((tagWithCheckbox, index) => { if (tagWithCheckbox.tag.name === onEdit) { return ( <TagRow tag={ tagWithCheckbox.tag } checked={ tagWithCheckbox.checked } key={ tagWithCheckbox.tag.getKey() } withCheckbox={ withCheckbox } index={ index } handleDeleteTag={ handleDeleteTag } isEdit={ isEdit } handleEditable={ handleEditable } editable={ editable } updateStateWithTags={ updateStateWithTags } checkForRowDuplicates={ checkForRowDuplicates } /> ); } else { return ( <TagRow tag={ tagWithCheckbox.tag } checked={ tagWithCheckbox.checked } editable={ editable } key={ tagWithCheckbox.tag.getKey() } withCheckbox={ withCheckbox } index={ index } handleDeleteTag={ handleDeleteTag } isEdit={ false } handleEditable={ handleEditable } updateStateWithTags={ updateStateWithTags } checkForRowDuplicates={ checkForRowDuplicates } /> ); } } ) } </Popover> </WithPermission> </TableCell> );}); как это реализовать
- Assistant
Ниже ‑ один из самых простых способов «поставить в фокус» всю строку, когда пользователь кликает по
TableEditTagsCell, ничего не трогая вreact-virtuosoи не переписывая компоненты изsigur-ui-kit.Идея:
- Сделать каждую
<tr>фокусируемой (tabIndex={-1}). - По клику в
TableEditTagsCellнайти ближайшую строку (closest('tr')) и вызватьfocus(). - Задать CSS-стиль для состояния
:focus, чтобы визуально отличать «сфокусированную» строку от остальных.
Так мы обойдемся без дополнительных сторов, контекстов и пропов.
1. Делаем строку фокусируемой
В месте, где вы формируете строку (у вас это кастомный
TableRow), добавьтеtabIndex={-1}.
Точка входа — рендер пропTableRowвFixedTable.// FixedTable.tsx – кусок кода, где формируется <TableRow> <TableRow tabIndex={-1} // ① строка теперь может получить focus() sx={ parserSx( itemProps.style, isSelected ? classes.selectedTableRow : classes.tableRow, sx ) } { ...itemProps } { ...renderProps } />Если в
sigur-ui-kit/TableRowнетforwardRef, добавьте его или оберните в свой компонент-адаптер; главное, чтобы итоговый DOM-элемент былtrи имелtabIndex.
2. Фокусируем строку из
TableEditTagsCellВнутри
TableEditTagsCellлюбая «точка входа» (у вас этоopenMenu) уже перехватываетMouseEvent.
После того как вы вызываетеopenMenu, просто найдите ближайший<tr>и дайте ему фокус:// TableEditTagsCell.tsx (фрагмент) const openMenu = useCallback((e: MouseEvent<HTMLElement>): void => { e.stopPropagation(); // ① переводим строку (tr) в фокус const tr = (e.target as HTMLElement).closest('tr') as HTMLTableRowElement | null; tr?.focus(); // ② открываем Popover setAnchorEl(e.currentTarget); }, []);У вас несколько обработчиков (
onClickнаIconButton, наBox, т.д.).
Главное — вставить этотclosest('tr')?.focus()в самый ранний из них, чтобы он срабатывал независимо от того, где именно пользователь кликнул внутри ячейки.
3. Визуальное выделение сфокусированной строки
Добавьте стиль для любого класса строки (например,
.tableRow) в состоянии:focus:/* FixedTable.css или sass-модуль */ .tableRow:focus { outline: none; /* убираем стандартную пунктирную рамку */ background: #e3f2fd; /* подсветка, какую захотите */ }При желании можно переопределить цвет через MUI-тему (
theme.palette.action.focus).
4. (Необязательный) прокрутка к строке
Если нужно гарантированно «прокрутить» таблицу так, чтобы сфокусированная строка оказалась в окне,
react-virtuosoуже сделает это автоматически, потому чтоfocus()вызывается на реальном DOM-элементе, который виден в виртуализированном списке. Если строка отрендерена (а она отрендерена, раз по ней кликнули), прокрутка не требуется.
Итого
•
tabIndex={-1}на<tr>→ строка может получать фокус.
•closest('tr').focus()в клике поTableEditTagsCell→ переносим фокус.
•:focus-CSS → визуальная подсветка.Без MobX-сторов, без дополнительного состояния — только нативный
focus()и CSS. - Сделать каждую
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.