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