Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Record passed status for challenges #80

Merged
merged 17 commits into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 131 additions & 0 deletions static/js/passed-state.js
100gle marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
class PassedState {
_key = 'python-type-challenges';

/**
* Initializing when there is no state in the local storage. If there is no state in the local storage, the initial state is required.
* this function will check the new state and the old state whether is undefined or not and updated the old state based on new state.
*
* @param {object} initialState - the initial state of the challenges which grouped by the level.
* @returns void
*/
init(initialState) {
const currentState = this.get();
// initialize the state when there is no state in the local storage.
if (!currentState && !initialState) {
throw new Error('initial state is required when there is no state in the local storage.');
}

// add passed property to the challenges in the initial state.
const rawState = this._prepareState(initialState);
100gle marked this conversation as resolved.
Show resolved Hide resolved

// check new state and old state whether is undefined or not. and merge the new state to the old state.
const state = this._checkAndMerge(currentState, rawState);
this._save(state);
}
/**
* prepare the state for initialization.
*
* @param {object} rawState
* @returns state - the state contains the challenge name and whether the challenge is passed.
*/
_prepareState(rawState) {
100gle marked this conversation as resolved.
Show resolved Hide resolved
if (!rawState) {
return {};
}

const state = {};
for (const level in rawState) {
const challenges = [];
for (const challengeName of rawState[level]) {
challenges.push({
name: challengeName,
passed: false
});
}
state[level] = challenges;
}

return state;
}

get() {
const currentState = localStorage.getItem(this._key);
return JSON.parse(currentState);
}

/**
* Save the state to the local storage with JSON format.
* @param {object} state - the state contains the challenge name and whether the challenge is passed.
*/
_save(state) {
localStorage.setItem(this._key, JSON.stringify(state));
}

/**
* Set the target challenge as passed in the state.
*
* @param {'basic' | 'intermediate' | 'advanced' | 'extreme'} level - the level of the challenge.
* @param {string} challengeName - the name of the challenge.
* @returns void
*/
setPassed(level, challengeName) {
let state = this.get();

const challenges = state[level];
laike9m marked this conversation as resolved.
Show resolved Hide resolved
for (const challenge of challenges) {
if (challenge.name === challengeName) {
challenge.passed = true;
break;
}
}

this._save(state);
}

/**
* Merge the new state and the current state.
* this function will compare the new state with the current state and finally overwrite the current state based on the new state:
* - If the old key in the current state isn't in the new state, the old key will be removed from the current state.
* - If the new key in the new state isn't in the current state, the new key will be added to the current state.
*
* @param {object} oldState - the current state stored in the local storage.
* @param {object} newState - the latest state from the server.
* @returns mergedState - the merged state.
*/
_checkAndMerge(oldState, newState) {
laike9m marked this conversation as resolved.
Show resolved Hide resolved
if (!newState && !oldState) {
throw new Error('one of the new state and the old state is required.');
}

if (!oldState && newState) {
return newState;
}

if (!newState && oldState) {
return oldState;
}

let mergedState = {};
const levels = ['basic', 'intermediate', 'advanced', 'extreme'];

for (const level of levels) {
// Initialize an empty array for merged challenges
let mergedChallenges = [];

// Create a map for quick lookup of challenges by name
const oldChallengesMap = new Map(oldState[level].map(challenge => [challenge.name, challenge]));
const newChallengesMap = new Map(newState[level].map(challenge => [challenge.name, challenge]));

// Add or update challenges from the newState
for (const [name, newChallenge] of newChallengesMap.entries()) {
let hasPassed = oldChallengesMap.get(name)?.passed || newChallenge.passed;
mergedChallenges.push({ ...newChallenge, passed: hasPassed });
}

// Set the merged challenges for the current level in the mergedState
mergedState[level] = mergedChallenges;
}

return mergedState;
}
}
3 changes: 3 additions & 0 deletions templates/challenge.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
overflow-y: auto;
padding-left: 8px;
padding-right: 8px;
width: 15vw;
}

