From 3aaa131ae9d9e9c87e1394fae4d1092d8475a446 Mon Sep 17 00:00:00 2001 From: Reverier Date: Thu, 16 Mar 2023 16:05:41 +0800 Subject: [PATCH] Support browser usage (#31) Co-authored-by: Sindre Sorhus --- index.js | 13 ++++++++++--- readme.md | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index e26cde0..9307dfc 100644 --- a/index.js +++ b/index.js @@ -5,7 +5,14 @@ const OSC = '\u001B]'; const BEL = '\u0007'; const SEP = ';'; -const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal'; +/* global window */ +const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined'; + +const isTerminalApp = !isBrowser && process.env.TERM_PROGRAM === 'Apple_Terminal'; +const isWindows = !isBrowser && process.platform === 'win32'; +const cwdFunction = isBrowser ? () => { + throw new Error('`process.cwd()` only works in Node.js, not the browser.'); +} : process.cwd; const ansiEscapes = {}; @@ -82,7 +89,7 @@ ansiEscapes.scrollDown = ESC + 'T'; ansiEscapes.clearScreen = '\u001Bc'; -ansiEscapes.clearTerminal = process.platform === 'win32' +ansiEscapes.clearTerminal = isWindows ? `${ansiEscapes.eraseScreen}${ESC}0f` // 1. Erases the screen (Only done in case `2` is not supported) // 2. Erases the whole screen including scrollback buffer @@ -126,7 +133,7 @@ ansiEscapes.image = (buffer, options = {}) => { }; ansiEscapes.iTerm = { - setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`, + setCwd: (cwd = cwdFunction()) => `${OSC}50;CurrentDir=${cwd}${BEL}`, annotation(message, options = {}) { let returnValue = `${OSC}1337;`; diff --git a/readme.md b/readme.md index 9467a24..30f73e7 100644 --- a/readme.md +++ b/readme.md @@ -18,6 +18,20 @@ process.stdout.write(ansiEscapes.cursorUp(2) + ansiEscapes.cursorLeft); //=> '\u001B[2A\u001B[1000D' ``` +**You can also use it in the browser with Xterm.js:** + +```js +import ansiEscapes from 'ansi-escapes'; +import {Terminal} from 'xterm'; +import 'xterm/css/xterm.css'; + +const terminal = new Terminal({…}); + +// Moves the cursor two rows up and to the left +terminal.write(ansiEscapes.cursorUp(2) + ansiEscapes.cursorLeft); +//=> '\u001B[2A\u001B[1000D' +``` + ## API ### cursorTo(x, y?)