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

Add Phone Number Linking #33

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# `linkify` [![pub package](https://img.shields.io/pub/v/linkify.svg)](https://pub.dartlang.org/packages/linkify)

Low-level link (text, URLs, emails) parsing library in Dart.
Low-level link (text, URLs, emails, phone numbers) parsing library in Dart.

[Flutter library](https://github.com/Cretezy/flutter_linkify).

Expand Down
61 changes: 61 additions & 0 deletions lib/src/phone_number.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import 'package:linkify/linkify.dart';

// matches "any amount of text with a phone number"
final _phoneNumberRegex = RegExp(r'(.*?)((\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4})', caseSensitive: false, dotAll: true);

class PhoneNumberLinkifier extends Linkifier {
const PhoneNumberLinkifier();

@override
List<LinkifyElement> parse(elements, options) {
final list = <LinkifyElement>[];

elements.forEach((element) {
if (element is TextElement) {
var match = _phoneNumberRegex.firstMatch(element.text);

if (match == null) {
list.add(element);
} else {
// create the preceding TextElement
if (match.group(1).isNotEmpty) {
list.add(TextElement(match.group(1)));
}

// create the PhoneNumberElement
if (match.group(2).isNotEmpty) {
var phoneNumberText = match.group(2);
var phoneNumberURL = "tel:" + phoneNumberText;

list.add(PhoneNumberElement(phoneNumberText, phoneNumberURL));
}

// create the following TextElement
final text = element.text.replaceFirst(match.group(0), '');
if (text.isNotEmpty) {
list.addAll(parse([TextElement(text)], options));
}
}
} else {
list.add(element);
}
});

return list;
}
}

class PhoneNumberElement extends LinkableElement {
PhoneNumberElement(String text, String url) : super(text, url);

@override
String toString() {
return "LinkElement: '$url' ($text)";
}

@override
bool operator ==(other) => equals(other);

@override
bool equals(other) => other is UrlElement && super.equals(other);
}