Rebase and migration to full React instead of react-lite

This commit is contained in:
Kyrylo Gliebov 2018-09-14 18:34:33 +02:00
parent 4ca9b76b23
commit 1abe64fe0c
7 changed files with 2275 additions and 2246 deletions

View file

@ -42,27 +42,26 @@
"sass-loader": "^7.0.3", "sass-loader": "^7.0.3",
"sizzle": "^2.3.3", "sizzle": "^2.3.3",
"stdio": "^0.2.7", "stdio": "^0.2.7",
"webpack": "^4.17.1", "webpack": "^4.19.0",
"webpack-cli": "^3.1.0" "webpack-cli": "^3.1.0"
}, },
"dependencies": { "dependencies": {
"@babel/polyfill": "^7.0.0", "@babel/polyfill": "^7.0.0",
"node-sass": "^4.9.0",
"react": "^16.4.2",
"react-dom": "^16.4.2"
"bootstrap": "3.3.7", "bootstrap": "3.3.7",
"patternfly": "3.35.1",
"webpack": "^2.6.1",
"jquery": "3.3.1",
"moment": "2.22.2",
"mustache": "2.3.0",
"bootstrap-datetime-picker": "2.4.4", "bootstrap-datetime-picker": "2.4.4",
"comment-json": "^1.1.3", "comment-json": "^1.1.3",
"term.js-cockpit": "0.0.10",
"fs.extra": "^1.3.2", "fs.extra": "^1.3.2",
"fs.realpath": "^1.0.0", "fs.realpath": "^1.0.0",
"ini": "^1.3.5", "ini": "^1.3.5",
"jquery": "3.3.1",
"moment": "2.22.2",
"mustache": "2.3.0",
"node-sass": "^4.9.0", "node-sass": "^4.9.0",
"raw-loader": "^0.5.1" "patternfly": "3.35.1",
"prop-types": "^15.6.2",
"raw-loader": "^0.5.1",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"term.js-cockpit": "0.0.10"
} }
} }

View file

