code stringlengths 24 2.07M | docstring stringlengths 25 85.3k | func_name stringlengths 1 92 | language stringclasses 1
value | repo stringlengths 5 64 | path stringlengths 4 172 | url stringlengths 44 218 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
function toggleDevTools () {
if (!main.win) return
log('toggleDevTools')
if (main.win.webContents.isDevToolsOpened()) {
main.win.webContents.closeDevTools()
} else {
main.win.webContents.openDevTools({ mode: 'detach' })
}
} | Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0. | toggleDevTools | javascript | webtorrent/webtorrent-desktop | src/main/windows/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js | MIT |
function toggleFullScreen (flag) {
if (!main.win || !main.win.isVisible()) {
return
}
if (flag == null) flag = !main.win.isFullScreen()
log(`toggleFullScreen ${flag}`)
if (flag) {
// Fullscreen and aspect ratio do not play well together. (Mac)
main.win.setAspectRatio(0)
}
main.win.setFullS... | Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0. | toggleFullScreen | javascript | webtorrent/webtorrent-desktop | src/main/windows/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js | MIT |
function onWindowBlur () {
menu.setWindowFocus(false)
if (process.platform !== 'darwin') {
const tray = require('../tray')
tray.setWindowFocus(false)
}
} | Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0. | onWindowBlur | javascript | webtorrent/webtorrent-desktop | src/main/windows/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js | MIT |
function onWindowFocus () {
menu.setWindowFocus(true)
if (process.platform !== 'darwin') {
const tray = require('../tray')
tray.setWindowFocus(true)
}
} | Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0. | onWindowFocus | javascript | webtorrent/webtorrent-desktop | src/main/windows/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js | MIT |
function getIconPath () {
return process.platform === 'win32'
? config.APP_ICON + '.ico'
: config.APP_ICON + '.png'
} | Set progress bar to [0, 1]. Indeterminate when > 1. Remove with < 0. | getIconPath | javascript | webtorrent/webtorrent-desktop | src/main/windows/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/main/windows/main.js | MIT |
function onState (err, _state) {
if (err) return onError(err)
// Make available for easier debugging
state = window.state = _state
window.dispatch = dispatch
telemetry.init(state)
sound.init(state)
// Log uncaught JS errors
window.addEventListener(
'error', (e) => telemetry.logUncaughtError('wind... | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onState | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function delayedInit () {
telemetry.send(state)
// Send telemetry data every 12 hours, for users who keep the app running
// for extended periods of time
setInterval(() => telemetry.send(state), 12 * 3600 * 1000)
// Warn if the download dir is gone, eg b/c an external drive is unplugged
checkDownloadPath(... | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | delayedInit | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function lazyLoadCast () {
if (!Cast) {
Cast = require('./lib/cast')
Cast.init(state, update) // Search the local network for Chromecast and Airplays
}
return Cast
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | lazyLoadCast | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function update () {
controllers.playback().showOrHidePlayerControls()
app.setState(state)
updateElectron()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | update | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function updateElectron () {
if (state.window.title !== state.prev.title) {
state.prev.title = state.window.title
ipcRenderer.send('setTitle', state.window.title)
}
if (state.dock.progress.toFixed(2) !== state.prev.progress.toFixed(2)) {
state.prev.progress = state.dock.progress
ipcRenderer.send('... | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | updateElectron | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function dispatch (action, ...args) {
// Log dispatch calls, for debugging, but don't spam
if (!['mediaMouseMoved', 'mediaTimeUpdate', 'update'].includes(action)) {
console.log('dispatch: %s %o', action, args)
}
const handler = dispatchHandlers[action]
if (handler) handler(...args)
else console.error('... | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | dispatch | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function setupIpc () {
ipcRenderer.on('log', (e, ...args) => console.log(...args))
ipcRenderer.on('error', (e, ...args) => console.error(...args))
ipcRenderer.on('dispatch', (e, ...args) => dispatch(...args))
ipcRenderer.on('fullscreenChanged', onFullscreenChanged)
ipcRenderer.on('windowBoundsChanged', onWi... | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | setupIpc | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function backToList () {
// Exit any modals and screens with a back button
state.modal = null
state.location.backToFirst(() => {
// If we were already on the torrent list, scroll to the top
const contentTag = document.querySelector('.content')
if (contentTag) contentTag.scrollTop = 0
})
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | backToList | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function escapeBack () {
if (state.modal) {
dispatch('exitModal')
} else if (state.window.isFullScreen) {
dispatch('toggleFullScreen')
} else {
dispatch('back')
}
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | escapeBack | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function resumeTorrents () {
state.saved.torrents
.map((torrentSummary) => {
// Torrent keys are ephemeral, reassigned each time the app runs.
// On startup, give all torrents a key, even the ones that are paused.
torrentSummary.torrentKey = state.nextTorrentKey++
return torrentSummary
... | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | resumeTorrents | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function setDimensions (dimensions) {
// Don't modify the window size if it's already maximized
if (electron.remote.getCurrentWindow().isMaximized()) {
state.window.bounds = null
return
}
// Save the bounds of the window for later. See restoreBounds()
state.window.bounds = {
x: window.screenX,
... | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | setDimensions | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onOpen (files) {
if (!Array.isArray(files)) files = [files]
// File API seems to transform "magnet:?foo" in "magnet:///?foo"
// this is a sanitization
files = files.map(file => {
if (typeof file !== 'string') return file
return file.replace(/^magnet:\/+\?/i, 'magnet:?')
})
const url = sta... | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onOpen | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onError (err) {
console.error(err.stack || err)
sound.play('ERROR')
state.errors.push({
time: new Date().getTime(),
message: err.message || err
})
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onError | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onPaste (e) {
if (e && editableHtmlTags.has(e.target.tagName.toLowerCase())) return
controllers.torrentList().addTorrent(electron.clipboard.readText())
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onPaste | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onKeydown (e) {
// prevent event fire on user input elements
if (editableHtmlTags.has(e.target.tagName.toLowerCase())) return
const key = e.key
if (key === 'ArrowLeft') {
dispatch('skip', -5)
} else if (key === 'ArrowRight') {
dispatch('skip', 5)
} else if (key === 'ArrowUp') {
dispat... | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onKeydown | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onFocus (e) {
state.window.isFocused = true
state.dock.badge = 0
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onFocus | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onBlur () {
state.window.isFocused = false
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onBlur | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onVisibilityChange () {
state.window.isVisible = !document.hidden
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onVisibilityChange | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onFullscreenChanged (e, isFullScreen) {
state.window.isFullScreen = isFullScreen
if (!isFullScreen) {
// Aspect ratio gets reset in fullscreen mode, so restore it (Mac)
ipcRenderer.send('setAspectRatio', state.playing.aspectRatio)
}
update()
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onFullscreenChanged | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function onWindowBoundsChanged (e, newBounds) {
if (state.location.url() !== 'player') {
state.saved.bounds = newBounds
dispatch('stateSave')
}
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | onWindowBoundsChanged | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function checkDownloadPath () {
fs.stat(state.saved.prefs.downloadPath, (err, stat) => {
if (err) {
state.downloadPathStatus = 'missing'
return console.error(err)
}
if (stat.isDirectory()) state.downloadPathStatus = 'ok'
else state.downloadPathStatus = 'missing'
})
} | Perf optimization: Hook into require() to modify how certain modules load:
- `inline-style-prefixer` (used by `material-ui`) takes ~40ms. It is not
actually used because auto-prefixing is disabled with
`darkBaseTheme.userAgent = false`. Return a fake object. | checkDownloadPath | javascript | webtorrent/webtorrent-desktop | src/renderer/main.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/main.js | MIT |
function init () {
listenToClientEvents()
ipcRenderer.on('wt-set-global-trackers', (e, globalTrackers) =>
setGlobalTrackers(globalTrackers))
ipcRenderer.on('wt-start-torrenting', (e, torrentKey, torrentID, path, fileModtimes, selections) =>
startTorrenting(torrentKey, torrentID, path, fileModtimes, selec... | Generate an ephemeral peer ID each time. | init | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function listenToClientEvents () {
client.on('warning', (err) => ipcRenderer.send('wt-warning', null, err.message))
client.on('error', (err) => ipcRenderer.send('wt-error', null, err.message))
} | Generate an ephemeral peer ID each time. | listenToClientEvents | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function setGlobalTrackers (globalTrackers) {
globalThis.WEBTORRENT_ANNOUNCE = globalTrackers
} | Generate an ephemeral peer ID each time. | setGlobalTrackers | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function startTorrenting (torrentKey, torrentID, path, fileModtimes, selections) {
console.log('starting torrent %s: %s', torrentKey, torrentID)
const torrent = client.add(torrentID, {
path,
fileModtimes
})
torrent.key = torrentKey
// Listen for ready event, progress notifications, etc
addTorrentE... | Generate an ephemeral peer ID each time. | startTorrenting | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function stopTorrenting (infoHash) {
console.log('--- STOP TORRENTING: ', infoHash)
const torrent = client.get(infoHash)
if (torrent) torrent.destroy()
} | Generate an ephemeral peer ID each time. | stopTorrenting | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function createTorrent (torrentKey, options) {
console.log('creating torrent', torrentKey, options)
const paths = options.files.map((f) => f.path)
const torrent = client.seed(paths, options)
torrent.key = torrentKey
addTorrentEvents(torrent)
ipcRenderer.send('wt-new-torrent')
} | Generate an ephemeral peer ID each time. | createTorrent | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function addTorrentEvents (torrent) {
torrent.on('warning', (err) =>
ipcRenderer.send('wt-warning', torrent.key, err.message))
torrent.on('error', (err) =>
ipcRenderer.send('wt-error', torrent.key, err.message))
torrent.on('infoHash', () =>
ipcRenderer.send('wt-parsed', torrent.key, torrent.infoHash, ... | Generate an ephemeral peer ID each time. | addTorrentEvents | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function torrentMetadata () {
const info = getTorrentInfo(torrent)
ipcRenderer.send('wt-metadata', torrent.key, info)
updateTorrentProgress()
} | Generate an ephemeral peer ID each time. | torrentMetadata | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function torrentReady () {
const info = getTorrentInfo(torrent)
ipcRenderer.send('wt-ready', torrent.key, info)
ipcRenderer.send('wt-ready-' + torrent.infoHash, torrent.key, info)
updateTorrentProgress()
} | Generate an ephemeral peer ID each time. | torrentReady | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function torrentDone () {
const info = getTorrentInfo(torrent)
ipcRenderer.send('wt-done', torrent.key, info)
updateTorrentProgress()
torrent.getFileModtimes((err, fileModtimes) => {
if (err) return onError(err)
ipcRenderer.send('wt-file-modtimes', torrent.key, fileModtimes)
})
} | Generate an ephemeral peer ID each time. | torrentDone | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function getTorrentInfo (torrent) {
return {
infoHash: torrent.infoHash,
magnetURI: torrent.magnetURI,
name: torrent.name,
path: torrent.path,
files: torrent.files.map(getTorrentFileInfo),
bytesReceived: torrent.received
}
} | Generate an ephemeral peer ID each time. | getTorrentInfo | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function getTorrentFileInfo (file) {
return {
name: file.name,
length: file.length,
path: file.path
}
} | Generate an ephemeral peer ID each time. | getTorrentFileInfo | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function saveTorrentFile (torrentKey) {
const torrent = getTorrent(torrentKey)
const torrentPath = path.join(config.TORRENT_PATH, torrent.infoHash + '.torrent')
fs.access(torrentPath, fs.constants.R_OK, err => {
const fileName = torrent.infoHash + '.torrent'
if (!err) {
// We've already saved the f... | Generate an ephemeral peer ID each time. | saveTorrentFile | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function generateTorrentPoster (torrentKey) {
const torrent = getTorrent(torrentKey)
torrentPoster(torrent, (err, buf, extension) => {
if (err) return console.log('error generating poster: %o', err)
// save it for next time
fs.mkdir(config.POSTER_PATH, { recursive: true }, err => {
if (err) return... | Generate an ephemeral peer ID each time. | generateTorrentPoster | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function updateTorrentProgress () {
const progress = getTorrentProgress()
// TODO: diff torrent-by-torrent, not once for the whole update
if (prevProgress && util.isDeepStrictEqual(progress, prevProgress)) {
return /* don't send heavy object if it hasn't changed */
}
ipcRenderer.send('wt-progress', progre... | Generate an ephemeral peer ID each time. | updateTorrentProgress | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function getTorrentProgress () {
// First, track overall progress
const progress = client.progress
const hasActiveTorrents = client.torrents.some(torrent => torrent.progress !== 1)
// Track progress for every file in each torrent
// TODO: ideally this would be tracked by WebTorrent, which could do it
// mo... | Generate an ephemeral peer ID each time. | getTorrentProgress | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function startServer (infoHash) {
const torrent = client.get(infoHash)
if (torrent.ready) startServerFromReadyTorrent(torrent)
else torrent.once('ready', () => startServerFromReadyTorrent(torrent))
} | Generate an ephemeral peer ID each time. | startServer | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function startServerFromReadyTorrent (torrent) {
if (server) return
// start the streaming torrent-to-http server
server = torrent.createServer()
server.listen(0, () => {
const port = server.address().port
const urlSuffix = ':' + port
const info = {
torrentKey: torrent.key,
localURL: 'h... | Generate an ephemeral peer ID each time. | startServerFromReadyTorrent | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function stopServer () {
if (!server) return
server.destroy()
server = null
} | Generate an ephemeral peer ID each time. | stopServer | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function getAudioMetadata (infoHash, index) {
const torrent = client.get(infoHash)
const file = torrent.files[index]
// Set initial matadata to display the filename first.
const metadata = { title: file.name }
ipcRenderer.send('wt-audio-metadata', infoHash, index, metadata)
const options = {
native: f... | Generate an ephemeral peer ID each time. | getAudioMetadata | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function selectFiles (torrentOrInfoHash, selections) {
// Get the torrent object
let torrent
if (typeof torrentOrInfoHash === 'string') {
torrent = client.get(torrentOrInfoHash)
} else {
torrent = torrentOrInfoHash
}
if (!torrent) {
throw new Error('selectFiles: missing torrent ' + torrentOrInfo... | Generate an ephemeral peer ID each time. | selectFiles | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function getTorrent (torrentKey) {
const ret = client.torrents.find((x) => x.key === torrentKey)
if (!ret) throw new TorrentKeyNotFoundError(torrentKey)
return ret
} | Generate an ephemeral peer ID each time. | getTorrent | javascript | webtorrent/webtorrent-desktop | src/renderer/webtorrent.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/webtorrent.js | MIT |
function calculateDataLengthByExtension (torrent, extensions) {
const files = filterOnExtension(torrent, extensions)
if (files.length === 0) return 0
return files
.map(file => file.length)
.reduce((a, b) => a + b)
} | Calculate the total data size of file matching one of the provided extensions
@param torrent
@param extensions List of extension to match
@returns {number} total size, of matches found (>= 0) | calculateDataLengthByExtension | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function getLargestFileByExtension (torrent, extensions) {
const files = filterOnExtension(torrent, extensions)
if (files.length === 0) return undefined
return files.reduce((a, b) => a.length > b.length ? a : b)
} | Get the largest file of a given torrent, filtered by provided extension
@param torrent Torrent to search in
@param extensions Extension whitelist filter
@returns Torrent file object | getLargestFileByExtension | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function filterOnExtension (torrent, extensions) {
return torrent.files.filter(file => {
const extname = path.extname(file.name).toLowerCase()
return extensions.indexOf(extname) !== -1
})
} | Filter file on a list extension, can be used to find al image files
@param torrent Torrent to filter files from
@param extensions File extensions to filter on
@returns {Array} Array of torrent file objects matching one of the given extensions | filterOnExtension | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function scoreAudioCoverFile (imgFile) {
const fileName = path.basename(imgFile.name, path.extname(imgFile.name)).toLowerCase()
const relevanceScore = {
cover: 80,
folder: 80,
album: 80,
front: 80,
back: 20,
spectrogram: -80
}
for (const keyword in relevanceScore) {
if (fileName ===... | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | scoreAudioCoverFile | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function torrentPosterFromAudio (torrent, cb) {
const imageFiles = filterOnExtension(torrent, mediaExtensions.image)
if (imageFiles.length === 0) return cb(new Error(msgNoSuitablePoster))
const bestCover = imageFiles.map(file => ({
file,
score: scoreAudioCoverFile(file)
})).reduce((a, b) => {
if (... | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | torrentPosterFromAudio | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function torrentPosterFromVideo (torrent, cb) {
const file = getLargestFileByExtension(torrent, mediaExtensions.video)
const index = torrent.files.indexOf(file)
const server = torrent.createServer(0)
server.listen(0, onListening)
function onListening () {
const port = server.address().port
const ur... | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | torrentPosterFromVideo | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function onListening () {
const port = server.address().port
const url = 'http://localhost:' + port + '/' + index
const video = document.createElement('video')
video.addEventListener('canplay', onCanPlay)
video.volume = 0
video.src = url
video.play()
function onCanPlay () {
video... | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | onListening | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function onCanPlay () {
video.removeEventListener('canplay', onCanPlay)
video.addEventListener('seeked', onSeeked)
video.currentTime = Math.min((video.duration || 600) * 0.03, 60)
} | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | onCanPlay | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function onSeeked () {
video.removeEventListener('seeked', onSeeked)
const frame = captureFrame(video)
const buf = frame && frame.image
// unload video element
video.pause()
video.src = ''
video.load()
server.destroy()
if (buf.length === 0) return cb(new Error(m... | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | onSeeked | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function torrentPosterFromImage (torrent, cb) {
const file = getLargestFileByExtension(torrent, mediaExtensions.image)
extractPoster(file, cb)
} | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | torrentPosterFromImage | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function extractPoster (file, cb) {
const extname = path.extname(file.name)
file.getBuffer((err, buf) => cb(err, buf, extname))
} | Returns a score how likely the file is suitable as a poster
@param imgFile File object of an image
@returns {number} Score, higher score is a better match | extractPoster | javascript | webtorrent/webtorrent-desktop | src/renderer/lib/torrent-poster.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/lib/torrent-poster.js | MIT |
function renderTrack (common, key) {
// Audio metadata: track-number
if (common[key] && common[key].no) {
let str = `${common[key].no}`
if (common[key].of) {
str += ` of ${common[key].of}`
}
const style = { textTransform: 'capitalize' }
return (
<div className={`audio-${key}`}>
... | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderTrack | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderAudioMetadata (state) {
const fileSummary = state.getPlayingFileSummary()
if (!fileSummary.audioInfo) return
const common = fileSummary.audioInfo.common || {}
// Get audio track info
const title = common.title ? common.title : fileSummary.name
// Show a small info box in the middle of the s... | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderAudioMetadata | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderEta (total, downloaded) {
const missing = (total || 0) - (downloaded || 0)
const downloadSpeed = prog.downloadSpeed || 0
if (downloadSpeed === 0 || missing === 0) return
const etaStr = calculateEta(missing, downloadSpeed)
return (<span>{etaStr}</span>)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderEta | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderCastOptions (state) {
if (!state.devices.castMenu) return
const { location, devices } = state.devices.castMenu
const player = state.devices[location]
const items = devices.map((device, ix) => {
const isSelected = player.device === device
const name = device.name
return (
<li k... | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderCastOptions | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderSubtitleOptions (state) {
const subtitles = state.playing.subtitles
if (!subtitles.tracks.length || !subtitles.showMenu) return
const items = subtitles.tracks.map((track, ix) => {
const isSelected = state.playing.subtitles.selectedIndex === ix
return (
<li key={ix} onClick={dispatche... | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderSubtitleOptions | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderAudioTrackOptions (state) {
const audioTracks = state.playing.audioTracks
if (!audioTracks.tracks.length || !audioTracks.showMenu) return
const items = audioTracks.tracks.map((track, ix) => {
const isSelected = state.playing.audioTracks.selectedIndex === ix
return (
<li key={ix} onCl... | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderAudioTrackOptions | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderPlayerControls (state) {
const positionPercent = 100 * state.playing.currentTime / state.playing.duration
const playbackCursorStyle = { left: 'calc(' + positionPercent + '% - 3px)' }
const captionsClass = state.playing.subtitles.tracks.length === 0
? 'disabled'
: state.playing.subtitles.sel... | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderPlayerControls | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleDragStart (e) {
if (e.dataTransfer) {
const dt = e.dataTransfer
// Prevent the cursor from changing, eg to a green + icon on Mac
dt.effectAllowed = 'none'
// Prevent ghost image
dt.setDragImage(emptyImage, 0, 0)
}
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleDragStart | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleScrubPreview (e) {
// Only show for videos
if (!e.clientX || state.playing.type !== 'video') return
dispatch('mediaMouseMoved')
dispatch('preview', e.clientX)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleScrubPreview | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function clearPreview () {
if (state.playing.type !== 'video') return
dispatch('clearPreview')
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | clearPreview | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleScrub (e) {
if (!e.clientX) return
dispatch('mediaMouseMoved')
const windowWidth = document.querySelector('body').clientWidth
const fraction = e.clientX / windowWidth
const position = fraction * state.playing.duration /* seconds */
dispatch('skipTo', position)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleScrub | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleVolumeMute () {
if (state.playing.volume === 0.0) {
dispatch('setVolume', 1.0)
} else {
dispatch('setVolume', 0.0)
}
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleVolumeMute | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleVolumeScrub (e) {
dispatch('setVolume', e.target.value)
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleVolumeScrub | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function handleSubtitles (e) {
if (!state.playing.subtitles.tracks.length || e.ctrlKey || e.metaKey) {
// if no subtitles available select it
dispatch('openSubtitles')
} else {
dispatch('toggleSubtitlesMenu')
}
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | handleSubtitles | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderPreview (state) {
const { previewXCoord = null } = state.playing
// Calculate time from x-coord as fraction of track width
const windowWidth = document.querySelector('body').clientWidth
const fraction = previewXCoord / windowWidth
const time = fraction * state.playing.duration /* seconds */
... | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderPreview | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function renderLoadingBar (state) {
if (config.IS_TEST) return // Don't integration test the loading bar. Screenshots won't match.
const torrentSummary = state.getPlayingTorrentSummary()
if (!torrentSummary.progress) {
return null
}
// Find all contiguous parts of the torrent which are loaded
const pr... | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | renderLoadingBar | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function cssBackgroundImagePoster (state) {
const torrentSummary = state.getPlayingTorrentSummary()
const posterPath = TorrentSummary.getPosterPath(torrentSummary)
if (!posterPath) return ''
return cssBackgroundImageDarkGradient() + `, url('${posterPath}')`
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | cssBackgroundImagePoster | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function cssBackgroundImageDarkGradient () {
return 'radial-gradient(circle at center, ' +
'rgba(0,0,0,0.4) 0%, rgba(0,0,0,1) 100%)'
} | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | cssBackgroundImageDarkGradient | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
function formatTime (time, total) {
if (typeof time !== 'number' || Number.isNaN(time)) {
return '0:00'
}
const totalHours = Math.floor(total / 3600)
const totalMinutes = Math.floor(total / 60)
const hours = Math.floor(time / 3600)
let minutes = Math.floor(time % 3600 / 60)
if (totalMinutes > 9 && mi... | Render track or disk number string
@param common metadata.common part
@param key should be either 'track' or 'disk'
@return track or disk number metadata as JSX block | formatTime | javascript | webtorrent/webtorrent-desktop | src/renderer/pages/player-page.js | https://github.com/webtorrent/webtorrent-desktop/blob/master/src/renderer/pages/player-page.js | MIT |
constructor(name, description) {
this.description = description || '';
this.variadic = false;
this.parseArg = undefined;
this.defaultValue = undefined;
this.defaultValueDescription = undefined;
this.argChoices = undefined;
switch (name[0]) {
case '<': // e.g. <required>
this.r... | Initialize a new command argument with the given name and description.
The default is that the argument is required, and you can explicitly
indicate this with <> around the name. Put [] around the name for an optional argument.
@param {string} name
@param {string} [description] | constructor | javascript | tj/commander.js | lib/argument.js | https://github.com/tj/commander.js/blob/master/lib/argument.js | MIT |
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
} | Set the default value, and optionally supply the description to be displayed in the help.
@param {*} value
@param {string} [description]
@return {Argument} | default | javascript | tj/commander.js | lib/argument.js | https://github.com/tj/commander.js/blob/master/lib/argument.js | MIT |
argParser(fn) {
this.parseArg = fn;
return this;
} | Set the custom handler for processing CLI command arguments into argument values.
@param {Function} [fn]
@return {Argument} | argParser | javascript | tj/commander.js | lib/argument.js | https://github.com/tj/commander.js/blob/master/lib/argument.js | MIT |
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError(
`Allowed choices are ${this.argChoices.join(', ')}.`,
);
}
if (this.variadic) {
return this._concatVa... | Only allow argument value to be one of choices.
@param {string[]} values
@return {Argument} | choices | javascript | tj/commander.js | lib/argument.js | https://github.com/tj/commander.js/blob/master/lib/argument.js | MIT |
function humanReadableArgName(arg) {
const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
} | Takes an argument and returns its human readable equivalent for help usage.
@param {Argument} arg
@return {string}
@private | humanReadableArgName | javascript | tj/commander.js | lib/argument.js | https://github.com/tj/commander.js/blob/master/lib/argument.js | MIT |
constructor(name) {
super();
/** @type {Command[]} */
this.commands = [];
/** @type {Option[]} */
this.options = [];
this.parent = null;
this._allowUnknownOption = false;
this._allowExcessArguments = false;
/** @type {Argument[]} */
this.registeredArguments = [];
this._args =... | Initialize a new `Command`.
@param {string} [name] | constructor | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
copyInheritedSettings(sourceCommand) {
this._outputConfiguration = sourceCommand._outputConfiguration;
this._helpOption = sourceCommand._helpOption;
this._helpCommand = sourceCommand._helpCommand;
this._helpConfiguration = sourceCommand._helpConfiguration;
this._exitCallback = sourceCommand._exitCal... | Copy settings that are useful to have in common across root command and subcommands.
(Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
@param {Command} sourceCommand
@return {Command} `this` command for chaining | copyInheritedSettings | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
let desc = actionOptsOrExecDesc;
let opts = execOpts;
if (typeof desc === 'object' && desc !== null) {
opts = desc;
desc = null;
}
opts = opts || {};
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
const cmd = thi... | Define a command.
There are two styles of command: pay attention to where to put the description.
@example
// Command implemented using action handler (description is supplied separately to `.command`)
program
.command('clone <source> [destination]')
.description('clone a repository into a newly created directory... | command | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
createCommand(name) {
return new Command(name);
} | Factory routine to create a new unattached command.
See .command() for creating an attached subcommand, which uses this routine to
create the command. You can override createCommand to customise subcommands.
@param {string} [name]
@return {Command} new command | createCommand | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
createHelp() {
return Object.assign(new Help(), this.configureHelp());
} | You can customise the help with a subclass of Help by overriding createHelp,
or by overriding Help properties using configureHelp().
@return {Help} | createHelp | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
configureHelp(configuration) {
if (configuration === undefined) return this._helpConfiguration;
this._helpConfiguration = configuration;
return this;
} | You can customise the help by overriding Help properties using configureHelp(),
or with a subclass of Help by overriding createHelp().
@param {object} [configuration] - configuration options
@return {(Command | object)} `this` command for chaining, or stored configuration | configureHelp | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
configureOutput(configuration) {
if (configuration === undefined) return this._outputConfiguration;
this._outputConfiguration = Object.assign(
{},
this._outputConfiguration,
configuration,
);
return this;
} | The default output goes to stdout and stderr. You can customise this for special
applications. You can also customise the display of errors by overriding outputError.
The configuration properties are all functions:
// change how output being written, defaults to stdout and stderr
writeOut(str)
writeErr(st... | configureOutput | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
showHelpAfterError(displayHelp = true) {
if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
this._showHelpAfterError = displayHelp;
return this;
} | Display the help or a custom message after an error occurs.
@param {(boolean|string)} [displayHelp]
@return {Command} `this` command for chaining | showHelpAfterError | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
showSuggestionAfterError(displaySuggestion = true) {
this._showSuggestionAfterError = !!displaySuggestion;
return this;
} | Display suggestion of similar commands for unknown commands, or options for unknown options.
@param {boolean} [displaySuggestion]
@return {Command} `this` command for chaining | showSuggestionAfterError | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
addCommand(cmd, opts) {
if (!cmd._name) {
throw new Error(`Command passed to .addCommand() must have a name
- specify the name in Command constructor or using .name()`);
}
opts = opts || {};
if (opts.isDefault) this._defaultCommandName = cmd._name;
if (opts.noHelp || opts.hidden) cmd._hidden ... | Add a prepared subcommand.
See .command() for creating an attached subcommand which inherits settings from its parent.
@param {Command} cmd - new subcommand
@param {object} [opts] - configuration options
@return {Command} `this` command for chaining | addCommand | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
createArgument(name, description) {
return new Argument(name, description);
} | Factory routine to create a new unattached argument.
See .argument() for creating an attached argument, which uses this routine to
create the argument. You can override createArgument to return a custom argument.
@param {string} name
@param {string} [description]
@return {Argument} new argument | createArgument | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
argument(name, description, parseArg, defaultValue) {
const argument = this.createArgument(name, description);
if (typeof parseArg === 'function') {
argument.default(defaultValue).argParser(parseArg);
} else {
argument.default(parseArg);
}
this.addArgument(argument);
return this;
} | Define argument syntax for command.
The default is that the argument is required, and you can explicitly
indicate this with <> around the name. Put [] around the name for an optional argument.
@example
program.argument('<input-file>');
program.argument('[output-file]');
@param {string} name
@param {string} [descript... | argument | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
arguments(names) {
names
.trim()
.split(/ +/)
.forEach((detail) => {
this.argument(detail);
});
return this;
} | Define argument syntax for command, adding multiple at once (without descriptions).
See also .argument().
@example
program.arguments('<cmd> [env]');
@param {string} names
@return {Command} `this` command for chaining | arguments | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
addArgument(argument) {
const previousArgument = this.registeredArguments.slice(-1)[0];
if (previousArgument && previousArgument.variadic) {
throw new Error(
`only the last argument can be variadic '${previousArgument.name()}'`,
);
}
if (
argument.required &&
argument.def... | Define argument syntax for command, adding a prepared argument.
@param {Argument} argument
@return {Command} `this` command for chaining | addArgument | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
helpCommand(enableOrNameAndArgs, description) {
if (typeof enableOrNameAndArgs === 'boolean') {
this._addImplicitHelpCommand = enableOrNameAndArgs;
if (enableOrNameAndArgs && this._defaultCommandGroup) {
// make the command to store the group
this._initCommandGroup(this._getHelpCommand()... | Customise or override default help command. By default a help command is automatically added if your command has subcommands.
@example
program.helpCommand('help [cmd]');
program.helpCommand('help [cmd]', 'show help');
program.helpCommand(false); // suppress default help command
program.helpCommand(true); /... | helpCommand | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
addHelpCommand(helpCommand, deprecatedDescription) {
// If not passed an object, call through to helpCommand for backwards compatibility,
// as addHelpCommand was originally used like helpCommand is now.
if (typeof helpCommand !== 'object') {
this.helpCommand(helpCommand, deprecatedDescription);
... | Add prepared custom help command.
@param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
@param {string} [deprecatedDescription] - deprecated custom description used with custom name only
@return {Command} `this` command for chaining | addHelpCommand | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
_getHelpCommand() {
const hasImplicitHelpCommand =
this._addImplicitHelpCommand ??
(this.commands.length &&
!this._actionHandler &&
!this._findCommand('help'));
if (hasImplicitHelpCommand) {
if (this._helpCommand === undefined) {
this.helpCommand(undefined, undefined);... | Lazy create help command.
@return {(Command|null)}
@package | _getHelpCommand | javascript | tj/commander.js | lib/command.js | https://github.com/tj/commander.js/blob/master/lib/command.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.