Added eslint. To lint, npm run lint.

Linted the entire project. Using different rules for the script files
as there are a lot of undefined variables just because of the way the
DOM's global scope works.

Mostly just code cleanup, however the linter did catch a minor bug with
a settings regex. That has been corrected.
This commit is contained in:
Daniel Scalzi 2018-07-22 13:31:15 -04:00
parent ededf85892
commit 810e81521c
No known key found for this signature in database
GPG Key ID: 5CA2F145B63535F9
18 changed files with 1205 additions and 261 deletions

50
.eslintrc.json Normal file
View File

@ -0,0 +1,50 @@
{
"env": {
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 2017,
"sourceType": "module"
},
"rules": {
"indent": [
"error",
4,
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"windows"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"never"
],
"no-var": [
"error"
],
"no-console": [
0
],
"no-control-regex": [
0
],
"no-unused-vars": [
"error",
{
"vars": "all",
"args": "none",
"ignoreRestSiblings": false,
"argsIgnorePattern": "reject"
}
]
}
}

47
.eslintrc.scripts.json Normal file
View File

@ -0,0 +1,47 @@
{
"env": {
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 2017,
"sourceType": "module"
},
"rules": {
"indent": [
"error",
4,
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"windows"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"never"
],
"no-var": [
"error"
],
"no-console": [
0
],
"no-control-regex": [
0
],
"no-unused-vars": [
0
],
"no-undef": [
0
]
}
}

View File

@ -22,7 +22,7 @@ const crypto = require('crypto')
const EventEmitter = require('events') const EventEmitter = require('events')
const fs = require('fs') const fs = require('fs')
const isDev = require('electron-is-dev') const isDev = require('electron-is-dev')
const mkpath = require('mkdirp'); const mkpath = require('mkdirp')
const path = require('path') const path = require('path')
const Registry = require('winreg') const Registry = require('winreg')
const request = require('request') const request = require('request')
@ -70,13 +70,13 @@ class Library extends Asset {
static mojangFriendlyOS(){ static mojangFriendlyOS(){
const opSys = process.platform const opSys = process.platform
if (opSys === 'darwin') { if (opSys === 'darwin') {
return 'osx'; return 'osx'
} else if (opSys === 'win32'){ } else if (opSys === 'win32'){
return 'windows'; return 'windows'
} else if (opSys === 'linux'){ } else if (opSys === 'linux'){
return 'linux'; return 'linux'
} else { } else {
return 'unknown_os'; return 'unknown_os'
} }
} }
@ -241,12 +241,11 @@ class AssetGuard extends EventEmitter {
if(hash == null){ if(hash == null){
return true return true
} }
let fileName = path.basename(filePath)
let buf = fs.readFileSync(filePath) let buf = fs.readFileSync(filePath)
let calcdhash = AssetGuard._calculateHash(buf, algo) let calcdhash = AssetGuard._calculateHash(buf, algo)
return calcdhash === hash return calcdhash === hash
} }
return false; return false
} }
/** /**
@ -926,7 +925,7 @@ class AssetGuard extends EventEmitter {
} }
// Check the JAVA_HOME environment variable. // Check the JAVA_HOME environment variable.
const jHome = AssetGuard._scanJavaHome() let jHome = AssetGuard._scanJavaHome()
if(jHome != null){ if(jHome != null){
// Ensure we are at the absolute root. // Ensure we are at the absolute root.
if(jHome.contains('/Contents/Home')){ if(jHome.contains('/Contents/Home')){
@ -1099,7 +1098,6 @@ class AssetGuard extends EventEmitter {
//Asset constants //Asset constants
const resourceURL = 'http://resources.download.minecraft.net/' const resourceURL = 'http://resources.download.minecraft.net/'
const localPath = path.join(self.commonPath, 'assets') const localPath = path.join(self.commonPath, 'assets')
const indexPath = path.join(localPath, 'indexes')
const objectPath = path.join(localPath, 'objects') const objectPath = path.join(localPath, 'objects')
const assetDlQueue = [] const assetDlQueue = []
@ -1112,7 +1110,7 @@ class AssetGuard extends EventEmitter {
self.emit('progress', 'assets', acc, total) self.emit('progress', 'assets', acc, total)
const hash = value.hash const hash = value.hash
const assetName = path.join(hash.substring(0, 2), hash) const assetName = path.join(hash.substring(0, 2), hash)
const urlName = hash.substring(0, 2) + "/" + hash const urlName = hash.substring(0, 2) + '/' + hash
const ast = new Asset(key, hash, value.size, resourceURL + urlName, path.join(objectPath, assetName)) const ast = new Asset(key, hash, value.size, resourceURL + urlName, path.join(objectPath, assetName))
if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){ if(!AssetGuard._validateLocal(ast.to, 'sha1', ast.hash)){
dlSize += (ast.size*1) dlSize += (ast.size*1)
@ -1271,7 +1269,7 @@ class AssetGuard extends EventEmitter {
_parseDistroModules(modules, version, servid){ _parseDistroModules(modules, version, servid){
let alist = [] let alist = []
let asize = 0; let asize = 0
let decompressqueue = [] let decompressqueue = []
for(let ob of modules){ for(let ob of modules){
let obType = ob.getType let obType = ob.getType
@ -1361,15 +1359,15 @@ class AssetGuard extends EventEmitter {
let h = null let h = null
fs.createReadStream(a.to) fs.createReadStream(a.to)
.on('error', err => console.log(err)) .on('error', err => console.log(err))
.pipe(zlib.createGunzip()) .pipe(zlib.createGunzip())
.on('error', err => console.log(err)) .on('error', err => console.log(err))
.pipe(tar.extract(dataDir, { .pipe(tar.extract(dataDir, {
map: (header) => { map: (header) => {
if(h == null){ if(h == null){
h = header.name h = header.name
}
} }
} }))
}))
.on('error', err => console.log(err)) .on('error', err => console.log(err))
.on('finish', () => { .on('finish', () => {
fs.unlink(a.to, err => { fs.unlink(a.to, err => {
@ -1525,7 +1523,7 @@ class AssetGuard extends EventEmitter {
}, (err) => { }, (err) => {
if(err){ if(err){
console.log('An item in ' + identifier + ' failed to process'); console.log('An item in ' + identifier + ' failed to process')
} else { } else {
console.log('All ' + identifier + ' have been processed successfully') console.log('All ' + identifier + ' have been processed successfully')
} }

View File

@ -73,7 +73,7 @@ const DEFAULT_CONFIG = {
modConfigurations: [] modConfigurations: []
} }
let config = null; let config = null
// Persistance Utility Functions // Persistance Utility Functions

View File

@ -1,6 +1,5 @@
// Work in progress // Work in progress
const {Client} = require('discord-rpc') const {Client} = require('discord-rpc')
const ConfigManager = require('./configmanager')
let client let client
let activity let activity

View File

@ -483,7 +483,7 @@ class DistroIndex {
* @returns {Server} The main server. * @returns {Server} The main server.
*/ */
getMainServer(){ getMainServer(){
return getServer(this.mainServer) return this.mainServer != null ? this.getServer(this.mainServer) : null
} }
} }

View File

@ -88,34 +88,34 @@ exports.statusToHex = function(status){
exports.status = function(){ exports.status = function(){
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request.get('https://status.mojang.com/check', request.get('https://status.mojang.com/check',
{ {
json: true, json: true,
timeout: 2500 timeout: 2500
}, },
function(error, response, body){ function(error, response, body){
if(error || response.statusCode !== 200){ if(error || response.statusCode !== 200){
console.warn('Unable to retrieve Mojang status.') console.warn('Unable to retrieve Mojang status.')
console.debug('Error while retrieving Mojang statuses:', error) console.debug('Error while retrieving Mojang statuses:', error)
//reject(error || response.statusCode) //reject(error || response.statusCode)
for(let i=0; i<statuses.length; i++){ for(let i=0; i<statuses.length; i++){
statuses[i].status = 'grey' statuses[i].status = 'grey'
} }
resolve(statuses) resolve(statuses)
} else { } else {
for(let i=0; i<body.length; i++){ for(let i=0; i<body.length; i++){
const key = Object.keys(body[i])[0] const key = Object.keys(body[i])[0]
inner: inner:
for(let j=0; j<statuses.length; j++){ for(let j=0; j<statuses.length; j++){
if(statuses[j].service === key) { if(statuses[j].service === key) {
statuses[j].status = body[i][key] statuses[j].status = body[i][key]
break inner break inner
}
} }
} }
resolve(statuses)
} }
resolve(statuses) })
}
})
}) })
} }
@ -133,28 +133,28 @@ exports.status = function(){
exports.authenticate = function(username, password, clientToken, requestUser = true, agent = minecraftAgent){ exports.authenticate = function(username, password, clientToken, requestUser = true, agent = minecraftAgent){
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request.post(authpath + '/authenticate', request.post(authpath + '/authenticate',
{ {
json: true, json: true,
body: { body: {
agent, agent,
username, username,
password, password,
clientToken, clientToken,
requestUser requestUser
}
},
function(error, response, body){
if(error){
console.error('Error during authentication.', error)
reject(error)
} else {
if(response.statusCode === 200){
resolve(body)
} else {
reject(body || {code: 'ENOTFOUND'})
} }
} },
}) function(error, response, body){
if(error){
console.error('Error during authentication.', error)
reject(error)
} else {
if(response.statusCode === 200){
resolve(body)
} else {
reject(body || {code: 'ENOTFOUND'})
}
}
})
}) })
} }
@ -170,26 +170,26 @@ exports.authenticate = function(username, password, clientToken, requestUser = t
exports.validate = function(accessToken, clientToken){ exports.validate = function(accessToken, clientToken){
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request.post(authpath + '/validate', request.post(authpath + '/validate',
{ {
json: true, json: true,
body: { body: {
accessToken, accessToken,
clientToken clientToken
}
},
function(error, response, body){
if(error){
console.error('Error during validation.', error)
reject(error)
} else {
if(response.statusCode === 403){
resolve(false)
} else {
// 204 if valid
resolve(true)
} }
} },
}) function(error, response, body){
if(error){
console.error('Error during validation.', error)
reject(error)
} else {
if(response.statusCode === 403){
resolve(false)
} else {
// 204 if valid
resolve(true)
}
}
})
}) })
} }
@ -205,25 +205,25 @@ exports.validate = function(accessToken, clientToken){
exports.invalidate = function(accessToken, clientToken){ exports.invalidate = function(accessToken, clientToken){
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request.post(authpath + '/invalidate', request.post(authpath + '/invalidate',
{ {
json: true, json: true,
body: { body: {
accessToken, accessToken,
clientToken clientToken
}
},
function(error, response, body){
if(error){
console.error('Error during invalidation.', error)
reject(error)
} else {
if(response.statusCode === 204){
resolve()
} else {
reject(body)
} }
} },
}) function(error, response, body){
if(error){
console.error('Error during invalidation.', error)
reject(error)
} else {
if(response.statusCode === 204){
resolve()
} else {
reject(body)
}
}
})
}) })
} }
@ -241,25 +241,25 @@ exports.invalidate = function(accessToken, clientToken){
exports.refresh = function(accessToken, clientToken, requestUser = true){ exports.refresh = function(accessToken, clientToken, requestUser = true){
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request.post(authpath + '/refresh', request.post(authpath + '/refresh',
{ {
json: true, json: true,
body: { body: {
accessToken, accessToken,
clientToken, clientToken,
requestUser requestUser
}
},
function(error, response, body){
if(error){
console.error('Error during refresh.', error)
reject(error)
} else {
if(response.statusCode === 200){
resolve(body)
} else {
reject(body)
} }
} },
}) function(error, response, body){
if(error){
console.error('Error during refresh.', error)
reject(error)
} else {
if(response.statusCode === 200){
resolve(body)
} else {
reject(body)
}
}
})
}) })
} }

