Skip to content

Commit

Permalink
Add clipboard addon
Browse files Browse the repository at this point in the history
This addon enables xtermjs to access the system clipboard to read/write
data. It uses the Clipboard API to do so and leverages xtermjs OSC52
implementation to read/write data from and to the system clipboard.
Users must enable the `allowClipboardAccess` options for this addon to
work.

Signed-off-by: Ayman Bagabas <ayman.bagabas@gmail.com>
  • Loading branch information
aymanbagabas committed Dec 26, 2022
1 parent 3aac12c commit 420f758
Show file tree
Hide file tree
Showing 19 changed files with 420 additions and 17 deletions.
2 changes: 2 additions & 0 deletions .eslintrc.json
Expand Up @@ -16,6 +16,8 @@
"addons/xterm-addon-attach/src/tsconfig.json",
"addons/xterm-addon-attach/test/tsconfig.json",
"addons/xterm-addon-canvas/src/tsconfig.json",
"addons/xterm-addon-clipboard/src/tsconfig.json",
"addons/xterm-addon-clipboard/test/tsconfig.json",
"addons/xterm-addon-fit/src/tsconfig.json",
"addons/xterm-addon-fit/test/tsconfig.json",
"addons/xterm-addon-ligatures/src/tsconfig.json",
Expand Down
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -79,6 +79,7 @@ terminal.loadAddon(new WebLinksAddon());
The xterm.js team maintains the following addons, but anyone can build them:

