• Stars
    star
    2,124
  • Rank 21,727 (Top 0.5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ‘¨β€πŸ’» A component that renders a terminal

Terminal in React

Downloads Downloads NPM Version Dependencies Dev Dependencies License size size

A component that renders a terminal

Table of contents

Install

npm install terminal-in-react --save

or if you use yarn

yarn add terminal-in-react

This package also depends on react so make sure you've already installed it.

Usage

import React, { Component } from 'react';
import Terminal from 'terminal-in-react';

class App extends Component {
  showMsg = () => 'Hello World'

  render() {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh"
        }}
      >
        <Terminal
          color='green'
          backgroundColor='black'
          barColor='black'
          style={{ fontWeight: "bold", fontSize: "1em" }}
          commands={{
            'open-google': () => window.open('https://www.google.com/', '_blank'),
            showmsg: this.showMsg,
            popup: () => alert('Terminal in React')
          }}
          descriptions={{
            'open-google': 'opens google.com',
            showmsg: 'shows a message',
            alert: 'alert', popup: 'alert'
          }}
          msg='You can write anything here. Example - Hello! My name is Foo and I like Bar.'
        />
      </div>
    );
  }
}

Be careful when copying this example because it uses window object ('open-google': () => window.open("https://www.google.com/", "_blank"),) which is only available on the client-side and it will give you an error if you're doing server side rendering.

Working

Adding commands ✍️

To add your own command, use prop commands which accepts an object. This objects then maps command name -> command function.

Let's take an example. You want to open a website with a command open-google

<Terminal commands={{ 'open-google': () => window.open("https://www.google.com/", "_blank")}} />

Adding description of your command πŸ’πŸΌβ€β™‚οΈ

Add a description of your command using prop description.

<Terminal descriptions={{ 'open-google': 'opens google' }} />

Console logging

You can have the terminal watch console.log/info function and print out. It does so by default.

<Terminal watchConsoleLogging />

Command passthrough

You can have the terminal pass out the cmd that was input

<Terminal commandPassThrough={cmd => `-PassedThrough:${cmd}: command not found`} />

Async handling of commands 😎

you can also handle the result with a callback

<Terminal
  commandPassThrough={(cmd, print) => {
    // do something async
    print(`-PassedThrough:${cmd}: command not found`);
  }}
/>

Minimise, maximise and close the window

<Terminal
  closedTitle='OOPS! You closed the window.'
  closedMessage='Click on the icon to reopen.'
/>

Hide the default options

<Terminal descriptions={{ color: false, show: false, clear: false }} />

This will hide the option color, show and clear.

Advanced commands πŸ‘¨β€πŸ’»

You can give your commands options and get them back parsed to the method. Using this method will also give your command a build in help output. With the option -h or --help.

<Terminal
  commands={{
    color: {
      method: (args, print, runCommand) => {
        print(`The color is ${args._[0] || args.color}`);
      },
      options: [
        {
          name: 'color',
          description: 'The color the output should be',
          defaultValue: 'white',
        },
      ],
    },
  }}
/>

The command API has three parameters arguments, print, and runCommand.

  • arguments will be an array of the input split on spaces or and object with parameters meeting the options given as well as a _ option with any strings given after the options.
  • print is a method to write a new line to the terminals output. Any string returned as a result of a command will also be printed.
  • runCommand is a method to call other commands it takes a string and will attempt to run the command given

Let's take an another example -

<Terminal
  commands={{
    'type-text': (args, print, runCommand) => {
      const text = args.slice(1).join(' ');
      print('');
      for (let i = 0; i < text.length; i += 1) {
        setTimeout(() => {
          runCommand(`edit-line ${text.slice(0, i + 1)}`);
        }, 100 * i);
      }
    }
  }}
/>

Using plugins πŸ”₯

Plugin Documentation.

We have also developed a plugin system for the <Terminal /> component which helps you develop custom plugins. Here is one example of plugin which creates a fake file system called terminal-in-react-pseudo-file-system-plugin.

Instantiating the plugin

import pseudoFileSystem from 'terminal-in-react-pseudo-file-system-plugin';
const FileSystemPlugin = pseudoFileSystem();

<Terminal
  plugins={[
    FileSystemPlugin,
  ]}
/>

or if the plugin requires config

import NodeEvalPlugin from 'terminal-in-react-node-eval-plugin';
import pseudoFileSystemPlugin from 'terminal-in-react-pseudo-file-system-plugin';
const FileSystemPlugin = pseudoFileSystemPlugin();

