A cross platform Audiobookshelf client for Android and iOS
Dart
Add podcast chapter support and rich HTML descriptions
Nathan Poulsondb9ba314145d
diff --git a/lib/screens/admin_podcasts_screen.dart b/lib/screens/admin_podcasts_screen.dartindex 1fe85f68..628b9eae 100644--- a/lib/screens/admin_podcasts_screen.dart+++ b/lib/screens/admin_podcasts_screen.dart@@ -3,6 +3,7 @@ import 'package:provider/provider.dart';import '../providers/auth_provider.dart';import '../services/api_service.dart';import '../widgets/absorb_page_header.dart';+import '../widgets/html_description.dart';class AdminPodcastsScreen extends StatefulWidget {final Map<String, dynamic> library;@@ -553,11 +554,11 @@ class _PodcastPreviewScreenState extends State<_PodcastPreviewScreen> {// Descriptionif (_description.isNotEmpty) ...[- Text(- _description,- style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.5), height: 1.5),+ HtmlDescription(+ html: _description,maxLines: 6,- overflow: TextOverflow.ellipsis,+ style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.5), height: 1.5),+ linkColor: cs.primary,),const SizedBox(height: 16),],@@ -1050,7 +1051,7 @@ class _EpisodeDetailSheet extends StatelessWidget {final tt = Theme.of(context).textTheme;final title = episode['title']?.toString() ?? 'Episode';- final description = _cleanHtml(episode['description']?.toString() ?? episode['subtitle']?.toString() ?? '');+ final descriptionHtml = episode['description']?.toString() ?? episode['subtitle']?.toString() ?? '';final pubDateRaw = episode['publishedAt'] ?? episode['pubDate'];final pubDate = pubDateRaw is num ? pubDateRaw : (num.tryParse(pubDateRaw?.toString() ?? ''));final duration = episode['duration']?.toString() ?? '';@@ -1105,12 +1106,17 @@ class _EpisodeDetailSheet extends StatelessWidget {child: Text(fileType, style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.24), fontSize: 10)))),// Description- if (description.isNotEmpty)+ if (descriptionHtml.isNotEmpty)Flexible(child: Padding(padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),child: SingleChildScrollView(child: SizedBox(width: double.infinity,- child: Text(description, style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.54), height: 1.5))),+ child: HtmlDescription(+ html: descriptionHtml,+ maxLines: 200,+ style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.54), height: 1.5),+ linkColor: cs.primary,+ )),)),),@@ -1151,22 +1157,6 @@ class _EpisodeDetailSheet extends StatelessWidget {);}- String _cleanHtml(String html) {- return html- .replaceAll(RegExp(r'<br\s*/?>'), '\n')- .replaceAll(RegExp(r'<p\s*>'), '\n')- .replaceAll(RegExp(r'</p>'), '')- .replaceAll(RegExp(r'<[^>]+>'), '')- .replaceAll('&', '&')- .replaceAll('<', '<')- .replaceAll('>', '>')- .replaceAll('"', '"')- .replaceAll(''', "'")- .replaceAll(' ', ' ')- .replaceAll(RegExp(r'\n{3,}'), '\n\n')- .trim();- }-String _fmtDate(int ms) {final dt = DateTime.fromMillisecondsSinceEpoch(ms);const m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];@@ -1206,7 +1196,7 @@ class _DownloadedEpisodeDetailSheet extends StatelessWidget {final tt = Theme.of(context).textTheme;final title = episode['title']?.toString() ?? 'Episode';- final description = _cleanHtml(episode['description']?.toString() ?? episode['subtitle']?.toString() ?? '');+ final descriptionHtml = episode['description']?.toString() ?? episode['subtitle']?.toString() ?? '';final pubAt = episode['publishedAt'];final pubDate = pubAt is num ? pubAt : (num.tryParse(pubAt?.toString() ?? ''));final durRaw = episode['duration'];@@ -1249,12 +1239,17 @@ class _DownloadedEpisodeDetailSheet extends StatelessWidget {child: Text(c, style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.54), fontSize: 11)),)).toList()))),- if (description.isNotEmpty)+ if (descriptionHtml.isNotEmpty)Flexible(child: Padding(padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),child: SingleChildScrollView(child: SizedBox(width: double.infinity,- child: Text(description, style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.54), height: 1.5))),+ child: HtmlDescription(+ html: descriptionHtml,+ maxLines: 200,+ style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.54), height: 1.5),+ linkColor: cs.primary,+ )),)),),@@ -1296,22 +1291,6 @@ class _DownloadedEpisodeDetailSheet extends StatelessWidget {);}- String _cleanHtml(String html) {- return html- .replaceAll(RegExp(r'<br\s*/?>'), '\n')- .replaceAll(RegExp(r'<p\s*>'), '\n')- .replaceAll(RegExp(r'</p>'), '')- .replaceAll(RegExp(r'<[^>]+>'), '')- .replaceAll('&', '&')- .replaceAll('<', '<')- .replaceAll('>', '>')- .replaceAll('"', '"')- .replaceAll(''', "'")- .replaceAll(' ', ' ')- .replaceAll(RegExp(r'\n{3,}'), '\n\n')- .trim();- }-String _fmtDate(int ms) {final dt = DateTime.fromMillisecondsSinceEpoch(ms);const m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex 302ecae9..7918069c 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -20,6 +20,7 @@ import '../services/metadata_override_service.dart';import '../screens/app_shell.dart';import 'series_books_sheet.dart';import 'absorbing_shared.dart';+import 'html_description.dart';import 'metadata_lookup_sheet.dart';// ─── BOOK DETAIL BOTTOM SHEET ───────────────────────────────@@ -196,7 +197,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final authorName = metadata['authorName'] as String? ?? '';final narrator = metadata['narratorName'] as String? ?? '';final descRaw = metadata['description'] as String? ?? '';- final desc = descRaw.replaceAll(RegExp(r'<[^>]*>'), '').replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll(''', "'").replaceAll(' ', ' ').trim();final duration = (media['duration'] as num?)?.toDouble() ?? 0;final seriesEntries = metadata['series'] as List<dynamic>? ?? [];final genres = (metadata['genres'] as List<dynamic>?)?.cast<String>() ?? [];@@ -402,10 +402,15 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {),));})],- if (desc.isNotEmpty) ...[const SizedBox(height: 16),+ if (descRaw.isNotEmpty) ...[const SizedBox(height: 16),Text('About', style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),const SizedBox(height: 6),- Text(desc, style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.7), height: 1.5))],+ HtmlDescription(+ html: descRaw,+ maxLines: 6,+ style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.7), height: 1.5),+ linkColor: cs.primary,+ )],if (chapters.isNotEmpty) ...[const SizedBox(height: 16),GestureDetector(onTap: () => setState(() => _chaptersExpanded = !_chaptersExpanded),child: Row(children: [diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dartindex e364167f..beb48bfc 100644--- a/lib/widgets/episode_list_sheet.dart+++ b/lib/widgets/episode_list_sheet.dart@@ -8,6 +8,7 @@ import '../services/download_service.dart';import '../services/progress_sync_service.dart';import '../services/chromecast_service.dart';import '../providers/auth_provider.dart';+import 'html_description.dart';/// Bottom sheet that shows a podcast's episode list./// Mirrors the UX of [BookDetailSheet] but adapted for podcast shows.@@ -50,7 +51,6 @@ class EpisodeListSheet extends StatefulWidget {class _EpisodeListSheetState extends State<EpisodeListSheet> {List<dynamic> _episodes = [];bool _isLoading = true;- bool _descriptionExpanded = false;bool _isDownloadingAll = false;String get _itemId => widget.podcastItem['id'] as String? ?? '';@@ -124,6 +124,8 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {final duration = (episode['duration'] as num?)?.toDouble() ?? 0;final coverUrl = api.getCoverUrl(_itemId);+ final chapters = episode['chapters'] as List<dynamic>? ?? [];+// Check if Chromecast is connectedfinal cast = ChromecastService();if (cast.isConnected) {@@ -134,7 +136,7 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {author: _title,coverUrl: coverUrl,totalDuration: duration,- chapters: [],+ chapters: chapters,episodeId: episodeId,);if (mounted) Navigator.of(context, rootNavigator: true).popUntil((route) => route.isFirst);@@ -149,7 +151,7 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {author: _title,coverUrl: coverUrl,totalDuration: duration,- chapters: [],+ chapters: chapters,episodeId: episodeId,episodeTitle: episodeTitle,);@@ -272,13 +274,11 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {// Descriptionif (_description.isNotEmpty) ...[const SizedBox(height: 10),- GestureDetector(- onTap: () => setState(() => _descriptionExpanded = !_descriptionExpanded),- child: Text(_description,- maxLines: _descriptionExpanded ? 100 : 2,- overflow: TextOverflow.ellipsis,- textAlign: TextAlign.center,- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, height: 1.4)),+ HtmlDescription(+ html: _description,+ maxLines: 2,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, height: 1.4),+ linkColor: cs.primary,),],@@ -479,7 +479,7 @@ class EpisodeDetailSheet extends StatefulWidget {}class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {- bool _descriptionExpanded = false;+ bool _chaptersExpanded = false;String get _itemId => widget.podcastItem['id'] as String? ?? '';@@ -501,17 +501,9 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {int get _publishedAt => (widget.episode['publishedAt'] as num?)?.toInt() ?? 0;String? get _episodeNumber => widget.episode['episode'] as String?;String? get _season => widget.episode['season'] as String?;+ List<dynamic> get _chapters => widget.episode['chapters'] as List<dynamic>? ?? [];- String get _cleanDescription {- final desc = widget.episode['description'] as String? ?? '';- return desc- .replaceAll(RegExp(r'<[^>]*>'), '')- .replaceAll(' ', ' ')- .replaceAll('&', '&')- .replaceAll('<', '<')- .replaceAll('>', '>')- .trim();- }+ String get _rawDescription => widget.episode['description'] as String? ?? '';Future<void> _play() async {final auth = context.read<AuthProvider>();@@ -522,7 +514,7 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {if (cast.isConnected) {await cast.castItem(api: api, itemId: _itemId, title: _episodeTitle, author: _showTitle,- coverUrl: api.getCoverUrl(_itemId), totalDuration: _duration, chapters: [],+ coverUrl: api.getCoverUrl(_itemId), totalDuration: _duration, chapters: _chapters,episodeId: _episodeId,);if (mounted) Navigator.of(context, rootNavigator: true).popUntil((route) => route.isFirst);@@ -531,7 +523,7 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {await AudioPlayerService().playItem(api: api, itemId: _itemId, title: _episodeTitle, author: _showTitle,- coverUrl: api.getCoverUrl(_itemId), totalDuration: _duration, chapters: [],+ coverUrl: api.getCoverUrl(_itemId), totalDuration: _duration, chapters: _chapters,episodeId: _episodeId,episodeTitle: _episodeTitle,);@@ -872,29 +864,34 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {),),+ // Chapters+ if (_chapters.isNotEmpty) ...[const SizedBox(height: 16),+ GestureDetector(onTap: () => setState(() => _chaptersExpanded = !_chaptersExpanded),+ child: Row(children: [+ Text('Chapters (${_chapters.length})', style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),+ const Spacer(), Icon(_chaptersExpanded ? Icons.expand_less : Icons.expand_more, color: cs.onSurface.withValues(alpha: 0.3), size: 20)])),+ if (_chaptersExpanded) ...[const SizedBox(height: 8),+ ..._chapters.asMap().entries.map((e) {+ final ch = e.value as Map<String, dynamic>;+ return Padding(padding: const EdgeInsets.symmetric(vertical: 3),+ child: Row(children: [+ SizedBox(width: 28, child: Text('${e.key + 1}', style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3)))),+ Expanded(child: Text(ch['title'] as String? ?? 'Chapter ${e.key + 1}', maxLines: 1, overflow: TextOverflow.ellipsis, style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.6)))),+ Text(_fmtDur(((ch['end'] as num?)?.toDouble() ?? 0) - ((ch['start'] as num?)?.toDouble() ?? 0)), style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3))),+ ]));+ })]],+// Description- if (_cleanDescription.isNotEmpty) ...[+ if (_rawDescription.isNotEmpty) ...[const SizedBox(height: 16),Text('About This Episode', style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),const SizedBox(height: 6),- GestureDetector(- onTap: () => setState(() => _descriptionExpanded = !_descriptionExpanded),- child: Text(_cleanDescription,- maxLines: _descriptionExpanded ? 200 : 4,- overflow: TextOverflow.ellipsis,- style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.7), height: 1.5)),+ HtmlDescription(+ html: _rawDescription,+ maxLines: 4,+ style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.7), height: 1.5),+ linkColor: cs.primary,),- if (_cleanDescription.length > 200)- Padding(- padding: const EdgeInsets.only(top: 4),- child: GestureDetector(- onTap: () => setState(() => _descriptionExpanded = !_descriptionExpanded),- child: Text(- _descriptionExpanded ? 'Show less' : 'Show more',- style: TextStyle(fontSize: 12, color: cs.primary, fontWeight: FontWeight.w500),- ),- ),- ),],],),@@ -912,6 +909,12 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {Text(label, style: TextStyle(color: cs.onSurfaceVariant, fontSize: 12, fontWeight: FontWeight.w500))])));}+ String _fmtDur(double s) {+ final h = (s / 3600).floor(); final m = ((s % 3600) / 60).floor();+ if (h > 0) return '${h}h ${m}m';+ return '${m}m';+ }+Future<void> _resetProgress(BuildContext context) async {final confirmed = await showDialog<bool>(context: context,diff --git a/lib/widgets/expanded_card.dart b/lib/widgets/expanded_card.dartindex 2c0d8eb2..aae2de93 100644--- a/lib/widgets/expanded_card.dart+++ b/lib/widgets/expanded_card.dart@@ -105,7 +105,11 @@ class _ExpandedCardState extends State<ExpandedCard> {double get _duration => (_media['duration'] as num?)?.toDouble() ?? 0;List<dynamic> get _chapters {if (_fetchedChapters != null && _fetchedChapters!.isNotEmpty) return _fetchedChapters!;- return _media['chapters'] as List<dynamic>? ?? [];+ final inline = _media['chapters'] as List<dynamic>? ?? [];+ if (inline.isNotEmpty) return inline;+ // For active podcast episodes, chapters come from the playback session+ if (_isActive && widget.player.chapters.isNotEmpty) return widget.player.chapters;+ return [];}bool get _isActive {if (widget.player.currentItemId != _itemId) return false;@@ -550,7 +554,7 @@ class _ExpandedCardState extends State<ExpandedCard> {shadows: [Shadow(color: isDark ? Colors.black.withValues(alpha: 0.6) : Colors.white.withValues(alpha: 0.6), blurRadius: 4)],)),const Spacer(),- if (totalChapters > 0 && !_isPodcastEpisode)+ if (totalChapters > 0 && (!_isPodcastEpisode || _chapters.isNotEmpty))Text('Ch ${(chapterIdx + 1).clamp(1, totalChapters)} / $totalChapters',style: tt.labelMedium?.copyWith(color: isDark ? Colors.white.withValues(alpha: 0.85) : Colors.black.withValues(alpha: 0.75),@@ -563,7 +567,7 @@ class _ExpandedCardState extends State<ExpandedCard> {// ── Book progress bar ──Padding(padding: const EdgeInsets.symmetric(horizontal: 20),- child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: progress, staticDuration: _effectiveDuration, chapters: _chapters, showBookBar: !_isPodcastEpisode && !lib.isPodcastLibrary, showChapterBar: false, itemId: _itemId),+ child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: progress, staticDuration: _effectiveDuration, chapters: _chapters, showBookBar: (!_isPodcastEpisode || _chapters.isNotEmpty) && (!lib.isPodcastLibrary || _chapters.isNotEmpty), showChapterBar: false, itemId: _itemId),),const SizedBox(height: 16),// ── Cover art (larger — 90% width) ──@@ -730,7 +734,7 @@ class _ExpandedCardState extends State<ExpandedCard> {// ── Chapter scrubber ──Padding(padding: const EdgeInsets.symmetric(horizontal: 20),- child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: _isPodcastEpisode ? 0.0 : progress, staticDuration: _isPodcastEpisode ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: _isPodcastEpisode ? (widget.player.currentEpisodeTitle ?? widget.player.currentTitle ?? _title) : (_episodeId != null && !_isActive ? (_recentEpisode?['title'] as String? ?? _title) : _chapterName(chapterIdx)), chapterIndex: chapterIdx, totalChapters: totalChapters, itemId: _itemId),+ child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: (_isPodcastEpisode && _chapters.isEmpty) ? 0.0 : progress, staticDuration: (_isPodcastEpisode && _chapters.isEmpty) ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: (_isPodcastEpisode && _chapters.isEmpty) ? (widget.player.currentEpisodeTitle ?? widget.player.currentTitle ?? _title) : (_episodeId != null && !_isActive ? (_recentEpisode?['title'] as String? ?? _title) : _chapterName(chapterIdx)), chapterIndex: chapterIdx, totalChapters: totalChapters, itemId: _itemId),),// ── Controls + buttons ──Expanded(diff --git a/lib/widgets/html_description.dart b/lib/widgets/html_description.dartnew file mode 100644index 00000000..f612414d--- /dev/null+++ b/lib/widgets/html_description.dart@@ -0,0 +1,256 @@+import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:url_launcher/url_launcher.dart';++/// Lightweight HTML-to-RichText widget with clickable links.+///+/// Handles common podcast/book description HTML:+/// - `<a href>` → tappable links+/// - `<b>`, `<strong>` → bold+/// - `<i>`, `<em>` → italic+/// - `<br>`, `<p>` → newlines+/// - Bare URLs → tappable links+/// - HTML entities → decoded+///+/// Includes built-in "Show more / Show less" toggle.+class HtmlDescription extends StatefulWidget {+ final String html;+ final int maxLines;+ final TextStyle? style;+ final Color? linkColor;++ const HtmlDescription({+ super.key,+ required this.html,+ this.maxLines = 4,+ this.style,+ this.linkColor,+ });++ @override+ State<HtmlDescription> createState() => _HtmlDescriptionState();+}++class _HtmlDescriptionState extends State<HtmlDescription> {+ bool _expanded = false;++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final baseStyle = widget.style ?? Theme.of(context).textTheme.bodySmall?.copyWith(+ color: cs.onSurface.withValues(alpha: 0.7), height: 1.5);+ final linkColor = widget.linkColor ?? cs.primary;++ final spans = _parseHtml(widget.html, baseStyle ?? const TextStyle(), linkColor);+ final richText = Text.rich(+ TextSpan(children: spans),+ maxLines: _expanded ? null : widget.maxLines,+ overflow: _expanded ? TextOverflow.clip : TextOverflow.ellipsis,+ );++ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ richText,+ // Show toggle if text is likely long enough to be truncated+ if (_isLikelyTruncated(widget.html, widget.maxLines))+ Padding(+ padding: const EdgeInsets.only(top: 4),+ child: GestureDetector(+ onTap: () => setState(() => _expanded = !_expanded),+ child: Text(+ _expanded ? 'Show less' : 'Show more',+ style: TextStyle(fontSize: 12, color: linkColor, fontWeight: FontWeight.w500),+ ),+ ),+ ),+ ],+ );+ }++ /// Rough heuristic: text is likely truncated if the plain-text content+ /// exceeds ~80 chars per line × maxLines (conservative estimate).+ bool _isLikelyTruncated(String html, int maxLines) {+ final plain = _stripTags(html);+ return plain.length > maxLines * 80 || '\n'.allMatches(plain).length >= maxLines;+ }+}++// ─── HTML Parsing ──────────────────────────────────────────++/// Regex for bare URLs not already inside an <a> tag.+final _bareUrlRegex = RegExp(+ r'https?://[^\s<>\])"]+',+ caseSensitive: false,+);++/// Parse HTML string into a list of styled TextSpans.+List<InlineSpan> _parseHtml(String html, TextStyle baseStyle, Color linkColor) {+ // Pre-process: convert block elements to newlines+ var text = html+ .replaceAll(RegExp(r'<br\s*/?>'), '\n')+ .replaceAll(RegExp(r'</p>'), '\n')+ .replaceAll(RegExp(r'<p[^>]*>'), '')+ .replaceAll(RegExp(r'</div>'), '\n')+ .replaceAll(RegExp(r'<div[^>]*>'), '')+ .replaceAll(RegExp(r'</?ul[^>]*>'), '\n')+ .replaceAll(RegExp(r'</?ol[^>]*>'), '\n')+ .replaceAll(RegExp(r'<li[^>]*>'), ' \u2022 ')+ .replaceAll(RegExp(r'</li>'), '\n')+ .replaceAll(RegExp(r'\n{3,}'), '\n\n'); // collapse excess newlines++ final spans = <InlineSpan>[];+ final tagPattern = RegExp(+ r'<(/?)(a|b|strong|i|em)(\s[^>]*)?>',+ caseSensitive: false,+ );++ var bold = false;+ var italic = false;+ String? linkUrl;+ var pos = 0;++ for (final match in tagPattern.allMatches(text)) {+ // Add text before this tag+ if (match.start > pos) {+ final segment = text.substring(pos, match.start);+ spans.addAll(_textWithLinks(+ _decodeEntities(segment),+ _buildStyle(baseStyle, bold, italic, linkUrl != null, linkColor),+ linkColor,+ linkUrl,+ ));+ }+ pos = match.end;++ final isClosing = match.group(1) == '/';+ final tag = match.group(2)!.toLowerCase();++ switch (tag) {+ case 'a':+ if (isClosing) {+ linkUrl = null;+ } else {+ final attrs = match.group(3) ?? '';+ final hrefMatch = RegExp(r'href\s*=\s*"([^"]*)"').firstMatch(attrs) ??+ RegExp(r"href\s*=\s*'([^']*)'").firstMatch(attrs);+ linkUrl = hrefMatch?.group(1);+ }+ break;+ case 'b':+ case 'strong':+ bold = !isClosing;+ break;+ case 'i':+ case 'em':+ italic = !isClosing;+ break;+ }+ }++ // Add remaining text after last tag+ if (pos < text.length) {+ final segment = text.substring(pos);+ // Strip any remaining unknown tags+ final cleaned = segment.replaceAll(RegExp(r'<[^>]+>'), '');+ spans.addAll(_textWithLinks(+ _decodeEntities(cleaned),+ _buildStyle(baseStyle, bold, italic, linkUrl != null, linkColor),+ linkColor,+ linkUrl,+ ));+ }++ // Trim trailing newlines+ while (spans.isNotEmpty) {+ final last = spans.last;+ if (last is TextSpan && last.text != null) {+ final trimmed = last.text!.replaceAll(RegExp(r'\n+$'), '');+ if (trimmed.isEmpty) {+ spans.removeLast();+ } else {+ spans[spans.length - 1] = TextSpan(+ text: trimmed,+ style: last.style,+ recognizer: last.recognizer,+ );+ break;+ }+ } else {+ break;+ }+ }++ return spans;+}++TextStyle _buildStyle(TextStyle base, bool bold, bool italic, bool isLink, Color linkColor) {+ var style = base;+ if (bold) style = style.copyWith(fontWeight: FontWeight.w600);+ if (italic) style = style.copyWith(fontStyle: FontStyle.italic);+ if (isLink) style = style.copyWith(color: linkColor, decoration: TextDecoration.underline, decorationColor: linkColor.withValues(alpha: 0.4));+ return style;+}++/// Split text into plain segments and bare-URL segments, making URLs tappable.+List<InlineSpan> _textWithLinks(String text, TextStyle style, Color linkColor, String? explicitUrl) {+ if (explicitUrl != null) {+ // Entire segment is inside an <a> tag+ return [_tappableSpan(text, style, explicitUrl)];+ }++ // Detect bare URLs+ final spans = <InlineSpan>[];+ var pos = 0;+ for (final match in _bareUrlRegex.allMatches(text)) {+ if (match.start > pos) {+ spans.add(TextSpan(text: text.substring(pos, match.start), style: style));+ }+ final url = match.group(0)!;+ final linkStyle = style.copyWith(+ color: linkColor,+ decoration: TextDecoration.underline,+ decorationColor: linkColor.withValues(alpha: 0.4),+ );+ spans.add(_tappableSpan(url, linkStyle, url));+ pos = match.end;+ }+ if (pos < text.length) {+ spans.add(TextSpan(text: text.substring(pos), style: style));+ }+ return spans;+}++TextSpan _tappableSpan(String text, TextStyle style, String url) {+ return TextSpan(+ text: text,+ style: style,+ recognizer: TapGestureRecognizer()+ ..onTap = () => launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication),+ );+}++String _decodeEntities(String text) {+ return text+ .replaceAll(' ', ' ')+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('"', '"')+ .replaceAll(''', "'")+ .replaceAll(''', "'")+ .replaceAll(''', "'")+ .replaceAll('—', '\u2014')+ .replaceAll('–', '\u2013')+ .replaceAll('…', '\u2026')+ .replaceAll('«', '\u00AB')+ .replaceAll('»', '\u00BB');+}++String _stripTags(String html) {+ return _decodeEntities(html+ .replaceAll(RegExp(r'<br\s*/?>'), '\n')+ .replaceAll(RegExp(r'</p>'), '\n')+ .replaceAll(RegExp(r'<[^>]+>'), ''))+ .trim();+}