-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathtutorial_prefetch_processor.dart
More file actions
85 lines (70 loc) · 2.29 KB
/
tutorial_prefetch_processor.dart
File metadata and controls
85 lines (70 loc) · 2.29 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
// Copyright 2025 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:jaspr/dom.dart';
import 'package:jaspr/jaspr.dart';
import 'package:jaspr_content/jaspr_content.dart';
import '../models/tutorial_model.dart';
/// A page extension for Jaspr Content that adds page navigation and a
/// prefetch link for the next unit to the current tutorial page.
final class TutorialNavigationExtension implements PageExtension {
const TutorialNavigationExtension();
@override
Future<List<Node>> apply(Page page, List<Node> nodes) async {
if (!page.path.startsWith('learn/pathway/')) {
return nodes;
}
final tutorial = switch (page.data['tutorial']) {
final Map<Object?, Object?>? tutorialData when tutorialData != null =>
TutorialModel.fromMap(tutorialData),
_ => throw Exception('No tutorial data found.'),
};
final normalizedPageUrl = page.url.endsWith('/')
? page.url
: '${page.url}/';
final allChapters = [
for (final unit in tutorial.units) ...unit.chapters,
];
final currentChapterIndex = allChapters.indexWhere((chapter) {
final normalizedUnitUrl = chapter.url.endsWith('/')
? chapter.url
: '${chapter.url}/';
return normalizedUnitUrl == normalizedPageUrl;
});
if (currentChapterIndex == -1) {
return nodes;
}
final nextChapter = allChapters.length > currentChapterIndex + 1
? allChapters[currentChapterIndex + 1]
: null;
final prevChapter = currentChapterIndex > 0
? allChapters[currentChapterIndex - 1]
: null;
if (nextChapter == null && prevChapter == null) {
return nodes;
}
page.apply(
data: {
'page': {
if (nextChapter != null)
'next': {'title': nextChapter.title, 'path': nextChapter.url},
if (prevChapter != null)
'prev': {'title': prevChapter.title, 'path': prevChapter.url},
},
},
);
if (nextChapter == null) {
return nodes;
}
return [
ComponentNode(
Document.head(
children: [
link(rel: 'prefetch', href: nextChapter.url),
],
),
),
...nodes,
];
}
}