diff --git a/README.md b/README.md index 89aaefee8..a58ac7c74 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,21 @@ Online comments are broken. Our open-source Talk tool rethinks how moderation, c Third party licenses are available via the `/client/3rdpartylicenses.txt` endpoint when the server is running with built assets. -## Documentation +## Important Links -See our [Talk Documentation & Guides](https://coralproject.github.io/talk/). +- Developer Documentation & Setup Guides: https://coralproject.github.io/talk/ + +- Pivotal Tracker Backlog & Release Schedule: https://www.pivotaltracker.com/n/projects/1863625 + +## Learn More about Coral + +- Community Forums: https://community.coralproject.net/ + +- Website: https://coralproject.net + +- Blog: https://blog.coralproject.net + +- Community Guides for Journalism: https://guides.coralproject.net/ ## License diff --git a/app.js b/app.js index 0be7a1830..741dac93f 100644 --- a/app.js +++ b/app.js @@ -3,71 +3,42 @@ const bodyParser = require('body-parser'); const morgan = require('morgan'); const path = require('path'); const helmet = require('helmet'); -const authentication = require('./middleware/authentication'); -const {passport} = require('./services/passport'); -const plugins = require('./services/plugins'); -const pubsub = require('./services/pubsub'); -const i18n = require('./services/i18n'); -const enabled = require('debug').enabled; -const errors = require('./errors'); -const {createGraphOptions} = require('./graph'); -const apollo = require('graphql-server-express'); -const accepts = require('accepts'); const compression = require('compression'); const cookieParser = require('cookie-parser'); -const {ROOT_URL} = require('./config'); +const {BASE_URL, BASE_PATH, MOUNT_PATH} = require('./url'); +const routes = require('./routes'); +const debug = require('debug')('talk:app'); const app = express(); -// Middleware declarations. +//============================================================================== +// APPLICATION WIDE MIDDLEWARE +//============================================================================== // Add the logging middleware only if we aren't testing. -if (app.get('env') !== 'test') { +if (process.env.NODE_ENV !== 'test') { app.use(morgan('dev')); } -//============================================================================== -// APP MIDDLEWARE -//============================================================================== - +// Trust the first proxy in front of us, this will enable us to trust the fact +// that SSL was terminated correctly. app.set('trust proxy', 1); -// We disable frameward on helmet to allow crossdomain injection of the embed +// Enable a suite of security good practices through helmet. We disable +// frameguard to allow crossdomain injection of the embed. app.use(helmet({ - frameguard: false + frameguard: false, })); + +// Compress the responses if appropriate. app.use(compression()); + +// Parse the cookies on the request. app.use(cookieParser()); + +// Parse the body json if it's there. app.use(bodyParser.json()); -//============================================================================== -// STATIC FILES -//============================================================================== - -// If the application is in production mode, then add gzip rewriting for the -// content. -if (process.env.NODE_ENV === 'production') { - app.get('*.js', (req, res, next) => { - const accept = accepts(req); - if (accept.encoding(['gzip']) === 'gzip') { - - // Adjsut the headers on the request by adding a content type header - // because express won't be able to detect the mime-type with the .gz - // extension and we need to decalre support for the gzip encoding. - res.set('Content-Type', 'application/javascript'); - res.set('Content-Encoding', 'gzip'); - - // Rewrite the url so that the gzip version will be served instead. - req.url = `${req.url}.gz`; - } - - next(); - }); -} - -app.use('/client', express.static(path.join(__dirname, 'dist'))); -app.use('/public', express.static(path.join(__dirname, 'public'))); - //============================================================================== // VIEW CONFIGURATION //============================================================================== @@ -75,124 +46,19 @@ app.use('/public', express.static(path.join(__dirname, 'public'))); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); -// Set the BASE_URL as the ROOT_URL. -app.locals.BASE_URL = ROOT_URL; -if (app.locals.BASE_URL[app.locals.BASE_URL.length - 1] !== '/') { - app.locals.BASE_URL += '/'; -} - -//============================================================================== -// PASSPORT MIDDLEWARE -//============================================================================== - -const passportDebug = require('debug')('talk:passport'); - -// Install the passport plugins. -plugins.get('server', 'passport').forEach((plugin) => { - passportDebug(`added plugin '${plugin.plugin.name}'`); - - // Pass the passport.js instance to the plugin to allow it to inject it's - // functionality. - plugin.passport(passport); -}); - -// Setup the PassportJS Middleware. -app.use(passport.initialize()); - -// Attach the authentication middleware, this will be responsible for decoding -// (if present) the JWT on the request. -app.use('/api', authentication); - -const pubsubClient = pubsub.createClientFactory(); - -// To handle dependancy injection safer, we inject the pubsub handle onto the -// request object. -app.use('/api', (req, res, next) => { - - // Attach the pubsub handle to the requests. - req.pubsub = pubsubClient(); - - // Forward on the request. - next(); -}); - -//============================================================================== -// GraphQL Router -//============================================================================== - -// GraphQL endpoint. -app.use('/api/v1/graph/ql', apollo.graphqlExpress(createGraphOptions)); - -// Only include the graphiql tool if we aren't in production mode. -if (app.get('env') !== 'production') { - - // Interactive graphiql interface. - app.use('/api/v1/graph/iql', (req, res) => { - res.render('graphiql', { - endpointURL: '/api/v1/graph/ql' - }); - }); - - // GraphQL documention. - app.get('/admin/docs', (req, res) => { - res.render('admin/docs'); - }); - -} - //============================================================================== // ROUTES //============================================================================== -app.use('/', require('./routes')); +// Apply the BASE_PATH, BASE_URL, and MOUNT_PATH on the app.locals, which will +// make them available on the templates and the routers. +app.locals.BASE_URL = BASE_URL; +app.locals.BASE_PATH = BASE_PATH; +app.locals.MOUNT_PATH = MOUNT_PATH; -//============================================================================== -// ERROR HANDLING -//============================================================================== +debug(`mounting routes on the ${MOUNT_PATH} path`); -// Catch 404 and forward to error handler. -app.use((req, res, next) => { - next(errors.ErrNotFound); -}); - -// General error handler. Respond with the message and error if we have it while -// returning a status code that makes sense. -app.use('/api', (err, req, res, next) => { - if (err !== errors.ErrNotFound) { - if (app.get('env') !== 'test' || enabled('talk:errors')) { - console.error(err); - } - } - - if (err instanceof errors.APIError) { - res.status(err.status).json({ - message: err.message, - error: err - }); - } else { - res.status(500).json({}); - } -}); - -app.use('/', (err, req, res, next) => { - if (err !== errors.ErrNotFound) { - console.error(err); - } - - i18n.init(req); - - if (err instanceof errors.APIError) { - res.status(err.status); - res.render('error', { - message: err.message, - error: app.get('env') === 'development' ? err : {} - }); - } else { - res.render('error', { - message: err.message, - error: app.get('env') === 'development' ? err : {} - }); - } -}); +// Actually apply the routes. +app.use(MOUNT_PATH, routes); module.exports = app; diff --git a/bin/cli-setup b/bin/cli-setup index 9ecdecc95..2e5c1e5b8 100755 --- a/bin/cli-setup +++ b/bin/cli-setup @@ -94,7 +94,7 @@ const performSetup = async () => { name: 'requireEmailConfirmation', default: settings.requireEmailConfirmation, message: 'Should emails always be confirmed' - } + }, ]); // Update the settings that were changed. @@ -104,6 +104,32 @@ const performSetup = async () => { } }); + answers = await inquirer.prompt([ + { + type: 'confirm', + name: 'inputWhitelistedDomains', + default: true, + message: 'Would you like to specify a whitelisted domain' + }, + { + type: 'input', + name: 'whitelistedDomain', + message: 'Whitelisted Domain', + when: ({inputWhitelistedDomains}) => inputWhitelistedDomains, + validate: (input) => { + if (input && input.length > 0) { + return true; + } + + return 'Whitelisted Domain cannot be empty.'; + } + } + ]); + + if (answers.inputWhitelistedDomains) { + settings.domains.whitelist = [answers.whitelistedDomain]; + } + console.log('\nWe\'ll ask you some questions about your first admin user.\n'); let user = await inquirer.prompt([ @@ -147,7 +173,11 @@ const performSetup = async () => { name: 'confirmPassword', message: 'Confirm Password', type: 'password', - filter: (confirmPassword) => { + filter: (confirmPassword, {password}) => { + if (password !== confirmPassword) { + return Promise.reject(new Error('Passwords do not match')); + } + return UsersService .isValidPassword(confirmPassword) .catch((err) => { @@ -157,10 +187,6 @@ const performSetup = async () => { }, ]); - if (user.password !== user.confirmPassword) { - return Promise.reject(new Error('Passwords do not match')); - } - let {user: newUser} = await SetupService.setup({ settings: settings.toObject(), user: { diff --git a/client/coral-admin/src/AppRouter.js b/client/coral-admin/src/AppRouter.js index 4b3ea0f0b..9772ebf17 100644 --- a/client/coral-admin/src/AppRouter.js +++ b/client/coral-admin/src/AppRouter.js @@ -37,27 +37,11 @@ const routes = ( - - - - - - - - - - - - - - - - - - - - + + + + diff --git a/client/coral-admin/src/actions/assets.js b/client/coral-admin/src/actions/assets.js index 75bd2477d..b9ebe0ada 100644 --- a/client/coral-admin/src/actions/assets.js +++ b/client/coral-admin/src/actions/assets.js @@ -35,7 +35,7 @@ export const fetchAssets = (skip = '', limit = '', search = '', sort = '', filte // Update an asset state // Get comments to fill each of the three lists on the mod queue export const updateAssetState = (id, closedAt) => (dispatch) => { - dispatch({type: UPDATE_ASSET_STATE_REQUEST}); + dispatch({type: UPDATE_ASSET_STATE_REQUEST, id, closedAt}); return coralApi(`/assets/${id}/status`, {method: 'PUT', body: {closedAt}}) .then(() => dispatch({type: UPDATE_ASSET_STATE_SUCCESS})) .catch((error) => { diff --git a/client/coral-admin/src/actions/install.js b/client/coral-admin/src/actions/install.js index 33cefab63..6393c58dd 100644 --- a/client/coral-admin/src/actions/install.js +++ b/client/coral-admin/src/actions/install.js @@ -93,21 +93,21 @@ const validation = (formData, dispatch, next) => { }; export const submitSettings = () => (dispatch, getState) => { - const settingsFormData = getState().install.toJS().data.settings; + const settingsFormData = getState().install.data.settings; validation(settingsFormData, dispatch, function() { dispatch(nextStep()); }); }; export const submitUser = () => (dispatch, getState) => { - const userFormData = getState().install.toJS().data.user; + const userFormData = getState().install.data.user; validation(userFormData, dispatch, function() { dispatch(nextStep()); }); }; export const finishInstall = () => (dispatch, getState) => { - const data = getState().install.toJS().data; + const data = getState().install.data; dispatch(installRequest()); return coralApi('/setup', {method: 'POST', body: data}) .then(() => { diff --git a/client/coral-admin/src/actions/settings.js b/client/coral-admin/src/actions/settings.js index ba8b917ea..ca9062b9e 100644 --- a/client/coral-admin/src/actions/settings.js +++ b/client/coral-admin/src/actions/settings.js @@ -42,7 +42,7 @@ export const updateDomainlist = (listName, list) => { }; export const saveSettingsToServer = () => (dispatch, getState) => { - let settings = getState().settings.toJS(); + let settings = getState().settings; if (settings.charCount) { settings.charCount = parseInt(settings.charCount); } diff --git a/client/coral-admin/src/components/CommentBodyHighlighter.js b/client/coral-admin/src/components/CommentBodyHighlighter.js index 3b3ee3318..9a430f7c7 100644 --- a/client/coral-admin/src/components/CommentBodyHighlighter.js +++ b/client/coral-admin/src/components/CommentBodyHighlighter.js @@ -8,18 +8,16 @@ export default ({suspectWords, bannedWords, body, ...rest}) => { const links = linkify.getMatches(body); const linkText = links ? links.map((link) => link.raw) : []; - // since words are checked against word boundaries on the backend, - // should be the behavior on the front end as well. - // currently the highlighter plugin does not support out of the box. - const searchWords = [...suspectWords, ...bannedWords] - .filter((w) => { - return new RegExp(`(^|\\s)${w}(\\s|$)`, 'i').test(body); - }) - .concat(linkText); + const searchWords = [ + ...suspectWords, + ...bannedWords, + ...linkText + ]; return ( diff --git a/client/coral-admin/src/components/CommentType.css b/client/coral-admin/src/components/CommentType.css index b5dbc229b..969d9511d 100644 --- a/client/coral-admin/src/components/CommentType.css +++ b/client/coral-admin/src/components/CommentType.css @@ -3,11 +3,12 @@ color: white; background: grey; box-sizing: border-box; - padding: 2px 8px; - border-radius: 2px; + padding: 2px 5px; font-size: 12px; - height: 28px; - + height: 24px; + letter-spacing: 0.4px; + line-height: 22px; + > i { font-size: 14px; vertical-align: text-top; diff --git a/client/coral-admin/src/components/FlagBox.css b/client/coral-admin/src/components/FlagBox.css index 402a88045..232803203 100644 --- a/client/coral-admin/src/components/FlagBox.css +++ b/client/coral-admin/src/components/FlagBox.css @@ -1,6 +1,6 @@ .flagBox { border-top: 1px solid rgba(66, 66, 66, 0.12); - + margin-top: 10px; .container { padding: 0 14px; } diff --git a/client/coral-admin/src/components/LoadMore.css b/client/coral-admin/src/components/LoadMore.css new file mode 100644 index 000000000..64c51f870 --- /dev/null +++ b/client/coral-admin/src/components/LoadMore.css @@ -0,0 +1,21 @@ +.loadMoreContainer { + display: flex; + justify-content: center; + width: 100%; +} + +.loadMore { + width: 100%; + text-align: center; + color: #FFF; + max-width: 660px; + margin-bottom: 30px; + background-color: #2376D8; + cursor: pointer; +} + +.loadMore:hover { + background-color: #4399FF; +} + + diff --git a/client/coral-admin/src/routes/Moderation/components/LoadMore.js b/client/coral-admin/src/components/LoadMore.js similarity index 63% rename from client/coral-admin/src/routes/Moderation/components/LoadMore.js rename to client/coral-admin/src/components/LoadMore.js index 612629647..969c6734f 100644 --- a/client/coral-admin/src/routes/Moderation/components/LoadMore.js +++ b/client/coral-admin/src/components/LoadMore.js @@ -1,9 +1,10 @@ import React, {PropTypes} from 'react'; import {Button} from 'coral-ui'; -import styles from './styles.css'; +import styles from './LoadMore.css'; +import cn from 'classnames'; -const LoadMore = ({loadMore, showLoadMore}) => -
+const LoadMore = ({loadMore, showLoadMore, className, ...rest}) => +
{ showLoadMore &&
+ ); diff --git a/client/coral-admin/src/components/UserDetailComment.css b/client/coral-admin/src/components/UserDetailComment.css index 0e10f00c0..2dfd61cf3 100644 --- a/client/coral-admin/src/components/UserDetailComment.css +++ b/client/coral-admin/src/components/UserDetailComment.css @@ -8,6 +8,10 @@ min-height: 0; } +.root:last-child { + border: 0; +} + .rootSelected { background-color: #ecf4ff; } @@ -51,7 +55,7 @@ position: relative; } -.commentType { +.badgeBar { position: absolute; right: 0px; } diff --git a/client/coral-admin/src/components/UserDetailComment.js b/client/coral-admin/src/components/UserDetailComment.js index 9b4936847..dc809b9c7 100644 --- a/client/coral-admin/src/components/UserDetailComment.js +++ b/client/coral-admin/src/components/UserDetailComment.js @@ -3,6 +3,7 @@ import {Link} from 'react-router'; import {Icon} from 'coral-ui'; import FlagBox from './FlagBox'; +import ReplyBadge from './ReplyBadge'; import styles from './UserDetailComment.css'; import CommentType from './CommentType'; import {getActionSummary} from 'coral-framework/utils'; @@ -56,7 +57,11 @@ class UserDetailComment extends React.Component { ?  ({t('comment.edited')}) : null } - + +
+ {comment.hasParent && } + +
Story: {comment.asset.title} diff --git a/client/coral-admin/src/components/ui/Logo.css b/client/coral-admin/src/components/ui/Logo.css index af2758bcb..62a223683 100644 --- a/client/coral-admin/src/components/ui/Logo.css +++ b/client/coral-admin/src/components/ui/Logo.css @@ -10,16 +10,18 @@ .logo span { display: inline-block; margin-left: 10px; - font-size: 18px; + font-size: 26px; vertical-align: middle; font-weight: 500; + color: white; } .logo { - background: #E5E5E5; + background: #696969; height: 100%; width: 128px; z-index: 10; + border-right: 1px #757575 solid; } .base { diff --git a/client/coral-admin/src/containers/Layout.js b/client/coral-admin/src/containers/Layout.js index 8b119fb72..ae022f2ef 100644 --- a/client/coral-admin/src/containers/Layout.js +++ b/client/coral-admin/src/containers/Layout.js @@ -74,10 +74,8 @@ class LayoutContainer extends Component { } const mapStateToProps = (state) => ({ - auth: state.auth.toJS(), - TALK_RECAPTCHA_PUBLIC: state.config - .get('data') - .get('TALK_RECAPTCHA_PUBLIC', null) + auth: state.auth, + TALK_RECAPTCHA_PUBLIC: state.config.data.TALK_RECAPTCHA_PUBLIC, }); const mapDispatchToProps = (dispatch) => ({ diff --git a/client/coral-admin/src/containers/UserDetail.js b/client/coral-admin/src/containers/UserDetail.js index a54e70734..01b28f200 100644 --- a/client/coral-admin/src/containers/UserDetail.js +++ b/client/coral-admin/src/containers/UserDetail.js @@ -14,6 +14,7 @@ import { } from 'coral-admin/src/actions/userDetail'; import {withSetCommentStatus} from 'coral-framework/graphql/mutations'; import UserDetailComment from './UserDetailComment'; +import update from 'immutability-helper'; const commentConnectionFragment = gql` fragment CoralAdmin_Moderation_CommentConnection on CommentConnection { @@ -32,6 +33,7 @@ const slots = [ ]; class UserDetailContainer extends React.Component { + isLoadingMore = false; // status can be 'ACCEPTED' or 'REJECTED' bulkSetCommentStatus = (status) => { @@ -40,7 +42,6 @@ class UserDetailContainer extends React.Component { }); Promise.all(changes).then(() => { - this.props.data.refetch(); // some comments may have moved out of this tab this.props.clearUserDetailSelections(); // un-select everything }); } @@ -61,12 +62,53 @@ class UserDetailContainer extends React.Component { return this.props.setCommentStatus({commentId, status: 'REJECTED'}); } + loadMore = () => { + if (this.isLoadingMore) { + return; + } + + this.isLoadingMore = true; + const variables = { + limit: 10, + cursor: this.props.root.comments.endCursor, + author_id: this.props.data.variables.author_id, + statuses: this.props.data.variables.statuses, + }; + this.props.data.fetchMore({ + query: LOAD_MORE_QUERY, + variables, + updateQuery: (prev, {fetchMoreResult:{comments}}) => { + return update(prev, { + comments: { + nodes: {$push: comments.nodes}, + hasNextPage: {$set: comments.hasNextPage}, + startCursor: {$set: comments.startCursor}, + endCursor: {$set: comments.endCursor}, + }, + }); + } + }) + .then(() => { + this.isLoadingMore = false; + }) + .catch((err) => { + this.isLoadingMore = false; + throw err; + }); + }; + + componentWillReceiveProps(next) { + if (this.props.userId === null && next.userId) { + next.data.refetch(); + } + } + render () { if (!this.props.userId) { return null; } - const loading = !('user' in this.props.root) || this.props.root.user.id !== this.props.userId; + const loading = this.props.data.loading; return ; } } +const LOAD_MORE_QUERY = gql` + query CoralAdmin_Moderation_LoadMore($limit: Int = 10, $cursor: Date, $author_id: ID!, $statuses: [COMMENT_STATUS!]) { + comments(query: {limit: $limit, cursor: $cursor, author_id: $author_id, statuses: $statuses}) { + ...CoralAdmin_Moderation_CommentConnection + } + } + ${commentConnectionFragment} +`; + export const withUserDetailQuery = withQuery(gql` query CoralAdmin_UserDetail($author_id: ID!, $statuses: [COMMENT_STATUS!]) { user(id: $author_id) { @@ -90,6 +142,9 @@ export const withUserDetailQuery = withQuery(gql` id provider } + reliable { + flagger + } ${getSlotFragmentSpreads(slots, 'user')} } totalComments: commentCount(query: {author_id: $author_id}) @@ -117,8 +172,8 @@ const mapStateToProps = (state) => ({ selectedCommentIds: state.userDetail.selectedCommentIds, statuses: state.userDetail.statuses, activeTab: state.userDetail.activeTab, - bannedWords: state.settings.toJS().wordlist.banned, - suspectWords: state.settings.toJS().wordlist.suspect, + bannedWords: state.settings.wordlist.banned, + suspectWords: state.settings.wordlist.suspect, }); const mapDispatchToProps = (dispatch) => ({ diff --git a/client/coral-admin/src/containers/UserDetailComment.js b/client/coral-admin/src/containers/UserDetailComment.js index a70a9394d..9f0e3a793 100644 --- a/client/coral-admin/src/containers/UserDetailComment.js +++ b/client/coral-admin/src/containers/UserDetailComment.js @@ -9,6 +9,7 @@ export default withFragments({ body created_at status + hasParent asset { id title diff --git a/client/coral-admin/src/reducers/assets.js b/client/coral-admin/src/reducers/assets.js index 03f0be9bb..bb8751973 100644 --- a/client/coral-admin/src/reducers/assets.js +++ b/client/coral-admin/src/reducers/assets.js @@ -1,35 +1,40 @@ -import {Map, List, fromJS} from 'immutable'; import * as actions from '../constants/assets'; +import update from 'immutability-helper'; -const initialState = Map({ - byId: Map(), - ids: List(), - assets: List() -}); +const initialState = { + byId: {}, + ids: [], + assets: [] +}; export default function assets (state = initialState, action) { switch (action.type) { - case actions.FETCH_ASSETS_SUCCESS: - return replaceAssets(action, state); + case actions.FETCH_ASSETS_SUCCESS: { + const assets = action.assets.reduce((prev, curr) => { + prev[curr.id] = curr; + return prev; + }, {}); + + return update(state, { + byId: {$set: assets}, + count: {$set: action.count}, + ids: {$set: Object.keys(assets)}, + }); + } case actions.UPDATE_ASSET_STATE_REQUEST: - return state - .setIn(['byId', action.id, 'closedAt'], action.closedAt); + return update(state, { + byId: { + [action.id]: { + closedAt: {$set: action.closedAt}, + }, + }, + }); case actions.UPDATE_ASSETS: - return state - .set('assets', List(action.assets)); + return update(state, { + assets: {$set: action.assets}, + }); default: return state; } } -const replaceAssets = (action, state) => { - const assets = fromJS(action.assets.reduce((prev, curr) => { - prev[curr.id] = curr; - return prev; - }, {})); - - return state - .set('byId', assets) - .set('count', action.count) - .set('ids', List(assets.keys())); -}; diff --git a/client/coral-admin/src/reducers/auth.js b/client/coral-admin/src/reducers/auth.js index a60d73cec..a9c7f520e 100644 --- a/client/coral-admin/src/reducers/auth.js +++ b/client/coral-admin/src/reducers/auth.js @@ -1,43 +1,63 @@ -import {Map} from 'immutable'; import * as actions from '../constants/auth'; -const initialState = Map({ +const initialState = { loggedIn: false, user: null, loginError: null, loginMaxExceeded: false, passwordRequestSuccess: null -}); +}; export default function auth (state = initialState, action) { switch (action.type) { case actions.CHECK_LOGIN_REQUEST: - return state - .set('loadingUser', true); + return { + ...state, + loadingUser: true, + }; case actions.CHECK_LOGIN_FAILURE: - return state - .set('loggedIn', false) - .set('loadingUser', false) - .set('user', null); + return { + ...state, + loggedIn: false, + loadingUser: false, + user: null, + }; case actions.CHECK_LOGIN_SUCCESS: - return state - .set('loggedIn', true) - .set('loadingUser', false) - .set('user', action.user); + return { + ...state, + loggedIn: true, + loadingUser: false, + user: action.user, + }; case actions.LOGOUT: return initialState; case actions.LOGIN_SUCCESS: - return state.set('loginMaxExceeded', false).set('loginError', null); + return { + ...state, + loginMaxExceeded: false, + loginError: null, + }; case actions.LOGIN_FAILURE: - return state.set('loginError', action.message); + return { + ...state, + loginError: action.message, + }; case actions.FETCH_FORGOT_PASSWORD_REQUEST: - return state.set('passwordRequestSuccess', null); + return { + ...state, + passwordRequestSuccess: null, + }; case actions.FETCH_FORGOT_PASSWORD_SUCCESS: - return state.set('passwordRequestSuccess', 'If you have a registered account, a password reset link was sent to that email.'); + return { + ...state, + passwordRequestSuccess: 'If you have a registered account, a password reset link was sent to that email.', + }; case actions.LOGIN_MAXIMUM_EXCEEDED: - return state - .set('loginMaxExceeded', true) - .set('loginError', action.message); + return { + ...state, + loginMaxExceeded: true, + loginError: action.message, + }; default : return state; } diff --git a/client/coral-admin/src/reducers/community.js b/client/coral-admin/src/reducers/community.js index 3fba504f8..9f724c8d6 100644 --- a/client/coral-admin/src/reducers/community.js +++ b/client/coral-admin/src/reducers/community.js @@ -1,5 +1,3 @@ -import {Map} from 'immutable'; - import { FETCH_COMMENTERS_REQUEST, FETCH_COMMENTERS_FAILURE, @@ -13,8 +11,8 @@ import { HIDE_REJECT_USERNAME_DIALOG } from '../constants/community'; -const initialState = Map({ - community: Map(), +const initialState = { + community: {}, isFetchingPeople: false, errorPeople: '', accounts: [], @@ -22,72 +20,87 @@ const initialState = Map({ ascPeople: false, totalPagesPeople: 0, pagePeople: 0, - user: Map({}), + user: {}, banDialog: false, rejectUsernameDialog: false -}); +}; export default function community (state = initialState, action) { switch (action.type) { case FETCH_COMMENTERS_REQUEST : - return state - .set('isFetchingPeople', true); + return { + ...state, + isFetchingPeople: true, + }; case FETCH_COMMENTERS_FAILURE : - return state - .set('isFetchingPeople', false) - .set('errorPeople', action.error); - + return { + ...state, + isFetchingPeople: false, + errorPeople: action.error, + }; case FETCH_COMMENTERS_SUCCESS : { const {accounts, type, page, count, limit, totalPages, ...rest} = action; // eslint-disable-line - return state - .merge({ - isFetchingPeople: false, - errorPeople: '', - pagePeople: page, - countPeople: count, - limitPeople: limit, - totalPagesPeople: totalPages, - ...rest - }) - .set('accounts', accounts); // Sets to normal array + return { + ...state, + isFetchingPeople: false, + errorPeople: '', + pagePeople: page, + countPeople: count, + limitPeople: limit, + totalPagesPeople: totalPages, + ...rest, + accounts, // Sets to normal array + }; } case SET_ROLE : { - const commenters = state.get('accounts'); + const commenters = state.accounts; const idx = commenters.findIndex((el) => el.id === action.id); commenters[idx].roles[0] = action.role; - return state.set('accounts', commenters.map((id) => id)); + return { + ...state, + accounts: commenters.map((id) => id), + }; } case SET_COMMENTER_STATUS: { - const commenters = state.get('accounts'); + const commenters = state.accounts; const idx = commenters.findIndex((el) => el.id === action.id); commenters[idx].status = action.status; - return state.set('accounts', commenters.map((id) => id)); + return { + ...state, + accounts: commenters.map((id) => id), + }; } case SORT_UPDATE : - return state - .set('fieldPeople', action.sort.field) - .set('ascPeople', !state.get('ascPeople')); + return { + ...state, + fieldPeople: action.sort.field, + ascPeople: !state.ascPeople, + }; case HIDE_BANUSER_DIALOG: - return state - .set('banDialog', false); + return { + ...state, + banDialog: false, + }; case SHOW_BANUSER_DIALOG: - return state - .merge({ - user: Map(action.user), - banDialog: true - }); + return { + ...state, + user: action.user, + banDialog: true, + }; case HIDE_REJECT_USERNAME_DIALOG: - return state - .set('rejectUsernameDialog', false); + return { + ...state, + rejectUsernameDialog: false, + }; case SHOW_REJECT_USERNAME_DIALOG: - return state - .merge({ - user: Map(action.user), - rejectUsernameDialog: true - }); + return { + ...state, + user: action.user, + rejectUsernameDialog: true + }; default : return state; } diff --git a/client/coral-admin/src/reducers/config.js b/client/coral-admin/src/reducers/config.js index a5d11d6eb..310a198ed 100644 --- a/client/coral-admin/src/reducers/config.js +++ b/client/coral-admin/src/reducers/config.js @@ -1,15 +1,16 @@ -import {Map} from 'immutable'; - import * as actions from '../actions/config'; -const initialState = Map({ - data: Map({}) -}); +const initialState = { + data: {} +}; export default function config (state = initialState, action) { switch (action.type) { case actions.CONFIG_UPDATED: - return state.set('data', Map(action.data)); + return { + ...state, + data: action.data, + }; default: return state; } diff --git a/client/coral-admin/src/reducers/install.js b/client/coral-admin/src/reducers/install.js index 1f0f079ff..c6e85c69f 100644 --- a/client/coral-admin/src/reducers/install.js +++ b/client/coral-admin/src/reducers/install.js @@ -1,30 +1,29 @@ -import {Map, List} from 'immutable'; - import * as actions from '../constants/install'; +import update from 'immutability-helper'; -const initialState = Map({ +const initialState = { isLoading: false, - data: Map({ - settings: Map({ + data: { + settings: { organizationName: '', - domains: Map({ - whitelist: List() - }) - }), - user: Map({ + domains: { + whitelist: [], + } + }, + user: { username: '', email: '', password: '', confirmPassword: '' - }) - }), - errors: Map({ + } + }, + errors: { organizationName: '', username: '', email: '', password: '', confirmPassword: '' - }), + }, showErrors: false, hasError: false, error: null, @@ -44,57 +43,91 @@ const initialState = Map({ installRequest: null, installRequestError: null, alreadyInstalled: false -}); +}; export default function install (state = initialState, action) { switch (action.type) { case actions.NEXT_STEP: - return state - .set('step', state.get('step') + 1); + return { + ...state, + step: state.step + 1, + }; case actions.PREVIOUS_STEP: - return state - .set('step', state.get('step') - 1); + return { + ...state, + step: state.step - 1, + }; case actions.GO_TO_STEP: - return state - .set('step', action.step); + return { + ...state, + step: action.step, + }; case actions.UPDATE_PERMITTED_DOMAINS_SETTINGS: - return state - .setIn(['data', 'settings', 'domains', 'whitelist'], action.value); + return update(state, { + data: { + settings: { + domains: { + whitelist: {$set: action.value}, + }, + }, + }, + }); case actions.UPDATE_FORMDATA_SETTINGS: - return state - .setIn(['data', 'settings', action.name], action.value); + return update(state, { + data: { + settings: { + [action.name]: {$set: action.value}, + }, + }, + }); case actions.UPDATE_FORMDATA_USER: - return state - .setIn(['data', 'user', action.name], action.value); + return update(state, { + data: { + user: { + [action.name]: {$set: action.value}, + }, + }, + }); case actions.HAS_ERROR: - return state - .merge({ - hasError: true, - showErrors: true - }); + return { + ...state, + hasError: true, + showErrors: true, + }; case actions.ADD_ERROR: - return state - .setIn(['errors', action.name], action.error); + return update(state, { + errors: { + [action.name]: {$set: action.error}, + }, + }); case actions.CLEAR_ERRORS: - return state - .set('errors', Map()); + return { + ...state, + errors: {}, + }; case actions.INSTALL_REQUEST: - return state - .set('isLoading', true); + return { + ...state, + isLoading: true, + }; case actions.INSTALL_SUCCESS: - return state - .set('isLoading', false) - .set('installRequest', 'SUCCESS'); + return { + ...state, + isLoading: false, + installRequest: 'SUCCESS', + }; case actions.INSTALL_FAILURE: - return state - .merge({ - isLoading: false, - installRequest: 'FAILURE', - installRequestError: action.error - }); + return { + ...state, + isLoading: false, + installRequest: 'FAILURE', + installRequestError: action.error + }; case actions.CHECK_INSTALL_SUCCESS: - return state - .set('alreadyInstalled', action.installed); + return { + ...state, + alreadyInstalled: action.installed, + }; default : return state; } diff --git a/client/coral-admin/src/reducers/moderation.js b/client/coral-admin/src/reducers/moderation.js index a0cba1f5f..e0a608488 100644 --- a/client/coral-admin/src/reducers/moderation.js +++ b/client/coral-admin/src/reducers/moderation.js @@ -1,37 +1,54 @@ -import {fromJS} from 'immutable'; import * as actions from '../constants/moderation'; -const initialState = fromJS({ +const initialState = { singleView: false, modalOpen: false, storySearchVisible: false, storySearchString: '', shortcutsNoteVisible: window.localStorage.getItem('coral:shortcutsNote') || 'show', sortOrder: 'REVERSE_CHRONOLOGICAL', -}); +}; export default function moderation (state = initialState, action) { switch (action.type) { case actions.MODERATION_CLEAR_STATE: return initialState; case actions.TOGGLE_MODAL: - return state - .set('modalOpen', action.open); + return { + ...state, + modalOpen: action.open, + }; case actions.SINGLE_VIEW: - return state - .set('singleView', !state.get('singleView')); + return { + ...state, + singleView: !state.singleView, + }; case actions.HIDE_SHORTCUTS_NOTE: - return state - .set('shortcutsNoteVisible', 'hide'); + return { + ...state, + shortcutsNoteVisible: 'hide', + }; case actions.SHOW_STORY_SEARCH: - return state.set('storySearchVisible', true); + return { + ...state, + storySearchVisible: true, + }; case actions.HIDE_STORY_SEARCH: - return state.set('storySearchVisible', false); + return { + ...state, + storySearchVisible: false, + }; case actions.STORY_SEARCH_CHANGE_VALUE: - return state.set('storySearchString', action.value); + return { + ...state, + storySearchString: action.value, + }; case actions.SET_SORT_ORDER: - return state.set('sortOrder', action.order); - default : + return { + ...state, + sortOrder: action.order, + }; + default: return state; } } diff --git a/client/coral-admin/src/reducers/settings.js b/client/coral-admin/src/reducers/settings.js index 67907b327..336047e5b 100644 --- a/client/coral-admin/src/reducers/settings.js +++ b/client/coral-admin/src/reducers/settings.js @@ -1,5 +1,5 @@ -import {Map, List} from 'immutable'; import * as actions from '../actions/settings'; +import update from 'immutability-helper'; // this is initialized here because // currently you have to reload the dashboard to get new stats @@ -10,63 +10,82 @@ const DASHBOARD_WINDOW_MINUTES = 5; let then = new Date(); then.setMinutes(then.getMinutes() - DASHBOARD_WINDOW_MINUTES); -const initialState = Map({ - wordlist: Map({ - banned: List(), - suspect: List() - }), +const initialState = { + wordlist: { + banned: [], + suspect: [] + }, dashboardWindowStart: then.toISOString(), dashboardWindowEnd: new Date().toISOString(), - domains: Map({ - whitelist: List() - }), + domains: { + whitelist: [] + }, saveSettingsError: null, fetchSettingsError: null, fetchingSettings: false -}); +}; export default function settings (state = initialState, action) { switch (action.type) { case actions.SETTINGS_LOADING: - return state - .set('fetchingSettings', true) - .set('fetchSettingsError', null); + return { + ...state, + fetchingSettings: true, + fetchSettingsError: null, + }; case actions.SETTINGS_RECEIVED: - return state.merge({ + return { + ...state, fetchingSettings: false, fetchSettingsError: null, ...action.settings - }); + }; case actions.SETTINGS_FETCH_ERROR: - return state - .set('fetchingSettings', false) - .set('fetchSettingsError', action.error); + return { + ...state, + fetchingSettings: false, + fetchSettingsError: action.error, + }; case actions.SETTINGS_UPDATED: - return state.merge({ + return { + ...state, fetchingSettings: false, fetchSettingsError: null, ...action.settings - }); + }; case actions.SAVE_SETTINGS_LOADING: - return state - .set('fetchingSettings', true) - .set('saveSettingsError', null); + return { + ...state, + fetchingSettings: true, + saveSettingsError: null, + }; case actions.SAVE_SETTINGS_SUCCESS: - return state.merge({ + return { + ...state, fetchingSettings: false, fetchSettingsError: null, ...action.settings - }); + }; case actions.SAVE_SETTINGS_FAILED: - return state - .set('fetchingSettings', false) - .set('fetchSettingsError', action.error); + return { + ...state, + fetchingSettings: false, + fetchSettingsError: action.error, + }; case actions.WORDLIST_UPDATED: - return state - .setIn(['wordlist', action.listName], action.list); + return update(state, { + wordlist: { + [action.listName]: { + $set: action.list + } + } + }); case actions.DOMAINLIST_UPDATED: - return state - .setIn(['domains', action.listName], action.list); + return update(state, { + domains: { + [action.listName]: {$set: action.list}, + } + }); default: return state; } diff --git a/client/coral-admin/src/routes/Community/containers/Community.js b/client/coral-admin/src/routes/Community/containers/Community.js index a9a164ac9..b04fc0281 100644 --- a/client/coral-admin/src/routes/Community/containers/Community.js +++ b/client/coral-admin/src/routes/Community/containers/Community.js @@ -87,8 +87,8 @@ export const withCommunityQuery = withQuery(gql` }); const mapStateToProps = (state) => ({ - community: state.community.toJS(), - currentUser: state.auth.toJS().user, + community: state.community, + currentUser: state.auth.user, }); const mapDispatchToProps = (dispatch) => diff --git a/client/coral-admin/src/routes/Community/containers/Table.js b/client/coral-admin/src/routes/Community/containers/Table.js index 8bd5395e4..5d4e4914f 100644 --- a/client/coral-admin/src/routes/Community/containers/Table.js +++ b/client/coral-admin/src/routes/Community/containers/Table.js @@ -23,7 +23,7 @@ class TableContainer extends Component { } const mapStateToProps = (state) => ({ - commenters: state.community.get('accounts'), + commenters: state.community.accounts, }); const mapDispatchToProps = (dispatch) => diff --git a/client/coral-admin/src/routes/Configure/containers/Configure.js b/client/coral-admin/src/routes/Configure/containers/Configure.js index c68b39e0c..aff1e57b2 100644 --- a/client/coral-admin/src/routes/Configure/containers/Configure.js +++ b/client/coral-admin/src/routes/Configure/containers/Configure.js @@ -23,8 +23,8 @@ class ConfigureContainer extends Component { } const mapStateToProps = (state) => ({ - auth: state.auth.toJS(), - settings: state.settings.toJS() + auth: state.auth, + settings: state.settings }); const mapDispatchToProps = (dispatch) => diff --git a/client/coral-admin/src/routes/Dashboard/components/ActivityWidget.js b/client/coral-admin/src/routes/Dashboard/components/ActivityWidget.js index 5f974971c..d92b2bd14 100644 --- a/client/coral-admin/src/routes/Dashboard/components/ActivityWidget.js +++ b/client/coral-admin/src/routes/Dashboard/components/ActivityWidget.js @@ -17,11 +17,11 @@ const ActivityWidget = ({assets}) => { ? assets.map((asset) => { return (
- Moderate + Moderate

{asset.commentCount}

- +

{asset.title}

- +

{asset.author} — Published: {new Date(asset.created_at).toLocaleDateString()}

); diff --git a/client/coral-admin/src/routes/Dashboard/components/FlagWidget.js b/client/coral-admin/src/routes/Dashboard/components/FlagWidget.js index ef0974fbd..ef4a6857e 100644 --- a/client/coral-admin/src/routes/Dashboard/components/FlagWidget.js +++ b/client/coral-admin/src/routes/Dashboard/components/FlagWidget.js @@ -24,11 +24,11 @@ const FlagWidget = ({assets}) => { return (
- Moderate + Moderate

{flagSummary ? flagSummary.actionCount : 0}

- +

{asset.title}

- +

{asset.author} — Published: {new Date(asset.created_at).toLocaleDateString()}

); diff --git a/client/coral-admin/src/routes/Dashboard/components/LikeWidget.js b/client/coral-admin/src/routes/Dashboard/components/LikeWidget.js index 2188e38dd..a61f888bf 100644 --- a/client/coral-admin/src/routes/Dashboard/components/LikeWidget.js +++ b/client/coral-admin/src/routes/Dashboard/components/LikeWidget.js @@ -19,11 +19,11 @@ const LikeWidget = ({assets}) => { const likeSummary = asset.action_summaries.find((s) => s.type === 'LikeAssetActionSummary'); return (
- Moderate + Moderate

{likeSummary ? likeSummary.actionCount : 0}

- +

{asset.title}

- +

{asset.author} — Published: {new Date(asset.created_at).toLocaleDateString()}

); diff --git a/client/coral-admin/src/routes/Dashboard/containers/Dashboard.js b/client/coral-admin/src/routes/Dashboard/containers/Dashboard.js index ea1fb2b6c..74faedcf7 100644 --- a/client/coral-admin/src/routes/Dashboard/containers/Dashboard.js +++ b/client/coral-admin/src/routes/Dashboard/containers/Dashboard.js @@ -54,8 +54,8 @@ export const witDashboardQuery = withQuery(gql` const mapStateToProps = (state) => { return { - settings: state.settings.toJS(), - moderation: state.moderation.toJS() + settings: state.settings, + moderation: state.moderation }; }; diff --git a/client/coral-admin/src/routes/Install/containers/Install.js b/client/coral-admin/src/routes/Install/containers/Install.js index 5dcb35705..442127e47 100644 --- a/client/coral-admin/src/routes/Install/containers/Install.js +++ b/client/coral-admin/src/routes/Install/containers/Install.js @@ -35,7 +35,7 @@ InstallContainer.contextTypes = { }; const mapStateToProps = (state) => ({ - install: state.install.toJS() + install: state.install }); const mapDispatchToProps = (dispatch) => diff --git a/client/coral-admin/src/routes/Moderation/components/Comment.js b/client/coral-admin/src/routes/Moderation/components/Comment.js index c6ec0fd4c..c73d15eaa 100644 --- a/client/coral-admin/src/routes/Moderation/components/Comment.js +++ b/client/coral-admin/src/routes/Moderation/components/Comment.js @@ -2,6 +2,7 @@ import React, {PropTypes} from 'react'; import {Link} from 'react-router'; import {Icon} from 'coral-ui'; +import ReplyBadge from 'coral-admin/src/components/ReplyBadge'; import FlagBox from 'coral-admin/src/components/FlagBox'; import styles from './styles.css'; import CommentType from 'coral-admin/src/components/CommentType'; @@ -20,6 +21,31 @@ import t, {timeago} from 'coral-framework/services/i18n'; class Comment extends React.Component { + showSuspendUserDialog = () => { + const {comment, showSuspendUserDialog} = this.props; + return showSuspendUserDialog({ + userId: comment.user.id, + username: comment.user.username, + commentId: comment.id, + commentStatus: comment.status, + }); + }; + + showBanUserDialog = () => { + const {comment, showBanUserDialog} = this.props; + return showBanUserDialog({ + userId: comment.user.id, + username: comment.user.username, + commentId: comment.id, + commentStatus: comment.status, + }); + }; + + viewUserDetail = () => { + const {viewUserDetail, comment} = this.props; + return viewUserDetail(comment.user.id); + }; + render() { const { actions = [], @@ -29,7 +55,12 @@ class Comment extends React.Component { bannedWords, selected, className, - ...props + data, + root, + currentUserId, + currentAsset, + acceptComment, + rejectComment, } = this.props; const flagActionSummaries = getActionSummary('FlagActionSummary', comment); @@ -38,19 +69,7 @@ class Comment extends React.Component { let selectionStateCSS = selected ? 'mdl-shadow--16dp' : 'mdl-shadow--2dp'; - const showSuspenUserDialog = () => props.showSuspendUserDialog({ - userId: comment.user.id, - username: comment.user.username, - commentId: comment.id, - commentStatus: comment.status, - }); - - const showBanUserDialog = () => props.showBanUserDialog({ - userId: comment.user.id, - username: comment.user.username, - commentId: comment.id, - commentStatus: comment.status, - }); + const queryData = {root, comment, asset: comment.asset}; return (
  • { ( - viewUserDetail(comment.user.id)}> + {comment.user.username} ) @@ -75,27 +94,26 @@ class Comment extends React.Component { ?  ({t('comment.edited')}) : null } - {props.currentUserId !== comment.user.id && + {currentUserId !== comment.user.id && + onClick={this.showSuspendUserDialog}> Suspend User + onClick={this.showBanUserDialog}> Ban User }
    + {comment.hasParent && }
  • @@ -103,7 +121,7 @@ class Comment extends React.Component {
    Story: {comment.asset.title} - {!props.currentAsset && + {!currentAsset && {t('modqueue.moderate')}}
    @@ -124,10 +142,9 @@ class Comment extends React.Component {

    @@ -150,30 +167,28 @@ class Comment extends React.Component { acceptComment={() => (comment.status === 'ACCEPTED' ? null - : props.acceptComment({commentId: comment.id}))} + : acceptComment({commentId: comment.id}))} rejectComment={() => (comment.status === 'REJECTED' ? null - : props.rejectComment({commentId: comment.id}))} + : rejectComment({commentId: comment.id}))} /> ); })}
    {flagActions && flagActions.length ? ({ + key: queue, + name: queueConfig[queue].name, + icon: queueConfig[queue].icon, + count: root[`${queue}Count`] + })); return (
    @@ -139,16 +125,10 @@ export default class Moderation extends Component { />
    diff --git a/client/coral-admin/src/routes/Moderation/components/ModerationMenu.js b/client/coral-admin/src/routes/Moderation/components/ModerationMenu.js index 62bbd4d2e..7b427ac54 100644 --- a/client/coral-admin/src/routes/Moderation/components/ModerationMenu.js +++ b/client/coral-admin/src/routes/Moderation/components/ModerationMenu.js @@ -9,16 +9,10 @@ import cn from 'classnames'; import t from 'coral-framework/services/i18n'; const ModerationMenu = ({ - asset = {}, - allCount, - approvedCount, - premodCount, - newCount, - rejectedCount, - reportedCount, + asset = {}, + items, selectSort, sort, - premodEnabled, getModPath, activeTab }) => { @@ -27,49 +21,15 @@ const ModerationMenu = ({
    - - { - premodEnabled ? ( - - {t('modqueue.premod')} - - ) : ( - - {t('modqueue.new')} - - ) - } - - - {t('modqueue.reported')} - - - {t('modqueue.approved')} - - - {t('modqueue.rejected')} - - - {t('modqueue.all')} - + {items.map((queue) => + + {queue.name} + + )}
    { + return handleCommentChange(root, comment, this.props.data.variables.sort, notify, queueConfig, this.activeTab); + }; + get activeTab() { - const {root: {asset, settings}, router, route} = this.props; + const {root: {asset, settings}} = this.props; + const id = getAssetId(this.props); + const tab = getTab(this.props); // Grab premod from asset or from settings - const premod = !router.params.id ? settings.moderation : asset.settings.moderation; + const premod = !id ? settings.moderation : asset.settings.moderation; const queue = isPremod(premod) ? 'premod' : 'new'; - const activeTab = route.path && route.path !== ':id' ? route.path : queue; + const activeTab = tab ? tab : queue; return activeTab; } @@ -57,15 +78,10 @@ class ModerationContainer extends Component { variables, updateQuery: (prev, {subscriptionData: {data: {commentAccepted: comment}}}) => { const user = comment.status_history[comment.status_history.length - 1].assigned_by; - const sort = this.props.moderation.sortOrder; const notify = this.props.auth.user.id === user.id - ? {} - : { - activeQueue: this.activeTab, - text: t('modqueue.notify_accepted', user.username, prepareNotificationText(comment.body)), - anyQueue: false, - }; - return handleCommentChange(prev, comment, sort, notify); + ? '' + : t('modqueue.notify_accepted', user.username, prepareNotificationText(comment.body)); + return this.handleCommentChange(prev, comment, notify); }, }); @@ -74,15 +90,10 @@ class ModerationContainer extends Component { variables, updateQuery: (prev, {subscriptionData: {data: {commentRejected: comment}}}) => { const user = comment.status_history[comment.status_history.length - 1].assigned_by; - const sort = this.props.moderation.sortOrder; const notify = this.props.auth.user.id === user.id - ? {} - : { - activeQueue: this.activeTab, - text: t('modqueue.notify_rejected', user.username, prepareNotificationText(comment.body)), - anyQueue: false, - }; - return handleCommentChange(prev, comment, sort, notify); + ? '' + : t('modqueue.notify_rejected', user.username, prepareNotificationText(comment.body)); + return this.handleCommentChange(prev, comment, notify); }, }); @@ -90,13 +101,8 @@ class ModerationContainer extends Component { document: COMMENT_EDITED_SUBSCRIPTION, variables, updateQuery: (prev, {subscriptionData: {data: {commentEdited: comment}}}) => { - const sort = this.props.moderation.sortOrder; - const notify = { - activeQueue: this.activeTab, - text: t('modqueue.notify_edited', comment.user.username, prepareNotificationText(comment.body)), - anyQueue: false, - }; - return handleCommentChange(prev, comment, sort, notify); + const notify = t('modqueue.notify_edited', comment.user.username, prepareNotificationText(comment.body)); + return this.handleCommentChange(prev, comment, notify); }, }); @@ -105,13 +111,8 @@ class ModerationContainer extends Component { variables, updateQuery: (prev, {subscriptionData: {data: {commentFlagged: comment}}}) => { const user = comment.actions[comment.actions.length - 1].user; - const sort = this.props.moderation.sortOrder; - const notify = { - activeQueue: this.activeTab, - text: t('modqueue.notify_flagged', user.username, prepareNotificationText(comment.body)), - anyQueue: true, - }; - return handleCommentChange(prev, comment, sort, notify); + const notify = t('modqueue.notify_flagged', user.username, prepareNotificationText(comment.body)); + return this.handleCommentChange(prev, comment, notify); }, }); @@ -160,28 +161,9 @@ class ModerationContainer extends Component { cursor: this.props.root[tab].endCursor, sort: this.props.data.variables.sort, asset_id: this.props.data.variables.asset_id, + statuses: queueConfig[tab].statuses, + action_type: queueConfig[tab].action_type, }; - switch(tab) { - case 'all': - variables.statuses = null; - break; - case 'new': - variables.statuses = ['NONE', 'PREMOD']; - break; - case 'approved': - variables.statuses = ['ACCEPTED']; - break; - case 'premod': - variables.statuses = ['PREMOD']; - break; - case 'reported': - variables.statuses = ['NONE', 'PREMOD']; - variables.action_type = 'FLAG'; - break; - case 'rejected': - variables.statuses = ['REJECTED']; - break; - } return this.props.data.fetchMore({ query: LOAD_MORE_QUERY, variables, @@ -199,7 +181,8 @@ class ModerationContainer extends Component { }; render () { - const {root, root: {asset, settings}, data, params: {id: assetId}} = this.props; + const {root, root: {asset, settings}, data} = this.props; + const assetId = getAssetId(this.props); if (data.error) { return
    Error
    ; @@ -222,6 +205,14 @@ class ModerationContainer extends Component { return ; } + const premodEnabled = assetId ? isPremod(asset.settings.moderation) : isPremod(settings.moderation); + const currentQueueConfig = Object.assign({}, queueConfig); + if (premodEnabled) { + delete currentQueueConfig.new; + } else { + delete currentQueueConfig.premod; + } + return ; } } @@ -314,49 +306,25 @@ const commentConnectionFragment = gql` const withModQueueQuery = withQuery(gql` query CoralAdmin_Moderation($asset_id: ID, $sort: SORT_ORDER, $allAssets: Boolean!) { - all: comments(query: { - statuses: [NONE, PREMOD, ACCEPTED, REJECTED], - asset_id: $asset_id, - sort: $sort - }) { - ...CoralAdmin_Moderation_CommentConnection - } - new: comments(query: { - statuses: [NONE, PREMOD], - asset_id: $asset_id, - sort: $sort - }) { - ...CoralAdmin_Moderation_CommentConnection - } - approved: comments(query: { - statuses: [ACCEPTED], - asset_id: $asset_id, - sort: $sort - }) { - ...CoralAdmin_Moderation_CommentConnection - } - premod: comments(query: { - statuses: [PREMOD], + ${Object.keys(queueConfig).map((queue) => ` + ${queue}: comments(query: { + ${queueConfig[queue].statuses ? `statuses: [${queueConfig[queue].statuses.join(', ')}],` : ''} + ${queueConfig[queue].tags ? `tags: ["${queueConfig[queue].tags.join('", "')}"],` : ''} + ${queueConfig[queue].action_type ? `action_type: ${queueConfig[queue].action_type}` : ''} asset_id: $asset_id, sort: $sort - }) { - ...CoralAdmin_Moderation_CommentConnection - } - reported: comments(query: { - action_type: FLAG, + }) { + ...CoralAdmin_Moderation_CommentConnection + } + `)} + ${Object.keys(queueConfig).map((queue) => ` + ${queue}Count: commentCount(query: { + ${queueConfig[queue].statuses ? `statuses: [${queueConfig[queue].statuses.join(', ')}],` : ''} + ${queueConfig[queue].tags ? `tags: ["${queueConfig[queue].tags.join('", "')}"],` : ''} + ${queueConfig[queue].action_type ? `action_type: ${queueConfig[queue].action_type}` : ''} asset_id: $asset_id, - statuses: [NONE, PREMOD], - sort: $sort - }) { - ...CoralAdmin_Moderation_CommentConnection - } - rejected: comments(query: { - statuses: [REJECTED], - asset_id: $asset_id, - sort: $sort - }) { - ...CoralAdmin_Moderation_CommentConnection - } + }) + `)} asset(id: $asset_id) @skip(if: $allAssets) { id title @@ -365,30 +333,6 @@ const withModQueueQuery = withQuery(gql` moderation } } - allCount: commentCount(query: { - asset_id: $asset_id - }) - newCount: commentCount(query: { - statuses: [NONE, PREMOD], - asset_id: $asset_id - }) - approvedCount: commentCount(query: { - statuses: [ACCEPTED], - asset_id: $asset_id - }) - premodCount: commentCount(query: { - statuses: [PREMOD], - asset_id: $asset_id - }) - rejectedCount: commentCount(query: { - statuses: [REJECTED], - asset_id: $asset_id - }) - reportedCount: commentCount(query: { - action_type: FLAG, - asset_id: $asset_id, - statuses: [NONE, PREMOD] - }) settings { organizationName moderation @@ -396,11 +340,12 @@ const withModQueueQuery = withQuery(gql` } ${commentConnectionFragment} `, { - options: ({params: {id = null}, moderation: {sortOrder}}) => { + options: (props) => { + const id = getAssetId(props); return { variables: { asset_id: id, - sort: sortOrder, + sort: props.moderation.sortOrder, allAssets: id === null } }; @@ -409,33 +354,18 @@ const withModQueueQuery = withQuery(gql` const withQueueCountPolling = withQuery(gql` query CoralAdmin_ModerationCountPoll($asset_id: ID) { - allCount: commentCount(query: { - asset_id: $asset_id - }) - newCount: commentCount(query: { - statuses: [NONE, PREMOD], - asset_id: $asset_id - }) - approvedCount: commentCount(query: { - statuses: [ACCEPTED], - asset_id: $asset_id - }) - premodCount: commentCount(query: { - statuses: [PREMOD], - asset_id: $asset_id - }) - rejectedCount: commentCount(query: { - statuses: [REJECTED], - asset_id: $asset_id - }) - reportedCount: commentCount(query: { - action_type: FLAG, - asset_id: $asset_id, - statuses: [NONE, PREMOD] - }) + ${Object.keys(queueConfig).map((queue) => ` + ${queue}Count: commentCount(query: { + ${queueConfig[queue].statuses ? `statuses: [${queueConfig[queue].statuses.join(', ')}],` : ''} + ${queueConfig[queue].tags ? `tags: ["${queueConfig[queue].tags.join('", "')}"],` : ''} + ${queueConfig[queue].action_type ? `action_type: ${queueConfig[queue].action_type}` : ''} + asset_id: $asset_id, + }) + `)} } `, { - options: ({params: {id = null}}) => { + options: (props) => { + const id = getAssetId(props); return { pollInterval: 5000, variables: { @@ -446,9 +376,9 @@ const withQueueCountPolling = withQuery(gql` }); const mapStateToProps = (state) => ({ - moderation: state.moderation.toJS(), - settings: state.settings.toJS(), - auth: state.auth.toJS(), + moderation: state.moderation, + settings: state.settings, + auth: state.auth, }); const mapDispatchToProps = (dispatch) => ({ diff --git a/client/coral-admin/src/graphql/utils.js b/client/coral-admin/src/routes/Moderation/graphql.js similarity index 74% rename from client/coral-admin/src/graphql/utils.js rename to client/coral-admin/src/routes/Moderation/graphql.js index f729cc0ea..0d4991f72 100644 --- a/client/coral-admin/src/graphql/utils.js +++ b/client/coral-admin/src/routes/Moderation/graphql.js @@ -1,7 +1,6 @@ import update from 'immutability-helper'; import * as notification from 'coral-admin/src/services/notification'; -const queues = ['all', 'premod', 'reported', 'approved', 'rejected', 'new']; const limit = 10; const ascending = (a, b) => { @@ -67,32 +66,24 @@ function addCommentToQueue(root, queue, comment, sort) { /** * getCommentQueues determines in which queues a comment should be placed. */ -function getCommentQueues(comment) { - const queues = ['all']; - const isFlagged = comment.actions && comment.actions.some((a) => a.__typename === 'FlagAction'); - - switch(comment.status) { - case 'ACCEPTED': - queues.push('approved'); - break; - case 'REJECTED': - queues.push('rejected'); - break; - case 'PREMOD': - queues.push('premod'); - queues.push('new'); - if (isFlagged) { - queues.push('reported'); +function getCommentQueues(comment, queueConfig) { + const queues = []; + Object.keys(queueConfig).forEach((key) => { + const {action_type, statuses, tags} = queueConfig[key]; + let addToQueues = false; + if (statuses && statuses.indexOf(comment.status) >= 0) { + addToQueues = true; } - break; - case 'NONE': - queues.push('new'); - if (isFlagged) { - queues.push('reported'); + if (tags && comment.tags && comment.tags.some((tagLink) => tags.indexOf(tagLink.tag.name) >= 0)) { + addToQueues = true; } - break; - } - + if (action_type && comment.actions && comment.actions.some((a) => a.__typename.toLowerCase() === `${action_type}action`)) { + addToQueues = true; + } + if (addToQueues) { + queues.push(key); + } + }); return queues; } @@ -106,42 +97,42 @@ function getCommentQueues(comment) { * @param {string} notify.text notification text to show * @param {bool} notify.anyQueue if true show the notification when the comment is shown * in the current active queue besides the 'all' queue. + * @param {Object} queueConfig queue configuration * @return {Object} next state of the store */ -export function handleCommentChange(root, comment, sort, notify) { +export function handleCommentChange(root, comment, sort, notify, queueConfig, activeQueue) { let next = root; - const nextQueues = getCommentQueues(comment); + const nextQueues = getCommentQueues(comment, queueConfig); let notificationShown = false; const showNotificationOnce = () => { if (notificationShown) { return; } - notification.info(notify.text); + notification.info(notify); notificationShown = true; }; - queues.forEach((queue) => { + Object.keys(queueConfig).forEach((queue) => { if (nextQueues.indexOf(queue) >= 0) { if (!queueHasComment(next, queue, comment.id)) { next = addCommentToQueue(next, queue, comment, sort); - if (notify && notify.activeQueue === queue && shouldCommentBeAdded(next, queue, comment, sort)) { + if (notify && activeQueue === queue && shouldCommentBeAdded(next, queue, comment, sort)) { showNotificationOnce(comment); } } } else if(queueHasComment(next, queue, comment.id)){ next = removeCommentFromQueue(next, queue, comment.id); - if (notify && notify.activeQueue === queue) { + if (notify && activeQueue === queue) { showNotificationOnce(comment); } } if ( notify - && (queue === 'all' || notify.anyQueue) && queueHasComment(next, queue, comment.id) - && notify.activeQueue === queue + && activeQueue === queue ) { showNotificationOnce(comment); } diff --git a/client/coral-admin/src/routes/Moderation/queueConfig.js b/client/coral-admin/src/routes/Moderation/queueConfig.js new file mode 100644 index 000000000..b9e9e5320 --- /dev/null +++ b/client/coral-admin/src/routes/Moderation/queueConfig.js @@ -0,0 +1,37 @@ +import t from 'coral-framework/services/i18n'; +import {getModQueueConfigs} from 'coral-framework/helpers/plugins'; + +export default { + premod: { + statuses: ['PREMOD'], + icon: 'access_time', + name: t('modqueue.premod'), + }, + new: { + statuses: ['NONE', 'PREMOD'], + icon: 'question_answer', + name: t('modqueue.new'), + }, + reported: { + action_type: 'FLAG', + statuses: ['NONE', 'PREMOD'], + icon: 'flag', + name: t('modqueue.reported'), + }, + approved: { + statuses: ['ACCEPTED'], + icon: 'check', + name: t('modqueue.approved'), + }, + rejected: { + statuses: ['REJECTED'], + icon: 'close', + name: t('modqueue.rejected'), + }, + all: { + statuses: ['NONE', 'PREMOD', 'ACCEPTED', 'REJECTED'], + icon: 'question_answer', + name: t('modqueue.all'), + }, + ...getModQueueConfigs(), +}; diff --git a/client/coral-admin/src/routes/Stories/containers/Stories.js b/client/coral-admin/src/routes/Stories/containers/Stories.js index 450efcf74..f645f310c 100644 --- a/client/coral-admin/src/routes/Stories/containers/Stories.js +++ b/client/coral-admin/src/routes/Stories/containers/Stories.js @@ -12,7 +12,7 @@ class StoriesContainer extends Component { } const mapStateToProps = (state) => ({ - assets: state.assets.toJS() + assets: state.assets }); const mapDispatchToProps = (dispatch) => diff --git a/client/coral-configure/containers/ConfigureStreamContainer.js b/client/coral-configure/containers/ConfigureStreamContainer.js index e7b937030..1db8f497a 100644 --- a/client/coral-configure/containers/ConfigureStreamContainer.js +++ b/client/coral-configure/containers/ConfigureStreamContainer.js @@ -15,7 +15,7 @@ class ConfigureStreamContainer extends Component { this.state = { changed: false, - dirtySettings: props.asset.settings, + dirtySettings: {...props.asset.settings}, closedAt: !props.asset.isClosed ? 'open' : 'closed' }; @@ -48,26 +48,28 @@ class ConfigureStreamContainer extends Component { changed: false }); }, 300); - - // this.props.loadAsset(this.props.data.asset); } } handleChange (e) { + const changes = {}; - // TODO: Don’t directly manipulate state and make state change immutable. if (e.target && e.target.id === 'qboxenable') { - this.state.dirtySettings.questionBoxEnable = e.target.checked; + changes.questionBoxEnable = e.target.checked; } if (e.target && e.target.id === 'qboxcontent') { - this.state.dirtySettings.questionBoxContent = e.target.value; + changes.questionBoxContent = e.target.value; } if (e.target && e.target.id === 'plinksenable') { - this.state.dirtySettings.premodLinksEnable = e.target.value; + changes.premodLinksEnable = e.target.value; } this.setState({ - changed: true + changed: true, + dirtySettings: { + ...this.state.dirtySettings, + ...changes, + }, }); } @@ -119,7 +121,7 @@ class ConfigureStreamContainer extends Component { } const mapStateToProps = (state) => ({ - asset: state.asset.toJS() + asset: state.asset }); const mapDispatchToProps = (dispatch) => ({ diff --git a/client/coral-embed-stream/src/components/AllCommentsPane.js b/client/coral-embed-stream/src/components/AllCommentsPane.js index 7166aa6e9..c141f0618 100644 --- a/client/coral-embed-stream/src/components/AllCommentsPane.js +++ b/client/coral-embed-stream/src/components/AllCommentsPane.js @@ -5,7 +5,7 @@ import IgnoredCommentTombstone from './IgnoredCommentTombstone'; import NewCount from './NewCount'; import {TransitionGroup} from 'react-transition-group'; import {forEachError} from 'coral-framework/utils'; -import Comment from '../components/Comment'; +import Comment from '../containers/Comment'; const hasComment = (nodes, id) => nodes.some((node) => node.id === id); @@ -93,6 +93,7 @@ class AllCommentsPane extends React.Component { viewNewComments = () => { this.setState(resetCursors); + this.props.emit('ui.AllCommentsPane.viewNewComments'); }; // getVisibileComments returns a list containing comments @@ -142,6 +143,7 @@ class AllCommentsPane extends React.Component { charCountEnable, maxCharCount, editComment, + emit, } = this.props; const {loadingState} = this.state; @@ -181,6 +183,7 @@ class AllCommentsPane extends React.Component { charCountEnable={charCountEnable} maxCharCount={maxCharCount} editComment={editComment} + emit={emit} />; })} diff --git a/client/coral-embed-stream/src/components/Comment.css b/client/coral-embed-stream/src/components/Comment.css index 32a034f51..578df2d80 100644 --- a/client/coral-embed-stream/src/components/Comment.css +++ b/client/coral-embed-stream/src/components/Comment.css @@ -163,6 +163,7 @@ .header { display: flex; align-items: center; + margin: 10px 0; } .content { @@ -171,3 +172,7 @@ .footer { min-height: 10px; } + +.username { + margin-right: 5px; +} \ No newline at end of file diff --git a/client/coral-embed-stream/src/components/Comment.js b/client/coral-embed-stream/src/components/Comment.js index 34f672d8a..85dee9392 100644 --- a/client/coral-embed-stream/src/components/Comment.js +++ b/client/coral-embed-stream/src/components/Comment.js @@ -1,7 +1,6 @@ import React from 'react'; import PropTypes from 'prop-types'; -import AuthorName from 'talk-plugin-author-name/AuthorName'; import TagLabel from 'talk-plugin-tag-label/TagLabel'; import PubDate from 'talk-plugin-pubdate/PubDate'; import {ReplyBox, ReplyButton} from 'talk-plugin-replies'; @@ -16,14 +15,17 @@ import mapValues from 'lodash/mapValues'; import LoadMore from './LoadMore'; import {getEditableUntilDate} from './util'; +import {findCommentWithId} from '../graphql/utils'; import {TopRightMenu} from './TopRightMenu'; import CommentContent from './CommentContent'; import Slot from 'coral-framework/components/Slot'; import IgnoredCommentTombstone from './IgnoredCommentTombstone'; import InactiveCommentLabel from './InactiveCommentLabel'; import {EditableCommentContent} from './EditableCommentContent'; -import {getActionSummary, iPerformedThisAction, forEachError, isCommentActive} from 'coral-framework/utils'; +import {getActionSummary, iPerformedThisAction, forEachError, isCommentActive, getShallowChanges} from 'coral-framework/utils'; import t from 'coral-framework/services/i18n'; +import CommentContainer from '../containers/Comment'; +import {CommentAuthorName} from 'coral-framework/components'; const isStaff = (tags) => !tags.every((t) => t.tag.name !== 'STAFF'); const hasTag = (tags, lookupTag) => !!tags.filter((t) => t.tag.name === lookupTag).length; @@ -72,6 +74,17 @@ const ActionButton = ({children}) => { ); }; +// Determine whether the comment with id is in the part of the comments tree. +function containsCommentId(props, id) { + if (props.comment.id === id) { + return true; + } + if (props.comment.replies) { + return findCommentWithId(props.comment.replies.nodes, id); + } + return false; +} + export default class Comment extends React.Component { constructor(props) { @@ -86,7 +99,6 @@ export default class Comment extends React.Component { // Whether the comment should be editable (e.g. after a commenter clicking the 'Edit' button on their own comment) isEditing: false, replyBoxVisible: false, - animateEnter: false, loadingState: '', ...resetCursors({}, props), }; @@ -112,20 +124,21 @@ export default class Comment extends React.Component { } } - componentWillEnter(callback) { - callback(); - const userId = this.props.currentUser ? this.props.currentUser.id : null; - if (this.props.comment.id.indexOf('pending') >= 0) { - return; - } - if (userId && this.props.comment.user.id === userId) { + shouldComponentUpdate(nextProps, nextState) { - // This comment was just added by currentUser. - if (Date.now() - Number(new Date(this.props.comment.created_at)) < 30 * 1000) { - return; + // Specifically handle `activeReplyBox` if it is the only change. + const changes = [...getShallowChanges(this.props, nextProps), ...getShallowChanges(this.state, nextState)]; + if (changes.length === 1 && changes[0] === 'activeReplyBox') { + if ( + !containsCommentId(this.props, this.props.activeReplyBox) && + !containsCommentId(nextProps, nextProps.activeReplyBox) + ) { + return false; } } - this.setState({animateEnter: true}); + + // Prevent Slot from rerendering when no props has shallowly changed. + return changes.length !== 0; } static propTypes = { @@ -180,6 +193,9 @@ export default class Comment extends React.Component { // edit a comment, passed (id, asset_id, { body }) editComment: PropTypes.func, + + // emit custom events + emit: PropTypes.func.isRequired, } editComment = (...args) => { @@ -207,7 +223,7 @@ export default class Comment extends React.Component { } loadNewReplies = () => { - const {replies, replyCount, id} = this.props.comment; + const {comment: {replies, replyCount, id}, emit} = this.props; if (replyCount > replies.nodes.length) { this.setState({loadingState: 'loading'}); this.props.loadMore(id) @@ -221,9 +237,11 @@ export default class Comment extends React.Component { this.setState({loadingState: 'error'}); forEachError(error, ({msg}) => {this.props.addNotification('error', msg);}); }); + emit('ui.Comment.showMoreReplies', {id}); return; } this.setState(resetCursors); + emit('ui.Comment.showMoreReplies', {id}); }; showReplyBox = () => { @@ -239,6 +257,10 @@ export default class Comment extends React.Component { return; } + commentPostedHandler = () => { + this.props.setActiveReplyBox(''); + } + // getVisibileReplies returns a list containing comments // which were authored by current user or comes before the `idCursor`. getVisibileReplies() { @@ -314,6 +336,8 @@ export default class Comment extends React.Component { showSignInDialog, liveUpdates, commentIsIgnored, + animateEnter, + emit, commentClassNames = [] } = this.props; @@ -366,7 +390,7 @@ export default class Comment extends React.Component { styles[`rootLevel${depth}`], { ...conditionalClassNames, - [styles.enter]: this.state.animateEnter, + [styles.enter]: animateEnter, }, ); @@ -386,10 +410,13 @@ export default class Comment extends React.Component { // props that are passed down the slots. const slotProps = { data, + depth, + }; + + const queryData = { root, asset, comment, - depth, }; return ( @@ -400,16 +427,24 @@ export default class Comment extends React.Component {
    -
    +
    +
    + + -
    - {isStaff(comment.tags) ? Staff : null} @@ -425,6 +460,7 @@ export default class Comment extends React.Component { className={styles.commentInfoBar} fill="commentInfoBar" {...slotProps} + queryData={queryData} /> { isActive && (currentUser && (comment.user.id === currentUser.id)) && @@ -471,6 +507,7 @@ export default class Comment extends React.Component { fill="commentContent" defaultComponent={CommentContent} {...slotProps} + queryData={queryData} />
    } @@ -482,6 +519,7 @@ export default class Comment extends React.Component { {!disableReply && @@ -498,6 +536,7 @@ export default class Comment extends React.Component { fill="commentActions" wrapperComponent={ActionButton} {...slotProps} + queryData={queryData} inline /> @@ -523,9 +562,7 @@ export default class Comment extends React.Component { {activeReplyBox === comment.id ? { - setActiveReplyBox(''); - }} + commentPostedHandler={this.commentPostedHandler} charCountEnable={charCountEnable} maxCharCount={maxCharCount} setActiveReplyBox={setActiveReplyBox} @@ -541,7 +578,7 @@ export default class Comment extends React.Component { {view.map((reply) => { return commentIsIgnored(reply) ? - : ; })} diff --git a/client/coral-embed-stream/src/components/Embed.js b/client/coral-embed-stream/src/components/Embed.js index f918b7a16..a74028627 100644 --- a/client/coral-embed-stream/src/components/Embed.js +++ b/client/coral-embed-stream/src/components/Embed.js @@ -28,7 +28,7 @@ export default class Embed extends React.Component { }; render() { - const {activeTab, commentId, auth: {showSignInDialog, signInDialogFocus}, blurSignInDialog, focusSignInDialog, hideSignInDialog} = this.props; + const {activeTab, commentId, root, data, auth: {showSignInDialog, signInDialogFocus}, blurSignInDialog, focusSignInDialog, hideSignInDialog} = this.props; const {user} = this.props.auth; const hasHighlightedComment = !!commentId; @@ -64,14 +64,18 @@ export default class Embed extends React.Component { } - + - + diff --git a/client/coral-embed-stream/src/components/Stream.js b/client/coral-embed-stream/src/components/Stream.js index 1e0ff7ea9..b37d232f7 100644 --- a/client/coral-embed-stream/src/components/Stream.js +++ b/client/coral-embed-stream/src/components/Stream.js @@ -1,7 +1,7 @@ import React from 'react'; import PropTypes from 'prop-types'; import {StreamError} from './StreamError'; -import Comment from '../components/Comment'; +import Comment from '../containers/Comment'; import SuspendedAccount from './SuspendedAccount'; import Slot from 'coral-framework/components/Slot'; import InfoBox from 'talk-plugin-infobox/InfoBox'; @@ -10,16 +10,16 @@ import {ModerationLink} from 'talk-plugin-moderation'; import RestrictedMessageBox from 'coral-framework/components/RestrictedMessageBox'; import t, {timeago} from 'coral-framework/services/i18n'; -import {getSlotComponents} from 'coral-framework/helpers/plugins'; import CommentBox from 'talk-plugin-commentbox/CommentBox'; import QuestionBox from 'talk-plugin-questionbox/QuestionBox'; import {isCommentActive} from 'coral-framework/utils'; -import {Button, TabBar, Tab, TabCount, TabContent, TabPane} from 'coral-ui'; +import {Button, Tab, TabCount, TabPane} from 'coral-ui'; import cn from 'classnames'; import {getTopLevelParent, attachCommentToParent} from '../graphql/utils'; import AllCommentsPane from './AllCommentsPane'; import AutomaticAssetClosure from '../containers/AutomaticAssetClosure'; +import StreamTabPanel from '../containers/StreamTabPanel'; import styles from './Stream.css'; @@ -35,46 +35,20 @@ class Stream extends React.Component { componentWillReceiveProps(next) { // Keep comment box when user was live suspended, banned, ... - if (!this.userIsDegraged(this.props) && this.userIsDegraged(next)) { + if (!this.props.userIsDegraged && next.userIsDegraged) { this.setState({keepCommentBox: true}); } - - this.fallbackAllTab(next); } - componentDidMount() { - this.fallbackAllTab(); - } - - fallbackAllTab(props = this.props) { - if (props.activeStreamTab !== 'all') { - const slotPlugins = this.getSlotComponents('streamTabs', props).map((c) => c.talkPluginName); - if (slotPlugins.indexOf(props.activeStreamTab) === -1) { - props.setActiveStreamTab('all'); - } - } - } - - getSlotProps({data, root, root: {asset}} = this.props) { - return {data, root, asset}; - } - - getSlotComponents(slot, props = this.props) { - return getSlotComponents(slot, props.reduxState, this.getSlotProps(props)); - } - - setActiveReplyBox = (id) => { - if (!this.props.auth.user) { - this.props.showSignInDialog(); - } else { - this.props.setActiveReplyBox(id); - } + commentIsIgnored = (comment) => { + const me = this.props.root.me; + return ( + me && + me.ignoredUsers && + me.ignoredUsers.find((u) => u.id === comment.user.id) + ); }; - userIsDegraged({auth: {user}} = this.props) { - return !can(user, 'INTERACT_WITH_COMMUNITY'); - } - render() { const { data, @@ -83,7 +57,7 @@ class Stream extends React.Component { setActiveReplyBox, appendItemArray, commentClassNames, - root: {asset, asset: {comment, comments, totalCommentCount}, me}, + root: {asset, asset: {comment, comments, totalCommentCount}}, postComment, addNotification, editComment, @@ -99,7 +73,8 @@ class Stream extends React.Component { loadMoreComments, viewAllComments, auth: {loggedIn, user}, - editName + editName, + emit, } = this.props; const {keepCommentBox} = this.state; const open = !asset.isClosed; @@ -124,16 +99,9 @@ class Stream extends React.Component { user.suspension.until && new Date(user.suspension.until) > new Date(); - const commentIsIgnored = (comment) => { - return ( - me && - me.ignoredUsers && - me.ignoredUsers.find((u) => u.id === comment.user.id) - ); - }; - const showCommentBox = loggedIn && ((!banned && !temporarilySuspended && !highlightedComment) || keepCommentBox); - const slotProps = this.getSlotProps(); + const slotProps = {data}; + const slotQueryData = {root, asset}; if (!comment && !comments) { console.error('Talk: No comments came back from the graph given that query. Please, check the query params.'); @@ -195,6 +163,7 @@ class Stream extends React.Component { @@ -229,11 +198,12 @@ class Stream extends React.Component { deleteAction={deleteAction} showSignInDialog={showSignInDialog} key={highlightedComment.id} - commentIsIgnored={commentIsIgnored} + commentIsIgnored={this.commentIsIgnored} comment={highlightedComment} charCountEnable={asset.settings.charCountEnable} maxCharCount={asset.settings.charCount} editComment={editComment} + emit={emit} liveUpdates={true} />
    @@ -244,57 +214,54 @@ class Stream extends React.Component { >
    - - {this.getSlotComponents('streamTabs').map((PluginComponent) => ( - - + + All Comments {totalCommentCount} - ))} - - All Comments {totalCommentCount} - - - - {this.getSlotComponents('streamTabPanes').map((PluginComponent) => ( - - + - ))} - - - - + } + sub + />
    }
    diff --git a/client/coral-embed-stream/src/components/StreamTabPanel.js b/client/coral-embed-stream/src/components/StreamTabPanel.js new file mode 100644 index 000000000..0f2092092 --- /dev/null +++ b/client/coral-embed-stream/src/components/StreamTabPanel.js @@ -0,0 +1,37 @@ +import React from 'react'; +import {TabBar, TabContent} from 'coral-ui'; +import PropTypes from 'prop-types'; + +class StreamTabPanel extends React.Component { + + render() { + const {activeTab, setActiveTab, tabs, tabPanes, sub} = this.props; + return ( +
    + + {tabs} + + + {tabPanes} + +
    + ); + } +} + +StreamTabPanel.propTypes = { + activeTab: PropTypes.string.isRequired, + setActiveTab: PropTypes.func.isRequired, + tabs: PropTypes.oneOfType([ + PropTypes.element, + PropTypes.arrayOf(PropTypes.element) + ]), + tabPanes: PropTypes.oneOfType([ + PropTypes.element, + PropTypes.arrayOf(PropTypes.element) + ]), + className: PropTypes.string, + sub: PropTypes.bool, +}; + +export default StreamTabPanel; diff --git a/client/coral-embed-stream/src/components/Toggleable.js b/client/coral-embed-stream/src/components/Toggleable.js index 49f2a701b..a65e8212c 100644 --- a/client/coral-embed-stream/src/components/Toggleable.js +++ b/client/coral-embed-stream/src/components/Toggleable.js @@ -19,7 +19,9 @@ export default class Toggleable extends React.Component { } close = () => { - this.setState({isOpen: false}); + if (this.state.isOpen) { + this.setState({isOpen: false}); + } } render() { diff --git a/client/coral-embed-stream/src/containers/Comment.js b/client/coral-embed-stream/src/containers/Comment.js index 5d43e9eb7..e34218883 100644 --- a/client/coral-embed-stream/src/containers/Comment.js +++ b/client/coral-embed-stream/src/containers/Comment.js @@ -1,7 +1,11 @@ -import {gql} from 'react-apollo'; +import {gql, compose} from 'react-apollo'; +import React from 'react'; import Comment from '../components/Comment'; import {withFragments} from 'coral-framework/hocs'; import {getSlotFragmentSpreads} from 'coral-framework/utils'; +import {THREADING_LEVEL} from '../constants/stream'; +import hoistStatics from 'recompose/hoistStatics'; +import {nest} from '../graphql/utils'; const slots = [ 'streamQuestionArea', @@ -11,10 +15,79 @@ const slots = [ 'commentActions', 'commentContent', 'commentReactions', - 'commentAvatar' + 'commentAvatar', + 'commentAuthorName' ]; -export default withFragments({ +/** + * withAnimateEnter is a HOC that passes a property `animateEnter` to the + * underlying BaseComponent. It must be a direct child of a `TransitionGroup` + * from https://github.com/reactjs/react-transition-group and as such must + * be the uppermost HOC applied to the BaseComponent. + */ +const withAnimateEnter = hoistStatics((BaseComponent) => { + class WithAnimateEnter extends React.Component { + state = { + animateEnter: false, + }; + + componentWillEnter(callback) { + callback(); + const userId = this.props.currentUser ? this.props.currentUser.id : null; + if (this.props.comment.id.indexOf('pending') >= 0) { + return; + } + if (userId && this.props.comment.user.id === userId) { + + // This comment was just added by currentUser. + if (Date.now() - Number(new Date(this.props.comment.created_at)) < 30 * 1000) { + return; + } + } + this.setState({animateEnter: true}); + } + + render() { + return ; + } + } + return WithAnimateEnter; +}); + +const singleCommentFragment = gql` + fragment CoralEmbedStream_Comment_SingleComment on Comment { + id + body + created_at + status + replyCount + tags { + tag { + name + } + } + user { + id + username + } + action_summaries { + __typename + count + current_user { + id + } + } + editing { + edited + editableUntil + } + } +`; + +const withCommentFragments = withFragments({ root: gql` fragment CoralEmbedStream_Comment_root on RootQuery { __typename @@ -24,37 +97,33 @@ export default withFragments({ asset: gql` fragment CoralEmbedStream_Comment_asset on Asset { __typename + id ${getSlotFragmentSpreads(slots, 'asset')} } `, comment: gql` fragment CoralEmbedStream_Comment_comment on Comment { - id - body - created_at - status - replyCount - tags { - tag { - name + ...CoralEmbedStream_Comment_SingleComment + ${nest(` + replies(limit: 3, excludeIgnored: $excludeIgnored) { + nodes { + ...CoralEmbedStream_Comment_SingleComment + ...nest + } + hasNextPage + startCursor + endCursor } - } - user { - id - username - } - action_summaries { - __typename - count - current_user { - id - } - } - editing { - edited - editableUntil - } + `, THREADING_LEVEL)} ${getSlotFragmentSpreads(slots, 'comment')} } + ${singleCommentFragment} ` -})(Comment); +}); + +const enhance = compose( + withAnimateEnter, + withCommentFragments, +); + +export default enhance(Comment); diff --git a/client/coral-embed-stream/src/containers/Embed.js b/client/coral-embed-stream/src/containers/Embed.js index 06646a6c2..731cab264 100644 --- a/client/coral-embed-stream/src/containers/Embed.js +++ b/client/coral-embed-stream/src/containers/Embed.js @@ -11,7 +11,7 @@ import {Spinner} from 'coral-ui'; import * as authActions from 'coral-framework/actions/auth'; import * as assetActions from 'coral-framework/actions/asset'; import pym from 'coral-framework/services/pym'; -import {getDefinitionName} from 'coral-framework/utils'; +import {getDefinitionName, getSlotFragmentSpreads} from 'coral-framework/utils'; import {withQuery} from 'coral-framework/hocs'; import Embed from '../components/Embed'; import Stream from './Stream'; @@ -146,12 +146,17 @@ const USERNAME_REJECTED_SUBSCRIPTION = gql` } `; +const slots = [ + 'embed', +]; + const EMBED_QUERY = gql` query CoralEmbedStream_Embed($assetId: ID, $assetUrl: String, $commentId: ID!, $hasComment: Boolean!, $excludeIgnored: Boolean) { me { id status } + ${getSlotFragmentSpreads(slots, 'root')} ...${getDefinitionName(Stream.fragments.root)} } ${Stream.fragments.root} @@ -170,7 +175,7 @@ export const withEmbedQuery = withQuery(EMBED_QUERY, { }); const mapStateToProps = (state) => ({ - auth: state.auth.toJS(), + auth: state.auth, commentId: state.stream.commentId, assetId: state.stream.assetId, assetUrl: state.stream.assetUrl, diff --git a/client/coral-embed-stream/src/containers/Stream.js b/client/coral-embed-stream/src/containers/Stream.js index fcedbcb0b..ef5838453 100644 --- a/client/coral-embed-stream/src/containers/Stream.js +++ b/client/coral-embed-stream/src/containers/Stream.js @@ -10,13 +10,13 @@ import { import * as authActions from 'coral-framework/actions/auth'; import * as notificationActions from 'coral-framework/actions/notification'; -import {editName} from 'coral-framework/actions/user'; import {setActiveReplyBox, setActiveTab, viewAllComments} from '../actions/stream'; import Stream from '../components/Stream'; import Comment from './Comment'; -import {withFragments} from 'coral-framework/hocs'; +import {withFragments, withEmit} from 'coral-framework/hocs'; import {getDefinitionName, getSlotFragmentSpreads} from 'coral-framework/utils'; import {Spinner} from 'coral-ui'; +import {can} from 'coral-framework/services/perms'; import { findCommentInEmbedQuery, insertCommentIntoEmbedQuery, @@ -24,9 +24,8 @@ import { insertFetchedCommentsIntoEmbedQuery, nest, } from '../graphql/utils'; -import omit from 'lodash/omit'; -const {showSignInDialog} = authActions; +const {showSignInDialog, editName} = authActions; const {addNotification} = notificationActions; class StreamContainer extends React.Component { @@ -141,8 +140,16 @@ class StreamContainer extends React.Component { clearInterval(this.countPoll); } + userIsDegraged({auth: {user}} = this.props) { + return !can(user, 'INTERACT_WITH_COMMUNITY'); + } + render() { - if (this.props.refetching) { + if (this.props.refetching + || !this.props.root.asset + || !this.props.root.asset.comment + && !this.props.root.asset.comments + ) { return ; } return ; } } @@ -157,19 +165,11 @@ class StreamContainer extends React.Component { const commentFragment = gql` fragment CoralEmbedStream_Stream_comment on Comment { id + status + user { + id + } ...${getDefinitionName(Comment.fragments.comment)} - ${nest(` - replies(excludeIgnored: $excludeIgnored) { - nodes { - id - ...${getDefinitionName(Comment.fragments.comment)} - ...nest - } - hasNextPage - startCursor - endCursor - } - `, THREADING_LEVEL)} } ${Comment.fragments.comment} `; @@ -206,27 +206,14 @@ const LOAD_MORE_QUERY = gql` query CoralEmbedStream_LoadMoreComments($limit: Int = 5, $cursor: Date, $parent_id: ID, $asset_id: ID, $sort: SORT_ORDER, $excludeIgnored: Boolean) { comments(query: {limit: $limit, cursor: $cursor, parent_id: $parent_id, asset_id: $asset_id, sort: $sort, excludeIgnored: $excludeIgnored}) { nodes { - id - ...${getDefinitionName(Comment.fragments.comment)} - ${nest(` - replies(limit: 3, excludeIgnored: $excludeIgnored) { - nodes { - id - ...${getDefinitionName(Comment.fragments.comment)} - ...nest - } - hasNextPage - startCursor - endCursor - } - `, THREADING_LEVEL)} + ...CoralEmbedStream_Stream_comment } hasNextPage startCursor endCursor } } - ${Comment.fragments.comment} + ${commentFragment} `; const slots = [ @@ -298,7 +285,7 @@ const fragments = { }; const mapStateToProps = (state) => ({ - auth: state.auth.toJS(), + auth: state.auth, refetching: state.embed.refetching, commentCountCache: state.stream.commentCountCache, activeReplyBox: state.stream.activeReplyBox, @@ -311,7 +298,6 @@ const mapStateToProps = (state) => ({ previousStreamTab: state.stream.previousTab, commentClassNames: state.stream.commentClassNames, pluginConfig: state.config.plugin_config, - reduxState: omit(state, 'apollo'), }); const mapDispatchToProps = (dispatch) => @@ -326,6 +312,7 @@ const mapDispatchToProps = (dispatch) => export default compose( withFragments(fragments), + withEmit, connect(mapStateToProps, mapDispatchToProps), withPostComment, withPostFlag, diff --git a/client/coral-embed-stream/src/containers/StreamTabPanel.js b/client/coral-embed-stream/src/containers/StreamTabPanel.js new file mode 100644 index 000000000..7b91d58ee --- /dev/null +++ b/client/coral-embed-stream/src/containers/StreamTabPanel.js @@ -0,0 +1,108 @@ +import React from 'react'; +import StreamTabPanel from '../components/StreamTabPanel'; +import {connect} from 'react-redux'; +import omit from 'lodash/omit'; +import {getSlotComponents, getSlotComponentProps} from 'coral-framework/helpers/plugins'; +import {Tab, TabPane} from 'coral-ui'; +import {getShallowChanges} from 'coral-framework/utils'; +import isEqual from 'lodash/isEqual'; +import PropTypes from 'prop-types'; + +class StreamTabPanelContainer extends React.Component { + + componentDidMount() { + this.fallbackAllTab(); + } + + componentWillReceiveProps(next) { + this.fallbackAllTab(next); + } + + shouldComponentUpdate(next) { + + // Prevent Slot from rerendering when only reduxState has changed and + // it does not result in a change of slot children. + const changes = getShallowChanges(this.props, next); + if (changes.length === 1 && changes[0] === 'reduxState') { + const prevUuid = this.getSlotComponents(this.props.tabSlot, this.props).map((cmp) => cmp.talkUuid); + const nextUuid = this.getSlotComponents(next.tabSlot, next).map((cmp) => cmp.talkUuid); + return !isEqual(prevUuid, nextUuid); + } + + // Prevent Slot from rerendering when no props has shallowly changed. + return changes.length !== 0; + } + + fallbackAllTab(props = this.props) { + if (props.activeTab !== props.fallbackTab) { + const slotPlugins = this.getSlotComponents(props.tabSlot, props).map((c) => c.talkPluginName); + if (slotPlugins.indexOf(props.activeTab) === -1) { + props.setActiveTab(props.fallbackTab); + } + } + } + + getSlotComponents(slot, props = this.props) { + return getSlotComponents(slot, props.reduxState, props.slotProps, props.queryData); + } + + getPluginTabElements(props = this.props) { + return this.getSlotComponents(props.tabSlot).map((PluginComponent) => ( + + + + )); + } + + getPluginTabPaneElements(props = this.props) { + return this.getSlotComponents(props.tabPaneSlot).map((PluginComponent) => ( + + + + )); + } + + render() { + return ( + + ); + } +} + +StreamTabPanelContainer.propTypes = { + activeTab: PropTypes.string.isRequired, + setActiveTab: PropTypes.func.isRequired, + appendTabs: PropTypes.oneOfType([ + PropTypes.element, + PropTypes.arrayOf(PropTypes.element) + ]), + appendTabPanes: PropTypes.oneOfType([ + PropTypes.element, + PropTypes.arrayOf(PropTypes.element) + ]), + fallbackTab: PropTypes.string.isRequired, + tabSlot: PropTypes.string.isRequired, + tabPaneSlot: PropTypes.string.isRequired, + slotProps: PropTypes.object.isRequired, + queryData: PropTypes.object, + className: PropTypes.string, + sub: PropTypes.bool, +}; + +const mapStateToProps = (state) => ({ + reduxState: omit(state, 'apollo'), +}); + +export default connect(mapStateToProps, null)(StreamTabPanelContainer); diff --git a/client/coral-embed-stream/src/graphql/index.js b/client/coral-embed-stream/src/graphql/index.js index a16af23e7..b4c5ce163 100644 --- a/client/coral-embed-stream/src/graphql/index.js +++ b/client/coral-embed-stream/src/graphql/index.js @@ -73,6 +73,11 @@ const extension = { created_at status replyCount + asset { + id + title + url + } tags { tag { name @@ -142,13 +147,11 @@ const extension = { __typename: 'Comment', user: { __typename: 'User', - id: auth.toJS().user.id, - username: auth.toJS().user.username + id: auth.user.id, + username: auth.user.username }, created_at: new Date().toISOString(), body, - parent_id, - asset_id, action_summaries: [], tags: tags.map((tag) => ({ tag: { @@ -157,15 +160,21 @@ const extension = { __typename: 'Tag' }, assigned_by: { - id: auth.toJS().user.id, + id: auth.user.id, __typename: 'User' }, __typename: 'TagLink' })), status: 'NONE', replyCount: 0, + asset: { + __typename: 'Asset', + id: asset_id, + title: '', + url: '', + }, parent: parent_id - ? {id: parent_id} + ? {__typename: 'Comment', id: parent_id} : null, replies: { __typename: 'CommentConnection', @@ -190,6 +199,15 @@ const extension = { } return insertCommentIntoEmbedQuery(prev, comment); }, + CoralEmbedStream_Profile: (prev, {mutationResult: {data: {createComment: {comment}}}}) => { + return update(prev, { + me: { + comments: { + nodes: {$unshift: [comment]}, + }, + }, + }); + }, } }), EditComment: () => ({ diff --git a/client/coral-embed-stream/src/graphql/utils.js b/client/coral-embed-stream/src/graphql/utils.js index ac6298616..11d3d411b 100644 --- a/client/coral-embed-stream/src/graphql/utils.js +++ b/client/coral-embed-stream/src/graphql/utils.js @@ -117,7 +117,7 @@ export function getTopLevelParent(comment) { return comment; } -function findComment(nodes, callback) { +export function findComment(nodes, callback) { for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (callback(node)) { @@ -133,6 +133,10 @@ function findComment(nodes, callback) { return false; } +export function findCommentWithId(nodes, id) { + return findComment(nodes, (node) => node.id === id); +} + export function findCommentInEmbedQuery(root, callbackOrId) { let callback = callbackOrId; if (typeof callbackOrId === 'string') { diff --git a/client/coral-embed-stream/style/default.css b/client/coral-embed-stream/style/default.css index 802cd2e5b..d4078bf27 100644 --- a/client/coral-embed-stream/style/default.css +++ b/client/coral-embed-stream/style/default.css @@ -13,7 +13,7 @@ body { width: 100%; font-size: 14px; margin: 0px; - padding: 0px 0px 50px 0px; + padding: 0px 0px 100px 0px; height: auto !important; } @@ -238,16 +238,6 @@ body { line-height: 1.3; } -.talk-plugin-author-name-text { - display: inline-block; - margin: 10px 5px 10px 0; - font-weight: bold; -} - -.talk-plugin-author-name-bio-flag { - float: right; -} - /* Tag Labels */ .talk-plugin-tag-label { diff --git a/client/coral-framework/actions/asset.js b/client/coral-framework/actions/asset.js index 24739ddde..aab3caf3a 100644 --- a/client/coral-framework/actions/asset.js +++ b/client/coral-framework/actions/asset.js @@ -13,7 +13,7 @@ const updateAssetSettingsSuccess = (settings) => ({type: actions.UPDATE_ASSET_SE const updateAssetSettingsFailure = (error) => ({type: actions.UPDATE_ASSET_SETTINGS_FAILURE, error}); export const updateConfiguration = (newConfig) => (dispatch, getState) => { - const assetId = getState().asset.toJS().id; + const assetId = getState().asset.id; dispatch(updateAssetSettingsRequest()); coralApi(`/assets/${assetId}/settings`, {method: 'PUT', body: newConfig}) .then(() => { @@ -27,7 +27,7 @@ export const updateConfiguration = (newConfig) => (dispatch, getState) => { }; export const updateOpenStream = (closedBody) => (dispatch, getState) => { - const assetId = getState().asset.toJS().id; + const assetId = getState().asset.id; dispatch(fetchAssetRequest()); coralApi(`/assets/${assetId}/status`, {method: 'PUT', body: closedBody}) .then(() => { diff --git a/client/coral-framework/actions/auth.js b/client/coral-framework/actions/auth.js index f4cf5217e..7c6d3bf89 100644 --- a/client/coral-framework/actions/auth.js +++ b/client/coral-framework/actions/auth.js @@ -4,6 +4,7 @@ import * as actions from '../constants/auth'; import * as Storage from '../helpers/storage'; import coralApi, {base} from '../helpers/request'; import pym from '../services/pym'; +import {addNotification} from '../actions/notification'; import {resetWebsocket} from 'coral-framework/services/client'; import t from 'coral-framework/services/i18n'; @@ -220,7 +221,7 @@ const signUpSuccess = (user) => ({type: actions.FETCH_SIGNUP_SUCCESS, user}); const signUpFailure = (error) => ({type: actions.FETCH_SIGNUP_FAILURE, error}); export const fetchSignUp = (formData) => (dispatch, getState) => { - const redirectUri = getState().auth.toJS().redirectUri; + const redirectUri = getState().auth.redirectUri; dispatch(signUpRequest()); coralApi('/users', { @@ -257,7 +258,7 @@ const forgotPasswordFailure = (error) => ({ export const fetchForgotPassword = (email) => (dispatch, getState) => { dispatch(forgotPasswordRequest(email)); - const redirectUri = getState().auth.toJS().redirectUri; + const redirectUri = getState().auth.redirectUri; coralApi('/account/password/reset', { method: 'POST', body: {email, loc: redirectUri} @@ -351,7 +352,7 @@ const verifyEmailFailure = () => ({ }); export const requestConfirmEmail = (email) => (dispatch, getState) => { - const redirectUri = getState().auth.toJS().redirectUri; + const redirectUri = getState().auth.redirectUri; dispatch(verifyEmailRequest()); return coralApi('/users/resend-verify', { method: 'POST', @@ -378,3 +379,23 @@ export const setRedirectUri = (uri) => ({ type: actions.SET_REDIRECT_URI, uri, }); + +//============================================================================== +// Edit Username +//============================================================================== + +const editUsernameFailure = (error) => ({type: actions.EDIT_USERNAME_FAILURE, error}); +const editUsernameSuccess = () => ({type: actions.EDIT_USERNAME_SUCCESS}); + +export const editName = (username) => (dispatch) => { + return coralApi('/account/username', {method: 'PUT', body: {username}}) + .then(() => { + dispatch(editUsernameSuccess()); + dispatch(addNotification('success', t('framework.success_name_update'))); + }) + .catch((error) => { + console.error(error); + const errorMessage = error.translation_key ? t(`error.${error.translation_key}`) : error.toString(); + dispatch(editUsernameFailure(errorMessage)); + }); +}; diff --git a/client/coral-framework/actions/user.js b/client/coral-framework/actions/user.js deleted file mode 100644 index a6ad45d4a..000000000 --- a/client/coral-framework/actions/user.js +++ /dev/null @@ -1,21 +0,0 @@ -import {addNotification} from '../actions/notification'; -import coralApi from '../helpers/request'; -import * as actions from '../constants/auth'; - -import t from 'coral-framework/services/i18n'; - -const editUsernameFailure = (error) => ({type: actions.EDIT_USERNAME_FAILURE, error}); -const editUsernameSuccess = () => ({type: actions.EDIT_USERNAME_SUCCESS}); - -export const editName = (username) => (dispatch) => { - return coralApi('/account/username', {method: 'PUT', body: {username}}) - .then(() => { - dispatch(editUsernameSuccess()); - dispatch(addNotification('success', t('framework.success_name_update'))); - }) - .catch((error) => { - console.error(error); - const errorMessage = error.translation_key ? t(`error.${error.translation_key}`) : error.toString(); - dispatch(editUsernameFailure(errorMessage)); - }); -}; diff --git a/client/coral-framework/components/CommentAuthorName.css b/client/coral-framework/components/CommentAuthorName.css new file mode 100644 index 000000000..c06360000 --- /dev/null +++ b/client/coral-framework/components/CommentAuthorName.css @@ -0,0 +1,3 @@ +.authorName { + font-weight: bold; +} \ No newline at end of file diff --git a/client/coral-framework/components/CommentAuthorName.js b/client/coral-framework/components/CommentAuthorName.js new file mode 100644 index 000000000..5a2e60c70 --- /dev/null +++ b/client/coral-framework/components/CommentAuthorName.js @@ -0,0 +1,9 @@ +import React from 'react'; +import styles from './CommentAuthorName.css'; + +const CommentAuthorName = ({comment}) => + + {comment.user.username} + ; + +export default CommentAuthorName; diff --git a/client/coral-framework/components/IfSlotIsEmpty.js b/client/coral-framework/components/IfSlotIsEmpty.js index 424a59bc7..e9211fc57 100644 --- a/client/coral-framework/components/IfSlotIsEmpty.js +++ b/client/coral-framework/components/IfSlotIsEmpty.js @@ -3,13 +3,36 @@ import {connect} from 'react-redux'; import {isSlotEmpty} from 'coral-framework/helpers/plugins'; import PropTypes from 'prop-types'; import omit from 'lodash/omit'; +import {getShallowChanges} from 'coral-framework/utils'; -function IfSlotIsEmpty({slot, className, reduxState, component: Component = 'div', children, ...rest}) { - return ( - - {isSlotEmpty(slot, reduxState, rest) ? children : null} - - ); +class IfSlotIsEmpty extends React.Component { + + shouldComponentUpdate(next) { + + // Prevent Slot from rerendering when only reduxState has changed and + // it does not result in a change. + const changes = getShallowChanges(this.props, next); + if (changes.length === 1 && changes[0] === 'reduxState') { + return this.isSlotEmpty(this.props) !== this.isSlotEmpty(next); + } + + // Prevent Slot from rerendering when no props has shallowly changed. + return changes.length !== 0; + } + + isSlotEmpty(props = this.props) { + const {slot, className: _a, reduxState, component: _b = 'div', children: _c, ...rest} = props; + return isSlotEmpty(slot, reduxState, rest); + } + + render() { + const {className, component: Component = 'div', children} = this.props; + return ( + + {this.isSlotEmpty() ? children : null} + + ); + } } IfSlotIsEmpty.propTypes = { diff --git a/client/coral-framework/components/IfSlotIsNotEmpty.js b/client/coral-framework/components/IfSlotIsNotEmpty.js index 3a41fffbd..e7a0e83ce 100644 --- a/client/coral-framework/components/IfSlotIsNotEmpty.js +++ b/client/coral-framework/components/IfSlotIsNotEmpty.js @@ -3,13 +3,36 @@ import {connect} from 'react-redux'; import {isSlotEmpty} from 'coral-framework/helpers/plugins'; import PropTypes from 'prop-types'; import omit from 'lodash/omit'; +import {getShallowChanges} from 'coral-framework/utils'; -function IfSlotIsNotEmpty({slot, className, reduxState, component: Component = 'div', children, ...rest}) { - return ( - - {!isSlotEmpty(slot, reduxState, rest) ? children : null} - - ); +class IfSlotIsNotEmpty extends React.Component { + + shouldComponentUpdate(next) { + + // Prevent Slot from rerendering when only reduxState has changed and + // it does not result in a change. + const changes = getShallowChanges(this.props, next); + if (changes.length === 1 && changes[0] === 'reduxState') { + return this.isSlotEmpty(this.props) !== this.isSlotEmpty(next); + } + + // Prevent Slot from rerendering when no props has shallowly changed. + return changes.length !== 0; + } + + isSlotEmpty(props = this.props) { + const {slot, className: _a, reduxState, component: _b = 'div', children: _c, ...rest} = props; + return isSlotEmpty(slot, reduxState, rest); + } + + render() { + const {className, component: Component = 'div', children} = this.props; + return ( + + {this.isSlotEmpty() ? null : children} + + ); + } } IfSlotIsNotEmpty.propTypes = { diff --git a/client/coral-framework/components/Slot.js b/client/coral-framework/components/Slot.js index b1df6647a..c0cca143c 100644 --- a/client/coral-framework/components/Slot.js +++ b/client/coral-framework/components/Slot.js @@ -2,25 +2,58 @@ import React from 'react'; import cn from 'classnames'; import styles from './Slot.css'; import {connect} from 'react-redux'; -import {getSlotElements} from 'coral-framework/helpers/plugins'; +import {getSlotElements, getSlotComponentProps} from 'coral-framework/helpers/plugins'; import omit from 'lodash/omit'; +import isEqual from 'lodash/isEqual'; +import {getShallowChanges} from 'coral-framework/utils'; -function Slot ({fill, inline = false, className, reduxState, defaultComponent: DefaultComponent, ...rest}) { - let children = getSlotElements(fill, reduxState, rest); - const pluginConfig = reduxState.config.pluginConfig || {}; - if (children.length === 0 && DefaultComponent) { - children = ; +const emptyConfig = {}; + +class Slot extends React.Component { + shouldComponentUpdate(next) { + + // Prevent Slot from rerendering when only reduxState has changed and + // it does not result in a change of slot children. + const changes = getShallowChanges(this.props, next); + if (changes.length === 1 && changes[0] === 'reduxState') { + const prevChildrenUuid = this.getChildren(this.props).map((child) => child.type.talkUuid); + const nextChildrenUuid = this.getChildren(next).map((child) => child.type.talkUuid); + return !isEqual(prevChildrenUuid, nextChildrenUuid); + } + + // Prevent Slot from rerendering when no props has shallowly changed. + return changes.length !== 0; } - return ( -
    - {children} -
    - ); + getSlotProps({fill: _a, inline: _b, className: _c, reduxState: _d, defaultComponent_: _e, queryData: _f, ...rest} = this.props) { + return rest; + } + + getChildren(props = this.props) { + return getSlotElements(props.fill, props.reduxState, this.getSlotProps(props), props.queryData); + } + + render() { + const {inline = false, className, reduxState, defaultComponent: DefaultComponent, queryData} = this.props; + let children = this.getChildren(); + const pluginConfig = reduxState.config.pluginConfig || emptyConfig; + if (children.length === 0 && DefaultComponent) { + children = ; + } + + return ( +
    + {children} +
    + ); + } } Slot.propTypes = { - fill: React.PropTypes.string + fill: React.PropTypes.string.isRequired, + + // props coming from graphql must be passed through this property. + queryData: React.PropTypes.object, }; const mapStateToProps = (state) => ({ diff --git a/client/coral-framework/components/index.js b/client/coral-framework/components/index.js index b7aaef665..8ad08aa09 100644 --- a/client/coral-framework/components/index.js +++ b/client/coral-framework/components/index.js @@ -1 +1,2 @@ export {default as Slot} from './Slot'; +export {default as CommentAuthorName} from './CommentAuthorName'; diff --git a/client/coral-framework/constants/assets.js b/client/coral-framework/constants/assets.js deleted file mode 100644 index 3883ee835..000000000 --- a/client/coral-framework/constants/assets.js +++ /dev/null @@ -1,3 +0,0 @@ -export const MULTIPLE_ASSETS_REQUEST = 'MULTIPLE_ASSETS_REQUEST'; -export const MULTIPLE_ASSETS_SUCCESS = 'MULTIPLE_ASSETS_SUCCESS'; -export const MULTIPLE_ASSSETS_FAILURE = 'MULTIPLE_ASSSETS_FAILURE'; diff --git a/client/coral-framework/constants/user.js b/client/coral-framework/constants/user.js deleted file mode 100644 index 1557a42c9..000000000 --- a/client/coral-framework/constants/user.js +++ /dev/null @@ -1,10 +0,0 @@ -export const EDIT_NAME_REQUEST = 'EDIT_NAME_REQUEST'; -export const EDIT_NAME_SUCCESS = 'EDIT_NAME_SUCCESS'; -export const EDIT_NAME_FAILURE = 'EDIT_NAME_FAILURE'; -export const COMMENTS_BY_USER_REQUEST = 'COMMENTS_BY_USER_REQUEST'; -export const COMMENTS_BY_USER_SUCCESS = 'COMMENTS_BY_USER_SUCCESS'; -export const COMMENTS_BY_USER_FAILURE = 'COMMENTS_BY_USER_FAILURE'; -export const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS'; -export const UPDATE_USERNAME = 'UPDATE_USERNAME'; -export const IGNORE_USER_SUCCESS = 'IGNORE_USER_SUCCESS'; -export const STOP_IGNORING_USER_SUCCESS = 'STOP_IGNORING_USER_SUCCESS'; diff --git a/client/coral-framework/helpers/plugins.js b/client/coral-framework/helpers/plugins.js index 1af2a9a59..3173115c2 100644 --- a/client/coral-framework/helpers/plugins.js +++ b/client/coral-framework/helpers/plugins.js @@ -3,14 +3,21 @@ import uniq from 'lodash/uniq'; import pick from 'lodash/pick'; import merge from 'lodash/merge'; import flattenDeep from 'lodash/flattenDeep'; +import isEmpty from 'lodash/isEmpty'; import flatten from 'lodash/flatten'; +import mapValues from 'lodash/mapValues'; import {loadTranslations} from 'coral-framework/services/i18n'; import {injectReducers} from 'coral-framework/services/store'; +import {getDisplayName} from 'coral-framework/helpers/hoc'; import camelize from './camelize'; import plugins from 'pluginsConfig'; +import uuid from 'uuid/v4'; -export function getSlotComponents(slot, reduxState, props = {}) { - const pluginConfig = reduxState.config.pluginConfig || {}; +// This is returned for pluginConfig when it is empty. +const emptyConfig = {}; + +export function getSlotComponents(slot, reduxState, props = {}, queryData = {}) { + const pluginConfig = reduxState.config.plugin_config || emptyConfig; return flatten(plugins // Filter out components that have slots and have been disabled in `plugin_config` @@ -23,7 +30,7 @@ export function getSlotComponents(slot, reduxState, props = {}) { if(!component.isExcluded) { return true; } - let resolvedProps = {...props, config: pluginConfig}; + let resolvedProps = getSlotComponentProps(component, reduxState, props, queryData); if (component.mapStateToProps) { resolvedProps = {...resolvedProps, ...component.mapStateToProps(reduxState)}; } @@ -31,17 +38,70 @@ export function getSlotComponents(slot, reduxState, props = {}) { }); } -export function isSlotEmpty(slot, reduxState, props) { - return getSlotComponents(slot, reduxState, props).length === 0; +export function isSlotEmpty(slot, reduxState, props = {}, queryData = {}) { + return getSlotComponents(slot, reduxState, props, queryData).length === 0; +} + +// Memoize the warnings so we only show them once. +const memoizedWarnings = []; + +// withWarnings decorates the props of queryData with a proxy that +// prints a warning when accessing deeper props. +function withWarnings(component, queryData) { + if (process.env.NODE_ENV !== 'production' && window.Proxy) { + + // Show warnings when accessing queryData only when not in production. + return mapValues(queryData, (value, key) => { + + // Keep null values.. + if (!queryData[key]) { + return queryData[key]; + } + return new Proxy(queryData[key], { + get(target, name) { + + // Only care about the components defined in the plugins. + if (component.talkPluginName) { + const warning = `'${getDisplayName(component)}' of '${component.talkPluginName}' accessed '${key}.${name}' but did not define fragments using the withFragment HOC`; + if (memoizedWarnings.indexOf(warning) === -1) { + console.warn(warning); + memoizedWarnings.push(warning); + } + } + return queryData[key][name]; + } + }); + }); + } + + return queryData; +} + +/** + * getSlotComponentProps calculate the props we would pass to the slot component. + * query datas are only passed to the component if it is defined in `component.fragments`. + */ +export function getSlotComponentProps(component, reduxState, props, queryData) { + const pluginConfig = reduxState.config.plugin_config || emptyConfig; + return { + ...props, + config: pluginConfig, + ...( + component.fragments + ? pick(queryData, Object.keys(component.fragments)) + : withWarnings(component, queryData) + ) + }; } /** * Returns React Elements for given slot. */ -export function getSlotElements(slot, reduxState, props = {}) { - const pluginConfig = reduxState.config.pluginConfig || {}; - return getSlotComponents(slot, reduxState, props) - .map((component, i) => React.createElement(component, {key: i, ...props, config: pluginConfig})); +export function getSlotElements(slot, reduxState, props = {}, queryData = {}) { + return getSlotComponents(slot, reduxState, props, queryData) + .map((component, i) => { + return React.createElement(component, {key: i, ...getSlotComponentProps(component, reduxState, props, queryData)}); + }); } export function getSlotFragments(slot, part) { @@ -64,7 +124,13 @@ export function getSlotFragments(slot, part) { export function getGraphQLExtensions() { return plugins .map((o) => pick(o.module, ['mutations', 'queries', 'fragments'])) - .filter((o) => o); + .filter((o) => !isEmpty(o)); +} + +export function getModQueueConfigs() { + return merge(...plugins + .map((o) => o.module.modQueues) + .filter((o) => o)); } function getTranslations() { @@ -93,7 +159,12 @@ function addMetaDataToSlotComponents() { const slots = plugin.module.slots; slots && Object.keys(slots).forEach((slot) => { slots[slot].forEach((component) => { + + // Attach plugin name to the component component.talkPluginName = plugin.name; + + // Attach uuid to the component + component.talkUuid = uuid(); }); }); }); diff --git a/client/coral-framework/hocs/withCopyToClipboard.js b/client/coral-framework/hocs/withCopyToClipboard.js index 9e8046802..4de606c40 100644 --- a/client/coral-framework/hocs/withCopyToClipboard.js +++ b/client/coral-framework/hocs/withCopyToClipboard.js @@ -1,8 +1,9 @@ import React from 'react'; import ReactDOM from 'react-dom'; import Clipboard from 'clipboard'; +import hoistStatics from 'recompose/hoistStatics'; -export default (WrappedComponent) => { +export default hoistStatics((WrappedComponent) => { class WithCopyToClipboard extends React.Component { componentDidMount() { const clipboard = new Clipboard(ReactDOM.findDOMNode(this)); @@ -26,4 +27,4 @@ export default (WrappedComponent) => { } return WithCopyToClipboard; -}; +}); diff --git a/client/coral-framework/hocs/withEmit.js b/client/coral-framework/hocs/withEmit.js index 3a3216c8a..22d98bb27 100644 --- a/client/coral-framework/hocs/withEmit.js +++ b/client/coral-framework/hocs/withEmit.js @@ -1,11 +1,12 @@ import React from 'react'; -const PropTypes = require('prop-types'); +import hoistStatics from 'recompose/hoistStatics'; +import PropTypes from 'prop-types'; /** * WithEmit provides a property `emit: (eventName, value)` * to the wrapped component. */ -export default (WrappedComponent) => { +export default hoistStatics((WrappedComponent) => { class WithEmit extends React.Component { static contextTypes = { eventEmitter: PropTypes.object, @@ -24,4 +25,4 @@ export default (WrappedComponent) => { } return WithEmit; -}; +}); diff --git a/client/coral-framework/hocs/withFragments.js b/client/coral-framework/hocs/withFragments.js index 62e96444c..9bc06290e 100644 --- a/client/coral-framework/hocs/withFragments.js +++ b/client/coral-framework/hocs/withFragments.js @@ -1,5 +1,109 @@ -// TODO: revisit `filtering` after https://github.com/apollographql/graphql-anywhere/issues/38. -export default (fragments) => (BaseComponent) => { - BaseComponent.fragments = fragments; - return BaseComponent; -}; +import React from 'react'; +import graphql from 'graphql-anywhere'; +import {resolveFragments} from 'coral-framework/services/graphqlRegistry'; +import mapValues from 'lodash/mapValues'; +import hoistStatics from 'recompose/hoistStatics'; +import {getShallowChanges} from 'coral-framework/utils'; +import union from 'lodash/union'; + +// TODO: Should not depend on `props.data` +// Currently necessary because of this https://github.com/apollographql/graphql-anywhere/issues/38 +function filter(doc, data, variables) { + const resolver = ( + fieldName, + root, + args, + context, + info, + ) => { + return root[info.resultKey]; + }; + + return graphql(resolver, doc, data, null, variables); +} + +// filterProps returns only the property as defined in the fragments. +// TODO: Should not depend on `props.data` +function filterProps(props, fragments) { + const filtered = {}; + Object.keys(fragments).forEach((key) => { + if (!(key in props)) { + return; + } + filtered[key] = props.data + ? filter(fragments[key], props[key], props.data.variables) + : props[key]; + }); + return filtered; +} + +// hasEqualLeaves compares two different apollo query result for equality. +function hasEqualLeaves(a, b, path = '') { + for (const key of union(Object.keys(a), Object.keys(b))) { + if (!(key in a) || !(key in b)) { + return false; + } + if (typeof a[key] === 'object' && a[key] && b[key]) { + if (Array.isArray(a[key])) { + if (a[key].length !== b[key].length) { + return false; + } + } + if (!hasEqualLeaves(a[key], b[key], `${path}.${key}`)) { + return false; + } + continue; + } + if (a[key] !== b[key]) { + return false; + } + } + return true; +} + +export default (fragments) => hoistStatics((BaseComponent) => { + class WithFragments extends React.Component { + fragments = mapValues(fragments, (val) => resolveFragments(val)); + fragmentKeys = Object.keys(fragments).sort(); + + // Cache variables between lifecycles to speed up render. + filteredProps = filterProps(this.props, this.fragments) + queryDataHasChanged = false; + shallowChanges = null; + + componentWillReceiveProps(next) { + this.shallowChanges = getShallowChanges(this.props, next); + + if (this.fragmentKeys.some((key) => this.shallowChanges.indexOf(key) >= 0)) { + const nextFilteredProps = filterProps(next, this.fragments); + this.queryDataHasChanged = !hasEqualLeaves(this.filteredProps, nextFilteredProps); + if (this.queryDataHasChanged) { + + // Only changed props when query data has changed. + this.filteredProps = filterProps(next, this.fragments); + } + } + } + + shouldComponentUpdate(next) { + const onlyQueryDataChanges = this.shallowChanges.every((key) => this.fragmentKeys.indexOf(key) >= 0); + + if (onlyQueryDataChanges) { + return this.queryDataHasChanged; + } + + return this.shallowChanges.length !== 0; + } + + render() { + const queryProps = this.filteredProps; + return ; + } + } + + WithFragments.fragments = fragments; + return WithFragments; +}); diff --git a/client/coral-framework/hocs/withMutation.js b/client/coral-framework/hocs/withMutation.js index c9108c0fe..7c3dcfa1a 100644 --- a/client/coral-framework/hocs/withMutation.js +++ b/client/coral-framework/hocs/withMutation.js @@ -8,6 +8,8 @@ import {getMutationOptions, resolveFragments} from 'coral-framework/services/gra import {getDefinitionName, getResponseErrors} from '../utils'; import PropTypes from 'prop-types'; import t from 'coral-framework/services/i18n'; +import hoistStatics from 'recompose/hoistStatics'; +import union from 'lodash/union'; class ResponseErrors extends Error { constructor(errors) { @@ -30,7 +32,7 @@ class ResponseError { * Exports a HOC with the same signature as `graphql`, that will * apply mutation options registered in the graphRegistry. */ -export default (document, config = {}) => (WrappedComponent) => { +export default (document, config = {}) => hoistStatics((WrappedComponent) => { config = { ...config, options: config.options || {}, @@ -46,7 +48,13 @@ export default (document, config = {}) => (WrappedComponent) => { // Lazily resolve fragments from graphRegistry to support circular dependencies. memoized = null; - wrappedProps = (data) => { + // Props as we would pass to the BaseComponent without optimizations. + dynamicProps = {}; + + // Props that are optimized by keeping the identity of function callbacks. + staticProps = {}; + + propsWrapper = (data) => { const name = getDefinitionName(document); const callbacks = getMutationOptions(name); const mutate = (base) => { @@ -92,13 +100,13 @@ export default (document, config = {}) => (WrappedComponent) => { // Do not run updates when we have mutation errors. return prev; } - return map[key](prev, result); + return map[key](prev, result) || prev; }; } else { const existing = res[key]; res[key] = (prev, result) => { const next = existing(prev, result); - return map[key](next, result); + return map[key](next, result) || next; }; } }); @@ -132,12 +140,34 @@ export default (document, config = {}) => (WrappedComponent) => { throw error; }); }; - return config.props({...data, mutate}); + + // Save current props to `dynamicProps` + this.dynamicProps = config.props({...data, mutate}); + + // Sync props to `staticProps`. + // `staticProps` ultimately contains the same props as `dynamicProps` but all callbacks + // keep their identity. + union(Object.keys(this.dynamicProps), Object.keys(this.staticProps)).forEach((key) => { + if (!(key in this.dynamicProps)) { + delete this.staticProps[key]; + return; + } + if (typeof this.dynamicProps[key] !== 'function') { + this.staticProps[key] = this.dynamicProps[key]; + return; + } + + if (!(key in this.staticProps)) { + this.staticProps[key] = (...args) => this.dynamicProps[key](...args); + return; + } + }); + return this.staticProps; }; getWrapped = () => { if (!this.memoized) { - this.memoized = graphql(resolveFragments(document), {...config, props: this.wrappedProps})(WrappedComponent); + this.memoized = graphql(resolveFragments(document), {...config, props: this.propsWrapper})(WrappedComponent); } return this.memoized; }; @@ -147,4 +177,4 @@ export default (document, config = {}) => (WrappedComponent) => { return ; } }; -}; +}); diff --git a/client/coral-framework/hocs/withQuery.js b/client/coral-framework/hocs/withQuery.js index adb67b7b3..f19c3209e 100644 --- a/client/coral-framework/hocs/withQuery.js +++ b/client/coral-framework/hocs/withQuery.js @@ -3,6 +3,7 @@ import {graphql} from 'react-apollo'; import {getQueryOptions, resolveFragments} from 'coral-framework/services/graphqlRegistry'; import {getDefinitionName, separateDataAndRoot, getResponseErrors} from '../utils'; import PropTypes from 'prop-types'; +import hoistStatics from 'recompose/hoistStatics'; const withSkipOnErrors = (reducer) => (prev, action, ...rest) => { if (action.type === 'APOLLO_MUTATION_RESULT' && getResponseErrors(action.result)) { @@ -35,7 +36,7 @@ function networkStatusToString(networkStatus) { * Exports a HOC with the same signature as `graphql`, that will * apply query options registered in the graphRegistry. */ -export default (document, config = {}) => (WrappedComponent) => { +export default (document, config = {}) => hoistStatics((WrappedComponent) => { const name = getDefinitionName(document); return class WithQuery extends React.Component { @@ -46,6 +47,7 @@ export default (document, config = {}) => (WrappedComponent) => { // Lazily resolve fragments from graphRegistry to support circular dependencies. memoized = null; lastNetworkStatus = null; + data = null; emitWhenNeeded(data) { const {variables, networkStatus} = data; @@ -60,59 +62,93 @@ export default (document, config = {}) => (WrappedComponent) => { this.context.eventEmitter.emit(`query.${name}.${status}`, {variables, data: root}); } + nextData(data) { + this.emitWhenNeeded(data); + + // If data was previously set, we update it in a immutable way. + if (this.data) { + if (this.data.networkStatus !== data.networkStatus || + this.data.loading !== data.loading || + this.data.error !== data.error || + this.data.variables !== data.variables) { + this.data = { + ...this.data, + error: data.error, + networkStatus: data.networkStatus, + loading: data.loading, + variables: data.variables, + }; + } + } + else { + + // Set data for the first time. + this.data = { + error: data.error, + variables: data.variables, + networkStatus: data.networkStatus, + loading: data.loading, + startPolling: data.startPolling, + stopPolling: data.stopPolling, + refetch: data.refetch, + updateQuery: data.updateQuery, + subscribeToMore: (stmArgs) => { + + // Resolve document fragments before passing it to `apollo-client`. + return data.subscribeToMore({ + ...stmArgs, + document: resolveFragments(stmArgs.document), + onError: (err) => { + if (stmArgs.onErr) { + return stmArgs.onErr(err); + } + throw err; + }, + }); + }, + fetchMore: (lmArgs) => { + const fetchName = getDefinitionName(lmArgs.query); + this.context.eventEmitter.emit( + `query.${name}.fetchMore.${fetchName}.begin`, + {variables: lmArgs.variables}); + + // Resolve document fragments before passing it to `apollo-client`. + return data.fetchMore({ + ...lmArgs, + query: resolveFragments(lmArgs.query), + }) + .then((res) => { + this.context.eventEmitter.emit( + `query.${name}.fetchMore.${fetchName}.success`, + {variables: lmArgs.variables, data: res.data}); + return Promise.resolve(res); + }) + .catch((err) => { + this.context.eventEmitter.emit( + `query.${name}.fetchMore.${fetchName}.error`, + {variables: lmArgs.variables, error: err}); + throw err; + }); + }, + }; + } + return this.data; + } + wrappedConfig = { ...config, options: config.options || {}, props: (args) => { - this.emitWhenNeeded(args.data); + const nextData = this.nextData(args.data); + const {root} = separateDataAndRoot(args.data); + if (config.props) { - const wrappedArgs = { - ...args, - data: { - ...args.data, - subscribeToMore: (stmArgs) => { + // Custom props, in this case we just pass the wrapped args to it. + return config.props({...args, data: {...args.data, ...nextData}}); + } - // Resolve document fragments before passing it to `apollo-client`. - return args.data.subscribeToMore({ - ...stmArgs, - document: resolveFragments(stmArgs.document), - onError: (err) => { - if (stmArgs.onErr) { - return stmArgs.onErr(err); - } - throw err; - }, - }); - }, - fetchMore: (lmArgs) => { - const fetchName = getDefinitionName(lmArgs.query); - this.context.eventEmitter.emit( - `query.${name}.fetchMore.${fetchName}.begin`, - {variables: lmArgs.variables}); - - // Resolve document fragments before passing it to `apollo-client`. - return args.data.fetchMore({ - ...lmArgs, - query: resolveFragments(lmArgs.query), - }) - .then((res) => { - this.context.eventEmitter.emit( - `query.${name}.fetchMore.${fetchName}.success`, - {variables: lmArgs.variables, data: res.data}); - return Promise.resolve(res); - }) - .catch((err) => { - this.context.eventEmitter.emit( - `query.${name}.fetchMore.${fetchName}.error`, - {variables: lmArgs.variables, error: err}); - throw err; - }); - }, - }, - }; - return config.props - ? config.props(wrappedArgs) - : separateDataAndRoot(wrappedArgs.data); + // Return our wrapped data with a separated root. + return {...args, data: nextData, root}; }, }; @@ -128,8 +164,10 @@ export default (document, config = {}) => (WrappedComponent) => { const reducer = withSkipOnErrors( reducerCallbacks.reduce( - (a, b) => (prev, ...rest) => - b(a(prev, ...rest), ...rest), + (a, b) => (prev, ...rest) => { + const next = a(prev, ...rest); + return b(next, ...rest) || next; + } )); return { @@ -153,4 +191,4 @@ export default (document, config = {}) => (WrappedComponent) => { return ; } }; -}; +}); diff --git a/client/coral-framework/reducers/asset.js b/client/coral-framework/reducers/asset.js index f9d0a55e3..b9837eddd 100644 --- a/client/coral-framework/reducers/asset.js +++ b/client/coral-framework/reducers/asset.js @@ -1,24 +1,27 @@ -import {Map} from 'immutable'; import * as actions from '../constants/asset'; -const initialState = Map({ +const initialState = { closedAt: null, settings: null, title: null, url: null, - features: Map({}), + features: {}, status: 'open', moderation: null -}); +}; export default function asset (state = initialState, action) { switch (action.type) { case actions.FETCH_ASSET_SUCCESS: - return state - .merge(action.asset); + return { + ...state, + ...action.asset, + }; case actions.UPDATE_ASSET_SETTINGS_SUCCESS: - return state - .setIn(['settings'], action.settings); + return { + ...state, + settings: action.settings, + }; default: return state; } diff --git a/client/coral-framework/reducers/auth.js b/client/coral-framework/reducers/auth.js index 5481b7a5e..1e18ddffa 100644 --- a/client/coral-framework/reducers/auth.js +++ b/client/coral-framework/reducers/auth.js @@ -1,8 +1,7 @@ -import {Map, fromJS} from 'immutable'; import * as actions from '../constants/auth'; import pym from 'coral-framework/services/pym'; -const initialState = Map({ +const initialState = { isLoading: false, loggedIn: false, user: null, @@ -21,27 +20,34 @@ const initialState = Map({ fromSignUp: false, requireEmailConfirmation: false, redirectUri: pym.parentUrl || location.href, -}); +}; const purge = (user) => { - const {settings, profiles, ...userData} = user; // eslint-disable-line - return fromJS(userData); + const {settings, ...userData} = user; // eslint-disable-line + return userData; }; export default function auth (state = initialState, action) { switch (action.type) { case actions.FOCUS_SIGNIN_DIALOG: - return state - .set('signInDialogFocus', true); + return { + ...state, + signInDialogFocus: true, + }; case actions.BLUR_SIGNIN_DIALOG: - return state - .set('signInDialogFocus', false); - case actions.SHOW_SIGNIN_DIALOG : - return state - .set('showSignInDialog', true) - .set('signInDialogFocus', true); + return { + ...state, + signInDialogFocus: false, + }; + case actions.SHOW_SIGNIN_DIALOG: + return { + ...state, + showSignInDialog: true, + signInDialogFocus: true, + }; case actions.HIDE_SIGNIN_DIALOG : - return state.merge(Map({ + return { + ...state, isLoading: false, showSignInDialog: false, signInDialogFocus: false, @@ -53,125 +59,198 @@ export default function auth (state = initialState, action) { emailVerificationSuccess: false, emailVerificationLoading: false, successSignUp: false - })); - case actions.SHOW_CREATEUSERNAME_DIALOG : - return state - .set('showCreateUsernameDialog', true); - case actions.HIDE_CREATEUSERNAME_DIALOG : - return state.merge(Map({ - showCreateUsernameDialog: false - })); - case actions.CREATE_USERNAME_SUCCESS : - return state.merge(Map({ + }; + case actions.SHOW_CREATEUSERNAME_DIALOG: + return { + ...state, + showCreateUsernameDialog: true, + }; + case actions.HIDE_CREATEUSERNAME_DIALOG: + return { + ...state, showCreateUsernameDialog: false, - error: '' - })); - case actions.CREATE_USERNAME_FAILURE : - return state - .set('error', action.error); - case actions.CHANGE_VIEW : - return state - .set('error', '') - .set('view', action.view); + }; + case actions.CREATE_USERNAME_SUCCESS: + return { + ...state, + showCreateUsernameDialog: false, + error: '', + }; + case actions.CREATE_USERNAME_FAILURE: + return { + ...state, + error: action.error, + }; + case actions.CHANGE_VIEW: + return { + ...state, + error: action.error, + view: action.view, + }; case actions.CLEAN_STATE: return initialState; case actions.FETCH_SIGNIN_REQUEST: - return state - .set('isLoading', true); + return { + ...state, + isLoading: true, + }; case actions.CHECK_LOGIN_FAILURE: - return state - .set('checkedInitialLogin', true) - .set('loggedIn', false) - .set('user', null); + return { + ...state, + checkedInitialLogin: true, + loggedIn: false, + user: null, + }; case actions.CHECK_LOGIN_SUCCESS: - return state - .set('checkedInitialLogin', true) - .set('loggedIn', true) - .set('user', purge(action.user)); + return { + ...state, + checkedInitialLogin: true, + loggedIn: true, + user: purge(action.user), + }; case actions.FETCH_SIGNIN_SUCCESS: - return state - .set('loggedIn', true) - .set('user', purge(action.user)); + return { + ...state, + loggedIn: true, + user: purge(action.user), + }; case actions.FETCH_SIGNIN_FAILURE: - return state - .set('isLoading', false) - .set('error', action.error) - .set('user', null); + return { + ...state, + isLoading: false, + error: action.error, + user: null, + }; case actions.FETCH_SIGNUP_FACEBOOK_REQUEST: - return state - .set('fromSignUp', true); + return { + ...state, + fromSignUp: true, + }; case actions.FETCH_SIGNIN_FACEBOOK_REQUEST: - return state - .set('fromSignUp', false); + return { + ...state, + fromSignUp: false, + }; case actions.FETCH_SIGNIN_FACEBOOK_SUCCESS: - return state - .set('user', purge(action.user)) - .set('loggedIn', true); + return { + ...state, + loggedIn: true, + user: purge(action.user), + }; case actions.FETCH_SIGNIN_FACEBOOK_FAILURE: - return state - .set('error', action.error) - .set('user', null); + return { + ...state, + error: action.error, + user: null, + }; case actions.FETCH_SIGNUP_REQUEST: - return state - .set('isLoading', true); + return { + ...state, + isLoading: true, + }; case actions.FETCH_SIGNUP_FAILURE: - return state - .set('error', action.error) - .set('isLoading', false); + return { + ...state, + error: action.error, + isLoading: false, + }; case actions.FETCH_SIGNUP_SUCCESS: - return state - .set('isLoading', false) - .set('successSignUp', true); + return { + ...state, + isLoading: false, + successSignUp: true, + }; case actions.LOGOUT: - return state - .set('user', null) - .set('isLoading', false) - .set('loggedIn', false); + return { + ...state, + user: null, + isLoading: false, + loggedIn: false, + }; case actions.INVALID_FORM: - return state - .set('error', action.error); + return { + ...state, + error: action.error, + }; case actions.VALID_FORM: - return state - .set('error', ''); + return { + ...state, + error: '', + }; case actions.FETCH_FORGOT_PASSWORD_SUCCESS: - return state - .set('passwordRequestFailure', null) - .set('passwordRequestSuccess', 'If you have a registered account, a password reset link was sent to that email'); + return { + ...state, + passwordRequestFailure: null, + passwordRequestSuccess: 'If you have a registered account, a password reset link was sent to that email', + }; case actions.FETCH_FORGOT_PASSWORD_FAILURE: - return state - .set('passwordRequestFailure', 'There was an error sending your password reset email. Please try again soon!') - .set('passwordRequestSuccess', null); + return { + ...state, + passwordRequestFailure: 'There was an error sending your password reset email. Please try again soon!', + passwordRequestSuccess: null, + }; case actions.UPDATE_USERNAME: - return state - .setIn(['user', 'username'], action.username); + return { + ...state, + user: { + ...state.user, + username: action.username, + } + }; case actions.VERIFY_EMAIL_FAILURE: - return state - .set('emailVerificationFailure', true) - .set('emailVerificationLoading', false); + return { + ...state, + emailVerificationFailure: true, + emailVerificationLoading: false, + }; case actions.VERIFY_EMAIL_REQUEST: - return state.set('emailVerificationLoading', true); + return { + ...state, + emailVerificationLoading: true, + }; case actions.VERIFY_EMAIL_SUCCESS: - return state - .set('emailVerificationSuccess', true) - .set('emailVerificationLoading', false); + return { + ...state, + emailVerificationSuccess: true, + emailVerificationLoading: false, + }; case actions.SET_REQUIRE_EMAIL_VERIFICATION: - return state - .set('requireEmailConfirmation', action.required); + return { + ...state, + requireEmailConfirmation: action.required, + }; case actions.SET_REDIRECT_URI: - return state - .set('redirectUri', action.uri); + return { + ...state, + redirectUri: action.uri, + }; case 'APOLLO_SUBSCRIPTION_RESULT': if (action.operationName === 'UserBanned' && state.getIn(['user', 'id']) === action.variables.user_id) { - return state - .mergeIn(['user'], action.result.data.userBanned); + return { + ...state, + user: { + ...state.user, + ...action.result.data.userBanned, + }, + }; } if (action.operationName === 'UserSuspended' && state.getIn(['user', 'id']) === action.variables.user_id) { - return state - .mergeIn(['user'], action.result.data.userSuspended); + return { + ...state, + user: { + ...state.user, + ...action.result.data.userSuspended, + }, + }; } if (action.operationName === 'UsernameRejected' && state.getIn(['user', 'id']) === action.variables.user_id) { - return state - .mergeIn(['user'], action.result.data.usernameRejected); + return { + ...state, + user: { + ...state.user, + ...action.result.data.usernameRejected, + }, + }; } return state; default : diff --git a/client/coral-framework/reducers/index.js b/client/coral-framework/reducers/index.js index f1ac580dc..6b9b730ca 100644 --- a/client/coral-framework/reducers/index.js +++ b/client/coral-framework/reducers/index.js @@ -1,11 +1,9 @@ import auth from './auth'; -import user from './user'; import asset from './asset'; import {reducer as commentBox} from '../../talk-plugin-commentbox'; export default { auth, - user, asset, commentBox, }; diff --git a/client/coral-framework/reducers/user.js b/client/coral-framework/reducers/user.js deleted file mode 100644 index bc40cf3ae..000000000 --- a/client/coral-framework/reducers/user.js +++ /dev/null @@ -1,43 +0,0 @@ -import {Map} from 'immutable'; -import * as authActions from '../constants/auth'; -import * as actions from '../constants/user'; -import * as assetActions from '../constants/assets'; - -const initialState = Map({ - username: '', - profiles: [], - settings: {}, - myComments: [], - myAssets: [], // the assets from which myComments (above) originated -}); - -const purge = (user) => { - const {_id, created_at, updated_at, __v, roles, ...userData} = user; // eslint-disable-line - return userData; -}; - -export default function user (state = initialState, action) { - switch (action.type) { - case authActions.CHECK_LOGIN_SUCCESS: - return state.merge(Map(purge(action.user))); - case authActions.CHECK_LOGIN_FAILURE: - return initialState; - case authActions.FETCH_SIGNIN_SUCCESS: - return state.merge(Map(purge(action.user))); - case authActions.FETCH_SIGNIN_FAILURE: - return initialState; - case authActions.FETCH_SIGNIN_FACEBOOK_SUCCESS: - return state.merge(Map(purge(action.user))); - case authActions.FETCH_SIGNIN_FACEBOOK_FAILURE: - return initialState; - case actions.SAVE_BIO_SUCCESS: - return state.set('settings', action.settings); - case actions.COMMENTS_BY_USER_SUCCESS: - return state.set('myComments', action.comments); - case assetActions.MULTIPLE_ASSETS_SUCCESS: - return state.set('myAssets', action.assets); - case actions.LOGOUT_SUCCESS: - return initialState; - } - return state; -} diff --git a/client/coral-framework/utils/index.js b/client/coral-framework/utils/index.js index 63dfd7dc4..2b4b6378f 100644 --- a/client/coral-framework/utils/index.js +++ b/client/coral-framework/utils/index.js @@ -1,5 +1,6 @@ import {gql} from 'react-apollo'; import t from 'coral-framework/services/i18n'; +import union from 'lodash/union'; import {capitalize} from 'coral-framework/helpers/strings'; export const getTotalActionCount = (type, comment) => { @@ -184,3 +185,8 @@ export function getSlotFragmentSpreads(slots, resource) { export function isCommentActive(commentStatus) { return ['NONE', 'ACCEPTED'].indexOf(commentStatus) >= 0; } + +export function getShallowChanges(a, b) { + return union(Object.keys(a), Object.keys(b)) + .filter((key) => a[key] !== b[key]); +} diff --git a/client/coral-framework/utils/user.js b/client/coral-framework/utils/user.js new file mode 100644 index 000000000..044583026 --- /dev/null +++ b/client/coral-framework/utils/user.js @@ -0,0 +1,14 @@ + /** + * getReliability + * retrieves reliability value as string + */ + +export const getReliability = (reliabilityValue) => { + if (reliabilityValue === null) { + return 'neutral'; + } else if (reliabilityValue) { + return 'reliable'; + } else { + return 'unreliable'; + } +}; diff --git a/client/coral-settings/containers/ProfileContainer.js b/client/coral-settings/containers/ProfileContainer.js index 91de923b2..f1b3787dd 100644 --- a/client/coral-settings/containers/ProfileContainer.js +++ b/client/coral-settings/containers/ProfileContainer.js @@ -1,7 +1,8 @@ import {connect} from 'react-redux'; -import {compose, graphql, gql} from 'react-apollo'; +import {compose, gql} from 'react-apollo'; import React, {Component} from 'react'; import {bindActionCreators} from 'redux'; +import {withQuery} from 'coral-framework/hocs'; import {withStopIgnoringUser} from 'coral-framework/graphql/mutations'; @@ -11,18 +12,13 @@ import IgnoredUsers from '../components/IgnoredUsers'; import {Spinner} from 'coral-ui'; import CommentHistory from 'talk-plugin-history/CommentHistory'; import {showSignInDialog, checkLogin} from 'coral-framework/actions/auth'; +import {insertCommentsSorted} from 'plugin-api/beta/client/utils'; +import update from 'immutability-helper'; +import {getSlotFragmentSpreads} from 'coral-framework/utils'; import t from 'coral-framework/services/i18n'; class ProfileContainer extends Component { - constructor() { - super(); - - this.state = { - activeTab: 0 - }; - } - componentWillReceiveProps(nextProps) { if (!this.props.auth.loggedIn && nextProps.auth.loggedIn) { @@ -31,32 +27,51 @@ class ProfileContainer extends Component { } } - handleTabChange = (tab) => { - this.setState({ - activeTab: tab + loadMore = () => { + return this.props.data.fetchMore({ + query: LOAD_MORE_QUERY, + variables: { + limit: 5, + cursor: this.props.root.me.comments.endCursor, + }, + updateQuery: (previous, {fetchMoreResult:{comments}}) => { + const updated = update(previous, { + me: { + comments: { + nodes: { + $apply: (nodes) => insertCommentsSorted(nodes, comments.nodes, 'REVERSE_CHRONOLOGICAL'), + }, + hasNextPage: {$set: comments.hasNextPage}, + endCursor: {$set: comments.endCursor}, + }, + } + }); + return updated; + }, }); }; render() { - const {auth, asset, data, showSignInDialog, stopIgnoringUser} = this.props; - const {me} = this.props.data; + const {auth, auth: {user}, showSignInDialog, stopIgnoringUser, root, data} = this.props; + const {me} = this.props.root; + const loading = this.props.data.loading; if (!auth.loggedIn) { return ; } - if (!me || data.loading) { + if (loading) { return ; } - const localProfile = this.props.user.profiles.find( + const localProfile = user.profiles.find( (p) => p.provider === 'local' ); const emailAddress = localProfile && localProfile.id; return (
    -

    {this.props.user.username}

    +

    {user.username}

    {emailAddress ?

    {emailAddress}

    : null} {me.ignoredUsers && me.ignoredUsers.length @@ -73,14 +88,47 @@ class ProfileContainer extends Component {

    {t('framework.my_comments')}

    {me.comments.nodes.length - ? + ? :

    {t('user_no_comment')}

    }
    ); } } -const withQuery = graphql( +// TODO: This Slot should be included in `talk-plugin-history` instead. +const slots = [ + 'commentContent', +]; + +const CommentFragment = gql` + fragment TalkSettings_CommentConnectionFragment on CommentConnection { + nodes { + id + body + asset { + id + title + url + ${getSlotFragmentSpreads(slots, 'asset')} + } + created_at + ${getSlotFragmentSpreads(slots, 'comment')} + } + endCursor + hasNextPage + } +`; + +const LOAD_MORE_QUERY = gql` + query TalkSettings_LoadMoreComments($limit: Int, $cursor: Date) { + comments(query: {limit: $limit, cursor: $cursor}) { + ...TalkSettings_CommentConnectionFragment + } + } + ${CommentFragment} +`; + +const withProfileQuery = withQuery( gql` query CoralEmbedStream_Profile { me { @@ -89,26 +137,17 @@ const withQuery = graphql( id, username, } - comments { - nodes { - id - body - asset { - id - title - url - } - created_at - } + comments(query: {limit: 10}) { + ...TalkSettings_CommentConnectionFragment } } - }` -); + ${getSlotFragmentSpreads(slots, 'root')} + } + ${CommentFragment} +`); const mapStateToProps = (state) => ({ - user: state.user.toJS(), - asset: state.asset.toJS(), - auth: state.auth.toJS() + auth: state.auth }); const mapDispatchToProps = (dispatch) => @@ -117,5 +156,5 @@ const mapDispatchToProps = (dispatch) => export default compose( connect(mapStateToProps, mapDispatchToProps), withStopIgnoringUser, - withQuery + withProfileQuery )(ProfileContainer); diff --git a/client/coral-ui/components/Badge.css b/client/coral-ui/components/Badge.css new file mode 100644 index 000000000..db68ebd58 --- /dev/null +++ b/client/coral-ui/components/Badge.css @@ -0,0 +1,20 @@ +.badge { + display: inline-block; + color: white; + background: grey; + box-sizing: border-box; + padding: 2px 5px; + font-size: 12px; + height: 24px; + letter-spacing: 0.4px; + line-height: 22px; + background-color: #3D73D5; + margin-right: 4px; +} + +.icon { + font-size: 14px; + vertical-align: text-top; + margin: 0; + margin-right: 4px; +} \ No newline at end of file diff --git a/client/coral-ui/components/Badge.js b/client/coral-ui/components/Badge.js new file mode 100644 index 000000000..c1ba8100b --- /dev/null +++ b/client/coral-ui/components/Badge.js @@ -0,0 +1,13 @@ +import React from 'react'; +import styles from './Badge.css'; +import Icon from './Icon'; +import cn from 'classnames'; + +const Badge = ({className, children, icon, props}) => ( + + {icon && } + {children} + +); + +export default Badge; diff --git a/client/coral-ui/components/Button.css b/client/coral-ui/components/Button.css index 7bd1d4379..1b7efb205 100644 --- a/client/coral-ui/components/Button.css +++ b/client/coral-ui/components/Button.css @@ -27,9 +27,10 @@ } .icon { - margin-right: 13px; + margin-right: 5px; font-size: 18px; vertical-align: middle; + margin-top: -3px; } .type--black { @@ -143,7 +144,7 @@ border-radius: 3px; text-transform: capitalize; box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.03), 0 3px 1px -2px rgba(0,0,0,.2), 0 1px 5px 0 rgba(0,0,0,.09); - width: 128px; + width: 129px; &:hover { box-shadow: none; @@ -166,7 +167,7 @@ border-radius: 3px; text-transform: capitalize; box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.03), 0 3px 1px -2px rgba(0,0,0,.2), 0 1px 5px 0 rgba(0,0,0,.09); - width: 128px; + width: 129px; &:hover { color: white; diff --git a/client/coral-ui/components/Drawer.css b/client/coral-ui/components/Drawer.css index d6a7e6871..88c30425f 100644 --- a/client/coral-ui/components/Drawer.css +++ b/client/coral-ui/components/Drawer.css @@ -3,7 +3,7 @@ min-width: 550px; position: fixed; top: 0; - right: -17px; + right: 0px; bottom: 0; background-color: white; transition: transform 500ms ease-in-out; diff --git a/client/coral-ui/components/Icon.css b/client/coral-ui/components/Icon.css index 16fe6d235..1a118257a 100644 --- a/client/coral-ui/components/Icon.css +++ b/client/coral-ui/components/Icon.css @@ -1,3 +1,5 @@ .root { + vertical-align: middle; + font-size: inherit; } diff --git a/client/coral-ui/index.js b/client/coral-ui/index.js index 8a538d120..8f261bcca 100644 --- a/client/coral-ui/index.js +++ b/client/coral-ui/index.js @@ -26,3 +26,4 @@ export {default as Option} from './components/Option'; export {default as SnackBar} from './components/SnackBar'; export {default as TextArea} from './components/TextArea'; export {default as Drawer} from './components/Drawer'; +export {default as Badge} from './components/Badge'; diff --git a/client/talk-plugin-author-name/AuthorName.js b/client/talk-plugin-author-name/AuthorName.js deleted file mode 100644 index 89835a742..000000000 --- a/client/talk-plugin-author-name/AuthorName.js +++ /dev/null @@ -1,31 +0,0 @@ -import React, {Component} from 'react'; -const packagename = 'talk-plugin-author-name'; - -export default class AuthorName extends Component { - - state = {showTooltip: false} - - handleClick = () => { - this.setState((state) => ({ - showTooltip: !state.showTooltip - })); - } - - handleMouseLeave = () => { - setTimeout(() => { - this.setState({ - showTooltip: false - }); - }, 500); - } - - render () { - const {author} = this.props; - return ( -
    - {author && author.username} -
    - ); - } -} diff --git a/client/talk-plugin-author-name/styles.css b/client/talk-plugin-author-name/styles.css deleted file mode 100644 index b7870a862..000000000 --- a/client/talk-plugin-author-name/styles.css +++ /dev/null @@ -1,34 +0,0 @@ -.authorName { - color: black; - display: inline-block; - margin: 10px 8px 10px 0; -} - -.hasBio { - &:hover { - cursor: pointer; - } -} - -.arrowDown { - top: 0; - width: 0; - height: 0; - margin-top: -2px; - margin-left: 2px; - display: inline-block; - vertical-align: middle; - border-bottom: 0; - border-left: 3px solid transparent; - border-right: 3px solid transparent; - border-top: 3px solid #000000; -} - -.arrowUp { - width: 0; - height: 0; - border-top: 0; - border-left: 3px solid transparent; - border-right: 3px solid transparent; - border-bottom: 3px solid black; -} diff --git a/client/talk-plugin-flags/components/FlagButton.js b/client/talk-plugin-flags/components/FlagButton.js index 85ceed0ea..1d8438ba0 100644 --- a/client/talk-plugin-flags/components/FlagButton.js +++ b/client/talk-plugin-flags/components/FlagButton.js @@ -133,7 +133,9 @@ export default class FlagButton extends Component { } handleClickOutside = () => { - this.closeMenu(); + if (this.state.showMenu) { + this.closeMenu(); + } } render () { diff --git a/client/talk-plugin-history/Comment.js b/client/talk-plugin-history/Comment.js index f90362e2d..4cf9d875c 100644 --- a/client/talk-plugin-history/Comment.js +++ b/client/talk-plugin-history/Comment.js @@ -7,54 +7,55 @@ import CommentContent from '../coral-embed-stream/src/components/CommentContent' import t from 'coral-framework/services/i18n'; -const Comment = (props) => { - return ( - -
    - ); -}; + ); + } +} Comment.propTypes = { comment: PropTypes.shape({ id: PropTypes.string, body: PropTypes.string }).isRequired, - asset: PropTypes.shape({ - url: PropTypes.string, - title: PropTypes.string - }).isRequired }; export default Comment; diff --git a/client/talk-plugin-history/CommentHistory.js b/client/talk-plugin-history/CommentHistory.js index 72c4de982..43ae93f1d 100644 --- a/client/talk-plugin-history/CommentHistory.js +++ b/client/talk-plugin-history/CommentHistory.js @@ -1,25 +1,54 @@ import React, {PropTypes} from 'react'; import Comment from './Comment'; import styles from './CommentHistory.css'; +import LoadMore from './LoadMore'; +import {forEachError} from 'plugin-api/beta/client/utils'; -const CommentHistory = (props) => { - return ( -
    -
    - {props.comments.map((comment, i) => { - return ; - })} +class CommentHistory extends React.Component { + state = { + loadingState: '', + }; + + loadMore = () => { + this.setState({loadingState: 'loading'}); + this.props.loadMore() + .then(() => { + this.setState({loadingState: 'success'}); + }) + .catch((error) => { + this.setState({loadingState: 'error'}); + forEachError(error, ({msg}) => {this.props.addNotification('error', msg);}); + }); + } + + render() { + const {link, comments, data, root} = this.props; + return ( +
    +
    + {comments.nodes.map((comment, i) => { + return ; + })} +
    + {comments.hasNextPage && + + }
    -
    - ); -}; + ); + } +} CommentHistory.propTypes = { - comments: PropTypes.array.isRequired + comments: PropTypes.object.isRequired }; export default CommentHistory; diff --git a/client/talk-plugin-history/LoadMore.js b/client/talk-plugin-history/LoadMore.js new file mode 100644 index 000000000..a168ed43a --- /dev/null +++ b/client/talk-plugin-history/LoadMore.js @@ -0,0 +1,30 @@ +import React from 'react'; +import PropTypes from 'prop-types'; +import {Button} from 'coral-ui'; +import t from 'coral-framework/services/i18n'; +import cn from 'classnames'; + +class LoadMore extends React.Component { + render () { + const {loadingState, loadMore} = this.props; + const disabled = loadingState === 'loading'; + return ( +
    + +
    + ); + } +} + +LoadMore.propTypes = { + loadMore: PropTypes.func.isRequired, + loadingState: PropTypes.oneOf(['', 'loading', 'success', 'error']), +}; + +export default LoadMore; diff --git a/client/talk-plugin-moderation/ModerationLink.js b/client/talk-plugin-moderation/ModerationLink.js index 020b8c345..1a10160ee 100644 --- a/client/talk-plugin-moderation/ModerationLink.js +++ b/client/talk-plugin-moderation/ModerationLink.js @@ -2,10 +2,11 @@ import React, {PropTypes} from 'react'; import styles from './styles.css'; import t from 'coral-framework/services/i18n'; +import {BASE_PATH} from 'coral-framework/constants/url'; const ModerationLink = (props) => props.isAdmin ? ( diff --git a/config.js b/config.js index faa911c83..d02cb59ab 100644 --- a/config.js +++ b/config.js @@ -7,6 +7,9 @@ // entrypoint for the entire applications configuration. require('env-rewrite').rewrite(); +const uniq = require('lodash/uniq'); +const ms = require('ms'); + //============================================================================== // CONFIG INITIALIZATION //============================================================================== @@ -31,6 +34,13 @@ const CONFIG = { // token. JWT_COOKIE_NAME: process.env.TALK_JWT_COOKIE_NAME || 'authorization', + // JWT_SIGNING_COOKIE_NAME will be the cookie set when cookies are issued. + // This defaults to the TALK_JWT_COOKIE_NAME value. + JWT_SIGNING_COOKIE_NAME: process.env.TALK_JWT_SIGNING_COOKIE_NAME || process.env.TALK_JWT_COOKIE_NAME || 'authorization', + + // JWT_COOKIE_NAMES declares the many cookie names used for verification. + JWT_COOKIE_NAMES: process.env.TALK_JWT_COOKIE_NAMES || null, + // JWT_CLEAR_COOKIE_LOGOUT specifies whether the named cookie should be // cleared when the user is logged out. JWT_CLEAR_COOKIE_LOGOUT: process.env.TALK_JWT_CLEAR_COOKIE_LOGOUT ? process.env.TALK_JWT_CLEAR_COOKIE_LOGOUT !== 'FALSE' : true, @@ -75,6 +85,23 @@ const CONFIG = { MONGO_URL: process.env.TALK_MONGO_URL, REDIS_URL: process.env.TALK_REDIS_URL, + // REDIS_RECONNECTION_MAX_ATTEMPTS is the amount of attempts that a redis + // connection will attempt to reconnect before aborting with an error. + REDIS_RECONNECTION_MAX_ATTEMPTS: parseInt(process.env.TALK_REDIS_RECONNECTION_MAX_ATTEMPTS || '100'), + + // REDIS_RECONNECTION_MAX_RETRY_TIME is the time in string format for the + // maximum amount of time that a client can be considered "connecting" before + // attempts at reconnection are aborted with an error. + REDIS_RECONNECTION_MAX_RETRY_TIME: ms(process.env.TALK_REDIS_RECONNECTION_MAX_RETRY_TIME || '1 min'), + + // REDIS_RECONNECTION_BACKOFF_FACTOR is the factor that will be multiplied + // against the current attempt count inbetween attempts to connect to redis. + REDIS_RECONNECTION_BACKOFF_FACTOR: ms(process.env.TALK_REDIS_RECONNECTION_BACKOFF_FACTOR || '500 ms'), + + // REDIS_RECONNECTION_BACKOFF_MINIMUM_TIME is the minimum time used to delay + // before attempting to reconnect to redis. + REDIS_RECONNECTION_BACKOFF_MINIMUM_TIME: ms(process.env.TALK_REDIS_RECONNECTION_BACKOFF_MINIMUM_TIME || '1 sec'), + //------------------------------------------------------------------------------ // Server Config //------------------------------------------------------------------------------ @@ -85,6 +112,10 @@ const CONFIG = { // The URL for this Talk Instance as viewable from the outside. ROOT_URL: process.env.TALK_ROOT_URL || null, + // ROOT_URL_MOUNT_PATH when TRUE will extract the pathname from the + // TALK_ROOT_URL and use it to mount the paths on. + ROOT_URL_MOUNT_PATH: process.env.TALK_ROOT_URL_MOUNT_PATH === 'TRUE', + // The keepalive timeout (in ms) that should be used to send keep alive // messages through the websocket to keep the socket alive. KEEP_ALIVE: process.env.TALK_KEEP_ALIVE || '30s', @@ -122,13 +153,17 @@ const CONFIG = { DISABLE_AUTOFLAG_SUSPECT_WORDS: process.env.TALK_DISABLE_AUTOFLAG_SUSPECT_WORDS === 'TRUE', // TRUST_THRESHOLDS defines the thresholds used for automoderation. - TRUST_THRESHOLDS: process.env.TRUST_THRESHOLDS || 'comment:-1,-1;flag:-1,-1' + TRUST_THRESHOLDS: process.env.TRUST_THRESHOLDS || 'comment:2,-1;flag:2,-1' }; //============================================================================== // CONFIG VALIDATION //============================================================================== +if (CONFIG.ROOT_URL_MOUNT_PATH && !CONFIG.ROOT_URL) { + throw new Error('TALK_ROOT_URL must be specified if TALK_ROOT_URL_MOUNT_PATH is set to TRUE'); +} + if (process.env.NODE_ENV === 'test' && !CONFIG.ROOT_URL) { CONFIG.ROOT_URL = 'http://localhost:3000'; } else if (!CONFIG.ROOT_URL) { @@ -165,18 +200,28 @@ if (CONFIG.JWT_DISABLE_ISSUER) { CONFIG.JWT_ISSUER = undefined; } +// Parse and handle cookie names. +if (CONFIG.JWT_COOKIE_NAMES) { + CONFIG.JWT_COOKIE_NAMES = CONFIG.JWT_COOKIE_NAMES.split(','); +} else { + CONFIG.JWT_COOKIE_NAMES = []; +} + +// Add in the default cookie names and strip duplicates. +CONFIG.JWT_COOKIE_NAMES = uniq(CONFIG.JWT_COOKIE_NAMES.concat([CONFIG.JWT_COOKIE_NAME, CONFIG.JWT_SIGNING_COOKIE_NAME])); + //------------------------------------------------------------------------------ // External database url's //------------------------------------------------------------------------------ -// Reset the mongo url in the event it hasn't been overrided and we are in a +// Reset the mongo url in the event it hasn't been overridden and we are in a // testing environment. Every new mongo instance comes with a test database by // default, this is consistent with common testing and use case practices. if (process.env.NODE_ENV === 'test' && !CONFIG.MONGO_URL) { CONFIG.MONGO_URL = 'mongodb://localhost/test'; } -// Reset the redis url in the event it hasn't been overrided and we are in a +// Reset the redis url in the event it hasn't been overridden and we are in a // testing environment. if (process.env.NODE_ENV === 'test' && !CONFIG.REDIS_URL) { CONFIG.REDIS_URL = 'redis://localhost/1'; diff --git a/docs/_docs/00-01-faq.md b/docs/_docs/00-01-faq.md index cdaf5dbf3..01172f84a 100644 --- a/docs/_docs/00-01-faq.md +++ b/docs/_docs/00-01-faq.md @@ -5,39 +5,63 @@ permalink: /docs/faq/ ### How are new stories/assets added to Talk? Is there an API? -There are three ways that new assets can make their way into Talk: _just in time_, _active_ and manual. +There are three ways that new assets can make their way into Talk: + +- Just in time +- Active +- Manual #### Just in Time asset creation -Talk ships with a _just in time_ mechanism that works out of the box without integration with any CMS or manual work needed. +Talk ships with a _just in time_ mechanism that works out of the box without +integration with any CMS or manual work needed. The _just in time_ flow looks like this: * Request comes in for a stream on an asset that doesn't yet exist. * Talk screens the domain against the domain whitelist, fails if doesn't pass. * Then, concurrently - * Talk creates a new asset record and returns the stream data (which will be empty) + * Talk creates a new asset record and returns the stream data (which will be + empty) * Schedules a job to scrape the new page and fill in asset information. -The scraping mechanism utilizes [metascraper](https://www.npmjs.com/package/metascraper) and is queued using the [Que](https://www.npmjs.com/package/kue). If your Talk deployments is configured to run separate job worker cluster, scraping will be performed by them. +The scraping mechanism utilizes +[metascraper](https://www.npmjs.com/package/metascraper) and is queued using the +[Que](https://www.npmjs.com/package/kue). If your Talk deployments is configured +to run separate job worker cluster, scraping will be performed by them. #### Active (or push based) asset creation -If tighter CMS integration is required to push custom data into assets and/or keep data in sync as changes are made in a CMS an _active_ push based workflow must be implemented. +If tighter CMS integration is required to push custom data into assets and/or +keep data in sync as changes are made in a CMS an _active_ push based workflow +must be implemented. -This is an ideal candidate for a plugin. If you are interested in working on it, please [contact us](https://coralproject.net/contact)! +This is an ideal candidate for a plugin. If you are interested in working on it, +please [contact us](https://coralproject.net/contact)! #### Manual asset creation -Sometimes you want to load a lot of assets into the database. The most common use case for this is populating the database during an initial installation. We recommend writing a script that transforms the data from it's source and inserts it into the _assets_ collection. +Sometimes you want to load a lot of assets into the database. The most common +use case for this is populating the database during an initial installation. We +recommend writing a script that transforms the data from it's source and inserts +it into the _assets_ collection. -For current schema information, please see the [asset model](https://github.com/coralproject/talk/blob/master/models/asset.js). +For current schema information, please see the +[asset model](https://github.com/coralproject/talk/blob/master/models/asset.js). ### Where are your http API docs? -Coral relies on GraphQL for the vast majority of it's client <-> server communication. All core queries, mutations and subscriptions are defined along with types and comments in our central [TypeDef](https://github.com/coralproject/talk/blob/master/graph/typeDefs.graphql). For plugin graph api typedefs, see each plugin's `/server/` directory. +Coral relies on GraphQL for the vast majority of it's client and server +communication. All core queries, mutations and subscriptions are defined along +with types and comments in our central +[TypeDef](https://github.com/coralproject/talk/blob/master/graph/typeDefs.graphql). +For plugin graph api typedefs, see each plugin's `/server/` directory. -In addition, Talk Server ships with [GraphiQL](https://github.com/graphql/graphiql). GraphiQL provides a full data layer IDE including interactive documentation. The autocompletes and documentation are populated from introspection meaning that Core _and plugin_ apis will be fully explorable. +In addition, Talk Server ships with +[GraphiQL](https://github.com/graphql/graphiql). GraphiQL provides a full data +layer IDE including interactive documentation. The autocomplete and +documentation are populated from introspection meaning that Core _and plugin_ +apis can be explored. To access GraphiQL: @@ -46,22 +70,33 @@ To access GraphiQL: ### Where is documentation for a specific component? -We strive for clear inline documentation across our codebase, but have gaps. Contributions to documentation would be greatly appreciated and is a great way to start contributing to the project! +We strive for clear inline documentation across our codebase, but have gaps. +Contributions to documentation would be greatly appreciated and is a great way +to start contributing to the project! -If you are considering changing a core component (aka, one that is not in a plugin), you are entering the realm of a core developer. We strongly ask that you reach out the coral team before forking and changing core code. We are glad to help talk through your product need and come up with a strategy for implementing as a plugin, or working with you to extend the plugin API for your use case. +If you are considering changing a core component (aka, one that is not in a +plugin), you are entering the realm of a core developer. We strongly ask that +you reach out the coral team before forking and changing core code. We are glad +to help talk through your product need and come up with a strategy for +implementing as a plugin, or working with you to extend the plugin API for your +use case. ### How do I contribute to these docs? -Contributions to the docs are much appreciated and a great way to get involved in the project. +Contributions to the docs are much appreciated and a great way to get involved +in the project. -Fork the Talk repo, clone it locally (no need to go through the install from source process), then: +Fork the Talk repo, clone it locally (no need to go through the install from +source process), then: ``` cd docs docker run --rm --volume=$PWD:/srv/jekyll -p 127.0.0.1:4000:4000 -it jekyll/jekyll:pages jekyll serve ``` -You can edit the files in docs with any editor and view the live updates in a browser by hitting From the docs directory. -Then visit: [http://127.0.0.1:4000/talk/](http://127.0.0.1:4000/talk/). +You can edit the files in docs with any editor and view the live updates in a +browser by hitting From the docs directory. Then visit: +[http://127.0.0.1:4000/talk/](http://127.0.0.1:4000/talk/). -Once you've made the changes, file a PR back to the `coralproject/talk` repo. +Once you've made the changes, file a PR back to the `coralproject/talk` +repository. diff --git a/docs/_docs/01-02-install-docker.md b/docs/_docs/01-02-install-docker.md index cf9c1fa0e..9d177049e 100644 --- a/docs/_docs/01-02-install-docker.md +++ b/docs/_docs/01-02-install-docker.md @@ -11,8 +11,9 @@ Available as [coralproject/talk](https://hub.docker.com/r/coralproject/talk/) on Images are tagged using the following notation: -- `x` (where `x` is the major version number): any minor or patch updates will be included in this. If you're ok getting - new features occasionally and all the bug fixes, this is the tag for you. +- `x` (where `x` is the major version number): any minor or patch updates will + be included in this. If you're ok getting new features occasionally and all + the bug fixes, this is the tag for you. - `x.y` (where `y` is the minor version number): any patch updates will be included with this tag. If you like getting fixes and having features change only when you want, this is the tag for you. **(recommended)** @@ -42,7 +43,7 @@ An example docker-compose.yml: version: '2' services: talk: - image: coralproject/talk:1.5 + image: coralproject/talk:latest restart: always ports: - "5000:5000" @@ -85,7 +86,7 @@ on different machines. You can achieve this easily with docker compose: version: '2' services: talk-api: - image: coralproject/talk:1.5 + image: coralproject/talk:latest command: cli serve restart: always ports: @@ -97,7 +98,7 @@ services: - TALK_MONGO_URL=mongodb://mongo/talk - TALK_REDIS_URL=redis://redis talk-jobs: - image: coralproject/talk:1.5 + image: coralproject/talk:latest command: cli jobs process restart: always ports: diff --git a/docs/_docs/01-03-install-source.md b/docs/_docs/01-03-install-source.md index 3f05478ce..66dc94db6 100644 --- a/docs/_docs/01-03-install-source.md +++ b/docs/_docs/01-03-install-source.md @@ -36,7 +36,7 @@ git clone https://github.com/coralproject/talk.git We now have to install the dependencies and build the static assets. ```bash -# Install package dependancies +# Install package dependencies yarn # Build static files diff --git a/docs/_docs/01-05-install-microservices.md b/docs/_docs/01-05-install-microservices.md index 8e80a13ac..dc5ff112e 100644 --- a/docs/_docs/01-05-install-microservices.md +++ b/docs/_docs/01-05-install-microservices.md @@ -70,7 +70,7 @@ independently. Each variety of process can always have just enough resources. An install that heavily utilizes the jobs queue could see delays in http service because of heavy jobs processes and/or delays in the execution of jobs processes -due to increased server load as a result of Node's single thread infrustructure. +due to increased server load as a result of Node's single thread infrastructure. ## Deployment Methodologies diff --git a/docs/_docs/02-01-configuration.md b/docs/_docs/02-01-configuration.md index 74bd8972e..df790b24b 100644 --- a/docs/_docs/02-01-configuration.md +++ b/docs/_docs/02-01-configuration.md @@ -52,14 +52,36 @@ These are only used during the webpack build. - `TALK_MONGO_URL` (*required*) - the database connection string for the MongoDB database. - `TALK_REDIS_URL` (*required*) - the database connection string for the Redis database. +#### Advanced + +- `TALK_REDIS_RECONNECTION_MAX_ATTEMPTS` (_optional_) - the amount of attempts + that a redis connection will attempt to reconnect before aborting with an + error. (Default `100`) +- `TALK_REDIS_RECONNECTION_MAX_RETRY_TIME` (_optional_) - the time in string + format for the maximum amount of time that a client can be considered + "connecting" before attempts at reconnection are aborted with an error. + (Default `1 min`) +- `TALK_REDIS_RECONNECTION_BACKOFF_FACTOR` (_optional_) - the time factor that + will be multiplied against the current attempt count inbetween attempts to + connect to redis. (Default `500 ms`) +- `TALK_REDIS_RECONNECTION_BACKOFF_MINIMUM_TIME` (_optional_) - the minimum time + used to delay before attempting to reconnect to redis. (Default `1 sec`) + ### Server - `TALK_ROOT_URL` (*required*) - root url of the installed application externally - available in the format: `://` without the path. + available in the format: `://:/`. - `TALK_KEEP_ALIVE` (_optional_) - The keepalive timeout that should be used to send keep alive messages through the websocket to keep the socket alive. (Default `30s`) - `TALK_INSTALL_LOCK` (_optional for dynamic setup_) - When `TRUE`, disables the dynamic setup endpoint. (Default `FALSE`) +#### Advanced + +- `TALK_ROOT_URL_MOUNT_PATH` (_optional_) - when set to `TRUE`, the routes will + be mounted onto the `` component of the `TALK_ROOT_URL`. You would + use this when your upstream proxy cannot strip the prefix from the url. + (Default `FALSE`) + ### Word Filter - `TALK_DISABLE_AUTOFLAG_SUSPECT_WORDS` (_optional_) When `TRUE`, disables flagging of comments that match the suspect word filter. (Default `FALSE`) @@ -87,8 +109,16 @@ on the contents of those variables.** These are advanced settings for fine tuning the auth integration, and is not needed in most situations. -- `TALK_JWT_COOKIE_NAME` (_optional_) - the name of the cookie to extract the - JWT from (Default `authorization`) +- `TALK_JWT_COOKIE_NAME` (_optional_) - the default cookie name to check for a + valid JWT token to use for verifying a user. (Default `authorization`) +- `TALK_JWT_SIGNING_COOKIE_NAME` (_optional_) - the default cookie name that is + use to set a cookie containing a JWT that was issued by Talk. + (Default `process.env.TALK_JWT_COOKIE_NAME`) +- `TALK_JWT_COOKIE_NAMES` (_optional_) - the different cookie names to check for + a JWT token in, seperated by `,`. By default, we always use the + `process.env.TALK_JWT_COOKIE_NAME` and `process.env.TALK_JWT_SIGNING_COOKIE_NAME` + for this value. Any additional cookie names specified here will be appended to + the list of cookie names to inspect. - `TALK_JWT_CLEAR_COOKIE_LOGOUT` (_optional_) - when `FALSE`, Talk will not clear the cookie with name `TALK_JWT_COOKIE_NAME` when logging out (Default `TRUE`) @@ -110,11 +140,19 @@ will be used: "iss": TALK_JWT_ISSUER, // *optional* if TALK_JWT_DISABLE_ISSUER === 'TRUE', *required* otherwise [TALK_JWT_USER_ID_CLAIM]: "", // *required* the id of the user - // Note, if TALK_JWT_USER_ID_CLAIM contains '.', it will be used to deliniate an object, for example + // Note, if TALK_JWT_USER_ID_CLAIM contains '.', it will be used to delineate an object, for example // `user.id` would store it like: `{user: {id}}` } ``` +When our passport middleware checks for JWT tokens, it searches in the following +order: + +1. Custom cookies named from the list in `TALK_JWT_COOKIE_NAMES`. +2. Default cookies named `TALK_JWT_COOKIE_NAME` then `TALK_JWT_SIGNING_COOKIE_NAME`. +3. Query parameter `?access_token={TOKEN}`. +4. Header: `Authorization: Bearer {TOKEN}`. + ### Email - `TALK_SMTP_EMAIL` (*required for email*) - the address to send emails from @@ -135,11 +173,11 @@ will be used: ### Trust -Trust can automoderate comments based on user history. By specifying this -option, the beheviour can be changed to offer different results. +Trust can auto-moderate comments based on user history. By specifying this +option, the behavior can be changed to offer different results. - `TRUST_THRESHOLDS` (_optional_) - configure the reliability thresholds for - flagging and commenting. (Default `comment:-1,-1;flag:-1,-1`) + flagging and commenting. (Default `comment:2,-1;flag:2,-1`) The form of the environment variable: @@ -150,10 +188,10 @@ The form of the environment variable: The default could be read as: - When a commenter has one comment rejected, their next comment must be - premoderated once in order to post freely again. If they instead get rejected + pre-moderated once in order to post freely again. If they instead get rejected again, then they must have two of their comments approved in order to get added back to the queue. -- At the moment of writing, beheviour is not attached to the flagging +- At the moment of writing, behavior is not attached to the flagging reliability, but it is recorded. ### Cache diff --git a/docs/_docs/02-02-secrets.md b/docs/_docs/02-02-secrets.md index c974c350f..42c1946b6 100644 --- a/docs/_docs/02-02-secrets.md +++ b/docs/_docs/02-02-secrets.md @@ -67,7 +67,7 @@ for more details. ## Authentication Types -Talk also supports two methods of providing authenticationd details. +Talk also supports two methods of providing authentication details. - Single key: this is used when your secrets do not need to be rotated. - Multiple keys: this is used when you expect to rotate your secrets. diff --git a/docs/_docs/03-05-client-architecture.md b/docs/_docs/03-05-client-architecture.md index 6bb44bfad..f102573f2 100644 --- a/docs/_docs/03-05-client-architecture.md +++ b/docs/_docs/03-05-client-architecture.md @@ -6,7 +6,6 @@ permalink: /docs/architecture/client ## The Stack - [React](#react) - [Redux](#redux) - - [ImmutableJS](#immutablejs) ## The Architecture @@ -32,7 +31,7 @@ It basically consist in having two types of components: ### Container Components * __How things work__ * They don’t have markup nor styles -* They provide data and behaviour to Presentational or Container Components +* They provide data and behavior to Presentational or Container Components * They connect via `react-redux`’s `connect()` to the state. * They `mapStateToProps` the state to the Presentational Container. * They `mapDispatchToProps` to send actions to the Presentational Container. @@ -96,14 +95,6 @@ We use [Apollo](http://www.apollodata.com/) to handle graph requests and handle ## Redux We use [Redux](http://redux.js.org/) to handle the auth state. - -## ImmutableJS -We use Immutable JS to maintain our state immutable. -We found some really good tradeoffs while building Talk. - -[How to use ImmutableJS and how we use it with Talk](https://facebook.github.io/immutable-js/docs/#/) - - ## Test [How we do testing at Coral with Talk]({{ "/docs/development/tools" | absolute_url }}) diff --git a/docs/_docs/04-01-plugins.md b/docs/_docs/04-01-plugins.md index 8b9b1c99a..3182f6e3a 100644 --- a/docs/_docs/04-01-plugins.md +++ b/docs/_docs/04-01-plugins.md @@ -82,7 +82,7 @@ need to reconcile the plugins and build the static assets: # get plugin dependancies and remote plugins ./bin/cli plugins reconcile -# build staic assets (including enabled client side plugins) +# build static assets (including enabled client side plugins) yarn build ``` diff --git a/docs/_docs/04-02-plugins-quickstart.md b/docs/_docs/04-02-plugins-quickstart.md index cb2d2800b..ec5e23fef 100644 --- a/docs/_docs/04-02-plugins-quickstart.md +++ b/docs/_docs/04-02-plugins-quickstart.md @@ -236,6 +236,6 @@ Once you've taken this step, anyone can register your plugin into their Talk ser ### Publish to version control -This plugin is open source, so I'm also going to [publish it to github](https://github.com/jde/talk-plugin-asset-manager/commit/66b626caa85cb8030b3ddaa7c1a4821bf01e350a) and [cut a release](https://github.com/jde/talk-plugin-asset-manager/releases/tag/v0.1) that mirrors the npm relese. +This plugin is open source, so I'm also going to [publish it to github](https://github.com/jde/talk-plugin-asset-manager/commit/66b626caa85cb8030b3ddaa7c1a4821bf01e350a) and [cut a release](https://github.com/jde/talk-plugin-asset-manager/releases/tag/v0.1) that mirrors the npm release. ## Done! diff --git a/docs/_docs/04-03-plugins-client.md b/docs/_docs/04-03-plugins-client.md index 052b90873..511ccde6c 100644 --- a/docs/_docs/04-03-plugins-client.md +++ b/docs/_docs/04-03-plugins-client.md @@ -218,7 +218,7 @@ Basic settings can be added via json configuration in a plugin. * Default value * Variable name -#### Advanced Custom Configuration (low prioritiy) +#### Advanced Custom Configuration (low priority) Users can inject configuration interfaces that they create into the configuration allowing for more advanced configuration. diff --git a/docs/_docs/04-04-plugins-server.md b/docs/_docs/04-04-plugins-server.md index 6f204e6b8..13df5564f 100644 --- a/docs/_docs/04-04-plugins-server.md +++ b/docs/_docs/04-04-plugins-server.md @@ -220,7 +220,7 @@ when a valid token is provided but a user can't be found in the database that matches the provided id. The function is async, and should return the user object that was created in the -database, or null if the user wasn't found. The `jwt` paramenter of the object +database, or null if the user wasn't found. The `jwt` parameter of the object is the unpacked token, while `token` is the original jwt token string. ### Routes @@ -314,14 +314,14 @@ module.exports = { const {passport} = require('services/passport'); /** - * Facebook auth endpoint, this will redirect the user immediatly to facebook + * Facebook auth endpoint, this will redirect the user immediately to facebook * for authorization. */ router.get('/facebook', passport.authenticate('facebook', {display: 'popup', authType: 'rerequest', scope: ['public_profile']})); /** * Facebook callback endpoint, this will send the user a html page designed to - * send back the user credentials upon sucesfull login. + * send back the user credentials upon successful login. */ router.get('/facebook/callback', (req, res, next) => { diff --git a/docs/_docs/05-01-development-tools.md b/docs/_docs/05-01-development-tools.md index 609d3ef48..fc19a077c 100644 --- a/docs/_docs/05-01-development-tools.md +++ b/docs/_docs/05-01-development-tools.md @@ -1,6 +1,6 @@ --- title: Development Tooling -permalink: /docs/development/tools +permalink: /docs/development/tools/ --- ## Debugging diff --git a/errors.js b/errors.js index 79731dad6..ab1667e07 100644 --- a/errors.js +++ b/errors.js @@ -5,7 +5,7 @@ class ExtendableError { constructor(message = null) { this.message = message; - this.stack = (new Error()).stack; + this.stack = (new Error(message)).stack; } } diff --git a/graph/context.js b/graph/context.js index cffec0896..8d7c740b6 100644 --- a/graph/context.js +++ b/graph/context.js @@ -53,7 +53,7 @@ class Context { this.plugins = decorateContextPlugins(this, contextPlugins); // Bind the publish/subscribe to the context. - this.pubsub = pubsub.createClient(); + this.pubsub = pubsub.getClient(); } } diff --git a/graph/helpers/response.js b/graph/helpers/response.js index ebdbc02ec..1db1e9b89 100644 --- a/graph/helpers/response.js +++ b/graph/helpers/response.js @@ -2,18 +2,21 @@ const errors = require('../../errors'); const {Error: {ValidationError}} = require('mongoose'); /** - * Wraps up a promise to return an object with the resolution of the promise + * Wraps up a promise or value to return an object with the resolution of the promise * keyed at `key` or an error caught at `errors`. */ -const wrapResponse = (key) => (promise) => { - return promise.then((value) => { +const wrapResponse = (key) => async (promise) => { + try { + let value = await promise; + let res = {}; if (key) { res[key] = value; } + return res; - }).catch((err) => { + } catch (err) { if (err instanceof errors.APIError) { return { errors: [err] @@ -25,7 +28,7 @@ const wrapResponse = (key) => (promise) => { } throw err; - }); + } }; module.exports = wrapResponse; diff --git a/graph/resolvers/comment.js b/graph/resolvers/comment.js index 0fd3a730c..57ebc4d56 100644 --- a/graph/resolvers/comment.js +++ b/graph/resolvers/comment.js @@ -1,6 +1,9 @@ const {decorateWithTags} = require('./util'); const Comment = { + hasParent({parent_id}) { + return !!parent_id; + }, parent({parent_id}, _, {loaders: {Comments}}) { if (parent_id == null) { return null; diff --git a/graph/resolvers/user.js b/graph/resolvers/user.js index 2878d6561..c2818bd20 100644 --- a/graph/resolvers/user.js +++ b/graph/resolvers/user.js @@ -22,22 +22,18 @@ const User = { } }, - created_at({roles, created_at}, _, {user}) { - if (user && user.can(SEARCH_OTHER_USERS)) { - return created_at; + comments({id}, {query}, {loaders: {Comments}, user}) { + + // If there is no user, or there is a user, but they are requesting someone + // else's comments, and they aren't allowed, don't return then anything! + if (!user || (user.id !== id && !user.can(SEARCH_OTHERS_COMMENTS))) { + return null; } - return null; - }, - comments({id}, _, {loaders: {Comments}, user}) { + // Set the author id on the query. + query.author_id = id; - // If the user is not an admin, only return comment list for the owner of - // the comments. - if (user && (user.can(SEARCH_OTHERS_COMMENTS) || user.id === id)) { - return Comments.getByQuery({author_id: id, sort: 'REVERSE_CHRONOLOGICAL'}); - } - - return null; + return Comments.getByQuery(query); }, profiles({profiles}, _, {user}) { diff --git a/graph/subscriptions.js b/graph/subscriptions.js index adac849e0..71b8abc6a 100644 --- a/graph/subscriptions.js +++ b/graph/subscriptions.js @@ -26,6 +26,8 @@ const { SUBSCRIBE_ALL_USERNAME_REJECTED, } = require('../perms/constants'); +const {BASE_PATH} = require('../url'); + /** * Plugin support requires that we merge in existing setupFunctions with our new * plugin based ones. This allows plugins to extend existing setupFunctions as well @@ -127,15 +129,13 @@ const setupFunctions = plugins.get('server', 'setupFunctions').reduce((acc, {plu }), }); -const pubsubClient = pubsub.createClientFactory(); - /** * This creates a new subscription manager. */ const createSubscriptionManager = (server) => new SubscriptionServer({ subscriptionManager: new SubscriptionManager({ schema, - pubsub: pubsubClient(), + pubsub: pubsub.getClient(), setupFunctions, }), onConnect: ({token}, connection) => { @@ -172,7 +172,7 @@ const createSubscriptionManager = (server) => new SubscriptionServer({ keepAlive: ms(KEEP_ALIVE) }, { server, - path: '/api/v1/live' + path: `${BASE_PATH}api/v1/live` }); module.exports = { diff --git a/graph/typeDefs.graphql b/graph/typeDefs.graphql index d2c1ffe1f..0e430cd84 100644 --- a/graph/typeDefs.graphql +++ b/graph/typeDefs.graphql @@ -76,7 +76,7 @@ type User { username: String! # creation date of user - created_at: String! + created_at: Date! # Action summaries against the user. action_summaries: [ActionSummary!]! @@ -339,6 +339,9 @@ type Comment { # describes how the comment can be edited editing: EditInfo + + # Indicates if it has a parent + hasParent: Boolean } # CommentConnection represents a paginable subset of a comment list. diff --git a/locales/en.yml b/locales/en.yml index 54d5315d5..2ec0c816c 100644 --- a/locales/en.yml +++ b/locales/en.yml @@ -281,6 +281,7 @@ en: prev_comment: "Go to the previous comment" reject: "Reject" rejected: "Rejected" + reply: "Reply" select_stream: "Select Stream" shift_key: "⇧" shortcuts: "Shortcuts" diff --git a/locales/es.yml b/locales/es.yml index 8c3e7927b..877a42841 100644 --- a/locales/es.yml +++ b/locales/es.yml @@ -272,6 +272,7 @@ es: prev_comment: "Ir al comentario anterior" reject: "Rechazar" rejected: "rechazado" + reply: "Respuesta" select_stream: "Seleccionar hilo de comentarios" shift_key: ⇧ shortcuts: Atajos diff --git a/middleware/authorization.js b/middleware/authorization.js index d93913109..742b6983a 100644 --- a/middleware/authorization.js +++ b/middleware/authorization.js @@ -10,18 +10,29 @@ const debug = require('debug')('talk:middleware:authorization'); const ErrNotAuthorized = require('../errors').ErrNotAuthorized; /** - * has returns true if the user has all the roles specified, otherwise it will - * return false. + * has returns true if the user has at least one of the roles specified, + * otherwise it will return false. * @param {Object} user the user to check for roles - * @param {Array} roles all the roles that a user must have - * @return {Boolean} true if the user has all the roles required, false + * @param {Array} roles roles to check if the user has + * @return {Boolean} true if the user has some the roles required, false * otherwise */ -authorization.has = (user, ...roles) => roles.every((role) => { +authorization.has = (user, ...roles) => { - // TODO: remove toUpperCase once we've migrated over the roles. - return user.roles.indexOf(role.toUpperCase()) >= 0; -}); + // If no user is specified, then they can't have the roles you want! + if (!user || !user.roles) { + return false; + } + + // If no roles are specified, then any user has the roles you want! + if (!roles || roles.length === 0) { + return true; + } + + // If there's a user, and roles, then check to see that the user has at least + // one of those roles. + return roles.some((role) => user.roles.includes(role)); +}; /** * needed is a connect middleware layer that ensures that all requests coming diff --git a/middleware/pubsub.js b/middleware/pubsub.js new file mode 100644 index 000000000..957a523a7 --- /dev/null +++ b/middleware/pubsub.js @@ -0,0 +1,12 @@ +const pubsub = require('../services/pubsub'); + +// To handle dependancy injection safer, we inject the pubsub handle onto the +// request object. +module.exports = (req, res, next) => { + + // Attach the pubsub handle to the requests. + req.pubsub = pubsub.getClient(); + + // Forward on the request. + next(); +}; diff --git a/package.json b/package.json index 476e7eda5..71477361e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "talk", - "version": "3.0.0", + "version": "3.2.0", "description": "A better commenting experience from Mozilla, The New York Times, and the Washington Post. https://coralproject.net", "main": "app.js", "scripts": { @@ -93,7 +93,7 @@ "graphql-tools": "^0.10.1", "helmet": "^3.5.0", "immutability-helper": "^2.2.0", - "inquirer": "^3.0.6", + "inquirer": "^3.2.1", "joi": "^10.4.1", "jsonwebtoken": "^7.3.0", "jwt-decode": "^2.2.0", @@ -116,7 +116,7 @@ "passport-local": "^1.0.0", "prop-types": "^15.5.10", "query-strings": "^0.0.1", - "react-apollo": "^1.1.0", + "react-apollo": "^1.4.12", "react-input-autosize": "^1.1.4", "react-recaptcha": "^2.2.6", "react-toastify": "^1.5.0", @@ -136,7 +136,7 @@ "yamljs": "^0.2.10" }, "devDependencies": { - "apollo-client": "^1.0.4", + "apollo-client": "^1.9.1", "autoprefixer": "^6.5.2", "babel-cli": "^6.24.0", "babel-core": "^6.24.0", @@ -180,7 +180,6 @@ "hammerjs": "^2.0.8", "history": "^3.0.0", "ignore-styles": "^5.0.1", - "immutable": "^3.8.1", "imports-loader": "^0.7.1", "istanbul": "^1.1.0-alpha.1", "jsdom": "^9.8.3", diff --git a/plugin-api/beta/client/components/index.js b/plugin-api/beta/client/components/index.js index 6466b9ffc..8b0448f4e 100644 --- a/plugin-api/beta/client/components/index.js +++ b/plugin-api/beta/client/components/index.js @@ -1,2 +1,3 @@ export {Slot} from 'coral-framework/components'; export {default as ClickOutside} from 'coral-framework/components/ClickOutside'; +export {default as CommentAuthorName} from 'coral-framework/components/CommentAuthorName'; diff --git a/plugin-api/beta/client/hocs/index.js b/plugin-api/beta/client/hocs/index.js index 68547692d..60b118522 100644 --- a/plugin-api/beta/client/hocs/index.js +++ b/plugin-api/beta/client/hocs/index.js @@ -3,3 +3,4 @@ export {default as withTags} from './withTags'; export {default as withFragments} from 'coral-framework/hocs/withFragments'; export {default as excludeIf} from 'coral-framework/hocs/excludeIf'; export {default as connect} from 'coral-framework/hocs/connect'; +export {default as withEmit} from 'coral-framework/hocs/withEmit'; diff --git a/plugin-api/beta/client/hocs/withReaction.js b/plugin-api/beta/client/hocs/withReaction.js index 40ee6e14c..3300ac2d3 100644 --- a/plugin-api/beta/client/hocs/withReaction.js +++ b/plugin-api/beta/client/hocs/withReaction.js @@ -11,14 +11,29 @@ import {showSignInDialog} from 'coral-framework/actions/auth'; import {addNotification} from 'coral-framework/actions/notification'; import {capitalize} from 'coral-framework/helpers/strings'; import {getMyActionSummary, getTotalActionCount} from 'coral-framework/utils'; +import hoistStatics from 'recompose/hoistStatics'; import * as PropTypes from 'prop-types'; +import {getDefinitionName} from '../utils'; -export default (reaction) => (WrappedComponent) => { +/* + * Disable false-positive warning below, as it doesn't work well with how we currently + * assemble the queries. + * + * Warning: fragment with name {fragment name} already exists. + * graphql-tag enforces all fragment names across your application to be unique; read more about + * this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names + */ +gql.disableFragmentWarnings(); + +export default (reaction, options = {}) => hoistStatics((WrappedComponent) => { if (typeof reaction !== 'string') { console.error('Reaction must be a valid string'); return null; } + // fragments allow the extension of the fragments defined in this HOC. + const {fragments = {}} = options; + // Global instance counter for each `reaction` type. let instances = 0; @@ -175,7 +190,7 @@ export default (reaction) => (WrappedComponent) => { createdSubscription = context.client.subscribe({ query: REACTION_CREATED_SUBSCRIPTION, variables: { - assetId: this.props.root.asset.id, + assetId: this.props.asset.id, }, }).subscribe({ next: this.onReactionCreated, @@ -185,7 +200,7 @@ export default (reaction) => (WrappedComponent) => { deletedSubscription = context.client.subscribe({ query: REACTION_DELETED_SUBSCRIPTION, variables: { - assetId: this.props.root.asset.id, + assetId: this.props.asset.id, }, }).subscribe({ next: this.onReactionDeleted, @@ -247,7 +262,7 @@ export default (reaction) => (WrappedComponent) => { } render() { - const {comment} = this.props; + const {root, asset, comment} = this.props; const reactionSummary = getMyActionSummary( `${Reaction}ActionSummary`, @@ -262,15 +277,18 @@ export default (reaction) => (WrappedComponent) => { const alreadyReacted = !!reactionSummary; return ; } } @@ -362,7 +380,7 @@ export default (reaction) => (WrappedComponent) => { ); const mapStateToProps = (state) => ({ - user: state.auth.toJS().user, + user: state.auth.user, }); const mapDispatchToProps = (dispatch) => @@ -370,9 +388,19 @@ export default (reaction) => (WrappedComponent) => { const enhance = compose( withFragments({ + ...fragments, + asset: gql` + fragment ${Reaction}Button_asset on Asset { + id + ${fragments.asset ? `...${getDefinitionName(fragments.asset)}` : ''} + } + ${fragments.asset ? fragments.asset : ''} + `, comment: gql` fragment ${Reaction}Button_comment on Comment { + id action_summaries { + __typename ... on ${Reaction}ActionSummary { count current_user { @@ -380,7 +408,10 @@ export default (reaction) => (WrappedComponent) => { } } } - }` + ${fragments.comment ? `...${getDefinitionName(fragments.comment)}` : ''} + } + ${fragments.comment ? fragments.comment : ''} + ` }), connect(mapStateToProps, mapDispatchToProps), withDeleteReaction, @@ -390,4 +421,4 @@ export default (reaction) => (WrappedComponent) => { WithReactions.displayName = `WithReactions(${getDisplayName(WrappedComponent)})`; return enhance(WithReactions); -}; +}); diff --git a/plugin-api/beta/client/hocs/withTags.js b/plugin-api/beta/client/hocs/withTags.js index 75d434bef..491c35038 100644 --- a/plugin-api/beta/client/hocs/withTags.js +++ b/plugin-api/beta/client/hocs/withTags.js @@ -8,13 +8,28 @@ import {withAddTag, withRemoveTag} from 'coral-framework/graphql/mutations'; import withFragments from 'coral-framework/hocs/withFragments'; import {addNotification} from 'coral-framework/actions/notification'; import {forEachError, isTagged} from 'coral-framework/utils'; +import hoistStatics from 'recompose/hoistStatics'; +import {getDefinitionName} from '../utils'; -export default (tag) => (WrappedComponent) => { +/* + * Disable false-positive warning below, as it doesn't work well with how we currently + * assemble the queries. + * + * Warning: fragment with name {fragment name} already exists. + * graphql-tag enforces all fragment names across your application to be unique; read more about + * this in the docs: http://dev.apollodata.com/core/fragments.html#unique-names + */ +gql.disableFragmentWarnings(); + +export default (tag, options = {}) => hoistStatics((WrappedComponent) => { if (typeof tag !== 'string') { console.error('Tag must be a valid string'); return null; } + // fragments allow the extension of the fragments defined in this HOC. + const {fragments = {}} = options; + const Tag = capitalize(tag); const TAG = tag.toUpperCase(); @@ -68,22 +83,25 @@ export default (tag) => (WrappedComponent) => { } render() { - const {comment} = this.props; + const {root, asset, comment, user, config} = this.props; const alreadyTagged = isTagged(comment.tags, TAG); return ; } } const mapStateToProps = (state) => ({ - user: state.auth.toJS().user, + user: state.auth.user, }); const mapDispatchToProps = (dispatch) => @@ -91,14 +109,26 @@ export default (tag) => (WrappedComponent) => { const enhance = compose( withFragments({ + ...fragments, + asset: gql` + fragment ${Tag}Button_asset on Asset { + id + ${fragments.asset ? `...${getDefinitionName(fragments.asset)}` : ''} + } + ${fragments.asset ? fragments.asset : ''} + `, comment: gql` fragment ${Tag}Button_comment on Comment { + id tags { tag { name } } - }` + ${fragments.comment ? `...${getDefinitionName(fragments.comment)}` : ''} + } + ${fragments.comment ? fragments.comment : ''} + ` }), connect(mapStateToProps, mapDispatchToProps), withAddTag, @@ -108,4 +138,4 @@ export default (tag) => (WrappedComponent) => { WithTags.displayName = `WithTags(${getDisplayName(WrappedComponent)})`; return enhance(WithTags); -}; +}); diff --git a/plugins/talk-plugin-auth/client/components/ChangeUsername.js b/plugins/talk-plugin-auth/client/components/ChangeUsername.js index ed3c5ace0..c1ad081b1 100644 --- a/plugins/talk-plugin-auth/client/components/ChangeUsername.js +++ b/plugins/talk-plugin-auth/client/components/ChangeUsername.js @@ -122,7 +122,7 @@ class ChangeUsernameContainer extends React.Component { } const mapStateToProps = ({auth}) => ({ - auth: auth.toJS() + auth: auth }); const mapDispatchToProps = (dispatch) => diff --git a/plugins/talk-plugin-auth/client/components/CreateUsernameDialog.js b/plugins/talk-plugin-auth/client/components/CreateUsernameDialog.js index 12916b4dd..4b0babed6 100644 --- a/plugins/talk-plugin-auth/client/components/CreateUsernameDialog.js +++ b/plugins/talk-plugin-auth/client/components/CreateUsernameDialog.js @@ -32,7 +32,7 @@ const CreateUsernameDialog = ({ className={styles.fakeComment} username={formData.username} created_at={Date.now()} - comment={{body:t('createdisplay.fake_comment_body')}} + body={t('createdisplay.fake_comment_body')} />

    {t('createdisplay.if_you_dont_change_your_name')} diff --git a/plugins/talk-plugin-auth/client/components/FakeComment.css b/plugins/talk-plugin-auth/client/components/FakeComment.css new file mode 100644 index 000000000..bc751b115 --- /dev/null +++ b/plugins/talk-plugin-auth/client/components/FakeComment.css @@ -0,0 +1,38 @@ +.root { + border-top: 1px solid rgba(0, 0, 0, 0.1); + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + margin-bottom: 10px; + padding: 8px 0px 10px 0px; + position: relative; +} + +.footer { + display: flex; + justify-content: space-between; +} + +.button { + color: #2a2a2a; + margin: 5px 10px 5px 0px; + background: none; + padding: 0px; + border: none; + font-size: inherit; + vertical-align: middle; + + &:hover { + color: #767676; + cursor: pointer; + } +} + +.icon { + font-size: 12px; + padding: 0 2px 0 5px; + vertical-align: middle; +} + +.authorName { + margin-right: 5px; + font-weight: bold; +} \ No newline at end of file diff --git a/plugins/talk-plugin-auth/client/components/FakeComment.js b/plugins/talk-plugin-auth/client/components/FakeComment.js index b6b4e7609..9f1d90ae7 100644 --- a/plugins/talk-plugin-auth/client/components/FakeComment.js +++ b/plugins/talk-plugin-auth/client/components/FakeComment.js @@ -2,65 +2,44 @@ import React from 'react'; import t from 'coral-framework/services/i18n'; import {ReplyButton} from 'talk-plugin-replies'; import PubDate from 'talk-plugin-pubdate/PubDate'; -import Slot from 'coral-framework/components/Slot'; -import AuthorName from 'talk-plugin-author-name/AuthorName'; -import styles from 'coral-embed-stream/src/components/Comment.css'; +import styles from './FakeComment.css'; +import {Icon} from 'plugin-api/beta/client/components/ui'; -export const FakeComment = ({username, created_at, comment}) => ( -

    -
    - +export const FakeComment = ({username, created_at, body}) => ( +
    + + {username} + ; - -
    -
    - + {}} + parentCommentId={'commentID'} + currentUserId={{}} + />
    - {}} - parentCommentId={'commentID'} - currentUserId={{}} - /> -
    -
    -
    - -
    -
    -
    diff --git a/plugins/talk-plugin-auth/client/components/SignInButton.js b/plugins/talk-plugin-auth/client/components/SignInButton.js index 0adb300a7..9c8a04b11 100644 --- a/plugins/talk-plugin-auth/client/components/SignInButton.js +++ b/plugins/talk-plugin-auth/client/components/SignInButton.js @@ -16,7 +16,7 @@ const SignInButton = ({loggedIn, showSignInDialog}) => ( ); const mapStateToProps = ({auth}) => ({ - loggedIn: auth.toJS().loggedIn + loggedIn: auth.loggedIn }); const mapDispatchToProps = (dispatch) => diff --git a/plugins/talk-plugin-auth/client/components/SignInContainer.js b/plugins/talk-plugin-auth/client/components/SignInContainer.js index 6950f4124..188651186 100644 --- a/plugins/talk-plugin-auth/client/components/SignInContainer.js +++ b/plugins/talk-plugin-auth/client/components/SignInContainer.js @@ -176,7 +176,7 @@ class SignInContainer extends React.Component { } const mapStateToProps = (state) => ({ - auth: state.auth.toJS() + auth: state.auth }); const mapDispatchToProps = (dispatch) => diff --git a/plugins/talk-plugin-auth/client/components/UserBox.js b/plugins/talk-plugin-auth/client/components/UserBox.js index 5b79b664a..61540d3c5 100644 --- a/plugins/talk-plugin-auth/client/components/UserBox.js +++ b/plugins/talk-plugin-auth/client/components/UserBox.js @@ -22,8 +22,8 @@ const UserBox = ({loggedIn, user, logout, onShowProfile}) => ( ); const mapStateToProps = ({auth}) => ({ - loggedIn: auth.toJS().loggedIn, - user: auth.toJS().user + loggedIn: auth.loggedIn, + user: auth.user }); const mapDispatchToProps = (dispatch) => diff --git a/plugins/talk-plugin-featured-comments/client/components/Comment.css b/plugins/talk-plugin-featured-comments/client/components/Comment.css index 36f3e790e..b800401e3 100644 --- a/plugins/talk-plugin-featured-comments/client/components/Comment.css +++ b/plugins/talk-plugin-featured-comments/client/components/Comment.css @@ -64,4 +64,4 @@ .actionsContainer { text-align: right; -} +} \ No newline at end of file diff --git a/plugins/talk-plugin-featured-comments/client/components/Comment.js b/plugins/talk-plugin-featured-comments/client/components/Comment.js index 01b5f864c..ada7ae7b6 100644 --- a/plugins/talk-plugin-featured-comments/client/components/Comment.js +++ b/plugins/talk-plugin-featured-comments/client/components/Comment.js @@ -2,7 +2,7 @@ import React from 'react'; import cn from 'classnames'; import styles from './Comment.css'; import {t, timeago} from 'plugin-api/beta/client/services'; -import {Slot} from 'plugin-api/beta/client/components'; +import {Slot, CommentAuthorName} from 'plugin-api/beta/client/components'; import {Icon} from 'plugin-api/beta/client/components/ui'; import {pluginName} from '../../package.json'; @@ -22,9 +22,16 @@ class Comment extends React.Component {
    - - {comment.user.username} - + + + ,{' '}{timeago(comment.created_at)} diff --git a/plugins/talk-plugin-featured-comments/client/components/ModTag.css b/plugins/talk-plugin-featured-comments/client/components/ModTag.css index c8ba1b6ba..683c16570 100644 --- a/plugins/talk-plugin-featured-comments/client/components/ModTag.css +++ b/plugins/talk-plugin-featured-comments/client/components/ModTag.css @@ -4,13 +4,14 @@ color: #696969; background-color: white; box-sizing: border-box; - padding: 2px 8px; + padding: 0px 5px; border-radius: 2px; font-size: 12px; - height: 28px; + height: 24px; transition: background-color .2s cubic-bezier(.4,0,.2,1), color .2s cubic-bezier(.4,0,.2,1), border-color .2s cubic-bezier(.4,0,.2,1); margin: 2px 0px; letter-spacing: 0.4px; + } .tag:hover { @@ -39,4 +40,3 @@ font-size: 15px; vertical-align: text-bottom; } - \ No newline at end of file diff --git a/plugins/talk-plugin-featured-comments/client/components/TabPane.js b/plugins/talk-plugin-featured-comments/client/components/TabPane.js index 3cf8b2cfd..2f5d0c7c2 100644 --- a/plugins/talk-plugin-featured-comments/client/components/TabPane.js +++ b/plugins/talk-plugin-featured-comments/client/components/TabPane.js @@ -36,7 +36,7 @@ class TabPane extends React.Component { {featuredComments.hasNextPage && }
    diff --git a/plugins/talk-plugin-featured-comments/client/containers/Comment.js b/plugins/talk-plugin-featured-comments/client/containers/Comment.js index 7080627e6..a647bf1b4 100644 --- a/plugins/talk-plugin-featured-comments/client/containers/Comment.js +++ b/plugins/talk-plugin-featured-comments/client/containers/Comment.js @@ -5,6 +5,7 @@ import {getSlotFragmentSpreads} from 'plugin-api/beta/client/utils'; const slots = [ 'commentReactions', + 'commentAuthorName', ]; export default withFragments({ @@ -31,7 +32,6 @@ export default withFragments({ name } } - user { id username diff --git a/plugins/talk-plugin-featured-comments/client/containers/ModSubscription.js b/plugins/talk-plugin-featured-comments/client/containers/ModSubscription.js index 647c7ecfd..82f323530 100644 --- a/plugins/talk-plugin-featured-comments/client/containers/ModSubscription.js +++ b/plugins/talk-plugin-featured-comments/client/containers/ModSubscription.js @@ -2,7 +2,6 @@ import React from 'react'; import {gql} from 'react-apollo'; import {connect} from 'react-redux'; import Comment from 'coral-admin/src/routes/Moderation/containers/Comment'; -import {handleCommentChange} from 'coral-admin/src/graphql/utils'; import {getDefinitionName} from 'coral-framework/utils'; import truncate from 'lodash/truncate'; import t from 'coral-framework/services/i18n'; @@ -22,20 +21,14 @@ class ModSubscription extends React.Component { assetId: this.props.data.variables.asset_id, }, updateQuery: (prev, {subscriptionData: {data: {commentFeatured: {user, comment}}}}) => { - const sort = this.props.data.variables.sort; - const text = this.props.user.id === user.id - ? {} + const notify = this.props.user.id === user.id + ? '' : t( 'talk-plugin-featured-comments.notify_featured', user.username, prepareNotificationText(comment.body), ); - const notify = { - activeQueue: this.props.activeTab, - text, - anyQueue: true, - }; - return handleCommentChange(prev, comment, sort, notify); + return this.props.handleCommentChange(prev, comment, notify); }, }, { @@ -44,20 +37,14 @@ class ModSubscription extends React.Component { assetId: this.props.data.variables.asset_id, }, updateQuery: (prev, {subscriptionData: {data: {commentUnfeatured: {user, comment}}}}) => { - const sort = this.props.data.variables.sort; - const text = this.props.user.id === user.id - ? {} + const notify = this.props.user.id === user.id + ? '' : t( 'talk-plugin-featured-comments.notify_unfeatured', user.username, prepareNotificationText(comment.body), ); - const notify = { - activeQueue: this.props.activeTab, - text, - anyQueue: true, - }; - return handleCommentChange(prev, comment, sort, notify); + return this.props.handleCommentChange(prev, comment, notify); } }, ]; @@ -104,7 +91,7 @@ const COMMENT_UNFEATURED_SUBSCRIPTION = gql` `; const mapStateToProps = (state) => ({ - user: state.auth.toJS().user, + user: state.auth.user, }); export default connect(mapStateToProps, null)(ModSubscription); diff --git a/plugins/talk-plugin-featured-comments/client/containers/ModTag.js b/plugins/talk-plugin-featured-comments/client/containers/ModTag.js index 3b564d127..7081c7ec6 100644 --- a/plugins/talk-plugin-featured-comments/client/containers/ModTag.js +++ b/plugins/talk-plugin-featured-comments/client/containers/ModTag.js @@ -1,5 +1,16 @@ import ModTag from '../components/ModTag'; import {withTags} from 'plugin-api/beta/client/hocs'; +import {gql} from 'react-apollo'; -export default withTags('featured')(ModTag); +const fragments = { + comment: gql` + fragment TalkFeaturedComments_ModTag_comment on Comment { + user { + username + } + } + ` +}; + +export default withTags('featured', {fragments})(ModTag); diff --git a/plugins/talk-plugin-featured-comments/client/containers/TabPane.js b/plugins/talk-plugin-featured-comments/client/containers/TabPane.js index 2195b0107..63ce30d01 100644 --- a/plugins/talk-plugin-featured-comments/client/containers/TabPane.js +++ b/plugins/talk-plugin-featured-comments/client/containers/TabPane.js @@ -16,8 +16,8 @@ class TabPaneContainer extends React.Component { query: LOAD_MORE_QUERY, variables: { limit: 5, - cursor: this.props.root.asset.featuredComments.endCursor, - asset_id: this.props.root.asset.id, + cursor: this.props.asset.featuredComments.endCursor, + asset_id: this.props.asset.id, sort: 'REVERSE_CHRONOLOGICAL', excludeIgnored: this.props.data.variables.excludeIgnored, }, diff --git a/plugins/talk-plugin-featured-comments/client/containers/Tag.js b/plugins/talk-plugin-featured-comments/client/containers/Tag.js new file mode 100644 index 000000000..60d9e1e2b --- /dev/null +++ b/plugins/talk-plugin-featured-comments/client/containers/Tag.js @@ -0,0 +1,15 @@ +import {gql} from 'react-apollo'; +import Tag from '../components/Tag'; +import {withFragments} from 'plugin-api/beta/client/hocs'; + +export default withFragments({ + comment: gql` + fragment TalkFeaturedComments_Tag_comment on Comment { + tags { + tag { + name + } + } + } + ` +})(Tag); diff --git a/plugins/talk-plugin-featured-comments/client/index.js b/plugins/talk-plugin-featured-comments/client/index.js index 82cba8b91..79c3d874f 100644 --- a/plugins/talk-plugin-featured-comments/client/index.js +++ b/plugins/talk-plugin-featured-comments/client/index.js @@ -1,5 +1,5 @@ import Tab from './containers/Tab'; -import Tag from './components/Tag'; +import Tag from './containers/Tag'; import Button from './components/Button'; import TabPane from './containers/TabPane'; import translations from './translations.yml'; @@ -26,6 +26,9 @@ export default { IgnoreUser: ({variables}) => ({ updateQueries: { CoralEmbedStream_Embed: (previous) => { + if (!previous.asset.featuredComments) { + return previous; + } const ignoredUserId = variables.id; const newNodes = previous.asset.featuredComments.nodes.filter((n) => n.user.id !== ignoredUserId); const removedCount = previous.asset.featuredComments.nodes.length - newNodes.length; diff --git a/plugins/talk-plugin-offtopic/client/components/OffTopicFilter.js b/plugins/talk-plugin-offtopic/client/components/OffTopicFilter.js index 171bafeb2..426dea29a 100644 --- a/plugins/talk-plugin-offtopic/client/components/OffTopicFilter.js +++ b/plugins/talk-plugin-offtopic/client/components/OffTopicFilter.js @@ -16,7 +16,6 @@ export default class OffTopicFilter extends React.Component { this.props.removeCommentClassName(idx); this.props.toggleCheckbox(); } - this.props.closeViewingOptions(); } render() { diff --git a/plugins/talk-plugin-offtopic/client/containers/OffTopicFilter.js b/plugins/talk-plugin-offtopic/client/containers/OffTopicFilter.js index 9548b764e..7eab8c526 100644 --- a/plugins/talk-plugin-offtopic/client/containers/OffTopicFilter.js +++ b/plugins/talk-plugin-offtopic/client/containers/OffTopicFilter.js @@ -3,9 +3,6 @@ import {bindActionCreators} from 'redux'; import {toggleCheckbox} from '../actions'; import {commentClassNamesSelector} from 'plugin-api/alpha/client/selectors'; import OffTopicFilter from '../components/OffTopicFilter'; -import { - closeViewingOptions -} from 'plugins/talk-plugin-viewing-options/client/actions'; import { addCommentClassName, removeCommentClassName @@ -20,7 +17,6 @@ const mapDispatchToProps = (dispatch) => bindActionCreators( { toggleCheckbox, - closeViewingOptions, addCommentClassName, removeCommentClassName }, diff --git a/plugins/talk-plugin-offtopic/client/containers/OffTopicTag.js b/plugins/talk-plugin-offtopic/client/containers/OffTopicTag.js new file mode 100644 index 000000000..bf57dc5cb --- /dev/null +++ b/plugins/talk-plugin-offtopic/client/containers/OffTopicTag.js @@ -0,0 +1,15 @@ +import {gql} from 'react-apollo'; +import OffTopicTag from '../components/OffTopicTag'; +import {withFragments} from 'plugin-api/beta/client/hocs'; + +export default withFragments({ + comment: gql` + fragment TalkOfftopic_OffTopicTag_comment on Comment { + tags { + tag { + name + } + } + } + ` +})(OffTopicTag); diff --git a/plugins/talk-plugin-offtopic/client/index.js b/plugins/talk-plugin-offtopic/client/index.js index b284f7280..24bfc095f 100644 --- a/plugins/talk-plugin-offtopic/client/index.js +++ b/plugins/talk-plugin-offtopic/client/index.js @@ -1,5 +1,5 @@ import translations from './translations.json'; -import OffTopicTag from './components/OffTopicTag'; +import OffTopicTag from './containers/OffTopicTag'; import OffTopicFilter from './containers/OffTopicFilter'; import OffTopicCheckbox from './containers/OffTopicCheckbox'; import reducer from './reducer'; diff --git a/plugins/talk-plugin-permalink/client/components/PermalinkButton.js b/plugins/talk-plugin-permalink/client/components/PermalinkButton.js index 27cbf9188..e2536f86f 100644 --- a/plugins/talk-plugin-permalink/client/components/PermalinkButton.js +++ b/plugins/talk-plugin-permalink/client/components/PermalinkButton.js @@ -28,9 +28,11 @@ export default class PermalinkButton extends React.Component { } handleClickOutside = () => { - this.setState({ - popoverOpen: false - }); + if (this.state.popoverOpen) { + this.setState({ + popoverOpen: false + }); + } } copyPermalink = () => { diff --git a/plugins/talk-plugin-permalink/client/containers/PermalinkButton.js b/plugins/talk-plugin-permalink/client/containers/PermalinkButton.js new file mode 100644 index 000000000..5e1d11110 --- /dev/null +++ b/plugins/talk-plugin-permalink/client/containers/PermalinkButton.js @@ -0,0 +1,16 @@ +import {gql} from 'react-apollo'; +import PermalinkButton from '../components/PermalinkButton'; +import {withFragments} from 'plugin-api/beta/client/hocs'; + +export default withFragments({ + asset: gql` + fragment TalkPermalink_Button_asset on Asset { + url + } + `, + comment: gql` + fragment TalkPermalink_Button_comment on Comment { + id + } + ` +})(PermalinkButton); diff --git a/plugins/talk-plugin-permalink/client/index.js b/plugins/talk-plugin-permalink/client/index.js index d413da870..c28c4ae71 100644 --- a/plugins/talk-plugin-permalink/client/index.js +++ b/plugins/talk-plugin-permalink/client/index.js @@ -1,4 +1,4 @@ -import PermalinkButton from './components/PermalinkButton'; +import PermalinkButton from './containers/PermalinkButton'; export default { slots: { diff --git a/routes/api/users/index.js b/routes/api/users/index.js index 60c568253..41b2771ca 100644 --- a/routes/api/users/index.js +++ b/routes/api/users/index.js @@ -10,7 +10,7 @@ const { } = require('../../../config'); // get a list of users. -router.get('/', authorization.needed('ADMIN'), async (req, res, next) => { +router.get('/', authorization.needed('ADMIN', 'MODERATOR'), async (req, res, next) => { const { value = '', field = 'created_at', @@ -44,7 +44,7 @@ router.get('/', authorization.needed('ADMIN'), async (req, res, next) => { }); -router.post('/:user_id/role', authorization.needed('ADMIN'), async (req, res, next) => { +router.post('/:user_id/role', authorization.needed('ADMIN', 'MODERATOR'), async (req, res, next) => { try { await UsersService.addRoleToUser(req.params.user_id, req.body.role); res.status(204).end(); @@ -54,7 +54,7 @@ router.post('/:user_id/role', authorization.needed('ADMIN'), async (req, res, ne }); // update the status of a user -router.post('/:user_id/status', authorization.needed('ADMIN'), async (req, res, next) => { +router.post('/:user_id/status', authorization.needed('ADMIN', 'MODERATOR'), async (req, res, next) => { let {status} = req.body; try { @@ -74,7 +74,7 @@ router.post('/:user_id/status', authorization.needed('ADMIN'), async (req, res, } }); -router.post('/:user_id/username-enable', authorization.needed('ADMIN'), async (req, res, next) => { +router.post('/:user_id/username-enable', authorization.needed('ADMIN', 'MODERATOR'), async (req, res, next) => { try { await UsersService.toggleNameEdit(req.params.user_id, true); res.status(204).end(); @@ -83,7 +83,7 @@ router.post('/:user_id/username-enable', authorization.needed('ADMIN'), async (r } }); -router.post('/:user_id/email', authorization.needed('ADMIN'), async (req, res, next) => { +router.post('/:user_id/email', authorization.needed('ADMIN', 'MODERATOR'), async (req, res, next) => { try { let user = await UsersService.findById(req.params.user_id); @@ -189,7 +189,7 @@ router.post('/resend-verify', async (req, res, next) => { }); // trigger an email confirmation re-send from the admin panel -router.post('/:user_id/email/confirm', authorization.needed('ADMIN'), async (req, res, next) => { +router.post('/:user_id/email/confirm', authorization.needed('ADMIN', 'MODERATOR'), async (req, res, next) => { const { user_id } = req.params; diff --git a/routes/index.js b/routes/index.js index f1992e83d..6a8920dc3 100644 --- a/routes/index.js +++ b/routes/index.js @@ -2,12 +2,45 @@ const express = require('express'); const path = require('path'); const plugins = require('../services/plugins'); const debug = require('debug')('talk:routes'); +const authentication = require('../middleware/authentication'); +const {passport} = require('../services/passport'); +const pubsub = require('../middleware/pubsub'); +const i18n = require('../services/i18n'); +const enabled = require('debug').enabled; +const errors = require('../errors'); +const {createGraphOptions} = require('../graph'); +const accepts = require('accepts'); +const apollo = require('graphql-server-express'); const router = express.Router(); -router.use('/api/v1', require('./api')); -router.use('/admin', require('./admin')); -router.use('/embed', require('./embed')); +//============================================================================== +// STATIC FILES +//============================================================================== + +// If the application is in production mode, then add gzip rewriting for the +// content. +if (process.env.NODE_ENV === 'production') { + router.get('*.js', (req, res, next) => { + const accept = accepts(req); + if (accept.encoding(['gzip']) === 'gzip') { + + // Adjsut the headers on the request by adding a content type header + // because express won't be able to detect the mime-type with the .gz + // extension and we need to decalre support for the gzip encoding. + res.set('Content-Type', 'application/javascript'); + res.set('Content-Encoding', 'gzip'); + + // Rewrite the url so that the gzip version will be served instead. + req.url = `${req.url}.gz`; + } + + next(); + }); +} + +router.use('/client', express.static(path.join(__dirname, '../dist'))); +router.use('/public', express.static(path.join(__dirname, '../public'))); /** * Serves a file based on a relative path. @@ -21,6 +54,60 @@ router.get('/embed.js', serveFile('../dist/embed.js')); router.get('/embed.js.gz', serveFile('../dist/embed.js.gz')); router.get('/embed.js.map', serveFile('../dist/embed.js.map')); +//============================================================================== +// PASSPORT MIDDLEWARE +//============================================================================== + +const passportDebug = require('debug')('talk:passport'); + +// Install the passport plugins. +plugins.get('server', 'passport').forEach((plugin) => { + passportDebug(`added plugin '${plugin.plugin.name}'`); + + // Pass the passport.js instance to the plugin to allow it to inject it's + // functionality. + plugin.passport(passport); +}); + +// Setup the PassportJS Middleware. +router.use(passport.initialize()); + +// Attach the authentication middleware, this will be responsible for decoding +// (if present) the JWT on the request. +router.use('/api', authentication, pubsub); + +//============================================================================== +// GraphQL Router +//============================================================================== + +// GraphQL endpoint. +router.use('/api/v1/graph/ql', apollo.graphqlExpress(createGraphOptions)); + +// Only include the graphiql tool if we aren't in production mode. +if (process.env.NODE_ENV !== 'production') { + + // Interactive graphiql interface. + router.use('/api/v1/graph/iql', (req, res) => { + res.render('graphiql', { + endpointURL: `${req.app.locals.BASE_URL}api/v1/graph/ql` + }); + }); + + // GraphQL documention. + router.get('/admin/docs', (req, res) => { + res.render('admin/docs'); + }); + +} + +//============================================================================== +// ROUTES +//============================================================================== + +router.use('/api/v1', require('./api')); +router.use('/admin', require('./admin')); +router.use('/embed', require('./embed')); + if (process.env.NODE_ENV !== 'production') { router.use('/assets', require('./assets')); @@ -43,4 +130,53 @@ plugins.get('server', 'router').forEach((plugin) => { plugin.router(router); }); +//============================================================================== +// ERROR HANDLING +//============================================================================== + +// Catch 404 and forward to error handler. +router.use((req, res, next) => { + next(errors.ErrNotFound); +}); + +// General api error handler. Respond with the message and error if we have it +// while returning a status code that makes sense. +router.use('/api', (err, req, res, next) => { + if (err !== errors.ErrNotFound) { + if (process.env.NODE_ENV !== 'test' || enabled('talk:errors')) { + console.error(err); + } + } + + if (err instanceof errors.APIError) { + res.status(err.status).json({ + message: err.message, + error: err + }); + } else { + res.status(500).json({}); + } +}); + +router.use('/', (err, req, res, next) => { + if (err !== errors.ErrNotFound) { + console.error(err); + } + + i18n.init(req); + + if (err instanceof errors.APIError) { + res.status(err.status); + res.render('error', { + message: err.message, + error: process.env.NODE_ENV === 'development' ? err : {} + }); + } else { + res.render('error', { + message: err.message, + error: process.env.NODE_ENV === 'development' ? err : {} + }); + } +}); + module.exports = router; diff --git a/services/karma.js b/services/karma.js index a2c087eaa..687b67af0 100644 --- a/services/karma.js +++ b/services/karma.js @@ -19,7 +19,7 @@ const { * * The default used is: * - * comment:-1,-1;flag:-1,-1 + * comment:2,-2;flag:2,-2 */ const parseThresholds = (thresholds) => thresholds .split(';') diff --git a/services/passport.js b/services/passport.js index 409bb2279..14a2134ce 100644 --- a/services/passport.js +++ b/services/passport.js @@ -23,7 +23,8 @@ const { JWT_ALG, RECAPTCHA_SECRET, RECAPTCHA_ENABLED, - JWT_COOKIE_NAME, + JWT_SIGNING_COOKIE_NAME, + JWT_COOKIE_NAMES, JWT_CLEAR_COOKIE_LOGOUT, JWT_USER_ID_CLAIM, } = require('../config'); @@ -53,7 +54,7 @@ const GenerateToken = (user) => { const SetTokenForSafari = (req, res, token) => { const browser = bowser._detect(req.headers['user-agent']); if (browser.ios || browser.safari) { - res.cookie(JWT_COOKIE_NAME, token, { + res.cookie(JWT_SIGNING_COOKIE_NAME, token, { httpOnly: true, secure: process.env.NODE_ENV === 'production', expires: new Date(Date.now() + ms(JWT_EXPIRY)) @@ -169,7 +170,7 @@ const HandleLogout = (req, res, next) => { // Only clear the cookie on logout if enabled. if (JWT_CLEAR_COOKIE_LOGOUT) { - res.clearCookie(JWT_COOKIE_NAME); + res.clearCookie(JWT_SIGNING_COOKIE_NAME); } res.status(204).end(); @@ -209,14 +210,20 @@ const CheckBlacklisted = async (jwt) => { const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; -let cookieExtractor = function(req) { - let token = null; - +let cookieExtractor = (req) => { if (req && req.cookies) { - token = req.cookies[JWT_COOKIE_NAME]; + + // Walk over all the cookie names in JWT_COOKIE_NAMES. + for (const cookieName of JWT_COOKIE_NAMES) { + + // Check to see if that cookie is set. + if (cookieName in req.cookies && req.cookies[cookieName] !== null && req.cookies[cookieName].length > 0) { + return req.cookies[cookieName]; + } + } } - return token; + return null; }; // Override the JwtVerifier method on the JwtStrategy so we can pack the diff --git a/services/pubsub.js b/services/pubsub.js index 780aeba16..9fc2ae902 100644 --- a/services/pubsub.js +++ b/services/pubsub.js @@ -1,23 +1,24 @@ const {RedisPubSub} = require('graphql-redis-subscriptions'); +const {connectionOptions, attachMonitors} = require('./redis'); -const {connectionOptions} = require('./redis'); +/** + * getClient returns the pubsub singleton for this instance. + */ +let pubsub = null; +const getClient = () => { + if (pubsub !== null) { + return pubsub; + } -const createClient = () => new RedisPubSub({connection: connectionOptions}); + pubsub = new RedisPubSub({connection: connectionOptions}); -const createClientFactory = () => { - let ins = null; - return () => { - if (ins) { - return ins; - } + // Attach the node monitors to the subscriber + publishers. + attachMonitors(pubsub.redisPublisher); + attachMonitors(pubsub.redisSubscriber); - ins = createClient(); - - return ins; - }; + return pubsub; }; module.exports = { - createClient, - createClientFactory + getClient, }; diff --git a/services/redis.js b/services/redis.js index 1983249f1..b87e5e9fd 100644 --- a/services/redis.js +++ b/services/redis.js @@ -1,45 +1,80 @@ const redis = require('redis'); const debug = require('debug')('talk:services:redis'); +const enabled = require('debug').enabled('talk:services:redis'); const { - REDIS_URL + REDIS_URL, + REDIS_RECONNECTION_MAX_ATTEMPTS, + REDIS_RECONNECTION_MAX_RETRY_TIME, + REDIS_RECONNECTION_BACKOFF_FACTOR, + REDIS_RECONNECTION_BACKOFF_MINIMUM_TIME, } = require('../config'); +const attachMonitors = (client) => { + debug('client created'); + + // Debug events. + if (enabled) { + client.on('ready', () => debug('client ready')); + client.on('connect', () => debug('client connected')); + client.on('reconnecting', () => debug('client connection lost, attempting to reconnect')); + client.on('end', () => debug('client ended')); + } + + // Error events. + client.on('error', (err) => { + if (err) { + console.error('Error connecting to redis:', err); + } + }); +}; + const connectionOptions = { url: REDIS_URL, retry_strategy: function(options) { - if (options.error && options.error.code === 'ECONNREFUSED') { + if (options.error && options.error.code !== 'ECONNREFUSED') { + + debug('retry strategy: none, an error occured'); // End reconnecting on a specific error and flush all commands with a individual error - return new Error('The server refused the connection'); + return options.error; } - if (options.total_retry_time > 1000 * 60 * 60) { + if (options.total_retry_time > REDIS_RECONNECTION_MAX_RETRY_TIME) { + + debug('retry strategy: none, exhausted retry time'); // End reconnecting after a specific timeout and flush all commands with a individual error return new Error('Retry time exhausted'); } - if (options.times_connected > 10) { + if (options.attempt > REDIS_RECONNECTION_MAX_ATTEMPTS) { + + debug('retry strategy: none, exhausted retry attempts'); // End reconnecting with built in error return undefined; } // reconnect after - return Math.max(options.attempt * 100, 3000); + const delay = Math.max(options.attempt * REDIS_RECONNECTION_BACKOFF_FACTOR, REDIS_RECONNECTION_BACKOFF_MINIMUM_TIME); + + debug(`retry strategy: try to reconnect ${delay} ms from now`); + + return delay; } }; const createClient = () => { let client = redis.createClient(connectionOptions); + // Attach the monitors that will print debug messages to the console. + attachMonitors(client); + client.ping((err) => { if (err) { console.error('Can\'t ping the redis server!'); throw err; } - - debug('connection established'); }); return client; @@ -47,12 +82,13 @@ const createClient = () => { module.exports = { connectionOptions, + attachMonitors, createClient, createClientFactory: () => { let client = null; return () => { - if (client) { + if (client !== null) { return client; } diff --git a/services/tags.js b/services/tags.js index fbe6b58ec..b0d0c4b96 100644 --- a/services/tags.js +++ b/services/tags.js @@ -205,8 +205,8 @@ class TagsService { return updateModel(item_type, query, { $pull: { tags: { - name: link.tag.name - } + 'tag.name': link.tag.name, + }, } }); } diff --git a/services/wordlist.js b/services/wordlist.js index 2ae8ed90c..8744de4ba 100644 --- a/services/wordlist.js +++ b/services/wordlist.js @@ -1,8 +1,8 @@ const debug = require('debug')('talk:services:wordlist'); const _ = require('lodash'); -const natural = require('natural'); -const tokenizer = new natural.WordTokenizer(); -const nameTokenizer = new natural.RegexpTokenizer({pattern: /\_/}); +const {RegexpTokenizer} = require('natural'); +const tokenizer = new RegexpTokenizer({pattern: /[\.\s\'\"\?\!]/}); +const nameTokenizer = new RegexpTokenizer({pattern: /\_/}); const SettingsService = require('./settings'); const Errors = require('../errors'); @@ -73,7 +73,7 @@ class Wordlist { if (word.length === 1) { return [word]; } - + return tokenizer.tokenize(word.toLowerCase()); }) .filter((tokens) => { diff --git a/test/server/middleware/authorization.js b/test/server/middleware/authorization.js new file mode 100644 index 000000000..7966cffa9 --- /dev/null +++ b/test/server/middleware/authorization.js @@ -0,0 +1,47 @@ +const chai = require('chai'); +const expect = chai.expect; + +const authz = require('../../../middleware/authorization'); + +describe('middleware.authorization', () => { + describe('#has', () => { + it('allows if no roles are specified', () => { + expect(authz.has({roles: []})).to.be.true; + }); + it('allows if the correct roles are met', () => { + expect(authz.has({roles: ['ADMIN']}, 'ADMIN', 'MODERATOR')).to.be.true; + }); + it('disallows if the role required is missing', () => { + expect(authz.has({roles: []}, 'ADMIN', 'MODERATOR')).to.be.false; + }); + }); + + describe('#needed', () => { + let needed = (...roles) => { + let middleware = authz.needed(...roles); + + return middleware[middleware.length - 1]; + }; + + it('allows if no roles are specified', () => { + needed()({user: {roles: []}}, {}, (err) => { + expect(err).to.be.undefined; + }); + }); + it('allows if the correct roles are met', () => { + needed()({user: {roles: ['ADMIN']}}, {}, (err) => { + expect(err).to.be.undefined; + }); + }); + it('disallows if the role required is missing', () => { + needed('ADMIN', 'MODERATOR')({user: {roles: []}}, {}, (err) => { + expect(err).to.not.be.undefined; + }); + }); + it('disallows if there is no user on the request', () => { + needed('ADMIN', 'MODERATOR')({}, {}, (err) => { + expect(err).to.not.be.undefined; + }); + }); + }); +}); diff --git a/test/server/routes/api/account/index.js b/test/server/routes/api/account/index.js index 8d4e0057a..3195db0e5 100644 --- a/test/server/routes/api/account/index.js +++ b/test/server/routes/api/account/index.js @@ -1,71 +1,57 @@ const passport = require('../../../passport'); const app = require('../../../../../app'); + const chai = require('chai'); +chai.use(require('chai-as-promised')); +chai.use(require('chai-http')); const expect = chai.expect; +const UsersService = require('../../../../../services/users'); const SettingsService = require('../../../../../services/settings'); const settings = {id: '1', moderation: 'PRE', wordlist: {banned: ['bad words'], suspect: ['suspect words']}}; -// Setup chai. -chai.should(); -chai.use(require('chai-http')); - -const UsersService = require('../../../../../services/users'); - describe('/api/v1/account/username', () => { let mockUser; - - beforeEach(() => SettingsService.init(settings).then(() => { - return UsersService.createLocalUser('ana@gmail.com', '123321123', 'Ana'); - }) - .then((user) => { - mockUser = user; - })); + beforeEach(async () => { + await SettingsService.init(settings); + mockUser = await UsersService.createLocalUser('ana@gmail.com', '123321123', 'Ana'); + }); describe('#put', () => { - it('it should enable a user to edit their username if canEditName is enabled', () => { - return chai.request(app) + it('it should enable a user to edit their username if canEditName is enabled', async () => { + await chai.request(app) .post(`/api/v1/users/${mockUser.id}/username-enable`) - .set(passport.inject({id: '456', roles: ['ADMIN']})) - .then(() => chai.request(app) + .set(passport.inject({id: '456', roles: ['ADMIN']})); + + const res = await chai.request(app) .put('/api/v1/account/username') .set(passport.inject({id: mockUser.id, roles: []})) - .send({username: 'MojoJojo'})) - .then((res) => { - expect(res).to.have.status(204); - }); + .send({username: 'MojoJojo'}); + + expect(res).to.have.status(204); }); - it('it should return an error if the wrong user tries to edit a username', (done) => { - chai.request(app) + it('it should return an error if the wrong user tries to edit a username', async () => { + await chai.request(app) .post(`/api/v1/users/${mockUser.id}/username-enable`) - .set(passport.inject({id: '456', roles: ['ADMIN']})) - .then(() => chai.request(app) + .set(passport.inject({id: '456', roles: ['ADMIN']})); + + let res = chai.request(app) .put('/api/v1/account/username') .set(passport.inject({id: 'wrongid', roles: []})) - .send({username: 'MojoJojo'})) - .then(() => { - done(new Error('Expected Error')); - }) - .catch((err) => { - expect(err).to.be.ok; - done(); - }); + .send({username: 'MojoJojo'}); + + return expect(res).to.eventually.be.rejected; }); - it('it should return an error when the user tries to edit their username if canEditName is disabled', (done) => { - chai.request(app) + it('it should return an error when the user tries to edit their username if canEditName is disabled', () => { + let res = chai.request(app) .put('/api/v1/account/username') .set(passport.inject({id: mockUser.id, roles: []})) - .send({username: 'MojoJojo'}) - .then(() => { - done(new Error('Expected Error')); - }) - .catch((err) => { - expect(err).to.be.ok; - done(); - }); + .send({username: 'MojoJojo'}); + + return expect(res).to.eventually.be.rejected; }); }); }); diff --git a/test/server/services/tags.js b/test/server/services/tags.js index 7cdad829e..1080563f0 100644 --- a/test/server/services/tags.js +++ b/test/server/services/tags.js @@ -27,7 +27,7 @@ describe('services.TagsService', () => { const id = comment.id; const name = 'BEST'; const assigned_by = user.id; - + await TagsService.add(id, 'COMMENTS', { tag: { name @@ -45,7 +45,7 @@ describe('services.TagsService', () => { const id = comment.id; const name = 'BEST'; const assigned_by = user.id; - + await TagsService.add(id, 'COMMENTS', { tag: { name @@ -103,5 +103,43 @@ describe('services.TagsService', () => { expect(tags.length).to.equal(0); } }); + it('removes a tag out of 2', async () => { + const id = comment.id; + const name = 'BEST'; + const assigned_by = user.id; + + await TagsService.add(id, 'COMMENTS', { + tag: { + name: 'ANOTHER' + }, + assigned_by + }); + + await TagsService.add(id, 'COMMENTS', { + tag: { + name + }, + assigned_by + }); + + { + const {tags} = await CommentsService.findById(id); + expect(tags.length).to.equal(2); + } + + // ok now to remove it + await TagsService.remove(id, 'COMMENTS', { + tag: { + name + }, + assigned_by + }); + + { + const {tags} = await CommentsService.findById(id); + expect(tags.length).to.equal(1); + expect(tags[0].tag.name).to.equal('ANOTHER'); + } + }); }); }); diff --git a/test/server/services/wordlist.js b/test/server/services/wordlist.js index 417844da4..19545ff3e 100644 --- a/test/server/services/wordlist.js +++ b/test/server/services/wordlist.js @@ -10,10 +10,13 @@ describe('services.Wordlist', () => { 'cookies', 'how to do bad things', 'how to do really bad things', - 's h i t' + 's h i t', + '$hit', + 'p**ch', + 'p*ch', ], suspect: [ - 'do bad things' + 'do bad things', ] }; @@ -26,9 +29,19 @@ describe('services.Wordlist', () => { before(() => wordlist.upsert(wordlists)); - it('has entries', () => { - expect(wordlist.lists.banned).to.not.be.empty; - expect(wordlist.lists.suspect).to.not.be.empty; + it('parses the wordlists correctly', () => { + expect(wordlist.lists.banned).to.deep.equal([ + [ 'cookies' ], + [ 'how', 'to', 'do', 'bad', 'things' ], + [ 'how', 'to', 'do', 'really', 'bad', 'things' ], + [ 's', 'h', 'i', 't' ], + [ '$hit' ], + [ 'p**ch' ], + [ 'p*ch' ], + ]); + expect(wordlist.lists.suspect).to.deep.equal([ + [ 'do', 'bad', 'things' ], + ]); }); }); @@ -57,7 +70,9 @@ describe('services.Wordlist', () => { 'cookies', 'COOKIES.', 'how to do bad things', - 'How To do bad things!' + 'How To do bad things!', + 'This stuff is $hit!', + 'That\'s a p**ch!', ].forEach((word) => { expect(wordlist.match(bannedList, word)).to.be.true; }); @@ -68,7 +83,10 @@ describe('services.Wordlist', () => { 'how to', 'cookie', 'how to be a great person?', - 'how to not do really bad things?' + 'how to not do really bad things?', + 'i have $100 dollars.', + 'I have bad $ hit lling', + 'That\'s a p***ch!', ].forEach((word) => { expect(wordlist.match(bannedList, word)).to.be.false; }); @@ -76,6 +94,39 @@ describe('services.Wordlist', () => { }); + describe('#scan', () => { + + it('does match on a bad word', () => { + [ + 'how to do really bad things', + 'what is cookies', + 'cookies', + 'COOKIES.', + 'how to do bad things', + 'How To do bad things!', + 'This stuff is $hit!', + 'That\'s a p**ch!', + ].forEach((word) => { + expect(wordlist.scan('body', word)).to.not.be.undefined; + }); + }); + + it('does not match on a good word', () => { + [ + 'how to', + 'cookie', + 'how to be a great person?', + 'how to not do really bad things?', + 'i have $100 dollars.', + 'I have bad $ hit lling', + 'That\'s a p***ch!', + ].forEach((word) => { + expect(wordlist.scan('body', word)).to.be.undefined; + }); + }); + + }); + describe('#checkName', () => { [ 'flowers', diff --git a/url.js b/url.js new file mode 100644 index 000000000..1def7a707 --- /dev/null +++ b/url.js @@ -0,0 +1,19 @@ +const {ROOT_URL, ROOT_URL_MOUNT_PATH} = require('./config'); +const {URL} = require('url'); + +// Set the BASE_URL as the ROOT_URL, here we derive the root url by ensuring +// that it ends in a `/`. +const BASE_URL = ROOT_URL && ROOT_URL.length > 0 && ROOT_URL[ROOT_URL.length - 1] === '/' ? ROOT_URL : `${ROOT_URL}/`; + +// The BASE_PATH is simply the path component of the BASE_URL. +const BASE_PATH = new URL(BASE_URL).pathname; + +// The MOUNT_PATH is derived from the BASE_PATH, if it is provided and enabled. +// This will mount all the application routes onto it. +const MOUNT_PATH = ROOT_URL_MOUNT_PATH ? BASE_PATH : '/'; + +module.exports = { + BASE_URL: BASE_URL, + BASE_PATH: BASE_PATH, + MOUNT_PATH: MOUNT_PATH, +}; diff --git a/views/admin.ejs b/views/admin.ejs index 0a7c1c218..2aa23aa58 100644 --- a/views/admin.ejs +++ b/views/admin.ejs @@ -42,6 +42,6 @@
    - + diff --git a/views/admin/confirm-email.ejs b/views/admin/confirm-email.ejs index 20d213fa2..ed23d3dc8 100644 --- a/views/admin/confirm-email.ejs +++ b/views/admin/confirm-email.ejs @@ -71,7 +71,7 @@ $('.error-console').removeClass('active'); $.ajax({ - url: '/api/v1/account/email/verify', + url: '<%= BASE_PATH %>api/v1/account/email/verify', contentType: 'application/json', method: 'POST', data: JSON.stringify({token: location.hash.replace('#', '')}) diff --git a/views/admin/docs.ejs b/views/admin/docs.ejs index de288e055..d13dff064 100644 --- a/views/admin/docs.ejs +++ b/views/admin/docs.ejs @@ -28,6 +28,6 @@
    - + diff --git a/views/admin/password-reset.ejs b/views/admin/password-reset.ejs index 704b5213d..f02e5b6f8 100644 --- a/views/admin/password-reset.ejs +++ b/views/admin/password-reset.ejs @@ -117,7 +117,7 @@ } $.ajax({ - url: '/api/v1/account/password/reset', + url: '<%= BASE_PATH %>api/v1/account/password/reset', contentType: 'application/json', method: 'PUT', data: JSON.stringify({password: password, token: location.hash.replace('#', '')}) diff --git a/views/article.ejs b/views/article.ejs index 098a95524..0f8c75594 100644 --- a/views/article.ejs +++ b/views/article.ejs @@ -17,15 +17,14 @@ } <%= title %> -

    <%= title %>

    <%= body %>

    -

    Admin - All Assets

    +

    Admin - All Assets

    - + diff --git a/yarn.lock b/yarn.lock index 255dc7415..818049337 100644 --- a/yarn.lock +++ b/yarn.lock @@ -9,10 +9,6 @@ git-url-parse "^6.0.2" shelljs "^0.7.0" -"@types/async@^2.0.31": - version "2.0.40" - resolved "https://registry.yarnpkg.com/@types/async/-/async-2.0.40.tgz#ac02de68e66c004a61b7cb16df8b1db3a254cca9" - "@types/express-serve-static-core@*": version "4.0.44" resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.0.44.tgz#a1c3bd5d80e93c72fba91a03f5412c47f21d4ae7" @@ -26,18 +22,18 @@ "@types/express-serve-static-core" "*" "@types/serve-static" "*" +"@types/graphql@0.10.2": + version "0.10.2" + resolved "https://registry.yarnpkg.com/@types/graphql/-/graphql-0.10.2.tgz#d7c79acbaa17453b6681c80c34b38fcb10c4c08c" + "@types/graphql@^0.8.5", "@types/graphql@^0.8.6": version "0.8.6" resolved "https://registry.yarnpkg.com/@types/graphql/-/graphql-0.8.6.tgz#b34fb880493ba835b0c067024ee70130d6f9bb68" -"@types/graphql@^0.9.0", "@types/graphql@^0.9.1": +"@types/graphql@^0.9.1": version "0.9.1" resolved "https://registry.yarnpkg.com/@types/graphql/-/graphql-0.9.1.tgz#b04ebe84bc997cc60dbea2ed4d0d4342c737f99d" -"@types/isomorphic-fetch@0.0.33": - version "0.0.33" - resolved "https://registry.yarnpkg.com/@types/isomorphic-fetch/-/isomorphic-fetch-0.0.33.tgz#3ea1b86f8b73e6a7430d01d4dbd5b1f63fd72718" - "@types/mime@*": version "0.0.29" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-0.0.29.tgz#fbcfd330573b912ef59eeee14602bface630754b" @@ -162,6 +158,10 @@ ansi-escapes@^1.1.0: version "1.4.0" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-1.4.0.tgz#d3a8a83b319aa67793662b13e761c7911422306e" +ansi-escapes@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-2.0.0.tgz#5bae52be424878dd9783e8910e3fc2922e83c81b" + ansi-regex@^1.0.0, ansi-regex@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-1.1.1.tgz#41c847194646375e6a1a5d10c3ca054ef9fc980d" @@ -170,10 +170,20 @@ ansi-regex@^2.0.0: version "2.1.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" +ansi-regex@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998" + ansi-styles@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" +ansi-styles@^3.1.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.0.tgz#c159b8d5be0f9e5a6f346dab94f16ce022161b88" + dependencies: + color-convert "^1.9.0" + any-promise@^0.1.0, any-promise@~0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/any-promise/-/any-promise-0.1.0.tgz#830b680aa7e56f33451d4b049f3bd8044498ee27" @@ -189,20 +199,27 @@ anymatch@^1.3.0: arrify "^1.0.0" micromatch "^2.1.5" -apollo-client@^1.0.2, apollo-client@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/apollo-client/-/apollo-client-1.0.4.tgz#af75db8cdd27e08a835ddfb39807849e178540f9" +apollo-client@^1.4.0, apollo-client@^1.9.1: + version "1.9.1" + resolved "https://registry.yarnpkg.com/apollo-client/-/apollo-client-1.9.1.tgz#9e6a383605572c755038cf5d7fdac9382bcdc040" dependencies: - graphql "^0.9.3" + apollo-link-core "^0.5.0" + graphql "^0.10.0" graphql-anywhere "^3.0.1" graphql-tag "^2.0.0" redux "^3.4.0" symbol-observable "^1.0.2" whatwg-fetch "^2.0.0" optionalDependencies: - "@types/async" "^2.0.31" - "@types/graphql" "^0.9.0" - "@types/isomorphic-fetch" "0.0.33" + "@types/graphql" "0.10.2" + +apollo-link-core@^0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/apollo-link-core/-/apollo-link-core-0.5.0.tgz#dc87da1aaa63b029321ae70938dc26257f5ab8c6" + dependencies: + graphql "^0.10.3" + graphql-tag "^2.4.2" + zen-observable-ts "^0.4.0" app-module-path@^2.2.0: version "2.2.0" @@ -1498,6 +1515,14 @@ chalk@1.1.3, chalk@^1.0.0, chalk@^1.1.0, chalk@^1.1.1, chalk@^1.1.3: strip-ansi "^3.0.0" supports-color "^2.0.0" +chalk@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.1.0.tgz#ac5becf14fa21b99c6c92ca7a7d7cfd5b17e743e" + dependencies: + ansi-styles "^3.1.0" + escape-string-regexp "^1.0.5" + supports-color "^4.0.0" + change-emitter@^0.1.2: version "0.1.6" resolved "https://registry.yarnpkg.com/change-emitter/-/change-emitter-0.1.6.tgz#e8b2fe3d7f1ab7d69a32199aff91ea6931409515" @@ -1727,7 +1752,7 @@ codemirror@*: version "5.25.2" resolved "https://registry.yarnpkg.com/codemirror/-/codemirror-5.25.2.tgz#8c77677ca9c9248d757d3a07ed1e89a8404850b7" -color-convert@^1.3.0: +color-convert@^1.3.0, color-convert@^1.9.0: version "1.9.0" resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.0.tgz#1accf97dd739b983bf994d56fec8f95853641b7a" dependencies: @@ -3053,10 +3078,12 @@ extend@^1.2.1: version "1.3.0" resolved "https://registry.yarnpkg.com/extend/-/extend-1.3.0.tgz#d1516fb0ff5624d2ebf9123ea1dac5a1994004f8" -external-editor@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/external-editor/-/external-editor-2.0.1.tgz#4c597c6c88fa6410e41dbbaa7b1be2336aa31095" +external-editor@^2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/external-editor/-/external-editor-2.0.4.tgz#1ed9199da9cbfe2ef2f7a31b2fde8b0d12368972" dependencies: + iconv-lite "^0.4.17" + jschardet "^1.4.2" tmp "^0.0.31" extglob@^0.3.1: @@ -3687,6 +3714,10 @@ graphql-tag@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/graphql-tag/-/graphql-tag-2.0.0.tgz#f3efe3b4d64f33bfe8479ae06a461c9d72f2a6fe" +graphql-tag@^2.4.2: + version "2.4.2" + resolved "https://registry.yarnpkg.com/graphql-tag/-/graphql-tag-2.4.2.tgz#6a63297d8522d03a2b72d26f1b239aab343840cd" + graphql-tools@^0.10.1: version "0.10.1" resolved "https://registry.yarnpkg.com/graphql-tools/-/graphql-tools-0.10.1.tgz#274aa338d50b1c0b3ed6936eafd8ed3a19ed1828" @@ -3697,13 +3728,19 @@ graphql-tools@^0.10.1: optionalDependencies: "@types/graphql" "^0.8.5" +graphql@^0.10.0, graphql@^0.10.3: + version "0.10.5" + resolved "https://registry.yarnpkg.com/graphql/-/graphql-0.10.5.tgz#c9be17ca2bdfdbd134077ffd9bbaa48b8becd298" + dependencies: + iterall "^1.1.0" + graphql@^0.7.2: version "0.7.2" resolved "https://registry.yarnpkg.com/graphql/-/graphql-0.7.2.tgz#cc894a32823399b8a0cb012b9e9ecad35cd00f72" dependencies: iterall "1.0.2" -graphql@^0.9.1, graphql@^0.9.3: +graphql@^0.9.1: version "0.9.3" resolved "https://registry.yarnpkg.com/graphql/-/graphql-0.9.3.tgz#71fc0fa331bffb9c20678485861cfb370803118e" dependencies: @@ -3757,6 +3794,10 @@ has-flag@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" +has-flag@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-2.0.0.tgz#e8207af1cc7b30d446cc70b734b5e8be18f88d51" + has-unicode@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9" @@ -3848,6 +3889,10 @@ hoist-non-react-statics@^1.0.0, hoist-non-react-statics@^1.0.3, hoist-non-react- version "1.2.0" resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-1.2.0.tgz#aa448cf0986d55cc40773b17174b7dd066cb7cfb" +hoist-non-react-statics@^2.2.0: + version "2.2.2" + resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-2.2.2.tgz#c0eca5a7d5a28c5ada3107eb763b01da6bfa81fb" + home-or-tmp@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/home-or-tmp/-/home-or-tmp-2.0.0.tgz#e36c3f2d2cae7d746a857e38d18d5f32a7882db8" @@ -3968,10 +4013,14 @@ iconv-lite@0.4.13: version "0.4.13" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.13.tgz#1f88aba4ab0b1508e8312acc39345f36e992e2f2" -iconv-lite@0.4.15, iconv-lite@^0.4.5, iconv-lite@~0.4.13: +iconv-lite@0.4.15: version "0.4.15" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.15.tgz#fe265a218ac6a57cfe854927e9d04c19825eddeb" +iconv-lite@^0.4.17, iconv-lite@^0.4.5, iconv-lite@~0.4.13: + version "0.4.18" + resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.18.tgz#23d8656b16aae6742ac29732ea8f0336a4789cf2" + icss-replace-symbols@1.0.2, icss-replace-symbols@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/icss-replace-symbols/-/icss-replace-symbols-1.0.2.tgz#cb0b6054eb3af6edc9ab1d62d01933e2d4c8bfa5" @@ -4002,10 +4051,6 @@ immutability-helper@^2.2.0: dependencies: invariant "^2.2.0" -immutable@^3.8.1: - version "3.8.1" - resolved "https://registry.yarnpkg.com/immutable/-/immutable-3.8.1.tgz#200807f11ab0f72710ea485542de088075f68cd2" - imports-loader@^0.7.1: version "0.7.1" resolved "https://registry.yarnpkg.com/imports-loader/-/imports-loader-0.7.1.tgz#f204b5f34702a32c1db7d48d89d5e867a0441253" @@ -4103,22 +4148,23 @@ inquirer@0.8.2: rx "^2.4.3" through "^2.3.6" -inquirer@^3.0.6: - version "3.0.6" - resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-3.0.6.tgz#e04aaa9d05b7a3cb9b0f407d04375f0447190347" +inquirer@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-3.2.1.tgz#06ceb0f540f45ca548c17d6840959878265fa175" dependencies: - ansi-escapes "^1.1.0" - chalk "^1.0.0" + ansi-escapes "^2.0.0" + chalk "^2.0.0" cli-cursor "^2.1.0" cli-width "^2.0.0" - external-editor "^2.0.1" + external-editor "^2.0.4" figures "^2.0.0" lodash "^4.3.0" mute-stream "0.0.7" run-async "^2.2.0" - rx "^4.1.0" - string-width "^2.0.0" - strip-ansi "^3.0.0" + rx-lite "^4.0.8" + rx-lite-aggregates "^4.0.8" + string-width "^2.1.0" + strip-ansi "^4.0.0" through "^2.3.6" interpret@^1.0.0: @@ -4498,7 +4544,7 @@ iterall@1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/iterall/-/iterall-1.0.3.tgz#e0b31958f835013c323ff0b10943829ac69aa4b7" -iterall@^1.1.1: +iterall@^1.1.0, iterall@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/iterall/-/iterall-1.1.1.tgz#f7f0af11e9a04ec6426260f5019d9fcca4d50214" @@ -4560,6 +4606,10 @@ jsbn@~0.1.0: version "0.1.1" resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" +jschardet@^1.4.2: + version "1.5.1" + resolved "https://registry.yarnpkg.com/jschardet/-/jschardet-1.5.1.tgz#c519f629f86b3a5bedba58a88d311309eec097f9" + jsdom@^7.0.2: version "7.2.2" resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-7.2.2.tgz#40b402770c2bda23469096bee91ab675e3b1fc6e" @@ -6875,14 +6925,14 @@ react-addons-test-utils@^15.4.2: fbjs "^0.8.4" object-assign "^4.1.0" -react-apollo@^1.1.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/react-apollo/-/react-apollo-1.1.1.tgz#136a6be6e0ed7bfa5292e67073e1829fe12e1e17" +react-apollo@^1.4.12: + version "1.4.12" + resolved "https://registry.yarnpkg.com/react-apollo/-/react-apollo-1.4.12.tgz#0cacbdd335acec4c1079feb48047df1c43f77bdf" dependencies: - apollo-client "^1.0.2" + apollo-client "^1.4.0" graphql-anywhere "^3.0.0" graphql-tag "^2.0.0" - hoist-non-react-statics "^1.2.0" + hoist-non-react-statics "^2.2.0" invariant "^2.2.1" lodash.flatten "^4.2.0" lodash.isequal "^4.1.1" @@ -6890,10 +6940,8 @@ react-apollo@^1.1.0: lodash.pick "^4.4.0" object-assign "^4.0.1" prop-types "^15.5.8" - optionalDependencies: - react-dom "0.14.x || 15.* || ^15.0.0" -"react-dom@0.14.x || 15.* || ^15.0.0", react-dom@^15.3.1, react-dom@^15.4.2: +react-dom@^15.3.1, react-dom@^15.4.2: version "15.5.4" resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-15.5.4.tgz#ba0c28786fd52ed7e4f2135fe0288d462aef93da" dependencies: @@ -7434,6 +7482,16 @@ run-async@^2.2.0: dependencies: is-promise "^2.1.0" +rx-lite-aggregates@^4.0.8: + version "4.0.8" + resolved "https://registry.yarnpkg.com/rx-lite-aggregates/-/rx-lite-aggregates-4.0.8.tgz#753b87a89a11c95467c4ac1626c4efc4e05c67be" + dependencies: + rx-lite "*" + +rx-lite@*, rx-lite@^4.0.8: + version "4.0.8" + resolved "https://registry.yarnpkg.com/rx-lite/-/rx-lite-4.0.8.tgz#0b1e11af8bc44836f04a6407e92da42467b79444" + rx-lite@^3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/rx-lite/-/rx-lite-3.1.2.tgz#19ce502ca572665f3b647b10939f97fd1615f102" @@ -7442,10 +7500,6 @@ rx@^2.4.3: version "2.5.3" resolved "https://registry.yarnpkg.com/rx/-/rx-2.5.3.tgz#21adc7d80f02002af50dae97fd9dbf248755f566" -rx@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/rx/-/rx-4.1.0.tgz#a5f13ff79ef3b740fe30aa803fb09f98805d4782" - safe-buffer@^5.0.1, safe-buffer@~5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.0.1.tgz#d263ca54696cd8a306b5ca6551e92de57918fbe7" @@ -7826,12 +7880,12 @@ string-width@^1.0.1, string-width@^1.0.2: is-fullwidth-code-point "^1.0.0" strip-ansi "^3.0.0" -string-width@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.0.0.tgz#635c5436cc72a6e0c387ceca278d4e2eec52687e" +string-width@^2.0.0, string-width@^2.1.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" dependencies: is-fullwidth-code-point "^2.0.0" - strip-ansi "^3.0.0" + strip-ansi "^4.0.0" string.prototype.codepointat@^0.2.0: version "0.2.0" @@ -7871,6 +7925,12 @@ strip-ansi@^3.0.0, strip-ansi@^3.0.1: dependencies: ansi-regex "^2.0.0" +strip-ansi@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" + dependencies: + ansi-regex "^3.0.0" + strip-bom@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e" @@ -7961,6 +8021,12 @@ supports-color@^3.1.2, supports-color@^3.2.3: dependencies: has-flag "^1.0.0" +supports-color@^4.0.0: + version "4.2.1" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-4.2.1.tgz#65a4bb2631e90e02420dba5554c375a4754bb836" + dependencies: + has-flag "^2.0.0" + svgo@^0.7.0: version "0.7.2" resolved "https://registry.yarnpkg.com/svgo/-/svgo-0.7.2.tgz#9f5772413952135c6fefbf40afe6a4faa88b4bb5" @@ -8754,3 +8820,7 @@ yauzl@^2.5.0: dependencies: buffer-crc32 "~0.2.3" fd-slicer "~1.0.1" + +zen-observable-ts@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/zen-observable-ts/-/zen-observable-ts-0.4.0.tgz#a74bc9fe59747948a577bd513d438e70fcfae7e2"