Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"test": "vitest run",
"lint": "eslint .",
"format": "prettier --write .",
"prepublishOnly": "pnpm run build",
"clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
"prepublishOnly": "pnpm run clean && pnpm run build",
"gen:x402-metrics": "node scripts/generate-x402-metrics.mjs"
},
"keywords": [
Expand Down Expand Up @@ -68,7 +69,7 @@
"glassnode-api": "^0.29.3",
"ink": "^7.1.1",
"ink-spinner": "^5.0.0",
"ink-uplot": "^0.2.13",
"ink-uplot": "^0.2.15",
"path2d": "^0.3.4",
"react": "^19.3.0",
"uplot": "^1.6.32",
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 17 additions & 4 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ import { LogView } from './components/LogView.js';
import { PriceTicker } from './components/PriceTicker.js';
import { Spinner } from './components/Spinner.js';
import { usePulses, getTickerAssets } from './hooks/usePulses.js';
import { useRedrawAfterInput } from './hooks/useRedrawAfterInput.js';
import { detectFormat } from 'ink-uplot';

// Inline-image charts (iTerm2 protocol — VS Code, iTerm2 — and sixels) live in the text
// cells, so Ink repaints after a keypress can erase them. Kitty's graphics layer and text
// charts survive repaints.
const CHART_ERASED_BY_REPAINTS = ['iterm2', 'sixels'].includes(detectFormat());
import { loadStartupData, buildMetricList } from './lib/startup-data.js';
import {
Pane,
Expand All @@ -33,7 +40,8 @@ function cycleNext<T>(arr: readonly T[], current: T): T {
export function App(): React.ReactElement {
const { stdout } = useStdout();
const [termHeight, setTermHeight] = useState(stdout?.rows ?? 24);
const [termWidth, setTermWidth] = useState(stdout?.columns ?? 80);
// Not read directly: updating it re-renders on width-only resizes so DataView re-measures the chart.
const [, setTermWidth] = useState(stdout?.columns ?? 80);

useEffect(() => {
if (!stdout) return;
Expand Down Expand Up @@ -80,6 +88,7 @@ export function App(): React.ReactElement {
const [dataViewMode, setDataViewMode] = useState<DataViewMode>('chart');
const [showPrice, setShowPrice] = useState(true);
const [showLogs, setShowLogs] = useState(false);
const chartRedrawKey = useRedrawAfterInput(150, CHART_ERASED_BY_REPAINTS && !showLogs && dataViewMode === 'chart');
const [leftSearchQuery, setLeftSearchQuery] = useState('');
const [middleSearchQuery, setMiddleSearchQuery] = useState('');
const activeSearchQuery = activePane === Pane.Left ? leftSearchQuery : middleSearchQuery;
Expand Down Expand Up @@ -323,7 +332,11 @@ export function App(): React.ReactElement {
params,
showPrice,
);
const dataNavReal = useListNavigation({ itemCount: data.length, viewportSize });
// Table page size = rows DataView measured for its body, minus the table header row.
// Until the first measurement, assume the pane's param bar, metric line and header.
const [dataBodyHeight, setDataBodyHeight] = useState<number | null>(null);
const dataPageSize = Math.max(1, dataBodyHeight === null ? viewportSize - 3 : dataBodyHeight - 1);
const dataNavReal = useListNavigation({ itemCount: data.length, viewportSize: dataPageSize });

// Pane switching
const nextPane = useCallback(() => {
Expand Down Expand Up @@ -569,8 +582,8 @@ export function App(): React.ReactElement {
viewMode={dataViewMode}
showPrice={showPrice}
priceData={priceData}
chartWidth={Math.max(20, termWidth - 30 - 50 - 6)}
chartHeight={viewportSize}
chartRedrawKey={chartRedrawKey}
onBodyHeightChange={setDataBodyHeight}
/>
)}
</Box>
Expand Down
4 changes: 3 additions & 1 deletion src/cli.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ if (!hasApiKey && !hasX402) {
try {
// Build the client up front (x402 setup is async) so hooks can use it synchronously.
await initClient();
render(<App />, { exitOnCtrlC: true });
// Incremental rendering rewrites only changed lines, so live updates (price ticker)
// don't repaint the rows under an inline-image chart and erase it.
render(<App />, { exitOnCtrlC: true, incrementalRendering: true });
} catch (err) {
fail(`Error initializing Glassnode client: ${err instanceof Error ? err.message : String(err)}`);
}
Expand Down
125 changes: 72 additions & 53 deletions src/components/DataView.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useMemo } from 'react';
import { Box, Text } from 'ink';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Box, Text, measureElement, type DOMElement } from 'ink';
import { InkUPlot } from 'ink-uplot';
import type { DataPoint, MetricParams } from '../lib/types.js';
import { formatDate, formatValue, padRight } from '../lib/format.js';
Expand All @@ -21,8 +21,10 @@ interface DataViewProps {
viewMode: DataViewMode;
showPrice: boolean;
priceData: DataPoint[];
chartWidth: number;
chartHeight: number;
/** Changing this re-draws the chart (see useRedrawAfterInput). */
chartRedrawKey: number;
/** Called with the rows available for the table/chart body (sizes the table's page). */
onBodyHeightChange?: (height: number) => void;
}

export function DataView({
Expand All @@ -38,10 +40,28 @@ export function DataView({
viewMode,
showPrice,
priceData,
chartWidth,
chartHeight,
chartRedrawKey,
onBodyHeightChange,
}: DataViewProps): React.ReactElement {
const [start, end] = visibleRange;

// Measure the space actually left in the pane for the table/chart body (below the param
// bar and metric line, which wrap when the pane is narrow). Inline-image charts are drawn
// at exactly this size, and the table's page size comes from it (via onBodyHeightChange),
// so a guess would spill over the pane border.
const bodyRef = useRef<DOMElement>(null);
// `measured` distinguishes "not laid out yet" from a real 0 (a pane too short for a body).
const [bodyArea, setBodyArea] = useState({ width: 0, height: 0, measured: false });
useEffect(() => {
if (!bodyRef.current) return;
const { width, height } = measureElement(bodyRef.current);
if (!bodyArea.measured || width !== bodyArea.width || height !== bodyArea.height) {
setBodyArea({ width, height, measured: true });
}
});
useEffect(() => {
if (bodyArea.measured) onBodyHeightChange?.(bodyArea.height);
}, [bodyArea.measured, bodyArea.height, onBodyHeightChange]);
const visible = data.slice(start, end);

// Price lookup for table view
Expand Down Expand Up @@ -96,7 +116,9 @@ export function DataView({
}

return { width: 800, height: 400, series, axes };
}, [priceMap]);
// chartRedrawKey: a new opts object makes InkUPlot re-render and re-stamp an inline
// image that an Ink repaint erased.
}, [priceMap, chartRedrawKey]);

return (
<Box flexDirection="column" flexGrow={2} borderStyle="single" borderColor={isFocused ? 'cyan' : 'gray'}>
Expand All @@ -116,57 +138,54 @@ export function DataView({
</Box>
)}

{!loading && !error && data.length > 0 && viewMode === 'table' && (
<Box flexDirection="column">
<Box paddingX={1} gap={2}>
<Text bold>{padRight('Date', 16)}</Text>
<Text bold>{padRight('Value', 16)}</Text>
{priceMap && <Text bold dimColor>Price</Text>}
</Box>
{visible.map((point, i) => {
const globalIndex = start + i;
const isSelected = globalIndex === selectedIndex;
const value = point.v !== undefined ? point.v : point.o;
const price = priceMap?.get(point.t);
return (
<Box key={point.t} paddingX={1} gap={2}>
<Text
color={isSelected ? 'black' : undefined}
backgroundColor={isSelected && isFocused ? 'cyan' : undefined}
>
{padRight(formatDate(point.t, params.interval), 16)}
</Text>
<Text
color={isSelected ? 'black' : undefined}
backgroundColor={isSelected && isFocused ? 'cyan' : undefined}
>
{padRight(formatValue(value), 16)}
</Text>
{priceMap && (
<Text dimColor>
{price != null ? formatValue(price) : '—'}
</Text>
)}
</Box>
);
})}
</Box>
)}

{!loading && !error && data.length > 0 && viewMode === 'chart' && chartData && (
<InkUPlot
opts={chartOpts}
data={chartData}
width={Math.max(20, chartWidth)}
height={Math.max(5, chartHeight)}
/>
)}

{!loading && !error && data.length === 0 && selectedMetric && selectedAsset && (
<Box paddingX={1}>
<Text dimColor>No data</Text>
</Box>
)}

<Box ref={bodyRef} flexDirection="column" flexGrow={1} flexShrink={1} flexBasis={0} overflow="hidden">
{!loading && !error && data.length > 0 && viewMode === 'table' && (
<Box flexDirection="column">
<Box paddingX={1} gap={2}>
<Text bold>{padRight('Date', 16)}</Text>
<Text bold>{padRight('Value', 16)}</Text>
{priceMap && <Text bold dimColor>Price</Text>}
</Box>
{visible.map((point, i) => {
const globalIndex = start + i;
const isSelected = globalIndex === selectedIndex;
const value = point.v !== undefined ? point.v : point.o;
const price = priceMap?.get(point.t);
return (
<Box key={point.t} paddingX={1} gap={2}>
<Text
color={isSelected ? 'black' : undefined}
backgroundColor={isSelected && isFocused ? 'cyan' : undefined}
>
{padRight(formatDate(point.t, params.interval), 16)}
</Text>
<Text
color={isSelected ? 'black' : undefined}
backgroundColor={isSelected && isFocused ? 'cyan' : undefined}
>
{padRight(formatValue(value), 16)}
</Text>
{priceMap && (
<Text dimColor>
{price != null ? formatValue(price) : '—'}
</Text>
)}
</Box>
);
})}
</Box>
)}

{!loading && !error && data.length > 0 && viewMode === 'chart' && chartData && bodyArea.width > 0 && bodyArea.height > 0 && (
<InkUPlot opts={chartOpts} data={chartData} width={bodyArea.width} height={bodyArea.height} />
)}
</Box>
</Box>
);
}
11 changes: 11 additions & 0 deletions src/hooks/useListNavigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,17 @@ export function useListNavigation({ itemCount, viewportSize, isSelectable }: Lis
}
}, [itemCount]); // eslint-disable-line react-hooks/exhaustive-deps

// When the viewport changes size (terminal resize, a pane header wrapping), keep the
// selection visible and don't leave empty rows past the end of the list.
useEffect(() => {
setScrollOffset((prev) => {
let next = prev;
if (selectedIndex >= next + viewportSize) next = selectedIndex - viewportSize + 1;
if (selectedIndex < next) next = selectedIndex;
return Math.max(0, Math.min(next, Math.max(0, itemCount - viewportSize)));
});
}, [viewportSize]); // eslint-disable-line react-hooks/exhaustive-deps

const findSelectable = useCallback(
(from: number, direction: 1 | -1): number => {
if (!isSelectable) return from;
Expand Down
29 changes: 29 additions & 0 deletions src/hooks/useRedrawAfterInput.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useEffect, useRef, useState } from 'react';
import { useInput } from 'ink';

/**
* Returns a counter that bumps once, `delayMs` after the last keypress.
*
* Inline-image charts (iTerm2 protocol, e.g. in VS Code) are written straight to the
* terminal, outside Ink's frame. Any Ink repaint of the rows under the image erases it,
* and a keypress (pane focus, list navigation, search) can repaint every row. Feeding
* this counter into the chart's inputs re-stamps the image once after the user stops
* typing, instead of redrawing it on a timer (which flickers).
*
* Pass `enabled = false` when no chart is shown or the chart's format survives repaints
* (kitty's graphics layer, text charts): each bump re-renders and re-sends the image.
*/
export function useRedrawAfterInput(delayMs = 150, enabled = true): number {
const [epoch, setEpoch] = useState(0);
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);

useInput(() => {
if (!enabled) return;
clearTimeout(timer.current);
timer.current = setTimeout(() => setEpoch((e) => e + 1), delayMs);
});

useEffect(() => () => clearTimeout(timer.current), []);

return epoch;
}
1 change: 1 addition & 0 deletions test/components/App.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ vi.mock('../../src/lib/api-client.js', () => ({

vi.mock('ink-uplot', () => ({
InkUPlot: () => null,
detectFormat: () => 'symbols',
}));

// Helper: wait for async renders to settle
Expand Down
Loading
Loading