File size: 4,977 Bytes
52efc7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

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 { useOverflowActions } from '../../contexts/OverflowContext.js';
import { isNarrowWidth } from '../../utils/isNarrowWidth.js';
import { Command } from '../../key/keyBindings.js';
import { formatCommand } from '../../key/keybindingUtils.js';

/**
 * Minimum height for the MaxSizedBox component.
 * This ensures there is room for at least one line of content as well as the
 * message that content was truncated.
 */
export const MINIMUM_MAX_HEIGHT = 2;

export interface MaxSizedBoxProps {
  children?: React.ReactNode;
  maxWidth?: number;
  maxHeight?: number;
  overflowDirection?: 'top' | 'bottom';
  additionalHiddenLinesCount?: number;
  paddingX?: number;
}

/**
 * A React component that constrains the size of its children and provides
 * content-aware truncation when the content exceeds the specified `maxHeight`.
 */
export const MaxSizedBox: React.FC<MaxSizedBoxProps> = ({
  children,
  maxWidth,
  maxHeight,
  overflowDirection = 'top',
  additionalHiddenLinesCount = 0,
  paddingX = 0,
}) => {
  const id = useId();
  const { addOverflowingId, removeOverflowingId } = useOverflowActions() || {};
  const observerRef = useRef<ResizeObserver | null>(null);

  useEffect(
    () => () => {
      observerRef.current?.disconnect();
    },
    [],
  );

  const [contentHeight, setContentHeight] = useState(0);

  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(Math.round(entry.contentRect.height));
          }
        });
        observer.observe(node);
        observerRef.current = observer;
      }
    },
    [maxHeight],
  );

  const effectiveMaxHeight =
    maxHeight !== undefined
      ? Math.max(Math.round(maxHeight), MINIMUM_MAX_HEIGHT)
      : undefined;

  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 =
    isOverflowing && effectiveMaxHeight !== undefined
      ? effectiveMaxHeight - 1
      : effectiveMaxHeight;

  const hiddenLinesCount =
    visibleContentHeight !== undefined
      ? Math.max(0, contentHeight - visibleContentHeight)
      : 0;

  const totalHiddenLines = hiddenLinesCount + additionalHiddenLinesCount;

  const isNarrow = maxWidth !== undefined && isNarrowWidth(maxWidth);
  const showMoreKey = formatCommand(Command.SHOW_MORE_LINES);

  useEffect(() => {
    if (totalHiddenLines > 0) {
      addOverflowingId?.(id);
    } else {
      removeOverflowingId?.(id);
    }
  }, [id, totalHiddenLines, addOverflowingId, removeOverflowingId]);

  useEffect(
    () => () => {
      removeOverflowingId?.(id);
    },
    [id, removeOverflowingId],
  );

  if (effectiveMaxHeight === undefined && totalHiddenLines === 0) {
    return (
      <Box flexDirection="column" width={maxWidth}>
        {children}
      </Box>
    );
  }

  const offset =
    hiddenLinesCount > 0 && overflowDirection === 'top' ? -hiddenLinesCount : 0;

  return (
    <Box
      flexDirection="column"
      width={maxWidth}
      maxHeight={effectiveMaxHeight}
      flexShrink={0}
    >
      {totalHiddenLines > 0 && overflowDirection === 'top' && (
        <Box paddingX={paddingX}>
          <Text color={theme.text.secondary} wrap="truncate">
            {isNarrow
              ? `... ${totalHiddenLines} hidden (${showMoreKey}) ...`
              : `... first ${totalHiddenLines} line${totalHiddenLines === 1 ? '' : 's'} hidden (${showMoreKey} to show) ...`}
          </Text>
        </Box>
      )}
      <Box
        flexDirection="column"
        overflow="hidden"
        flexGrow={0}
        maxHeight={isOverflowing ? visibleContentHeight : undefined}
      >
        <Box
          flexDirection="column"
          ref={onRefChange}
          flexShrink={0}
          marginTop={offset}
        >
          {children}
        </Box>
      </Box>
      {totalHiddenLines > 0 && overflowDirection === 'bottom' && (
        <Box paddingX={paddingX}>
          <Text color={theme.text.secondary} wrap="truncate">
            {isNarrow
              ? `... ${totalHiddenLines} hidden (${showMoreKey}) ...`
              : `... last ${totalHiddenLines} line${totalHiddenLines === 1 ? '' : 's'} hidden (${showMoreKey} to show) ...`}
          </Text>
        </Box>
      )}
    </Box>
  );
};