@ -22,10 +22,11 @@
let cockpit = require("cockpit"); let cockpit = require("cockpit");
let React = require("react"); let React = require("react");
let ReactDOM = require("react-dom");
let json = require('comment-json'); let json = require('comment-json');
let ini = require('ini'); let ini = require('ini');
let Config = class extends React.Component { class Config extends React.Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.handleInputChange = this.handleInputChange.bind(this); this.handleInputChange = this.handleInputChange.bind(this);
@ -38,7 +39,7 @@
config: null, config: null,
file_error: null, file_error: null,
submitting: "none", submitting: "none",
} };
} }
handleInputChange(e) { handleInputChange(e) {
@ -59,10 +60,8 @@
handleSubmit(event) { handleSubmit(event) {
this.setState({submitting:"block"}); this.setState({submitting:"block"});
console.log(event);
this.prepareConfig(); this.prepareConfig();
this.file.replace(this.state.config).done(() => { this.file.replace(this.state.config).done(() => {
console.log('updated');
this.setState({submitting:"none"}); this.setState({submitting:"none"});
}) })
.fail((error) => { .fail((error) => {
@ -72,20 +71,16 @@
} }
setConfig(data) { setConfig(data) {
console.log(data);
this.setState({config: data}); this.setState({config: data});
} }
fileReadFailed(reason) { fileReadFailed(reason) {
console.log(reason); console.log(reason);
this.setState({file_error: reason}); this.setState({file_error: reason});
console.log('failed to read file');
} }
componentDidMount() { componentDidMount() {
let parseFunc = function(data) { let parseFunc = function(data) {
console.log(data);
// return data;
return json.parse(data, null, true); return json.parse(data, null, true);
}; };
@ -106,8 +101,6 @@
// host: string // host: string
}); });
console.log(this.file);
let promise = this.file.read(); let promise = this.file.read();
promise.done((data) => { promise.done((data) => {
@ -253,10 +246,9 @@
</tr> </tr>
<tr> <tr>
<td className="top" /> <td className="top" />
<div className="spinner spinner-sm" style={{display: this.state.submitting}} />
<td> <td>
<button className="btn btn-default" type="submit">Save</button> <button className="btn btn-default" type="submit">Save</button>
<div className="spinner spinner-sm" style={{display: this.state.submitting}} />
</td> </td>
</tr> </tr>
</tbody> </tbody>
@ -274,9 +266,9 @@
); );
} }
} }
}; }
let SssdConfig = class extends React.Component { class SssdConfig extends React.Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.handleSubmit = this.handleSubmit.bind(this); this.handleSubmit = this.handleSubmit.bind(this);
@ -284,27 +276,24 @@
this.setConfig = this.setConfig.bind(this); this.setConfig = this.setConfig.bind(this);
this.file = null; this.file = null;
this.state = { this.state = {
config: { scope: "",
session_recording: { users: "",
scope: null, groups: "",
users: null, submitting: "none",
groups: null,
},
},
}; };
} }
handleInputChange(e){ handleInputChange(e) {
const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value; const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
const name = e.target.name; const name = e.target.name;
const config = this.state.config; const state = {};
config.session_recording[name] = value; state[name] = value;
this.setState(state);
this.forceUpdate();
} }
setConfig(data) { setConfig(data) {
this.setState({config: data}); const config = {...data['session_recording']};
this.setState(config);
} }
componentDidMount() { componentDidMount() {
@ -327,14 +316,21 @@
}); });
} }
handleSubmit() { handleSubmit(e) {
this.file.replace(this.state.config).done( function() { this.setState({submitting:"block"});
console.log('updated'); const obj = {};
obj.users = this.state.users;
obj.groups = this.state.groups;
obj.scope = this.state.scope;
obj['session_recording'] = this.state;
let _this = this;
this.file.replace(obj).done(function() {
_this.setState({submitting:"none"});
}) })
.fail( function(error) { .fail(function(error) {
console.log(error); console.log(error);
}); });
event.preventDefault(); e.preventDefault();
} }
render() { render() {
@ -342,49 +338,48 @@
<form onSubmit={this.handleSubmit}> <form onSubmit={this.handleSubmit}>
<table className="info-table-ct col-md-12"> <table className="info-table-ct col-md-12">
<tbody> <tbody>
<tr> <tr>
<td><label htmlFor="scope">Scope</label></td> <td><label htmlFor="scope">Scope</label></td>
<td> <td>
<select name="scope" id="scope" className="form-control" <select name="scope" id="scope" className="form-control"
value={this.state.config.session_recording.scope} value={this.state.scope}
onChange={this.handleInputChange} > onChange={this.handleInputChange} >
<option value="none">None</option> <option value="none">None</option>
<option value="some">Some</option> <option value="some">Some</option>
<option value="all">All</option> <option value="all">All</option>
</select> </select>
</td> </td>
</tr> </tr>
<tr> <tr>
<td><label htmlFor="users">Users</label></td> <td><label htmlFor="users">Users</label></td>
<td> <td>
<input type="text" id="users" name="users" <input type="text" id="users" name="users"
value={this.state.config.session_recording.users} value={this.state.users}
className="form-control" />
</td>
</tr>
<tr>
<td><label htmlFor="groups">Groups</label></td>
<td>
<input type="text" id="groups" name="groups"
value={this.state.config.session_recording.groups}
className="form-control" onChange={this.handleInputChange} /> className="form-control" onChange={this.handleInputChange} />
</td> </td>
</tr> </tr>
<tr> <tr>
<td> <td><label htmlFor="groups">Groups</label></td>
<td>
</td> <input type="text" id="groups" name="groups"
<td> value={this.state.groups}
<button className="btn btn-default" type="submit">Save</button> className="form-control" onChange={this.handleInputChange} />
</td> </td>
</tr> </tr>
<tr>
<td />
<td>
<button className="btn btn-default" type="submit">Save</button>
<span className="spinner spinner-sm" style={{display: this.state.submitting}} />
</td>
</tr>
</tbody> </tbody>
</table> </table>
</form> </form>
); );
} }
}; }
React.render(<Config />, document.getElementById('sr_config')); ReactDOM.render(<Config />, document.getElementById('sr_config'));
React.render(<SssdConfig />, document.getElementById('sssd_config')); ReactDOM.render(<SssdConfig />, document.getElementById('sssd_config'));
}()); }());

View file

@ -17,11 +17,9 @@
* along with Cockpit; If not, see <http://www.gnu.org/licenses/>. * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
*/ */
"use strict"; import PropTypes from 'prop-types';
import React from 'react';
var React = require('react'); import './listing.less';
require('./listing.less');
/* entry for an alert in the listing, can be expanded (with details) or standard /* entry for an alert in the listing, can be expanded (with details) or standard
* rowId optional: an identifier for the row which will be set as "data-row-id" attribute on the <tr> * rowId optional: an identifier for the row which will be set as "data-row-id" attribute on the <tr>
@ -47,55 +45,43 @@ require('./listing.less');
* initiallyExpanded optional: the entry will be initially rendered as expanded, but then behaves normally * initiallyExpanded optional: the entry will be initially rendered as expanded, but then behaves normally
* expandChanged optional: callback will be used if the row is either expanded or collapsed passing single `isExpanded` boolean argument * expandChanged optional: callback will be used if the row is either expanded or collapsed passing single `isExpanded` boolean argument
*/ */
var ListingRow = React.createClass({ export class ListingRow extends React.Component {
propTypes: { constructor(props) {
rowId: React.PropTypes.string, super(props);
columns: React.PropTypes.array.isRequired, this.state = {
tabRenderers: React.PropTypes.array,
navigateToItem: React.PropTypes.func,
listingDetail: React.PropTypes.node,
listingActions: React.PropTypes.arrayOf(React.PropTypes.node),
selectChanged: React.PropTypes.func,
selected: React.PropTypes.bool,
initiallyExpanded: React.PropTypes.bool,
expandChanged: React.PropTypes.func,
initiallyActiveTab: React.PropTypes.bool,
},
getDefaultProps: function () {
return {
tabRenderers: [],
navigateToItem: null,
};
},
getInitialState: function() {
return {
expanded: this.props.initiallyExpanded, // show expanded view if true, otherwise one line compact expanded: this.props.initiallyExpanded, // show expanded view if true, otherwise one line compact
activeTab: this.props.initiallyActiveTab ? this.props.initiallyActiveTab : 0, // currently active tab in expanded mode, defaults to first tab activeTab: this.props.initiallyActiveTab ? this.props.initiallyActiveTab : 0, // currently active tab in expanded mode, defaults to first tab
loadedTabs: {}, // which tabs were already loaded - this is important for 'loadOnDemand' setting loadedTabs: {}, // which tabs were already loaded - this is important for 'loadOnDemand' setting
// contains tab indices // contains tab indices
selected: this.props.selected, // whether the current row is selected selected: this.props.selected, // whether the current row is selected
}; };
}, this.handleNavigateClick = this.handleNavigateClick.bind(this);
handleNavigateClick: function(e) { this.handleExpandClick = this.handleExpandClick.bind(this);
this.handleSelectClick = this.handleSelectClick.bind(this);
this.handleTabClick = this.handleTabClick.bind(this);
}
handleNavigateClick(e) {
// only consider primary mouse button // only consider primary mouse button
if (!e || e.button !== 0) if (!e || e.button !== 0)
return; return;
this.props.navigateToItem(); this.props.navigateToItem();
}, }
handleExpandClick: function(e) {
handleExpandClick(e) {
// only consider primary mouse button // only consider primary mouse button
if (!e || e.button !== 0) if (!e || e.button !== 0)
return; return;
var willBeExpanded = !this.state.expanded && this.props.tabRenderers.length > 0; let willBeExpanded = !this.state.expanded && this.props.tabRenderers.length > 0;
this.setState({ expanded: willBeExpanded }); this.setState({ expanded: willBeExpanded });
var loadedTabs = {}; let loadedTabs = {};
// unload all tabs if not expanded // unload all tabs if not expanded
if (willBeExpanded) { if (willBeExpanded) {
// see if we should preload some tabs // see if we should preload some tabs
var tabIdx; let tabIdx;
var tabPresence; let tabPresence;
for (tabIdx = 0; tabIdx < this.props.tabRenderers.length; tabIdx++) { for (tabIdx = 0; tabIdx < this.props.tabRenderers.length; tabIdx++) {
if ('presence' in this.props.tabRenderers[tabIdx]) if ('presence' in this.props.tabRenderers[tabIdx])
tabPresence = this.props.tabRenderers[tabIdx].presence; tabPresence = this.props.tabRenderers[tabIdx].presence;
@ -115,13 +101,14 @@ var ListingRow = React.createClass({
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
}, }
handleSelectClick: function(e) {
handleSelectClick(e) {
// only consider primary mouse button // only consider primary mouse button
if (!e || e.button !== 0) if (!e || e.button !== 0)
return; return;
var selected = !this.state.selected; let selected = !this.state.selected;
this.setState({ selected: selected }); this.setState({ selected: selected });
if (this.props.selectChanged) if (this.props.selectChanged)
@ -129,14 +116,15 @@ var ListingRow = React.createClass({
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
}, }
handleTabClick: function(tabIdx, e) {
handleTabClick(tabIdx, e) {
// only consider primary mouse button // only consider primary mouse button
if (!e || e.button !== 0) if (!e || e.button !== 0)
return; return;
var prevTab = this.state.activeTab; let prevTab = this.state.activeTab;
var prevTabPresence = 'default'; let prevTabPresence = 'default';
var loadedTabs = this.state.loadedTabs; let loadedTabs = this.state.loadedTabs;
if (prevTab !== tabIdx) { if (prevTab !== tabIdx) {
// see if we need to unload the previous tab // see if we need to unload the previous tab
if ('presence' in this.props.tabRenderers[prevTab]) if ('presence' in this.props.tabRenderers[prevTab])
@ -151,41 +139,42 @@ var ListingRow = React.createClass({
} }
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
}, }
render: function() {
var self = this;
// only enable navigation if a function is provided and the row isn't expanded (prevent accidental navigation)
var allowNavigate = !!this.props.navigateToItem && !this.state.expanded;
var headerEntries = this.props.columns.map(function(itm) { render() {
let self = this;
// only enable navigation if a function is provided and the row isn't expanded (prevent accidental navigation)
let allowNavigate = !!this.props.navigateToItem && !this.state.expanded;
let headerEntries = this.props.columns.map((itm, index) => {
if (typeof itm === 'string' || typeof itm === 'number' || itm === null || itm === undefined || itm instanceof String || React.isValidElement(itm)) if (typeof itm === 'string' || typeof itm === 'number' || itm === null || itm === undefined || itm instanceof String || React.isValidElement(itm))
return (<td>{itm}</td>); return (<td key={index}>{itm}</td>);
else if ('header' in itm && itm.header) else if ('header' in itm && itm.header)
return (<th>{itm.name}</th>); return (<th key={index}>{itm.name}</th>);
else if ('tight' in itm && itm.tight) else if ('tight' in itm && itm.tight)
return (<td className="listing-ct-actions">{itm.name || itm.element}</td>); return (<td key={index} className="listing-ct-actions">{itm.name || itm.element}</td>);
else else
return (<td>{itm.name}</td>); return (<td key={index}>{itm.name}</td>);
}); });
var allowExpand = (this.props.tabRenderers.length > 0); let allowExpand = (this.props.tabRenderers.length > 0);
var expandToggle; let expandToggle;
if (allowExpand) { if (allowExpand) {
expandToggle = <td className="listing-ct-toggle" onClick={ allowNavigate ? this.handleExpandClick : undefined }> expandToggle = <td key="expandToggle" className="listing-ct-toggle" onClick={ allowNavigate ? this.handleExpandClick : undefined }>
<i className="fa fa-fw" /> <i className="fa fa-fw" />
</td>; </td>;
} else { } else {
expandToggle = <td className="listing-ct-toggle" />; expandToggle = <td key="expandToggle-empty" className="listing-ct-toggle" />;
} }
var listingItemClasses = ["listing-ct-item"]; let listingItemClasses = ["listing-ct-item"];
if (!allowNavigate) if (!allowNavigate)
listingItemClasses.push("listing-ct-nonavigate"); listingItemClasses.push("listing-ct-nonavigate");
if (!allowExpand) if (!allowExpand)
listingItemClasses.push("listing-ct-noexpand"); listingItemClasses.push("listing-ct-noexpand");
var allowSelect = !(allowNavigate || allowExpand) && (this.state.selected !== undefined); let allowSelect = !(allowNavigate || allowExpand) && (this.state.selected !== undefined);
var clickHandler; let clickHandler;
if (allowSelect) { if (allowSelect) {
clickHandler = this.handleSelectClick; clickHandler = this.handleSelectClick;
if (this.state.selected) if (this.state.selected)
@ -197,7 +186,7 @@ var ListingRow = React.createClass({
clickHandler = this.handleExpandClick; clickHandler = this.handleExpandClick;
} }
var listingItem = ( let listingItem = (
<tr data-row-id={ this.props.rowId } <tr data-row-id={ this.props.rowId }
className={ listingItemClasses.join(' ') } className={ listingItemClasses.join(' ') }
onClick={clickHandler}> onClick={clickHandler}>
@ -207,18 +196,18 @@ var ListingRow = React.createClass({
); );
if (this.state.expanded) { if (this.state.expanded) {
var links = this.props.tabRenderers.map(function(itm, idx) { let links = this.props.tabRenderers.map((itm, idx) => {
return ( return (
<li key={idx} className={ (idx === self.state.activeTab) ? "active" : ""} > <li key={idx} className={ (idx === self.state.activeTab) ? "active" : ""} >
<a href="#" tabIndex="0" onClick={ self.handleTabClick.bind(self, idx) }>{itm.name}</a> <a href="#" tabIndex="0" onClick={ self.handleTabClick.bind(self, idx) }>{itm.name}</a>
</li> </li>
); );
}); });
var tabs = []; let tabs = [];
var tabIdx; let tabIdx;
var Renderer; let Renderer;
var rendererData; let rendererData;
var row; let row;
for (tabIdx = 0; tabIdx < this.props.tabRenderers.length; tabIdx++) { for (tabIdx = 0; tabIdx < this.props.tabRenderers.length; tabIdx++) {
Renderer = this.props.tabRenderers[tabIdx].renderer; Renderer = this.props.tabRenderers[tabIdx].renderer;
rendererData = this.props.tabRenderers[tabIdx].data; rendererData = this.props.tabRenderers[tabIdx].data;
@ -231,7 +220,7 @@ var ListingRow = React.createClass({
tabs.push(<div className="listing-ct-body" key={tabIdx} hidden>{row}</div>); tabs.push(<div className="listing-ct-body" key={tabIdx} hidden>{row}</div>);
} }
var listingDetail; let listingDetail;
if ('listingDetail' in this.props) { if ('listingDetail' in this.props) {
listingDetail = ( listingDetail = (
<span className="listing-ct-caption"> <span className="listing-ct-caption">
@ -268,8 +257,26 @@ var ListingRow = React.createClass({
); );
} }
} }
}); }
ListingRow.defaultProps = {
tabRenderers: [],
navigateToItem: null,
};
ListingRow.propTypes = {
rowId: PropTypes.string,
columns: PropTypes.array.isRequired,
tabRenderers: PropTypes.array,
navigateToItem: PropTypes.func,
listingDetail: PropTypes.node,
listingActions: PropTypes.arrayOf(PropTypes.node),
selectChanged: PropTypes.func,
selected: PropTypes.bool,
initiallyExpanded: PropTypes.bool,
expandChanged: PropTypes.func,
initiallyActiveTab: PropTypes.bool
};
/* Implements a PatternFly 'List View' pattern /* Implements a PatternFly 'List View' pattern
* https://www.patternfly.org/list-view/ * https://www.patternfly.org/list-view/
* Properties: * Properties:
@ -281,80 +288,77 @@ var ListingRow = React.createClass({
* receives the column index as argument * receives the column index as argument
* - actions: additional listing-wide actions (displayed next to the list's title) * - actions: additional listing-wide actions (displayed next to the list's title)
*/ */
var Listing = React.createClass({ export const Listing = (props) => {
propTypes: { let bodyClasses = ["listing", "listing-ct"];
title: React.PropTypes.string.isRequired, if (props.fullWidth)
fullWidth: React.PropTypes.bool, bodyClasses.push("listing-ct-wide");
emptyCaption: React.PropTypes.string.isRequired, let headerClasses;
columnTitles: React.PropTypes.arrayOf(React.PropTypes.string), let headerRow;
columnTitleClick: React.PropTypes.func, let selectableRows;
actions: React.PropTypes.arrayOf(React.PropTypes.node) if (!props.children || props.children.length === 0) {
}, headerClasses = "listing-ct-empty";
getDefaultProps: function () { headerRow = <tr><td>{props.emptyCaption}</td></tr>;
return { } else if (props.columnTitles.length) {
fullWidth: true, // check if any of the children are selectable
columnTitles: [], selectableRows = false;
actions: [] props.children.forEach(function(r) {
}; if (r.props.selected !== undefined)
}, selectableRows = true;
render: function() { });
var self = this;
var bodyClasses = ["listing", "listing-ct"]; if (selectableRows) {
if (this.props.fullWidth) // now make sure that if one is set, it's available on all items
bodyClasses.push("listing-ct-wide"); props.children.forEach(function(r) {
var headerClasses; if (r.props.selected === undefined)
var headerRow; r.props.selected = false;
var selectableRows;
if (!this.props.children || this.props.children.length === 0) {
headerClasses = "listing-ct-empty";
headerRow = <tr><td>{this.props.emptyCaption}</td></tr>;
} else if (this.props.columnTitles.length) {
// check if any of the children are selectable
selectableRows = false;
this.props.children.forEach(function(r) {
if (r.props.selected !== undefined)
selectableRows = true;
}); });
if (selectableRows) {
// now make sure that if one is set, it's available on all items
this.props.children.forEach(function(r) {
if (r.props.selected === undefined)
r.props.selected = false;
});
}
headerRow = (
<tr>
<th className="listing-ct-toggle" />
{ this.props.columnTitles.map(function (title, index) {
var clickHandler = null;
if (self.props.columnTitleClick)
clickHandler = function() { self.props.columnTitleClick(index) };
return <th onClick={clickHandler}>{title}</th>;
}) }
</tr>
);
} else {
headerRow = <tr />
} }
var caption;
if (this.props.title || (this.props.actions && this.props.actions.length > 0))
caption = <caption className="cockpit-caption">{this.props.title}{this.props.actions}</caption>;
return ( headerRow = (
<table className={ bodyClasses.join(" ") }> <tr>
{caption} <th key="empty" className="listing-ct-toggle" />
<thead className={headerClasses}> { props.columnTitles.map((title, index) => {
{headerRow} let clickHandler = null;
</thead> if (props.columnTitleClick)
{this.props.children} clickHandler = function() { props.columnTitleClick(index) };
</table> return <th key={index} onClick={clickHandler}>{title}</th>;
}) }
</tr>
); );
}, } else {
}); headerRow = <tr />;
}
let caption;
if (props.title || (props.actions && props.actions.length > 0))
caption = <caption className="cockpit-caption">{props.title}{props.actions}</caption>;
module.exports = { return (
ListingRow: ListingRow, <table className={ bodyClasses.join(" ") }>
Listing: Listing, {caption}
<thead className={headerClasses}>
{headerRow}
</thead>
{props.children}
</table>
);
};
Listing.defaultProps = {
title: '',
fullWidth: true,
columnTitles: [],
actions: []
};
Listing.propTypes = {
title: PropTypes.string,
fullWidth: PropTypes.bool,
emptyCaption: PropTypes.string.isRequired,
columnTitles: PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
])),
columnTitleClick: PropTypes.func,
actions: PropTypes.arrayOf(PropTypes.node)
}; };

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -17,175 +17,177 @@
* along with Cockpit; If not, see <http://www.gnu.org/licenses/>. * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
*/ */
(function() { import Player from "./player";
"use strict";
var React = require("react");
var Term = require("term");
let $ = require("jquery");
require("console.css"); "use strict";
require("jquery-resizable");
require("jquery-resizable/resizable.css");
/* var React = require("react");
* A terminal component that communicates over a cockpit channel. var Term = require("term");
* let $ = require("jquery");
* The only required property is 'channel', which must point to a cockpit
* stream channel.
*
* The size of the terminal can be set with the 'rows' and 'cols'
* properties. If those properties are not given, the terminal will fill
* its container.
*
* If the 'onTitleChanged' callback property is set, it will be called whenever
* the title of the terminal changes.
*
* Call focus() to set the input focus on the terminal.
*/
var Terminal = React.createClass({
propTypes: {
cols: React.PropTypes.number,
rows: React.PropTypes.number,
channel: React.PropTypes.object.isRequired,
onTitleChanged: React.PropTypes.func
},
componentWillMount: function () { require("console.css");
var term = new Term({ require("jquery-resizable");
cols: this.state.cols || 80, require("jquery-resizable/resizable.css");
rows: this.state.rows || 25,
screenKeys: true, /*
useStyle: true * A terminal component that communicates over a cockpit channel.
*
* The only required property is 'channel', which must point to a cockpit
* stream channel.
*
* The size of the terminal can be set with the 'rows' and 'cols'
* properties. If those properties are not given, the terminal will fill
* its container.
*
* If the 'onTitleChanged' callback property is set, it will be called whenever
* the title of the terminal changes.
*
* Call focus() to set the input focus on the terminal.
*/
var Terminal = React.createClass({
propTypes: {
// cols: React.PropTypes.number,
rows: React.PropTypes.number,
channel: React.PropTypes.object.isRequired,
onTitleChanged: React.PropTypes.func
},
componentWillMount: function () {
var term = new Term({
cols: this.state.cols || 80,
rows: this.state.rows || 25,
screenKeys: true,
useStyle: true
});
term.on('data', function(data) {
if (this.props.channel.valid)
this.props.channel.send(data);
}.bind(this));
if (this.props.onTitleChanged)
term.on('title', this.props.onTitleChanged);
this.setState({ terminal: term });
},
componentDidMount: function () {
this.state.terminal.open(this.refs.terminal);
this.connectChannel();
let term = this.refs.terminal;
let onWindowResize = this.onWindowResize;
$(function() {
$(term).resizable({
direction: ['right', 'bottom'],
stop: function() {
onWindowResize();
},
}); });
});
term.on('data', function(data) { if (!this.props.rows) {
if (this.props.channel.valid) window.addEventListener('resize', this.onWindowResize);
this.props.channel.send(data); this.onWindowResize();
}.bind(this));
if (this.props.onTitleChanged)
term.on('title', this.props.onTitleChanged);
this.setState({ terminal: term });
},
componentDidMount: function () {
this.state.terminal.open(this.refs.terminal);
this.connectChannel();
let term = this.refs.terminal;
let onWindowResize = this.onWindowResize;
$(function() {
$(term).resizable({
direction: ['right', 'bottom'],
stop: function() {
onWindowResize();
},
});
});
if (!this.props.rows) {
window.addEventListener('resize', this.onWindowResize);
this.onWindowResize();
}
},
componentWillUpdate: function (nextProps, nextState) {
if (nextState.cols !== this.state.cols || nextState.rows !== this.state.rows) {
this.state.terminal.resize(nextState.cols, nextState.rows);
this.props.channel.control({
window: {
rows: nextState.rows,
cols: nextState.cols
}
});
}
if (nextProps.channel !== this.props.channel) {
this.state.terminal.reset();
this.disconnectChannel();
}
},
componentDidUpdate: function (prevProps) {
if (prevProps.channel !== this.props.channel)
this.connectChannel();
},
render: function () {
let style = {
'min-width': '300px',
'min-height': '100px',
}
// ensure react never reuses this div by keying it with the terminal widget
return <div ref="terminal" style={style} className="console-ct" key={this.state.terminal} />;
},
componentWillUnmount: function () {
this.disconnectChannel();
this.state.terminal.destroy();
},
onChannelMessage: function (event, data) {
if (this.state.terminal) {
this.state.terminal.write(data);
}
},
onChannelClose: function (event, options) {
var term = this.state.terminal;
term.write('\x1b[31m' + (options.problem || 'disconnected') + '\x1b[m\r\n');
term.cursorHidden = true;
term.refresh(term.y, term.y);
},
connectChannel: function () {
var channel = this.props.channel;
if (channel && channel.valid) {
channel.addEventListener('message', this.onChannelMessage.bind(this));
channel.addEventListener('close', this.onChannelClose.bind(this));
}
},
disconnectChannel: function () {
if (this.props.channel) {
this.props.channel.removeEventListener('message', this.onChannelMessage);
this.props.channel.removeEventListener('close', this.onChannelClose);
}
},
focus: function () {
if (this.state.terminal)
this.state.terminal.focus();
},
onWindowResize: function () {
if (this.refs) {
var padding = 2 * 11;
var node = this.getDOMNode();
var terminal = this.refs.terminal.querySelector('.terminal');
var ch = document.createElement('div');
ch.textContent = 'M';
terminal.appendChild(ch);
var height = ch.offsetHeight; // offsetHeight is only correct for block elements
ch.style.display = 'inline';
var width = ch.offsetWidth;
terminal.removeChild(ch);
this.setState({
rows: Math.floor((node.parentElement.clientHeight - padding) / height),
cols: Math.floor((node.parentElement.clientWidth - padding) / width)
});
}
},
send: function(value) {
this.state.terminal.send(value);
} }
}); },
module.exports = { Terminal: Terminal }; componentWillUpdate: function (nextProps, nextState) {
}()); if (nextState.cols !== this.state.cols || nextState.rows !== this.state.rows) {
this.state.terminal.resize(nextState.cols, nextState.rows);
this.props.channel.control({
window: {
rows: nextState.rows,
cols: nextState.cols
}
});
}
if (nextProps.channel !== this.props.channel) {
this.state.terminal.reset();
this.disconnectChannel();
}
},
componentDidUpdate: function (prevProps) {
if (prevProps.channel !== this.props.channel)
this.connectChannel();
},
render: function () {
let style = {
'min-width': '300px',
'min-height': '100px',
};
// ensure react never reuses this div by keying it with the terminal widget
return <div ref="terminal" style={style} className="console-ct" key={this.state.terminal} />;
},
componentWillUnmount: function () {
this.disconnectChannel();
this.state.terminal.destroy();
},
onChannelMessage: function (event, data) {
if (this.state.terminal) {
this.state.terminal.write(data);
}
},
onChannelClose: function (event, options) {
var term = this.state.terminal;
term.write('\x1b[31m' + (options.problem || 'disconnected') + '\x1b[m\r\n');
term.cursorHidden = true;
term.refresh(term.y, term.y);
},
connectChannel: function () {
var channel = this.props.channel;
if (channel && channel.valid) {
channel.addEventListener('message', this.onChannelMessage.bind(this));
channel.addEventListener('close', this.onChannelClose.bind(this));
}
},
disconnectChannel: function () {
if (this.props.channel) {
this.props.channel.removeEventListener('message', this.onChannelMessage);
this.props.channel.removeEventListener('close', this.onChannelClose);
}
},
focus: function () {
if (this.state.terminal)
this.state.terminal.focus();
},
onWindowResize: function () {
if (this.refs) {
var padding = 2 * 11;
var node = this.getDOMNode();
var terminal = this.refs.terminal.querySelector('.terminal');
var ch = document.createElement('div');
ch.textContent = 'M';
terminal.appendChild(ch);
var height = ch.offsetHeight; // offsetHeight is only correct for block elements
ch.style.display = 'inline';
var width = ch.offsetWidth;
terminal.removeChild(ch);
this.setState({
rows: Math.floor((node.parentElement.clientHeight - padding) / height),
cols: Math.floor((node.parentElement.clientWidth - padding) / width)
});
}
},
send: function(value) {
this.state.terminal.send(value);
}
});
// module.exports = { Terminal: Terminal };
export class Terminal;

View file

@ -30,6 +30,7 @@ var info = {
"config": [ "config": [
"./config.jsx", "./config.jsx",
"./recordings.css", "./recordings.css",
"./table.css",
] ]
}, },
files: [ files: [
@ -38,6 +39,7 @@ var info = {
"player.jsx", "player.jsx",
"recordings.jsx", "recordings.jsx",
"recordings.css", "recordings.css",
"table.css",
"terminal.jsx", "terminal.jsx",
"manifest.json", "manifest.json",
"timer.css", "timer.css",