Skip to content

Commit

Permalink
Support browser usage (#31)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
Reverier-Xu and sindresorhus committed Mar 16, 2023
1 parent b10a9b8 commit 3aaa131
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
13 changes: 10 additions & 3 deletions index.js
Expand Up @@ -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 = {};

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;`;
Expand Down
14 changes: 14 additions & 0 deletions readme.md
Expand Up @@ -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?)
Expand Down

0 comments on commit 3aaa131

Please sign in to comment.