Skip to content

Commit

Permalink
Apply prettier to all JavaScript, style, and HTML files in htdocs.
Browse files Browse the repository at this point in the history
  • Loading branch information
drgrice1 committed Feb 19, 2024
1 parent 017733e commit 3f74166
Show file tree
Hide file tree
Showing 31 changed files with 2,300 additions and 1,867 deletions.
1 change: 0 additions & 1 deletion htdocs/css/rtl.css
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,3 @@
/* The changes which were needed here in WeBWorK 2.16 are no
* longer needed in WeBWorK 2.17. The file is being retained
* for potential future use. */

85 changes: 49 additions & 36 deletions htdocs/generate-assets.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ const rtlcss = require('rtlcss');
const cssMinify = require('cssnano');

const argv = yargs
.usage('$0 Options').version(false).alias('help', 'h').wrap(100)
.usage('$0 Options')
.version(false)
.alias('help', 'h')
.wrap(100)
.option('enable-sourcemaps', {
alias: 's',
description: 'Generate source maps. (Not for use in production!)',
Expand All @@ -30,8 +33,7 @@ const argv = yargs
alias: 'd',
description: 'Delete all generated files.',
type: 'boolean'
})
.argv;
}).argv;

const assetFile = path.resolve(__dirname, 'static-assets.json');
const assets = {};
Expand All @@ -48,7 +50,7 @@ const cleanDir = (dir) => {
}
}
}
}
};

// The is set to true after all files are processed for the first time.
let ready = false;
Expand All @@ -75,12 +77,13 @@ const processFile = async (file, _details) => {
return;
}

const minJS = result.code + (
argv.enableSourcemaps && result.map
? `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${
Buffer.from(result.map).toString('base64')}`
: ''
);
const minJS =
result.code +
(argv.enableSourcemaps && result.map
? `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(
result.map
).toString('base64')}`
: '');

const contentHash = crypto.createHash('sha256');
contentHash.update(minJS);
Expand Down Expand Up @@ -114,18 +117,19 @@ const processFile = async (file, _details) => {
return;
}

if (result.sourceMap) result.sourceMap.sources = [ baseName ];
if (result.sourceMap) result.sourceMap.sources = [baseName];

// Pass the compiled css through the autoprefixer.
// This is really only needed for the bootstrap.css files, but doesn't hurt for the rest.
let prefixedResult = await postcss([autoprefixer, cssMinify]).process(result.css, { from: baseName });

const minCSS = prefixedResult.css + (
argv.enableSourcemaps && result.sourceMap
? `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${
Buffer.from(JSON.stringify(result.sourceMap)).toString('base64')}*/`
: ''
);
const minCSS =
prefixedResult.css +
(argv.enableSourcemaps && result.sourceMap
? `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(
JSON.stringify(result.sourceMap)
).toString('base64')}*/`
: '');

const contentHash = crypto.createHash('sha256');
contentHash.update(minCSS);
Expand All @@ -149,18 +153,21 @@ const processFile = async (file, _details) => {
// Pass the compiled css through rtlcss and autoprefixer to generate css for right-to-left languages.
let rtlResult = await postcss([rtlcss, autoprefixer, cssMinify]).process(result.css, { from: baseName });

const rtlCSS = rtlResult.css + (
argv.enableSourcemaps && result.sourceMap
? `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${
Buffer.from(JSON.stringify(result.sourceMap)).toString('base64')}*/`
: ''
);
const rtlCSS =
rtlResult.css +
(argv.enableSourcemaps && result.sourceMap
? `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(
JSON.stringify(result.sourceMap)
).toString('base64')}*/`
: '');

const rtlContentHash = crypto.createHash('sha256');
rtlContentHash.update(rtlCSS);

const newRTLVersion = file.replace(/\.s?css$/,
`.rtl.${rtlContentHash.digest('hex').substring(0, 8)}.min.css`);
const newRTLVersion = file.replace(
/\.s?css$/,
`.rtl.${rtlContentHash.digest('hex').substring(0, 8)}.min.css`
);
fs.writeFileSync(path.resolve(__dirname, newRTLVersion), rtlCSS);

const rtlAssetName = file.replace(/\.s?css$/, '.rtl.css');
Expand All @@ -180,8 +187,9 @@ const processFile = async (file, _details) => {
}
} else {
if (argv.watchFiles)
console.log('\x1b[33mWatches established, and initial build complete.\n'
+ 'Press Control-C to stop.\x1b[0m');
console.log(
'\x1b[33mWatches established, and initial build complete.\n' + 'Press Control-C to stop.\x1b[0m'
);
ready = true;
}

