Developing: Custom backgrounds

This commit is contained in:
SethBurkart123
2023-10-08 07:44:26 +11:00
parent 6cd1e59fa7
commit 44025ecfa0
12 changed files with 465 additions and 638 deletions
+3 -3
View File
@@ -4,9 +4,9 @@ import Settings from './pages/Settings';
import logo from './assets/betterseqta-dark-full.png'; import logo from './assets/betterseqta-dark-full.png';
import logoDark from './assets/betterseqta-light-full.png'; import logoDark from './assets/betterseqta-light-full.png';
import Shortcuts from './pages/Shortcuts'; import Shortcuts from './pages/Shortcuts';
import About from './pages/About';
import { useSettingsContext } from './SettingsContext'; import { useSettingsContext } from './SettingsContext';
import Picker from './components/Picker'; import Picker from './components/Picker';
import Themes from './pages/Themes';
const App: React.FC = () => { const App: React.FC = () => {
@@ -30,8 +30,8 @@ const App: React.FC = () => {
content: <Shortcuts /> content: <Shortcuts />
}, },
{ {
title: 'About', title: 'Themes',
content: <About /> content: <Themes />
} }
]; ];
+104
View File
@@ -0,0 +1,104 @@
import React, { useState, useEffect } from 'react';
// IndexedDB utility functions
const openDB = () => {
return new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open('MyDatabase', 1);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
db.createObjectStore('backgrounds', { keyPath: 'id' });
};
});
};
const writeData = async (type: string, data: any) => {
return new Promise((resolve, reject) => {
openDB().then(async db => {
const tx = db.transaction('backgrounds', 'readwrite');
const store = tx.objectStore('backgrounds');
const request = store.put({ id: 'customBackground', type, data });
// Wait for the transaction to complete
await new Promise((res, rej) => {
tx.oncomplete = () => res(request.result);
tx.onerror = () => rej(tx.error);
}).then(resolve, reject);
}).catch(reject);
});
};
const readData = async () => {
const db = await openDB();
const tx = db.transaction('backgrounds', 'readonly');
const store = tx.objectStore('backgrounds');
const request = store.get('customBackground');
return await new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
};
const Themes: React.FC = () => {
const [imageSrc, setImageSrc] = useState<string | null>(null);
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const fileType = 'image';
const reader = new FileReader();
reader.onload = async () => {
const dataURL = reader.result;
await writeData(fileType, dataURL);
setImageSrc(dataURL as string);
};
if (fileType === 'image') {
reader.readAsDataURL(file);
} else {
// Handle video file
}
};
useEffect(() => {
(async () => {
const data = await readData();
if (data?.type === 'image') {
setImageSrc(data.data);
}
})();
}, []);
return (
<div className="flex flex-col overflow-y-scroll divide-y divide-zinc-100/50 dark:divide-zinc-700/50">
<div>
<h2 className="text-lg font-bold">Custom Background</h2>
</div>
<input type="file" onChange={handleFileChange} />
{imageSrc && <img src={imageSrc} alt="Uploaded content" />}
<div>
<h2 className="text-lg font-bold">Themes</h2>
</div>
<div className="grid grid-cols-2 gap-2 py-4">
<button className="flex flex-col items-center justify-center w-full h-32 rounded-md bg-zinc-100 dark:bg-zinc-700">
<h2 className="text-lg font-bold">Light</h2>
</button>
<button className="flex flex-col items-center justify-center w-full h-32 rounded-md bg-zinc-800 dark:bg-zinc-600">
<h2 className="text-lg font-bold">Dark</h2>
</button>
</div>
</div>
);
};
export default Themes;
+81 -529
View File
@@ -10,14 +10,17 @@ import loading, { AppendLoadingSymbol } from "./seqta/ui/Loading.js";
import assessmentsicon from "./seqta/icons/assessmentsIcon.js"; import assessmentsicon from "./seqta/icons/assessmentsIcon.js";
import coursesicon from "./seqta/icons/coursesIcon.js"; import coursesicon from "./seqta/icons/coursesIcon.js";
import StorageListener from "./seqta/utils/StorageListener.js"; import StorageListener from "./seqta/utils/StorageListener.js";
import { updateBgDurations } from "./seqta/ui/Animation.js";
import { updateAllColors } from "./seqta/ui/Colors.js";
import { appendBackgroundToUI } from "./seqta/ui/Background.js";
let isChrome = window.chrome; export let isChrome = window.chrome;
let SettingsClicked = false; let SettingsClicked = false;
let MenuOptionsOpen = false; let MenuOptionsOpen = false;
let UserInitalCode = ""; let UserInitalCode = "";
let currentSelectedDate = new Date(); let currentSelectedDate = new Date();
let LessonInterval; let LessonInterval;
let DarkMode; export let DarkMode;
function delay(ms) { function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
@@ -36,27 +39,7 @@ function animbkEnable(item) {
} }
} }
function bkValues (item) { export function ApplyCSSToHiddenMenuItems() {
const bg = document.getElementsByClassName("bg");
const bg2 = document.getElementsByClassName("bg2");
const bg3 = document.getElementsByClassName("bg3");
const value = 200 - item.bksliderinput; // reverse the slider direction to match the animation direction
if (bg.length == 0 || bg2.length == 0 || bg3.length == 0) return;
const minDuration = 1; // minimum duration in seconds
const maxDuration = 10; // maximum duration in seconds
const durationRange = maxDuration - minDuration;
const bgDuration = minDuration + (value / 200) * durationRange;
const bg2Duration = minDuration + ((value / 200) + 0.05) * durationRange;
const bg3Duration = minDuration + ((value / 200) + 0.1) * durationRange;
bg[0].style.animationDuration = `${bgDuration}s`;
bg2[0].style.animationDuration = `${bg2Duration}s`;
bg3[0].style.animationDuration = `${bg3Duration}s`;
}
function ApplyCSSToHiddenMenuItems() {
var stylesheetInnerText = ""; var stylesheetInnerText = "";
chrome.storage.local.get(null, function (result) { chrome.storage.local.get(null, function (result) {
for (let i = 0; i < Object.keys(result.menuitems).length; i++) { for (let i = 0; i < Object.keys(result.menuitems).length; i++) {
@@ -245,7 +228,7 @@ function RemoveBackground() {
bk3[0].remove(); bk3[0].remove();
} }
function waitForElm(selector) { export function waitForElm(selector) {
return new Promise((resolve) => { return new Promise((resolve) => {
if (document.querySelector(selector)) { if (document.querySelector(selector)) {
return resolve(document.querySelector(selector)); return resolve(document.querySelector(selector));
@@ -518,7 +501,7 @@ function CheckNoticeTextColour(notice) {
}); });
} }
function tryLoad() { export function tryLoad() {
waitForElm(".login").then(() => { waitForElm(".login").then(() => {
finishLoad(); finishLoad();
}); });
@@ -573,7 +556,7 @@ function ChangeMenuItemPositions(storage) {
} }
} }
async function ObserveMenuItemPosition() { export async function ObserveMenuItemPosition() {
chrome.storage.local.get(null, function (result) { chrome.storage.local.get(null, function (result) {
let menuorder = result.menuorder; let menuorder = result.menuorder;
if (menuorder && result.onoff) { if (menuorder && result.onoff) {
@@ -601,7 +584,67 @@ async function ObserveMenuItemPosition() {
}); });
} }
function AppendElementsToDisabledPage() { function main(storedSetting) {
DarkMode = storedSetting.DarkMode;
// If the option is 'on', open BetterSEQTA
if (typeof storedSetting.onoff == "undefined") {
chrome.runtime.sendMessage({ type: "setDefaultStorage" });
}
if (storedSetting.onoff) {
console.log("[BetterSEQTA+] Enabled");
// Injecting CSS File to the webpage to overwrite SEQTA's default CSS
var cssFile = chrome.runtime.getURL("inject/injected.css");
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", cssFile);
document.head.appendChild(fileref);
document.getElementsByTagName("html")[0].appendChild(fileref);
// Injecting custom icons font file
const fontURL = chrome.runtime.getURL("fonts/IconFamily.woff");
const style = document.createElement("style");
style.setAttribute("type", "text/css");
style.innerHTML = `
@font-face {
font-family: 'IconFamily';
src: url('${fontURL}') format('woff');
font-weight: normal;
font-style: normal;
}`;
document.head.appendChild(style);
updateAllColors(storedSetting);
ApplyCSSToHiddenMenuItems();
loading();
CheckLoadOnPeriods();
if (!isChrome || isChrome == "undefined") {
tryLoad();
}
window.addEventListener("load", function () {
tryLoad();
});
} else {
if (!isChrome || isChrome == "undefined") {
waitForElm(".code").then(() => {
AppendElementsToDisabledPage();
});
}
window.addEventListener("load", function () {
waitForElm(".code").then(() => {
AppendElementsToDisabledPage();
});
});
}
}
export function AppendElementsToDisabledPage() {
AddBetterSEQTAElements(false); AddBetterSEQTAElements(false);
let settingsStyle = document.createElement("style"); let settingsStyle = document.createElement("style");
@@ -757,146 +800,6 @@ async function CheckLoadOnPeriods() {
} }
} }
function main(storedSetting) {
DarkMode = storedSetting.DarkMode;
// If the option is 'on', open BetterSEQTA
if (typeof storedSetting.onoff == "undefined") {
chrome.runtime.sendMessage({ type: "setDefaultStorage" });
}
if (storedSetting.onoff) {
console.log("[BetterSEQTA+] Enabled");
// Injecting CSS File to the webpage to overwrite SEQTA's default CSS
var cssFile = chrome.runtime.getURL("inject/injected.css");
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", cssFile);
document.head.appendChild(fileref);
document.getElementsByTagName("html")[0].appendChild(fileref);
// Injecting custom icons font file
const fontURL = chrome.runtime.getURL("fonts/IconFamily.woff");
const style = document.createElement("style");
style.setAttribute("type", "text/css");
style.innerHTML = `
@font-face {
font-family: 'IconFamily';
src: url('${fontURL}') format('woff');
font-weight: normal;
font-style: normal;
}`;
document.head.appendChild(style);
document.documentElement.style.setProperty("--better-sub", "#161616");
document.documentElement.style.setProperty(
"--better-alert-highlight",
"#c61851",
);
if (storedSetting.DarkMode) {
document.documentElement.style.setProperty(
"--background-primary",
"#232323",
);
document.documentElement.style.setProperty(
"--background-secondary",
"#1a1a1a",
);
document.documentElement.style.setProperty("--text-primary", "white");
} else {
try {
document.documentElement.style.setProperty(
"--better-pale",
lightenAndPaleColor(storedSetting.selectedColor),
);
} catch (err) {
console.log(err);
}
document.documentElement.style.setProperty(
"--background-primary",
"#ffffff",
);
document.documentElement.style.setProperty(
"--background-secondary",
"#e5e7eb",
);
document.documentElement.style.setProperty("--text-primary", "black");
}
document.querySelector("link[rel*=\"icon\"]").href =
chrome.runtime.getURL("icons/icon-48.png");
let rbg = GetThresholdofHex(storedSetting.selectedColor);
if (rbg > 210) {
document.documentElement.style.setProperty("--text-color", "black");
document.documentElement.style.setProperty(
"--betterseqta-logo",
`url(${chrome.runtime.getURL("icons/betterseqta-dark-full.png")})`,
);
} else {
document.documentElement.style.setProperty("--text-color", "white");
document.documentElement.style.setProperty(
"--betterseqta-logo",
`url(${chrome.runtime.getURL("icons/betterseqta-light-full.png")})`,
);
}
document.documentElement.style.setProperty(
"--better-main",
storedSetting.selectedColor,
);
if (storedSetting.selectedColor == "#ffffff") {
document.documentElement.style.setProperty("--better-light", "#b7b7b7");
} else {
document.documentElement.style.setProperty(
"--better-light",
ColorLuminance(storedSetting.selectedColor, 0.95),
);
}
ApplyCSSToHiddenMenuItems();
loading();
CheckLoadOnPeriods();
if (!isChrome || isChrome == "undefined") {
tryLoad();
}
window.addEventListener("load", function () {
tryLoad();
});
} else {
if (!isChrome || isChrome == "undefined") {
waitForElm(".code").then(() => {
AppendElementsToDisabledPage();
});
}
window.addEventListener("load", function () {
waitForElm(".code").then(() => {
AppendElementsToDisabledPage();
});
});
}
}
async function CheckForMenuList() {
if (!MenuItemMutation) {
try {
if (document.getElementById("menu").firstChild) {
ObserveMenuItemPosition();
MenuItemMutation = true;
}
} catch (error) {
return;
}
}
}
var MenuItemMutation = false; var MenuItemMutation = false;
var NonSEQTAPage = false; var NonSEQTAPage = false;
var IsSEQTAPage = false; var IsSEQTAPage = false;
@@ -933,361 +836,8 @@ document.addEventListener(
}, },
true, true,
); );
/*
function RunExtensionSettingsJS() {
const whatsnewsettings = document.getElementById("whatsnewsettings");
whatsnewsettings.addEventListener("click", function () {
if (!WhatsNewOpen) {
WhatsNewOpen = true;
OpenWhatsNewPopup();
}
});
const onoffselection = document.querySelector("#onoff");
const notificationcollector = document.querySelector("#notification");
const lessonalert = document.querySelector("#lessonalert");
const aboutsection = document.querySelector("#aboutsection");
const shortcutsection = document.querySelector("#shortcutsection");
const miscsection = document.querySelector("#miscsection");
const colorpicker = document.querySelector("#colorpicker");
const animatedbk = document.querySelector("#animatedbk");
const bkslider = document.querySelector("#bksliderinput");
const customshortcutbutton = document.getElementsByClassName(
"custom-shortcuts-button",
)[0];
const customshortcutdiv = document.getElementsByClassName(
"custom-shortcuts-container",
)[0];
const customshortcutsubmit = document.getElementsByClassName(
"custom-shortcuts-submit",
)[0];
const customshortcutinputname = document.querySelector("#shortcutname");
const customshortcutinputurl = document.querySelector("#shortcuturl");
const shortcutmenuitemselection =
document.getElementsByClassName("menushortcut")[0];
const applybutton = document.querySelector("#applychanges");
const navbuttons = document.getElementsByClassName("navitem");
const menupages = document.getElementsByClassName("menu-page");
const allinputs = document.getElementsByTagName("input");
const menupage = document.querySelector("#menupage");
const shortcutpage = document.querySelector("#shortcutpage");
const miscpage = document.querySelector("#miscpage");
var shortcutbuttons = document.getElementsByClassName("shortcutitem");
var validURL = false;
var validName = false;
function resetActive() {
for (let i = 0; i < navbuttons.length; i++) {
navbuttons[i].classList.remove("activenav");
}
for (let i = 0; i < menupages.length; i++) {
menupages[i].classList.add("hiddenmenu");
}
}
function FindSEQTATab() {
chrome.runtime.sendMessage({ type: "reloadTabs" });
}
// Store the currently selected settings using chrome.storage.local.
function storeSettings() {
chrome.storage.local.set({ onoff: onoffselection.checked }, function () {
FindSEQTATab();
});
}
function storeNotificationSettings() {
chrome.storage.local.set({
notificationcollector: notificationcollector.checked,
});
chrome.storage.local.set({ lessonalert: lessonalert.checked });
chrome.storage.local.set({ animatedbk: animatedbk.checked });
chrome.storage.local.set({ bksliderinput: bkslider.value });
}
function StoreAllSettings() {
chrome.storage.local.get(["shortcuts"], function (result) {
var shortcuts = Object.values(result)[0];
for (var i = 0; i < shortcutbuttons.length; i++) {
shortcuts[i].enabled = shortcutbuttons[i].checked;
}
chrome.storage.local.set({ shortcuts: shortcuts });
});
FindSEQTATab();
}
// Update the options UI with the settings values retrieved from storage,
// or the default settings if the stored settings are empty.
function updateUI(restoredSettings) {
if (typeof restoredSettings.onoff == "undefined") {
chrome.runtime.sendMessage({ type: "setDefaultStorage" });
chrome.storage.local.get(null, function (result) {
updateUI(result);
});
} else {
onoffselection.checked = restoredSettings.onoff;
notificationcollector.checked = restoredSettings.notificationcollector;
lessonalert.checked = restoredSettings.lessonalert;
animatedbk.checked = restoredSettings.animatedbk;
bkslider.value = restoredSettings.bksliderinput;
chrome.storage.local.get(["shortcuts"], function (result) {
var shortcuts = Object.values(result)[0];
for (var i = 0; i < shortcutbuttons.length; i++) {
shortcutbuttons[i].checked = shortcuts[i].enabled;
}
chrome.storage.local.set({ shortcuts: shortcuts });
});
}
}
function CreateShortcutDiv(name) {
let div = stringToHTML(`
<div class="item-container menushortcuts" data-customshortcut="${name}">
<div class="text-container">
<h1 class="addonitem" style="font-size: 8px !important;font-weight: 300;">Custom</h1>
<h1 class="addonitem">${name}</h1>
</div>
<svg id="delete-${name}" style="width:24px;height:24px;margin: 9px;cursor:pointer;" viewBox="0 0 24 24">
<path fill="#ffffff" d="M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,2C6.47,2 2,6.47 2,12C2,17.53 6.47,22 12,22C17.53,22 22,17.53 22,12C22,6.47 17.53,2 12,2M14.59,8L12,10.59L9.41,8L8,9.41L10.59,12L8,14.59L9.41,16L12,13.41L14.59,16L16,14.59L13.41,12L16,9.41L14.59,8Z"></path></svg>
</div>`).firstChild;
shortcutmenuitemselection.append(div);
const deletebutton = document.getElementById(`delete-${name}`);
deletebutton.addEventListener("click", function () {
DeleteCustomShortcut(name);
applybutton.style.left = "4px";
});
}
function AddCustomShortcuts() {
chrome.storage.local.get(["customshortcuts"], function (result) {
var customshortcuts = Object.values(result)[0];
for (let i = 0; i < customshortcuts.length; i++) {
const element = customshortcuts[i];
CreateShortcutDiv(element.name);
}
});
}
function DeleteCustomShortcut(name) {
let item = document.querySelector(`[data-customshortcut="${name}"]`);
item.remove();
chrome.storage.local.get(["customshortcuts"], function (result) {
var customshortcuts = Object.values(result)[0];
for (let i = 0; i < customshortcuts.length; i++) {
if (customshortcuts[i].name == name) {
customshortcuts.splice(i, 1);
}
}
chrome.storage.local.set({ customshortcuts: customshortcuts });
});
}
function CustomShortcutMenu() {
customshortcutinputname.value = "";
customshortcutinputurl.value = "";
validURL = false;
validName = false;
customshortcutsubmit.classList.remove("customshortcut-submit-valid");
if (
customshortcutdiv.classList.contains("custom-shortcuts-container-shown")
) {
customshortcutdiv.classList.remove("custom-shortcuts-container-shown");
} else {
customshortcutdiv.classList.add("custom-shortcuts-container-shown");
}
}
function CreateCustomShortcut() {
const shortcutname = customshortcutinputname.value;
var shortcuturl = customshortcutinputurl.value;
if (!shortcuturl.includes("http")) {
shortcuturl = "https://" + shortcuturl;
}
chrome.storage.local.get(["customshortcuts"], function (result) {
var customshortcuts = Object.values(result)[0];
customshortcuts.push({
name: shortcutname,
url: shortcuturl,
icon: shortcutname[0].toUpperCase(),
});
chrome.storage.local.set({ customshortcuts: customshortcuts });
});
CreateShortcutDiv(shortcutname);
document.getElementsByClassName("shortcut-container")[0].style.display =
"block";
}
chrome.storage.local.get(null, function (result) {
document.getElementsByClassName("clr-field")[0].style.color =
result.selectedColor;
colorpicker.value = result.selectedColor;
updateUI(result);
});
aboutsection.addEventListener("click", () => {
resetActive();
aboutsection.classList.add("activenav");
menupage.classList.remove("hiddenmenu");
});
shortcutsection.addEventListener("click", () => {
resetActive();
shortcutsection.classList.add("activenav");
shortcutpage.classList.remove("hiddenmenu");
});
miscsection.addEventListener("click", () => {
resetActive();
miscsection.classList.add("activenav");
miscpage.classList.remove("hiddenmenu");
});
customshortcutbutton.addEventListener("click", () => {
CustomShortcutMenu();
});
customshortcutsubmit.addEventListener("click", () => {
if (validName && validURL) {
CreateCustomShortcut();
CustomShortcutMenu();
}
});
var sameName = false;
customshortcutinputname.addEventListener("input", function () {
sameName = false;
chrome.storage.local.get(["customshortcuts"], function (result) {
var customshortcuts = Object.values(result)[0];
for (let i = 0; i < customshortcuts.length; i++) {
if (customshortcuts[i].name == customshortcutinputname.value) {
sameName = true;
}
}
if (
customshortcutinputname.value.length > 0 &&
customshortcutinputname.value.length < 22 &&
!sameName
) {
validName = true;
} else {
validName = false;
}
if (validName && validURL) {
customshortcutsubmit.classList.add("customshortcut-submit-valid");
} else {
customshortcutsubmit.classList.remove("customshortcut-submit-valid");
}
});
});
customshortcutinputurl.addEventListener("input", function () {
if (
customshortcutinputurl.value.length > 0 &&
customshortcutinputurl.value.includes(".")
) {
validURL = true;
} else {
validURL = false;
}
if (validName && validURL) {
customshortcutsubmit.classList.add("customshortcut-submit-valid");
} else {
customshortcutsubmit.classList.remove("customshortcut-submit-valid");
}
});
AddCustomShortcuts();
onoffselection.addEventListener("change", storeSettings);
notificationcollector.addEventListener("change", storeNotificationSettings);
lessonalert.addEventListener("change", storeNotificationSettings);
bkslider.addEventListener("change", () => {
storeNotificationSettings();
chrome.storage.local.get(["bksliderinput"]).then(bkValues);
});
animatedbk.addEventListener("change", () => {
storeNotificationSettings();
animbkEnable({ animatedbk: animatedbk.checked });
});
for (let i = 0; i < allinputs.length; i++) {
if (
allinputs[i].id != "colorpicker" &&
allinputs[i].id != "shortcuturl" &&
allinputs[i].id != "shortcutname" &&
allinputs[i].id != "bkslider" &&
allinputs[i].id != "bksliderinput"
) {
allinputs[i].addEventListener("change", () => {
applybutton.style.left = "4px";
});
}
}
applybutton.addEventListener("click", () => {
StoreAllSettings();
applybutton.style.left = "-150px";
});
colorpicker.addEventListener("input", function () {
var colorPreview = document.querySelector("#clr-color-preview");
if (colorPreview.style.color) {
var hex = colorPreview.style.color.split("(")[1].split(")")[0];
hex = hex.split(",");
var b = hex.map(function (x) {
//For each array element
x = parseInt(x).toString(16); //Convert to a base16 string
return x.length == 1 ? "0" + x : x; //Add zero if we get only one character
});
b = "#" + b.join("");
chrome.storage.local.set({ selectedColor: b });
}
});
}*/
function CallExtensionSettings() { function CallExtensionSettings() {
// Injecting CSS File to the webpage to overwrite iFrame default CSS
var cssFile = chrome.runtime.getURL("popup/info.css");
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", cssFile);
document.head.append(fileref);
var jsFile = chrome.runtime.getURL("popup/coloris.js");
fileref = document.createElement("script");
fileref.setAttribute("src", jsFile);
document.head.append(fileref);
cssFile = chrome.runtime.getURL("popup/coloris.css");
fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", cssFile);
document.head.append(fileref);
let Settings = let Settings =
stringToHTML( stringToHTML(
String.raw` String.raw`
@@ -1607,6 +1157,7 @@ function ReplaceMenuSVG(element, svg) {
function AddBetterSEQTAElements(toggle) { function AddBetterSEQTAElements(toggle) {
var code = document.getElementsByClassName("code")[0]; var code = document.getElementsByClassName("code")[0];
appendBackgroundToUI();
// Replaces students code with the version of BetterSEQTA // Replaces students code with the version of BetterSEQTA
if (code != null) { if (code != null) {
if (!code.innerHTML.includes("BetterSEQTA")) { if (!code.innerHTML.includes("BetterSEQTA")) {
@@ -1632,7 +1183,7 @@ function AddBetterSEQTAElements(toggle) {
const sliderVal = chrome.storage.local.get(["bksliderinput"]); const sliderVal = chrome.storage.local.get(["bksliderinput"]);
result.then(animbkEnable); result.then(animbkEnable);
sliderVal.then(bkValues); sliderVal.then(updateBgDurations);
// Load darkmode state // Load darkmode state
chrome.storage.local.get(["DarkMode"], function (result) { chrome.storage.local.get(["DarkMode"], function (result) {
@@ -1776,7 +1327,6 @@ function AddBetterSEQTAElements(toggle) {
} }
CallExtensionSettings(); CallExtensionSettings();
//RunExtensionSettingsJS();
// If betterSEQTA+ is enabled, run the code // If betterSEQTA+ is enabled, run the code
if (toggle) { if (toggle) {
@@ -3098,16 +2648,18 @@ function SendNewsPage() {
}, 8); }, 8);
} }
/* async function CheckForMenuList() {
function EnabledDisabledToBool(input) { if (!MenuItemMutation) {
if (input == "enabled") { try {
return true; if (document.getElementById("menu").firstChild) {
ObserveMenuItemPosition();
MenuItemMutation = true;
}
} catch (error) {
return;
} }
if (input == "disabled") {
return false;
} }
} }
*/
function LoadInit() { function LoadInit() {
console.log("[BetterSEQTA] Started Init"); console.log("[BetterSEQTA] Started Init");
+96 -78
View File
@@ -1,5 +1,7 @@
/*global chrome*/ /*global chrome*/
import { readData, writeData } from "./seqta/utils/IndexedDB.js";
function ReloadSEQTAPages() { function ReloadSEQTAPages() {
chrome.tabs.query({}, function (tabs) { chrome.tabs.query({}, function (tabs) {
for (let tab of tabs) { for (let tab of tabs) {
@@ -10,69 +12,110 @@ function ReloadSEQTAPages() {
}); });
} }
chrome.runtime.onMessage.addListener(function (request) { // Helper function to handle IndexedDB actions
if (request.type == "reloadTabs") { const handleIndexedDBActions = (request) => {
ReloadSEQTAPages(); return new Promise((resolve, reject) => {
} else if (request.type == "githubTab") { console.log("request");
chrome.tabs.create({ if (request.action === "save") {
url: "github.com/SethBurkart123/EvenBetterSEQTA", writeData(request.data.type, request.data.data)
}); .then(() => {
} else if (request.type == "setDefaultStorage") { resolve({ message: "Data saved successfully" });
console.log("setting default values"); })
SetStorageValue(DefaultValues); .catch(reject);
} else if (request.type == "addPermissions") { } else if (request.action === "read") {
if (typeof chrome.declarativeContent != "undefined") { readData()
chrome.declarativeContent.onPageChanged.removeRules( .then(data => {
undefined, resolve(data);
function () {}, })
); .catch(reject);
} else {
reject(new Error("Invalid action type"));
} }
});
};
// Helper function to handle setting permissions
const handleAddPermissions = () => {
if (typeof chrome.declarativeContent !== "undefined") {
chrome.declarativeContent.onPageChanged.removeRules(undefined, () => {});
}
chrome.permissions.request( chrome.permissions.request(
{ permissions: ["declarativeContent"], origins: ["*://*/*"] }, { permissions: ["declarativeContent"], origins: ["*://*/*"] },
function (granted) { (granted) => {
if (granted) { if (granted) {
let rules = [ const rules = [
{ // Define your rules here
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: {
urlContains: "site.seqta.com.au",
schemes: ["https"],
},
}),
],
actions: [
new chrome.declarativeContent.RequestContentScript({
js: ["SEQTA.js"],
}),
],
},
{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: "learn.", schemes: ["https"] },
}),
],
actions: [
new chrome.declarativeContent.RequestContentScript({
js: ["SEQTA.js"],
}),
],
},
]; ];
for (let i = 0; i < rules.length; i++) {
chrome.declarativeContent.onPageChanged.addRules([rules[i]]); rules.forEach(rule => {
chrome.declarativeContent.onPageChanged.addRules([rule]);
});
alert("Permissions granted. Reload SEQTA pages to see changes. If this workaround doesn't work, please contact the developer. It will be an easy fix");
} }
alert(
"Permissions granted. Reload SEQTA pages to see changes. If this workaround doesn't work, please contact the developer. It will be an easy fix",
);
} }
},
); );
};
// Main message listener
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
console.log("Message received in background script", request);
sendResponse({ type: "success" });
switch (request.type) {
case "reloadTabs":
ReloadSEQTAPages();
break;
case "IndexedDB":
handleIndexedDBActions(request, sendResponse);
return true; // This keeps the message channel open for async sendResponse
// eslint-disable-next-line no-unreachable
break;
case "githubTab":
chrome.tabs.create({ url: "github.com/SethBurkart123/EvenBetterSEQTA" });
break;
case "setDefaultStorage":
console.log("Setting default values");
SetStorageValue(DefaultValues);
break;
case "addPermissions":
handleAddPermissions();
break;
case "sendNews":
GetNews(sendResponse);
return true;
// eslint-disable-next-line no-unreachable
break;
default:
console.log("Unknown request type");
} }
}); });
function GetNews(url, sendResponse) { function GetNews(sendResponse) {
// Gets the current date
const date = new Date();
// Formats the current date used send a request for timetable and notices later
const TodayFormatted =
date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
const from =
date.getFullYear() +
"-" +
(date.getMonth() + 1) +
"-" +
(date.getDate() - 1);
console.log(TodayFormatted);
console.log(from);
let url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=17c0da766ba347c89d094449504e3080`;
fetch(url) fetch(url)
.then((result) => result.json()) .then((result) => result.json())
.then((response) => { .then((response) => {
@@ -85,31 +128,6 @@ function GetNews(url, sendResponse) {
}); });
} }
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.type === "sendNews") {
// Gets the current date
const date = new Date();
// Formats the current date used send a request for timetable and notices later
var TodayFormatted =
date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
var from =
date.getFullYear() +
"-" +
(date.getMonth() + 1) +
"-" +
(date.getDate() - 1);
console.log(TodayFormatted);
console.log(from);
var url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=17c0da766ba347c89d094449504e3080`;
GetNews(url, sendResponse);
return true;
}
});
const DefaultValues = { const DefaultValues = {
onoff: true, onoff: true,
animatedbk: true, animatedbk: true,
@@ -241,7 +259,7 @@ function migrateOldStorage() {
} }
} }
// If there's something to update, set the new values in storage // If there"s something to update, set the new values in storage
if (shouldUpdate) { if (shouldUpdate) {
chrome.storage.local.set({ shortcuts: items.shortcuts }, function() { chrome.storage.local.set({ shortcuts: items.shortcuts }, function() {
console.log("Migration completed."); console.log("Migration completed.");
+4
View File
@@ -41,6 +41,10 @@ table th {
background-color: #161616; background-color: #161616;
} }
/* .cke_panel_listItem {
} */
::-webkit-scrollbar { ::-webkit-scrollbar {
width: 10px; width: 10px;
height: 10px; height: 10px;
+11
View File
@@ -1169,6 +1169,17 @@ div > ol:has(.uiFileHandlerWrapper) {
border-radius: 0.5rem; border-radius: 0.5rem;
} }
.cke_panel > iframe {
height: 180px;
background: var(--background-primary);
}
.cke_panel {
border-radius: 1rem;
overflow: hidden;
background: unset;
}
.Avatar__Avatar___gE5kx.Avatar__staff___4gVLs { .Avatar__Avatar___gE5kx.Avatar__staff___4gVLs {
--person-colour: var(--better-light); --person-colour: var(--better-light);
background: var(--person-colour, var(--navy)); background: var(--person-colour, var(--navy));
+6
View File
@@ -20,3 +20,9 @@
height: 590px; height: 590px;
z-index: 20; z-index: 20;
} }
.imageBackground {
width: 100%;
height: 100%;
object-fit: cover;
}
+32
View File
@@ -0,0 +1,32 @@
/**
* Update the background animation durations based on the slider input.
* @param {Object} item - The object containing the bksliderinput property.
* @param {number} [minDuration=1] - The minimum animation duration in seconds.
* @param {number} [maxDuration=10] - The maximum animation duration in seconds.
*/
export function updateBgDurations(item, minDuration = 1, maxDuration = 10) {
// Class names to look for
const bgClasses = ["bg", "bg2", "bg3"];
// Reverse the slider direction to align with the animation
const reversedValue = 200 - item.bksliderinput;
// Range of possible animation durations
const durationRange = maxDuration - minDuration;
// Function to calculate animation duration
const calcDuration = (baseValue, offset = 0) => minDuration + ((baseValue / 200) + offset) * durationRange;
// Iterate through each class name to update its animation duration
bgClasses.forEach((className, index) => {
const elements = document.getElementsByClassName(className);
if (elements.length === 0) {
console.error(`No elements found with class name: ${className}`);
return;
}
const offset = index * 0.05;
const duration = calcDuration(reversedValue, offset);
elements[0].style.animationDuration = `${duration}s`;
});
}
+37
View File
@@ -0,0 +1,37 @@
/* global chrome */
export async function appendBackgroundToUI() {
try {
const response = await new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ type: "IndexedDB" }, (response) => {
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
resolve(response);
});
});
console.log("response:", response);
} catch (error) {
console.log("Error:", error);
}
const mount = document.getElementById("container");
console.log("Starting to append background");
let data;
const response = await chrome.runtime.sendMessage({ type: "IndexedDB" });
data = response;
const imgElement = document.createElement("img");
imgElement.src = data;
imgElement.alt = "Uploaded Image";
imgElement.classList.add("imageBackground");
mount.appendChild(imgElement);
/* if (data) {
continue
} else if (data?.type === "video") {
// Handle video
} */
}
appendBackgroundToUI();
+46 -13
View File
@@ -1,19 +1,52 @@
/* global chrome */ /* global chrome */
import { ColorLuminance, GetThresholdofHex } from "../../SEQTA.js"; import { ColorLuminance, GetThresholdofHex, lightenAndPaleColor } from "../../SEQTA.js";
export function updateDocumentColors(newColor) { // Helper functions
const rbg = GetThresholdofHex(newColor); const setCSSVar = (varName, value) => document.documentElement.style.setProperty(varName, value);
const textColor = rbg > 210 ? "black" : "white"; const getChromeURL = (path) => chrome.runtime.getURL(path);
const logo = `url(${chrome.runtime.getURL( const applyProperties = (props) => Object.entries(props).forEach(([key, value]) => setCSSVar(key, value));
`icons/betterseqta-${textColor === "black" ? "dark" : "light"}-full.png`
)})`;
document.documentElement.style.setProperty("--text-color", textColor); export function updateAllColors(storedSetting, newColor = null) {
document.documentElement.style.setProperty("--betterseqta-logo", logo); // Determine the color to use
document.documentElement.style.setProperty("--better-main", newColor); const selectedColor = newColor || storedSetting.selectedColor;
const DarkMode = storedSetting ? storedSetting.DarkMode : null;
const lightColor = // Common properties, always applied
newColor === "#ffffff" ? "#b7b7b7" : ColorLuminance(newColor, 0.99); const commonProps = {
"--better-sub": "#161616",
"--better-alert-highlight": "#c61851",
"--better-main": selectedColor
};
document.documentElement.style.setProperty("--better-light", lightColor); // Mode-based properties, applied if storedSetting is provided
let modeProps = {};
if (DarkMode !== null) {
modeProps = DarkMode ? {
"--background-primary": "#232323",
"--background-secondary": "#1a1a1a",
"--text-primary": "white"
} : {
"--background-primary": "#ffffff",
"--background-secondary": "#e5e7eb",
"--text-primary": "black",
"--better-pale": lightenAndPaleColor(selectedColor) // Wrap this in try-catch if needed
};
}
// Dynamic properties, always applied
const rgbThreshold = GetThresholdofHex(selectedColor);
const isBright = rgbThreshold > 210;
const dynamicProps = {
"--text-color": isBright ? "black" : "white",
"--betterseqta-logo": `url(${getChromeURL(`icons/betterseqta-${isBright ? "dark" : "light"}-full.png`)})`,
"--better-light": selectedColor === "#ffffff" ? "#b7b7b7" : ColorLuminance(selectedColor, 0.95)
};
// Apply all the properties
applyProperties({ ...commonProps, ...modeProps, ...dynamicProps });
// Set favicon, if storedSetting is provided
if (DarkMode !== null) {
document.querySelector("link[rel*='icon']").href = getChromeURL("icons/icon-48.png");
}
} }
+34
View File
@@ -0,0 +1,34 @@
// IndexedDB utility functions
export const openDB = () => {
return new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open("MyDatabase", 1);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
request.onupgradeneeded = (event) => {
const db = (event.target).result;
db.createObjectStore("backgrounds", { keyPath: "id" });
};
});
};
export const writeData = async (type, data) => {
return new Promise((resolve, reject) => {
openDB().then(db => {
const tx = db.transaction("backgrounds", "readwrite");
const store = tx.objectStore("backgrounds");
const request = store.put({ id: "customBackground", type, data });
tx.oncomplete = () => resolve(request.result);
tx.onerror = () => reject(tx.error);
}).catch(reject);
});
};
export const readData = async () => {
const db = await openDB();
const tx = db.transaction("backgrounds", "readonly");
const store = tx.objectStore("backgrounds");
return store.get("customBackground");
};
+2 -6
View File
@@ -4,7 +4,7 @@ import {
CreateCustomShortcutDiv, CreateCustomShortcutDiv,
RemoveCustomShortcutDiv, RemoveCustomShortcutDiv,
} from "../../SEQTA.js"; } from "../../SEQTA.js";
import { updateDocumentColors } from "../ui/Colors.js"; import { updateAllColors } from "../ui/Colors.js";
export default class StorageListener { export default class StorageListener {
constructor() { constructor() {
@@ -26,11 +26,7 @@ export default class StorageListener {
handleSelectedColorChange(newColor) { handleSelectedColorChange(newColor) {
try { try {
chrome.storage.local.get(["DarkMode"], (result) => { updateAllColors(null, newColor);
if (!result.DarkMode) {
updateDocumentColors(newColor);
}
});
} catch (err) { } catch (err) {
console.error(err); console.error(err);
} }