3 const isTerm = process.env.TERM_PROGRAM === 'Apple_Terminal';
4 const colors = require('ansi-colors');
5 const utils = require('./utils');
6 const ansi = module.exports = exports;
11 const code = ansi.code = {
17 getPosition: `${ESC}6n`,
21 lineStart: `${ESC}1K`,
22 restorePosition: ESC + (isTerm ? '8' : 'u'),
23 savePosition: ESC + (isTerm ? '7' : 's'),
29 const cursor = ansi.cursor = {
43 forward: (count = 1) => `${ESC}${count}C`,
44 backward: (count = 1) => `${ESC}${count}D`,
45 nextLine: (count = 1) => `${ESC}E`.repeat(count),
46 prevLine: (count = 1) => `${ESC}F`.repeat(count),
48 up: (count = 1) => count ? `${ESC}${count}A` : '',
49 down: (count = 1) => count ? `${ESC}${count}B` : '',
50 right: (count = 1) => count ? `${ESC}${count}C` : '',
51 left: (count = 1) => count ? `${ESC}${count}D` : '',
54 return y ? `${ESC}${y + 1};${x + 1}H` : `${ESC}${x + 1}G`;
59 res += (x < 0) ? cursor.left(-x) : (x > 0) ? cursor.right(x) : '';
60 res += (y < 0) ? cursor.up(-y) : (y > 0) ? cursor.down(y) : '';
65 let { after, cursor, initial, input, prompt, size, value } = state;
66 initial = utils.isPrimitive(initial) ? String(initial) : '';
67 input = utils.isPrimitive(input) ? String(input) : '';
68 value = utils.isPrimitive(value) ? String(value) : '';
71 let codes = ansi.cursor.up(size) + ansi.cursor.to(prompt.length);
72 let diff = input.length - cursor;
74 codes += ansi.cursor.left(diff);
80 let pos = (!input && !!initial) ? -initial.length : -input.length + cursor;
81 if (after) pos -= after.length;
82 if (input === '' && initial && !prompt.includes(initial)) {
83 pos += initial.length;
85 return ansi.cursor.move(pos);
90 const erase = ansi.erase = {
95 lineEnd: code.lineEnd,
96 lineStart: code.lineStart,
99 for (let i = 0; i < n; i++) {
100 str += ansi.erase.line + (i < n - 1 ? ansi.cursor.up(1) : '');
102 if (n) str += ansi.code.beginning;
107 ansi.clear = (input = '', columns = process.stdout.columns) => {
108 if (!columns) return erase.line + cursor.to(0);
109 let width = str => [...colors.unstyle(str)].length;
110 let lines = input.split(/\r?\n/);
112 for (let line of lines) {
113 rows += 1 + Math.floor(Math.max(width(line) - 1, 0) / columns);
115 return (erase.line + cursor.prevLine()).repeat(rows - 1) + erase.line + cursor.to(0);