-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
219 lines (189 loc) · 7.93 KB
/
Copy pathindex.html
File metadata and controls
219 lines (189 loc) · 7.93 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python Friendly Error Messages - Demo</title>
<script>
(() => {
const localHosts = new Set(['localhost', '127.0.0.1', '::1']);
const isLocalDevelopment = window.location.protocol === 'file:' || localHosts.has(window.location.hostname);
window.__PFEM_IS_LOCAL_DEVELOPMENT__ = isLocalDevelopment;
if (isLocalDevelopment) {
document.documentElement.classList.add('demo--local-dev');
}
})();
</script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="demo__source-bar" id="source-bar">
<div class="container">
Loading source info...
</div>
</div>
<h1>Python Friendly Error Messages - Demo</h1>
<p class="demo__nav">
<a href="anatomy.html" class="demo__nav-link">Anatomy of a friendly error message →</a>
</p>
<div class="demo__table-page" id="demo-container">
Loading demo...
</div>
<script type="module">
import { examples } from './demo-examples.js';
import { PYODIDE_VERSION } from './pyodide-config.js';
import { runAndCaptureTrace, getVersions } from './run-pyodide.js';
const isLocalDevelopment = Boolean(window.__PFEM_IS_LOCAL_DEVELOPMENT__);
const pageParams = new URLSearchParams(window.location.search);
const useLocal = isLocalDevelopment && pageParams.has('local');
const navigationEntry = performance.getEntriesByType('navigation')[0];
const isReload = navigationEntry && navigationEntry.type === 'reload';
let cacheBust = pageParams.get('cb');
if (isReload) {
cacheBust = String(Date.now());
pageParams.set('cb', cacheBust);
const nextUrl = `${window.location.pathname}?${pageParams.toString()}${window.location.hash}`;
window.history.replaceState(null, '', nextUrl);
}
const libPathBase = useLocal
? '../dist/index.browser.js'
: './vendor/python-friendly-error-messages/index.browser.js';
const libPath = cacheBust ? `${libPathBase}?cb=${encodeURIComponent(cacheBust)}` : libPathBase;
const { friendlyExplain, loadCopydeckFor, cpythonAdapter } = await import(libPath);
async function initDemo() {
const container = document.getElementById('demo-container');
const sourceBar = document.getElementById('source-bar');
if (!isLocalDevelopment) {
sourceBar.remove();
}
if (isLocalDevelopment) {
const switchUrl = useLocal ? 'index.html' : 'index.html?local=true';
const bar = document.querySelector('#source-bar .container');
if (useLocal) {
bar.innerHTML = `
<span class="demo__source-active demo__source-active--local">● local build <code>dist/</code></span>
<a class="demo__source-switch" href="${switchUrl}">switch to vendored release</a>
`;
} else {
bar.innerHTML = `
<span class="demo__source-active demo__source-active--vendor">● vendored release</span>
<a class="demo__source-switch" href="${switchUrl}">switch to local build</a>
`;
}
const switchLink = bar.querySelector('.demo__source-switch');
if (switchLink) {
switchLink.addEventListener('click', (event) => {
event.preventDefault();
const target = new URL(switchLink.getAttribute('href'), window.location.href);
target.searchParams.set('cb', String(Date.now()));
window.location.assign(target.toString());
});
}
}
try {
await loadCopydeckFor('en');
// Errors are generated live by running each snippet through real Pyodide (pinned in pyodide-config.js), so the demo shows exactly what that version of Pyodide / Python produces
const versionNote = document.createElement('p');
versionNote.className = 'demo__runtime-note';
versionNote.textContent = `Loading Pyodide v${PYODIDE_VERSION}…`;
container.before(versionNote);
const versions = await getVersions();
versionNote.innerHTML =
`Errors below are generated live by ` +
`<strong>Pyodide v${escapeHtml(versions.pyodide)}</strong> · ` +
`<strong>Python ${escapeHtml(versions.python)}</strong>`;
const processedExamples = [];
for (const example of examples) {
try {
const trace = await runAndCaptureTrace(example.code);
if (!trace) {
throw new Error('Code ran without raising an error.');
}
const parsedTrace = cpythonAdapter(trace, example.code);
if (!parsedTrace) {
throw new Error('Could not parse the Pyodide trace.');
}
const result = friendlyExplain({ error: parsedTrace, code: example.code });
if (!result) {
throw new Error('No friendly mapping for this error - nothing to show.');
}
processedExamples.push({ example, trace, result, error: null });
} catch (err) {
processedExamples.push({ example, trace: '', result: null, error: err });
}
}
const tableRowsHtml = processedExamples.map(({ example, trace, result, error }, index) => {
const rowId = getRowId(example.title, index);
const explanationCell = error
? `<div class="demo__error demo__error--inline">Error processing: ${escapeHtml(error.message)}</div>`
: result.html;
return `
<tr id="${rowId}">
<td>
<a class="demo__row-link" href="#${rowId}" aria-label="Link to row ${index + 1}">${index + 1}</a>
</td>
<td>${escapeHtml(example.title)}</td>
<td><span class="demo__badge demo__badge--pyodide">pyodide</span></td>
<td><div class="demo__mono">${escapeHtml(example.code)}</div></td>
<td><div class="demo__mono demo__mono--trace">${escapeHtml(trace)}</div></td>
<td><div class="demo__table-explanation">${explanationCell}</div></td>
</tr>
`;
}).join('');
container.innerHTML = `
<section class="demo__table-section demo__table-section--full">
<div class="demo__table-wrap">
<table class="demo__table">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Runtime</th>
<th>Code</th>
<th>Trace</th>
<th>Friendly Explanation</th>
</tr>
</thead>
<tbody>
${tableRowsHtml}
</tbody>
</table>
</div>
</section>
`;
applyHashTarget();
window.addEventListener('hashchange', applyHashTarget);
} catch (err) {
container.innerHTML = `<div class="demo__error">Failed to load demo: ${escapeHtml(err.message)}</div>`;
}
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function getRowId(title, index) {
const slug = title
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
return `example-${index + 1}-${slug}`;
}
function applyHashTarget() {
document.querySelectorAll('.demo__row-target').forEach((el) => {
el.classList.remove('demo__row-target');
});
const hash = window.location.hash;
if (!hash || hash.length <= 1) return;
const targetId = decodeURIComponent(hash.slice(1));
const targetRow = document.getElementById(targetId);
if (!targetRow) return;
targetRow.classList.add('demo__row-target');
requestAnimationFrame(() => {
targetRow.scrollIntoView({ block: 'center', behavior: 'auto' });
});
}
initDemo();
</script>
</body>
</html>