First question loads

This commit is contained in:
Berkeley Martinez
2015-12-26 00:42:39 -08:00
parent 935760a84a
commit 205b0da43f
7 changed files with 374 additions and 324 deletions

View File

@ -2,10 +2,17 @@ import { Cat } from 'thundercats';
import stamp from 'stampit'; import stamp from 'stampit';
import { Disposable, Observable } from 'rx'; import { Disposable, Observable } from 'rx';
import { postJSON$ } from '../utils/ajax-stream.js';
import { AppActions, AppStore } from './flux'; import { AppActions, AppStore } from './flux';
import { HikesActions } from './routes/Hikes/flux'; import { HikesActions } from './routes/Hikes/flux';
import { JobActions, JobsStore} from './routes/Jobs/flux'; import { JobActions, JobsStore} from './routes/Jobs/flux';
const ajaxStamp = stamp({
methods: {
postJSON$: postJSON$
}
});
export default Cat().init(({ instance: cat, args: [services] }) => { export default Cat().init(({ instance: cat, args: [services] }) => {
const serviceStamp = stamp({ const serviceStamp = stamp({
methods: { methods: {
@ -30,7 +37,7 @@ export default Cat().init(({ instance: cat, args: [services] }) => {
} }
}); });
cat.register(HikesActions.compose(serviceStamp), null, services); cat.register(HikesActions.compose(serviceStamp, ajaxStamp), null, services);
cat.register(AppActions.compose(serviceStamp), null, services); cat.register(AppActions.compose(serviceStamp), null, services);
cat.register(AppStore, null, cat); cat.register(AppStore, null, cat);

View File

@ -8,7 +8,9 @@ const initValue = {
points: 0, points: 0,
hikesApp: { hikesApp: {
hikes: [], hikes: [],
currentHikes: {} currentHikes: {},
currentQuestion: 1,
showQuestion: false
} }
}; };
@ -20,13 +22,13 @@ export default Store({
init({ instance: appStore, args: [cat] }) { init({ instance: appStore, args: [cat] }) {
const { updateRoute, getUser, setTitle } = cat.getActions('appActions'); const { updateRoute, getUser, setTitle } = cat.getActions('appActions');
const register = createRegistrar(appStore); const register = createRegistrar(appStore);
const { fetchHikes } = cat.getActions('hikesActions'); const { toggleQuestions, fetchHikes } = cat.getActions('hikesActions');
// app // app
register(setter(fromMany(getUser, setTitle, updateRoute))); register(setter(fromMany(getUser, setTitle, updateRoute)));
// hikes // hikes
register(fetchHikes); register(fromMany(fetchHikes, toggleQuestions));
return appStore; return appStore;
} }

View File

@ -12,38 +12,22 @@ export default React.createClass({
displayName: 'Hike', displayName: 'Hike',
propTypes: { propTypes: {
dashedName: PropTypes.string,
currentHike: PropTypes.object, currentHike: PropTypes.object,
showQuestions: PropTypes.bool showQuestions: PropTypes.bool
}, },
renderBody(showQuestions, currentHike, dashedName) { renderBody(showQuestions) {
if (showQuestions) { if (showQuestions) {
return ( return <Questions />;
<Questions hike={ currentHike }/>
);
} }
return <Lecture />;
const {
challengeSeed: [ id ] = ['1'],
description = []
} = currentHike;
return (
<Lecture
dashedName={ dashedName }
description={ description }
id={ id } />
);
}, },
render() { render() {
const { const {
currentHike = {}, currentHike: { title } = {},
dashedName,
showQuestions showQuestions
} = this.props; } = this.props;
const { title } = currentHike;
const videoTitle = <h2>{ title }</h2>; const videoTitle = <h2>{ title }</h2>;
@ -53,7 +37,7 @@ export default React.createClass({
<Panel <Panel
className={ 'text-center' } className={ 'text-center' }
title={ videoTitle }> title={ videoTitle }>
{ this.renderBody(showQuestions, currentHike, dashedName) } { this.renderBody(showQuestions) }
</Panel> </Panel>
</Row> </Row>
</Col> </Col>

View File

@ -31,7 +31,8 @@ export default contain(
children: PropTypes.element, children: PropTypes.element,
currentHike: PropTypes.object, currentHike: PropTypes.object,
hikes: PropTypes.array, hikes: PropTypes.array,
params: PropTypes.object params: PropTypes.object,
showQuestions: PropTypes.bool
}, },
componentWillMount() { componentWillMount() {
@ -45,15 +46,15 @@ export default contain(
); );
}, },
renderChild(children, hikes, currentHike, dashedName) { renderChild({ children, ...props }) {
if (!children) { if (!children) {
return null; return null;
} }
return React.cloneElement(children, { hikes, currentHike, dashedName }); return React.cloneElement(children, props);
}, },
render() { render() {
const { hikes, children, currentHike } = this.props; const { hikes } = this.props;
const { dashedName } = this.props.params; const { dashedName } = this.props.params;
const preventOverflow = { overflow: 'hidden' }; const preventOverflow = { overflow: 'hidden' };
return ( return (
@ -61,7 +62,7 @@ export default contain(
<Row style={ preventOverflow }> <Row style={ preventOverflow }>
{ {
// render sub-route // render sub-route
this.renderChild(children, hikes, currentHike, dashedName) || this.renderChild({ ...this.props, dashedName }) ||
// if no sub-route render hikes map // if no sub-route render hikes map
this.renderMap(hikes) this.renderMap(hikes)
} }

View File

@ -1,4 +1,5 @@
import React, { PropTypes } from 'react'; import React, { PropTypes } from 'react';
import { contain } from 'thundercats-react';
import { Button, Col, Row } from 'react-bootstrap'; import { Button, Col, Row } from 'react-bootstrap';
import { History } from 'react-router'; import { History } from 'react-router';
import Vimeo from 'react-vimeo'; import Vimeo from 'react-vimeo';
@ -6,53 +7,82 @@ import debugFactory from 'debug';
const debug = debugFactory('freecc:hikes'); const debug = debugFactory('freecc:hikes');
export default React.createClass({ export default contain(
displayName: 'Lecture', {
mixins: [History], actions: ['hikesActions'],
store: 'appStore',
map(state) {
const {
currentHike: {
dashedName,
description,
challengeSeed: [id] = [0]
} = {}
} = state.hikesApp;
propTypes: { return {
dashedName: PropTypes.string, dashedName,
description: PropTypes.array, description,
id: PropTypes.string id
};
}
}, },
React.createClass({
displayName: 'Lecture',
mixins: [History],
handleError: debug, propTypes: {
dashedName: PropTypes.string,
description: PropTypes.array,
id: PropTypes.string,
hikesActions: PropTypes.object
},
handleFinish() { shouldComponentUpdate(nextProps) {
debug('loading questions'); const { props } = this;
}, return nextProps.id !== props.id;
},
renderTranscript(transcript, dashedName) { handleError: debug,
return transcript.map((line, index) => (
<p key={ dashedName + index }>{ line }</p>
));
},
render() { handleFinish(hikesActions) {
const { debug('loading questions');
id = '1', hikesActions.toggleQuestions();
dashedName, },
description = []
} = this.props;
return ( renderTranscript(transcript, dashedName) {
<Col xs={ 12 }> return transcript.map((line, index) => (
<Row> <p key={ dashedName + index }>{ line }</p>
<Vimeo ));
onError={ this.handleError } },
onFinish= { this.handleFinish }
videoId={ id } /> render() {
</Row> const {
<Row> id = '1',
{ this.renderTranscript(description, dashedName) } description = [],
<Button hikesActions
block={ true } } = this.props;
bsSize='large' const dashedName = 'foo';
onClick={ this.handleFinish }>
Take me to the Questions return (
</Button> <Col xs={ 12 }>
</Row> <Row>
</Col> <Vimeo
); onError={ this.handleError }
} onFinish= { this.handleFinish }
}); videoId={ id } />
</Row>
<Row>
{ this.renderTranscript(description, dashedName) }
<Button
block={ true }
bsSize='large'
onClick={ () => this.handleFinish(hikesActions) }>
Take me to the Questions
</Button>
</Row>
</Col>
);
}
})
);

View File

@ -1,6 +1,6 @@
import React, { PropTypes } from 'react'; import React, { PropTypes } from 'react';
import { Motion } from 'react-motion'; import { Motion } from 'react-motion';
import { History, Lifecycle } from 'react-router'; import { contain } from 'thundercats-react';
import debugFactory from 'debug'; import debugFactory from 'debug';
import { import {
Button, Button,
@ -10,269 +10,250 @@ import {
Row Row
} from 'react-bootstrap'; } from 'react-bootstrap';
import { postJSON$ } from '../../../../utils/ajax-stream.js';
const debug = debugFactory('freecc:hikes'); const debug = debugFactory('freecc:hikes');
const ANSWER_THRESHOLD = 200; const ANSWER_THRESHOLD = 200;
export default React.createClass({ export default contain(
displayName: 'Questions', {
store: 'appStore',
actions: ['hikesAction'],
map(state) {
const { currentQuestion, currentHike } = state.hikesApp;
mixins: [ return {
History, hike: currentHike,
Lifecycle currentQuestion
], };
propTypes: {
currentHike: PropTypes.object,
dashedName: PropTypes.string,
hikes: PropTypes.array,
params: PropTypes.object
},
getInitialState: () => ({
mouse: [0, 0],
correct: false,
delta: [0, 0],
isPressed: false,
showInfo: false,
shake: false
}),
getTweenValues() {
const { mouse: [x, y] } = this.state;
return {
val: { x, y },
config: [120, 10]
};
},
handleMouseDown({ pageX, pageY, touches }) {
if (touches) {
({ pageX, pageY } = touches[0]);
} }
const { mouse: [pressX, pressY] } = this.state;
const dx = pageX - pressX;
const dy = pageY - pressY;
this.setState({
isPressed: true,
delta: [dx, dy],
mouse: [pageX - dx, pageY - dy]
});
}, },
React.createClass({
displayName: 'Questions',
handleMouseUp() { propTypes: {
const { correct } = this.state; dashedName: PropTypes.string,
if (correct) { currentQuestion: PropTypes.number,
return this.setState({ hike: PropTypes.object,
isPressed: false, hikesActions: PropTypes.object
delta: [0, 0] },
});
} getInitialState: () => ({
this.setState({
isPressed: false,
mouse: [0, 0], mouse: [0, 0],
delta: [0, 0] correct: false,
}); delta: [0, 0],
}, isPressed: false,
showInfo: false,
shake: false
}),
handleMouseMove(answer) { getTweenValues() {
return (e) => { const { mouse: [x, y] } = this.state;
let { pageX, pageY, touches } = e; return {
val: { x, y },
config: [120, 10]
};
},
handleMouseDown({ pageX, pageY, touches }) {
if (touches) { if (touches) {
e.preventDefault();
// these reassins the values of pageX, pageY from touches
({ pageX, pageY } = touches[0]); ({ pageX, pageY } = touches[0]);
} }
const { mouse: [pressX, pressY] } = this.state;
const { isPressed, delta: [dx, dy] } = this.state; const dx = pageX - pressX;
if (isPressed) { const dy = pageY - pressY;
const mouse = [pageX - dx, pageY - dy];
if (mouse[0] >= ANSWER_THRESHOLD) {
this.handleMouseUp();
return this.onAnswer(answer, true)();
}
if (mouse[0] <= -ANSWER_THRESHOLD) {
this.handleMouseUp();
return this.onAnswer(answer, false)();
}
this.setState({ mouse });
}
};
},
hideInfo() {
this.setState({ showInfo: false });
},
onAnswer(answer, userAnswer) {
return (e) => {
if (e && e.preventDefault) {
e.preventDefault();
}
if (this.disposeTimeout) {
clearTimeout(this.disposeTimeout);
this.disposeTimeout = null;
}
if (answer === userAnswer) {
debug('correct answer!');
this.setState({
correct: true,
mouse: [ userAnswer ? 1000 : -1000, 0]
});
this.disposeTimeout = setTimeout(() => {
this.onCorrectAnswer();
}, 1000);
return;
}
debug('incorrect');
this.setState({ this.setState({
showInfo: true, isPressed: true,
shake: true delta: [dx, dy],
mouse: [pageX - dx, pageY - dy]
}); });
},
this.disposeTimeout = setTimeout( handleMouseUp() {
() => this.setState({ shake: false }), const { correct } = this.state;
500 if (correct) {
); return this.setState({
}; isPressed: false,
}, delta: [0, 0]
});
onCorrectAnswer() {
const { hikes, currentHike } = this.props;
const { dashedName, number } = this.props.params;
const { id, name, difficulty, tests } = currentHike;
const nextQuestionIndex = +number;
postJSON$('/completed-challenge', { id, name }).subscribeOnCompleted(() => {
if (tests[nextQuestionIndex]) {
return this.history.pushState(
null,
`/hikes/${ dashedName }/questions/${ nextQuestionIndex + 1 }`
);
} }
// next questions does not exist; this.setState({
debug('finding next hike'); isPressed: false,
const nextHike = [].slice.call(hikes) mouse: [0, 0],
// hikes is in oder of difficulty, lets get reverse order delta: [0, 0]
.reverse() });
// now lets find the hike with the difficulty right above this one },
.reduce((lowerHike, hike) => {
if (hike.difficulty > difficulty) { handleMouseMove(answer) {
return hike; return (e) => {
let { pageX, pageY, touches } = e;
if (touches) {
e.preventDefault();
// these reassins the values of pageX, pageY from touches
({ pageX, pageY } = touches[0]);
}
const { isPressed, delta: [dx, dy] } = this.state;
if (isPressed) {
const mouse = [pageX - dx, pageY - dy];
if (mouse[0] >= ANSWER_THRESHOLD) {
this.handleMouseUp();
return this.onAnswer(answer, true)();
} }
return lowerHike; if (mouse[0] <= -ANSWER_THRESHOLD) {
}, null); this.handleMouseUp();
return this.onAnswer(answer, false)();
if (nextHike) { }
return this.history.pushState(null, `/hikes/${ nextHike.dashedName }`); this.setState({ mouse });
} }
debug(
'next Hike was not found, currentHike %s',
currentHike.dashedName
);
this.history.pushState(null, '/hikes');
});
},
routerWillLeave(nextState, router, cb) {
// TODO(berks): do animated transitions here stuff here
this.setState({
showInfo: false,
correct: false,
mouse: [0, 0]
}, cb);
},
renderInfo(showInfo, info) {
if (!info) {
return null;
}
return (
<Modal
backdrop={ true }
onHide={ this.hideInfo }
show={ showInfo }>
<Modal.Body>
<h3>
{ info }
</h3>
</Modal.Body>
<Modal.Footer>
<Button
block={ true }
bsSize='large'
onClick={ this.hideInfo }>
hide
</Button>
</Modal.Footer>
</Modal>
);
},
renderQuestion(number, question, answer, shake) {
return ({ x: xFunc }) => {
const x = xFunc().val.x;
const style = {
WebkitTransform: `translate3d(${ x }px, 0, 0)`,
transform: `translate3d(${ x }px, 0, 0)`
}; };
const title = <h4>Question { number }</h4>; },
hideInfo() {
this.setState({ showInfo: false });
},
onAnswer(answer, userAnswer) {
return (e) => {
if (e && e.preventDefault) {
e.preventDefault();
}
if (this.disposeTimeout) {
clearTimeout(this.disposeTimeout);
this.disposeTimeout = null;
}
if (answer === userAnswer) {
debug('correct answer!');
this.setState({
correct: true,
mouse: [ userAnswer ? 1000 : -1000, 0]
});
this.disposeTimeout = setTimeout(() => {
this.onCorrectAnswer();
}, 1000);
return;
}
debug('incorrect');
this.setState({
showInfo: true,
shake: true
});
this.disposeTimeout = setTimeout(
() => this.setState({ shake: false }),
500
);
};
},
onCorrectAnswer() {
const {
hikesActions,
hike: { id, name }
} = this.props;
hikesActions.completedHike({ id, name });
},
routerWillLeave(nextState, router, cb) {
// TODO(berks): do animated transitions here stuff here
this.setState({
showInfo: false,
correct: false,
mouse: [0, 0]
}, cb);
},
renderInfo(showInfo, info) {
if (!info) {
return null;
}
return ( return (
<Panel <Modal
className={ shake ? 'animated swing shake' : '' } backdrop={ true }
header={ title } onHide={ this.hideInfo }
onMouseDown={ this.handleMouseDown } show={ showInfo }>
onMouseLeave={ this.handleMouseUp } <Modal.Body>
onMouseMove={ this.handleMouseMove(answer) } <h3>
onMouseUp={ this.handleMouseUp } { info }
onTouchEnd={ this.handleMouseUp } </h3>
onTouchMove={ this.handleMouseMove(answer) } </Modal.Body>
onTouchStart={ this.handleMouseDown } <Modal.Footer>
style={ style }> <Button
<p>{ question }</p> block={ true }
</Panel> bsSize='large'
onClick={ this.hideInfo }>
hide
</Button>
</Modal.Footer>
</Modal>
); );
}; },
},
render() { renderQuestion(number, question, answer, shake) {
const { showInfo, shake } = this.state; return ({ x: xFunc }) => {
const { currentHike: { tests = [] } } = this.props; const x = xFunc().val.x;
const { number = '1' } = this.props.params; const style = {
WebkitTransform: `translate3d(${ x }px, 0, 0)`,
const [question, answer, info] = tests[number - 1] || []; transform: `translate3d(${ x }px, 0, 0)`
};
return ( const title = <h4>Question { number }</h4>;
<Col return (
onMouseUp={ this.handleMouseUp } <Panel
xs={ 8 } className={ shake ? 'animated swing shake' : '' }
xsOffset={ 2 }> header={ title }
<Row> onMouseDown={ this.handleMouseDown }
<Motion style={{ x: this.getTweenValues }}> onMouseLeave={ this.handleMouseUp }
{ this.renderQuestion(number, question, answer, shake) } onMouseMove={ this.handleMouseMove(answer) }
</Motion> onMouseUp={ this.handleMouseUp }
{ this.renderInfo(showInfo, info) } onTouchEnd={ this.handleMouseUp }
<Panel> onTouchMove={ this.handleMouseMove(answer) }
<Button onTouchStart={ this.handleMouseDown }
bsSize='large' style={ style }>
className='pull-left' <p>{ question }</p>
onClick={ this.onAnswer(answer, false, info) }>
false
</Button>
<Button
bsSize='large'
className='pull-right'
onClick={ this.onAnswer(answer, true, info) }>
true
</Button>
</Panel> </Panel>
</Row> );
</Col> };
); },
}
}); render() {
const { showInfo, shake } = this.state;
const {
hike: { tests = [] } = {},
currentQuestion
} = this.props;
const [ question, answer, info ] = tests[currentQuestion - 1] || [];
return (
<Col
onMouseUp={ this.handleMouseUp }
xs={ 8 }
xsOffset={ 2 }>
<Row>
<Motion style={{ x: this.getTweenValues }}>
{ this.renderQuestion(currentQuestion, question, answer, shake) }
</Motion>
{ this.renderInfo(showInfo, info) }
<Panel>
<Button
bsSize='large'
className='pull-left'
onClick={ this.onAnswer(answer, false, info) }>
false
</Button>
<Button
bsSize='large'
className='pull-right'
onClick={ this.onAnswer(answer, true, info) }>
true
</Button>
</Panel>
</Row>
</Col>
);
}
})
);

View File

@ -1,3 +1,5 @@
import _ from 'lodash';
import { Observable } from 'rx';
import { Actions } from 'thundercats'; import { Actions } from 'thundercats';
import debugFactory from 'debug'; import debugFactory from 'debug';
@ -24,6 +26,15 @@ function getCurrentHike(hikes = [{}], dashedName, currentHike) {
}, currentHike || {}); }, currentHike || {});
} }
function findNextHike(hikes, id) {
if (!id) {
debug('find next hike no id provided');
return hikes[0];
}
const currentIndex = _.findIndex(hikes, ({ id: _id }) => _id === id);
return hikes[currentIndex + 1] || hikes[0];
}
export default Actions({ export default Actions({
refs: { displayName: 'HikesActions' }, refs: { displayName: 'HikesActions' },
shouldBindMethods: true, shouldBindMethods: true,
@ -47,19 +58,53 @@ export default Actions({
return this.readService$('hikes', null, null) return this.readService$('hikes', null, null)
.map(hikes => { .map(hikes => {
const hikesApp = { const currentHike = getCurrentHike(hikes, dashedName);
hikes,
currentHike: getCurrentHike(hikes, dashedName)
};
return { return {
transform(oldState) { transform(state) {
return Object.assign({}, oldState, { hikesApp }); const hikesApp = { ...state.hikesApp, currentHike, hikes };
return { ...state, hikesApp };
} }
}; };
}) })
.catch(err => { .catch(err => {
console.error(err); console.error(err);
}); });
},
toggleQuestions() {
return {
transform(state) {
state.hikesApp.showQuestions = !state.hikesApp.showQuestions;
return Object.assign({}, state);
}
};
},
completedHike(data = {}) {
return this.postJSON$('/completed-challenge', data)
.map(() => {
return {
transform(state) {
const { hikes, currentHike: { id } } = state.hikesApp;
const currentHike = findNextHike(hikes, id);
// go to next route
state.route = currentHike && currentHike.dashedName ?
`/hikes/${ currentHike.dashedName }` :
'/hikes';
const hikesApp = { ...state.hikesApp, currentHike };
return { ...state, hikesApp };
}
};
})
.catch(err => {
console.error(err);
return Observable.just({
set: {
error: err
}
});
});
} }
}); });