Better multi-canvas, but failed to make split settings

This commit is contained in:
Guy Sandler committed 2026-09-29 20:46:26 -07:00
1 parent 902eb5b128
commit a4a4db7fb9
7 files changed
+257 -63

No files matched your search

+2
View File
@@ -32,6 +32,8 @@ chrome.runtime.onInstalled.addListener(function () {
"auto_dark_end": { "hour": "08", "minute": "00" },
"num_assignments": 4,
"custom_domain": [""],
"custom_domain_denied": [],
"auto_detect_disabled": false,
"assignments_done": [],
"dashboard_grades": true,
"assignment_date_format": false,
+120 -39
View File
@@ -757,31 +757,131 @@ function showExampleReminder() {
}
// Canvas detection: if the domain is in the user's list, start normally.
// Otherwise probe it (unless detection was declined for it); an empty list
// auto-adds the first canvas, and with canvases already in the list the user
// is asked once per domain.
isDomainCanvasPage();
function isDomainCanvasPage() {
chrome.storage.sync.get(['custom_domain', 'dark_mode', 'dark_preset', 'device_dark', 'remind'], result => {
chrome.storage.sync.get(['custom_domain', 'custom_domain_denied', 'auto_detect_disabled', 'dark_mode', 'dark_preset', 'device_dark', 'remind'], result => {
options = result;
if (result.custom_domain.length && result.custom_domain[0] !== "") {
for (let i = 0; i < result.custom_domain.length; i++) {
if (domain.includes(result.custom_domain[i])) {
startExtension();
return;
}
}
// if the code reaches this point, its not a canvas page so run the reminders
setTimeout(reminderWatch, 2000);
setInterval(reminderWatch, 60000);
// turn the reminders on/off if the option is changed
chrome.storage.onChanged.addListener((changes) => {
Object.keys(changes).forEach(key => {
if (key === "remind") reminderWatch();
})
})
} else {
setupCustomURL();
const domains = (result.custom_domain || []).filter(d => d && d !== "");
const denied = result.custom_domain_denied || [];
if (domains.some(d => domain.includes(d))) {
startExtension();
return;
}
// not in the list — no prompting/probing if the user turned auto detect
// off, or already said no here; just run reminders
if (result.auto_detect_disabled === true || denied.some(d => domain.includes(d))) {
startReminderMode();
return;
}
detectCanvasPage().then(({ isCanvas, courses }) => {
if (!isCanvas) {
startReminderMode();
return;
}
if (domains.length === 0) {
// first canvas ever — add it automatically (original first-run
// behavior) and reload so the extension starts
addCanvasDomain(courses).then(() => location.reload());
} else {
// at least one canvas already in the list: ask the first time
// this page is seen. Saying no means we never ask again here.
promptAddCanvasDomain(courses);
}
});
});
}
function startReminderMode() {
setTimeout(reminderWatch, 2000);
setInterval(reminderWatch, 60000);
// turn the reminders on/off if the option is changed
chrome.storage.onChanged.addListener((changes) => {
Object.keys(changes).forEach(key => {
if (key === "remind") reminderWatch();
})
})
}
// The courses API only answers on real Canvas installs. Resolves { isCanvas, courses }.
async function detectCanvasPage() {
try {
const courses = await getData(`${domain}/api/v1/courses?${/*enrollment_state=active&*/""}per_page=100`);
if (Array.isArray(courses) && courses.length) {
return { isCanvas: true, courses };
}
console.log("Canvas Refined - this url doesn't seem to be a canvas url (1)");
return { isCanvas: false, courses: null };
} catch (err) {
console.log("Canvas Refined - this url doesn't seem to be a canvas url (2)");
return { isCanvas: false, courses: null };
}
}
// Register the domain in the canvas list. `courses` (from detectCanvasPage) is
// passed to getCards so this school's courses are indexed before the reload,
// exactly like the original first-run flow did.
function addCanvasDomain(courses) {
return getCards(courses).then(() => new Promise(resolve => {
setTimeout(() => {
console.log("Canvas Refined - setting custom domain to " + domain);
chrome.storage.sync.get(["custom_domain"], storage => {
const domains = (storage.custom_domain || []).filter(d => d && d !== "");
domains.push(domain);
// the domain was just accepted — make sure it isn't on the
// "don't ask again" list
chrome.storage.sync.get(["custom_domain_denied"], deniedStorage => {
const denied = (deniedStorage.custom_domain_denied || []).filter(d => !domain.includes(d));
chrome.storage.sync.set({ custom_domain: domains, custom_domain_denied: denied }).then(resolve);
});
});
}, 100);
}));
}
function promptAddCanvasDomain(courses) {
// content scripts run at document_start, so the body may not exist yet
const show = () => showCanvasPrompt(courses);
if (document.body) show();
else document.addEventListener("DOMContentLoaded", show, { once: true });
}
function showCanvasPrompt(courses) {
if (document.getElementById("canvasrefined-domain-prompt-backdrop")) return;
const host = domain.replace(/^https?:\/\//, "");
// modal with a backdrop so the ask is impossible to miss
const backdrop = makeElement("div", document.body, { "id": "canvasrefined-domain-prompt-backdrop" });
const prompt = makeElement("div", backdrop, { "id": "canvasrefined-domain-prompt" });
makeElement("h3", prompt, { "textContent": "New Canvas detected" });
const text = makeElement("p", prompt, {});
text.append("Canvas Refined detected a Canvas page at ");
makeElement("span", text, { "className": "canvasrefined-domain-host", "textContent": host });
text.append(". Add it to your canvas list?");
const actions = makeElement("div", prompt, { "className": "canvasrefined-domain-prompt-actions" });
const yes = makeElement("button", actions, { "textContent": chrome.i18n.getMessage("add_to_list") || "Add to list", "className": "canvasrefined-domain-yes" });
const no = makeElement("button", actions, { "textContent": chrome.i18n.getMessage("no_thanks") || "No thanks", "className": "canvasrefined-domain-no" });
const dismiss = () => backdrop.remove();
yes.addEventListener("click", () => {
dismiss();
addCanvasDomain(courses).then(() => location.reload());
});
no.addEventListener("click", () => {
dismiss();
chrome.storage.sync.get(["custom_domain_denied"], storage => {
const denied = storage.custom_domain_denied || [];
if (!denied.some(d => domain.includes(d))) denied.push(domain);
chrome.storage.sync.set({ custom_domain_denied: denied });
});
startReminderMode();
});
}
@@ -7634,25 +7734,6 @@ function cleanCustomAssignments() {
});
}
function setupCustomURL() {
//let test = getData(`${domain}/api/v1/dashboard/dashboard_cards?include[]=concluded&include[]=term`);
let test = getData(`${domain}/api/v1/courses?${/*enrollment_state=active&*/""}per_page=100`);
test.then(res => {
if (res.length) {
getCards(res).then(() => {
setTimeout(() => {
console.log("Canvas Refined - setting custom domain to " + domain);
chrome.storage.sync.set({ custom_domain: [domain] }).then(location.reload());
}, 100);
});
} else {
console.log("Canvas Refined - this url doesn't seem to be a canvas url (1)");
}
}).catch(err => {
console.log("Canvas Refined - this url doesn't seem to be a canvas url (2)");
});
}
function getGrades() {
if (options.gpa_calc === true || options.dashboard_grades === true) {
grades = getData(`${domain}/api/v1/courses?${/*enrollment_state=active&*/""}include[]=concluded&include[]=total_scores&include[]=computed_current_score&include[]=current_grading_period_scores&per_page=100`);
+89 -19
View File
@@ -29,6 +29,7 @@ const syncedSubOptions = [
"todo_show_scores",
"grade_hover",
"card_letter",
"auto_detect_disabled",
// "hide_completed",
"num_todo_items",
"hover_preview",
@@ -111,6 +112,8 @@ const defaultOptions = {
"auto_dark_end": { "hour": "08", "minute": "00" },
"num_assignments": 4,
"custom_domain": [""],
"custom_domain_denied": [],
"auto_detect_disabled": false,
"assignments_done": [],
"dashboard_grades": false,
"assignment_date_format": false,
@@ -876,8 +879,8 @@ function setupFeatureSearch(menu) {
add({ key: "sub:" + keyIdOf(sub), text, el: sub, action: () => goToMainElement(sub) });
});
// Home: custom Canvas URL
const customDomain = document.querySelector("#customDomain");
// Home: custom Canvas URLs
const customDomain = document.querySelector(".customDomain");
if (customDomain && !shouldSkip(customDomain)) {
const wrap = customDomain.closest(".customDomain");
const label = wrap ? wrap.querySelector("[data-i18n='enter_url']") : null;
@@ -1094,6 +1097,7 @@ function setup() {
"todo_show_scores",
"grade_hover",
"card_letter",
"auto_detect_disabled",
// "hide_completed",
"hover_preview",
"customBackgroundDaily",
@@ -1491,28 +1495,94 @@ function setup() {
}
updateStorageUsage();
// activate custom url input
document.querySelector('#customDomain').addEventListener('input', function () {
let domains = this.value.split(",");
domains.forEach((domain, index) => {
let val = domain.replace(" ", "");
if (val === "") return;
//if (!val.includes("https://") && !val.includes("http://")) val = "https://" + val;
try {
let url = new URL(val);
domains[index] = url.hostname;
// Canvas URL list — each school gets its own text box
const domainListEl = document.querySelector("#custom-domain-list");
const addDomainBtn = document.querySelector("#add-domain-btn");
// Normalize a single entry: a full URL becomes its hostname, anything else
// is kept as typed. Idempotent — rows store bare hostnames
// ("canvas.school.edu"), which fail new URL() without a scheme, so they're
// validated as hostnames instead of re-flagged as invalid on every save.
function sanitizeDomainEntry(val, showAlert = true) {
let trimmed = val.trim().replace(/ /g, "");
if (trimmed === "") return "";
try {
const host = new URL(trimmed).hostname;
if (host) {
clearAlert();
} catch (e) {
domains[index] = val;
displayAlert(true, "The URL you entered appears to be invalid, so it might not work.");
return host;
}
} catch (e) { /* not a full URL — may still be a bare hostname */ }
// strip scheme/path if new URL couldn't parse it, then validate as a hostname
const host = trimmed.replace(/^https?:\/\//i, "").replace(/\/.*$/, "");
if (host && /^[a-z0-9][a-z0-9.-]*$/i.test(host)) {
clearAlert();
return host;
}
if (showAlert) displayAlert(true, "The URL you entered appears to be invalid, so it might not work.");
return trimmed;
}
function saveDomainList() {
const domains = [];
domainListEl.querySelectorAll(".domain-row input").forEach(input => {
const val = sanitizeDomainEntry(input.value);
if (val !== "") domains.push(val);
});
// keep the legacy [""]-when-empty shape the rest of the code expects
chrome.storage.sync.set({ custom_domain: domains.length ? domains : [""] });
}
function makeDomainRow(value) {
const row = document.createElement("div");
row.className = "domain-row";
const input = document.createElement("input");
input.type = "text";
input.placeholder = "canvas.myschool.edu";
input.value = value || "";
input.spellcheck = false;
input.addEventListener("input", saveDomainList);
input.addEventListener("blur", () => {
// normalize what's shown and drop rows left empty
if (input.value.trim() === "") {
if (domainListEl.querySelectorAll(".domain-row").length > 1) row.remove();
} else {
input.value = sanitizeDomainEntry(input.value);
}
saveDomainList();
});
const remove = document.createElement("button");
remove.className = "domain-remove";
remove.type = "button";
remove.textContent = "\u2715";
remove.title = "Remove";
remove.addEventListener("click", () => {
const val = sanitizeDomainEntry(input.value, false);
row.remove();
saveDomainList();
// clear any past "no thanks" for this canvas so the detection
// prompt can ask again if it's visited later
if (val) {
chrome.storage.sync.get(["custom_domain_denied"], storage => {
const denied = (storage.custom_domain_denied || []).filter(d => d !== val);
chrome.storage.sync.set({ custom_domain_denied: denied });
});
}
});
chrome.storage.sync.set({ custom_domain: domains });
row.appendChild(input);
row.appendChild(remove);
return row;
}
chrome.storage.sync.get(["custom_domain"], storage => {
const domains = (storage.custom_domain || []).filter(d => d && d.trim() !== "");
domains.forEach(d => domainListEl.appendChild(makeDomainRow(d)));
});
// setup custom url
chrome.storage.sync.get(["custom_domain"], storage => {
document.querySelector("#customDomain").value = storage.custom_domain ? storage.custom_domain : "";
addDomainBtn.addEventListener("click", () => {
domainListEl.appendChild(makeDomainRow(""));
const rows = domainListEl.querySelectorAll(".domain-row input");
rows[rows.length - 1].focus();
});
// activate import input box