Added Explore page with Gab Trends partner data

• Added:
- Explore page with Gab Trends partner data
This commit is contained in:
mgabdev 2020-07-01 22:39:43 -04:00
parent 96ee203a54
commit f3b57b5810
15 changed files with 342 additions and 41 deletions

View File

@ -22,6 +22,22 @@ class Api::V1::GabTrendsController < Api::BaseController
end end
end end
render json: body
elsif type == 'partner'
body = Redis.current.get("gabtrends:partner")
if body.nil?
uri = URI("https://trends.gab.com/partner")
uri.query = URI.encode_www_form({})
res = Net::HTTP.get_response(uri)
if res.is_a?(Net::HTTPSuccess)
body = res.body
Redis.current.set("gabtrends:partner", res.body)
Redis.current.expire("gabtrends:partner", 1.minute.seconds)
end
end
render json: body render json: body
else else
raise GabSocial::NotPermittedError raise GabSocial::NotPermittedError

View File

@ -1,5 +1,4 @@
import api from '../api'; import api from '../api'
import { me } from '../initial_state'
export const GAB_TRENDS_RESULTS_FETCH_REQUEST = 'GAB_TRENDS_RESULTS_FETCH_REQUEST' export const GAB_TRENDS_RESULTS_FETCH_REQUEST = 'GAB_TRENDS_RESULTS_FETCH_REQUEST'
export const GAB_TRENDS_RESULTS_FETCH_SUCCESS = 'GAB_TRENDS_RESULTS_FETCH_SUCCESS' export const GAB_TRENDS_RESULTS_FETCH_SUCCESS = 'GAB_TRENDS_RESULTS_FETCH_SUCCESS'
@ -9,8 +8,8 @@ export const fetchGabTrends = (feedType) => {
return function (dispatch, getState) { return function (dispatch, getState) {
dispatch(fetchGabTrendsRequest(feedType)) dispatch(fetchGabTrendsRequest(feedType))
api(getState).get(`/api/v1/gab_trends?type=${feedType}`).then(response => { api(getState).get(`/api/v1/gab_trends?type=${feedType}`).then((response) => {
dispatch(fetchGabTrendsSuccess(response.data.items, feedType)) dispatch(fetchGabTrendsSuccess(response.data, feedType))
}).catch(function (error) { }).catch(function (error) {
dispatch(fetchGabTrendsFail(error, feedType)) dispatch(fetchGabTrendsFail(error, feedType))
}) })

View File

@ -51,9 +51,10 @@ class FooterBar extends PureComponent {
active: currentPathname === '/groups', active: currentPathname === '/groups',
}, },
{ {
href: 'https://trends.gab.com', to: '/explore',
icon: 'trends', icon: 'trends',
title: 'Trends', title: 'Trends',
active: currentPathname === '/explore',
}, },
] ]

View File

@ -107,6 +107,7 @@ class NavigationBar extends ImmutablePureComponent {
<div className={[_s.default, _s.height53PX, _s.pl15, _s.flexRow, _s.alignItemsCenter, _s.justifyContentSpaceBetween].join(' ')}> <div className={[_s.default, _s.height53PX, _s.pl15, _s.flexRow, _s.alignItemsCenter, _s.justifyContentSpaceBetween].join(' ')}>
<NavigationBarButton title='Home' icon='home' to='/home' /> <NavigationBarButton title='Home' icon='home' to='/home' />
<NavigationBarButton title='Explore' icon='explore' to='/explore' />
<NavigationBarButtonDivider /> <NavigationBarButtonDivider />

View File

@ -68,7 +68,11 @@ class TrendsPanel extends ImmutablePureComponent {
key={`gab-trend-${i}`} key={`gab-trend-${i}`}
index={i + 1} index={i + 1}
isLast={i === 7} isLast={i === 7}
trend={trend} title={trend.get('title')}
description={trend.get('description')}
url={trend.get('url')}
author={trend.getIn(['author', 'name'], '')}
date={trend.get('date_published')}
/> />
)) ))
} }

View File

