diff --git a/README.md b/README.md index 3dd310f..3cfaf2b 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,10 @@ Follow me on Twitter [@NTulswani](https://twitter.com/NTulswani) for new updates * `echo` - Outputs anything given * `edit-line` - Edits the last line or a given line using the `-l` argument +## Built-in functionality + +* Check history of your commands by pressing key up and key down. + ## Where to use ? * Embed it as a toy on your website diff --git a/components/Content.js b/components/Content.js index b5a78b1..0687146 100644 --- a/components/Content.js +++ b/components/Content.js @@ -10,6 +10,7 @@ class Content extends Component { prompt: PropTypes.objectOf(PropTypes.string), inputStyles: PropTypes.objectOf(PropTypes.string), handleChange: PropTypes.func, + setHistoryCommand: PropTypes.func, }; static contextTypes = { @@ -36,6 +37,7 @@ class Content extends Component { prompt, inputStyles, handleChange, + setHistoryCommand, } = this.props; const { symbol, maximise } = this.context; @@ -60,6 +62,7 @@ class Content extends Component { type="text" ref={com => (this.com = com)} onKeyPress={handleChange} + onKeyDown={(e)=> setHistoryCommand(e, this.com)} /> diff --git a/components/Terminal.js b/components/Terminal.js index 1fbe955..284f1e2 100644 --- a/components/Terminal.js +++ b/components/Terminal.js @@ -96,6 +96,8 @@ class Terminal extends Component { summary: [], commands: {}, description: {}, + history: [], + historyCounter: 0, show: true, minimise: false, maximise: false, @@ -248,6 +250,34 @@ class Terminal extends Component { } }; + /** + * set the input value with the possible history value + * @param {number} next position on the history + */ + setValueWithHistory = (position, inputRef) => { + const { history } = this.state; + if (history[position]) { + this.setState({ historyCounter: position }); + inputRef.value = history[position]; + } + }; + + /** + * Base of key code set the value of the input + * with the history + * 38 is key up + * 40 is key down + * @param {event} event of input + */ + setHistoryCommand = (e, inputRef) => { + const { historyCounter } = this.state; + if (e.keyCode === 38) { + this.setValueWithHistory(historyCounter - 1, inputRef); + } else if (e.keyCode === 40) { + this.setValueWithHistory(historyCounter + 1, inputRef); + } + }; + handleChange = (e) => { if (e.key === 'Enter') { this.adder(`${this.state.prompt} ${e.target.value}`); @@ -258,6 +288,11 @@ class Terminal extends Component { this.adder(res); } + const history = [...this.state.history, e.target.value]; + this.setState({ + history, + historyCounter: history.length, + }); e.target.value = ''; // eslint-disable-line no-param-reassign } }; @@ -313,6 +348,7 @@ class Terminal extends Component { prompt={promptStyles} inputStyles={inputStyles} handleChange={this.handleChange} + setHistoryCommand={this.setHistoryCommand} /> );