File size: 6,960 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import type React from 'react';
import { useState, useRef } from 'react';
import { Text, Box, type DOMElement } from 'ink';
import { theme } from '../../semantic-colors.js';
import {
  useSelectionList,
  type SelectionListItem,
} from '../../hooks/useSelectionList.js';
import { useMouseClick } from '../../hooks/useMouseClick.js';

export interface RenderItemContext {
  isSelected: boolean;
  titleColor: string;
  numberColor: string;
}

export interface BaseSelectionListProps<
  T,
  TItem extends SelectionListItem<T> = SelectionListItem<T>,
> {
  items: TItem[];
  initialIndex?: number;
  onSelect: (value: T) => void;
  onHighlight?: (value: T) => void;
  isFocused?: boolean;
  showNumbers?: boolean;
  showScrollArrows?: boolean;
  maxItemsToShow?: number;
  wrapAround?: boolean;
  focusKey?: string;
  priority?: boolean;
  selectedIndicator?: string;
  renderItem: (item: TItem, context: RenderItemContext) => React.ReactNode;
}

interface SelectionListItemRowProps<
  T,
  TItem extends SelectionListItem<T> = SelectionListItem<T>,
> {
  item: TItem;
  itemIndex: number;
  isSelected: boolean;
  isFocused: boolean;
  showNumbers: boolean;
  selectedIndicator: string;
  numberColumnWidth: number;
  onSelect: (value: T) => void;
  setActiveIndex: (index: number) => void;
  renderItem: (item: TItem, context: RenderItemContext) => React.ReactNode;
}

function SelectionListItemRow<
  T,
  TItem extends SelectionListItem<T> = SelectionListItem<T>,
>({
  item,
  itemIndex,
  isSelected,
  isFocused,
  showNumbers,
  selectedIndicator,
  numberColumnWidth,
  onSelect,
  setActiveIndex,
  renderItem,
}: SelectionListItemRowProps<T, TItem>) {
  const containerRef = useRef<DOMElement>(null);

  useMouseClick(
    containerRef,
    () => {
      if (!item.disabled) {
        if (isSelected) {
          // Second click on the same item triggers submission
          onSelect(item.value);
        } else {
          // First click highlights the item
          setActiveIndex(itemIndex);
        }
      }
    },
    { isActive: isFocused },
  );

  let titleColor = theme.text.primary;
  let numberColor = theme.text.primary;

  if (isSelected) {
    titleColor = theme.ui.focus;
    numberColor = theme.ui.focus;
  } else if (item.disabled) {
    titleColor = theme.text.secondary;
    numberColor = theme.text.secondary;
  }

  if (!isFocused && !item.disabled) {
    numberColor = theme.text.secondary;
  }

  if (!showNumbers) {
    numberColor = theme.text.secondary;
  }

  const itemNumberText = `${String(itemIndex + 1).padStart(
    numberColumnWidth,
  )}.`;

  return (
    <Box
      ref={containerRef}
      key={item.key}
      alignItems="flex-start"
      backgroundColor={isSelected ? theme.background.focus : undefined}
    >
      {/* Radio button indicator */}
      <Box minWidth={2} flexShrink={0}>
        <Text
          color={isSelected ? theme.ui.focus : theme.text.primary}
          aria-hidden
        >
          {isSelected ? selectedIndicator : ' '}
        </Text>
      </Box>

      {/* Item number */}
      {showNumbers && !item.hideNumber && (
        <Box
          marginRight={1}
          flexShrink={0}
          minWidth={itemNumberText.length}
          aria-state={{ checked: isSelected }}
        >
          <Text color={numberColor}>{itemNumberText}</Text>
        </Box>
      )}

      {/* Custom content via render prop */}
      <Box flexGrow={1}>
        {renderItem(item, {
          isSelected,
          titleColor,
          numberColor,
        })}
      </Box>
    </Box>
  );
}

/**
 * Base component for selection lists that provides common UI structure
 * and keyboard navigation logic via the useSelectionList hook.
 *
 * This component handles:
 * - Radio button indicators
 * - Item numbering
 * - Scrolling for long lists
 * - Color theming based on selection/disabled state
 * - Keyboard navigation and numeric selection
 *
 * Specific components should use this as a base and provide
 * their own renderItem implementation for custom content.
 */
export function BaseSelectionList<
  T,
  TItem extends SelectionListItem<T> = SelectionListItem<T>,
>({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showNumbers = true,
  showScrollArrows = false,
  maxItemsToShow = 10,
  wrapAround = true,
  focusKey,
  priority,
  selectedIndicator = '●',
  renderItem,
}: BaseSelectionListProps<T, TItem>): React.JSX.Element {
  const { activeIndex, setActiveIndex } = useSelectionList({
    items,
    initialIndex,
    onSelect,
    onHighlight,
    isFocused,
    showNumbers,
    wrapAround,
    focusKey,
    priority,
  });

  const [scrollOffset, setScrollOffset] = useState(0);

  // Derive the effective scroll offset during render to avoid "no-selection" flicker.
  // This ensures that the visibleItems calculation uses an offset that includes activeIndex.
  let effectiveScrollOffset = scrollOffset;
  if (activeIndex < effectiveScrollOffset) {
    effectiveScrollOffset = activeIndex;
  } else if (activeIndex >= effectiveScrollOffset + maxItemsToShow) {
    effectiveScrollOffset = Math.max(
      0,
      Math.min(activeIndex - maxItemsToShow + 1, items.length - maxItemsToShow),
    );
  }

  // Synchronize state if it changed during derivation
  if (effectiveScrollOffset !== scrollOffset) {
    setScrollOffset(effectiveScrollOffset);
  }

  const visibleItems = items.slice(
    effectiveScrollOffset,
    effectiveScrollOffset + maxItemsToShow,
  );
  const numberColumnWidth = String(items.length).length;

  const showArrows = showScrollArrows && items.length > maxItemsToShow;

  return (
    <Box flexDirection="column">
      {/* Use conditional coloring instead of conditional rendering */}
      {showArrows && (
        <Text
          color={
            effectiveScrollOffset > 0
              ? theme.text.primary
              : theme.text.secondary
          }
        >
          ▲
        </Text>
      )}

      {visibleItems.map((item, index) => {
        const itemIndex = effectiveScrollOffset + index;
        const isSelected = activeIndex === itemIndex;

        return (
          <SelectionListItemRow
            key={item.key}
            item={item}
            itemIndex={itemIndex}
            isSelected={isSelected}
            isFocused={isFocused}
            showNumbers={showNumbers}
            selectedIndicator={selectedIndicator}
            numberColumnWidth={numberColumnWidth}
            onSelect={onSelect}
            setActiveIndex={setActiveIndex}
            renderItem={renderItem}
          />
        );
      })}

      {showArrows && (
        <Text
          color={
            effectiveScrollOffset + maxItemsToShow < items.length
              ? theme.text.primary
              : theme.text.secondary
          }
        >
          ▼
        </Text>
      )}
    </Box>
  );
}