View File

@ -14,7 +14,7 @@ ConfigManager.load()
function onDistroLoad(data){ function onDistroLoad(data){
if(data != null){ if(data != null){
// Resolve the selected server if its value has yet to be set. // Resolve the selected server if its value has yet to be set.
if(ConfigManager.getSelectedServer() == null || data.getServer(ConfigManager.getSelectedServer()) == null){ if(ConfigManager.getSelectedServer() == null || data.getServer(ConfigManager.getSelectedServer()) == null){
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Determining default selected server..') console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Determining default selected server..')
ConfigManager.setSelectedServer(data.getMainServer().getID()) ConfigManager.setSelectedServer(data.getMainServer().getID())
@ -28,7 +28,7 @@ function onDistroLoad(data){
DistroManager.pullRemote().then((data) => { DistroManager.pullRemote().then((data) => {
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Loaded distribution index.') console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Loaded distribution index.')
onDistroLoad(data) onDistroLoad(data)
}).catch((err) => { }).catch((err) => {
console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Failed to load distribution index.') console.log('%c[Preloader]', 'color: #a02d2a; font-weight: bold', 'Failed to load distribution index.')

View File

@ -210,11 +210,11 @@ class ProcessBuilder {
constructJVMArguments(mods, tempNativePath){ constructJVMArguments(mods, tempNativePath){
let args = ['-Xmx' + ConfigManager.getMaxRAM(), let args = ['-Xmx' + ConfigManager.getMaxRAM(),
'-Xms' + ConfigManager.getMinRAM(), '-Xms' + ConfigManager.getMinRAM(),
'-Djava.library.path=' + tempNativePath, '-Djava.library.path=' + tempNativePath,
'-cp', '-cp',
this.classpathArg(mods, tempNativePath).join(process.platform === 'win32' ? ';' : ':'), this.classpathArg(mods, tempNativePath).join(process.platform === 'win32' ? ';' : ':'),
this.forgeData.mainClass] this.forgeData.mainClass]
if(process.platform === 'darwin'){ if(process.platform === 'darwin'){
args.unshift('-Xdock:name=WesterosCraft') args.unshift('-Xdock:name=WesterosCraft')
@ -241,13 +241,13 @@ class ProcessBuilder {
for(let i=0; i<mcArgs.length; ++i){ for(let i=0; i<mcArgs.length; ++i){
if(argDiscovery.test(mcArgs[i])){ if(argDiscovery.test(mcArgs[i])){
const identifier = mcArgs[i].match(argDiscovery)[1] const identifier = mcArgs[i].match(argDiscovery)[1]
let val = null; let val = null
switch(identifier){ switch(identifier){
case 'auth_player_name': case 'auth_player_name':
val = this.authUser.displayName val = this.authUser.displayName
break break
case 'version_name': case 'version_name':
//val = versionData.id //val = versionData.id
val = this.server.getID() val = this.server.getID()
break break
case 'game_directory': case 'game_directory':
@ -273,7 +273,7 @@ class ProcessBuilder {
break break
} }
if(val != null){ if(val != null){
mcArgs[i] = val; mcArgs[i] = val
} }
} }
} }

View File

@ -152,8 +152,8 @@ const refreshMojangStatuses = async function(){
console.log('Refreshing Mojang Statuses..') console.log('Refreshing Mojang Statuses..')
let status = 'grey' let status = 'grey'
let tooltipEssentialHTML = `` let tooltipEssentialHTML = ''
let tooltipNonEssentialHTML = `` let tooltipNonEssentialHTML = ''
try { try {
const statuses = await Mojang.status() const statuses = await Mojang.status()
@ -358,7 +358,7 @@ function asyncSystemScan(launchAfter = true){
switch(m.data){ switch(m.data){
case 'download': case 'download':
// Downloading.. // Downloading..
setDownloadPercentage(m.value, m.total, m.percent) setDownloadPercentage(m.value, m.total, m.percent)
break break
} }
@ -366,7 +366,7 @@ function asyncSystemScan(launchAfter = true){
} else if(m.context === 'complete'){ } else if(m.context === 'complete'){
switch(m.data){ switch(m.data){
case 'download': case 'download': {
// Show installing progress bar. // Show installing progress bar.
remote.getCurrentWindow().setProgressBar(2) remote.getCurrentWindow().setProgressBar(2)
@ -383,8 +383,9 @@ function asyncSystemScan(launchAfter = true){
setLaunchDetails(eLStr + dotStr) setLaunchDetails(eLStr + dotStr)
}, 750) }, 750)
break break
}
case 'java': case 'java':
// Download & extraction complete, remove the loading from the OS progress bar. // Download & extraction complete, remove the loading from the OS progress bar.
remote.getCurrentWindow().setProgressBar(-1) remote.getCurrentWindow().setProgressBar(-1)
// Extraction completed successfully. // Extraction completed successfully.
@ -497,14 +498,15 @@ function dlAsync(login = true){
} }
} else if(m.context === 'progress'){ } else if(m.context === 'progress'){
switch(m.data){ switch(m.data){
case 'assets': case 'assets': {
const perc = (m.value/m.total)*20 const perc = (m.value/m.total)*20
setLaunchPercentage(40+perc, 100, parseInt(40+perc)) setLaunchPercentage(40+perc, 100, parseInt(40+perc))
break break
}
case 'download': case 'download':
setDownloadPercentage(m.value, m.total, m.percent) setDownloadPercentage(m.value, m.total, m.percent)
break break
case 'extract': case 'extract': {
// Show installing progress bar. // Show installing progress bar.
remote.getCurrentWindow().setProgressBar(2) remote.getCurrentWindow().setProgressBar(2)
@ -521,6 +523,7 @@ function dlAsync(login = true){
setLaunchDetails(eLStr + dotStr) setLaunchDetails(eLStr + dotStr)
}, 750) }, 750)
break break
}
} }
} else if(m.context === 'complete'){ } else if(m.context === 'complete'){
switch(m.data){ switch(m.data){
@ -1001,54 +1004,54 @@ function loadNews(){
const newsFeed = distroData.getRSS() const newsFeed = distroData.getRSS()
const newsHost = new URL(newsFeed).origin + '/' const newsHost = new URL(newsFeed).origin + '/'
$.ajax( $.ajax(
{ {
url: newsFeed, url: newsFeed,
success: (data) => { success: (data) => {
const items = $(data).find('item') const items = $(data).find('item')
const articles = [] const articles = []
for(let i=0; i<items.length; i++){ for(let i=0; i<items.length; i++){
// JQuery Element // JQuery Element
const el = $(items[i]) const el = $(items[i])
// Resolve date. // Resolve date.
const date = new Date(el.find('pubDate').text()).toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'}) const date = new Date(el.find('pubDate').text()).toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'})
// Resolve comments. // Resolve comments.
let comments = el.find('slash\\:comments').text() || '0' let comments = el.find('slash\\:comments').text() || '0'
comments = comments + ' Comment' + (comments === '1' ? '' : 's') comments = comments + ' Comment' + (comments === '1' ? '' : 's')
// Fix relative links in content. // Fix relative links in content.
let content = el.find('content\\:encoded').text() let content = el.find('content\\:encoded').text()
let regex = /src="(?!http:\/\/|https:\/\/)(.+)"/g let regex = /src="(?!http:\/\/|https:\/\/)(.+)"/g
let matches let matches
while(matches = regex.exec(content)){ while((matches = regex.exec(content))){
content = content.replace(matches[1], newsHost + matches[1]) content = content.replace(matches[1], newsHost + matches[1])
}
let link = el.find('link').text()
let title = el.find('title').text()
let author = el.find('dc\\:creator').text()
// Generate article.
articles.push(
{
link,
title,
date,
author,
content,
comments,
commentsLink: link + '#comments'
} }
)
} let link = el.find('link').text()
resolve({ let title = el.find('title').text()
articles let author = el.find('dc\\:creator').text()
})
}, // Generate article.
timeout: 2500 articles.push(
}).catch(err => { {
link,
title,
date,
author,
content,
comments,
commentsLink: link + '#comments'
}
)
}
resolve({
articles
})
},
timeout: 2500
}).catch(err => {
resolve({ resolve({
articles: null articles: null
}) })

View File

@ -22,7 +22,7 @@ function toggleOverlay(toggleState, dismissable = false, content = 'overlayConte
if(toggleState){ if(toggleState){
document.getElementById('main').setAttribute('overlay', true) document.getElementById('main').setAttribute('overlay', true)
// Make things untabbable. // Make things untabbable.
$("#main *").attr('tabindex', '-1') $('#main *').attr('tabindex', '-1')
$('#' + content).parent().children().hide() $('#' + content).parent().children().hide()
$('#' + content).show() $('#' + content).show()
if(dismissable){ if(dismissable){
@ -41,7 +41,7 @@ function toggleOverlay(toggleState, dismissable = false, content = 'overlayConte
} else { } else {
document.getElementById('main').removeAttribute('overlay') document.getElementById('main').removeAttribute('overlay')
// Make things tabbable. // Make things tabbable.
$("#main *").removeAttr('tabindex') $('#main *').removeAttr('tabindex')
$('#overlayContainer').fadeOut({ $('#overlayContainer').fadeOut({
duration: 250, duration: 250,
start: () => { start: () => {
@ -232,9 +232,9 @@ function populateServerListings(){
const distro = DistroManager.getDistribution() const distro = DistroManager.getDistribution()
const giaSel = ConfigManager.getSelectedServer() const giaSel = ConfigManager.getSelectedServer()
const servers = distro.getServers() const servers = distro.getServers()
let htmlString = `` let htmlString = ''
for(const serv of servers){ for(const serv of servers){
htmlString += `<button class="serverListing" servid="${serv.getID()}" ${serv.getID() === giaSel ? `selected` : ``}> htmlString += `<button class="serverListing" servid="${serv.getID()}" ${serv.getID() === giaSel ? 'selected' : ''}>
<img class="serverListingImg" src="${serv.getIcon()}"/> <img class="serverListingImg" src="${serv.getIcon()}"/>
<div class="serverListingDetails"> <div class="serverListingDetails">
<span class="serverListingName">${serv.getName()}</span> <span class="serverListingName">${serv.getName()}</span>
@ -251,7 +251,7 @@ function populateServerListings(){
<circle class="cls-2" cx="53.73" cy="53.9" r="38"/> <circle class="cls-2" cx="53.73" cy="53.9" r="38"/>
</svg> </svg>
<span class="serverListingStarTooltip">Main Server</span> <span class="serverListingStarTooltip">Main Server</span>
</div>` : ``} </div>` : ''}
</div> </div>
</div> </div>
</button>` </button>`
@ -262,8 +262,8 @@ function populateServerListings(){
function populateAccountListings(){ function populateAccountListings(){
const accountsObj = ConfigManager.getAuthAccounts() const accountsObj = ConfigManager.getAuthAccounts()
const accounts = Array.from(Object.keys(accountsObj), v=>accountsObj[v]); const accounts = Array.from(Object.keys(accountsObj), v=>accountsObj[v])
let htmlString = `` let htmlString = ''
for(let i=0; i<accounts.length; i++){ for(let i=0; i<accounts.length; i++){
htmlString += `<button class="accountListing" uuid="${accounts[i].uuid}" ${i===0 ? 'selected' : ''}> htmlString += `<button class="accountListing" uuid="${accounts[i].uuid}" ${i===0 ? 'selected' : ''}>
<img src="https://crafatar.com/renders/head/${accounts[i].uuid}?scale=2&default=MHF_Steve&overlay"> <img src="https://crafatar.com/renders/head/${accounts[i].uuid}?scale=2&default=MHF_Steve&overlay">

View File

@ -12,7 +12,7 @@ const settingsState = {
* General Settings Functions * General Settings Functions
*/ */
/** /**
* Bind value validators to the settings UI elements. These will * Bind value validators to the settings UI elements. These will
* validate against the criteria defined in the ConfigManager (if * validate against the criteria defined in the ConfigManager (if
* and). If the value is invalid, the UI will reflect this and saving * and). If the value is invalid, the UI will reflect this and saving
@ -59,8 +59,8 @@ function initSettingsValues(){
if(typeof gFn === 'function'){ if(typeof gFn === 'function'){
if(v.tagName === 'INPUT'){ if(v.tagName === 'INPUT'){
if(v.type === 'number' || v.type === 'text'){ if(v.type === 'number' || v.type === 'text'){
// Special Conditions // Special Conditions
const cVal = v.getAttribute('cValue') const cVal = v.getAttribute('cValue')
if(cVal === 'JavaExecutable'){ if(cVal === 'JavaExecutable'){
populateJavaExecDetails(v.value) populateJavaExecDetails(v.value)
v.value = gFn() v.value = gFn()
@ -363,7 +363,7 @@ function populateAuthAccounts(){
const authKeys = Object.keys(authAccounts) const authKeys = Object.keys(authAccounts)
const selectedUUID = ConfigManager.getSelectedAccount().uuid const selectedUUID = ConfigManager.getSelectedAccount().uuid
let authAccountStr = `` let authAccountStr = ''
authKeys.map((val) => { authKeys.map((val) => {
const acc = authAccounts[val] const acc = authAccounts[val]
@ -408,16 +408,16 @@ function prepareAccountsTab() {
* Minecraft Tab * Minecraft Tab
*/ */
/** /**
* Disable decimals, negative signs, and scientific notation. * Disable decimals, negative signs, and scientific notation.
*/ */
document.getElementById('settingsGameWidth').addEventListener('keydown', (e) => { document.getElementById('settingsGameWidth').addEventListener('keydown', (e) => {
if(/[-\.eE]/.test(e.key)){ if(/^[-.eE]$/.test(e.key)){
e.preventDefault() e.preventDefault()
} }
}) })
document.getElementById('settingsGameHeight').addEventListener('keydown', (e) => { document.getElementById('settingsGameHeight').addEventListener('keydown', (e) => {
if(/[-\.eE]/.test(e.key)){ if(/^[-.eE]$/.test(e.key)){
e.preventDefault() e.preventDefault()
} }
}) })
@ -472,7 +472,7 @@ settingsMinRAMRange.onchange = (e) => {
if(sMaxV < sMinV){ if(sMaxV < sMinV){
const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange) const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
updateRangedSlider(settingsMaxRAMRange, sMinV, updateRangedSlider(settingsMaxRAMRange, sMinV,
((sMinV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc) ((sMinV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
settingsMaxRAMLabel.innerHTML = sMinV.toFixed(1) + 'G' settingsMaxRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
} }
@ -504,7 +504,7 @@ settingsMaxRAMRange.onchange = (e) => {
if(sMaxV < sMinV){ if(sMaxV < sMinV){
const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange) const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
updateRangedSlider(settingsMinRAMRange, sMaxV, updateRangedSlider(settingsMinRAMRange, sMaxV,
((sMaxV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc) ((sMaxV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
settingsMinRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G' settingsMinRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
} }
settingsMaxRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G' settingsMaxRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
@ -730,7 +730,7 @@ function prepareAboutTab(){
* Settings preparation functions. * Settings preparation functions.
*/ */
/** /**
* Prepare the entire settings UI. * Prepare the entire settings UI.
* *
* @param {boolean} first Whether or not it is the first load. * @param {boolean} first Whether or not it is the first load.

View File

@ -104,7 +104,7 @@ function showMainUI(data){
}, 750) }, 750)
// Disable tabbing to the news container. // Disable tabbing to the news container.
initNews().then(() => { initNews().then(() => {
$("#newsContainer *").attr('tabindex', '-1') $('#newsContainer *').attr('tabindex', '-1')
}) })
} }
@ -275,12 +275,12 @@ function mergeModConfiguration(o, n){
function refreshDistributionIndex(remote, onSuccess, onError){ function refreshDistributionIndex(remote, onSuccess, onError){
if(remote){ if(remote){
DistroManager.pullRemote() DistroManager.pullRemote()
.then(onSuccess) .then(onSuccess)
.catch(onError) .catch(onError)
} else { } else {
DistroManager.pullLocal() DistroManager.pullLocal()
.then(onSuccess) .then(onSuccess)
.catch(onError) .catch(onError)
} }
} }
@ -313,7 +313,7 @@ async function validateSelectedAccount(){
}) })
} else { } else {
const accountsObj = ConfigManager.getAuthAccounts() const accountsObj = ConfigManager.getAuthAccounts()
const accounts = Array.from(Object.keys(accountsObj), v => accountsObj[v]); const accounts = Array.from(Object.keys(accountsObj), v => accountsObj[v])
// This function validates the account switch. // This function validates the account switch.
setSelectedAccount(accounts[0].uuid) setSelectedAccount(accounts[0].uuid)
toggleOverlay(false) toggleOverlay(false)
@ -375,7 +375,7 @@ ipcRenderer.on('distributionIndexDone', (event, res) => {
} else { } else {
fatalStartupError = true fatalStartupError = true
if(document.readyState === 'complete'){ if(document.readyState === 'complete'){
showFatalStartupError() showFatalStartupError()
} else { } else {
rscShouldLoad = true rscShouldLoad = true
} }

View File

@ -5,7 +5,7 @@
* modules, excluding dependencies. * modules, excluding dependencies.
*/ */
// Requirements // Requirements
const $ = require('jquery'); const $ = require('jquery')
const {ipcRenderer, remote, shell, webFrame} = require('electron') const {ipcRenderer, remote, shell, webFrame} = require('electron')
const isDev = require('electron-is-dev') const isDev = require('electron-is-dev')
@ -50,6 +50,7 @@ if(!isDev){
ipcRenderer.send('autoUpdateAction', 'checkForUpdate') ipcRenderer.send('autoUpdateAction', 'checkForUpdate')
}, 1800000) }, 1800000)
ipcRenderer.send('autoUpdateAction', 'checkForUpdate') ipcRenderer.send('autoUpdateAction', 'checkForUpdate')
break
case 'realerror': case 'realerror':
if(info != null && info.code != null){ if(info != null && info.code != null){
if(info.code === 'ERR_UPDATER_INVALID_RELEASE_FEED'){ if(info.code === 'ERR_UPDATER_INVALID_RELEASE_FEED'){
@ -108,7 +109,7 @@ $(function(){
document.addEventListener('readystatechange', function () { document.addEventListener('readystatechange', function () {
if (document.readyState === 'interactive'){ if (document.readyState === 'interactive'){
console.log('UICore Initializing..'); console.log('UICore Initializing..')
// Bind close button. // Bind close button.
Array.from(document.getElementsByClassName('fCb')).map((val) => { Array.from(document.getElementsByClassName('fCb')).map((val) => {
@ -157,10 +158,10 @@ document.addEventListener('readystatechange', function () {
//const targetWidth2 = document.getElementById("server_selection").getBoundingClientRect().width //const targetWidth2 = document.getElementById("server_selection").getBoundingClientRect().width
//const targetWidth3 = document.getElementById("launch_button").getBoundingClientRect().width //const targetWidth3 = document.getElementById("launch_button").getBoundingClientRect().width
document.getElementById("launch_details").style.maxWidth = 266.01 document.getElementById('launch_details').style.maxWidth = 266.01
document.getElementById("launch_progress").style.width = 170.8 document.getElementById('launch_progress').style.width = 170.8
document.getElementById("launch_details_right").style.maxWidth = 170.8 document.getElementById('launch_details_right').style.maxWidth = 170.8
document.getElementById("launch_progress_label").style.width = 53.21 document.getElementById('launch_progress_label').style.width = 53.21
} }
@ -170,7 +171,7 @@ document.addEventListener('readystatechange', function () {
* Open web links in the user's default browser. * Open web links in the user's default browser.
*/ */
$(document).on('click', 'a[href^="http"]', function(event) { $(document).on('click', 'a[href^="http"]', function(event) {
event.preventDefault(); event.preventDefault()
//console.log(os.homedir()) //console.log(os.homedir())
shell.openExternal(this.href) shell.openExternal(this.href)
}) })

View File

@ -1,44 +0,0 @@
const app = require('electron')
const remote = require('electron').BrowserWindow
/**
* Doesn't work yet.
*/
exports.setIconBadge = function(text){
if(process.platform === 'darwin'){
app.dock.setBadge('' + text)
} else if (process.platform === 'win32'){
const win = remote.getFocusedWindow()
if(text === ''){
win.setOverlayIcon(null, '')
return;
}
//Create badge
const canvas = document.createElement('canvas')
canvas.height = 140;
canvas.width = 140;
const ctx = canvas.getContext('2d')
ctx.fillStyle = '#a02d2a'
ctx.beginPath()
ctx.ellipse(70, 70, 70, 70, 0, 0, 2 * Math.PI)
ctx.fill()
ctx.textAlign = 'center'
ctx.fillStyle = 'white'
if(text.length > 2 ){
ctx.font = '75px sans-serif'
ctx.fillText('' + text, 70, 98)
} else if (text.length > 1){
ctx.font = '100px sans-serif'
ctx.fillText('' + text, 70, 105)
} else {
ctx.font = '125px sans-serif'
ctx.fillText('' + text, 70, 112)
}
const badgeDataURL = canvas.toDataURL()
const img = NativeImage.createFromDataURL(badgeDataURL)
win.setOverlayIcon(img, '' + text)
}
}

View File

@ -130,7 +130,7 @@ function getPlatformIcon(filename){
return path.join(__dirname, 'app', 'assets', 'images', filename) return path.join(__dirname, 'app', 'assets', 'images', filename)
} }
app.on('ready', createWindow); app.on('ready', createWindow)
app.on('window-all-closed', () => { app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar // On macOS it is common for applications and their menu bar

888
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -12,7 +12,8 @@
"dist:win": "npm run dist -- --win --x64", "dist:win": "npm run dist -- --win --x64",
"dist:mac": "npm run dist -- --mac", "dist:mac": "npm run dist -- --mac",
"dist:linux": "npm run dist -- --linux --x64", "dist:linux": "npm run dist -- --linux --x64",
"dist:all": "npm run dist -- -wl --x64" "dist:all": "npm run dist -- -wl --x64",
"lint": "eslint --config .eslintrc.json --ignore-pattern app/assets/js/scripts/*.js . && eslint --config .eslintrc.scripts.json app/assets/js/scripts"
}, },
"engines": { "engines": {
"node": "10.5.x" "node": "10.5.x"
@ -47,7 +48,8 @@
}, },
"devDependencies": { "devDependencies": {
"electron": "^2.0.5", "electron": "^2.0.5",
"electron-builder": "^20.24.4" "electron-builder": "^20.24.4",
"eslint": "^5.2.0"
}, },
"build": { "build": {
"appId": "westeroscraftlauncher", "appId": "westeroscraftlauncher",