removeddit/src/state.js

72 lines
2 KiB
JavaScript
Raw Normal View History

2018-07-16 18:12:01 +00:00
import React from 'react'
import { Subscribe, Container } from 'unstated'
2018-07-29 01:59:04 +00:00
import { get, put } from './utils'
2018-01-14 13:41:00 +00:00
2018-07-16 18:12:01 +00:00
// Sort types for comments
export const sort = {
top: 'SORT_TOP',
bottom: 'SORT_BOTTOM',
new: 'SORT_NEW',
old: 'SORT_OLD'
}
2018-01-13 17:20:08 +00:00
2018-07-16 18:12:01 +00:00
// Filter types for comments
export const filter = {
all: 'SHOW_ALL',
removedDeleted: 'SHOW_REMOVED_DELETED',
removed: 'SHOW_REMOVED',
deleted: 'SHOW_DELETED'
}
2018-01-13 17:20:08 +00:00
export const maxCommentsDefault = 800
export const maxCommentsLimit = 20000
2018-07-16 18:12:01 +00:00
// Keys for localStorage
const sortKey = 'commentSort'
const filterKey = 'commentFilter'
const maxCommentsKey = 'maxComments'
2018-07-16 18:12:01 +00:00
class GlobalState extends Container {
state = {
commentSort: get(sortKey, sort.top),
commentFilter: get(filterKey, filter.removedDeleted),
maxComments: get(maxCommentsKey, maxCommentsDefault),
statusText: '',
statusImage: undefined
2018-07-16 18:12:01 +00:00
}
setCommentSort (sortType) {
put(sortKey, sortType)
this.setState({commentSort: sortType})
}
setCommentFilter (filterType) {
put(filterKey, filterType)
this.setState({commentFilter: filterType})
}
saveMaxComments (maxComments) {
maxComments = Math.min(Math.round(maxComments), maxCommentsLimit)
if (!(maxComments >= 100)) // also true when maxComments isn't a number
maxComments = 100
put(maxCommentsKey, maxComments)
return maxComments
}
loadMaxComments = () => this.setState({maxComments: get(maxCommentsKey, maxCommentsDefault)})
setSuccess = () => this.setState({statusText: '', statusImage: '/images/success.png'})
setLoading = (text) => this.setState({statusText: text, statusImage: '/images/loading.gif'})
setError = (error) => this.setState({statusText: error.message, statusImage: '/images/error.png'})
clearStatus = () => this.setState({statusText: '', statusImage: undefined})
2018-07-16 18:12:01 +00:00
}
// A redux-like connect function for Unstated
export const connect = Component => {
return props => (
<Subscribe to={[GlobalState]}>
{globalState => <Component {...props} global={globalState} />}
2018-07-16 18:12:01 +00:00
</Subscribe>
)
}