attachment_picker.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. import 'dart:io';
  2. import 'package:flutter/material.dart';
  3. import 'package:image_picker/image_picker.dart';
  4. import 'package:file_picker/file_picker.dart';
  5. import 'package:tdesign_flutter/tdesign_flutter.dart';
  6. import '../models/attachment_file.dart';
  7. import '../../core/i18n/app_localizations.dart';
  8. import '../../core/theme/app_colors.dart';
  9. import '../../core/theme/app_colors_extension.dart';
  10. // ═══════════════════════════════════════════════════════════════
  11. // Controller
  12. // ═══════════════════════════════════════════════════════════════
  13. class AttachmentPickerController extends ChangeNotifier {
  14. final int maxCount;
  15. final List<AttachmentFile> _files = [];
  16. List<AttachmentFile> get files => List.unmodifiable(_files);
  17. int get count => _files.length;
  18. bool get isFull => _files.length >= maxCount;
  19. AttachmentPickerController({
  20. this.maxCount = 9,
  21. List<AttachmentFile>? initialFiles,
  22. }) {
  23. if (initialFiles != null) {
  24. _files.addAll(initialFiles.take(maxCount));
  25. }
  26. }
  27. void addFile(AttachmentFile file) {
  28. if (_files.length >= maxCount) return;
  29. _files.add(file);
  30. notifyListeners();
  31. }
  32. void addFiles(List<AttachmentFile> files) {
  33. for (final f in files) {
  34. if (_files.length >= maxCount) break;
  35. _files.add(f);
  36. }
  37. notifyListeners();
  38. }
  39. void removeFile(int index) {
  40. if (index < 0 || index >= _files.length) return;
  41. _files.removeAt(index);
  42. notifyListeners();
  43. }
  44. void clear() {
  45. if (_files.isEmpty) return;
  46. _files.clear();
  47. notifyListeners();
  48. }
  49. /// 从路径列表恢复(草稿兼容)
  50. Future<void> restoreFromPaths(List<String> paths) async {
  51. _files.clear();
  52. for (final path in paths.take(maxCount)) {
  53. _files.add(await AttachmentFile.fromPath(path));
  54. }
  55. notifyListeners();
  56. }
  57. /// 导出为路径列表(草稿持久化)
  58. List<String> toPathList() => _files.map((f) => f.path).toList();
  59. }
  60. // ═══════════════════════════════════════════════════════════════
  61. // Widget
  62. // ═══════════════════════════════════════════════════════════════
  63. class AttachmentPicker extends StatefulWidget {
  64. final AttachmentPickerController controller;
  65. /// 图片大小上限(MB),null 不限制
  66. final double? maxImageSizeMB;
  67. /// 文件大小上限(MB),null 不限制
  68. final double? maxFileSizeMB;
  69. /// 允许的文件扩展名,null 使用默认 pdf/doc/docx/xls/xlsx/ppt/pptx/txt
  70. final List<String>? allowedExtensions;
  71. /// 文件被拒时回调
  72. final void Function(AttachmentFile file, String reason)? onFileRejected;
  73. /// 缩略图尺寸
  74. final double thumbnailSize;
  75. const AttachmentPicker({
  76. super.key,
  77. required this.controller,
  78. this.maxImageSizeMB,
  79. this.maxFileSizeMB,
  80. this.allowedExtensions,
  81. this.onFileRejected,
  82. this.thumbnailSize = 80,
  83. });
  84. @override
  85. State<AttachmentPicker> createState() => _AttachmentPickerState();
  86. }
  87. class _AttachmentPickerState extends State<AttachmentPicker> {
  88. List<AttachmentFile> get _files => widget.controller.files;
  89. @override
  90. void initState() {
  91. super.initState();
  92. widget.controller.addListener(_onChanged);
  93. }
  94. @override
  95. void dispose() {
  96. widget.controller.removeListener(_onChanged);
  97. super.dispose();
  98. }
  99. void _onChanged() {
  100. if (mounted) setState(() {});
  101. }
  102. // ── 选择入口 ──
  103. Future<void> _showPicker() async {
  104. _unfocus();
  105. final l10n = AppLocalizations.of(context);
  106. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  107. final choice = await showModalBottomSheet<String>(
  108. context: context,
  109. backgroundColor: colors.bgCard,
  110. shape: const RoundedRectangleBorder(
  111. borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
  112. ),
  113. builder: (ctx) => SafeArea(
  114. child: Column(
  115. mainAxisSize: MainAxisSize.min,
  116. children: [
  117. ListTile(
  118. leading: const Icon(Icons.image_outlined),
  119. title: Text(l10n.get('pickImage')),
  120. onTap: () => Navigator.pop(ctx, 'image'),
  121. ),
  122. ListTile(
  123. leading: const Icon(Icons.description_outlined),
  124. title: Text(l10n.get('pickFile')),
  125. onTap: () => Navigator.pop(ctx, 'file'),
  126. ),
  127. ],
  128. ),
  129. ),
  130. );
  131. if (!mounted || choice == null) return;
  132. if (choice == 'image') {
  133. await _pickImages();
  134. } else {
  135. await _pickDocuments();
  136. }
  137. }
  138. Future<void> _pickImages() async {
  139. final available = widget.controller.maxCount - widget.controller.count;
  140. if (available <= 0) return;
  141. final picker = ImagePicker();
  142. final images = await picker.pickMultiImage(limit: available);
  143. if (!mounted || images.isEmpty) return;
  144. for (final img in images) {
  145. if (widget.controller.isFull) break;
  146. final file = await AttachmentFile.fromXFile(img);
  147. if (_checkOversized(file)) continue;
  148. widget.controller.addFile(file);
  149. }
  150. }
  151. Future<void> _pickDocuments() async {
  152. final available = widget.controller.maxCount - widget.controller.count;
  153. if (available <= 0) return;
  154. final result = await FilePicker.pickFiles(
  155. type: FileType.custom,
  156. allowedExtensions: widget.allowedExtensions ??
  157. const ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'],
  158. allowMultiple: true,
  159. );
  160. if (!mounted || result == null || result.files.isEmpty) return;
  161. for (final pf in result.files) {
  162. if (widget.controller.isFull) break;
  163. if (pf.path == null) continue;
  164. final file = AttachmentFile.fromPlatformFile(pf);
  165. if (_checkOversized(file)) continue;
  166. widget.controller.addFile(file);
  167. }
  168. }
  169. /// 返回 true 表示文件超过大小限制
  170. bool _checkOversized(AttachmentFile file) {
  171. final l10n = AppLocalizations.of(context);
  172. final sizeMB = file.sizeMB;
  173. if (file.isImage && widget.maxImageSizeMB != null && sizeMB > widget.maxImageSizeMB!) {
  174. final reason = l10n.getString('imageSizeLimit', args: {'max': widget.maxImageSizeMB!.toStringAsFixed(0)});
  175. widget.onFileRejected?.call(file, reason);
  176. if (mounted) TDToast.showText(reason, context: context);
  177. return true;
  178. }
  179. if (!file.isImage && widget.maxFileSizeMB != null && sizeMB > widget.maxFileSizeMB!) {
  180. final reason = l10n.getString('fileSizeLimit', args: {'max': widget.maxFileSizeMB!.toStringAsFixed(0)});
  181. widget.onFileRejected?.call(file, reason);
  182. if (mounted) TDToast.showText(reason, context: context);
  183. return true;
  184. }
  185. return false;
  186. }
  187. void _unfocus() => FocusScope.of(context).unfocus();
  188. // ── UI ──
  189. @override
  190. Widget build(BuildContext context) {
  191. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  192. return Column(
  193. crossAxisAlignment: CrossAxisAlignment.start,
  194. children: [
  195. Wrap(
  196. spacing: 8,
  197. runSpacing: 8,
  198. children: [
  199. ..._files.asMap().entries.map(
  200. (e) => Stack(
  201. clipBehavior: Clip.none,
  202. children: [
  203. _buildThumbnail(e.value),
  204. Positioned(
  205. right: -4,
  206. top: -4,
  207. child: GestureDetector(
  208. onTap: () => widget.controller.removeFile(e.key),
  209. child: Container(
  210. width: 20,
  211. height: 20,
  212. decoration: BoxDecoration(
  213. color: colors.danger,
  214. shape: BoxShape.circle,
  215. ),
  216. child: const Icon(
  217. Icons.close,
  218. size: 12,
  219. color: Colors.white,
  220. ),
  221. ),
  222. ),
  223. ),
  224. ],
  225. ),
  226. ),
  227. if (!widget.controller.isFull)
  228. GestureDetector(
  229. onTap: () => _showPicker(),
  230. child: Container(
  231. width: widget.thumbnailSize,
  232. height: widget.thumbnailSize,
  233. decoration: BoxDecoration(
  234. color: colors.bgPage,
  235. borderRadius: BorderRadius.circular(4),
  236. border: Border.all(color: colors.border, width: 1),
  237. ),
  238. child: Center(
  239. child: Icon(
  240. Icons.add,
  241. size: 24,
  242. color: colors.textPlaceholder,
  243. ),
  244. ),
  245. ),
  246. ),
  247. ],
  248. ),
  249. ],
  250. );
  251. }
  252. Widget _buildThumbnail(AttachmentFile file) {
  253. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  254. final size = widget.thumbnailSize;
  255. if (file.isImage) {
  256. return Container(
  257. width: size,
  258. height: size,
  259. decoration: BoxDecoration(
  260. borderRadius: BorderRadius.circular(4),
  261. border: Border.all(color: colors.border, width: 0.5),
  262. ),
  263. child: ClipRRect(
  264. borderRadius: BorderRadius.circular(4),
  265. child: Image.file(
  266. File(file.path),
  267. width: size,
  268. height: size,
  269. fit: BoxFit.cover,
  270. errorBuilder: (_, _, _) => _buildDocTile(file, colors, size),
  271. ),
  272. ),
  273. );
  274. }
  275. return _buildDocTile(file, colors, size);
  276. }
  277. Widget _buildDocTile(AttachmentFile file, AppColorsExtension colors, double size) {
  278. return SizedBox(
  279. width: size,
  280. child: Column(
  281. mainAxisSize: MainAxisSize.min,
  282. children: [
  283. Container(
  284. width: size,
  285. height: size,
  286. decoration: BoxDecoration(
  287. color: colors.primaryLight,
  288. borderRadius: BorderRadius.circular(4),
  289. ),
  290. child: Center(
  291. child: Icon(
  292. _fileTypeIcon(file.extension),
  293. color: colors.primary,
  294. size: size * 0.4,
  295. ),
  296. ),
  297. ),
  298. const SizedBox(height: 4),
  299. SizedBox(
  300. width: size,
  301. height: 16,
  302. child: _MarqueeText(
  303. text: file.name,
  304. style: TextStyle(
  305. fontSize: AppFontSizes.caption,
  306. color: colors.textSecondary,
  307. ),
  308. ),
  309. ),
  310. ],
  311. ),
  312. );
  313. }
  314. IconData _fileTypeIcon(String ext) {
  315. switch (ext) {
  316. case 'pdf':
  317. return Icons.picture_as_pdf;
  318. case 'doc':
  319. case 'docx':
  320. return Icons.description;
  321. case 'xls':
  322. case 'xlsx':
  323. return Icons.table_chart;
  324. case 'ppt':
  325. case 'pptx':
  326. return Icons.slideshow;
  327. default:
  328. return Icons.insert_drive_file;
  329. }
  330. }
  331. }
  332. // ═══════════════════════════════════════════════════════════════
  333. // Marquee Text
  334. // ═══════════════════════════════════════════════════════════════
  335. class _MarqueeText extends StatefulWidget {
  336. final String text;
  337. final TextStyle style;
  338. const _MarqueeText({required this.text, required this.style});
  339. @override
  340. State<_MarqueeText> createState() => _MarqueeTextState();
  341. }
  342. class _MarqueeTextState extends State<_MarqueeText>
  343. with SingleTickerProviderStateMixin {
  344. late final AnimationController _controller;
  345. final ScrollController _scrollController = ScrollController();
  346. bool _needsScroll = false;
  347. @override
  348. void initState() {
  349. super.initState();
  350. _controller = AnimationController(
  351. vsync: this,
  352. duration: const Duration(milliseconds: 3000),
  353. );
  354. WidgetsBinding.instance.addPostFrameCallback(_measure);
  355. }
  356. void _measure(_) {
  357. if (!mounted || !_scrollController.hasClients) return;
  358. if (_scrollController.position.maxScrollExtent > 0) {
  359. setState(() => _needsScroll = true);
  360. _controller.addListener(_onScroll);
  361. _controller.repeat(reverse: true);
  362. }
  363. }
  364. void _onScroll() {
  365. if (!_scrollController.hasClients) return;
  366. final max = _scrollController.position.maxScrollExtent;
  367. if (max > 0) {
  368. _scrollController.jumpTo(_controller.value * max);
  369. }
  370. }
  371. @override
  372. void dispose() {
  373. _controller.dispose();
  374. _scrollController.dispose();
  375. super.dispose();
  376. }
  377. @override
  378. Widget build(BuildContext context) {
  379. return SingleChildScrollView(
  380. controller: _scrollController,
  381. scrollDirection: Axis.horizontal,
  382. physics: _needsScroll
  383. ? const NeverScrollableScrollPhysics()
  384. : const ClampingScrollPhysics(),
  385. child: Text(widget.text, style: widget.style, maxLines: 1),
  386. );
  387. }
  388. }