fix url parsing
Some checks are pending
Flutter analyze & test / flutter_analyze_and_test (push) Waiting to run

This commit is contained in:
otsmr 2026-08-05 21:47:26 +02:00
parent 8094949c76
commit 8505ed865a
2 changed files with 64 additions and 1 deletions

View file

@ -13,7 +13,7 @@ class BetterText extends StatelessWidget {
Widget build(BuildContext context) {
// Regular expression to find URLs and domains
final urlRegExp = RegExp(
r'(?:(?:https?://|www\.)[^\s]+|(?:[a-zA-Z0-9-]+\.[a-zA-Z]{2,}))',
r'''(?:(?:https?://|www\.)(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\([^\s()<>]+\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))|(?:(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})''',
caseSensitive: false,
);

View file

@ -0,0 +1,63 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:twonly/src/visual/elements/better_text.element.dart';
void main() {
testWidgets('BetterText parses URLs correctly', (WidgetTester tester) async {
const text =
'Test: (https://google.com) and another link https://example.com/#fragment, plus www.test.com. Also check https://wikipedia.org/wiki/Test_(disambiguation) !';
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: BetterText(
text: text,
textColor: Colors.black,
),
),
),
);
final richTextFinder = find.byType(RichText);
expect(richTextFinder, findsWidgets);
final richTexts = tester.widgetList<RichText>(richTextFinder);
final parsedTexts = <String>[];
void extractTexts(InlineSpan span) {
if (span is TextSpan) {
if (span.text != null) parsedTexts.add(span.text!);
if (span.children != null) {
span.children!.forEach(extractTexts);
}
}
}
for (final richText in richTexts) {
extractTexts(richText.text);
}
// BetterText creates one span for text, one for link, etc.
// The URLs will be parsed as individual TextSpans inside the top-level TextSpan.
expect(
parsedTexts.contains('https://google.com'),
isTrue,
reason: 'Parenthesis should not be in the URL',
);
expect(
parsedTexts.contains('https://example.com/#fragment'),
isTrue,
reason: 'Hashtag/fragment should be in the URL',
);
expect(
parsedTexts.contains('www.test.com'),
isTrue,
reason: 'Trailing period should not be in the URL',
);
expect(
parsedTexts.contains('https://wikipedia.org/wiki/Test_(disambiguation)'),
isTrue,
reason: 'Should parse URLs with parentheses correctly',
);
});
}