diff --git a/lib/core/widgets/shared_forms/attachments_section.dart b/lib/core/widgets/shared_forms/attachments_section.dart index f03e1e4..54d669d 100644 --- a/lib/core/widgets/shared_forms/attachments_section.dart +++ b/lib/core/widgets/shared_forms/attachments_section.dart @@ -283,22 +283,35 @@ class _SharedAttachmentsSectionState extends State { } // --- APERTURA VIEWER --- - void _openFile(AttachmentModel file) { + void _openFile( + AttachmentModel file, { + List? files, + int? initialIndex, + }) { // 1. Catturiamo il BLoC dalla pagina corrente prima di navigare final operationFilesBloc = context.read(); + final allFilesList = files ?? operationFilesBloc.state.allFiles; + final index = initialIndex ?? + (allFilesList.isNotEmpty ? allFilesList.indexOf(file) : 0); + Navigator.push( context, MaterialPageRoute( builder: (viewerContext) => BlocProvider.value( value: operationFilesBloc, child: AttachmentViewerScreen( - attachment: file, - onRename: (newName) { + attachments: allFilesList.isNotEmpty ? allFilesList : [file], + initialIndex: index >= 0 ? index : 0, + onRenameAttachment: (targetFile, newName) { // Spara l'evento al BLoC e lui farà il resto! - operationFilesBloc.add(RenameAttachmentEvent(file, newName)); + operationFilesBloc.add( + RenameAttachmentEvent(targetFile, newName), + ); }, - onDelete: () { - operationFilesBloc.add(DeleteSpecificAttachmentEvent(file)); + onDeleteAttachment: (targetFile) { + operationFilesBloc.add( + DeleteSpecificAttachmentEvent(targetFile), + ); }, ), ), @@ -890,7 +903,11 @@ class _SharedAttachmentsSectionState extends State { children: [ // CARD DEL FILE InkWell( - onTap: () => _openFile(file), + onTap: () => _openFile( + file, + files: allFiles, + initialIndex: index, + ), onLongPress: () { // Selezione rapida con long press! context.read().add( diff --git a/lib/features/attachments/ui/attachment_viewer_screen.dart b/lib/features/attachments/ui/attachment_viewer_screen.dart index b1a9347..a801d94 100644 --- a/lib/features/attachments/ui/attachment_viewer_screen.dart +++ b/lib/features/attachments/ui/attachment_viewer_screen.dart @@ -1,110 +1,191 @@ -import 'dart:typed_data'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flux/core/utils/functions.dart'; import 'package:flux/features/attachments/models/attachment_model.dart'; import 'package:pdfx/pdfx.dart'; import 'package:internet_file/internet_file.dart'; class AttachmentViewerScreen extends StatefulWidget { - final AttachmentModel attachment; + final AttachmentModel? attachment; + final List? attachments; + final int initialIndex; final Function(String newName)? onRename; + final Function(AttachmentModel attachment, String newName)? onRenameAttachment; final VoidCallback? onDelete; + final Function(AttachmentModel attachment)? onDeleteAttachment; const AttachmentViewerScreen({ super.key, - required this.attachment, + this.attachment, + this.attachments, + this.initialIndex = 0, this.onRename, + this.onRenameAttachment, this.onDelete, - }); + this.onDeleteAttachment, + }) : assert( + attachment != null || (attachments != null && attachments.length > 0), + 'Devi fornire un allegato o una lista di allegati non vuota.', + ); @override State createState() => _AttachmentViewerScreenState(); } class _AttachmentViewerScreenState extends State { + late List _items; + late int _currentIndex; + final FocusNode _focusNode = FocusNode(); + PdfControllerPinch? _pdfController; bool _isLoading = true; String? _errorMessage; Uint8List? _fileBytes; - late String _fileName; + int _loadToken = 0; - bool get isPdf => widget.attachment.extension.toLowerCase() == 'pdf'; + AttachmentModel get _currentAttachment => _items[_currentIndex]; + bool get isPdf => + _currentAttachment.extension.toLowerCase().replaceAll('.', '') == 'pdf'; + bool get hasMultipleFiles => _items.length > 1; + bool get canGoPrevious => _currentIndex > 0; + bool get canGoNext => _currentIndex < _items.length - 1; @override void initState() { super.initState(); - _fileName = widget.attachment.name; - _loadFile(); - } - - Future _loadFile() async { - try { - // 1. Capiamo da dove prendere i dati - if (widget.attachment.localBytes != null) { - _fileBytes = widget.attachment.localBytes; - } else if (widget.attachment.storagePath != null && - widget.attachment.storagePath!.isNotEmpty) { - final signedUrl = await getSignedUrl(widget.attachment.storagePath!); - _fileBytes = await InternetFile.get(signedUrl); - } else { - throw Exception("Nessun documento trovato o byte mancanti."); - } - - // 2. Se è PDF, inizializziamo il controller - if (isPdf && _fileBytes != null) { - _pdfController = PdfControllerPinch( - document: PdfDocument.openData(_fileBytes!), - ); - } - - if (mounted) setState(() => _isLoading = false); - } catch (e) { - if (mounted) { - setState(() { - _isLoading = false; - _errorMessage = e.toString(); - }); - } + if (widget.attachments != null && widget.attachments!.isNotEmpty) { + _items = List.from(widget.attachments!); + _currentIndex = widget.initialIndex.clamp(0, _items.length - 1); + } else if (widget.attachment != null) { + _items = [widget.attachment!]; + _currentIndex = 0; + } else { + _items = []; + _currentIndex = 0; } + + _loadFile(); + + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _focusNode.requestFocus(); + } + }); } @override void dispose() { + _focusNode.dispose(); _pdfController?.dispose(); super.dispose(); } + void _goToPrevious() { + if (!canGoPrevious) return; + _changeFile(_currentIndex - 1); + } + + void _goToNext() { + if (!canGoNext) return; + _changeFile(_currentIndex + 1); + } + + void _changeFile(int newIndex) { + if (newIndex < 0 || newIndex >= _items.length) return; + _pdfController?.dispose(); + _pdfController = null; + setState(() { + _currentIndex = newIndex; + _isLoading = true; + _errorMessage = null; + _fileBytes = null; + }); + _loadFile(); + } + + KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) { + if (event is KeyDownEvent) { + if (event.logicalKey == LogicalKeyboardKey.arrowLeft) { + if (canGoPrevious) { + _goToPrevious(); + return KeyEventResult.handled; + } + } else if (event.logicalKey == LogicalKeyboardKey.arrowRight) { + if (canGoNext) { + _goToNext(); + return KeyEventResult.handled; + } + } + } + return KeyEventResult.ignored; + } + + Future _loadFile() async { + final token = ++_loadToken; + final item = _currentAttachment; + + try { + Uint8List? bytes; + if (item.localBytes != null) { + bytes = item.localBytes; + } else if (item.storagePath != null && + item.storagePath!.isNotEmpty) { + final signedUrl = await getSignedUrl(item.storagePath!); + bytes = await InternetFile.get(signedUrl); + } else { + throw Exception("Nessun documento trovato o byte mancanti."); + } + + if (token != _loadToken || !mounted) return; + + PdfControllerPinch? controller; + if (isPdf && bytes != null) { + controller = PdfControllerPinch( + document: PdfDocument.openData(bytes), + ); + } + + setState(() { + _fileBytes = bytes; + _pdfController = controller; + _isLoading = false; + }); + } catch (e) { + if (token != _loadToken || !mounted) return; + setState(() { + _isLoading = false; + _errorMessage = e.toString(); + }); + } + } + void _showRenameDialog() { - final ctrl = TextEditingController(text: _fileName); + final current = _currentAttachment; + final ctrl = TextEditingController(text: current.name); ctrl.selection = TextSelection( baseOffset: 0, extentOffset: ctrl.text.length, ); - final focusNode = FocusNode(); + final dialogFocusNode = FocusNode(); showDialog( context: context, builder: (context) { WidgetsBinding.instance.addPostFrameCallback( - (_) => focusNode.requestFocus(), + (_) => dialogFocusNode.requestFocus(), ); return AlertDialog( title: const Text('Rinomina File'), content: TextField( controller: ctrl, - focusNode: focusNode, + focusNode: dialogFocusNode, decoration: InputDecoration( labelText: 'Nuovo nome', - suffixText: '.${widget.attachment.extension}', + suffixText: '.${current.extension}', ), onSubmitted: (val) { Navigator.pop(context); - if (val.trim().isNotEmpty && widget.onRename != null) { - setState(() { - _fileName = val.trim(); - }); - widget.onRename!(val.trim()); - } + _applyRename(val); }, ), actions: [ @@ -115,73 +196,141 @@ class _AttachmentViewerScreenState extends State { ElevatedButton( onPressed: () { Navigator.pop(context); - if (ctrl.text.trim().isNotEmpty && widget.onRename != null) { - setState(() { - _fileName = ctrl.text.trim(); - }); - widget.onRename!(ctrl.text.trim()); - } + _applyRename(ctrl.text); }, child: const Text('Salva'), ), ], ); }, + ).then((_) { + if (mounted) { + _focusNode.requestFocus(); + } + }); + } + + void _applyRename(String val) { + final trimmed = val.trim(); + if (trimmed.isEmpty) return; + final current = _currentAttachment; + final updated = current.copyWith(name: trimmed); + setState(() { + _items[_currentIndex] = updated; + }); + widget.onRenameAttachment?.call(current, trimmed); + widget.onRename?.call(trimmed); + } + + void _confirmDelete() { + final current = _currentAttachment; + showDialog( + context: context, + builder: (c) => AlertDialog( + title: const Text('Eliminare file?'), + content: const Text( + 'Sei sicuro di voler eliminare questo allegato?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(c), + child: const Text('Annulla'), + ), + ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + ), + onPressed: () { + Navigator.pop(c); // Chiude dialog + widget.onDeleteAttachment?.call(current); + widget.onDelete?.call(); + Navigator.pop(context); // Chiude il viewer + }, + child: const Text('Elimina'), + ), + ], + ), ); } @override Widget build(BuildContext context) { - return Scaffold( - backgroundColor: Colors.black87, // Sfondo scuro per i viewer è il top - appBar: AppBar( - backgroundColor: Colors.black, - foregroundColor: Colors.white, - title: Text(_fileName, style: const TextStyle(fontSize: 16)), - actions: [ - if (widget.onRename != null) - IconButton( - icon: const Icon(Icons.edit), - tooltip: 'Rinomina', - onPressed: _showRenameDialog, + return Focus( + focusNode: _focusNode, + autofocus: true, + onKeyEvent: _handleKeyEvent, + child: Scaffold( + backgroundColor: Colors.black87, + appBar: AppBar( + backgroundColor: Colors.black, + foregroundColor: Colors.white, + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _currentAttachment.name, + style: const TextStyle(fontSize: 16), + overflow: TextOverflow.ellipsis, + ), + if (hasMultipleFiles) + Text( + '${_currentIndex + 1} di ${_items.length}', + style: const TextStyle(fontSize: 12, color: Colors.white70), + ), + ], + ), + actions: [ + if (widget.onRename != null || widget.onRenameAttachment != null) + IconButton( + icon: const Icon(Icons.edit), + tooltip: 'Rinomina', + onPressed: _showRenameDialog, + ), + if (widget.onDelete != null || widget.onDeleteAttachment != null) + IconButton( + icon: const Icon(Icons.delete, color: Colors.redAccent), + tooltip: 'Elimina', + onPressed: _confirmDelete, + ), + ], + ), + body: Stack( + children: [ + Positioned.fill( + child: _buildBody(), ), - if (widget.onDelete != null) - IconButton( - icon: const Icon(Icons.delete, color: Colors.redAccent), - tooltip: 'Elimina', - onPressed: () { - // Chiediamo conferma - showDialog( - context: context, - builder: (c) => AlertDialog( - title: const Text('Eliminare file?'), - content: const Text( - 'Sei sicuro di voler eliminare questo allegato?', - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(c), - child: const Text('Annulla'), - ), - ElevatedButton( - style: ElevatedButton.styleFrom( - backgroundColor: Colors.red, - ), - onPressed: () { - Navigator.pop(c); // Chiude dialog - widget.onDelete!(); // Lancia eliminazione - Navigator.pop(context); // Chiude il viewer - }, - child: const Text('Elimina'), - ), - ], + // Freccia Precedente + if (hasMultipleFiles && canGoPrevious) + Positioned( + left: 16, + top: 0, + bottom: 0, + child: Center( + child: _NavigationArrowButton( + icon: Icons.arrow_back_ios_new_rounded, + tooltip: 'File precedente (←)', + onPressed: _goToPrevious, ), - ); - }, - ), - ], + ), + ), + // Freccia Successivo + if (hasMultipleFiles && canGoNext) + Positioned( + right: 16, + top: 0, + bottom: 0, + child: Center( + child: _NavigationArrowButton( + icon: Icons.arrow_forward_ios_rounded, + tooltip: 'File successivo (→)', + onPressed: _goToNext, + ), + ), + ), + ], + ), ), - body: _buildBody(), ); } @@ -218,3 +367,41 @@ class _AttachmentViewerScreenState extends State { } } } + +class _NavigationArrowButton extends StatelessWidget { + final IconData icon; + final String tooltip; + final VoidCallback onPressed; + + const _NavigationArrowButton({ + required this.icon, + required this.tooltip, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + return Tooltip( + message: tooltip, + child: Material( + color: Colors.black.withValues(alpha: 0.55), + shape: const CircleBorder(), + clipBehavior: Clip.antiAlias, + elevation: 6, + child: InkWell( + onTap: onPressed, + hoverColor: Colors.white.withValues(alpha: 0.2), + splashColor: Colors.white.withValues(alpha: 0.3), + child: Padding( + padding: const EdgeInsets.all(12), + child: Icon( + icon, + color: Colors.white, + size: 28, + ), + ), + ), + ), + ); + } +} diff --git a/lib/features/tickets/ui/widgets/ticket_list_card.dart b/lib/features/tickets/ui/widgets/ticket_list_card.dart index d2c4586..085e2ab 100644 --- a/lib/features/tickets/ui/widgets/ticket_list_card.dart +++ b/lib/features/tickets/ui/widgets/ticket_list_card.dart @@ -26,22 +26,32 @@ class TicketListCard extends StatelessWidget { void _openFile({ required BuildContext context, required AttachmentModel file, + List? attachments, + int? initialIndex, }) { // 1. Catturiamo il BLoC dalla pagina corrente prima di navigare final operationFilesBloc = context.read(); + final list = attachments ?? [file]; + final index = initialIndex ?? (list.isNotEmpty ? list.indexOf(file) : 0); + Navigator.push( context, MaterialPageRoute( builder: (viewerContext) => BlocProvider.value( value: operationFilesBloc, child: AttachmentViewerScreen( - attachment: file, - onRename: (newName) { + attachments: list, + initialIndex: index >= 0 ? index : 0, + onRenameAttachment: (targetFile, newName) { // Spara l'evento al BLoC e lui farà il resto! - operationFilesBloc.add(RenameAttachmentEvent(file, newName)); + operationFilesBloc.add( + RenameAttachmentEvent(targetFile, newName), + ); }, - onDelete: () { - operationFilesBloc.add(DeleteSpecificAttachmentEvent(file)); + onDeleteAttachment: (targetFile) { + operationFilesBloc.add( + DeleteSpecificAttachmentEvent(targetFile), + ); }, ), ), @@ -155,6 +165,8 @@ class TicketListCard extends StatelessWidget { _openFile( context: context, file: attachments.first, + attachments: attachments, + initialIndex: 0, ); } else { // CASO 2: Più allegati. Mostriamo una BottomSheet fulminea per far scegliere all'utente. @@ -188,6 +200,8 @@ class TicketListCard extends StatelessWidget { _openFile( context: context, file: file, + attachments: attachments, + initialIndex: index, ); // Apre il viewer }, ); diff --git a/pubspec.yaml b/pubspec.yaml index ed7e633..96a0dcf 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: flux description: "Gestione attività negozio di telefonia" publish_to: 'none' -version: 2.0.0+56 +version: 2.0.1+57 environment: sdk: ^3.11.3