Memoize event handlers

Stop virtualdom from swapping out every event handler on every update
This commit is contained in:
DC
2016-03-27 00:55:42 -07:00
parent 8313855ea4
commit 5ae6d43e39
6 changed files with 125 additions and 94 deletions

View File

@@ -23,6 +23,8 @@ var config = require('../config')
var TorrentPlayer = require('./lib/torrent-player')
var torrentPoster = require('./lib/torrent-poster')
var util = require('./util')
var {setDispatch} = require('./lib/dispatcher')
setDispatch(dispatch)
// These two dependencies are the slowest-loading, so we lazy load them
// This cuts time from icon click to rendered window from ~550ms to ~150ms on my laptop
@@ -170,7 +172,7 @@ function initWebtorrent () {
// This is the (mostly) pure function from state -> UI. Returns a virtual DOM
// tree. Any events, such as button clicks, will turn into calls to dispatch()
function render (state) {
return App(state, dispatch)
return App(state)
}
// Calls render() to go from state -> UI, then applies to vdom to the real DOM.
@@ -216,32 +218,23 @@ function dispatch (action, ...args) {
if (action === 'seed') {
seed(args[0] /* files */)
}
if (action === 'play') {
state.location.go({
url: 'player',
onbeforeload: function (cb) {
openPlayer(args[0] /* torrentSummary */, args[1] /* index */, cb)
},
onbeforeunload: closePlayer
})
}
if (action === 'openFile') {
openFile(args[0] /* torrentSummary */, args[1] /* index */)
openFile(args[0] /* infoHash */, args[1] /* index */)
}
if (action === 'openFolder') {
openFolder(args[0] /* torrentSummary */)
openFolder(args[0] /* infoHash */)
}
if (action === 'toggleTorrent') {
toggleTorrent(args[0] /* torrentSummary */)
toggleTorrent(args[0] /* infoHash */)
}
if (action === 'deleteTorrent') {
deleteTorrent(args[0] /* torrentSummary */)
deleteTorrent(args[0] /* infoHash */)
}
if (action === 'toggleSelectTorrent') {
toggleSelectTorrent(args[0] /* infoHash */)
}
if (action === 'openTorrentContextMenu') {
openTorrentContextMenu(args[0] /* torrentSummary */)
openTorrentContextMenu(args[0] /* infoHash */)
}
if (action === 'openChromecast') {
lazyLoadCast().openChromecast()
@@ -265,6 +258,13 @@ function dispatch (action, ...args) {
playPause()
}
if (action === 'play') {
state.location.go({
url: 'player',
onbeforeload: function (cb) {
openPlayer(args[0] /* infoHash */, args[1] /* index */, cb)
},
onbeforeunload: closePlayer
})
playPause(false)
}
if (action === 'pause') {
@@ -285,7 +285,7 @@ function dispatch (action, ...args) {
ipcRenderer.send('unblockPowerSave')
}
if (action === 'toggleFullScreen') {
ipcRenderer.send('toggleFullScreen', args[0])
ipcRenderer.send('toggleFullScreen', args[0] /* optional bool */)
}
if (action === 'mediaMouseMoved') {
state.playing.mouseStationarySince = new Date().getTime()
@@ -739,8 +739,9 @@ function stopServer () {
}
// Opens the video player
function openPlayer (torrentSummary, index, cb) {
var torrent = lazyLoadClient().get(torrentSummary.infoHash)
function openPlayer (infoHash, index, cb) {
var torrentSummary = getTorrentSummary(infoHash)
var torrent = lazyLoadClient().get(infoHash)
if (!torrent || !torrent.done) playInterfaceSound('PLAY')
torrentSummary.playStatus = 'requested'
update()
@@ -792,16 +793,16 @@ function closePlayer (cb) {
cb()
}
function openFile (torrentSummary, index) {
var torrent = lazyLoadClient().get(torrentSummary.infoHash)
function openFile (infoHash, index) {
var torrent = lazyLoadClient().get(infoHash)
if (!torrent) return
var filePath = path.join(torrent.path, torrent.files[index].path)
ipcRenderer.send('openItem', filePath)
}
function openFolder (torrentSummary) {
var torrent = lazyLoadClient().get(torrentSummary.infoHash)
function openFolder (infoHash) {
var torrent = lazyLoadClient().get(infoHash)
if (!torrent) return
var folderPath = path.join(torrent.path, torrent.name)
@@ -815,7 +816,8 @@ function openFolder (torrentSummary) {
})
}
function toggleTorrent (torrentSummary) {
function toggleTorrent (infoHash) {
var torrentSummary = getTorrentSummary(infoHash)
if (torrentSummary.status === 'paused') {
torrentSummary.status = 'new'
startTorrentingSummary(torrentSummary)
@@ -827,8 +829,7 @@ function toggleTorrent (torrentSummary) {
}
}
function deleteTorrent (torrentSummary) {
var infoHash = torrentSummary.infoHash
function deleteTorrent (infoHash) {
var torrent = getTorrent(infoHash)
if (torrent) torrent.destroy()
@@ -845,7 +846,8 @@ function toggleSelectTorrent (infoHash) {
update()
}
function openTorrentContextMenu (torrentSummary) {
function openTorrentContextMenu (infoHash) {
var torrentSummary = getTorrentSummary(infoHash)
var menu = new remote.Menu()
menu.append(new remote.MenuItem({
label: 'Save Torrent File As...',

View File

@@ -0,0 +1,36 @@
module.exports = {
setDispatch,
dispatch,
dispatcher
}
// _memoize most of our event handlers, which are functions in the form
// () => dispatch(<args>)
// ... this prevents virtual-dom from updating tons of listeners on every update()
var _dispatchers = {}
var _dispatch = () => {}
function setDispatch (dispatch) {
_dispatch = dispatch
}
// Get a _memoized event handler that calls dispatch()
// All args must be JSON-able
function dispatcher (...args) {
var json = JSON.stringify(args)
var handler = _dispatchers[json]
if (!handler) {
_dispatchers[json] = (e) => {
// Don't click on whatever is below the button
e.stopPropagation()
// Don't regisiter clicks on disabled buttons
if (e.target.classList.contains('disabled')) return
_dispatch.apply(null, args)
}
}
return handler
}
function dispatch (...args) {
_dispatch.apply(null, args)
}

View File

@@ -4,7 +4,9 @@ var h = require('virtual-dom/h')
var hyperx = require('hyperx')
var hx = hyperx(h)
function Header (state, dispatch) {
var {dispatcher} = require('../lib/dispatcher')
function Header (state) {
return hx`
<div class='header'>
${getTitle()}
@@ -12,13 +14,13 @@ function Header (state, dispatch) {
<i.icon.back
class=${state.location.hasBack() ? '' : 'disabled'}
title='Back'
onclick=${() => dispatch('back')}>
onclick=${dispatcher('back')}>
chevron_left
</i>
<i.icon.forward
class=${state.location.hasForward() ? '' : 'disabled'}
title='Forward'
onclick=${() => dispatch('forward')}>
onclick=${dispatcher('forward')}>
chevron_right
</i>
</div>
@@ -40,7 +42,7 @@ function Header (state, dispatch) {
<i
class='icon add'
title='Add torrent'
onclick=${() => dispatch('showOpenTorrentFile')}>
onclick=${dispatcher('showOpenTorrentFile')}>
add
</i>
`

View File

@@ -4,7 +4,9 @@ var h = require('virtual-dom/h')
var hyperx = require('hyperx')
var hx = hyperx(h)
function OpenTorrentAddressModal (state, dispatch) {
var {dispatch} = require('../lib/dispatcher')
function OpenTorrentAddressModal (state) {
return hx`
<div class='open-torrent-address-modal'>
<p><strong>Enter torrent address or magnet link</strong></p>
@@ -15,17 +17,17 @@ function OpenTorrentAddressModal (state, dispatch) {
</p>
</div>
`
function handleKeyPress (e) {
if (e.which === 13) handleOK() /* hit Enter to submit */
}
function handleOK () {
dispatch('exitModal')
dispatch('addTorrent', document.querySelector('#add-torrent-url').value)
}
function handleCancel () {
dispatch('exitModal')
}
}
function handleKeyPress (e) {
if (e.which === 13) handleOK() /* hit Enter to submit */
}
function handleOK () {
dispatch('exitModal')
dispatch('addTorrent', document.querySelector('#add-torrent-url').value)
}
function handleCancel () {
dispatch('exitModal')
}

View File

@@ -5,23 +5,24 @@ var hyperx = require('hyperx')
var hx = hyperx(h)
var util = require('../util')
var {dispatch, dispatcher} = require('../lib/dispatcher')
// Shows a streaming video player. Standard features + Chromecast + Airplay
function Player (state, dispatch) {
function Player (state) {
// Show the video as large as will fit in the window, play immediately
// If the video is on Chromecast or Airplay, show a title screen instead
var showVideo = state.playing.location === 'local'
return hx`
<div
class='player'
onmousemove=${() => dispatch('mediaMouseMoved')}>
${showVideo ? renderMedia(state, dispatch) : renderCastScreen(state, dispatch)}
${renderPlayerControls(state, dispatch)}
onmousemove=${dispatcher('mediaMouseMoved')}>
${showVideo ? renderMedia(state) : renderCastScreen(state)}
${renderPlayerControls(state)}
</div>
`
}
function renderMedia (state, dispatch) {
function renderMedia (state) {
if (!state.server) return
// Unfortunately, play/pause can't be done just by modifying HTML.
@@ -54,11 +55,11 @@ function renderMedia (state, dispatch) {
var mediaTag = hx`
<div
src='${state.server.localURL}'
ondblclick=${() => dispatch('toggleFullScreen')}
ondblclick=${dispatcher('toggleFullScreen')}
onloadedmetadata=${onLoadedMetadata}
onended=${onEnded}
onplay=${() => dispatch('mediaPlaying')}
onpause=${() => dispatch('mediaPaused')}
onplay=${dispatcher('mediaPlaying')}
onpause=${dispatcher('mediaPaused')}
autoplay>
</div>
`
@@ -75,7 +76,7 @@ function renderMedia (state, dispatch) {
<div
class='letterbox'
style=${style}
onmousemove=${() => dispatch('mediaMouseMoved')}>
onmousemove=${dispatcher('mediaMouseMoved')}>
${mediaTag}
${renderAudioMetadata(state)}
</div>
@@ -126,7 +127,7 @@ function renderAudioMetadata (state) {
return hx`<div class='audio-metadata'>${elems}</div>`
}
function renderCastScreen (state, dispatch) {
function renderCastScreen (state) {
var isChromecast = state.playing.location.startsWith('chromecast')
var isAirplay = state.playing.location.startsWith('airplay')
var isStarting = state.playing.location.endsWith('-pending')
@@ -166,7 +167,7 @@ function getPlayingTorrentSummary (state) {
return state.saved.torrents.find((x) => x.infoHash === infoHash)
}
function renderPlayerControls (state, dispatch) {
function renderPlayerControls (state) {
var positionPercent = 100 * state.playing.currentTime / state.playing.duration
var playbackCursorStyle = { left: 'calc(' + positionPercent + '% - 8px)' }
@@ -183,7 +184,7 @@ function renderPlayerControls (state, dispatch) {
`,
hx`
<i class='icon fullscreen'
onclick=${() => dispatch('toggleFullScreen')}>
onclick=${dispatcher('toggleFullScreen')}>
${state.window.isFullScreen ? 'fullscreen_exit' : 'fullscreen'}
</i>
`
@@ -196,18 +197,18 @@ function renderPlayerControls (state, dispatch) {
if (isOnChromecast) {
chromecastClass = 'active'
airplayClass = 'disabled'
chromecastHandler = () => dispatch('stopCasting')
chromecastHandler = dispatcher('stopCasting')
airplayHandler = undefined
} else if (isOnAirplay) {
chromecastClass = 'disabled'
airplayClass = 'active'
chromecastHandler = undefined
airplayHandler = () => dispatch('stopCasting')
airplayHandler = dispatcher('stopCasting')
} else {
chromecastClass = ''
airplayClass = ''
chromecastHandler = () => dispatch('openChromecast')
airplayHandler = () => dispatch('openAirplay')
chromecastHandler = dispatcher('openChromecast')
airplayHandler = dispatcher('openAirplay')
}
if (state.devices.chromecast || isOnChromecast) {
elements.push(hx`
@@ -233,7 +234,7 @@ function renderPlayerControls (state, dispatch) {
if (process.platform !== 'darwin') {
elements.push(hx`
<i.icon.back
onclick=${() => dispatch('back')}>
onclick=${dispatcher('back')}>
chevron_left
</i>
`)
@@ -241,7 +242,7 @@ function renderPlayerControls (state, dispatch) {
// Finally, the big button in the center plays or pauses the video
elements.push(hx`
<i class='icon play-pause' onclick=${() => dispatch('playPause')}>
<i class='icon play-pause' onclick=${dispatcher('playPause')}>
${state.playing.isPaused ? 'play_arrow' : 'pause'}
</i>
`)

View File

@@ -8,8 +8,9 @@ var prettyBytes = require('prettier-bytes')
var util = require('../util')
var TorrentPlayer = require('../lib/torrent-player')
var {dispatcher} = require('../lib/dispatcher')
function TorrentList (state, dispatch) {
function TorrentList (state) {
var torrentRows = state.saved.torrents.map(
(torrentSummary) => renderTorrent(torrentSummary))
return hx`
@@ -53,8 +54,8 @@ function TorrentList (state, dispatch) {
classes = classes.join(' ')
return hx`
<div style=${style} class=${classes}
oncontextmenu=${() => dispatch('openTorrentContextMenu', torrentSummary)}
onclick=${() => dispatch('toggleSelectTorrent', infoHash)}>
oncontextmenu=${dispatcher('openTorrentContextMenu', infoHash)}
onclick=${dispatcher('toggleSelectTorrent', infoHash)}>
${renderTorrentMetadata(torrent, torrentSummary)}
${renderTorrentButtons(torrentSummary)}
${isSelected ? renderTorrentDetails(torrent, torrentSummary) : ''}
@@ -110,6 +111,8 @@ function TorrentList (state, dispatch) {
// Download button toggles between torrenting (DL/seed) and paused
// Play button starts streaming the torrent immediately, unpausing if needed
function renderTorrentButtons (torrentSummary) {
var infoHash = torrentSummary.infoHash
var playIcon, playTooltip, playClass
if (torrentSummary.playStatus === 'unplayable') {
playIcon = 'play_arrow'
@@ -141,34 +144,28 @@ function TorrentList (state, dispatch) {
<i.btn.icon.play
title=${playTooltip}
class=${playClass}
onclick=${(e) => handleButton('play', e)}>
onclick=${dispatcher('play', infoHash)}>
${playIcon}
</i>
<i.btn.icon.download
class=${torrentSummary.status}
title=${downloadTooltip}
onclick=${(e) => handleButton('toggleTorrent', e)}>
onclick=${dispatcher('toggleTorrent', infoHash)}>
${downloadIcon}
</i>
<i
class='icon delete'
title='Remove torrent'
onclick=${(e) => handleButton('deleteTorrent', e)}>
onclick=${dispatcher('deleteTorrent', infoHash)}>
close
</i>
</div>
`
function handleButton (action, e) {
// Prevent propagation so that we don't select/unselect the torrent
e.stopPropagation()
if (e.target.classList.contains('disabled')) return
dispatch(action, torrentSummary)
}
}
// Show files, per-file download status and play buttons, and so on
function renderTorrentDetails (torrent, torrentSummary) {
var infoHash = torrentSummary.infoHash
var filesElement
if (!torrentSummary.files) {
// We don't know what files this torrent contains
@@ -183,7 +180,10 @@ function TorrentList (state, dispatch) {
filesElement = hx`
<div class='files'>
<strong>Files</strong>
<span class='open-folder' onclick=${handleOpenFolder}>Open folder</span>
<span class='open-folder'
onclick=${dispatcher('openFolder', infoHash)}>
Open folder
</span>
<table>
${fileRows}
</table>
@@ -196,11 +196,6 @@ function TorrentList (state, dispatch) {
${filesElement}
</div>
`
function handleOpenFolder (e) {
e.stopPropagation()
dispatch('openFolder', torrentSummary)
}
}
// Show a single torrentSummary file in the details view for a single torrent
@@ -210,15 +205,20 @@ function TorrentList (state, dispatch) {
var progress = Math.round(100 * file.numPiecesPresent / (file.numPieces || 0)) + '%'
// Second, render the file as a table row
var infoHash = torrentSummary.infoHash
var icon
var rowClass = ''
if (state.playing.infoHash === torrentSummary.infoHash && state.playing.fileIndex === index) {
var handleClick
if (state.playing.infoHash === infoHash && state.playing.fileIndex === index) {
icon = 'pause_arrow' /* playing? add option to pause */
handleClick = undefined // TODO: pause audio
} else if (TorrentPlayer.isPlayable(file)) {
icon = 'play_arrow' /* playable? add option to play */
handleClick = dispatcher('play', infoHash, index)
} else {
icon = 'description' /* file icon, opens in OS default app */
rowClass = isDone ? '' : 'disabled'
handleClick = dispatcher('openFile', infoHash, index)
}
return hx`
<tr onclick=${handleClick} class='${rowClass}'>
@@ -230,17 +230,5 @@ function TorrentList (state, dispatch) {
<td class='col-size'>${prettyBytes(file.length)}</td>
</tr>
`
// Finally, let the user click on the row to play media or open files
function handleClick (e) {
e.stopPropagation()
if (icon === 'pause_arrow') {
throw new Error('Unimplemented') // TODO: pause audio
} else if (icon === 'play_arrow') {
dispatch('play', torrentSummary, index)
} else if (isDone) {
dispatch('openFile', torrentSummary, index)
}
}
}
}