Skip to content

Commit

Permalink
fix: flutter highlight traverse
Browse files Browse the repository at this point in the history
  • Loading branch information
pd4d10 committed Aug 21, 2019
1 parent 4da9ce8 commit 6ae2549
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 23 deletions.
49 changes: 31 additions & 18 deletions flutter_highlight/lib/flutter_highlight.dart
Expand Up @@ -6,38 +6,51 @@ class Highlighter extends StatelessWidget {
static final _h = Highlight();

final String code;
final String language;
final Map<String, TextStyle> style;

Highlighter(this.code);
Highlighter(this.code, {this.language, this.style = const {}});

List<TextSpan> convert(List<Node> nodes) {
List<TextSpan> spans = [];
var currentSpans = spans;
List<List<TextSpan>> stack = [];

traverse(Node node) {
_traverse(Node node) {
if (node.value != null) {
if (node.className != null) {
spans.add(TextSpan(
text: node.value,
style: TextStyle(
color: Color(0xff122345),
fontStyle: FontStyle.italic,
fontWeight: FontWeight.normal,
)));
} else {
spans.add(TextSpan(text: node.value));
}
currentSpans.add(node.className == null
? TextSpan(text: node.value)
: TextSpan(text: node.value, style: style[node.className]));
} else if (node.children != null) {
node.children.forEach(traverse);
List<TextSpan> tmp = [];
currentSpans.add(TextSpan(children: tmp, style: style[node.className]));
stack.add(currentSpans);
currentSpans = tmp;

node.children.forEach((n) {
_traverse(n);
if (n == node.children.last) {
currentSpans = stack.isEmpty ? spans : stack.removeLast();
}
});
}
}

nodes.forEach(traverse);
for (var node in nodes) {
_traverse(node);
}

return spans;
}

@override
Widget build(BuildContext context) {
all.forEach(_h.registerLanguage);
var nodes = _h.highlight(code).value;
return RichText(text: TextSpan(children: convert(nodes)));
all.forEach(_h.registerLanguage); // FIXME:

var nodes = _h.highlight(code, language: language).value;
return RichText(
text: TextSpan(
children: convert(nodes),
style: TextStyle(color: Color(0xff000000), fontFamily: 'Menlo')));
}
}
7 changes: 2 additions & 5 deletions flutter_highlight/pubspec.yaml
Expand Up @@ -10,16 +10,13 @@ environment:
dependencies:
flutter:
sdk: flutter
highlight: ^0.0.1
highlight:
path: ../highlight

dev_dependencies:
flutter_test:
sdk: flutter

dependency_overrides:
highlight:
path: ../highlight

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

Expand Down

0 comments on commit 6ae2549

Please sign in to comment.