break-word обрезает строку по словам, как обрезать по… · The Chat Archive
Explore break-word обрезает строку по словам, как обрезать по символам Save Share Download ▾ ReportFrom a Chatbot Arena battle The same person sent this prompt to two anonymous models at once. Compare it with o3-2025-04-16 ’s answer. break-word обрезает строку по словам, как обрезать по символам
AssistantCopy response
Свойство может сбивать с толку — оно , как может показаться. Чтобы , а не по словам, нужно использовать CSS-свойство:
Copy first prompt Copy first response
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 2 (4 messages)
Language en
Added to archive Nov 16, 2026
ID 01m7jf63ayh7jweh32x61mw1j1Source & license Imported from LMArena Human Preference 140K (source ). Imported records earn no Research Points.
Upstream record: eaa44013-1aed-4bea-bfdc-630785d29cff:a
Chiang et al., Chatbot Arena: An Open Platform for Evaluating LLMs by Human Preference (2024). LMArena 140K preference release.
License: Prompts CC-BY-4.0; outputs governed by provider terms
Dataset releases Not yet included in a published release.
word-break: break-word
не разрывает строку по символам
обрезать строку по символам
✅ Правильное решение: css Copy code
word-break: break-all;
🔍 Объяснение: Свойство Что делает word-break: break-word(на деле) разрешает перенос слов на границе контейнера , если это нужно, но старается сохранять слова целиком word-break: break-allРазрывает строку по символам, не обращая внимания на границы слов overflow-wrap: break-wordПозволяет разрывать слова, только если они не помещаются полностью, но по границе слова
Пример использования:
❌ По умолчанию или break-word — слово не перенесётся посимвольно: css Copy code
.long-text {
width: 150px;
word-break: break-word;
border: 1px solid black;
}
👉 Результат: длинное слово может вылезти за пределы контейнера.
✅ Для переноса по символам: css Copy code
.long-text {
width: 150px;
word-break: break-all;
border: 1px solid black;
}
👉 Результат: слово будет переноситься по каждому символу , если не помещается.
✨ Дополнительно (если нужно обрезание и многоточие): css Copy code
.ellipsis-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Если используешь white-space: nowrap — перенос вообще отключается, но с ellipsis, строка обрежется и покажет ....
💡 Пример в HTML: html Copy code
<div style="width: 150px; word-break: break-all; border: 1px solid red;">
Supercalifragilisticexpialidocious
</div>
Эта строка будет переноситься по символам , точно так, как ты хочешь.
Если тебе нужно разное поведение для обычного текста и специальных слов — можно комбинировать стили с учетом контекста.
есть компонент 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;
// }, []);
Show full message · 629 lines AssistantCopy response
Чтобы установить "фокусное состояние" строки таблицы (TableRow) при клике на TableEditTagsCell , необходимо:
🔧 Цель
Когда пользователь кликает по иконке в TableEditTagsCell, строка (SchedulesTableRow) должна визуально выделиться (например, подсветиться другим цветом), то есть — перейти в фокусное состояние .
✅ Решение: Передача isFocused в TableRow
Нужно:
Создать состояние текущего фокуса в родителе (в компоненте FixedTable).
Передать "фокус" текущей строке по id.
Обработать клик из TableEditTagsCell, чтобы переключить фокус.
Применить стили к строке, если она фокусная.
🔁 Этапы пошагово
1. Добавляем состояние focusedRowId в FixedTable
В FixedTable в useState добавим:
tsx Copy code
const [focusedRowId, setFocusedRowId] = useState<number | null>(null);
И передаём focusedRowId и setFocusedRowId в renderRow:
tsx Copy code
itemContent={(index, item) => renderRow(index, item, focusedRowId, setFocusedRowId)}
📌 Обнови сигнатуру renderRow в props (и его вызовы):
ts Copy code
renderRow: (index: number, element: T, focusedId?: number | null, setFocused?: (id: number | null) => void) => ReactNode;
2. В SchedulesTableRow получаем эти параметры
Расширим SchedulesTableRowProps:
ts Copy code
interface SchedulesTableRowProps {
schedule: Schedule;
isSelected?: boolean;
handleChangeSelect: (schedule: Schedule) => void;
// ⚠ Добавляем:
isFocused?: boolean;
setFocus?: (id: number | null) => void;
// ... другие поля
}
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;
code Copy code
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;
code Copy code
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>
);
3. Внутри SchedulesTableRow передаём setFocus в TableEditTagsCell tsx Copy code
<TableEditTagsCell
// ... другие пропсы
onFocusRow={(): void => setFocus?.(schedule.id)} // <--- Добавлено
/>
4. Расширим TableEditTagsCellProps, добавим onFocusRow ts Copy code
interface TableEditTagsCellProps {
// ... другие пропсы
onFocusRow?: () => void;
}
5. В TableEditTagsCell вызываем onFocusRow при открытии Измени функцию openMenu, чтобы вызвать onFocusRow:
tsx Copy code
const openMenu = useCallback((e: MouseEvent<HTMLElement>): void => {
e.stopPropagation();
setAnchorEl(e.currentTarget);
props.onFocusRow?.(); // <--- важное добавление
}, [props]);
6. Добавляем стиль для фокусной строки Например, анимируем рамку или фон в SchedulesTableRow:
tsx Copy code
<TableCell
ref={ hoverRef }
sx={ parserSx(
classes.cell,
classes.nameCell,
isFocused && classes.focusedRow // если фокус
) }
>
<TypographyOverflow variant='body2' fontWeight={500}>
{ schedule.id === -1 ? t('Always (default schedule)') : schedule.name }
</TypographyOverflow>
</TableCell>
7. В стилях (.style файл) добавь: ts Copy code
focusedRow: {
backgroundColor: '#e0edff',
transition: 'background-color 0.3s ease',
}
📌 Можно сделать глобальную обводку строки вместо изменения ячейки, если использовать флаг sx на уровне TableRow, когда ты его создаёшь в обёртке observer в FixedTable.
✅ Результат
При клике на иконку ("редактировать теги") строка подсвечивается как активная (фокусная).
Фокус сбрасывается при повторном клике или можно реализовать отдельную кнопку/условие для снятия фокуса (setFocusedRowId(null)).
💡 Дополнительно
Можешь положить focusedRowId в MobX-стор, если хочешь масштабировать поведение или запоминать фокус между табами.
Если таблица интерактивна, полезно сбрасывать focusedRowId, когда пользователь кликает вне строки.
Если нужно — могу прислать diff патч или отрефакторенный полный код этого изменения 👇.