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 all 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
118 changes: 118 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,118 @@
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];
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) {
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;
}
}

const passedState = new PassedState();
export default passedState;
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
22 changes: 15 additions & 7 deletions templates/components/challenge_area.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@
<div class="codemirror-container">
<div id="editor">
<a id="playground-link" target="_blank" rel="noopener noreferrer">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-4m-8-2l8-8m0 0v5m0-5h-5"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M10 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-4m-8-2l8-8m0 0v5m0-5h-5" />
</svg>
<span>Open Pyright Playground</span>
</a>
</div>
Expand All @@ -48,7 +51,9 @@
</div>
</div>

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

/**
* Render the code area with CodeMirror and Jinja2.
*
Expand Down Expand Up @@ -108,6 +113,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 +159,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>
</script>
37 changes: 35 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,24 @@ <h5 class="challenge-level">{{ level }}</h5>
</nav>
</aside>

<script>
<script type="module">
import passedState from "{{ url_for('static', filename='js/passed-state.js')}}";
const initialState = {{ challenges_groupby_level | tojson }};
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>

<script type="text/javascript">
const sidebarTogglers = document.querySelectorAll('.sidebar-toggle');
const drawer = document.querySelector('.drawer');

Expand All @@ -140,7 +173,7 @@ <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');
Expand Down
Loading