react-blessed - CUIアプリケーションでもReact!
Reactの良いところは表示されている状態を管理する必要なく、ただバーチャルDOMに描画すればReactがいいように仕上げてくれるところにあります。これはWebだけでなく、React Nativeのようにアプリでも使える考えと言えます。 他にもWindowsやMac OSXでもReactの考えが取り入れられていくかも知れません。そんな中、いち早くReactを取り込んだのがreact-blessedで、CUIの世界で実現しています。
react-blessedの使い方
例えばこんな画面です。この時点で頑張りすぎな気もしますが。
そしてこれがreact-blessedを使うとこんな感じに動くわけです。
そして以下がそのコード。面白いので全部載せます。
import React, {Component} from 'react';
import blessed from 'blessed';
import {render} from '../src/render.js';
class App extends Component {
render() {
return (
<box label="react-blessed demo"
border={{type: 'line'}}
style={{border: {fg: 'cyan'}}}>
<innerbox position="left" />
<innerbox position="right" />
<progressbar />
Random text here...
</box>
);
}
}
class InnerBox extends Component {
constructor(props) {
super(props);
this.state = {
hey: true
};
setInterval(() => {
this.setState({hey: !this.state.hey});
}, 1000);
}
render() {
const position = this.props.position;
const left = position === 'left' ? '2%' : '53%';
return (
<box label={this.state.hey ? 'First step' : 'Second step'}
ref="box"
left={left}
width='45%'
height="70%"
top="10%"
border={{type: 'line'}}
style={{border: {fg: 'green'}}}>
{this.state.hey ? 'Hey...' : 'Ho...'}
</box>
);
}
}
class ProgressBar extends Component {
constructor(props) {
super(props);
this.state = {completion: 0};
const interval = setInterval(() => {
if (this.state.completion >= 100)
return clearInterval(interval);
this.setState({completion: this.state.completion + 10});
}, 1000);
}
render() {
return <progressbar orientation="horizontal"
filled={this.state.completion}
top="80%"
left="center"
height="15%"
width="80%"
label="progress"
border={{type: 'line'}}
style={{border: {fg: 'red'}, bar: {bg: 'red'}}} />
}
}
const screen = blessed.screen({
autoPadding: true,
smartCSR: true,
title: 'react-blessed demo app'
});
screen.key(['escape', 'q', 'C-c'], function(ch, key) {
return process.exit(0);
});
const component = render(<app />, screen);
こんな細かいダッシュボード風にもできます。
blessedをベースにすることでリッチなCUIアプリケーションを組み上げ、さらにReactによってJavaScriptで自在に操作できるようになっています。非常に面白い試みです。
react-blessedはnode/JavaScriptのオープンソース・ソフトウェア(MIT License)です。