preface

The business department of the new company focuses on K12 programming education. The xterm.js library was used in the company project, and some changes were made based on the Master branch. In order to get familiar with the business and the code of the company as soon as possible, I plan to learn the document of Xterm.js (a rough translation for easy reference. Where the original text is reserved, I have not yet understood the specific usage scenarios and usage).

I have been busy recently, and I dare not go home too early. So it’s only updated this Saturday at 😢

What is xterm.js?

Xterm is a front-end terminal component written in TypeScript. It has been used in popular projects such as Vscode

The document

The installation


npm install xterm
Copy the code

Initialize the

// Initialize the terminal
import { Terminal } from 'xterm'
import 'xterm/dist/xterm.css'

let term = new Terminal()

// Drop the term on the DOM node
term.open(document.getElementById('app'))

term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
Copy the code

The use of plug-in

Plug-ins for javascript modules can extend the Terminal prototype


import { Terminal } from 'xterm';
import * as fit from 'xterm/lib/addons/fit/fit'

/ / expand the Terminal
Terminal.applyAddon(fit)

let term = new Terminal()
term.open(document.getElementById('#terminal'))

Use the FIT method
term.fit()
Copy the code

The API documentation

The module

xterm

This contains the type declaration file d.ts for xterm.js

type alias FontWeight

Font size of the terminal

type alias RendererType

Terminal render, DOM render or Canvas render

class

Terminal
Constructor

Create a new Terminal object

// The parameter type needs to be defined by the ITerminalOptions interface
// Return the Terminal type

newTerminal(options? : ITerminalOptions): TerminalCopy the code
Attribute cols

Cols specifies the number of columns in the Terminal window

// At most one column per row in a terminal
let term = new Terminal({ cols: 1 })
Copy the code
Attribute element
// The Dom element mounted by the terminal
term.element
Copy the code
Attributes markers

All flags of the terminal

Attributes, rows

The number of rows in the Terminal window can be specified when creating Terminal


let term = new Terminal({ rows: 30 })
Copy the code
Attribute textarea

Returns the DOM node that accepts the textarea input from the terminal

Static property strings

Natural language strings that can be localized.

Methods addCsiHandler

Adds a handler for CSI escape sequences.

Methods addDisposableListener

Add an event listener to the terminal and return an object that can be used to remove the event listener. The method of the Dispose property in the object can cancel the listener. The supported events refer to the contents of the OFF method.


Dispose function can cancel the listener of focus event

const { dispose } = term.addDisposableListener('focus'.function () {
  console.log('focus')
  dispose()
})
Copy the code
Methods addMarker

Add a marker, and addMarker takes a number as a parameter representing the offset from the current cursor to marker Y, and returns the marker.


let buffer = term.addMarker(cursorYOffset: number): IMarker

let term = new Terminal()
term.open(document.getElementById('app'))
term.write('Hello from \x1B[1;3;31mxterm.js\x1B')
term.addMarker(0)
term.addMarker(1)
// Return two tokens
console.log(term.markers)
Copy the code
Methods addOscHandler

Adds a handler for OSC escape sequences.

Methods attachCustomKeyEventHandler

Attaches a custom key event handler which is run before keys are processed, giving consumers of xterm.js ultimate control as to what keys should be processed by the terminal and what keys should not.

Methods deregisterCharacterJoiner

Deregisters the character joiner if one was registered. NOTE: character joiners are only used by the canvas renderer.

Methods deregisterLinkMatcher

Deregisters a link matcher if it has been registered.

Methods the blur

Cause terminal to lose focus

Methods the clear

Clear the entire terminal, reserving only the current line

Methods selectAll

Select all the text in the terminal

Methods selectLines

Selects terminal text between the specified two specified lines


term.write('Hello from \x1B[1;3;31mxterm.js\x1B')

term.selectLines(0.0)
Copy the code
Methods clearSelection

Clear the currently selected terminal (clear the selected content, not clear the terminal)

Methods destroy

Destroy the terminal. Not recommended. Dispose () is recommended

Methods the dispose

Destruction of the terminal

Methods the focus

Terminal gain focus

Methods getOption

To obtain the configuration options of the terminal, you need to specify the configuration key


let term = new Terminal({
  fontWeight: '800'.fontSize: 20
})

term.open(document.getElementById('app'))
term.write('Hello from \x1B[1;3;31mxterm.js\x1B')

/ / '800'
console.log(term.getOption('fontWeight'))
/ / 20
console.log(term.getOption('fontSize'))
Copy the code

See the figure below for a detailed type derivation

Methods getSelection

Gets the current terminal selection. (Mouse cursor selected)

