44
55import 'package:jaspr_content/jaspr_content.dart' ;
66
7- /// A node-processing, page extension for Jaspr Content that
8- /// wraps each `h1` -> `h5` element in a div with the `header-wrapper` class
9- /// and adds an anchor that can clicked and linked to.
7+ /// An extension that wraps `h2` through `h5` headings and
8+ /// adds permalink anchors.
9+ ///
10+ /// Heading IDs must already be unique.
1011final class HeaderWrapperExtension implements PageExtension {
1112 const HeaderWrapperExtension ();
1213
1314 @override
14- Future <List <Node >> apply (Page page, List <Node > nodes) async {
15- final usedIds = < String > {};
16- return _processNodes (nodes, usedIds);
17- }
15+ Future <List <Node >> apply (Page page, List <Node > nodes) async =>
16+ _processNodes (nodes);
1817
19- List <Node > _processNodes (List <Node > nodes, Set < String > usedIds) {
20- return [ for (final node in nodes) _processNode (node, usedIds)];
21- }
18+ List <Node > _processNodes (List <Node > nodes) => [
19+ for (final node in nodes) _processNode (node),
20+ ];
2221
23- Node _processNode (Node node, Set < String > usedIds ) {
22+ Node _processNode (Node node) {
2423 if (node is ! ElementNode ) return node;
2524
2625 final tagName = node.tag.toLowerCase ();
@@ -31,23 +30,12 @@ final class HeaderWrapperExtension implements PageExtension {
3130 return ElementNode (
3231 node.tag,
3332 node.attributes,
34- nodeChildren != null ? _processNodes (nodeChildren, usedIds ) : null ,
33+ nodeChildren != null ? _processNodes (nodeChildren) : null ,
3534 );
3635 }
3736
38- final rawHeaderId = node.attributes['id' ];
39- if (rawHeaderId == null ) return node;
40-
41- // Account for headers with the same base id,
42- // appending a dash and an integer until the header has a unique id.
43- var headerId = rawHeaderId;
44- for (var i = 1 ; usedIds.contains (headerId); i += 1 ) {
45- headerId = '$rawHeaderId -$i ' ;
46- }
47- usedIds.add (headerId);
48-
49- // Update header ID to be the unique one as well.
50- node.attributes['id' ] = headerId;
37+ final headerId = node.attributes['id' ];
38+ if (headerId == null ) return node;
5139
5240 final headerText = node.innerText;
5341
0 commit comments