major file and function refactoring

This commit is contained in:
SethBurkart123
2023-12-11 07:42:24 +11:00
parent 703e592151
commit ec01eeb1b2
5 changed files with 141 additions and 171 deletions
+2 -2
View File
@@ -12,8 +12,8 @@ const useSettingsState = ({ settingsState, setSettingsState }: SettingsProps) =>
RanOnce = true; RanOnce = true;
// get the current settings state // get the current settings state
// @ts-expect-error idk js/ts wizardry // @ts-expect-error - TODO: Fix this
browser.storage.local.get().then().then(function(result: MainConfig) { browser.storage.local.get().then((result: MainConfig) => {
setSettingsState({ setSettingsState({
notificationCollector: result.notificationcollector, notificationCollector: result.notificationcollector,
lessonAlerts: result.lessonalert, lessonAlerts: result.lessonalert,
+70 -145
View File
@@ -41,6 +41,8 @@ import { updateBgDurations } from './seqta/ui/Animation';
import { updateAllColors } from './seqta/ui/colors/Manager'; import { updateAllColors } from './seqta/ui/colors/Manager';
import { appendBackgroundToUI } from './seqta/ui/ImageBackgrounds'; import { appendBackgroundToUI } from './seqta/ui/ImageBackgrounds';
import { enableCurrentTheme } from './seqta/ui/Themes'; import { enableCurrentTheme } from './seqta/ui/Themes';
import { delay } from "./seqta/utils/delay";
import { SettingsState } from "./types/storage";
declare global { declare global {
interface Window { interface Window {
@@ -62,15 +64,12 @@ var IsSEQTAPage = false;
document.addEventListener( document.addEventListener(
'load', 'load',
function () { async function () {
CheckForMenuList(); CheckForMenuList();
if ( const hasSEQTAText = document.childNodes[1].textContent?.includes('Copyright (c) SEQTA Software');
document.childNodes[1].textContent?.includes( const hasSEQTATitle = document.title.includes('SEQTA Learn');
'Copyright (c) SEQTA Software',
) && if (hasSEQTAText && hasSEQTATitle && !IsSEQTAPage) {
document.title.includes('SEQTA Learn') &&
!IsSEQTAPage
) {
IsSEQTAPage = true; IsSEQTAPage = true;
console.log('[BetterSEQTA+] Verified SEQTA Page'); console.log('[BetterSEQTA+] Verified SEQTA Page');
@@ -78,26 +77,22 @@ document.addEventListener(
document.getElementsByTagName('html')[0].appendChild(link); document.getElementsByTagName('html')[0].appendChild(link);
enableCurrentTheme(); enableCurrentTheme();
const result = browser.storage.local.get() try {
function open (items: any) { const items = await browser.storage.local.get() as SettingsState;
main(items); main(items);
} catch (error: any) {
onError(error);
} }
result.then(open, onError)
} }
if (
!document.childNodes[1].textContent?.includes('SEQTA') && if (!hasSEQTAText && !NonSEQTAPage) {
!NonSEQTAPage
) {
NonSEQTAPage = true; NonSEQTAPage = true;
} }
}, },
true, true,
); );
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function SetDisplayNone(ElementName: string) { function SetDisplayNone(ElementName: string) {
return `li[data-key=${ElementName}]{display:var(--menuHidden) !important; transition: 1s;}`; return `li[data-key=${ElementName}]{display:var(--menuHidden) !important; transition: 1s;}`;
} }
@@ -107,30 +102,28 @@ function animbkEnable(item: any) {
CreateBackground(); CreateBackground();
} else { } else {
RemoveBackground(); RemoveBackground();
// @ts-ignore Element always exists document.getElementById('container')!.style.background = 'var(--background-secondary)';
document.getElementById('container').style.background = 'var(--background-secondary)';
} }
} }
export function ApplyCSSToHiddenMenuItems() { export async function HideMenuItems(): Promise<void> {
var stylesheetInnerText = ''; try {
const result = browser.storage.local.get() const result = await browser.storage.local.get() as SettingsState;
function open (result: any) {
for (let i = 0; i < Object.keys(result.menuitems).length; i++) { let stylesheetInnerText: string = '';
if (!Object.values<any>(result.menuitems)[i].toggle) { for (const [menuItem, { toggle }] of Object.entries(result.menuitems)) {
stylesheetInnerText += SetDisplayNone(Object.keys(result.menuitems)[i]); if (!toggle) {
console.log( stylesheetInnerText += SetDisplayNone(menuItem);
`[BetterSEQTA+] Hiding ${ console.log(`[BetterSEQTA+] Hiding ${menuItem} menu item`);
Object.keys(result.menuitems)[i]
} menu item`,
);
} }
} }
let MenuItemStyle = document.createElement('style');
MenuItemStyle.innerText = stylesheetInnerText; const menuItemStyle: HTMLStyleElement = document.createElement('style');
document.head.appendChild(MenuItemStyle); menuItemStyle.innerText = stylesheetInnerText;
document.head.appendChild(menuItemStyle);
} catch (error) {
console.error("An error occurred:", error);
} }
result.then(open, onError)
} }
function OpenWhatsNewPopup() { function OpenWhatsNewPopup() {
@@ -438,7 +431,7 @@ function CheckiFrameItems() {
mutation.addedNodes.forEach(function (added_node) { mutation.addedNodes.forEach(function (added_node) {
const node = added_node as HTMLElement const node = added_node as HTMLElement
if (node.tagName == 'IFRAME') { if (node.tagName == 'IFRAME') {
const result = browser.storage.local.get('DarkMode'); const result = browser.storage.local.get('DarkMode') as Promise<SettingsState>;
function open (result: any) { function open (result: any) {
DarkMode = result.DarkMode; DarkMode = result.DarkMode;
const node = added_node as HTMLIFrameElement const node = added_node as HTMLIFrameElement
@@ -505,8 +498,9 @@ function SortMessagePageItems(messagesParentElement: any) {
'MessageList__MessageList___3DxoC', 'MessageList__MessageList___3DxoC',
)[0].firstChild as HTMLElement; )[0].firstChild as HTMLElement;
header.append(filterbutton); header.append(filterbutton);
messagesParentElement
const observer = new MutationObserver(function (mutations_list) { /* const observer = new MutationObserver(function (mutations_list) {
mutations_list.forEach(function (mutation) { mutations_list.forEach(function (mutation) {
mutation.addedNodes.forEach(function (added_node) { mutation.addedNodes.forEach(function (added_node) {
const node = added_node as HTMLElement const node = added_node as HTMLElement
@@ -520,56 +514,47 @@ function SortMessagePageItems(messagesParentElement: any) {
observer.observe(messagesParentElement, { observer.observe(messagesParentElement, {
subtree: true, subtree: true,
childList: true, childList: true,
}); }); */
} }
async function LoadPageElements() { async function LoadPageElements(): Promise<void> {
await AddBetterSEQTAElements(true); await AddBetterSEQTAElements(true);
var sublink = window.location.href.split('/')[4]; const sublink: string | undefined = window.location.href.split('/')[4];
switch (sublink) {
case 'news': {
console.log('[BetterSEQTA+] Started Init');
const result = browser.storage.local.get()
function open (result: any) {
if (result.onoff) {
SendNewsPage();
// Sends similar HTTP Post Request for the notices async function handleNewsPage(): Promise<void> {
const result = browser.storage.local.get() console.log('[BetterSEQTA+] Started Init');
function open (result: any) { const settings: SettingsState = await browser.storage.local.get() as SettingsState;
if (result.notificationcollector) { if (settings.onoff) {
SendNewsPage();
const notificationSettings: SettingsState = await browser.storage.local.get() as SettingsState;
if (notificationSettings.notificationcollector) {
enableNotificationCollector(); enableNotificationCollector();
} }
}
result.then(open, onError)
finishLoad(); finishLoad();
} }
} }
result.then(open, onError)
break; async function handleDefault(): Promise<void> {
finishLoad();
const settings: SettingsState = await browser.storage.local.get() as SettingsState;
if (settings.notificationcollector) {
enableNotificationCollector();
} }
case 'home': }
window.location.replace(`${location.origin}/#?page=/home`);
LoadInit(); switch (sublink) {
case 'news':
await handleNewsPage();
break; break;
case 'home':
case undefined: case undefined:
window.location.replace(`${location.origin}/#?page=/home`); window.location.replace(`${location.origin}/#?page=/home`);
LoadInit(); LoadInit();
break; break;
default: { default:
finishLoad(); await handleDefault();
// Sends similar HTTP Post Request for the notices
const result1 = browser.storage.local.get()
function open1(result: any) {
if (result.notificationcollector) {
enableNotificationCollector();
}
}
result1.then(open1, onError)
break; break;
} }
}
const observer = new MutationObserver(function (mutations_list) { const observer = new MutationObserver(function (mutations_list) {
mutations_list.forEach(function (mutation) { mutations_list.forEach(function (mutation) {
@@ -580,65 +565,8 @@ async function LoadPageElements() {
element.innerText = 'Direct Messages'; element.innerText = 'Direct Messages';
document.title = 'Direct Messages ― SEQTA Learn'; document.title = 'Direct Messages ― SEQTA Learn';
SortMessagePageItems(added_node); SortMessagePageItems(added_node);
waitForElm('[data-message]').then(() => {
animate(
'[data-message]',
{ opacity: [0, 1], y: [10, 0] },
{
delay: stagger(0.05),
duration: 0.5,
easing: [.22, .03, .26, 1]
}
);
});
} else if (node.classList.contains('notices')) { } else if (node.classList.contains('notices')) {
CheckNoticeTextColour(added_node); CheckNoticeTextColour(added_node);
} else if (node.classList.contains('dashboard')) {
let ranOnce = false;
waitForElm('.dashlet').then(() => {
if (ranOnce) return;
ranOnce = true;
animate(
'.dashboard > *',
{ opacity: [0, 1], y: [10, 0] },
{
delay: stagger(0.1),
duration: 0.5,
easing: [.22, .03, .26, 1]
}
);
});
} else if (node.classList.contains('documents')) {
let ranOnce = false;
waitForElm('.document').then(() => {
if (ranOnce) return;
ranOnce = true;
animate(
'.documents tbody tr.document',
{ opacity: [0, 1], y: [10, 0] },
{
delay: stagger(0.05),
duration: 0.5,
easing: [.22, .03, .26, 1]
}
);
});
} else if (node.classList.contains('reports')) {
let ranOnce = false;
waitForElm('.report').then(() => {
if (ranOnce) return;
ranOnce = true;
animate(
'.reports .item',
{ opacity: [0, 1], y: [10, 0] },
{
delay: stagger(0.05, { start: 0.2 }),
duration: 0.5,
easing: [.22, .03, .26, 1]
}
);
});
} }
}); });
}); });
@@ -773,31 +701,28 @@ export async function ObserveMenuItemPosition() {
result.then(open, onError) result.then(open, onError)
} }
function main(storedSetting: any) { function main(storedSetting: SettingsState) {
const onoff = storedSetting.onoff;
DarkMode = storedSetting.DarkMode;
// Handle undefined onoff setting // Handle undefined onoff setting
if (typeof onoff === 'undefined') { if (typeof storedSetting.onoff === 'undefined') {
browser.runtime.sendMessage({ type: 'setDefaultStorage' }); browser.runtime.sendMessage({ type: 'setDefaultStorage' });
} }
const initialize = () => {
InjectStyles();
InjectCustomIcons();
updateAllColors(storedSetting);
ApplyCSSToHiddenMenuItems();
loading();
CheckLoadOnPeriods();
};
const handleDisabled = () => { const handleDisabled = () => {
waitForElm('.code').then(AppendElementsToDisabledPage); waitForElm('.code').then(AppendElementsToDisabledPage);
}; };
if (onoff) { if (storedSetting.DarkMode) {
console.log('[BetterSEQTA+] Enabled'); console.log('[BetterSEQTA+] Enabled');
initialize(); if (DarkMode) {
document.documentElement.classList.add('dark');
}
InjectStyles();
InjectCustomIcons();
loading();
updateAllColors(storedSetting);
HideMenuItems();
CheckLoadOnPeriods();
tryLoad(); tryLoad();
window.addEventListener('load', tryLoad); window.addEventListener('load', tryLoad);
+7 -14
View File
@@ -2,7 +2,7 @@ import browser from 'webextension-polyfill'
import { GetThresholdOfColor, GetCSSElement } from '../../../SEQTA'; import { GetThresholdOfColor, GetCSSElement } from '../../../SEQTA';
import { lightenAndPaleColor } from './lightenAndPaleColor'; import { lightenAndPaleColor } from './lightenAndPaleColor';
import ColorLuminance from './ColorLuminance'; import ColorLuminance from './ColorLuminance';
import { onError } from '../../utils/onError'; import { SettingsState } from '../../../types/storage';
// Helper functions // Helper functions
const setCSSVar = (varName: any, value: any) => document.documentElement.style.setProperty(varName, value); const setCSSVar = (varName: any, value: any) => document.documentElement.style.setProperty(varName, value);
@@ -76,9 +76,6 @@ export function updateAllColors(storedSetting: any, newColor = null) {
continue; continue;
} }
console.log(element);
console.log(element.contentDocument!.documentElement);
(element.contentDocument!.documentElement.childNodes[1] as HTMLIFrameElement).style.color = (element.contentDocument!.documentElement.childNodes[1] as HTMLIFrameElement).style.color =
DarkMode ? 'white' : 'black'; DarkMode ? 'white' : 'black';
element.contentDocument!.documentElement.firstChild!.appendChild( element.contentDocument!.documentElement.firstChild!.appendChild(
@@ -87,15 +84,11 @@ export function updateAllColors(storedSetting: any, newColor = null) {
} }
} }
export function getDarkMode() { export async function getDarkMode() {
return new Promise((resolve, reject) => { try {
const result = browser.storage.local.get('DarkMode') const result = await browser.storage.local.get() as SettingsState;
function open (result: any) { return result.DarkMode;
if (browser.runtime.lastError) { } catch (error) {
return reject(browser.runtime.lastError); throw error;
} }
resolve(result.DarkMode);
}
result.then(open, onError)
});
} }
+3
View File
@@ -0,0 +1,3 @@
export function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+49
View File
@@ -0,0 +1,49 @@
export interface SettingsState {
DarkMode: boolean;
animatedbk: boolean;
bksliderinput: string;
customshortcuts: CustomShortcut[];
defaultmenuorder: any[];
lessonalert: boolean;
menuitems: {
assessments: ToggleItem;
courses: ToggleItem;
dashboard: ToggleItem;
documents: ToggleItem;
forums: ToggleItem;
goals: ToggleItem;
home: ToggleItem;
messages: ToggleItem;
myed: ToggleItem;
news: ToggleItem;
notices: ToggleItem;
portals: ToggleItem;
reports: ToggleItem;
settings: ToggleItem;
timetable: ToggleItem;
welcome: ToggleItem;
};
menuorder: any[];
notificationcollector: boolean;
telemetry: boolean;
onoff: boolean;
selectedColor: string;
shortcuts: Shortcut[];
subjectfilters: Record<string, any>;
transparencyEffects: boolean;
}
interface ToggleItem {
toggle: boolean;
}
interface Shortcut {
enabled: boolean;
name: string;
}
export interface CustomShortcut {
name: string;
url: string;
icon: string;
}