前言入职的新公司所在的事业部专注于K12的编程教育。公司项目里有使用xterm.js这个库, 并基于master分支做出了一定的修改。为了尽快的熟悉业务以及公司的代码, 所以这里打算学习xterm.js的文档(粗略的翻译, 方便自己查阅, 凡是保留原文的地方, 是我目前还没有明白具体使用场景和用法的地方)最近比较忙啊, 还没有过试用期也不敢太早回家。所以只有这个周六更新了 ????xterm.js是什么?xterm是一个使用TypeScript编写的前端终端组件。并在Vscode等热门项目中得到了应用文档安装npm install xterm初始化// 初始化终端import { Terminal } from ‘xterm’import ‘xterm/dist/xterm.css’let term = new Terminal()// 将term挂砸到dom节点上term.open(document.getElementById(‘app’))term.write(‘Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ‘)使用插件插件为javascript的模块可以扩展Terminal的原型import { Terminal } from ‘xterm’;import * as fit from ‘xterm/lib/addons/fit/fit’// 扩展TerminalTerminal.applyAddon(fit)let term = new Terminal()term.open(document.getElementById(’#terminal’))// 使用fit方法term.fit()API文档模块xterm这里包含了xterm.js的类型声明文件d.tstype alias FontWeight终端的字体粗细type alias RendererType终端的渲染方式, dom渲染或者是canvas渲染类Terminal构造函数 constructor创建一个新的Terminal对象// 参数类型, 需要ITerminalOptions接口的定义// 返回Terminal类型new Terminal(options?: ITerminalOptions): Terminal属性 cols终端窗口的列数, 可以在创建Terminal指定cols// 终端中每一行最多一列let term = new Terminal({ cols: 1 })属性 element// 终端挂载的Dom元素term.element属性 markers终端的所有标记属性 rows终端窗口的行数, 可以在创建Terminal指定rowslet term = new Terminal({ rows: 30 })属性 textarea返回, 接受终端输入的textarea的dom节点静态属性 stringsNatural language strings that can be localized.方法 addCsiHandlerAdds a handler for CSI escape sequences.方法 addDisposableListener向终端添加事件监听器, 并返回可用于删除事件监听器的对象, 对象中dispose属性的方法可以取消监听。支持的事件参考off方法的内容。// 终端添加focus事件的监听, dispose函数可以取消监听const { dispose } = term.addDisposableListener(‘focus’, function () { console.log(‘focus’) dispose()})方法 addMarker添加标记, addMarker接受一个数字作为参数, 数字表示当前光标到标记y的偏移量,并返回标记。let buffer = term.addMarker(cursorYOffset: number): IMarkerlet term = new Terminal()term.open(document.getElementById(‘app’))term.write(‘Hello from \x1B[1;3;31mxterm.js\x1B’)term.addMarker(0)term.addMarker(1)// 返回两个标记console.log(term.markers)方法 addOscHandlerAdds a handler for OSC escape sequences.方法 attachCustomKeyEventHandlerAttaches 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.方法 deregisterCharacterJoinerDeregisters the character joiner if one was registered. NOTE: character joiners are only used by the canvas renderer.方法 deregisterLinkMatcherDeregisters a link matcher if it has been registered.方法 blur使终端失焦方法 clear清除整个终端, 只保留当前行方法 selectAll选择终端内的所有文本方法 selectLines选中指定的两个指定行之间的终端文本term.write(‘Hello from \x1B[1;3;31mxterm.js\x1B’)term.selectLines(0, 0)方法 clearSelection清除当前选择的终端(只是清除选择的内容, 而非清除终端)方法 destroy销毁终端, 不推荐使用。推荐使用dispose()方法 dispose销毁终端方法 focus终端获得焦点方法 getOption获取的终端的配置选项, 需要指定配置的keylet 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’))// 20console.log(term.getOption(‘fontSize’))详细的类型推导请参考下图方法 getSelection获取当前终端选择的内容。(鼠标光标选中的内容)方法 hasSelection判断当前终端是否有选中的内容。(鼠标光标选中的内容)方法 off删除事件监听, 支持的方法见上图方法 on添加事件监听, 支持注册的事件如上图方法 open打开终端。(xterm必须挂载dom完成)方法 refresh刷新指定两行之间的内容方法 registerCharacterJoinerRegisters 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.方法 registerLinkMatcherRegisters a link matcher, allowing custom link patterns to be matched and handled.方法 reset重置整个终端方法 resize调整终端的大小, 参数为指定的col, row方法 scrollLines控制终端滚动条的滚动的行数(正数向下滚动, 负数向上滚动)方法 scrollPages滚动的页面树(正数向下滚动, 负数向上滚动)方法 scrollToBottom滚动到底部方法 scrollToLine滚动到具体的行方法 scrollToTop滚动到顶部方法 setOption设置终端的配置, 具体的配置请参考下图方法 writeln向终端写入文本并换行方法 write向终端写入文本静态方法 applyAddon添加插件到终端的原型上接口这里没有什么好翻译的了, Xterm.js是由TypeScript编写。这里定义Xterm内部以及外部参数和返回值的iterface插件attach插件attach可以将终端附加到websocket流中。Terminal实例会捕获所有键盘和鼠标事件并通过socket发送给后端import * as Terminal from ‘xterm’;import * as attach from ‘xterm/lib/addons/attach/attach’;// 添加attach插件Terminal.applyAddon(attach);var term = new Terminal();var socket = new WebSocket(‘wss://docker.example.com/containers/mycontainerid/attach/ws’);term.attach(socket)方法 attach// socket socoket实例// bidirectional 终端是否向套接字发送数据// bufferred 终端是否缓冲输出获得更好的性能attach(socket: WebSocket, bidirectional: Boolean, bufferred: Boolean)方法 detach// 分离当前终端和scoketdetach(socket)fit调整终端的大小以及行和列适配父级元素fullscreenfullscreen插件提供了设置全屏终端的toggleFullScreen方法, toggleFullScreen接受Boolean类型的值, 设置是否全屏展示终端前后端示例// 前端代码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 <iostream> using namespace std; int main() { cout << "Nice to meet you."; return 0; } }) socket.on(‘writeIn’, function (xml) { term.writeln(xml) })})// 后端代码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’, ‘编译成功’) socket.emit(‘writeIn’, ‘代码运行结束’) })})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结语到这里我们大概对Xterm.js这个库有了一个初步的认知, 不至于在接下来的工作中无从下手了