-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
37 additions
and
44 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,20 @@ | ||
// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences | ||
// https://github.com/nodejs/node/blob/a717fa211194b735cdfc1044c7351c6cf96b8783/lib/internal/readline/utils.js | ||
// https://github.com/terkelg/sisteransi/blob/e219f8672540dde6e92a19e48a3567ef2548d620/src/index.js | ||
export const ESC = `\x1b`; | ||
export const CSI = `${ESC}[`; | ||
export const kClearToLineBeginning = `${CSI}1K`; | ||
export const kClearToLineEnd = `${CSI}1K`; | ||
export const kClearLine = `${CSI}2K`; | ||
export const kClearScreenDown = `${CSI}0J`; | ||
export const kClearAll = `${CSI}2J`; | ||
export const CSI = "\x1b["; | ||
|
||
export function cursorTo(x: number, y?: number) { | ||
return typeof y !== "number" ? `${CSI}${x + 1}G` : `${CSI}${y + 1};${x + 1}H`; | ||
// cf. https://github.com/terkelg/prompts/blob/735603af7c7990ac9efcfba6146967a7dbb15f50/lib/util/clear.js#L5-L6 | ||
export function computeHeight(s: string, width: number) { | ||
// strip CSI | ||
const s2 = s.replaceAll(/\x1b\[\d*[A-Za-z]/g, ""); | ||
|
||
// check line wrap | ||
const wraps = s2 | ||
.split("\n") | ||
.map((line) => computeLineWrap(line.length, width)); | ||
return wraps.reduce((x, y) => x + y); | ||
} | ||
|
||
export function moveCursor(dx: number, dy: number) { | ||
return [ | ||
dx < 0 && `${CSI}${-dx}D`, | ||
dx > 0 && `${CSI}${dx}C`, | ||
dy < 0 && `${CSI}${-dy}A`, | ||
dy > 0 && `${CSI}${dy}B`, | ||
] | ||
.filter(Boolean) | ||
.join(""); | ||
function computeLineWrap(l: number, w: number) { | ||
return Math.floor(Math.max((l - 1) / w, 0) + 1); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters