repo stringlengths 5 106 | file_url stringlengths 78 301 | file_path stringlengths 4 211 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:56:49 2026-01-05 02:23:25 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/util/useTranslation.js | src/util/useTranslation.js | import { useLocalization } from "./LocalizationContext";
import translationsEn from "../locales/en.json";
import translationsEs from "../locales/es.json";
import translationsSe from "../locales/se.json";
export const useTranslation = () => {
const { language, setLanguage } = useLocalization();
const translationsMap = {
en: translationsEn,
es: translationsEs,
se: translationsSe,
};
const translations = translationsMap[language] || translationsMap['en'];
const translate = (key) => {
return key.split(".").reduce((obj, k) => (obj || {})[k], translations);
};
return { translate, setLanguage };
};
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/util/wrongAnswerReasons.js | src/util/wrongAnswerReasons.js | const { Enumify } = require("./enumify");
class WrongAnswerReasons extends Enumify {
static wrong = new WrongAnswerReasons();
static sameAsProblem = new WrongAnswerReasons();
static errored = new WrongAnswerReasons();
static _ = this.closeEnum();
}
export default WrongAnswerReasons
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/util/withTranslation.js | src/util/withTranslation.js | import React from 'react';
import { useTranslation } from './useTranslation';
const withTranslation = (WrappedComponent) => {
return (props) => {
const { translate, setLanguage } = useTranslation();
return <WrappedComponent translate={translate} setLanguage={setLanguage} {...props} />;
};
};
export default withTranslation;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/util/parseMatrixTex.js | src/util/parseMatrixTex.js | export function parseMatrixTex(solTex) {
const solutionMatrices = []
;(Array.isArray(solTex) ? solTex : [solTex]).forEach(sol => {
const _start = sol.indexOf("matrix} ") + "matrix} ".length
const _end = sol.indexOf("\\end{")
let _solutionMatrix = sol
.substring(_start, _end)
.trim()
.split("\\\\")
.map(row => row.split("&").map(val => val.trim()))
solutionMatrices.push(_solutionMatrix)
})
return solutionMatrices;
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/util/calculateSemester.js | src/util/calculateSemester.js | const { SESSION_SYSTEM } = require('@common/global-config')
const calculateSemester = (ms) => {
const date = new Date(ms)
const semesters = [
{
name: "Fall",
start: 70,
end: 100
},
{
name: "Spring",
start: 0,
end: 45
},
{
name: "Summer",
start: 45,
end: 70
}
]
const quarters = [
{
name: "Fall",
start: 75,
end: 100
},
{
name: "Winter",
start: 0,
end: 30
},
{
name: "Spring",
start: 30,
end: 55
},
{
name: "Summer",
start: 55,
end: 75
}
]
const currentYear = date.getUTCFullYear()
const nextYear = date.getUTCFullYear() + 1
const _baseline = new Date(0)
_baseline.setUTCFullYear(currentYear)
const baseline = _baseline.getTime()
const _eoy = new Date(0)
_eoy.setUTCFullYear(nextYear)
const eoy = _eoy.getTime()
const progress = (ms - baseline) / (eoy - baseline) * 100
const session = (SESSION_SYSTEM === "SEMESTER" ? semesters : quarters)
.find(({ start, end }) => progress >= start && progress < end);
return `${session.name} ${currentYear}`
}
module.exports = {
calculateSemester
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/util/toastIds.js | src/util/toastIds.js | const { Enumify } = require("./enumify");
class ToastID extends Enumify {
static expired_session = new ToastID();
static not_authorized = new ToastID();
static set_lesson_unknown_error = new ToastID();
static set_lesson_duplicate_error = new ToastID();
static set_lesson_success = new ToastID();
static submit_grade_unknown_error = new ToastID();
static submit_grade_link_lost = new ToastID();
static submit_grade_unable = new ToastID();
static warn_not_from_canvas = new ToastID();
static successfully_completed_lesson = new ToastID();
// noinspection JSVoidFunctionReturnValueUsed
/**
* @private
*/
static _ = this.closeEnum();
}
export default ToastID
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/util/daysSinceEpoch.js | src/util/daysSinceEpoch.js | export default function daysSinceEpoch(){
return Math.floor(Date.now() / (1000 * 60 * 60 * 24))
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/util/LocalizationContext.js | src/util/LocalizationContext.js | import React, { createContext, useState, useContext, useEffect } from 'react';
const LocalizationContext = createContext();
export const LocalizationProvider = ({ children }) => {
const [language, setLanguage] = useState(() => {
const hashParams = new URLSearchParams(window.location.hash.split('?')[1]);
const langFromUrl = hashParams.get('locale');
if (langFromUrl && ['en', 'es', 'se'].includes(langFromUrl)) {
localStorage.setItem('locale', langFromUrl);
localStorage.setItem('defaultLocale', langFromUrl);
return langFromUrl;
}
const storedLocale = localStorage.getItem('locale');
return storedLocale && ['en', 'es', 'se'].includes(storedLocale) ? storedLocale : 'en';
});
useEffect(() => {
const updateLanguageFromUrl = () => {
const hashParams = new URLSearchParams(window.location.hash.split('?')[1]);
const langFromUrl = hashParams.get('locale');
if (langFromUrl && ['en', 'es', 'se'].includes(langFromUrl)) {
setLanguage(langFromUrl);
localStorage.setItem('locale', langFromUrl);
localStorage.setItem('defaultLocale', langFromUrl);
}
};
window.addEventListener('hashchange', updateLanguageFromUrl);
return () => {
window.removeEventListener('hashchange', updateLanguageFromUrl);
};
}, []);
useEffect(() => {
if (['en', 'es', 'se'].includes(language)) {
localStorage.setItem('locale', language);
}
}, [language]);
return (
<LocalizationContext.Provider value={{ language, setLanguage }}>
{children}
</LocalizationContext.Provider>
);
};
export const useLocalization = () => useContext(LocalizationContext);
export const LocalizationConsumer = LocalizationContext.Consumer;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/util/parseJWT.js | src/util/parseJWT.js | function parseJwt(token) {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
}
module.exports = parseJwt
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/util/getBuildType.js | src/util/getBuildType.js | const buildType = process.env.REACT_APP_BUILD_TYPE || ""
console.debug(`This has the build type: ${buildType}`)
const IS_STAGING = buildType.includes("staging")
const IS_STAGING_CONTENT = buildType === "staging-content"
const IS_STAGING_PLATFORM = buildType === "staging-platform"
const IS_PRODUCTION = buildType.includes("production")
const IS_DEVELOPMENT = buildType.includes("development")
const IS_STAGING_OR_DEVELOPMENT = IS_STAGING || IS_DEVELOPMENT
export {
IS_PRODUCTION,
IS_DEVELOPMENT,
IS_STAGING_CONTENT,
IS_STAGING_PLATFORM,
IS_STAGING,
IS_STAGING_OR_DEVELOPMENT
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/tools/readJsExportedObject.js | src/tools/readJsExportedObject.js | const tempy = require("tempy-legacy");
const readFile = require("fs/promises").readFile;
const pathToFileURL = require("url").pathToFileURL;
async function readJsExportedObject(file) {
const objectFile = await readFile(file)
return await tempy.write.task(objectFile, async (temporaryPath) => {
return (await import(pathToFileURL(temporaryPath))).default
}, {
extension: "mjs"
})
}
module.exports = readJsExportedObject
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/tools/preprocessProblemPool.js | src/tools/preprocessProblemPool.js | const path = require("path");
const fs = require("fs");
const util = require('util');
const { CONTENT_SOURCE } = require('../../common/global-config')
const copyFile = util.promisify(fs.copyFile)
const readdir = util.promisify(fs.readdir)
const lstat = util.promisify(fs.lstat)
const writeFile = util.promisify(fs.writeFile)
const mkdir = util.promisify(fs.mkdir)
const rm = util.promisify(fs.rm)
if (+process.versions.node.split(".")[0] < 10) {
console.debug('Please upgrade to node v10.12.X+')
process.exit(1)
}
// the current file should be in src/tools so ../content-sources/* should be src/content-sources/*
const problemPoolPath = path.join(__dirname, '..', 'content-sources', CONTENT_SOURCE, 'content-pool')
const generatedPath = path.join(__dirname, '..', '..', 'generated', 'processed-content-pool')
const poolFilePath = path.join(generatedPath, `${CONTENT_SOURCE}.json`)
const staticFiguresPath = path.join(__dirname, '..', '..', 'public', 'static', 'images', 'figures', CONTENT_SOURCE)
;(async () => {
// let hasPrevPool = true, config = {};
// await access(poolFilePath).catch(err => {
// hasPrevPool = false
// })
//
// if (hasPrevPool) {
// await readFile(poolFilePath, "utf8").then(data => {
// config = JSON.parse(data.toString())
// }).catch(err => {
// console.debug('error reading pool file: ', err)
// hasPrevPool = false
// })
// }
//
// console.debug('has previous pool file? ', hasPrevPool)
// const { meta = {}, pool = [] } = config
// if (hasPrevPool && (!meta || !pool || !meta.timestamp)) {
// console.debug('previous pool file is invalid, regenerating pool file...')
// }
//
// const { updatedTime = -1 } = meta
// if (hasPrevPool && updatedTime > -1) {
// console.debug(`last update time was ${new Date(updatedTime)}`)
// }
const updatedTime = -1; // optimizing file reads based on last updated time makes negligible difference right now.
// let modifiedProblems = 0
const directoryItems = await readdir(problemPoolPath)
const problemDirs = await Promise.all(directoryItems.map(async item => {
const stat = await lstat(path.join(problemPoolPath, item))
let directory = ""
if (stat.isDirectory()) {
if (fs.lstatSync(path.join(problemPoolPath, item)).mtime > updatedTime) {
// modifiedProblems++
directory = item
}
}
return new Promise((resolve, reject) => {
resolve(directory)
})
})).catch(err => {
console.debug(err)
console.error('error reading problem directories')
process.exit(1)
})
// remove existing static figures
await rm(staticFiguresPath, { recursive: true }).catch(err => {
console.debug(err)
console.error('error removing existing figures (this is ok on the first run)')
if (err.code !== 'ENOENT') {
process.exit(1)
}
})
const problems = await Promise.all(
problemDirs
.filter(d => d.length > 0) // only keep resolved directories
.filter(d => !(d.toString().startsWith("_") || d.toString().startsWith("."))) // ignore directories that start with _ or .
.map(
async problemDir => {
const problemName = problemDir.toString()
const problemPath = path.join(problemPoolPath, problemName)
const problem = require(path.join(problemPath, `${problemName}.json`))
const stepDirs = await readdir(path.join(problemPath, 'steps'))
if (!stepDirs || stepDirs.length === 0) {
throw Error(`${problemName.toString()} has no steps.`)
}
const figurePaths = await readdir(path.join(problemPath, 'figures')).catch(err => {
// ignore, see below
})
if (!figurePaths || figurePaths.length === 0) {
// it is okay if a problem doesn't have figures
} else {
await Promise.all(figurePaths.map(async figure => {
await mkdir(path.join(staticFiguresPath, problemDir.toString()), {
recursive: true
})
await copyFile(path.join(problemPath, 'figures', figure), path.join(staticFiguresPath, problemDir.toString(), figure))
return new Promise((resolve, reject) => {
resolve(true)
})
}))
}
problem.steps = await Promise.all(
stepDirs.map(
async stepDir => {
const stepName = stepDir.toString()
const stepPath = path.join(problemPath, 'steps', stepName)
const step = require(path.join(stepPath, `${stepDir}.json`))
const hintPathwaysDir = await readdir(path.join(stepPath, 'tutoring')) || []
if (hintPathwaysDir.length === 0) {
console.warn(`${problemName} -> ${stepName} has no hints (pathways).`)
}
const hintPathways = await Promise.all(
hintPathwaysDir.map(
async hintPathwayFile => {
const hintPathwayFullName = hintPathwayFile.toString()
const hintPathwayPath = path.join(stepPath, 'tutoring', hintPathwayFullName)
const hintPathway = require(hintPathwayPath)
const hintPathwayName = hintPathwayFullName.includes(stepName)
? hintPathwayFullName.substr(hintPathwayFullName.indexOf(stepName) + stepName.length).replace(/\.[^/.]+$/, "")
: hintPathwayFullName
return new Promise((resolve, reject) => {
resolve({ [hintPathwayName]: hintPathway })
})
}))
// merge down into one object
step.hints = Object.fromEntries(hintPathways.map(obj => [Object.keys(obj)[0], obj[Object.keys(obj)[0]]]))
return new Promise((resolve, reject) => {
resolve(step)
})
}))
return new Promise((resolve, reject) => {
resolve(problem)
})
})
).catch(err => {
console.debug(err)
console.error('error reading individual problem directory')
process.exit(1)
})
// console.debug(`${modifiedProblems} problems have been modified.`)
console.debug(`writing to pool file...`)
const config = problems
await mkdir(generatedPath, {
recursive: true
})
await writeFile(poolFilePath, JSON.stringify(config))
})()
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/tools/populateGoogleSheets.js | src/tools/populateGoogleSheets.js | require('dotenv').config({
path: './.env.local'
})
const fromEntries = require('object.fromentries');
const admin = require('firebase-admin');
const to = require('await-to-js').default;
const serviceAccount = require('./service-account-credentials.json');
const { GoogleSpreadsheet } = require("google-spreadsheet");
const crypto = require("crypto")
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
const db = admin.firestore();
const sheetsServiceAccount = require('./sheets-service-account.json');
const doc = new GoogleSpreadsheet(process.env.SPREADSHEET_ID);
const COLLECTION_NAME = "feedbacks";
const { calculateSemester } = require("../util/calculateSemester")
const CURRENT_SEMESTER = calculateSemester(Date.now())
const SHEET_NAME = `All Feedbacks`
const COLUMN_NAME_MAPPING = {
"id": "Id",
"time_stamp": "date",
"feedback": "Feedback",
"oats_user_id": "studentName",
"problemID": "problemName",
"treatment": "treatmentID",
"problemFinished": "problemFinished?"
};
const COLUMN_TITLES = ["Id", "date", "Content", "problemName", "studentName", "Feedback", "steps", "Issue Type", "status", "resolution", "resolveDate", "deployDate", "problemFinished?", "siteVersion", "versionFixed", "treatmentID", "Semester"]
const INTERPOLATORS = {
"date": val => getFormattedDate(val),
"Semester": val => calculateSemester(val)
}
const EXCLUDED_FIELDS = ["semester", "lms_user_id", "course_code", "course_id", "server_time"]
const HASH_EXCLUDE_FIELDS = ['status', 'resolution', 'resolveDate', 'deployDate', 'versionFixed', 'Issue Type']
if (!Object.fromEntries) {
fromEntries.shim();
}
;(async () => {
let err;
[err] = await to(doc.useServiceAccountAuth(sheetsServiceAccount));
if (err) {
console.debug(err.message)
console.log("Errored when trying to use Service Account")
return
}
[err] = await to(doc.loadInfo());
if (err) {
console.debug(err.message)
console.log(`Errored when trying to load doc: ${process.env.SPREADSHEET_ID}`)
return
}
let snapshot;
[err, snapshot] = await to(db.collection(COLLECTION_NAME).where("semester", "==", CURRENT_SEMESTER).orderBy('time_stamp').get())
if (err) {
console.debug(err.message)
console.log(`Errored when trying to get a snapshot of collection: ${COLLECTION_NAME}. Are you sure it exists?`)
return
}
const _rows = snapshot.docs
.map(doc => doc.data())
.map(data => ({ ...data, Semester: data.time_stamp }))
// sort each data point by its keys to ensure consistent hash
.map(data => sort(data))
// generates id based on content
.map(data => {
const hash = crypto
.createHash('sha1')
.update(JSON.stringify(removeFields(data, HASH_EXCLUDE_FIELDS)))
.digest('hex');
return {
id: hash,
...data
}
})
// map db key names to column names
.map(data => Object.fromEntries(Object.entries(data).map(([key, value]) => [COLUMN_NAME_MAPPING[key] || key, value])));
// interpolate then convert all none string/number value into string
let nRows = _rows.map(_row =>
Object.fromEntries(Object.entries(_row)
.map(([key, val]) => [key, INTERPOLATORS[key] ? INTERPOLATORS[key](val) : val])
.map(([key, val]) => [key, typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean' ? val : JSON.stringify(val)])
)
)
// calculate additional headings
const additionalHeadings = new Set()
_rows.forEach(row => {
Object.keys(row).forEach(key => {
if (!COLUMN_TITLES.includes(key) && !EXCLUDED_FIELDS.includes(key)) {
additionalHeadings.add(key)
}
})
})
const headerValues = [...COLUMN_TITLES, ...additionalHeadings]
let sheet;
sheet = doc.sheetsByTitle[SHEET_NAME];
if (!sheet) {
console.debug(`Did not find a sheet by the name of ${SHEET_NAME}, creating new sheet automatically..`);
[err, sheet] = await to(doc.addSheet({
title: SHEET_NAME,
headerValues
}))
if (err) {
console.debug(err.message)
console.log("Errored when trying to create a new sheet.")
return
}
}
let oRows;
[err, oRows] = await to(sheet.getRows());
const oldIds = oRows.map(_row => _row[COLUMN_NAME_MAPPING['id'] || 'id']).filter(id => id && id.length > 6);
nRows = nRows.filter(_row => !oldIds.includes(_row[COLUMN_NAME_MAPPING['id'] || 'id']));
if (nRows.length === 0) {
console.debug('No new feedback found! Returning early..')
return
}
[err] = await to(sheet.addRows(nRows))
if (err) {
console.debug(err.message)
console.log(`Errored when writing to sheets`)
} else {
console.debug(`Successfully inserted ${nRows.length} rows.`)
}
})()
function removeFields(obj, keys) {
return Object.fromEntries(Object.entries(obj).filter(([key, _]) => !keys.includes(key)))
}
function getFormattedDate(ms) {
const date = new Date(ms);
return (
("0" + (date.getMonth() + 1)).slice(-2) + '-' +
("0" + date.getDate()).slice(-2) + '-' +
date.getFullYear() + " " +
("0" + date.getHours()).slice(-2) + ":" +
("0" + date.getMinutes()).slice(-2) + ":" +
("0" + date.getSeconds()).slice(-2)
)
}
function sort(obj) {
if (typeof obj !== "object")
return obj;
if (Array.isArray(obj)) {
return obj.map(obj => sort(obj)).sort()
}
const sortedObject = {};
const keys = Object.keys(obj).sort();
keys.forEach(key => sortedObject[key] = sort(obj[key]));
return sortedObject;
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/pages/AssignmentAlreadyLinked.js | src/pages/AssignmentAlreadyLinked.js | import React, { useContext } from "react";
import { findLessonById, _lessonPlansNoEditor, ThemeContext } from "../config/config";
import { AppBar, Box, Toolbar } from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
import Divider from "@material-ui/core/Divider";
import BrandLogoNav from "@components/BrandLogoNav";
import Spacer from "@components/Spacer";
const AssignmentAlreadyLinked = (props) => {
const lessonPlans = _lessonPlansNoEditor;
const context = useContext(ThemeContext)
const _linkedLesson = +context.alreadyLinkedLesson
const linkedLesson = !isNaN(_linkedLesson)
? lessonPlans[+context.alreadyLinkedLesson]
: context.alreadyLinkedLesson.length > 1 ?
findLessonById(context.alreadyLinkedLesson) :
null
console.debug("linkedLesson", linkedLesson)
return <>
<div style={{ backgroundColor: "#F6F6F6", paddingBottom: 20 }}>
<AppBar position="static">
<Toolbar>
<Grid container spacing={0} role={"navigation"}>
<Grid item xs={3} key={1}>
<BrandLogoNav noLink={true}/>
</Grid>
</Grid>
</Toolbar>
</AppBar>
<div>
<Grid
container
spacing={0}
direction="column"
alignItems="center"
justifyContent="center"
>
<Box width="75%" maxWidth={1500}>
<center>
{linkedLesson
? <h1>This assignment has been linked to
lesson {linkedLesson.name} {linkedLesson.topic} successfully!</h1>
: <h1>This assignment has been linked successfully!</h1>
}
<h2>To link a new OATutor lesson, please create a new assignment on your LMS.</h2>
<h2>To preview the lesson, click on "Student View" on Canvas.</h2>
</center>
<Divider/>
<center>
<Spacer/>
{linkedLesson
&& <>
<p>Course Name: {linkedLesson.courseName}</p>
<p>Lesson Name: {linkedLesson.name} {linkedLesson.topics}</p>
</>
}
<Spacer height={24 * 4}/>
</center>
</Box>
</Grid>
</div>
</div>
</>
}
export default AssignmentAlreadyLinked
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/pages/SessionExpired.js | src/pages/SessionExpired.js | import React from "react";
import { AppBar, Box, Toolbar } from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
import Divider from "@material-ui/core/Divider";
import BrandLogoNav from "@components/BrandLogoNav";
import Spacer from "@components/Spacer";
const SessionExpired = () => {
return <>
<div style={{ backgroundColor: "#F6F6F6", paddingBottom: 20 }}>
<AppBar position="static">
<Toolbar>
<Grid container spacing={0} role={"navigation"}>
<Grid item xs={3} key={1}>
<BrandLogoNav noLink={true}/>
</Grid>
</Grid>
</Toolbar>
</AppBar>
<div>
<Grid
container
spacing={0}
direction="column"
alignItems="center"
justifyContent="center"
>
<Box width="75%" maxWidth={1500}>
<center>
<h1>Oops, something went wrong!</h1>
<h2>It looks like your session has expired.</h2>
</center>
<Divider/>
<center>
<Spacer/>
<p>If you are a student, please reload the page or open the page from your LMS again.</p>
<Spacer/>
<p>If you are an instructor, please reload the page or create a new assignment.</p>
<Spacer height={24 * 3}/>
</center>
</Box>
</Grid>
</div>
</div>
</>
}
export default SessionExpired
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/pages/AssignmentNotLinked.js | src/pages/AssignmentNotLinked.js | import React from "react";
import { AppBar, Box, Toolbar } from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
import Divider from "@material-ui/core/Divider";
import BrandLogoNav from "@components/BrandLogoNav";
import Spacer from "@components/Spacer";
import { SITE_NAME } from "../config/config";
const AssignmentNotLinked = () => {
return <>
<div style={{ backgroundColor: "#F6F6F6", paddingBottom: 20 }}>
<AppBar position="static">
<Toolbar>
<Grid container spacing={0} role={"navigation"}>
<Grid item xs={3} key={1}>
<BrandLogoNav noLink={true}/>
</Grid>
</Grid>
</Toolbar>
</AppBar>
<div>
<Grid
container
spacing={0}
direction="column"
alignItems="center"
justifyContent="center"
>
<Box width="75%" maxWidth={1500}>
<center>
<h1>Welcome to {SITE_NAME.replace(/\s/, "")}!</h1>
<h2>Your instructor has not linked a lesson to this assignment yet.</h2>
</center>
<Divider/>
<center>
<Spacer/>
<p>Please check back later.</p>
<Spacer height={24 * 3}/>
</center>
</Box>
</Grid>
</div>
</div>
</>
}
export default AssignmentNotLinked
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/pages/Posts/CanvasAssignments.js | src/pages/Posts/CanvasAssignments.js | import React from "react";
import Spacer from "@components/Spacer";
import { useStyles } from "./Posts";
import { Link } from "react-router-dom";
import clsx from "clsx";
import ZoomImage from "@components/ZoomImage";
const CanvasAssignments = () => {
const classes = useStyles()
return <>
<h1>
Creating OATutor Assignments Through Canvas
</h1>
<h4 style={{
marginTop: 0
}}>
Last updated: {new Date(1642208021289).toLocaleString()}
</h4>
<h4>Prerequisites</h4>
Make sure that you have followed the previous tutorial to set up the Canvas integration first! You may re-visit
the tutorial with this link: <Link to={"/posts/set-up-canvas-integration"}>Setting up Canvas to work with
OATutor</Link>
<h4>Navigating to the Create Assignment Page</h4>
First select the course you want to add the Assignment to.
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing the user selecting their first course in the courses tab."}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/setting-up-canvas-integration/courses%20selection.PNG`}/>
</div>
Navigate to the Assignments tab of that course. Then click on the blue "+ Assignment" button.
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing the user on the assignment tab of the settings page."}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/canvas-assignments/add%20assignment.png`}/>
</div>
<h4>Creating the Canvas Assignment</h4>
Give the Canvas Assignment a name and description as you would with any other Canvas assignments.
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing the assignment creation page with the assignment title and description filled out"}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/canvas-assignments/create%20an%20assignment%20as%20you%20would%20usually.PNG`}/>
</div>
In the "Submission Type" section, select the "External Tool" option then click "Find".
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing the user on the submission type section."}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/canvas-assignments/submission%20type.PNG`}/>
</div>
In the "Configure External Tool" window that pops up, click on the external tool that corresponds with OATutor.
After seeing the URL field get populated, click select to confirm using OATutor for this assignment.
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing the user on the external tool configuration screen."}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/canvas-assignments/configure%20external%20tool.PNG`}/>
</div>
At this point, you may change any other assignment settings (e.g., submission attempts, anonymous grading,
assign) before clicking the blue "Save" button to begin the OATutor linking process.
<h4>Linking the Assignment to the OATutor Lesson Plan</h4>
After clicking "Save" in the previous step, you will be automatically directed to the instructors' view of the
assignment. If you are not on the assignment page, navigate to the target assignment via the "Assignments" tab
of the course page. You should be greeted with an OATutor welcome screen:
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing the user on the assignment page, selecting a course."}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/canvas-assignments/select%20a%20course.PNG`}/>
</div>
<blockquote>
If you do not see this greeting screen, make sure that the assignment has OATutor configured as the
external tool. If there is an error screen instead or a blank screen, please contact your OATutor point of
contact.
</blockquote>
Choose a course to select a lesson from (such as OpenStax: College Algebra). You will be redirected to a list of
lesson plans:
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing the user on the lesson plan selecting page."}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/canvas-assignments/select%20a%20lesson%20plan.PNG`}/>
</div>
<blockquote>
If you do not see this list of lesson plans, see an error screen, or see a blank screen, please contact your
OATutor point of contact to submit and record these issues.
</blockquote>
Click on a lesson plan to "select" it. If the OATutor lesson has been successfully linked to the Canvas
assignment, this prompt will appear on the blue OATutor navbar:
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing the linkage success prompt."}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/canvas-assignments/successfully%20linked%20assignment.PNG`}/>
</div>
If you refresh the assignment page, you will be greeted with this information screen:
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing the already linked information page."}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/canvas-assignments/already%20been%20linked.PNG`}/>
</div>
At this point, the Canvas assignment has been registered with the OATutor system and you may now publish the
assignment.
<Spacer height={24 * 8}/>
</>
}
export default CanvasAssignments
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/pages/Posts/Posts.js | src/pages/Posts/Posts.js | import { Link, Route, Switch, useRouteMatch } from "react-router-dom";
import React, { useState } from "react";
import { AppBar, Box, Button, makeStyles, Menu, MenuItem, Toolbar } from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
import BrandLogoNav from "@components/BrandLogoNav";
import { SITE_NAME, SITE_VERSION } from "../../config/config";
import HowToUse from "./HowToUse";
import CanvasAssignments from "./CanvasAssignments";
import SetUpCanvasIntegration from "./SetUpCanvasIntegration";
const POSTS = [
{
name: "Setting up Canvas Integration",
paths: ['set-up-canvas-integration'],
component: SetUpCanvasIntegration
},
{
name: "Creating Canvas Assignments",
paths: ['canvas-assignments'],
component: CanvasAssignments
},
{
name: `How to use ${SITE_NAME} v${SITE_VERSION}`,
paths: [`how-to-use`],
component: HowToUse
}
]
const useStyles = makeStyles({
button: {
textDecoration: "underline",
"&:hover": {
cursor: "pointer"
}
},
fullWidth: {
width: "100%"
},
textCenter: {
textAlign: "center",
},
unselectable: {
userSelect: "none"
},
image: {
maxWidth: "100%",
marginBottom: 8
},
"p-8": {
padding: "2rem"
},
"p-16": {
padding: "4rem"
},
"pt-2": {
paddingTop: "0.5rem"
},
"pt-8": {
paddingTop: "2rem"
},
contentContainer: {
width: "75%",
maxWidth: "75ch"
}
});
const Posts = () => {
const classes = useStyles()
const { path, url } = useRouteMatch();
const [anchorEl, setAnchorEl] = useState(null);
const open = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return <>
<div style={{ backgroundColor: "#F6F6F6", paddingBottom: 50 }}>
<AppBar position="static">
<Toolbar>
<Grid container justifyContent={"space-between"} spacing={0} role={"navigation"} alignItems={"center"}>
<Grid item xs={3} key={1}>
<BrandLogoNav/>
</Grid>
<Grid item xs={3} key={3}>
<div style={{ textAlign: 'right', paddingTop: "3px" }}>
<Button
variant={"contained"}
id="basic-button"
aria-controls="basic-menu"
aria-haspopup="true"
aria-expanded={open ? 'true' : undefined}
onClick={handleClick}
>
All Posts
</Button>
<Menu
id="basic-menu"
anchorEl={anchorEl}
getContentAnchorEl={null}
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
transformOrigin={{ vertical: "top", horizontal: "center" }}
open={open}
onClose={handleClose}
MenuListProps={{
'aria-labelledby': 'basic-button',
dense: true
}}
>
{POSTS.map(post => {
return <MenuItem key={post.paths[0]} onClick={handleClose}>
<Link to={`${url}/${post.paths[0]}`}>{post.name}</Link>
</MenuItem>
})}
</Menu>
</div>
</Grid>
</Grid>
</Toolbar>
</AppBar>
<div>
<Grid
container
spacing={0}
direction="column"
alignItems="center"
justifyContent="center"
>
<Box className={classes.contentContainer} role={"main"}>
<Switch>
<Route exact path={path}>
<h3>Click the top right corner to select a post.</h3>
</Route>
{
POSTS.map(post => <Route key={post.paths[0]}
path={post.paths.map(_path => `${path}/${_path}`)}>
{post.component()}
</Route>)
}
<Route>
<h3>Post not found :(</h3>
</Route>
</Switch>
</Box>
</Grid>
</div>
</div>
</>
}
export { Posts, useStyles }
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/pages/Posts/SetUpCanvasIntegration.js | src/pages/Posts/SetUpCanvasIntegration.js | import React, { useState } from "react";
import Spacer from "@components/Spacer";
import { useStyles } from "./Posts";
import clsx from "clsx";
import ZoomImage from "@components/ZoomImage";
import { SITE_NAME } from "../../config/config";
const createCourseLink = "https://community.canvaslms.com/t5/Instructor-Guide/How-do-I-create-a-new-course-from-the-Dashboard-as-an-instructor/ta-p/794"
const SetUpCanvasIntegration = () => {
const classes = useStyles()
const [consumerKey, setConsumerKey] = useState(null);
const [consumerSecret, setConsumerSecret] = useState(null);
const getConsumerKeySecret = () => {
setConsumerKey("key")
setConsumerSecret("secret")
}
return <>
<h1>
Setting up Canvas to work with OATutor (formerly known as OpenITS)
</h1>
<h4 style={{
marginTop: 0
}}>
Last updated: {new Date(1638826551614).toLocaleString()}
</h4>
<h4>Creating a Canvas Course</h4>
Please visit Canvas' post on their community posts <a href={createCourseLink} target={"_blank"}
rel="noreferrer">here</a>.
<h4>Navigating to the Course App Settings</h4>
Select the course you want to add OATutor to.
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing the user selecting their first course in the courses tab."}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/setting-up-canvas-integration/courses%20selection.PNG`}/>
</div>
Navigate to the Settings > Apps tab of that course. Then click on the blue "+ App" button.
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing the user on the app tab of the settings page."}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/setting-up-canvas-integration/settings%20app%20page.PNG`}/>
</div>
Select "By URL" in the Configuration Type dropdown.
<h4>For the App Fields</h4>
<div className={classes.fullWidth}><span className={classes.unselectable}>Name: </span><code>{SITE_NAME}</code>
</div>
Click <b className={classes.button} onClick={getConsumerKeySecret}>here</b> to generate the required
consumer key and shared secret.
{consumerKey && consumerSecret && <>
<div className={classes.fullWidth}>
<span className={classes.unselectable}>Consumer Key: </span><code>{consumerKey}</code>
</div>
<div className={classes.fullWidth}>
<span className={classes.unselectable}>Shared Secret: </span><code>{consumerSecret}</code>
</div>
</>}
<div className={classes.fullWidth}>
<span
className={classes.unselectable}>Config URL: </span><code>https://cahlr.github.io/{SITE_NAME}/lti-consumer-config.xml</code>
</div>
<div className={clsx(classes.fullWidth, classes.textCenter, classes["p-8"])}>
<ZoomImage
alt={"Screenshot showing an example App configuration with the fields filled out."}
className={classes.image}
src={`${process.env.PUBLIC_URL}/static/images/posts/setting-up-canvas-integration/add%20app.PNG`}/>
</div>
Click "Submit" and you will be able to start using {SITE_NAME} as an external tool.
<Spacer height={24 * 8}/>
</>
}
export default SetUpCanvasIntegration
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/pages/Posts/About.js | src/pages/Posts/About.js | import React from "react";
import Spacer from "@components/Spacer";
import { useStyles } from "./Posts";
import { HELP_DOCUMENT, SITE_NAME } from "../../config/config";
const VPAT_LINK = `${process.env.PUBLIC_URL}/static/documents/OATutor_Sec508_WCAG.pdf`
const About = () => {
const classes = useStyles()
const currentYear = new Date().getFullYear();
return <>
<h2>
About {SITE_NAME}
</h2>
Open Adaptive Tutor ({SITE_NAME}) is an open-source adaptive tutoring system based on Intelligent Tutoring System (ITS) Principles.
<h3>Question Input Types & Shortcuts</h3>
To learn more about how to fill in and submit {SITE_NAME} assignments,<span> </span>
<a href={HELP_DOCUMENT} target={"_blank"} rel={"noreferrer"}>visit our help document</a>.
<h3>Contributors</h3>
OATutor was created and developed by a dedicated team from the Computational Approaches to Human Learning (CAHL) Research Lab at the UC Berkeley School of Education.
<h3>Learn more</h3>
<ul>
<li>Visit <a href="https://www.oatutor.io/" target={"_blank"} rel={"noreferrer"}>https://www.oatutor.io/</a> to explore more about OATutor, our mission, and how it can benefit you.</li>
<li>Read our <a href="https://dl.acm.org/doi/10.1145/3544548.3581574" target={"_blank"} rel={"noreferrer"}>research paper</a> to learn more about the scientific foundation and methodology behind OATutor.</li>
</ul>
<h3>Accessibility Standards</h3>
<p>
{SITE_NAME} strives to ensure an easy and accessible experience for all users, regardless of disabilities.
The site, {SITE_NAME}, is built with the most up-to-date HTML5 and CSS3 standards; all whilst complying with
W3C's Web Accessibility Guidelines (WCAG) and Section 508 guidelines.
</p>
<p className={classes["pt-2"]}>
The Voluntary Product Accessibility Template, or VPAT, is a tool that administrators and decision-makers can
use to evaluate {SITE_NAME}{SITE_NAME.match(/s$/i) ? "'" : "'s"} conformance with the accessibility
standards under Section 508 of the Rehabilitation Act.
</p>
<p className={classes["pt-2"]}>
You may read our most recent publication of our Voluntary Product Accessibility Template at this
url:<span> </span>
<a href={VPAT_LINK} target={"_blank"} rel={"noreferrer"}>{VPAT_LINK.match(/\/[^/]*$/)[0].substr(1)}</a>
</p>
<Spacer height={24 * 1}/>
<sub>
<p>OATutor code is licensed under a MIT Open Source License, with its adaptive learning content made available under a CC BY 4.0 license.</p>
<p>© {currentYear}, CAHL Research Lab, UC Berkley School of Education.</p>
</sub>
</>
}
export default About
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/pages/Posts/HowToUse.js | src/pages/Posts/HowToUse.js | import React from "react";
import Spacer from "@components/Spacer";
import { useStyles } from "./Posts";
import { HELP_DOCUMENT, SITE_NAME } from "../../config/config";
const VPAT_LINK = `${process.env.PUBLIC_URL}/static/documents/OATutor_Sec508_WCAG.pdf`
const HowToUse = () => {
const classes = useStyles()
return <>
<h1>
How to use {SITE_NAME}?
</h1>
<h2>
Accessibility Standards, Input Types, and Shortcuts
</h2>
<h4 style={{
marginTop: 0
}}>
Last updated: {new Date(1643007791501).toLocaleString()}
</h4>
<h4>Question Input Types & Shortcuts</h4>
To learn more about how to fill in and submit {SITE_NAME} assignments,<span> </span>
<a href={HELP_DOCUMENT} target={"_blank"} rel={"noreferrer"}>visit our help document</a>.
<h4>Accessibility Standards</h4>
<p>
{SITE_NAME} strives to ensure an easy and accessible experience for all users, regardless of disabilities.
The site, {SITE_NAME}, is built with the most up-to-date HTML5 and CSS3 standards; all whilst complying with
W3C's Web Accessibility Guidelines (WCAG) and Section 508 guidelines.
</p>
<p className={classes["pt-2"]}>
The Voluntary Product Accessibility Template, or VPAT, is a tool that administrators and decision-makers can
use to evaluate {SITE_NAME}{SITE_NAME.match(/s$/i) ? "'" : "'s"} conformance with the accessibility
standards under Section 508 of the Rehabilitation Act.
</p>
<p className={classes["pt-2"]}>
You may read our most recent publication of our Voluntary Product Accessibility Template at this
url:<span> </span>
<a href={VPAT_LINK} target={"_blank"} rel={"noreferrer"}>{VPAT_LINK.match(/\/[^/]*$/)[0].substr(1)}</a>
</p>
<Spacer height={24 * 8}/>
</>
}
export default HowToUse
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/ZoomImage.js | src/components/ZoomImage.js | import React from 'react'
import Zoom from 'react-medium-image-zoom'
import 'react-medium-image-zoom/dist/styles.css'
/**
* @param {Partial<HTMLImageElement>} props
*/
const ZoomImage = (props) => {
return <>
<Zoom zoomMargin={40}>
<img {...props} alt={props.alt}/>
</Zoom>
</>
}
export default ZoomImage
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/BrandLogoNav.js | src/components/BrandLogoNav.js | import React, { useContext } from "react";
import { SITE_NAME, SITE_VERSION, ThemeContext } from "../config/config";
import { useHistory } from "react-router-dom";
import { makeStyles } from "@material-ui/core";
const useStyles = makeStyles({
"siteNavLink": {
textAlign: 'left',
paddingTop: "3px",
"&:hover": {
cursor: "pointer"
}
}
})
function BrandLogoNav({ isPrivileged = false, noLink = false }) {
const context = useContext(ThemeContext)
const history = useHistory()
const classes = useStyles()
const brandString = `${SITE_NAME} (v${SITE_VERSION})`
const navigateLink = (evt) => {
if (evt.type === "click" || evt.key === "Enter") {
history.push("/")
}
}
return <>
{/* specified to not link or was launched from lms as student*/}
{noLink || (context.jwt.length !== 0 && !isPrivileged)
? <div style={{ textAlign: 'left', paddingTop: 6 }}>
{brandString}
</div>
:
<div role={"link"} tabIndex={0} onClick={navigateLink} onKeyDown={navigateLink}
className={classes.siteNavLink}>
{brandString}
</div>
}
</>
}
export default BrandLogoNav
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/NotFound.js | src/components/NotFound.js | import React from "react";
const NotFound = () => <h1>Not found</h1>;
export default NotFound;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/BuildTimeIndicator.js | src/components/BuildTimeIndicator.js | export default function BuildTimeIndicator (props) {
const buildTime = +process.env.REACT_APP_BUILD_TIMESTAMP
if (isNaN(buildTime)) {
return <></>
}
return <h4>
(Built on: {new Date(buildTime).toUTCString()})
</h4>
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/GlobalErrorBoundary.js | src/components/GlobalErrorBoundary.js | import React from 'react';
import { ThemeContext } from "../config/config";
import ErrorBoundary from "./ErrorBoundary";
export default class GlobalErrorBoundary extends ErrorBoundary {
static contextType = ThemeContext;
constructor(props, context) {
super(props, context);
this.componentName = "_global_"
}
render() {
if (this.state.hasError) {
return <>
<div style={{
textAlign: "center",
paddingTop: "10vh"
}}>
<h1>Something went wrong</h1>
<p style={{
fontSize: "150%"
}}>This incident has been reported to the developer team. Please try again later.</p>
</div>
</>
}
return this.props.children;
}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/TabFocusTrackerWrapper.js | src/components/TabFocusTrackerWrapper.js | import React from "react";
import { ThemeContext } from "../config/config";
import TabFocusTracker from "./TabFocusTracker";
export default class TabFocusTrackerWrapper extends React.Component {
static contextType = ThemeContext;
render() {
return <TabFocusTracker context={this.context}/>
}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/RenderMedia.js | src/components/RenderMedia.js | import React from "react"
import ZoomImage from "./ZoomImage";
const REGEX_YOUTUBE = /^((?:https?:)?\/\/)?((?:www|m)\.)?(youtube(-nocookie)?\.com|youtu.be)(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/
export default class RenderMedia extends React.Component {
render() {
const url = this.props.url?.toString() || ""
const { problemID = "", contentSource } = this.props
const yt_match = url.match(REGEX_YOUTUBE)
if (yt_match) {
const vid_id = yt_match[6]
return <div style={{
maxWidth: 520
}}>
<div style={{
paddingBottom: "56.25%",
position: "relative",
width: "100%"
}}>
<iframe allowFullScreen={true} frameBorder={0} width={800} height={480}
title={"Video"}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%"
}}
src={`https://www.youtube-nocookie.com/embed/${vid_id}/?controls=1&modestbranding=1&showinfo=0&iv_load_policy=3&html5=1&fs=1&rel=0&hl=en&cc_lang_pref=en&cc_load_policy=1&start=0`}/>
</div>
</div>
}
return <ZoomImage src={`${process.env.PUBLIC_URL}/static/images/figures/${contentSource}/${problemID}/${url}`}
alt={`${problemID} figure`} style={{ width: "100%", objectFit: "scale-down" }}/>
}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/ErrorBoundary.js | src/components/ErrorBoundary.js | import React from 'react';
import { ThemeContext } from "../config/config";
export default class ErrorBoundary extends React.Component {
static contextType = ThemeContext;
constructor(props, context) {
super(props);
this.state = { hasError: false };
this.context = context
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
const { componentName = "_default_" } = this.props
this.context.firebase.submitSiteLog("site-error", `componentName: ${componentName}`, {
errorName: error.name || "n/a",
errorCode: error.code || "n/a",
errorMsg: error.message || "n/a",
errorStack: error.stack || "n/a",
errorInfo
}, this.context.problemID);
}
render() {
const { replacement } = this.props
if (this.state.hasError) {
return <>
<div style={{
textAlign: "center",
display: this.props.inline ? "inline" : "block"
}}>
{replacement
? replacement
: <i>This {this.props.descriptor || "component"} could not be loaded</i>
}
</div>
</>
}
return this.props.children;
}
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/Spacer.js | src/components/Spacer.js | import React from "react";
const Spacer = ({ width = 24, height = 24, }) => {
return <div style={{width, height}}/>
}
export default Spacer
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/Firebase.js | src/components/Firebase.js | import {
CURRENT_SEMESTER,
DO_LOG_DATA,
DO_LOG_MOUSE_DATA,
ENABLE_FIREBASE,
GRANULARITY,
MAX_BUFFER_SIZE,
} from "../config/config.js";
import { initializeApp } from "firebase/app";
import {
arrayUnion,
doc,
getFirestore,
serverTimestamp,
setDoc,
} from "firebase/firestore";
import daysSinceEpoch from "../util/daysSinceEpoch";
import {
IS_PRODUCTION,
IS_STAGING_CONTENT,
IS_STAGING_OR_DEVELOPMENT,
IS_STAGING_PLATFORM,
} from "../util/getBuildType";
const problemSubmissionsOutput = "problemSubmissions";
const problemStartLogOutput = "problemStartLogs";
const GPTExperimentOutput = "GPTExperimentOutput";
const feedbackOutput = "feedbacks";
const siteLogOutput = "siteLogs";
const focusStatus = "focusStatus";
class Firebase {
constructor(oats_user_id, credentials, treatment, siteVersion, ltiContext) {
if (!ENABLE_FIREBASE) {
console.debug("Not using firebase for logging");
return;
}
const app = initializeApp(credentials);
this.oats_user_id = oats_user_id;
this.db = getFirestore(app);
this.treatment = treatment;
this.siteVersion = siteVersion;
this.mouseLogBuffer = [];
this.ltiContext = ltiContext;
}
getCollectionName(targetCollection) {
const cond1 =
IS_STAGING_CONTENT &&
[feedbackOutput, siteLogOutput].includes(targetCollection);
const cond2 =
IS_STAGING_PLATFORM && [siteLogOutput].includes(targetCollection);
return IS_PRODUCTION || cond1 || cond2
? targetCollection
: `development_${targetCollection}`;
}
/**
* Instead of creating a new doc, pushes to an array instead.
* @param _collection
* @param documentId
* @param arrField
* @param data
* @param doPartitioning partition data into a sub-collection's documents (for large amount of data)
* @param partitionFn
* @returns {Promise<void>}
*/
async pushDataToArr(
_collection,
documentId,
arrField,
data,
doPartitioning = false,
partitionFn = daysSinceEpoch
) {
if (!ENABLE_FIREBASE) return;
const collection = this.getCollectionName(_collection);
const payload = this.addMetaData(data, true);
if (IS_STAGING_OR_DEVELOPMENT) {
console.debug(`Upserting document: ${documentId}, with ${data}`);
}
const path = [this.db, collection, documentId];
if (doPartitioning) {
path.push("partitions", partitionFn().toString());
}
const docRef = doc(...path);
await setDoc(
docRef,
{
[arrField]: arrayUnion(payload),
},
{
merge: true,
}
).catch((err) => {
console.log("a non-critical error occurred.");
console.debug(err);
});
}
/*
Collection: Collection of Key/Value pairs
Document: Key - How you will access this data later. Usually username
Data: Value - JSON object of data you want to store
*/
async writeData(_collection, data) {
if (!ENABLE_FIREBASE) return;
const collection = this.getCollectionName(_collection);
const payload = this.addMetaData(data);
if (IS_STAGING_OR_DEVELOPMENT) {
// console.log("payload: ", payload);
console.debug("Writing this payload to firebase: ", payload);
}
await setDoc(
doc(this.db, collection, this._getReadableID()),
payload
).catch((err) => {
console.log("a non-critical error occurred.");
console.log("Error is: ", err);
console.debug(err);
});
}
/**
*
* @param data
* @param isArrayElement if true, cannot use FieldValue methods like serverTimestamp()
* @returns {{[p: string]: *}}
*/
addMetaData(data, isArrayElement = false) {
const _payload = {
semester: CURRENT_SEMESTER,
siteVersion: this.siteVersion,
siteCommitHash: process.env.REACT_APP_COMMIT_HASH,
oats_user_id: this.oats_user_id,
treatment: this.treatment,
time_stamp: Date.now(),
...(process.env.REACT_APP_STUDY_ID
? {
study_id: process.env.REACT_APP_STUDY_ID,
}
: {}),
...(!isArrayElement
? {
server_time: serverTimestamp(),
}
: {}),
...(this.ltiContext?.user_id
? {
course_id: this.ltiContext.course_id,
course_name: this.ltiContext.course_name,
course_code: this.ltiContext.course_code,
lms_user_id: this.ltiContext.user_id,
}
: {
course_id: "n/a",
course_name: "n/a",
course_code: "n/a",
lms_user_id: "n/a",
}),
...data,
};
return Object.fromEntries(
Object.entries(_payload).map(([key, val]) => [
key,
typeof val === "undefined" ? null : val,
])
);
}
_getReadableID() {
const today = new Date();
return (
("0" + (today.getMonth() + 1)).slice(-2) +
"-" +
("0" + today.getDate()).slice(-2) +
"-" +
today.getFullYear() +
" " +
("0" + today.getHours()).slice(-2) +
":" +
("0" + today.getMinutes()).slice(-2) +
":" +
("0" + today.getSeconds()).slice(-2) +
"|" +
Math.floor(Math.random() * Math.pow(10, 5))
.toString()
.padStart(5, "0")
);
}
// TODO: consider using just the context instead
log(
inputVal,
problemID,
step,
hint,
isCorrect,
hintsFinished,
eventType,
variabilization,
lesson,
courseName,
hintType,
dynamicHint,
bioInfo
) {
if (!DO_LOG_DATA) {
console.debug("Not using firebase for logging (2)");
return;
}
console.debug("trying to log hint: ", hint, "step", step);
if (Array.isArray(hintsFinished) && Array.isArray(hintsFinished[0])) {
hintsFinished = hintsFinished.map((step) => step.join(", "));
}
const data = {
eventType: eventType,
problemID: problemID,
stepID: step?.id,
hintID: hint?.id,
input: inputVal?.toString(),
correctAnswer: step?.stepAnswer?.toString(),
isCorrect,
hintInput: null,
hintAnswer: null,
hintIsCorrect: null,
hintsFinished,
variabilization,
lesson,
Content: courseName,
knowledgeComponents: step?.knowledgeComponents,
hintType,
dynamicHint,
bioInfo,
};
// return this.writeData(GPTExperimentOutput, data);
return this.writeData(problemSubmissionsOutput, data);
}
hintLog(
hintInput,
problemID,
step,
hint,
isCorrect,
hintsFinished,
variabilization,
lesson,
courseName,
hintType,
dynamicHint,
bioInfo
) {
if (!DO_LOG_DATA) return;
console.debug("step", step);
const data = {
eventType: "hintScaffoldLog",
problemID,
stepID: step?.id,
hintID: hint?.id,
input: null,
correctAnswer: null,
isCorrect: null,
hintInput: hintInput?.toString(),
hintAnswer: hint?.hintAnswer?.toString(),
hintIsCorrect: isCorrect,
hintsFinished,
dynamicHint: "abc",
bioInfo: "abcedf",
variabilization,
Content: courseName,
lesson,
knowledgeComponents: step?.knowledgeComponents,
hintType,
dynamicHint,
bioInfo,
};
// return this.writeData(GPTExperimentOutput, data);
return this.writeData(problemSubmissionsOutput, data);
}
mouseLog(payload) {
if (!DO_LOG_DATA || !DO_LOG_MOUSE_DATA) return;
if (this.mouseLogBuffer.length > 0) {
if (
!(
Math.abs(
payload.position.x -
this.mouseLogBuffer[this.mouseLogBuffer.length - 1]
.x
) > GRANULARITY ||
Math.abs(
payload.position.y -
this.mouseLogBuffer[this.mouseLogBuffer.length - 1]
.y
) > GRANULARITY
)
) {
return;
}
}
if (this.mouseLogBuffer.length < MAX_BUFFER_SIZE) {
this.mouseLogBuffer.push({
x: payload.position.x,
y: payload.position.y,
});
return;
}
const data = {
eventType: "mouseLog",
_logBufferSize: MAX_BUFFER_SIZE,
_logGranularity: GRANULARITY,
screenSize: payload.elementDimensions,
mousePos: this.mouseLogBuffer,
};
this.mouseLogBuffer = [];
console.debug("Logged mouseMovement");
return this.writeData("mouseMovement", data);
}
startedProblem(problemID, courseName, lesson, lessonObjectives) {
if (!DO_LOG_DATA) return;
console.debug(
`Logging that the problem has been started (${problemID})`
);
const data = {
problemID,
Content: courseName,
lesson,
lessonObjectives,
};
return this.writeData(problemStartLogOutput, data);
}
submitSiteLog(logType, logMessage, relevantInformation, problemID = "n/a") {
const data = {
logType,
logMessage,
relevantInformation,
problemID,
};
return this.writeData(siteLogOutput, data);
}
submitFocusChange(_focusStatus) {
const data = {
focusStatus: _focusStatus,
};
// TODO: oats_user_id is not guaranteed to be unique across users; is this a problem?
return this.pushDataToArr(
focusStatus,
this.oats_user_id,
"focusHistory",
data,
true
);
}
submitFeedback(
problemID,
feedback,
problemFinished,
variables,
courseName,
steps,
lesson
) {
const data = {
problemID,
problemFinished,
feedback,
lesson,
status: "open",
Content: courseName,
variables,
steps: steps.map(
({
answerType,
id,
stepAnswer,
problemType,
knowledgeComponents,
}) => ({
answerType,
id,
stepAnswer,
problemType,
knowledgeComponents,
})
),
};
return this.writeData(feedbackOutput, data);
}
}
export default Firebase;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/TabFocusTracker.js | src/components/TabFocusTracker.js | import { useEffect } from "react";
import useWindowFocus from "use-window-focus";
import { useLocation } from 'react-router-dom';
export default function TabFocusTracker(props) {
const { context } = props
const { firebase } = context
const windowFocused = useWindowFocus();
const pathname = useLocation()?.pathname;
useEffect(() => {
if (!firebase) return
;(async () => {
if (pathname.startsWith("/lessons/")) {
await firebase.submitFocusChange(windowFocused);
}
})()
}, [windowFocused, firebase, pathname])
return <></>
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/Popup/popup-styles.js | src/components/Popup/popup-styles.js | export const popupStyles = {
popupContent: {
background: '#FFF',
padding: '0px 30px 30px 30px',
borderRadius: '8px',
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: '1080px',
maxWidth: '95vw',
maxHeight: '95vh',
fontSize: '16px',
overflowY: 'scroll',
scrollbarWidth: 'none',
'& ul': {
paddingLeft: '30px',
marginTop: '0px',
},
'& h2, & h3': {
marginBottom: '0px',
},
},
button: {
position: 'absolute',
top: '5px',
right: '5px',
fontSize: '20px',
background: 'none',
border: 'none',
cursor: 'pointer',
},
iconButton: {
backgroundColor: '#E5E5E5',
color: '#4F4F4F',
borderRadius: '50%',
padding: '0.5px',
fontSize: 24
}
}; | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/Popup/Popup.js | src/components/Popup/Popup.js | import React from "react";
import Modal from "@material-ui/core/Modal";
import Box from "@material-ui/core/Box";
import IconButton from '@material-ui/core/IconButton';
import CloseRoundedIcon from '@material-ui/icons/CloseRounded';
import { withStyles } from "@material-ui/core/styles";
import { popupStyles } from "./popup-styles.js";
const Popup = ({ classes, isOpen, onClose, children }) => {
return (
<Modal
open={isOpen}
onClose={onClose}
>
<Box className={classes.popupContent}>
<IconButton
onClick={onClose}
className={classes.button}
>
<CloseRoundedIcon
className={classes.iconButton}
/>
</IconButton>
{children}
</Box>
</Modal>
);
};
export default withStyles(popupStyles)(Popup); | javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-input/GridInput.js | src/components/problem-input/GridInput.js | import React, { createRef } from "react";
import './GridInput.css'
import Button from "@material-ui/core/Button";
import clsx from 'clsx';
import EquationEditor from "equation-editor-react";
import { Box, ClickAwayListener, Grow, Paper, Popper, TextField } from "@material-ui/core";
import CloseIcon from '@material-ui/icons/Close';
import { toast } from "react-toastify";
import { EQUATION_EDITOR_AUTO_COMMANDS, EQUATION_EDITOR_AUTO_OPERATORS } from "../../config/config";
import generateRandomInt from "../../util/generateRandomInt";
import { stagingProp } from "../../util/addStagingProperty";
class GridInput extends React.Component {
constructor(props) {
super(props);
this.state = {
gridState: props.defaultValue || this.genEmptyGrid(0, 0),
numRows: props.numRows || 0,
numCols: props.numCols || 0,
openChangeDimensions: false,
fer: Math.random() // fer: force equation-editor remount
};
this.gridRef = createRef()
this.changeDimRef = createRef()
this.rowId = `matrix-row-count-${generateRandomInt()}`
this.colId = `matrix-col-count-${generateRandomInt()}`
this.clearCells = this.clearCells.bind(this)
}
genEmptyGrid = (numRows, numCols) => new Array(numRows)
.fill(0)
.map(_ => new Array(numCols).fill(""))
cellFieldChange(str, idx, jdx) {
const gridState = this.state.gridState
gridState[idx][jdx] = str;
this.setState({
gridState
}, () => {
this.props.onChange(JSON.stringify(this.state.gridState))
})
}
dimensionFieldChange(evt, idx) {
if (idx === 0) {
this.setState({
numRows: +evt.target.value
})
} else {
this.setState({
numCols: +evt.target.value
})
}
}
clearCells(evt) {
if (evt != null && evt.type === 'submit') {
evt.preventDefault()
}
const { numRows, numCols } = this.state;
if (isNaN(numRows) || numRows <= 0 || isNaN(numCols) || numCols <= 0) {
toast.error('Matrix must be at least 1 x 1')
return
}
this.setState({
gridState: this.genEmptyGrid(numRows, numCols),
fer: Math.random()
}, () => {
this.props.onChange(JSON.stringify(this.state.gridState))
})
}
toggleChangeDimensionsPopover(to) {
this.setState({
openChangeDimensions: to
})
}
render() {
const { classes, index } = this.props;
const { gridState, fer } = this.state;
const revealClearButton = gridState.reduce((acc, cur, _) =>
acc + cur.reduce((_acc, _cur, __) =>
_acc + _cur.length, 0
), 0
) > 0; // only reveal the clear button if there is at least something in a cell
const showInitialSlide = gridState.length === 0;
return (
<Box textAlign={'center'} display={'flex'} flexDirection={'column'} alignItems={'center'} pt={1} pb={1}>
{showInitialSlide ? (
<form onSubmit={this.clearCells}>
<Box className={'grid-input-notice-container'} p={2} bgcolor={'rgb(249,249,250)'}
borderRadius={8}>
<div style={{
fontWeight: 700,
fontSize: 18
}}>
Enter in matrix dimensions.
</div>
<p>(This can be changed later)</p>
<Box display={'flex'} justifyContent={'center'} alignItems={'center'} mt={1}>
<TextField
id={this.rowId}
inputProps={{
"aria-labelledby": `${this.rowId}-label`
}}
variant={"outlined"} label={`# rows (Q${index})`} type={'number'}
className={'grid-input-dim-input'}
{...stagingProp({
"data-selenium-target": `grid-answer-row-input-${index}`
})}
onChange={(evt) => this.dimensionFieldChange(evt, 0)}
/>
<CloseIcon/>
<TextField
id={this.colId}
inputProps={{
"aria-labelledby": `${this.colId}-label`
}}
variant={"outlined"} label={`# cols (Q${index})`} type={'number'}
className={'grid-input-dim-input'}
{...stagingProp({
"data-selenium-target": `grid-answer-col-input-${index}`
})}
onChange={(evt) => this.dimensionFieldChange(evt, 1)}
/>
</Box>
<Box mt={2}>
<Button variant={'contained'} color={'primary'} type={'submit'}
{...stagingProp({
"data-selenium-target": `grid-answer-next-${index}`
})}
>
Next
</Button>
</Box>
</Box>
</form>
) : (
<div style={{
maxWidth: '100%'
}}>
<Box mb={1} display={'flex'} width={'100%'} alignItems={'center'} justifyContent={'flex-end'}>
<Button variant="contained" color="primary"
onClick={() => this.toggleChangeDimensionsPopover(true)}
ref={this.changeDimRef}>DIMENSIONS: {gridState.length} x {gridState[0].length}</Button>
<Popper open={this.state.openChangeDimensions}
anchorEl={this.changeDimRef.current} role={undefined}
transition disablePortal
placement={'bottom-end'}
style={{
zIndex: 10
}}
>
{({ TransitionProps, placement }) => (
<Grow
{...TransitionProps}
style={{ transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom' }}
>
<Paper>
<ClickAwayListener
onClickAway={() => this.toggleChangeDimensionsPopover(false)}>
<form onSubmit={(e) => {
e.preventDefault()
this.clearCells()
this.toggleChangeDimensionsPopover(false)
}}>
<Box className={'grid-input-notice-container'} p={2}
display={'flex'}
flexDirection={'column'} alignItems={'flex-end'} boxShadow={3}
borderRadius={3}>
<Box display={'flex'} justifyContent={'center'}
alignItems={'center'} mt={1}>
<TextField
size={'small'}
variant={"filled"} label={'# Rows'} type={'number'}
className={'grid-input-dim-input'}
onChange={(evt) => this.dimensionFieldChange(evt, 0)}
/>
<CloseIcon/>
<TextField
size={'small'}
variant={"filled"} label={'# Cols'} type={'number'}
className={'grid-input-dim-input'}
onChange={(evt) => this.dimensionFieldChange(evt, 1)}
/>
</Box>
<Box mt={1}>
<Button variant={'contained'} color={'primary'}
type={'submit'} size={'small'}>
Done
</Button>
</Box>
</Box>
</form>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
</Box>
<div ref={this.gridRef} className={clsx(this.props.isMatrix && 'matrix-container')}>
{this.props.isMatrix && <div className={'matrix-bracket-left'}/>}
<Box display={'grid'}
gridTemplateColumns={`repeat(${gridState[0].length}, 1fr)`}
overflow={'auto'}
pt={1}
pb={1}
gridGap={8}
justifyItems={'center'}
>
{
gridState.map((row, idx) =>
row.map((val, jdx) => {
return (
<center
className={clsx(classes.textBoxLatex, 'grid-cell')}
key={`cell-${idx}-${jdx}-${fer}`}
aria-label={`Cell (${idx}, ${jdx})`}
{...stagingProp({
"data-selenium-target": `grid-answer-cell-${jdx + idx * this.state.numCols}-${index}`
})}
>
<EquationEditor
value={val}
onChange={(str) => this.cellFieldChange(str, idx, jdx)}
style={{ width: "100%" }}
autoCommands={EQUATION_EDITOR_AUTO_COMMANDS}
autoOperatorNames={EQUATION_EDITOR_AUTO_OPERATORS}
/>
</center>
)
})
)
}
</Box>
{this.props.isMatrix && <div className={'matrix-bracket-right'}/>}
</div>
<Box mt={1} display={'flex'} width={'100%'} alignItems={'center'} justifyContent={'flex-end'}>
<Button variant="contained" color="secondary" onClick={this.clearCells}
className={clsx("revealable", revealClearButton && "revealed")}>clear all
cells</Button>
</Box>
</div>
)}
</Box>
)
}
}
export default GridInput;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-input/MatrixInput.js | src/components/problem-input/MatrixInput.js | import React from "react";
import GridInput from "./GridInput";
class MatrixInput extends React.Component {
// "$$\begin{bmatrix} -840 & 650 & -530 \\ 330 & 360 & 250 \\ -10 & 900 & 110 \end{bmatrix}$$"
render() {
return (
<GridInput {...this.props} isMatrix={true}/>
)
}
}
export default MatrixInput;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-input/MultipleChoice.js | src/components/problem-input/MultipleChoice.js | import React from 'react';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormControl from '@material-ui/core/FormControl';
import { renderText } from '../../platform-logic/renderText.js';
import { ThemeContext } from "../../config/config";
class MultipleChoice extends React.Component {
static contextType = ThemeContext;
constructor(props) {
super(props);
this.state = {
value: props.defaultValue || null,
};
}
handleChange = (event) => {
this.setState({ value: event.target.value });
this.props.onChange(event);
};
render() {
let { choices: _choices = [], variabilization } = this.props;
const choices = []
if (Array.isArray(_choices)) {
[...new Set(_choices)].forEach(choice => {
if (choice.includes(" above")) {
choices.push(choice);
} else {
choices.unshift(choice);
}
})
}
return (
<div style={{ marginRight: "5%", textAlign: "center" }}>
<FormControl>
<RadioGroup value={this.state.value} onChange={this.handleChange}>
{choices.length > 0
? choices.map((choice, i) =>
<FormControlLabel value={choice} control={<Radio/>}
label={renderText(choice, null, variabilization, this.context)}
key={choice}/>)
: "Error: This problem has no answer choices. Please submit feedback."}
</RadioGroup>
</FormControl>
</div>
);
}
}
export default MultipleChoice;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-input/ProblemInput.js | src/components/problem-input/ProblemInput.js | import React, { createRef } from "react";
import Grid from "@material-ui/core/Grid";
import TextField from "@material-ui/core/TextField";
import MultipleChoice from "./MultipleChoice";
import GridInput from "./GridInput";
import MatrixInput from "./MatrixInput";
import { renderText } from "../../platform-logic/renderText";
import clsx from "clsx";
import "mathlive";
import './ProblemInput.css'
import { shuffleArray } from "../../util/shuffleArray";
import { EQUATION_EDITOR_AUTO_COMMANDS, EQUATION_EDITOR_AUTO_OPERATORS, ThemeContext } from "../../config/config";
import { stagingProp } from "../../util/addStagingProperty";
import { parseMatrixTex } from "../../util/parseMatrixTex";
class ProblemInput extends React.Component {
static contextType = ThemeContext;
constructor(props) {
super(props);
this.equationRef = createRef()
this.mathFieldRef = React.createRef();
this.onEquationChange = this.onEquationChange.bind(this)
this.state = {
value: "",
isMathFieldFocused: false,
};
}
componentDidMount() {
document.addEventListener('click', this.handleClickOutside);
console.debug('problem', this.props.step, 'seed', this.props.seed)
if (this.isMatrixInput()) {
console.log('automatically determined matrix input to be the correct problem type')
}
const mqDisplayArea = this.equationRef?.current?.querySelector(".mq-editable-field > .mq-root-block")
if (mqDisplayArea != null) {
mqDisplayArea.ariaHidden = true
}
const textareaEl = this.equationRef?.current?.querySelector(".mq-textarea > textarea")
if (textareaEl != null) {
textareaEl.ariaLabel = `Answer question number ${this.props.index} here`
}
}
componentDidUpdate(_, prevState) {
if (prevState.isMathFieldFocused !== this.state.isMathFieldFocused && !this.state.isMathFieldFocused) {
const mathField = this.mathFieldRef.current;
if (mathField) {
mathField.executeCommand('hideVirtualKeyboard');
console.log("componentDidUpdate hide keyboard")
}}
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClickOutside);
}
handleFocus = () => {
this.setState({ isMathFieldFocused: true });
console.log('MathField is focused');
};
handleBlur = () => {
this.setState({ isMathFieldFocused: false });
console.log('MathField lost focus');
};
handleClickOutside = (event) => {
const mathField = this.mathFieldRef.current;
if (
mathField &&
!mathField.contains(event.target) &&
this.state.isMathFieldFocused
) {
console.log('Clicked outside keyboard');
}
};
isMatrixInput() {
if (this.props.step?.stepAnswer) {
return this.props.step?.problemType !== "MultipleChoice" &&
/\\begin{[a-zA-Z]?matrix}/.test(this.props.step.stepAnswer[0])
}
if (this.props.step?.hintAnswer) {
return this.props.step?.problemType !== "MultipleChoice" &&
/\\begin{[a-zA-Z]?matrix}/.test(this.props.step.hintAnswer[0])
}
}
onEquationChange(eq) {
const containerEl = this.equationRef?.current
const eqContentEl = this.equationRef?.current?.querySelector(".mq-editable-field")
const textareaEl = this.equationRef?.current?.querySelector(".mq-textarea > textarea")
if (textareaEl != null) {
// console.debug("not null!", textareaEl)
textareaEl.ariaLabel = `The current value is: ${eq}. Answer question number ${this.props.index} here.`
}
if (containerEl != null && eqContentEl != null) {
const eqContainer = eqContentEl.querySelector("*[mathquill-block-id]")
if (eqContainer != null) {
const tallestEqElement = Math.max(...Array.from(eqContainer.childNodes.values()).map(el => el.offsetHeight))
const newHeight = Math.max(tallestEqElement + 20, 50)
containerEl.style.height = `${newHeight}px`;
eqContainer.style.height = `${newHeight}px`;
}
}
this.props.setInputValState(eq)
}
render() {
const { classes, state, index, showCorrectness, allowRetry, variabilization } = this.props;
const { use_expanded_view, debug } = this.context;
let { problemType, stepAnswer, hintAnswer, units } = this.props.step;
const keepMCOrder = this.props.keepMCOrder;
const keyboardType = this.props.keyboardType;
const problemAttempted = state.isCorrect != null
const correctAnswer = Array.isArray(stepAnswer) ? stepAnswer[0] : hintAnswer[0]
const disableInput = problemAttempted && !allowRetry
if (this.isMatrixInput()) {
problemType = "MatrixInput"
}
try {
window.mathVirtualKeyboard.layouts = [keyboardType];
} catch {
window.mathVirtualKeyboard.layouts = ["default"];
}
return (
<Grid container spacing={0} justifyContent="center" alignItems="center"
className={clsx(disableInput && 'disable-interactions')}>
<Grid item xs={1} md={problemType === "TextBox" ? 4 : false}/>
<Grid item xs={9} md={problemType === "TextBox" ? 3 : 12}>
{(problemType === "TextBox" && this.props.step.answerType !== "string") && (
<math-field
ref={this.mathFieldRef}
math-virtual-keyboard-policy="sandboxed"
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onInput={evt => this.props.setInputValState(evt.target.value)}
style={{"display": "block"}}
value={(use_expanded_view && debug) ? correctAnswer : state.inputVal}
onChange={this.onEquationChange}
autoCommands={EQUATION_EDITOR_AUTO_COMMANDS}
autoOperatorNames={EQUATION_EDITOR_AUTO_OPERATORS}
>
</math-field>
)}
{(problemType === "TextBox" && this.props.step.answerType === "string") && (
<TextField
ref={this.textFieldRef}
inputProps={{
min: 0,
style: { textAlign: 'center' },
"aria-label": "Enter a response to the question above"
}}
{...stagingProp({
"data-selenium-target": `string-answer-${index}`
})}
error={showCorrectness && state.isCorrect === false}
className={classes.inputField}
variant="outlined"
onChange={(evt) => this.props.editInput(evt)}
onKeyPress={(evt) => this.props.handleKey(evt)}
InputProps={{
classes: {
notchedOutline: ((showCorrectness && state.isCorrect !== false && state.usedHints) ? classes.muiUsedHint : null)
}
}}
{...(use_expanded_view && debug) ? {
defaultValue: correctAnswer
} : {}}
>
</TextField>
)}
{(problemType === "TextBox" && this.props.step.answerType === "short-essay") && (
<textarea
className="short-essay-input"
onChange={(evt) => this.props.editInput(evt)}
onKeyPress={(evt) => this.props.handleKey(evt)}
>
</textarea>
)}
{(problemType === "MultipleChoice" && keepMCOrder) ? (
<MultipleChoice
onChange={(evt) => this.props.editInput(evt)}
choices={[...this.props.step.choices].reverse()}
index={index}
{...(use_expanded_view && debug) ? {
defaultValue: correctAnswer
} : {}}
variabilization={variabilization}
/>
) :
(problemType === "MultipleChoice") && (
<MultipleChoice
onChange={(evt) => this.props.editInput(evt)}
choices={shuffleArray(this.props.step.choices, this.props.seed)}
index={index}
{...(use_expanded_view && debug) ? {
defaultValue: correctAnswer
} : {}}
variabilization={variabilization}
/>
)}
{problemType === "GridInput" && (
<GridInput
onChange={(newVal) => this.props.setInputValState(newVal)}
numRows={this.props.step.numRows}
numCols={this.props.step.numCols}
context={this.props.context}
classes={this.props.classes}
index={index}
{...(use_expanded_view && debug) ? {
defaultValue: parseMatrixTex(correctAnswer)[0]
} : {}}
/>
)}
{problemType === "MatrixInput" && (
<MatrixInput
onChange={(newVal) => this.props.setInputValState(newVal)}
numRows={this.props.step.numRows}
numCols={this.props.step.numCols}
context={this.props.context}
classes={this.props.classes}
index={index}
{...(use_expanded_view && debug) ? {
defaultValue: parseMatrixTex(correctAnswer)[0]
} : {}}
/>
)}
</Grid>
<Grid item xs={2} md={1}>
<div style={{ marginLeft: "20%" }}>
{units && renderText(units, this.context.problemID, variabilization, this.context)}
</div>
</Grid>
<Grid item xs={false} md={problemType === "TextBox" ? 3 : false}/>
</Grid>
)
}
}
export default ProblemInput
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/ReloadIcon.js | src/components/problem-layout/ReloadIcon.js | import React from 'react';
import Tooltip from '@material-ui/core/Tooltip';
import IconButton from '@material-ui/core/IconButton';
// This reload icon is used to regenerate ChatGPT generated hints
const ReloadIconButton = ({ onClick }) => (
<Tooltip title="Regenerate Hint">
<IconButton onClick={onClick} aria-label="regenerate">
<img
src={`${process.env.PUBLIC_URL}/static/images/icons/reload.png`}
alt="Reload Icon"
style={{ width: '24px', height: '24px' }}
/>
</IconButton>
</Tooltip>
);
export default ReloadIconButton;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/HintSystem.js | src/components/problem-layout/HintSystem.js | import React from "react";
import { withStyles } from "@material-ui/core/styles";
import Accordion from "@material-ui/core/Accordion";
import AccordionSummary from "@material-ui/core/AccordionSummary";
import AccordionDetails from "@material-ui/core/AccordionDetails";
import Typography from "@material-ui/core/Typography";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import HintTextbox from "./HintTextbox.js";
import {
renderText,
chooseVariables,
} from "../../platform-logic/renderText.js";
import SubHintSystem from "./SubHintSystem.js";
import { ThemeContext } from "../../config/config";
import Spacer from "../Spacer";
import { stagingProp } from "../../util/addStagingProperty";
import ErrorBoundary from "../ErrorBoundary";
import withTranslation from '../../util/withTranslation';
import ReloadIcon from './ReloadIcon';
class HintSystem extends React.Component {
static contextType = ThemeContext;
constructor(props) {
super(props);
var subHintsFinished = [];
for (var i = 0; i < this.props.hints.length; i++) {
subHintsFinished.push(
new Array(
this.props.hints[i].subHints !== undefined
? this.props.hints[i].subHints.length
: 0
).fill(0)
);
}
this.giveStuFeedback = props.giveStuFeedback;
this.unlockFirstHint = props.unlockFirstHint;
this.isIncorrect = props.isIncorrect;
this.giveHintOnIncorrect = props.giveHintOnIncorrect
this.generateHintFromGPT = props.generateHintFromGPT;
this.state = {
latestStep: 0,
currentExpanded: (this.unlockFirstHint || this.isIncorrect) ? 0 : -1,
hintAnswer: "",
showSubHints: new Array(this.props.hints.length).fill(false),
subHintsFinished: subHintsFinished,
};
if (this.unlockFirstHint && this.props.hintStatus.length > 0) {
this.props.unlockHint(0, this.props.hints[0].type);
}
if (this.giveHintOnIncorrect && this.isIncorrect && this.props.hintStatus.length > 0) {
this.props.unlockHint(0, this.props.hints[0].type);
}
}
unlockHint = (event, expanded, i) => {
if (this.state.currentExpanded === i ) {
this.setState({ currentExpanded: -1 });
} else {
this.setState({ currentExpanded: i });
if (expanded && i < this.props.hintStatus.length) {
this.props.unlockHint(i, this.props.hints[i].type);
}
this.setState({ latestStep: i });
}
};
isLocked = (hintNum) => {
if (hintNum === 0) {
return false;
}
var dependencies = this.props.hints[hintNum].dependencies;
var isSatisfied = dependencies.every(
(dependency) => this.props.hintStatus[dependency] === 1
);
return !isSatisfied;
};
toggleSubHints = (event, i) => {
this.setState(
(prevState) => {
var displayHints = prevState.showSubHints;
displayHints[i] = !displayHints[i];
return {
showSubHints: displayHints,
};
},
() => {
this.props.answerMade(
this.index,
this?.step?.knowledgeComponents,
false
);
}
);
};
unlockSubHint = (hintNum, i, isScaffold) => {
this.setState(
(prevState) => {
prevState.subHintsFinished[i][hintNum] = !isScaffold ? 1 : 0.5;
return { subHintsFinished: prevState.subHintsFinished };
},
() => {
this.context.firebase.log(
null,
this.props.problemID,
this.step,
null,
null,
this.state.subHintsFinished,
"unlockSubHint",
chooseVariables(this.props.stepVars, this.props.seed),
this.props.lesson,
this.props.courseName
);
}
);
};
submitSubHint = (parsed, hint, isCorrect, i, hintNum) => {
if (isCorrect) {
this.setState((prevState) => {
prevState.subHintsFinished[i][hintNum] = 1;
return { subHintsFinished: prevState.subHintsFinished };
});
}
this.context.firebase.hintLog(
parsed,
this.props.problemID,
this.step,
hint,
isCorrect,
this.state.hintsFinished,
chooseVariables(
Object.assign({}, this.props.stepVars, hint.variabilization),
this.props.seed
),
this.props.lesson,
this.props.courseName
);
};
render() {
const { translate } = this.props;
const { classes, index, hints, problemID, seed, stepVars } = this.props;
const { currentExpanded, showSubHints } = this.state;
const { debug, use_expanded_view } = this.context;
return (
<div className={classes.root}>
{/* {this.giveDynamicHint && <div>hi</div>} */}
{hints.map((hint, i) => (
<Accordion
key={`${problemID}-${hint.id}`}
onChange={(event, expanded) =>
this.unlockHint(event, expanded, i)
}
disabled={
this.isLocked(i) && !(use_expanded_view && debug)
}
expanded={
currentExpanded === i ||
(use_expanded_view != null &&
use_expanded_view &&
debug)
}
defaultExpanded={false}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
{...stagingProp({
"data-selenium-target": `hint-expand-${i}-${index}`,
})}
>
<Typography className={classes.heading}>
{translate('hintsystem.hint') + (i + 1) + ": "}
{renderText(
hint.title === "nan" ? "" : hint.title,
problemID,
chooseVariables(
Object.assign(
{},
stepVars,
hint.variabilization
),
seed
),
this.context
)}
</Typography>
</AccordionSummary>
<AccordionDetails >
<div style={{ width: "100%" }}>
<Typography
component={"span"}
style={{ width: "100%" }}
>
{renderText(
hint.text,
problemID,
chooseVariables(
Object.assign(
{},
stepVars,
hint.variabilization
),
seed
),
this.context
)}
{hint.type === "scaffold" ? (
<div>
<Spacer />
<HintTextbox
hintNum={i}
hint={hint}
index={index}
submitHint={this.props.submitHint}
seed={this.props.seed}
hintVars={Object.assign(
{},
this.props.stepVars,
hint.variabilization
)}
toggleHints={(event) =>
this.toggleSubHints(event, i)
}
giveStuFeedback={
this.giveStuFeedback
}
/>
</div>
) : (
""
)}
{(showSubHints[i] ||
(use_expanded_view && debug)) &&
hint.subHints !== undefined ? (
<div className="SubHints">
<Spacer />
<ErrorBoundary
componentName={"SubHintSystem"}
>
<SubHintSystem
giveStuFeedback={
this.giveStuFeedback
}
unlockFirstHint={
this.unlockFirstHint
}
problemID={problemID}
hints={hint.subHints}
unlockHint={this.unlockSubHint}
hintStatus={
this.state.subHintsFinished[
i
]
}
submitHint={this.submitSubHint}
parent={i}
index={index}
seed={this.props.seed}
hintVars={Object.assign(
{},
this.props.stepVars,
hint.variabilization
)}
/>
</ErrorBoundary>
<Spacer />
</div>
) : (
""
)}
</Typography>
{/* Check if the hint is dynamic (AI-generated) */}
{hint.type === "gptHint"
&& !this.props.isGeneratingHint
&& (
<div
style={{
display: "flex",
justifyContent: "flex-end",
}}
>
<ReloadIcon
style={{
cursor: "pointer",
fontSize: "24px",
}}
onClick={() => this.generateHintFromGPT(true)}
title="Regenerate Hint"
/>
</div>
)}
</div>
</AccordionDetails>
</Accordion>
))}
</div>
);
}
}
const styles = (theme) => ({
root: {
width: "100%",
},
heading: {
fontSize: theme.typography.pxToRem(15),
fontWeight: theme.typography.fontWeightRegular,
},
});
export default withStyles(styles)(withTranslation(HintSystem));
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/ProblemCard.js | src/components/problem-layout/ProblemCard.js | import React from "react";
import Card from "@material-ui/core/Card";
import CardActions from "@material-ui/core/CardActions";
import CardContent from "@material-ui/core/CardContent";
import Grid from "@material-ui/core/Grid";
import Button from "@material-ui/core/Button";
import IconButton from "@material-ui/core/IconButton";
import { fetchDynamicHint } from "./DynamicHintHelper";
import { checkAnswer } from "../../platform-logic/checkAnswer.js";
import styles from "./common-styles.js";
import { withStyles } from "@material-ui/core/styles";
import HintSystem from "./HintSystem.js";
import {
chooseVariables,
renderText,
} from "../../platform-logic/renderText.js";
import {
DYNAMIC_HINT_URL,
DYNAMIC_HINT_TEMPLATE,
ENABLE_BOTTOM_OUT_HINTS,
ThemeContext,
} from "../../config/config.js";
import "./ProblemCard.css";
import ProblemInput from "../problem-input/ProblemInput";
import Spacer from "../Spacer";
import { stagingProp } from "../../util/addStagingProperty";
import ErrorBoundary from "../ErrorBoundary";
import {
toastNotifyCompletion,
toastNotifyCorrectness, toastNotifyEmpty
} from "./ToastNotifyCorrectness";
import { joinList } from "../../util/formListString";
import withTranslation from "../../util/withTranslation.js"
import CryptoJS from "crypto-js";
class ProblemCard extends React.Component {
static contextType = ThemeContext;
constructor(props, context) {
super(props);
//console.log("problem lesson props:", props);
this.translate = props.translate
this.step = props.step;
this.index = props.index;
this.giveStuFeedback = props.giveStuFeedback;
this.giveStuHints = props.giveStuHints;
this.unlockFirstHint = props.unlockFirstHint;
this.giveHintOnIncorrect = props.giveHintOnIncorrect
this.keepMCOrder = props.keepMCOrder;
this.keyboardType = props.keyboardType;
this.allowRetry = this.giveStuFeedback;
this.giveStuBottomHint = props.giveStuBottomHint;
this.giveDynamicHint = props.giveDynamicHint;
this.showHints = this.giveStuHints == null || this.giveStuHints;
this.showCorrectness = this.giveStuFeedback;
this.expandFirstIncorrect = false;
this.problemTitle = props.problemTitle;
this.problemSubTitle = props.problemSubTitle;
this.prompt_template = props.prompt_template
? props.prompt_template
: DYNAMIC_HINT_TEMPLATE;
console.debug(
"this.step",
this.step,
"showHints",
this.showHints,
"hintPathway",
context.hintPathway
);
this.hints = this.giveDynamicHint
? []
: JSON.parse(JSON.stringify(this.step.hints[context.hintPathway]));
for (let hint of this.hints) {
hint.dependencies = hint.dependencies.map((dependency) =>
this._findHintId(this.hints, dependency)
);
if (hint.subHints) {
for (let subHint of hint.subHints) {
subHint.dependencies = subHint.dependencies.map(
(dependency) =>
this._findHintId(hint.subHints, dependency)
);
}
}
}
// Bottom out hints option
if (
this.giveStuBottomHint &&
!(context.debug && context["use_expanded_view"])
) {
// Bottom out hints
this.hints.push({
id: this.step.id + "-h" + (this.hints.length + 1),
title: this.translate('hintsystem.answer'),
text: this.translate('hintsystem.answerIs') + this.step.stepAnswer,
type: "bottomOut",
dependencies: Array.from(Array(this.hints.length).keys()),
});
// Bottom out sub hints
this.hints.map((hint, i) => {
if (hint.type === "scaffold") {
if (hint.subHints == null) {
hint.subHints = [];
}
hint.subHints.push({
id:
this.step.id +
"-h" +
i +
"-s" +
(hint.subHints.length + 1),
title: this.translate('hintsystem.answer'),
text: this.translate('hintsystem.answerIs') + hint.hintAnswer[0],
type: "bottomOut",
dependencies: Array.from(
Array(hint.subHints.length).keys()
),
});
}
return null;
});
}
this.state = {
inputVal: "",
isCorrect: context.use_expanded_view && context.debug ? true : null,
checkMarkOpacity:
context.use_expanded_view && context.debug ? "100" : "0",
displayHints: false,
hintsFinished: new Array(this.hints.length).fill(0),
equation: "",
usedHints: false,
dynamicHint: "",
bioInfo: "",
enableHintGeneration: true,
activeHintType: "none", // "none", or "normal".
hints: this.hints,
// When we are currently streaming the response from ChatGPT, this variable is `true`
isGeneratingHint: false,
lastAIHintHash: null,
};
// This is used for AI hint generation
if (this.giveDynamicHint) {
const gptHint = {
id: this.step.id + "-h0", // Unique ID for the GPT hint
title: "ChatGPT AI Hint", // Translated title
text: "Loading...",
type: "gptHint", // Custom type for GPT hint
dependencies: [],
};
this.hints.unshift(gptHint);
}
}
hashAnswer = (answer) => {
return CryptoJS.SHA256(answer).toString();
};
_findHintId = (hints, targetId) => {
for (var i = 0; i < hints.length; i++) {
if (hints[i].id === targetId) {
return i;
}
}
console.debug("hint not found..?", hints, "target:", targetId);
return -1;
};
// TODO: Incorporate this in the AI Hinting workflow
updateBioInfo() {
const bioInfo = JSON.parse(localStorage.getItem("bioInfo"));
if (bioInfo) {
const {
gender,
age,
confidenceQ1,
confidenceQ2,
judgementQ1,
judgementQ2,
judgementQ3,
other,
} = bioInfo;
const bio = `I'm a ${gender} and I'm ${age} years old. ${confidenceQ1}. ${confidenceQ2}.
For the statement that "if I had more time for practice, I would be better in mathematics", my answer is ${judgementQ1}.
For the statement that "if I was more patient while solving mathematical problems, I would be better in mathematics", my answer is ${judgementQ2}.
For the statement that "No matter how much time I devote for studying mathematics, I can’t improve my grades", my answer is ${judgementQ3}.
${other}
`;
this.setState({ bioInfo: bio });
}
}
componentDidMount() {
// Start an asynchronous task
this.updateBioInfo();
console.log("student show hints status: ", this.showHints);
}
componentDidUpdate(prevProps) {
// Check if specific props have changed
if (
this.props.clearStateOnPropChange !==
prevProps.clearStateOnPropChange
) {
// Clear out state variables
this.setState({
dynamicHint: "",
});
this.updateBioInfo();
}
}
submit = () => {
console.debug("submitting problem");
const { inputVal, hintsFinished } = this.state;
const {
variabilization,
knowledgeComponents,
precision,
stepAnswer,
answerType,
stepBody,
stepTitle,
} = this.step;
const { seed, problemVars, problemID, courseName, answerMade, lesson } =
this.props;
if (inputVal == '') {
toastNotifyEmpty(this.translate)
return;
}
const [parsed, correctAnswer, reason] = checkAnswer({
attempt: inputVal,
actual: stepAnswer,
answerType: answerType,
precision: precision,
variabilization: chooseVariables(
Object.assign({}, problemVars, variabilization),
seed
),
questionText: stepBody.trim() || stepTitle.trim(),
});
const isCorrect = !!correctAnswer;
this.context.firebase.log(
parsed,
problemID,
this.step,
null,
isCorrect,
hintsFinished,
"answerStep",
chooseVariables(
Object.assign({}, problemVars, variabilization),
seed
),
lesson,
courseName,
this.giveDynamicHint ? "dynamic" : "regular",
this.state.dynamicHint,
this.state.bioInfo
);
if (this.showCorrectness) {
toastNotifyCorrectness(isCorrect, reason, this.translate);
} else {
toastNotifyCompletion(this.translate);
}
this.setState({
isCorrect,
checkMarkOpacity: isCorrect ? "100" : "0",
});
answerMade(this.index, knowledgeComponents, isCorrect);
};
editInput = (event) => {
this.setInputValState(event.target.value);
this.setState({
enableHintGeneration: true,
});
};
setInputValState = (inputVal) => {
this.setState(({ isCorrect }) => ({
inputVal,
isCorrect: isCorrect ? true : null,
}));
};
handleKey = (event) => {
if (event.key === "Enter") {
this.submit();
}
};
toggleHints = (event) => {
if (this.giveDynamicHint && !this.state.activeHintType !== "normal") {
this.generateHintFromGPT();
} else if (!this.state.displayHints) {
this.setState(
() => ({
enableHintGeneration: false,
}))
}
this.setState(
(prevState) => ({
activeHintType: prevState.activeHintType === "normal" ? "none" : "normal"
}),
() => {
this.props.answerMade(
this.index,
this.step.knowledgeComponents,
false
);
}
);
};
unlockHint = (hintNum, hintType) => {
// Mark question as wrong if hints are used (on the first time)
const { seed, problemVars, problemID, courseName, answerMade, lesson } =
this.props;
const { isCorrect, hintsFinished } = this.state;
const { knowledgeComponents, variabilization } = this.step;
if (hintsFinished.reduce((a, b) => a + b) === 0 && isCorrect !== true) {
this.setState({ usedHints: true });
answerMade(this.index, knowledgeComponents, false);
}
// If the user has not opened a scaffold before, mark it as in-progress.
if (hintsFinished[hintNum] !== 1) {
this.setState(
(prevState) => {
prevState.hintsFinished[hintNum] =
hintType !== "scaffold" ? 1 : 0.5;
return { hintsFinished: prevState.hintsFinished };
},
() => {
const { firebase } = this.context;
firebase.log(
null,
problemID,
this.step,
this.hints[hintNum],
null,
hintsFinished,
"unlockHint",
chooseVariables(
Object.assign({}, problemVars, variabilization),
seed
),
lesson,
courseName,
this.giveDynamicHint ? "dynamic" : "regular",
this.state.dynamicHint,
this.state.bioInfo
);
}
);
}
};
submitHint = (parsed, hint, isCorrect, hintNum) => {
if (isCorrect) {
this.setState((prevState) => {
prevState.hintsFinished[hintNum] = 1;
return { hintsFinished: prevState.hintsFinished };
});
}
this.context.firebase.hintLog(
parsed,
this.props.problemID,
this.step,
hint,
isCorrect,
this.state.hintsFinished,
chooseVariables(
Object.assign(
{},
this.props.problemVars,
this.step.variabilization
),
this.props.seed
),
this.props.lesson,
this.props.courseName,
this.giveDynamicHint ? "dynamic" : "regular",
this.state.dynamicHint,
this.state.bioInfo
);
};
generateGPTHintParameters = (prompt_template, bio_info) => {
let inputVal = this.state.inputVal || "The student did not provide an answer.";
let correctAnswer = Array.isArray(this.step.stepAnswer) ? this.step.stepAnswer[0] : "";
const problemTitle = this.problemTitle || "Problem Title";
const problemSubTitle = this.problemSubTitle || "Problem Subtitle";
const questionTitle = this.step.stepTitle || "Question Title";
const questionSubTitle = this.step.stepBody || "Question Subtitle";
// Replace placeholders in the template with actual values
const promptContent = prompt_template
.replace("{problem_title}", problemTitle)
.replace("{problem_subtitle}", problemSubTitle)
.replace("{question_title}", questionTitle)
.replace("{question_subtitle}", questionSubTitle)
.replace("{student_answer}", inputVal)
.replace("{correct_answer}", correctAnswer);
return {
role: "user",
message: promptContent
}
};
generateHintFromGPT = async (forceRegenerate) => {
const { inputVal, lastAIHintHash, isGeneratingHint } = this.state;
const currentHash = this.hashAnswer(inputVal);
// If a hint is currently being generated through streaming,
// do not generate a new hint
if (isGeneratingHint) {
return;
}
// If the current hash matches the last hash, skip regeneration
// If forceRegenerate is true, the regenerate button was pressed
if ((currentHash === lastAIHintHash) && !forceRegenerate) {
console.log("Hint already generated for this answer, skipping regeneration.");
return;
}
this.setState({
dynamicHint: "Loading...", // Clear previous hint
isGeneratingHint: true,
lastAIHintHash: currentHash,
});
const [parsed, correctAnswer, reason] = checkAnswer({
attempt: this.state.inputVal,
actual: this.step.stepAnswer,
answerType: this.step.answerType,
precision: this.step.precision,
variabilization: chooseVariables(
Object.assign(
{},
this.props.problemVars,
this.props.variabilization
),
this.props.seed
),
questionText:
this.step.stepBody.trim() || this.step.stepTitle.trim(),
});
const isCorrect = !!correctAnswer;
// Define callbacks
const onChunkReceived = (streamedHint) => {
this.setState((prevState) => ({
hints: prevState.hints.map((hint) =>
hint.type === "gptHint"
? { ...hint, text: streamedHint || this.translate("hintsystem.errorHint") }
: hint
),
}));
};
/** When the hint generation is completed, set the `isGeneratingHint` state to false
* in order to regenerate the hint.
*/
const onSuccessfulCompletion = () => {
this.setState({
isGeneratingHint: false,
});
}
/** When we receive an error in the hint generation process,
* revert back to manual hints.
*/
const onError = (error) => {
this.setState({
isGeneratingHint: false,
})
console.error("Error generating AI hint:", error);
this.hints = JSON.parse(
JSON.stringify(this.step.hints[this.context.hintPathway])
);
for (let hint of this.hints) {
hint.dependencies = hint.dependencies.map((dependency) =>
this._findHintId(this.hints, dependency)
);
if (hint.subHints) {
for (let subHint of hint.subHints) {
subHint.dependencies = subHint.dependencies.map(
(dependency) =>
this._findHintId(hint.subHints, dependency)
);
}
}
}
// Bottom out hints option
if (
this.giveStuBottomHint
) {
// Bottom out hints
this.hints.push({
id: this.step.id + "-h" + (this.hints.length + 1),
title: this.translate('hintsystem.answer'),
text: this.translate('hintsystem.answerIs') + this.step.stepAnswer,
type: "bottomOut",
dependencies: Array.from(Array(this.hints.length).keys()),
});
// Bottom out sub hints
this.hints.map((hint, i) => {
if (hint.type === "scaffold") {
if (hint.subHints == null) {
hint.subHints = [];
}
hint.subHints.push({
id:
this.step.id +
"-h" +
i +
"-s" +
(hint.subHints.length + 1),
title: this.translate('hintsystem.answer'),
text: this.translate('hintsystem.answerIs') + hint.hintAnswer[0],
type: "bottomOut",
dependencies: Array.from(
Array(hint.subHints.length).keys()
),
});
}
return null;
});
}
this.setState({
hints: this.hints,
giveDynamicHint: false, // Switch to manual hints
activeHintType: "normal",
dynamicHint: "Failed to generate AI hint. Displaying manual hints.",
hintsFinished: new Array(this.hints.length).fill(0),
});
};
// Call ChatGPT to fetch the dynamic hint using streaming
fetchDynamicHint(
DYNAMIC_HINT_URL,
this.generateGPTHintParameters(this.prompt_template, this.state.bioInfo),
onChunkReceived,
onSuccessfulCompletion,
onError,
this.props.problemID,
chooseVariables(
Object.assign(
{},
this.props.problemVars,
this.step.variabilization
),
this.props.seed
),
this.context
);
// TODO: Update firebase logging to log when
// 1. The dynamic hint is opened
// 2. The regenerate button is clicked
this.context.firebase.log(
parsed,
this.props.problemID,
this.step,
"",
isCorrect,
this.state.hintsFinished,
"requestDynamicHint",
chooseVariables(
Object.assign(
{},
this.props.problemVars,
this.props.variabilization
),
this.props.seed
),
this.props.lesson,
this.props.courseName,
"dynamic",
this.state.dynamicHint,
this.state.bioInfo
);
};
render() {
const { translate } = this.props;
const { classes, problemID, problemVars, seed } = this.props;
const { isCorrect } = this.state;
const { debug, use_expanded_view } = this.context;
const problemAttempted = isCorrect != null;
return (
<Card className={classes.card}>
<CardContent>
<h2 className={classes.stepHeader}>
{renderText(
this.step.stepTitle,
problemID,
chooseVariables(
Object.assign(
{},
problemVars,
this.step.variabilization
),
seed
),
this.context
)}
<hr />
</h2>
<div className={classes.stepBody}>
{renderText(
this.step.stepBody,
problemID,
chooseVariables(
Object.assign(
{},
problemVars,
this.step.variabilization
),
seed
),
this.context
)}
</div>
{(this.state.activeHintType === "normal" || (debug && use_expanded_view)) &&
this.showHints && (
<div className="Hints">
<ErrorBoundary
componentName={"HintSystem"}
descriptor={"hint"}
>
<HintSystem
key={`hints-${this.giveDynamicHint ? 'dynamic' : 'manual'}`}
giveHintOnIncorrect={this.giveHintOnIncorrect}
giveDynamicHint={this.giveDynamicHint}
giveStuFeedback={this.giveStuFeedback}
unlockFirstHint={this.unlockFirstHint}
problemID={this.props.problemID}
index={this.props.index}
step={this.step}
hints={this.state.hints}
unlockHint={this.unlockHint}
hintStatus={this.state.hintsFinished}
submitHint={this.submitHint}
seed={this.props.seed}
stepVars={Object.assign(
{},
this.props.problemVars,
this.step.variabilization
)}
answerMade={this.props.answerMade}
lesson={this.props.lesson}
courseName={this.props.courseName}
isIncorrect={this.expandFirstIncorrect}
generateHintFromGPT={this.generateHintFromGPT}
isGeneratingHint={this.state.isGeneratingHint}
/>
</ErrorBoundary>
<Spacer />
</div>
)}
<div className={classes.root}>
<ProblemInput
variabilization={chooseVariables(
Object.assign(
{},
this.props.problemVars,
this.step.variabilization
),
this.props.seed
)}
allowRetry={this.allowRetry}
giveStuFeedback={this.giveStuFeedback}
showCorrectness={this.showCorrectness}
classes={classes}
state={this.state}
step={this.step}
seed={this.props.seed}
keepMCOrder={this.props.keepMCOrder}
keyboardType={this.props.keyboardType}
_setState={(state) => this.setState(state)}
context={this.context}
editInput={this.editInput}
setInputValState={this.setInputValState}
handleKey={this.handleKey}
index={this.props.index}
/>
</div>
</CardContent>
<CardActions>
<Grid
container
spacing={0}
justifyContent="center"
alignItems="center"
>
<Grid item xs={false} sm={false} md={4} />
<Grid item xs={4} sm={4} md={1}>
{this.showHints && (
<center>
<IconButton
aria-label="delete"
onClick={this.toggleHints}
title="View available hints"
disabled={
!this.state.enableHintGeneration
}
className="image-container"
{...stagingProp({
"data-selenium-target": `hint-button-${this.props.index}`,
})}
>
<img
src={`${process.env.PUBLIC_URL}/static/images/icons/raise_hand.png`}
className={
this.state.enableHintGeneration
? "image"
: "image image-grayed-out"
}
alt="hintToggle"
/>
</IconButton>
</center>
)}
</Grid>
<Grid item xs={4} sm={4} md={2}>
<center>
<Button
className={classes.button}
style={{ width: "80%" }}
size="small"
onClick={this.submit}
disabled={
(use_expanded_view && debug) ||
(!this.allowRetry && problemAttempted)
}
{...stagingProp({
"data-selenium-target": `submit-button-${this.props.index}`,
})}
>
{translate('problem.Submit')}
</Button>
</center>
</Grid>
<Grid item xs={4} sm={3} md={1}>
<div
style={{
display: "flex",
flexDirection: "row",
alignContent: "center",
justifyContent: "center",
}}
>
{(!this.showCorrectness ||
!this.allowRetry) && (
<img
className={classes.checkImage}
style={{
opacity:
this.state.isCorrect == null
? 0
: 1,
width: "45%",
}}
alt="Exclamation Mark Icon"
title={`The instructor has elected to ${joinList(
!this.showCorrectness &&
"hide correctness",
!this.allowRetry &&
"disallow retries"
)}`}
{...stagingProp({
"data-selenium-target": `step-correct-img-${this.props.index}`,
})}
src={`${process.env.PUBLIC_URL}/static/images/icons/exclamation.svg`}
/>
)}
{this.state.isCorrect &&
this.showCorrectness &&
this.allowRetry && (
<img
className={classes.checkImage}
style={{
opacity:
this.state.checkMarkOpacity,
width: "45%",
}}
alt="Green Checkmark Icon"
{...stagingProp({
"data-selenium-target": `step-correct-img-${this.props.index}`,
})}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | true |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/ViewAllProblems.js | src/components/problem-layout/ViewAllProblems.js | import React, {
useEffect,
useState,
useMemo,
useContext,
} from 'react';
import { useParams } from 'react-router-dom';
import {
AppBar,
Toolbar,
Container,
Grid,
IconButton,
Box,
Typography,
makeStyles,
} from '@material-ui/core';
import HelpOutlineOutlinedIcon from '@material-ui/icons/HelpOutlineOutlined';
import BrandLogoNav from '@components/BrandLogoNav';
import Popup from '@components/Popup/Popup';
import About from '../../pages/Posts/About';
import ProblemWrapper from '@components/problem-layout/ProblemWrapper';
import { findLessonById, ThemeContext, SHOW_COPYRIGHT, SITE_NAME } from '../../config/config.js';
import { CONTENT_SOURCE } from '@common/global-config';
import withTranslation from '../../util/withTranslation.js';
const useStyles = makeStyles(theme => ({
root: {
backgroundColor: theme.palette.background.default,
minHeight: '100vh',
display: 'flex',
flexDirection: 'column',
},
container: {
flexGrow: 1,
padding: theme.spacing(4, 0),
},
problemCard: {
position: 'relative', // allow absolute positioning of id badge
marginBottom: theme.spacing(4),
},
noFooterWrapper: {
'& footer': {
display: 'none',
},
'& div[width="100%"]': {
display: 'none',
},
},
loadingBox: {
textAlign: 'center',
padding: theme.spacing(2),
},
footer: {
marginTop: 'auto',
padding: theme.spacing(2),
display: 'flex',
alignItems: 'center',
},
spacer: {
flexGrow: 1,
},
idBadge: {
position: 'absolute',
top: theme.spacing(1),
right: theme.spacing(1),
backgroundColor: 'rgba(255,255,255,0.8)',
padding: theme.spacing(0.5, 1),
borderRadius: theme.shape.borderRadius,
},
}));
const BATCH_SIZE = 3;
const ViewAllProblems = ({ translate }) => {
const classes = useStyles();
const { lessonID } = useParams();
const context = useContext(ThemeContext);
const [lesson, setLesson] = useState(null);
const [problemPool, setProblemPool] = useState([]);
const [filteredProblems, setFilteredProblems] = useState([]);
const [visibleProblems, setVisibleProblems] = useState([]);
const [showPopup, setShowPopup] = useState(false);
const [seed] = useState(() => Date.now().toString());
// no-op handlers for ProblemWrapper
const displayMastery = () => {};
const problemComplete = () => {};
// Load pool
useEffect(() => {
import(`@generated/processed-content-pool/${CONTENT_SOURCE}.json`)
.then(m => setProblemPool(m.default || []))
.catch(console.error);
}, []);
// Find lesson
useEffect(() => {
const found = findLessonById(lessonID);
if (found) setLesson(found);
}, [lessonID]);
// Filter by objectives
const memoFiltered = useMemo(() => {
if (!lesson || problemPool.length === 0) return [];
const pool = problemPool.filter(problem =>
problem.steps.some(step =>
(context.skillModel[step.id] || []).some(kc => kc in lesson.learningObjectives)
)
);
return pool;
}, [lesson, problemPool, context.skillModel]);
useEffect(() => {
setFilteredProblems(memoFiltered);
}, [memoFiltered]);
// Chunk rendering
useEffect(() => {
setVisibleProblems(filteredProblems);
}, [filteredProblems]);
// Safely build topics string
const topicsText = lesson?.topics
? Array.isArray(lesson.topics)
? lesson.topics.join(', ')
: String(lesson.topics)
: '';
return (
<Box className={classes.root}>
<AppBar position="static">
<Toolbar>
<Grid container alignItems="center">
<Grid item xs={3}><BrandLogoNav /></Grid>
<Grid item xs={6} style={{ textAlign: 'center' }}>
{lesson?.name}{topicsText && `: ${topicsText}`}
</Grid>
<Grid item xs={3} />
</Grid>
</Toolbar>
</AppBar>
<Container maxWidth="lg" className={classes.container}>
{visibleProblems.length ? visibleProblems.map(problem => (
<Box key={problem.id} className={classes.problemCard}>
{/* ID badge */}
<Box className={classes.idBadge}>
<Typography variant="caption" color="textSecondary">
{problem.id}
</Typography>
</Box>
<Box className={classes.noFooterWrapper}>
<ProblemWrapper
autoScroll={false}
problem={problem}
lesson={lesson}
seed={seed}
clearStateOnPropChange={lessonID}
displayMastery={displayMastery}
problemComplete={problemComplete}
/>
</Box>
</Box>
)) : (
<Box className={classes.loadingBox}>
<Typography>{translate('loadingProblems') || 'Loading problems…'}</Typography>
</Box>
)}
</Container>
<Box className={classes.footer}>
<Box component="span">
{SHOW_COPYRIGHT && `© ${new Date().getFullYear()} ${SITE_NAME}`}
</Box>
<Box className={classes.spacer} />
<IconButton onClick={() => setShowPopup(true)} title={`About ${SITE_NAME}`}>
<HelpOutlineOutlinedIcon />
</IconButton>
</Box>
<Popup isOpen={showPopup} onClose={() => setShowPopup(false)}>
<About />
</Popup>
</Box>
);
};
export default withTranslation(ViewAllProblems);
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/LessonSelection.js | src/components/problem-layout/LessonSelection.js | import React, { Fragment } from 'react';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import Divider from '@material-ui/core/Divider';
import Paper from '@material-ui/core/Paper';
import { withStyles } from '@material-ui/core/styles';
import styles from './common-styles.js';
import IconButton from '@material-ui/core/IconButton';
import { _coursePlansNoEditor, ThemeContext, SITE_NAME, SHOW_COPYRIGHT } from '../../config/config.js';
import Spacer from "../Spacer";
import HelpOutlineOutlinedIcon from "@material-ui/icons/HelpOutlineOutlined";
import { Typography } from "@material-ui/core";
import { IS_STAGING_OR_DEVELOPMENT } from "../../util/getBuildType";
import BuildTimeIndicator from "@components/BuildTimeIndicator";
import withTranslation from "../../util/withTranslation.js";
import Popup from '../Popup/Popup.js';
import About from '../../pages/Posts/About.js';
import MenuBookIcon from '@material-ui/icons/MenuBook';
class LessonSelection extends React.Component {
static contextType = ThemeContext;
constructor(props, context) {
super(props);
const { courseNum, setLanguage } = this.props;
if (courseNum == 6) {
setLanguage('se')
}
if (props.history.location.pathname == '/') {
const defaultLocale = localStorage.getItem('defaultLocale');
setLanguage(defaultLocale)
}
this.user = context.user || {}
this.isPrivileged = !!this.user.privileged
this.coursePlans = _coursePlansNoEditor;
this.togglePopup = this.togglePopup.bind(this);
this.state = {
preparedRemoveProgress: false,
removedProgress: false,
showPopup: false
}
}
togglePopup = () => {
console.log("Toggling popup visibility");
this.setState((prevState) => ({
showPopup: !prevState.showPopup,
}));
};
removeProgress = () => {
this.setState({ removedProgress: true });
this.props.removeProgress();
}
prepareRemoveProgress = () => {
this.setState({ preparedRemoveProgress: true });
}
render() {
const { translate } = this.props;
const { classes, courseNum } = this.props;
const selectionMode = courseNum == null ? "course" : "lesson"
const { showPopup } = this.state;
if (selectionMode === "lesson" && courseNum >= this.coursePlans.length) {
return <Box width={'100%'} textAlign={'center'} pt={4} pb={4}>
<Typography variant={'h3'}>Course <code>{courseNum}</code> is not valid!</Typography>
</Box>
}
return (
<>
<div>
<Grid
container
spacing={0}
direction="column"
alignItems="center"
justifyContent="center"
>
<Box width="75%" maxWidth={1500} role={"main"}>
<center>
{this.isPrivileged
? <h1>{translate('lessonSelection.welcomeInstructor')}</h1>
: <h1>{translate('lessonSelection.welcomeTo')} {SITE_NAME.replace(/\s/, "")}!</h1>
}
<h2>{translate('lessonSelection.select')} {selectionMode === "course" ? translate('lessonSelection.course') : translate('lessonSelection.lessonplan')}</h2>
{this.isPrivileged
&& <h4>(for {this.user.resource_link_title})</h4>
}
{
IS_STAGING_OR_DEVELOPMENT && <BuildTimeIndicator/>
}
</center>
<Divider/>
<Spacer/>
<Grid container spacing={3}>
{selectionMode === "course"
? this.coursePlans
.map((course, i) =>
<Grid item xs={12} sm={6} md={4} key={course.courseName}>
<center>
<Paper className={classes.paper}>
<h2 style={{
marginTop: "5px",
marginBottom: "10px"
}}>{course.courseName}</h2>
<IconButton aria-label={`View Course ${i}`}
aria-roledescription={`Navigate to course ${i}'s page to view available lessons`}
role={"link"}
onClick={() => {
this.props.history.push(`/courses/${i}`)
}}>
<img
src={`${process.env.PUBLIC_URL}/static/images/icons/folder.png`}
width="64px"
alt="folderIcon"/>
</IconButton>
</Paper>
</center>
</Grid>
)
: this.coursePlans[this.props.courseNum].lessons.map((lesson, i) => {
return (
<Grid item xs={12} sm={6} md={4} key={i}>
<center>
<Paper className={classes.paper} style={{ position: 'relative' }}>
{/* top-right “view all problems” button */}
<IconButton
size="small"
style={{ position: 'absolute', top: 8, right: 8 }}
aria-label={`View all problems for lesson ${lesson.id}`}
onClick={() => this.props.history.push(`/lessons/${lesson.id}/problems`)}
>
<MenuBookIcon fontSize="small" />
</IconButton>
<h2 style={{ marginTop: 5, marginBottom: 10 }}>
{lesson.name.replace(/##/g, "")}
</h2>
<h3 style={{ marginTop: 5 }}>{lesson.topics}</h3>
<Button
variant="contained"
color="primary"
className={classes.button}
onClick={() => this.props.history.push(`/lessons/${lesson.id}`)}
>
{translate('lessonSelection.onlyselect')}
</Button>
</Paper>
</center>
</Grid>
)
})
}
</Grid>
<Spacer/>
</Box>
</Grid>
<Spacer/>
<Grid container spacing={0}>
<Grid item xs={3} sm={3} md={5} key={1}/>
{!this.isPrivileged && <Grid item xs={6} sm={6} md={2} key={2}>
{this.state.preparedRemoveProgress ?
<Button className={classes.button} style={{ width: "100%" }} size="small"
onClick={this.removeProgress}
disabled={this.state.removedProgress}>{this.state.removedProgress ? translate('lessonSelection.reset') : translate('lessonSelection.aresure')}</Button> :
<Button className={classes.button} style={{ width: "100%" }} size="small"
onClick={this.prepareRemoveProgress}
disabled={this.state.preparedRemoveProgress}>{translate('lessonSelection.resetprogress')}</Button>}
</Grid>}
<Grid item xs={3} sm={3} md={4} key={3}/>
</Grid>
<Spacer/>
</div>
<footer>
<div style={{ display: "flex", flexDirection: "row", alignItems: "center" }}>
<div style={{ marginLeft: 20, fontSize: 16 }}>
{SHOW_COPYRIGHT && <>© {new Date().getFullYear()} {SITE_NAME}</>}
</div>
<div style={{ display: "flex", flexGrow: 1, marginRight: 20, justifyContent: "flex-end" }}>
<IconButton aria-label="about" title={`About ${SITE_NAME}`}
onClick={this.togglePopup}>
<HelpOutlineOutlinedIcon htmlColor={"#000"} style={{
fontSize: 36,
margin: -2
}}/>
</IconButton>
</div>
<Popup isOpen={showPopup} onClose={this.togglePopup}>
<About />
</Popup>
</div>
</footer>
</>
)
}
}
export default withStyles(styles)(withTranslation(LessonSelection));
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/DynamicHintHelper.js | src/components/problem-layout/DynamicHintHelper.js | import { renderGPTText } from "../../platform-logic/renderText.js";
import AWS from "aws-sdk";
export async function fetchDynamicHint(
DYNAMIC_HINT_URL,
promptParameters,
onChunkReceived,
onSuccessfulCompletion,
onError,
problemID,
variabilization,
context
) {
try {
AWS.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: "us-west-1",
});
const request = new AWS.HttpRequest(DYNAMIC_HINT_URL, AWS.config.region);
request.method = "POST";
request.headers["Content-Type"] = "application/json";
request.headers['Host'] = new URL(DYNAMIC_HINT_URL).host;
request.body = JSON.stringify(promptParameters);
const signer = new AWS.Signers.V4(request, "lambda");
signer.addAuthorization(AWS.config.credentials, new Date());
// Send the signed request using fetch
let response;
try {
response = await fetch(DYNAMIC_HINT_URL, {
mode: 'cors',
method: request.method,
headers: request.headers,
body: request.body,
});
} catch (error) {
console.error('Error sending request:', error);
throw error;
}
if (!response.body) {
throw new Error("No response body from server.");
}
if (!response.ok) {
const errorText = await response.text();
console.error("AWS Error Response:", errorText);
throw new Error(`Request failed with status ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let streamedHint = "";
while (true) {
const { done, value } = await reader.read();
if (done) {
const finalHint = renderGPTText(streamedHint, problemID, variabilization, context);
console.log("GPT OUTPUT: ", finalHint);
onChunkReceived(finalHint); // Call the final processing callback
onSuccessfulCompletion(); //Set `isHintGenerating` to false
break;
} else {
let chunk = decoder.decode(value, { stream: true });
chunk = convertDoubleToSingleQuotes(chunk);
// Ensure proper string termination
chunk = ensureProperTermination(chunk);
// Add the chunk to the streamedHint
streamedHint += chunk;
}
onChunkReceived(streamedHint);
}
} catch (error) {
console.error("Error fetching dynamic hint:", error);
onError(error);
}
}
function convertDoubleToSingleQuotes(input) {
if (input.startsWith('"') && input.endsWith('"')) {
return `'${input.slice(1, -1)}'`;
}
return input; // Return unchanged if not surrounded by double quotes
}
function ensureProperTermination(input) {
// Check if input starts and ends with the same type of quote
if ((input.startsWith('"') && !input.endsWith('"')) ||
(input.startsWith("'") && !input.endsWith("'"))) {
// Append the missing quote
return input + input[0]; // Add the matching quote at the end
}
return input; // Return unchanged if it's already valid
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/HintTextbox.js | src/components/problem-layout/HintTextbox.js | import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import styles from './common-styles.js';
import { checkAnswer } from '../../platform-logic/checkAnswer.js';
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import IconButton from '@material-ui/core/IconButton';
import { chooseVariables } from '../../platform-logic/renderText.js';
import { ThemeContext } from '../../config/config.js';
import ProblemInput from "../problem-input/ProblemInput";
import { stagingProp } from "../../util/addStagingProperty";
import { toastNotifyCorrectness } from "./ToastNotifyCorrectness";
import { joinList } from "../../util/formListString";
import withTranslation from "../../util/withTranslation.js"
import {
toastNotifyEmpty
} from "./ToastNotifyCorrectness";
class HintTextbox extends React.Component {
static contextType = ThemeContext;
constructor(props, context) {
super(props);
this.translate = props.translate
this.hint = props.hint;
this.index = props.index;
this.giveStuFeedback = props.giveStuFeedback
this.allowRetry = this.giveStuFeedback
this.showCorrectness = this.giveStuFeedback
this.state = {
inputVal: "",
isCorrect: context.use_expanded_view && context.debug ? true : null,
checkMarkOpacity: context.use_expanded_view && context.debug ? '100' : '0',
showHints: false,
}
}
handleKey = (event) => {
if (event.key === 'Enter') {
this.submit();
}
}
submit = () => {
const [parsed, correctAnswer, reason] = checkAnswer({
attempt: this.state.inputVal,
actual: this.hint.hintAnswer,
answerType: this.hint.answerType,
precision: this.hint.precision,
variabilization: chooseVariables(this.props.hintVars, this.props.seed),
questionText: this.hint.text
});
if (parsed == '') {
toastNotifyEmpty(this.translate)
return;
}
this.props.submitHint(parsed, this.hint, correctAnswer, this.props.hintNum);
const isCorrect = !!correctAnswer
toastNotifyCorrectness(isCorrect, reason, this.translate);
this.setState({
isCorrect,
checkMarkOpacity: isCorrect ? '100' : '0'
}, () => parsed);
}
editInput = (event) => {
this.setInputValState(event.target.value)
}
setInputValState = (inputVal) => {
// console.debug("new inputVal state: ", inputVal)
this.setState(({ isCorrect }) => ({ inputVal, isCorrect: isCorrect ? true : null }))
}
render() {
const { translate } = this.props;
const { classes, index, hintNum } = this.props;
const { isCorrect } = this.state;
const { debug, use_expanded_view } = this.context;
const hintIndex = `${hintNum}-${index}`
const problemAttempted = isCorrect != null
return (
<div>
<ProblemInput
variabilization={chooseVariables(this.props.hintVars, this.props.seed)}
allowRetry={this.allowRetry}
giveStuFeedback={this.giveStuFeedback}
showCorrectness={this.showCorrectness}
classes={classes}
state={this.state}
step={this.hint}
seed={this.props.seed}
_setState={(state) => this.setState(state)}
context={this.context}
editInput={this.editInput}
setInputValState={this.setInputValState}
handleKey={this.handleKey}
index={hintIndex}
/>
<Grid container spacing={0} justifyContent="center" alignItems="center">
<Grid item xs={false} sm={false} md={4}/>
<Grid item xs={4} sm={4} md={1}>
{this.props.type !== "subHintTextbox" && this.hint.subHints !== undefined ?
<center>
<IconButton aria-label="delete" onClick={this.props.toggleHints}
title="View available hints"
disabled={(use_expanded_view && debug)}
{...stagingProp({
"data-selenium-target": `hint-button-${hintIndex}`
})}
>
<img src={`${process.env.PUBLIC_URL}/static/images/icons/raise_hand.png`}
alt="hintToggle"/>
</IconButton>
</center> :
<img src={'/static/images/icons/raise_hand.png'}
alt="hintToggle"
style={{ visibility: "hidden" }}/>
}
</Grid>
<Grid item xs={4} sm={4} md={2}>
<center>
<Button className={classes.button} style={{ width: "80%" }} size="small"
onClick={this.submit}
disabled={(use_expanded_view && debug) || (!this.allowRetry && problemAttempted)}
{...stagingProp({
"data-selenium-target": `submit-button-${hintIndex}`
})}
>
{translate('problem.Submit')}
</Button>
</center>
</Grid>
<Grid item xs={4} sm={3} md={1}>
<div style={{
display: "flex",
flexDirection: "row",
alignContent: "center",
justifyContent: "center"
}}>
{(!this.showCorrectness || !this.allowRetry) &&
<img className={classes.checkImage}
style={{ opacity: this.state.isCorrect == null ? 0 : 1, width: "45%" }}
alt="Exclamation Mark Icon"
title={`The instructor has elected to ${joinList(!this.showCorrectness && 'hide correctness', !this.allowRetry && "disallow retries")}`}
{...stagingProp({
"data-selenium-target": `step-correct-img-${hintIndex}`
})}
src={`${process.env.PUBLIC_URL}/static/images/icons/exclamation.svg`}/>
}
{this.state.isCorrect && this.showCorrectness && this.allowRetry &&
<img className={classes.checkImage}
style={{ opacity: this.state.checkMarkOpacity, width: "45%" }}
alt="Green Checkmark Icon"
{...stagingProp({
"data-selenium-target": `step-correct-img-${hintIndex}`
})}
src={`${process.env.PUBLIC_URL}/static/images/icons/green_check.svg`}/>
}
{this.state.isCorrect === false && this.showCorrectness && this.allowRetry &&
<img className={classes.checkImage}
style={{ opacity: 100 - this.state.checkMarkOpacity, width: "45%" }}
alt="Red X Icon"
{...stagingProp({
"data-selenium-target": `step-correct-img-${hintIndex}`
})}
src={`${process.env.PUBLIC_URL}/static/images/icons/error.svg`}/>
}
</div>
</Grid>
<Grid item xs={false} sm={1} md={4}/>
</Grid>
</div>
);
}
}
export default withStyles(styles)(withTranslation(HintTextbox));
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/ProblemCardWrapper.js | src/components/problem-layout/ProblemCardWrapper.js | import React from 'react';
import { LocalizationConsumer } from '../../util/LocalizationContext';
import ProblemCard from './ProblemCard';
const ProblemCardWrapper = (props) => (
<LocalizationConsumer>
{({ setLanguage }) => <ProblemCard {...props} setLanguage={setLanguage} />}
</LocalizationConsumer>
);
export default ProblemCardWrapper;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/common-styles.js | src/components/problem-layout/common-styles.js | const styles = theme => ({
card: {
width: '65%',
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: 20
},
hintCard: {
width: '40em',
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: 20
},
bullet: {
display: 'inline-block',
margin: '0 2px',
transform: 'scale(0.8)',
},
title: {
fontSize: 14,
},
pos: {
marginBottom: 12,
},
button: {
backgroundColor: '#8c94ff',
marginLeft: 'auto',
marginRight: 'auto',
paddingLeft: 10,
paddingRight: 10,
width: "20%"
},
stepHeader: {
//textAlign: 'center',
fontSize: 20,
marginTop: 0,
marginLeft: 10
},
stepBody: {
//textAlign: 'center',
fontSize: 20,
marginTop: 10,
marginBottom: 30,
marginLeft: 10
},
inputField: {
width: '100%',
textAlign: 'center',
//marginLeft: '19em'
},
muiUsedHint: {
borderWidth: '1px',
borderColor: 'GoldenRod !important'
},
inputHintField: {
width: '10em',
//marginLeft: '16em',
},
center: {
marginLeft: '19em',
marginRight: '19em',
marginTop: '1em'
},
checkImage: {
width: '3em',
marginLeft: '0.5em',
},
root: {
flexGrow: 1,
},
paper: {
padding: theme.spacing(3, 2),
},
// Problem
prompt: {
marginLeft: 0,
marginRight: 0,
marginTop: 20,
textAlign: 'center',
fontSize: 20,
fontFamily: 'Titillium Web, sans-serif',
},
titleCard: {
width: '75%',
marginLeft: 'auto',
marginRight: 'auto',
paddingBottom: 0,
},
problemHeader: {
fontSize: 25,
marginTop: 0,
},
problemBody: {
fontSize: 20,
marginTop: 10,
},
problemStepHeader: {
fontSize: 25,
marginTop: 0,
marginLeft: 10
},
problemStepBody: {
fontSize: 20,
marginTop: 10,
marginLeft: 10
},
textBox: {
paddingLeft: 70,
paddingRight: 70,
},
textBoxHeader: {
fontWeight: 'bold',
fontSize: 16,
},
textBoxLatex: {
border: "1px solid #c4c4c4",
borderRadius: "4px",
'&:hover': {
border: "1px solid #000000",
},
'&:focus-within': {
border: "2px solid #3f51b5",
},
height: 50,
width: '100%',
'& > .mq-editable-field': {
display: 'table',
tableLayout: 'fixed'
},
'& > * > *[mathquill-block-id]': {
height: 50,
display: 'table-cell',
paddingBottom: 5
}
},
textBoxLatexIncorrect: {
boxShadow: "0 0 0.75pt 0.75pt red",
'&:focus-within': {
border: "1px solid red",
},
},
textBoxLatexUsedHint: {
boxShadow: "0 0 0.75pt 0.75pt GoldenRod",
'&:focus-within': {
border: "1px solid GoldenRod",
},
}
});
export default styles;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/Problem.js | src/components/problem-layout/Problem.js | import React from "react";
import { withStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import ProblemCardWrapper from "./ProblemCardWrapper";
import Grid from "@material-ui/core/Grid";
import { animateScroll as scroll, Element, scroller } from "react-scroll";
import update from "../../models/BKT/BKT-brain.js";
import {
chooseVariables,
renderText,
} from "../../platform-logic/renderText.js";
import styles from "./common-styles.js";
import IconButton from "@material-ui/core/IconButton";
import TextField from "@material-ui/core/TextField";
import { NavLink } from "react-router-dom";
import HelpOutlineOutlinedIcon from "@material-ui/icons/HelpOutlineOutlined";
import FeedbackOutlinedIcon from "@material-ui/icons/FeedbackOutlined";
import withTranslation from "../../util/withTranslation.js"
import {
CANVAS_WARNING_STORAGE_KEY,
MIDDLEWARE_URL,
SHOW_NOT_CANVAS_WARNING,
SITE_NAME,
ThemeContext,
} from "../../config/config.js";
import { toast } from "react-toastify";
import to from "await-to-js";
import ToastID from "../../util/toastIds";
import Spacer from "../Spacer";
import { stagingProp } from "../../util/addStagingProperty";
import { cleanArray } from "../../util/cleanObject";
import Popup from '../Popup/Popup.js';
import About from '../../pages/Posts/About.js';
class Problem extends React.Component {
static defaultProps = {
autoScroll: true
};
static contextType = ThemeContext;
constructor(props, context) {
super(props);
this.bktParams = context.bktParams;
this.heuristic = context.heuristic;
const giveStuFeedback = this.props.lesson?.giveStuFeedback;
const giveStuHints = this.props.lesson?.giveStuHints;
const keepMCOrder = this.props.lesson?.keepMCOrder;
const giveHintOnIncorrect = this.props.lesson?.giveHintOnIncorrect;
const keyboardType = this.props.lesson?.keyboardType;
const doMasteryUpdate = this.props.lesson?.doMasteryUpdate;
const unlockFirstHint = this.props.lesson?.unlockFirstHint;
const giveStuBottomHint = this.props.lesson?.allowBottomHint;
this.giveHintOnIncorrect = giveHintOnIncorrect != null && giveHintOnIncorrect;
this.giveStuFeedback = giveStuFeedback == null || giveStuFeedback;
this.keepMCOrder = keepMCOrder != null && keepMCOrder;
this.keyboardType = keyboardType != null && keyboardType;
this.giveStuHints = giveStuHints == null || giveStuHints;
this.doMasteryUpdate = doMasteryUpdate == null || doMasteryUpdate;
this.unlockFirstHint = unlockFirstHint != null && unlockFirstHint;
this.giveStuBottomHint = giveStuBottomHint == null || giveStuBottomHint;
this.giveDynamicHint = this.props.lesson?.allowDynamicHint;
this.prompt_template = this.props.lesson?.prompt_template
? this.props.lesson?.prompt_template
: "";
this.state = {
stepStates: {},
firstAttempts: {},
problemFinished: false,
showFeedback: false,
feedback: "",
feedbackSubmitted: false,
showPopup: false
};
}
componentDidMount() {
const { lesson } = this.props;
document["oats-meta-courseName"] = lesson?.courseName || "";
document["oats-meta-textbookName"] =
lesson?.courseName
.substring((lesson?.courseName || "").indexOf(":") + 1)
.trim() || "";
// query selects all katex annotation and adds aria label attribute to it
for (const annotation of document.querySelectorAll("annotation")) {
annotation.ariaLabel = annotation.textContent;
}
}
componentWillUnmount() {
document["oats-meta-courseName"] = "";
document["oats-meta-textbookName"] = "";
}
updateCanvas = async (mastery, components) => {
if (this.context.jwt) {
console.debug("updating canvas with problem score");
let err, response;
[err, response] = await to(
fetch(`${MIDDLEWARE_URL}/postScore`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
token: this.context?.jwt || "",
mastery,
components,
}),
})
);
if (err || !response) {
toast.error(
`An unknown error occurred trying to submit this problem. If reloading does not work, please contact us.`,
{
toastId: ToastID.submit_grade_unknown_error.toString(),
}
);
console.debug(err, response);
} else {
if (response.status !== 200) {
switch (response.status) {
case 400:
const responseText = await response.text();
let [message, ...addInfo] = responseText.split("|");
if (
Array.isArray(addInfo) &&
addInfo.length > 0 &&
addInfo[0]
) {
addInfo = JSON.parse(addInfo[0]);
}
switch (message) {
case "lost_link_to_lms":
toast.error(
"It seems like the link back to your LMS has been lost. Please re-open the assignment to make sure your score is saved.",
{
toastId:
ToastID.submit_grade_link_lost.toString(),
}
);
return;
case "unable_to_handle_score":
toast.warn(
"Something went wrong and we can't update your score right now. Your progress will be saved locally so you may continue working.",
{
toastId:
ToastID.submit_grade_unable.toString(),
closeOnClick: true,
}
);
return;
default:
toast.error(`Error: ${responseText}`, {
closeOnClick: true,
});
return;
}
case 401:
toast.error(
`Your session has either expired or been invalidated, please reload the page to try again.`,
{
toastId: ToastID.expired_session.toString(),
}
);
return;
case 403:
toast.error(
`You are not authorized to make this action. (Are you a registered student?)`,
{
toastId: ToastID.not_authorized.toString(),
}
);
return;
default:
toast.error(
`An unknown error occurred trying to submit this problem. If reloading does not work, please contact us.`,
{
toastId:
ToastID.set_lesson_unknown_error.toString(),
}
);
return;
}
} else {
console.debug("successfully submitted grade to Canvas");
}
}
} else {
const { getByKey, setByKey } = this.context.browserStorage;
const showWarning =
!(await getByKey(CANVAS_WARNING_STORAGE_KEY)) &&
SHOW_NOT_CANVAS_WARNING;
if (showWarning) {
toast.warn(
"No credentials found (did you launch this assignment from Canvas?)",
{
toastId: ToastID.warn_not_from_canvas.toString(),
autoClose: false,
onClick: () => {
toast.dismiss(
ToastID.warn_not_from_canvas.toString()
);
},
onClose: () => {
setByKey(CANVAS_WARNING_STORAGE_KEY, 1);
},
}
);
} else {
// can ignore
}
}
};
answerMade = (cardIndex, kcArray, isCorrect) => {
const { stepStates, firstAttempts } = this.state;
const { lesson, problem } = this.props;
console.debug(`answer made and is correct: ${isCorrect}`);
if (stepStates[cardIndex] === true) {
return;
}
if (stepStates[cardIndex] == null) {
if (kcArray == null) {
kcArray = [];
}
const _kcArray = cleanArray(kcArray);
for (const kc of _kcArray) {
if (!this.bktParams[kc]) {
console.debug("invalid KC", kc);
this.context.firebase.submitSiteLog(
"site-warning",
"missing-kc",
{
kc,
cardIndex,
},
this.context.problemID
);
continue;
}
if (this.doMasteryUpdate && (firstAttempts[cardIndex] === undefined || firstAttempts[cardIndex] === false)) {
firstAttempts[cardIndex] = true;
update(this.bktParams[kc], isCorrect);
}
}
}
if (!this.context.debug) {
const objectives = Object.keys(lesson.learningObjectives);
objectives.unshift(0);
let score = objectives.reduce((x, y) => {
return x + this.bktParams[y].probMastery;
});
score /= objectives.length - 1;
//console.log(this.context.studentName + " " + score);
this.props.displayMastery(score);
const relevantKc = {};
Object.keys(lesson.learningObjectives).forEach((x) => {
relevantKc[x] = this.bktParams[x].probMastery;
});
this.updateCanvas(score, relevantKc);
}
const nextStepStates = {
...stepStates,
[cardIndex]: isCorrect,
};
const giveStuFeedback = this.giveStuFeedback;
const numSteps = problem.steps.length;
if (!giveStuFeedback) {
const numAttempted = Object.values(nextStepStates).filter(
(stepState) => stepState != null
).length;
// console.log("num attempted: ", numAttempted);
// console.log("num steps: ", numSteps);
// console.log("step states: ", Object.values(nextStepStates));
this.setState({
stepStates: nextStepStates,
});
if (numAttempted === numSteps) {
this.setState({
problemFinished: true,
stepStates: nextStepStates,
});
}
// don't attempt to auto scroll to next step
return;
}
if (isCorrect) {
const numCorrect = Object.values(nextStepStates).filter(
(stepState) => stepState === true
).length;
if (numSteps !== numCorrect) {
console.debug(
"not last step so not done w/ problem, step states:",
nextStepStates
);
if (this.props.autoScroll) {
scroller.scrollTo((cardIndex + 1).toString(), {
duration: 500,
smooth: true,
offset: -100,
});
}
this.setState({
stepStates: nextStepStates,
});
} else {
this.setState({
problemFinished: true,
stepStates: nextStepStates,
});
}
}
};
clickNextProblem = async () => {
scroll.scrollToTop({ duration: 900, smooth: true });
await this.props.problemComplete(this.context);
this.setState({
stepStates: {},
firstAttempts: {},
problemFinished: false,
feedback: "",
feedbackSubmitted: false,
});
};
submitFeedback = () => {
const { problem } = this.props;
console.debug("problem when submitting feedback", problem);
this.context.firebase.submitFeedback(
problem.id,
this.state.feedback,
this.state.problemFinished,
chooseVariables(problem.variabilization, this.props.seed),
problem.courseName,
problem.steps,
problem.lesson
);
this.setState({ feedback: "", feedbackSubmitted: true });
};
toggleFeedback = () => {
scroll.scrollToBottom({ duration: 500, smooth: true });
this.setState((prevState) => ({
showFeedback: !prevState.showFeedback,
}));
};
togglePopup = () => {
console.log("Toggling popup visibility");
this.setState((prevState) => ({
showPopup: !prevState.showPopup,
}));
};
_getNextDebug = (offset) => {
return (
this.context.problemIDs[
this.context.problemIDs.indexOf(this.props.problem.id) + offset
] || "/"
);
};
getOerLicense = () => {
const { lesson, problem } = this.props;
var oerArray, licenseArray;
var oerLink, oerName;
var licenseLink, licenseName;
try {
if (problem.oer != null && problem.oer.includes(" <")) {
oerArray = problem.oer.split(" <");
} else if (lesson.courseOER != null && lesson.courseOER.includes(" ")) {
oerArray = lesson.courseOER.split(" <");
} else {
oerArray = ["", ""];
}
} catch(error) {
oerArray = ["", ""];
}
oerLink = oerArray[0];
oerName = oerArray[1].substring(0, oerArray[1].length - 1);
try {
if (problem.license != null && problem.license.includes(" ")) {
licenseArray = problem.license.split(" <");
} else if (
lesson.courseLicense != null &&
lesson.courseLicense.includes(" ")
) {
licenseArray = lesson.courseLicense.split(" <");
} else {
licenseArray = ["", ""];
}
} catch(error) {
licenseArray = ["", ""];
}
licenseLink = licenseArray[0];
licenseName = licenseArray[1].substring(0, licenseArray[1].length - 1);
return [oerLink, oerName, licenseLink, licenseName];
};
render() {
const { translate } = this.props;
const { classes, problem, seed } = this.props;
const [oerLink, oerName, licenseLink, licenseName] =
this.getOerLicense();
const { showPopup } = this.state;
if (problem == null) {
return <div></div>;
}
return (
<>
<div>
<div className={classes.prompt} role={"banner"}>
<Card className={classes.titleCard}>
<CardContent
{...stagingProp({
"data-selenium-target": "problem-header",
})}
>
<h1 className={classes.problemHeader}>
{renderText(
problem.title,
problem.id,
chooseVariables(
problem.variabilization,
seed
),
this.context
)}
<hr />
</h1>
<div className={classes.problemBody}>
{renderText(
problem.body,
problem.id,
chooseVariables(
problem.variabilization,
seed
),
this.context
)}
</div>
</CardContent>
</Card>
<Spacer height={8} />
<hr />
</div>
<div role={"main"}>
{problem.steps.map((step, idx) => (
<Element
name={idx.toString()}
key={`${problem.id}-${step.id}`}
>
<ProblemCardWrapper
problemID={problem.id}
step={step}
index={idx}
answerMade={this.answerMade}
seed={seed}
problemVars={problem.variabilization}
lesson={problem.lesson}
courseName={problem.courseName}
problemTitle={problem.title}
problemSubTitle={problem.body}
giveStuFeedback={this.giveStuFeedback}
giveStuHints={this.giveStuHints}
keepMCOrder={this.keepMCOrder}
keyboardType={this.keyboardType}
giveHintOnIncorrect={
this.giveHintOnIncorrect
}
unlockFirstHint={this.unlockFirstHint}
giveStuBottomHint={this.giveStuBottomHint}
giveDynamicHint={this.giveDynamicHint}
prompt_template={this.prompt_template}
/>
</Element>
))}
</div>
<div width="100%">
{this.context.debug ? (
<Grid container spacing={0}>
<Grid item xs={2} key={0} />
<Grid item xs={2} key={1}>
<NavLink
activeClassName="active"
className="link"
to={this._getNextDebug(-1)}
type="menu"
style={{ marginRight: "10px" }}
>
<Button
className={classes.button}
style={{ width: "100%" }}
size="small"
onClick={() =>
(this.context.needRefresh = true)
}
>
{translate('problem.PreviousProblem')}
</Button>
</NavLink>
</Grid>
<Grid item xs={4} key={2} />
<Grid item xs={2} key={3}>
<NavLink
activeClassName="active"
className="link"
to={this._getNextDebug(1)}
type="menu"
style={{ marginRight: "10px" }}
>
<Button
className={classes.button}
style={{ width: "100%" }}
size="small"
onClick={() =>
(this.context.needRefresh = true)
}
>
{translate('problem.NextProblem')}
</Button>
</NavLink>
</Grid>
<Grid item xs={2} key={4} />
</Grid>
) : (
<Grid container spacing={0}>
<Grid item xs={3} sm={3} md={5} key={1} />
<Grid item xs={6} sm={6} md={2} key={2}>
<Button
className={classes.button}
style={{ width: "100%" }}
size="small"
onClick={this.clickNextProblem}
disabled={
!(
this.state.problemFinished ||
this.state.feedbackSubmitted
)
}
>
{translate('problem.NextProblem')}
</Button>
</Grid>
<Grid item xs={3} sm={3} md={5} key={3} />
</Grid>
)}
</div>
</div>
<footer>
<div
style={{
display: "flex",
flexDirection: "row",
alignItems: "center",
}}
>
<div style={{ marginLeft: 20, fontSize: 12 }}>
{licenseName !== "" && licenseLink !== "" ? (
<div>
"{problem.title}" {translate('problem.Derivative')}
<a
href={oerLink}
target="_blank"
rel="noreferrer"
>
"{oerName}"
</a>
{translate('problem.Used')}
<a
href={licenseLink}
target="_blank"
rel="noreferrer"
>
{licenseName}
</a>
</div>
) : (
<div>
{oerName !== "" && oerLink !== "" ? (
<div>
"{problem.title}" {translate('problem.Derivative')}
<a
href={oerLink}
target="_blank"
rel="noreferrer"
>
"{oerName}"
</a>
</div>
) : (
<></>
)}
</div>
)}
</div>
<div
style={{
display: "flex",
flexGrow: 1,
marginRight: 20,
justifyContent: "flex-end",
}}
>
<IconButton
aria-label="about"
title={`About ${SITE_NAME}`}
onClick={this.togglePopup}
>
<HelpOutlineOutlinedIcon
htmlColor={"#000"}
style={{
fontSize: 36,
margin: -2,
}}
/>
</IconButton>
<IconButton
aria-label="report problem"
onClick={this.toggleFeedback}
title={"Report Problem"}
>
<FeedbackOutlinedIcon
htmlColor={"#000"}
style={{
fontSize: 32,
}}
/>
</IconButton>
</div>
<Popup isOpen={showPopup} onClose={this.togglePopup}>
<About />
</Popup>
</div>
{this.state.showFeedback ? (
<div className="Feedback">
<center>
<h1>{translate('problem.Feedback')}</h1>
</center>
<div className={classes.textBox}>
<div className={classes.textBoxHeader}>
<center>
{this.state.feedbackSubmitted
? translate('problem.Thanks')
: translate('problem.Description')}
</center>
</div>
{this.state.feedbackSubmitted ? (
<Spacer />
) : (
<Grid container spacing={0}>
<Grid
item
xs={1}
sm={2}
md={2}
key={1}
/>
<Grid
item
xs={10}
sm={8}
md={8}
key={2}
>
<TextField
id="outlined-multiline-flexible"
label={translate('problem.Response')}
multiline
fullWidth
minRows="6"
maxRows="20"
value={this.state.feedback}
onChange={(event) =>
this.setState({
feedback:
event.target.value,
})
}
className={classes.textField}
margin="normal"
variant="outlined"
/>{" "}
</Grid>
<Grid
item
xs={1}
sm={2}
md={2}
key={3}
/>
</Grid>
)}
</div>
{this.state.feedbackSubmitted ? (
""
) : (
<div className="submitFeedback">
<Grid container spacing={0}>
<Grid
item
xs={3}
sm={3}
md={5}
key={1}
/>
<Grid item xs={6} sm={6} md={2} key={2}>
<Button
className={classes.button}
style={{ width: "100%" }}
size="small"
onClick={this.submitFeedback}
disabled={
this.state.feedback === ""
}
>
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | true |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/LessonSelectionWrapper.js | src/components/problem-layout/LessonSelectionWrapper.js | import React from 'react';
import { LocalizationConsumer } from '../../util/LocalizationContext';
import LessonSelection from './LessonSelection';
const LessonSelectionWrapper = (props) => (
<LocalizationConsumer>
{({ setLanguage }) => <LessonSelection {...props} setLanguage={setLanguage} />}
</LocalizationConsumer>
);
export default LessonSelectionWrapper;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/ProblemWrapper.js | src/components/problem-layout/ProblemWrapper.js | import React from 'react';
import { LocalizationConsumer } from '../../util/LocalizationContext';
import Problem from './Problem';
const ProblemWrapper = (props) => (
<LocalizationConsumer>
{({ setLanguage }) => <Problem {...props} setLanguage={setLanguage} />}
</LocalizationConsumer>
);
export default ProblemWrapper;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/SubHintSystem.js | src/components/problem-layout/SubHintSystem.js | import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Accordion from '@material-ui/core/Accordion';
import AccordionSummary from '@material-ui/core/AccordionSummary';
import AccordionDetails from '@material-ui/core/AccordionDetails';
import Typography from '@material-ui/core/Typography';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import HintTextbox from './HintTextbox.js';
import { renderText, chooseVariables } from '../../platform-logic/renderText.js';
import Spacer from "../Spacer";
import { ThemeContext } from "../../config/config";
import withTranslation from "../../util/withTranslation.js"
class SubHintSystem extends React.Component {
static contextType = ThemeContext;
constructor(props) {
super(props);
this.giveStuFeedback = props.giveStuFeedback;
this.unlockFirstHint = props.unlockFirstHint;
this.state = {
latestStep: 0,
currentExpanded: this.unlockFirstHint ? 0 : -1,
hintAnswer: ""
}
if (this.unlockFirstHint && this.props.hintStatus.length > 0) {
this.props.unlockHint(0, this.props.parent);
}
}
unlockHint = (event, expanded, i) => {
if (this.state.currentExpanded === i) {
this.setState({ currentExpanded: -1 });
} else {
this.setState({ currentExpanded: i });
if (expanded && i < this.props.hintStatus.length) {
this.props.unlockHint(i, this.props.parent);
}
this.setState({ latestStep: i });
}
}
isLocked = (hintNum) => {
if (hintNum === 0) {
return false;
}
var dependencies = this.props.hints[hintNum].dependencies;
var isSatisfied = dependencies.every(dependency => this.props.hintStatus[dependency] === 1);
return !isSatisfied;
}
render() {
const { translate } = this.props;
const { classes, index, parent, hintVars, problemID, seed } = this.props;
const { currentExpanded } = this.state;
const { debug, use_expanded_view } = this.context;
return (
<div className={classes.root}>
{this.props.hints.map((hint, i) => {
return <Accordion key={i}
onChange={(event, expanded) => this.unlockHint(event, expanded, i)}
disabled={this.isLocked(i) && !(use_expanded_view && debug)}
expanded={currentExpanded === i || (use_expanded_view != null && use_expanded_view && debug)}
defaultExpanded={false}>
<AccordionSummary
expandIcon={<ExpandMoreIcon/>}
aria-controls="panel1a-content"
id="panel1a-header"
>
<Typography className={classes.heading}>
{translate('hintsystem.hint') + (i + 1) + ": "} {renderText(hint.title, problemID,
chooseVariables(Object.assign({}, hintVars, hint.variabilization), seed), this.context)} </Typography>
</AccordionSummary>
<AccordionDetails>
<Typography component={'span'} style={{ width: "100%" }}>
{renderText(hint.text, problemID, chooseVariables(Object.assign({}, hintVars, hint.variabilization), seed), this.context)}
{hint.type === "scaffold" ?
<div>
<Spacer/>
<HintTextbox hint={hint} type={"subHintTextbox"}
hintNum={i}
index={`${index}-${parent}`}
submitHint={(parsed, hint, correctAnswer, hintNum) => this.props.submitHint(parsed, hint, correctAnswer, i, hintNum)}
giveStuFeedback={this.giveStuFeedback}
/>
</div> : ""}
</Typography>
</AccordionDetails>
</Accordion>
}
)}
</div>
)
};
}
const styles = theme => ({
root: {
width: '100%',
},
heading: {
fontSize: theme.typography.pxToRem(15),
fontWeight: theme.typography.fontWeightRegular,
},
});
export default withStyles(styles)(withTranslation(SubHintSystem));
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/components/problem-layout/ToastNotifyCorrectness.js | src/components/problem-layout/ToastNotifyCorrectness.js | import { toast } from "react-toastify";
import WrongAnswerReasons from "../../util/wrongAnswerReasons";
export function toastNotifyCorrectness(isCorrect, reason, translate) {
if (isCorrect) {
toast.success(translate("toast.correct"), {
autoClose: 3000
})
} else {
if (reason === WrongAnswerReasons.wrong) {
toast.error(translate("toast.incorrect"), {
autoClose: 3000
})
} else if (reason === WrongAnswerReasons.sameAsProblem) {
toast.error(translate("toast.simplify"), {
autoClose: 3000
})
} else if (reason === WrongAnswerReasons.errored) {
toast.error(translate("toast.cantProcess"), {
autoClose: 3000
})
}
}
}
export function toastNotifyCompletion(translate) {
toast.info(translate("toast.stepComplete"), {
autoClose: 3000
})
}
export function toastNotifyEmpty(translate) {
toast.info(translate("toast.provideAnswer"), {
autoClose: 3000
})
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/models/BKT/BKT-brain.js | src/models/BKT/BKT-brain.js | export default function update(model, isCorrect) {
let numerator;
let masteryAndGuess;
if (isCorrect) {
numerator = model.probMastery * (1 - model.probSlip);
masteryAndGuess = (1 - model.probMastery) * model.probGuess;
} else {
numerator = model.probMastery * model.probSlip;
masteryAndGuess = (1 - model.probMastery) * (1 - model.probGuess);
}
let probMasteryGivenObservation = numerator / (numerator + masteryAndGuess);
model.probMastery = probMasteryGivenObservation + ((1 - probMasteryGivenObservation) * model.probTransit);
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/models/BKT/problem-select-heuristics/defaultHeuristic.js | src/models/BKT/problem-select-heuristics/defaultHeuristic.js | import {MASTERY_THRESHOLD} from "../../../config/config.js"
function heuristic(problems, completedProbs) {
var chosenProblem = [];
for (var problem of problems) {
// Already completed this problem or irrelevant (null if not in learning goals)
if (completedProbs.has(problem.id) || problem.probMastery == null || problem.probMastery >= MASTERY_THRESHOLD) {
continue;
} else if (chosenProblem.length === 0 || chosenProblem[0].probMastery > problem.probMastery) {
chosenProblem = [problem];
} else if (chosenProblem.length > 0 && chosenProblem[0].probMastery === problem.probMastery) {
chosenProblem.push(problem);
}
}
// Choose random from problems with equal mastery
return chosenProblem[Math.floor(Math.random() * chosenProblem.length)];
}
export { heuristic };
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/models/BKT/problem-select-heuristics/experimentalHeuristic.js | src/models/BKT/problem-select-heuristics/experimentalHeuristic.js | import {MASTERY_THRESHOLD} from "../../../config/config.js"
function heuristic(problems, completedProbs) {
var chosenProblem = [];
for (var problem of problems) {
// Already completed this problem or irrelevant (null if not in learning goals)
if (completedProbs.has(problem.id) || problem.probMastery == null || problem.probMastery >= MASTERY_THRESHOLD) {
continue;
} else if (chosenProblem.length === 0 || chosenProblem[0].probMastery < problem.probMastery) {
chosenProblem = [problem];
} else if (chosenProblem.length > 0 && chosenProblem[0].probMastery === problem.probMastery) {
chosenProblem.push(problem);
}
}
// Choose random from problems with equal mastery
return chosenProblem[Math.floor(Math.random() * chosenProblem.length)];
}
export { heuristic };
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/platform-logic/Platform.js | src/platform-logic/Platform.js | import React from "react";
import { AppBar, Toolbar } from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
import ProblemWrapper from "@components/problem-layout/ProblemWrapper.js";
import LessonSelectionWrapper from "@components/problem-layout/LessonSelectionWrapper.js";
import { withRouter } from "react-router-dom";
import {
coursePlans,
findLessonById,
LESSON_PROGRESS_STORAGE_KEY,
MIDDLEWARE_URL,
SITE_NAME,
ThemeContext,
MASTERY_THRESHOLD,
} from "../config/config.js";
import to from "await-to-js";
import { toast } from "react-toastify";
import ToastID from "../util/toastIds";
import BrandLogoNav from "@components/BrandLogoNav";
import { cleanArray } from "../util/cleanObject";
import ErrorBoundary from "@components/ErrorBoundary";
import { CONTENT_SOURCE } from "@common/global-config";
import withTranslation from '../util/withTranslation';
let problemPool = require(`@generated/processed-content-pool/${CONTENT_SOURCE}.json`);
let seed = Date.now().toString();
console.log("Generated seed");
class Platform extends React.Component {
static contextType = ThemeContext;
constructor(props, context) {
super(props);
this.problemIndex = {
problems: problemPool,
};
this.completedProbs = new Set();
this.lesson = null;
this.user = context.user || {};
console.debug("USER: ", this.user)
this.isPrivileged = !!this.user.privileged;
this.context = context;
// Add each Q Matrix skill model attribute to each step
for (const problem of this.problemIndex.problems) {
for (
let stepIndex = 0;
stepIndex < problem.steps.length;
stepIndex++
) {
const step = problem.steps[stepIndex];
step.knowledgeComponents = cleanArray(
context.skillModel[step.id] || []
);
}
}
if (this.props.lessonID == null) {
this.state = {
currProblem: null,
status: "courseSelection",
seed: seed,
};
} else {
this.state = {
currProblem: null,
status: "courseSelection",
seed: seed,
};
}
this.selectLesson = this.selectLesson.bind(this);
}
componentDidMount() {
this._isMounted = true;
if (this.props.lessonID != null) {
console.log("calling selectLesson from componentDidMount...")
const lesson = findLessonById(this.props.lessonID)
console.debug("lesson: ", lesson)
this.selectLesson(lesson).then(
(_) => {
console.debug(
"loaded lesson " + this.props.lessonID,
this.lesson
);
}
);
const { setLanguage } = this.props;
const language = lesson.language || localStorage.getItem('defaultLocale');
setLanguage(language);
} else if (this.props.courseNum != null) {
this.selectCourse(coursePlans[parseInt(this.props.courseNum)]);
}
this.onComponentUpdate(null, null, null);
}
componentWillUnmount() {
this._isMounted = false;
this.context.problemID = "n/a";
}
componentDidUpdate(prevProps, prevState, snapshot) {
this.onComponentUpdate(prevProps, prevState, snapshot);
}
onComponentUpdate(prevProps, prevState, snapshot) {
if (
Boolean(this.state.currProblem?.id) &&
this.context.problemID !== this.state.currProblem.id
) {
this.context.problemID = this.state.currProblem.id;
}
if (this.state.status !== "learning") {
this.context.problemID = "n/a";
}
}
async selectLesson(lesson, updateServer=true) {
const context = this.context;
console.debug("lesson: ", context)
console.debug("update server: ", updateServer)
console.debug("context: ", context)
if (!this._isMounted) {
console.debug("component not mounted, returning early (1)");
return;
}
if (this.isPrivileged) {
// from canvas or other LTI Consumers
console.log("valid privilege")
let err, response;
[err, response] = await to(
fetch(`${MIDDLEWARE_URL}/setLesson`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
token: context?.jwt || this.context?.jwt || "",
lesson,
}),
})
);
if (err || !response) {
toast.error(
`Error setting lesson for assignment "${this.user.resource_link_title}"`
);
console.debug(err, response);
return;
} else {
if (response.status !== 200) {
switch (response.status) {
case 400:
const responseText = await response.text();
let [message, ...addInfo] = responseText.split("|");
if (
Array.isArray(addInfo) &&
addInfo[0].length > 1
) {
addInfo = JSON.parse(addInfo[0]);
}
switch (message) {
case "resource_already_linked":
toast.error(
`${addInfo.from} has already been linked to lesson ${addInfo.to}. Please create a new assignment.`,
{
toastId:
ToastID.set_lesson_duplicate_error.toString(),
}
);
return;
default:
toast.error(`Error: ${responseText}`, {
toastId:
ToastID.expired_session.toString(),
closeOnClick: true,
});
return;
}
case 401:
toast.error(
`Your session has either expired or been invalidated, please reload the page to try again.`,
{
toastId: ToastID.expired_session.toString(),
}
);
this.props.history.push("/session-expired");
return;
case 403:
toast.error(
`You are not authorized to make this action. (Are you an instructor?)`,
{
toastId: ToastID.not_authorized.toString(),
}
);
return;
default:
toast.error(
`Error setting lesson for assignment "${this.user.resource_link_title}." If reloading does not work, please contact us.`,
{
toastId:
ToastID.set_lesson_unknown_error.toString(),
}
);
return;
}
} else {
toast.success(
`Successfully linked assignment "${this.user.resource_link_title}" to lesson ${lesson.id} "${lesson.topics}"`,
{
toastId: ToastID.set_lesson_success.toString(),
}
);
const responseText = await response.text();
let [message, ...addInfo] = responseText.split("|");
this.props.history.push(
`/assignment-already-linked?to=${addInfo.to}`
);
}
}
}
this.lesson = lesson;
const loadLessonProgress = async () => {
const { getByKey } = this.context.browserStorage;
return await getByKey(
LESSON_PROGRESS_STORAGE_KEY(this.lesson.id)
).catch((err) => {});
};
const [, prevCompletedProbs] = await Promise.all([
this.props.loadBktProgress(),
loadLessonProgress(),
]);
if (!this._isMounted) {
console.debug("component not mounted, returning early (2)");
return;
}
if (prevCompletedProbs) {
console.debug(
"student has already made progress w/ problems in this lesson before",
prevCompletedProbs
);
this.completedProbs = new Set(prevCompletedProbs);
}
this.setState(
{
currProblem: this._nextProblem(
this.context ? this.context : context
),
},
() => {
//console.log(this.state.currProblem);
//console.log(this.lesson);
}
);
}
selectCourse = (course, context) => {
this.course = course;
this.setState({
status: "lessonSelection",
});
};
_nextProblem = (context) => {
seed = Date.now().toString();
this.setState({ seed: seed });
this.props.saveProgress();
const problems = this.problemIndex.problems.filter(
({ courseName }) => !courseName.toString().startsWith("!!")
);
let chosenProblem;
console.debug(
"Platform.js: sample of available problems",
problems.slice(0, 10)
);
for (const problem of problems) {
// Calculate the mastery for this problem
let probMastery = 1;
let isRelevant = false;
for (const step of problem.steps) {
if (typeof step.knowledgeComponents === "undefined") {
continue;
}
for (const kc of step.knowledgeComponents) {
if (typeof context.bktParams[kc] === "undefined") {
console.log("BKT Parameter " + kc + " does not exist.");
continue;
}
if (kc in this.lesson.learningObjectives) {
isRelevant = true;
}
// Multiply all the mastery priors
if (!(kc in context.bktParams)) {
console.log("Missing BKT parameter: " + kc);
}
probMastery *= context.bktParams[kc].probMastery;
}
}
if (isRelevant) {
problem.probMastery = probMastery;
} else {
problem.probMastery = null;
}
}
console.debug(
`Platform.js: available problems ${problems.length}, completed problems ${this.completedProbs.size}`
);
chosenProblem = context.heuristic(problems, this.completedProbs);
console.debug("Platform.js: chosen problem", chosenProblem);
const objectives = Object.keys(this.lesson.learningObjectives);
console.debug("Platform.js: objectives", objectives);
let score = objectives.reduce((x, y) => {
return x + context.bktParams[y].probMastery;
}, 0);
score /= objectives.length;
this.displayMastery(score);
//console.log(Object.keys(context.bktParams).map((skill) => (context.bktParams[skill].probMastery <= this.lesson.learningObjectives[skill])));
// There exists a skill that has not yet been mastered (a True)
// Note (number <= null) returns false
if (
!Object.keys(context.bktParams).some(
(skill) =>
context.bktParams[skill].probMastery <= MASTERY_THRESHOLD
)
) {
this.setState({ status: "graduated" });
console.log("Graduated");
return null;
} else if (chosenProblem == null) {
console.debug("no problems were chosen");
// We have finished all the problems
if (this.lesson && !this.lesson.allowRecycle) {
// If we do not allow problem recycle then we have exhausted the pool
this.setState({ status: "exhausted" });
return null;
} else {
this.completedProbs = new Set();
chosenProblem = context.heuristic(
problems,
this.completedProbs
);
}
}
if (chosenProblem) {
this.setState({ currProblem: chosenProblem, status: "learning" });
// console.log("Next problem: ", chosenProblem.id);
console.debug("problem information", chosenProblem);
this.context.firebase.startedProblem(
chosenProblem.id,
chosenProblem.courseName,
chosenProblem.lesson,
this.lesson.learningObjectives
);
return chosenProblem;
} else {
console.debug("still no chosen problem..? must be an error");
}
};
problemComplete = async (context) => {
this.completedProbs.add(this.state.currProblem.id);
const { setByKey } = this.context.browserStorage;
await setByKey(
LESSON_PROGRESS_STORAGE_KEY(this.lesson.id),
this.completedProbs
).catch((error) => {
this.context.firebase.submitSiteLog(
"site-error",
`componentName: Platform.js`,
{
errorName: error.name || "n/a",
errorCode: error.code || "n/a",
errorMsg: error.message || "n/a",
errorStack: error.stack || "n/a",
},
this.state.currProblem.id
);
});
if (this.lesson.enableCompletionMode) {
const relevantKc = {};
Object.keys(this.lesson.learningObjectives).forEach((x) => {
relevantKc[x] = context.bktParams[x]?.probMastery ?? 0;
});
// Check if all problems are completed or all skills
const progressData = this.getProgressBarData();
const progressPercent = progressData.percent / 100;
const allProblemsCompleted = progressData.completed === progressData.total;
if (allProblemsCompleted) {
console.debug("updateCanvas called because lesson is complete");
this.updateCanvas(progressPercent, relevantKc);
}
this.updateCanvas(progressPercent, relevantKc);
this._nextProblem(context);
} else {
this._nextProblem(context);
}
};
displayMastery = (mastery) => {
this.setState({ mastery: mastery });
if (mastery >= MASTERY_THRESHOLD) {
toast.success("You've successfully completed this assignment!", {
toastId: ToastID.successfully_completed_lesson.toString(),
});
}
};
render() {
const { translate } = this.props;
this.studentNameDisplay = this.context.studentName
? decodeURIComponent(this.context.studentName) + " | "
: translate('platform.LoggedIn') + " | ";
return (
<div
style={{
backgroundColor: "#F6F6F6",
paddingBottom: 20,
display: "flex",
flexDirection: "column",
}}
>
<AppBar position="static">
<Toolbar>
<Grid
container
spacing={0}
role={"navigation"}
alignItems={"center"}
>
<Grid item xs={3} key={1}>
<BrandLogoNav
isPrivileged={this.isPrivileged}
/>
</Grid>
<Grid item xs={6} key={2}>
<div
style={{
textAlign: "center",
textAlignVertical: "center",
paddingTop: "3px",
}}
>
{Boolean(
findLessonById(this.props.lessonID)
)
? findLessonById(this.props.lessonID)
.name +
" " +
findLessonById(this.props.lessonID)
.topics
: ""}
</div>
</Grid>
<Grid item xs={3} key={3}>
<div
style={{
textAlign: "right",
paddingTop: "3px",
}}
>
{this.state.status !== "courseSelection" &&
this.state.status !== "lessonSelection" &&
(this.lesson.showStuMastery == null ||
this.lesson.showStuMastery)
? this.studentNameDisplay +
translate('platform.Mastery') +
Math.round(this.state.mastery * 100) +
"%"
: ""}
</div>
</Grid>
</Grid>
</Toolbar>
</AppBar>
{this.state.status === "courseSelection" ? (
<LessonSelectionWrapper
selectLesson={this.selectLesson}
selectCourse={this.selectCourse}
history={this.props.history}
removeProgress={this.props.removeProgress}
/>
) : (
""
)}
{this.state.status === "lessonSelection" ? (
<LessonSelectionWrapper
selectLesson={this.selectLesson}
removeProgress={this.props.removeProgress}
history={this.props.history}
courseNum={this.props.courseNum}
/>
) : (
""
)}
{this.state.status === "learning" ? (
<ErrorBoundary
componentName={"Problem"}
descriptor={"problem"}
>
<ProblemWrapper
problem={this.state.currProblem}
problemComplete={this.problemComplete}
lesson={this.lesson}
seed={this.state.seed}
lessonID={this.props.lessonID}
displayMastery={this.displayMastery}
progressPercent={this.getProgressBarData().percent / 100}
/>
</ErrorBoundary>
) : (
""
)}
{this.state.status === "exhausted" ? (
<center>
<h2>
Thank you for learning with {SITE_NAME}. You have
finished all problems.
</h2>
</center>
) : (
""
)}
{this.state.status === "graduated" ? (
<center>
<h2>
Thank you for learning with {SITE_NAME}. You have
mastered all the skills for this session!
</h2>
</center>
) : (
""
)}
</div>
);
}
}
export default withRouter(withTranslation(Platform));
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/platform-logic/checkAnswer.js | src/platform-logic/checkAnswer.js | import { variabilize } from './variabilize.js';
import insert from "../util/strInsert";
import { parseMatrixTex } from "../util/parseMatrixTex";
import { IS_DEVELOPMENT, IS_STAGING_OR_DEVELOPMENT } from "../util/getBuildType";
import WrongAnswerReasons from "../util/wrongAnswerReasons";
const KAS = require('../kas.js');
if (IS_DEVELOPMENT) {
window.KAS = KAS
}
// attempt = student answer, actual = [ans1, ans2]
function _equality(attempt, actual) {
const parsedAttempt = attempt.replace(/\s+/g, '').replace(/\\left/g, '').replace(/\\right/g, '');
return actual.filter(stepAns => {
const parsedStepAns = stepAns.replace(/\s+/g, '').replace(/\\left/g, '').replace(/\\right/g, '');
//console.log("parsedAttempt: " + parsedAttempt + " parsedStepAns: " + parsedStepAns);
return parsedAttempt === parsedStepAns
});
}
// attempt = student answer, actual = [ans1, ans2]
/**
*
* @param attempt {Expr}
* @param actual {Expr[]}
* @returns {Expr[]}
* @private
*/
function _parseEquality(attempt, actual) {
//console.log("PARSED: " + attempt.print());
//console.log("ANSWER: " + actual[0].print());
return actual.filter(stepAns => KAS.compare(attempt, stepAns).equal);
}
// Round to precision number of decimal places
function round(num, precision) {
if (precision != null) {
return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision);
} else {
return num;
}
}
/**
* Uses parse
* @param _string the expression string
*/
function parse(_string) {
// explicitly group outermost absolute value pair with parenthesis to imply multiplication when neighboring constant
if (_string.split("|").length === 3) {
const leftIdx = _string.indexOf("\\left|")
if (leftIdx > -1) {
const rightIdx = _string.lastIndexOf("\\right|")
_string = insert(_string, leftIdx, "(")
_string = insert(_string, rightIdx + 8, ")")
} else {
const leftBarIdx = _string.indexOf("|")
const rightBarIdx = _string.lastIndexOf("|")
_string = insert(_string, leftBarIdx, "(")
_string = insert(_string, rightBarIdx + 2, ")")
}
}
const string = _string
.replace(/\$\$/g, '') // replace $$ as KAS can parse LaTex but without the $$ prepended/appended
return KAS.parse(string)
}
function validateAndCorrectFormat(input) {
const fraction = /\\frac(\d)(\d)/g;
const correctedInputFraction = input.replace(fraction, (match, numerator, denominator) => {
return `\\frac{${numerator}}{${denominator}}`;
});
const sqrt = /\\sqrt(\d)/g;
const correctedInput = correctedInputFraction.replace(sqrt, (match, number) => {
return `\\sqrt{${number}}`;
});
return correctedInput;
}
function convertSwedishToUS(numberString) {
let noSpaces = numberString.replace(/\s/g, '');
let formattedNumber = noSpaces.replace(/(?<=\d),(?=\d)/g, '.');
return formattedNumber;
}
/**
*
* @param attempt
* @param actual
* @param answerType
* @param precision
* @param variabilization
* @param questionText {string} allows for a check to see if student pasted in the answer exactly
* @returns {[string, boolean | string, null | WrongAnswerReasons]}
*/
function checkAnswer({ attempt, actual, answerType, precision = 5, variabilization = {}, questionText = ""}) {
if (localStorage.getItem('locale') == 'se') {
attempt = convertSwedishToUS(attempt)
}
let parsed = attempt.replace(/\s+/g, '');
if (variabilization) {
actual = actual.map((actualAns) => variabilize(actualAns, variabilization));
}
try {
if (parsed === "") {
return [parsed, false, WrongAnswerReasons.wrong];
}
if (answerType === "arithmetic") {
// checks if anticipated answer is a matrix
if (/\\begin{[a-zA-Z]?matrix}/.test(actual)) {
console.debug(`attempt: ${attempt} vs. actual:`, actual)
const studentMatrix = JSON.parse(attempt)
const solutionMatrices = parseMatrixTex(actual);
console.debug('solutions: ', solutionMatrices)
let correctAnswers = solutionMatrices.filter(matrix => {
return matrix.reduce((acc, row, idx) => acc && row.reduce((_acc, cell, jdx) => {
const _studentRow = studentMatrix[idx] || []
const _studentCell = _studentRow[jdx] || ""
const _studentExpr = parse(_studentCell).expr
const _solExpr = parse(cell).expr
return _acc && KAS.compare(_studentExpr, _solExpr).equal
}, true), true)
})
if (correctAnswers.length > 0) {
return [attempt, correctAnswers[0], null]
}
return [attempt, false, WrongAnswerReasons.wrong]
} else {
attempt = validateAndCorrectFormat(attempt);
parsed = parse(attempt).expr;
if (!parsed) {
parsed = attempt
}
if (IS_STAGING_OR_DEVELOPMENT) {
console.debug("checkAnswer.js: Using KAS to compare answer with solution", "attempt", attempt, "actual", actual, "parsed", parsed)
console.debug("checkAnswer.js: questionText vs attempt", questionText, "vs", attempt)
}
// try to see if student paste in exact question
try {
const questionTextRepr = parse(questionText).expr.repr()
if (questionTextRepr === parsed.repr()) {
return [parsed.print(), false, WrongAnswerReasons.sameAsProblem];
}
} catch (_) {
// ignored
}
let correctAnswers = _parseEquality(parsed, actual.map((actualAns) => parse(actualAns).expr));
if (correctAnswers.length > 0) {
return [parsed.print(), correctAnswers[0], null]
}
return [parsed.print(), false, WrongAnswerReasons.wrong];
}
} else if (answerType === "string") {
parsed = attempt;
//console.log(parsed);
//console.log(actual);
const correctAnswers = _equality(parsed, actual);
if (correctAnswers.length > 0) {
return [parsed, correctAnswers[0], null]
}
return [parsed, false, WrongAnswerReasons.wrong];
} else {
// guess it is a number problem
parsed = +attempt;
const correctAnswers = _equality(round(parsed, precision), actual.map((actualAns) => round(+actualAns, precision)));
if (correctAnswers.length > 0) {
return [parsed, correctAnswers[0], null]
}
return [parsed, false, WrongAnswerReasons.wrong];
}
} catch (err) {
console.log("error", err);
return [parsed, false, WrongAnswerReasons.errored];
}
}
export { checkAnswer };
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/platform-logic/renderText.js | src/platform-logic/renderText.js | import React from "react";
import { InlineMath } from "react-katex";
import { dynamicText } from "../config/config.js";
import { variabilize, chooseVariables } from "./variabilize.js";
import Spacer from "@components/Spacer";
import ErrorBoundary from "@components/ErrorBoundary";
import RenderMedia from "@components/RenderMedia";
import { CONTENT_SOURCE } from "@common/global-config";
/**
* @param {string|*} text
* @param problemID
* @param {*} variabilization
* @param context
*/
function renderText(text, problemID, variabilization, context) {
if (typeof text !== "string") {
return text;
}
text = text.replaceAll("\\neq", "≠");
text = text.replaceAll("**", "^");
let result = text;
result = parseForMetaVariables(result, context);
for (const d in dynamicText) {
const replace = dynamicText[d];
result = result.split(d).join(replace); // expands all "%dynamic%" text to their specific counterparts
}
if (variabilization) {
result = variabilize(result, variabilization);
}
const lines = result.split("\\n");
return lines.map((line, idx) => {
/**
* If line has LaTeX, split by the "&&" delimiter to separate plain text from LaTeX
* @type {(string | JSX.Element)[]}
*/
let lineParts = line.split("$$");
lineParts = lineParts.map((part, jdx) => {
const isLaTeX = jdx % 2 !== 0; // implies it is in between two "$$" delimiters
if (isLaTeX) {
const regex = /^_{3,}$/;
if (regex.test(part)) {
return parseForFillInQuestions(part);
}
return (
<ErrorBoundary
componentName={"InlineMath"}
replacement={part}
inline
key={Math.random() * 2 ** 16}
>
<InlineMath
math={part}
renderError={(error) => {
throw error;
}}
/>
</ErrorBoundary>
);
}
const lineSubParts = part.split("##");
return lineSubParts.map((subPart, kdx) => {
const isMedia = kdx % 2 !== 0;
if (isMedia) {
return (
<center key={Math.random() * 2 ** 16}>
<RenderMedia
url={subPart}
problemID={problemID}
contentSource={CONTENT_SOURCE}
/>
</center>
);
}
return parseForFillInQuestions(subPart);
});
});
// add a spacer if it isn't the last line
if (idx !== lines.length - 1) {
lineParts.push(
<Spacer height={2} width={2} key={Math.random() * 2 ** 16} />
);
}
return lineParts;
});
}
/**
* Renders the text generated from ChatGPT.
* @param {string|*} text
* @param problemID
* @param {*} variabilization
* @param context
*/
function renderGPTText(text, problemID, variabilization, context) {
if (typeof text !== "string") {
return text;
}
text = preprocessChatGPTResponse(text);
text = text.replaceAll("\\neq", "≠");
text = text.replaceAll("**", "^");
let result = text;
result = parseForMetaVariables(result, context);
for (const d in dynamicText) {
const replace = dynamicText[d];
result = result.split(d).join(replace); // expands all "%dynamic%" text to their specific counterparts
}
if (variabilization) {
result = variabilize(result, variabilization);
}
let lines = result.split("\\n");
lines = lines.map((line, idx) => {
/**
* If line has LaTeX, split by the "&&" delimiter to separate plain text from LaTeX
* @type {(string | JSX.Element)[]}
*/
let lineParts = line.split("$$");
lineParts = lineParts.map((part, jdx) => {
const isLaTeX = jdx % 2 !== 0; // implies it is in between two "$$" delimiters
if (isLaTeX) {
const regex = /^_{3,}$/;
if (regex.test(part)) {
return parseForFillInQuestions(part);
}
return (
<ErrorBoundary
componentName={"InlineMath"}
replacement={part}
inline
key={Math.random() * 2 ** 16}
>
<InlineMath
math={part}
renderError={(error) => {
throw error;
}}
/>
</ErrorBoundary>
);
}
const lineSubParts = part.split("##");
return lineSubParts.map((subPart, kdx) => {
const isMedia = kdx % 2 !== 0;
if (isMedia) {
return (
<center key={Math.random() * 2 ** 16}>
<RenderMedia
url={subPart}
problemID={problemID}
contentSource={CONTENT_SOURCE}
/>
</center>
);
}
return parseForFillInQuestions(subPart);
});
});
// add a spacer if it isn't the last line
if (idx !== lines.length - 1) {
lineParts.push(
<Spacer height={2} width={2} key={Math.random() * 2 ** 16} />
);
}
return lineParts;
});
return lines;
}
const META_REGEX = /%\{([^{}%"]+)}/g;
const mapper = {
oats_user_id: (context) => context.userID,
};
/**
* Takes in a string and iff there is a part that matches %{variable}, replace it with some context metadata
* @param {string} str
* @param context
* @return {string}
*/
function parseForMetaVariables(str, context) {
return str.replaceAll(META_REGEX, (ogMatch, group1) => {
if (group1 in mapper) {
return mapper[group1].call(this, context);
}
return ogMatch;
});
}
function preprocessChatGPTResponse(input) {
// Step 1: Replace ChatGPT '\n' new lines with '\\n'
input = input.replace(/\n/g, "\\n");
// Step 2: Replace monetary values ($12,000) with (\uFF04)12,000
const moneyRegex = /\$(\d{1,3}(,\d{3})*(\.\d{2})?|(\d+))/g;
input = input.replace(moneyRegex, (_, moneyValue) => `\uFF04${moneyValue}`);
// Step 3: Convert any remaining single dollar signs (not part of monetary values) to double dollars
input = input.replace(/(?<!\$)\$(?!\$)/g, "$$$$");
// Step 4: Replace all instances of \uFF04 back to $
input = input.replace(/\uFF04/g, "$");
return input;
}
/**
* Takes in a string and iff there is 3+ underscores in a row, convert it into a fill-in-the-blank box.
* @param {(string)} str
* @return {(string | JSX.Element)[]}
*/
function parseForFillInQuestions(str) {
const strParts = str.split(/_{3,}/);
let result = [];
strParts.forEach((part, idx) => {
if (idx > 0) {
result.push(
<span
key={Math.random() * 2 ** 16}
aria-label={"fill in the blank"}
style={{
// TODO: choose between the following two styles
marginLeft: "0.5ch",
marginRight: "0.5ch",
paddingLeft: "2.5ch",
paddingRight: "2.5ch",
position: "relative",
background: "rgb(242,243,244)",
borderRadius: "0.6ch",
}}
>
<div
style={{
position: "absolute",
bottom: 3.5,
left: 4,
right: 4,
height: 1.5,
borderRadius: "0.6ch",
background: "rgb(75,76,77)",
}}
/>
</span>
);
}
result.push(part);
});
return result;
}
export { renderText, renderGPTText, chooseVariables };
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/platform-logic/variabilize.js | src/platform-logic/variabilize.js | var gen = require('random-seed');
// Replace variables with their values in a string of text
function variabilize(text, variabilization) {
if (typeof variabilization === 'undefined' || Object.keys(variabilization).length === 0) {
return text;
}
Object.keys(variabilization).forEach(v => {
if (variabilization[v].length !== 1) {
console.log("[WARNING] - variable not properly chosen");
}
var replaceOption = variabilization[v][0];
text = text.replace(new RegExp('@{' + v + '}', 'g'), replaceOption);
});
return text;
}
// Lock in variables chosen at Problem/Step/Hint. This method must be imported and called elsewhere
function chooseVariables(variabilization, seed) {
if (typeof variabilization === 'undefined' || Object.keys(variabilization).length === 0) {
return variabilization
}
var numOptions = 0;
for (var v in variabilization) {
numOptions = Math.max(numOptions, variabilization[v].length);
}
var rand1 = gen.create(seed);
var chosen = rand1(numOptions)
Object.keys(variabilization).forEach(v => {
// Take r index of each variable, r is same across all vars.
var replaceOption = variabilization[v][(chosen + 1) % variabilization[v].length];
variabilization[v] = [replaceOption];
});
return variabilization;
}
export { variabilize, chooseVariables }
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/platform-logic/DebugPlatform.js | src/platform-logic/DebugPlatform.js | import React from 'react';
import { AppBar, Toolbar, Typography } from '@material-ui/core';
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import ProblemWrapper from "@components/problem-layout/ProblemWrapper.js";
import { ThemeContext } from '../config/config.js';
import Box from "@material-ui/core/Box";
import BrandLogoNav from "@components/BrandLogoNav";
import { CONTENT_SOURCE } from "@common/global-config";
let problemPool = require(`@generated/processed-content-pool/${CONTENT_SOURCE}.json`)
let seed = Date.now().toString();
console.log("Generated seed");
class DebugPlatform extends React.Component {
static contextType = ThemeContext;
constructor(props, context) {
context.debug = true;
super(props);
this.problemIndex = {
problems: problemPool
};
this.completedProbs = new Set();
this.lesson = null;
let chosenProblem = null;
const problemIDs = [];
// Add each Q Matrix skill model attribute to each step
for (const problem of this.problemIndex.problems) {
problemIDs.push(problem.id)
if (problem.id === this.props.problemID) {
chosenProblem = problem;
}
for (let stepIndex = 0; stepIndex < problem.steps.length; stepIndex++) {
const step = problem.steps[stepIndex];
step.knowledgeComponents = context.skillModel[step.id];
}
}
context.problemID = this.props.problemID
context.problemIDs = problemIDs.sort(this.__compareProblemID)
this.state = {
currProblem: chosenProblem,
status: "learning",
seed: seed
}
}
componentDidMount() {
if (this.context.needRefresh) {
this.context.needRefresh = false;
window.location.reload();
}
this.onComponentUpdate(null, null, null)
}
componentWillUnmount() {
this.context.problemID = "n/a"
}
componentDidUpdate(prevProps, prevState, snapshot) {
this.onComponentUpdate(prevProps, prevState, snapshot)
}
onComponentUpdate(prevProps, prevState, snapshot){
if (Boolean(this.state.currProblem?.id) && this.context.problemID !== this.state.currProblem.id) {
this.context.problemID = this.state.currProblem.id
}
}
selectProblem = (problemID, context) => {
seed = Date.now().toString();
this.setState({ seed: seed }, () => console.log(seed));
context.debug = true;
this.problemIndex = {
problems: problemPool
};
this.completedProbs = new Set();
this.lesson = null;
let chosenProblem = null;
const problemIDs = [];
// Add each Q Matrix skill model attribute to each step
for (const problem of this.problemIndex.problems) {
problemIDs.push(problem.id)
if (problem.id === this.props.problemID) {
chosenProblem = problem;
}
for (let stepIndex = 0; stepIndex < problem.steps.length; stepIndex++) {
const step = problem.steps[stepIndex];
step.knowledgeComponents = context.skillModel[step.id];
}
}
context.problemIDs = problemIDs.sort(this.__compareProblemID);
console.log(context.problemIDs)
this.setState({
currProblem: chosenProblem,
status: "learning",
seed: seed
})
}
__compareProblemID = (a, b) => {
var aNum = a.match(/\d+$/);
if (aNum) {
aNum = parseInt(aNum[0]);
}
var bNum = b.match(/\d+$/);
if (bNum) {
bNum = parseInt(bNum[0]);
}
var aName = a.match(/^[^0-9]+/);
if (aName) {
aName = aName[0];
}
var bName = b.match(/^[^0-9]+/);
if (bName) {
bName = bName[0];
}
if (aName !== bName) {
return aName.localeCompare(bName);
} else {
return aNum - bNum;
}
}
_nextProblem = (context, problemID) => {
seed = Date.now().toString();
this.setState({ seed: seed });
this.props.saveProgress();
var chosenProblem = null;
for (var problem of this.problemIndex.problems) {
// Calculate the mastery for this problem
var probMastery = 1;
var isRelevant = false;
for (var step of problem.steps) {
if (typeof step.knowledgeComponents === "undefined") {
continue;
}
for (var kc of step.knowledgeComponents) {
if (typeof context.bktParams[kc] === "undefined") {
console.log("BKT Parameter " + kc + " does not exist.");
continue;
}
// Multiply all the mastery priors
if (!(kc in context.bktParams)) {
console.log("Missing BKT parameter: " + kc);
}
probMastery *= context.bktParams[kc].probMastery;
}
}
if (isRelevant) {
problem.probMastery = probMastery;
} else {
problem.probMastery = null;
}
}
chosenProblem = context.heuristic(this.problemIndex.problems, this.completedProbs);
//console.log(Object.keys(context.bktParams).map((skill) => (context.bktParams[skill].probMastery <= this.lesson.learningObjectives[skill])));
this.setState({ currProblem: chosenProblem, status: "learning" });
console.log("Next problem: ", chosenProblem.id)
return chosenProblem;
}
problemComplete = (context) => {
this.completedProbs.add(this.state.currProblem.id);
return this._nextProblem(context);
}
render() {
return (
<div style={{ backgroundColor: "#F6F6F6", paddingBottom: 20 }}>
<AppBar position="static">
<Toolbar>
<Grid container spacing={0} role={"navigation"}>
<Grid item xs={3} key={1}>
<BrandLogoNav noLink={true}/>
</Grid>
<Grid item xs={6} key={2}>
<div
style={{
textAlign: 'center',
textAlignVertical: 'center',
paddingTop: "6px",
paddingBottom: "6px"
}}>
{"Debug Mode: " + this.props.problemID}
</div>
</Grid>
<Grid item xs={3} key={3}>
<div style={{ textAlign: 'right' }}>
<Button
aria-label={`Return to home`}
aria-roledescription={`Return to the home page`}
role={"link"}
color="inherit"
onClick={() => {
this.props.history.push("/")
this.setState({ status: "lessonSelection" })
}}>
Home
</Button>
</div>
</Grid>
</Grid>
</Toolbar>
</AppBar>
{this.state.currProblem
? <ProblemWrapper problem={this.state.currProblem} problemComplete={this.problemComplete}
lesson={this.lesson}
seed={this.state.seed}/>
: <Box width={'100%'} textAlign={'center'} pt={4} pb={4}>
<Typography variant={'h3'}>Problem id <code>{this.props.problemID}</code> is not
valid!</Typography>
</Box>
}
</div>
);
}
}
export default DebugPlatform;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/platform-logic/bioInfo.js | src/platform-logic/bioInfo.js | import React, { Component } from "react";
import { AppBar, Toolbar } from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
import BrandLogoNav from "@components/BrandLogoNav";
import "./bioInfo.css";
class BioInfo extends Component {
constructor(props) {
super(props);
this.state = {
userInput: {
gender: "",
age: "",
confidenceQ1: "",
confidenceQ2: "",
judgementQ1: "",
judgementQ2: "",
judgementQ3: "",
other: "",
},
showModal: false,
allowSave: true,
};
}
componentDidMount() {
const savedData = localStorage.getItem("bioInfo");
if (savedData) {
this.setState({ userInput: JSON.parse(savedData) });
}
}
handleInputChange = (event) => {
const { value, name } = event.target;
// console.log(name, value);
this.setState((prevState) => ({
userInput: {
...prevState.userInput,
[name]: value,
},
allowSave: true,
}));
};
checkValidAnswer = () => {
const { userInput } = this.state;
if (
!userInput.age ||
!userInput.gender ||
!userInput.confidenceQ1 ||
!userInput.confidenceQ2 ||
!userInput.judgementQ1 ||
!userInput.judgementQ2 ||
!userInput.judgementQ3
) {
alert("Empty values detected. Please answer all questions.");
return false;
}
return true;
};
handleSave = () => {
const { userInput } = this.state;
if (this.checkValidAnswer()) {
localStorage.setItem("bioInfo", JSON.stringify(userInput));
// console.log(userInput);
this.setState({ allowSave: false });
alert("Information saved successfully!");
}
};
handleDelete = () => {
this.setState({ showModal: true });
};
handleConfirmDelete = () => {
localStorage.removeItem("bioInfo");
alert("Information deleted successfully!");
this.setState({
userInput: {
gender: "",
age: "",
confidenceQ1: "",
confidenceQ2: "",
judgementQ1: "",
judgementQ2: "",
judgementQ3: "",
other: "",
},
showModal: false,
allowSave: true,
});
};
handleCancelDelete = () => {
this.setState({ showModal: false });
};
render() {
const { userInput, showModal } = this.state;
return (
<div className="container">
<AppBar position="static">
<Toolbar>
<Grid
container
spacing={0}
role={"navigation"}
alignItems={"center"}
>
<Grid item xs={3} key={1}>
<BrandLogoNav
isPrivileged={this.isPrivileged}
/>
</Grid>
</Grid>
</Toolbar>
</AppBar>
<div className="content-container">
<h1 className="title">Enter your Bio Information</h1>
<div className="survey-quest">
<label className="survey-text">
What gender do you identify as?
</label>
<select
name="gender"
value={userInput.gender}
onChange={(e) => this.handleInputChange(e)}
>
<option value="">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
</div>
<div className="survey-quest">
<label className="survey-text">What is your age?</label>
<input
type="number"
name="age"
value={userInput.age}
onChange={(e) => this.handleInputChange(e)}
></input>
</div>
<div className="survey-quest">
<label className="survey-text">
Please select the option you most agree with:
</label>
<select
name="confidenceQ1"
value={userInput.confidenceQ1}
onChange={(e) => this.handleInputChange(e)}
>
<option value="">Select</option>
<option value="I’m no good at math">
I’m no good at math
</option>
<option
value="For some reason, even though I study, math seems
unusually hard for me"
>
For some reason, even though I study, math seems
unusually hard for me
</option>
<option value="I can get good grades in math">
I can get good grades in math
</option>
</select>
</div>
<div className="survey-quest">
<label className="survey-text">
Please select the option you most agree with:
</label>
<select
name="confidenceQ2"
value={userInput.confidenceQ2}
onChange={(e) => this.handleInputChange(e)}
>
<option value="">Select</option>
<option value="I am confident that I can get an A in math">
I am confident that I can get an A in math
</option>
<option value="I am confident that I can get an B in math">
I am confident that I can get an B in math
</option>
<option value="I am confident that I can get an C in math">
I am confident that I can get an C in math
</option>
<option
value="I am confident that I can get a passing grade in
math"
>
I am confident that I can get a passing grade in
math
</option>
</select>
</div>
<div className="survey-quest">
<label className="survey-text">
If I had more time for practice, I would be better
in mathematics.
</label>
<select
name="judgementQ1"
value={userInput.judgementQ1}
onChange={(e) => this.handleInputChange(e)}
>
<option value="">Select</option>
<option value="Strongly don’t agree">
Strongly don’t agree
</option>
<option value="Don’t agree">Don’t agree</option>
<option value="Undecided">Undecided</option>
<option value="Agree">Agree</option>
<option value="Strongly agree">
Strongly agree
</option>
</select>
</div>
<div className="survey-quest">
<label className="survey-text">
If I was more patient while solving mathematical
problems, I would be better in mathematics.
</label>
<select
name="judgementQ2"
value={userInput.judgementQ2}
onChange={(e) => this.handleInputChange(e)}
>
<option value="">Select</option>
<option value="Strongly don’t agree">
Strongly don’t agree
</option>
<option value="Don’t agree">Don’t agree</option>
<option value="Undecided">Undecided</option>
<option value="Agree">Agree</option>
<option value="Strongly agree">
Strongly agree
</option>
</select>
</div>
<div className="survey-quest">
<label className="survey-text">
No matter how much time I devote for studying
mathematics, I can’t improve my grades.
</label>
<select
name="judgementQ3"
value={userInput.judgementQ3}
onChange={(e) => this.handleInputChange(e)}
>
<option value="">Select</option>
<option value="Strongly don’t agree">
Strongly don’t agree
</option>
<option value="Don’t agree">Don’t agree</option>
<option value="Undecided">Undecided</option>
<option value="Agree">Agree</option>
<option value="Strongly agree">
Strongly agree
</option>
</select>
</div>
<div className="survey-quest">
<span>Other information</span>
<textarea
className="input-field"
name="other"
value={userInput.other}
onChange={(e) => this.handleInputChange(e)}
placeholder="Enter your information..."
/>
</div>
<div className="button-row">
<button
className="save-button"
onClick={this.handleSave}
disabled={!this.state.allowSave}
>
Save
</button>
<button
className="delete-button"
onClick={this.handleDelete}
>
Delete
</button>
</div>
{showModal && (
<div className="modal">
<div className="modal-content">
<h3>Confirm Deletion</h3>
<p>
Are you sure you want to delete the
information?
</p>
<div className="modal-buttons">
<button
className="confirm-button"
onClick={this.handleConfirmDelete}
>
Yes
</button>
<button
className="cancel-button"
onClick={this.handleCancelDelete}
>
No
</button>
</div>
</div>
</div>
)}
</div>
</div>
);
}
}
export default BioInfo;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/config/firebaseConfig.js | src/config/firebaseConfig.js | const config = {
apiKey: "[apikey]",
authDomain: "[projId].firebaseapp.com",
databaseURL: "https://[projId].firebaseio.com",
projectId: "[projId]",
storageBucket: "[projId].appspot.com",
messagingSenderId: "[messagingSenderId]",
appId: "[appId]",
measurementId: "[measurementId]",
};
export default config;
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/src/config/config.js | src/config/config.js | import React from "react";
import courses from "../content-sources/oatutor/coursePlans.json";
import { calculateSemester } from "../util/calculateSemester.js";
import { SITE_NAME } from "@common/global-config";
import { cleanObjectKeys } from "../util/cleanObject";
const ThemeContext = React.createContext(0);
const SITE_VERSION = "1.6";
const CURRENT_SEMESTER = calculateSemester(Date.now());
/**
* If user does not access the website through Canvas, show a warning (for the first time).
* @type {boolean}
*/
const SHOW_NOT_CANVAS_WARNING = false;
/**
* Indicates whether the copyright disclaimer should be shown in the footer of the website.
* @type {boolean}
*/
const SHOW_COPYRIGHT = false;
/**
* Only set to true if firebaseConfig.js is set, and you wish to use Firebase to store events. Events include user
* feedback, user interactions, and site logs.
* @type {boolean}
*/
const ENABLE_FIREBASE = true;
/**
* If ENABLE_FIREBASE, indicates whether the site should use Firebase to store, process, and analyze general user
* interactions.
* @type {boolean}
*/
const DO_LOG_DATA = true;
/**
* Indicates whether a log event should be fired everytime a user leaves or returns to this window.
* @type {boolean}
*/
const DO_FOCUS_TRACKING = true;
/**
* If DO_LOG_DATA is enabled, indicates whether the site should also track user mouse interactions with the site. See
* the README.md to properly enable this feature.
* @type {boolean}
*/
const DO_LOG_MOUSE_DATA = false;
/**
* Flag to enable or disable A/B testing
* @type {boolean}
*/
const AB_TEST_MODE = false;
/**
* If reach bottom of provided hints, give correct answer to question
* @type {boolean}
*/
const ENABLE_BOTTOM_OUT_HINTS = true;
// DynamicText not supported for HTML body types
const dynamicText = {
"%CAR%": "Tesla car",
};
const _SHORT_SITE_NAME = SITE_NAME.toLowerCase()
.replace(/[^a-z]/g, "")
.substr(0, 16);
const USER_ID_STORAGE_KEY = `${_SHORT_SITE_NAME}-user_id`;
const PROGRESS_STORAGE_KEY = `${_SHORT_SITE_NAME}-progress`;
export const LESSON_PROGRESS_STORAGE_KEY = (lessonId) =>
`${PROGRESS_STORAGE_KEY}-${lessonId}`;
const CANVAS_WARNING_STORAGE_KEY = `${_SHORT_SITE_NAME}-canvas-warning-dismissed`;
// Firebase Config
const MAX_BUFFER_SIZE = 100;
const GRANULARITY = 5;
const EQUATION_EDITOR_AUTO_COMMANDS =
"pi theta sqrt sum prod int alpha beta gamma rho nthroot pm";
const EQUATION_EDITOR_AUTO_OPERATORS = "sin cos tan";
const MIDDLEWARE_URL =
"https://di2iygvxtg.execute-api.us-west-1.amazonaws.com/prod";
const HELP_DOCUMENT =
"https://docs.google.com/document/d/e/2PACX-1vToe2F3RiCx1nwcX9PEkMiBA2bFy9lQRaeWIbyqlc8W_KJ9q-hAMv34QaO_AdEelVY7zjFAF1uOP4pG/pub";
const DYNAMIC_HINT_URL = process.env.AI_HINT_GENERATION_AWS_ENDPOINT;
const DYNAMIC_HINT_TEMPLATE =
"<{problem_title}.> <{problem_subtitle}.> <{question_title}.> <{question_subtitle}.> <Student's answer is: {student_answer}.> <The correct answer is: {correct_answer}.> Please give a hint for this.";
const MASTERY_THRESHOLD = 0.95;
// const coursePlans = courses.sort((a, b) => a.courseName.localeCompare(b.courseName));
const coursePlans = courses;
const _coursePlansNoEditor = coursePlans.filter(({ editor }) => !!!editor);
const lessonPlans = [];
for (let i = 0; i < coursePlans.length; i++) {
const course = coursePlans[i];
for (let j = 0; j < course.lessons.length; j++) {
course.lessons[j].learningObjectives = cleanObjectKeys(
course.lessons[j].learningObjectives
);
lessonPlans.push({
...course.lessons[j],
courseName: course.courseName,
courseOER: course.courseOER != null ? course.courseOER : "",
courseLicense:
course.courseLicense != null ? course.courseLicense : "",
});
}
}
const _lessonPlansNoEditor = lessonPlans.filter(
({ courseName }) => !courseName.startsWith("!!")
);
const findLessonById = (ID) => {
return _lessonPlansNoEditor.find((lessonPlan) => lessonPlan.id === ID);
};
export {
ThemeContext,
SITE_VERSION,
ENABLE_FIREBASE,
DO_LOG_DATA,
DO_LOG_MOUSE_DATA,
AB_TEST_MODE,
dynamicText,
ENABLE_BOTTOM_OUT_HINTS,
lessonPlans,
coursePlans,
_lessonPlansNoEditor,
_coursePlansNoEditor,
MAX_BUFFER_SIZE,
GRANULARITY,
EQUATION_EDITOR_AUTO_COMMANDS,
EQUATION_EDITOR_AUTO_OPERATORS,
MIDDLEWARE_URL,
DYNAMIC_HINT_URL,
DYNAMIC_HINT_TEMPLATE,
MASTERY_THRESHOLD,
USER_ID_STORAGE_KEY,
PROGRESS_STORAGE_KEY,
SITE_NAME,
HELP_DOCUMENT,
SHOW_COPYRIGHT,
CURRENT_SEMESTER,
CANVAS_WARNING_STORAGE_KEY,
DO_FOCUS_TRACKING,
findLessonById,
SHOW_NOT_CANVAS_WARNING,
};
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
CAHLR/OATutor | https://github.com/CAHLR/OATutor/blob/10a5baf153a505267af8045b05c217b4be6bd8b4/common/global-config.js | common/global-config.js | const SESSION_SYSTEM = "SEMESTER"
const SITE_NAME = "OATutor"
const CONTENT_SOURCE = "oatutor"
module.exports = {
SESSION_SYSTEM,
SITE_NAME,
CONTENT_SOURCE
}
| javascript | MIT | 10a5baf153a505267af8045b05c217b4be6bd8b4 | 2026-01-05T03:39:09.711315Z | false |
youhunwl/TVAPP | https://github.com/youhunwl/TVAPP/blob/aecf353f0f3261932f501a17a866d2cbe301541e/电视直播/酷9直播/webview双模式播放全攻略/webview_jscode.js | 电视直播/酷9直播/webview双模式播放全攻略/webview_jscode.js | (function () {
const startTime = Date.now();
let videoElement = null;
let controlsVisible = false;
let controlsTimeout = null;
// 移除默认控制条
function removeControls() {
const selectors = [
'#control_bar', '.controls',
'.vjs-control-bar', 'xg-controls',
'.xgplayer-ads', '.fixed-layer',
'div[style*="z-index: 9999"]',
'.video-controls', '.player-controls', '.live-controls'
];
selectors.forEach((selector) => {
document.querySelectorAll(selector).forEach((element) => {
element.style.display = 'none';
element.parentNode?.removeChild(element);
});
});
}
// 创建控制面板
function createControlPanel() {
const panel = document.createElement('div');
panel.id = 'custom-control-panel';
panel.style.cssText = `
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
width: 80%;
max-width: 800px;
height: 60px;
background-color: rgba(0,0,0,0.7);
border-radius: 10px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 2147483646;
transition: opacity 0.3s;
opacity: 0;
pointer-events: none;
`;
// 进度条
const progressContainer = document.createElement('div');
progressContainer.style.cssText = `
width: 90%;
height: 10px;
background-color: rgba(255,255,255,0.3);
border-radius: 5px;
margin: 5px 0;
cursor: pointer;
`;
const progressBar = document.createElement('div');
progressBar.id = 'custom-progress-bar';
progressBar.style.cssText = `
width: 0%;
height: 100%;
background-color: #ff0000;
border-radius: 5px;
position: relative;
`;
const progressThumb = document.createElement('div');
progressThumb.style.cssText = `
width: 15px;
height: 15px;
background-color: #fff;
border-radius: 50%;
position: absolute;
right: -7.5px;
top: 50%;
transform: translateY(-50%);
display: none;
`;
progressBar.appendChild(progressThumb);
progressContainer.appendChild(progressBar);
panel.appendChild(progressContainer);
// 控制按钮容器
const buttonsContainer = document.createElement('div');
buttonsContainer.style.cssText = `
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 40px;
`;
// 播放/暂停按钮
const playPauseBtn = document.createElement('div');
playPauseBtn.id = 'custom-play-pause';
playPauseBtn.innerHTML = '⏸';
playPauseBtn.style.cssText = `
font-size: 24px;
color: white;
margin: 0 15px;
cursor: pointer;
user-select: none;
`;
// 时间显示
const timeDisplay = document.createElement('div');
timeDisplay.id = 'custom-time-display';
timeDisplay.textContent = '00:00 / 00:00';
timeDisplay.style.cssText = `
color: white;
font-family: Arial, sans-serif;
font-size: 14px;
margin: 0 15px;
user-select: none;
`;
buttonsContainer.appendChild(playPauseBtn);
buttonsContainer.appendChild(timeDisplay);
panel.appendChild(buttonsContainer);
document.body.appendChild(panel);
// 事件监听
playPauseBtn.addEventListener('click', togglePlayPause);
progressContainer.addEventListener('click', handleProgressClick);
progressContainer.addEventListener('mousemove', () => progressThumb.style.display = 'block');
progressContainer.addEventListener('mouseout', () => progressThumb.style.display = 'none');
// 鼠标移动显示控制面板
document.addEventListener('mousemove', showControls);
}
// 显示控制面板
function showControls() {
const panel = document.getElementById('custom-control-panel');
if (!panel) return;
panel.style.opacity = '1';
panel.style.pointerEvents = 'auto';
controlsVisible = true;
clearTimeout(controlsTimeout);
controlsTimeout = setTimeout(() => {
panel.style.opacity = '0';
panel.style.pointerEvents = 'none';
controlsVisible = false;
}, 3000);
}
// 切换播放/暂停
function togglePlayPause() {
if (!videoElement) return;
if (videoElement.paused) {
play();
} else {
pause();
}
}
// 更新进度条
function updateProgressBar() {
if (!videoElement) return;
const progressBar = document.getElementById('custom-progress-bar');
const timeDisplay = document.getElementById('custom-time-display');
if (progressBar && timeDisplay) {
const percent = (videoElement.currentTime / videoElement.duration) * 100;
progressBar.style.width = `${percent}%`;
const currentTime = formatTime(videoElement.currentTime);
const duration = formatTime(videoElement.duration);
timeDisplay.textContent = `${currentTime} / ${duration}`;
ku9.setposition(videoElement.currentTime);
ku9.setduration(videoElement.duration);
}
}
// 格式化时间
function formatTime(seconds) {
const minutes = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
// 处理进度条点击
function handleProgressClick(e) {
if (!videoElement) return;
const progressContainer = e.currentTarget;
const rect = progressContainer.getBoundingClientRect();
const percent = (e.clientX - rect.left) / rect.width;
const seekTime = percent * videoElement.duration;
setposition(seekTime);
}
// 设置视频比例
window.setscale = function (scaletype) {
if (!videoElement) return;
const container = videoElement.parentElement;
const baseStyle = `
position: absolute !important;
top: 50% !important;
left: 50% !important;
transform: translate(-50%, -50%) !important;
outline: none !important;
border: none !important;
box-shadow: none !important;
`;
switch (scaletype) {
case 0: // 默认(填充)
videoElement.style.cssText = baseStyle + `
width: 100% !important;
height: 100% !important;
object-fit: fill !important;
`;
break;
case 1: // 16:9
videoElement.style.cssText = baseStyle + `
width: 100% !important;
height: 100% !important;
aspect-ratio: 16 / 9 !important;
`;
break;
case 2: // 4:3
videoElement.style.cssText = baseStyle + `
width: 100% !important;
height: 100% !important;
aspect-ratio: 4 / 3 !important;
`;
break;
case 3: // 填充
videoElement.style.cssText = baseStyle + `
width: 100% !important;
height: 100% !important;
object-fit: fill !important;
`;
break;
case 4: // 原始
videoElement.style.cssText = baseStyle + `
width: 100% !important;
height: 100% !important;
object-fit: none !important;
`;
break;
case 5: // 裁剪
videoElement.style.cssText = baseStyle + `
width: 100% !important;
height: 100% !important;
object-fit: cover !important;
`;
break;
}
};
// 设置全屏容器
function setupVideo(video) {
videoElement = video;
const container = document.createElement('div');
container.id = 'video-fullscreen-container';
container.style.cssText = `
position: fixed !important;
top: 0 !important;
left: 0 !important;
width: 100% !important;
height: 100% !important;
z-index: 2147483647 !important;
background: black !important;
overflow: hidden !important;
transform: translateZ(0);
`;
// 设置画面比例
setscale(ku9.getscale());
document.body.appendChild(container);
container.appendChild(video);
// 创建控制面板
createControlPanel();
// 设置进度更新定时器
setInterval(updateProgressBar, 500);
// 进入全屏模式
const enterFullscreen = () => {
const fullscreenElem = container.requestFullscreen
? container
: video;
const requestFS =
fullscreenElem.requestFullscreen ||
fullscreenElem.webkitRequestFullscreen ||
fullscreenElem.mozRequestFullScreen;
if (requestFS) {
requestFS.call(fullscreenElem).catch(() => {
container.style.width = `${window.innerWidth}px`;
container.style.height = `${window.innerHeight}px`;
});
}
video.volume = 1;
};
setTimeout(enterFullscreen, 300);
}
// 检测视频元素
function checkVideo() {
if (Date.now() - startTime > 15000) {
clearInterval(interval);
return;
}
const video = document.querySelector('video');
if (!video) return;
if (video.paused) video.play();
if (video && video.readyState > 0) {
clearInterval(interval);
removeControls();
setupVideo(video);
if (video.videoWidth && video.videoHeight) {
ku9.setvideo(video.videoWidth, video.videoHeight);
ku9.setaudio("立体声");
}
}
}
// 启动检测
const interval = setInterval(checkVideo, 100);
// 移动端适配
const viewportMeta = document.createElement('meta');
viewportMeta.name = "viewport";
viewportMeta.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no";
document.head.appendChild(viewportMeta);
// 错误处理
window.onerror = function (message, source, lineno, colno, error) {
console.error(`Error: ${message}\nSource: ${source}\nLine: ${lineno}\nColumn: ${colno}\nError: ${error}`);
};
// 视频控制函数
function pause() {
if (videoElement) {
videoElement.pause();
const btn = document.getElementById('custom-play-pause');
if (btn) btn.innerHTML = '▶';
}
}
function play() {
if (videoElement) {
videoElement.play();
const btn = document.getElementById('custom-play-pause');
if (btn) btn.innerHTML = '⏸';
}
}
function setposition(position) {
if (videoElement) {
videoElement.currentTime = position;
updateProgressBar();
}
}
// 暴露函数到全局
window.pause = pause;
window.play = play;
window.setposition = setposition;
})(); | javascript | Apache-2.0 | aecf353f0f3261932f501a17a866d2cbe301541e | 2026-01-04T15:58:58.323523Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.