Expand All @@ -202,20 +210,25 @@ for (const file of fs.readdirSync(themesDir, { withFileTypes: true })) {
if (!file.isDirectory()) continue;
if (!fs.existsSync(path.resolve(themesDir, file.name, 'math4-overrides.js')))
fs.closeSync(fs.openSync(path.resolve(themesDir, file.name, 'math4-overrides.js'), 'w'));
if (!fs.existsSync(path.resolve(themesDir, file.name, 'math4-overrides.css'))
&& !fs.existsSync(path.resolve(themesDir, file.name, 'math4-overrides.scss')))
if (
!fs.existsSync(path.resolve(themesDir, file.name, 'math4-overrides.css')) &&
!fs.existsSync(path.resolve(themesDir, file.name, 'math4-overrides.scss'))
)
fs.closeSync(fs.openSync(path.resolve(themesDir, file.name, 'math4-overrides.css'), 'w'));
}

// Set up the watcher.
if (argv.watchFiles) console.log('\x1b[32mEstablishing watches and performing initial build.\x1b[0m');
chokidar.watch(['js', 'themes'], {
ignored: /layouts|\.min\.(js|css)$/,
cwd: __dirname, // Make sure all paths are given relative to the htdocs directory.
awaitWriteFinish: { stabilityThreshold: 500 },
persistent: argv.watchFiles ? true : false
})
.on('add', processFile).on('change', processFile).on('ready', processFile)
chokidar
.watch(['js', 'themes'], {
ignored: /layouts|\.min\.(js|css)$/,
cwd: __dirname, // Make sure all paths are given relative to the htdocs directory.
awaitWriteFinish: { stabilityThreshold: 500 },
persistent: argv.watchFiles ? true : false
})
.on('add', processFile)
.on('change', processFile)
.on('ready', processFile)
.on('unlink', (file) => {
// If a file is deleted, then also delete the corresponding generated file.
if (assets[file]) {
Expand Down
8 changes: 3 additions & 5 deletions htdocs/index.dist.html
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en" dir="ltr">
<head>
<title>WeBWorK Placeholder Page</title>
</head>
<body>
<h1>WeBWorK Placeholder Page</h1>
<p>Exploring?</p>
<p>
This is the default page for the root url of this site.
</p>
<p>This is the default page for the root url of this site.</p>
<p>
If you want to see something better here, then copy webwork2/htdocs/index.dist.html (this file) to
webwork/htdocs/index.html, and modify it to show what you want to show. Then that file will be displayed
webwork/htdocs/index.html, and modify it to show what you want to show. Then that file will be displayed
instead.
</p>
<p>
Expand Down
10 changes: 5 additions & 5 deletions htdocs/js/DatePicker/datepicker.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@
// Compute the time difference between the current browser timezone and the course timezone.
// flatpickr gives the time in the browser's timezone, and this is used to adjust to the course timezone.
// Note that this is in seconds.
const timezoneAdjustment = (
(new Date((new Date).toLocaleString('en-US'))).getTime() -
(new Date((new Date).toLocaleString('en-US',
{ timeZone: rule.dataset.timezone ?? 'America/New_York' }))).getTime()
);
const timezoneAdjustment =
new Date(new Date().toLocaleString('en-US')).getTime() -
new Date(
new Date().toLocaleString('en-US', { timeZone: rule.dataset.timezone ?? 'America/New_York' })
).getTime();

const fp = flatpickr(rule.parentNode, {
allowInput: true,
Expand Down
60 changes: 41 additions & 19 deletions htdocs/js/GatewayQuiz/gateway.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
const timerDiv = document.getElementById('gwTimer'); // The timer div element
let actuallySubmit = false; // This needs to be set to true to allow an actual submission.
// The 'Grade Test' submit button.
const submitAnswers = document.gwquiz.elements.submitAnswers instanceof NodeList
? document.gwquiz.elements.submitAnswers[document.gwquiz.elements.submitAnswers.length - 1]
: document.gwquiz.elements.submitAnswers;
const submitAnswers =
document.gwquiz.elements.submitAnswers instanceof NodeList
? document.gwquiz.elements.submitAnswers[document.gwquiz.elements.submitAnswers.length - 1]
: document.gwquiz.elements.submitAnswers;
let timeDelta; // The difference between the browser time and the server time
let serverDueTime; // The time the test is due
let gracePeriod; // The grace period
Expand All @@ -32,7 +33,14 @@
const alertToast = (message, delay = 5000) => {
const toastContainer = document.createElement('div');
toastContainer.classList.add(
'gwAlert', 'toast-container', 'position-fixed', 'top-0', 'start-50', 'translate-middle-x', 'p-3');
'gwAlert',
'toast-container',
'position-fixed',
'top-0',
'start-50',
'translate-middle-x',
'p-3'
);
toastContainer.innerHTML =
'<div class="toast bg-white" role="alert" aria-live="assertive" aria-atomic="true">' +
'<div class="toast-header">' +
Expand All @@ -43,7 +51,10 @@
'</div>';
document.body.prepend(toastContainer);
const bsToast = new bootstrap.Toast(toastContainer.firstElementChild, { delay });
toastContainer.addEventListener('hidden.bs.toast', () => { bsToast.dispose(); toastContainer.remove(); })
toastContainer.addEventListener('hidden.bs.toast', () => {
bsToast.dispose();
toastContainer.remove();
});
bsToast.show();
};

Expand Down Expand Up @@ -72,23 +83,29 @@
submitAnswers.click();
} else if (remainingTime > 10 - gracePeriod && remainingTime <= 0) {
if (alertStatus !== '1') {
alertToast(timerDiv.dataset.alertOne ??
'<div>You are out of time!</div><div>Press "Grade Test" now!</div>',
(remainingTime + gracePeriod) * 1000);
alertToast(
timerDiv.dataset.alertOne ??
'<div>You are out of time!</div><div>Press "Grade Test" now!</div>',
(remainingTime + gracePeriod) * 1000
);
sessionStorage.setItem('gatewayAlertStatus', '1');
}
} else if (remainingTime > 0 && remainingTime <= 45) {
if (alertStatus !== '2') {
alertToast(timerDiv.dataset.alertTwo ??
'<div>You have less than 45 seconds left!</div><div>Press "Grade Test" soon!</div>',
remainingTime * 1000);
alertToast(
timerDiv.dataset.alertTwo ??
'<div>You have less than 45 seconds left!</div><div>Press "Grade Test" soon!</div>',
remainingTime * 1000
);
sessionStorage.setItem('gatewayAlertStatus', '2');
}
} else if (remainingTime > 45 && remainingTime <= 90) {
if (alertStatus !== '3') {
alertToast(timerDiv.dataset.alertThree ??
'You have less than 90 seconds left to complete this assignment. You should finish it soon!',
(remainingTime - 45) * 1000);
alertToast(
timerDiv.dataset.alertThree ??
'You have less than 90 seconds left to complete this assignment. You should finish it soon!',
(remainingTime - 45) * 1000
);
sessionStorage.setItem('gatewayAlertStatus', '3');
}
}
Expand Down Expand Up @@ -122,15 +139,17 @@
setInterval(updateTimer, 1000);
}
}
};
}

