forked from pamelafox/python-code-element
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-exercise.js
More file actions
229 lines (211 loc) · 7.62 KB
/
code-exercise.js
File metadata and controls
229 lines (211 loc) · 7.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import {LitElement, html} from 'lit';
import {ref, createRef} from 'lit/directives/ref.js';
import {basicSetup} from 'codemirror';
import {EditorState} from '@codemirror/state';
import {python} from '@codemirror/lang-python';
import {EditorView, keymap} from '@codemirror/view';
import {indentWithTab} from '@codemirror/commands';
import {indentUnit} from '@codemirror/language';
import {prepareCode, processTestResults, processTestError} from './doctest-grader.js';
import {FiniteWorker} from './finite-worker.js';
import {get, set} from './user-storage.js';
import './loader-element.js';
export class CodeExerciseElement extends LitElement {
static properties = {
starterCode: {type: String},
exerciseName: {type: String, attribute: 'name'},
isLoading: {type: Boolean},
runStatus: {type: String},
testResultsStatus: {type: String},
testResultsHeader: {type: String},
testResultsDetails: {type: String},
runOutput: {type: String},
runStdout: {type: String},
showTests: {type: Boolean, attribute: 'show-tests'},
};
editorRef = createRef();
editor = null;
createRenderRoot() {
return this;
}
connectedCallback() {
super.connectedCallback();
if (!this.starterCode && this.innerHTML.trim()) {
// Unescape the HTML entities in doctest output that get escaped by HTML parser
this.starterCode = this.innerHTML.trim().replace(/>/g, '>').replace(/</g, '<');
// Clear the innerHTML since it will be displayed in the editor
this.innerHTML = '';
}
// Remove the pre style from the editor area
this.style.whiteSpace = 'normal';
this.style.fontFamily = 'inherit';
}
render() {
return html`
<div class="card">
<div class="card-body">
<div ${ref(this.editorRef)} style="width: 100%; margin: 10px 0;"></div>
<div class="d-flex justify-content-between align-items-center mt-3">
<div>
<button
@click=${this.onRunCode}
type="button"
class="btn me-2"
style="background-color: #d1e1f0;"
aria-label="Run code">
▶️ Run Code
</button>
${this.showTests
? html`
<button
@click=${this.onRunTests}
type="button"
class="btn"
style="background-color: #a4d8ae;"
aria-label="Run tests">
🧪 Run Tests
</button>
`
: ''}
<span style="margin-left: 8px">
${this.runStatus && html`<loader-element></loader-element>`} ${this.runStatus}
</span>
</div>
<div>
<button @click=${this.resetCode} type="button" class="btn btn-secondary" title="Reset code to starter code">
Reset
</button>
</div>
</div>
${this.runOutput
? html`
<div class="mt-4">
<h4>Value of final expression</h4>
<div class="mt-2 bg-light rounded p-3">
<pre class="mb-0"><code>${this.runOutput}</code></pre>
</div>
</div>
`
: ''}
${this.runStdout
? html`
<div class="mt-4">
<h4>Standard output (i.e. from print statements)</h4>
<div class="mt-2 bg-light rounded p-3">
<pre class="mb-0"><code>${this.runStdout}</code></pre>
</div>
</div>
`
: ''}
${this.testResultsStatus
? html`
<div class="mt-4">
<h4>Test results (${this.testResultsHeader})</h4>
${this.testResultsStatus === 'pass'
? html` <div class="alert alert-success mt-2" role="alert">🎉 Congratulations, all tests passed!</div> `
: html` <div class="mt-2 bg-light rounded p-3">
<pre class="mb-0"><code>${this.testResultsDetails}</code></pre>
</div>`}
</div>
`
: ''}
</div>
</div>
`;
}
getStorageKey() {
return this.exerciseName ? `${this.exerciseName}-repr` : null;
}
firstUpdated() {
const key = this.getStorageKey();
// Try to get stored code for this exercise
const storedCode = key ? get(key) : null;
if (storedCode) {
console.log(`Loading stored code in localStorage from ${key}`);
} else if (!key) {
console.log('No exercise name provided, code will not be stored');
} else {
console.log(`No stored code found for ${key}, using starter code. Your code changes will be stored in localStorage.`);
}
const state = EditorState.create({
doc: storedCode || this.starterCode || '',
extensions: [
basicSetup,
python(),
keymap.of([indentWithTab]),
indentUnit.of(' '), // Use 4 spaces for indentation
EditorView.lineWrapping,
EditorView.updateListener.of((update) => {
const key = this.getStorageKey();
if (update.docChanged && key) {
// Save code when it changes
set(key, update.state.doc.toString());
}
}),
],
});
this.editor = new EditorView({
state: state,
parent: this.editorRef.value,
});
}
async onRunCode() {
this.runStatus = 'Running code...';
this.testResultsStatus = '';
const code = this.editor.state.doc.toString();
try {
const {results, error, stdout} = await new FiniteWorker(code);
this.runOutput = error?.message || results || '';
this.runStdout = stdout || '';
if (!this.runOutput && !this.runStdout) {
this.runOutput = 'No output from code execution.\n';
if (this.showTests) {
this.runOutput += 'To check if your function code is correct, select "Run Tests" button instead.';
}
}
} catch (e) {
console.warn(`Error in pyodideWorker at ${e.filename}, Line: ${e.lineno}, ${e.message}`);
this.runOutput = `Error: ${e.message}`;
}
this.runStatus = '';
}
async onRunTests() {
this.runStatus = 'Running tests...';
this.runOutput = '';
this.runStdout = '';
const submittedCode = this.editor.state.doc.toString();
let testResults = prepareCode(submittedCode);
if (testResults.code) {
try {
const {results, error, stdout} = await new FiniteWorker(testResults.code);
if (results) {
testResults = processTestResults(results);
} else {
testResults = processTestError(error, testResults.startLine);
}
this.runStdout = stdout || '';
} catch (e) {
console.warn(`Error in pyodideWorker at ${e.filename}, Line: ${e.lineno}, ${e.message}`);
}
}
this.runStatus = '';
this.testResultsStatus = testResults.status;
this.testResultsHeader = testResults.header;
this.testResultsDetails = testResults.details;
}
async resetCode() {
if (confirm('Are you sure you want to reset your code to the starter code? This cannot be undone.')) {
const state = EditorState.create({
doc: this.starterCode || '',
extensions: [basicSetup, python(), EditorView.lineWrapping],
});
this.editor.setState(state);
// Clear stored code if it exists
const key = this.getStorageKey();
if (key) {
set(key, this.starterCode);
}
}
}
}
window.customElements.define('code-exercise-element', CodeExerciseElement);