Modernize MaxSizedBox to use <Box maxHeight> and ResizeObservers (#16565)

This commit is contained in:
Jacob Richman
2026-01-13 20:22:10 -08:00
committed by GitHub
parent 4afd3741df
commit 933bc5774f
16 changed files with 482 additions and 1436 deletions

View File

@@ -5,19 +5,14 @@
*/
import { render } from '../../../test-utils/render.js';
import { waitFor } from '../../../test-utils/async.js';
import { OverflowProvider } from '../../contexts/OverflowContext.js';
import { MaxSizedBox, setMaxSizedBoxDebugging } from './MaxSizedBox.js';
import { MaxSizedBox } from './MaxSizedBox.js';
import { Box, Text } from 'ink';
import { describe, it, expect } from 'vitest';
describe('<MaxSizedBox />', () => {
// Make sure MaxSizedBox logs errors on invalid configurations.
// This is useful for debugging issues with the component.
// It should be set to false in production for performance and to avoid
// cluttering the console if there are ignorable issues.
setMaxSizedBoxDebugging(true);
it('renders children without truncation when they fit', () => {
it('renders children without truncation when they fit', async () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={10}>
@@ -27,53 +22,105 @@ describe('<MaxSizedBox />', () => {
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals('Hello, World!');
await waitFor(() => expect(lastFrame()).toContain('Hello, World!'));
expect(lastFrame()).toMatchSnapshot();
unmount();
});
it('hides lines when content exceeds maxHeight', () => {
it('hides lines when content exceeds maxHeight', async () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={2}>
<Box>
<Box flexDirection="column">
<Text>Line 1</Text>
</Box>
<Box>
<Text>Line 2</Text>
</Box>
<Box>
<Text>Line 3</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals(`... first 2 lines hidden ...
Line 3`);
await waitFor(() =>
expect(lastFrame()).toContain('... first 2 lines hidden ...'),
);
expect(lastFrame()).toMatchSnapshot();
unmount();
});
it('hides lines at the end when content exceeds maxHeight and overflowDirection is bottom', () => {
it('hides lines at the end when content exceeds maxHeight and overflowDirection is bottom', async () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={2} overflowDirection="bottom">
<Box>
<Box flexDirection="column">
<Text>Line 1</Text>
</Box>
<Box>
<Text>Line 2</Text>
</Box>
<Box>
<Text>Line 3</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals(`Line 1
... last 2 lines hidden ...`);
await waitFor(() =>
expect(lastFrame()).toContain('... last 2 lines hidden ...'),
);
expect(lastFrame()).toMatchSnapshot();
unmount();
});
it('wraps text that exceeds maxWidth', () => {
it('shows plural "lines" when more than one line is hidden', async () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={2}>
<Box flexDirection="column">
<Text>Line 1</Text>
<Text>Line 2</Text>
<Text>Line 3</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
await waitFor(() =>
expect(lastFrame()).toContain('... first 2 lines hidden ...'),
);
expect(lastFrame()).toMatchSnapshot();
unmount();
});
it('shows singular "line" when exactly one line is hidden', async () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={2} additionalHiddenLinesCount={1}>
<Box flexDirection="column">
<Text>Line 1</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
await waitFor(() =>
expect(lastFrame()).toContain('... first 1 line hidden ...'),
);
expect(lastFrame()).toMatchSnapshot();
unmount();
});
it('accounts for additionalHiddenLinesCount', async () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={2} additionalHiddenLinesCount={5}>
<Box flexDirection="column">
<Text>Line 1</Text>
<Text>Line 2</Text>
<Text>Line 3</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
await waitFor(() =>
expect(lastFrame()).toContain('... first 7 lines hidden ...'),
);
expect(lastFrame()).toMatchSnapshot();
unmount();
});
it('wraps text that exceeds maxWidth', async () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={10} maxHeight={5}>
@@ -84,325 +131,66 @@ Line 3`);
</OverflowProvider>,
);
expect(lastFrame()).equals(`This is a
long line
of text`);
await waitFor(() => expect(lastFrame()).toContain('This is a'));
expect(lastFrame()).toMatchSnapshot();
unmount();
});
it('handles mixed wrapping and non-wrapping segments', () => {
const multilineText = `This part will wrap around.
And has a line break.
Leading spaces preserved.`;
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={20} maxHeight={20}>
<Box>
<Text>Example</Text>
</Box>
<Box>
<Text>No Wrap: </Text>
<Text wrap="wrap">{multilineText}</Text>
</Box>
<Box>
<Text>Longer No Wrap: </Text>
<Text wrap="wrap">This part will wrap around.</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals(
`Example
No Wrap: This part
will wrap
around.
And has a
line break.
Leading
spaces
preserved.
Longer No Wrap: This
part
will
wrap
arou
nd.`,
);
unmount();
});
it('handles words longer than maxWidth by splitting them', () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={5} maxHeight={5}>
<Box>
<Text wrap="wrap">Supercalifragilisticexpialidocious</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals(`... …
istic
expia
lidoc
ious`);
unmount();
});
it('does not truncate when maxHeight is undefined', () => {
it('does not truncate when maxHeight is undefined', async () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={undefined}>
<Box>
<Box flexDirection="column">
<Text>Line 1</Text>
</Box>
<Box>
<Text>Line 2</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals(`Line 1
Line 2`);
await waitFor(() => expect(lastFrame()).toContain('Line 1'));
expect(lastFrame()).toMatchSnapshot();
unmount();
});
it('shows plural "lines" when more than one line is hidden', () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={2}>
<Box>
<Text>Line 1</Text>
</Box>
<Box>
<Text>Line 2</Text>
</Box>
<Box>
<Text>Line 3</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals(`... first 2 lines hidden ...
Line 3`);
unmount();
});
it('shows plural "lines" when more than one line is hidden and overflowDirection is bottom', () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={2} overflowDirection="bottom">
<Box>
<Text>Line 1</Text>
</Box>
<Box>
<Text>Line 2</Text>
</Box>
<Box>
<Text>Line 3</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals(`Line 1
... last 2 lines hidden ...`);
unmount();
});
it('renders an empty box for empty children', () => {
it('renders an empty box for empty children', async () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={10}></MaxSizedBox>
</OverflowProvider>,
);
// Expect an empty string or a box with nothing in it.
// Ink renders an empty box as an empty string.
expect(lastFrame()).equals('');
// Use waitFor to ensure ResizeObserver has a chance to run
await waitFor(() => expect(lastFrame()).toBeDefined());
expect(lastFrame()?.trim()).equals('');
unmount();
});
it('wraps text with multi-byte unicode characters correctly', () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={5} maxHeight={5}>
<Box>
<Text wrap="wrap"></Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
// "你好" has a visual width of 4. "世界" has a visual width of 4.
// With maxWidth=5, it should wrap after the second character.
expect(lastFrame()).equals(`你好
世界`);
unmount();
});
it('wraps text with multi-byte emoji characters correctly', () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={5} maxHeight={5}>
<Box>
<Text wrap="wrap">🐶🐶🐶🐶🐶</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
// Each "🐶" has a visual width of 2.
// With maxWidth=5, it should wrap every 2 emojis.
expect(lastFrame()).equals(`🐶🐶
🐶🐶
🐶`);
unmount();
});
it('falls back to an ellipsis when width is extremely small', () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={2} maxHeight={2}>
<Box>
<Text>No</Text>
<Text wrap="wrap">wrap</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals('N…');
unmount();
});
it('truncates long non-wrapping text with ellipsis', () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={3} maxHeight={2}>
<Box>
<Text>ABCDE</Text>
<Text wrap="wrap">wrap</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals('AB…');
unmount();
});
it('truncates non-wrapping text containing line breaks', () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={3} maxHeight={2}>
<Box>
<Text>{'A\nBCDE'}</Text>
<Text wrap="wrap">wrap</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals(`A\n…`);
unmount();
});
it('truncates emoji characters correctly with ellipsis', () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={3} maxHeight={2}>
<Box>
<Text>🐶🐶🐶</Text>
<Text wrap="wrap">wrap</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals(`🐶…`);
unmount();
});
it('shows ellipsis for multiple rows with long non-wrapping text', () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={3} maxHeight={3}>
<Box>
<Text>AAA</Text>
<Text wrap="wrap">first</Text>
</Box>
<Box>
<Text>BBB</Text>
<Text wrap="wrap">second</Text>
</Box>
<Box>
<Text>CCC</Text>
<Text wrap="wrap">third</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals(`AA…\nBB…\nCC…`);
unmount();
});
it('accounts for additionalHiddenLinesCount', () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={2} additionalHiddenLinesCount={5}>
<Box>
<Text>Line 1</Text>
</Box>
<Box>
<Text>Line 2</Text>
</Box>
<Box>
<Text>Line 3</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
// 1 line is hidden by overflow, 5 are additionally hidden.
expect(lastFrame()).equals(`... first 7 lines hidden ...
Line 3`);
unmount();
});
it('handles React.Fragment as a child', () => {
it('handles React.Fragment as a child', async () => {
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={10}>
<>
<Box>
<Box flexDirection="column">
<>
<Text>Line 1 from Fragment</Text>
</Box>
<Box>
<Text>Line 2 from Fragment</Text>
</Box>
</>
<Box>
</>
<Text>Line 3 direct child</Text>
</Box>
</MaxSizedBox>
</OverflowProvider>,
);
expect(lastFrame()).equals(`Line 1 from Fragment
Line 2 from Fragment
Line 3 direct child`);
await waitFor(() => expect(lastFrame()).toContain('Line 1 from Fragment'));
expect(lastFrame()).toMatchSnapshot();
unmount();
});
it('clips a long single text child from the top', () => {
it('clips a long single text child from the top', async () => {
const THIRTY_LINES = Array.from(
{ length: 30 },
(_, i) => `Line ${i + 1}`,
).join('\n');
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={10}>
<MaxSizedBox maxWidth={80} maxHeight={10} overflowDirection="top">
<Box>
<Text>{THIRTY_LINES}</Text>
</Box>
@@ -410,21 +198,18 @@ Line 3 direct child`);
</OverflowProvider>,
);
const expected = [
'... first 21 lines hidden ...',
...Array.from({ length: 9 }, (_, i) => `Line ${22 + i}`),
].join('\n');
expect(lastFrame()).equals(expected);
await waitFor(() =>
expect(lastFrame()).toContain('... first 21 lines hidden ...'),
);
expect(lastFrame()).toMatchSnapshot();
unmount();
});
it('clips a long single text child from the bottom', () => {
it('clips a long single text child from the bottom', async () => {
const THIRTY_LINES = Array.from(
{ length: 30 },
(_, i) => `Line ${i + 1}`,
).join('\n');
const { lastFrame, unmount } = render(
<OverflowProvider>
<MaxSizedBox maxWidth={80} maxHeight={10} overflowDirection="bottom">
@@ -435,12 +220,10 @@ Line 3 direct child`);
</OverflowProvider>,
);
const expected = [
...Array.from({ length: 9 }, (_, i) => `Line ${i + 1}`),
'... last 21 lines hidden ...',
].join('\n');
expect(lastFrame()).equals(expected);
await waitFor(() =>
expect(lastFrame()).toContain('... last 21 lines hidden ...'),
);
expect(lastFrame()).toMatchSnapshot();
unmount();
});
});

View File

@@ -4,15 +4,11 @@
* SPDX-License-Identifier: Apache-2.0
*/
import React, { Fragment, useEffect, useId } from 'react';
import { Box, Text } from 'ink';
import stringWidth from 'string-width';
import type React from 'react';
import { useCallback, useEffect, useId, useRef, useState } from 'react';
import { Box, Text, ResizeObserver, type DOMElement } from 'ink';
import { theme } from '../../semantic-colors.js';
import { toCodePoints } from '../../utils/textUtils.js';
import { useOverflowActions } from '../../contexts/OverflowContext.js';
import { debugLogger } from '@google/gemini-cli-core';
let enableDebugLog = false;
/**
* Minimum height for the MaxSizedBox component.
@@ -21,42 +17,10 @@ let enableDebugLog = false;
*/
export const MINIMUM_MAX_HEIGHT = 2;
export function setMaxSizedBoxDebugging(value: boolean) {
enableDebugLog = value;
}
function debugReportError(message: string, element: React.ReactNode) {
if (!enableDebugLog) return;
if (!React.isValidElement(element)) {
debugLogger.warn(
message,
`Invalid element: '${String(element)}' typeof=${typeof element}`,
);
return;
}
let sourceMessage = '<Unknown file>';
try {
const elementWithSource = element as {
_source?: { fileName?: string; lineNumber?: number };
};
const fileName = elementWithSource._source?.fileName;
const lineNumber = elementWithSource._source?.lineNumber;
sourceMessage = fileName ? `${fileName}:${lineNumber}` : '<Unknown file>';
} catch (error) {
debugLogger.warn('Error while trying to get file name:', error);
}
debugLogger.warn(
message,
`${String(element.type)}. Source: ${sourceMessage}`,
);
}
interface MaxSizedBoxProps {
children?: React.ReactNode;
maxWidth?: number;
maxHeight: number | undefined;
maxHeight?: number;
overflowDirection?: 'top' | 'bottom';
additionalHiddenLinesCount?: number;
}
@@ -64,41 +28,6 @@ interface MaxSizedBoxProps {
/**
* A React component that constrains the size of its children and provides
* content-aware truncation when the content exceeds the specified `maxHeight`.
*
* `MaxSizedBox` requires a specific structure for its children to correctly
* measure and render the content:
*
* 1. **Direct children must be `<Box>` elements.** Each `<Box>` represents a
* single row of content.
* 2. **Row `<Box>` elements must contain only `<Text>` elements.** These
* `<Text>` elements can be nested and there are no restrictions to Text
* element styling other than that non-wrapping text elements must be
* before wrapping text elements.
*
* **Constraints:**
* - **Box Properties:** Custom properties on the child `<Box>` elements are
* ignored. In debug mode, runtime checks will report errors for any
* unsupported properties.
* - **Text Wrapping:** Within a single row, `<Text>` elements with no wrapping
* (e.g., headers, labels) must appear before any `<Text>` elements that wrap.
* - **Element Types:** Runtime checks will warn if unsupported element types
* are used as children.
*
* @example
* <MaxSizedBox maxWidth={80} maxHeight={10}>
* <Box>
* <Text>This is the first line.</Text>
* </Box>
* <Box>
* <Text color="cyan" wrap="truncate">Non-wrapping Header: </Text>
* <Text>This is the rest of the line which will wrap if it's too long.</Text>
* </Box>
* <Box>
* <Text>
* Line 3 with <Text color="yellow">nested styled text</Text> inside of it.
* </Text>
* </Box>
* </MaxSizedBox>
*/
export const MaxSizedBox: React.FC<MaxSizedBoxProps> = ({
children,
@@ -109,49 +38,50 @@ export const MaxSizedBox: React.FC<MaxSizedBoxProps> = ({
}) => {
const id = useId();
const { addOverflowingId, removeOverflowingId } = useOverflowActions() || {};
const observerRef = useRef<ResizeObserver | null>(null);
const [contentHeight, setContentHeight] = useState(0);
const laidOutStyledText: StyledText[][] = [];
const targetMaxHeight = Math.max(
Math.round(maxHeight ?? Number.MAX_SAFE_INTEGER),
MINIMUM_MAX_HEIGHT,
const onRefChange = useCallback(
(node: DOMElement | null) => {
if (observerRef.current) {
observerRef.current.disconnect();
observerRef.current = null;
}
if (node && maxHeight !== undefined) {
const observer = new ResizeObserver((entries) => {
const entry = entries[0];
if (entry) {
setContentHeight(entry.contentRect.height);
}
});
observer.observe(node);
observerRef.current = observer;
}
},
[maxHeight],
);
if (maxWidth === undefined) {
throw new Error('maxWidth must be defined when maxHeight is set.');
}
function visitRows(element: React.ReactNode) {
if (!React.isValidElement<{ children?: React.ReactNode }>(element)) {
return;
}
const effectiveMaxHeight =
maxHeight !== undefined
? Math.max(Math.round(maxHeight), MINIMUM_MAX_HEIGHT)
: undefined;
if (element.type === Fragment) {
React.Children.forEach(element.props.children, visitRows);
return;
}
if (element.type === Box) {
layoutInkElementAsStyledText(element, maxWidth!, laidOutStyledText);
return;
}
debugReportError('MaxSizedBox children must be <Box> elements', element);
}
React.Children.forEach(children, visitRows);
const contentWillOverflow =
(targetMaxHeight !== undefined &&
laidOutStyledText.length > targetMaxHeight) ||
const isOverflowing =
(effectiveMaxHeight !== undefined && contentHeight > effectiveMaxHeight) ||
additionalHiddenLinesCount > 0;
// If we're overflowing, we need to hide at least 1 line for the message.
const visibleContentHeight =
contentWillOverflow && targetMaxHeight !== undefined
? targetMaxHeight - 1
: targetMaxHeight;
isOverflowing && effectiveMaxHeight !== undefined
? effectiveMaxHeight - 1
: effectiveMaxHeight;
const hiddenLinesCount =
visibleContentHeight !== undefined
? Math.max(0, laidOutStyledText.length - visibleContentHeight)
? Math.max(0, contentHeight - visibleContentHeight)
: 0;
const totalHiddenLines = hiddenLinesCount + additionalHiddenLinesCount;
useEffect(() => {
@@ -166,36 +96,40 @@ export const MaxSizedBox: React.FC<MaxSizedBoxProps> = ({
};
}, [id, totalHiddenLines, addOverflowingId, removeOverflowingId]);
const visibleStyledText =
hiddenLinesCount > 0
? overflowDirection === 'top'
? laidOutStyledText.slice(hiddenLinesCount, laidOutStyledText.length)
: laidOutStyledText.slice(0, visibleContentHeight)
: laidOutStyledText;
if (effectiveMaxHeight === undefined) {
return (
<Box flexDirection="column" width={maxWidth}>
{children}
</Box>
);
}
const visibleLines = visibleStyledText.map((line, index) => (
<Box key={index}>
{line.length > 0 ? (
line.map((segment, segIndex) => (
<Text key={segIndex} {...segment.props}>
{segment.text}
</Text>
))
) : (
<Text> </Text>
)}
</Box>
));
const offset =
hiddenLinesCount > 0 && overflowDirection === 'top' ? -hiddenLinesCount : 0;
return (
<Box flexDirection="column" width={maxWidth} flexShrink={0}>
<Box
flexDirection="column"
width={maxWidth}
maxHeight={effectiveMaxHeight}
flexShrink={0}
>
{totalHiddenLines > 0 && overflowDirection === 'top' && (
<Text color={theme.text.secondary} wrap="truncate">
... first {totalHiddenLines} line{totalHiddenLines === 1 ? '' : 's'}{' '}
hidden ...
</Text>
)}
{visibleLines}
<Box flexDirection="column" overflow="hidden" flexGrow={1}>
<Box
flexDirection="column"
ref={onRefChange}
flexShrink={0}
marginTop={offset}
>
{children}
</Box>
</Box>
{totalHiddenLines > 0 && overflowDirection === 'bottom' && (
<Text color={theme.text.secondary} wrap="truncate">
... last {totalHiddenLines} line{totalHiddenLines === 1 ? '' : 's'}{' '}
@@ -205,423 +139,3 @@ export const MaxSizedBox: React.FC<MaxSizedBoxProps> = ({
</Box>
);
};
// Define a type for styled text segments
interface StyledText {
text: string;
props: Record<string, unknown>;
}
/**
* Single row of content within the MaxSizedBox.
*
* A row can contain segments that are not wrapped, followed by segments that
* are. This is a minimal implementation that only supports the functionality
* needed today.
*/
interface Row {
noWrapSegments: StyledText[];
segments: StyledText[];
}
/**
* Flattens the child elements of MaxSizedBox into an array of `Row` objects.
*
* This function expects a specific child structure to function correctly:
* 1. The top-level child of `MaxSizedBox` should be a single `<Box>`. This
* outer box is primarily for structure and is not directly rendered.
* 2. Inside the outer `<Box>`, there should be one or more children. Each of
* these children must be a `<Box>` that represents a row.
* 3. Inside each "row" `<Box>`, the children must be `<Text>` components.
*
* The structure should look like this:
* <MaxSizedBox>
* <Box> // Row 1
* <Text>...</Text>
* <Text>...</Text>
* </Box>
* <Box> // Row 2
* <Text>...</Text>
* </Box>
* </MaxSizedBox>
*
* It is an error for a <Text> child without wrapping to appear after a
* <Text> child with wrapping within the same row Box.
*
* @param element The React node to flatten.
* @returns An array of `Row` objects.
*/
function visitBoxRow(element: React.ReactNode): Row {
if (
!React.isValidElement<{ children?: React.ReactNode }>(element) ||
element.type !== Box
) {
debugReportError(
`All children of MaxSizedBox must be <Box> elements`,
element,
);
return {
noWrapSegments: [{ text: '<ERROR>', props: {} }],
segments: [],
};
}
if (enableDebugLog) {
const boxProps = element.props as {
children?: React.ReactNode;
readonly flexDirection?:
| 'row'
| 'column'
| 'row-reverse'
| 'column-reverse';
};
// Ensure the Box has no props other than the default ones and key.
let maxExpectedProps = 4;
if (boxProps.children !== undefined) {
// Allow the key prop, which is automatically added by React.
maxExpectedProps += 1;
}
if (
boxProps.flexDirection !== undefined &&
boxProps.flexDirection !== 'row'
) {
debugReportError(
'MaxSizedBox children must have flexDirection="row".',
element,
);
}
if (Object.keys(boxProps).length > maxExpectedProps) {
debugReportError(
`Boxes inside MaxSizedBox must not have additional props. ${Object.keys(
boxProps,
).join(', ')}`,
element,
);
}
}
const row: Row = {
noWrapSegments: [],
segments: [],
};
let hasSeenWrapped = false;
function visitRowChild(
element: React.ReactNode,
parentProps: Record<string, unknown> | undefined,
) {
if (element === null) {
return;
}
if (typeof element === 'string' || typeof element === 'number') {
const text = String(element);
// Ignore empty strings as they don't need to be rendered.
if (!text) {
return;
}
const segment: StyledText = { text, props: parentProps ?? {} };
// Check the 'wrap' property from the merged props to decide the segment type.
if (parentProps === undefined || parentProps['wrap'] === 'wrap') {
hasSeenWrapped = true;
row.segments.push(segment);
} else {
if (!hasSeenWrapped) {
row.noWrapSegments.push(segment);
} else {
// put in the wrapped segment as the row is already stuck in wrapped mode.
row.segments.push(segment);
debugReportError(
'Text elements without wrapping cannot appear after elements with wrapping in the same row.',
element,
);
}
}
return;
}
if (!React.isValidElement<{ children?: React.ReactNode }>(element)) {
debugReportError('Invalid element.', element);
return;
}
if (element.type === Fragment) {
React.Children.forEach(element.props.children, (child) =>
visitRowChild(child, parentProps),
);
return;
}
if (element.type !== Text) {
debugReportError(
'Children of a row Box must be <Text> elements.',
element,
);
return;
}
// Merge props from parent <Text> elements. Child props take precedence.
const { children, ...currentProps } = element.props;
const mergedProps =
parentProps === undefined
? currentProps
: { ...parentProps, ...currentProps };
React.Children.forEach(children, (child) =>
visitRowChild(child, mergedProps),
);
}
React.Children.forEach(element.props.children, (child) =>
visitRowChild(child, undefined),
);
return row;
}
function layoutInkElementAsStyledText(
element: React.ReactElement,
maxWidth: number,
output: StyledText[][],
) {
const row = visitBoxRow(element);
if (row.segments.length === 0 && row.noWrapSegments.length === 0) {
// Return a single empty line if there are no segments to display
output.push([]);
return;
}
const lines: StyledText[][] = [];
const nonWrappingContent: StyledText[] = [];
let noWrappingWidth = 0;
// First, lay out the non-wrapping segments
row.noWrapSegments.forEach((segment) => {
nonWrappingContent.push(segment);
noWrappingWidth += stringWidth(segment.text);
});
if (row.segments.length === 0) {
// This is a bit of a special case when there are no segments that allow
// wrapping. It would be ideal to unify.
const lines: StyledText[][] = [];
let currentLine: StyledText[] = [];
nonWrappingContent.forEach((segment) => {
const textLines = segment.text.split('\n');
textLines.forEach((text, index) => {
if (index > 0) {
lines.push(currentLine);
currentLine = [];
}
if (text) {
currentLine.push({ text, props: segment.props });
}
});
});
if (
currentLine.length > 0 ||
(nonWrappingContent.length > 0 &&
nonWrappingContent[nonWrappingContent.length - 1].text.endsWith('\n'))
) {
lines.push(currentLine);
}
for (const line of lines) {
output.push(line);
}
return;
}
const availableWidth = maxWidth - noWrappingWidth;
if (availableWidth < 1) {
// No room to render the wrapping segments. Truncate the non-wrapping
// content and append an ellipsis so the line always fits within maxWidth.
// Handle line breaks in non-wrapping content when truncating
const lines: StyledText[][] = [];
let currentLine: StyledText[] = [];
let currentLineWidth = 0;
for (const segment of nonWrappingContent) {
const textLines = segment.text.split('\n');
textLines.forEach((text, index) => {
if (index > 0) {
// New line encountered, finish current line and start new one
lines.push(currentLine);
currentLine = [];
currentLineWidth = 0;
}
if (text) {
const textWidth = stringWidth(text);
// When there's no room for wrapping content, be very conservative
// For lines after the first line break, show only ellipsis if the text would be truncated
if (index > 0 && textWidth > 0) {
// This is content after a line break - just show ellipsis to indicate truncation
currentLine.push({ text: '…', props: {} });
currentLineWidth = stringWidth('…');
} else {
// This is the first line or a continuation, try to fit what we can
const maxContentWidth = Math.max(0, maxWidth - stringWidth('…'));
if (textWidth <= maxContentWidth && currentLineWidth === 0) {
// Text fits completely on this line
currentLine.push({ text, props: segment.props });
currentLineWidth += textWidth;
} else {
// Text needs truncation
const codePoints = toCodePoints(text);
let truncatedWidth = currentLineWidth;
let sliceEndIndex = 0;
for (const char of codePoints) {
const charWidth = stringWidth(char);
if (truncatedWidth + charWidth > maxContentWidth) {
break;
}
truncatedWidth += charWidth;
sliceEndIndex++;
}
const slice = codePoints.slice(0, sliceEndIndex).join('');
if (slice) {
currentLine.push({ text: slice, props: segment.props });
}
currentLine.push({ text: '…', props: {} });
currentLineWidth = truncatedWidth + stringWidth('…');
}
}
}
});
}
// Add the last line if it has content or if the last segment ended with \n
if (
currentLine.length > 0 ||
(nonWrappingContent.length > 0 &&
nonWrappingContent[nonWrappingContent.length - 1].text.endsWith('\n'))
) {
lines.push(currentLine);
}
// If we don't have any lines yet, add an ellipsis line
if (lines.length === 0) {
lines.push([{ text: '…', props: {} }]);
}
for (const line of lines) {
output.push(line);
}
return;
}
// Now, lay out the wrapping segments
let wrappingPart: StyledText[] = [];
let wrappingPartWidth = 0;
function addWrappingPartToLines() {
if (lines.length === 0) {
lines.push([...nonWrappingContent, ...wrappingPart]);
} else {
if (noWrappingWidth > 0) {
lines.push([
...[{ text: ' '.repeat(noWrappingWidth), props: {} }],
...wrappingPart,
]);
} else {
lines.push(wrappingPart);
}
}
wrappingPart = [];
wrappingPartWidth = 0;
}
function addToWrappingPart(text: string, props: Record<string, unknown>) {
if (
wrappingPart.length > 0 &&
wrappingPart[wrappingPart.length - 1].props === props
) {
wrappingPart[wrappingPart.length - 1].text += text;
} else {
wrappingPart.push({ text, props });
}
}
row.segments.forEach((segment) => {
const linesFromSegment = segment.text.split('\n');
linesFromSegment.forEach((lineText, lineIndex) => {
if (lineIndex > 0) {
addWrappingPartToLines();
}
const words = lineText.split(/(\s+)/); // Split by whitespace
words.forEach((word) => {
if (!word) return;
const wordWidth = stringWidth(word);
if (
wrappingPartWidth + wordWidth > availableWidth &&
wrappingPartWidth > 0
) {
addWrappingPartToLines();
if (/^\s+$/.test(word)) {
return;
}
}
if (wordWidth > availableWidth) {
// Word is too long, needs to be split across lines
const wordAsCodePoints = toCodePoints(word);
let remainingWordAsCodePoints = wordAsCodePoints;
while (remainingWordAsCodePoints.length > 0) {
let splitIndex = 0;
let currentSplitWidth = 0;
for (const char of remainingWordAsCodePoints) {
const charWidth = stringWidth(char);
if (
wrappingPartWidth + currentSplitWidth + charWidth >
availableWidth
) {
break;
}
currentSplitWidth += charWidth;
splitIndex++;
}
if (splitIndex > 0) {
const part = remainingWordAsCodePoints
.slice(0, splitIndex)
.join('');
addToWrappingPart(part, segment.props);
wrappingPartWidth += stringWidth(part);
remainingWordAsCodePoints =
remainingWordAsCodePoints.slice(splitIndex);
}
if (remainingWordAsCodePoints.length > 0) {
addWrappingPartToLines();
}
}
} else {
addToWrappingPart(word, segment.props);
wrappingPartWidth += wordWidth;
}
});
});
// Split omits a trailing newline, so we need to handle it here
if (segment.text.endsWith('\n')) {
addWrappingPartToLines();
}
});
if (wrappingPart.length > 0) {
addWrappingPartToLines();
}
for (const line of lines) {
output.push(line);
}
}

View File

@@ -0,0 +1,71 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`<MaxSizedBox /> > accounts for additionalHiddenLinesCount 1`] = `
"... first 7 lines hidden ...
Line 3"
`;
exports[`<MaxSizedBox /> > clips a long single text child from the bottom 1`] = `
"Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
... last 21 lines hidden ..."
`;
exports[`<MaxSizedBox /> > clips a long single text child from the top 1`] = `
"... first 21 lines hidden ...
Line 22
Line 23
Line 24
Line 25
Line 26
Line 27
Line 28
Line 29
Line 30"
`;
exports[`<MaxSizedBox /> > does not truncate when maxHeight is undefined 1`] = `
"Line 1
Line 2"
`;
exports[`<MaxSizedBox /> > handles React.Fragment as a child 1`] = `
"Line 1 from Fragment
Line 2 from Fragment
Line 3 direct child"
`;
exports[`<MaxSizedBox /> > hides lines at the end when content exceeds maxHeight and overflowDirection is bottom 1`] = `
"Line 1
... last 2 lines hidden ..."
`;
exports[`<MaxSizedBox /> > hides lines when content exceeds maxHeight 1`] = `
"... first 2 lines hidden ...
Line 3"
`;
exports[`<MaxSizedBox /> > renders children without truncation when they fit 1`] = `"Hello, World!"`;
exports[`<MaxSizedBox /> > shows plural "lines" when more than one line is hidden 1`] = `
"... first 2 lines hidden ...
Line 3"
`;
exports[`<MaxSizedBox /> > shows singular "line" when exactly one line is hidden 1`] = `
"... first 1 line hidden ...
Line 1"
`;
exports[`<MaxSizedBox /> > wraps text that exceeds maxWidth 1`] = `
"This is a
long line
of text"
`;