Xterm.js入門(mén)官方文檔示例詳解
前言
入職的新公司所在的事業(yè)部專(zhuān)注于K12的編程教育。公司項(xiàng)目里有使用xterm.js這個(gè)庫(kù), 并基于master分支做出了一定的修改。為了盡快的熟悉業(yè)務(wù)以及公司的代碼, 所以這里打算學(xué)習(xí)xterm.js的文檔(粗略的翻譯, 方便自己查閱, 凡是保留原文的地方, 是我目前還沒(méi)有明白具體使用場(chǎng)景和用法的地方)
xterm.js是什么?
xterm是一個(gè)使用TypeScript編寫(xiě)的前端終端組件。并在Vscode等熱門(mén)項(xiàng)目中得到了應(yīng)用
安裝
npm install xterm
初始化
// 初始化終端 import { Terminal } from 'xterm' import 'xterm/dist/xterm.css' let term = new Terminal() // 將term掛砸到dom節(jié)點(diǎn)上 term.open(document.getElementById('app')) term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
使用插件
插件為javascript的模塊可以擴(kuò)展Terminal的原型
import { Terminal } from 'xterm'; import * as fit from 'xterm/lib/addons/fit/fit' // 擴(kuò)展Terminal Terminal.applyAddon(fit) let term = new Terminal() term.open(document.getElementById('#terminal')) // 使用fit方法 term.fit()
API文檔模塊
xterm
這里包含了xterm.js的類(lèi)型聲明文件d.ts
type alias FontWeight
終端的字體粗細(xì)
type alias RendererType
終端的渲染方式, dom渲染或者是canvas渲染
類(lèi) Terminal
構(gòu)造函數(shù) constructor
創(chuàng)建一個(gè)新的Terminal對(duì)象
// 參數(shù)類(lèi)型, 需要ITerminalOptions接口的定義 // 返回Terminal類(lèi)型 new Terminal(options?: ITerminalOptions): Terminal
- 屬性 cols
終端窗口的列數(shù), 可以在創(chuàng)建Terminal指定cols
// 終端中每一行最多一列 let term = new Terminal({ cols: 1 })
- 屬性 element
// 終端掛載的Dom元素 term.element
- 屬性 markers
終端的所有標(biāo)記
- 屬性 rows
終端窗口的行數(shù), 可以在創(chuàng)建Terminal指定rows
let term = new Terminal({ rows: 30 })
- 屬性 textarea
返回, 接受終端輸入的textarea的dom節(jié)點(diǎn)
- 靜態(tài)屬性 strings
Natural language strings that can be localized.
- 方法 addCsiHandler
Adds a handler for CSI escape sequences.
- 方法 addDisposableListener
向終端添加事件監(jiān)聽(tīng)器, 并返回可用于刪除事件監(jiān)聽(tīng)器的對(duì)象, 對(duì)象中dispose屬性的方法可以取消監(jiān)聽(tīng)。支持的事件參考o(jì)ff方法的內(nèi)容。
// 終端添加focus事件的監(jiān)聽(tīng), dispose函數(shù)可以取消監(jiān)聽(tīng) const { dispose } = term.addDisposableListener('focus', function () { console.log('focus') dispose() })
- 方法 addMarker
添加標(biāo)記, addMarker接受一個(gè)數(shù)字作為參數(shù), 數(shù)字表示當(dāng)前光標(biāo)到標(biāo)記y的偏移量,并返回標(biāo)記。
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) // 返回兩個(gè)標(biāo)記 console.log(term.markers)
- 方法 addOscHandler
Adds a handler for OSC escape sequences.
- 方法 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.
- 方法 deregisterCharacterJoiner
Deregisters the character joiner if one was registered. NOTE: character joiners are only used by the canvas renderer.
- 方法 deregisterLinkMatcher
Deregisters a link matcher if it has been registered.
- 方法 blur
使終端失焦
- 方法 clear
清除整個(gè)終端, 只保留當(dāng)前行
- 方法 selectAll
選擇終端內(nèi)的所有文本
- 方法 selectLines
選中指定的兩個(gè)指定行之間的終端文本
term.write('Hello from \x1B[1;3;31mxterm.js\x1B') term.selectLines(0, 0)
方法 clearSelection 清除當(dāng)前選擇的終端(只是清除選擇的內(nèi)容, 而非清除終端)
方法 destroy 銷(xiāo)毀終端, 不推薦使用。推薦使用dispose()
方法 dispose 銷(xiāo)毀終端
方法 focus 終端獲得焦點(diǎn)
方法 getOption 獲取的終端的配置選項(xiàng), 需要指定配置的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'))
詳細(xì)的類(lèi)型推導(dǎo)請(qǐng)參考下圖
- 方法 getSelection
獲取當(dāng)前終端選擇的內(nèi)容。(鼠標(biāo)光標(biāo)選中的內(nèi)容)
- 方法 hasSelection
判斷當(dāng)前終端是否有選中的內(nèi)容。(鼠標(biāo)光標(biāo)選中的內(nèi)容)
- 方法 off
刪除事件監(jiān)聽(tīng), 支持的方法見(jiàn)上圖
- 方法 on
添加事件監(jiān)聽(tīng), 支持注冊(cè)的事件如上圖
方法 open 打開(kāi)終端。(xterm必須掛載dom完成)
方法 refresh 刷新指定兩行之間的內(nèi)容
- 方法 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.
- 方法 registerLinkMatcher
Registers a link matcher, allowing custom link patterns to be matched and handled.
方法 reset 重置整個(gè)終端
方法 resize 調(diào)整終端的大小, 參數(shù)為指定的col, row
方法 scrollLines 控制終端滾動(dòng)條的滾動(dòng)的行數(shù)(正數(shù)向下滾動(dòng), 負(fù)數(shù)向上滾動(dòng))
方法 scrollPages 滾動(dòng)的頁(yè)面樹(shù)(正數(shù)向下滾動(dòng), 負(fù)數(shù)向上滾動(dòng))
方法 scrollToBottom 滾動(dòng)到底部
方法 scrollToLine 滾動(dòng)到具體的行
方法 scrollToTop 滾動(dòng)到頂部
方法 setOption 設(shè)置終端的配置
具體的配置請(qǐng)參考下圖
方法 writeln 向終端寫(xiě)入文本并換行
方法 write 向終端寫(xiě)入文本
靜態(tài)方法 applyAddon
添加插件到終端的原型上
接口
這里沒(méi)有什么好翻譯的了, Xterm.js是由TypeScript編寫(xiě)。這里定義Xterm內(nèi)部以及外部參數(shù)和返回值的iterface
插件
attach插件
attach可以將終端附加到websocket流中。Terminal實(shí)例會(huì)捕獲所有鍵盤(pán)和鼠標(biāo)事件并通過(guò)socket發(fā)送給后端
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實(shí)例 // bidirectional 終端是否向套接字發(fā)送數(shù)據(jù) // bufferred 終端是否緩沖輸出獲得更好的性能 attach(socket: WebSocket, bidirectional: Boolean, bufferred: Boolean)
方法 detach
// 分離當(dāng)前終端和scoket detach(socket)
fit 調(diào)整終端的大小以及行和列適配父級(jí)元素
fullscreen
fullscreen插件提供了設(shè)置全屏終端的toggleFullScreen方法, toggleFullScreen接受Boolean類(lèi)型的值, 設(shè)置是否全屏展示終端
前后端示例
// 前端代碼 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', '代碼運(yùn)行結(jié)束') }) }) 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
結(jié)語(yǔ)
到這里我們大概對(duì)Xterm.js這個(gè)庫(kù)有了一個(gè)初步的認(rèn)知, 不至于在接下來(lái)的工作中無(wú)從下手了
以上就是Xterm.js入門(mén)官方文檔示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Xterm.js 官方文檔的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Typescript使用裝飾器實(shí)現(xiàn)接口字段映射與Mock實(shí)例
這篇文章主要為大家介紹了Typescript使用裝飾器實(shí)現(xiàn)接口字段映射與Mock實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04使用typeScript 進(jìn)行扁平化數(shù)據(jù)轉(zhuǎn)樹(shù)實(shí)現(xiàn)demo
這篇文章主要介紹了使用typeScript 進(jìn)行扁平化數(shù)據(jù)轉(zhuǎn)樹(shù)實(shí)現(xiàn)demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06聯(lián)合類(lèi)型Union?Types與交叉類(lèi)型Intersection?Types區(qū)別解析
這篇文章主要為大家介紹了聯(lián)合類(lèi)型Union?Types與交叉類(lèi)型Intersection?Types區(qū)別詳解2023-06-06基于Javascript實(shí)現(xiàn)頁(yè)面商品個(gè)數(shù)增減功能
本文給大家介紹基于Javascript實(shí)現(xiàn)頁(yè)面商品個(gè)數(shù)增減功能,通過(guò)點(diǎn)擊數(shù)量增減個(gè)數(shù),代碼分為前端頁(yè)面,后臺(tái)返回代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2019-07-07less簡(jiǎn)單入門(mén)(CSS 預(yù)處理語(yǔ)言)
Less 是一門(mén) CSS 預(yù)處理語(yǔ)言,它擴(kuò)充了 CSS 語(yǔ)言,增加了諸如變量、混合(mixin)、函數(shù)等功能,讓 CSS 更易維護(hù)、方便制作主題、擴(kuò)充2017-03-03FastAdmin表單驗(yàn)證data-rule插件—Nice-validator的使用方法
FastAdmin的表單驗(yàn)證data-rule非常方便,也很炫酷,采用的Nice-validator是一款非常強(qiáng)大的表單驗(yàn)證插件,通過(guò)簡(jiǎn)單在元素上配置規(guī)則,即可達(dá)到驗(yàn)證的效果,怎么使用Nice-validator插件呢2023-09-09