425 lines
12 KiB
Dart
425 lines
12 KiB
Dart
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:flux/core/utils/image_utils.dart';
|
|
import 'package:pdfrx/pdfrx.dart';
|
|
import 'package:internet_file/internet_file.dart';
|
|
|
|
class AttachmentViewerScreen extends StatefulWidget {
|
|
final AttachmentModel? attachment;
|
|
final List<AttachmentModel>? 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,
|
|
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<AttachmentViewerScreen> createState() => _AttachmentViewerScreenState();
|
|
}
|
|
|
|
class _AttachmentViewerScreenState extends State<AttachmentViewerScreen> {
|
|
late List<AttachmentModel> _items;
|
|
late int _currentIndex;
|
|
final FocusNode _focusNode = FocusNode();
|
|
|
|
bool _isLoading = true;
|
|
String? _errorMessage;
|
|
Uint8List? _fileBytes;
|
|
int _loadToken = 0;
|
|
int _rotationTurns = 0;
|
|
|
|
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();
|
|
if (widget.attachments != null && widget.attachments!.isNotEmpty) {
|
|
_items = List<AttachmentModel>.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();
|
|
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;
|
|
setState(() {
|
|
_currentIndex = newIndex;
|
|
_isLoading = true;
|
|
_errorMessage = null;
|
|
_fileBytes = null;
|
|
_rotationTurns = 0;
|
|
});
|
|
_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<void> _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;
|
|
|
|
if (bytes != null && !isPdf) {
|
|
bytes = ImageUtils.normalizeOrientation(bytes, extension: item.extension);
|
|
}
|
|
|
|
setState(() {
|
|
_fileBytes = bytes;
|
|
_isLoading = false;
|
|
});
|
|
} catch (e) {
|
|
if (token != _loadToken || !mounted) return;
|
|
setState(() {
|
|
_isLoading = false;
|
|
_errorMessage = e.toString();
|
|
});
|
|
}
|
|
}
|
|
|
|
void _showRenameDialog() {
|
|
final current = _currentAttachment;
|
|
final ctrl = TextEditingController(text: current.name);
|
|
ctrl.selection = TextSelection(
|
|
baseOffset: 0,
|
|
extentOffset: ctrl.text.length,
|
|
);
|
|
final dialogFocusNode = FocusNode();
|
|
|
|
showDialog(
|
|
context: context,
|
|
builder: (context) {
|
|
WidgetsBinding.instance.addPostFrameCallback(
|
|
(_) => dialogFocusNode.requestFocus(),
|
|
);
|
|
return AlertDialog(
|
|
title: const Text('Rinomina File'),
|
|
content: TextField(
|
|
controller: ctrl,
|
|
focusNode: dialogFocusNode,
|
|
decoration: InputDecoration(
|
|
labelText: 'Nuovo nome',
|
|
suffixText: '.${current.extension}',
|
|
),
|
|
onSubmitted: (val) {
|
|
Navigator.pop(context);
|
|
_applyRename(val);
|
|
},
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(context),
|
|
child: const Text('Annulla'),
|
|
),
|
|
ElevatedButton(
|
|
onPressed: () {
|
|
Navigator.pop(context);
|
|
_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 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 (!isPdf)
|
|
IconButton(
|
|
icon: const Icon(Icons.rotate_right),
|
|
tooltip: 'Ruota',
|
|
onPressed: () {
|
|
setState(() {
|
|
_rotationTurns = (_rotationTurns + 1) % 4;
|
|
});
|
|
},
|
|
),
|
|
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(),
|
|
),
|
|
// 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,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildBody() {
|
|
if (_isLoading) {
|
|
return const Center(
|
|
child: CircularProgressIndicator(color: Colors.white),
|
|
);
|
|
}
|
|
if (_errorMessage != null) {
|
|
return Center(
|
|
child: Text(
|
|
'Errore: $_errorMessage',
|
|
style: const TextStyle(color: Colors.redAccent),
|
|
),
|
|
);
|
|
}
|
|
if (_fileBytes == null) {
|
|
return const Center(
|
|
child: Text(
|
|
'File non disponibile',
|
|
style: TextStyle(color: Colors.white),
|
|
),
|
|
);
|
|
}
|
|
|
|
if (isPdf && _fileBytes != null) {
|
|
return PdfViewer.data(
|
|
_fileBytes!,
|
|
sourceName: '${_currentAttachment.id}_${_currentAttachment.name}.pdf',
|
|
params: const PdfViewerParams(
|
|
backgroundColor: Colors.transparent,
|
|
enableKeyboardNavigation: false,
|
|
),
|
|
);
|
|
} else {
|
|
return InteractiveViewer(
|
|
maxScale: 5.0,
|
|
child: Center(
|
|
child: RotatedBox(
|
|
quarterTurns: _rotationTurns,
|
|
child: Image.memory(_fileBytes!),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
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,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|