Skip to content

Instantly share code, notes, and snippets.

@remorses
Created December 29, 2024 11:58
Show Gist options
  • Save remorses/ac7374b55f74a9c34593740bff5569ba to your computer and use it in GitHub Desktop.
Save remorses/ac7374b55f74a9c34593740bff5569ba to your computer and use it in GitHub Desktop.
scrolling with ink
import { useEffect, useState } from 'react';
import React from 'react';
import type { BoxProps, DOMElement } from 'ink';
async function main() {
const { render, Text, measureElement, Box } = await import('ink');
interface ScrollProps {
onUp?: () => void;
onDown?: () => void;
}
const isNotProduction = process.env['NODE_ENV'] !== 'production';
type Props = {
children: React.ReactNode[];
/** cursor index */
cursor: number;
/** initial height */
initialHeight?: number;
/** initial offset */
initialOffset?: number;
} & BoxProps;
function InViewBox(props: Props) {
const {
children,
cursor,
initialHeight = 0,
initialOffset = 0,
...boxProps
} = props;
if (isNotProduction && (cursor < 0 || cursor > children.length - 1)) {
console.warn('cursor is out of range');
}
const ref = React.useRef<DOMElement>(null);
const [height, setHeight] = React.useState(initialHeight);
React.useLayoutEffect(() => {
if (ref && ref.current) {
setHeight(measureElement(ref.current).height);
}
}, [ref, props.height]);
const offset = React.useRef(initialOffset);
const slice = {
start: offset.current,
end: height + offset.current,
};
// move to cursor position if cursor is out of range
if (cursor < offset.current) {
slice.start = cursor;
slice.end = cursor + height;
} else if (cursor > height + offset.current - 1) {
slice.start = cursor - height + 1;
slice.end = cursor + 1;
}
// reset offset if out of range
if (slice.start < 0) {
offset.current = 0;
} else if (slice.start > children.length - 1) {
offset.current = children.length - 1;
} else {
offset.current = slice.start;
}
return (
<Box {...boxProps} flexDirection="column" ref={ref}>
{children.slice(slice.start, slice.end)}
</Box>
);
}
const useScroll = ({ onUp, onDown }: ScrollProps = {}): void => {
useEffect(() => {
const stdin = process.stdin;
// Enable raw mode and start listening for input
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf-8');
// Enable mouse tracking (SGR mode)
process.stdout.write('\x1b[?1000h'); // Enable basic mouse events
process.stdout.write('\x1b[?1002h'); // Enable mouse motion events
process.stdout.write('\x1b[?1015h'); // Enable urxvt mouse mode
process.stdout.write('\x1b[?1006h'); // Enable SGR mouse mode
const handleInput = (data: string): void => {
// Handle Ctrl+C
if (data === '\x03') {
stop();
process.exit(0);
}
// Check for mouse wheel events
if (data.startsWith('\x1b[<')) {
const match = data.match(/\x1b\[<(\d+);/);
if (match) {
const code = parseInt(match[1]);
// Based on the buffer output, 65 is scroll up and 64 is scroll down
if (code === 65 && typeof onUp === 'function') {
onUp();
} else if (code === 64 && typeof onDown === 'function') {
onDown();
}
}
}
};
stdin.on('data', handleInput);
const stop = () => {
stdin.setRawMode(false);
stdin.pause();
stdin.removeListener('data', handleInput);
// Disable mouse tracking
process.stdout.write('\x1b[?1000l'); // Disable basic mouse events
process.stdout.write('\x1b[?1002l'); // Disable mouse motion events
process.stdout.write('\x1b[?1015l'); // Disable urxvt mouse mode
process.stdout.write('\x1b[?1006l'); // Disable SGR mouse mode
};
// Cleanup on unmount
return stop;
}, [onUp, onDown]); // Re-run effect if callbacks change
};
const App = () => {
const [cursor, setCursor] = useState(0);
const loremIpsum = [
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
'Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.',
'Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.',
'Totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit.',
'Sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.',
'Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.',
'Sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.',
];
const logs = Array.from({ length: 100 }, (_, i) => ({
timestamp: new Date(Date.now() - i * 60000).toISOString(),
level: ['INFO', 'WARN', 'ERROR'][Math.floor(Math.random() * 3)],
message: loremIpsum[i % loremIpsum.length],
}));
// Transform logs into lines that fit the terminal width
const terminalWidth = process.stdout.columns;
const contentHeight = process.stdout.rows - 2;
const logLines = logs.flatMap((log) => {
const prefix = `[${log.timestamp}] ${log.level}: `;
const availableWidth = terminalWidth;
const words = log.message.split(' ');
const lines: string[] = [];
let currentLine = prefix;
words.forEach((word) => {
if (currentLine.length + word.length + 1 <= availableWidth) {
currentLine += (currentLine === prefix ? '' : ' ') + word;
} else {
lines.push(currentLine);
currentLine = word; // Remove prefix spacing for wrapped lines
}
});
if (currentLine) {
lines.push(currentLine);
}
return lines;
});
useScroll({
onUp: () => setCursor((prev) => Math.max(0, prev - 1)),
onDown: () =>
setCursor((prev) => Math.min(logLines.length - 1, prev + 1)),
});
const logComponents = logLines.map((line, i) => (
<Box key={i}>
<Text>{line}</Text>
</Box>
));
return (
<Box flexDirection="column" height={process.stdout.rows - 1}>
<InViewBox
height={contentHeight}
cursor={cursor}
flexDirection="column"
>
{logComponents}
</InViewBox>
<Text>
Line {cursor + 1} of {logLines.length}
</Text>
</Box>
);
};
render(<App />);
}
main().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment