溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Xterm.js是什么及怎么使用

發(fā)布時(shí)間:2022-11-03 10:17:32 來源:億速云 閱讀:269 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Xterm.js是什么及怎么使用”的相關(guān)知識(shí),小編通過實(shí)際案例向大家展示操作過程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“Xterm.js是什么及怎么使用”文章能幫助大家解決問題。

    xterm.js是什么?

    xterm是一個(gè)使用TypeScript編寫的前端終端組件。并在Vscode等熱門項(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的類型聲明文件d.ts

    type alias FontWeight

    終端的字體粗細(xì)

    type alias RendererType

    終端的渲染方式, dom渲染或者是canvas渲染

    類 Terminal

    構(gòu)造函數(shù) constructor

    創(chuàng)建一個(gè)新的Terminal對(duì)象

    // 參數(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

    終端的所有標(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)聽器, 并返回可用于刪除事件監(jiān)聽器的對(duì)象, 對(duì)象中dispose屬性的方法可以取消監(jiān)聽。支持的事件參考o(jì)ff方法的內(nèi)容。

    // 終端添加focus事件的監(jiān)聽, dispose函數(shù)可以取消監(jiān)聽
    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 銷毀終端, 不推薦使用。推薦使用dispose()

    方法 dispose 銷毀終端

    方法 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ì)的類型推導(dǎo)請(qǐng)參考下圖

    Xterm.js是什么及怎么使用

    • 方法 getSelection

    獲取當(dāng)前終端選擇的內(nèi)容。(鼠標(biāo)光標(biāo)選中的內(nèi)容)

    • 方法 hasSelection

    判斷當(dāng)前終端是否有選中的內(nèi)容。(鼠標(biāo)光標(biāo)選中的內(nèi)容)

    • 方法 off

    Xterm.js是什么及怎么使用

    刪除事件監(jiān)聽, 支持的方法見上圖

    • 方法 on

    Xterm.js是什么及怎么使用

    添加事件監(jiān)聽, 支持注冊(cè)的事件如上圖

    方法 open 打開終端。(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ù)向下滾動(dòng), 負(fù)數(shù)向上滾動(dòng))

    方法 scrollToBottom 滾動(dòng)到底部

    方法 scrollToLine 滾動(dòng)到具體的行

    方法 scrollToTop 滾動(dòng)到頂部

    方法 setOption 設(shè)置終端的配置

    具體的配置請(qǐng)參考下圖

    Xterm.js是什么及怎么使用

    方法 writeln 向終端寫入文本并換行

    方法 write 向終端寫入文本

    靜態(tài)方法 applyAddon

    添加插件到終端的原型上

    接口

    這里沒有什么好翻譯的了, Xterm.js是由TypeScript編寫。這里定義Xterm內(nèi)部以及外部參數(shù)和返回值的iterface

    插件

    attach插件

    attach可以將終端附加到websocket流中。Terminal實(shí)例會(huì)捕獲所有鍵盤和鼠標(biāo)事件并通過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類型的值, 設(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

    關(guān)于“Xterm.js是什么及怎么使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI