Files
flutter/lib/features/mapflow/presentation/mapflow_shell.dart
T
Ruslan Bakiev e641837815
Build and deploy Flutter Web / build (push) Successful in 2m30s
Launch add review through URL route params
2026-06-13 00:46:55 +07:00

1819 lines
51 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';
import 'package:latlong2/latlong.dart' hide Path;
import 'package:waveform_flutter/waveform_flutter.dart' show Amplitude;
import 'package:waveform_recorder/waveform_recorder.dart';
import '../../../app/router/app_router.dart';
import '../../../app/theme/mapflow_theme.dart';
import '../../../shared/auth/telegram_login_button.dart';
import '../../../shared/auth/telegram_session.dart' as telegram_session;
import '../application/place_cubit.dart';
import '../data/auth_repository.dart';
import '../data/places_repository.dart';
import '../domain/place_models.dart';
import 'widgets/place_photo_card.dart';
const _mapboxAccessToken = String.fromEnvironment('MAPBOX_ACCESS_TOKEN');
const _mapboxStyle = String.fromEnvironment(
'MAPBOX_STYLE',
defaultValue: 'mapbox/streets-v12',
);
class MapflowShell extends StatelessWidget {
const MapflowShell({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<PlaceCubit, PlaceViewState>(
builder: (context, viewState) {
return switch (viewState.status) {
PlaceLoadStatus.loading => const _MapLoading(),
PlaceLoadStatus.failure => _MapError(
message: viewState.errorMessage ?? '',
),
PlaceLoadStatus.ready =>
viewState.placeState!.hasTelegramAuth
? _MapContent(state: viewState.placeState!)
: _TelegramLoginScreen(
onAuthenticated: () => context.read<PlaceCubit>().load(),
),
};
},
);
}
}
class _MapContent extends StatelessWidget {
const _MapContent({required this.state});
static const _fallbackCenter = LatLng(10.7718, 106.6982);
final PlaceState state;
@override
Widget build(BuildContext context) {
final selected = state.selectedPlace;
final userCoordinate = state.userCoordinate;
final mapCenter = userCoordinate ?? selected?.coordinate ?? _fallbackCenter;
final placeCubit = context.read<PlaceCubit>();
final traitCounts = _countPlaceTraits(state.places);
final availableTraits = [
for (final trait in PlaceTrait.values)
if ((traitCounts[trait] ?? 0) > 0) trait,
];
final hasVoiceRecommendation =
state.voiceFilterTranscript.isNotEmpty ||
state.voiceFilterTags.isNotEmpty;
final hasRecommendationSurface =
hasVoiceRecommendation || state.selectedTrait != null;
return Scaffold(
body: Stack(
children: [
FlutterMap(
options: MapOptions(
initialCenter: mapCenter,
initialZoom: 14.2,
minZoom: 3,
maxZoom: 18,
),
children: [
const _BaseMapTileLayer(),
MarkerLayer(
markers: [
for (final place in state.recommendations)
Marker(
width: 52,
height: 52,
point: place.coordinate,
child: _PlaceMarker(
selected: selected?.id == place.id,
onTap: () => placeCubit.selectPlace(place.id),
),
),
if (userCoordinate != null)
Marker(
width: 30,
height: 30,
point: userCoordinate,
child: const _UserLocationMarker(),
),
],
),
const _MapAttribution(),
],
),
SafeArea(
child: Align(
alignment: Alignment.topLeft,
child: _UserAvatar(
user: state.currentUser,
onAdminReviews: state.currentUser?.isAdmin == true
? () => context.push('/admin/reviews')
: null,
onLogout: () {
telegram_session.clearMapflowSession();
placeCubit.load();
telegram_session.reloadApp();
},
),
),
),
Align(
alignment: Alignment.bottomCenter,
child: SafeArea(
top: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (hasRecommendationSurface)
_PlaceCarousel(
places: state.recommendations,
onSelect: (place) => placeCubit.selectPlace(place.id),
onFavoriteToggle: placeCubit.toggleFavorite,
),
_RecommendationControls(
active: hasRecommendationSurface,
traits: availableTraits,
selectedTrait: state.selectedTrait,
traitCounts: traitCounts,
onAddReview: () => _openAddFlow(
context,
userCoordinate ?? selected?.coordinate,
),
onVoice: placeCubit.recommendPlacesByVoice,
onClear: hasVoiceRecommendation
? () => unawaited(placeCubit.clearVoiceFilter())
: placeCubit.clearTrait,
),
],
),
),
),
],
),
);
}
void _openAddFlow(BuildContext context, LatLng? coordinate) {
context.push(
MapflowRoutes.addExperienceLocation(
coordinate: coordinate,
hasTelegramAuth: state.hasTelegramAuth,
),
);
}
}
Map<PlaceTrait, int> _countPlaceTraits(List<PlaceRecommendation> places) {
final counts = <PlaceTrait, int>{};
for (final place in places) {
for (final trait in place.traits) {
counts[trait] = (counts[trait] ?? 0) + 1;
}
}
return counts;
}
class _UserLocationMarker extends StatelessWidget {
const _UserLocationMarker();
@override
Widget build(BuildContext context) {
final color = Theme.of(context).colorScheme.primary;
return DecoratedBox(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: color.withValues(alpha: 0.18),
),
child: Center(
child: Container(
width: 14,
height: 14,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: color,
border: Border.all(color: Colors.white, width: 3),
),
),
),
);
}
}
class _UserAvatar extends StatelessWidget {
const _UserAvatar({
required this.user,
required this.onAdminReviews,
required this.onLogout,
});
final AppUser? user;
final VoidCallback? onAdminReviews;
final VoidCallback onLogout;
@override
Widget build(BuildContext context) {
final photoUrl = user?.photoUrl;
final imageUrl = photoUrl == null || photoUrl.isEmpty
? null
: _avatarImageUrl(photoUrl);
final fallback = _fallbackText();
return Padding(
padding: const EdgeInsets.only(left: 12, top: 8),
child: PopupMenuButton<_AvatarAction>(
tooltip: '',
offset: const Offset(0, 8),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
onSelected: (action) {
switch (action) {
case _AvatarAction.adminReviews:
onAdminReviews?.call();
case _AvatarAction.logout:
onLogout();
}
},
itemBuilder: (_) => [
if (onAdminReviews != null)
const PopupMenuItem<_AvatarAction>(
value: _AvatarAction.adminReviews,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.table_rows_outlined, size: 18),
SizedBox(width: 10),
Text('Отзывы'),
],
),
),
const PopupMenuItem<_AvatarAction>(
value: _AvatarAction.logout,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.logout, size: 18),
SizedBox(width: 10),
Text('Выйти'),
],
),
),
],
child: ClipOval(
child: SizedBox.square(
dimension: 44,
child: imageUrl == null
? _AvatarFallback(text: fallback)
: _AvatarImage(url: imageUrl, fallback: fallback),
),
),
),
);
}
String _fallbackText() {
final firstName = user?.firstName?.trim();
if (firstName != null && firstName.isNotEmpty) {
return firstName.characters.first.toUpperCase();
}
final username = user?.username?.trim();
if (username != null && username.isNotEmpty) {
return username.characters.first.toUpperCase();
}
return 'M';
}
String _avatarImageUrl(String photoUrl) {
final separator = photoUrl.contains('?') ? '&' : '?';
return '$photoUrl${separator}v=2';
}
}
class _RecommendationControls extends StatelessWidget {
const _RecommendationControls({
required this.active,
required this.traits,
required this.selectedTrait,
required this.traitCounts,
required this.onAddReview,
required this.onVoice,
required this.onClear,
});
final bool active;
final List<PlaceTrait> traits;
final PlaceTrait? selectedTrait;
final Map<PlaceTrait, int> traitCounts;
final VoidCallback onAddReview;
final Future<void> Function({
required String audioContentBase64,
required String audioMimeType,
})
onVoice;
final VoidCallback onClear;
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
return Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
child: Material(
color: tokens.mapPanel,
borderRadius: BorderRadius.circular(tokens.panelRadius),
child: Padding(
padding: const EdgeInsets.all(8),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton.filled(
onPressed: onAddReview,
icon: const Icon(Icons.add_location_alt_outlined),
tooltip: 'Добавить отзыв',
),
const SizedBox(width: 8),
Expanded(
child: FilledButton.icon(
onPressed: () => _openVoice(context),
icon: const Icon(Icons.mic_none_rounded, size: 18),
label: const Text('Голосом'),
),
),
const SizedBox(width: 8),
Expanded(
child: OutlinedButton.icon(
onPressed: traits.isEmpty ? null : () => _openTraits(context),
icon: const Icon(Icons.tune_rounded, size: 18),
label: const Text('Теги'),
),
),
if (active) ...[
const SizedBox(width: 4),
IconButton(
onPressed: onClear,
icon: const Icon(Icons.close_rounded),
tooltip: 'Сбросить',
),
],
],
),
),
),
);
}
Future<void> _openVoice(BuildContext context) async {
final result = await showDialog<_VoiceFilterAudio>(
context: context,
builder: (_) => const _VoiceFilterDialog(),
);
if (result == null) {
return;
}
await onVoice(
audioContentBase64: result.audioContentBase64,
audioMimeType: result.audioMimeType,
);
}
Future<void> _openTraits(BuildContext context) async {
await showModalBottomSheet<void>(
context: context,
showDragHandle: true,
builder: (sheetContext) {
return _TraitPickerSheet(
traits: traits,
selectedTrait: selectedTrait,
traitCounts: traitCounts,
onSelect: (trait) {
final controller = context.read<PlaceCubit>();
if (trait == selectedTrait) {
controller.clearTrait();
} else {
controller.selectTrait(trait);
}
Navigator.of(sheetContext).pop();
},
);
},
);
}
}
class _VoiceFilterAudio {
const _VoiceFilterAudio({
required this.audioContentBase64,
required this.audioMimeType,
});
final String audioContentBase64;
final String audioMimeType;
}
class _VoiceFilterDialog extends StatefulWidget {
const _VoiceFilterDialog();
@override
State<_VoiceFilterDialog> createState() => _VoiceFilterDialogState();
}
class _VoiceFilterDialogState extends State<_VoiceFilterDialog> {
final _waveController = WaveformRecorderController(
interval: const Duration(milliseconds: 60),
config: const RecordConfig(
numChannels: 1,
sampleRate: 44100,
autoGain: true,
echoCancel: true,
noiseSuppress: true,
),
);
var _recording = false;
var _submitting = false;
var _hasRecording = false;
@override
void dispose() {
_waveController.dispose();
super.dispose();
}
Future<void> _toggleRecording() async {
if (_recording) {
await _waveController.stopRecording();
setState(() {
_recording = false;
_hasRecording = true;
});
return;
}
await _waveController.startRecording();
setState(() => _recording = true);
}
Future<void> _apply() async {
if (_recording) {
await _waveController.stopRecording();
setState(() {
_recording = false;
_hasRecording = true;
});
}
final file = _waveController.file;
if (file == null) {
throw StateError('Voice filter recording file is required.');
}
setState(() => _submitting = true);
final bytes = await file.readAsBytes();
if (!mounted) {
return;
}
Navigator.of(context).pop(
_VoiceFilterAudio(
audioContentBase64: base64Encode(bytes),
audioMimeType: file.mimeType ?? 'audio/wav',
),
);
}
@override
Widget build(BuildContext context) {
return AlertDialog(
contentPadding: const EdgeInsets.fromLTRB(18, 18, 18, 8),
content: SizedBox(
width: 260,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
IconButton.filled(
onPressed: _submitting ? null : _toggleRecording,
icon: Icon(_recording ? Icons.stop_rounded : Icons.mic_rounded),
iconSize: 34,
style: IconButton.styleFrom(
fixedSize: const Size.square(82),
minimumSize: const Size.square(82),
),
tooltip: _recording ? 'Стоп' : 'Записать',
),
const SizedBox(height: 16),
Text(
_recording ? 'Слушаю' : 'Голосовой фильтр',
style: const TextStyle(fontWeight: FontWeight.w900),
),
],
),
),
actions: [
TextButton(
onPressed: _submitting ? null : () => Navigator.of(context).pop(),
child: const Text('Отмена'),
),
FilledButton(
onPressed: _submitting || !_hasRecording ? null : _apply,
child: _submitting
? const SizedBox.square(
dimension: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Применить'),
),
],
);
}
}
enum _AvatarAction { adminReviews, logout }
class _AvatarImage extends StatelessWidget {
const _AvatarImage({required this.url, required this.fallback});
final String url;
final String fallback;
@override
Widget build(BuildContext context) {
if (url.endsWith('.svg') || url.contains('.svg?')) {
return SvgPicture.network(
url,
fit: BoxFit.cover,
placeholderBuilder: (_) => _AvatarFallback(text: fallback),
errorBuilder: (_, _, _) => _AvatarFallback(text: fallback),
);
}
return Image.network(
url,
fit: BoxFit.cover,
errorBuilder: (_, _, _) => _AvatarFallback(text: fallback),
);
}
}
class _AvatarFallback extends StatelessWidget {
const _AvatarFallback({required this.text});
final String text;
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
return ColoredBox(
color: tokens.mapPanel,
child: Center(
child: Text(
text,
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
fontWeight: FontWeight.w900,
),
),
),
);
}
}
class _TelegramLoginScreen extends StatefulWidget {
const _TelegramLoginScreen({required this.onAuthenticated});
final VoidCallback onAuthenticated;
@override
State<_TelegramLoginScreen> createState() => _TelegramLoginScreenState();
}
class _TelegramLoginScreenState extends State<_TelegramLoginScreen> {
late final AuthRepository _authRepository;
var _loading = false;
var _message = '';
@override
void initState() {
super.initState();
_authRepository = context.read<AuthRepository>();
final urlToken = telegram_session.telegramLoginTokenFromUrl();
if (urlToken.isNotEmpty) {
_completeLogin(urlToken);
}
}
Future<void> _startLogin() async {
setState(() {
_loading = true;
_message = '';
});
final login = await _authRepository.startTelegramBotLogin();
telegram_session.openExternalUrl(login.botUrl);
setState(() {
_loading = false;
_message = '';
});
}
Future<void> _completeLogin(String token) async {
setState(() {
_loading = true;
_message = '';
});
final session = await _authRepository.completeTelegramBotLogin(token);
telegram_session.saveMapflowSessionToken(session.sessionToken);
widget.onAuthenticated();
telegram_session.reloadApp();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: SizedBox(
width: 320,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'MapFlow',
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.w900,
letterSpacing: 0,
),
),
const SizedBox(height: 24),
TelegramLoginButton(onPressed: _startLogin, loading: _loading),
if (_message.isNotEmpty) ...[
const SizedBox(height: 14),
Text(
_message,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium,
),
],
],
),
),
),
),
);
}
}
class _MapLoading extends StatelessWidget {
const _MapLoading();
@override
Widget build(BuildContext context) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
}
class _MapError extends StatelessWidget {
const _MapError({required this.message});
final String message;
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
return Scaffold(
body: Stack(
children: [
FlutterMap(
options: const MapOptions(
initialCenter: LatLng(10.7718, 106.6982),
initialZoom: 14.2,
),
children: [const _BaseMapTileLayer(), const _MapAttribution()],
),
SafeArea(
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
margin: const EdgeInsets.all(12),
padding: const EdgeInsets.all(12),
color: tokens.mapPanel,
child: Text(
message,
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
),
),
],
),
);
}
}
class _BaseMapTileLayer extends StatelessWidget {
const _BaseMapTileLayer();
static const _osmUrl = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
@override
Widget build(BuildContext context) {
if (_mapboxAccessToken.isEmpty) {
return TileLayer(
urlTemplate: _osmUrl,
userAgentPackageName: 'com.mapflow.app',
);
}
return TileLayer(
urlTemplate:
'https://api.mapbox.com/styles/v1/$_mapboxStyle/tiles/512/{z}/{x}/{y}@2x'
'?access_token=$_mapboxAccessToken',
tileDimension: 512,
zoomOffset: -1,
maxNativeZoom: 22,
userAgentPackageName: 'com.mapflow.app',
);
}
}
class _MapAttribution extends StatelessWidget {
const _MapAttribution();
@override
Widget build(BuildContext context) {
if (_mapboxAccessToken.isEmpty) {
return const RichAttributionWidget(
attributions: [TextSourceAttribution('OpenStreetMap contributors')],
);
}
return const RichAttributionWidget(
attributions: [
TextSourceAttribution('Mapbox', prependCopyright: false),
TextSourceAttribution('OpenStreetMap contributors'),
],
);
}
}
class _TraitPickerSheet extends StatelessWidget {
const _TraitPickerSheet({
required this.selectedTrait,
required this.traits,
required this.traitCounts,
required this.onSelect,
});
final PlaceTrait? selectedTrait;
final List<PlaceTrait> traits;
final Map<PlaceTrait, int> traitCounts;
final ValueChanged<PlaceTrait> onSelect;
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
return SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 18),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final item in traits)
ChoiceChip(
avatar: Icon(item.icon, size: 17),
label: Text('${item.label} ${traitCounts[item] ?? 0}'),
selected: item == selectedTrait,
onSelected: (_) => onSelect(item),
backgroundColor: tokens.mapPanel,
selectedColor: Theme.of(context).colorScheme.primaryContainer,
side: BorderSide.none,
shape: const StadiumBorder(),
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 9,
),
),
],
),
),
);
}
}
class _PlaceMarker extends StatelessWidget {
const _PlaceMarker({required this.selected, required this.onTap});
final bool selected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final color = Theme.of(context).colorScheme.primary;
final tokens = context.mapflowTokens;
return GestureDetector(
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 160),
decoration: BoxDecoration(
color: selected ? color : Colors.white,
shape: BoxShape.circle,
border: Border.all(color: color, width: selected ? 3 : 2),
boxShadow: [
BoxShadow(
color: tokens.mapShadow,
blurRadius: 14,
offset: const Offset(0, 8),
),
],
),
child: Icon(Icons.place, color: selected ? Colors.white : color),
),
);
}
}
class _PlaceCarousel extends StatelessWidget {
const _PlaceCarousel({
required this.places,
required this.onSelect,
required this.onFavoriteToggle,
});
final List<PlaceRecommendation> places;
final ValueChanged<PlaceRecommendation> onSelect;
final ValueChanged<PlaceRecommendation> onFavoriteToggle;
@override
Widget build(BuildContext context) {
if (places.isEmpty) {
return const SizedBox.shrink();
}
return SizedBox(
height: 172,
child: ListView.separated(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
itemCount: places.length,
separatorBuilder: (_, _) => const SizedBox(width: 10),
itemBuilder: (context, index) {
final place = places[index];
return PlacePhotoCard(
place: place,
onTap: () => onSelect(place),
onFavoriteToggle: () => onFavoriteToggle(place),
);
},
),
);
}
}
class AddExperienceFlow extends StatefulWidget {
const AddExperienceFlow({
super.key,
required this.coordinate,
required this.hasTelegramAuth,
});
final LatLng? coordinate;
final bool hasTelegramAuth;
@override
State<AddExperienceFlow> createState() => _AddExperienceFlowState();
}
class _AddExperienceFlowState extends State<AddExperienceFlow> {
static const _minimumInformationUnits = 16.0;
static const _nearbyPlaceRadiusMeters = 50;
static const _voicePromptHints = [
'атмосфера',
'еда',
'сервис',
'люди',
'шум',
'цены',
];
final _waveController = WaveformRecorderController(
interval: const Duration(milliseconds: 45),
config: const RecordConfig(
numChannels: 1,
sampleRate: 44100,
autoGain: true,
echoCancel: true,
noiseSuppress: true,
),
);
Future<List<PlaceRecommendation>>? _nearbyPlacesFuture;
StreamSubscription<Amplitude>? _amplitudeSub;
var _step = 0;
var _informationUnits = 0.0;
var _recording = false;
var _submitting = false;
var _micAllowed = true;
var _noiseDb = -72.0;
var _voicePeakDb = -34.0;
var _liveLevel = 0.0;
DateTime? _lastInformationAt;
PlaceRecommendation? _selectedPlaceForSubmit;
@override
void initState() {
super.initState();
}
@override
void dispose() {
_amplitudeSub?.cancel();
_waveController.dispose();
super.dispose();
}
Future<void> _toggleRecording() async {
if (_recording) {
await _stopRecording();
return;
}
await _startRecording();
}
Future<List<PlaceRecommendation>> _loadNearbyPlaces() async {
final coordinate = widget.coordinate;
if (coordinate == null) {
return const [];
}
return context.read<PlacesRepository>().fetchNearbyPlaces(
coordinate: coordinate,
radiusMeters: _nearbyPlaceRadiusMeters,
);
}
Future<void> _startRecording() async {
await _waveController.startRecording();
await _amplitudeSub?.cancel();
_lastInformationAt = DateTime.now();
_amplitudeSub = _waveController.amplitudeStream.listen(_handleAmplitude);
setState(() {
_micAllowed = true;
_recording = true;
_liveLevel = 0;
_informationUnits = 0;
});
}
Future<void> _stopRecording() async {
await _amplitudeSub?.cancel();
_amplitudeSub = null;
await _waveController.stopRecording();
_lastInformationAt = null;
if (!mounted) {
return;
}
setState(() {
_recording = false;
_liveLevel = 0;
});
}
void _handleAmplitude(Amplitude amplitude) {
final currentDb = amplitude.current;
final now = DateTime.now();
final level = _normalizeDbLevel(currentDb);
final informationDelta = _consumeInformationDelta(level, now);
setState(() {
_liveLevel = _smoothLevel(_liveLevel, level);
_informationUnits = math.min(
_minimumInformationUnits,
_informationUnits + informationDelta,
);
});
context.read<PlaceCubit>().setReviewDuration(_waveController.timeElapsed);
}
double _normalizeDbLevel(double currentDb) {
final db = currentDb.clamp(-160.0, 0.0);
if (db < _noiseDb) {
_noiseDb = _noiseDb * 0.90 + db * 0.10;
} else {
_noiseDb = _noiseDb * 0.995 + db * 0.005;
}
if (db > _voicePeakDb) {
_voicePeakDb = _voicePeakDb * 0.72 + db * 0.28;
} else {
_voicePeakDb = math.max(_noiseDb + 18, _voicePeakDb * 0.998 + db * 0.002);
}
final range = math.max(18.0, _voicePeakDb - _noiseDb);
final gated = ((db - _noiseDb - 5) / range).clamp(0.0, 1.0);
return math.pow(gated, 0.62).toDouble();
}
double _smoothLevel(double current, double next) {
final weight = next > current ? 0.46 : 0.18;
return current + (next - current) * weight;
}
double _consumeInformationDelta(double voicedAmount, DateTime now) {
final previous = _lastInformationAt ?? now;
_lastInformationAt = now;
final deltaSeconds =
now.difference(previous).inMilliseconds.clamp(20, 180) / 1000;
return voicedAmount.clamp(0.0, 1.0) * deltaSeconds;
}
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
final controller = context.read<PlaceCubit>();
final informationProgress = (_informationUnits / _minimumInformationUnits)
.clamp(0.0, 1.0);
final content = switch (_step) {
0 => _VoiceStep(
placeName: '',
promptHints: _voicePromptHints,
hasTelegramAuth: widget.hasTelegramAuth,
informationProgress: informationProgress,
isRecording: _recording,
isSubmitting: _submitting,
micAllowed: _micAllowed,
liveLevel: _liveLevel,
canContinue: widget.hasTelegramAuth && informationProgress >= 1,
onToggleRecording: _toggleRecording,
onNext: () async {
if (_recording) {
await _stopRecording();
}
setState(() {
_nearbyPlacesFuture = _loadNearbyPlaces();
_step = 1;
});
},
),
1 => _PlaceStep(
placesFuture: _nearbyPlacesFuture,
radiusMeters: _nearbyPlaceRadiusMeters,
isSubmitting: _submitting,
onSelect: (place) async {
controller.setReviewPlace(place.name);
setState(() {
_selectedPlaceForSubmit = place;
_step = 2;
});
},
),
_ => const SizedBox.shrink(),
};
final contentWithFavoriteStep = _step == 2
? _FavoriteStep(
place: _selectedPlaceForSubmit,
isSubmitting: _submitting,
onSubmit: _submitSelectedPlace,
)
: content;
return Scaffold(
backgroundColor: tokens.darkSurface,
body: SafeArea(
child: Padding(
padding: EdgeInsets.fromLTRB(
16,
10,
16,
MediaQuery.viewInsetsOf(context).bottom + 18,
),
child: Column(
children: [
_StoryProgress(
step: _step,
total: 3,
dark: true,
onClose: () => context.pop(),
),
const SizedBox(height: 18),
Expanded(
child: AnimatedSwitcher(
duration: const Duration(milliseconds: 220),
child: KeyedSubtree(
key: ValueKey(_step),
child: contentWithFavoriteStep,
),
),
),
],
),
),
),
);
}
Future<void> _submitSelectedPlace(bool addToFavorites) async {
final place = _selectedPlaceForSubmit;
if (place == null) {
throw StateError('Place is required to publish a review.');
}
setState(() => _submitting = true);
final controller = context.read<PlaceCubit>();
final file = _waveController.file;
if (file == null) {
throw StateError('Voice recording file is required.');
}
final bytes = await file.readAsBytes();
await controller.publishReview(
place: place,
audioObjectKey:
'web-recording-${DateTime.now().microsecondsSinceEpoch}-${file.name}',
audioContentBase64: base64Encode(bytes),
audioMimeType: file.mimeType ?? 'audio/wav',
addToFavorites: addToFavorites,
promptHintsShown: _voicePromptHints,
recordingPayload: {
'source': 'web',
'nearbyPlaceRadiusMeters': _nearbyPlaceRadiusMeters,
'informationUnits': _informationUnits,
'minimumInformationUnits': _minimumInformationUnits,
'selectedPlace': {
'googlePlaceId': place.googlePlaceId,
'name': place.name,
'googlePrimaryType': place.googlePrimaryType,
'googleTypes': place.googleTypes,
'latitude': place.coordinate.latitude,
'longitude': place.coordinate.longitude,
},
},
);
if (!mounted) {
return;
}
context.pop();
}
}
class _PlaceStep extends StatelessWidget {
const _PlaceStep({
required this.placesFuture,
required this.radiusMeters,
required this.isSubmitting,
required this.onSelect,
});
final Future<List<PlaceRecommendation>>? placesFuture;
final int radiusMeters;
final bool isSubmitting;
final Future<void> Function(PlaceRecommendation) onSelect;
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
return _StepLayout(
body: Column(
children: [
Text(
'Выбери место рядом',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
color: Colors.white,
fontWeight: FontWeight.w900,
letterSpacing: 0,
),
),
const SizedBox(height: 16),
Expanded(
child: FutureBuilder<List<PlaceRecommendation>>(
future: placesFuture,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return Center(
child: CircularProgressIndicator(color: tokens.voiceAccent),
);
}
if (snapshot.hasError) {
return Center(
child: Icon(
Icons.error_outline,
color: tokens.onDark,
size: 42,
),
);
}
final places = snapshot.data ?? const <PlaceRecommendation>[];
if (places.isEmpty) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.location_off_outlined,
color: tokens.onDark,
size: 42,
),
const SizedBox(height: 10),
Text(
'Нет мест в $radiusMetersм',
style: TextStyle(color: tokens.onDark),
),
],
),
);
}
return ListView.separated(
itemCount: places.length,
separatorBuilder: (_, _) => const SizedBox(height: 10),
itemBuilder: (context, index) {
final place = places[index];
return _NearbyPlaceCard(
place: place,
disabled: isSubmitting,
onTap: () => onSelect(place),
);
},
);
},
),
),
],
),
);
}
}
class _FavoriteStep extends StatelessWidget {
const _FavoriteStep({
required this.place,
required this.isSubmitting,
required this.onSubmit,
});
final PlaceRecommendation? place;
final bool isSubmitting;
final Future<void> Function(bool) onSubmit;
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
final selectedPlace = place;
if (selectedPlace == null) {
return const SizedBox.shrink();
}
return _StepLayout(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.favorite_border, color: tokens.onDark, size: 48),
const SizedBox(height: 18),
Text(
selectedPlace.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
color: tokens.onDark,
fontWeight: FontWeight.w900,
letterSpacing: 0,
),
),
const SizedBox(height: 26),
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: isSubmitting ? null : () => onSubmit(false),
child: const Text('Не сейчас'),
),
),
const SizedBox(width: 10),
Expanded(
child: FilledButton(
onPressed: isSubmitting ? null : () => onSubmit(true),
child: isSubmitting
? const SizedBox.square(
dimension: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('В избранное'),
),
),
],
),
],
),
);
}
}
class _NearbyPlaceCard extends StatelessWidget {
const _NearbyPlaceCard({
required this.place,
required this.disabled,
required this.onTap,
});
final PlaceRecommendation place;
final bool disabled;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final primaryType = _formatType(place.googlePrimaryType);
final tokens = context.mapflowTokens;
return Material(
color: tokens.darkSurfaceAlt,
borderRadius: BorderRadius.circular(tokens.panelRadius),
child: InkWell(
onTap: disabled ? null : onTap,
borderRadius: BorderRadius.circular(tokens.panelRadius),
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
Icons.place_outlined,
color: tokens.onDark.withValues(alpha: 0.70),
),
const SizedBox(width: 10),
Expanded(
child: Text(
place.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: tokens.onDark,
fontWeight: FontWeight.w900,
height: 1.1,
),
),
),
],
),
if (primaryType != null) ...[
const SizedBox(height: 12),
Wrap(
spacing: 6,
runSpacing: 6,
children: [_PlaceTypeChip(label: primaryType, primary: true)],
),
],
],
),
),
),
);
}
String? _formatType(String? type) {
if (type == null || type.isEmpty) {
return null;
}
return type.replaceAll('_', ' ');
}
}
class _PlaceTypeChip extends StatelessWidget {
const _PlaceTypeChip({required this.label, required this.primary});
final String label;
final bool primary;
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
return DecoratedBox(
decoration: BoxDecoration(
color: primary
? tokens.voiceAccent
: tokens.onDark.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(tokens.panelRadius),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
child: Text(
label,
style: TextStyle(
color: primary
? tokens.onDark
: tokens.onDark.withValues(alpha: 0.92),
fontSize: 12,
fontWeight: FontWeight.w700,
height: 1,
),
),
),
);
}
}
class _VoiceStep extends StatelessWidget {
const _VoiceStep({
required this.placeName,
required this.promptHints,
required this.hasTelegramAuth,
required this.informationProgress,
required this.isRecording,
required this.isSubmitting,
required this.micAllowed,
required this.liveLevel,
required this.canContinue,
required this.onToggleRecording,
required this.onNext,
});
final String placeName;
final List<String> promptHints;
final bool hasTelegramAuth;
final double informationProgress;
final bool isRecording;
final bool isSubmitting;
final bool micAllowed;
final double liveLevel;
final bool canContinue;
final Future<void> Function() onToggleRecording;
final VoidCallback onNext;
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
final canFinish = canContinue;
return Column(
children: [
if (placeName.trim().isNotEmpty) ...[
Text(
placeName.trim(),
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: Theme.of(
context,
).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w900),
),
const SizedBox(height: 10),
],
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Wrap(
alignment: WrapAlignment.center,
spacing: 6,
runSpacing: 6,
children: [
for (final hint in promptHints)
Chip(
label: Text(hint),
side: BorderSide.none,
backgroundColor: tokens.onDark.withValues(alpha: 0.12),
labelStyle: TextStyle(
color: tokens.onDark.withValues(alpha: 0.92),
fontWeight: FontWeight.w700,
),
),
],
),
),
Expanded(child: _VoiceProgressGrid(progress: informationProgress)),
if (!micAllowed)
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Icon(
Icons.mic_off_outlined,
color: tokens.voiceAccentSoft,
size: 22,
),
),
_VoiceRecordButton(
progress: informationProgress,
liveLevel: liveLevel,
isRecording: isRecording,
canFinish: canFinish,
enabled: hasTelegramAuth && !isSubmitting,
onPressed: canFinish ? onNext : onToggleRecording,
),
],
);
}
}
class _VoiceProgressGrid extends StatelessWidget {
const _VoiceProgressGrid({required this.progress});
final double progress;
@override
Widget build(BuildContext context) {
const columns = 18;
const rows = 12;
const total = columns * rows;
final filled = (progress.clamp(0.0, 1.0) * total).round();
return LayoutBuilder(
builder: (context, constraints) {
const gap = 4.0;
final maxCellWidth =
(constraints.maxWidth - gap * (columns - 1)) / columns;
final maxCellHeight = (constraints.maxHeight - gap * (rows - 1)) / rows;
final cellSize = math.max(
10.0,
math.min(maxCellWidth, maxCellHeight).clamp(10.0, 28.0),
);
final gridWidth = columns * cellSize + gap * (columns - 1);
final gridHeight = rows * cellSize + gap * (rows - 1);
return Center(
child: SizedBox(
width: gridWidth,
height: gridHeight,
child: Wrap(
spacing: gap,
runSpacing: gap,
children: [
for (var index = 0; index < total; index++)
_VoiceProgressCell(
filled: _gridOrder(index, columns, rows) < filled,
size: cellSize,
),
],
),
),
);
},
);
}
static int _gridOrder(int index, int columns, int rows) {
final row = index ~/ columns;
final column = index % columns;
final centerX = (columns - 1) / 2;
final centerY = (rows - 1) / 2;
final dx = column - centerX;
final dy = row - centerY;
final radius = math.sqrt(dx * dx + dy * dy);
final angle = math.atan2(dy, dx);
final shell = (radius * 7.0 + angle * 5.0).floor();
final noise = (math.sin((column + 1) * 37.17 + (row + 1) * 91.43) * 10000)
.abs();
return ((shell * 31 + noise.floor()) % (columns * rows));
}
}
class _VoiceProgressCell extends StatelessWidget {
const _VoiceProgressCell({required this.filled, required this.size});
final bool filled;
final double size;
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
return AnimatedContainer(
duration: const Duration(milliseconds: 180),
curve: Curves.easeOutCubic,
width: size,
height: size,
decoration: BoxDecoration(
color: filled
? tokens.voiceAccent
: tokens.onDark.withValues(alpha: 0.11),
borderRadius: BorderRadius.circular(3),
boxShadow: filled
? [
BoxShadow(
color: tokens.voiceAccent.withValues(alpha: 0.34),
blurRadius: 12,
spreadRadius: 1,
),
]
: null,
),
);
}
}
class _VoiceRecordButton extends StatefulWidget {
const _VoiceRecordButton({
required this.progress,
required this.liveLevel,
required this.isRecording,
required this.canFinish,
required this.enabled,
required this.onPressed,
});
final double progress;
final double liveLevel;
final bool isRecording;
final bool canFinish;
final bool enabled;
final VoidCallback onPressed;
@override
State<_VoiceRecordButton> createState() => _VoiceRecordButtonState();
}
class _VoiceRecordButtonState extends State<_VoiceRecordButton>
with SingleTickerProviderStateMixin {
late final AnimationController _pulseController;
@override
void initState() {
super.initState();
_pulseController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1400),
);
_syncPulse();
}
@override
void didUpdateWidget(covariant _VoiceRecordButton oldWidget) {
super.didUpdateWidget(oldWidget);
_syncPulse();
}
@override
void dispose() {
_pulseController.dispose();
super.dispose();
}
void _syncPulse() {
if (widget.isRecording && !_pulseController.isAnimating) {
_pulseController.repeat();
}
if (!widget.isRecording && _pulseController.isAnimating) {
_pulseController.stop();
_pulseController.value = 0;
}
}
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
return SizedBox(
width: 280,
height: 280,
child: AnimatedBuilder(
animation: _pulseController,
builder: (context, child) {
final pulse = widget.isRecording ? _pulseController.value : 0.0;
final level = widget.isRecording ? widget.liveLevel : 0.0;
return Stack(
alignment: Alignment.center,
children: [
for (final offset in const [0.0, 0.32, 0.64])
Transform.scale(
scale:
1 +
((pulse + offset) % 1) * (0.20 + level * 0.44) +
level * 0.16,
child: Container(
width: 190,
height: 190,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: tokens.voiceAccent.withValues(
alpha: widget.isRecording
? ((0.06 + level * 0.26) *
(1 - ((pulse + offset) % 1)))
: 0,
),
width: 2.5 + level * 2.5,
),
),
),
),
SizedBox(
width: 216,
height: 216,
child: CircularProgressIndicator(
value: widget.progress,
strokeWidth: 8,
strokeCap: StrokeCap.round,
color: tokens.voiceAccent,
backgroundColor: tokens.onDark.withValues(alpha: 0.12),
),
),
child!,
],
);
},
child: SizedBox(
width: 156,
height: 156,
child: FilledButton(
onPressed: widget.enabled ? widget.onPressed : null,
style: FilledButton.styleFrom(
backgroundColor: tokens.onDark,
foregroundColor: tokens.onVoiceControl,
disabledBackgroundColor: tokens.onDark.withValues(alpha: 0.28),
disabledForegroundColor: tokens.onDark.withValues(alpha: 0.52),
shape: const CircleBorder(),
padding: EdgeInsets.zero,
elevation: 0,
),
child: Icon(
widget.canFinish
? Icons.check_rounded
: widget.isRecording
? Icons.pause_rounded
: Icons.mic_rounded,
size: 56,
),
),
),
),
);
}
}
class _StepLayout extends StatelessWidget {
const _StepLayout({required this.body});
final Widget body;
@override
Widget build(BuildContext context) {
return Column(children: [Expanded(child: body)]);
}
}
class _StoryProgress extends StatelessWidget {
const _StoryProgress({
required this.step,
required this.total,
required this.dark,
required this.onClose,
});
final int step;
final int total;
final bool dark;
final VoidCallback onClose;
@override
Widget build(BuildContext context) {
final tokens = context.mapflowTokens;
return Row(
children: [
Expanded(
child: Row(
children: [
for (var index = 0; index < total; index++) ...[
Expanded(
child: AnimatedContainer(
duration: const Duration(milliseconds: 180),
height: 5,
decoration: BoxDecoration(
color: index <= step
? (dark
? tokens.voiceAccent
: Theme.of(context).colorScheme.primary)
: (dark
? tokens.onDark.withValues(alpha: 0.16)
: tokens.mapPanelBorder),
borderRadius: BorderRadius.circular(99),
),
),
),
if (index != total - 1) const SizedBox(width: 6),
],
],
),
),
const SizedBox(width: 10),
IconButton(
onPressed: onClose,
icon: Icon(Icons.close, color: dark ? Colors.white : null),
tooltip: 'Закрыть',
),
],
);
}
}