File size: 1,503 Bytes
5448d8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState } from "react";
import { Box, Text, useInput } from "ink";
import { theme } from "./theme.jsx";

function formatCell(v, col) {
  if (v == null) return "-";
  if (col.formatter) return col.formatter(v);
  return String(v);
}

export function DataTable({ rows = [], schema = [], selectable = false, onSelect }) {
  const [selectedIdx, setSelectedIdx] = useState(0);

  useInput((input, key) => {
    if (!selectable || rows.length === 0) return;
    if (key.upArrow) setSelectedIdx((i) => Math.max(0, i - 1));
    if (key.downArrow) setSelectedIdx((i) => Math.min(rows.length - 1, i + 1));
    if (key.return && onSelect) onSelect(rows[selectedIdx]);
  });

  if (rows.length === 0) {
    return <Text dimColor>No data.</Text>;
  }

  return (
    <Box flexDirection="column">

      <Box>

        {schema.map((col) => (

          <Box key={col.key} width={col.width ?? 16} marginRight={1}>

            <Text bold color={theme.header}>

              {col.header}

            </Text>

          </Box>

        ))}

      </Box>

      {rows.map((row, idx) => (

        <Box

          key={idx}

          backgroundColor={selectable && idx === selectedIdx ? theme.selected : undefined}

        >

          {schema.map((col) => (

            <Box key={col.key} width={col.width ?? 16} marginRight={1}>

              <Text>{formatCell(row[col.key], col)}</Text>

            </Box>

          ))}

        </Box>

      ))}

    </Box>
  );
}