- [`xterm-addon-attach`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-attach): Attaches to a server running a process via a websocket
- [`xterm-addon-clipboard`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-clipboard): Access the browser's clipboard
- [`xterm-addon-fit`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-fit): Fits the terminal to the containing element
- [`xterm-addon-search`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-search): Adds search functionality
- [`xterm-addon-web-links`](https://github.com/xtermjs/xterm.js/tree/master/addons/xterm-addon-web-links): Adds web link detection and interaction
Expand Down
2 changes: 2 additions & 0 deletions addons/xterm-addon-clipboard/.gitignore
@@ -0,0 +1,2 @@
lib
node_modules
29 changes: 29 additions & 0 deletions addons/xterm-addon-clipboard/.npmignore
@@ -0,0 +1,29 @@
# Blacklist - exclude everything except npm defaults such as LICENSE, etc
*
!*/

# Whitelist - lib/
!lib/**/*.d.ts

!lib/**/*.js
!lib/**/*.js.map

!lib/**/*.css

# Whitelist - src/
!src/**/*.ts
!src/**/*.d.ts

!src/**/*.js
!src/**/*.js.map

!src/**/*.css

# Blacklist - src/ test files
src/**/*.test.ts
src/**/*.test.d.ts
src/**/*.test.js
src/**/*.test.js.map

# Whitelist - typings/
!typings/*.d.ts
19 changes: 19 additions & 0 deletions addons/xterm-addon-clipboard/LICENSE
@@ -0,0 +1,19 @@
Copyright (c) 2023, The xterm.js authors (https://github.com/xtermjs/xterm.js)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
22 changes: 22 additions & 0 deletions addons/xterm-addon-clipboard/README.md
@@ -0,0 +1,22 @@
## xterm-addon-clipboard

An addon for [xterm.js](https://github.com/xtermjs/xterm.js) that enables accessing the system clipboard. This addon requires xterm.js v4+.

### Install

```bash
npm install --save xterm-addon-clipboard
```

### Usage

```ts
import { Terminal } from 'xterm';
import { ClipboardAddon } from 'xterm-addon-clipboard';

const terminal = new Terminal();
const clipboardAddon = new ClipboardAddon();
terminal.loadAddon(clipboardAddon);
```

See the full [API](https://github.com/xtermjs/xterm.js/blob/master/addons/xterm-addon-clipboard/typings/xterm-addon-clipboard.d.ts) for more advanced usage.
26 changes: 26 additions & 0 deletions addons/xterm-addon-clipboard/package.json
@@ -0,0 +1,26 @@
{
"name": "xterm-addon-clipboard",
"version": "0.1.0",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
},
"main": "lib/xterm-addon-clipboard.js",
"types": "typings/xterm-addon-clipboard.d.ts",
"repository": "https://github.com/xtermjs/xterm.js",
"license": "MIT",
"keywords": [
"terminal",
"xterm",
"xterm.js"
],
"scripts": {
"build": "../../node_modules/.bin/tsc -p .",
"prepackage": "npm run build",
"package": "../../node_modules/.bin/webpack",
"prepublishOnly": "npm run package"
},
"peerDependencies": {
"xterm": "^5.0.0"
}
}
67 changes: 67 additions & 0 deletions addons/xterm-addon-clipboard/src/ClipboardAddon.ts
@@ -0,0 +1,67 @@
/**
* Copyright (c) 2023 The xterm.js authors. All rights reserved.
* @license MIT
*/

import { Terminal, ITerminalAddon, IClipboardEvent, ClipboardEventType, ClipboardSelectionType } from 'xterm';
import { Disposable } from 'common/Lifecycle';
import { ITerminal } from 'browser/Types';
import * as Base64 from 'common/Base64';


export class ClipboardAddon extends Disposable implements ITerminalAddon {
private _terminal: Terminal | undefined;

constructor() {
super();
}

// eslint-disable-next-line @typescript-eslint/naming-convention
private _handleClipboard(event: IClipboardEvent): void {
if (!this._terminal) {
return;
}
if (event.selection !== ClipboardSelectionType.CLIPBOARD) {
// TODO support primary selection on linux, browser doesn't support
// primary selection.
return;
}
const core = (this._terminal as any)._core as ITerminal;
switch (event.type) {
case ClipboardEventType.QUERY:
this.readText()
// report base64 encoded text back to terminal.
.then(text => Base64.encode(text))
.then(data => core.coreService.triggerDataEvent(data))
.catch(err => console.error(`Failed to read from clipboard: ${err}`));
break;
case ClipboardEventType.SET:
this.writeText(event.payload || '')
.catch(err => console.error(`Failed to write to clipboard: ${err}`));
break;
}
}

public activate(terminal: Terminal): void {
this._terminal = terminal;
this.register(terminal.onClipboard((event) => this._handleClipboard(event)));
}

public dispose(): void {
super.dispose();
}

public writeText(data: string): Promise<void> {
if (navigator.clipboard) {
return navigator.clipboard.writeText(data);
}
return Promise.reject(new Error('Clipboard API not available'));
}

public readText(): Promise<string> {
if (navigator.clipboard) {
return navigator.clipboard.readText();
}
return Promise.reject(new Error('Clipboard API not available'));
}
}
38 changes: 38 additions & 0 deletions addons/xterm-addon-clipboard/src/tsconfig.json
@@ -0,0 +1,38 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2015",
"lib": [
"dom",
"es2015"
],
"rootDir": ".",
"outDir": "../out",
"sourceMap": true,
"removeComments": true,
"strict": true,
"types": [
"../../../node_modules/@types/mocha"
],
"paths": {
"common/*": [
"../../../src/common/*"
],
"browser/*": [
"../../../src/browser/*"
]
}
},
"include": [
"./**/*",
"../../../typings/xterm.d.ts"
],
"references": [
{
"path": "../../../src/common"
},
{
"path": "../../../src/browser"
}
]
}
79 changes: 79 additions & 0 deletions addons/xterm-addon-clipboard/test/ClipboardAddon.api.ts
@@ -0,0 +1,79 @@
/**
* Copyright (c) 2023 The xterm.js authors. All rights reserved.
* @license MIT
*/

import { assert } from 'chai';
import { openTerminal, launchBrowser, writeSync, getBrowserType } from '../../../out-test/api/TestUtils';
import { Browser, BrowserContext, Page } from 'playwright';

const APP = 'http://127.0.0.1:3001/test';

let browser: Browser;
let context: BrowserContext;
let page: Page;
const width = 800;
const height = 600;

