forked from microsoft/pxt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial.ts
More file actions
298 lines (262 loc) · 11.4 KB
/
tutorial.ts
File metadata and controls
298 lines (262 loc) · 11.4 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
namespace pxt.tutorial {
const _h2Regex = /^##[^#](.*)$([\s\S]*?)(?=^##[^#]|$(?![\r\n]))/gmi;
const _h3Regex = /^###[^#](.*)$([\s\S]*?)(?=^###[^#]|$(?![\r\n]))/gmi;
export function parseTutorial(tutorialmd: string): TutorialInfo {
const { metadata, body } = parseTutorialMetadata(tutorialmd);
const { steps, activities } = parseTutorialMarkdown(body, metadata);
const title = parseTutorialTitle(body);
if (!steps)
return undefined; // error parsing steps
// collect code and infer editor
let editor: string = undefined;
const regex = /```(sim|block|blocks|filterblocks|spy|ghost|typescript|ts|js|javascript|template|python)?\s*\n([\s\S]*?)\n```/gmi;
let code = '';
let templateCode: string;
// Concatenate all blocks in separate code blocks and decompile so we can detect what blocks are used (for the toolbox)
body
.replace(/((?!.)\s)+/g, "\n")
.replace(regex, function (m0, m1, m2) {
switch (m1) {
case "block":
case "blocks":
case "filterblocks":
if (!checkTutorialEditor(pxt.BLOCKS_PROJECT_NAME))
return undefined;
break;
case "spy":
case "python":
if (!checkTutorialEditor(pxt.PYTHON_PROJECT_NAME))
return undefined;
if (m1 == "python")
return undefined; // TODO: support for those?
break;
case "typescript":
case "ts":
case "javascript":
case "js":
if (!checkTutorialEditor(pxt.JAVASCRIPT_PROJECT_NAME))
return undefined;
break;
case "template":
templateCode = m2;
break;
}
code += "\n { \n " + m2 + "\n } \n";
return "";
});
if (!metadata.noDiffs && editor != pxt.BLOCKS_PROJECT_NAME)
diffify(steps, activities);
return <pxt.tutorial.TutorialInfo>{
editor: editor || pxt.BLOCKS_PROJECT_NAME,
title: title,
steps: steps,
activities: activities,
code,
templateCode,
metadata
};
function checkTutorialEditor(expected: string) {
if (editor && editor != expected) {
pxt.debug(`tutorial ambiguous: contains snippets of different types`);
return false;
} else {
editor = expected;
return true;
}
}
}
function diffify(steps: TutorialStepInfo[], activities: TutorialActivityInfo[]) {
// convert typescript snippets into diff snippets
let lastSrc: string = undefined;
steps.forEach((step, stepi) => {
// reset diff on each activity or when requested
if (step.resetDiff
|| (activities && activities.find(activity => activity.step == stepi)))
lastSrc = undefined;
// extract typescript snippet from hint or content
let s = convertSnippetToDiff(step.hintContentMd);
if (s && s != step.hintContentMd)
step.hintContentMd = s;
else {
s = convertSnippetToDiff(step.headerContentMd);
if (s && s != step.headerContentMd)
step.headerContentMd = s;
}
})
function convertSnippetToDiff(src: string): string {
const highlightRx = /\s*(\/\/|#)\s*@highlight/gm;
if (!src) return src;
return src
.replace(/```(typescript|spy|python)((?:.|[\r\n])+)```/, function (m, type, code) {
const fileA = lastSrc;
const hasHighlight = highlightRx.test(code);
code = code.replace(/^\n+/, '').replace(/\n+$/, ''); // always trim lines
if (hasHighlight) code = code.replace(highlightRx, '');
lastSrc = code;
if (!fileA || hasHighlight)
return m; // leave unchanged or reuse highlight info
else
return `\`\`\`diff${type == "spy" ? type : ''}
${fileA}
----------
${code}
\`\`\``
})
}
}
function parseTutorialTitle(tutorialmd: string): string {
let title = tutorialmd.match(/^#[^#](.*)$/mi);
return title && title.length > 1 ? title[1] : null;
}
function parseTutorialMarkdown(tutorialmd: string, metadata: TutorialMetadata): { steps: TutorialStepInfo[], activities: TutorialActivityInfo[] } {
tutorialmd = stripHiddenSnippets(tutorialmd);
if (metadata && metadata.activities) {
// tutorial with "## ACTIVITY", "### STEP" syntax
return parseTutorialActivities(tutorialmd, metadata);
} else {
// tutorial with "## STEP" syntax
let steps = parseTutorialSteps(tutorialmd, null, metadata);
// old: "### STEP" syntax (no activity header guaranteed)
if (!steps || steps.length < 1) steps = parseTutorialSteps(tutorialmd, _h3Regex, metadata);
return { steps: steps, activities: null };
}
}
function parseTutorialActivities(markdown: string, metadata: TutorialMetadata): { steps: TutorialStepInfo[], activities: TutorialActivityInfo[] } {
let stepInfo: TutorialStepInfo[] = [];
let activityInfo: TutorialActivityInfo[] = [];
markdown.replace(_h2Regex, function (match, name, activity) {
let i = activityInfo.length;
activityInfo.push({
name: name || lf("Activity {0}", i),
step: stepInfo.length
})
let steps = parseTutorialSteps(activity, _h3Regex, metadata);
steps = steps.map(step => {
step.activity = i;
return step;
})
stepInfo = stepInfo.concat(steps);
return "";
})
return { steps: stepInfo, activities: activityInfo };
}
function parseTutorialSteps(markdown: string, regex?: RegExp, metadata?: TutorialMetadata): TutorialStepInfo[] {
// use regex override if present
let stepRegex = regex || _h2Regex;
let stepInfo: TutorialStepInfo[] = [];
markdown.replace(stepRegex, function (match, flags, step) {
step = step.trim();
let { header, hint } = parseTutorialHint(step, metadata && metadata.explicitHints);
let info: TutorialStepInfo = {
fullscreen: /@(fullscreen|unplugged)/.test(flags),
unplugged: /@unplugged/.test(flags),
tutorialCompleted: /@tutorialCompleted/.test(flags),
resetDiff: /@resetDiff/.test(flags),
contentMd: step,
headerContentMd: header,
hintContentMd: hint,
hasHint: hint && hint.length > 0
}
stepInfo.push(info);
return "";
});
if (markdown.indexOf("# Not found") == 0) {
pxt.debug(`tutorial not found`);
return undefined;
}
return stepInfo;
}
function parseTutorialHint(step: string, explicitHints?: boolean): { header: string, hint: string } {
let header = step, hint;
if (explicitHints) {
// hint is explicitly set with hint syntax "#### ~ tutorialhint" and terminates at the next heading
const hintTextRegex = /#+ ~ tutorialhint([\s\S]*)/i;
header = step.replace(hintTextRegex, function (f, m) {
hint = m;
return "";
});
} else {
// everything after the first ``` section OR the first image is treated as a "hint"
const hintTextRegex = /(^[\s\S]*?\S)\s*((```|\!\[[\s\S]+?\]\(\S+?\))[\s\S]*)/mi;
let hintText = step.match(hintTextRegex);
if (hintText && hintText.length > 2) {
header = hintText[1].trim();
hint = hintText[2].trim();
}
}
return { header, hint };
}
/* Remove hidden snippets from text */
function stripHiddenSnippets(str: string): string {
if (!str) return null;
const hiddenSnippetRegex = /```(filterblocks|package|ghost|config|template)\s*\n([\s\S]*?)\n```/gmi;
return str.replace(hiddenSnippetRegex, '').trim();
}
/*
Parses metadata at the beginning of tutorial markown. Metadata is a key-value
pair in the format: `### @KEY VALUE`
*/
function parseTutorialMetadata(tutorialmd: string): { metadata: TutorialMetadata, body: string } {
const metadataRegex = /### @(\S+) ([ \S]+)/gi;
const m: any = {};
const body = tutorialmd.replace(metadataRegex, function (f, k, v) {
try {
m[k] = JSON.parse(v);
} catch {
m[k] = v;
}
return "";
});
return { metadata: (m as TutorialMetadata), body };
}
export function highlight(pre: HTMLElement): void {
let text = pre.textContent;
if (!/@highlight/.test(text)) // shortcut, nothing to do
return;
// collapse image python/js literales
text = text.replace(/img\s*\(\s*"{3}(.|\n)*"{3}\s*\)/g, `""" """`);
text = text.replace(/img\s*\(\s*`(.|\n)*`\s*\)/g, "img` `");
// render lines
pre.textContent = ""; // clear up and rebuild
const lines = text.split('\n');
for (let i = 0; i < lines.length; ++i) {
if (i > 0 && i < lines.length)
pre.appendChild(document.createTextNode("\n"))
let line = lines[i];
if (/@highlight/.test(line)) {
// highlight next line
line = lines[++i];
if (line !== undefined) {
const span = document.createElement("span");
span.className = "highlight-line";
span.textContent = line;
pre.appendChild(span);
}
} else {
pre.appendChild(document.createTextNode(line));
}
}
}
export function getTutorialOptions(md: string, tutorialId: string, filename: string, reportId: string, recipe: boolean): { options: pxt.tutorial.TutorialOptions, editor: string } {
const tutorialInfo = pxt.tutorial.parseTutorial(md);
if (!tutorialInfo)
throw new Error(lf("Invalid tutorial format"));
const tutorialOptions: pxt.tutorial.TutorialOptions = {
tutorial: tutorialId,
tutorialName: tutorialInfo.title || filename,
tutorialReportId: reportId,
tutorialStep: 0,
tutorialReady: true,
tutorialHintCounter: 0,
tutorialStepInfo: tutorialInfo.steps,
tutorialActivityInfo: tutorialInfo.activities,
tutorialMd: md,
tutorialCode: tutorialInfo.code,
tutorialRecipe: !!recipe,
templateCode: tutorialInfo.templateCode,
autoexpandStep: true,
metadata: tutorialInfo.metadata
};
return { options: tutorialOptions, editor: tutorialInfo.editor };
}
}