18C / Assignments

// ==UserScript==
// @name        Assignments
// @namespace   CCAU
// @description Automate course copies
// @match       https://*.instructure.com/courses/*/assignments
// @version     0.2.0
// @author      18-carat
// @grant       none
// @license     GPL-3.0-or-later
// ==/UserScript==
"use strict";
(() => {
  // out/assignments.js
  function openMenuItem(g, name) {
    console.log("Deleting group");
    const button = g.querySelector(`.ig-header > .ag-header-controls > div > .al-options > li > a[aria-label='${name}']`);
    button?.click();
  }
  function withOverriddenConfirm(fn) {
    const orig = window.confirm;
    window.confirm = () => true;
    fn();
    window.confirm = orig;
  }
  function isEmpty(g) {
    return g.querySelector(".assignment-list > ul > .no-items") !== null;
  }
  function deleteEmptyGroups() {
    withOverriddenConfirm(() => {
      Array.from(document.querySelectorAll(".assignment_group")).map((e) => e).filter(isEmpty).forEach((g) => openMenuItem(g, "Delete Assignment Group"));
    });
  }
  function addButton() {
    const slot = document.querySelector(".header-bar-right");
    const button = document.createElement("a");
    button.id = "ccau_deleteEmptyAssignmentGroups";
    button.textContent = "Delete Empty Groups";
    button.classList.add("btn");
    button.setAttribute("tabindex", "0");
    button.addEventListener("click", deleteEmptyGroups);
    if (!slot || slot?.innerHTML.includes(button.id)) {
      return;
    }
    slot?.insertAdjacentElement("afterbegin", button);
  }

  // out/ccau.js
  function isAdmin() {
    const adminButton = document.querySelector("#global_nav_accounts_link");
    return adminButton ? true : false;
  }
  function getCourseID() {
    return window.location.href.match(/courses\/(\d+)/)?.[1] ?? "NO_COURSE_ID";
  }
  async function isLiveCourse() {
    const response = await fetch("https://se.instructure.com/api/v1/courses/" + getCourseID());
    const data = await response.json();
    if (!data.start_at) {
      return new Promise((resolve) => resolve(false));
    }
    return new Date(data.start_at) < /* @__PURE__ */ new Date();
  }
  function observeDOM(element, callback) {
    const observer = new MutationObserver(callback);
    observer.observe(element, {
      childList: true
    });
    return observer;
  }

  // out/index.js
  async function main() {
    if (!isAdmin()) {
      throw new Error("Only admins can use CCAU");
    }
    if (await isLiveCourse()) {
      throw new Error("CCAU is disabled in live courses");
    }
    observeDOM(document.body, () => setTimeout(addButton, 1e3));
  }
  main();
})();