Merge pull request #129 from 6ea86b96/faster-discover

Some small fixes
This commit is contained in:
Jeremy Kauffman 2017-05-23 11:43:54 -04:00 committed by GitHub
commit 9183717354
19 changed files with 261 additions and 134 deletions

View file

@ -6,7 +6,12 @@ import {
selectUpgradeDownloadItem, selectUpgradeDownloadItem,
selectUpgradeFilename, selectUpgradeFilename,
selectPageTitle, selectPageTitle,
selectCurrentPage,
selectCurrentParams,
} from 'selectors/app' } from 'selectors/app'
import {
doSearch,
} from 'actions/search'
const {remote, ipcRenderer, shell} = require('electron'); const {remote, ipcRenderer, shell} = require('electron');
const path = require('path'); const path = require('path');
@ -43,6 +48,16 @@ export function doChangePath(path) {
path, path,
} }
}) })
const state = getState()
const pageTitle = selectPageTitle(state)
window.document.title = pageTitle
const currentPage = selectCurrentPage(state)
if (currentPage === 'search') {
const params = selectCurrentParams(state)
dispatch(doSearch(params.query))
}
} }
} }
@ -59,7 +74,6 @@ export function doHistoryPush(params, title, relativeUrl) {
const url = pathParts.join('/') const url = pathParts.join('/')
title += " - LBRY" title += " - LBRY"
history.pushState(params, title, url) history.pushState(params, title, url)
window.document.title = title
} }
} }
@ -210,3 +224,16 @@ export function doDaemonReady() {
type: types.DAEMON_READY type: types.DAEMON_READY
} }
} }
export function doShowSnackBar(data) {
return {
type: types.SHOW_SNACKBAR,
data,
}
}
export function doRemoveSnackBarSnack() {
return {
type: types.REMOVE_SNACKBAR_SNACK,
}
}

View file

