From 755b7285aafadbc3661de657bf046912d487a248 Mon Sep 17 00:00:00 2001 From: sethburkart123 Date: Sun, 9 Jun 2024 14:08:04 +1000 Subject: [PATCH] refactor: clean up initialisation logic --- src/SEQTA.ts | 483 +++++++++++++++++++++++---------------------------- 1 file changed, 222 insertions(+), 261 deletions(-) diff --git a/src/SEQTA.ts b/src/SEQTA.ts index 22a6674c..e5cdba23 100644 --- a/src/SEQTA.ts +++ b/src/SEQTA.ts @@ -775,7 +775,6 @@ export async function ObserveMenuItemPosition() { } function main(storedSetting: SettingsState) { - // Handle undefined onoff setting if (typeof storedSetting.onoff === 'undefined') { browser.runtime.sendMessage({ type: 'setDefaultStorage' }) } @@ -797,7 +796,6 @@ function main(storedSetting: SettingsState) { loading() InjectCustomIcons() HideMenuItems() - CheckLoadOnPeriods() tryLoad() window.addEventListener('load', tryLoad) @@ -855,22 +853,6 @@ export function AppendElementsToDisabledPage() { document.head.append(settingsStyle) } -var PageLoaded = false -async function CheckLoadOnPeriods() { - if (!PageLoaded) { - await delay(1000) - var code = document.getElementsByClassName('code')[0] - if (code && !UserInitalCode) { - LoadPageElements() - finishLoad() - PageLoaded = true - } - if (!code) { - CheckLoadOnPeriods() - } - } -} - export function closeSettings() { const ExtensionSettings = document.getElementById('ExtensionPopup')! const ExtensionIframe = document.getElementById('ExtensionIframe') as HTMLIFrameElement @@ -1174,266 +1156,245 @@ function ReplaceMenuSVG(element: HTMLElement, svg: string) { } async function AddBetterSEQTAElements(toggle: any) { - const code = document.getElementsByClassName('code')[0] - // Replaces students code with the version of BetterSEQTA - if (code != null) { - if (!code.innerHTML.includes('BetterSEQTA')) { - UserInitalCode = code.innerHTML - code.innerHTML = `BetterSEQTA+ v${browser.runtime.getManifest().version}` - code.setAttribute('data-hover', 'Click for user code') - code.addEventListener('click', function () { - var code = document.getElementsByClassName('code')[0] - if (code.innerHTML.includes('BetterSEQTA')) { - code.innerHTML = UserInitalCode - code.setAttribute('data-hover', 'Click for BetterSEQTA+ version') - } else { - code.innerHTML = `BetterSEQTA+ v${ - browser.runtime.getManifest().version - }` - code.setAttribute('data-hover', 'Click for user code') - } + if (toggle) { + // Creates Home menu button and appends it as the first child of the list + + const result = await browser.storage.local.get() + + animbkEnable(result) + updateBgDurations(result) + + DarkMode = result.DarkMode + if (DarkMode) { + document.documentElement.classList.add('dark') + } + + const container = document.getElementById('content')! + const div = document.createElement('div') + div.classList.add('titlebar') + container.append(div) + const NewButton = stringToHTML('
  • ') + + const menu = document.getElementById('menu')! + const List = menu.firstChild! as HTMLElement + + if (NewButton.firstChild) { + List.insertBefore(NewButton.firstChild, List.firstChild) + } + + try { + // Fetch the response and wait for it + const response = await fetch(`${location.origin}/seqta/student/login`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json; charset=utf-8', + }, + body: JSON.stringify({ + mode: 'normal', + query: null, + redirect_url: location.origin, + }), }) - if (toggle) { - // Creates Home menu button and appends it as the first child of the list - const result = await browser.storage.local.get() + // Parse the JSON response and wait for it + const responseData = await response.json() + let info = responseData.payload - animbkEnable(result) - updateBgDurations(result) + // Manipulate the DOM as needed + const titlebar = document.getElementsByClassName('titlebar')[0] + const userInfo = stringToHTML( + /* html */` +
    + +
    +
    + ` + ).firstChild + titlebar.append(userInfo!) - DarkMode = result.DarkMode - if (DarkMode) { - document.documentElement.classList.add('dark') - } + const userinfo = stringToHTML(/* html */ + `
    +
    +
    +

    +

    ${info.userDesc}

    +
    +

    ${UserInitalCode}

    +
    +
    `).firstChild + titlebar.append(userinfo!) - const container = document.getElementById('content')! - const div = document.createElement('div') - div.classList.add('titlebar') - container.append(div) - const NewButton = stringToHTML('
  • ') + var logoutbutton = document.getElementsByClassName('logout')[0] + var userInfosvgdiv = document.getElementById('logouttooltip')! + userInfosvgdiv.appendChild(logoutbutton) - const menu = document.getElementById('menu')! - const List = menu.firstChild! as HTMLElement - - if (NewButton.firstChild) { - List.insertBefore(NewButton.firstChild, List.firstChild) - } + // Await the fetch response + const peopleResponse = await fetch(`${location.origin}/seqta/student/load/message/people`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json; charset=utf-8', + }, + body: JSON.stringify({ mode: 'student' }), + }) - try { - // Fetch the response and wait for it - const response = await fetch(`${location.origin}/seqta/student/login`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', - }, - body: JSON.stringify({ - mode: 'normal', - query: null, - redirect_url: location.origin, - }), - }) - - // Parse the JSON response and wait for it - const responseData = await response.json() - let info = responseData.payload - - // Manipulate the DOM as needed - const titlebar = document.getElementsByClassName('titlebar')[0] - const userInfo = stringToHTML( - /* html */` -
    - -
    -
    - ` - ).firstChild - titlebar.append(userInfo!) - - const userinfo = stringToHTML(/* html */ - `
    -
    -
    -

    -

    ${info.userDesc}

    -
    -

    ${UserInitalCode}

    -
    -
    `).firstChild - titlebar.append(userinfo!) - - var logoutbutton = document.getElementsByClassName('logout')[0] - var userInfosvgdiv = document.getElementById('logouttooltip')! - userInfosvgdiv.appendChild(logoutbutton) + // Await the JSON parsing of the response + const peopleResponseData = await peopleResponse.json() + let students = peopleResponseData.payload - // Await the fetch response - const peopleResponse = await fetch(`${location.origin}/seqta/student/load/message/people`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', - }, - body: JSON.stringify({ mode: 'student' }), - }) - - // Await the JSON parsing of the response - const peopleResponseData = await peopleResponse.json() - let students = peopleResponseData.payload - - // Process the students data - var index = students.findIndex(function (person: any) { - return ( - person.firstname == info.userDesc.split(' ')[0] && - person.surname == info.userDesc.split(' ')[1] - ) - }) - - let houseelement1 = document.getElementsByClassName('userInfohouse')[0] - const houseelement = houseelement1 as HTMLElement - if (students[index]?.house) { - if (students[index]?.house_colour) { - houseelement.style.background = students[index].house_colour - try { - let colorresult = GetThresholdOfColor(students[index]?.house_colour) - - houseelement.style.color = colorresult && colorresult > 300 ? 'black' : 'white' - houseelement.innerText = students[index].year + students[index].house - } catch (error) { - houseelement.innerText = students[index].house - } - } - } else { - houseelement.innerText = students[index].year - } - - } catch (error) { - console.error('Error fetching and processing student data:', error) - } - - const NewsButtonStr = '
  • ' - const NewsButton = stringToHTML(NewsButtonStr) - List!.appendChild(NewsButton.firstChild!) - - let a = document.createElement('div') - a.classList.add('icon-cover') - a.id = 'icon-cover' - menu!.appendChild(a) - - const menuCover = document.querySelector('#icon-cover') - menuCover!.addEventListener('click', function () { - location.href = '../#?page=/home' - loadHomePage(); - (document! - .getElementById('menu')! - .firstChild! as HTMLElement).classList.remove('noscroll') - }) - // Creates the home container when the menu button is pressed - const homebutton = document.getElementById('homebutton') - homebutton!.addEventListener('click', function () { - if (!MenuOptionsOpen) { - loadHomePage() - } - }) - - // Creates the news container when the menu button is pressed - const newsbutton = document.getElementById('newsbutton') - newsbutton!.addEventListener('click', function () { - if (!MenuOptionsOpen) { - SendNewsPage() - } - }) - } - - appendBackgroundToUI() - addExtensionSettings() - - // If betterSEQTA+ is enabled, run the code - if (toggle) { - // Creates settings and dashboard buttons next to alerts - let SettingsButton = stringToHTML( - '', + // Process the students data + var index = students.findIndex(function (person: any) { + return ( + person.firstname == info.userDesc.split(' ')[0] && + person.surname == info.userDesc.split(' ')[1] ) - let ContentDiv = document.getElementById('content') - ContentDiv!.append(SettingsButton.firstChild!) + }) - const result: any = await new Promise(resolve => { - const result = browser.storage.local.get() - result.then(resolve, onError) - }) - - const DarkMode = result!.DarkMode - const tooltipString = GetLightDarkModeString(DarkMode) - const svgContent = DarkMode ? '' : - '' - - const LightDarkModeButton = stringToHTML(` - - `) - - ContentDiv!.append(LightDarkModeButton.firstChild!) - - updateAllColors(DarkMode, result.selectedColor) + let houseelement1 = document.getElementsByClassName('userInfohouse')[0] + const houseelement = houseelement1 as HTMLElement + if (students[index]?.house) { + if (students[index]?.house_colour) { + houseelement.style.background = students[index].house_colour + try { + let colorresult = GetThresholdOfColor(students[index]?.house_colour) - document.getElementById('LightDarkModeButton')!.addEventListener('click', async () => { - const result: any = await new Promise(resolve => { - const result = browser.storage.local.get() - result.then(resolve, onError) - }) - - console.log(!settingsState.DarkMode) - settingsState.DarkMode = !settingsState.DarkMode; - - updateAllColors(!settingsState.DarkMode, result.selectedColor) - - const darklightText = document.getElementById('darklighttooliptext') - darklightText!.innerText = GetLightDarkModeString(!settingsState.DarkMode) - }) - - // Locate the menuToggle element - const menuToggle = document.getElementById('menuToggle') - menuToggle!.innerHTML = '' - - // Create three divs to act as lines of the hamburger icon - for (let i = 0; i < 3; i++) { - const line = document.createElement('div') - line.className = 'hamburger-line' - menuToggle!.appendChild(line) + houseelement.style.color = colorresult && colorresult > 300 ? 'black' : 'white' + houseelement.innerText = students[index].year + students[index].house + } catch (error) { + houseelement.innerText = students[index].house + } } } else { - // Creates settings and dashboard buttons next to alerts - let SettingsButton = stringToHTML( - '', - ) - let ContentDiv = document.getElementById('content') - ContentDiv!.append(SettingsButton.firstChild!) + houseelement.innerText = students[index].year } - var AddedSettings = document.getElementById('AddedSettings') - var extensionPopup = document.getElementById('ExtensionPopup') - - AddedSettings!.addEventListener('click', function () { - if (SettingsClicked) { - extensionPopup!.classList.add('hide') - animate( - '#ExtensionPopup', - { opacity: [1, 0], scale: [1, 0] }, - { easing: spring({ stiffness: 220, damping: 18 }) } - ); - (document.getElementById('ExtensionIframe')! as HTMLIFrameElement).contentWindow!.postMessage('popupClosed', '*') - SettingsClicked = false; - } else { - extensionPopup!.classList.remove('hide') - animate( - '#ExtensionPopup', - { opacity: [0, 1], scale: [0, 1] }, - { easing: spring({ stiffness: 260, damping: 24 }) } - ) - SettingsClicked = true - } - }) + } catch (error) { + console.error('Error fetching and processing student data:', error) } + + const NewsButtonStr = '
  • ' + const NewsButton = stringToHTML(NewsButtonStr) + List!.appendChild(NewsButton.firstChild!) + + let a = document.createElement('div') + a.classList.add('icon-cover') + a.id = 'icon-cover' + menu!.appendChild(a) + + const menuCover = document.querySelector('#icon-cover') + menuCover!.addEventListener('click', function () { + location.href = '../#?page=/home' + loadHomePage(); + (document! + .getElementById('menu')! + .firstChild! as HTMLElement).classList.remove('noscroll') + }) + // Creates the home container when the menu button is pressed + const homebutton = document.getElementById('homebutton') + homebutton!.addEventListener('click', function () { + if (!MenuOptionsOpen) { + loadHomePage() + } + }) + + // Creates the news container when the menu button is pressed + const newsbutton = document.getElementById('newsbutton') + newsbutton!.addEventListener('click', function () { + if (!MenuOptionsOpen) { + SendNewsPage() + } + }) } + + appendBackgroundToUI() + addExtensionSettings() + + // If betterSEQTA+ is enabled, run the code + if (toggle) { + // Creates settings and dashboard buttons next to alerts + let SettingsButton = stringToHTML( + '', + ) + let ContentDiv = document.getElementById('content') + ContentDiv!.append(SettingsButton.firstChild!) + + const result: any = await new Promise(resolve => { + const result = browser.storage.local.get() + result.then(resolve, onError) + }) + + const DarkMode = result!.DarkMode + const tooltipString = GetLightDarkModeString(DarkMode) + const svgContent = DarkMode ? '' : + '' + + const LightDarkModeButton = stringToHTML(` + + `) + + ContentDiv!.append(LightDarkModeButton.firstChild!) + + updateAllColors(DarkMode, result.selectedColor) + + document.getElementById('LightDarkModeButton')!.addEventListener('click', async () => { + const result: any = await new Promise(resolve => { + const result = browser.storage.local.get() + result.then(resolve, onError) + }) + + console.log(!settingsState.DarkMode) + settingsState.DarkMode = !settingsState.DarkMode; + + updateAllColors(!settingsState.DarkMode, result.selectedColor) + + const darklightText = document.getElementById('darklighttooliptext') + darklightText!.innerText = GetLightDarkModeString(!settingsState.DarkMode) + }) + + // Locate the menuToggle element + const menuToggle = document.getElementById('menuToggle') + menuToggle!.innerHTML = '' + + // Create three divs to act as lines of the hamburger icon + for (let i = 0; i < 3; i++) { + const line = document.createElement('div') + line.className = 'hamburger-line' + menuToggle!.appendChild(line) + } + } else { + // Creates settings and dashboard buttons next to alerts + let SettingsButton = stringToHTML( + '', + ) + let ContentDiv = document.getElementById('content') + ContentDiv!.append(SettingsButton.firstChild!) + } + + var AddedSettings = document.getElementById('AddedSettings') + var extensionPopup = document.getElementById('ExtensionPopup') + + AddedSettings!.addEventListener('click', function () { + if (SettingsClicked) { + extensionPopup!.classList.add('hide') + animate( + '#ExtensionPopup', + { opacity: [1, 0], scale: [1, 0] }, + { easing: spring({ stiffness: 220, damping: 18 }) } + ); + (document.getElementById('ExtensionIframe')! as HTMLIFrameElement).contentWindow!.postMessage('popupClosed', '*') + SettingsClicked = false; + } else { + extensionPopup!.classList.remove('hide') + animate( + '#ExtensionPopup', + { opacity: [0, 1], scale: [0, 1] }, + { easing: spring({ stiffness: 260, damping: 24 }) } + ) + SettingsClicked = true + } + }) } function GetLightDarkModeString(darkMode: boolean) {