// Show a confirmation dialog when a student clicks 'Grade Test'.
if (typeof submitAnswers?.dataset?.confirmDialogMessage !== 'undefined') {
submitAnswers.addEventListener('click', (evt) => {
// Don't show the dialog if the test is timed and in the last 90 seconds.
// The alerts above are now being shown telling the student to submit the test.
if (typeof serverDueTime !== 'undefined' &&
serverDueTime - Math.round(new Date().getTime() / 1000) + timeDelta < 90)
if (
typeof serverDueTime !== 'undefined' &&
serverDueTime - Math.round(new Date().getTime() / 1000) + timeDelta < 90
)
return;

if (actuallySubmit) return;
Expand Down Expand Up @@ -196,7 +215,10 @@

const bsModal = new bootstrap.Modal(modal);
bsModal.show();
modal.addEventListener('hidden.bs.modal', () => { bsModal.dispose(); modal.remove(); });
modal.addEventListener('hidden.bs.modal', () => {
bsModal.dispose();
modal.remove();
});
});
}

Expand All @@ -214,7 +236,7 @@
document.querySelectorAll('.problem-jump-link').forEach((jumpLink) => {
jumpLink.addEventListener('click', (evt) => {
// Prevent the link from being followed.
evt.preventDefault()
evt.preventDefault();
if (jumpLink.dataset.problemNumber) {
// Note that the anchor indexing starts at 0, not 1.
const problem = document.getElementById(`prob${parseInt(jumpLink.dataset.problemNumber) - 1}`);
Expand Down
22 changes: 14 additions & 8 deletions htdocs/js/InstructorTools/instructortools.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,27 @@
const form = document.forms['instructor-tools-form'];

form?.addEventListener('submit', (e) => {
const selectedUsers = Array.from(document.querySelector('select[name=selected_users]')?.options ?? [])
.filter((option) => option.selected);
const selectedSets = Array.from(document.querySelector('select[name=selected_sets]')?.options ?? [])
.filter((option) => option.selected);
const selectedUsers = Array.from(document.querySelector('select[name=selected_users]')?.options ?? []).filter(
(option) => option.selected
);
const selectedSets = Array.from(document.querySelector('select[name=selected_sets]')?.options ?? []).filter(
(option) => option.selected
);

// Check for the neccessary data for the requested module.
// Show a message and prevent submission if it is missing.
const messages = [];

if ((e.submitter.dataset.usersNeeded === 'at least one' && !selectedUsers.length) ||
(e.submitter.dataset.usersNeeded === 'exactly one' && selectedUsers.length !== 1))
if (
(e.submitter.dataset.usersNeeded === 'at least one' && !selectedUsers.length) ||
(e.submitter.dataset.usersNeeded === 'exactly one' && selectedUsers.length !== 1)
)
messages.push(e.submitter.dataset.errorUsers);
if ((e.submitter.dataset.setsNeeded === 'at least one' && !selectedSets.length) ||
if (
(e.submitter.dataset.setsNeeded === 'at least one' && !selectedSets.length) ||
(e.submitter.dataset.setsNeeded === 'exactly one' && selectedSets.length !== 1) ||
(e.submitter.dataset.setsNeeded === 'at most one' && selectedSets.length > 1))
(e.submitter.dataset.setsNeeded === 'at most one' && selectedSets.length > 1)
)
messages.push(e.submitter.dataset.errorSets);
if (e.submitter.dataset.setNameNeeded) {
const newSetName = form.querySelector('input[name="new_set_name"]')?.value ?? '';
Expand Down
5 changes: 3 additions & 2 deletions htdocs/js/LocalStorage/localstorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
const container = document.getElementById('problemMainForm');
const storeId = 'wwStickyAnswers';

const identifier = (document.querySelector("input[name='problemUUID']")?.value ?? '') +
const identifier =
(document.querySelector("input[name='problemUUID']")?.value ?? '') +
(document.querySelector("input[name='sourceFilePath']")?.value ?? '') +
(document.querySelector("input[name='problemSource']")?.value ?? '') +
(document.querySelector("input[name='problemSeed']")?.value ?? '');
Expand All @@ -26,7 +27,7 @@

store[identifier] = problemData;
localStorage.setItem(storeId, JSON.stringify(store));
}
};

container.addEventListener('submit', storeData);

Expand Down
Loading

0 comments on commit 3f74166

Please sign in to comment.