@ -223,8 +223,11 @@ export function doPurchaseUri(uri) {
// the blobs. Or perhaps there's another way to see if a file was already // the blobs. Or perhaps there's another way to see if a file was already
// purchased? // purchased?
// we already fully downloaded the file // we already fully downloaded the file. If completed is true but
if (fileInfo && fileInfo.completed) { // writtenBytes is false then we downloaded it before but deleted it again,
// which means it needs to be reconstructed from the blobs by dispatching
// doLoadVideo.
if (fileInfo && fileInfo.completed && !!fileInfo.writtenBytes) {
return Promise.resolve() return Promise.resolve()
} }

View file

@ -31,9 +31,6 @@ export function doSearch(query) {
if(page != 'search') { if(page != 'search') {
dispatch(doNavigate('search', { query: query })) dispatch(doNavigate('search', { query: query }))
} else { } else {
dispatch(doHistoryPush({ query }, "Search for " + query, '/search'))
}
lighthouse.search(query).then(results => { lighthouse.search(query).then(results => {
results.forEach(result => { results.forEach(result => {
const uri = lbryuri.build({ const uri = lbryuri.build({
@ -54,3 +51,4 @@ export function doSearch(query) {
}) })
} }
} }
}

View file

@ -1,6 +1,6 @@
import store from 'store.js'; import store from 'store.js';
const env = process.env.NODE_ENV || 'production'; const env = ENV;
const config = require(`./config/${env}`); const config = require(`./config/${env}`);
const logs = []; const logs = [];
const app = { const app = {

View file

@ -58,11 +58,17 @@ class FileListSearch extends React.Component{
} = this.props } = this.props
return ( return (
isSearching ? <div>
<BusyMessage message="Looking up the Dewey Decimals" /> : {isSearching && !results &&
(results && results.length) ? <BusyMessage message="Looking up the Dewey Decimals" />}
{isSearching && results &&
<BusyMessage message="Refreshing the Dewey Decimals" />}
{(results && !!results.length) ?
<FileListSearchResults {...this.props} /> : <FileListSearchResults {...this.props} /> :
<SearchNoResults {...this.props} /> <SearchNoResults {...this.props} />}
</div>
) )
} }
} }

View file

@ -1,60 +0,0 @@
import React from 'react';
export class SnackBar extends React.Component {
constructor(props) {
super(props);
this._displayTime = 5; // in seconds
this._hideTimeout = null;
this.state = {
snacks: []
};
}
handleSnackReceived(event) {
// if (this._hideTimeout) {
// clearTimeout(this._hideTimeout);
// }
let snacks = this.state.snacks;
snacks.push(event.detail);
this.setState({ snacks: snacks});
}
componentWillMount() {
document.addEventListener('globalNotice', this.handleSnackReceived);
}
componentWillUnmount() {
document.removeEventListener('globalNotice', this.handleSnackReceived);
}
render() {
if (!this.state.snacks.length) {
this._hideTimeout = null; //should be unmounting anyway, but be safe?
return null;
}
let snack = this.state.snacks[0];
if (this._hideTimeout === null) {
this._hideTimeout = setTimeout(() => {
this._hideTimeout = null;
let snacks = this.state.snacks;
snacks.shift();
this.setState({ snacks: snacks });
}, this._displayTime * 1000);
}
return (
<div className="snack-bar">
{snack.message}
{snack.linkText && snack.linkTarget ?
<a className="snack-bar__action" href={snack.linkTarget}>{snack.linkText}</a> : ''}
</div>
);
}
}
export default SnackBar;

View file

@ -0,0 +1,23 @@
import React from 'react'
import {
connect,
} from 'react-redux'
import {
doNavigate,
doRemoveSnackBarSnack,
} from 'actions/app'
import {
selectSnackBarSnacks,
} from 'selectors/app'
import SnackBar from './view'
const perform = (dispatch) => ({
navigate: (path) => dispatch(doNavigate(path)),
removeSnack: () => dispatch(doRemoveSnackBarSnack()),
})
const select = (state) => ({
snacks: selectSnackBarSnacks(state),
})
export default connect(select, perform)(SnackBar)

View file

@ -0,0 +1,49 @@
import React from 'react';
import Link from 'component/link'
class SnackBar extends React.Component {
constructor(props) {
super(props);
this._displayTime = 5; // in seconds
this._hideTimeout = null;
}
render() {
const {
navigate,
snacks,
removeSnack,
} = this.props
if (!snacks.length) {
this._hideTimeout = null; //should be unmounting anyway, but be safe?
return null;
}
const snack = snacks[0];
const {
message,
linkText,
linkTarget,
} = snack
if (this._hideTimeout === null) {
this._hideTimeout = setTimeout(() => {
this._hideTimeout = null;
removeSnack()
}, this._displayTime * 1000);
}
return (
<div className="snack-bar">
{message}
{linkText && linkTarget &&
<Link onClick={() => navigate(linkTarget)} label={linkText} />
}
</div>
);
}
}
export default SnackBar;

View file

@ -7,9 +7,6 @@ import {
selectWunderBarAddress, selectWunderBarAddress,
selectWunderBarIcon selectWunderBarIcon
} from 'selectors/search' } from 'selectors/search'
import {
doSearch,
} from 'actions/search'
import { import {
doNavigate, doNavigate,
} from 'actions/app' } from 'actions/app'
@ -21,7 +18,7 @@ const select = (state) => ({
}) })
const perform = (dispatch) => ({ const perform = (dispatch) => ({
onSearch: (query) => dispatch(doSearch(query)), onSearch: (query) => dispatch(doNavigate('/search', { query, })),
onSubmit: (query) => dispatch(doNavigate('/show', { uri: lbryuri.normalize(query) } )) onSubmit: (query) => dispatch(doNavigate('/show', { uri: lbryuri.normalize(query) } ))
}) })

View file

@ -2,6 +2,8 @@ export const CHANGE_PATH = 'CHANGE_PATH'
export const OPEN_MODAL = 'OPEN_MODAL' export const OPEN_MODAL = 'OPEN_MODAL'
export const CLOSE_MODAL = 'CLOSE_MODAL' export const CLOSE_MODAL = 'CLOSE_MODAL'
export const HISTORY_BACK = 'HISTORY_BACK' export const HISTORY_BACK = 'HISTORY_BACK'
export const SHOW_SNACKBAR = 'SHOW_SNACKBAR'
export const REMOVE_SNACKBAR_SNACK = 'REMOVE_SNACKBAR_SNACK'
export const DAEMON_READY = 'DAEMON_READY' export const DAEMON_READY = 'DAEMON_READY'

View file

@ -5,9 +5,10 @@ import lbryio from './lbryio.js';
import lighthouse from './lighthouse.js'; import lighthouse from './lighthouse.js';
import App from 'component/app/index.js'; import App from 'component/app/index.js';
import SplashScreen from 'component/splash.js'; import SplashScreen from 'component/splash.js';
import SnackBar from 'component/snack-bar.js'; import SnackBar from 'component/snackBar';
import {AuthOverlay} from 'component/auth.js'; import {AuthOverlay} from 'component/auth.js';
import { Provider } from 'react-redux'; import { Provider } from 'react-redux';
import batchActions from 'util/batchActions'
import store from 'store.js'; import store from 'store.js';
import { import {
doChangePath, doChangePath,
@ -21,7 +22,9 @@ import {
import { import {
doFileList doFileList
} from 'actions/file_info' } from 'actions/file_info'
import parseQueryParams from 'util/query_params' import {
toQueryString,
} from 'util/query_params'
const {remote, ipcRenderer, shell} = require('electron'); const {remote, ipcRenderer, shell} = require('electron');
const contextMenu = remote.require('./menu/context-menu'); const contextMenu = remote.require('./menu/context-menu');
@ -36,15 +39,19 @@ window.addEventListener('contextmenu', (event) => {
}); });
window.addEventListener('popstate', (event, param) => { window.addEventListener('popstate', (event, param) => {
const queryString = document.location.search const params = event.state
const pathParts = document.location.pathname.split('/') const pathParts = document.location.pathname.split('/')
const route = '/' + pathParts[pathParts.length - 1] const route = '/' + pathParts[pathParts.length - 1]
const queryString = toQueryString(params)
if (route.match(/html$/)) return let action
if (route.match(/html$/)) {
action = doChangePath('/discover')
} else {
action = doChangePath(`${route}?${queryString}`)
}
console.log('title should be set here, but it is not in popstate? TODO') app.store.dispatch(action)
app.store.dispatch(doChangePath(`${route}${queryString}`))
}) })
ipcRenderer.on('open-uri-requested', (event, uri) => { ipcRenderer.on('open-uri-requested', (event, uri) => {
@ -73,12 +80,16 @@ const initialState = app.store.getState();
var init = function() { var init = function() {
function onDaemonReady() { function onDaemonReady() {
app.store.dispatch(doDaemonReady())
window.sessionStorage.setItem('loaded', 'y'); //once we've made it here once per session, we don't need to show splash again window.sessionStorage.setItem('loaded', 'y'); //once we've made it here once per session, we don't need to show splash again
app.store.dispatch(doHistoryPush({}, "" + const actions = []
"Discover", "/discover"))
app.store.dispatch(doFetchDaemonSettings()) actions.push(doDaemonReady())
app.store.dispatch(doFileList()) actions.push(doChangePath('/discover'))
actions.push(doFetchDaemonSettings())
actions.push(doFileList())
app.store.dispatch(batchActions(actions))
ReactDOM.render(<Provider store={store}><div>{ lbryio.enabled ? <AuthOverlay/> : '' }<App /><SnackBar /></div></Provider>, canvas) ReactDOM.render(<Provider store={store}><div>{ lbryio.enabled ? <AuthOverlay/> : '' }<App /><SnackBar /></div></Provider>, canvas)
} }

View file

@ -34,24 +34,23 @@ class DiscoverPage extends React.Component{
fetchingFeaturedUris, fetchingFeaturedUris,
} = this.props } = this.props
let content
if (fetchingFeaturedUris) {
content = <BusyMessage message="Fetching content" />
} else {
if (typeof featuredUris === "object") {
content = Object.keys(featuredUris).map(category => {
return featuredUris[category].length ?
<FeaturedCategory key={category} category={category} names={featuredUris[category]} /> :
'';
})
} else if (featuredUris !== undefined) {
content = <div className="empty">Failed to load landing content.</div>
}
}
return ( return (
<main>{content}</main> <main>
{
fetchingFeaturedUris &&
<BusyMessage message="Fetching content" />
}
{
typeof featuredUris === "object" &&
Object.keys(featuredUris).map(category => (
featuredUris[category].length ? <FeaturedCategory key={category} category={category} names={featuredUris[category]} /> : ''
))
}
{
typeof featuredUris !== undefined &&
<div className="empty">Failed to load landing content.</div>
}
</main>
) )
} }
} }

View file

@ -93,6 +93,44 @@ reducers[types.DAEMON_READY] = function(state, action) {
}) })
} }
reducers[types.SHOW_SNACKBAR] = function(state, action) {
const {
message,
linkText,
linkTarget,
isError,
} = action.data
const snackBar = Object.assign({}, state.snackBar)
const snacks = Object.assign([], snackBar.snacks)
snacks.push({
message,
linkText,
linkTarget,
isError,
})
const newSnackBar = Object.assign({}, snackBar, {
snacks,
})
return Object.assign({}, state, {
snackBar: newSnackBar,
})
}
reducers[types.REMOVE_SNACKBAR_SNACK] = function(state, action) {
const snackBar = Object.assign({}, state.snackBar)
const snacks = Object.assign([], snackBar.snacks)
snacks.shift()
const newSnackBar = Object.assign({}, snackBar, {
snacks,
})
return Object.assign({}, state, {
snackBar: newSnackBar,
})
}
export default function reducer(state = defaultState, action) { export default function reducer(state = defaultState, action) {
const handler = reducers[action.type]; const handler = reducers[action.type];
if (handler) return handler(state, action); if (handler) return handler(state, action);

View file

@ -1,5 +1,8 @@
import lbry from './lbry.js'; import lbry from 'lbry';
import lbryio from './lbryio.js'; import lbryio from 'lbryio';
import {
doShowSnackBar,
} from 'actions/app'
function rewardMessage(type, amount) { function rewardMessage(type, amount) {
return { return {
@ -40,14 +43,13 @@ rewards.claimReward = function (type) {
}; };
// Display global notice // Display global notice
document.dispatchEvent(new CustomEvent('globalNotice', { const action = doShowSnackBar({
detail: { message,
message: message,
linkText: "Show All", linkText: "Show All",
linkTarget: "/rewards", linkTarget: "/rewards",
isError: false, isError: false,
}, })
})); window.app.store.dispatch(action)
// Add more events here to display other places // Add more events here to display other places

View file

@ -1,5 +1,7 @@
import {createSelector} from 'reselect' import {createSelector} from 'reselect'
import parseQueryParams from 'util/query_params' import {
parseQueryParams,
} from 'util/query_params'
import lbryuri from 'lbryuri' import lbryuri from 'lbryuri'
export const _selectState = state => state.app || {} export const _selectState = state => state.app || {}
@ -37,7 +39,7 @@ export const selectPageTitle = createSelector(
(page, params) => { (page, params) => {
switch (page) { switch (page) {
case 'search': case 'search':
return 'Search' return params.query ? `Search results for ${params.query}` : 'Search'
case 'settings': case 'settings':
return 'Settings' return 'Settings'
case 'help': case 'help':
@ -192,3 +194,13 @@ export const selectObscureNsfw = createSelector(
_selectState, _selectState,
(state) => !!state.obscureNsfw (state) => !!state.obscureNsfw
) )
export const selectSnackBar = createSelector(
_selectState,
(state) => state.snackBar || {}
)
export const selectSnackBarSnacks = createSelector(
selectSnackBar,
(snackBar) => snackBar.snacks || []
)

View file

@ -1,6 +1,6 @@
const redux = require('redux'); const redux = require('redux');
const thunk = require("redux-thunk").default; const thunk = require("redux-thunk").default;
const env = process.env.NODE_ENV || 'production'; const env = ENV;
import { import {
createLogger createLogger

View file

@ -1,4 +1,4 @@
function parseQueryParams(queryString) { export function parseQueryParams(queryString) {
if (queryString === '') return {}; if (queryString === '') return {};
const parts = queryString const parts = queryString
.split('?') .split('?')
@ -13,4 +13,14 @@ function parseQueryParams(queryString) {
return params; return params;
} }
export default parseQueryParams export function toQueryString(params) {
if (!params) return ""
const parts = []
for (const key in params) {
if (params.hasOwnProperty(key) && params[key]) {
parts.push(key + "=" + params[key])
}
}
return parts.join("&")
}

View file

@ -1,4 +1,5 @@
const path = require('path'); const path = require('path');
const webpack = require('webpack')
const appPath = path.resolve(__dirname, 'js'); const appPath = path.resolve(__dirname, 'js');
const PATHS = { const PATHS = {
@ -18,6 +19,11 @@ module.exports = {
root: appPath, root: appPath,
extensions: ['', '.js', '.jsx', '.css'], extensions: ['', '.js', '.jsx', '.css'],
}, },
plugins: [
new webpack.DefinePlugin({
ENV: JSON.stringify("development"),
}),
],
module: { module: {
preLoaders: [ preLoaders: [
{ {

View file

@ -1,4 +1,5 @@
const path = require('path'); const path = require('path');
const webpack = require('webpack')
const WebpackNotifierPlugin = require('webpack-notifier') const WebpackNotifierPlugin = require('webpack-notifier')
const appPath = path.resolve(__dirname, 'js'); const appPath = path.resolve(__dirname, 'js');
@ -25,6 +26,9 @@ module.exports = {
}, },
plugins: [ plugins: [
new WebpackNotifierPlugin(), new WebpackNotifierPlugin(),
new webpack.DefinePlugin({
ENV: JSON.stringify("development"),
}),
], ],
module: { module: {
preLoaders: [ preLoaders: [