settings.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. const settingsNavDone = document.getElementById('settingsNavDone')
  2. // Account Management Tab
  3. const settingsAddAccount = document.getElementById('settingsAddAccount')
  4. const settingsCurrentAccounts = document.getElementById('settingsCurrentAccounts')
  5. // Minecraft Tab
  6. const settingsGameWidth = document.getElementById('settingsGameWidth')
  7. const settingsGameHeight = document.getElementById('settingsGameHeight')
  8. // Java Tab
  9. const settingsMaxRAMRange = document.getElementById('settingsMaxRAMRange')
  10. const settingsMinRAMRange = document.getElementById('settingsMinRAMRange')
  11. const settingsState = {
  12. invalid: new Set()
  13. }
  14. /**
  15. * General Settings Functions
  16. */
  17. /**
  18. * Bind value validators to the settings UI elements. These will
  19. * validate against the criteria defined in the ConfigManager (if
  20. * and). If the value is invalid, the UI will reflect this and saving
  21. * will be disabled until the value is corrected. This is an automated
  22. * process. More complex UI may need to be bound separately.
  23. */
  24. function initSettingsValidators(){
  25. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  26. Array.from(sEls).map((v, index, arr) => {
  27. const vFn = ConfigManager['validate' + v.getAttribute('cValue')]
  28. if(typeof vFn === 'function'){
  29. if(v.tagName === 'INPUT'){
  30. if(v.type === 'number' || v.type === 'text'){
  31. v.addEventListener('keyup', (e) => {
  32. const v = e.target
  33. if(!vFn(v.value)){
  34. settingsState.invalid.add(v.id)
  35. v.setAttribute('error', '')
  36. settingsSaveDisabled(true)
  37. } else {
  38. if(v.hasAttribute('error')){
  39. v.removeAttribute('error')
  40. settingsState.invalid.delete(v.id)
  41. if(settingsState.invalid.size === 0){
  42. settingsSaveDisabled(false)
  43. }
  44. }
  45. }
  46. })
  47. }
  48. }
  49. }
  50. })
  51. }
  52. /**
  53. * Load configuration values onto the UI. This is an automated process.
  54. */
  55. function initSettingsValues(){
  56. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  57. Array.from(sEls).map((v, index, arr) => {
  58. const gFn = ConfigManager['get' + v.getAttribute('cValue')]
  59. if(typeof gFn === 'function'){
  60. if(v.tagName === 'INPUT'){
  61. if(v.type === 'number' || v.type === 'text'){
  62. v.value = gFn()
  63. } else if(v.type === 'checkbox'){
  64. v.checked = gFn()
  65. }
  66. } else if(v.tagName === 'DIV'){
  67. if(v.classList.contains('rangeSlider')){
  68. v.setAttribute('value', Number.parseFloat(gFn()))
  69. }
  70. }
  71. }
  72. })
  73. }
  74. /**
  75. * Save the settings values.
  76. */
  77. function saveSettingsValues(){
  78. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  79. Array.from(sEls).map((v, index, arr) => {
  80. const sFn = ConfigManager['set' + v.getAttribute('cValue')]
  81. if(typeof sFn === 'function'){
  82. if(v.tagName === 'INPUT'){
  83. if(v.type === 'number' || v.type === 'text'){
  84. sFn(v.value)
  85. } else if(v.type === 'checkbox'){
  86. sFn(v.checked)
  87. // Special Conditions
  88. const cVal = v.getAttribute('cValue')
  89. if(cVal === 'AllowPrerelease'){
  90. changeAllowPrerelease(v.checked)
  91. }
  92. }
  93. }
  94. }
  95. })
  96. }
  97. let selectedTab = 'settingsTabAccount'
  98. /**
  99. * Bind functionality for the settings navigation items.
  100. */
  101. function setupSettingsTabs(){
  102. Array.from(document.getElementsByClassName('settingsNavItem')).map((val) => {
  103. val.onclick = (e) => {
  104. if(val.hasAttribute('selected')){
  105. return
  106. }
  107. const navItems = document.getElementsByClassName('settingsNavItem')
  108. for(let i=0; i<navItems.length; i++){
  109. if(navItems[i].hasAttribute('selected')){
  110. navItems[i].removeAttribute('selected')
  111. }
  112. }
  113. val.setAttribute('selected', '')
  114. let prevTab = selectedTab
  115. selectedTab = val.getAttribute('rSc')
  116. $(`#${prevTab}`).fadeOut(250, () => {
  117. $(`#${selectedTab}`).fadeIn(250)
  118. })
  119. }
  120. })
  121. }
  122. /**
  123. * Set if the settings save (done) button is disabled.
  124. *
  125. * @param {boolean} v True to disable, false to enable.
  126. */
  127. function settingsSaveDisabled(v){
  128. settingsNavDone.disabled = v
  129. }
  130. /* Closes the settings view and saves all data. */
  131. settingsNavDone.onclick = () => {
  132. saveSettingsValues()
  133. ConfigManager.save()
  134. switchView(getCurrentView(), VIEWS.landing)
  135. }
  136. /**
  137. * Account Management Tab
  138. */
  139. // Bind the add account button.
  140. settingsAddAccount.onclick = (e) => {
  141. switchView(getCurrentView(), VIEWS.login, 500, 500, () => {
  142. loginViewOnCancel = VIEWS.settings
  143. loginViewOnSuccess = VIEWS.settings
  144. loginCancelEnabled(true)
  145. })
  146. }
  147. /**
  148. * Bind functionality for the account selection buttons. If another account
  149. * is selected, the UI of the previously selected account will be updated.
  150. */
  151. function bindAuthAccountSelect(){
  152. Array.from(document.getElementsByClassName('settingsAuthAccountSelect')).map((val) => {
  153. val.onclick = (e) => {
  154. if(val.hasAttribute('selected')){
  155. return
  156. }
  157. const selectBtns = document.getElementsByClassName('settingsAuthAccountSelect')
  158. for(let i=0; i<selectBtns.length; i++){
  159. if(selectBtns[i].hasAttribute('selected')){
  160. selectBtns[i].removeAttribute('selected')
  161. selectBtns[i].innerHTML = 'Select Account'
  162. }
  163. }
  164. val.setAttribute('selected', '')
  165. val.innerHTML = 'Selected Account &#10004;'
  166. setSelectedAccount(val.closest('.settingsAuthAccount').getAttribute('uuid'))
  167. }
  168. })
  169. }
  170. /**
  171. * Bind functionality for the log out button. If the logged out account was
  172. * the selected account, another account will be selected and the UI will
  173. * be updated accordingly.
  174. */
  175. function bindAuthAccountLogOut(){
  176. Array.from(document.getElementsByClassName('settingsAuthAccountLogOut')).map((val) => {
  177. val.onclick = (e) => {
  178. let isLastAccount = false
  179. if(Object.keys(ConfigManager.getAuthAccounts()).length === 1){
  180. isLastAccount = true
  181. setOverlayContent(
  182. 'Warning<br>This is Your Last Account',
  183. 'In order to use the launcher you must be logged into at least one account. You will need to login again after.<br><br>Are you sure you want to log out?',
  184. 'I\'m Sure',
  185. 'Cancel'
  186. )
  187. setOverlayHandler(() => {
  188. processLogOut(val, isLastAccount)
  189. switchView(getCurrentView(), VIEWS.login)
  190. toggleOverlay(false)
  191. })
  192. setDismissHandler(() => {
  193. toggleOverlay(false)
  194. })
  195. toggleOverlay(true, true)
  196. } else {
  197. processLogOut(val, isLastAccount)
  198. }
  199. }
  200. })
  201. }
  202. /**
  203. * Process a log out.
  204. *
  205. * @param {Element} val The log out button element.
  206. * @param {boolean} isLastAccount If this logout is on the last added account.
  207. */
  208. function processLogOut(val, isLastAccount){
  209. const parent = val.closest('.settingsAuthAccount')
  210. const uuid = parent.getAttribute('uuid')
  211. const prevSelAcc = ConfigManager.getSelectedAccount()
  212. AuthManager.removeAccount(uuid).then(() => {
  213. if(!isLastAccount && uuid === prevSelAcc.uuid){
  214. const selAcc = ConfigManager.getSelectedAccount()
  215. refreshAuthAccountSelected(selAcc.uuid)
  216. updateSelectedAccount(selAcc)
  217. validateSelectedAccount()
  218. }
  219. })
  220. $(parent).fadeOut(250, () => {
  221. parent.remove()
  222. })
  223. }
  224. /**
  225. * Refreshes the status of the selected account on the auth account
  226. * elements.
  227. *
  228. * @param {string} uuid The UUID of the new selected account.
  229. */
  230. function refreshAuthAccountSelected(uuid){
  231. Array.from(document.getElementsByClassName('settingsAuthAccount')).map((val) => {
  232. const selBtn = val.getElementsByClassName('settingsAuthAccountSelect')[0]
  233. if(uuid === val.getAttribute('uuid')){
  234. selBtn.setAttribute('selected', '')
  235. selBtn.innerHTML = 'Selected Account &#10004;'
  236. } else {
  237. if(selBtn.hasAttribute('selected')){
  238. selBtn.removeAttribute('selected')
  239. }
  240. selBtn.innerHTML = 'Select Account'
  241. }
  242. })
  243. }
  244. /**
  245. * Add auth account elements for each one stored in the authentication database.
  246. */
  247. function populateAuthAccounts(){
  248. const authAccounts = ConfigManager.getAuthAccounts()
  249. const authKeys = Object.keys(authAccounts)
  250. const selectedUUID = ConfigManager.getSelectedAccount().uuid
  251. let authAccountStr = ``
  252. authKeys.map((val) => {
  253. const acc = authAccounts[val]
  254. authAccountStr += `<div class="settingsAuthAccount" uuid="${acc.uuid}">
  255. <div class="settingsAuthAccountLeft">
  256. <img class="settingsAuthAccountImage" alt="${acc.displayName}" src="https://crafatar.com/renders/body/${acc.uuid}?scale=3&default=MHF_Steve&overlay">
  257. </div>
  258. <div class="settingsAuthAccountRight">
  259. <div class="settingsAuthAccountDetails">
  260. <div class="settingsAuthAccountDetailPane">
  261. <div class="settingsAuthAccountDetailTitle">Username</div>
  262. <div class="settingsAuthAccountDetailValue">${acc.displayName}</div>
  263. </div>
  264. <div class="settingsAuthAccountDetailPane">
  265. <div class="settingsAuthAccountDetailTitle">${acc.displayName === acc.username ? 'UUID' : 'Email'}</div>
  266. <div class="settingsAuthAccountDetailValue">${acc.displayName === acc.username ? acc.uuid : acc.username}</div>
  267. </div>
  268. </div>
  269. <div class="settingsAuthAccountActions">
  270. <button class="settingsAuthAccountSelect" ${selectedUUID === acc.uuid ? 'selected>Selected Account &#10004;' : '>Select Account'}</button>
  271. <div class="settingsAuthAccountWrapper">
  272. <button class="settingsAuthAccountLogOut">Log Out</button>
  273. </div>
  274. </div>
  275. </div>
  276. </div>`
  277. })
  278. settingsCurrentAccounts.innerHTML = authAccountStr
  279. }
  280. function prepareAccountsTab() {
  281. populateAuthAccounts()
  282. bindAuthAccountSelect()
  283. bindAuthAccountLogOut()
  284. }
  285. /**
  286. * Minecraft Tab
  287. */
  288. /**
  289. * Disable decimals, negative signs, and scientific notation.
  290. */
  291. settingsGameWidth.addEventListener('keydown', (e) => {
  292. if(/[-\.eE]/.test(e.key)){
  293. e.preventDefault()
  294. }
  295. })
  296. settingsGameHeight.addEventListener('keydown', (e) => {
  297. if(/[-\.eE]/.test(e.key)){
  298. e.preventDefault()
  299. }
  300. })
  301. /**
  302. * Java Tab
  303. */
  304. settingsMaxRAMRange.setAttribute('max', ConfigManager.getAbsoluteMaxRAM())
  305. settingsMaxRAMRange.setAttribute('min', ConfigManager.getAbsoluteMinRAM())
  306. settingsMinRAMRange.setAttribute('max', ConfigManager.getAbsoluteMaxRAM())
  307. settingsMinRAMRange.setAttribute('min', ConfigManager.getAbsoluteMinRAM())
  308. settingsMinRAMRange.onchange = (e) => {
  309. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  310. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  311. if(sMaxV < sMinV){
  312. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  313. updateRangedSlider(settingsMaxRAMRange, sMinV,
  314. (1+(sMinV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  315. }
  316. }
  317. settingsMaxRAMRange.onchange = (e) => {
  318. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  319. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  320. if(sMaxV < sMinV){
  321. e.preventDefault()
  322. }
  323. }
  324. function calculateRangeSliderMeta(v){
  325. const val = {
  326. max: Number(v.getAttribute('max')),
  327. min: Number(v.getAttribute('min')),
  328. step: Number(v.getAttribute('step')),
  329. }
  330. val.ticks = 1+(val.max-val.min)/val.step
  331. val.inc = 100/val.ticks
  332. return val
  333. }
  334. function bindRangeSlider(){
  335. Array.from(document.getElementsByClassName('rangeSlider')).map((v) => {
  336. const track = v.getElementsByClassName('rangeSliderTrack')[0]
  337. const value = v.getAttribute('value')
  338. const sliderMeta = calculateRangeSliderMeta(v)
  339. updateRangedSlider(v, value,
  340. (1+(value-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  341. track.onmousedown = (e) => {
  342. document.onmouseup = (e) => {
  343. document.onmousemove = null
  344. document.onmouseup = null
  345. }
  346. document.onmousemove = (e) => {
  347. const diff = e.pageX - v.offsetLeft - track.offsetWidth/2
  348. if(diff >= 0 && diff <= v.offsetWidth-track.offsetWidth/2){
  349. const perc = (diff/v.offsetWidth)*100
  350. const notch = Number(perc/sliderMeta.inc).toFixed(0)*sliderMeta.inc
  351. if(Math.abs(perc-notch) < sliderMeta.inc/2){
  352. updateRangedSlider(v, sliderMeta.min+(sliderMeta.step*((notch/sliderMeta.inc)-1)), notch)
  353. }
  354. }
  355. }
  356. }
  357. })
  358. }
  359. function updateRangedSlider(element, value, notch){
  360. const oldVal = element.getAttribute('value')
  361. const bar = element.getElementsByClassName('rangeSliderBar')[0]
  362. const track = element.getElementsByClassName('rangeSliderTrack')[0]
  363. element.setAttribute('value', value)
  364. const event = new MouseEvent('change', {
  365. target: element,
  366. type: 'change',
  367. bubbles: false,
  368. cancelable: true
  369. })
  370. let cancelled = !element.dispatchEvent(event)
  371. if(!cancelled){
  372. track.style.left = notch + '%'
  373. bar.style.width = notch + '%'
  374. } else {
  375. element.setAttribute('value', oldVal)
  376. }
  377. }
  378. function prepareJavaTab(){
  379. bindRangeSlider()
  380. }
  381. /**
  382. * Settings preparation functions.
  383. */
  384. /**
  385. * Prepare the entire settings UI.
  386. *
  387. * @param {boolean} first Whether or not it is the first load.
  388. */
  389. function prepareSettings(first = false) {
  390. if(first){
  391. setupSettingsTabs()
  392. initSettingsValidators()
  393. }
  394. initSettingsValues()
  395. prepareAccountsTab()
  396. prepareJavaTab()
  397. }
  398. // Prepare the settings UI on startup.
  399. prepareSettings(true)