mirror of
https://github.com/jonasbark/swiftcontrol.git
synced 2026-11-29 09:11:17 +01:00
Adds a "Use {controller} with {app}" link that opens the matching
bikecontrol.app/use-<controller>-with-<app>/ how-to page:
- as the first entry in the Help & Support dropdown (above Instruction
Videos), using the connected controller + selected trainer app;
- on the controller detail page, for that controller + the selected app.
Each controller device and trainer app maps to its website slug
(SupportedApp.helpSlug + a controller lookup in help_article.dart), with a
generic "other-training-app" fallback when a combination has no dedicated
page and no entry when the controller type has none. New localized string
useControllerWithApp across all 6 languages.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
580 lines
20 KiB
Dart
580 lines
20 KiB
Dart
import 'package:bike_control/gen/l10n.dart';
|
|
import 'package:bike_control/pages/markdown.dart';
|
|
import 'package:bike_control/pages/support_chat/support_chat_page.dart';
|
|
import 'package:bike_control/services/overview_screenshot.dart';
|
|
import 'package:bike_control/services/support_chat_models.dart';
|
|
import 'package:bike_control/services/support_chat_service.dart';
|
|
import 'package:bike_control/services/telemetry_snapshot.dart';
|
|
import 'package:bike_control/utils/core.dart';
|
|
import 'package:bike_control/utils/help_article.dart';
|
|
import 'package:bike_control/utils/i18n_extension.dart';
|
|
import 'package:bike_control/widgets/menu.dart';
|
|
import 'package:bike_control/widgets/ui/colored_title.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:prop/utils/shared.dart';
|
|
import 'package:shadcn_flutter/shadcn_flutter.dart';
|
|
import 'package:url_launcher/url_launcher_string.dart';
|
|
|
|
class HelpButton extends StatefulWidget {
|
|
final bool isMobile;
|
|
const HelpButton({super.key, required this.isMobile});
|
|
|
|
@override
|
|
State<HelpButton> createState() => _HelpButtonState();
|
|
}
|
|
|
|
class _HelpButtonState extends State<HelpButton> {
|
|
bool _hasUnread = false;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
if (core.settings.getSupportChatActive()) {
|
|
_checkForUnread();
|
|
}
|
|
}
|
|
|
|
/// Polls the support chat in the background and surfaces a small dot on
|
|
/// the help button when at least one admin message has arrived since the
|
|
/// last seen timestamp on the chat. Failures (no auth, network down,
|
|
/// edge function unavailable) are swallowed — the dot just stays off.
|
|
Future<void> _checkForUnread() async {
|
|
if (core.supabase.auth.currentSession == null) return;
|
|
try {
|
|
final fetched = await SupportChatService().fetchChat(skipLastSeen: true);
|
|
if (!mounted) return;
|
|
final lastSeen = fetched.chat?.lastSeenAt;
|
|
final hasUnreadAdminReply = fetched.messages.any(
|
|
(m) => m.senderRole == SupportMessageSenderRole.admin && (lastSeen == null || m.createdAt.isAfter(lastSeen)),
|
|
);
|
|
if (hasUnreadAdminReply != _hasUnread) {
|
|
setState(() => _hasUnread = hasUnreadAdminReply);
|
|
}
|
|
} catch (error) {
|
|
// Best-effort — leave the dot off.
|
|
Logger.error('Failed to check for unread support messages $error');
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final isMobile = widget.isMobile;
|
|
final border = isMobile
|
|
? BorderRadius.only(topRight: Radius.circular(8), topLeft: Radius.circular(8))
|
|
: BorderRadius.only(bottomLeft: Radius.circular(8), bottomRight: Radius.circular(8));
|
|
return Container(
|
|
decoration: BoxDecoration(
|
|
borderRadius: border,
|
|
),
|
|
child: Builder(
|
|
builder: (context) {
|
|
return Button(
|
|
onPressed: () {
|
|
final controllers = core.connection.controllerDevices;
|
|
final article = helpArticleFor(
|
|
context,
|
|
controller: controllers.isEmpty ? null : controllers.first,
|
|
app: core.settings.getTrainerApp(),
|
|
);
|
|
showDropdown(
|
|
context: context,
|
|
builder: (c) => DropdownMenu(
|
|
children: [
|
|
MenuLabel(child: Text(context.i18n.instructions)),
|
|
if (article != null)
|
|
MenuButton(
|
|
leading: Icon(Icons.menu_book_outlined),
|
|
child: Text(article.label),
|
|
onPressed: (c) => launchUrlString(article.url),
|
|
),
|
|
MenuButton(
|
|
leading: Icon(Icons.ondemand_video),
|
|
child: const Text('Instruction Videos'),
|
|
onPressed: (c) {
|
|
openDrawer(
|
|
context: context,
|
|
position: OverlayPosition.bottom,
|
|
builder: (c) => const _InstructionVideosDrawer(),
|
|
);
|
|
},
|
|
),
|
|
MenuButton(
|
|
leading: Icon(Icons.help_outline),
|
|
child: Text(AppLocalizations.of(context).troubleshootingPage),
|
|
onPressed: (c) {
|
|
openDrawer(
|
|
context: context,
|
|
position: OverlayPosition.bottom,
|
|
builder: (c) => MarkdownPage(assetPath: 'TROUBLESHOOTING.md'),
|
|
);
|
|
},
|
|
),
|
|
MenuDivider(),
|
|
MenuLabel(child: Text(context.i18n.getSupport)),
|
|
MenuButton(
|
|
leading: Icon(Icons.reddit_outlined),
|
|
onPressed: (c) {
|
|
launchUrlString('https://www.reddit.com/r/BikeControl/');
|
|
},
|
|
child: Text('Reddit'),
|
|
),
|
|
MenuButton(
|
|
leading: Icon(Icons.facebook_outlined),
|
|
onPressed: (c) {
|
|
launchUrlString('https://www.facebook.com/groups/1892836898778912');
|
|
},
|
|
child: Text('Facebook'),
|
|
),
|
|
MenuButton(
|
|
leading: Icon(RadixIcons.githubLogo),
|
|
onPressed: (c) {
|
|
launchUrlString('https://github.com/OpenBikeControl/bikecontrol/issues');
|
|
},
|
|
child: Text('GitHub'),
|
|
),
|
|
MenuButton(
|
|
leading: Icon(
|
|
LucideIcons.messageCircle,
|
|
color: _hasUnread ? Theme.of(context).colorScheme.destructive : null,
|
|
),
|
|
trailing: _hasUnread ? const _UnreadDot() : null,
|
|
child: _hasUnread
|
|
? Text(context.i18n.chatWithSupport).semiBold
|
|
: Text(context.i18n.chatWithSupport),
|
|
onPressed: (c) async {
|
|
final screenshot = await captureOverviewScreenshot(context: context);
|
|
// Gather diagnostics in the background so the chat opens
|
|
// immediately; the page awaits this future lazily for the
|
|
// preview and at send time (it resolves once and is reused).
|
|
final debugFuture = debugText();
|
|
await Navigator.of(context).push(
|
|
MaterialPageRoute(
|
|
builder: (_) => SupportChatPage(
|
|
diagnosticPreviewFuture: debugFuture,
|
|
initialAttachment: screenshot,
|
|
telemetryBuilder: () async =>
|
|
TelemetrySnapshot.general(freetext: await debugFuture),
|
|
),
|
|
),
|
|
);
|
|
if (mounted) {
|
|
setState(() => _hasUnread = false);
|
|
_checkForUnread();
|
|
}
|
|
},
|
|
),
|
|
],
|
|
),
|
|
);
|
|
},
|
|
leading: Padding(
|
|
padding: EdgeInsets.only(
|
|
bottom: isMobile
|
|
? MediaQuery.viewPaddingOf(context).bottom / MediaQuery.devicePixelRatioOf(context)
|
|
: 0,
|
|
),
|
|
child: Stack(
|
|
clipBehavior: Clip.none,
|
|
children: [
|
|
Icon(
|
|
LucideIcons.messageCircle,
|
|
color: _hasUnread ? Theme.of(context).colorScheme.destructive : null,
|
|
),
|
|
if (_hasUnread)
|
|
const Positioned(
|
|
right: -8,
|
|
top: -8,
|
|
child: _PulsingUnreadBadge(),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
style: ButtonStyle.secondary()
|
|
.withBorderRadius(
|
|
borderRadius: border,
|
|
hoverBorderRadius: border,
|
|
)
|
|
.withBorder(
|
|
border: Border.all(
|
|
width: _hasUnread ? 1.2 : 0.3,
|
|
color: _hasUnread
|
|
? Theme.of(context).colorScheme.destructive
|
|
: Theme.of(context).colorScheme.mutedForeground,
|
|
),
|
|
),
|
|
child: Padding(
|
|
padding: EdgeInsets.only(
|
|
bottom: isMobile
|
|
? MediaQuery.viewPaddingOf(context).bottom / MediaQuery.devicePixelRatioOf(context)
|
|
: 0,
|
|
),
|
|
child: Text(context.i18n.troubleshootingGuide),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
class _UnreadDot extends StatelessWidget {
|
|
const _UnreadDot();
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Container(
|
|
width: 10,
|
|
height: 10,
|
|
decoration: BoxDecoration(
|
|
color: Theme.of(context).colorScheme.destructive,
|
|
shape: BoxShape.circle,
|
|
border: Border.all(
|
|
color: Theme.of(context).colorScheme.background,
|
|
width: 1.5,
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Animated unread indicator: a red dot with a halo ring that pulses outward.
|
|
/// Used on the Help button's icon overlay so a new support reply is hard to miss.
|
|
class _PulsingUnreadBadge extends StatefulWidget {
|
|
const _PulsingUnreadBadge();
|
|
|
|
@override
|
|
State<_PulsingUnreadBadge> createState() => _PulsingUnreadBadgeState();
|
|
}
|
|
|
|
class _PulsingUnreadBadgeState extends State<_PulsingUnreadBadge> with SingleTickerProviderStateMixin {
|
|
late final AnimationController _controller;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_controller = AnimationController(
|
|
vsync: this,
|
|
duration: const Duration(milliseconds: 1400),
|
|
)..repeat();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_controller.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final destructive = Theme.of(context).colorScheme.destructive;
|
|
final scaleTween = Tween<double>(begin: 1.0, end: 2.6).animate(
|
|
CurvedAnimation(parent: _controller, curve: Curves.easeOut),
|
|
);
|
|
final opacityTween = Tween<double>(begin: 0.55, end: 0.0).animate(
|
|
CurvedAnimation(parent: _controller, curve: Curves.easeOut),
|
|
);
|
|
|
|
return IgnorePointer(
|
|
child: SizedBox(
|
|
width: 24,
|
|
height: 24,
|
|
child: Stack(
|
|
alignment: Alignment.center,
|
|
children: [
|
|
AnimatedBuilder(
|
|
animation: _controller,
|
|
builder: (_, _) => Transform.scale(
|
|
scale: scaleTween.value,
|
|
child: Opacity(
|
|
opacity: opacityTween.value,
|
|
child: Container(
|
|
width: 10,
|
|
height: 10,
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: destructive,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
const _UnreadDot(),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
class _InstructionVideosDrawer extends StatefulWidget {
|
|
const _InstructionVideosDrawer();
|
|
|
|
@override
|
|
State<_InstructionVideosDrawer> createState() => _InstructionVideosDrawerState();
|
|
}
|
|
|
|
class _InstructionVideosDrawerState extends State<_InstructionVideosDrawer> {
|
|
static const _channelId = 'UCPuQFntEz__QxznGqNPmpsw';
|
|
late Future<List<_InstructionVideo>> _videosFuture;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_videosFuture = _fetchVideos();
|
|
}
|
|
|
|
void _retry() {
|
|
setState(() {
|
|
_videosFuture = _fetchVideos();
|
|
});
|
|
}
|
|
|
|
Future<List<_InstructionVideo>> _fetchVideos() async {
|
|
final uri = Uri.parse('https://www.youtube.com/feeds/videos.xml?channel_id=$_channelId');
|
|
final response = await http.get(uri);
|
|
if (response.statusCode != 200) {
|
|
throw Exception('Failed to load videos');
|
|
}
|
|
|
|
final entryRegex = RegExp(r'<entry>([\s\S]*?)</entry>');
|
|
final videos = <_InstructionVideo>[];
|
|
for (final match in entryRegex.allMatches(response.body)) {
|
|
final entry = match.group(1) ?? '';
|
|
final url = _extract(entry, RegExp(r'<link[^>]*rel="alternate"[^>]*href="([^"]+)"'));
|
|
if (url == null || url.isEmpty) {
|
|
continue;
|
|
}
|
|
|
|
final title = _normalizeTitle(
|
|
_decodeXmlEntities(_extract(entry, RegExp(r'<title>([\s\S]*?)</title>')) ?? 'YouTube Video'),
|
|
);
|
|
final description = _decodeXmlEntities(
|
|
_extract(entry, RegExp(r'<media:description>([\s\S]*?)</media:description>')) ?? '',
|
|
).trim();
|
|
final videoId = _extract(entry, RegExp(r'<yt:videoId>([^<]+)</yt:videoId>'));
|
|
final feedThumbnail = _extract(entry, RegExp(r'<media:thumbnail[^>]*url="([^"]+)"'));
|
|
final thumbnailUrl =
|
|
feedThumbnail ??
|
|
(videoId == null || videoId.isEmpty
|
|
? 'https://img.youtube.com/vi/default/hqdefault.jpg'
|
|
: 'https://img.youtube.com/vi/$videoId/hqdefault.jpg');
|
|
|
|
final uri = Uri.tryParse(url);
|
|
final isShort = uri?.pathSegments.contains('shorts') ?? url.contains('/shorts/');
|
|
videos.add(
|
|
_InstructionVideo(
|
|
url: url,
|
|
title: title,
|
|
description: description,
|
|
thumbnailUrl: thumbnailUrl,
|
|
isShort: isShort,
|
|
),
|
|
);
|
|
}
|
|
|
|
return videos;
|
|
}
|
|
|
|
String? _extract(String value, RegExp regex) {
|
|
final match = regex.firstMatch(value);
|
|
if (match == null) {
|
|
return null;
|
|
}
|
|
return match.group(1)?.trim();
|
|
}
|
|
|
|
String _decodeXmlEntities(String input) {
|
|
return input
|
|
.replaceAll('&', '&')
|
|
.replaceAll('"', '"')
|
|
.replaceAll(''', "'")
|
|
.replaceAll('<', '<')
|
|
.replaceAll('>', '>');
|
|
}
|
|
|
|
String _normalizeTitle(String title) {
|
|
const prefix = 'BikeControl - ';
|
|
if (title.startsWith(prefix)) {
|
|
return title.substring(prefix.length).trim();
|
|
}
|
|
return title.trim();
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Padding(
|
|
padding: const EdgeInsets.all(16),
|
|
child: Column(
|
|
spacing: 8,
|
|
children: [
|
|
ColoredTitle(text: 'Instruction Videos'),
|
|
Expanded(
|
|
child: FutureBuilder<List<_InstructionVideo>>(
|
|
future: _videosFuture,
|
|
builder: (context, snapshot) {
|
|
if (snapshot.connectionState == ConnectionState.waiting) {
|
|
return _statusCard(text: 'Loading videos...');
|
|
}
|
|
|
|
if (snapshot.hasError) {
|
|
return _statusCard(
|
|
text: 'Could not load videos from YouTube.',
|
|
action: SecondaryButton(
|
|
onPressed: _retry,
|
|
child: const Text('Retry'),
|
|
),
|
|
);
|
|
}
|
|
|
|
final videos = snapshot.data ?? <_InstructionVideo>[];
|
|
if (videos.isEmpty) {
|
|
return _statusCard(
|
|
text: 'No videos found on the channel right now.',
|
|
action: SecondaryButton(
|
|
onPressed: _retry,
|
|
child: const Text('Retry'),
|
|
),
|
|
);
|
|
}
|
|
|
|
final regularVideos = videos.where((video) => !video.isShort).toList();
|
|
final shortVideos = videos.where((video) => video.isShort).toList();
|
|
|
|
return SingleChildScrollView(
|
|
physics: ClampingScrollPhysics(),
|
|
child: Column(
|
|
spacing: 12,
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
for (final video in regularVideos)
|
|
SizedBox(
|
|
height: 280,
|
|
child: _buildVideoCard(video, fullWidth: true),
|
|
),
|
|
if (shortVideos.isNotEmpty)
|
|
LayoutBuilder(
|
|
builder: (context, constraints) {
|
|
final crossAxisCount = (constraints.maxWidth / 280).floor().clamp(1, 4);
|
|
return GridView.builder(
|
|
shrinkWrap: true,
|
|
physics: const NeverScrollableScrollPhysics(),
|
|
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
|
crossAxisCount: crossAxisCount,
|
|
mainAxisSpacing: 12,
|
|
crossAxisSpacing: 12,
|
|
childAspectRatio: 0.9,
|
|
),
|
|
itemCount: shortVideos.length,
|
|
itemBuilder: (context, index) {
|
|
return _buildVideoCard(shortVideos[index], fullWidth: false);
|
|
},
|
|
);
|
|
},
|
|
),
|
|
],
|
|
),
|
|
);
|
|
},
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _statusCard({required String text, Widget? action}) {
|
|
return Center(
|
|
child: Container(
|
|
width: 420,
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
borderRadius: BorderRadius.circular(12),
|
|
border: Border.all(color: Colors.gray.withAlpha(100)),
|
|
),
|
|
child: Column(
|
|
spacing: 12,
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Text(text, textAlign: TextAlign.center),
|
|
if (action != null) action,
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildVideoCard(_InstructionVideo video, {required bool fullWidth}) {
|
|
return GestureDetector(
|
|
onTap: () => launchUrlString(video.url),
|
|
child: Container(
|
|
decoration: BoxDecoration(
|
|
borderRadius: BorderRadius.circular(12),
|
|
border: Border.all(color: Colors.gray.withAlpha(100)),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
Expanded(
|
|
child: ClipRRect(
|
|
borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
|
|
child: Stack(
|
|
fit: StackFit.expand,
|
|
children: [
|
|
Image.network(video.thumbnailUrl, fit: BoxFit.cover),
|
|
Center(
|
|
child: Container(
|
|
padding: const EdgeInsets.all(10),
|
|
decoration: BoxDecoration(
|
|
color: Colors.black.withAlpha(166),
|
|
shape: BoxShape.circle,
|
|
),
|
|
child: const Icon(Icons.play_arrow, color: Colors.white),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
Padding(
|
|
padding: const EdgeInsets.all(10),
|
|
child: Column(
|
|
spacing: 6,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
video.title,
|
|
maxLines: fullWidth ? 3 : 2,
|
|
overflow: TextOverflow.ellipsis,
|
|
),
|
|
if (video.description.isNotEmpty)
|
|
Text(
|
|
video.description,
|
|
maxLines: fullWidth ? 4 : 2,
|
|
overflow: TextOverflow.ellipsis,
|
|
).xSmall.muted,
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
class _InstructionVideo {
|
|
final String url;
|
|
final String title;
|
|
final String description;
|
|
final String thumbnailUrl;
|
|
final bool isShort;
|
|
|
|
const _InstructionVideo({
|
|
required this.url,
|
|
required this.title,
|
|
required this.description,
|
|
required this.thumbnailUrl,
|
|
required this.isShort,
|
|
});
|
|
}
|