...
<Terminal
  plugins={[
    FileSystemPlugin,
    {
      class: NodeEvalPlugin,
      config: {
        filesystem: FileSystemPlugin.displayName
      }
    }
  ]}
/>
...

Awesome! Right? Let us know if you make something interesting πŸ˜ƒ

Plugin List

More features

Tab autocomplete

Multiline input πŸ€ΉπŸΌβ€β™€οΈ

via shift + enter

Check history of your commands πŸ–±οΈ

using arrow down and up keys

Keyboard shortcuts ⌨

You can define keyboard shortcuts. They have to be grouped by os. The three available are win, darwin, and linux. You can group multiple os by a , for example if the shortcut was for all platforms win,darwin,linux would be fine as a key

<Terminal
  shortcuts={{
    'darwin,win,linux': {
      'ctrl + a': 'echo whoo',
    },
  }}
/>

But you might want to specific

<Terminal
  shortcuts={{
    'win': {
      'ctrl + a': 'echo hi windows',
    },
    'darwin': {
      'cmd + a': 'echo hi mac'
    },
    'linux': {
      'ctrl + a': 'echo hi linux'
    }
  }}
/>

You can mix and match

<Terminal
  shortcuts={{
    'win,linux': {
      'ctrl + b': 'echo we are special',
    },
    'win': {
      'ctrl + a': 'echo hi windows',
    },
    'darwin': {
      'cmd + a': 'echo hi mac'
    },
    'linux': {
      'ctrl + a': 'echo hi linux'
    }
  }}
/>

The value of the shortcut should be a command to run.

Override the top bar buttons actionHandlers

Use the prop actionHandlers.

The object allows for 3 methods handleClose, handleMaximise, handleMinimise;

Each one is a function and will pass in the default method as the first param. Any method not passed in will use the default.

<Terminal
  actionHandlers={{
    handleClose: (toggleClose) => {
      // do something on close
      toggleClose();
    },
    handleMaximise: (toggleMaximise) => {
      // do something on maximise
      toggleMaximise();
    }
  }}
/>

Customization

Use

  • prop color to change the color of the text.
  • prop outputColor to change the color of the output text defaults to color prop.
  • prop backgroundColor to change the background.
  • prop barColor to change the color of bar.
  • prop prompt to change the prompt (>) color.
  • prop showActions to change if the three circles are shown.
  • prop hideTopBar to hide the top bar altogether.
  • prop allowTabs to allow multiple tabs.

API

component props

Props Type Default
color string 'green'
outputColor string props.color
backgroundColor string 'black'
prompt string 'green'
barColor string 'black'
description object {}
commands object { clear, help, show, }
msg string -
closedTitle string OOPS! You closed the window.
closedMessage string Click on the icon to reopen.
watchConsoleLogging bool false
commandPassThrough function null
promptSymbol string >
plugins array [ { name: '', load: new Plugin(), commands: {} descriptions: {} } ]
startState string ['open', 'maximised', 'minimised', 'closed'] 'open'
showActions bool true
hideTopBar bool false
allowTabs bool true
actionHandlers object -

Built-in commands

  • clear - Clears the screen
  • help - List all the commands
  • show - Shows a msg if any
  • echo - Display the input message
  • edit-line - Edits the last line or a given line using the -l argument

Where to use ?

  • Embed it as a toy on your website
  • For showcasing
  • Explain any of your projects using this terminal component
  • or just play with it

You want a X feature

Sure! Check our todolist or create an issue.

Contributing

Contributing Guide

Troubleshooting

Build errors when using with create-react-app

Eject from create-react-app and use a custom webpack configuration with babili-webpack-plugin. Read more about this here.

Style issues when maximizing

Set the style to height: 100vh on parent element.

Sponsor

More Repositories

1

react-perf-devtool

A browser developer tool extension to inspect performance of React components.
JavaScript
2,324
star
2

react-imgpro

πŸ“· Image Processing Component for React
JavaScript
2,176
star
3

redocx

πŸ“„ Create word documents with React
JavaScript
1,389
star
4

Making-a-custom-React-renderer

Tutorial on how to make a custom React renderer
JavaScript
1,286
star
5

animate-components

✨ Elemental components for doing animations in React
JavaScript
909
star
6

React-Web-AR

πŸ•ΆοΈ Augmented Reality on web with React
JavaScript
571
star
7

react-color-extractor

A React component which extracts colors from an image
JavaScript
351
star
8

Python-Automation

πŸ’» These are some projects which I worked upon to automate stuffs using python
Python
246
star
9

Animated-Timeline

πŸ”₯ Create timeline and playback based animations in React
JavaScript
197
star
10

react-video-scroll

A React component to seek or control the video frame rate on scroll.
JavaScript
135
star
11

glamorous-primitives

πŸ’„ style primitive React interfaces with glamorous
JavaScript
92
star
12

react-tint

A React component that applies image processing filters to an image using Processing
JavaScript
87
star
13

react-color-tools

A set of tools as React components for working with colors 🎨
JavaScript
87
star
14

shaping-functions

Visualisation of shaping functions
JavaScript
75
star
15

linkify-markdown

πŸš€ A cli tool which automatically add references to issues, pull requests, user mentions and forks to a markdown file.
JavaScript
69
star
16

react-handy-renderer

✏️ Draw 2D primitives in sketchy style with React
JavaScript
61
star
17

generative-designs

A collection of generative design React components
JavaScript
58
star
18

stylus-in-react

πŸ’„ Style React components with Stylus
JavaScript
54
star
19

react-text-fun

React meets Blotter.js
JavaScript
52
star
20

react-marker

πŸ–οΈ Highlight keywords and add colors to your text.
JavaScript
47
star
21

generative-art-tools

Utilities for creating generative art
JavaScript
27
star
22

vscode-glamorous

πŸ€™ code snippets for glamorous
21
star
23

Elements-of-physics

Representing elements of physics using React
JavaScript
20
star
24

react-shader-canvas

A small utility function to render the shaders using React
JavaScript
20
star
25

Creating-a-pretty-printer

This is a tutorial for creating a pretty printer in JavaScript
JavaScript
13
star
26

generative-art-snippets

A collection of some useful snippets used in crafting computational art
10
star
27

glamorous-redocx

style redocx components with glamorous πŸ’„
JavaScript
10
star
28

Tidings

πŸ—žοΈ A NLP based news app powered by API.ai
JavaScript
8
star
29

pro-branch

A small package that provides helpers to manage control flow in React
JavaScript
8
star
30

lightup

πŸ’‘ A cli tool to quickly launch your react app in an effortless way.
JavaScript
8
star
31

glamorous-stylus

Use Stylus with glamorous
JavaScript
6
star
32

react-image-overlay-effect

A React component for displaying an overlay effect on an image.
TypeScript
5
star
33

component-dot-json

Create and mock stateless React components using JSON
JavaScript
5
star
34

Creating-a-JavaScript-UI-library

This is a tutorial for creating a JavaScript UI library.
5
star
35

babel-preset-hyperapp

A Babel preset for HyperApp
JavaScript
4
star
36

HyperApp-Examples

HyperApp examples
JavaScript
4
star
37

word-classes-visualiser

A small tool based on Compromise NLP to visualise the different word classes from English grammar.
JavaScript
4
star
38

Blog

πŸ“— My writings
3
star
39

algorithmic-art-sketchbook

work in progress
JavaScript
3
star
40

Learning-Processing

A curated list of resources, links and books for learning processing
JavaScript
3
star
41

glam-atom

Glamorous Snippets for Atom
3
star
42

css-to-rn

Convert css string to React Native
JavaScript
3
star
43

myspace

Blog
2
star
44

Working-with-APIs

This repository contains scripts for accessing the third party APIs using Python, JavaScript and Ruby.
Python
2
star
45

T-Box

A command line utility to manage the file uploads, downloads and sharing directly from terminal on your Dropbox.
JavaScript
2
star
46

Nitin-Blog

Welcome to my blog!
2
star
47

personal-blog

My blog
JavaScript
2
star
48

Resume

1
star
49

test-repo

1
star
50

test-draft-releaser

1
star
51

nextjs-netlify-blog-template

TypeScript
1
star
52

Escaper

A small library which provides methods to escape and unescape HTML entities.
JavaScript
1
star
53

nextjs-netlify-blog-template-nitin

1
star
54

insiderin-assignment

assignment
JavaScript
1
star
55

Project-Euler

Contains my solutions to the computational problems at https://projecteuler.net/
Python
1
star
56

nitin42

My personal repository
1
star
57

Real-Markdown

An app that let’s us view the raw markdown on one side and the converted markdown (to HTML) on the other side.
JavaScript
1
star
58

routes-getter

Walks through your routes folder and imports them to your project.
JavaScript
1
star
59

grabvatar

An amazing tool to generate cool avatars for your profile picture given an identifier.
JavaScript
1
star