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 15 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
115 changes: 115 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,115 @@
export default 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} newState - the initial state of the challenges which grouped by the level.
* @returns void
*/
init(newState) {
const oldState = this.get();
// initialize the state when there is no state in the local storage.
if (!oldState && !newState) {
throw new Error('initial state is required when there is no state in the local storage.');
}

// check new state and old state whether is undefined or not. and merge the new state to the old state.
const state = this._checkAndMerge(oldState, newState);
this._save(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 (!newState && oldState) {
return oldState;
}

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

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

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(state[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
17 changes: 12 additions & 5 deletions templates/components/challenge_area.html
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@
</div>
</div>

<script type="text/javascript">
<script type="module">
import PassedState from "{{ url_for('static', filename='js/passed-state.js')}}";

100gle marked this conversation as resolved.
Show resolved Hide resolved
let passedState = new PassedState();

/**
* Render the code area with CodeMirror and Jinja2.
*
Expand Down Expand Up @@ -108,6 +112,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,11 +158,11 @@
}

// 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
}

codeUnderTest = {{code_under_test | tojson}};
testCode = {{ test_code | tojson }};
let codeUnderTest = {{code_under_test | tojson}};
let testCode = {{ test_code | tojson }};
renderCodeArea(codeUnderTest, testCode, "{{level}}", "{{name}}");
</script>
36 changes: 34 additions & 2 deletions 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,7 +140,8 @@ <h5 class="challenge-level">{{ level }}</h5>
</nav>
</aside>

<script>
<script type="module">
import PassedState from "{{ url_for('static', filename='js/passed-state.js')}}";
100gle marked this conversation as resolved.
Show resolved Hide resolved
const sidebarTogglers = document.querySelectorAll('.sidebar-toggle');
const drawer = document.querySelector('.drawer');

Expand All @@ -140,10 +157,25 @@ <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.
let state = passedState.get();
Object.keys(state).forEach(level => {
state[level].forEach(challenge => {
let id = `#${level}-${challenge.name}`;
if (challenge.passed) {
document.querySelector(id).parentNode.classList.add('passed');
}
})
})
</script>
Loading