mirror of
https://cdm-project.com/Download-Tools/udemy-downloader.git
synced 2025-04-30 00:34:24 +02:00
fix articles
This commit is contained in:
parent
745ea117de
commit
2d6a3020aa
@ -1,118 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
|
||||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
||||||
<title>Coding Assignment</title>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
body {
|
|
||||||
font-family: sf pro text, -apple-system, BlinkMacSystemFont, Roboto,
|
|
||||||
segoe ui, Helvetica, Arial, sans-serif, apple color emoji,
|
|
||||||
segoe ui emoji, segoe ui symbol;
|
|
||||||
font-weight: 400;
|
|
||||||
line-height: 22.4px;
|
|
||||||
font-size: 16px;
|
|
||||||
}
|
|
||||||
p, ul, ol {
|
|
||||||
font-size: 16px;
|
|
||||||
font-weight: 400;
|
|
||||||
}
|
|
||||||
h1, h2, h3, h4, h5, h6 {
|
|
||||||
font-weight: bold;
|
|
||||||
}
|
|
||||||
ul {
|
|
||||||
list-style: none;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
max-width: none;
|
|
||||||
}
|
|
||||||
.code-snippet {
|
|
||||||
background-color: #fff;
|
|
||||||
border: 1px solid #d1d7dc;
|
|
||||||
color: #b4690e;
|
|
||||||
font-size: 90%;
|
|
||||||
padding: 0.2rem 0.4rem;
|
|
||||||
}
|
|
||||||
.code-block {
|
|
||||||
background-color: #fff;
|
|
||||||
color: #b4690e;
|
|
||||||
font-size: 90%;
|
|
||||||
}
|
|
||||||
.black-block {
|
|
||||||
color: #000000;
|
|
||||||
}
|
|
||||||
.italic-text {
|
|
||||||
font-style: italic;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body onload="main()">
|
|
||||||
<h1 id="coding-title"></h1>
|
|
||||||
<div>
|
|
||||||
<h2>Instructions</h2>
|
|
||||||
<div id="coding-instructions"></div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h2>Test(s)</h2>
|
|
||||||
<div id="coding-tests"></div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h2>Solution(s)</h2>
|
|
||||||
<div id="coding-solutions"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
const quizData = __data_placeholder__;
|
|
||||||
|
|
||||||
function renderCodeList(rootElement, codeList, className, titlePrefix) {
|
|
||||||
for (var i = 0; i < codeList.length; i++) {
|
|
||||||
var elem = codeList[i];
|
|
||||||
var jsElem = document.createElement("div");
|
|
||||||
jsElem.className = className;
|
|
||||||
var jsElemTitle = document.createElement("h3");
|
|
||||||
jsElemTitle.innerHTML = titlePrefix + " " + (i + 1);
|
|
||||||
var jsElemBody = document.createElement("code");
|
|
||||||
jsElemBody.className = "code-block black-block";
|
|
||||||
jsElemBody.innerHTML = "<pre>" + elem.content + "</pre>";
|
|
||||||
jsElem.appendChild(jsElemTitle);
|
|
||||||
jsElem.appendChild(jsElemBody);
|
|
||||||
rootElement.appendChild(jsElem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function main() {
|
|
||||||
// display the assignment
|
|
||||||
var codingTitle = document.getElementById("coding-title");
|
|
||||||
codingTitle.innerHTML = quizData.title;
|
|
||||||
|
|
||||||
var codingInstructions = document.getElementById("coding-instructions");
|
|
||||||
if (quizData.hasInstructions) {
|
|
||||||
codingInstructions.innerHTML = quizData.instructions;
|
|
||||||
} else {
|
|
||||||
codingInstructions.innerHTML = "<span class=\"italic-text\">" + quizData.instructions
|
|
||||||
+ "</span>";
|
|
||||||
}
|
|
||||||
|
|
||||||
// display the test(s)
|
|
||||||
var codingTests = document.getElementById("coding-tests");
|
|
||||||
if (!quizData.hasTests) {
|
|
||||||
codingTests.innerHTML = "<span class=\"italic-text\">" + quizData.tests + "</span>";
|
|
||||||
} else {
|
|
||||||
renderCodeList(codingTests, quizData.tests, "coding-test", "Test");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// display the solution(s)
|
|
||||||
var codingSolutions = document.getElementById("coding-solutions");
|
|
||||||
if (!quizData.hasSolutions) {
|
|
||||||
codingSolutions.innerHTML = "<span class=\"italic-text\">" + quizData.solutions + "</span>";
|
|
||||||
} else {
|
|
||||||
renderCodeList(codingSolutions, quizData.solutions, "coding-solution", "Solution");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
24
constants.py
24
constants.py
@ -12,24 +12,32 @@ HEADERS = {
|
|||||||
LOGIN_URL = "https://www.udemy.com/join/login-popup/?ref=&display_type=popup&loc"
|
LOGIN_URL = "https://www.udemy.com/join/login-popup/?ref=&display_type=popup&loc"
|
||||||
LOGOUT_URL = "https://www.udemy.com/user/logout"
|
LOGOUT_URL = "https://www.udemy.com/user/logout"
|
||||||
# COURSE_URL = "https://{portal_name}.udemy.com/api-2.0/courses/{course_id}/cached-subscriber-curriculum-items?fields[asset]=results,title,external_url,time_estimation,download_urls,slide_urls,filename,asset_type,captions,media_license_token,course_is_drmed,media_sources,stream_urls,body&fields[chapter]=object_index,title,sort_order&fields[lecture]=id,title,object_index,asset,supplementary_assets,view_html&page_size=10000"
|
# COURSE_URL = "https://{portal_name}.udemy.com/api-2.0/courses/{course_id}/cached-subscriber-curriculum-items?fields[asset]=results,title,external_url,time_estimation,download_urls,slide_urls,filename,asset_type,captions,media_license_token,course_is_drmed,media_sources,stream_urls,body&fields[chapter]=object_index,title,sort_order&fields[lecture]=id,title,object_index,asset,supplementary_assets,view_html&page_size=10000"
|
||||||
COURSE_URL = "https://{portal_name}.udemy.com/api-2.0/courses/{course_id}/subscriber-curriculum-items/?page_size=100&fields[asset]=asset_type,length,media_license_token,course_is_drmed,media_sources,thumbnail_sprite,slides,slide_urls,filename,download_urls,external_url,stream_urls&fields[chapter]=object_index,title&fields[lecture]=id,title,object_index,asset,supplementary_assets,view_html&caching_intent=True"
|
CURRICULUM_ITEMS_URL = "https://{portal_name}.udemy.com/api-2.0/courses/{course_id}/subscriber-curriculum-items/"
|
||||||
COURSE_INFO_URL = "https://{portal_name}.udemy.com/api-2.0/courses/{course_id}/"
|
COURSE_URL = "https://{portal_name}.udemy.com/api-2.0/courses/{course_id}/"
|
||||||
COURSE_SEARCH = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses?fields[course]=id,url,title,published_title&page=1&page_size=500&search={course_name}"
|
COURSE_SEARCH = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses?fields[course]=id,url,title,published_title&page=1&page_size=500&search={course_name}"
|
||||||
SUBSCRIBED_COURSES = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses/?ordering=-last_accessed&fields[course]=id,title,url&page=1&page_size=12"
|
SUBSCRIBED_COURSES = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses/?ordering=-last_accessed&fields[course]=id,title,url&page=1&page_size=12"
|
||||||
MY_COURSES_URL = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses?fields[course]=id,url,title,published_title&ordering=-last_accessed,-access_time&page=1&page_size=10000"
|
MY_COURSES_URL = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses?fields[course]=id,url,title,published_title&ordering=-last_accessed,-access_time&page=1&page_size=10000"
|
||||||
COLLECTION_URL = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses-collections/?collection_has_courses=True&course_limit=20&fields[course]=last_accessed_time,title,published_title&fields[user_has_subscribed_courses_collection]=@all&page=1&page_size=1000"
|
COLLECTION_URL = "https://{portal_name}.udemy.com/api-2.0/users/me/subscribed-courses-collections/?collection_has_courses=True&course_limit=20&fields[course]=last_accessed_time,title,published_title&fields[user_has_subscribed_courses_collection]=@all&page=1&page_size=1000"
|
||||||
QUIZ_URL = "https://{portal_name}.udemy.com/api-2.0/quizzes/{quiz_id}/assessments/?version=1&page_size=250&fields[assessment]=id,assessment_type,prompt,correct_response,section,question_plain,related_lectures"
|
QUIZ_URL = "https://{portal_name}.udemy.com/api-2.0/quizzes/{quiz_id}/assessments/?version=1&page_size=250&fields[assessment]=id,assessment_type,prompt,correct_response,section,question_plain,related_lectures"
|
||||||
|
|
||||||
|
CURRICULUM_ITEMS_PARAMS = {
|
||||||
|
"fields[lecture]": "title,object_index,created,asset,supplementary_assets,description,download_url",
|
||||||
|
"fields[quiz]": "title,object_index,type",
|
||||||
|
"fields[practice]": "title,object_index",
|
||||||
|
"fields[chapter]": "title,object_index",
|
||||||
|
"fields[asset]": "title,filename,asset_type,status,is_external,media_license_token,course_is_drmed,media_sources,captions,slides,slide_urls,download_urls,external_url,@min,status,delayed_asset_message,processing_errors,body",
|
||||||
|
"caching_intent": True,
|
||||||
|
"page_size": "200",
|
||||||
|
}
|
||||||
|
|
||||||
|
COURSE_URL_PARAMS = {"fields[course]": "title", "use_remote_version": True, "caching_intent": True}
|
||||||
|
|
||||||
HOME_DIR = os.getcwd()
|
HOME_DIR = os.getcwd()
|
||||||
SAVED_DIR = os.path.join(os.getcwd(), "saved")
|
SAVED_DIR = os.path.join(os.getcwd(), "saved")
|
||||||
KEY_FILE_PATH = os.path.join(os.getcwd(), "keyfile.json")
|
KEY_FILE_PATH = os.path.join(os.getcwd(), "keyfile.json")
|
||||||
COOKIE_FILE_PATH = os.path.join(os.getcwd(), "cookies.txt")
|
COOKIE_FILE_PATH = os.path.join(os.getcwd(), "cookies.txt")
|
||||||
LOG_DIR_PATH = os.path.join(os.getcwd(), "logs")
|
LOG_DIR_PATH = os.path.join(os.getcwd(), "logs")
|
||||||
LOG_FILE_PATH = os.path.join(
|
LOG_FILE_PATH = os.path.join(os.getcwd(), "logs", f"{time.strftime('%Y-%m-%d-%I-%M-%S')}.log")
|
||||||
os.getcwd(), "logs", f"{time.strftime('%Y-%m-%d-%I-%M-%S')}.log"
|
LOG_FORMAT = "[%(asctime)s] [%(name)s] [%(funcName)s:%(lineno)d] %(levelname)s: %(message)s"
|
||||||
)
|
|
||||||
LOG_FORMAT = (
|
|
||||||
"[%(asctime)s] [%(name)s] [%(funcName)s:%(lineno)d] %(levelname)s: %(message)s"
|
|
||||||
)
|
|
||||||
LOG_DATE_FORMAT = "%I:%M:%S"
|
LOG_DATE_FORMAT = "%I:%M:%S"
|
||||||
LOG_LEVEL = logging.INFO
|
LOG_LEVEL = logging.INFO
|
||||||
|
77
main.py
77
main.py
@ -1,6 +1,5 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
import argparse
|
import argparse
|
||||||
import glob
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import math
|
import math
|
||||||
@ -481,6 +480,14 @@ class Udemy:
|
|||||||
)
|
)
|
||||||
return _temp
|
return _temp
|
||||||
|
|
||||||
|
def _extract_article(self, asset, id):
|
||||||
|
return [{
|
||||||
|
"type": "article",
|
||||||
|
"body": asset.get("body"),
|
||||||
|
"extension": "html",
|
||||||
|
"id": id,
|
||||||
|
}]
|
||||||
|
|
||||||
def _extract_ppt(self, asset, lecture_counter):
|
def _extract_ppt(self, asset, lecture_counter):
|
||||||
_temp = []
|
_temp = []
|
||||||
download_urls = asset.get("download_urls")
|
download_urls = asset.get("download_urls")
|
||||||
@ -813,7 +820,7 @@ class Udemy:
|
|||||||
|
|
||||||
def _extract_course_info_json(self, url, course_id):
|
def _extract_course_info_json(self, url, course_id):
|
||||||
self.session._headers.update({"Referer": url})
|
self.session._headers.update({"Referer": url})
|
||||||
url = COURSE_INFO_URL.format(portal_name=portal_name, course_id=course_id)
|
url = COURSE_URL.format(portal_name=portal_name, course_id=course_id)
|
||||||
try:
|
try:
|
||||||
resp = self.session._get(url).json()
|
resp = self.session._get(url).json()
|
||||||
except conn_error as error:
|
except conn_error as error:
|
||||||
@ -823,12 +830,12 @@ class Udemy:
|
|||||||
else:
|
else:
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
def _extract_course_json(self, url, course_id, portal_name):
|
def _extract_course_curriculum(self, url, course_id, portal_name):
|
||||||
self.session._headers.update({"Referer": url})
|
self.session._headers.update({"Referer": url})
|
||||||
url = COURSE_URL.format(portal_name=portal_name, course_id=course_id)
|
url = CURRICULUM_ITEMS_URL.format(portal_name=portal_name, course_id=course_id)
|
||||||
page = 1
|
page = 1
|
||||||
try:
|
try:
|
||||||
data = self.session._get(url).json()
|
data = self.session._get(url, CURRICULUM_ITEMS_PARAMS).json()
|
||||||
except conn_error as error:
|
except conn_error as error:
|
||||||
logger.fatal(f"Connection error: {error}")
|
logger.fatal(f"Connection error: {error}")
|
||||||
time.sleep(0.8)
|
time.sleep(0.8)
|
||||||
@ -838,7 +845,7 @@ class Udemy:
|
|||||||
_count = data.get("count")
|
_count = data.get("count")
|
||||||
est_page_count = math.ceil(_count / 100) # 100 is the max results per page
|
est_page_count = math.ceil(_count / 100) # 100 is the max results per page
|
||||||
while _next:
|
while _next:
|
||||||
logger.info(f"> Downloading course information.. (Page {page + 1}/{est_page_count})")
|
logger.info(f"> Downloading course curriculum.. (Page {page + 1}/{est_page_count})")
|
||||||
try:
|
try:
|
||||||
resp = self.session._get(_next)
|
resp = self.session._get(_next)
|
||||||
if not resp.ok:
|
if not resp.ok:
|
||||||
@ -987,19 +994,18 @@ class Udemy:
|
|||||||
if isinstance(asset, dict):
|
if isinstance(asset, dict):
|
||||||
asset_type = asset.get("asset_type").lower() or asset.get("assetType").lower()
|
asset_type = asset.get("asset_type").lower() or asset.get("assetType").lower()
|
||||||
if asset_type == "article":
|
if asset_type == "article":
|
||||||
if isinstance(supp_assets, list) and len(supp_assets) > 0:
|
retVal.extend(self._extract_article(asset, index))
|
||||||
retVal = self._extract_supplementary_assets(supp_assets, index)
|
|
||||||
elif asset_type == "video":
|
elif asset_type == "video":
|
||||||
if isinstance(supp_assets, list) and len(supp_assets) > 0:
|
if isinstance(supp_assets, list) and len(supp_assets) > 0:
|
||||||
retVal = self._extract_supplementary_assets(supp_assets, index)
|
retVal.extend(self._extract_supplementary_assets(supp_assets, index))
|
||||||
elif asset_type == "e-book":
|
elif asset_type == "e-book":
|
||||||
retVal = self._extract_ebook(asset, index)
|
retVal.extend(self._extract_ebook(asset, index))
|
||||||
elif asset_type == "file":
|
elif asset_type == "file":
|
||||||
retVal = self._extract_file(asset, index)
|
retVal.extend(self._extract_file(asset, index))
|
||||||
elif asset_type == "presentation":
|
elif asset_type == "presentation":
|
||||||
retVal = self._extract_ppt(asset, index)
|
retVal.extend(self._extract_ppt(asset, index))
|
||||||
elif asset_type == "audio":
|
elif asset_type == "audio":
|
||||||
retVal = self._extract_audio(asset, index)
|
retVal.extend(self._extract_audio(asset, index))
|
||||||
else:
|
else:
|
||||||
logger.warning(f"Unknown asset type: {asset_type}")
|
logger.warning(f"Unknown asset type: {asset_type}")
|
||||||
|
|
||||||
@ -1108,9 +1114,9 @@ class Session(object):
|
|||||||
self._headers["Authorization"] = "Bearer {}".format(bearer_token)
|
self._headers["Authorization"] = "Bearer {}".format(bearer_token)
|
||||||
self._headers["X-Udemy-Authorization"] = "Bearer {}".format(bearer_token)
|
self._headers["X-Udemy-Authorization"] = "Bearer {}".format(bearer_token)
|
||||||
|
|
||||||
def _get(self, url):
|
def _get(self, url, params = None):
|
||||||
for i in range(10):
|
for i in range(10):
|
||||||
session = self._session.get(url, headers=self._headers, cookies=cj)
|
session = self._session.get(url, headers=self._headers, cookies=cj, params=params)
|
||||||
if session.ok or session.status_code in [502, 503]:
|
if session.ok or session.status_code in [502, 503]:
|
||||||
return session
|
return session
|
||||||
if not session.ok:
|
if not session.ok:
|
||||||
@ -1550,7 +1556,7 @@ def process_normal_quiz(quiz, lecture, chapter_dir):
|
|||||||
lecture_path = os.path.join(chapter_dir, lecture_file_name)
|
lecture_path = os.path.join(chapter_dir, lecture_file_name)
|
||||||
|
|
||||||
logger.info(f" > Processing quiz {lecture_index}")
|
logger.info(f" > Processing quiz {lecture_index}")
|
||||||
with open("quiz_template.html", "r") as f:
|
with open("./templates/quiz_template.html", "r") as f:
|
||||||
html = f.read()
|
html = f.read()
|
||||||
quiz_data = {
|
quiz_data = {
|
||||||
"quiz_id": lecture["data"].get("id"),
|
"quiz_id": lecture["data"].get("id"),
|
||||||
@ -1572,7 +1578,7 @@ def process_coding_assignment(quiz, lecture, chapter_dir):
|
|||||||
|
|
||||||
logger.info(f" > Processing quiz {lecture_index} (coding assignment)")
|
logger.info(f" > Processing quiz {lecture_index} (coding assignment)")
|
||||||
|
|
||||||
with open("coding_assignment_template.html", "r") as f:
|
with open("./templates/coding_assignment_template.html", "r") as f:
|
||||||
html = f.read()
|
html = f.read()
|
||||||
quiz_data = {
|
quiz_data = {
|
||||||
"title": lecture_title,
|
"title": lecture_title,
|
||||||
@ -1648,7 +1654,6 @@ def parse_new(udemy: Udemy, udemy_object: dict):
|
|||||||
try:
|
try:
|
||||||
with open(lecture_path, encoding="utf8", mode="w") as f:
|
with open(lecture_path, encoding="utf8", mode="w") as f:
|
||||||
f.write(html_content)
|
f.write(html_content)
|
||||||
f.close()
|
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception(" > Failed to write html file")
|
logger.exception(" > Failed to write html file")
|
||||||
else:
|
else:
|
||||||
@ -1673,20 +1678,19 @@ def parse_new(udemy: Udemy, udemy_object: dict):
|
|||||||
download_url = asset.get("download_url")
|
download_url = asset.get("download_url")
|
||||||
|
|
||||||
if asset_type == "article":
|
if asset_type == "article":
|
||||||
logger.warning(
|
body = asset.get("body")
|
||||||
"If you're seeing this message, that means that you reached a secret area that I haven't finished! jk I haven't implemented handling for this asset type, please report this at https://github.com/Puyodead1/udemy-downloader/issues so I can add it. When reporting, please provide the following information: "
|
lecture_path = os.path.join(
|
||||||
)
|
chapter_dir, "{}.html".format(sanitize_filename(lecture_title)))
|
||||||
logger.warning("AssetType: Article; AssetData: ", asset)
|
try:
|
||||||
# html_content = lecture.get("html_content")
|
with open("./templates/article_template.html", "r") as f:
|
||||||
# lecture_path = os.path.join(
|
content = f.read()
|
||||||
# chapter_dir, "{}.html".format(sanitize(lecture_title)))
|
content = content.replace("__title_placeholder__", lecture_title)
|
||||||
# try:
|
content = content.replace("__data_placeholder__", body)
|
||||||
# with open(lecture_path, 'w') as f:
|
with open(lecture_path, encoding="utf8", mode="w") as f:
|
||||||
# f.write(html_content)
|
f.write(content)
|
||||||
# f.close()
|
except Exception as e:
|
||||||
# except Exception as e:
|
print("Failed to write html file: ", e)
|
||||||
# print("Failed to write html file: ", e)
|
continue
|
||||||
# continue
|
|
||||||
elif asset_type == "video":
|
elif asset_type == "video":
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"If you're seeing this message, that means that you reached a secret area that I haven't finished! jk I haven't implemented handling for this asset type, please report this at https://github.com/Puyodead1/udemy-downloader/issues so I can add it. When reporting, please provide the following information: "
|
"If you're seeing this message, that means that you reached a secret area that I haven't finished! jk I haven't implemented handling for this asset type, please report this at https://github.com/Puyodead1/udemy-downloader/issues so I can add it. When reporting, please provide the following information: "
|
||||||
@ -1727,7 +1731,6 @@ def parse_new(udemy: Udemy, udemy_object: dict):
|
|||||||
if name.lower() not in file_data:
|
if name.lower() not in file_data:
|
||||||
with open(filename, "a", encoding="utf-8", errors="ignore") as f:
|
with open(filename, "a", encoding="utf-8", errors="ignore") as f:
|
||||||
f.write(content)
|
f.write(content)
|
||||||
f.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _print_course_info(udemy: Udemy, udemy_object: dict):
|
def _print_course_info(udemy: Udemy, udemy_object: dict):
|
||||||
@ -1843,7 +1846,7 @@ def main():
|
|||||||
title = sanitize_filename(course_info.get("title"))
|
title = sanitize_filename(course_info.get("title"))
|
||||||
course_title = course_info.get("published_title")
|
course_title = course_info.get("published_title")
|
||||||
|
|
||||||
logger.info("> Fetching course content, this may take a minute...")
|
logger.info("> Fetching course curriculum, this may take a minute...")
|
||||||
if load_from_file:
|
if load_from_file:
|
||||||
course_json = json.loads(
|
course_json = json.loads(
|
||||||
open(os.path.join(os.getcwd(), "saved", "course_content.json"), encoding="utf8", mode="r").read()
|
open(os.path.join(os.getcwd(), "saved", "course_content.json"), encoding="utf8", mode="r").read()
|
||||||
@ -1852,15 +1855,14 @@ def main():
|
|||||||
course_title = course_json.get("published_title")
|
course_title = course_json.get("published_title")
|
||||||
portal_name = course_json.get("portal_name")
|
portal_name = course_json.get("portal_name")
|
||||||
else:
|
else:
|
||||||
course_json = udemy._extract_course_json(course_url, course_id, portal_name)
|
course_json = udemy._extract_course_curriculum(course_url, course_id, portal_name)
|
||||||
course_json["portal_name"] = portal_name
|
course_json["portal_name"] = portal_name
|
||||||
|
|
||||||
if save_to_file:
|
if save_to_file:
|
||||||
with open(os.path.join(os.getcwd(), "saved", "course_content.json"), encoding="utf8", mode="w") as f:
|
with open(os.path.join(os.getcwd(), "saved", "course_content.json"), encoding="utf8", mode="w") as f:
|
||||||
f.write(json.dumps(course_json))
|
f.write(json.dumps(course_json))
|
||||||
f.close()
|
|
||||||
|
|
||||||
logger.info("> Course content retrieved!")
|
logger.info("> Course curriculum retrieved!")
|
||||||
course = course_json.get("results")
|
course = course_json.get("results")
|
||||||
resource = course_json.get("detail")
|
resource = course_json.get("detail")
|
||||||
|
|
||||||
@ -1999,7 +2001,6 @@ def main():
|
|||||||
udemy_object.pop("bearer_token")
|
udemy_object.pop("bearer_token")
|
||||||
udemy_object["portal_name"] = portal_name
|
udemy_object["portal_name"] = portal_name
|
||||||
f.write(json.dumps(udemy_object))
|
f.write(json.dumps(udemy_object))
|
||||||
f.close()
|
|
||||||
logger.info("> Saved parsed data to json")
|
logger.info("> Saved parsed data to json")
|
||||||
|
|
||||||
if info:
|
if info:
|
||||||
|
@ -1,515 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
|
||||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
||||||
<title> Quiz </title>
|
|
||||||
<style>
|
|
||||||
* {
|
|
||||||
font-family: system-ui, -apple-system, BlinkMacSystemFont,
|
|
||||||
"Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans",
|
|
||||||
"Helvetica Neue", sans-serif;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
box-sizing: border-box;
|
|
||||||
font-size: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
main {
|
|
||||||
padding-top: 48px;
|
|
||||||
}
|
|
||||||
|
|
||||||
:root {
|
|
||||||
--large-device-width: 850px;
|
|
||||||
--primary-color: #0f172a;
|
|
||||||
--secondary-color: #020617;
|
|
||||||
--primary-text-color: #c7d1dd;
|
|
||||||
--secondary-text-color: #061602;
|
|
||||||
--success-background: hsl(159, 82%, 24%);
|
|
||||||
--success-foreground: hsl(164, 86%, 16%);
|
|
||||||
--success: hsl(160, 84%, 39%);
|
|
||||||
--danger: #ef4444;
|
|
||||||
--warning: #f59e0b;
|
|
||||||
--info-background: hsl(218, 81%, 8%);
|
|
||||||
--info-foreground: hsl(217, 91%, 85%);
|
|
||||||
--border-color: #d1d7dc;
|
|
||||||
--check-box-size: 20px;
|
|
||||||
/* control the size */
|
|
||||||
--check-box-color: var(--info-foreground);
|
|
||||||
/* the active color */
|
|
||||||
}
|
|
||||||
|
|
||||||
body {
|
|
||||||
position: relative;
|
|
||||||
background-color: #020617;
|
|
||||||
color: var(--primary-text-color);
|
|
||||||
}
|
|
||||||
|
|
||||||
#score-stats-container {
|
|
||||||
position: fixed;
|
|
||||||
z-index: 10;
|
|
||||||
top: 0;
|
|
||||||
height: 40px;
|
|
||||||
width: 100%;
|
|
||||||
background-color: var(--info-background);
|
|
||||||
|
|
||||||
padding: 0px 16px;
|
|
||||||
color: var(--info-foreground);
|
|
||||||
font-weight: 600;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
}
|
|
||||||
|
|
||||||
#quiz-container {
|
|
||||||
border-radius: 8px;
|
|
||||||
display: flex;
|
|
||||||
gap: 16px;
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
|
|
||||||
input[type="radio"] {
|
|
||||||
height: var(--check-box-size);
|
|
||||||
aspect-ratio: 1;
|
|
||||||
border: calc(var(--check-box-size) / 8) solid #939393;
|
|
||||||
padding: calc(var(--check-box-size) / 8);
|
|
||||||
background: radial-gradient(farthest-side,
|
|
||||||
var(--check-box-color) 94%,
|
|
||||||
#0000) 50%/0 0 no-repeat content-box;
|
|
||||||
border-radius: 50%;
|
|
||||||
outline-offset: calc(var(--check-box-size) / 10);
|
|
||||||
-webkit-appearance: none;
|
|
||||||
-moz-appearance: none;
|
|
||||||
appearance: none;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: inherit;
|
|
||||||
transition: 0.3s;
|
|
||||||
}
|
|
||||||
|
|
||||||
input[type="radio"]:checked {
|
|
||||||
border-color: var(--check-box-color);
|
|
||||||
background-size: 100% 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
input[type="radio"]:disabled {
|
|
||||||
background: linear-gradient(#939393 0 0) 50%/100% 20% no-repeat content-box;
|
|
||||||
opacity: 0.5;
|
|
||||||
cursor: not-allowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
label {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 10px;
|
|
||||||
cursor: pointer;
|
|
||||||
padding: 4px 6px;
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 767px) {
|
|
||||||
|
|
||||||
input[type="radio"],
|
|
||||||
label {
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
|
|
||||||
#quiz-container {
|
|
||||||
margin-left: 8px;
|
|
||||||
margin-right: 8px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* PC (Desktop devices) */
|
|
||||||
@media (min-width: 768px) {
|
|
||||||
body {
|
|
||||||
display: flex;
|
|
||||||
justify-content: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
main {
|
|
||||||
max-width: var(--large-device-width);
|
|
||||||
}
|
|
||||||
|
|
||||||
#score-stats-container {
|
|
||||||
max-width: var(--large-device-width);
|
|
||||||
}
|
|
||||||
|
|
||||||
dialog {
|
|
||||||
max-width: var(--large-device-width);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media print {
|
|
||||||
input[type="radio"] {
|
|
||||||
background: none !important;
|
|
||||||
border-color: #939393 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
input[type="radio"]:checked {
|
|
||||||
border-color: #939393 !important;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.question-lable {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
button {
|
|
||||||
-webkit-tap-highlight-color: transparent;
|
|
||||||
-webkit-touch-callout: none;
|
|
||||||
-webkit-user-select: none;
|
|
||||||
user-select: none;
|
|
||||||
outline: none;
|
|
||||||
position: relative;
|
|
||||||
overflow: hidden;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.button {
|
|
||||||
background-color: var(--success-background);
|
|
||||||
border: none;
|
|
||||||
color: #f4f5f7;
|
|
||||||
opacity: 0.8;
|
|
||||||
font-size: 18px;
|
|
||||||
flex-grow: 1;
|
|
||||||
padding: 8px 16px;
|
|
||||||
border-radius: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.button:hover {
|
|
||||||
opacity: 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.explanation-btn {
|
|
||||||
border: none;
|
|
||||||
color: var(--success);
|
|
||||||
background-color: transparent;
|
|
||||||
}
|
|
||||||
|
|
||||||
#submit-button:active::after {
|
|
||||||
background-color: #ef4444;
|
|
||||||
}
|
|
||||||
|
|
||||||
.single-question-container {
|
|
||||||
background-color: var(--primary-color);
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 8px;
|
|
||||||
padding: 16px;
|
|
||||||
border-radius: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
#modal-content {
|
|
||||||
padding: 16px;
|
|
||||||
line-height: 24px;
|
|
||||||
}
|
|
||||||
|
|
||||||
dialog::backdrop {
|
|
||||||
background: rgba(0, 0, 0, 0.5);
|
|
||||||
}
|
|
||||||
|
|
||||||
dialog {
|
|
||||||
position: fixed;
|
|
||||||
border: 1px solid var(--border-color);
|
|
||||||
background-color: var(--primary-color);
|
|
||||||
color: rgb(240, 241, 248);
|
|
||||||
padding: 16px;
|
|
||||||
border-radius: 8px;
|
|
||||||
width: 80vw;
|
|
||||||
max-height: 80vh;
|
|
||||||
overflow: auto;
|
|
||||||
top: 50%;
|
|
||||||
left: 50%;
|
|
||||||
-webkit-transform: translateX(-50%) translateY(-50%);
|
|
||||||
-moz-transform: translateX(-50%) translateY(-50%);
|
|
||||||
-ms-transform: translateX(-50%) translateY(-50%);
|
|
||||||
transform: translateX(-50%) translateY(-50%);
|
|
||||||
}
|
|
||||||
|
|
||||||
#close-modal-btn {
|
|
||||||
position: absolute;
|
|
||||||
top: 4px;
|
|
||||||
right: 4px;
|
|
||||||
padding: 2px 8px;
|
|
||||||
border-radius: 2px;
|
|
||||||
border: none;
|
|
||||||
background-color: var(--danger);
|
|
||||||
}
|
|
||||||
|
|
||||||
.correct-answer label {
|
|
||||||
border: 2px solid var(--success);
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.incorrect-answer label {
|
|
||||||
border: 2px solid var(--danger);
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.options-container {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
#quiz-meta-container {
|
|
||||||
border-radius: 8px;
|
|
||||||
background-color: var(--primary-color);
|
|
||||||
margin-bottom: 12px;
|
|
||||||
padding: 8px;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
#quiz-title {
|
|
||||||
text-align: center;
|
|
||||||
font-size: 24px;
|
|
||||||
margin-bottom: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
#quiz-description {
|
|
||||||
line-height: 1.5;
|
|
||||||
padding: 2px 6px;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body onload="main()">
|
|
||||||
<main>
|
|
||||||
<section id="quiz-meta-container">
|
|
||||||
<h1 id="quiz-title"></h1>
|
|
||||||
<p id="quiz-description"></p>
|
|
||||||
</section>
|
|
||||||
<section id="score-stats-container">
|
|
||||||
<div id="score-card">
|
|
||||||
Score: <span id="current-score">999</span> of
|
|
||||||
<span id="pass-percent">999%</span>
|
|
||||||
</div>
|
|
||||||
<div>Correct: <span id="correct-answers">999</span></div>
|
|
||||||
<div>Incorrect: <span id="wrong-answers">999</span></div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section id="quiz-container"></section>
|
|
||||||
|
|
||||||
<dialog id="modal" class="modal-container">
|
|
||||||
<div id="modal-content">
|
|
||||||
<p id="modal-text"></p>
|
|
||||||
</div>
|
|
||||||
</dialog>
|
|
||||||
</main>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
const quizData = __data_placeholder__;
|
|
||||||
let correct = new Set();
|
|
||||||
let incorrect = new Set();
|
|
||||||
let totalNumberOfQuestions = 0;
|
|
||||||
const quizTitle = quizData.quiz_title;
|
|
||||||
const quizDescription = quizData.quiz_description;
|
|
||||||
const questionData = quizData.questions;
|
|
||||||
const passPercent = quizData.pass_percent;
|
|
||||||
const modalTextElement = document.getElementById("modal-text");
|
|
||||||
const quizContainerElement =
|
|
||||||
document.getElementById("quiz-container");
|
|
||||||
|
|
||||||
const dialog = document.querySelector("dialog");
|
|
||||||
const showButton = document.getElementById("view-explanatin");
|
|
||||||
const closeButton = document.getElementById("close-modal-btn");
|
|
||||||
const quizTitleElement = document.getElementById("quiz-title");
|
|
||||||
const quizDescriptionElement =
|
|
||||||
document.getElementById("quiz-description");
|
|
||||||
|
|
||||||
function main() {
|
|
||||||
// update quiz meta data
|
|
||||||
document.title = quizTitle;
|
|
||||||
quizTitleElement.innerHTML = quizTitle;
|
|
||||||
quizDescriptionElement.innerHTML = quizDescription;
|
|
||||||
|
|
||||||
const passPercentElement =
|
|
||||||
document.getElementById("pass-percent");
|
|
||||||
passPercentElement.innerHTML = passPercent + "%";
|
|
||||||
totalNumberOfQuestions = questionData.length;
|
|
||||||
// shuffle the questionData to randomize the order of the questions
|
|
||||||
for (let i = questionData.length - 1; i > 0; i--) {
|
|
||||||
const j = Math.floor(Math.random() * (i + 1));
|
|
||||||
[questionData[i], questionData[j]] = [
|
|
||||||
questionData[j],
|
|
||||||
questionData[i],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
let formattedQuestions = questionData.map(
|
|
||||||
formatSingleQuestionData
|
|
||||||
);
|
|
||||||
updateScore();
|
|
||||||
// display the formattedQuestions
|
|
||||||
formattedQuestions.forEach((question, idx) => {
|
|
||||||
renderSingleQuestion(question, idx + 1);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Formats the question data from the given QuizData object.
|
|
||||||
*
|
|
||||||
* @param {Object} singleQuizData - The singleQuizData object containing prompt and correct_response.
|
|
||||||
* @return {Object} The formatted question object with the following properties:
|
|
||||||
* - id: The ID of the question.
|
|
||||||
* - question: The text of the question.
|
|
||||||
* - answers: The array of answer options.
|
|
||||||
* - correctAnswer: The text of the correct answer.
|
|
||||||
* - explanation: The explanation of the correct answer.
|
|
||||||
*/
|
|
||||||
function formatSingleQuestionData(singleQuizData = null) {
|
|
||||||
const { prompt, correct_response, id } = singleQuizData;
|
|
||||||
const questionText = prompt.question;
|
|
||||||
const answers = prompt.answers;
|
|
||||||
const correctAnswer = correct_response[0];
|
|
||||||
const correctAnswerText =
|
|
||||||
answers[correctAnswer.toLowerCase().charCodeAt(0) - 97];
|
|
||||||
const questionObj = {
|
|
||||||
id: id,
|
|
||||||
question: questionText,
|
|
||||||
answers: answers,
|
|
||||||
correctAnswer: correctAnswerText,
|
|
||||||
explanation: prompt?.explanation || "",
|
|
||||||
};
|
|
||||||
return questionObj;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Renders a single question with its options and submit button.
|
|
||||||
*
|
|
||||||
* @param {Object} singleQuestionData - The data of the question to render.
|
|
||||||
* @param {number} rootIndex - The index of the question in the quiz.
|
|
||||||
* @return {void} return nothing.
|
|
||||||
*/
|
|
||||||
|
|
||||||
const renderSingleQuestion = (
|
|
||||||
singleQuestionData = {},
|
|
||||||
rootIndex = 1
|
|
||||||
) => {
|
|
||||||
const { id, explanation, answers, correctAnswer, question } =
|
|
||||||
singleQuestionData;
|
|
||||||
// shuffle the answers to randomize the order of the answers
|
|
||||||
for (let i = answers.length - 1; i > 0; i--) {
|
|
||||||
const j = Math.floor(Math.random() * (i + 1));
|
|
||||||
[answers[i], answers[j]] = [answers[j], answers[i]];
|
|
||||||
}
|
|
||||||
const optionsHTML = answers
|
|
||||||
.map((option, index) => {
|
|
||||||
const optionId = `${id}_${index}`;
|
|
||||||
|
|
||||||
return `
|
|
||||||
<div class="question-lable">
|
|
||||||
<input type="radio" id="${optionId}" name="${"answer"}" value="${option}" />
|
|
||||||
<label for="${optionId}">${option}</label>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
})
|
|
||||||
|
|
||||||
.join("");
|
|
||||||
|
|
||||||
const container = document.createElement("div");
|
|
||||||
container.innerHTML = `
|
|
||||||
<form data-correct-answer="${correctAnswer}" data-question-id="${id}" class="single-question-container" onsubmit="submitButtonListener(event)">
|
|
||||||
<div style="display: flex;justify-content: space-between;">
|
|
||||||
<p style="font-weight: 600">Question ${rootIndex}:</p>
|
|
||||||
<button type="button" onclick="renderExplanation(event)" id="${`explanation-${id}`}" data-explanation="${explanation}" class="explanation-btn">View Explanation</button>
|
|
||||||
</div>
|
|
||||||
<p style="margin-bottom: 8px;line-height: 1.5">${question}</p>
|
|
||||||
<div class="options-container">
|
|
||||||
${optionsHTML}
|
|
||||||
</div>
|
|
||||||
<div style="display: flex; gap: 8px;">
|
|
||||||
<button type="submit" id="submit-button" class="button">Submit</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
`;
|
|
||||||
quizContainerElement.appendChild(container);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates the score on the page based on the number of correct and incorrect answers.
|
|
||||||
*
|
|
||||||
* @return {void} This function does not return a value.
|
|
||||||
*/
|
|
||||||
function updateScore() {
|
|
||||||
const currentParcentageElement =
|
|
||||||
document.getElementById("current-score");
|
|
||||||
const correctAnswerElement =
|
|
||||||
document.getElementById("correct-answers");
|
|
||||||
const wrongAnswerElement =
|
|
||||||
document.getElementById("wrong-answers");
|
|
||||||
correctAnswerElement.innerHTML = correct.size;
|
|
||||||
wrongAnswerElement.innerHTML = incorrect.size;
|
|
||||||
const score = Number(
|
|
||||||
(correct.size / totalNumberOfQuestions) * 100
|
|
||||||
).toFixed(2);
|
|
||||||
currentParcentageElement.innerHTML = score;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Handles the event when the submit button is clicked.
|
|
||||||
*
|
|
||||||
* @param {Event} e - The event object.
|
|
||||||
* @return {void} This function does not return anything.
|
|
||||||
*/
|
|
||||||
const submitButtonListener = (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
const formData = new FormData(e.target);
|
|
||||||
const form = e.target;
|
|
||||||
const selectedOption = e.target.querySelector(
|
|
||||||
'input[type="radio"]:checked'
|
|
||||||
);
|
|
||||||
if (!selectedOption) {
|
|
||||||
alert("Please select an answer!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let isCorrect = false;
|
|
||||||
const { answer: userAnswer } = Object.fromEntries(
|
|
||||||
formData.entries()
|
|
||||||
);
|
|
||||||
const correctAnswer = e.target.dataset.correctAnswer;
|
|
||||||
const questionId = e.target.dataset.questionId;
|
|
||||||
if (userAnswer == correctAnswer) {
|
|
||||||
correct.add(questionId);
|
|
||||||
incorrect.delete(questionId);
|
|
||||||
isCorrect = true;
|
|
||||||
} else {
|
|
||||||
incorrect.add(e.target.dataset.questionId);
|
|
||||||
correct.delete(questionId);
|
|
||||||
}
|
|
||||||
updateScore();
|
|
||||||
|
|
||||||
const resultClass = isCorrect
|
|
||||||
? "correct-answer"
|
|
||||||
: "incorrect-answer";
|
|
||||||
|
|
||||||
form.querySelectorAll(".question-lable").forEach((label) => {
|
|
||||||
label.classList.remove(
|
|
||||||
"correct-answer",
|
|
||||||
"incorrect-answer"
|
|
||||||
);
|
|
||||||
});
|
|
||||||
selectedOption
|
|
||||||
.closest(".question-lable")
|
|
||||||
.classList.add(resultClass);
|
|
||||||
};
|
|
||||||
|
|
||||||
function renderExplanation(ev) {
|
|
||||||
modalTextElement.innerHTML =
|
|
||||||
ev.target.dataset?.explanation || "no explanation found";
|
|
||||||
dialog.showModal();
|
|
||||||
dialog.addEventListener("click", (event) => {
|
|
||||||
if (event.target === dialog) {
|
|
||||||
dialog.close();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
|
|
||||||
</html>
|
|
66
templates/article_template.html
Normal file
66
templates/article_template.html
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>__title_placeholder__</title>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
font-family: var(--font-stack-text);
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 1.4;
|
||||||
|
font-size: 1.6rem;
|
||||||
|
color: #2d2f31;
|
||||||
|
}
|
||||||
|
.container {
|
||||||
|
position: relative;
|
||||||
|
height: 100%;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
.content {
|
||||||
|
padding: 3.2rem 4.8rem;
|
||||||
|
word-break: break-word;
|
||||||
|
max-width: 69.6rem;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
.heading {
|
||||||
|
margin-bottom: 2.4rem;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, Roboto, "Segoe UI", Helvetica, Arial, sans-serif,
|
||||||
|
"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.2;
|
||||||
|
letter-spacing: 0;
|
||||||
|
font-size: 3.2rem;
|
||||||
|
max-width: 36em;
|
||||||
|
}
|
||||||
|
.article-asset-container {
|
||||||
|
padding: 2.4rem;
|
||||||
|
}
|
||||||
|
code {
|
||||||
|
background-color: #fff;
|
||||||
|
border: 1px solid #d1d7dc;
|
||||||
|
color: #b4690e;
|
||||||
|
font-size: 90%;
|
||||||
|
padding: 0.2rem 0.4rem;
|
||||||
|
font-family: sfmono-regular, Consolas, liberation mono, Menlo, Courier, monospace;
|
||||||
|
}
|
||||||
|
p {
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<div class="content">
|
||||||
|
<div class="heading">__title_placeholder__</div>
|
||||||
|
<div class="article-asset-container">__data_placeholder__</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
122
templates/coding_assignment_template.html
Normal file
122
templates/coding_assignment_template.html
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Coding Assignment</title>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
font-family: sf pro text, -apple-system, BlinkMacSystemFont, Roboto, segoe ui, Helvetica, Arial,
|
||||||
|
sans-serif, apple color emoji, segoe ui emoji, segoe ui symbol;
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 22.4px;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
p,
|
||||||
|
ul,
|
||||||
|
ol {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3,
|
||||||
|
h4,
|
||||||
|
h5,
|
||||||
|
h6 {
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
ul {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
|
.code-snippet {
|
||||||
|
background-color: #fff;
|
||||||
|
border: 1px solid #d1d7dc;
|
||||||
|
color: #b4690e;
|
||||||
|
font-size: 90%;
|
||||||
|
padding: 0.2rem 0.4rem;
|
||||||
|
}
|
||||||
|
.code-block {
|
||||||
|
background-color: #fff;
|
||||||
|
color: #b4690e;
|
||||||
|
font-size: 90%;
|
||||||
|
}
|
||||||
|
.black-block {
|
||||||
|
color: #000000;
|
||||||
|
}
|
||||||
|
.italic-text {
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body onload="main()">
|
||||||
|
<h1 id="coding-title"></h1>
|
||||||
|
<div>
|
||||||
|
<h2>Instructions</h2>
|
||||||
|
<div id="coding-instructions"></div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2>Test(s)</h2>
|
||||||
|
<div id="coding-tests"></div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2>Solution(s)</h2>
|
||||||
|
<div id="coding-solutions"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const quizData = __data_placeholder__;
|
||||||
|
|
||||||
|
function renderCodeList(rootElement, codeList, className, titlePrefix) {
|
||||||
|
for (var i = 0; i < codeList.length; i++) {
|
||||||
|
var elem = codeList[i];
|
||||||
|
var jsElem = document.createElement("div");
|
||||||
|
jsElem.className = className;
|
||||||
|
var jsElemTitle = document.createElement("h3");
|
||||||
|
jsElemTitle.innerHTML = titlePrefix + " " + (i + 1);
|
||||||
|
var jsElemBody = document.createElement("code");
|
||||||
|
jsElemBody.className = "code-block black-block";
|
||||||
|
jsElemBody.innerHTML = "<pre>" + elem.content + "</pre>";
|
||||||
|
jsElem.appendChild(jsElemTitle);
|
||||||
|
jsElem.appendChild(jsElemBody);
|
||||||
|
rootElement.appendChild(jsElem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
// display the assignment
|
||||||
|
var codingTitle = document.getElementById("coding-title");
|
||||||
|
codingTitle.innerHTML = quizData.title;
|
||||||
|
|
||||||
|
var codingInstructions = document.getElementById("coding-instructions");
|
||||||
|
if (quizData.hasInstructions) {
|
||||||
|
codingInstructions.innerHTML = quizData.instructions;
|
||||||
|
} else {
|
||||||
|
codingInstructions.innerHTML = '<span class="italic-text">' + quizData.instructions + "</span>";
|
||||||
|
}
|
||||||
|
|
||||||
|
// display the test(s)
|
||||||
|
var codingTests = document.getElementById("coding-tests");
|
||||||
|
if (!quizData.hasTests) {
|
||||||
|
codingTests.innerHTML = '<span class="italic-text">' + quizData.tests + "</span>";
|
||||||
|
} else {
|
||||||
|
renderCodeList(codingTests, quizData.tests, "coding-test", "Test");
|
||||||
|
}
|
||||||
|
|
||||||
|
// display the solution(s)
|
||||||
|
var codingSolutions = document.getElementById("coding-solutions");
|
||||||
|
if (!quizData.hasSolutions) {
|
||||||
|
codingSolutions.innerHTML = '<span class="italic-text">' + quizData.solutions + "</span>";
|
||||||
|
} else {
|
||||||
|
renderCodeList(codingSolutions, quizData.solutions, "coding-solution", "Solution");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
479
templates/quiz_template.html
Normal file
479
templates/quiz_template.html
Normal file
@ -0,0 +1,479 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Quiz</title>
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell,
|
||||||
|
"Open Sans", "Helvetica Neue", sans-serif;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
padding-top: 48px;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--large-device-width: 850px;
|
||||||
|
--primary-color: #0f172a;
|
||||||
|
--secondary-color: #020617;
|
||||||
|
--primary-text-color: #c7d1dd;
|
||||||
|
--secondary-text-color: #061602;
|
||||||
|
--success-background: hsl(159, 82%, 24%);
|
||||||
|
--success-foreground: hsl(164, 86%, 16%);
|
||||||
|
--success: hsl(160, 84%, 39%);
|
||||||
|
--danger: #ef4444;
|
||||||
|
--warning: #f59e0b;
|
||||||
|
--info-background: hsl(218, 81%, 8%);
|
||||||
|
--info-foreground: hsl(217, 91%, 85%);
|
||||||
|
--border-color: #d1d7dc;
|
||||||
|
--check-box-size: 20px;
|
||||||
|
/* control the size */
|
||||||
|
--check-box-color: var(--info-foreground);
|
||||||
|
/* the active color */
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
position: relative;
|
||||||
|
background-color: #020617;
|
||||||
|
color: var(--primary-text-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
#score-stats-container {
|
||||||
|
position: fixed;
|
||||||
|
z-index: 10;
|
||||||
|
top: 0;
|
||||||
|
height: 40px;
|
||||||
|
width: 100%;
|
||||||
|
background-color: var(--info-background);
|
||||||
|
|
||||||
|
padding: 0px 16px;
|
||||||
|
color: var(--info-foreground);
|
||||||
|
font-weight: 600;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
}
|
||||||
|
|
||||||
|
#quiz-container {
|
||||||
|
border-radius: 8px;
|
||||||
|
display: flex;
|
||||||
|
gap: 16px;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="radio"] {
|
||||||
|
height: var(--check-box-size);
|
||||||
|
aspect-ratio: 1;
|
||||||
|
border: calc(var(--check-box-size) / 8) solid #939393;
|
||||||
|
padding: calc(var(--check-box-size) / 8);
|
||||||
|
background: radial-gradient(farthest-side, var(--check-box-color) 94%, #0000) 50%/0 0 no-repeat
|
||||||
|
content-box;
|
||||||
|
border-radius: 50%;
|
||||||
|
outline-offset: calc(var(--check-box-size) / 10);
|
||||||
|
-webkit-appearance: none;
|
||||||
|
-moz-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: inherit;
|
||||||
|
transition: 0.3s;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="radio"]:checked {
|
||||||
|
border-color: var(--check-box-color);
|
||||||
|
background-size: 100% 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="radio"]:disabled {
|
||||||
|
background: linear-gradient(#939393 0 0) 50%/100% 20% no-repeat content-box;
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 4px 6px;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 767px) {
|
||||||
|
input[type="radio"],
|
||||||
|
label {
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
#quiz-container {
|
||||||
|
margin-left: 8px;
|
||||||
|
margin-right: 8px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* PC (Desktop devices) */
|
||||||
|
@media (min-width: 768px) {
|
||||||
|
body {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
max-width: var(--large-device-width);
|
||||||
|
}
|
||||||
|
|
||||||
|
#score-stats-container {
|
||||||
|
max-width: var(--large-device-width);
|
||||||
|
}
|
||||||
|
|
||||||
|
dialog {
|
||||||
|
max-width: var(--large-device-width);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
input[type="radio"] {
|
||||||
|
background: none !important;
|
||||||
|
border-color: #939393 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="radio"]:checked {
|
||||||
|
border-color: #939393 !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.question-lable {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
-webkit-tap-highlight-color: transparent;
|
||||||
|
-webkit-touch-callout: none;
|
||||||
|
-webkit-user-select: none;
|
||||||
|
user-select: none;
|
||||||
|
outline: none;
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button {
|
||||||
|
background-color: var(--success-background);
|
||||||
|
border: none;
|
||||||
|
color: #f4f5f7;
|
||||||
|
opacity: 0.8;
|
||||||
|
font-size: 18px;
|
||||||
|
flex-grow: 1;
|
||||||
|
padding: 8px 16px;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button:hover {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.explanation-btn {
|
||||||
|
border: none;
|
||||||
|
color: var(--success);
|
||||||
|
background-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
#submit-button:active::after {
|
||||||
|
background-color: #ef4444;
|
||||||
|
}
|
||||||
|
|
||||||
|
.single-question-container {
|
||||||
|
background-color: var(--primary-color);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 16px;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#modal-content {
|
||||||
|
padding: 16px;
|
||||||
|
line-height: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
dialog::backdrop {
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
dialog {
|
||||||
|
position: fixed;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
background-color: var(--primary-color);
|
||||||
|
color: rgb(240, 241, 248);
|
||||||
|
padding: 16px;
|
||||||
|
border-radius: 8px;
|
||||||
|
width: 80vw;
|
||||||
|
max-height: 80vh;
|
||||||
|
overflow: auto;
|
||||||
|
top: 50%;
|
||||||
|
left: 50%;
|
||||||
|
-webkit-transform: translateX(-50%) translateY(-50%);
|
||||||
|
-moz-transform: translateX(-50%) translateY(-50%);
|
||||||
|
-ms-transform: translateX(-50%) translateY(-50%);
|
||||||
|
transform: translateX(-50%) translateY(-50%);
|
||||||
|
}
|
||||||
|
|
||||||
|
#close-modal-btn {
|
||||||
|
position: absolute;
|
||||||
|
top: 4px;
|
||||||
|
right: 4px;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 2px;
|
||||||
|
border: none;
|
||||||
|
background-color: var(--danger);
|
||||||
|
}
|
||||||
|
|
||||||
|
.correct-answer label {
|
||||||
|
border: 2px solid var(--success);
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.incorrect-answer label {
|
||||||
|
border: 2px solid var(--danger);
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.options-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#quiz-meta-container {
|
||||||
|
border-radius: 8px;
|
||||||
|
background-color: var(--primary-color);
|
||||||
|
margin-bottom: 12px;
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#quiz-title {
|
||||||
|
text-align: center;
|
||||||
|
font-size: 24px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#quiz-description {
|
||||||
|
line-height: 1.5;
|
||||||
|
padding: 2px 6px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body onload="main()">
|
||||||
|
<main>
|
||||||
|
<section id="quiz-meta-container">
|
||||||
|
<h1 id="quiz-title"></h1>
|
||||||
|
<p id="quiz-description"></p>
|
||||||
|
</section>
|
||||||
|
<section id="score-stats-container">
|
||||||
|
<div id="score-card">
|
||||||
|
Score: <span id="current-score">999</span> of
|
||||||
|
<span id="pass-percent">999%</span>
|
||||||
|
</div>
|
||||||
|
<div>Correct: <span id="correct-answers">999</span></div>
|
||||||
|
<div>Incorrect: <span id="wrong-answers">999</span></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="quiz-container"></section>
|
||||||
|
|
||||||
|
<dialog id="modal" class="modal-container">
|
||||||
|
<div id="modal-content">
|
||||||
|
<p id="modal-text"></p>
|
||||||
|
</div>
|
||||||
|
</dialog>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const quizData = __data_placeholder__;
|
||||||
|
let correct = new Set();
|
||||||
|
let incorrect = new Set();
|
||||||
|
let totalNumberOfQuestions = 0;
|
||||||
|
const quizTitle = quizData.quiz_title;
|
||||||
|
const quizDescription = quizData.quiz_description;
|
||||||
|
const questionData = quizData.questions;
|
||||||
|
const passPercent = quizData.pass_percent;
|
||||||
|
const modalTextElement = document.getElementById("modal-text");
|
||||||
|
const quizContainerElement = document.getElementById("quiz-container");
|
||||||
|
|
||||||
|
const dialog = document.querySelector("dialog");
|
||||||
|
const showButton = document.getElementById("view-explanatin");
|
||||||
|
const closeButton = document.getElementById("close-modal-btn");
|
||||||
|
const quizTitleElement = document.getElementById("quiz-title");
|
||||||
|
const quizDescriptionElement = document.getElementById("quiz-description");
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
// update quiz meta data
|
||||||
|
document.title = quizTitle;
|
||||||
|
quizTitleElement.innerHTML = quizTitle;
|
||||||
|
quizDescriptionElement.innerHTML = quizDescription;
|
||||||
|
|
||||||
|
const passPercentElement = document.getElementById("pass-percent");
|
||||||
|
passPercentElement.innerHTML = passPercent + "%";
|
||||||
|
totalNumberOfQuestions = questionData.length;
|
||||||
|
// shuffle the questionData to randomize the order of the questions
|
||||||
|
for (let i = questionData.length - 1; i > 0; i--) {
|
||||||
|
const j = Math.floor(Math.random() * (i + 1));
|
||||||
|
[questionData[i], questionData[j]] = [questionData[j], questionData[i]];
|
||||||
|
}
|
||||||
|
|
||||||
|
let formattedQuestions = questionData.map(formatSingleQuestionData);
|
||||||
|
updateScore();
|
||||||
|
// display the formattedQuestions
|
||||||
|
formattedQuestions.forEach((question, idx) => {
|
||||||
|
renderSingleQuestion(question, idx + 1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats the question data from the given QuizData object.
|
||||||
|
*
|
||||||
|
* @param {Object} singleQuizData - The singleQuizData object containing prompt and correct_response.
|
||||||
|
* @return {Object} The formatted question object with the following properties:
|
||||||
|
* - id: The ID of the question.
|
||||||
|
* - question: The text of the question.
|
||||||
|
* - answers: The array of answer options.
|
||||||
|
* - correctAnswer: The text of the correct answer.
|
||||||
|
* - explanation: The explanation of the correct answer.
|
||||||
|
*/
|
||||||
|
function formatSingleQuestionData(singleQuizData = null) {
|
||||||
|
const { prompt, correct_response, id } = singleQuizData;
|
||||||
|
const questionText = prompt.question;
|
||||||
|
const answers = prompt.answers;
|
||||||
|
const correctAnswer = correct_response[0];
|
||||||
|
const correctAnswerText = answers[correctAnswer.toLowerCase().charCodeAt(0) - 97];
|
||||||
|
const questionObj = {
|
||||||
|
id: id,
|
||||||
|
question: questionText,
|
||||||
|
answers: answers,
|
||||||
|
correctAnswer: correctAnswerText,
|
||||||
|
explanation: prompt?.explanation || "",
|
||||||
|
};
|
||||||
|
return questionObj;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders a single question with its options and submit button.
|
||||||
|
*
|
||||||
|
* @param {Object} singleQuestionData - The data of the question to render.
|
||||||
|
* @param {number} rootIndex - The index of the question in the quiz.
|
||||||
|
* @return {void} return nothing.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const renderSingleQuestion = (singleQuestionData = {}, rootIndex = 1) => {
|
||||||
|
const { id, explanation, answers, correctAnswer, question } = singleQuestionData;
|
||||||
|
// shuffle the answers to randomize the order of the answers
|
||||||
|
for (let i = answers.length - 1; i > 0; i--) {
|
||||||
|
const j = Math.floor(Math.random() * (i + 1));
|
||||||
|
[answers[i], answers[j]] = [answers[j], answers[i]];
|
||||||
|
}
|
||||||
|
const optionsHTML = answers
|
||||||
|
.map((option, index) => {
|
||||||
|
const optionId = `${id}_${index}`;
|
||||||
|
|
||||||
|
return `
|
||||||
|
<div class="question-lable">
|
||||||
|
<input type="radio" id="${optionId}" name="${"answer"}" value="${option}" />
|
||||||
|
<label for="${optionId}">${option}</label>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
})
|
||||||
|
|
||||||
|
.join("");
|
||||||
|
|
||||||
|
const container = document.createElement("div");
|
||||||
|
container.innerHTML = `
|
||||||
|
<form data-correct-answer="${correctAnswer}" data-question-id="${id}" class="single-question-container" onsubmit="submitButtonListener(event)">
|
||||||
|
<div style="display: flex;justify-content: space-between;">
|
||||||
|
<p style="font-weight: 600">Question ${rootIndex}:</p>
|
||||||
|
<button type="button" onclick="renderExplanation(event)" id="${`explanation-${id}`}" data-explanation="${explanation}" class="explanation-btn">View Explanation</button>
|
||||||
|
</div>
|
||||||
|
<p style="margin-bottom: 8px;line-height: 1.5">${question}</p>
|
||||||
|
<div class="options-container">
|
||||||
|
${optionsHTML}
|
||||||
|
</div>
|
||||||
|
<div style="display: flex; gap: 8px;">
|
||||||
|
<button type="submit" id="submit-button" class="button">Submit</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
`;
|
||||||
|
quizContainerElement.appendChild(container);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the score on the page based on the number of correct and incorrect answers.
|
||||||
|
*
|
||||||
|
* @return {void} This function does not return a value.
|
||||||
|
*/
|
||||||
|
function updateScore() {
|
||||||
|
const currentParcentageElement = document.getElementById("current-score");
|
||||||
|
const correctAnswerElement = document.getElementById("correct-answers");
|
||||||
|
const wrongAnswerElement = document.getElementById("wrong-answers");
|
||||||
|
correctAnswerElement.innerHTML = correct.size;
|
||||||
|
wrongAnswerElement.innerHTML = incorrect.size;
|
||||||
|
const score = Number((correct.size / totalNumberOfQuestions) * 100).toFixed(2);
|
||||||
|
currentParcentageElement.innerHTML = score;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles the event when the submit button is clicked.
|
||||||
|
*
|
||||||
|
* @param {Event} e - The event object.
|
||||||
|
* @return {void} This function does not return anything.
|
||||||
|
*/
|
||||||
|
const submitButtonListener = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const formData = new FormData(e.target);
|
||||||
|
const form = e.target;
|
||||||
|
const selectedOption = e.target.querySelector('input[type="radio"]:checked');
|
||||||
|
if (!selectedOption) {
|
||||||
|
alert("Please select an answer!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let isCorrect = false;
|
||||||
|
const { answer: userAnswer } = Object.fromEntries(formData.entries());
|
||||||
|
const correctAnswer = e.target.dataset.correctAnswer;
|
||||||
|
const questionId = e.target.dataset.questionId;
|
||||||
|
if (userAnswer == correctAnswer) {
|
||||||
|
correct.add(questionId);
|
||||||
|
incorrect.delete(questionId);
|
||||||
|
isCorrect = true;
|
||||||
|
} else {
|
||||||
|
incorrect.add(e.target.dataset.questionId);
|
||||||
|
correct.delete(questionId);
|
||||||
|
}
|
||||||
|
updateScore();
|
||||||
|
|
||||||
|
const resultClass = isCorrect ? "correct-answer" : "incorrect-answer";
|
||||||
|
|
||||||
|
form.querySelectorAll(".question-lable").forEach((label) => {
|
||||||
|
label.classList.remove("correct-answer", "incorrect-answer");
|
||||||
|
});
|
||||||
|
selectedOption.closest(".question-lable").classList.add(resultClass);
|
||||||
|
};
|
||||||
|
|
||||||
|
function renderExplanation(ev) {
|
||||||
|
modalTextElement.innerHTML = ev.target.dataset?.explanation || "no explanation found";
|
||||||
|
dialog.showModal();
|
||||||
|
dialog.addEventListener("click", (event) => {
|
||||||
|
if (event.target === dialog) {
|
||||||
|
dialog.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
Loading…
x
Reference in New Issue
Block a user