Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow configuring text to be selectable #73

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions flutter_highlighting/lib/flutter_highlighting.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,25 @@ class HighlightView extends StatelessWidget {
/// Specify text styles such as font family and font size
final TextStyle? textStyle;

/// Text selectable
///
/// Specify if the text is selectable
final bool selectable;

/// Text selection color
///
/// Specify the text selection highlight color
final Color selectionColor;

HighlightView(
String input, {
this.languageId,
this.theme = const {},
this.padding,
this.textStyle,
int tabSize = 8, // TODO: https://github.com/flutter/flutter/issues/50087
this.selectable = false,
this.selectionColor = _defaultTextSelectionColor,
}) : source = input.replaceAll('\t', ' ' * tabSize);

List<TextSpan> _convert(List<Node> nodes) {
Expand Down Expand Up @@ -71,6 +83,7 @@ class HighlightView extends StatelessWidget {
static const _rootKey = 'root';
static const _defaultFontColor = Color(0xff000000);
static const _defaultBackgroundColor = Color(0xffffffff);
static const _defaultTextSelectionColor = Color(0xAF6694e8);

// TODO: dart:io is not available at web platform currently
// See: https://github.com/flutter/flutter/issues/39998
Expand All @@ -79,20 +92,23 @@ class HighlightView extends StatelessWidget {

@override
Widget build(BuildContext context) {
var _textStyle = TextStyle(
var textStyle = TextStyle(
fontFamily: _defaultFontFamily,
color: theme[_rootKey]?.color ?? _defaultFontColor,
);
if (textStyle != null) {
_textStyle = _textStyle.merge(textStyle);
textStyle = textStyle.merge(textStyle);
}

return Container(
color: theme[_rootKey]?.backgroundColor ?? _defaultBackgroundColor,
padding: padding,
child: RichText(
selectionRegistrar:
selectable ? SelectionContainer.maybeOf(context) : null,
selectionColor: selectionColor,
text: TextSpan(
style: _textStyle,
style: textStyle,
children: _convert(
highlight.highlight(languageId ?? '', source, true).nodes ?? [],
),
Expand Down