@ -23,7 +23,7 @@ class PillItem extends PureComponent {
// If user navigates to different page, ensure tab bar item // If user navigates to different page, ensure tab bar item
// with this.props.to that is on location is set to active. // with this.props.to that is on location is set to active.
if (this.props.location !== prevProps.location) { if (this.props.location !== prevProps.location) {
const isCurrent = this.props.to === this.props.location.pathname const isCurrent = this.props.to === this.props.location.pathname && !this.props.location.search
if (this.state.isCurrent !== isCurrent) { if (this.state.isCurrent !== isCurrent) {
this.setState({ isCurrent }) this.setState({ isCurrent })
@ -43,7 +43,7 @@ class PillItem extends PureComponent {
// Combine state, props, location to make absolutely // Combine state, props, location to make absolutely
// sure of active status. // sure of active status.
const active = isActive || to === location.pathname || isCurrent const active = isActive || (to === location.pathname && !location.search) || isCurrent
const containerClasses = CX({ const containerClasses = CX({
default: 1, default: 1,

View File

@ -139,6 +139,11 @@ class Sidebar extends ImmutablePureComponent {
icon: 'list', icon: 'list',
to: '/lists', to: '/lists',
}, },
{
title: 'Explore',
icon: 'explore',
to: '/explore',
},
{ {
title: 'More', title: 'More',
icon: 'more', icon: 'more',

View File

@ -18,7 +18,7 @@ export default class TabBar extends PureComponent {
return ( return (
<ResponsiveClassesComponent <ResponsiveClassesComponent
classNames={[_s.default, _s.height53PX, _s.px5, _s.flexRow].join(' ')} classNames={[_s.default, _s.height53PX, _s.px5, _s.flexRow, _s.overflowXScroll, _s.noScrollbar].join(' ')}
classNamesXS={[_s.default, _s.height40PX, _s.px5, _s.flexRow].join(' ')} classNamesXS={[_s.default, _s.height40PX, _s.px5, _s.flexRow].join(' ')}
> >
{ {

View File

@ -31,7 +31,7 @@ class TabBarItem extends PureComponent {
// If user navigates to different page, ensure tab bar item // If user navigates to different page, ensure tab bar item
// with this.props.to that is on location is set to active. // with this.props.to that is on location is set to active.
if (this.props.location !== prevProps.location) { if (this.props.location !== prevProps.location) {
const isCurrent = this.props.to === this.props.location.pathname const isCurrent = this.props.to === this.props.location.pathname && !this.props.location.search
if (this.state.isCurrent !== isCurrent) { if (this.state.isCurrent !== isCurrent) {
this.setState({ isCurrent }) this.setState({ isCurrent })
@ -52,7 +52,7 @@ class TabBarItem extends PureComponent {
// Combine state, props, location to make absolutely // Combine state, props, location to make absolutely
// sure of active status. // sure of active status.
const active = isActive || to === location.pathname || isCurrent const active = isActive || (to === location.pathname && !location.search) || isCurrent
const containerClasses = CX({ const containerClasses = CX({
default: 1, default: 1,

View File

@ -1,6 +1,4 @@
import { Fragment } from 'react' import { Fragment } from 'react'
import ImmutablePureComponent from 'react-immutable-pure-component'
import ImmutablePropTypes from 'react-immutable-proptypes'
import { urlRegex } from '../features/ui/util/url_regex' import { urlRegex } from '../features/ui/util/url_regex'
import { import {
CX, CX,
@ -8,23 +6,28 @@ import {
} from '../constants' } from '../constants'
import Button from './button' import Button from './button'
import DotTextSeperator from './dot_text_seperator' import DotTextSeperator from './dot_text_seperator'
import Image from './image'
import RelativeTimestamp from './relative_timestamp' import RelativeTimestamp from './relative_timestamp'
import Text from './text' import Text from './text'
export default class TrendingItem extends ImmutablePureComponent { export default class TrendingItem extends PureComponent {
static propTypes = { static propTypes = {
index: PropTypes.number, index: PropTypes.number,
trend: ImmutablePropTypes.map.isRequired,
isLast: PropTypes.bool, isLast: PropTypes.bool,
isHidden: PropTypes.bool, isHidden: PropTypes.bool,
title: PropTypes.string,
description: PropTypes.string,
author: PropTypes.string,
url: PropTypes.string,
date: PropTypes.string,
} }
static defaultProps = { static defaultProps = {
title: '', title: '',
description: '', description: '',
author: '', author: '',
url: '',
date: '',
} }
state = { state = {
@ -42,25 +45,29 @@ export default class TrendingItem extends ImmutablePureComponent {
render() { render() {
const { const {
index, index,
trend,
isLast, isLast,
isHidden, isHidden,
title,
description,
author,
url,
date,
} = this.props } = this.props
const { hovering } = this.state const { hovering } = this.state
if (!trend) return null if (!title || !url) return null
const title = `${trend.get('title')}`.trim() const correctedTitle = `${title}`.trim()
const description = trend.get('description') || '' let correctedDescription = description || ''
const correctedAuthor = trend.getIn(['author', 'name'], '').replace('www.', '') const correctedAuthor = `${author}`.replace('www.', '')
const correctedDescription = description.length >= 120 ? `${description.substring(0, 120).trim()}...` : description correctedDescription = correctedDescription.length >= 120 ? `${correctedDescription.substring(0, 120).trim()}...` : correctedDescription
const descriptionHasLink = correctedDescription.match(urlRegex) const descriptionHasLink = correctedDescription.match(urlRegex)
if (isHidden) { if (isHidden) {
return ( return (
<Fragment> <Fragment>
{title} {correctedTitle}
{!descriptionHasLink && correctedDescription} {!descriptionHasLink && correctedDescription}
{correctedAuthor} {correctedAuthor}
</Fragment> </Fragment>
@ -86,30 +93,18 @@ export default class TrendingItem extends ImmutablePureComponent {
return ( return (
<Button <Button
noClasses noClasses
href={trend.get('url')} href={url}
target='_blank' target='_blank'
rel={DEFAULT_REL} rel={DEFAULT_REL}
className={containerClasses} className={containerClasses}
onMouseEnter={() => this.handleOnMouseEnter()} onMouseEnter={() => this.handleOnMouseEnter()}
onMouseLeave={() => this.handleOnMouseLeave()} onMouseLeave={() => this.handleOnMouseLeave()}
> >
{
/*
<Image
nullable
width='116px'
height='78px'
alt={title}
src={trend.get('image')}
className={[_s.radiusSmall, _s.overflowHidden, _s.mb10].join(' ')}
/>
*/
}
<div className={[_s.default, _s.flexNormal, _s.pb5].join(' ')}> <div className={[_s.default, _s.flexNormal, _s.pb5].join(' ')}>
<div className={_s.default}> <div className={_s.default}>
<Text size='medium' color='primary' weight='bold'> <Text size='medium' color='primary' weight='bold'>
{title} {correctedTitle}
</Text> </Text>
</div> </div>
@ -132,7 +127,7 @@ export default class TrendingItem extends ImmutablePureComponent {
</Text> </Text>
<DotTextSeperator /> <DotTextSeperator />
<Text color='secondary' size='small' className={subtitleClasses}> <Text color='secondary' size='small' className={subtitleClasses}>
<RelativeTimestamp timestamp={trend.get('date_published')} /> <RelativeTimestamp timestamp={date} />
</Text> </Text>
{ {
hovering && hovering &&

View File

@ -0,0 +1,221 @@
import { withRouter } from 'react-router-dom'
import isObject from 'lodash.isobject'
import queryString from 'query-string'
import { fetchGabTrends } from '../actions/gab_trends'
import { BREAKPOINT_EXTRA_SMALL } from '../constants'
import Block from '../components/block'
import Heading from '../components/heading'
import Text from '../components/text'
import TrendsItem from '../components/trends_item'
import TabBar from '../components/tab_bar'
import Pills from '../components/pills'
import ColumnIndicator from '../components/column_indicator'
import Responsive from './ui/util/responsive_component';
// const messages = defineMessages({
// title: { id: 'trends.title', defaultMessage: 'Trending right now' },
// })
const mapStateToProps = (state) => ({
isError: state.getIn(['gab_trends', 'partner', 'isError']),
isLoading: state.getIn(['gab_trends', 'partner', 'isLoading']),
items: state.getIn(['gab_trends', 'partner', 'items']),
})
const mapDispatchToProps = (dispatch) => ({
onfetchGabTrends: () => dispatch(fetchGabTrends('partner')),
})
export default
@withRouter
@connect(mapStateToProps, mapDispatchToProps)
class Explore extends PureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
}
static propTypes = {
intl: PropTypes.object.isRequired,
isError: PropTypes.bool,
isLoading: PropTypes.bool,
items: PropTypes.object,
onfetchGabTrends: PropTypes.func.isRequired,
}
state = {
activeDomain: null,
}
updateOnProps = [
'items',
'isLoading',
'isError',
]
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
this.setActiveDomain(this.props.location)
}
}
componentDidMount() {
this.props.onfetchGabTrends()
this.setActiveDomain(this.props.location)
}
setActiveDomain(location) {
const { search } = location
const qp = queryString.parse(search)
const domain = qp.domain ? `${qp.domain}`.toLowerCase() : undefined
console.log("domain: ", qp, domain)
if (!!domain) {
this.setState({ activeDomain: domain })
} else {
this.setState({ activeDomain: null })
}
}
render () {
const {
intl,
isError,
isLoading,
items,
} = this.props
const { activeDomain } = this.state
console.log("activeDomain:", activeDomain)
console.log("items:", items)
if (isError || !isObject(items)) {
return <div>error</div>
}
let domainExists = !activeDomain
let headline, headlineLink
let todaysTopTitle
let leadHeadlines = []
let todaysTop = []
let domainTabs = []
try {
console.log("items.headline:", items.headline)
headline = items.headline.title
headlineLink = items.headline.href
leadHeadlines = items.leadHeadlines
if (activeDomain) {
const domainBlock = items.trackedDomains.find((d) => `${d.domain}`.toLowerCase() === activeDomain)
if (domainBlock) domainExists = true
todaysTop = domainBlock.topUrls
todaysTopTitle = domainBlock.title
} else {
todaysTop = items.trending.topUrls
todaysTopTitle = "Today's Top"
}
const domains = items.trackedDomains
domainTabs = domains.map((block) => ({
title: block.title,
to: `/explore?domain=${block.domain}`,
onClick: () => {},
active: activeDomain === `${block.domain}`.toLowerCase(),
}))
domainTabs = [
{
title: "Today's Top",
to: `/explore`,
onClick: () => {},
active: !activeDomain,
},
...domainTabs,
]
} catch (error) {
return (
<div className={[_s.default, _s.width100PC].join(' ')}>
<Block>
<ColumnIndicator type='loading' />
</Block>
</div>
)
}
if (!domainExists) {
return <div>error</div>
}
console.log("domainTabs:", domainTabs)
return (
<div className={[_s.default, _s.width100PC].join(' ')}>
<Block>
<div className={[_s.default, _s.width100PC, _s.borderBottom1PX, _s.borderColorSecondary].join(' ')}>
<Responsive min={BREAKPOINT_EXTRA_SMALL}>
<TabBar tabs={domainTabs} />
</Responsive>
<Responsive max={BREAKPOINT_EXTRA_SMALL}>
<div className={[_s.default, _s.width100PC, _s.pt10, _s.pb5].join(' ')}>
<Pills pills={domainTabs} />
</div>
</Responsive>
</div>
<div className={[_s.default, _s.px15, _s.py15].join(' ')}>
<div className={[_s.default].join(' ')}>
{
!activeDomain &&
leadHeadlines.map((lead) => (
<div className={[_s.default].join(' ')}>
<Text size='small'>
{lead.title}
</Text>
</div>
))
}
</div>
{
!activeDomain &&
<div className={[_s.default, _s.py15, _s.mt15, _s.mb15].join(' ')}>
<Heading size='h1'>
<a href={headlineLink} className={[_s.noUnderline, _s.colorPrimary].join(' ')}>
{headline}
</a>
</Heading>
</div>
}
<div>
<div className={[_s.default, _s.px15, _s.py10, _s.bgSubtle, _s.justifyContentCenter].join(' ')}>
<Heading size='h2'>
{todaysTopTitle}
</Heading>
</div>
<div className={[_s.default, _s.py10].join(' ')}>
{
todaysTop.map((block, i) => (
<TrendsItem
key={`explore-trending-item-${i}`}
index={i + 1}
title={block.pagePreview.title}
author={block.domain.domain}
description={block.pagePreview.description}
url={block.pagePreview.url}
date={block.created}
/>
))
}
</div>
</div>
</div>
</Block>
</div>
)
}
}

View File

@ -37,6 +37,7 @@ import BasicPage from '../../pages/basic_page'
import ModalPage from '../../pages/modal_page' import ModalPage from '../../pages/modal_page'
import SettingsPage from '../../pages/settings_page' import SettingsPage from '../../pages/settings_page'
import ProPage from '../../pages/pro_page' import ProPage from '../../pages/pro_page'
import ExplorePage from '../../pages/explore_page'
import { import {
AccountGallery, AccountGallery,
@ -45,6 +46,7 @@ import {
BlockedDomains, BlockedDomains,
CommunityTimeline, CommunityTimeline,
Compose, Compose,
Explore,
// Filters, // Filters,
Followers, Followers,
Following, Following,
@ -150,6 +152,8 @@ class SwitchingArea extends PureComponent {
<Redirect from='/' to='/home' exact /> <Redirect from='/' to='/home' exact />
<WrappedRoute path='/home' exact page={HomePage} component={HomeTimeline} content={children} /> <WrappedRoute path='/home' exact page={HomePage} component={HomeTimeline} content={children} />
<WrappedRoute path='/explore' publicRoute page={ExplorePage} component={Explore} content={children} componentParams={{ title: 'Explore' }} />
<WrappedRoute path='/compose' exact page={BasicPage} component={Compose} content={children} componentParams={{ title: 'Compose' }} /> <WrappedRoute path='/compose' exact page={BasicPage} component={Compose} content={children} componentParams={{ title: 'Compose' }} />
<WrappedRoute path='/timeline/all' exact page={CommunityPage} component={CommunityTimeline} content={children} componentParams={{ title: 'Community Feed' }} /> <WrappedRoute path='/timeline/all' exact page={CommunityPage} component={CommunityTimeline} content={children} componentParams={{ title: 'Community Feed' }} />

View File

@ -17,6 +17,7 @@ export function EditProfileModal() { return import(/* webpackChunkName: "compone
export function EmbedModal() { return import(/* webpackChunkName: "modals/embed_modal" */'../../../components/modal/embed_modal') } export function EmbedModal() { return import(/* webpackChunkName: "modals/embed_modal" */'../../../components/modal/embed_modal') }
export function EmojiPicker() { return import(/* webpackChunkName: "emoji_picker" */'../../../components/emoji/emoji_picker') } export function EmojiPicker() { return import(/* webpackChunkName: "emoji_picker" */'../../../components/emoji/emoji_picker') }
export function EmojiPickerPopover() { return import(/* webpackChunkName: "components/emoji_picker_popover" */'../../../components/popover/emoji_picker_popover') } export function EmojiPickerPopover() { return import(/* webpackChunkName: "components/emoji_picker_popover" */'../../../components/popover/emoji_picker_popover') }
export function Explore() { return import(/* webpackChunkName: "features/explore" */'../../explore') }
export function Followers() { return import(/* webpackChunkName: "features/followers" */'../../followers') } export function Followers() { return import(/* webpackChunkName: "features/followers" */'../../followers') }
export function Following() { return import(/* webpackChunkName: "features/following" */'../../following') } export function Following() { return import(/* webpackChunkName: "features/following" */'../../following') }
export function FollowRequests() { return import(/* webpackChunkName: "features/follow_requests" */'../../follow_requests') } export function FollowRequests() { return import(/* webpackChunkName: "features/follow_requests" */'../../follow_requests') }

View File

@ -0,0 +1,39 @@
import { Fragment } from 'react'
import PageTitle from '../features/ui/util/page_title'
import DefaultLayout from '../layouts/default_layout'
import ProgressPanel from '../components/panel/progress_panel'
import VerifiedAccountsPanel from '../components/panel/verified_accounts_panel'
import ShopPanel from '../components/panel/shop_panel'
import LinkFooter from '../components/link_footer'
export default class ExplorePage extends PureComponent {
static propTypes = {
title: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
}
render() {
const { children, title } = this.props
return (
<DefaultLayout
title={title}
noComposeButton
showBackBtn
layout={(
<Fragment>
<ProgressPanel />
<VerifiedAccountsPanel />
<ShopPanel />
<LinkFooter />
</Fragment>
)}
>
<PageTitle path={title} />
{children}
</DefaultLayout>
)
}
}

View File

@ -15,6 +15,11 @@ const initialState = ImmutableMap({
isLoading: false, isLoading: false,
isError: false, isError: false,
}), }),
partner: ImmutableMap({
items: {},
isLoading: false,
isError: false,
}),
}) })
const normalizeList = (state, type, items) => { const normalizeList = (state, type, items) => {
@ -38,7 +43,17 @@ export default function (state = initialState, action) {
case GAB_TRENDS_RESULTS_FETCH_REQUEST: case GAB_TRENDS_RESULTS_FETCH_REQUEST:
return state.setIn([action.feedType, 'isLoading'], true); return state.setIn([action.feedType, 'isLoading'], true);
case GAB_TRENDS_RESULTS_FETCH_SUCCESS: case GAB_TRENDS_RESULTS_FETCH_SUCCESS:
return normalizeList(state, action.feedType, action.items) if (action.feedType === 'feed') {
return normalizeList(state, action.feedType, action.items.items)
} else if (action.feedType === 'partner') {
return state.set('partner', ImmutableMap({
items: action.items['trends'] || {},
isLoading: false,
isError: false,
}))
}
return state
case GAB_TRENDS_RESULTS_FETCH_FAIL: case GAB_TRENDS_RESULTS_FETCH_FAIL:
return setListFailed(state, action.feedType) return setListFailed(state, action.feedType)
default: default: