js
stringlengths
15
72.5k
jest_block
stringlengths
27
48.7k
description
stringlengths
1
1.46k
import React from 'react';import { BrowserRouter as Router, Route } from 'react-router-dom';import { Switch } from 'react-router'; import App from './010-app';import LargeMessage from './200-largeMessage';const Root = () => ( <Router> <Switch> <Route exact path="/" component={App} />
describe('Root', () => { it('renders correctly', () => { const tree = renderer.create(<Root />).toJSON(); expect(tree).toMatchSnapshot(); }); });
Root renders correctly
import React from 'react';import * as ReactRedux from 'react-redux';import { Floats, Notifications, Hints, hintDefine, hintShow, LargeMessage, Spinner, isDark,} from 'giu';import tinycolor from 'tinycolor2';import pick from 'lodash/pick';import Toolbar from './015-toolbar';import Story from './020-story';require('./app.sass');const mapStateToProps = (state) => ({ fRelativeTime: state.settings.timeType === 'RELATIVE', cxState: state.cx.cxState, mainStory: state.stories.mainStory, colors: pick(state.settings, [ 'colorClientBg', 'colorServerBg', 'colorUiBg', 'colorClientFg', 'colorServerFg', 'colorUiFg', 'colorClientBgIsDark', 'colorServerBgIsDark', 'colorUiBgIsDark', ]),});class App extends React.PureComponent { static propTypes = { fRelativeTime: React.PropTypes.bool.isRequired, cxState: React.PropTypes.string.isRequired, mainStory: React.PropTypes.object.isRequired, colors: React.PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { seqFullRefresh: 0, timeRef: null, }; } componentDidMount() { this.timerFullRefresh = setInterval(this.fullRefresh, 30e3); window.addEventListener('scroll', this.onScroll); this.showHint(); } componentWillUnmount() { clearInterval(this.timerFullRefresh); this.timerFullRefresh = null; window.removeEventListener('scroll', this.onScroll); } componentDidUpdate() { if (this.fAnchoredToBottom) { window.scrollTo(0, document.body.scrollHeight); } this.showHint(); } fullRefresh = () => { if (!this.props.fRelativeTime) return; this.setState({ seqFullRefresh: this.state.seqFullRefresh + 1, }); } onScroll = () => { const bcr = this.refs.outer.getBoundingClientRect(); this.fAnchoredToBottom = bcr.bottom - window.innerHeight < 30; } render() { let reduxDevTools; const { cxState, colors } = this.props; const fConnected = cxState === 'CONNECTED'; return ( <div ref="outer" id="appRoot" style={style.outer(colors)}> <Floats /> <Notifications /> <Hints /> {!fConnected && this.renderConnecting()} {fConnected && <Toolbar colors={colors} />} {fConnected && this.renderStories()} {reduxDevTools} </div> ); } renderStories() { return ( <div style={style.stories}> <Story story={this.props.mainStory} level={0} seqFullRefresh={this.state.seqFullRefresh} timeRef={this.state.timeRef} setTimeRef={this.setTimeRef} colors={this.props.colors} /> </div> ); } renderConnecting() { return ( <LargeMessage style={style.largeMessage(this.props.colors)}> <div><Spinner /> Connecting to Storyboard...</div>{' '} <div>Navigate to your Storyboard-equipped app (and log in if required)</div> </LargeMessage> ); } setTimeRef = (timeRef) => { this.setState({ timeRef }); } showHint() { if (this.props.cxState !== 'CONNECTED') return; if (this.fAttempted) return; this.fAttempted = true; const elements = () => { const out = []; const nodeToolbar = document.getElementById('sbToolbar'); if (nodeToolbar) { const wWin = window.innerWidth; const bcr = nodeToolbar.getBoundingClientRect(); let x; x = 50; const y = 80; if (wWin > 500) { out.push({ type: 'LABEL', x, y, align: 'left', children: <span>Settings, collapse/expand…<br />that sort of stuff</span>, style: { width: 150 }, }); out.push({ type: 'ARROW', from: { x: x - 5, y }, to: { x: 20, y: bcr.bottom - 2 }, }); } x = wWin - 80; out.push({ type: 'LABEL', x, y, align: 'right', children: <span>Maybe you need to log in to see <span style={{ color: 'yellow' }}>server logs</span></span>, style: { width: 150 }, }); out.push({ type: 'ARROW', from: { x: x + 5, y }, to: { x: wWin - 50, y: bcr.bottom - 2 }, counterclockwise: true, }); } { const x = 50; const y = 230; out.push({ type: 'LABEL', x, y, align: 'left', children: ( <span> <span style={{ color: '#4df950' }}>Click</span> on timestamps to toggle: local, UTC, relative to now <br /> <span style={{ color: '#4df950' }}>Right-click</span> to set a reference timestamp </span> ), style: { width: 2000 }, }); out.push({ type: 'ARROW', from: { x: x - 5, y }, to: { x: 20, y: y + 40 }, counterclockwise: true, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy!' }); hintShow('main'); }}const style = { outer: (colors) => ({ height: '100%', backgroundColor: colors.colorUiBg, color: colors.colorUiFg, }), largeMessage: (colors) => { let color = tinycolor(colors.colorUiFg); color = isDark(colors.colorUiFg) ? color.lighten(20) : color.darken(20); return { color: color.toRgbString() }; }, stories: { padding: 4 },};const connect = ReactRedux.connect(mapStateToProps);export default connect(App);export { App as _App };
describe('App', () => { it('renders correctly when disconnected', () => { const tree = renderer.create( <App fRelativeTime={false} cxState="DISCONNECTED" mainStory={{ placeholderFor: 'mainStory' }} colors={BASE_COLORS} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); });
App renders correctly when disconnected
import React from 'react';import * as ReactRedux from 'react-redux';import { Floats, Notifications, Hints, hintDefine, hintShow, LargeMessage, Spinner, isDark,} from 'giu';import tinycolor from 'tinycolor2';import pick from 'lodash/pick';import Toolbar from './015-toolbar';import Story from './020-story';require('./app.sass');const mapStateToProps = (state) => ({ fRelativeTime: state.settings.timeType === 'RELATIVE', cxState: state.cx.cxState, mainStory: state.stories.mainStory, colors: pick(state.settings, [ 'colorClientBg', 'colorServerBg', 'colorUiBg', 'colorClientFg', 'colorServerFg', 'colorUiFg', 'colorClientBgIsDark', 'colorServerBgIsDark', 'colorUiBgIsDark', ]),});class App extends React.PureComponent { static propTypes = { fRelativeTime: React.PropTypes.bool.isRequired, cxState: React.PropTypes.string.isRequired, mainStory: React.PropTypes.object.isRequired, colors: React.PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { seqFullRefresh: 0, timeRef: null, }; } componentDidMount() { this.timerFullRefresh = setInterval(this.fullRefresh, 30e3); window.addEventListener('scroll', this.onScroll); this.showHint(); } componentWillUnmount() { clearInterval(this.timerFullRefresh); this.timerFullRefresh = null; window.removeEventListener('scroll', this.onScroll); } componentDidUpdate() { if (this.fAnchoredToBottom) { window.scrollTo(0, document.body.scrollHeight); } this.showHint(); } fullRefresh = () => { if (!this.props.fRelativeTime) return; this.setState({ seqFullRefresh: this.state.seqFullRefresh + 1, }); } onScroll = () => { const bcr = this.refs.outer.getBoundingClientRect(); this.fAnchoredToBottom = bcr.bottom - window.innerHeight < 30; } render() { let reduxDevTools; const { cxState, colors } = this.props; const fConnected = cxState === 'CONNECTED'; return ( <div ref="outer" id="appRoot" style={style.outer(colors)}> <Floats /> <Notifications /> <Hints /> {!fConnected && this.renderConnecting()} {fConnected && <Toolbar colors={colors} />} {fConnected && this.renderStories()} {reduxDevTools} </div> ); } renderStories() { return ( <div style={style.stories}> <Story story={this.props.mainStory} level={0} seqFullRefresh={this.state.seqFullRefresh} timeRef={this.state.timeRef} setTimeRef={this.setTimeRef} colors={this.props.colors} /> </div> ); } renderConnecting() { return ( <LargeMessage style={style.largeMessage(this.props.colors)}> <div><Spinner /> Connecting to Storyboard...</div>{' '} <div>Navigate to your Storyboard-equipped app (and log in if required)</div> </LargeMessage> ); } setTimeRef = (timeRef) => { this.setState({ timeRef }); } showHint() { if (this.props.cxState !== 'CONNECTED') return; if (this.fAttempted) return; this.fAttempted = true; const elements = () => { const out = []; const nodeToolbar = document.getElementById('sbToolbar'); if (nodeToolbar) { const wWin = window.innerWidth; const bcr = nodeToolbar.getBoundingClientRect(); let x; x = 50; const y = 80; if (wWin > 500) { out.push({ type: 'LABEL', x, y, align: 'left', children: <span>Settings, collapse/expand…<br />that sort of stuff</span>, style: { width: 150 }, }); out.push({ type: 'ARROW', from: { x: x - 5, y }, to: { x: 20, y: bcr.bottom - 2 }, }); } x = wWin - 80; out.push({ type: 'LABEL', x, y, align: 'right', children: <span>Maybe you need to log in to see <span style={{ color: 'yellow' }}>server logs</span></span>, style: { width: 150 }, }); out.push({ type: 'ARROW', from: { x: x + 5, y }, to: { x: wWin - 50, y: bcr.bottom - 2 }, counterclockwise: true, }); } { const x = 50; const y = 230; out.push({ type: 'LABEL', x, y, align: 'left', children: ( <span> <span style={{ color: '#4df950' }}>Click</span> on timestamps to toggle: local, UTC, relative to now <br /> <span style={{ color: '#4df950' }}>Right-click</span> to set a reference timestamp </span> ), style: { width: 2000 }, }); out.push({ type: 'ARROW', from: { x: x - 5, y }, to: { x: 20, y: y + 40 }, counterclockwise: true, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy!' }); hintShow('main'); }}const style = { outer: (colors) => ({ height: '100%', backgroundColor: colors.colorUiBg, color: colors.colorUiFg, }), largeMessage: (colors) => { let color = tinycolor(colors.colorUiFg); color = isDark(colors.colorUiFg) ? color.lighten(20) : color.darken(20); return { color: color.toRgbString() }; }, stories: { padding: 4 },};const connect = ReactRedux.connect(mapStateToProps);export default connect(App);export { App as _App };
describe('App', () => { it('renders correctly when connected', () => { const tree = renderer.create( <App fRelativeTime={false} cxState="CONNECTED" mainStory={{ placeholderFor: 'mainStory' }} colors={BASE_COLORS} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); });
App renders correctly when connected
import React from 'react';import socketio from 'socket.io-client';import type { FolderT, SnapshotSuiteT } from '../../common/types';import AppContents from './015-appContents';const socket = socketio.connect();const socketDisconnect = () => { socket.close();};type SidebarTypeT = 'FOLDER' | 'SUITE';type Props = { match: Object, location: Object,};type State = { fetchedItemType: ?SidebarTypeT, fetchedItem: ?(FolderT | SnapshotSuiteT), fetchedItemPath: ?string, error: ?string, fRedirectToRoot: boolean,};class App extends React.Component<Props, State> { state = { fetchedItemType: null, fetchedItem: null, fetchedItemPath: null, error: null, fRedirectToRoot: false, }; _setState(state: Object) { this.setState(state); } componentDidMount() { this.fetchSidebarData(undefined, this.props); socket.on('REFRESH', this.refetch); } componentWillUnmount() { socket.off('REFRESH', this.refetch); } componentWillUpdate(nextProps: Props) { this.fetchSidebarData(this.props, nextProps); } fetchSidebarData(prevProps?: Props, nextProps: Props) { const { match } = nextProps; const { path, url, params } = match; if (prevProps != null && url === prevProps.match.url) return; if (path === '/') { this.fetchFolder('-');
describe('App', () => { it('renders correctly', () => { const match = { path: '/', url: '/', params: {}, }; const tree = renderer.create(<App match={match} location={{}} />).toJSON(); expect(tree).toMatchSnapshot(); }); });
App renders correctly
import React from 'react';import * as ReactRedux from 'react-redux';import { TextInput, PasswordInput, Icon, Spinner,} from 'giu';import Promise from 'bluebird';import * as actions from '../actions/actions';const RETURN_KEY = 13;const mapStateToProps = ({ cx: { fLoginRequired, loginState, login } }) => ({ fLoginRequired, loginState, login,});class Login extends React.PureComponent { static propTypes = { colors: React.PropTypes.object.isRequired, fLoginRequired: React.PropTypes.bool, loginState: React.PropTypes.string.isRequired, login: React.PropTypes.string, logIn: React.PropTypes.func.isRequired, logOut: React.PropTypes.func.isRequired, }; render() { const { fLoginRequired, loginState, colors } = this.props; if (fLoginRequired == null) { return ( <div style={style.outer(colors)}> <Spinner size="lg" fixedWidth /> </div> ); } if (!fLoginRequired) { return <div style={style.outer(colors)}><i>No login required to see server logs</i></div>; } return loginState === 'LOGGED_IN' ? this.renderLogOut() : this.renderLogIn(); } renderLogOut() { const { login, colors } = this.props; const msg = login ? `Logged in as ${login}` : 'Logged in'; return ( <div style={style.outer(colors)}> {msg} {' '} <Icon icon="sign-out" title="Log out" size="lg" fixedWidth onClick={this.logOut} /> </div> ); } renderLogIn() { const { loginState, colors } = this.props; let btn; switch (loginState) { case 'LOGGED_OUT': btn = ( <Icon icon="sign-in" title="Log in" size="lg" fixedWidth onClick={this.logIn} /> ); break; case 'LOGGING_IN': btn = <Spinner title="Logging in" size="lg" fixedWidth />; break; default: btn = ''; break; } return ( <div style={style.outer(colors, true)}> <b>Server logs:</b> {' '} <TextInput ref="login" id="login" placeholder="Login" onKeyUp={this.onKeyUpCredentials} style={style.field} required errorZ={12} /> <PasswordInput ref="password" id="password" placeholder="Password" onKeyUp={this.onKeyUpCredentials} style={style.field} required errorZ={12} /> {btn} </div> ); } logIn = () => { const credentials = {}; Promise.map(['login', 'password'], (key) => this.refs[key].validateAndGetValue() .then((val) => { credentials[key] = val; }) ) .then(() => this.props.logIn(credentials)); } logOut = () => { this.props.logOut(); } onKeyUpCredentials = (ev) => { if (ev.which !== RETURN_KEY) return; this.logIn(); }}const style = { outer: (colors, fHighlight) => ({ padding: '4px 10px', backgroundColor: fHighlight ? colors.colorServerBg : colors.colorUiBg, color: fHighlight ? colors.colorServerFg : colors.colorUiFg, }), field: { marginRight: 4, width: 70, backgroundColor: 'transparent', },};const connect = ReactRedux.connect(mapStateToProps, actions);export default connect(Login);export { Login as _Login };
describe('Login', () => { it('renders correctly when login needs are still unknown', () => { const tree = renderer.create( <Login colors={BASE_COLORS} loginState="LOGGED_OUT" logIn={() => {}} logOut={() => {}} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); });
Login renders correctly when login needs are still unknown
import React from 'react';import * as ReactRedux from 'react-redux';import { TextInput, PasswordInput, Icon, Spinner,} from 'giu';import Promise from 'bluebird';import * as actions from '../actions/actions';const RETURN_KEY = 13;const mapStateToProps = ({ cx: { fLoginRequired, loginState, login } }) => ({ fLoginRequired, loginState, login,});class Login extends React.PureComponent { static propTypes = { colors: React.PropTypes.object.isRequired, fLoginRequired: React.PropTypes.bool, loginState: React.PropTypes.string.isRequired, login: React.PropTypes.string, logIn: React.PropTypes.func.isRequired, logOut: React.PropTypes.func.isRequired, }; render() { const { fLoginRequired, loginState, colors } = this.props; if (fLoginRequired == null) { return ( <div style={style.outer(colors)}> <Spinner size="lg" fixedWidth /> </div> ); } if (!fLoginRequired) { return <div style={style.outer(colors)}><i>No login required to see server logs</i></div>; } return loginState === 'LOGGED_IN' ? this.renderLogOut() : this.renderLogIn(); } renderLogOut() { const { login, colors } = this.props; const msg = login ? `Logged in as ${login}` : 'Logged in'; return ( <div style={style.outer(colors)}> {msg} {' '} <Icon icon="sign-out" title="Log out" size="lg" fixedWidth onClick={this.logOut} /> </div> ); } renderLogIn() { const { loginState, colors } = this.props; let btn; switch (loginState) { case 'LOGGED_OUT': btn = ( <Icon icon="sign-in" title="Log in" size="lg" fixedWidth onClick={this.logIn} /> ); break; case 'LOGGING_IN': btn = <Spinner title="Logging in" size="lg" fixedWidth />; break; default: btn = ''; break; } return ( <div style={style.outer(colors, true)}> <b>Server logs:</b> {' '} <TextInput ref="login" id="login" placeholder="Login" onKeyUp={this.onKeyUpCredentials} style={style.field} required errorZ={12} /> <PasswordInput ref="password" id="password" placeholder="Password" onKeyUp={this.onKeyUpCredentials} style={style.field} required errorZ={12} /> {btn} </div> ); } logIn = () => { const credentials = {}; Promise.map(['login', 'password'], (key) => this.refs[key].validateAndGetValue() .then((val) => { credentials[key] = val; }) ) .then(() => this.props.logIn(credentials)); } logOut = () => { this.props.logOut(); } onKeyUpCredentials = (ev) => { if (ev.which !== RETURN_KEY) return; this.logIn(); }}const style = { outer: (colors, fHighlight) => ({ padding: '4px 10px', backgroundColor: fHighlight ? colors.colorServerBg : colors.colorUiBg, color: fHighlight ? colors.colorServerFg : colors.colorUiFg, }), field: { marginRight: 4, width: 70, backgroundColor: 'transparent', },};const connect = ReactRedux.connect(mapStateToProps, actions);export default connect(Login);export { Login as _Login };
describe('Login', () => { it('renders correctly when no login is required', () => { const tree = renderer.create( <Login colors={BASE_COLORS} fLoginRequired={false} loginState="LOGGED_OUT" logIn={() => {}} logOut={() => {}} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); });
Login renders correctly when no login is required
import React from 'react';import * as ReactRedux from 'react-redux';import { TextInput, PasswordInput, Icon, Spinner,} from 'giu';import Promise from 'bluebird';import * as actions from '../actions/actions';const RETURN_KEY = 13;const mapStateToProps = ({ cx: { fLoginRequired, loginState, login } }) => ({ fLoginRequired, loginState, login,});class Login extends React.PureComponent { static propTypes = { colors: React.PropTypes.object.isRequired, fLoginRequired: React.PropTypes.bool, loginState: React.PropTypes.string.isRequired, login: React.PropTypes.string, logIn: React.PropTypes.func.isRequired, logOut: React.PropTypes.func.isRequired, }; render() { const { fLoginRequired, loginState, colors } = this.props; if (fLoginRequired == null) { return ( <div style={style.outer(colors)}> <Spinner size="lg" fixedWidth /> </div> ); } if (!fLoginRequired) { return <div style={style.outer(colors)}><i>No login required to see server logs</i></div>; } return loginState === 'LOGGED_IN' ? this.renderLogOut() : this.renderLogIn(); } renderLogOut() { const { login, colors } = this.props; const msg = login ? `Logged in as ${login}` : 'Logged in'; return ( <div style={style.outer(colors)}> {msg} {' '} <Icon icon="sign-out" title="Log out" size="lg" fixedWidth onClick={this.logOut} /> </div> ); } renderLogIn() { const { loginState, colors } = this.props; let btn; switch (loginState) { case 'LOGGED_OUT': btn = ( <Icon icon="sign-in" title="Log in" size="lg" fixedWidth onClick={this.logIn} /> ); break; case 'LOGGING_IN': btn = <Spinner title="Logging in" size="lg" fixedWidth />; break; default: btn = ''; break; } return ( <div style={style.outer(colors, true)}> <b>Server logs:</b> {' '} <TextInput ref="login" id="login" placeholder="Login" onKeyUp={this.onKeyUpCredentials} style={style.field} required errorZ={12} /> <PasswordInput ref="password" id="password" placeholder="Password" onKeyUp={this.onKeyUpCredentials} style={style.field} required errorZ={12} /> {btn} </div> ); } logIn = () => { const credentials = {}; Promise.map(['login', 'password'], (key) => this.refs[key].validateAndGetValue() .then((val) => { credentials[key] = val; }) ) .then(() => this.props.logIn(credentials)); } logOut = () => { this.props.logOut(); } onKeyUpCredentials = (ev) => { if (ev.which !== RETURN_KEY) return; this.logIn(); }}const style = { outer: (colors, fHighlight) => ({ padding: '4px 10px', backgroundColor: fHighlight ? colors.colorServerBg : colors.colorUiBg, color: fHighlight ? colors.colorServerFg : colors.colorUiFg, }), field: { marginRight: 4, width: 70, backgroundColor: 'transparent', },};const connect = ReactRedux.connect(mapStateToProps, actions);export default connect(Login);export { Login as _Login };
describe('Login', () => { it('renders correctly when LOGGED_IN', () => { const tree = renderer.create( <Login colors={BASE_COLORS} fLoginRequired loginState="LOGGED_IN" login="Guille" logIn={() => {}} logOut={() => {}} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); });
Login renders correctly when LOGGED_IN
import React from 'react';import * as ReactRedux from 'react-redux';import { TextInput, PasswordInput, Icon, Spinner,} from 'giu';import Promise from 'bluebird';import * as actions from '../actions/actions';const RETURN_KEY = 13;const mapStateToProps = ({ cx: { fLoginRequired, loginState, login } }) => ({ fLoginRequired, loginState, login,});class Login extends React.PureComponent { static propTypes = { colors: React.PropTypes.object.isRequired, fLoginRequired: React.PropTypes.bool, loginState: React.PropTypes.string.isRequired, login: React.PropTypes.string, logIn: React.PropTypes.func.isRequired, logOut: React.PropTypes.func.isRequired, }; render() { const { fLoginRequired, loginState, colors } = this.props; if (fLoginRequired == null) { return ( <div style={style.outer(colors)}> <Spinner size="lg" fixedWidth /> </div> ); } if (!fLoginRequired) { return <div style={style.outer(colors)}><i>No login required to see server logs</i></div>; } return loginState === 'LOGGED_IN' ? this.renderLogOut() : this.renderLogIn(); } renderLogOut() { const { login, colors } = this.props; const msg = login ? `Logged in as ${login}` : 'Logged in'; return ( <div style={style.outer(colors)}> {msg} {' '} <Icon icon="sign-out" title="Log out" size="lg" fixedWidth onClick={this.logOut} /> </div> ); } renderLogIn() { const { loginState, colors } = this.props; let btn; switch (loginState) { case 'LOGGED_OUT': btn = ( <Icon icon="sign-in" title="Log in" size="lg" fixedWidth onClick={this.logIn} /> ); break; case 'LOGGING_IN': btn = <Spinner title="Logging in" size="lg" fixedWidth />; break; default: btn = ''; break; } return ( <div style={style.outer(colors, true)}> <b>Server logs:</b> {' '} <TextInput ref="login" id="login" placeholder="Login" onKeyUp={this.onKeyUpCredentials} style={style.field} required errorZ={12} /> <PasswordInput ref="password" id="password" placeholder="Password" onKeyUp={this.onKeyUpCredentials} style={style.field} required errorZ={12} /> {btn} </div> ); } logIn = () => { const credentials = {}; Promise.map(['login', 'password'], (key) => this.refs[key].validateAndGetValue() .then((val) => { credentials[key] = val; }) ) .then(() => this.props.logIn(credentials)); } logOut = () => { this.props.logOut(); } onKeyUpCredentials = (ev) => { if (ev.which !== RETURN_KEY) return; this.logIn(); }}const style = { outer: (colors, fHighlight) => ({ padding: '4px 10px', backgroundColor: fHighlight ? colors.colorServerBg : colors.colorUiBg, color: fHighlight ? colors.colorServerFg : colors.colorUiFg, }), field: { marginRight: 4, width: 70, backgroundColor: 'transparent', },};const connect = ReactRedux.connect(mapStateToProps, actions);export default connect(Login);export { Login as _Login };
describe('Login', () => { it('renders correctly when LOGGED_OUT', () => { const tree = renderer.create( <div> <Floats /> <Login colors={BASE_COLORS} fLoginRequired loginState="LOGGED_OUT" logIn={() => {}} logOut={() => {}} /> </div> ).toJSON(); expect(tree).toMatchSnapshot(); }); });
Login renders correctly when LOGGED_OUT
import React from 'react';import * as ReactRedux from 'react-redux';import { TextInput, PasswordInput, Icon, Spinner,} from 'giu';import Promise from 'bluebird';import * as actions from '../actions/actions';const RETURN_KEY = 13;const mapStateToProps = ({ cx: { fLoginRequired, loginState, login } }) => ({ fLoginRequired, loginState, login,});class Login extends React.PureComponent { static propTypes = { colors: React.PropTypes.object.isRequired, fLoginRequired: React.PropTypes.bool, loginState: React.PropTypes.string.isRequired, login: React.PropTypes.string, logIn: React.PropTypes.func.isRequired, logOut: React.PropTypes.func.isRequired, }; render() { const { fLoginRequired, loginState, colors } = this.props; if (fLoginRequired == null) { return ( <div style={style.outer(colors)}> <Spinner size="lg" fixedWidth /> </div> ); } if (!fLoginRequired) { return <div style={style.outer(colors)}><i>No login required to see server logs</i></div>; } return loginState === 'LOGGED_IN' ? this.renderLogOut() : this.renderLogIn(); } renderLogOut() { const { login, colors } = this.props; const msg = login ? `Logged in as ${login}` : 'Logged in'; return ( <div style={style.outer(colors)}> {msg} {' '} <Icon icon="sign-out" title="Log out" size="lg" fixedWidth onClick={this.logOut} /> </div> ); } renderLogIn() { const { loginState, colors } = this.props; let btn; switch (loginState) { case 'LOGGED_OUT': btn = ( <Icon icon="sign-in" title="Log in" size="lg" fixedWidth onClick={this.logIn} /> ); break; case 'LOGGING_IN': btn = <Spinner title="Logging in" size="lg" fixedWidth />; break; default: btn = ''; break; } return ( <div style={style.outer(colors, true)}> <b>Server logs:</b> {' '} <TextInput ref="login" id="login" placeholder="Login" onKeyUp={this.onKeyUpCredentials} style={style.field} required errorZ={12} /> <PasswordInput ref="password" id="password" placeholder="Password" onKeyUp={this.onKeyUpCredentials} style={style.field} required errorZ={12} /> {btn} </div> ); } logIn = () => { const credentials = {}; Promise.map(['login', 'password'], (key) => this.refs[key].validateAndGetValue() .then((val) => { credentials[key] = val; }) ) .then(() => this.props.logIn(credentials)); } logOut = () => { this.props.logOut(); } onKeyUpCredentials = (ev) => { if (ev.which !== RETURN_KEY) return; this.logIn(); }}const style = { outer: (colors, fHighlight) => ({ padding: '4px 10px', backgroundColor: fHighlight ? colors.colorServerBg : colors.colorUiBg, color: fHighlight ? colors.colorServerFg : colors.colorUiFg, }), field: { marginRight: 4, width: 70, backgroundColor: 'transparent', },};const connect = ReactRedux.connect(mapStateToProps, actions);export default connect(Login);export { Login as _Login };
describe('Login', () => { it('renders correctly when LOGGING_IN', () => { const tree = renderer.create( <div> <Floats /> <Login colors={BASE_COLORS} fLoginRequired loginState="LOGGING_IN" logIn={() => {}} logOut={() => {}} /> </div> ).toJSON(); expect(tree).toMatchSnapshot(); }); });
Login renders correctly when LOGGING_IN
import React from 'react';import { Redirect } from 'react-router'; import { Floats, Hints, Spinner, Icon, Button, flexContainer, hintDefine, hintShow,} from 'giu';import type { FolderT, SnapshotSuiteT } from '../../common/types';import { UI } from '../gral/constants';import { waitUntil } from '../gral/helpers';import Sidebar from './110-sidebar';import SidebarItem, { SidebarGroup } from './115-sidebarItem';import Preview from './120-preview';import LargeMessage from './200-largeMessage';require('./010-app.sass');const breakAtDots = str => str.replace(/\./g, '.\u200B');const lastSegment = path => { if (!path) return ''; const segments = path.split('/'); return segments[segments.length - 1];};const snapshotName = id => { const segments = id.split(' '); return segments.slice(0, segments.length - 1).join(' ');};type SidebarTypeT = 'FOLDER' | 'SUITE';type Props = { fetchedItemType: ?SidebarTypeT, fetchedItem: ?(FolderT | SnapshotSuiteT), fetchedItemPath: ?string, error: ?string, onRedirectToRoot: () => void, fRedirectToRoot?: boolean, location: Object, saveAsBaseline: (snapshotId: string) => any,};type State = { fRaw: boolean, fShowBaseline: boolean,};class AppContents extends React.PureComponent<Props, State> { state = { fRaw: false, fShowBaseline: false, }; componentDidMount() { this.hintIfNeeded(); } render() { if (this.props.fRedirectToRoot) return <Redirect to="/" />; if (this.props.error) { return ( <LargeMessage> <Icon icon="warning" disabled /> <b>An error occurred:</b> <br /> {this.props.error} <br /> <Button onClick={this.props.onRedirectToRoot}> <Icon icon="home" disabled /> Home </Button> </LargeMessage> ); } if (!this.props.fetchedItem) { return ( <LargeMessage> <Spinner /> &nbsp;Loading… </LargeMessage> ); } return ( <div style={style.outer}> <Floats /> <Hints /> {this.renderSidebar()} {this.renderPreview()} {this.state.fShowBaseline && this.renderBaselineWarning()} </div> ); } renderSidebar() { const fFolder = this.props.fetchedItemType === 'FOLDER'; const { fetchedItemPath } = this.props; const { contents, linkBack } = fFolder ? this.renderFolder() : this.renderSuite(); let title; if (fFolder) { const folder: FolderT = (this.props.fetchedItem: any); title = folder.parentFolderPath != null ? ( <span> <Icon icon="folder-open-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath)} </span> ) : ( <span> <Icon icon="home" style={style.titleBarIcon} /> &nbsp;Root </span> ); } else { title = ( <span> <Icon icon="file-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath).split('.')[0]} </span> ); } return ( <Sidebar title={title} subtitle={fetchedItemPath} linkBack={linkBack} fRaw={this.state.fRaw} toggleRaw={this.toggleRaw} > {contents} </Sidebar> ); } renderFolder() { const folder: FolderT = (this.props.fetchedItem: any); const contents = []; folder.childrenFolderPaths.forEach((folderPath, idx) => { const id = `folder_${folderPath}`; let label = folderPath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.childrenFolderDirtyFlags[idx]} link={`/folder/${folderPath}`} icon="folder-o" fSelected={false} /> ); }); folder.filePaths.forEach((filePath, idx) => { const id = `suite_${filePath}`; let label = filePath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.suiteDirtyFlags[idx]} link={`/suite/${filePath}`} icon="file-o" fSelected={false} /> ); }); const linkBack = folder.parentFolderPath != null ? `/folder/${folder.parentFolderPath}` : null; return { contents, linkBack }; } renderSuite() { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); const { location } = this.props; const contents = []; const groups = {}; Object.keys(suite).forEach(id => { if (id === '__folderPath' || id === '__dirty' || id === '__deleted') return; const name = snapshotName(id); const snapshot = suite[id]; if (groups[name]) { groups[name].snapshots.push(snapshot); } else { groups[name] = { snapshots: [snapshot] }; } }); Object.keys(groups).forEach(name => { const { snapshots } = groups[name]; if (snapshots.length === 1) { const snapshot = snapshots[0]; const { id, dirty, deleted } = snapshot; contents.push( this.renderSnapshotSidebarItem( id, snapshotName(id), dirty, deleted, location ) ); } else { const items = snapshots.map(({ id, dirty, deleted }) => { const label = id.slice(name.length).trim(); return this.renderSnapshotSidebarItem( id, label, dirty, deleted, location ); }); contents.push( <SidebarGroup key={name} name={name}> {items} </SidebarGroup> ); } }); const linkBack = `/folder/${suite.__folderPath}`; return { contents, linkBack }; } renderSnapshotSidebarItem( id: string, label: string, dirty: boolean, deleted: boolean, location: ?Object ) { const fetchedItemPath: any = this.props.fetchedItemPath; return ( <SidebarItem key={id} id={id} label={label} dirty={dirty} deleted={deleted} link={{ pathname: `/suite/${fetchedItemPath}`, state: { id } }} icon="camera" fSelected={!!location && location.state && location.state.id === id} showBaseline={this.showBaseline} hideBaseline={this.hideBaseline} saveAsBaseline={this.props.saveAsBaseline} /> ); } renderPreview() { const { location } = this.props; const { fetchedItemType, fetchedItemPath } = this.props; let snapshot; let key = 'preview'; if ( fetchedItemType === 'SUITE' && location && location.state && location.state.id != null && fetchedItemPath ) { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); snapshot = suite[location.state.id]; key = `${fetchedItemPath}_${location.state.id}`; } return ( <Preview key={key} snapshot={snapshot} fRaw={this.state.fRaw} fShowBaseline={this.state.fShowBaseline} /> ); } renderBaselineWarning() { return ( <div className="pulsate" style={style.baselineWarning}> <Icon icon="undo" /> </div> ); } toggleRaw = () => { const { fRaw } = this.state; this.setState({ fRaw: !fRaw }); }; showBaseline = () => { this.setState({ fShowBaseline: true }); }; hideBaseline = () => { this.setState({ fShowBaseline: false }); }; hintIfNeeded = async () => { try { await waitUntil( () => !!document.getElementById('jh-sidebar'), 2000, 'hintMain' ); } catch (err) { return; } const elements = () => { const out = []; let node; node = document.getElementById('jh-sidebar'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.width / 2; const y = window.innerHeight / 2; out.push({ type: 'LABEL', x, y, align: 'center', children: 'Navigate through folders, suites and snapshots', }); out.push({ type: 'ARROW', from: { x, y }, to: { x, y: y - 40 }, counterclockwise: true, }); const x2 = bcr.width + (window.innerWidth - bcr.width) / 2; out.push({ type: 'LABEL', x: x2, y, align: 'center', children: 'Previews will appear here', }); out.push({ type: 'ARROW', from: { x: x2, y }, to: { x: x2, y: y - 40 }, counterclockwise: true, }); } node = document.getElementById('jh-toggle-raw'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.right + 60; const y = bcr.top + bcr.height / 2; out.push({ type: 'LABEL', x, y, align: 'left', children: 'Toggle between raw snapshot and HTML preview', }); out.push({ type: 'ARROW', from: { x, y }, to: { x: bcr.right + 6, y }, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy testing!' }); hintShow('main'); };}const style = { outer: flexContainer('row', { minHeight: '100vh', }), titleBarIcon: { cursor: 'default', }, baselineWarning: { fontWeight: 'bold', fontFamily: 'sans-serif', fontSize: 32, position: 'fixed', color: UI.color.accentBg, top: 10, right: 20, },};export default AppContents;
describe('AppContents', () => { it('can redirect to root if needed', () => { const tree = renderer.create(<AppContents fRedirectToRoot />).toJSON(); expect(tree).toMatchSnapshot(); }); });
AppContents can redirect to root if needed
import React from 'react';import { Redirect } from 'react-router'; import { Floats, Hints, Spinner, Icon, Button, flexContainer, hintDefine, hintShow,} from 'giu';import type { FolderT, SnapshotSuiteT } from '../../common/types';import { UI } from '../gral/constants';import { waitUntil } from '../gral/helpers';import Sidebar from './110-sidebar';import SidebarItem, { SidebarGroup } from './115-sidebarItem';import Preview from './120-preview';import LargeMessage from './200-largeMessage';require('./010-app.sass');const breakAtDots = str => str.replace(/\./g, '.\u200B');const lastSegment = path => { if (!path) return ''; const segments = path.split('/'); return segments[segments.length - 1];};const snapshotName = id => { const segments = id.split(' '); return segments.slice(0, segments.length - 1).join(' ');};type SidebarTypeT = 'FOLDER' | 'SUITE';type Props = { fetchedItemType: ?SidebarTypeT, fetchedItem: ?(FolderT | SnapshotSuiteT), fetchedItemPath: ?string, error: ?string, onRedirectToRoot: () => void, fRedirectToRoot?: boolean, location: Object, saveAsBaseline: (snapshotId: string) => any,};type State = { fRaw: boolean, fShowBaseline: boolean,};class AppContents extends React.PureComponent<Props, State> { state = { fRaw: false, fShowBaseline: false, }; componentDidMount() { this.hintIfNeeded(); } render() { if (this.props.fRedirectToRoot) return <Redirect to="/" />; if (this.props.error) { return ( <LargeMessage> <Icon icon="warning" disabled /> <b>An error occurred:</b> <br /> {this.props.error} <br /> <Button onClick={this.props.onRedirectToRoot}> <Icon icon="home" disabled /> Home </Button> </LargeMessage> ); } if (!this.props.fetchedItem) { return ( <LargeMessage> <Spinner /> &nbsp;Loading… </LargeMessage> ); } return ( <div style={style.outer}> <Floats /> <Hints /> {this.renderSidebar()} {this.renderPreview()} {this.state.fShowBaseline && this.renderBaselineWarning()} </div> ); } renderSidebar() { const fFolder = this.props.fetchedItemType === 'FOLDER'; const { fetchedItemPath } = this.props; const { contents, linkBack } = fFolder ? this.renderFolder() : this.renderSuite(); let title; if (fFolder) { const folder: FolderT = (this.props.fetchedItem: any); title = folder.parentFolderPath != null ? ( <span> <Icon icon="folder-open-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath)} </span> ) : ( <span> <Icon icon="home" style={style.titleBarIcon} /> &nbsp;Root </span> ); } else { title = ( <span> <Icon icon="file-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath).split('.')[0]} </span> ); } return ( <Sidebar title={title} subtitle={fetchedItemPath} linkBack={linkBack} fRaw={this.state.fRaw} toggleRaw={this.toggleRaw} > {contents} </Sidebar> ); } renderFolder() { const folder: FolderT = (this.props.fetchedItem: any); const contents = []; folder.childrenFolderPaths.forEach((folderPath, idx) => { const id = `folder_${folderPath}`; let label = folderPath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.childrenFolderDirtyFlags[idx]} link={`/folder/${folderPath}`} icon="folder-o" fSelected={false} /> ); }); folder.filePaths.forEach((filePath, idx) => { const id = `suite_${filePath}`; let label = filePath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.suiteDirtyFlags[idx]} link={`/suite/${filePath}`} icon="file-o" fSelected={false} /> ); }); const linkBack = folder.parentFolderPath != null ? `/folder/${folder.parentFolderPath}` : null; return { contents, linkBack }; } renderSuite() { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); const { location } = this.props; const contents = []; const groups = {}; Object.keys(suite).forEach(id => { if (id === '__folderPath' || id === '__dirty' || id === '__deleted') return; const name = snapshotName(id); const snapshot = suite[id]; if (groups[name]) { groups[name].snapshots.push(snapshot); } else { groups[name] = { snapshots: [snapshot] }; } }); Object.keys(groups).forEach(name => { const { snapshots } = groups[name]; if (snapshots.length === 1) { const snapshot = snapshots[0]; const { id, dirty, deleted } = snapshot; contents.push( this.renderSnapshotSidebarItem( id, snapshotName(id), dirty, deleted, location ) ); } else { const items = snapshots.map(({ id, dirty, deleted }) => { const label = id.slice(name.length).trim(); return this.renderSnapshotSidebarItem( id, label, dirty, deleted, location ); }); contents.push( <SidebarGroup key={name} name={name}> {items} </SidebarGroup> ); } }); const linkBack = `/folder/${suite.__folderPath}`; return { contents, linkBack }; } renderSnapshotSidebarItem( id: string, label: string, dirty: boolean, deleted: boolean, location: ?Object ) { const fetchedItemPath: any = this.props.fetchedItemPath; return ( <SidebarItem key={id} id={id} label={label} dirty={dirty} deleted={deleted} link={{ pathname: `/suite/${fetchedItemPath}`, state: { id } }} icon="camera" fSelected={!!location && location.state && location.state.id === id} showBaseline={this.showBaseline} hideBaseline={this.hideBaseline} saveAsBaseline={this.props.saveAsBaseline} /> ); } renderPreview() { const { location } = this.props; const { fetchedItemType, fetchedItemPath } = this.props; let snapshot; let key = 'preview'; if ( fetchedItemType === 'SUITE' && location && location.state && location.state.id != null && fetchedItemPath ) { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); snapshot = suite[location.state.id]; key = `${fetchedItemPath}_${location.state.id}`; } return ( <Preview key={key} snapshot={snapshot} fRaw={this.state.fRaw} fShowBaseline={this.state.fShowBaseline} /> ); } renderBaselineWarning() { return ( <div className="pulsate" style={style.baselineWarning}> <Icon icon="undo" /> </div> ); } toggleRaw = () => { const { fRaw } = this.state; this.setState({ fRaw: !fRaw }); }; showBaseline = () => { this.setState({ fShowBaseline: true }); }; hideBaseline = () => { this.setState({ fShowBaseline: false }); }; hintIfNeeded = async () => { try { await waitUntil( () => !!document.getElementById('jh-sidebar'), 2000, 'hintMain' ); } catch (err) { return; } const elements = () => { const out = []; let node; node = document.getElementById('jh-sidebar'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.width / 2; const y = window.innerHeight / 2; out.push({ type: 'LABEL', x, y, align: 'center', children: 'Navigate through folders, suites and snapshots', }); out.push({ type: 'ARROW', from: { x, y }, to: { x, y: y - 40 }, counterclockwise: true, }); const x2 = bcr.width + (window.innerWidth - bcr.width) / 2; out.push({ type: 'LABEL', x: x2, y, align: 'center', children: 'Previews will appear here', }); out.push({ type: 'ARROW', from: { x: x2, y }, to: { x: x2, y: y - 40 }, counterclockwise: true, }); } node = document.getElementById('jh-toggle-raw'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.right + 60; const y = bcr.top + bcr.height / 2; out.push({ type: 'LABEL', x, y, align: 'left', children: 'Toggle between raw snapshot and HTML preview', }); out.push({ type: 'ARROW', from: { x, y }, to: { x: bcr.right + 6, y }, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy testing!' }); hintShow('main'); };}const style = { outer: flexContainer('row', { minHeight: '100vh', }), titleBarIcon: { cursor: 'default', }, baselineWarning: { fontWeight: 'bold', fontFamily: 'sans-serif', fontSize: 32, position: 'fixed', color: UI.color.accentBg, top: 10, right: 20, },};export default AppContents;
describe('AppContents', () => { it('renders error messages', () => { const tree = renderer .create(<AppContents error="Something horrible!" />) .toJSON(); expect(tree).toMatchSnapshot(); }); });
AppContents renders error messages
import React from 'react';import { Redirect } from 'react-router'; import { Floats, Hints, Spinner, Icon, Button, flexContainer, hintDefine, hintShow,} from 'giu';import type { FolderT, SnapshotSuiteT } from '../../common/types';import { UI } from '../gral/constants';import { waitUntil } from '../gral/helpers';import Sidebar from './110-sidebar';import SidebarItem, { SidebarGroup } from './115-sidebarItem';import Preview from './120-preview';import LargeMessage from './200-largeMessage';require('./010-app.sass');const breakAtDots = str => str.replace(/\./g, '.\u200B');const lastSegment = path => { if (!path) return ''; const segments = path.split('/'); return segments[segments.length - 1];};const snapshotName = id => { const segments = id.split(' '); return segments.slice(0, segments.length - 1).join(' ');};type SidebarTypeT = 'FOLDER' | 'SUITE';type Props = { fetchedItemType: ?SidebarTypeT, fetchedItem: ?(FolderT | SnapshotSuiteT), fetchedItemPath: ?string, error: ?string, onRedirectToRoot: () => void, fRedirectToRoot?: boolean, location: Object, saveAsBaseline: (snapshotId: string) => any,};type State = { fRaw: boolean, fShowBaseline: boolean,};class AppContents extends React.PureComponent<Props, State> { state = { fRaw: false, fShowBaseline: false, }; componentDidMount() { this.hintIfNeeded(); } render() { if (this.props.fRedirectToRoot) return <Redirect to="/" />; if (this.props.error) { return ( <LargeMessage> <Icon icon="warning" disabled /> <b>An error occurred:</b> <br /> {this.props.error} <br /> <Button onClick={this.props.onRedirectToRoot}> <Icon icon="home" disabled /> Home </Button> </LargeMessage> ); } if (!this.props.fetchedItem) { return ( <LargeMessage> <Spinner /> &nbsp;Loading… </LargeMessage> ); } return ( <div style={style.outer}> <Floats /> <Hints /> {this.renderSidebar()} {this.renderPreview()} {this.state.fShowBaseline && this.renderBaselineWarning()} </div> ); } renderSidebar() { const fFolder = this.props.fetchedItemType === 'FOLDER'; const { fetchedItemPath } = this.props; const { contents, linkBack } = fFolder ? this.renderFolder() : this.renderSuite(); let title; if (fFolder) { const folder: FolderT = (this.props.fetchedItem: any); title = folder.parentFolderPath != null ? ( <span> <Icon icon="folder-open-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath)} </span> ) : ( <span> <Icon icon="home" style={style.titleBarIcon} /> &nbsp;Root </span> ); } else { title = ( <span> <Icon icon="file-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath).split('.')[0]} </span> ); } return ( <Sidebar title={title} subtitle={fetchedItemPath} linkBack={linkBack} fRaw={this.state.fRaw} toggleRaw={this.toggleRaw} > {contents} </Sidebar> ); } renderFolder() { const folder: FolderT = (this.props.fetchedItem: any); const contents = []; folder.childrenFolderPaths.forEach((folderPath, idx) => { const id = `folder_${folderPath}`; let label = folderPath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.childrenFolderDirtyFlags[idx]} link={`/folder/${folderPath}`} icon="folder-o" fSelected={false} /> ); }); folder.filePaths.forEach((filePath, idx) => { const id = `suite_${filePath}`; let label = filePath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.suiteDirtyFlags[idx]} link={`/suite/${filePath}`} icon="file-o" fSelected={false} /> ); }); const linkBack = folder.parentFolderPath != null ? `/folder/${folder.parentFolderPath}` : null; return { contents, linkBack }; } renderSuite() { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); const { location } = this.props; const contents = []; const groups = {}; Object.keys(suite).forEach(id => { if (id === '__folderPath' || id === '__dirty' || id === '__deleted') return; const name = snapshotName(id); const snapshot = suite[id]; if (groups[name]) { groups[name].snapshots.push(snapshot); } else { groups[name] = { snapshots: [snapshot] }; } }); Object.keys(groups).forEach(name => { const { snapshots } = groups[name]; if (snapshots.length === 1) { const snapshot = snapshots[0]; const { id, dirty, deleted } = snapshot; contents.push( this.renderSnapshotSidebarItem( id, snapshotName(id), dirty, deleted, location ) ); } else { const items = snapshots.map(({ id, dirty, deleted }) => { const label = id.slice(name.length).trim(); return this.renderSnapshotSidebarItem( id, label, dirty, deleted, location ); }); contents.push( <SidebarGroup key={name} name={name}> {items} </SidebarGroup> ); } }); const linkBack = `/folder/${suite.__folderPath}`; return { contents, linkBack }; } renderSnapshotSidebarItem( id: string, label: string, dirty: boolean, deleted: boolean, location: ?Object ) { const fetchedItemPath: any = this.props.fetchedItemPath; return ( <SidebarItem key={id} id={id} label={label} dirty={dirty} deleted={deleted} link={{ pathname: `/suite/${fetchedItemPath}`, state: { id } }} icon="camera" fSelected={!!location && location.state && location.state.id === id} showBaseline={this.showBaseline} hideBaseline={this.hideBaseline} saveAsBaseline={this.props.saveAsBaseline} /> ); } renderPreview() { const { location } = this.props; const { fetchedItemType, fetchedItemPath } = this.props; let snapshot; let key = 'preview'; if ( fetchedItemType === 'SUITE' && location && location.state && location.state.id != null && fetchedItemPath ) { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); snapshot = suite[location.state.id]; key = `${fetchedItemPath}_${location.state.id}`; } return ( <Preview key={key} snapshot={snapshot} fRaw={this.state.fRaw} fShowBaseline={this.state.fShowBaseline} /> ); } renderBaselineWarning() { return ( <div className="pulsate" style={style.baselineWarning}> <Icon icon="undo" /> </div> ); } toggleRaw = () => { const { fRaw } = this.state; this.setState({ fRaw: !fRaw }); }; showBaseline = () => { this.setState({ fShowBaseline: true }); }; hideBaseline = () => { this.setState({ fShowBaseline: false }); }; hintIfNeeded = async () => { try { await waitUntil( () => !!document.getElementById('jh-sidebar'), 2000, 'hintMain' ); } catch (err) { return; } const elements = () => { const out = []; let node; node = document.getElementById('jh-sidebar'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.width / 2; const y = window.innerHeight / 2; out.push({ type: 'LABEL', x, y, align: 'center', children: 'Navigate through folders, suites and snapshots', }); out.push({ type: 'ARROW', from: { x, y }, to: { x, y: y - 40 }, counterclockwise: true, }); const x2 = bcr.width + (window.innerWidth - bcr.width) / 2; out.push({ type: 'LABEL', x: x2, y, align: 'center', children: 'Previews will appear here', }); out.push({ type: 'ARROW', from: { x: x2, y }, to: { x: x2, y: y - 40 }, counterclockwise: true, }); } node = document.getElementById('jh-toggle-raw'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.right + 60; const y = bcr.top + bcr.height / 2; out.push({ type: 'LABEL', x, y, align: 'left', children: 'Toggle between raw snapshot and HTML preview', }); out.push({ type: 'ARROW', from: { x, y }, to: { x: bcr.right + 6, y }, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy testing!' }); hintShow('main'); };}const style = { outer: flexContainer('row', { minHeight: '100vh', }), titleBarIcon: { cursor: 'default', }, baselineWarning: { fontWeight: 'bold', fontFamily: 'sans-serif', fontSize: 32, position: 'fixed', color: UI.color.accentBg, top: 10, right: 20, },};export default AppContents;
describe('AppContents', () => { it('renders a spinner while loading', () => { const tree = renderer .create(<AppContents error={null} fetchedItem={null} />) .toJSON(); expect(tree).toMatchSnapshot(); }); });
AppContents renders a spinner while loading
import React from 'react';import { Redirect } from 'react-router'; import { Floats, Hints, Spinner, Icon, Button, flexContainer, hintDefine, hintShow,} from 'giu';import type { FolderT, SnapshotSuiteT } from '../../common/types';import { UI } from '../gral/constants';import { waitUntil } from '../gral/helpers';import Sidebar from './110-sidebar';import SidebarItem, { SidebarGroup } from './115-sidebarItem';import Preview from './120-preview';import LargeMessage from './200-largeMessage';require('./010-app.sass');const breakAtDots = str => str.replace(/\./g, '.\u200B');const lastSegment = path => { if (!path) return ''; const segments = path.split('/'); return segments[segments.length - 1];};const snapshotName = id => { const segments = id.split(' '); return segments.slice(0, segments.length - 1).join(' ');};type SidebarTypeT = 'FOLDER' | 'SUITE';type Props = { fetchedItemType: ?SidebarTypeT, fetchedItem: ?(FolderT | SnapshotSuiteT), fetchedItemPath: ?string, error: ?string, onRedirectToRoot: () => void, fRedirectToRoot?: boolean, location: Object, saveAsBaseline: (snapshotId: string) => any,};type State = { fRaw: boolean, fShowBaseline: boolean,};class AppContents extends React.PureComponent<Props, State> { state = { fRaw: false, fShowBaseline: false, }; componentDidMount() { this.hintIfNeeded(); } render() { if (this.props.fRedirectToRoot) return <Redirect to="/" />; if (this.props.error) { return ( <LargeMessage> <Icon icon="warning" disabled /> <b>An error occurred:</b> <br /> {this.props.error} <br /> <Button onClick={this.props.onRedirectToRoot}> <Icon icon="home" disabled /> Home </Button> </LargeMessage> ); } if (!this.props.fetchedItem) { return ( <LargeMessage> <Spinner /> &nbsp;Loading… </LargeMessage> ); } return ( <div style={style.outer}> <Floats /> <Hints /> {this.renderSidebar()} {this.renderPreview()} {this.state.fShowBaseline && this.renderBaselineWarning()} </div> ); } renderSidebar() { const fFolder = this.props.fetchedItemType === 'FOLDER'; const { fetchedItemPath } = this.props; const { contents, linkBack } = fFolder ? this.renderFolder() : this.renderSuite(); let title; if (fFolder) { const folder: FolderT = (this.props.fetchedItem: any); title = folder.parentFolderPath != null ? ( <span> <Icon icon="folder-open-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath)} </span> ) : ( <span> <Icon icon="home" style={style.titleBarIcon} /> &nbsp;Root </span> ); } else { title = ( <span> <Icon icon="file-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath).split('.')[0]} </span> ); } return ( <Sidebar title={title} subtitle={fetchedItemPath} linkBack={linkBack} fRaw={this.state.fRaw} toggleRaw={this.toggleRaw} > {contents} </Sidebar> ); } renderFolder() { const folder: FolderT = (this.props.fetchedItem: any); const contents = []; folder.childrenFolderPaths.forEach((folderPath, idx) => { const id = `folder_${folderPath}`; let label = folderPath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.childrenFolderDirtyFlags[idx]} link={`/folder/${folderPath}`} icon="folder-o" fSelected={false} /> ); }); folder.filePaths.forEach((filePath, idx) => { const id = `suite_${filePath}`; let label = filePath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.suiteDirtyFlags[idx]} link={`/suite/${filePath}`} icon="file-o" fSelected={false} /> ); }); const linkBack = folder.parentFolderPath != null ? `/folder/${folder.parentFolderPath}` : null; return { contents, linkBack }; } renderSuite() { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); const { location } = this.props; const contents = []; const groups = {}; Object.keys(suite).forEach(id => { if (id === '__folderPath' || id === '__dirty' || id === '__deleted') return; const name = snapshotName(id); const snapshot = suite[id]; if (groups[name]) { groups[name].snapshots.push(snapshot); } else { groups[name] = { snapshots: [snapshot] }; } }); Object.keys(groups).forEach(name => { const { snapshots } = groups[name]; if (snapshots.length === 1) { const snapshot = snapshots[0]; const { id, dirty, deleted } = snapshot; contents.push( this.renderSnapshotSidebarItem( id, snapshotName(id), dirty, deleted, location ) ); } else { const items = snapshots.map(({ id, dirty, deleted }) => { const label = id.slice(name.length).trim(); return this.renderSnapshotSidebarItem( id, label, dirty, deleted, location ); }); contents.push( <SidebarGroup key={name} name={name}> {items} </SidebarGroup> ); } }); const linkBack = `/folder/${suite.__folderPath}`; return { contents, linkBack }; } renderSnapshotSidebarItem( id: string, label: string, dirty: boolean, deleted: boolean, location: ?Object ) { const fetchedItemPath: any = this.props.fetchedItemPath; return ( <SidebarItem key={id} id={id} label={label} dirty={dirty} deleted={deleted} link={{ pathname: `/suite/${fetchedItemPath}`, state: { id } }} icon="camera" fSelected={!!location && location.state && location.state.id === id} showBaseline={this.showBaseline} hideBaseline={this.hideBaseline} saveAsBaseline={this.props.saveAsBaseline} /> ); } renderPreview() { const { location } = this.props; const { fetchedItemType, fetchedItemPath } = this.props; let snapshot; let key = 'preview'; if ( fetchedItemType === 'SUITE' && location && location.state && location.state.id != null && fetchedItemPath ) { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); snapshot = suite[location.state.id]; key = `${fetchedItemPath}_${location.state.id}`; } return ( <Preview key={key} snapshot={snapshot} fRaw={this.state.fRaw} fShowBaseline={this.state.fShowBaseline} /> ); } renderBaselineWarning() { return ( <div className="pulsate" style={style.baselineWarning}> <Icon icon="undo" /> </div> ); } toggleRaw = () => { const { fRaw } = this.state; this.setState({ fRaw: !fRaw }); }; showBaseline = () => { this.setState({ fShowBaseline: true }); }; hideBaseline = () => { this.setState({ fShowBaseline: false }); }; hintIfNeeded = async () => { try { await waitUntil( () => !!document.getElementById('jh-sidebar'), 2000, 'hintMain' ); } catch (err) { return; } const elements = () => { const out = []; let node; node = document.getElementById('jh-sidebar'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.width / 2; const y = window.innerHeight / 2; out.push({ type: 'LABEL', x, y, align: 'center', children: 'Navigate through folders, suites and snapshots', }); out.push({ type: 'ARROW', from: { x, y }, to: { x, y: y - 40 }, counterclockwise: true, }); const x2 = bcr.width + (window.innerWidth - bcr.width) / 2; out.push({ type: 'LABEL', x: x2, y, align: 'center', children: 'Previews will appear here', }); out.push({ type: 'ARROW', from: { x: x2, y }, to: { x: x2, y: y - 40 }, counterclockwise: true, }); } node = document.getElementById('jh-toggle-raw'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.right + 60; const y = bcr.top + bcr.height / 2; out.push({ type: 'LABEL', x, y, align: 'left', children: 'Toggle between raw snapshot and HTML preview', }); out.push({ type: 'ARROW', from: { x, y }, to: { x: bcr.right + 6, y }, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy testing!' }); hintShow('main'); };}const style = { outer: flexContainer('row', { minHeight: '100vh', }), titleBarIcon: { cursor: 'default', }, baselineWarning: { fontWeight: 'bold', fontFamily: 'sans-serif', fontSize: 32, position: 'fixed', color: UI.color.accentBg, top: 10, right: 20, },};export default AppContents;
describe('AppContents', () => { it('renders a folder with subfolders correctly', () => { const tree = renderer .create( <AppContents fetchedItemType="FOLDER" fetchedItem={FOLDER_WITH_SUBFOLDERS} fetchedItemPath="-/path/to/snapshots" /> ) .toJSON(); expect(tree).toMatchSnapshot(); }); });
AppContents renders a folder with subfolders correctly
import React from 'react';import { Redirect } from 'react-router'; import { Floats, Hints, Spinner, Icon, Button, flexContainer, hintDefine, hintShow,} from 'giu';import type { FolderT, SnapshotSuiteT } from '../../common/types';import { UI } from '../gral/constants';import { waitUntil } from '../gral/helpers';import Sidebar from './110-sidebar';import SidebarItem, { SidebarGroup } from './115-sidebarItem';import Preview from './120-preview';import LargeMessage from './200-largeMessage';require('./010-app.sass');const breakAtDots = str => str.replace(/\./g, '.\u200B');const lastSegment = path => { if (!path) return ''; const segments = path.split('/'); return segments[segments.length - 1];};const snapshotName = id => { const segments = id.split(' '); return segments.slice(0, segments.length - 1).join(' ');};type SidebarTypeT = 'FOLDER' | 'SUITE';type Props = { fetchedItemType: ?SidebarTypeT, fetchedItem: ?(FolderT | SnapshotSuiteT), fetchedItemPath: ?string, error: ?string, onRedirectToRoot: () => void, fRedirectToRoot?: boolean, location: Object, saveAsBaseline: (snapshotId: string) => any,};type State = { fRaw: boolean, fShowBaseline: boolean,};class AppContents extends React.PureComponent<Props, State> { state = { fRaw: false, fShowBaseline: false, }; componentDidMount() { this.hintIfNeeded(); } render() { if (this.props.fRedirectToRoot) return <Redirect to="/" />; if (this.props.error) { return ( <LargeMessage> <Icon icon="warning" disabled /> <b>An error occurred:</b> <br /> {this.props.error} <br /> <Button onClick={this.props.onRedirectToRoot}> <Icon icon="home" disabled /> Home </Button> </LargeMessage> ); } if (!this.props.fetchedItem) { return ( <LargeMessage> <Spinner /> &nbsp;Loading… </LargeMessage> ); } return ( <div style={style.outer}> <Floats /> <Hints /> {this.renderSidebar()} {this.renderPreview()} {this.state.fShowBaseline && this.renderBaselineWarning()} </div> ); } renderSidebar() { const fFolder = this.props.fetchedItemType === 'FOLDER'; const { fetchedItemPath } = this.props; const { contents, linkBack } = fFolder ? this.renderFolder() : this.renderSuite(); let title; if (fFolder) { const folder: FolderT = (this.props.fetchedItem: any); title = folder.parentFolderPath != null ? ( <span> <Icon icon="folder-open-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath)} </span> ) : ( <span> <Icon icon="home" style={style.titleBarIcon} /> &nbsp;Root </span> ); } else { title = ( <span> <Icon icon="file-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath).split('.')[0]} </span> ); } return ( <Sidebar title={title} subtitle={fetchedItemPath} linkBack={linkBack} fRaw={this.state.fRaw} toggleRaw={this.toggleRaw} > {contents} </Sidebar> ); } renderFolder() { const folder: FolderT = (this.props.fetchedItem: any); const contents = []; folder.childrenFolderPaths.forEach((folderPath, idx) => { const id = `folder_${folderPath}`; let label = folderPath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.childrenFolderDirtyFlags[idx]} link={`/folder/${folderPath}`} icon="folder-o" fSelected={false} /> ); }); folder.filePaths.forEach((filePath, idx) => { const id = `suite_${filePath}`; let label = filePath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.suiteDirtyFlags[idx]} link={`/suite/${filePath}`} icon="file-o" fSelected={false} /> ); }); const linkBack = folder.parentFolderPath != null ? `/folder/${folder.parentFolderPath}` : null; return { contents, linkBack }; } renderSuite() { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); const { location } = this.props; const contents = []; const groups = {}; Object.keys(suite).forEach(id => { if (id === '__folderPath' || id === '__dirty' || id === '__deleted') return; const name = snapshotName(id); const snapshot = suite[id]; if (groups[name]) { groups[name].snapshots.push(snapshot); } else { groups[name] = { snapshots: [snapshot] }; } }); Object.keys(groups).forEach(name => { const { snapshots } = groups[name]; if (snapshots.length === 1) { const snapshot = snapshots[0]; const { id, dirty, deleted } = snapshot; contents.push( this.renderSnapshotSidebarItem( id, snapshotName(id), dirty, deleted, location ) ); } else { const items = snapshots.map(({ id, dirty, deleted }) => { const label = id.slice(name.length).trim(); return this.renderSnapshotSidebarItem( id, label, dirty, deleted, location ); }); contents.push( <SidebarGroup key={name} name={name}> {items} </SidebarGroup> ); } }); const linkBack = `/folder/${suite.__folderPath}`; return { contents, linkBack }; } renderSnapshotSidebarItem( id: string, label: string, dirty: boolean, deleted: boolean, location: ?Object ) { const fetchedItemPath: any = this.props.fetchedItemPath; return ( <SidebarItem key={id} id={id} label={label} dirty={dirty} deleted={deleted} link={{ pathname: `/suite/${fetchedItemPath}`, state: { id } }} icon="camera" fSelected={!!location && location.state && location.state.id === id} showBaseline={this.showBaseline} hideBaseline={this.hideBaseline} saveAsBaseline={this.props.saveAsBaseline} /> ); } renderPreview() { const { location } = this.props; const { fetchedItemType, fetchedItemPath } = this.props; let snapshot; let key = 'preview'; if ( fetchedItemType === 'SUITE' && location && location.state && location.state.id != null && fetchedItemPath ) { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); snapshot = suite[location.state.id]; key = `${fetchedItemPath}_${location.state.id}`; } return ( <Preview key={key} snapshot={snapshot} fRaw={this.state.fRaw} fShowBaseline={this.state.fShowBaseline} /> ); } renderBaselineWarning() { return ( <div className="pulsate" style={style.baselineWarning}> <Icon icon="undo" /> </div> ); } toggleRaw = () => { const { fRaw } = this.state; this.setState({ fRaw: !fRaw }); }; showBaseline = () => { this.setState({ fShowBaseline: true }); }; hideBaseline = () => { this.setState({ fShowBaseline: false }); }; hintIfNeeded = async () => { try { await waitUntil( () => !!document.getElementById('jh-sidebar'), 2000, 'hintMain' ); } catch (err) { return; } const elements = () => { const out = []; let node; node = document.getElementById('jh-sidebar'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.width / 2; const y = window.innerHeight / 2; out.push({ type: 'LABEL', x, y, align: 'center', children: 'Navigate through folders, suites and snapshots', }); out.push({ type: 'ARROW', from: { x, y }, to: { x, y: y - 40 }, counterclockwise: true, }); const x2 = bcr.width + (window.innerWidth - bcr.width) / 2; out.push({ type: 'LABEL', x: x2, y, align: 'center', children: 'Previews will appear here', }); out.push({ type: 'ARROW', from: { x: x2, y }, to: { x: x2, y: y - 40 }, counterclockwise: true, }); } node = document.getElementById('jh-toggle-raw'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.right + 60; const y = bcr.top + bcr.height / 2; out.push({ type: 'LABEL', x, y, align: 'left', children: 'Toggle between raw snapshot and HTML preview', }); out.push({ type: 'ARROW', from: { x, y }, to: { x: bcr.right + 6, y }, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy testing!' }); hintShow('main'); };}const style = { outer: flexContainer('row', { minHeight: '100vh', }), titleBarIcon: { cursor: 'default', }, baselineWarning: { fontWeight: 'bold', fontFamily: 'sans-serif', fontSize: 32, position: 'fixed', color: UI.color.accentBg, top: 10, right: 20, },};export default AppContents;
describe('AppContents', () => { it('renders a folder with suites correctly', () => { const tree = renderer .create( <AppContents fetchedItemType="FOLDER" fetchedItem={FOLDER_WITH_SUITES} fetchedItemPath="-/path/to/snapshots" /> ) .toJSON(); expect(tree).toMatchSnapshot(); }); });
AppContents renders a folder with suites correctly
import React from 'react';import { Redirect } from 'react-router'; import { Floats, Hints, Spinner, Icon, Button, flexContainer, hintDefine, hintShow,} from 'giu';import type { FolderT, SnapshotSuiteT } from '../../common/types';import { UI } from '../gral/constants';import { waitUntil } from '../gral/helpers';import Sidebar from './110-sidebar';import SidebarItem, { SidebarGroup } from './115-sidebarItem';import Preview from './120-preview';import LargeMessage from './200-largeMessage';require('./010-app.sass');const breakAtDots = str => str.replace(/\./g, '.\u200B');const lastSegment = path => { if (!path) return ''; const segments = path.split('/'); return segments[segments.length - 1];};const snapshotName = id => { const segments = id.split(' '); return segments.slice(0, segments.length - 1).join(' ');};type SidebarTypeT = 'FOLDER' | 'SUITE';type Props = { fetchedItemType: ?SidebarTypeT, fetchedItem: ?(FolderT | SnapshotSuiteT), fetchedItemPath: ?string, error: ?string, onRedirectToRoot: () => void, fRedirectToRoot?: boolean, location: Object, saveAsBaseline: (snapshotId: string) => any,};type State = { fRaw: boolean, fShowBaseline: boolean,};class AppContents extends React.PureComponent<Props, State> { state = { fRaw: false, fShowBaseline: false, }; componentDidMount() { this.hintIfNeeded(); } render() { if (this.props.fRedirectToRoot) return <Redirect to="/" />; if (this.props.error) { return ( <LargeMessage> <Icon icon="warning" disabled /> <b>An error occurred:</b> <br /> {this.props.error} <br /> <Button onClick={this.props.onRedirectToRoot}> <Icon icon="home" disabled /> Home </Button> </LargeMessage> ); } if (!this.props.fetchedItem) { return ( <LargeMessage> <Spinner /> &nbsp;Loading… </LargeMessage> ); } return ( <div style={style.outer}> <Floats /> <Hints /> {this.renderSidebar()} {this.renderPreview()} {this.state.fShowBaseline && this.renderBaselineWarning()} </div> ); } renderSidebar() { const fFolder = this.props.fetchedItemType === 'FOLDER'; const { fetchedItemPath } = this.props; const { contents, linkBack } = fFolder ? this.renderFolder() : this.renderSuite(); let title; if (fFolder) { const folder: FolderT = (this.props.fetchedItem: any); title = folder.parentFolderPath != null ? ( <span> <Icon icon="folder-open-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath)} </span> ) : ( <span> <Icon icon="home" style={style.titleBarIcon} /> &nbsp;Root </span> ); } else { title = ( <span> <Icon icon="file-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath).split('.')[0]} </span> ); } return ( <Sidebar title={title} subtitle={fetchedItemPath} linkBack={linkBack} fRaw={this.state.fRaw} toggleRaw={this.toggleRaw} > {contents} </Sidebar> ); } renderFolder() { const folder: FolderT = (this.props.fetchedItem: any); const contents = []; folder.childrenFolderPaths.forEach((folderPath, idx) => { const id = `folder_${folderPath}`; let label = folderPath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.childrenFolderDirtyFlags[idx]} link={`/folder/${folderPath}`} icon="folder-o" fSelected={false} /> ); }); folder.filePaths.forEach((filePath, idx) => { const id = `suite_${filePath}`; let label = filePath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.suiteDirtyFlags[idx]} link={`/suite/${filePath}`} icon="file-o" fSelected={false} /> ); }); const linkBack = folder.parentFolderPath != null ? `/folder/${folder.parentFolderPath}` : null; return { contents, linkBack }; } renderSuite() { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); const { location } = this.props; const contents = []; const groups = {}; Object.keys(suite).forEach(id => { if (id === '__folderPath' || id === '__dirty' || id === '__deleted') return; const name = snapshotName(id); const snapshot = suite[id]; if (groups[name]) { groups[name].snapshots.push(snapshot); } else { groups[name] = { snapshots: [snapshot] }; } }); Object.keys(groups).forEach(name => { const { snapshots } = groups[name]; if (snapshots.length === 1) { const snapshot = snapshots[0]; const { id, dirty, deleted } = snapshot; contents.push( this.renderSnapshotSidebarItem( id, snapshotName(id), dirty, deleted, location ) ); } else { const items = snapshots.map(({ id, dirty, deleted }) => { const label = id.slice(name.length).trim(); return this.renderSnapshotSidebarItem( id, label, dirty, deleted, location ); }); contents.push( <SidebarGroup key={name} name={name}> {items} </SidebarGroup> ); } }); const linkBack = `/folder/${suite.__folderPath}`; return { contents, linkBack }; } renderSnapshotSidebarItem( id: string, label: string, dirty: boolean, deleted: boolean, location: ?Object ) { const fetchedItemPath: any = this.props.fetchedItemPath; return ( <SidebarItem key={id} id={id} label={label} dirty={dirty} deleted={deleted} link={{ pathname: `/suite/${fetchedItemPath}`, state: { id } }} icon="camera" fSelected={!!location && location.state && location.state.id === id} showBaseline={this.showBaseline} hideBaseline={this.hideBaseline} saveAsBaseline={this.props.saveAsBaseline} /> ); } renderPreview() { const { location } = this.props; const { fetchedItemType, fetchedItemPath } = this.props; let snapshot; let key = 'preview'; if ( fetchedItemType === 'SUITE' && location && location.state && location.state.id != null && fetchedItemPath ) { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); snapshot = suite[location.state.id]; key = `${fetchedItemPath}_${location.state.id}`; } return ( <Preview key={key} snapshot={snapshot} fRaw={this.state.fRaw} fShowBaseline={this.state.fShowBaseline} /> ); } renderBaselineWarning() { return ( <div className="pulsate" style={style.baselineWarning}> <Icon icon="undo" /> </div> ); } toggleRaw = () => { const { fRaw } = this.state; this.setState({ fRaw: !fRaw }); }; showBaseline = () => { this.setState({ fShowBaseline: true }); }; hideBaseline = () => { this.setState({ fShowBaseline: false }); }; hintIfNeeded = async () => { try { await waitUntil( () => !!document.getElementById('jh-sidebar'), 2000, 'hintMain' ); } catch (err) { return; } const elements = () => { const out = []; let node; node = document.getElementById('jh-sidebar'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.width / 2; const y = window.innerHeight / 2; out.push({ type: 'LABEL', x, y, align: 'center', children: 'Navigate through folders, suites and snapshots', }); out.push({ type: 'ARROW', from: { x, y }, to: { x, y: y - 40 }, counterclockwise: true, }); const x2 = bcr.width + (window.innerWidth - bcr.width) / 2; out.push({ type: 'LABEL', x: x2, y, align: 'center', children: 'Previews will appear here', }); out.push({ type: 'ARROW', from: { x: x2, y }, to: { x: x2, y: y - 40 }, counterclockwise: true, }); } node = document.getElementById('jh-toggle-raw'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.right + 60; const y = bcr.top + bcr.height / 2; out.push({ type: 'LABEL', x, y, align: 'left', children: 'Toggle between raw snapshot and HTML preview', }); out.push({ type: 'ARROW', from: { x, y }, to: { x: bcr.right + 6, y }, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy testing!' }); hintShow('main'); };}const style = { outer: flexContainer('row', { minHeight: '100vh', }), titleBarIcon: { cursor: 'default', }, baselineWarning: { fontWeight: 'bold', fontFamily: 'sans-serif', fontSize: 32, position: 'fixed', color: UI.color.accentBg, top: 10, right: 20, },};export default AppContents;
describe('AppContents', () => { it('renders a folder with subfolders and suites correctly', () => { const tree = renderer .create( <AppContents fetchedItemType="FOLDER" fetchedItem={FOLDER_WITH_SUBFOLDERS_AND_SUITES} fetchedItemPath="-/path/to/snapshots" /> ) .toJSON(); expect(tree).toMatchSnapshot(); }); });
AppContents renders a folder with subfolders and suites correctly
import React from 'react';import { Redirect } from 'react-router'; import { Floats, Hints, Spinner, Icon, Button, flexContainer, hintDefine, hintShow,} from 'giu';import type { FolderT, SnapshotSuiteT } from '../../common/types';import { UI } from '../gral/constants';import { waitUntil } from '../gral/helpers';import Sidebar from './110-sidebar';import SidebarItem, { SidebarGroup } from './115-sidebarItem';import Preview from './120-preview';import LargeMessage from './200-largeMessage';require('./010-app.sass');const breakAtDots = str => str.replace(/\./g, '.\u200B');const lastSegment = path => { if (!path) return ''; const segments = path.split('/'); return segments[segments.length - 1];};const snapshotName = id => { const segments = id.split(' '); return segments.slice(0, segments.length - 1).join(' ');};type SidebarTypeT = 'FOLDER' | 'SUITE';type Props = { fetchedItemType: ?SidebarTypeT, fetchedItem: ?(FolderT | SnapshotSuiteT), fetchedItemPath: ?string, error: ?string, onRedirectToRoot: () => void, fRedirectToRoot?: boolean, location: Object, saveAsBaseline: (snapshotId: string) => any,};type State = { fRaw: boolean, fShowBaseline: boolean,};class AppContents extends React.PureComponent<Props, State> { state = { fRaw: false, fShowBaseline: false, }; componentDidMount() { this.hintIfNeeded(); } render() { if (this.props.fRedirectToRoot) return <Redirect to="/" />; if (this.props.error) { return ( <LargeMessage> <Icon icon="warning" disabled /> <b>An error occurred:</b> <br /> {this.props.error} <br /> <Button onClick={this.props.onRedirectToRoot}> <Icon icon="home" disabled /> Home </Button> </LargeMessage> ); } if (!this.props.fetchedItem) { return ( <LargeMessage> <Spinner /> &nbsp;Loading… </LargeMessage> ); } return ( <div style={style.outer}> <Floats /> <Hints /> {this.renderSidebar()} {this.renderPreview()} {this.state.fShowBaseline && this.renderBaselineWarning()} </div> ); } renderSidebar() { const fFolder = this.props.fetchedItemType === 'FOLDER'; const { fetchedItemPath } = this.props; const { contents, linkBack } = fFolder ? this.renderFolder() : this.renderSuite(); let title; if (fFolder) { const folder: FolderT = (this.props.fetchedItem: any); title = folder.parentFolderPath != null ? ( <span> <Icon icon="folder-open-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath)} </span> ) : ( <span> <Icon icon="home" style={style.titleBarIcon} /> &nbsp;Root </span> ); } else { title = ( <span> <Icon icon="file-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath).split('.')[0]} </span> ); } return ( <Sidebar title={title} subtitle={fetchedItemPath} linkBack={linkBack} fRaw={this.state.fRaw} toggleRaw={this.toggleRaw} > {contents} </Sidebar> ); } renderFolder() { const folder: FolderT = (this.props.fetchedItem: any); const contents = []; folder.childrenFolderPaths.forEach((folderPath, idx) => { const id = `folder_${folderPath}`; let label = folderPath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.childrenFolderDirtyFlags[idx]} link={`/folder/${folderPath}`} icon="folder-o" fSelected={false} /> ); }); folder.filePaths.forEach((filePath, idx) => { const id = `suite_${filePath}`; let label = filePath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.suiteDirtyFlags[idx]} link={`/suite/${filePath}`} icon="file-o" fSelected={false} /> ); }); const linkBack = folder.parentFolderPath != null ? `/folder/${folder.parentFolderPath}` : null; return { contents, linkBack }; } renderSuite() { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); const { location } = this.props; const contents = []; const groups = {}; Object.keys(suite).forEach(id => { if (id === '__folderPath' || id === '__dirty' || id === '__deleted') return; const name = snapshotName(id); const snapshot = suite[id]; if (groups[name]) { groups[name].snapshots.push(snapshot); } else { groups[name] = { snapshots: [snapshot] }; } }); Object.keys(groups).forEach(name => { const { snapshots } = groups[name]; if (snapshots.length === 1) { const snapshot = snapshots[0]; const { id, dirty, deleted } = snapshot; contents.push( this.renderSnapshotSidebarItem( id, snapshotName(id), dirty, deleted, location ) ); } else { const items = snapshots.map(({ id, dirty, deleted }) => { const label = id.slice(name.length).trim(); return this.renderSnapshotSidebarItem( id, label, dirty, deleted, location ); }); contents.push( <SidebarGroup key={name} name={name}> {items} </SidebarGroup> ); } }); const linkBack = `/folder/${suite.__folderPath}`; return { contents, linkBack }; } renderSnapshotSidebarItem( id: string, label: string, dirty: boolean, deleted: boolean, location: ?Object ) { const fetchedItemPath: any = this.props.fetchedItemPath; return ( <SidebarItem key={id} id={id} label={label} dirty={dirty} deleted={deleted} link={{ pathname: `/suite/${fetchedItemPath}`, state: { id } }} icon="camera" fSelected={!!location && location.state && location.state.id === id} showBaseline={this.showBaseline} hideBaseline={this.hideBaseline} saveAsBaseline={this.props.saveAsBaseline} /> ); } renderPreview() { const { location } = this.props; const { fetchedItemType, fetchedItemPath } = this.props; let snapshot; let key = 'preview'; if ( fetchedItemType === 'SUITE' && location && location.state && location.state.id != null && fetchedItemPath ) { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); snapshot = suite[location.state.id]; key = `${fetchedItemPath}_${location.state.id}`; } return ( <Preview key={key} snapshot={snapshot} fRaw={this.state.fRaw} fShowBaseline={this.state.fShowBaseline} /> ); } renderBaselineWarning() { return ( <div className="pulsate" style={style.baselineWarning}> <Icon icon="undo" /> </div> ); } toggleRaw = () => { const { fRaw } = this.state; this.setState({ fRaw: !fRaw }); }; showBaseline = () => { this.setState({ fShowBaseline: true }); }; hideBaseline = () => { this.setState({ fShowBaseline: false }); }; hintIfNeeded = async () => { try { await waitUntil( () => !!document.getElementById('jh-sidebar'), 2000, 'hintMain' ); } catch (err) { return; } const elements = () => { const out = []; let node; node = document.getElementById('jh-sidebar'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.width / 2; const y = window.innerHeight / 2; out.push({ type: 'LABEL', x, y, align: 'center', children: 'Navigate through folders, suites and snapshots', }); out.push({ type: 'ARROW', from: { x, y }, to: { x, y: y - 40 }, counterclockwise: true, }); const x2 = bcr.width + (window.innerWidth - bcr.width) / 2; out.push({ type: 'LABEL', x: x2, y, align: 'center', children: 'Previews will appear here', }); out.push({ type: 'ARROW', from: { x: x2, y }, to: { x: x2, y: y - 40 }, counterclockwise: true, }); } node = document.getElementById('jh-toggle-raw'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.right + 60; const y = bcr.top + bcr.height / 2; out.push({ type: 'LABEL', x, y, align: 'left', children: 'Toggle between raw snapshot and HTML preview', }); out.push({ type: 'ARROW', from: { x, y }, to: { x: bcr.right + 6, y }, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy testing!' }); hintShow('main'); };}const style = { outer: flexContainer('row', { minHeight: '100vh', }), titleBarIcon: { cursor: 'default', }, baselineWarning: { fontWeight: 'bold', fontFamily: 'sans-serif', fontSize: 32, position: 'fixed', color: UI.color.accentBg, top: 10, right: 20, },};export default AppContents;
describe('AppContents', () => { it('renders the root folder correctly', () => { const tree = renderer .create( <AppContents fetchedItemType="FOLDER" fetchedItem={ROOT_FOLDER} fetchedItemPath="-" /> ) .toJSON(); expect(tree).toMatchSnapshot(); }); });
AppContents renders the root folder correctly
import React from 'react';import { Redirect } from 'react-router'; import { Floats, Hints, Spinner, Icon, Button, flexContainer, hintDefine, hintShow,} from 'giu';import type { FolderT, SnapshotSuiteT } from '../../common/types';import { UI } from '../gral/constants';import { waitUntil } from '../gral/helpers';import Sidebar from './110-sidebar';import SidebarItem, { SidebarGroup } from './115-sidebarItem';import Preview from './120-preview';import LargeMessage from './200-largeMessage';require('./010-app.sass');const breakAtDots = str => str.replace(/\./g, '.\u200B');const lastSegment = path => { if (!path) return ''; const segments = path.split('/'); return segments[segments.length - 1];};const snapshotName = id => { const segments = id.split(' '); return segments.slice(0, segments.length - 1).join(' ');};type SidebarTypeT = 'FOLDER' | 'SUITE';type Props = { fetchedItemType: ?SidebarTypeT, fetchedItem: ?(FolderT | SnapshotSuiteT), fetchedItemPath: ?string, error: ?string, onRedirectToRoot: () => void, fRedirectToRoot?: boolean, location: Object, saveAsBaseline: (snapshotId: string) => any,};type State = { fRaw: boolean, fShowBaseline: boolean,};class AppContents extends React.PureComponent<Props, State> { state = { fRaw: false, fShowBaseline: false, }; componentDidMount() { this.hintIfNeeded(); } render() { if (this.props.fRedirectToRoot) return <Redirect to="/" />; if (this.props.error) { return ( <LargeMessage> <Icon icon="warning" disabled /> <b>An error occurred:</b> <br /> {this.props.error} <br /> <Button onClick={this.props.onRedirectToRoot}> <Icon icon="home" disabled /> Home </Button> </LargeMessage> ); } if (!this.props.fetchedItem) { return ( <LargeMessage> <Spinner /> &nbsp;Loading… </LargeMessage> ); } return ( <div style={style.outer}> <Floats /> <Hints /> {this.renderSidebar()} {this.renderPreview()} {this.state.fShowBaseline && this.renderBaselineWarning()} </div> ); } renderSidebar() { const fFolder = this.props.fetchedItemType === 'FOLDER'; const { fetchedItemPath } = this.props; const { contents, linkBack } = fFolder ? this.renderFolder() : this.renderSuite(); let title; if (fFolder) { const folder: FolderT = (this.props.fetchedItem: any); title = folder.parentFolderPath != null ? ( <span> <Icon icon="folder-open-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath)} </span> ) : ( <span> <Icon icon="home" style={style.titleBarIcon} /> &nbsp;Root </span> ); } else { title = ( <span> <Icon icon="file-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath).split('.')[0]} </span> ); } return ( <Sidebar title={title} subtitle={fetchedItemPath} linkBack={linkBack} fRaw={this.state.fRaw} toggleRaw={this.toggleRaw} > {contents} </Sidebar> ); } renderFolder() { const folder: FolderT = (this.props.fetchedItem: any); const contents = []; folder.childrenFolderPaths.forEach((folderPath, idx) => { const id = `folder_${folderPath}`; let label = folderPath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.childrenFolderDirtyFlags[idx]} link={`/folder/${folderPath}`} icon="folder-o" fSelected={false} /> ); }); folder.filePaths.forEach((filePath, idx) => { const id = `suite_${filePath}`; let label = filePath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.suiteDirtyFlags[idx]} link={`/suite/${filePath}`} icon="file-o" fSelected={false} /> ); }); const linkBack = folder.parentFolderPath != null ? `/folder/${folder.parentFolderPath}` : null; return { contents, linkBack }; } renderSuite() { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); const { location } = this.props; const contents = []; const groups = {}; Object.keys(suite).forEach(id => { if (id === '__folderPath' || id === '__dirty' || id === '__deleted') return; const name = snapshotName(id); const snapshot = suite[id]; if (groups[name]) { groups[name].snapshots.push(snapshot); } else { groups[name] = { snapshots: [snapshot] }; } }); Object.keys(groups).forEach(name => { const { snapshots } = groups[name]; if (snapshots.length === 1) { const snapshot = snapshots[0]; const { id, dirty, deleted } = snapshot; contents.push( this.renderSnapshotSidebarItem( id, snapshotName(id), dirty, deleted, location ) ); } else { const items = snapshots.map(({ id, dirty, deleted }) => { const label = id.slice(name.length).trim(); return this.renderSnapshotSidebarItem( id, label, dirty, deleted, location ); }); contents.push( <SidebarGroup key={name} name={name}> {items} </SidebarGroup> ); } }); const linkBack = `/folder/${suite.__folderPath}`; return { contents, linkBack }; } renderSnapshotSidebarItem( id: string, label: string, dirty: boolean, deleted: boolean, location: ?Object ) { const fetchedItemPath: any = this.props.fetchedItemPath; return ( <SidebarItem key={id} id={id} label={label} dirty={dirty} deleted={deleted} link={{ pathname: `/suite/${fetchedItemPath}`, state: { id } }} icon="camera" fSelected={!!location && location.state && location.state.id === id} showBaseline={this.showBaseline} hideBaseline={this.hideBaseline} saveAsBaseline={this.props.saveAsBaseline} /> ); } renderPreview() { const { location } = this.props; const { fetchedItemType, fetchedItemPath } = this.props; let snapshot; let key = 'preview'; if ( fetchedItemType === 'SUITE' && location && location.state && location.state.id != null && fetchedItemPath ) { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); snapshot = suite[location.state.id]; key = `${fetchedItemPath}_${location.state.id}`; } return ( <Preview key={key} snapshot={snapshot} fRaw={this.state.fRaw} fShowBaseline={this.state.fShowBaseline} /> ); } renderBaselineWarning() { return ( <div className="pulsate" style={style.baselineWarning}> <Icon icon="undo" /> </div> ); } toggleRaw = () => { const { fRaw } = this.state; this.setState({ fRaw: !fRaw }); }; showBaseline = () => { this.setState({ fShowBaseline: true }); }; hideBaseline = () => { this.setState({ fShowBaseline: false }); }; hintIfNeeded = async () => { try { await waitUntil( () => !!document.getElementById('jh-sidebar'), 2000, 'hintMain' ); } catch (err) { return; } const elements = () => { const out = []; let node; node = document.getElementById('jh-sidebar'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.width / 2; const y = window.innerHeight / 2; out.push({ type: 'LABEL', x, y, align: 'center', children: 'Navigate through folders, suites and snapshots', }); out.push({ type: 'ARROW', from: { x, y }, to: { x, y: y - 40 }, counterclockwise: true, }); const x2 = bcr.width + (window.innerWidth - bcr.width) / 2; out.push({ type: 'LABEL', x: x2, y, align: 'center', children: 'Previews will appear here', }); out.push({ type: 'ARROW', from: { x: x2, y }, to: { x: x2, y: y - 40 }, counterclockwise: true, }); } node = document.getElementById('jh-toggle-raw'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.right + 60; const y = bcr.top + bcr.height / 2; out.push({ type: 'LABEL', x, y, align: 'left', children: 'Toggle between raw snapshot and HTML preview', }); out.push({ type: 'ARROW', from: { x, y }, to: { x: bcr.right + 6, y }, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy testing!' }); hintShow('main'); };}const style = { outer: flexContainer('row', { minHeight: '100vh', }), titleBarIcon: { cursor: 'default', }, baselineWarning: { fontWeight: 'bold', fontFamily: 'sans-serif', fontSize: 32, position: 'fixed', color: UI.color.accentBg, top: 10, right: 20, },};export default AppContents;
describe('AppContents', () => { it('renders a suite with individual snapshots correctly', () => { const tree = renderer .create( <AppContents fetchedItemType="SUITE" fetchedItem={SUITE_WITH_INDIVIDUAL_SNAPSHOTS} fetchedItemPath="-/path/to/folder/suite1.js.snap" /> ) .toJSON(); expect(tree).toMatchSnapshot(); }); });
AppContents renders a suite with individual snapshots correctly
import React from 'react';import { Redirect } from 'react-router'; import { Floats, Hints, Spinner, Icon, Button, flexContainer, hintDefine, hintShow,} from 'giu';import type { FolderT, SnapshotSuiteT } from '../../common/types';import { UI } from '../gral/constants';import { waitUntil } from '../gral/helpers';import Sidebar from './110-sidebar';import SidebarItem, { SidebarGroup } from './115-sidebarItem';import Preview from './120-preview';import LargeMessage from './200-largeMessage';require('./010-app.sass');const breakAtDots = str => str.replace(/\./g, '.\u200B');const lastSegment = path => { if (!path) return ''; const segments = path.split('/'); return segments[segments.length - 1];};const snapshotName = id => { const segments = id.split(' '); return segments.slice(0, segments.length - 1).join(' ');};type SidebarTypeT = 'FOLDER' | 'SUITE';type Props = { fetchedItemType: ?SidebarTypeT, fetchedItem: ?(FolderT | SnapshotSuiteT), fetchedItemPath: ?string, error: ?string, onRedirectToRoot: () => void, fRedirectToRoot?: boolean, location: Object, saveAsBaseline: (snapshotId: string) => any,};type State = { fRaw: boolean, fShowBaseline: boolean,};class AppContents extends React.PureComponent<Props, State> { state = { fRaw: false, fShowBaseline: false, }; componentDidMount() { this.hintIfNeeded(); } render() { if (this.props.fRedirectToRoot) return <Redirect to="/" />; if (this.props.error) { return ( <LargeMessage> <Icon icon="warning" disabled /> <b>An error occurred:</b> <br /> {this.props.error} <br /> <Button onClick={this.props.onRedirectToRoot}> <Icon icon="home" disabled /> Home </Button> </LargeMessage> ); } if (!this.props.fetchedItem) { return ( <LargeMessage> <Spinner /> &nbsp;Loading… </LargeMessage> ); } return ( <div style={style.outer}> <Floats /> <Hints /> {this.renderSidebar()} {this.renderPreview()} {this.state.fShowBaseline && this.renderBaselineWarning()} </div> ); } renderSidebar() { const fFolder = this.props.fetchedItemType === 'FOLDER'; const { fetchedItemPath } = this.props; const { contents, linkBack } = fFolder ? this.renderFolder() : this.renderSuite(); let title; if (fFolder) { const folder: FolderT = (this.props.fetchedItem: any); title = folder.parentFolderPath != null ? ( <span> <Icon icon="folder-open-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath)} </span> ) : ( <span> <Icon icon="home" style={style.titleBarIcon} /> &nbsp;Root </span> ); } else { title = ( <span> <Icon icon="file-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath).split('.')[0]} </span> ); } return ( <Sidebar title={title} subtitle={fetchedItemPath} linkBack={linkBack} fRaw={this.state.fRaw} toggleRaw={this.toggleRaw} > {contents} </Sidebar> ); } renderFolder() { const folder: FolderT = (this.props.fetchedItem: any); const contents = []; folder.childrenFolderPaths.forEach((folderPath, idx) => { const id = `folder_${folderPath}`; let label = folderPath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.childrenFolderDirtyFlags[idx]} link={`/folder/${folderPath}`} icon="folder-o" fSelected={false} /> ); }); folder.filePaths.forEach((filePath, idx) => { const id = `suite_${filePath}`; let label = filePath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.suiteDirtyFlags[idx]} link={`/suite/${filePath}`} icon="file-o" fSelected={false} /> ); }); const linkBack = folder.parentFolderPath != null ? `/folder/${folder.parentFolderPath}` : null; return { contents, linkBack }; } renderSuite() { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); const { location } = this.props; const contents = []; const groups = {}; Object.keys(suite).forEach(id => { if (id === '__folderPath' || id === '__dirty' || id === '__deleted') return; const name = snapshotName(id); const snapshot = suite[id]; if (groups[name]) { groups[name].snapshots.push(snapshot); } else { groups[name] = { snapshots: [snapshot] }; } }); Object.keys(groups).forEach(name => { const { snapshots } = groups[name]; if (snapshots.length === 1) { const snapshot = snapshots[0]; const { id, dirty, deleted } = snapshot; contents.push( this.renderSnapshotSidebarItem( id, snapshotName(id), dirty, deleted, location ) ); } else { const items = snapshots.map(({ id, dirty, deleted }) => { const label = id.slice(name.length).trim(); return this.renderSnapshotSidebarItem( id, label, dirty, deleted, location ); }); contents.push( <SidebarGroup key={name} name={name}> {items} </SidebarGroup> ); } }); const linkBack = `/folder/${suite.__folderPath}`; return { contents, linkBack }; } renderSnapshotSidebarItem( id: string, label: string, dirty: boolean, deleted: boolean, location: ?Object ) { const fetchedItemPath: any = this.props.fetchedItemPath; return ( <SidebarItem key={id} id={id} label={label} dirty={dirty} deleted={deleted} link={{ pathname: `/suite/${fetchedItemPath}`, state: { id } }} icon="camera" fSelected={!!location && location.state && location.state.id === id} showBaseline={this.showBaseline} hideBaseline={this.hideBaseline} saveAsBaseline={this.props.saveAsBaseline} /> ); } renderPreview() { const { location } = this.props; const { fetchedItemType, fetchedItemPath } = this.props; let snapshot; let key = 'preview'; if ( fetchedItemType === 'SUITE' && location && location.state && location.state.id != null && fetchedItemPath ) { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); snapshot = suite[location.state.id]; key = `${fetchedItemPath}_${location.state.id}`; } return ( <Preview key={key} snapshot={snapshot} fRaw={this.state.fRaw} fShowBaseline={this.state.fShowBaseline} /> ); } renderBaselineWarning() { return ( <div className="pulsate" style={style.baselineWarning}> <Icon icon="undo" /> </div> ); } toggleRaw = () => { const { fRaw } = this.state; this.setState({ fRaw: !fRaw }); }; showBaseline = () => { this.setState({ fShowBaseline: true }); }; hideBaseline = () => { this.setState({ fShowBaseline: false }); }; hintIfNeeded = async () => { try { await waitUntil( () => !!document.getElementById('jh-sidebar'), 2000, 'hintMain' ); } catch (err) { return; } const elements = () => { const out = []; let node; node = document.getElementById('jh-sidebar'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.width / 2; const y = window.innerHeight / 2; out.push({ type: 'LABEL', x, y, align: 'center', children: 'Navigate through folders, suites and snapshots', }); out.push({ type: 'ARROW', from: { x, y }, to: { x, y: y - 40 }, counterclockwise: true, }); const x2 = bcr.width + (window.innerWidth - bcr.width) / 2; out.push({ type: 'LABEL', x: x2, y, align: 'center', children: 'Previews will appear here', }); out.push({ type: 'ARROW', from: { x: x2, y }, to: { x: x2, y: y - 40 }, counterclockwise: true, }); } node = document.getElementById('jh-toggle-raw'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.right + 60; const y = bcr.top + bcr.height / 2; out.push({ type: 'LABEL', x, y, align: 'left', children: 'Toggle between raw snapshot and HTML preview', }); out.push({ type: 'ARROW', from: { x, y }, to: { x: bcr.right + 6, y }, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy testing!' }); hintShow('main'); };}const style = { outer: flexContainer('row', { minHeight: '100vh', }), titleBarIcon: { cursor: 'default', }, baselineWarning: { fontWeight: 'bold', fontFamily: 'sans-serif', fontSize: 32, position: 'fixed', color: UI.color.accentBg, top: 10, right: 20, },};export default AppContents;
describe('AppContents', () => { it('renders a suite with grouped snapshots correctly', () => { const tree = renderer .create( <AppContents fetchedItemType="SUITE" fetchedItem={SUITE_WITH_GROUPS_AND_INDIVIDUAL_SNAPSHOTS} fetchedItemPath="-/path/to/folder/suite1.js.snap" /> ) .toJSON(); expect(tree).toMatchSnapshot(); }); });
AppContents renders a suite with grouped snapshots correctly
import React from 'react';import { Redirect } from 'react-router'; import { Floats, Hints, Spinner, Icon, Button, flexContainer, hintDefine, hintShow,} from 'giu';import type { FolderT, SnapshotSuiteT } from '../../common/types';import { UI } from '../gral/constants';import { waitUntil } from '../gral/helpers';import Sidebar from './110-sidebar';import SidebarItem, { SidebarGroup } from './115-sidebarItem';import Preview from './120-preview';import LargeMessage from './200-largeMessage';require('./010-app.sass');const breakAtDots = str => str.replace(/\./g, '.\u200B');const lastSegment = path => { if (!path) return ''; const segments = path.split('/'); return segments[segments.length - 1];};const snapshotName = id => { const segments = id.split(' '); return segments.slice(0, segments.length - 1).join(' ');};type SidebarTypeT = 'FOLDER' | 'SUITE';type Props = { fetchedItemType: ?SidebarTypeT, fetchedItem: ?(FolderT | SnapshotSuiteT), fetchedItemPath: ?string, error: ?string, onRedirectToRoot: () => void, fRedirectToRoot?: boolean, location: Object, saveAsBaseline: (snapshotId: string) => any,};type State = { fRaw: boolean, fShowBaseline: boolean,};class AppContents extends React.PureComponent<Props, State> { state = { fRaw: false, fShowBaseline: false, }; componentDidMount() { this.hintIfNeeded(); } render() { if (this.props.fRedirectToRoot) return <Redirect to="/" />; if (this.props.error) { return ( <LargeMessage> <Icon icon="warning" disabled /> <b>An error occurred:</b> <br /> {this.props.error} <br /> <Button onClick={this.props.onRedirectToRoot}> <Icon icon="home" disabled /> Home </Button> </LargeMessage> ); } if (!this.props.fetchedItem) { return ( <LargeMessage> <Spinner /> &nbsp;Loading… </LargeMessage> ); } return ( <div style={style.outer}> <Floats /> <Hints /> {this.renderSidebar()} {this.renderPreview()} {this.state.fShowBaseline && this.renderBaselineWarning()} </div> ); } renderSidebar() { const fFolder = this.props.fetchedItemType === 'FOLDER'; const { fetchedItemPath } = this.props; const { contents, linkBack } = fFolder ? this.renderFolder() : this.renderSuite(); let title; if (fFolder) { const folder: FolderT = (this.props.fetchedItem: any); title = folder.parentFolderPath != null ? ( <span> <Icon icon="folder-open-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath)} </span> ) : ( <span> <Icon icon="home" style={style.titleBarIcon} /> &nbsp;Root </span> ); } else { title = ( <span> <Icon icon="file-o" style={style.titleBarIcon} /> &nbsp; {lastSegment(fetchedItemPath).split('.')[0]} </span> ); } return ( <Sidebar title={title} subtitle={fetchedItemPath} linkBack={linkBack} fRaw={this.state.fRaw} toggleRaw={this.toggleRaw} > {contents} </Sidebar> ); } renderFolder() { const folder: FolderT = (this.props.fetchedItem: any); const contents = []; folder.childrenFolderPaths.forEach((folderPath, idx) => { const id = `folder_${folderPath}`; let label = folderPath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.childrenFolderDirtyFlags[idx]} link={`/folder/${folderPath}`} icon="folder-o" fSelected={false} /> ); }); folder.filePaths.forEach((filePath, idx) => { const id = `suite_${filePath}`; let label = filePath; const tmpIndex = label.indexOf(`${folder.folderPath}/`); if (tmpIndex >= 0) label = label.slice(folder.folderPath.length + 1); label = breakAtDots(label); contents.push( <SidebarItem key={id} id={id} label={label} dirty={folder.suiteDirtyFlags[idx]} link={`/suite/${filePath}`} icon="file-o" fSelected={false} /> ); }); const linkBack = folder.parentFolderPath != null ? `/folder/${folder.parentFolderPath}` : null; return { contents, linkBack }; } renderSuite() { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); const { location } = this.props; const contents = []; const groups = {}; Object.keys(suite).forEach(id => { if (id === '__folderPath' || id === '__dirty' || id === '__deleted') return; const name = snapshotName(id); const snapshot = suite[id]; if (groups[name]) { groups[name].snapshots.push(snapshot); } else { groups[name] = { snapshots: [snapshot] }; } }); Object.keys(groups).forEach(name => { const { snapshots } = groups[name]; if (snapshots.length === 1) { const snapshot = snapshots[0]; const { id, dirty, deleted } = snapshot; contents.push( this.renderSnapshotSidebarItem( id, snapshotName(id), dirty, deleted, location ) ); } else { const items = snapshots.map(({ id, dirty, deleted }) => { const label = id.slice(name.length).trim(); return this.renderSnapshotSidebarItem( id, label, dirty, deleted, location ); }); contents.push( <SidebarGroup key={name} name={name}> {items} </SidebarGroup> ); } }); const linkBack = `/folder/${suite.__folderPath}`; return { contents, linkBack }; } renderSnapshotSidebarItem( id: string, label: string, dirty: boolean, deleted: boolean, location: ?Object ) { const fetchedItemPath: any = this.props.fetchedItemPath; return ( <SidebarItem key={id} id={id} label={label} dirty={dirty} deleted={deleted} link={{ pathname: `/suite/${fetchedItemPath}`, state: { id } }} icon="camera" fSelected={!!location && location.state && location.state.id === id} showBaseline={this.showBaseline} hideBaseline={this.hideBaseline} saveAsBaseline={this.props.saveAsBaseline} /> ); } renderPreview() { const { location } = this.props; const { fetchedItemType, fetchedItemPath } = this.props; let snapshot; let key = 'preview'; if ( fetchedItemType === 'SUITE' && location && location.state && location.state.id != null && fetchedItemPath ) { const suite: SnapshotSuiteT = (this.props.fetchedItem: any); snapshot = suite[location.state.id]; key = `${fetchedItemPath}_${location.state.id}`; } return ( <Preview key={key} snapshot={snapshot} fRaw={this.state.fRaw} fShowBaseline={this.state.fShowBaseline} /> ); } renderBaselineWarning() { return ( <div className="pulsate" style={style.baselineWarning}> <Icon icon="undo" /> </div> ); } toggleRaw = () => { const { fRaw } = this.state; this.setState({ fRaw: !fRaw }); }; showBaseline = () => { this.setState({ fShowBaseline: true }); }; hideBaseline = () => { this.setState({ fShowBaseline: false }); }; hintIfNeeded = async () => { try { await waitUntil( () => !!document.getElementById('jh-sidebar'), 2000, 'hintMain' ); } catch (err) { return; } const elements = () => { const out = []; let node; node = document.getElementById('jh-sidebar'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.width / 2; const y = window.innerHeight / 2; out.push({ type: 'LABEL', x, y, align: 'center', children: 'Navigate through folders, suites and snapshots', }); out.push({ type: 'ARROW', from: { x, y }, to: { x, y: y - 40 }, counterclockwise: true, }); const x2 = bcr.width + (window.innerWidth - bcr.width) / 2; out.push({ type: 'LABEL', x: x2, y, align: 'center', children: 'Previews will appear here', }); out.push({ type: 'ARROW', from: { x: x2, y }, to: { x: x2, y: y - 40 }, counterclockwise: true, }); } node = document.getElementById('jh-toggle-raw'); if (node) { const bcr = node.getBoundingClientRect(); const x = bcr.right + 60; const y = bcr.top + bcr.height / 2; out.push({ type: 'LABEL', x, y, align: 'left', children: 'Toggle between raw snapshot and HTML preview', }); out.push({ type: 'ARROW', from: { x, y }, to: { x: bcr.right + 6, y }, }); } return out; }; hintDefine('main', { elements, closeLabel: 'Enjoy testing!' }); hintShow('main'); };}const style = { outer: flexContainer('row', { minHeight: '100vh', }), titleBarIcon: { cursor: 'default', }, baselineWarning: { fontWeight: 'bold', fontFamily: 'sans-serif', fontSize: 32, position: 'fixed', color: UI.color.accentBg, top: 10, right: 20, },};export default AppContents;
describe('AppContents', () => { it('renders a suite with a selected snapshot', () => { const tree = renderer .create( <AppContents fetchedItemType="SUITE" fetchedItem={SUITE_WITH_GROUPS_AND_INDIVIDUAL_SNAPSHOTS} fetchedItemPath="-/path/to/folder/suite1.js.snap" location={{ state: { id: 'individual1 1' } }} /> ) .toJSON(); expect(tree).toMatchSnapshot(); }); });
AppContents renders a suite with a selected snapshot
import React from 'react';import * as ReactRedux from 'react-redux';import { Icon, isDark, hintShow } from 'giu';import Login from './010-login';import Settings from './016-settings';import * as actions from '../actions/actions';const mapStateToProps = (state) => ({ wsState: state.cx.wsState,});const mapDispatchToProps = { expandAllStories: actions.expandAllStories, collapseAllStories: actions.collapseAllStories, clearLogs: actions.clearLogs, quickFind: actions.quickFind,};class Toolbar extends React.PureComponent { static propTypes = { colors: React.PropTypes.object.isRequired, wsState: React.PropTypes.string.isRequired, expandAllStories: React.PropTypes.func.isRequired, collapseAllStories: React.PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { fSettingsShown: false, }; } render() { const { colors } = this.props; return ( <div id="sbToolbar"> {this.renderSettings()} <div style={style.outer(colors)}> <div style={style.left}> <Icon id="sbBtnShowSettings" icon="cog" size="lg" title="Show settings..." onClick={this.toggleSettings} style={style.icon(colors)} /> <Icon icon="chevron-circle-down" size="lg" title="Expand all stories" onClick={this.props.expandAllStories} style={style.icon(colors)} /> <Icon icon="chevron-circle-right" size="lg" title="Collapse all stories" onClick={this.props.collapseAllStories} style={style.icon(colors)} /> <Icon icon="remove" size="lg" title="Clear logs" onClick={this.props.clearLogs} style={style.icon(colors)} /> <Icon icon="info-circle" size="lg" title="Show hints" onClick={this.showHints} style={style.icon(colors)} /> {' '} <input id="quickFind" type="search" results={0} placeholder="Quick find..." onChange={this.onChangeQuickFind} style={style.quickFind(colors)} /> {this.renderWsStatus()} </div> <div style={style.spacer} /> <Login colors={colors} /> </div> <div style={style.placeholder} /> </div> ); } renderSettings() { if (!this.state.fSettingsShown) return null; return ( <Settings onClose={this.toggleSettings} colors={this.props.colors} /> ); } renderWsStatus() { const fConnected = this.props.wsState === 'CONNECTED'; const icon = fConnected ? 'chain' : 'chain-broken'; const title = fConnected ? 'Connection with the server is UP' : 'Connection with the server is DOWN'; return ( <Icon id="sbWsStatusIcon" icon={icon} size="lg" title={title} style={style.wsStatus(fConnected)} /> ); } toggleSettings = () => { this.setState({ fSettingsShown: !this.state.fSettingsShown }); } showHints = () => { hintShow('main', true); } onChangeQuickFind = (ev) => { this.props.quickFind(ev.target.value); }}const style = { outer: (colors) => { const rulerColor = isDark(colors.colorUiBg) ? '#ccc' : '#555'; return { position: 'fixed', top: 0, left: 0, height: 30, width: '100%', backgroundColor: colors.colorUiBg, borderBottom: `1px solid ${rulerColor}`, display: 'flex', flexDirection: 'row', whiteSpace: 'nowrap', zIndex: 10, }; }, icon: (colors) => ({ cursor: 'pointer', color: colors.colorUiFg, marginRight: 10, }), wsStatus: (fConnected) => ({ marginRight: 5, marginLeft: 10, color: fConnected ? 'green' : 'red', cursor: 'default', }), placeholder: { height: 30 }, left: { padding: '4px 4px 4px 8px' }, right: { padding: '4px 8px 4px 4px' }, spacer: { flex: '1 1 0px' }, quickFind: (colors) => ({ backgroundColor: 'transparent', color: colors.colorUiFg, borderWidth: 1, }),};const connect = ReactRedux.connect(mapStateToProps, mapDispatchToProps);export default connect(Toolbar);export { Toolbar as _Toolbar };
describe('Toolbar', () => { it('renders correctly when disconnected', () => { const tree = renderer.create( <Toolbar colors={BASE_COLORS} wsState="DISCONNECTED" expandAllStories={() => {}} collapseAllStories={() => {}} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); });
Toolbar renders correctly when disconnected
import React from 'react';import * as ReactRedux from 'react-redux';import { Icon, isDark, hintShow } from 'giu';import Login from './010-login';import Settings from './016-settings';import * as actions from '../actions/actions';const mapStateToProps = (state) => ({ wsState: state.cx.wsState,});const mapDispatchToProps = { expandAllStories: actions.expandAllStories, collapseAllStories: actions.collapseAllStories, clearLogs: actions.clearLogs, quickFind: actions.quickFind,};class Toolbar extends React.PureComponent { static propTypes = { colors: React.PropTypes.object.isRequired, wsState: React.PropTypes.string.isRequired, expandAllStories: React.PropTypes.func.isRequired, collapseAllStories: React.PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { fSettingsShown: false, }; } render() { const { colors } = this.props; return ( <div id="sbToolbar"> {this.renderSettings()} <div style={style.outer(colors)}> <div style={style.left}> <Icon id="sbBtnShowSettings" icon="cog" size="lg" title="Show settings..." onClick={this.toggleSettings} style={style.icon(colors)} /> <Icon icon="chevron-circle-down" size="lg" title="Expand all stories" onClick={this.props.expandAllStories} style={style.icon(colors)} /> <Icon icon="chevron-circle-right" size="lg" title="Collapse all stories" onClick={this.props.collapseAllStories} style={style.icon(colors)} /> <Icon icon="remove" size="lg" title="Clear logs" onClick={this.props.clearLogs} style={style.icon(colors)} /> <Icon icon="info-circle" size="lg" title="Show hints" onClick={this.showHints} style={style.icon(colors)} /> {' '} <input id="quickFind" type="search" results={0} placeholder="Quick find..." onChange={this.onChangeQuickFind} style={style.quickFind(colors)} /> {this.renderWsStatus()} </div> <div style={style.spacer} /> <Login colors={colors} /> </div> <div style={style.placeholder} /> </div> ); } renderSettings() { if (!this.state.fSettingsShown) return null; return ( <Settings onClose={this.toggleSettings} colors={this.props.colors} /> ); } renderWsStatus() { const fConnected = this.props.wsState === 'CONNECTED'; const icon = fConnected ? 'chain' : 'chain-broken'; const title = fConnected ? 'Connection with the server is UP' : 'Connection with the server is DOWN'; return ( <Icon id="sbWsStatusIcon" icon={icon} size="lg" title={title} style={style.wsStatus(fConnected)} /> ); } toggleSettings = () => { this.setState({ fSettingsShown: !this.state.fSettingsShown }); } showHints = () => { hintShow('main', true); } onChangeQuickFind = (ev) => { this.props.quickFind(ev.target.value); }}const style = { outer: (colors) => { const rulerColor = isDark(colors.colorUiBg) ? '#ccc' : '#555'; return { position: 'fixed', top: 0, left: 0, height: 30, width: '100%', backgroundColor: colors.colorUiBg, borderBottom: `1px solid ${rulerColor}`, display: 'flex', flexDirection: 'row', whiteSpace: 'nowrap', zIndex: 10, }; }, icon: (colors) => ({ cursor: 'pointer', color: colors.colorUiFg, marginRight: 10, }), wsStatus: (fConnected) => ({ marginRight: 5, marginLeft: 10, color: fConnected ? 'green' : 'red', cursor: 'default', }), placeholder: { height: 30 }, left: { padding: '4px 4px 4px 8px' }, right: { padding: '4px 8px 4px 4px' }, spacer: { flex: '1 1 0px' }, quickFind: (colors) => ({ backgroundColor: 'transparent', color: colors.colorUiFg, borderWidth: 1, }),};const connect = ReactRedux.connect(mapStateToProps, mapDispatchToProps);export default connect(Toolbar);export { Toolbar as _Toolbar };
describe('Toolbar', () => { it('renders correctly when connected', () => { const tree = renderer.create( <Toolbar colors={BASE_COLORS} wsState="CONNECTED" expandAllStories={() => {}} collapseAllStories={() => {}} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); });
Toolbar renders correctly when connected
import React from 'react';import * as ReactRedux from 'react-redux';import { Icon, isDark, hintShow } from 'giu';import Login from './010-login';import Settings from './016-settings';import * as actions from '../actions/actions';const mapStateToProps = (state) => ({ wsState: state.cx.wsState,});const mapDispatchToProps = { expandAllStories: actions.expandAllStories, collapseAllStories: actions.collapseAllStories, clearLogs: actions.clearLogs, quickFind: actions.quickFind,};class Toolbar extends React.PureComponent { static propTypes = { colors: React.PropTypes.object.isRequired, wsState: React.PropTypes.string.isRequired, expandAllStories: React.PropTypes.func.isRequired, collapseAllStories: React.PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { fSettingsShown: false, }; } render() { const { colors } = this.props; return ( <div id="sbToolbar"> {this.renderSettings()} <div style={style.outer(colors)}> <div style={style.left}> <Icon id="sbBtnShowSettings" icon="cog" size="lg" title="Show settings..." onClick={this.toggleSettings} style={style.icon(colors)} /> <Icon icon="chevron-circle-down" size="lg" title="Expand all stories" onClick={this.props.expandAllStories} style={style.icon(colors)} /> <Icon icon="chevron-circle-right" size="lg" title="Collapse all stories" onClick={this.props.collapseAllStories} style={style.icon(colors)} /> <Icon icon="remove" size="lg" title="Clear logs" onClick={this.props.clearLogs} style={style.icon(colors)} /> <Icon icon="info-circle" size="lg" title="Show hints" onClick={this.showHints} style={style.icon(colors)} /> {' '} <input id="quickFind" type="search" results={0} placeholder="Quick find..." onChange={this.onChangeQuickFind} style={style.quickFind(colors)} /> {this.renderWsStatus()} </div> <div style={style.spacer} /> <Login colors={colors} /> </div> <div style={style.placeholder} /> </div> ); } renderSettings() { if (!this.state.fSettingsShown) return null; return ( <Settings onClose={this.toggleSettings} colors={this.props.colors} /> ); } renderWsStatus() { const fConnected = this.props.wsState === 'CONNECTED'; const icon = fConnected ? 'chain' : 'chain-broken'; const title = fConnected ? 'Connection with the server is UP' : 'Connection with the server is DOWN'; return ( <Icon id="sbWsStatusIcon" icon={icon} size="lg" title={title} style={style.wsStatus(fConnected)} /> ); } toggleSettings = () => { this.setState({ fSettingsShown: !this.state.fSettingsShown }); } showHints = () => { hintShow('main', true); } onChangeQuickFind = (ev) => { this.props.quickFind(ev.target.value); }}const style = { outer: (colors) => { const rulerColor = isDark(colors.colorUiBg) ? '#ccc' : '#555'; return { position: 'fixed', top: 0, left: 0, height: 30, width: '100%', backgroundColor: colors.colorUiBg, borderBottom: `1px solid ${rulerColor}`, display: 'flex', flexDirection: 'row', whiteSpace: 'nowrap', zIndex: 10, }; }, icon: (colors) => ({ cursor: 'pointer', color: colors.colorUiFg, marginRight: 10, }), wsStatus: (fConnected) => ({ marginRight: 5, marginLeft: 10, color: fConnected ? 'green' : 'red', cursor: 'default', }), placeholder: { height: 30 }, left: { padding: '4px 4px 4px 8px' }, right: { padding: '4px 8px 4px 4px' }, spacer: { flex: '1 1 0px' }, quickFind: (colors) => ({ backgroundColor: 'transparent', color: colors.colorUiFg, borderWidth: 1, }),};const connect = ReactRedux.connect(mapStateToProps, mapDispatchToProps);export default connect(Toolbar);export { Toolbar as _Toolbar };
describe('Toolbar', () => { it('shows settings when the corresponding icon is clicked', () => { const component = renderer.create( <Toolbar colors={BASE_COLORS} wsState="CONNECTED" expandAllStories={() => {}} collapseAllStories={() => {}} /> ); let tree = component.toJSON(); const showSettingsBtn = $(tree, '#sbBtnShowSettings'); expect(showSettingsBtn).not.toBeNull(); showSettingsBtn.props.onClick(); tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); });
Toolbar shows settings when the corresponding icon is clicked
import React from 'react';import * as ReactRedux from 'react-redux';import { merge, omit } from 'timm';import { Icon, Modal, Button, Checkbox, TextInput, NumberInput, ColorInput,} from 'giu';import Promise from 'bluebird';import * as actions from '../actions/actions';import { DEFAULT_SETTINGS } from '../reducers/settingsReducer'; const FORM_KEYS = [ 'fShowClosedActions', 'fShorthandForDuplicates', 'fCollapseAllNewStories', 'fExpandAllNewAttachments', 'fDiscardRemoteClientLogs', 'serverFilter', 'localClientFilter', 'maxRecords', 'forgetHysteresis', 'colorClientBg', 'colorServerBg', 'colorUiBg',];let idxPresetColors = 2; const PRESET_COLORS = [ { colorClientBg: 'aliceblue', colorServerBg: 'rgb(214, 236, 255)', colorUiBg: 'white' }, { colorClientBg: 'rgb(255, 240, 240)', colorServerBg: 'rgb(255, 214, 215)', colorUiBg: 'white' }, { colorClientBg: 'rgb(250, 240, 255)', colorServerBg: 'rgb(238, 214, 255)', colorUiBg: 'white' }, { colorClientBg: 'rgb(17, 22, 54)', colorServerBg: 'rgb(14, 11, 33)', colorUiBg: 'black' },];const mapStateToProps = (state) => ({ settings: state.settings, serverFilter: state.cx.serverFilter, localClientFilter: state.cx.localClientFilter,});class Settings extends React.Component { static propTypes = { onClose: React.PropTypes.func.isRequired, colors: React.PropTypes.object.isRequired, settings: React.PropTypes.object.isRequired, serverFilter: React.PropTypes.string, localClientFilter: React.PropTypes.string, updateSettings: React.PropTypes.func.isRequired, setServerFilter: React.PropTypes.func.isRequired, setLocalClientFilter: React.PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = merge({}, this.props.settings, { _fCanSave: true, cmdsToInputs: null, }); } componentDidMount() { this.checkLocalStorage(); } render() { const { colors } = this.props; const buttons = [ { label: 'Cancel', onClick: this.props.onClose, left: true }, { label: 'Reset defaults', onClick: this.onReset, left: true }, { label: 'Save', onClick: this.onSubmit, defaultButton: true, style: style.modalDefaultButton(colors), }, ]; const { cmdsToInputs } = this.state; return ( <Modal buttons={buttons} onEsc={this.props.onClose} style={style.modal(colors)} > {this.renderLocalStorageWarning()} <Checkbox ref="fShowClosedActions" label={<span>Show <i>CLOSED</i> actions</span>} value={this.state.fShowClosedActions} cmds={cmdsToInputs} /><br /> <Checkbox ref="fShorthandForDuplicates" label={ <span> Use shorthand notation for identical consecutive logs ( <Icon icon="copy" style={style.icon} disabled /> ) </span> } value={this.state.fShorthandForDuplicates} cmds={cmdsToInputs} /><br /> <Checkbox ref="fCollapseAllNewStories" label="Collapse all new stories (even if they are still open)" value={this.state.fCollapseAllNewStories} cmds={cmdsToInputs} /><br /> <Checkbox ref="fExpandAllNewAttachments" label="Expand all attachments upon receipt" value={this.state.fExpandAllNewAttachments} cmds={cmdsToInputs} /><br /> <Checkbox ref="fDiscardRemoteClientLogs" label="Discard stories from remote clients upon receipt" value={this.state.fDiscardRemoteClientLogs} cmds={cmdsToInputs} /><br /> <br /> {this.renderLogFilters()} {this.renderForgetSettings()} {this.renderColors()} {this.renderVersion()} </Modal> ); } renderLogFilters() { const { cmdsToInputs } = this.state; return [ <div key="filterTitle" style={{ marginBottom: 5 }}> Log filters, e.g. <b>foo, ba*:INFO, -test, *:WARN</b>{' '} <a href="https: target="_blank" rel="noreferrer noopener" style={style.link} > (more examples here) </a>: </div>, <ul key="filterList" style={style.filters.list}> <li> <label htmlFor="serverFilter" style={style.filters.itemLabel}> Server: </label>{' '} <TextInput ref="serverFilter" id="serverFilter" value={this.props.serverFilter} required errorZ={52} style={style.textNumberInput(300)} cmds={cmdsToInputs} /> </li> <li> <label htmlFor="localClientFilter" style={style.filters.itemLabel}> Local client: </label>{' '} <TextInput ref="localClientFilter" id="localClientFilter" value={this.props.localClientFilter} required errorZ={52} style={style.textNumberInput(300)} cmds={cmdsToInputs} /> </li> </ul>, ]; } renderForgetSettings() { const { cmdsToInputs } = this.state; return ( <div> <label htmlFor="maxRecords"> Number of logs and stories to remember: </label>{' '} <NumberInput ref="maxRecords" id="maxRecords" step={1} min={0} value={this.state.maxRecords} onChange={(ev, maxRecords) => this.setState({ maxRecords })} style={style.textNumberInput(50)} required errorZ={52} cmds={cmdsToInputs} />{' '} <label htmlFor="forgetHysteresis"> with hysteresis: </label>{' '} <NumberInput ref="forgetHysteresis" id="forgetHysteresis" step={0.05} min={0} max={1} value={this.state.forgetHysteresis} onChange={(ev, forgetHysteresis) => this.setState({ forgetHysteresis })} style={style.textNumberInput(50)} required errorZ={52} cmds={cmdsToInputs} />{' '} <Icon icon="info-circle" title={this.maxLogsDesc()} style={style.maxLogsDesc} /> </div> ); } renderColors() { const { cmdsToInputs } = this.state; return ( <div> Colors: client stories: {' '} <ColorInput ref="colorClientBg" id="colorClientBg" value={this.state.colorClientBg} floatZ={52} styleOuter={style.colorInput} cmds={cmdsToInputs} /> {' '} server stories: {' '} <ColorInput ref="colorServerBg" id="colorServerBg" value={this.state.colorServerBg} floatZ={52} styleOuter={style.colorInput} cmds={cmdsToInputs} /> {' '} background: {' '} <ColorInput ref="colorUiBg" id="colorUiBg" value={this.state.colorUiBg} floatZ={52} styleOuter={style.colorInput} cmds={cmdsToInputs} /> <div style={{ marginTop: 3 }}> (Use very light or very dark colors for best results, or choose a {' '} <Button onClick={this.onClickPresetColors}>preset</Button>) </div> </div> ); } renderVersion() { if (!process.env.STORYBOARD_VERSION) return null; return ( <div style={style.version}> Storyboard DevTools v{process.env.STORYBOARD_VERSION}<br /> (c) <a href="https: target="_blank" rel="noreferrer noopener" style={style.link} > Guillermo Grau </a> 2016 </div> ); } renderLocalStorageWarning() { if (this.state._fCanSave) return null; const txt1 = "Changes to these settings can't be saved (beyond your current session) " + 'due to your current Chrome configuration. Please visit '; const url = 'chrome: const txt2 = ' and uncheck the option "Block third-party cookies and site' + ' data". Then close the Chrome DevTools and open them again.'; return ( <div className="allowUserSelect" style={style.localStorageWarning}> {txt1}<b>{url}</b>{txt2} </div> ); } maxLogsDesc() { const hyst = this.state.forgetHysteresis; const hi = this.state.maxRecords; const lo = hi - (hi * hyst); return `When the backlog reaches ${hi}, Storyboard will ` + `start forgetting old stuff until it goes below ${lo}`; } onSubmit = () => { const settings = {}; Promise.map(FORM_KEYS, (key) => { const ref = this.refs[key]; if (!ref) throw new Error('Could not read form'); return this.refs[key].validateAndGetValue() .then((val) => { settings[key] = val; }); }) .then(() => { const persistedSettings = omit(settings, ['serverFilter', 'localClientFilter']); this.props.updateSettings(persistedSettings); if (settings.serverFilter !== this.props.serverFilter) { this.props.setServerFilter(settings.serverFilter); } if (settings.localClientFilter !== this.props.localClientFilter) { this.props.setLocalClientFilter(settings.localClientFilter); } this.props.onClose(); }); } onReset = () => { this.setState(DEFAULT_SETTINGS); this.setState({ cmdsToInputs: [{ type: 'REVERT' }], }); } onClickPresetColors = () => { idxPresetColors = (idxPresetColors + 1) % PRESET_COLORS.length; const presetColors = PRESET_COLORS[idxPresetColors]; this.setState(presetColors); } checkLocalStorage() { try { const ls = localStorage.foo; this.setState({ _fCanSave: true }); } catch (error) { this.setState({ _fCanSave: false }); } }}const style = { modal: (colors) => ({ backgroundColor: colors.colorUiBgIsDark ? 'black' : 'white', color: colors.colorUiBgIsDark ? 'white' : 'black', }), modalDefaultButton: (colors) => ({ border: colors.colorUiBgIsDark ? '1px solid white' : undefined, }), version: { textAlign: 'right', color: '#888', marginTop: 8, marginBottom: 8, }, link: { color: 'currentColor' }, icon: { color: 'currentColor' }, localStorageWarning: { color: 'red', border: '1px solid red', padding: 15, marginBottom: 10, borderRadius: 2, maxWidth: 500, }, maxLogsDesc: { cursor: 'pointer' }, filters: { list: { marginTop: 0 }, itemLabel: { display: 'inline-block', width: 80, }, }, colorInput: { position: 'relative', top: 1, }, textNumberInput: (width) => ({ backgroundColor: 'transparent', width, }),};const connect = ReactRedux.connect(mapStateToProps, actions);export default connect(Settings);export { Settings as _Settings };
describe('Settings', () => { it('renders correctly', () => { const settings = { colorClientBg: 'aliceblue', colorClientBgIsDark: false, colorClientFg: 'black', colorServerBg: 'rgb(214, 236, 255)', colorServerBgIsDark: false, colorServerFg: 'black', colorUiBg: 'white', colorUiBgIsDark: false, colorUiFg: 'rgb(64, 64, 64)', fCollapseAllNewStories: false, fDiscardRemoteClientLogs: false, fExpandAllNewAttachments: false, fShorthandForDuplicates: true, fShowClosedActions: false, forgetHysteresis: 0.25, maxRecords: 800, timeType: 'LOCAL', }; const tree = renderer.create( <div> <Floats /> <Settings onClose={() => {}} colors={BASE_COLORS} settings={settings} serverFilter="*:INFO" localClientFilter="*:DEBUG" updateSettings={() => {}} setServerFilter={() => {}} setLocalClientFilter={() => {}} /> </div> ).toJSON(); expect(tree).toMatchSnapshot(); }); });
Settings renders correctly
import React from 'react';import * as ReactRedux from 'react-redux';import { set as timmSet } from 'timm';import dateFormat from 'date-fns/format';import dateDistanceInWords from 'date-fns/distance_in_words_strict';import { Icon, Spinner, cancelEvent } from 'giu';import pick from 'lodash/pick';import sortBy from 'lodash/sortBy';import padEnd from 'lodash/padEnd';import padStart from 'lodash/padStart';import repeat from 'lodash/repeat';import chalk from 'chalk';import { ansiColors, treeLines, serialize, constants } from 'storyboard-core';import * as actions from '../actions/actions';import ColoredText from './030-coloredText';const doQuickFind = (msg0, quickFind) => { if (!quickFind.length) return msg0; const re = new RegExp(quickFind, 'gi'); return msg0.replace(re, chalk.bgYellow('$1'));};const mapStateToProps = (state) => ({ timeType: state.settings.timeType, fShowClosedActions: state.settings.fShowClosedActions, quickFind: state.stories.quickFind,});const mapDispatchToProps = { setTimeType: actions.setTimeType, onToggleExpanded: actions.toggleExpanded, onToggleHierarchical: actions.toggleHierarchical, onToggleAttachment: actions.toggleAttachment,};class Story extends React.Component { static propTypes = { story: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, timeRef: React.PropTypes.number, setTimeRef: React.PropTypes.func.isRequired, colors: React.PropTypes.object.isRequired, timeType: React.PropTypes.string.isRequired, fShowClosedActions: React.PropTypes.bool.isRequired, quickFind: React.PropTypes.string.isRequired, setTimeType: React.PropTypes.func.isRequired, onToggleExpanded: React.PropTypes.func.isRequired, onToggleHierarchical: React.PropTypes.func.isRequired, onToggleAttachment: React.PropTypes.func.isRequired, }; render() { if (this.props.story.fWrapper) return <div>{this.renderRecords()}</div>; if (this.props.level === 1) return this.renderRootStory(); return this.renderNormalStory(); } renderRootStory() { const { level, story, colors } = this.props; return ( <div className="rootStory" style={styleStory.outer(level, story, colors)}> <MainStoryTitle title={story.title} numRecords={story.numRecords} fHierarchical={story.fHierarchical} fExpanded={story.fExpanded} onToggleExpanded={this.toggleExpanded} onToggleHierarchical={this.toggleHierarchical} /> {this.renderRecords()} </div> ); } renderNormalStory() { const { level, story, colors } = this.props; return ( <div className="story" style={styleStory.outer(level, story, colors)}> <Line record={story} level={this.props.level} fDirectChild={false} timeType={this.props.timeType} timeRef={this.props.timeRef} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} quickFind={this.props.quickFind} onToggleExpanded={this.toggleExpanded} onToggleHierarchical={this.toggleHierarchical} seqFullRefresh={this.props.seqFullRefresh} colors={colors} /> {this.renderRecords()} </div> ); } renderRecords() { if (!this.props.story.fExpanded) return null; const records = this.prepareRecords(this.props.story.records); let out = []; for (let i = 0; i < records.length; i++) { const record = records[i]; const el = this.renderRecord(record); if (el == null) continue; out.push(el); if (record.objExpanded && record.obj != null) { out = out.concat(this.renderAttachment(record)); } if (record.repetitions) out.push(this.renderRepetitions(record)); } return out; } renderRecord(record) { const { id, fStoryObject, storyId, action } = record; const fDirectChild = storyId === this.props.story.storyId; if (fStoryObject) { return ( <Story key={storyId} story={record} level={this.props.level + 1} seqFullRefresh={this.props.seqFullRefresh} colors={this.props.colors} timeType={this.props.timeType} timeRef={this.props.timeRef} fShowClosedActions={this.props.fShowClosedActions} quickFind={this.props.quickFind} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} onToggleExpanded={this.props.onToggleExpanded} onToggleHierarchical={this.props.onToggleHierarchical} onToggleAttachment={this.props.onToggleAttachment} /> ); } if (fDirectChild) { if (action === 'CREATED') return null; if (!this.props.fShowClosedActions && action === 'CLOSED') return null; } return ( <Line key={`${storyId}_${id}`} record={record} level={this.props.level} fDirectChild={fDirectChild} timeType={this.props.timeType} timeRef={this.props.timeRef} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} quickFind={this.props.quickFind} onToggleAttachment={this.toggleAttachment} seqFullRefresh={this.props.seqFullRefresh} colors={this.props.colors} /> ); } renderAttachment(record) { const { storyId, id, obj, objOptions, version } = record; const props = pick(this.props, [ 'level', 'timeType', 'timeRef', 'setTimeType', 'setTimeRef', 'quickFind', 'seqFullRefresh', 'colors', ]); const lines = version >= 2 ? treeLines(serialize.deserialize(obj), objOptions) : obj; return lines.map((line, idx) => <AttachmentLine key={`${storyId}_${id}_${idx}`} record={record} {...props} msg={line} /> ); } renderRepetitions(record) { const { storyId, id } = record; const props = pick(this.props, [ 'level', 'timeType', 'timeRef', 'setTimeType', 'setTimeRef', 'quickFind', 'seqFullRefresh', 'colors', ]); return ( <RepetitionLine key={`${storyId}_${id}_repetitions`} record={record} {...props} /> ); } toggleExpanded = () => { this.props.onToggleExpanded(this.props.story.pathStr); } toggleHierarchical = () => { this.props.onToggleHierarchical(this.props.story.pathStr); } toggleAttachment = (recordId) => { this.props.onToggleAttachment(this.props.story.pathStr, recordId); } prepareRecords(records) { return this.props.story.fHierarchical ? sortBy(records, 't') : this.flatten(records); } flatten(records, level = 0) { let out = []; for (let i = 0; i < records.length; i++) { const record = records[i]; if (record.fStoryObject) { out = out.concat(this.flatten(record.records, level + 1)); } else { out.push(record); } } if (level === 0) out = sortBy(out, 't'); return out; }}const styleStory = { outer: (level, story, colors) => ({ backgroundColor: story.fServer ? colors.colorServerBg : colors.colorClientBg, color: story.fServer ? colors.colorServerFg : colors.colorClientFg, marginBottom: level <= 1 ? 10 : undefined, padding: level <= 1 ? 2 : undefined, }),};const connect = ReactRedux.connect(mapStateToProps, mapDispatchToProps);const ConnectedStory = connect(Story);class MainStoryTitle extends React.PureComponent { static propTypes = { title: React.PropTypes.string.isRequired, numRecords: React.PropTypes.number.isRequired, fHierarchical: React.PropTypes.bool.isRequired, fExpanded: React.PropTypes.bool.isRequired, onToggleExpanded: React.PropTypes.func.isRequired, onToggleHierarchical: React.PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { fHovered: false, }; } render() { return ( <div className="rootStoryTitle" style={styleMainTitle.outer} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} > {this.renderCaret()} <span style={styleMainTitle.title} onClick={this.props.onToggleExpanded} > {this.props.title.toUpperCase()}{' '} <span style={styleMainTitle.numRecords}>[{this.props.numRecords}]</span> </span> {this.renderToggleHierarchical()} </div> ); } renderCaret() { if (!this.state.fHovered) return null; const icon = this.props.fExpanded ? 'caret-down' : 'caret-right'; return ( <span onClick={this.props.onToggleExpanded} style={styleMainTitle.caret.outer}> <Icon icon={icon} style={styleMainTitle.caret.icon} /> </span> ); } renderToggleHierarchical() { if (!this.state.fHovered) return null; return ( <HierarchicalToggle fHierarchical={this.props.fHierarchical} onToggleHierarchical={this.props.onToggleHierarchical} fFloat /> ); } onMouseEnter = () => { this.setState({ fHovered: true }); } onMouseLeave = () => { this.setState({ fHovered: false }); }}const styleMainTitle = { outer: { textAlign: 'center', marginBottom: 5, cursor: 'pointer', }, title: { fontWeight: 900, letterSpacing: 3, }, numRecords: { color: 'darkgrey' }, caret: { outer: { display: 'inline-block', position: 'absolute', }, icon: { display: 'inline-block', position: 'absolute', right: 6, top: 2, }, },};class AttachmentLine extends React.PureComponent { static propTypes = { record: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, msg: React.PropTypes.string.isRequired, quickFind: React.PropTypes.string.isRequired, colors: React.PropTypes.object.isRequired, }; render() { const { record, colors } = this.props; const style = styleLine.log(record, colors); const msg = doQuickFind(this.props.msg, this.props.quickFind); return ( <div className="attachmentLine allowUserSelect" style={style}> <Time fShowFull={false} timeType={this.props.timeType} timeRef={this.props.timeRef} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} seqFullRefresh={this.props.seqFullRefresh} /> <Src src={record.src} /> <Severity level={record.objLevel} /> <Indent level={this.props.level} /> <CaretOrSpace /> <ColoredText text={` ${msg}`} /> </div> ); }}class RepetitionLine extends React.PureComponent { static propTypes = { record: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, quickFind: React.PropTypes.string.isRequired, colors: React.PropTypes.object.isRequired, }; render() { const { record, level, timeType, timeRef, setTimeType, setTimeRef, seqFullRefresh, colors, } = this.props; const style = styleLine.log(record, colors); let msg = ` x${record.repetitions + 1}, latest: `; msg = doQuickFind(msg, this.props.quickFind); return ( <div className="attachmentLine allowUserSelect" style={style}> <Time fShowFull={false} timeType={timeType} timeRef={timeRef} setTimeType={setTimeType} setTimeRef={setTimeRef} seqFullRefresh={seqFullRefresh} /> <Src /> <Severity /> <Indent level={level} /> <CaretOrSpace /> <Icon icon="copy" disabled style={{ color: 'currentColor' }} /> <ColoredText text={msg} /> <Time t={record.tLastRepetition} fTrim timeType={timeType} timeRef={timeRef} setTimeType={setTimeType} setTimeRef={setTimeRef} seqFullRefresh={seqFullRefresh} /> </div> ); }}class Line extends React.PureComponent { static propTypes = { record: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, fDirectChild: React.PropTypes.bool.isRequired, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, quickFind: React.PropTypes.string.isRequired, onToggleExpanded: React.PropTypes.func, onToggleHierarchical: React.PropTypes.func, onToggleAttachment: React.PropTypes.func, seqFullRefresh: React.PropTypes.number.isRequired, colors: React.PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { fHovered: false, }; } render() { const { record, fDirectChild, level, colors } = this.props; const { fStory, fStoryObject, fServer, fOpen, title, action } = record; let { msg } = record; if (fStoryObject) msg = title; if (fStory) { msg = !fDirectChild ? `${title} ` : ''; if (action) msg += chalk.gray(`[${action}]`); } const style = fStoryObject ? styleLine.titleRow : styleLine.log(record, colors); const indentLevel = fStoryObject ? level - 1 : level; let className = fStoryObject ? 'storyTitle' : 'log'; className += ' allowUserSelect'; const fDarkBg = fServer ? colors.colorServerBgIsDark : colors.colorClientBgIsDark; if (!fDarkBg) className += ' fadeIn'; return ( <div className={className} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} style={style} > {this.renderTime(record)} <Src src={record.src} colors={colors} /> <Severity level={record.level} colors={colors} /> <Indent level={indentLevel} /> {this.renderCaretOrSpace(record)} {this.renderMsg(fStoryObject, msg, record.level)} {this.renderWarningIcon(record)} {fStoryObject && this.renderToggleHierarchical(record)} {fStoryObject && fOpen && <Spinner style={styleLine.spinner} />} {this.renderAttachmentIcon(record)} </div> ); } renderMsg(fStoryObject, msg0, level) { let msg = doQuickFind(msg0, this.props.quickFind); if (level >= constants.LEVEL_STR_TO_NUM.ERROR) { msg = chalk.red.bold(msg); } else if (level >= constants.LEVEL_STR_TO_NUM.WARN) { msg = chalk.red.yellow(msg); } if (!fStoryObject) return <ColoredText text={msg} />; return ( <ColoredText text={msg} onClick={this.props.onToggleExpanded} style={styleLine.title} /> ); } renderTime(record) { const { fStoryObject, t } = record; const { level, timeType, timeRef, setTimeType, setTimeRef, seqFullRefresh } = this.props; const fShowFull = (fStoryObject && level <= 2) || (level <= 1); return ( <Time t={t} fShowFull={fShowFull} timeType={timeType} timeRef={timeRef} setTimeType={setTimeType} setTimeRef={setTimeRef} seqFullRefresh={seqFullRefresh} /> ); } renderCaretOrSpace(record) { let fExpanded; if (this.props.onToggleExpanded && record.fStoryObject) { fExpanded = record.fExpanded; } return ( <CaretOrSpace fExpanded={fExpanded} onToggleExpanded={this.props.onToggleExpanded} /> ); } renderToggleHierarchical(story) { if (!this.props.onToggleHierarchical) return null; if (!this.state.fHovered) return null; return ( <HierarchicalToggle fHierarchical={story.fHierarchical} onToggleHierarchical={this.props.onToggleHierarchical} /> ); } renderWarningIcon(record) { if (record.fExpanded) return null; const { fHasWarning, fHasError } = record; if (!(fHasWarning || fHasError)) return null; const title = `Story contains ${fHasError ? 'an error' : 'a warning'}`; return ( <Icon icon="warning" title={title} onClick={this.props.onToggleExpanded} style={styleLine.warningIcon(fHasError ? 'error' : 'warning')} /> ); } renderAttachmentIcon(record) { if (record.obj == null) return null; let icon; let style; if (record.objIsError) { icon = record.objExpanded ? 'folder-open' : 'folder'; style = timmSet(styleLine.attachmentIcon, 'color', '#cc0000'); } else { icon = record.objExpanded ? 'folder-open-o' : 'folder-o'; style = styleLine.attachmentIcon; } return ( <Icon icon={icon} onClick={this.onClickAttachment} style={style} /> ); } onMouseEnter = () => { this.setState({ fHovered: true }); } onMouseLeave = () => { this.setState({ fHovered: false }); } onClickAttachment = () => { this.props.onToggleAttachment(this.props.record.id); }}const styleLine = { titleRow: { fontWeight: 900, fontFamily: 'Menlo, Consolas, monospace', whiteSpace: 'pre', overflowX: 'hidden', textOverflow: 'ellipsis', }, title: { cursor: 'pointer' }, log: (record, colors) => { const fServer = record.fServer; return { backgroundColor: fServer ? colors.colorServerBg : colors.colorClientBg, color: fServer ? colors.colorServerFg : colors.colorClientFg, fontFamily: 'Menlo, Consolas, monospace', whiteSpace: 'pre', fontWeight: record.fStory && record.action === 'CREATED' ? 900 : undefined, overflowX: 'hidden', textOverflow: 'ellipsis', }; }, spinner: { marginLeft: 8, overflow: 'hidden', }, attachmentIcon: { marginLeft: 8, cursor: 'pointer', display: 'inline', }, warningIcon: (type) => ({ marginLeft: 8, color: type === 'warning' ? '#ff6600' : '#cc0000', display: 'inline', }),};const TIME_LENGTH = 25;class Time extends React.PureComponent { static propTypes = { t: React.PropTypes.number, fShowFull: React.PropTypes.bool, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, fTrim: React.PropTypes.bool, }; render() { const { t, fShowFull, timeType, timeRef, fTrim } = this.props; if (t == null) return <span>{padEnd('', TIME_LENGTH)}</span>; let fTimeInWords = false; let fRefTimestamp = false; const localTime = dateFormat(t, 'YYYY-MM-DD HH:mm:ss.SSS'); let shownTime; if (timeRef == null) { if (timeType === 'RELATIVE') { shownTime = dateDistanceInWords(new Date(), t, { addSuffix: true }); fTimeInWords = true; } else { shownTime = timeType === 'UTC' ? new Date(t).toISOString().replace(/T/g, ' ') : localTime; shownTime = fShowFull ? shownTime : ` ${shownTime.slice(11)}`; } } else if (t === timeRef) { shownTime = timeType === 'UTC' ? new Date(t).toISOString().replace(/T/g, ' ') : localTime; fRefTimestamp = true; } else if (timeType === 'RELATIVE') { shownTime = dateDistanceInWords(timeRef, t, { partialMethod: 'round' }); shownTime += timeRef > t ? ' before' : ' later'; fTimeInWords = true; } else { const delta = Math.abs(t - timeRef); shownTime = new Date(delta).toISOString().replace(/T/g, ' ').slice(0, 23); if (shownTime.slice(0, 4) === '1970') shownTime = shownTime.slice(5); if (shownTime.slice(0, 2) === '01') shownTime = shownTime.slice(3); if (shownTime.slice(0, 2) === '01') shownTime = shownTime.slice(3); if (shownTime.slice(0, 2) === '00') shownTime = shownTime.slice(3); shownTime = `${timeRef > t ? '-' : '+'}${shownTime}`; shownTime = padStart(shownTime, 23); } shownTime = padEnd(shownTime, TIME_LENGTH); if (shownTime.length > TIME_LENGTH) { shownTime = `${shownTime.slice(0, TIME_LENGTH - 1)}…`; } if (fTrim) shownTime = shownTime.trim(); return ( <span onClick={this.onClick} onContextMenu={this.onClick} style={styleTime(fTimeInWords, fRefTimestamp)} title={shownTime.trim() !== localTime ? localTime : undefined} > {shownTime} </span> ); } onClick = (ev) => { const fSetTimeRef = ev.type === 'contextmenu' || ev.ctrlKey; if (fSetTimeRef) cancelEvent(ev); const { t, timeType: prevTimeType, timeRef: prevTimeRef } = this.props; if (fSetTimeRef) { const nextTimeRef = t !== prevTimeRef ? t : null; this.props.setTimeRef(nextTimeRef); } else { let nextTimeType; if (prevTimeType === 'LOCAL') nextTimeType = 'RELATIVE'; else if (prevTimeType === 'RELATIVE') nextTimeType = 'UTC'; else nextTimeType = 'LOCAL'; this.props.setTimeType(nextTimeType); } }}const styleTime = (fTimeInWords, fRefTimestamp) => ({ display: 'inline', cursor: 'pointer', fontStyle: fTimeInWords ? 'italic' : undefined, fontWeight: fRefTimestamp ? 'bold' : undefined, backgroundColor: fRefTimestamp ? '#d1bd0c' : undefined,});class Severity extends React.PureComponent { static propTypes = { level: React.PropTypes.number, }; render() { const { level } = this.props; return level != null ? <ColoredText text={ansiColors.LEVEL_NUM_TO_COLORED_STR[level]} /> : <span> </span>; }}class Src extends React.PureComponent { static propTypes = { src: React.PropTypes.string, }; render() { const { src } = this.props; if (src != null) { const srcStr = ansiColors.getSrcChalkColor(src)(padStart(`${src} `, 20)); return <ColoredText text={srcStr} />; } return <span>{repeat(' ', 20)}</span>; }}const Indent = ({ level }) => { const style = { display: 'inline-block', width: 20 * (level - 1), }; return <div style={style} />;};class CaretOrSpace extends React.PureComponent { static propTypes = { fExpanded: React.PropTypes.bool, onToggleExpanded: React.PropTypes.func, }; render() { let icon; if (this.props.fExpanded != null) { const iconType = this.props.fExpanded ? 'caret-down' : 'caret-right'; icon = <Icon icon={iconType} onClick={this.props.onToggleExpanded} />; } return <span style={styleCaretOrSpace}>{icon}</span>; }}const styleCaretOrSpace = { display: 'inline-block', width: 30, paddingLeft: 10, cursor: 'pointer',};class HierarchicalToggle extends React.PureComponent { static propTypes = { fHierarchical: React.PropTypes.bool.isRequired, onToggleHierarchical: React.PropTypes.func.isRequired, fFloat: React.PropTypes.bool, }; render() { const icon = this.props.fHierarchical ? 'bars' : 'sitemap'; const text = this.props.fHierarchical ? 'Show flat' : 'Show tree'; return ( <span onClick={this.props.onToggleHierarchical} style={styleHierarchical.outer(this.props.fFloat)} > <Icon icon={icon} style={styleHierarchical.icon} /> {text} </span> ); }}const styleHierarchical = { outer: (fFloat) => ({ position: fFloat ? 'absolute' : undefined, marginLeft: 10, color: 'darkgrey', textDecoration: 'underline', cursor: 'pointer', fontWeight: 'normal', fontFamily: 'Menlo, Consolas, monospace', }), icon: { marginRight: 4 },};export default ConnectedStory;export { Story as _Story };
describe('Story', () => { it('01 renders correctly an empty main story', () => { const el = renderMainStory(); const tree = renderer.create(el).toJSON(); expect(tree).toMatchSnapshot(); }); });
Story 01 renders correctly an empty main story
import React from 'react';import * as ReactRedux from 'react-redux';import { set as timmSet } from 'timm';import dateFormat from 'date-fns/format';import dateDistanceInWords from 'date-fns/distance_in_words_strict';import { Icon, Spinner, cancelEvent } from 'giu';import pick from 'lodash/pick';import sortBy from 'lodash/sortBy';import padEnd from 'lodash/padEnd';import padStart from 'lodash/padStart';import repeat from 'lodash/repeat';import chalk from 'chalk';import { ansiColors, treeLines, serialize, constants } from 'storyboard-core';import * as actions from '../actions/actions';import ColoredText from './030-coloredText';const doQuickFind = (msg0, quickFind) => { if (!quickFind.length) return msg0; const re = new RegExp(quickFind, 'gi'); return msg0.replace(re, chalk.bgYellow('$1'));};const mapStateToProps = (state) => ({ timeType: state.settings.timeType, fShowClosedActions: state.settings.fShowClosedActions, quickFind: state.stories.quickFind,});const mapDispatchToProps = { setTimeType: actions.setTimeType, onToggleExpanded: actions.toggleExpanded, onToggleHierarchical: actions.toggleHierarchical, onToggleAttachment: actions.toggleAttachment,};class Story extends React.Component { static propTypes = { story: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, timeRef: React.PropTypes.number, setTimeRef: React.PropTypes.func.isRequired, colors: React.PropTypes.object.isRequired, timeType: React.PropTypes.string.isRequired, fShowClosedActions: React.PropTypes.bool.isRequired, quickFind: React.PropTypes.string.isRequired, setTimeType: React.PropTypes.func.isRequired, onToggleExpanded: React.PropTypes.func.isRequired, onToggleHierarchical: React.PropTypes.func.isRequired, onToggleAttachment: React.PropTypes.func.isRequired, }; render() { if (this.props.story.fWrapper) return <div>{this.renderRecords()}</div>; if (this.props.level === 1) return this.renderRootStory(); return this.renderNormalStory(); } renderRootStory() { const { level, story, colors } = this.props; return ( <div className="rootStory" style={styleStory.outer(level, story, colors)}> <MainStoryTitle title={story.title} numRecords={story.numRecords} fHierarchical={story.fHierarchical} fExpanded={story.fExpanded} onToggleExpanded={this.toggleExpanded} onToggleHierarchical={this.toggleHierarchical} /> {this.renderRecords()} </div> ); } renderNormalStory() { const { level, story, colors } = this.props; return ( <div className="story" style={styleStory.outer(level, story, colors)}> <Line record={story} level={this.props.level} fDirectChild={false} timeType={this.props.timeType} timeRef={this.props.timeRef} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} quickFind={this.props.quickFind} onToggleExpanded={this.toggleExpanded} onToggleHierarchical={this.toggleHierarchical} seqFullRefresh={this.props.seqFullRefresh} colors={colors} /> {this.renderRecords()} </div> ); } renderRecords() { if (!this.props.story.fExpanded) return null; const records = this.prepareRecords(this.props.story.records); let out = []; for (let i = 0; i < records.length; i++) { const record = records[i]; const el = this.renderRecord(record); if (el == null) continue; out.push(el); if (record.objExpanded && record.obj != null) { out = out.concat(this.renderAttachment(record)); } if (record.repetitions) out.push(this.renderRepetitions(record)); } return out; } renderRecord(record) { const { id, fStoryObject, storyId, action } = record; const fDirectChild = storyId === this.props.story.storyId; if (fStoryObject) { return ( <Story key={storyId} story={record} level={this.props.level + 1} seqFullRefresh={this.props.seqFullRefresh} colors={this.props.colors} timeType={this.props.timeType} timeRef={this.props.timeRef} fShowClosedActions={this.props.fShowClosedActions} quickFind={this.props.quickFind} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} onToggleExpanded={this.props.onToggleExpanded} onToggleHierarchical={this.props.onToggleHierarchical} onToggleAttachment={this.props.onToggleAttachment} /> ); } if (fDirectChild) { if (action === 'CREATED') return null; if (!this.props.fShowClosedActions && action === 'CLOSED') return null; } return ( <Line key={`${storyId}_${id}`} record={record} level={this.props.level} fDirectChild={fDirectChild} timeType={this.props.timeType} timeRef={this.props.timeRef} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} quickFind={this.props.quickFind} onToggleAttachment={this.toggleAttachment} seqFullRefresh={this.props.seqFullRefresh} colors={this.props.colors} /> ); } renderAttachment(record) { const { storyId, id, obj, objOptions, version } = record; const props = pick(this.props, [ 'level', 'timeType', 'timeRef', 'setTimeType', 'setTimeRef', 'quickFind', 'seqFullRefresh', 'colors', ]); const lines = version >= 2 ? treeLines(serialize.deserialize(obj), objOptions) : obj; return lines.map((line, idx) => <AttachmentLine key={`${storyId}_${id}_${idx}`} record={record} {...props} msg={line} /> ); } renderRepetitions(record) { const { storyId, id } = record; const props = pick(this.props, [ 'level', 'timeType', 'timeRef', 'setTimeType', 'setTimeRef', 'quickFind', 'seqFullRefresh', 'colors', ]); return ( <RepetitionLine key={`${storyId}_${id}_repetitions`} record={record} {...props} /> ); } toggleExpanded = () => { this.props.onToggleExpanded(this.props.story.pathStr); } toggleHierarchical = () => { this.props.onToggleHierarchical(this.props.story.pathStr); } toggleAttachment = (recordId) => { this.props.onToggleAttachment(this.props.story.pathStr, recordId); } prepareRecords(records) { return this.props.story.fHierarchical ? sortBy(records, 't') : this.flatten(records); } flatten(records, level = 0) { let out = []; for (let i = 0; i < records.length; i++) { const record = records[i]; if (record.fStoryObject) { out = out.concat(this.flatten(record.records, level + 1)); } else { out.push(record); } } if (level === 0) out = sortBy(out, 't'); return out; }}const styleStory = { outer: (level, story, colors) => ({ backgroundColor: story.fServer ? colors.colorServerBg : colors.colorClientBg, color: story.fServer ? colors.colorServerFg : colors.colorClientFg, marginBottom: level <= 1 ? 10 : undefined, padding: level <= 1 ? 2 : undefined, }),};const connect = ReactRedux.connect(mapStateToProps, mapDispatchToProps);const ConnectedStory = connect(Story);class MainStoryTitle extends React.PureComponent { static propTypes = { title: React.PropTypes.string.isRequired, numRecords: React.PropTypes.number.isRequired, fHierarchical: React.PropTypes.bool.isRequired, fExpanded: React.PropTypes.bool.isRequired, onToggleExpanded: React.PropTypes.func.isRequired, onToggleHierarchical: React.PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { fHovered: false, }; } render() { return ( <div className="rootStoryTitle" style={styleMainTitle.outer} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} > {this.renderCaret()} <span style={styleMainTitle.title} onClick={this.props.onToggleExpanded} > {this.props.title.toUpperCase()}{' '} <span style={styleMainTitle.numRecords}>[{this.props.numRecords}]</span> </span> {this.renderToggleHierarchical()} </div> ); } renderCaret() { if (!this.state.fHovered) return null; const icon = this.props.fExpanded ? 'caret-down' : 'caret-right'; return ( <span onClick={this.props.onToggleExpanded} style={styleMainTitle.caret.outer}> <Icon icon={icon} style={styleMainTitle.caret.icon} /> </span> ); } renderToggleHierarchical() { if (!this.state.fHovered) return null; return ( <HierarchicalToggle fHierarchical={this.props.fHierarchical} onToggleHierarchical={this.props.onToggleHierarchical} fFloat /> ); } onMouseEnter = () => { this.setState({ fHovered: true }); } onMouseLeave = () => { this.setState({ fHovered: false }); }}const styleMainTitle = { outer: { textAlign: 'center', marginBottom: 5, cursor: 'pointer', }, title: { fontWeight: 900, letterSpacing: 3, }, numRecords: { color: 'darkgrey' }, caret: { outer: { display: 'inline-block', position: 'absolute', }, icon: { display: 'inline-block', position: 'absolute', right: 6, top: 2, }, },};class AttachmentLine extends React.PureComponent { static propTypes = { record: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, msg: React.PropTypes.string.isRequired, quickFind: React.PropTypes.string.isRequired, colors: React.PropTypes.object.isRequired, }; render() { const { record, colors } = this.props; const style = styleLine.log(record, colors); const msg = doQuickFind(this.props.msg, this.props.quickFind); return ( <div className="attachmentLine allowUserSelect" style={style}> <Time fShowFull={false} timeType={this.props.timeType} timeRef={this.props.timeRef} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} seqFullRefresh={this.props.seqFullRefresh} /> <Src src={record.src} /> <Severity level={record.objLevel} /> <Indent level={this.props.level} /> <CaretOrSpace /> <ColoredText text={` ${msg}`} /> </div> ); }}class RepetitionLine extends React.PureComponent { static propTypes = { record: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, quickFind: React.PropTypes.string.isRequired, colors: React.PropTypes.object.isRequired, }; render() { const { record, level, timeType, timeRef, setTimeType, setTimeRef, seqFullRefresh, colors, } = this.props; const style = styleLine.log(record, colors); let msg = ` x${record.repetitions + 1}, latest: `; msg = doQuickFind(msg, this.props.quickFind); return ( <div className="attachmentLine allowUserSelect" style={style}> <Time fShowFull={false} timeType={timeType} timeRef={timeRef} setTimeType={setTimeType} setTimeRef={setTimeRef} seqFullRefresh={seqFullRefresh} /> <Src /> <Severity /> <Indent level={level} /> <CaretOrSpace /> <Icon icon="copy" disabled style={{ color: 'currentColor' }} /> <ColoredText text={msg} /> <Time t={record.tLastRepetition} fTrim timeType={timeType} timeRef={timeRef} setTimeType={setTimeType} setTimeRef={setTimeRef} seqFullRefresh={seqFullRefresh} /> </div> ); }}class Line extends React.PureComponent { static propTypes = { record: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, fDirectChild: React.PropTypes.bool.isRequired, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, quickFind: React.PropTypes.string.isRequired, onToggleExpanded: React.PropTypes.func, onToggleHierarchical: React.PropTypes.func, onToggleAttachment: React.PropTypes.func, seqFullRefresh: React.PropTypes.number.isRequired, colors: React.PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { fHovered: false, }; } render() { const { record, fDirectChild, level, colors } = this.props; const { fStory, fStoryObject, fServer, fOpen, title, action } = record; let { msg } = record; if (fStoryObject) msg = title; if (fStory) { msg = !fDirectChild ? `${title} ` : ''; if (action) msg += chalk.gray(`[${action}]`); } const style = fStoryObject ? styleLine.titleRow : styleLine.log(record, colors); const indentLevel = fStoryObject ? level - 1 : level; let className = fStoryObject ? 'storyTitle' : 'log'; className += ' allowUserSelect'; const fDarkBg = fServer ? colors.colorServerBgIsDark : colors.colorClientBgIsDark; if (!fDarkBg) className += ' fadeIn'; return ( <div className={className} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} style={style} > {this.renderTime(record)} <Src src={record.src} colors={colors} /> <Severity level={record.level} colors={colors} /> <Indent level={indentLevel} /> {this.renderCaretOrSpace(record)} {this.renderMsg(fStoryObject, msg, record.level)} {this.renderWarningIcon(record)} {fStoryObject && this.renderToggleHierarchical(record)} {fStoryObject && fOpen && <Spinner style={styleLine.spinner} />} {this.renderAttachmentIcon(record)} </div> ); } renderMsg(fStoryObject, msg0, level) { let msg = doQuickFind(msg0, this.props.quickFind); if (level >= constants.LEVEL_STR_TO_NUM.ERROR) { msg = chalk.red.bold(msg); } else if (level >= constants.LEVEL_STR_TO_NUM.WARN) { msg = chalk.red.yellow(msg); } if (!fStoryObject) return <ColoredText text={msg} />; return ( <ColoredText text={msg} onClick={this.props.onToggleExpanded} style={styleLine.title} /> ); } renderTime(record) { const { fStoryObject, t } = record; const { level, timeType, timeRef, setTimeType, setTimeRef, seqFullRefresh } = this.props; const fShowFull = (fStoryObject && level <= 2) || (level <= 1); return ( <Time t={t} fShowFull={fShowFull} timeType={timeType} timeRef={timeRef} setTimeType={setTimeType} setTimeRef={setTimeRef} seqFullRefresh={seqFullRefresh} /> ); } renderCaretOrSpace(record) { let fExpanded; if (this.props.onToggleExpanded && record.fStoryObject) { fExpanded = record.fExpanded; } return ( <CaretOrSpace fExpanded={fExpanded} onToggleExpanded={this.props.onToggleExpanded} /> ); } renderToggleHierarchical(story) { if (!this.props.onToggleHierarchical) return null; if (!this.state.fHovered) return null; return ( <HierarchicalToggle fHierarchical={story.fHierarchical} onToggleHierarchical={this.props.onToggleHierarchical} /> ); } renderWarningIcon(record) { if (record.fExpanded) return null; const { fHasWarning, fHasError } = record; if (!(fHasWarning || fHasError)) return null; const title = `Story contains ${fHasError ? 'an error' : 'a warning'}`; return ( <Icon icon="warning" title={title} onClick={this.props.onToggleExpanded} style={styleLine.warningIcon(fHasError ? 'error' : 'warning')} /> ); } renderAttachmentIcon(record) { if (record.obj == null) return null; let icon; let style; if (record.objIsError) { icon = record.objExpanded ? 'folder-open' : 'folder'; style = timmSet(styleLine.attachmentIcon, 'color', '#cc0000'); } else { icon = record.objExpanded ? 'folder-open-o' : 'folder-o'; style = styleLine.attachmentIcon; } return ( <Icon icon={icon} onClick={this.onClickAttachment} style={style} /> ); } onMouseEnter = () => { this.setState({ fHovered: true }); } onMouseLeave = () => { this.setState({ fHovered: false }); } onClickAttachment = () => { this.props.onToggleAttachment(this.props.record.id); }}const styleLine = { titleRow: { fontWeight: 900, fontFamily: 'Menlo, Consolas, monospace', whiteSpace: 'pre', overflowX: 'hidden', textOverflow: 'ellipsis', }, title: { cursor: 'pointer' }, log: (record, colors) => { const fServer = record.fServer; return { backgroundColor: fServer ? colors.colorServerBg : colors.colorClientBg, color: fServer ? colors.colorServerFg : colors.colorClientFg, fontFamily: 'Menlo, Consolas, monospace', whiteSpace: 'pre', fontWeight: record.fStory && record.action === 'CREATED' ? 900 : undefined, overflowX: 'hidden', textOverflow: 'ellipsis', }; }, spinner: { marginLeft: 8, overflow: 'hidden', }, attachmentIcon: { marginLeft: 8, cursor: 'pointer', display: 'inline', }, warningIcon: (type) => ({ marginLeft: 8, color: type === 'warning' ? '#ff6600' : '#cc0000', display: 'inline', }),};const TIME_LENGTH = 25;class Time extends React.PureComponent { static propTypes = { t: React.PropTypes.number, fShowFull: React.PropTypes.bool, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, fTrim: React.PropTypes.bool, }; render() { const { t, fShowFull, timeType, timeRef, fTrim } = this.props; if (t == null) return <span>{padEnd('', TIME_LENGTH)}</span>; let fTimeInWords = false; let fRefTimestamp = false; const localTime = dateFormat(t, 'YYYY-MM-DD HH:mm:ss.SSS'); let shownTime; if (timeRef == null) { if (timeType === 'RELATIVE') { shownTime = dateDistanceInWords(new Date(), t, { addSuffix: true }); fTimeInWords = true; } else { shownTime = timeType === 'UTC' ? new Date(t).toISOString().replace(/T/g, ' ') : localTime; shownTime = fShowFull ? shownTime : ` ${shownTime.slice(11)}`; } } else if (t === timeRef) { shownTime = timeType === 'UTC' ? new Date(t).toISOString().replace(/T/g, ' ') : localTime; fRefTimestamp = true; } else if (timeType === 'RELATIVE') { shownTime = dateDistanceInWords(timeRef, t, { partialMethod: 'round' }); shownTime += timeRef > t ? ' before' : ' later'; fTimeInWords = true; } else { const delta = Math.abs(t - timeRef); shownTime = new Date(delta).toISOString().replace(/T/g, ' ').slice(0, 23); if (shownTime.slice(0, 4) === '1970') shownTime = shownTime.slice(5); if (shownTime.slice(0, 2) === '01') shownTime = shownTime.slice(3); if (shownTime.slice(0, 2) === '01') shownTime = shownTime.slice(3); if (shownTime.slice(0, 2) === '00') shownTime = shownTime.slice(3); shownTime = `${timeRef > t ? '-' : '+'}${shownTime}`; shownTime = padStart(shownTime, 23); } shownTime = padEnd(shownTime, TIME_LENGTH); if (shownTime.length > TIME_LENGTH) { shownTime = `${shownTime.slice(0, TIME_LENGTH - 1)}…`; } if (fTrim) shownTime = shownTime.trim(); return ( <span onClick={this.onClick} onContextMenu={this.onClick} style={styleTime(fTimeInWords, fRefTimestamp)} title={shownTime.trim() !== localTime ? localTime : undefined} > {shownTime} </span> ); } onClick = (ev) => { const fSetTimeRef = ev.type === 'contextmenu' || ev.ctrlKey; if (fSetTimeRef) cancelEvent(ev); const { t, timeType: prevTimeType, timeRef: prevTimeRef } = this.props; if (fSetTimeRef) { const nextTimeRef = t !== prevTimeRef ? t : null; this.props.setTimeRef(nextTimeRef); } else { let nextTimeType; if (prevTimeType === 'LOCAL') nextTimeType = 'RELATIVE'; else if (prevTimeType === 'RELATIVE') nextTimeType = 'UTC'; else nextTimeType = 'LOCAL'; this.props.setTimeType(nextTimeType); } }}const styleTime = (fTimeInWords, fRefTimestamp) => ({ display: 'inline', cursor: 'pointer', fontStyle: fTimeInWords ? 'italic' : undefined, fontWeight: fRefTimestamp ? 'bold' : undefined, backgroundColor: fRefTimestamp ? '#d1bd0c' : undefined,});class Severity extends React.PureComponent { static propTypes = { level: React.PropTypes.number, }; render() { const { level } = this.props; return level != null ? <ColoredText text={ansiColors.LEVEL_NUM_TO_COLORED_STR[level]} /> : <span> </span>; }}class Src extends React.PureComponent { static propTypes = { src: React.PropTypes.string, }; render() { const { src } = this.props; if (src != null) { const srcStr = ansiColors.getSrcChalkColor(src)(padStart(`${src} `, 20)); return <ColoredText text={srcStr} />; } return <span>{repeat(' ', 20)}</span>; }}const Indent = ({ level }) => { const style = { display: 'inline-block', width: 20 * (level - 1), }; return <div style={style} />;};class CaretOrSpace extends React.PureComponent { static propTypes = { fExpanded: React.PropTypes.bool, onToggleExpanded: React.PropTypes.func, }; render() { let icon; if (this.props.fExpanded != null) { const iconType = this.props.fExpanded ? 'caret-down' : 'caret-right'; icon = <Icon icon={iconType} onClick={this.props.onToggleExpanded} />; } return <span style={styleCaretOrSpace}>{icon}</span>; }}const styleCaretOrSpace = { display: 'inline-block', width: 30, paddingLeft: 10, cursor: 'pointer',};class HierarchicalToggle extends React.PureComponent { static propTypes = { fHierarchical: React.PropTypes.bool.isRequired, onToggleHierarchical: React.PropTypes.func.isRequired, fFloat: React.PropTypes.bool, }; render() { const icon = this.props.fHierarchical ? 'bars' : 'sitemap'; const text = this.props.fHierarchical ? 'Show flat' : 'Show tree'; return ( <span onClick={this.props.onToggleHierarchical} style={styleHierarchical.outer(this.props.fFloat)} > <Icon icon={icon} style={styleHierarchical.icon} /> {text} </span> ); }}const styleHierarchical = { outer: (fFloat) => ({ position: fFloat ? 'absolute' : undefined, marginLeft: 10, color: 'darkgrey', textDecoration: 'underline', cursor: 'pointer', fontWeight: 'normal', fontFamily: 'Menlo, Consolas, monospace', }), icon: { marginRight: 4 },};export default ConnectedStory;export { Story as _Story };
describe('Story', () => { it('01-b renders correctly the record counter', () => { let mainStory = EMPTY_MAIN_STORY; mainStory = setIn(mainStory, ['records', 0, 'numRecords'], 34); mainStory = setIn(mainStory, ['records', 1, 'numRecords'], 23); const el = renderMainStory({ story: mainStory }); expect(renderer.create(el).toJSON()).toMatchSnapshot(); }); });
Story 01-b renders correctly the record counter
import React from 'react';import * as ReactRedux from 'react-redux';import { set as timmSet } from 'timm';import dateFormat from 'date-fns/format';import dateDistanceInWords from 'date-fns/distance_in_words_strict';import { Icon, Spinner, cancelEvent } from 'giu';import pick from 'lodash/pick';import sortBy from 'lodash/sortBy';import padEnd from 'lodash/padEnd';import padStart from 'lodash/padStart';import repeat from 'lodash/repeat';import chalk from 'chalk';import { ansiColors, treeLines, serialize, constants } from 'storyboard-core';import * as actions from '../actions/actions';import ColoredText from './030-coloredText';const doQuickFind = (msg0, quickFind) => { if (!quickFind.length) return msg0; const re = new RegExp(quickFind, 'gi'); return msg0.replace(re, chalk.bgYellow('$1'));};const mapStateToProps = (state) => ({ timeType: state.settings.timeType, fShowClosedActions: state.settings.fShowClosedActions, quickFind: state.stories.quickFind,});const mapDispatchToProps = { setTimeType: actions.setTimeType, onToggleExpanded: actions.toggleExpanded, onToggleHierarchical: actions.toggleHierarchical, onToggleAttachment: actions.toggleAttachment,};class Story extends React.Component { static propTypes = { story: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, timeRef: React.PropTypes.number, setTimeRef: React.PropTypes.func.isRequired, colors: React.PropTypes.object.isRequired, timeType: React.PropTypes.string.isRequired, fShowClosedActions: React.PropTypes.bool.isRequired, quickFind: React.PropTypes.string.isRequired, setTimeType: React.PropTypes.func.isRequired, onToggleExpanded: React.PropTypes.func.isRequired, onToggleHierarchical: React.PropTypes.func.isRequired, onToggleAttachment: React.PropTypes.func.isRequired, }; render() { if (this.props.story.fWrapper) return <div>{this.renderRecords()}</div>; if (this.props.level === 1) return this.renderRootStory(); return this.renderNormalStory(); } renderRootStory() { const { level, story, colors } = this.props; return ( <div className="rootStory" style={styleStory.outer(level, story, colors)}> <MainStoryTitle title={story.title} numRecords={story.numRecords} fHierarchical={story.fHierarchical} fExpanded={story.fExpanded} onToggleExpanded={this.toggleExpanded} onToggleHierarchical={this.toggleHierarchical} /> {this.renderRecords()} </div> ); } renderNormalStory() { const { level, story, colors } = this.props; return ( <div className="story" style={styleStory.outer(level, story, colors)}> <Line record={story} level={this.props.level} fDirectChild={false} timeType={this.props.timeType} timeRef={this.props.timeRef} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} quickFind={this.props.quickFind} onToggleExpanded={this.toggleExpanded} onToggleHierarchical={this.toggleHierarchical} seqFullRefresh={this.props.seqFullRefresh} colors={colors} /> {this.renderRecords()} </div> ); } renderRecords() { if (!this.props.story.fExpanded) return null; const records = this.prepareRecords(this.props.story.records); let out = []; for (let i = 0; i < records.length; i++) { const record = records[i]; const el = this.renderRecord(record); if (el == null) continue; out.push(el); if (record.objExpanded && record.obj != null) { out = out.concat(this.renderAttachment(record)); } if (record.repetitions) out.push(this.renderRepetitions(record)); } return out; } renderRecord(record) { const { id, fStoryObject, storyId, action } = record; const fDirectChild = storyId === this.props.story.storyId; if (fStoryObject) { return ( <Story key={storyId} story={record} level={this.props.level + 1} seqFullRefresh={this.props.seqFullRefresh} colors={this.props.colors} timeType={this.props.timeType} timeRef={this.props.timeRef} fShowClosedActions={this.props.fShowClosedActions} quickFind={this.props.quickFind} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} onToggleExpanded={this.props.onToggleExpanded} onToggleHierarchical={this.props.onToggleHierarchical} onToggleAttachment={this.props.onToggleAttachment} /> ); } if (fDirectChild) { if (action === 'CREATED') return null; if (!this.props.fShowClosedActions && action === 'CLOSED') return null; } return ( <Line key={`${storyId}_${id}`} record={record} level={this.props.level} fDirectChild={fDirectChild} timeType={this.props.timeType} timeRef={this.props.timeRef} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} quickFind={this.props.quickFind} onToggleAttachment={this.toggleAttachment} seqFullRefresh={this.props.seqFullRefresh} colors={this.props.colors} /> ); } renderAttachment(record) { const { storyId, id, obj, objOptions, version } = record; const props = pick(this.props, [ 'level', 'timeType', 'timeRef', 'setTimeType', 'setTimeRef', 'quickFind', 'seqFullRefresh', 'colors', ]); const lines = version >= 2 ? treeLines(serialize.deserialize(obj), objOptions) : obj; return lines.map((line, idx) => <AttachmentLine key={`${storyId}_${id}_${idx}`} record={record} {...props} msg={line} /> ); } renderRepetitions(record) { const { storyId, id } = record; const props = pick(this.props, [ 'level', 'timeType', 'timeRef', 'setTimeType', 'setTimeRef', 'quickFind', 'seqFullRefresh', 'colors', ]); return ( <RepetitionLine key={`${storyId}_${id}_repetitions`} record={record} {...props} /> ); } toggleExpanded = () => { this.props.onToggleExpanded(this.props.story.pathStr); } toggleHierarchical = () => { this.props.onToggleHierarchical(this.props.story.pathStr); } toggleAttachment = (recordId) => { this.props.onToggleAttachment(this.props.story.pathStr, recordId); } prepareRecords(records) { return this.props.story.fHierarchical ? sortBy(records, 't') : this.flatten(records); } flatten(records, level = 0) { let out = []; for (let i = 0; i < records.length; i++) { const record = records[i]; if (record.fStoryObject) { out = out.concat(this.flatten(record.records, level + 1)); } else { out.push(record); } } if (level === 0) out = sortBy(out, 't'); return out; }}const styleStory = { outer: (level, story, colors) => ({ backgroundColor: story.fServer ? colors.colorServerBg : colors.colorClientBg, color: story.fServer ? colors.colorServerFg : colors.colorClientFg, marginBottom: level <= 1 ? 10 : undefined, padding: level <= 1 ? 2 : undefined, }),};const connect = ReactRedux.connect(mapStateToProps, mapDispatchToProps);const ConnectedStory = connect(Story);class MainStoryTitle extends React.PureComponent { static propTypes = { title: React.PropTypes.string.isRequired, numRecords: React.PropTypes.number.isRequired, fHierarchical: React.PropTypes.bool.isRequired, fExpanded: React.PropTypes.bool.isRequired, onToggleExpanded: React.PropTypes.func.isRequired, onToggleHierarchical: React.PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { fHovered: false, }; } render() { return ( <div className="rootStoryTitle" style={styleMainTitle.outer} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} > {this.renderCaret()} <span style={styleMainTitle.title} onClick={this.props.onToggleExpanded} > {this.props.title.toUpperCase()}{' '} <span style={styleMainTitle.numRecords}>[{this.props.numRecords}]</span> </span> {this.renderToggleHierarchical()} </div> ); } renderCaret() { if (!this.state.fHovered) return null; const icon = this.props.fExpanded ? 'caret-down' : 'caret-right'; return ( <span onClick={this.props.onToggleExpanded} style={styleMainTitle.caret.outer}> <Icon icon={icon} style={styleMainTitle.caret.icon} /> </span> ); } renderToggleHierarchical() { if (!this.state.fHovered) return null; return ( <HierarchicalToggle fHierarchical={this.props.fHierarchical} onToggleHierarchical={this.props.onToggleHierarchical} fFloat /> ); } onMouseEnter = () => { this.setState({ fHovered: true }); } onMouseLeave = () => { this.setState({ fHovered: false }); }}const styleMainTitle = { outer: { textAlign: 'center', marginBottom: 5, cursor: 'pointer', }, title: { fontWeight: 900, letterSpacing: 3, }, numRecords: { color: 'darkgrey' }, caret: { outer: { display: 'inline-block', position: 'absolute', }, icon: { display: 'inline-block', position: 'absolute', right: 6, top: 2, }, },};class AttachmentLine extends React.PureComponent { static propTypes = { record: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, msg: React.PropTypes.string.isRequired, quickFind: React.PropTypes.string.isRequired, colors: React.PropTypes.object.isRequired, }; render() { const { record, colors } = this.props; const style = styleLine.log(record, colors); const msg = doQuickFind(this.props.msg, this.props.quickFind); return ( <div className="attachmentLine allowUserSelect" style={style}> <Time fShowFull={false} timeType={this.props.timeType} timeRef={this.props.timeRef} setTimeType={this.props.setTimeType} setTimeRef={this.props.setTimeRef} seqFullRefresh={this.props.seqFullRefresh} /> <Src src={record.src} /> <Severity level={record.objLevel} /> <Indent level={this.props.level} /> <CaretOrSpace /> <ColoredText text={` ${msg}`} /> </div> ); }}class RepetitionLine extends React.PureComponent { static propTypes = { record: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, quickFind: React.PropTypes.string.isRequired, colors: React.PropTypes.object.isRequired, }; render() { const { record, level, timeType, timeRef, setTimeType, setTimeRef, seqFullRefresh, colors, } = this.props; const style = styleLine.log(record, colors); let msg = ` x${record.repetitions + 1}, latest: `; msg = doQuickFind(msg, this.props.quickFind); return ( <div className="attachmentLine allowUserSelect" style={style}> <Time fShowFull={false} timeType={timeType} timeRef={timeRef} setTimeType={setTimeType} setTimeRef={setTimeRef} seqFullRefresh={seqFullRefresh} /> <Src /> <Severity /> <Indent level={level} /> <CaretOrSpace /> <Icon icon="copy" disabled style={{ color: 'currentColor' }} /> <ColoredText text={msg} /> <Time t={record.tLastRepetition} fTrim timeType={timeType} timeRef={timeRef} setTimeType={setTimeType} setTimeRef={setTimeRef} seqFullRefresh={seqFullRefresh} /> </div> ); }}class Line extends React.PureComponent { static propTypes = { record: React.PropTypes.object.isRequired, level: React.PropTypes.number.isRequired, fDirectChild: React.PropTypes.bool.isRequired, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, quickFind: React.PropTypes.string.isRequired, onToggleExpanded: React.PropTypes.func, onToggleHierarchical: React.PropTypes.func, onToggleAttachment: React.PropTypes.func, seqFullRefresh: React.PropTypes.number.isRequired, colors: React.PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { fHovered: false, }; } render() { const { record, fDirectChild, level, colors } = this.props; const { fStory, fStoryObject, fServer, fOpen, title, action } = record; let { msg } = record; if (fStoryObject) msg = title; if (fStory) { msg = !fDirectChild ? `${title} ` : ''; if (action) msg += chalk.gray(`[${action}]`); } const style = fStoryObject ? styleLine.titleRow : styleLine.log(record, colors); const indentLevel = fStoryObject ? level - 1 : level; let className = fStoryObject ? 'storyTitle' : 'log'; className += ' allowUserSelect'; const fDarkBg = fServer ? colors.colorServerBgIsDark : colors.colorClientBgIsDark; if (!fDarkBg) className += ' fadeIn'; return ( <div className={className} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} style={style} > {this.renderTime(record)} <Src src={record.src} colors={colors} /> <Severity level={record.level} colors={colors} /> <Indent level={indentLevel} /> {this.renderCaretOrSpace(record)} {this.renderMsg(fStoryObject, msg, record.level)} {this.renderWarningIcon(record)} {fStoryObject && this.renderToggleHierarchical(record)} {fStoryObject && fOpen && <Spinner style={styleLine.spinner} />} {this.renderAttachmentIcon(record)} </div> ); } renderMsg(fStoryObject, msg0, level) { let msg = doQuickFind(msg0, this.props.quickFind); if (level >= constants.LEVEL_STR_TO_NUM.ERROR) { msg = chalk.red.bold(msg); } else if (level >= constants.LEVEL_STR_TO_NUM.WARN) { msg = chalk.red.yellow(msg); } if (!fStoryObject) return <ColoredText text={msg} />; return ( <ColoredText text={msg} onClick={this.props.onToggleExpanded} style={styleLine.title} /> ); } renderTime(record) { const { fStoryObject, t } = record; const { level, timeType, timeRef, setTimeType, setTimeRef, seqFullRefresh } = this.props; const fShowFull = (fStoryObject && level <= 2) || (level <= 1); return ( <Time t={t} fShowFull={fShowFull} timeType={timeType} timeRef={timeRef} setTimeType={setTimeType} setTimeRef={setTimeRef} seqFullRefresh={seqFullRefresh} /> ); } renderCaretOrSpace(record) { let fExpanded; if (this.props.onToggleExpanded && record.fStoryObject) { fExpanded = record.fExpanded; } return ( <CaretOrSpace fExpanded={fExpanded} onToggleExpanded={this.props.onToggleExpanded} /> ); } renderToggleHierarchical(story) { if (!this.props.onToggleHierarchical) return null; if (!this.state.fHovered) return null; return ( <HierarchicalToggle fHierarchical={story.fHierarchical} onToggleHierarchical={this.props.onToggleHierarchical} /> ); } renderWarningIcon(record) { if (record.fExpanded) return null; const { fHasWarning, fHasError } = record; if (!(fHasWarning || fHasError)) return null; const title = `Story contains ${fHasError ? 'an error' : 'a warning'}`; return ( <Icon icon="warning" title={title} onClick={this.props.onToggleExpanded} style={styleLine.warningIcon(fHasError ? 'error' : 'warning')} /> ); } renderAttachmentIcon(record) { if (record.obj == null) return null; let icon; let style; if (record.objIsError) { icon = record.objExpanded ? 'folder-open' : 'folder'; style = timmSet(styleLine.attachmentIcon, 'color', '#cc0000'); } else { icon = record.objExpanded ? 'folder-open-o' : 'folder-o'; style = styleLine.attachmentIcon; } return ( <Icon icon={icon} onClick={this.onClickAttachment} style={style} /> ); } onMouseEnter = () => { this.setState({ fHovered: true }); } onMouseLeave = () => { this.setState({ fHovered: false }); } onClickAttachment = () => { this.props.onToggleAttachment(this.props.record.id); }}const styleLine = { titleRow: { fontWeight: 900, fontFamily: 'Menlo, Consolas, monospace', whiteSpace: 'pre', overflowX: 'hidden', textOverflow: 'ellipsis', }, title: { cursor: 'pointer' }, log: (record, colors) => { const fServer = record.fServer; return { backgroundColor: fServer ? colors.colorServerBg : colors.colorClientBg, color: fServer ? colors.colorServerFg : colors.colorClientFg, fontFamily: 'Menlo, Consolas, monospace', whiteSpace: 'pre', fontWeight: record.fStory && record.action === 'CREATED' ? 900 : undefined, overflowX: 'hidden', textOverflow: 'ellipsis', }; }, spinner: { marginLeft: 8, overflow: 'hidden', }, attachmentIcon: { marginLeft: 8, cursor: 'pointer', display: 'inline', }, warningIcon: (type) => ({ marginLeft: 8, color: type === 'warning' ? '#ff6600' : '#cc0000', display: 'inline', }),};const TIME_LENGTH = 25;class Time extends React.PureComponent { static propTypes = { t: React.PropTypes.number, fShowFull: React.PropTypes.bool, timeType: React.PropTypes.string.isRequired, timeRef: React.PropTypes.number, setTimeType: React.PropTypes.func.isRequired, setTimeRef: React.PropTypes.func.isRequired, seqFullRefresh: React.PropTypes.number.isRequired, fTrim: React.PropTypes.bool, }; render() { const { t, fShowFull, timeType, timeRef, fTrim } = this.props; if (t == null) return <span>{padEnd('', TIME_LENGTH)}</span>; let fTimeInWords = false; let fRefTimestamp = false; const localTime = dateFormat(t, 'YYYY-MM-DD HH:mm:ss.SSS'); let shownTime; if (timeRef == null) { if (timeType === 'RELATIVE') { shownTime = dateDistanceInWords(new Date(), t, { addSuffix: true }); fTimeInWords = true; } else { shownTime = timeType === 'UTC' ? new Date(t).toISOString().replace(/T/g, ' ') : localTime; shownTime = fShowFull ? shownTime : ` ${shownTime.slice(11)}`; } } else if (t === timeRef) { shownTime = timeType === 'UTC' ? new Date(t).toISOString().replace(/T/g, ' ') : localTime; fRefTimestamp = true; } else if (timeType === 'RELATIVE') { shownTime = dateDistanceInWords(timeRef, t, { partialMethod: 'round' }); shownTime += timeRef > t ? ' before' : ' later'; fTimeInWords = true; } else { const delta = Math.abs(t - timeRef); shownTime = new Date(delta).toISOString().replace(/T/g, ' ').slice(0, 23); if (shownTime.slice(0, 4) === '1970') shownTime = shownTime.slice(5); if (shownTime.slice(0, 2) === '01') shownTime = shownTime.slice(3); if (shownTime.slice(0, 2) === '01') shownTime = shownTime.slice(3); if (shownTime.slice(0, 2) === '00') shownTime = shownTime.slice(3); shownTime = `${timeRef > t ? '-' : '+'}${shownTime}`; shownTime = padStart(shownTime, 23); } shownTime = padEnd(shownTime, TIME_LENGTH); if (shownTime.length > TIME_LENGTH) { shownTime = `${shownTime.slice(0, TIME_LENGTH - 1)}…`; } if (fTrim) shownTime = shownTime.trim(); return ( <span onClick={this.onClick} onContextMenu={this.onClick} style={styleTime(fTimeInWords, fRefTimestamp)} title={shownTime.trim() !== localTime ? localTime : undefined} > {shownTime} </span> ); } onClick = (ev) => { const fSetTimeRef = ev.type === 'contextmenu' || ev.ctrlKey; if (fSetTimeRef) cancelEvent(ev); const { t, timeType: prevTimeType, timeRef: prevTimeRef } = this.props; if (fSetTimeRef) { const nextTimeRef = t !== prevTimeRef ? t : null; this.props.setTimeRef(nextTimeRef); } else { let nextTimeType; if (prevTimeType === 'LOCAL') nextTimeType = 'RELATIVE'; else if (prevTimeType === 'RELATIVE') nextTimeType = 'UTC'; else nextTimeType = 'LOCAL'; this.props.setTimeType(nextTimeType); } }}const styleTime = (fTimeInWords, fRefTimestamp) => ({ display: 'inline', cursor: 'pointer', fontStyle: fTimeInWords ? 'italic' : undefined, fontWeight: fRefTimestamp ? 'bold' : undefined, backgroundColor: fRefTimestamp ? '#d1bd0c' : undefined,});class Severity extends React.PureComponent { static propTypes = { level: React.PropTypes.number, }; render() { const { level } = this.props; return level != null ? <ColoredText text={ansiColors.LEVEL_NUM_TO_COLORED_STR[level]} /> : <span> </span>; }}class Src extends React.PureComponent { static propTypes = { src: React.PropTypes.string, }; render() { const { src } = this.props; if (src != null) { const srcStr = ansiColors.getSrcChalkColor(src)(padStart(`${src} `, 20)); return <ColoredText text={srcStr} />; } return <span>{repeat(' ', 20)}</span>; }}const Indent = ({ level }) => { const style = { display: 'inline-block', width: 20 * (level - 1), }; return <div style={style} />;};class CaretOrSpace extends React.PureComponent { static propTypes = { fExpanded: React.PropTypes.bool, onToggleExpanded: React.PropTypes.func, }; render() { let icon; if (this.props.fExpanded != null) { const iconType = this.props.fExpanded ? 'caret-down' : 'caret-right'; icon = <Icon icon={iconType} onClick={this.props.onToggleExpanded} />; } return <span style={styleCaretOrSpace}>{icon}</span>; }}const styleCaretOrSpace = { display: 'inline-block', width: 30, paddingLeft: 10, cursor: 'pointer',};class HierarchicalToggle extends React.PureComponent { static propTypes = { fHierarchical: React.PropTypes.bool.isRequired, onToggleHierarchical: React.PropTypes.func.isRequired, fFloat: React.PropTypes.bool, }; render() { const icon = this.props.fHierarchical ? 'bars' : 'sitemap'; const text = this.props.fHierarchical ? 'Show flat' : 'Show tree'; return ( <span onClick={this.props.onToggleHierarchical} style={styleHierarchical.outer(this.props.fFloat)} > <Icon icon={icon} style={styleHierarchical.icon} /> {text} </span> ); }}const styleHierarchical = { outer: (fFloat) => ({ position: fFloat ? 'absolute' : undefined, marginLeft: 10, color: 'darkgrey', textDecoration: 'underline', cursor: 'pointer', fontWeight: 'normal', fontFamily: 'Menlo, Consolas, monospace', }), icon: { marginRight: 4 },};export default ConnectedStory;export { Story as _Story };
describe('Story', () => { it('02 renders correctly server and client records (root level)', () => { let mainStory = EMPTY_MAIN_STORY; mainStory = setIn(mainStory, ['records', 0, 'records'], [ buildLogRecord({ id: 'id1', msg: 'Client message 1' }), buildLogRecord({ id: 'id2', msg: `${chalk.yellow('Client')} message 2` }), buildLogRecord({ id: 'id3', msg: `${chalk.red('Server')} message`, fServer: true }), ]); mainStory = setIn(mainStory, ['records', 1, 'records'], [ buildLogRecord({ id: 'id1', msg: 'Server message 1', fServer: true }), ]); const el = renderMainStory({ story: mainStory }); expect(renderer.create(el).toJSON()).toMatchSnapshot(); }); });
Story 02 renders correctly server and client records (root level)

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
15
Add dataset card