describe('ClipboardAddon', () => {
before(async function (): Promise<any> {
browser = await launchBrowser({
// Enable clipboard access in firefox, mainly for readText
firefoxUserPrefs: {
'dom.events.testing.asyncClipboard': true,
'dom.events.asyncClipboard.readText': true
}
});
context = await browser.newContext();
if (getBrowserType().name() !== 'webkit') {
// Enable clipboard access in chromium without user gesture
context.grantPermissions(['clipboard-read', 'clipboard-write']);
}
page = await context.newPage();
await page.setViewportSize({ width, height });
await page.goto(APP);
await openTerminal(page, { allowClipboardAccess: true });
await page.evaluate(`
window.clipboardAddon = new ClipboardAddon();
window.term.loadAddon(window.clipboardAddon);
`);
});

after(() => {
browser.close();
});

beforeEach(async () => {
await page.evaluate(`window.term.reset()`);
});

const testDataEncoded = 'aGVsbG8gd29ybGQ=';
const testDataDecoded = 'hello world';

describe('write data', async function (): Promise<any> {
it('simple string', async () => {
await writeSync(page, `\x1b]52;c;${testDataEncoded}\x07`);
assert.deepEqual(await page.evaluate(() => window.navigator.clipboard.readText()), testDataDecoded);
});
it('invalid base64 string', async () => {
await writeSync(page, `\x1b]52;c;${testDataEncoded}invalid\x07`);
assert.deepEqual(await page.evaluate(() => window.navigator.clipboard.readText()), '');
});
it('empty string', async () => {
await writeSync(page, `\x1b]52;c;\x07`);
assert.deepEqual(await page.evaluate(() => window.navigator.clipboard.readText()), '');
});
});

describe('read data', async function (): Promise<any> {
it('simple string', async () => {
await page.evaluate(`
window.data = [];
window.term.onData(e => data.push(e));
`);
await page.evaluate(() => window.navigator.clipboard.writeText('hello world'));
await writeSync(page, `\x1b]52;c;?\x07`);
assert.deepEqual(await page.evaluate(`window.data`), [testDataEncoded]);
});
});
});
23 changes: 23 additions & 0 deletions addons/xterm-addon-clipboard/test/tsconfig.json
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2015",
"lib": [
"es2015"
],
"rootDir": ".",
"outDir": "../out-test",
"sourceMap": true,
"removeComments": true,
"strict": true,
"types": [
"../../../node_modules/@types/mocha",
"../../../node_modules/@types/node",
"../../../out-test/api/TestUtils"
]
},
"include": [
"./**/*",
"../../../typings/xterm.d.ts"
]
}
8 changes: 8 additions & 0 deletions addons/xterm-addon-clipboard/tsconfig.json
@@ -0,0 +1,8 @@
{
"files": [],
"include": [],
"references": [
{ "path": "./src" },
{ "path": "./test" }
]
}
42 changes: 42 additions & 0 deletions addons/xterm-addon-clipboard/typings/xterm-addon-clipboard.d.ts
@@ -0,0 +1,42 @@
/**
* Copyright (c) 2023 The xterm.js authors. All rights reserved.
* @license MIT
*/

import { Terminal, ITerminalAddon, IClipboardEvent } from 'xterm';
import { Disposable } from 'common/Lifecycle';

declare module 'xterm-addon-clipboard' {
/**
* An xterm.js addon that enables accessing the system clipboard from
* xterm.js.
*/
export class ClipboardAddon extends Disposable implements ITerminalAddon {
/**
* Creates a new clipboard addon.
*/
constructor();

/**
* Activates the addon
* @param terminal The terminal the addon is being loaded in.
*/
public activate(terminal: Terminal): void;

/**
* Disposes the addon.
*/
public dispose(): void

/**
* Writes text to the clipboard.
* @param data The text to write to the clipboard.
*/
public writeText(data: string): Promise<void>

/**
* Reads text from the clipboard.
*/
public readText(): Promise<string>
}
}

0 comments on commit 420f758

Please sign in to comment.