Skip to content

Instantly share code, notes, and snippets.

@chcesare
Last active November 9, 2023 21:50
Show Gist options
  • Save chcesare/c086b676927189236e6da7627280d2e1 to your computer and use it in GitHub Desktop.
Save chcesare/c086b676927189236e6da7627280d2e1 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Canvas Formatting
// @namespace http://tampermonkey.net/
// @version 0.6
// @description Canvas formatting
// @author Chas Cesare
// @match https://boisestatecanvas.instructure.com/*
// @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant none
// ==/UserScript==
'use strict';
//Wait for page to load so that iframe is available.
window.addEventListener('load', shortcut);
function shortcut() {
let editorContent;
//Conditionals based on whether editor iframe is on page, assignment, or discussion.
if (document.getElementById('wiki_page_body_ifr')) {
editorContent = document.getElementById('wiki_page_body_ifr').contentDocument.body;
}
else if (document.getElementById('assignment_description_ifr')) {
editorContent = document.getElementById('assignment_description_ifr').contentDocument.body;
}
else if (document.getElementById('discussion-topic-message10_ifr')) {
editorContent = document.getElementById('discussion-topic-message10_ifr').contentDocument.body;
}
else if (document.getElementById('quiz_description_ifr')) {
editorContent = document.getElementById('quiz_description_ifr').contentDocument.body;
}
editorContent.addEventListener('keydown', e => {
if (e.key == 'm' && e.ctrlKey) {
//Remove all br tags before adding new ones
editorContent.querySelectorAll('br').forEach(br => {
br.remove();
});
let paras = editorContent.querySelectorAll('p');
let headingRegex = /(\(H[1-4]\)) *$/;
//This loop matches headers, formats them, and removes indicator text. Also inserts either hr or br before, depending on header location and placement.
for (let para of paras) {
if (para.textContent == '') {
para.remove();
}
let match = headingRegex.exec(para.textContent);
if (match) {
let heading;
if (match[1] == '(H2)') {
heading = document.createElement('H2');
}
else if (match[1] == '(H3)') {
heading = document.createElement('H3');
}
else if (match[1] == '(H4)') {
heading = document.createElement('H4');
}
heading.textContent = para.textContent.slice(0, -match.length - 2);
para.replaceWith(heading);
if (para != paras.item(0)) {
if (heading.nodeName == 'H2') {
let hr = document.createElement('hr');
editorContent.insertBefore(hr, heading);
}
else {
let br = document.createElement('br');
heading.insertBefore(br, heading.firstChild);
}
}
}
}
//Remove all span tags
editorContent.querySelectorAll('span').forEach(spanElmt => {
spanElmt.outerHTML = spanElmt.innerHTML;
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment