I've recently started the process of migrating my sites from
bespoke static site generators
to the
jaspr_content
package.
I've been having a great time with that so far, but one feature I've added to my own
generator is the ability to generate code snippets from source files in
lib/
.
That is a quite convenient feature to have, because:
- You get analyzer warnings if something is broken, so outdated snippets can be fixed immediately.
- You can write unit tests for snippets!
I've written the
code_snippets
page for my own static site generator, and I kind of
need this functionality for
jaspr_content
as well.
code_snippets
has become a bit
outdated anyway, so I took a week of porting it to jaspr, polishing it and finally publishing it to pub.dev.
One thing I'm very proud of is that this uses the exact same code the analysis server uses to highlight Dart files, so you bet it's good:
import 'dart:io';
import 'package:tar/tar.dart';
void main() async {
final reader = TarReader(stdin);
while (await reader.moveNext()) {
final entry = reader.current;
print(
'Found tar entry ${entry.name}, ${FilePermissions(entry.header.mode).format}',
);
}
}
extension type FilePermissions(int code) implements int {
String get format => code.toRadixString(8);
}
Seriously, look at that:
-
It got all of the keywords exactly right, including modern stuff like
extension type
s that most highlighters are unaware of. It even recognizes thatcode
is a variable in the extension type's constructor but a property inget format
. -
It can distinguish between definitions and references (see how
FilePermissions
is bold once?) - This automatically generates LINKS TO THE DOCUMENTATION!!! Can your TextMate grammar do that?!
This is why I
love
writing things in Dart. In any other language, or any other static site generator,
this would have been an absolute mess of starting analyzers as sub-processes and dealing with their output.
In Dart, this neatly integrates into the
package:build
ecosystem to generate snippets that
jaspr_content
can pick up with a custom component, giving you fully automated rebuilds without having to worry about anything.
I'm serious, this is all it took to render that snippet above:
One thing I'm very proud of is that this uses the exact same code the analysis
server uses to highlight Dart files, so you bet it's good:
<Snippet href="/lib/src/snippets/tar.dart" />
Seriously, look at that:
In case it isn't obvious, that one wasn't a markdown code block either. It's a self-referential
<Snippet />
generating on its own input file.
These kinds of tricks ensure it's
impossible
for snippets to become outdated with your project, because
the snippets
are
the project.
I hope you've enjoyed this small demo. If you need to write documentation for any kind of Dart project,
jaspr_content
and this highlighter can give you high-quality snippets and a guarantee that you'll never
forget to update them.
Check out the package
on pub.dev
to learn more!