.sidebar-container .sidebar-actions {
Expand Down Expand Up @@ -196,6 +197,7 @@
height: 100%;
padding-left: 0px;
margin-right: auto;
width: auto;
}

.sidebar-container .sidebar-actions {
Expand Down Expand Up @@ -232,6 +234,7 @@

.active-challenge {
background-color: var(--primary-focus);
border-radius: 8px;
}

.CodeMirror {
Expand Down
9 changes: 7 additions & 2 deletions templates/components/challenge_area.html
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@
// add confetti effect when passed
if (json.passed) {
confetti.addConfetti()
// passedState is defined in challenge_sidebar.html
passedState.setPassed(level, name);
100gle marked this conversation as resolved.
Show resolved Hide resolved
document.getElementById(`${level}-${name}`).parentNode.classList.add('passed');
}
setTimeout(() => {
document.getElementById('answer-link').style.display = 'block';
Expand Down Expand Up @@ -151,10 +154,12 @@
}

// Make sure the current challenge is visible to user.
activeChallengeInList = document.getElementById(`${level}-${name}`);
activeChallengeInList.classList.add('active-challenge'); // Highlight
let activeChallengeInList = document.getElementById(`${level}-${name}`);
activeChallengeInList.parentNode.classList.add('active-challenge'); // Highlight
}

// Don't add `let` to the following variables which are handled by htmx
// else some errors will be raised.
codeUnderTest = {{code_under_test | tojson}};
testCode = {{ test_code | tojson }};
renderCodeArea(codeUnderTest, testCode, "{{level}}", "{{name}}");
Expand Down
33 changes: 32 additions & 1 deletion templates/components/challenge_sidebar.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@
display: none;
}

.passed {
position: relative;
}

.passed::after {
/* iconify: https://icon-sets.iconify.design/lets-icons/done-ring-round */
content: url('data:image/svg+xml,%3Csvg xmlns="http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg" width="24" height="24" viewBox="0 0 24 24"%3E%3Cg fill="none" stroke="%2366ba6f" stroke-linecap="round" stroke-width="2"%3E%3Cpath d="m9 10l3.258 2.444a1 1 0 0 0 1.353-.142L20 5"%2F%3E%3Cpath d="M21 12a9 9 0 1 1-6.67-8.693"%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E');
display: inline-block;
position: absolute;
width: 24px;
height: 24px;
top: 50%;
right: 0;
transform: translate(-50%, -50%);
transition: all 1.5s ease-out;
}

@media only screen and (max-width: 800px) {
.sidebar-toggle {
Expand Down Expand Up @@ -124,6 +140,7 @@ <h5 class="challenge-level">{{ level }}</h5>
</nav>
</aside>

<script type="text/javascript" src="{{ url_for('static', filename='js/passed-state.js')}}"></script>
<script>
const sidebarTogglers = document.querySelectorAll('.sidebar-toggle');
const drawer = document.querySelector('.drawer');
Expand All @@ -140,10 +157,24 @@ <h5 class="challenge-level">{{ level }}</h5>
* @param {Event} event - The click event.
*/
function removeHighlight(event) {
previousActiveChallenges = document.getElementsByClassName("active-challenge");
let previousActiveChallenges = document.getElementsByClassName("active-challenge");
for (c of previousActiveChallenges) {
// Remove previously highlighted challenge in the list.
c.classList.remove('active-challenge');
}
}

const initialState = {{ challenges_groupby_level | tojson }};
const passedState = new PassedState();
passedState.init(initialState);

// Highlight the passed challenges when the page is loaded.
Object.keys(passedState.get()).forEach(level => {
100gle marked this conversation as resolved.
Show resolved Hide resolved
passedState.get()[level].forEach(challenge => {
let id = `#${level}-${challenge.name}`;
if (challenge.passed) {
document.querySelector(id).parentNode.classList.add('passed');
}
})
})
</script>
Loading