Skip to content

Commit

Permalink
Simplify
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Oct 29, 2023
1 parent 3fa6be0 commit dc1bb73
Showing 1 changed file with 15 additions and 33 deletions.
48 changes: 15 additions & 33 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,71 +7,53 @@ import stripAnsi from 'strip-ansi';

const defaultTerminalHeight = 24;

const getWidth = stream => {
const {columns} = stream;

if (!columns) {
return 80;
}

return columns;
};
const getWidth = ({columns = 80}) => columns;

const fitToTerminalHeight = (stream, text) => {
const terminalHeight = stream.rows ?? defaultTerminalHeight;
const lines = text.split('\n');

const toRemove = lines.length - terminalHeight;
if (toRemove <= 0) {
return text;
}

return sliceAnsi(
text,
stripAnsi(lines.slice(0, toRemove).join('\n')).length + 1,
);
const toRemove = Math.max(0, lines.length - terminalHeight);
return toRemove ? sliceAnsi(text, stripAnsi(lines.slice(0, toRemove).join('\n')).length + 1) : text;
};

export function createLogUpdate(stream, {showCursor = false} = {}) {
let previousLineCount = 0;
let previousWidth = getWidth(stream);
let previousOutput = '';

const reset = () => {
previousOutput = '';
previousWidth = getWidth(stream);
previousLineCount = 0;
};

const render = (...arguments_) => {
if (!showCursor) {
cliCursor.hide();
}

let output = arguments_.join(' ') + '\n';
output = fitToTerminalHeight(stream, output);
let output = fitToTerminalHeight(stream, arguments_.join(' ') + '\n');
const width = getWidth(stream);

if (output === previousOutput && previousWidth === width) {
return;
}

previousOutput = output;
previousWidth = width;
output = wrapAnsi(output, width, {
trim: false,
hard: true,
wordWrap: false,
});
output = wrapAnsi(output, width, {trim: false, hard: true, wordWrap: false});

stream.write(ansiEscapes.eraseLines(previousLineCount) + output);
previousLineCount = output.split('\n').length;
};

render.clear = () => {
stream.write(ansiEscapes.eraseLines(previousLineCount));
previousOutput = '';
previousWidth = getWidth(stream);
previousLineCount = 0;
reset();
};

render.done = () => {
previousOutput = '';
previousWidth = getWidth(stream);
previousLineCount = 0;

reset();
if (!showCursor) {
cliCursor.show();
}
Expand Down

0 comments on commit dc1bb73

Please sign in to comment.