Gradescope assignment expander

Expands programming exercises with keyboard

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Gradescope assignment expander
// @namespace    https://gist.github.com/isaacl/86d5121ede0eeac3eb6a4016555ad70e
// @version      0.1.8
// @description  Expands programming exercises with keyboard
// @author       Isaac Levy
// @match        *://*.gradescope.com/*
// @grant        none
// @license      MIT
// ==/UserScript==

/* jshint esversion: 6 */
(function() {
    'use strict';
    const UP_CODE = 38;
    const DOWN_CODE = 40;
    const X_CODE = 88; // Cycle through.
    const C_CODE = 67; // Toggle autograder.
    const ALL_CODES = [UP_CODE, DOWN_CODE, X_CODE, C_CODE];

    let expanded = 0;
    let cur_href = window.location.href;

    document.addEventListener('keydown', (e) => {
        if (!ALL_CODES.includes(e.keyCode)) return;
        if (document.activeElement?.tagName === 'TEXTAREA') return;
        if (cur_href !== window.location.href) {
            expanded = 0;
            cur_href = window.location.href;
        }
        const allToggles = document.querySelectorAll('button.fileViewerHeader--toggleButton');
        const numToggles = allToggles.length;
        switch (e.keyCode) {
            case C_CODE:
                const autograderToggle = document.querySelector('div.autograderResultsContainer button')
                if (autograderToggle !== null) autograderToggle.click();
                // Don't mess with programming expansion, return immediately.
                return;
            case DOWN_CODE:
                if (expanded < numToggles - 1) expanded++;
                break;
            case UP_CODE:
                if (expanded > 0) expanded--;
                break;
            case X_CODE:
                if (e.shiftKey) {
                    expanded = (expanded - 1 + numToggles) % numToggles;
                } else {
                    expanded = (expanded + 1) % numToggles;
                }
                break;
        }

        allToggles.forEach((e, i) => {
            const shouldExpand = expanded === i;
            const isExpanded = e.getAttribute('aria-expanded') === 'true';
            if (shouldExpand !== isExpanded) e.click();
        });
    });
})();