vue-web-terminal

repository·vue3·Indexed 43 days ago

https://github.com/tzfun/vue-web-terminal

A Vue-based plugin for creating a web-side command line interface that simulates a native terminal experience. It handles UI concerns such as command history, cursor movement, and rendering various message formats including JSON, tables, code, HTML, and ANSI. Version 3.4.2 supports Vue 3, while version 2.x.x supports Vue 2 (archived as of December 2024). The plugin acts as an interface layer; developers must implement their own command execution logic by listening to the @exec-cmd event.

Tokens
6.4K
Snippets
22
Records
24
Agent score
56%

What's inside vue-web-terminal

  1. Overview of vue-web-terminal

    vue3

    vue-web-terminal is a Vue-based plugin that provides a web-based command-line interface (CLI) component. It is designed to display various message formats such as plain text, tables, JSON, code/multi-line text, HTML, and ANSI.

    Key Capabilities:

    • Message Rendering: Supports real-time echoing, appending, and various formats (tables, JSON, etc.).
    • User Interaction: Supports user input, command history (using ↑/↓ keys), and cursor movement (using ←/→ keys).
    • UI Features: Supports window dragging, pinning, full-screen mode, command input suggestions, and log grouping/collapsing.
    • Customization: Provides multiple slots for custom styling, built-in dark/light themes, and a rich JS API to simulate non-human operations.

    Important Mental Model: This plugin does not execute commands itself. It acts as the interface layer: it captures the command from the user and presents the results back to the user. The developer is responsible for implementing the actual command execution logic.

  2. Supported message formats and features

    vue3

    The vue-web-terminal supports a variety of message formats and UI features to simulate a native terminal experience:

    Message Formats:

    • Plain text
    • Tables
    • JSON
    • Code / Multi-line text
    • HTML
    • ANSI

    Core Features:

    • Real-time content display and appending (with animation effects).
    • User question and answer input.
    • Online text editing.
    • Window dragging and fixing.
    • Fullscreen support.
    • Command input prompts and logging group folding.
    • Keyboard support: ← and → for cursor/mode switching, ↑ and ↓ for command history.
    • Theming: Built-in dark and light themes, plus custom theme support.
    • Slot support: Multiple styles of slots for customization.
  3. Implement command execution logic

    vue3

    The vue-web-terminal component provides the interface for user input but does not execute commands itself. You must implement the execution logic by listening to the @exec-cmd event on the <terminal> component.

    When a user enters a command, the @exec-cmd event provides:

    • key: A string identifying the command type (e.g., 'fail').
    • command: The actual command string entered by the user.
    • success: A callback function (SuccessFunc) to display successful output.
    • failed: A callback function (FailedFunc) to display error messages.

    To display output via the success callback, pass an object with the following structure:

    • type: The message type (e.g., 'normal').
    • class: A CSS class for styling (e.g., 'success', 'error', 'system', 'info', 'warning').
    • tag: A tag for categorization (e.g., 'success').
    • content: The content to display.
    <script setup lang="ts">
      import {Terminal, SuccessFunc, FailedFunc} from "vue-web-terminal"
    
      const onExecCmd = (key: string, command: string, success: SuccessFunc, failed: FailedFunc) => {
        if (key === 'fail') {
          failed('Something wrong!!!')
        } else {
          let allClass = ['success', 'error', 'system', 'info', 'warning'];
    
          let clazz = allClass[Math.floor(Math.random() * allClass.length)];
          success({
            type: 'normal',
            class: clazz,
            tag: 'success',
            content: command
          })
        }
      }
    </script>
    
    <template>
      <div id="app">
        <terminal name="my-terminal" @exec-cmd="onExecCmd"></terminal>
      </div>
    </template>
  4. Install vue-web-terminal for Vue 2 or Vue 3

    vue3

    Install the version of vue-web-terminal that matches your Vue version using npm.

    • For Vue 2, use the 2.x.x version.
    • For Vue 3, use the 3.x.x version.

    Note: The Vue 2 version is officially archived as of December 24, 2024, and no longer receives maintenance updates.

    # install for vue2
    npm install vue-web-terminal@2.xx --save
    
    # install for vue3
    npm install vue-web-terminal@3.xx --save 
  5. Register the Terminal plugin in Vue 3

    vue3

    To use the terminal in a Vue 3 project, import createTerminal and use it with your app instance via app.use().

    import { createTerminal } from 'vue-web-terminal'
    
    const app = createApp(App)
    
    app.use(createTerminal())
    
    app.mount('#app')
  6. Define and send Terminal messages

    vue3

    Messages in the terminal are structured using the Message type. This allows for rich content types and visual styling.

    Message Properties:

    • type: The content format ('cmdLine' | 'normal' | 'json' | 'code' | 'table' | 'html' | 'ansi').
    • content: The actual data. Can be a string, number, object, MessageContentTable, or an Array.
    • class: The visual style ('success' | 'error' | 'info' | 'warning' | 'system').
    • tag: An optional identifier for grouping or filtering.
    • depth: An optional nesting level.

    MessageContentTable Format: For table-style messages, use the following structure:

    { 
      head: string[], 
      rows: string[][] 
    }
    // Example of a rich table message
    const tableMsg: Message = {
      type: 'table',
      content: {
        head: ['ID', 'Name', 'Status'],
        rows: [
          ['1', 'Server-A', 'Running'],
          ['2', 'Server-B', 'Stopped']
        ]
      },
      class: 'info'
    };
  7. Install vue-web-terminal as a Vue plugin

    vue3

    To use vue-web-terminal in your Vue application, use the install method provided by createTerminal(). This initializes the internal store and registers the Terminal component globally.

    import { createTerminal } from 'vue-web-terminal';
    
    const terminalPlugin = createTerminal();
    
    // In your main entry file (e.g., main.ts)
    const app = createApp(App);
    terminalPlugin.install(app);
    app.mount('#app');
  8. Implement command execution with the @exec-cmd event

    vue3

    To make the terminal functional, listen for the @exec-cmd event on the <terminal> component. This event provides the command key, the command string, and two callback functions: success and failed.

    • success(options): Use this to display a successful command output. The options object can include type, class, tag, and content.
    • failed(message): Use this to display an error message to the user.

    Example implementation in a Vue 3 <script setup> component:

    <script setup lang="ts">
      import {Terminal, SuccessFunc, FailedFunc} from "vue-web-terminal"
    
      const onExecCmd = (key: string, command: string, success: SuccessFunc, failed: FailedFunc) => {
        if (key === 'fail') {
          failed('Something wrong!!!')
        } else {
          // Example of cycling through different visual styles
          let allClass = ['success', 'error', 'system', 'info', 'warning'];
          let clazz = allClass[Math.floor(Math.random() * allClass.length)];
          
          success({
            type: 'normal',
            class: clazz,
            tag: 'success',
            content: command
          })
        }
      }
    </script>
    
    <template>
      <div id="app">
        <terminal name="my-terminal" @exec-cmd="onExecCmd"></terminal>
      </div>
    </template>
    
    <style>
      body, html, #app {
        margin: 0;
        padding: 0;
        width: 100%;
        height: 100%;
      }
    </style>
  9. Rename a terminal listener with rename()

    vue3

    The rename function allows you to change the identifier of an existing terminal listener. It internally unregisters the oldName and registers the new listener under newName.

    import { rename } from '~/common/api/index';
    
    // Renames 'old-id' to 'new-id' using the provided listener
    rename('new-id', 'old-id', (data) => {
      // listener logic
    });
  10. Register terminal listeners with register()

    vue3

    Use register to associate a unique name with a TerminalApiListenerFunc. This allows different parts of your application to interact with specific terminal instances via the central API pool. Note that registering a name that already exists will throw an error.

    import { register } from '~/common/api/index';
    
    // Assuming listener is a valid TerminalApiListenerFunc
    register('my-terminal', (data) => {
      console.log('Terminal event:', data);
    });
  11. Configure the VueWebTerminal plugin

    vue3

    The VueWebTerminal interface provides methods to customize the terminal plugin during or after installation. You can define custom themes, manage local storage settings, and control command history limits.

    Key methods:

    • configTheme(theme: string, css: string): Define a custom theme by providing a name and a CSS string. This can override default dark or light themes.
    • configStoreName(name: string): Set the name of the local storage key used for persisting terminal data.
    • configMaxStoredCommandCountPerInstance(count: number): Set the maximum number of command history entries to store per terminal instance.
    // Example usage of configuration methods
    const terminalPlugin: VueWebTerminal = ...;
    
    terminalPlugin.configTheme('my-custom-theme', '.terminal { background: #000; color: #fff; }');
    terminalPlugin.configStoreName('my-app-terminal-storage');
    terminalPlugin.configMaxStoredCommandCountPerInstance(100);