Methods hasSelection

Check whether the current terminal has selected content. (Mouse cursor selected)

Way off

Delete event listening. The supported methods are shown in the figure above

Methods on

Add event listener, support registered events as shown in the figure above

Methods the open

Open the terminal. (Xterm must mount DOM complete)

Methods the refresh

Refreshes the content between the specified two lines

Methods registerCharacterJoiner

Registers a character joiner, allowing custom sequences of characters to be rendered as a single unit. This is useful in particular for rendering ligatures and graphemes, among other things.

Each registered character joiner is called with a string of text representing a portion of a line in the terminal that can be rendered as a single unit. The joiner must return a sorted array, where each entry is itself an array of length two, containing the start (inclusive) and end (exclusive) index of a substring of the input that should be rendered as a single unit. When multiple joiners are provided, the results of each are collected. If there are any overlapping substrings between them, they are combined into one larger unit that is drawn together.

All character joiners that are registered get called every time a line is rendered in the terminal, so it is essential for the handler function to run as quickly as possible to avoid slowdowns when rendering. Similarly, joiners should strive to return the smallest possible substrings to render together, since they aren’t drawn as optimally as individual characters.

NOTE: character joiners are only used by the canvas renderer.

Methods registerLinkMatcher

Registers a link matcher, allowing custom link patterns to be matched and handled.

Methods the reset

Resetting the entire terminal

Methods the resize

Resize the terminal using the specified col, row

Methods scrollLines

Controls the number of lines that the terminal scroll bar scrolls (positive scroll down, negative scroll up)

Methods scrollPages

Page tree scrolling (positive scroll down, negative scroll up)

Methods scrollToBottom

Scroll to the bottom

Methods scrollToLine

Scroll to the specific row

Methods scrollToTop

Scroll to the top

Methods setOption

Set terminal configurations. For details, see the following figure

Methods writeln

Writes text to a terminal and wraps it

Methods the write

Writes text to a terminal

Static method applyAddon

Add a plug-in to the terminal prototype

interface

There is nothing to translate here, xterm.js is written in TypeScript. This defines the iterface of Xterm’s internal and external parameters and return values

The plug-in

Attach the plugin

Attach attaches a terminal to a WebSocket flow. The Terminal instance captures all keyboard and mouse events and sends them over the socket to the back end


import * as Terminal from 'xterm';
import * as attach from 'xterm/lib/addons/attach/attach';

// Add the attach plugin
Terminal.applyAddon(attach);

var term = new Terminal();
var socket = new WebSocket('wss://docker.example.com/containers/mycontainerid/attach/ws');

term.attach(socket)
Copy the code
Methods the attach
// socket socoket instance
// Whether the bidirectional terminal sends data to the socket
// Bufferred whether the terminal buffered output for better performance
attach(socket: WebSocket, bidirectional: Boolean.bufferred: Boolean)
Copy the code
Methods the detach
// Separate the current terminal from the scoket
detach(socket)
Copy the code
fit

Adjust the size of the terminal and the row and column to fit the parent element

fullscreen

The fullscreen plugin provides a toggleFullScreen method for setting up a full-screen terminal. ToggleFullScreen accepts a Boolean value for displaying a terminal in fullscreen

Front and back end Examples


// Front-end code

import { Terminal } from 'xterm'
import 'xterm/dist/xterm.css'
import io from 'socket.io-client';

const socket = io('http://localhost:3000');

let term = new Terminal({
  fontSize: 30
})

term.open(document.getElementById('app'))

socket.on('concat'.function (data) {
  socket.emit('run', { xml: ` #include 
      
        using namespace std; int main() { cout << "Nice to meet you."; return 0; } `
      })
  socket.on('writeIn'.function (xml) {
    term.writeln(xml)
  })
})
Copy the code

// Back-end code
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
const server = require('http').createServer(app.callback())
const io = require('socket.io')(server)

const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const config = require('./config')
const routes = require('./routes')

onerror(app)

app.use(bodyparser())
  .use(json())
  .use(logger())
  .use(router.routes())
  .use(router.allowedMethods())

routes(router)

io.on('connection'.function (socket) {
  socket.emit('concat');
  socket.on('run'.function () {
    socket.emit('writeIn'.'Compiled successfully')
    socket.emit('writeIn'.'End of code run')
  })
})

app.on('error'.function(err, ctx) {
  logger.error('server error', err, ctx)
})

module.exports = server.listen(config.port, () => {
  console.log(`Listening on http://localhost:${config.port}`)
})
s
Copy the code

conclusion

At this point, we have a general idea of the xterm.js library, so we won’t be confused about what to do next