repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/sort_bloc/sort_event.dart
part of 'sort_bloc.dart'; abstract class SortEvent extends Equatable { const SortEvent(); } class ChangeSortEvent extends SortEvent { const ChangeSortEvent({ required this.sortType, required this.isAsc, required this.onlyFavourite, required this.years, required this.tags, required this.displayTags, required this.filterTagsAsAnd, required this.bookType, this.filterOutTags = false, }); final SortType sortType; final bool isAsc; final bool onlyFavourite; final String? years; final String? tags; final bool displayTags; final bool filterTagsAsAnd; final BookFormat? bookType; final bool filterOutTags; @override List<Object?> get props => [ sortType, isAsc, onlyFavourite, years, tags, displayTags, filterTagsAsAnd, bookType, filterOutTags, ]; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/sort_bloc/sort_bloc.dart
import 'package:equatable/equatable.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; import 'package:openreads/core/constants/enums/enums.dart'; part 'sort_state.dart'; part 'sort_event.dart'; class SortBloc extends HydratedBloc<SortEvent, SortState> { SortBloc() : super(const SetSortState( sortType: SortType.byTitle, isAsc: true, onlyFavourite: false, years: null, tags: null, displayTags: false, filterTagsAsAnd: false, bookType: null, )) { on<ChangeSortEvent>((event, emit) { emit(SetSortState( sortType: event.sortType, isAsc: event.isAsc, onlyFavourite: event.onlyFavourite, years: event.years, tags: event.tags, displayTags: event.displayTags, filterTagsAsAnd: event.filterTagsAsAnd, bookType: event.bookType, filterOutTags: event.filterOutTags, )); }); } @override SortState? fromJson(Map<String, dynamic> json) { final sortTypeInt = json['sort_type'] as int; final isAsc = json['sort_order'] as bool; final onlyFavourite = json['only_favourite'] as bool; final years = json['years'] as String?; final tags = json['tags'] as String?; final displayTags = json['display_tags'] as bool; final filterTagsAsAnd = json['filter_tags_as_and'] as bool; final filterOutTags = json['filter_out_tags'] as bool; final bookType = json['filter_book_type'] as String?; late SortType sortType; switch (sortTypeInt) { case 0: sortType = SortType.byTitle; break; case 1: sortType = SortType.byAuthor; break; case 2: sortType = SortType.byRating; break; case 3: sortType = SortType.byPages; break; case 4: sortType = SortType.byStartDate; break; case 5: sortType = SortType.byFinishDate; break; case 6: sortType = SortType.byPublicationYear; break; default: sortType = SortType.byTitle; } return SetSortState( sortType: sortType, isAsc: isAsc, onlyFavourite: onlyFavourite, years: years, tags: tags, displayTags: displayTags, filterTagsAsAnd: filterTagsAsAnd, bookType: bookType == 'audiobook' ? BookFormat.audiobook : bookType == 'ebook' ? BookFormat.ebook : bookType == 'paper' || bookType == 'paperback' ? BookFormat.paperback : bookType == 'hardcover' ? BookFormat.hardcover : null, filterOutTags: filterOutTags, ); } @override Map<String, dynamic>? toJson(SortState state) { if (state is SetSortState) { late int sortTypeInt; switch (state.sortType) { case SortType.byTitle: sortTypeInt = 0; break; case SortType.byAuthor: sortTypeInt = 1; break; case SortType.byRating: sortTypeInt = 2; break; case SortType.byPages: sortTypeInt = 3; break; case SortType.byStartDate: sortTypeInt = 4; break; case SortType.byFinishDate: sortTypeInt = 5; break; case SortType.byPublicationYear: sortTypeInt = 6; break; default: sortTypeInt = 0; } return { 'sort_type': sortTypeInt, 'sort_order': state.isAsc, 'only_favourite': state.onlyFavourite, 'years': state.years, 'tags': state.tags, 'display_tags': state.displayTags, 'filter_tags_as_and': state.filterTagsAsAnd, 'filter_book_type': state.bookType == BookFormat.audiobook ? 'audiobook' : state.bookType == BookFormat.ebook ? 'ebook' : state.bookType == BookFormat.paperback ? 'paperback' : state.bookType == BookFormat.hardcover ? 'hardcover' : null, 'filter_out_tags': state.filterOutTags, }; } else { return { 'sort_type': 0, 'sort_order': true, 'only_favourite': false, 'years': null, 'tags': null, 'display_tags': false, 'filter_tags_as_and': false, 'filter_book_type': null, 'filter_out_tags': false, }; } } }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/sort_bloc/sort_state.dart
part of 'sort_bloc.dart'; abstract class SortState extends Equatable { const SortState(); } class SetSortState extends SortState { final SortType sortType; final bool isAsc; final bool onlyFavourite; final String? years; final String? tags; final bool displayTags; final bool filterTagsAsAnd; final BookFormat? bookType; final bool filterOutTags; const SetSortState({ required this.sortType, required this.isAsc, required this.onlyFavourite, required this.years, required this.tags, required this.displayTags, required this.filterTagsAsAnd, required this.bookType, this.filterOutTags = false, }); @override List<Object?> get props => [ isAsc, onlyFavourite, sortType, years, tags, displayTags, filterTagsAsAnd, bookType, filterOutTags, ]; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/rating_type_bloc/rating_type_bloc.dart
import 'package:equatable/equatable.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; import 'package:openreads/core/constants/enums/enums.dart'; part 'rating_type_event.dart'; part 'rating_type_state.dart'; class RatingTypeBloc extends HydratedBloc<RatingTypeEvent, RatingTypeState> { RatingTypeBloc() : super(RatingTypeBar()) { on<RatingTypeChange>((event, emit) { if (event.ratingType == RatingType.number) { emit(RatingTypeNumber()); } else { emit(RatingTypeBar()); } }); } @override RatingTypeState? fromJson(Map<String, dynamic> json) { final ratingType = json['rating_type'] as String?; if (ratingType == 'number') { return RatingTypeNumber(); } else { return RatingTypeBar(); } } @override Map<String, dynamic>? toJson(RatingTypeState state) { if (state is RatingTypeNumber) { return { 'rating_type': 'number', }; } else { return { 'rating_type': 'bar', }; } } }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/rating_type_bloc/rating_type_event.dart
part of 'rating_type_bloc.dart'; abstract class RatingTypeEvent extends Equatable { const RatingTypeEvent(); } class RatingTypeChange extends RatingTypeEvent { final RatingType ratingType; const RatingTypeChange({required this.ratingType}); @override List<Object?> get props => [ratingType]; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/rating_type_bloc/rating_type_state.dart
part of 'rating_type_bloc.dart'; abstract class RatingTypeState extends Equatable { const RatingTypeState(); @override List<Object> get props => []; } class RatingTypeBar extends RatingTypeState {} class RatingTypeNumber extends RatingTypeState {}
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/open_library_search_bloc/open_library_search_bloc.dart
import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; part 'open_library_search_event.dart'; part 'open_library_search_state.dart'; class OpenLibrarySearchBloc extends Bloc<OpenLibrarySearchEvent, OpenLibrarySearchState> { OpenLibrarySearchBloc() : super(const OpenLibrarySearchGeneral()) { on<OpenLibrarySearchSetGeneral>((event, emit) { emit(const OpenLibrarySearchGeneral()); }); on<OpenLibrarySearchSetAuthor>((event, emit) { emit(const OpenLibrarySearchAuthor()); }); on<OpenLibrarySearchSetTitle>((event, emit) { emit(const OpenLibrarySearchTitle()); }); on<OpenLibrarySearchSetISBN>((event, emit) { emit(const OpenLibrarySearchISBN()); }); } }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/open_library_search_bloc/open_library_search_event.dart
part of 'open_library_search_bloc.dart'; class OpenLibrarySearchEvent extends Equatable { const OpenLibrarySearchEvent(); @override List<Object> get props => []; } class OpenLibrarySearchSetGeneral extends OpenLibrarySearchEvent { const OpenLibrarySearchSetGeneral(); @override List<Object> get props => []; } class OpenLibrarySearchSetAuthor extends OpenLibrarySearchEvent { const OpenLibrarySearchSetAuthor(); @override List<Object> get props => []; } class OpenLibrarySearchSetTitle extends OpenLibrarySearchEvent { const OpenLibrarySearchSetTitle(); @override List<Object> get props => []; } class OpenLibrarySearchSetISBN extends OpenLibrarySearchEvent { const OpenLibrarySearchSetISBN(); @override List<Object> get props => []; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/open_library_search_bloc/open_library_search_state.dart
part of 'open_library_search_bloc.dart'; class OpenLibrarySearchState extends Equatable { const OpenLibrarySearchState(); @override List<Object> get props => []; } class OpenLibrarySearchGeneral extends OpenLibrarySearchState { const OpenLibrarySearchGeneral(); @override List<Object> get props => []; } class OpenLibrarySearchAuthor extends OpenLibrarySearchState { const OpenLibrarySearchAuthor(); @override List<Object> get props => []; } class OpenLibrarySearchTitle extends OpenLibrarySearchState { const OpenLibrarySearchTitle(); @override List<Object> get props => []; } class OpenLibrarySearchISBN extends OpenLibrarySearchState { const OpenLibrarySearchISBN(); @override List<Object> get props => []; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/display_bloc/display_state.dart
part of 'display_bloc.dart'; abstract class DisplayState extends Equatable { const DisplayState(); } class GridDisplayState extends DisplayState { const GridDisplayState(); @override List<Object?> get props => []; } class ListDisplayState extends DisplayState { const ListDisplayState(); @override List<Object?> get props => []; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/display_bloc/display_bloc.dart
import 'package:equatable/equatable.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; part 'display_state.dart'; part 'display_event.dart'; class DisplayBloc extends HydratedBloc<DisplayEvent, DisplayState> { DisplayBloc() : super(const ListDisplayState()) { on<ChangeDisplayEvent>((event, emit) { if (event.displayAsGrid) { emit(const GridDisplayState()); } else { emit(const ListDisplayState()); } }); } @override DisplayState? fromJson(Map<String, dynamic> json) { final displayAsGrid = json['display_as_grid'] as bool?; switch (displayAsGrid) { case true: return const GridDisplayState(); default: return const ListDisplayState(); } } @override Map<String, dynamic>? toJson(DisplayState state) { if (state is GridDisplayState) { return {'display_as_grid': true}; } else { return { 'display_as_grid': false, }; } } }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/display_bloc/display_event.dart
part of 'display_bloc.dart'; abstract class DisplayEvent extends Equatable { const DisplayEvent(); } class ChangeDisplayEvent extends DisplayEvent { final bool displayAsGrid; const ChangeDisplayEvent({ required this.displayAsGrid, }); @override List<Object?> get props => [ displayAsGrid, ]; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/migration_v1_to_v2_bloc/migration_v1_to_v2_state.dart
part of 'migration_v1_to_v2_bloc.dart'; abstract class MigrationV1ToV2State extends Equatable { const MigrationV1ToV2State(); @override List<Object?> get props => []; } class MigrationNotStarted extends MigrationV1ToV2State {} class MigrationOnging extends MigrationV1ToV2State { const MigrationOnging({ this.total, this.done, }); final int? total; final int? done; @override List<Object?> get props => [total, done]; } class MigrationTriggered extends MigrationV1ToV2State {} class MigrationSkipped extends MigrationV1ToV2State {} class MigrationSucceded extends MigrationV1ToV2State {} class MigrationFailed extends MigrationV1ToV2State { const MigrationFailed({required this.error}); final String error; @override List<Object> get props => [error]; }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/migration_v1_to_v2_bloc/migration_v1_to_v2_bloc.dart
import 'dart:convert'; import 'dart:io'; import 'package:equatable/equatable.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/logic/bloc/challenge_bloc/challenge_bloc.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/model/book_from_backup_v3.dart'; import 'package:openreads/model/year_from_backup_v3.dart'; import 'package:openreads/model/yearly_challenge.dart'; import 'package:path_provider/path_provider.dart'; import 'package:path/path.dart' as path; import 'package:sqflite/sqflite.dart'; import 'package:image/image.dart' as img; import 'package:blurhash_dart/blurhash_dart.dart' as blurhash_dart; part 'migration_v1_to_v2_event.dart'; part 'migration_v1_to_v2_state.dart'; class MigrationV1ToV2Bloc extends Bloc<MigrationV1ToV2Event, MigrationV1ToV2State> { MigrationV1ToV2Bloc() : super(MigrationNotStarted()) { on<StartMigration>((event, emit) async { emit(MigrationTriggered()); final v1BooksDbPath = await _checkIfV1DatabaseExists('BooksDB.db'); final v1YearsDbPath = await _checkIfV1DatabaseExists('YearDB.db'); if (!event.retrigger && await _checkIfNewDBIsPresent()) { emit(MigrationSkipped()); return; } if (v1BooksDbPath == null) { if (event.retrigger) { // ignore: use_build_context_synchronously _showSnackbar(event.context, 'Migration error 1'); } emit(MigrationSkipped()); return; } emit(const MigrationOnging()); await _migrateBooksFromV1ToV2(v1BooksDbPath); if (v1YearsDbPath != null) { // ignore: use_build_context_synchronously await _migrateYearsFromV1ToV2(event.context, v1YearsDbPath); } else { if (event.retrigger) { // ignore: use_build_context_synchronously _showSnackbar(event.context, 'Migration error 3'); } } emit(MigrationSucceded()); await Future.delayed(const Duration(seconds: 5)); }); } _showSnackbar(BuildContext context, String message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( message, ), ), ); } Future<bool> _checkIfNewDBIsPresent() async { Directory docDirectory = await getApplicationDocumentsDirectory(); final filePathToBeChecked = path.join(docDirectory.path, 'Books.db'); final files = await docDirectory.list().toList(); for (var file in files) { if (file.path == filePathToBeChecked) { return true; } } return false; } Future<String?> _checkIfV1DatabaseExists(String dbName) async { Directory docDirectory = await getApplicationDocumentsDirectory(); String dbDirectoryPath = path.join(docDirectory.parent.path, 'databases'); Directory dbDirectory = Directory(dbDirectoryPath); if (!dbDirectory.existsSync()) return null; final files = await dbDirectory.list().toList(); final filePathToBeChecked = path.join(dbDirectory.path, dbName); for (var file in files) { if (file.path == filePathToBeChecked) { return file.path; } } return null; } Future<void> _migrateBooksFromV1ToV2(String dbPath) async { final booksDB = await openDatabase(dbPath); final result = await booksDB.query("Book"); final List<BookFromBackupV3> books = result.isNotEmpty ? result.map((item) => BookFromBackupV3.fromJson(item)).toList() : []; final totalBooksToMigrate = books.length; var booksMigrated = 0; // ignore: invalid_use_of_visible_for_testing_member emit(MigrationOnging(total: totalBooksToMigrate, done: booksMigrated)); for (var book in books) { await _addBookFromBackupV3( book, totalBooksToMigrate, booksMigrated, ); booksMigrated += 1; // ignore: invalid_use_of_visible_for_testing_member emit(MigrationOnging(total: totalBooksToMigrate, done: booksMigrated)); } bookCubit.getAllBooksByStatus(); bookCubit.getAllBooks(); } Future<void> _addBookFromBackupV3( BookFromBackupV3 book, int total, int done, ) async { final blurHash = await compute(_generateBlurHash, book.bookCoverImg); final newBook = Book.fromBookFromBackupV3(book, blurHash); bookCubit.addBook(newBook, refreshBooks: false); } static String? _generateBlurHash(Uint8List? cover) { if (cover == null) return null; return blurhash_dart.BlurHash.encode( img.decodeImage(cover)!, numCompX: Constants.blurHashX, numCompY: Constants.blurHashY, ).hash; } Future<void> _migrateYearsFromV1ToV2( BuildContext context, String dbPath, ) async { final booksDB = await openDatabase(dbPath); final result = await booksDB.query("Year"); final List<YearFromBackupV3>? years = result.isNotEmpty ? result.map((item) => YearFromBackupV3.fromJson(item)).toList() : null; String newChallenges = ''; if (years == null) return; for (var year in years) { if (newChallenges.isEmpty) { if (year.year != null) { final newJson = json .encode(YearlyChallenge( year: int.parse(year.year!), books: year.yearChallengeBooks, pages: year.yearChallengePages, ).toJSON()) .toString(); newChallenges = [ newJson, ].join('|||||'); } } else { final splittedNewChallenges = newChallenges.split('|||||'); final newJson = json .encode(YearlyChallenge( year: int.parse(year.year!), books: year.yearChallengeBooks, pages: year.yearChallengePages, ).toJSON()) .toString(); splittedNewChallenges.add(newJson); newChallenges = splittedNewChallenges.join('|||||'); } } // ignore: use_build_context_synchronously BlocProvider.of<ChallengeBloc>(context).add( RestoreChallengesEvent( challenges: newChallenges, ), ); } }
0
mirrored_repositories/openreads/lib/logic/bloc
mirrored_repositories/openreads/lib/logic/bloc/migration_v1_to_v2_bloc/migration_v1_to_v2_event.dart
part of 'migration_v1_to_v2_bloc.dart'; abstract class MigrationV1ToV2Event extends Equatable { const MigrationV1ToV2Event(); } class StartMigration extends MigrationV1ToV2Event { final BuildContext context; final bool retrigger; const StartMigration({ required this.context, this.retrigger = false, }); @override List<Object?> get props => [ context, retrigger, ]; }
0
mirrored_repositories/openreads/lib/logic
mirrored_repositories/openreads/lib/logic/cubit/current_book_cubit.dart
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/model/book.dart'; class CurrentBookCubit extends Cubit<Book> { CurrentBookCubit() : super(Book.empty()); setBook(Book book) => emit(book); }
0
mirrored_repositories/openreads/lib/logic
mirrored_repositories/openreads/lib/logic/cubit/edit_book_cubit.dart
import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/reading.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/model/reading_time.dart'; class EditBookCubit extends Cubit<Book> { EditBookCubit() : super(Book.empty()); setBook(Book book) => emit(book); void updateBook(Uint8List? cover, BuildContext context) { if (state.id == null) return; bookCubit.updateBook(state, cover: cover, context: context); } void addNewBook(Uint8List? cover) { bookCubit.addBook(state, cover: cover); } void setStatus(BookStatus status) { final book = state.copyWith(); emit(book.copyWith(status: status)); } void setRating(double rating) { emit(state.copyWith(rating: (rating * 10).toInt())); } void setBookFormat(BookFormat bookFormat) { emit(state.copyWith(bookFormat: bookFormat)); } void setTitle(String title) { emit(state.copyWith(title: title)); } void setSubtitle(String subtitle) { final book = state.copyWith(); book.subtitle = subtitle.isNotEmpty ? subtitle : null; emit(book); } void setAuthor(String author) { emit(state.copyWith(author: author)); } void setPages(String pages) { final book = state.copyWith(); book.pages = pages.isEmpty ? null : int.parse(pages); emit(book); } void setDescription(String description) { final book = state.copyWith(); book.description = description.isNotEmpty ? description : null; emit(book); } void setISBN(String isbn) { final book = state.copyWith(); book.isbn = isbn.isNotEmpty ? isbn : null; emit(book); } void setOLID(String olid) { final book = state.copyWith(); book.olid = olid.isNotEmpty ? olid : null; emit(book); } void setPublicationYear(String publicationYear) { final book = state.copyWith(); book.publicationYear = publicationYear.isEmpty ? null : int.parse(publicationYear); emit(book); } void setMyReview(String myReview) { final book = state.copyWith(); book.myReview = myReview.isNotEmpty ? myReview : null; emit(book); } void setNotes(String notes) { final book = state.copyWith(); book.notes = notes.isNotEmpty ? notes : null; emit(book); } void setBlurHash(String? blurHash) { final book = state.copyWith(); book.blurHash = blurHash; emit(book); } void setHasCover(bool hasCover) { final book = state.copyWith(); book.hasCover = hasCover; emit(book); } void addNewTag(String tag) { // Remove space at the end of the string if exists if (tag.substring(tag.length - 1) == ' ') { tag = tag.substring(0, tag.length - 1); } // Remove illegal characters tag = tag.replaceAll('|', ''); //TODO: add same for @ in all needed places List<String> tags = state.tags == null ? [] : state.tags!.split('|||||'); if (tags.contains(tag)) return; tags.add(tag); final book = state.copyWith(); book.tags = tags.join('|||||'); emit(book); } void removeTag(String tag) { List<String> tags = state.tags == null ? [] : state.tags!.split('|||||'); if (!tags.contains(tag)) return; tags.remove(tag); final book = state.copyWith(); book.tags = tags.isEmpty ? null : tags.join('|||||'); emit(book); } void addNewReading(Reading reading) { List<Reading> readings = state.readings; readings.add(reading); final book = state.copyWith(); book.readings = readings; emit(book); } void removeReading(int index) { List<Reading> readings = state.readings; readings.removeAt(index); final book = state.copyWith(); book.readings = readings; emit(book); } void setReadingStartDate(DateTime? startDate, int index) { List<Reading> readings = state.readings; readings[index].startDate = startDate; final book = state.copyWith(); book.readings = readings; emit(book); } setReadingFinishDate(DateTime? finishDate, int index) { List<Reading> readings = state.readings; readings[index].finishDate = finishDate; final book = state.copyWith(); book.readings = readings; emit(book); } setCustomReadingTime(ReadingTime? readingTime, int index) { List<Reading> readings = state.readings; readings[index].customReadingTime = readingTime; final book = state.copyWith(); book.readings = readings; emit(book); } } class EditBookCoverCubit extends Cubit<Uint8List?> { EditBookCoverCubit() : super(null); setCover(Uint8List? cover) { imageCache.clear(); emit(cover); } deleteCover(int? bookID) async { if (bookID == null) return; emit(null); final coverExists = await File( '${appDocumentsDirectory.path}/$bookID.jpg', ).exists(); if (coverExists) { await File( '${appDocumentsDirectory.path}/$bookID.jpg', ).delete(); } } }
0
mirrored_repositories/openreads/lib/logic
mirrored_repositories/openreads/lib/logic/cubit/book_cubit.dart
import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/logic/cubit/current_book_cubit.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/resources/open_library_service.dart'; import 'package:openreads/resources/repository.dart'; import 'package:path_provider/path_provider.dart'; import 'package:rxdart/rxdart.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:blurhash_dart/blurhash_dart.dart' as blurhash_dart; import 'package:image/image.dart' as img; import 'package:openreads/core/constants/enums/enums.dart'; class BookCubit extends Cubit { final Repository repository = Repository(); final BehaviorSubject<List<Book>> _booksFetcher = BehaviorSubject<List<Book>>(); final BehaviorSubject<List<Book>> _finishedBooksFetcher = BehaviorSubject<List<Book>>(); final BehaviorSubject<List<Book>> _inProgressBooksFetcher = BehaviorSubject<List<Book>>(); final BehaviorSubject<List<Book>> _toReadBooksFetcher = BehaviorSubject<List<Book>>(); final BehaviorSubject<List<Book>> _deletedBooksFetcher = BehaviorSubject<List<Book>>(); final BehaviorSubject<List<Book>> _unfinishedBooksFetcher = BehaviorSubject<List<Book>>(); final BehaviorSubject<List<Book>> _searchBooksFetcher = BehaviorSubject<List<Book>>(); final BehaviorSubject<List<int>> _finishedYearsFetcher = BehaviorSubject<List<int>>(); final BehaviorSubject<List<String>> _tagsFetcher = BehaviorSubject<List<String>>(); final BehaviorSubject<List<String>> _authorsFetcher = BehaviorSubject<List<String>>(); final BehaviorSubject<Book?> _bookFetcher = BehaviorSubject<Book?>(); final BehaviorSubject<List<Book>?> _booksWithSameTagFetcher = BehaviorSubject<List<Book>?>(); final BehaviorSubject<List<Book>?> _booksWithSameAuthorFetcher = BehaviorSubject<List<Book>?>(); Stream<List<Book>> get allBooks => _booksFetcher.stream; Stream<List<Book>> get finishedBooks => _finishedBooksFetcher.stream; Stream<List<Book>> get inProgressBooks => _inProgressBooksFetcher.stream; Stream<List<Book>> get toReadBooks => _toReadBooksFetcher.stream; Stream<List<Book>> get deletedBooks => _deletedBooksFetcher.stream; Stream<List<Book>> get unfinishedBooks => _unfinishedBooksFetcher.stream; Stream<List<Book>> get searchBooks => _searchBooksFetcher.stream; Stream<List<int>> get finishedYears => _finishedYearsFetcher.stream; Stream<List<String>> get tags => _tagsFetcher.stream; Stream<List<String>> get authors => _authorsFetcher.stream; Stream<List<Book>?> get booksWithSameTag => _booksWithSameTagFetcher.stream; Stream<List<Book>?> get booksWithSameAuthor => _booksWithSameAuthorFetcher.stream; Stream<Book?> get book => _bookFetcher.stream; BookCubit() : super(null) { _initLoad(); } Future<void> _initLoad() async { if (!await _checkIfCoverMigrationDone()) { await _migrateCoversFromDatabaseToStorage(); } getFinishedBooks(); getInProgressBooks(); getToReadBooks(); getAllBooks(); } getAllBooks({ bool getTags = true, bool getAuthors = true, }) async { List<Book> books = await repository.getAllNotDeletedBooks(); _booksFetcher.sink.add(books); if (getTags) { _tagsFetcher.sink.add(_getTags(books)); } if (getAuthors) { _authorsFetcher.sink.add(_getAuthors(books)); } } removeAllBooks() async { await repository.removeAllBooks(); } getAllBooksByStatus() async { getFinishedBooks(); getInProgressBooks(); getToReadBooks(); getUnfinishedBooks(); } getFinishedBooks() async { List<Book> books = await repository.getBooks(0); _finishedBooksFetcher.sink.add(books); _finishedYearsFetcher.sink.add(_getFinishedYears(books)); } getInProgressBooks() async { List<Book> books = await repository.getBooks(1); _inProgressBooksFetcher.sink.add(books); } getToReadBooks() async { List<Book> books = await repository.getBooks(2); _toReadBooksFetcher.sink.add(books); } getDeletedBooks() async { List<Book> books = await repository.getDeletedBooks(); _deletedBooksFetcher.sink.add(books); } getUnfinishedBooks() async { List<Book> books = await repository.getBooks(3); _unfinishedBooksFetcher.sink.add(books); } getSearchBooks(String query) async { if (query.isEmpty) { _searchBooksFetcher.sink.add(List.empty()); } else { List<Book> books = await repository.searchBooks(query); _searchBooksFetcher.sink.add(books); } } addBook(Book book, {bool refreshBooks = true, Uint8List? cover}) async { final bookID = await repository.insertBook(book); await _saveCoverToStorage(bookID, cover); if (refreshBooks) { getAllBooksByStatus(); getAllBooks(); } } Future<List<int>> importAdditionalBooks(List<Book> books) async { final importedBookIDs = List<int>.empty(growable: true); for (var book in books) { final id = await repository.insertBook(book); importedBookIDs.add(id); } getAllBooksByStatus(); getAllBooks(); return importedBookIDs; } Future _saveCoverToStorage(int? bookID, Uint8List? cover) async { if (bookID == null || cover == null) return; final file = File('${appDocumentsDirectory.path}/$bookID.jpg'); await file.writeAsBytes(cover); } updateBook(Book book, {Uint8List? cover, BuildContext? context}) async { repository.updateBook(book); await _saveCoverToStorage(book.id!, cover); if (context != null) { // This looks bad but we need to wait for cover to be saved to storage // before updating current book context.read<CurrentBookCubit>().setBook(book.copyWith()); } getBook(book.id!); getAllBooksByStatus(); getAllBooks(); } bulkUpdateBookFormat(Set<int> ids, BookFormat bookFormat) async { repository.bulkUpdateBookFormat(ids, bookFormat); getAllBooksByStatus(); getAllBooks(); } bulkUpdateBookAuthor(Set<int> ids, String author) async { repository.bulkUpdateBookAuthor(ids, author); getAllBooksByStatus(); getAllBooks(); } deleteBook(int id) async { repository.deleteBook(id); getAllBooksByStatus(); getAllBooks(); } Future<Book?> getBook(int id) async { Book? book = await repository.getBook(id); _bookFetcher.sink.add(book); return book; } List<int> _getFinishedYears(List<Book> books) { final years = List<int>.empty(growable: true); for (var book in books) { for (var date in book.readings) { if (date.finishDate != null) { if (!years.contains(date.finishDate!.year)) { //TODO check if years should be duplicated or not years.add(date.finishDate!.year); } } } } years.sort((a, b) => b.compareTo(a)); return years; } List<String> _getTags(List<Book> books) { final tags = List<String>.empty(growable: true); for (var book in books) { if (book.tags != null) { for (var tag in book.tags!.split('|||||')) { if (!tags.contains(tag)) { tags.add(tag); } } } } tags.sort((a, b) => a.compareTo(b)); return tags; } List<String> _getAuthors(List<Book> books) { final authors = List<String>.empty(growable: true); for (var book in books) { if (!authors.contains(book.author)) { authors.add(book.author); } } authors.sort((a, b) => a.compareTo(b)); return authors; } Future<bool> _checkIfCoverMigrationDone() async { final SharedPreferences prefs = await SharedPreferences.getInstance(); final bool? check = prefs.getBool(SharedPreferencesKeys.coverMigrationDone); return check == true ? true : false; } Future<void> _migrateCoversFromDatabaseToStorage() async { List<Book> allBooks = await repository.getAllBooks(); for (var book in allBooks) { if (book.cover != null) { final directory = await getApplicationDocumentsDirectory(); final file = File('${directory.path}/${book.id}.jpg'); await file.writeAsBytes(book.cover!); Book updatedBook = book.copyWithNullCover(); updatedBook = book.copyWith(hasCover: true); await repository.updateBook(updatedBook); } } await _saveCoverMigrationStatus(); } Future<void> _saveCoverMigrationStatus() async { final SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setBool(SharedPreferencesKeys.coverMigrationDone, true); } getBooksWithSameTag(String tag) async { _booksWithSameTagFetcher.sink.add(null); List<Book> books = await repository.getBooksWithSameTag(tag); _booksWithSameTagFetcher.sink.add(books); } getBooksWithSameAuthor(String author) async { _booksWithSameAuthorFetcher.sink.add(null); List<Book> books = await repository.getBooksWithSameAuthor(author); _booksWithSameAuthorFetcher.sink.add(books); } Future<bool> downloadCoverByISBN(Book book) async { if (book.isbn == null) return false; if (book.isbn!.isEmpty) return false; final cover = await OpenLibraryService().getCover(book.isbn!); if (cover == null) return false; final file = File('${appDocumentsDirectory.path}/${book.id}.jpg'); await file.writeAsBytes(cover); final blurHash = _generateBlurHash(cover); await bookCubit.updateBook(book.copyWith( hasCover: true, blurHash: blurHash, )); return true; } static String? _generateBlurHash(Uint8List? cover) { if (cover == null) return null; return blurhash_dart.BlurHash.encode( img.decodeImage(cover)!, numCompX: Constants.blurHashX, numCompY: Constants.blurHashY, ).hash; } }
0
mirrored_repositories/openreads/lib/logic
mirrored_repositories/openreads/lib/logic/cubit/default_book_status_cubit.dart
import 'package:hydrated_bloc/hydrated_bloc.dart'; import 'package:openreads/core/constants/enums/enums.dart'; class DefaultBooksFormatCubit extends HydratedCubit<BookFormat> { DefaultBooksFormatCubit() : super(BookFormat.paperback); setBookFormat(BookFormat bookFormat) => emit(bookFormat); @override BookFormat? fromJson(Map<String, dynamic> json) { return parseBookFormat(json['default_books_format']); } @override Map<String, dynamic>? toJson(BookFormat state) { return { 'default_books_format': state.value, }; } }
0
mirrored_repositories/openreads/lib/logic
mirrored_repositories/openreads/lib/logic/cubit/backup_progress_cubit.dart
import 'package:flutter_bloc/flutter_bloc.dart'; class BackupProgressCubit extends Cubit<String?> { BackupProgressCubit() : super(null); void updateString(String progress) { emit(progress); } void resetString() { emit(null); } }
0
mirrored_repositories/openreads/lib
mirrored_repositories/openreads/lib/generated/locale_keys.g.dart
// DO NOT EDIT. This is code generated via package:easy_localization/generate.dart abstract class LocaleKeys { static const books_finished = 'books_finished'; static const books_in_progress = 'books_in_progress'; static const books_for_later = 'books_for_later'; static const books_unfinished = 'books_unfinished'; static const book_status_finished = 'book_status_finished'; static const book_status_in_progress = 'book_status_in_progress'; static const book_status_for_later = 'book_status_for_later'; static const book_status_unfinished = 'book_status_unfinished'; static const book_format_paperback = 'book_format_paperback'; static const book_format_hardcover = 'book_format_hardcover'; static const book_format_ebook = 'book_format_ebook'; static const book_format_audiobook = 'book_format_audiobook'; static const book_format_paper_plural = 'book_format_paper_plural'; static const book_format_paperback_plural = 'book_format_paperback_plural'; static const book_format_hardcover_plural = 'book_format_hardcover_plural'; static const book_format_ebook_plural = 'book_format_ebook_plural'; static const book_format_audiobook_plural = 'book_format_audiobook_plural'; static const book_format_all = 'book_format_all'; static const add_manually = 'add_manually'; static const add_search = 'add_search'; static const add_scan = 'add_scan'; static const add_book = 'add_book'; static const finished_on_date = 'finished_on_date'; static const started_on_date = 'started_on_date'; static const your_rating = 'your_rating'; static const edit_book = 'edit_book'; static const delete_book = 'delete_book'; static const delete_books = 'delete_books'; static const delete_permanently = 'delete_permanently'; static const restore_book = 'restore_book'; static const yes = 'yes'; static const no = 'no'; static const delete_book_question = 'delete_book_question'; static const delete_books_question = 'delete_books_question'; static const delete_perm_question = 'delete_perm_question'; static const restore_book_question = 'restore_book_question'; static const finish_reading = 'finish_reading'; static const start_reading = 'start_reading'; static const rate_book = 'rate_book'; static const skip = 'skip'; static const pages_uppercase = 'pages_uppercase'; static const pages_lowercase = 'pages_lowercase'; static const click_to_add_cover = 'click_to_add_cover'; static const start_date = 'start_date'; static const finish_date = 'finish_date'; static const edit_cover = 'edit_cover'; static const save = 'save'; static const enter_title = 'enter_title'; static const enter_subtitle = 'enter_subtitle'; static const enter_author = 'enter_author'; static const enter_pages = 'enter_pages'; static const enter_publication_year = 'enter_publication_year'; static const enter_description = 'enter_description'; static const isbn = 'isbn'; static const open_library_ID = 'open_library_ID'; static const enter_tags = 'enter_tags'; static const my_review = 'my_review'; static const notes = 'notes'; static const add_new_book = 'add_new_book'; static const select_start_date = 'select_start_date'; static const select_finish_date = 'select_finish_date'; static const title_cannot_be_empty = 'title_cannot_be_empty'; static const author_cannot_be_empty = 'author_cannot_be_empty'; static const finish_date_before_start = 'finish_date_before_start'; static const title = 'title'; static const author = 'author'; static const rating = 'rating'; static const description = 'description'; static const sort_by = 'sort_by'; static const only_favourite = 'only_favourite'; static const filter_by_finish_year = 'filter_by_finish_year'; static const filter_by_book_format = 'filter_by_book_format'; static const filter_by_tags = 'filter_by_tags'; static const display_tags = 'display_tags'; static const only_books_with_all_tags = 'only_books_with_all_tags'; static const sort_filter = 'sort_filter'; static const statistics = 'statistics'; static const settings = 'settings'; static const this_list_is_empty_1 = 'this_list_is_empty_1'; static const this_list_is_empty_2 = 'this_list_is_empty_2'; static const no_cover = 'no_cover'; static const choose_edition = 'choose_edition'; static const editions_lowercase = 'editions_lowercase'; static const published_lowercase = 'published_lowercase'; static const cancel = 'cancel'; static const flash_on = 'flash_on'; static const flash_off = 'flash_off'; static const search_in_books = 'search_in_books'; static const search = 'search'; static const results_lowercase = 'results_lowercase'; static const click_here_to_set_challenge = 'click_here_to_set_challenge'; static const set_books_goal_for_year = 'set_books_goal_for_year'; static const add_pages_goal = 'add_pages_goal'; static const set_pages_goal = 'set_pages_goal'; static const books_challenge = 'books_challenge'; static const pages_challenge = 'pages_challenge'; static const all_years = 'all_years'; static const all_books_by_status = 'all_books_by_status'; static const finished_books_by_month = 'finished_books_by_month'; static const finished_pages_by_month = 'finished_pages_by_month'; static const average_rating = 'average_rating'; static const average_pages = 'average_pages'; static const average_reading_time = 'average_reading_time'; static const longest_book = 'longest_book'; static const shortest_book = 'shortest_book'; static const fastest_book = 'fastest_book'; static const slowest_book = 'slowest_book'; static const january_short = 'january_short'; static const february_short = 'february_short'; static const march_short = 'march_short'; static const april_short = 'april_short'; static const may_short = 'may_short'; static const june_short = 'june_short'; static const july_short = 'july_short'; static const august_short = 'august_short'; static const september_short = 'september_short'; static const october_short = 'october_short'; static const november_short = 'november_short'; static const december_short = 'december_short'; static const language = 'language'; static const select_language = 'select_language'; static const default_locale = 'default_locale'; static const accent_color = 'accent_color'; static const material_you = 'material_you'; static const use_material_you = 'use_material_you'; static const select_accent_color = 'select_accent_color'; static const select_color = 'select_color'; static const standard_color = 'standard_color'; static const custom_color = 'custom_color'; static const rating_type = 'rating_type'; static const seletct_rating_type = 'seletct_rating_type'; static const rating_as_bar = 'rating_as_bar'; static const rating_as_number = 'rating_as_number'; static const theme_mode = 'theme_mode'; static const select_theme_mode = 'select_theme_mode'; static const theme_mode_system = 'theme_mode_system'; static const theme_mode_light = 'theme_mode_light'; static const theme_mode_dark = 'theme_mode_dark'; static const font = 'font'; static const select_font = 'select_font'; static const font_default = 'font_default'; static const display_outlines = 'display_outlines'; static const show_outlines = 'show_outlines'; static const hide_outlines = 'hide_outlines'; static const rounded_corners = 'rounded_corners'; static const select_corner_radius = 'select_corner_radius'; static const no_rounded_corners = 'no_rounded_corners'; static const small_rounded_corners = 'small_rounded_corners'; static const medium_rounded_corners = 'medium_rounded_corners'; static const big_rounded_corners = 'big_rounded_corners'; static const tabs_order = 'tabs_order'; static const select_tabs_order = 'select_tabs_order'; static const tabs_order_read_first = 'tabs_order_read_first'; static const tabs_order_in_progress_first = 'tabs_order_in_progress_first'; static const send_feedback = 'send_feedback'; static const report_bugs_or_ideas = 'report_bugs_or_ideas'; static const send_dev_email = 'send_dev_email'; static const raise_github_issue = 'raise_github_issue'; static const deleted_books = 'deleted_books'; static const unfinished_books = 'unfinished_books'; static const finished_books = 'finished_books'; static const finished_pages = 'finished_pages'; static const backup_and_restore = 'backup_and_restore'; static const no_deleted_books = 'no_deleted_books'; static const no_unfinished_books = 'no_unfinished_books'; static const join_community = 'join_community'; static const join_community_description = 'join_community_description'; static const rate_app = 'rate_app'; static const rate_app_description = 'rate_app_description'; static const translate_app = 'translate_app'; static const translate_app_description = 'translate_app_description'; static const app = 'app'; static const apperance = 'apperance'; static const about = 'about'; static const version = 'version'; static const source_code = 'source_code'; static const source_code_description = 'source_code_description'; static const changelog = 'changelog'; static const changelog_description = 'changelog_description'; static const licence = 'licence'; static const support_the_project = 'support_the_project'; static const support_the_project_description = 'support_the_project_description'; static const support_option_1 = 'support_option_1'; static const support_option_2 = 'support_option_2'; static const need_storage_permission = 'need_storage_permission'; static const open_settings = 'open_settings'; static const backup_successfull = 'backup_successfull'; static const choose_backup_folder = 'choose_backup_folder'; static const save_file_to_this_folder = 'save_file_to_this_folder'; static const restored = 'restored'; static const backup_not_valid = 'backup_not_valid'; static const restore_successfull = 'restore_successfull'; static const choose_backup_file = 'choose_backup_file'; static const use_this_file = 'use_this_file'; static const backup = 'backup'; static const create_local_backup = 'create_local_backup'; static const create_local_backup_description = 'create_local_backup_description'; static const create_cloud_backup = 'create_cloud_backup'; static const create_cloud_backup_description = 'create_cloud_backup_description'; static const restore_backup = 'restore_backup'; static const restore_backup_description_1 = 'restore_backup_description_1'; static const restore_backup_description_2 = 'restore_backup_description_2'; static const are_you_sure = 'are_you_sure'; static const restore_backup_alert_content = 'restore_backup_alert_content'; static const add_books_and_come_back = 'add_books_and_come_back'; static const welcome_1 = 'welcome_1'; static const welcome_1_description_1 = 'welcome_1_description_1'; static const welcome_1_description_2 = 'welcome_1_description_2'; static const welcome_2_description_1 = 'welcome_2_description_1'; static const welcome_2_description_2 = 'welcome_2_description_2'; static const welcome_3_description_1 = 'welcome_3_description_1'; static const welcome_3_description_2 = 'welcome_3_description_2'; static const welcome_3_description_3 = 'welcome_3_description_3'; static const start_button = 'start_button'; static const migration_v1_to_v2_1 = 'migration_v1_to_v2_1'; static const migration_v1_to_v2_2 = 'migration_v1_to_v2_2'; static const migration_v1_to_v2_finished = 'migration_v1_to_v2_finished'; static const migration_v1_to_v2_retrigger = 'migration_v1_to_v2_retrigger'; static const migration_v1_to_v2_retrigger_description = 'migration_v1_to_v2_retrigger_description'; static const dark_mode_style = 'dark_mode_style'; static const dark_mode_natural = 'dark_mode_natural'; static const dark_mode_amoled = 'dark_mode_amoled'; static const selected = 'selected'; static const change_book_format = 'change_book_format'; static const change_books_author = 'change_books_author'; static const update_successful_message = 'update_successful_message'; static const bulk_update_unsuccessful_message = 'bulk_update_unsuccessful_message'; static const export_successful = 'export_successful'; static const openreads_backup = 'openreads_backup'; static const csv = 'csv'; static const export_csv = 'export_csv'; static const export_csv_description_1 = 'export_csv_description_1'; static const import_goodreads_csv = 'import_goodreads_csv'; static const import_bookwyrm_csv = 'import_bookwyrm_csv'; static const import_csv = 'import_csv'; static const choose_not_finished_shelf = 'choose_not_finished_shelf'; static const import_successful = 'import_successful'; static const ok = 'ok'; static const daysSetCustomTimeTitle = 'day.set_custom_time_title'; static const day = 'day'; static const hoursSetCustomTimeTitle = 'hour.set_custom_time_title'; static const hour = 'hour'; static const minutesSetCustomTimeTitle = 'minute.set_custom_time_title'; static const minute = 'minute'; static const set_custom_reading_time = 'set_custom_reading_time'; static const select_all = 'select_all'; static const only_editions_with_covers = 'only_editions_with_covers'; static const general_search = 'general_search'; static const no_search_results = 'no_search_results'; static const click_to_add_book_manually = 'click_to_add_book_manually'; static const load_cover_from_phone = 'load_cover_from_phone'; static const get_cover_from_open_library = 'get_cover_from_open_library'; static const edit_current_cover = 'edit_current_cover'; static const isbn_cannot_be_empty = 'isbn_cannot_be_empty'; static const cover_not_found_in_ol = 'cover_not_found_in_ol'; static const books_settings = 'books_settings'; static const download_missing_covers = 'download_missing_covers'; static const download_missing_covers_explanation = 'download_missing_covers_explanation'; static const downloaded_covers = 'downloaded_covers'; static const try_downloading_covers = 'try_downloading_covers'; static const filter_out_selected_tags = 'filter_out_selected_tags'; static const add_additional_reading_time = 'add_additional_reading_time'; static const start_adding_books = 'start_adding_books'; static const help_to_get_started = 'help_to_get_started'; static const owned_book_tag = 'owned_book_tag'; static const read_x_times = 'read_x_times'; static const date_added = 'date_added'; static const date_modified = 'date_modified'; static const added_on = 'added_on'; static const modified_on = 'modified_on'; static const default_books_format = 'default_books_format'; static const coverStillDownloaded = 'cover_still_downloaded'; static const waitForDownloadingToFinish = 'wait_for_downloading_to_finish'; static const saveWithoutCover = 'save_without_cover'; static const searchOnlineForCover = 'search_online_for_cover'; static const bookCover = 'book_cover'; static const duplicateBook = 'duplicate_book'; static const copyBook = 'copy_book'; static const duckDuckGoWarning = 'duck_duck_go_warning'; static const warningYes = 'warning_yes'; static const warningNo = 'warning_no'; static const warningYesAndDontShow = 'warning_yes_and_dont_show'; }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/trash_screen/trash_screen.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/books_screen/widgets/widgets.dart'; class TrashScreen extends StatelessWidget { const TrashScreen({super.key}); @override Widget build(BuildContext context) { bookCubit.getDeletedBooks(); return Scaffold( appBar: AppBar( title: Text( LocaleKeys.deleted_books.tr(), style: const TextStyle(fontSize: 18), ), ), body: StreamBuilder<List<Book>>( stream: bookCubit.deletedBooks, builder: (context, AsyncSnapshot<List<Book>> snapshot) { if (snapshot.hasData) { if (snapshot.data == null || snapshot.data!.isEmpty) { return Center( child: Padding( padding: const EdgeInsets.all(50), child: Text( LocaleKeys.no_deleted_books.tr(), textAlign: TextAlign.center, style: const TextStyle( letterSpacing: 1.5, fontSize: 16, ), ), ), ); } return BooksList( books: snapshot.data!, listNumber: 5, allBooksCount: null, ); } else if (snapshot.hasError) { return Text( snapshot.error.toString(), ); } else { return const SizedBox(); } }, ), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/settings_screen/settings_apperance_screen.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flex_color_picker/flex_color_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/rating_type_bloc/rating_type_bloc.dart'; import 'package:openreads/logic/bloc/theme_bloc/theme_bloc.dart'; import 'package:openreads/ui/settings_screen/settings_accent_screen.dart'; import 'package:openreads/ui/settings_screen/widgets/widgets.dart'; import 'package:settings_ui/settings_ui.dart'; class SettingsApperanceScreen extends StatelessWidget { const SettingsApperanceScreen({super.key}); _showThemeModeDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), backgroundColor: Theme.of(context).colorScheme.surface, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), child: BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { if (state is SetThemeState) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.only(left: 10), child: Text( LocaleKeys.select_theme_mode.tr(), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), const SizedBox(height: 15), SettingsDialogButton( text: LocaleKeys.theme_mode_system.tr(), onPressed: () => _setThemeModeAuto(context, state), ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.theme_mode_light.tr(), onPressed: () => _setThemeModeLight(context, state), ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.theme_mode_dark.tr(), onPressed: () => _setThemeModeDark(context, state), ), ], ); } else { return const SizedBox(); } }, ), ), ); }, ); } _showDarkModeDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), backgroundColor: Theme.of(context).colorScheme.surface, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), child: BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { if (state is SetThemeState) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.only(left: 10), child: Text( LocaleKeys.dark_mode_style.tr(), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), const SizedBox(height: 15), SettingsDialogButton( text: LocaleKeys.dark_mode_natural.tr(), onPressed: () => _setDarkMode(context, state, false), ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.dark_mode_amoled.tr(), onPressed: () => _setDarkMode(context, state, true), ), ], ); } else { return const SizedBox(); } }, ), ), ); }, ); } _showFontDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), backgroundColor: Theme.of(context).colorScheme.surface, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), child: BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { if (state is SetThemeState) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(left: 10), child: Text( LocaleKeys.select_font.tr(), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), const SizedBox(height: 15), Expanded( child: Scrollbar( thumbVisibility: true, child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ SettingsDialogButton( text: LocaleKeys.font_default.tr(), onPressed: () => _setFont( context, state, Font.system, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Atkinson Hyperlegible', fontFamily: 'AtkinsonHyperlegible', onPressed: () => _setFont( context, state, Font.atkinsonHyperlegible, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Open Dyslexic', fontFamily: 'OpenDyslexic', onPressed: () => _setFont( context, state, Font.openDyslexic, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Nunito', fontFamily: 'Nunito', onPressed: () => _setFont( context, state, Font.nunito, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Jost', fontFamily: 'Jost', onPressed: () => _setFont( context, state, Font.jost, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Barlow', fontFamily: 'Barlow', onPressed: () => _setFont( context, state, Font.barlow, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Inter', fontFamily: 'Inter', onPressed: () => _setFont( context, state, Font.inter, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Kanit', fontFamily: 'Kanit', onPressed: () => _setFont( context, state, Font.kanit, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Lato', fontFamily: 'Lato', onPressed: () => _setFont( context, state, Font.lato, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Lora', fontFamily: 'Lora', onPressed: () => _setFont( context, state, Font.lora, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Montserrat', fontFamily: 'Montserrat', onPressed: () => _setFont( context, state, Font.montserrat, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Playfair Display', fontFamily: 'PlayfairDisplay', onPressed: () => _setFont( context, state, Font.playfairDisplay, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Poppins', fontFamily: 'Poppins', onPressed: () => _setFont( context, state, Font.poppins, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Raleway', fontFamily: 'Raleway', onPressed: () => _setFont( context, state, Font.raleway, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Sofia Sans', fontFamily: 'SofiaSans', onPressed: () => _setFont( context, state, Font.sofiaSans, ), ), const SizedBox(height: 5), SettingsDialogButton( text: 'Quicksand', fontFamily: 'Quicksand', onPressed: () => _setFont( context, state, Font.quicksand, ), ), ], ), ), ), ), ], ); } else { return const SizedBox(); } }, ), ), ); }, ); } _showOutlinesDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), backgroundColor: Theme.of(context).colorScheme.surface, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), child: BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { if (state is SetThemeState) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.only(left: 10), child: Text( LocaleKeys.display_outlines.tr(), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), const SizedBox(height: 15), SettingsDialogButton( text: LocaleKeys.show_outlines.tr(), onPressed: () => _showOutlines(context, state), ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.hide_outlines.tr(), onPressed: () => _hideOutlines(context, state), ), ], ); } else { return const SizedBox(); } }, ), ), ); }, ); } _showCornerRadiusDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), backgroundColor: Theme.of(context).colorScheme.surface, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), child: BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { if (state is SetThemeState) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.only(left: 10), child: Text( LocaleKeys.select_corner_radius.tr(), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), const SizedBox(height: 15), SettingsDialogButton( text: LocaleKeys.no_rounded_corners.tr(), onPressed: () => _changeCornerRadius(context, state, 0), ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.small_rounded_corners.tr(), onPressed: () => _changeCornerRadius(context, state, 5), ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.medium_rounded_corners.tr(), onPressed: () => _changeCornerRadius(context, state, 10), ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.big_rounded_corners.tr(), onPressed: () => _changeCornerRadius(context, state, 20), ), ], ); } else { return const SizedBox(); } }, ), ), ); }, ); } _showTabsOrderDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), backgroundColor: Theme.of(context).colorScheme.surface, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), child: BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { if (state is SetThemeState) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.only(left: 10), child: Text( LocaleKeys.select_tabs_order.tr(), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), const SizedBox(height: 15), SettingsDialogButton( text: LocaleKeys.tabs_order_read_first.tr(), onPressed: () { BlocProvider.of<ThemeBloc>(context).add( ChangeThemeEvent( themeMode: state.themeMode, showOutlines: state.showOutlines, cornerRadius: state.cornerRadius, primaryColor: state.primaryColor, fontFamily: state.fontFamily, readTabFirst: true, useMaterialYou: state.useMaterialYou, amoledDark: state.amoledDark, ), ); Navigator.of(context).pop(); }, ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.tabs_order_in_progress_first.tr(), onPressed: () { BlocProvider.of<ThemeBloc>(context).add( ChangeThemeEvent( themeMode: state.themeMode, showOutlines: state.showOutlines, cornerRadius: state.cornerRadius, primaryColor: state.primaryColor, fontFamily: state.fontFamily, readTabFirst: false, useMaterialYou: state.useMaterialYou, amoledDark: state.amoledDark, ), ); Navigator.of(context).pop(); }, ), ], ); } else { return const SizedBox(); } }, ), ), ); }, ); } _setThemeModeAuto(BuildContext context, SetThemeState state) { BlocProvider.of<ThemeBloc>(context).add(ChangeThemeEvent( themeMode: ThemeMode.system, showOutlines: state.showOutlines, cornerRadius: state.cornerRadius, primaryColor: state.primaryColor, fontFamily: state.fontFamily, readTabFirst: state.readTabFirst, useMaterialYou: state.useMaterialYou, amoledDark: state.amoledDark, )); Navigator.of(context).pop(); } _setThemeModeLight(BuildContext context, SetThemeState state) { BlocProvider.of<ThemeBloc>(context).add(ChangeThemeEvent( themeMode: ThemeMode.light, showOutlines: state.showOutlines, cornerRadius: state.cornerRadius, primaryColor: state.primaryColor, fontFamily: state.fontFamily, readTabFirst: state.readTabFirst, useMaterialYou: state.useMaterialYou, amoledDark: state.amoledDark, )); Navigator.of(context).pop(); } _setThemeModeDark(BuildContext context, SetThemeState state) { BlocProvider.of<ThemeBloc>(context).add(ChangeThemeEvent( themeMode: ThemeMode.dark, showOutlines: state.showOutlines, cornerRadius: state.cornerRadius, primaryColor: state.primaryColor, fontFamily: state.fontFamily, readTabFirst: state.readTabFirst, useMaterialYou: state.useMaterialYou, amoledDark: state.amoledDark, )); Navigator.of(context).pop(); } _setDarkMode(BuildContext context, SetThemeState state, bool amoledDark) { BlocProvider.of<ThemeBloc>(context).add(ChangeThemeEvent( themeMode: ThemeMode.dark, showOutlines: state.showOutlines, cornerRadius: state.cornerRadius, primaryColor: state.primaryColor, fontFamily: state.fontFamily, readTabFirst: state.readTabFirst, useMaterialYou: state.useMaterialYou, amoledDark: amoledDark, )); Navigator.of(context).pop(); } _setFont( BuildContext context, SetThemeState state, Font font, ) { String? fontFamily; switch (font) { case Font.system: fontFamily = null; break; case Font.montserrat: fontFamily = 'Montserrat'; break; case Font.lato: fontFamily = 'Lato'; break; case Font.sofiaSans: fontFamily = 'SofiaSans'; break; case Font.poppins: fontFamily = 'Poppins'; break; case Font.raleway: fontFamily = 'Raleway'; break; case Font.nunito: fontFamily = 'Nunito'; break; case Font.playfairDisplay: fontFamily = 'PlayfairDisplay'; break; case Font.kanit: fontFamily = 'Kanit'; break; case Font.lora: fontFamily = 'Lora'; break; case Font.quicksand: fontFamily = 'Quicksand'; break; case Font.barlow: fontFamily = 'Barlow'; break; case Font.inter: fontFamily = 'Inter'; break; case Font.jost: fontFamily = 'Jost'; break; case Font.atkinsonHyperlegible: fontFamily = 'AtkinsonHyperlegible'; break; case Font.openDyslexic: fontFamily = 'OpenDyslexic'; break; default: fontFamily = 'Nunito'; break; } BlocProvider.of<ThemeBloc>(context).add(ChangeThemeEvent( themeMode: state.themeMode, showOutlines: state.showOutlines, cornerRadius: state.cornerRadius, primaryColor: state.primaryColor, fontFamily: fontFamily, readTabFirst: state.readTabFirst, useMaterialYou: state.useMaterialYou, amoledDark: state.amoledDark, )); Navigator.of(context).pop(); } _showOutlines(BuildContext context, SetThemeState state) { BlocProvider.of<ThemeBloc>(context).add(ChangeThemeEvent( themeMode: state.themeMode, showOutlines: true, cornerRadius: state.cornerRadius, primaryColor: state.primaryColor, fontFamily: state.fontFamily, readTabFirst: state.readTabFirst, useMaterialYou: state.useMaterialYou, amoledDark: state.amoledDark, )); Navigator.of(context).pop(); } _hideOutlines(BuildContext context, SetThemeState state) { BlocProvider.of<ThemeBloc>(context).add(ChangeThemeEvent( themeMode: state.themeMode, showOutlines: false, cornerRadius: state.cornerRadius, primaryColor: state.primaryColor, fontFamily: state.fontFamily, readTabFirst: state.readTabFirst, useMaterialYou: state.useMaterialYou, amoledDark: state.amoledDark, )); Navigator.of(context).pop(); } _changeCornerRadius( BuildContext context, SetThemeState state, double radius) { BlocProvider.of<ThemeBloc>(context).add(ChangeThemeEvent( themeMode: state.themeMode, showOutlines: state.showOutlines, cornerRadius: radius, primaryColor: state.primaryColor, fontFamily: state.fontFamily, readTabFirst: state.readTabFirst, useMaterialYou: state.useMaterialYou, amoledDark: state.amoledDark, )); Navigator.of(context).pop(); } _showRatingBarDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), backgroundColor: Theme.of(context).colorScheme.surface, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.only(left: 10), child: Text( LocaleKeys.seletct_rating_type.tr(), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), const SizedBox(height: 15), SettingsDialogButton( text: LocaleKeys.rating_as_bar.tr(), onPressed: () { BlocProvider.of<RatingTypeBloc>(context).add( const RatingTypeChange(ratingType: RatingType.bar), ); Navigator.of(context).pop(); }, ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.rating_as_number.tr(), onPressed: () { BlocProvider.of<RatingTypeBloc>(context).add( const RatingTypeChange(ratingType: RatingType.number), ); Navigator.of(context).pop(); }, ), ], ), ), ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( LocaleKeys.apperance.tr(), style: const TextStyle(fontSize: 18), ), ), body: BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { late final bool amoledDark; if (state is SetThemeState) { amoledDark = state.amoledDark; } else { amoledDark = false; } return SettingsList( contentPadding: const EdgeInsets.only(top: 10), darkTheme: SettingsThemeData( settingsListBackground: amoledDark ? Colors.black : Theme.of(context).colorScheme.surface, ), lightTheme: SettingsThemeData( settingsListBackground: Theme.of(context).colorScheme.surface, ), sections: [ SettingsSection( tiles: <SettingsTile>[ _buildAccentSetting(context), _buildThemeModeSetting(context), _buildDarkModeSetting(context), _buildFontSetting(context), _buildRatingTypeSetting(context), _buildTabOrderSetting(context), _buildOutlinesSetting(context), _buildCornersSetting(context), ], ), ], ); }, ), ); } SettingsTile _buildThemeModeSetting(BuildContext context) { return SettingsTile( title: Text( LocaleKeys.theme_mode.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon(Icons.sunny), description: BlocBuilder<ThemeBloc, ThemeState>( builder: (_, themeState) { if (themeState is SetThemeState) { switch (themeState.themeMode) { case ThemeMode.light: return Text( LocaleKeys.theme_mode_light.tr(), style: const TextStyle(), ); case ThemeMode.dark: return Text( LocaleKeys.theme_mode_dark.tr(), style: const TextStyle(), ); default: return Text( LocaleKeys.theme_mode_system.tr(), style: const TextStyle(), ); } } else { return const SizedBox(); } }, ), onPressed: (context) => _showThemeModeDialog(context), ); } SettingsTile _buildDarkModeSetting(BuildContext context) { return SettingsTile( title: Text( LocaleKeys.dark_mode_style.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon(Icons.contrast), description: BlocBuilder<ThemeBloc, ThemeState>( builder: (_, themeState) { if (themeState is SetThemeState) { if (themeState.amoledDark) { return Text( LocaleKeys.dark_mode_amoled.tr(), style: const TextStyle(), ); } else { return Text( LocaleKeys.dark_mode_natural.tr(), style: const TextStyle(), ); } } else { return const SizedBox(); } }, ), onPressed: (context) => _showDarkModeDialog(context), ); } SettingsTile _buildFontSetting(BuildContext context) { return SettingsTile( title: Text( LocaleKeys.font.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon( Icons.font_download, size: 22, ), description: BlocBuilder<ThemeBloc, ThemeState>( builder: (_, state) { if (state is SetThemeState) { if (state.fontFamily != null) { return Text( state.fontFamily!, style: const TextStyle(), ); } else { return Text( LocaleKeys.font_default.tr(), style: const TextStyle(), ); } } else { return const SizedBox(); } }, ), onPressed: (context) => _showFontDialog(context), ); } SettingsTile _buildRatingTypeSetting(BuildContext context) { return SettingsTile( title: Text( LocaleKeys.rating_type.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon(Icons.star_rounded), description: BlocBuilder<RatingTypeBloc, RatingTypeState>( builder: (_, state) { if (state is RatingTypeNumber) { return Text( LocaleKeys.rating_as_number.tr(), style: const TextStyle(), ); } else if (state is RatingTypeBar) { return Text( LocaleKeys.rating_as_bar.tr(), style: const TextStyle(), ); } else { return const SizedBox(); } }, ), onPressed: (context) => _showRatingBarDialog(context), ); } SettingsTile _buildTabOrderSetting(BuildContext context) { return SettingsTile( title: Text( LocaleKeys.tabs_order.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const FaIcon( FontAwesomeIcons.tableColumns, size: 22, ), description: BlocBuilder<ThemeBloc, ThemeState>( builder: (_, state) { if (state is SetThemeState) { if (state.readTabFirst) { return Text( LocaleKeys.tabs_order_read_first.tr(), style: const TextStyle(), ); } else { return Text( LocaleKeys.tabs_order_in_progress_first.tr(), style: const TextStyle(), ); } } else { return const SizedBox(); } }, ), onPressed: (context) => _showTabsOrderDialog(context), ); } SettingsTile _buildAccentSetting(BuildContext context) { return SettingsTile.navigation( title: Text( LocaleKeys.accent_color.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon(Icons.color_lens), description: BlocBuilder<ThemeBloc, ThemeState>( builder: (_, themeState) { if (themeState is SetThemeState) { if (themeState.useMaterialYou) { return Text( LocaleKeys.material_you.tr(), style: const TextStyle(), ); } else { return Text( '0xFF${themeState.primaryColor.hex}', style: const TextStyle(), ); } } else { return const SizedBox(); } }, ), onPressed: (context) { Navigator.of(context).push( MaterialPageRoute( builder: (_) => const SettingsAccentScreen(), ), ); }, ); } SettingsTile _buildCornersSetting(BuildContext context) { return SettingsTile( title: Text( LocaleKeys.rounded_corners.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon(Icons.rounded_corner_rounded), description: BlocBuilder<ThemeBloc, ThemeState>( builder: (_, themeState) { if (themeState is SetThemeState) { if (themeState.cornerRadius == 5) { return Text( LocaleKeys.small_rounded_corners.tr(), style: const TextStyle(), ); } else if (themeState.cornerRadius == 10) { return Text( LocaleKeys.medium_rounded_corners.tr(), style: const TextStyle(), ); } else if (themeState.cornerRadius == 20) { return Text( LocaleKeys.big_rounded_corners.tr(), style: const TextStyle(), ); } else { return Text( LocaleKeys.no_rounded_corners.tr(), style: const TextStyle(), ); } } else { return const SizedBox(); } }, ), onPressed: (context) => _showCornerRadiusDialog(context), ); } SettingsTile _buildOutlinesSetting(BuildContext context) { return SettingsTile( title: Text( LocaleKeys.display_outlines.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon(Icons.check_box_outline_blank_rounded), description: BlocBuilder<ThemeBloc, ThemeState>( builder: (_, themeState) { if (themeState is SetThemeState) { if (themeState.showOutlines) { return Text( LocaleKeys.show_outlines.tr(), style: const TextStyle(), ); } else { return Text( LocaleKeys.hide_outlines.tr(), style: const TextStyle(), ); } } else { return const SizedBox(); } }, ), onPressed: (context) => _showOutlinesDialog(context), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/settings_screen/settings_accent_screen.dart
import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; import 'package:flex_color_picker/flex_color_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/theme_bloc/theme_bloc.dart'; class SettingsAccentScreen extends StatefulWidget { const SettingsAccentScreen({super.key}); @override State<SettingsAccentScreen> createState() => _SettingsAccentScreenState(); } class _SettingsAccentScreenState extends State<SettingsAccentScreen> { late Color pickerColor; _setMaterialYou(BuildContext context) { BlocProvider.of<ThemeBloc>(context).add(const ChangeAccentEvent( primaryColor: null, useMaterialYou: true, )); Navigator.of(context).pop(); } _setCustomColor(BuildContext context) { BlocProvider.of<ThemeBloc>(context).add(ChangeAccentEvent( primaryColor: pickerColor, useMaterialYou: false, )); Navigator.of(context).pop(); } @override void initState() { super.initState(); final state = context.read<ThemeBloc>().state; if (state is SetThemeState) { pickerColor = state.primaryColor; } else { pickerColor = Colors.blue; } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(LocaleKeys.select_accent_color.tr()), ), body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(8), child: Column( children: [ Platform.isAndroid ? Padding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 24), child: Row( children: [ Expanded( child: FilledButton( onPressed: () => _setMaterialYou(context), style: FilledButton.styleFrom( textStyle: const TextStyle(fontSize: 18), ), child: Text(LocaleKeys.use_material_you.tr()), ), ), ], ), ) : const SizedBox(), Card( child: ColorPicker( color: pickerColor, showColorCode: true, colorCodeReadOnly: false, enableShadesSelection: false, borderRadius: 50, columnSpacing: 12, wheelSquarePadding: 16, onColorChanged: (Color color) => setState( () => pickerColor = color, ), heading: Text( LocaleKeys.select_color.tr(), style: Theme.of(context).textTheme.headlineSmall, ), pickerTypeLabels: <ColorPickerType, String>{ ColorPickerType.primary: LocaleKeys.standard_color.tr(), ColorPickerType.wheel: LocaleKeys.custom_color.tr(), }, pickersEnabled: const <ColorPickerType, bool>{ ColorPickerType.both: false, ColorPickerType.primary: true, ColorPickerType.accent: false, ColorPickerType.wheel: true, }, ), ), Padding( padding: const EdgeInsets.fromLTRB(8, 24, 8, 16), child: Row( children: [ Expanded( child: FilledButton( style: FilledButton.styleFrom( backgroundColor: pickerColor, textStyle: const TextStyle(fontSize: 18), ), onPressed: () => _setCustomColor(context), child: Text(LocaleKeys.save.tr()), ), ), ], ), ), ], ), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/settings_screen/settings_backup_screen.dart
import 'dart:io'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:openreads/core/helpers/backup/backup.dart'; import 'package:openreads/logic/bloc/migration_v1_to_v2_bloc/migration_v1_to_v2_bloc.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/theme_bloc/theme_bloc.dart'; import 'package:openreads/logic/cubit/backup_progress_cubit.dart'; import 'package:openreads/ui/welcome_screen/widgets/widgets.dart'; import 'package:settings_ui/settings_ui.dart'; import 'package:share_plus/share_plus.dart'; class SettingsBackupScreen extends StatefulWidget { const SettingsBackupScreen({ super.key, this.autoMigrationV1ToV2 = false, }); final bool autoMigrationV1ToV2; @override State<SettingsBackupScreen> createState() => _SettingsBackupScreenState(); } class _SettingsBackupScreenState extends State<SettingsBackupScreen> { bool _creatingLocal = false; bool _creatingCloud = false; bool _restoringLocal = false; bool _exportingCSV = false; bool _importingGoodreadsCSV = false; bool _importingBookwyrmCSV = false; bool _importingCSV = false; late DeviceInfoPlugin deviceInfo; late AndroidDeviceInfo androidInfo; _startCreatingLocalBackup(context) async { setState(() => _creatingLocal = true); if (Platform.isAndroid) { if (androidInfo.version.sdkInt < 30) { await BackupGeneral.requestStoragePermission(context); await BackupExport.createLocalBackupLegacyStorage(context); } else { await BackupExport.createLocalBackup(context); } } else if (Platform.isIOS) { await BackupExport.createLocalBackup(context); } setState(() => _creatingLocal = false); } _startExportingCSV(context) async { setState(() => _exportingCSV = true); if (Platform.isAndroid) { if (androidInfo.version.sdkInt < 30) { await BackupGeneral.requestStoragePermission(context); await CSVExport.exportCSVLegacyStorage(context); } else { await CSVExport.exportCSV(); } } else if (Platform.isIOS) { await CSVExport.exportCSV(); } setState(() => _exportingCSV = false); } _startImportingGoodreadsCSV(context) async { setState(() => _importingGoodreadsCSV = true); if (Platform.isAndroid) { if (androidInfo.version.sdkInt < 30) { await BackupGeneral.requestStoragePermission(context); await CSVImportGoodreads.importCSVLegacyStorage(context); } else { await CSVImportGoodreads.importCSV(context); } } else if (Platform.isIOS) { await CSVImportGoodreads.importCSV(context); } setState(() => _importingGoodreadsCSV = false); } _startImportingBookwyrmCSV(context) async { setState(() => _importingBookwyrmCSV = true); if (Platform.isAndroid) { if (androidInfo.version.sdkInt < 30) { await BackupGeneral.requestStoragePermission(context); await CSVImportBookwyrm.importCSVLegacyStorage(context); } else { await CSVImportBookwyrm.importCSV(context); } } else if (Platform.isIOS) { await CSVImportBookwyrm.importCSV(context); } setState(() => _importingBookwyrmCSV = false); } _startImportingCSV(context) async { setState(() => _importingCSV = true); if (Platform.isAndroid) { if (androidInfo.version.sdkInt < 30) { await BackupGeneral.requestStoragePermission(context); await CSVImportOpenreads.importCSVLegacyStorage(context); } else { await CSVImportOpenreads.importCSV(context); } } else if (Platform.isIOS) { await CSVImportOpenreads.importCSV(context); } setState(() => _importingCSV = false); } _startCreatingCloudBackup(context) async { setState(() => _creatingCloud = true); final tmpBackupPath = await BackupExport.prepareTemporaryBackup(context); if (tmpBackupPath == null) return; Share.shareXFiles([ XFile(tmpBackupPath), ]); setState(() => _creatingCloud = false); } _startRestoringLocalBackup(context) async { setState(() => _restoringLocal = true); if (Platform.isAndroid) { if (androidInfo.version.sdkInt < 30) { await BackupGeneral.requestStoragePermission(context); await BackupImport.restoreLocalBackupLegacyStorage(context); } else { await BackupImport.restoreLocalBackup(context); } } else if (Platform.isIOS) { await BackupImport.restoreLocalBackup(context); } setState(() => _restoringLocal = false); } _startMigratingV1ToV2() { BlocProvider.of<MigrationV1ToV2Bloc>(context).add( StartMigration(context: context, retrigger: true), ); } initDeviceInfoPlugin() async { androidInfo = await DeviceInfoPlugin().androidInfo; } @override void initState() { if (Platform.isAndroid) { initDeviceInfoPlugin(); } super.initState(); } @override Widget build(BuildContext originalContext) { return BlocProvider( create: (context) => BackupProgressCubit(), child: Builder(builder: (context) { return Scaffold( appBar: AppBar( title: Text( LocaleKeys.backup.tr(), style: const TextStyle(fontSize: 18), ), ), body: Column( children: [ BlocBuilder<BackupProgressCubit, String?>( builder: (context, state) { if (state == null) return const SizedBox(); return Row( children: [ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const LinearProgressIndicator(), Container( padding: const EdgeInsets.fromLTRB(20, 10, 20, 0), child: Text( state, textAlign: TextAlign.center, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ], ), ), ], ); }, ), Expanded( child: BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { late final bool amoledDark; if (state is SetThemeState) { amoledDark = state.amoledDark; } else { amoledDark = false; } return SettingsList( contentPadding: const EdgeInsets.only(top: 10), darkTheme: SettingsThemeData( settingsListBackground: amoledDark ? Colors.black : Theme.of(context).colorScheme.surface, ), lightTheme: SettingsThemeData( settingsListBackground: Theme.of(context).colorScheme.surface, ), sections: [ _buildBackupSection(context), SettingsSection( title: Text( LocaleKeys.csv.tr(), style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.primary, ), ), tiles: <SettingsTile>[ _buildExportAsCSV(), _buildImportCSV(), _buildImportGoodreadsCSV(), _buildImportBookwyrmCSV(), ], ), ], ); }, ), ), BlocBuilder<MigrationV1ToV2Bloc, MigrationV1ToV2State>( builder: (context, migrationState) { if (migrationState is MigrationOnging) { return MigrationNotification( done: migrationState.done, total: migrationState.total, ); } else if (migrationState is MigrationFailed) { return MigrationNotification( error: migrationState.error, ); } else if (migrationState is MigrationSucceded) { return const MigrationNotification( success: true, ); } return const SizedBox(); }, ), ], ), ); }), ); } SettingsTile _buildV1ToV2Migration(BuildContext context) { return SettingsTile( title: Text( LocaleKeys.migration_v1_to_v2_retrigger.tr(), style: TextStyle( fontSize: 16, color: widget.autoMigrationV1ToV2 ? Theme.of(context).colorScheme.primary : null, ), ), leading: Icon( FontAwesomeIcons.wrench, color: widget.autoMigrationV1ToV2 ? Theme.of(context).colorScheme.primary : null, ), description: Text( LocaleKeys.migration_v1_to_v2_retrigger_description.tr(), style: TextStyle( color: widget.autoMigrationV1ToV2 ? Theme.of(context).colorScheme.primary : null, ), ), onPressed: (context) { showDialog( context: context, builder: (context) { return AlertDialog( title: Text( LocaleKeys.are_you_sure.tr(), ), content: Text( LocaleKeys.restore_backup_alert_content.tr(), ), actionsAlignment: MainAxisAlignment.spaceBetween, actions: [ FilledButton.tonal( onPressed: () { _startMigratingV1ToV2(); Navigator.of(context).pop(); }, child: Text(LocaleKeys.yes.tr()), ), FilledButton.tonal( onPressed: () => Navigator.of(context).pop(), child: Text(LocaleKeys.no.tr()), ), ], ); }, ); }, ); } SettingsTile _buildRestoreBackup(BuildContext builderContext) { return SettingsTile( title: Text( LocaleKeys.restore_backup.tr(), style: const TextStyle( fontSize: 16, ), ), leading: (_restoringLocal) ? const SizedBox( width: 24, height: 24, child: CircularProgressIndicator(), ) : const Icon(FontAwesomeIcons.arrowUpFromBracket), description: Text( '${LocaleKeys.restore_backup_description_1.tr()}\n${LocaleKeys.restore_backup_description_2.tr()}', ), onPressed: (context) { showDialog( context: context, builder: (context) { return Builder(builder: (context) { return AlertDialog( title: Text( LocaleKeys.are_you_sure.tr(), ), content: Text( LocaleKeys.restore_backup_alert_content.tr(), ), actionsAlignment: MainAxisAlignment.spaceBetween, actions: [ FilledButton.tonal( onPressed: () { _startRestoringLocalBackup(builderContext); Navigator.of(context).pop(); }, child: Text(LocaleKeys.yes.tr()), ), FilledButton.tonal( onPressed: () => Navigator.of(context).pop(), child: Text(LocaleKeys.no.tr()), ), ], ); }); }, ); }, ); } SettingsTile _buildCreateCloudBackup() { return SettingsTile( title: Text( LocaleKeys.create_cloud_backup.tr(), style: const TextStyle( fontSize: 16, ), ), leading: (_creatingCloud) ? const SizedBox( width: 24, height: 24, child: CircularProgressIndicator(), ) : const Icon(FontAwesomeIcons.cloudArrowUp), description: Text( LocaleKeys.create_cloud_backup_description.tr(), ), onPressed: _startCreatingCloudBackup, ); } SettingsTile _buildCreateLocalBackup() { return SettingsTile( title: Text( LocaleKeys.create_local_backup.tr(), style: const TextStyle( fontSize: 16, ), ), leading: (_creatingLocal) ? const SizedBox( width: 24, height: 24, child: CircularProgressIndicator(), ) : const Icon(FontAwesomeIcons.solidFloppyDisk), description: Text( LocaleKeys.create_local_backup_description.tr(), ), onPressed: _startCreatingLocalBackup, ); } SettingsTile _buildExportAsCSV() { return SettingsTile( title: Text( LocaleKeys.export_csv.tr(), style: const TextStyle( fontSize: 16, ), ), leading: (_exportingCSV) ? const SizedBox( width: 24, height: 24, child: CircularProgressIndicator(), ) : const Icon(FontAwesomeIcons.fileCsv), description: Text( LocaleKeys.export_csv_description_1.tr(), ), onPressed: _startExportingCSV, ); } SettingsTile _buildImportGoodreadsCSV() { return SettingsTile( title: Text( LocaleKeys.import_goodreads_csv.tr(), style: const TextStyle( fontSize: 16, ), ), leading: (_importingGoodreadsCSV) ? const SizedBox( width: 24, height: 24, child: CircularProgressIndicator(), ) : const Icon(FontAwesomeIcons.g), onPressed: _startImportingGoodreadsCSV, ); } SettingsTile _buildImportBookwyrmCSV() { return SettingsTile( title: Text( LocaleKeys.import_bookwyrm_csv.tr(), style: const TextStyle( fontSize: 16, ), ), leading: (_importingBookwyrmCSV) ? const SizedBox( width: 24, height: 24, child: CircularProgressIndicator(), ) : const Icon(FontAwesomeIcons.b), onPressed: _startImportingBookwyrmCSV, ); } SettingsTile _buildImportCSV() { return SettingsTile( title: Text( LocaleKeys.import_csv.tr(), style: const TextStyle( fontSize: 16, ), ), leading: (_importingCSV) ? const SizedBox( width: 24, height: 24, child: CircularProgressIndicator(), ) : Image.asset( 'assets/icons/icon_cropped.png', width: 24, height: 24, ), onPressed: _startImportingCSV, ); } _buildBackupSection(BuildContext context) { final listOfTiles = <SettingsTile>[ _buildCreateLocalBackup(), _buildCreateCloudBackup(), _buildRestoreBackup(context), ]; //TODO: This should be removed in the future if (Platform.isAndroid) { listOfTiles.add(_buildV1ToV2Migration(context)); } return SettingsSection( title: Text( LocaleKeys.openreads_backup.tr(), style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.primary, ), ), tiles: listOfTiles, ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/settings_screen/settings_screen.dart
import 'dart:io'; import 'package:animated_widgets/widgets/rotation_animated.dart'; import 'package:animated_widgets/widgets/shake_animated_widget.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_email_sender/flutter_email_sender.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/constants/locale.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/theme_bloc/theme_bloc.dart'; import 'package:openreads/logic/cubit/default_book_status_cubit.dart'; import 'package:openreads/ui/settings_screen/download_missing_covers_screen.dart'; import 'package:openreads/ui/settings_screen/settings_backup_screen.dart'; import 'package:openreads/ui/settings_screen/settings_apperance_screen.dart'; import 'package:openreads/ui/settings_screen/widgets/widgets.dart'; import 'package:openreads/ui/trash_screen/trash_screen.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:settings_ui/settings_ui.dart'; import 'package:url_launcher/url_launcher.dart'; class SettingsScreen extends StatelessWidget { const SettingsScreen({super.key}); static const licence = 'GNU General Public Licence v2.0'; static const repoUrl = 'https://github.com/mateusz-bak/openreads'; static const translationUrl = 'https://hosted.weblate.org/engage/openreads/'; static const communityUrl = 'https://matrix.to/#/#openreads:matrix.org'; static const rateUrlAndroid = 'market://details?id=software.mdev.bookstracker'; static const rateUrlIOS = 'https://apps.apple.com/app/id6476542305'; static const releasesUrl = '$repoUrl/releases'; static const licenceUrl = '$repoUrl/blob/master/LICENSE'; static const githubIssuesUrl = '$repoUrl/issues'; static const githubSponsorUrl = 'https://github.com/sponsors/mateusz-bak'; static const buyMeCoffeUrl = 'https://www.buymeacoffee.com/mateuszbak'; _sendEmailToDev( BuildContext context, String version, [ bool mounted = true, ]) async { final Email email = Email( subject: 'Openreads feedback', body: 'Version $version\n', recipients: ['[email protected]'], isHTML: false, ); try { await FlutterEmailSender.send(email); } catch (error) { if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( '$error', ), ), ); } } _openGithubIssue(BuildContext context, [bool mounted = true]) async { try { await launchUrl( Uri.parse(githubIssuesUrl), mode: LaunchMode.externalApplication, ); } catch (error) { if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( '$error', ), ), ); } } _supportGithub(BuildContext context, [bool mounted = true]) async { try { await launchUrl( Uri.parse(githubSponsorUrl), mode: LaunchMode.externalApplication, ); } catch (error) { if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( '$error', ), ), ); } } _supportBuyMeCoffe(BuildContext context, [bool mounted = true]) async { try { await launchUrl( Uri.parse(buyMeCoffeUrl), mode: LaunchMode.externalApplication, ); } catch (error) { if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( '$error', ), ), ); } } _showLanguageDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), backgroundColor: Theme.of(context).colorScheme.surface, child: Padding( padding: const EdgeInsets.symmetric(vertical: 20), child: BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { if (state is SetThemeState) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.only(left: 10), child: Text( LocaleKeys.select_language.tr(), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), const SizedBox(height: 10), Expanded( child: Scrollbar( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: SingleChildScrollView( child: Column( children: _buildLanguageButtons(context, state), ), ), ), ), ), ], ); } else { return const SizedBox(); } }, ), ), ); }, ); } _showDefaultBooksFormatDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), backgroundColor: Theme.of(context).colorScheme.surface, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.only(left: 10), child: Text( LocaleKeys.default_books_format.tr(), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), const SizedBox(height: 15), SettingsDialogButton( text: LocaleKeys.book_format_paperback.tr(), onPressed: () => _setDefaultBooksFormat( context, BookFormat.paperback, ), ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.book_format_hardcover.tr(), onPressed: () => _setDefaultBooksFormat( context, BookFormat.hardcover, ), ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.book_format_ebook.tr(), onPressed: () => _setDefaultBooksFormat( context, BookFormat.ebook, ), ), const SizedBox(height: 5), SettingsDialogButton( text: LocaleKeys.book_format_audiobook.tr(), onPressed: () => _setDefaultBooksFormat( context, BookFormat.audiobook, ), ), ], ), ), ); }, ); } _setDefaultBooksFormat(BuildContext context, BookFormat bookFormat) { BlocProvider.of<DefaultBooksFormatCubit>(context).setBookFormat(bookFormat); Navigator.of(context).pop(); } List<Widget> _buildLanguageButtons( BuildContext context, SetThemeState state, ) { final widgets = List<Widget>.empty(growable: true); widgets.add( LanguageButton( language: LocaleKeys.default_locale.tr(), onPressed: () => _setLanguage( context, state, null, ), ), ); for (var language in supportedLocales) { widgets.add( LanguageButton( language: language.fullName, onPressed: () => _setLanguage( context, state, language.locale, ), ), ); } return widgets; } _setLanguage(BuildContext context, SetThemeState state, Locale? locale) { if (locale == null) { if (context.supportedLocales.contains(context.deviceLocale)) { context.resetLocale(); } else { context.setLocale(context.fallbackLocale!); } } else { context.setLocale(locale); } BlocProvider.of<ThemeBloc>(context).add(ChangeThemeEvent( themeMode: state.themeMode, showOutlines: state.showOutlines, cornerRadius: state.cornerRadius, primaryColor: state.primaryColor, fontFamily: state.fontFamily, readTabFirst: state.readTabFirst, useMaterialYou: state.useMaterialYou, amoledDark: state.amoledDark, )); Navigator.of(context).pop(); } SettingsTile _buildURLSetting({ required String title, String? description, String? url, IconData? iconData, required BuildContext context, }) { return SettingsTile.navigation( title: Text( title, style: const TextStyle( fontSize: 16, ), ), leading: (iconData == null) ? null : Icon(iconData), description: (description != null) ? Text( description, style: const TextStyle(), ) : null, onPressed: (_) { if (url == null) return; launchUrl( Uri.parse(url), mode: LaunchMode.externalApplication, ); }, ); } SettingsTile _buildBasicSetting({ required String title, String? description, IconData? iconData, required BuildContext context, }) { return SettingsTile( title: Text( title, style: const TextStyle( fontSize: 16, ), ), leading: (iconData == null) ? null : Icon(iconData), description: (description != null) ? Text( description, style: const TextStyle(), ) : null, ); } SettingsTile _buildFeedbackSetting(BuildContext context, String version) { return SettingsTile.navigation( title: Text( LocaleKeys.send_feedback.tr(), style: const TextStyle( fontSize: 16, ), ), description: Text( LocaleKeys.report_bugs_or_ideas.tr(), style: const TextStyle(), ), leading: const Icon(Icons.record_voice_over_rounded), onPressed: (context) { FocusManager.instance.primaryFocus?.unfocus(); showModalBottomSheet( context: context, isScrollControlled: true, elevation: 0, backgroundColor: Theme.of(context).colorScheme.surface, builder: (context) { return Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 5), Container( height: 3, width: MediaQuery.of(context).size.width / 4, decoration: BoxDecoration( color: Colors.grey.shade300, borderRadius: BorderRadius.circular(10)), ), Container( padding: const EdgeInsets.fromLTRB(10, 20, 10, 40), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), ), child: IntrinsicHeight( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ const SizedBox(width: 10), Expanded( child: ContactButton( text: LocaleKeys.send_dev_email.tr(), icon: FontAwesomeIcons.solidEnvelope, onPressed: () => _sendEmailToDev(context, version), ), ), const SizedBox(width: 20), Expanded( child: ContactButton( text: LocaleKeys.raise_github_issue.tr(), icon: FontAwesomeIcons.github, onPressed: () => _openGithubIssue(context), ), ), const SizedBox(width: 10), ], ), ), ), ], ); }, ); }, ); } SettingsTile _buildSupportSetting(BuildContext context) { return SettingsTile.navigation( title: Text( LocaleKeys.support_the_project.tr(), style: TextStyle( fontSize: 17, color: Theme.of(context).colorScheme.primary, fontWeight: FontWeight.bold, letterSpacing: 0.8, ), ), description: Text( LocaleKeys.support_the_project_description.tr(), ), leading: ShakeAnimatedWidget( duration: const Duration(seconds: 3), shakeAngle: Rotation.deg(z: 20), curve: Curves.bounceInOut, child: Icon( FontAwesomeIcons.mugHot, color: Theme.of(context).colorScheme.primary, ), ), onPressed: (context) { FocusManager.instance.primaryFocus?.unfocus(); showModalBottomSheet( context: context, isScrollControlled: true, elevation: 0, backgroundColor: Theme.of(context).colorScheme.surface, builder: (context) { return Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 10), Container( height: 3, width: MediaQuery.of(context).size.width / 4, decoration: BoxDecoration( color: Colors.grey.shade300, borderRadius: BorderRadius.circular(10)), ), Container( padding: const EdgeInsets.fromLTRB(10, 32, 10, 40), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), ), child: IntrinsicHeight( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ const SizedBox(width: 10), Expanded( child: ContactButton( text: LocaleKeys.support_option_1.tr(), icon: FontAwesomeIcons.github, onPressed: () => _supportGithub(context), ), ), const SizedBox(width: 20), Expanded( child: ContactButton( text: LocaleKeys.support_option_2.tr(), icon: FontAwesomeIcons.mugHot, onPressed: () => _supportBuyMeCoffe(context), ), ), const SizedBox(width: 10), ], ), ), ), ], ); }, ); }, ); } SettingsTile _buildTrashSetting(BuildContext context) { return SettingsTile.navigation( title: Text( LocaleKeys.deleted_books.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon( FontAwesomeIcons.trash, size: 20, ), onPressed: (context) { Navigator.push( context, MaterialPageRoute( builder: (context) => const TrashScreen(), ), ); }, ); } SettingsTile _buildDownloadMissingCovers(BuildContext context) { return SettingsTile.navigation( title: Text( LocaleKeys.download_missing_covers.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon(Icons.image), onPressed: (context) { Navigator.push( context, MaterialPageRoute( builder: (context) => const DownloadMissingCoversScreen(), ), ); }, ); } SettingsTile _buildDefaultBooksFormat(BuildContext context) { return SettingsTile( title: Text( LocaleKeys.default_books_format.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon(Icons.book_rounded), description: BlocBuilder<DefaultBooksFormatCubit, BookFormat>( builder: (_, state) { if (state == BookFormat.paperback) { return Text( LocaleKeys.book_format_paperback.tr(), style: const TextStyle(), ); } else if (state == BookFormat.hardcover) { return Text( LocaleKeys.book_format_hardcover.tr(), style: const TextStyle(), ); } else if (state == BookFormat.ebook) { return Text( LocaleKeys.book_format_ebook.tr(), style: const TextStyle(), ); } else if (state == BookFormat.audiobook) { return Text( LocaleKeys.book_format_audiobook.tr(), style: const TextStyle(), ); } else { return const SizedBox(); } }, ), onPressed: (context) => _showDefaultBooksFormatDialog(context), ); } SettingsTile _buildBackupSetting(BuildContext context) { return SettingsTile.navigation( title: Text( LocaleKeys.backup_and_restore.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon(Icons.settings_backup_restore_rounded), onPressed: (context) { Navigator.push( context, MaterialPageRoute( builder: (context) => const SettingsBackupScreen(), ), ); }, ); } SettingsTile _buildAppearanceSetting(BuildContext context) { return SettingsTile.navigation( title: Text( LocaleKeys.apperance.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon(Icons.color_lens), onPressed: (context) { Navigator.push( context, MaterialPageRoute( builder: (context) => const SettingsApperanceScreen(), ), ); }, ); } SettingsTile _buildLanguageSetting(BuildContext context) { return SettingsTile( title: Text( LocaleKeys.language.tr(), style: const TextStyle( fontSize: 16, ), ), leading: const Icon(FontAwesomeIcons.earthAmericas), description: BlocBuilder<ThemeBloc, ThemeState>( builder: (_, themeState) { if (themeState is SetThemeState) { final locale = context.locale; for (var language in supportedLocales) { if (language.locale == locale) { return Text( language.fullName, style: const TextStyle(), ); } } return Text( LocaleKeys.default_locale.tr(), style: const TextStyle(), ); } else { return const SizedBox(); } }, ), onPressed: (context) => _showLanguageDialog(context), ); } Future<String> _getAppVersion() async { PackageInfo packageInfo = await PackageInfo.fromPlatform(); return packageInfo.version; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( LocaleKeys.settings.tr(), style: const TextStyle( fontSize: 18, ), ), ), body: FutureBuilder<String>( future: _getAppVersion(), builder: (context, snapshot) { if (snapshot.hasData) { final version = snapshot.data; return BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { late final bool amoledDark; if (state is SetThemeState) { amoledDark = state.amoledDark; } else { amoledDark = false; } return SettingsList( contentPadding: const EdgeInsets.only(top: 10), darkTheme: SettingsThemeData( settingsListBackground: amoledDark ? Colors.black : Theme.of(context).colorScheme.surface, ), lightTheme: SettingsThemeData( settingsListBackground: Theme.of(context).colorScheme.surface, ), sections: [ SettingsSection( tiles: _buildGeneralSettingsTiles(context, version), ), SettingsSection( title: Text( LocaleKeys.books_settings.tr(), style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.primary, ), ), tiles: <SettingsTile>[ _buildTrashSetting(context), _buildDownloadMissingCovers(context), _buildDefaultBooksFormat(context), ], ), SettingsSection( title: Text( LocaleKeys.app.tr(), style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.primary, ), ), tiles: <SettingsTile>[ _buildBackupSetting(context), _buildAppearanceSetting(context), _buildLanguageSetting(context), ], ), SettingsSection( title: Text( LocaleKeys.about.tr(), style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.primary, ), ), tiles: <SettingsTile>[ _buildBasicSetting( title: LocaleKeys.version.tr(), description: version, iconData: FontAwesomeIcons.rocket, context: context, ), _buildURLSetting( title: LocaleKeys.changelog.tr(), description: LocaleKeys.changelog_description.tr(), url: releasesUrl, iconData: Icons.auto_awesome_rounded, context: context, ), _buildURLSetting( title: LocaleKeys.source_code.tr(), description: LocaleKeys.source_code_description.tr(), url: repoUrl, iconData: FontAwesomeIcons.code, context: context, ), _buildURLSetting( title: LocaleKeys.licence.tr(), description: licence, url: licenceUrl, iconData: Icons.copyright_rounded, context: context, ), ], ), ], ); }, ); } else { return const SizedBox(); } }), ); } List<SettingsTile> _buildGeneralSettingsTiles( BuildContext context, String? version) { final tiles = List<SettingsTile>.empty(growable: true); // TODO: Implement in app purchase for iOS if (!Platform.isIOS) { tiles.add(_buildSupportSetting(context)); } tiles.add(_buildURLSetting( title: LocaleKeys.join_community.tr(), description: LocaleKeys.join_community_description.tr(), url: communityUrl, iconData: FontAwesomeIcons.peopleGroup, context: context, )); tiles.add(_buildURLSetting( title: LocaleKeys.rate_app.tr(), description: LocaleKeys.rate_app_description.tr(), url: Platform.isIOS ? rateUrlIOS : Platform.isAndroid ? rateUrlAndroid : null, iconData: Icons.star_rounded, context: context, )); tiles.add(_buildFeedbackSetting(context, version!)); tiles.add(_buildURLSetting( title: LocaleKeys.translate_app.tr(), description: LocaleKeys.translate_app_description.tr(), url: translationUrl, iconData: Icons.translate_rounded, context: context, )); return tiles; } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/settings_screen/download_missing_covers_screen.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/books_screen/books_screen.dart'; import 'package:openreads/ui/settings_screen/widgets/widgets.dart'; class DownloadMissingCoversScreen extends StatefulWidget { const DownloadMissingCoversScreen({ super.key, this.bookIDs, }); final List<int>? bookIDs; @override State<DownloadMissingCoversScreen> createState() => _DownloadMissingCoversScreenState(); } class _DownloadMissingCoversScreenState extends State<DownloadMissingCoversScreen> { bool _isDownloading = false; String _progress = ''; int _progressValue = 0; List<Book> downloadedCovers = []; _startCoverDownload() async { setState(() { _isDownloading = true; _progressValue = 0; }); final books = await bookCubit.allBooks.first; await _downloadCovers(books); setState(() { _isDownloading = false; }); } _startCoverDownloadForImportedBooks() async { setState(() { _isDownloading = true; _progressValue = 0; }); final books = await _getListOfBooksFromListOfIDs(widget.bookIDs!); await _downloadCovers(books); setState(() { _isDownloading = false; }); // ignore: use_build_context_synchronously Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => const BooksScreen(), ), (route) => false, ); } Future<List<Book>> _getListOfBooksFromListOfIDs(List<int> bookIDs) async { final listOfBooks = List<Book>.empty(growable: true); for (final bookID in widget.bookIDs!) { final book = await bookCubit.getBook(bookID); if (book != null) { listOfBooks.add(book); } } return listOfBooks; } _downloadCovers(List<Book> books) async { setState(() { _progress = '$_progressValue/${books.length}'; }); // Downloading covers 20 at a time final asyncTasks = <Future>[]; const asyncTasksNumber = 20; for (final book in books) { if (book.hasCover == false) { asyncTasks.add(_downloadCover(book)); } if (asyncTasks.length == asyncTasksNumber) { await Future.wait(asyncTasks); asyncTasks.clear(); } setState(() { _progressValue++; _progress = '$_progressValue/${books.length}'; }); } // Wait for the rest of async tasks await Future.wait(asyncTasks); } _downloadCover(Book book) async { final result = await bookCubit.downloadCoverByISBN(book); if (result == true) { setState(() { downloadedCovers.add(book); }); } } @override initState() { super.initState(); // If bookIDs is not null, then we are downloading covers automatically // for imported books if (widget.bookIDs != null) { _startCoverDownloadForImportedBooks(); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( LocaleKeys.download_missing_covers.tr(), style: const TextStyle(fontSize: 18), ), ), body: Column( children: [ _isDownloading ? const LinearProgressIndicator(minHeight: 4) : const SizedBox(height: 4), Expanded( child: Padding( padding: const EdgeInsets.fromLTRB(20, 20, 10, 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( LocaleKeys.download_missing_covers_explanation.tr(), style: const TextStyle(fontSize: 16), ), const SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ widget.bookIDs == null ? _buildStartButton(context) : const SizedBox(), const SizedBox(width: 20), Text( _progress, style: const TextStyle(fontSize: 16), ), ], ), const SizedBox(height: 20), _progress != '' ? Text( '${LocaleKeys.downloaded_covers.tr()} (${downloadedCovers.length})', style: const TextStyle(fontSize: 16), ) : const SizedBox(), const SizedBox(height: 10), _buildGridOfCovers(), ], ), ), ), ], ), ); } ElevatedButton _buildStartButton(BuildContext context) { return ElevatedButton( onPressed: _startCoverDownload, style: ElevatedButton.styleFrom( elevation: 0, backgroundColor: Theme.of(context).colorScheme.secondary, foregroundColor: Theme.of(context).colorScheme.onSecondary, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), ), child: Text(LocaleKeys.start_button.tr()), ); } Expanded _buildGridOfCovers() { return Expanded( child: Scrollbar( child: GridView.builder( itemCount: downloadedCovers.length, itemBuilder: (BuildContext context, int index) { final book = downloadedCovers[downloadedCovers.length - index - 1]; final coverFile = book.getCoverFile(); return MissingCoverView(coverFile: coverFile); }, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 4, crossAxisSpacing: 5, mainAxisSpacing: 5, childAspectRatio: 1 / 1.5, ), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/settings_screen
mirrored_repositories/openreads/lib/ui/settings_screen/widgets/settings_dialog_button.dart
import 'package:flutter/material.dart'; class SettingsDialogButton extends StatelessWidget { const SettingsDialogButton({ super.key, required this.text, required this.onPressed, this.fontFamily, }); final String text; final Function() onPressed; final String? fontFamily; static const example = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; @override Widget build(BuildContext context) { return Row( children: [ Expanded( child: SimpleDialogOption( padding: EdgeInsets.zero, onPressed: onPressed, child: Padding( padding: const EdgeInsets.symmetric( horizontal: 10, vertical: 10, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( text, style: TextStyle(fontSize: 16, fontFamily: fontFamily), ), fontFamily != null ? const Divider( height: 8, ) : const SizedBox(), fontFamily != null ? Text( example, style: TextStyle( fontSize: 14, fontFamily: fontFamily, ), ) : const SizedBox(), ], ), ), ), ), ], ); } }
0
mirrored_repositories/openreads/lib/ui/settings_screen
mirrored_repositories/openreads/lib/ui/settings_screen/widgets/missing_cover_view.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; class MissingCoverView extends StatelessWidget { const MissingCoverView({ super.key, this.coverFile, }); final File? coverFile; @override Widget build(BuildContext context) { return ClipRRect( borderRadius: BorderRadius.circular(cornerRadius), child: coverFile != null ? Image.file( coverFile!, fit: BoxFit.cover, width: (MediaQuery.of(context).size.width - 20 - 20 - 15) / 4, ) : const SizedBox(), ); } }
0
mirrored_repositories/openreads/lib/ui/settings_screen
mirrored_repositories/openreads/lib/ui/settings_screen/widgets/widgets.dart
export 'settings_dialog_button.dart'; export 'contact_button.dart'; export 'language_button.dart'; export 'missing_cover_view.dart';
0
mirrored_repositories/openreads/lib/ui/settings_screen
mirrored_repositories/openreads/lib/ui/settings_screen/widgets/contact_button.dart
import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; class ContactButton extends StatelessWidget { const ContactButton({ super.key, required this.text, required this.icon, required this.onPressed, }); final String text; final IconData icon; final Function() onPressed; @override Widget build(BuildContext context) { return InkWell( customBorder: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), onTap: onPressed, child: Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3), border: Border.all(color: dividerColor), ), child: Column( children: [ Icon( icon, size: 28, color: Theme.of(context).colorScheme.primary, ), const SizedBox(height: 10), Text( text, textAlign: TextAlign.center, style: const TextStyle( fontWeight: FontWeight.bold, ), ), ], ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/settings_screen
mirrored_repositories/openreads/lib/ui/settings_screen/widgets/language_button.dart
import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; class LanguageButton extends StatelessWidget { const LanguageButton({ super.key, required this.language, required this.onPressed, }); final String language; final Function() onPressed; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: Theme.of(context).colorScheme.surfaceVariant, border: Border.all(color: dividerColor), ), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Row( children: [ Expanded( child: SimpleDialogOption( padding: EdgeInsets.zero, onPressed: onPressed, child: Padding( padding: const EdgeInsets.symmetric( horizontal: 10, vertical: 10, ), child: Text( language, style: const TextStyle(fontSize: 16), ), ), ), ), ], ), ), ], ), ), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/search_ol_editions_screen/search_ol_editions_screen.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/cubit/default_book_status_cubit.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/model/reading.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/model/ol_edition_result.dart'; import 'package:openreads/ui/add_book_screen/add_book_screen.dart'; import 'package:openreads/ui/search_ol_editions_screen/widgets/widgets.dart'; class SearchOLEditionsScreen extends StatefulWidget { const SearchOLEditionsScreen({ super.key, required this.editions, required this.title, this.subtitle, required this.author, required this.pagesMedian, required this.isbn, required this.olid, required this.firstPublishYear, required this.status, }); final List<String> editions; final String title; final String? subtitle; final String author; final int? pagesMedian; final List<String>? isbn; final String? olid; final int? firstPublishYear; final BookStatus status; @override State<SearchOLEditionsScreen> createState() => _SearchOLEditionsScreenState(); } class _SearchOLEditionsScreenState extends State<SearchOLEditionsScreen> { Uint8List? editionCoverPreview; bool _onlyEditionsWithCovers = false; void _saveEdition({ required OLEditionResult result, required int? cover, String? work, }) { final defaultBookFormat = context.read<DefaultBooksFormatCubit>().state; final book = Book( title: result.title!, subtitle: result.subtitle, author: widget.author, pages: result.numberOfPages, status: widget.status, favourite: false, isbn: (result.isbn13 != null && result.isbn13!.isNotEmpty) ? result.isbn13![0] : (result.isbn10 != null && result.isbn10!.isNotEmpty) ? result.isbn10![0] : null, olid: (result.key != null) ? result.key!.replaceAll('/books/', '') : null, publicationYear: widget.firstPublishYear, bookFormat: result.physicalFormat ?? defaultBookFormat, readings: List<Reading>.empty(growable: true), tags: LocaleKeys.owned_book_tag.tr(), dateAdded: DateTime.now(), dateModified: DateTime.now(), ); context.read<EditBookCubit>().setBook(book); Navigator.of(context).push( MaterialPageRoute( builder: (_) => AddBookScreen( fromOpenLibrary: true, fromOpenLibraryEdition: true, work: work, coverOpenLibraryID: cover, ), ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( LocaleKeys.choose_edition.tr(), style: const TextStyle(fontSize: 18), ), ), body: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( child: Column( children: [ Padding( padding: const EdgeInsets.all(10), child: Row( children: [ Switch( value: _onlyEditionsWithCovers, onChanged: (value) { setState(() { _onlyEditionsWithCovers = value; }); }, ), const SizedBox(width: 10), Text( LocaleKeys.only_editions_with_covers.tr(), style: const TextStyle(fontSize: 16), ) ], ), ), // UniqueKey() is used to force the widget to rebuild OLEditionsGrid( key: UniqueKey(), editions: widget.editions, saveEdition: _saveEdition, onlyEditionsWithCovers: _onlyEditionsWithCovers, ), ], ), ), ], ), ); } }
0
mirrored_repositories/openreads/lib/ui/search_ol_editions_screen
mirrored_repositories/openreads/lib/ui/search_ol_editions_screen/widgets/ol_editions_grid.dart
import 'package:flutter/material.dart'; import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; import 'package:openreads/model/ol_edition_result.dart'; import 'package:openreads/resources/open_library_service.dart'; import 'package:openreads/ui/search_ol_editions_screen/widgets/widgets.dart'; class OLEditionsGrid extends StatelessWidget { OLEditionsGrid({ super.key, required this.editions, required this.saveEdition, required this.onlyEditionsWithCovers, }); final List<String> editions; final bool onlyEditionsWithCovers; final Function({ required OLEditionResult result, required int? cover, String? work, }) saveEdition; final sizeOfPage = 3; final _pagingController = PagingController<int, OLEditionResult>( firstPageKey: 0, invisibleItemsThreshold: 12, ); Future<void> _fetchPage(int pageKey) async { try { List<OLEditionResult> newResults = await _fetchResults(offset: pageKey); // If first page is empty the package will abort further requests. // This is a workaround to fetch the next page if the first page is empty // without appending the first page to the list of results. while (newResults.isEmpty && pageKey < editions.length) { pageKey += sizeOfPage; newResults = await _fetchResults(offset: pageKey); } if (pageKey >= editions.length) { _pagingController.appendLastPage(newResults); } else { final nextPageKey = pageKey + sizeOfPage; _pagingController.appendPage(newResults, nextPageKey); } } catch (error) { _pagingController.error = error; } } Future<List<OLEditionResult>> _fetchResults({required int offset}) async { final results = List<OLEditionResult>.empty(growable: true); for (var i = 0; i < sizeOfPage && i < editions.length; i++) { bool hasEditions = true; while (hasEditions) { if (offset + i < editions.length) { final newResult = await OpenLibraryService().getEdition(editions[offset + i]); if (onlyEditionsWithCovers) { if (newResult.covers != null && newResult.covers!.isNotEmpty) { results.add(newResult); } } else { results.add(newResult); } hasEditions = false; } else { hasEditions = false; } } } return results; } @override Widget build(BuildContext context) { if (editions.isNotEmpty) { _pagingController.addPageRequestListener((pageKey) { _fetchPage(pageKey); }); } return Expanded( child: Scrollbar( child: PagedGridView( padding: const EdgeInsets.all(10.0), pagingController: _pagingController, showNewPageProgressIndicatorAsGridChild: false, showNewPageErrorIndicatorAsGridChild: false, showNoMoreItemsIndicatorAsGridChild: false, builderDelegate: PagedChildBuilderDelegate<OLEditionResult>( firstPageProgressIndicatorBuilder: (_) => Center( child: LoadingAnimationWidget.staggeredDotsWave( color: Theme.of(context).colorScheme.primary, size: 50, ), ), newPageProgressIndicatorBuilder: (_) => Center( child: Padding( padding: const EdgeInsets.all(20.0), child: LoadingAnimationWidget.staggeredDotsWave( color: Theme.of(context).colorScheme.primary, size: 50, ), ), ), itemBuilder: (context, item, index) => BookCardOLEdition( publishers: item.publishers, publicationDate: item.publishDate, title: item.title ?? '', pages: item.numberOfPages, cover: item.covers != null && item.covers!.isNotEmpty ? item.covers![0] : null, onPressed: () => saveEdition( result: item, cover: item.covers != null && item.covers!.isNotEmpty ? item.covers![0] : null, work: item.works != null && item.works!.isNotEmpty ? item.works![0].key : null, ), ), ), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( childAspectRatio: 5 / 8.0, crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10, mainAxisExtent: 225, ), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/search_ol_editions_screen
mirrored_repositories/openreads/lib/ui/search_ol_editions_screen/widgets/book_card_ol_edition.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; class BookCardOLEdition extends StatelessWidget { BookCardOLEdition({ super.key, required this.title, required this.cover, required this.onPressed, required this.pages, this.publicationDate, this.publishers, }); final String title; final int? cover; final int? pages; final Function() onPressed; final String? publicationDate; final List<String>? publishers; static const String coverBaseUrl = 'https://covers.openlibrary.org/'; late final String coverUrl = '${coverBaseUrl}b/id/$cover-M.jpg'; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(0, 0, 0, 0), child: InkWell( customBorder: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), onTap: onPressed, child: Container( decoration: BoxDecoration( color: cover == null ? Theme.of(context) .colorScheme .primaryContainer .withOpacity(0.3) : null, borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ cover != null ? Expanded( child: ClipRRect( borderRadius: BorderRadius.circular(2), child: CachedNetworkImage( imageUrl: coverUrl, fadeInDuration: const Duration(milliseconds: 100), fadeOutDuration: const Duration(milliseconds: 100), placeholder: (context, url) => Center( child: Container( padding: const EdgeInsets.all(5), child: LoadingAnimationWidget.threeArchedCircle( color: Theme.of(context).colorScheme.primary, size: 24, ), ), ), errorWidget: (context, url, error) => const Icon(Icons.error), ), ), ) : Expanded( child: Padding( padding: const EdgeInsets.all(10), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ Flexible( child: Text( title, overflow: TextOverflow.ellipsis, maxLines: 20, textAlign: TextAlign.center, ), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ pages != null ? Text( '$pages ${LocaleKeys.pages_lowercase.tr()}', style: TextStyle( fontSize: 12, color: Theme.of(context) .colorScheme .onBackground .withOpacity(0.6), ), ) : const SizedBox(), publicationDate != null ? Text(publicationDate!) : const SizedBox.shrink(), ], ), ], ), ), ), (publishers != null && publishers!.isNotEmpty) ? Text( publishers![0], textAlign: TextAlign.center, style: TextStyle( fontSize: 10, color: Theme.of(context) .colorScheme .onBackground .withOpacity(0.8), ), ) : const SizedBox.shrink(), publicationDate != null && cover != null ? Text( publicationDate!, textAlign: TextAlign.center, style: TextStyle( fontSize: 13, color: Theme.of(context) .colorScheme .onBackground .withOpacity(0.8), ), ) : const SizedBox.shrink(), ], ), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/search_ol_editions_screen
mirrored_repositories/openreads/lib/ui/search_ol_editions_screen/widgets/widgets.dart
export 'book_card_ol_edition.dart'; export 'ol_editions_grid.dart';
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/search_covers_screen/search_covers_screen.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/add_book_screen/widgets/widgets.dart'; import 'package:openreads/ui/search_covers_screen/widgets/widgets.dart'; class SearchCoversScreen extends StatefulWidget { const SearchCoversScreen({ super.key, required this.book, }); final Book book; @override State<SearchCoversScreen> createState() => _SearchCoversScreenState(); } class _SearchCoversScreenState extends State<SearchCoversScreen> { final PagingController<int, String> _pagingController = PagingController(firstPageKey: 0); late TextEditingController controller; String searchQuery = ''; @override initState() { super.initState(); searchQuery = '${widget.book.title} ${widget.book.author} ${LocaleKeys.bookCover.tr()}'; controller = TextEditingController(text: searchQuery); controller.addListener(() { setState(() { if (searchQuery == controller.text) return; searchQuery = controller.text; }); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( LocaleKeys.searchOnlineForCover.tr(), style: const TextStyle(fontSize: 18), ), ), body: Column( children: [ Padding( padding: const EdgeInsets.only(bottom: 10), child: BookTextField( controller: controller, keyboardType: TextInputType.text, maxLength: 256, onSubmitted: (_) { setState(() { searchQuery = controller.text; _pagingController.refresh(); }); }, ), ), SearchCoversGrid( pagingController: _pagingController, query: searchQuery, ), ], ), ); } }
0
mirrored_repositories/openreads/lib/ui/search_covers_screen
mirrored_repositories/openreads/lib/ui/search_covers_screen/widgets/widgets.dart
export 'search_covers_grid.dart';
0
mirrored_repositories/openreads/lib/ui/search_covers_screen
mirrored_repositories/openreads/lib/ui/search_covers_screen/widgets/search_covers_grid.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:http/http.dart' as http; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/core/helpers/helpers.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; class SearchCoversGrid extends StatefulWidget { const SearchCoversGrid({ super.key, required this.query, required this.pagingController, }); final String query; final PagingController<int, String> pagingController; @override State<SearchCoversGrid> createState() => _SearchCoversGridState(); } class _SearchCoversGridState extends State<SearchCoversGrid> { Map<String, String?> params = {}; Map<String, String> headers = { 'authority': 'duckduckgo.com', 'accept': 'application/json, text/javascript, */*; q=0.01', 'sec-fetch-dest': 'empty', 'x-requested-with': 'XMLHttpRequest', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'referer': 'https://duckduckgo.com/', 'accept-language': 'en-US,en;q=0.9', }; Future<void> _fetchPage() async { try { await _getDuckDuckGoToken(); final newItems = await _getImageResults(); List<String> newImages = List<String>.empty(growable: true); for (var item in newItems['results']) { newImages.add(item['image']); } widget.pagingController.appendLastPage(newImages); } catch (error) { widget.pagingController.error = error; } } Future _getDuckDuckGoToken() async { final url = Uri.parse(Constants.duckDuckGoURL); final tokenResponse = await http.post(url, body: {'q': widget.query}); final tokenMatch = RegExp(r'vqd=([\d-]+)\&').firstMatch( tokenResponse.body, ); if (tokenMatch == null) { throw Exception('Token Parsing Failed !'); } final token = tokenMatch.group(1); params = { 'l': 'us-en', 'o': 'json', 'q': widget.query, 'vqd': token, 'f': ',,,', 'p': '1', 'v7exp': 'a', }; } Future<dynamic> _getImageResults() async { final requestUrl = Uri.parse(Constants.duckDuckGoImagesURL); final response = await http.get( requestUrl.replace(queryParameters: params), headers: headers, ); return jsonDecode(response.body); } void _editSelectedCover({ required BuildContext context, required Uint8List? bytes, }) async { if (bytes == null) return; final croppedPhoto = await cropImage(context, bytes); if (croppedPhoto == null) return; final croppedPhotoBytes = await croppedPhoto.readAsBytes(); await generateBlurHash(croppedPhotoBytes, context); context.read<EditBookCoverCubit>().setCover(croppedPhotoBytes); context.read<EditBookCubit>().setHasCover(true); Navigator.of(context).pop(); } @override void initState() { widget.pagingController.addPageRequestListener((_) { _fetchPage(); }); super.initState(); } @override Widget build(BuildContext context) { return Expanded( child: Scrollbar( child: PagedMasonryGridView( pagingController: widget.pagingController, padding: const EdgeInsets.all(10), mainAxisSpacing: 10, crossAxisSpacing: 10, gridDelegateBuilder: (context) => const SliverSimpleGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, ), builderDelegate: _createBuilderDelegate(context), ), ), ); } PagedChildBuilderDelegate<String> _createBuilderDelegate( BuildContext context, ) { return PagedChildBuilderDelegate<String>( firstPageProgressIndicatorBuilder: (_) => Center( child: LoadingAnimationWidget.staggeredDotsWave( color: Theme.of(context).colorScheme.primary, size: 50, ), ), itemBuilder: (context, imageURL, _) => InkWell( onTap: () async { final file = await DefaultCacheManager().getSingleFile(imageURL); final bytes = await file.readAsBytes(); _editSelectedCover(context: context, bytes: bytes); }, borderRadius: BorderRadius.circular(cornerRadius), child: CachedNetworkImage( imageUrl: imageURL, imageBuilder: (context, imageProvider) => Padding( padding: const EdgeInsets.all(0), child: ClipRRect( borderRadius: BorderRadius.circular(cornerRadius), child: Image(image: imageProvider), ), ), errorWidget: (context, url, error) => const SizedBox(), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/books_screen/books_screen.dart
import 'dart:io'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/helpers/helpers.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/display_bloc/display_bloc.dart'; import 'package:openreads/logic/bloc/sort_bloc/sort_bloc.dart'; import 'package:openreads/logic/bloc/theme_bloc/theme_bloc.dart'; import 'package:openreads/logic/cubit/default_book_status_cubit.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/add_book_screen/add_book_screen.dart'; import 'package:openreads/ui/books_screen/widgets/widgets.dart'; import 'package:openreads/ui/search_ol_screen/search_ol_screen.dart.dart'; import 'package:openreads/ui/search_page/search_page.dart'; import 'package:openreads/ui/settings_screen/settings_screen.dart'; import 'package:openreads/ui/statistics_screen/statistics_screen.dart'; import 'package:diacritic/diacritic.dart'; import 'package:openreads/ui/unfinished_screen/unfinished_screen.dart'; class BooksScreen extends StatefulWidget { const BooksScreen({super.key}); @override State<BooksScreen> createState() => _BooksScreenState(); } class _BooksScreenState extends State<BooksScreen> with AutomaticKeepAliveClientMixin, TickerProviderStateMixin { late List<String> moreButtonOptions; late double appBarHeight; Set<int> selectedBookIds = {}; late TabController _tabController; _onItemSelected(int id) { setState(() { if (selectedBookIds.contains(id)) { selectedBookIds.remove(id); } else { selectedBookIds.add(id); } }); } List<Book> _sortReadList({ required SetSortState state, required List<Book> list, }) { if (state.onlyFavourite) { list = _filterOutFav(list: list); } if (state.years != null) { list = _filterOutYears(list: list, years: state.years!); } if (state.tags != null) { list = _filterTags( list: list, tags: state.tags!, filterTagsAsAnd: state.filterTagsAsAnd, filterOutSelectedTags: state.filterOutTags, ); } if (state.bookType != null) { list = _filterOutBookTypes(list, state.bookType!); } switch (state.sortType) { case SortType.byAuthor: list = _sortByAuthor(list: list, isAsc: state.isAsc); break; case SortType.byRating: list = _sortByRating(list: list, isAsc: state.isAsc); break; case SortType.byPages: list = _sortByPages(list: list, isAsc: state.isAsc); break; case SortType.byStartDate: list = _sortByStartDate(list: list, isAsc: state.isAsc); break; case SortType.byFinishDate: list = _sortByFinishDate(list: list, isAsc: state.isAsc); break; case SortType.byPublicationYear: list = _sortByPublicationYear(list: list, isAsc: state.isAsc); break; case SortType.byDateAdded: list = _sortByDateAdded(list: list, isAsc: state.isAsc); break; case SortType.byDateModified: list = _sortByDateModified(list: list, isAsc: state.isAsc); break; default: list = _sortByTitle(list: list, isAsc: state.isAsc); } return list; } List<Book> _sortInProgressList({ required SetSortState state, required List<Book> list, }) { if (state.tags != null) { list = _filterTags( list: list, tags: state.tags!, filterTagsAsAnd: state.filterTagsAsAnd, filterOutSelectedTags: state.filterOutTags, ); } if (state.bookType != null) { list = _filterOutBookTypes(list, state.bookType!); } switch (state.sortType) { case SortType.byAuthor: list = _sortByAuthor(list: list, isAsc: state.isAsc); break; case SortType.byPages: list = _sortByPages(list: list, isAsc: state.isAsc); break; case SortType.byStartDate: list = _sortByStartDate(list: list, isAsc: state.isAsc); break; default: list = _sortByTitle(list: list, isAsc: state.isAsc); } return list; } List<Book> _sortForLaterList({ required SetSortState state, required List<Book> list, }) { if (state.tags != null) { list = _filterTags( list: list, tags: state.tags!, filterTagsAsAnd: state.filterTagsAsAnd, filterOutSelectedTags: state.filterOutTags, ); } if (state.bookType != null) { list = _filterOutBookTypes(list, state.bookType!); } switch (state.sortType) { case SortType.byAuthor: list = _sortByAuthor(list: list, isAsc: state.isAsc); break; case SortType.byPages: list = _sortByPages(list: list, isAsc: state.isAsc); break; default: list = _sortByTitle(list: list, isAsc: state.isAsc); } return list; } List<Book> _filterOutFav({required List<Book> list}) { final filteredOut = List<Book>.empty(growable: true); for (var book in list) { if (book.favourite) { filteredOut.add(book); } } return filteredOut; } List<Book> _filterOutYears({ required List<Book> list, required String years, }) { final yearsList = years.split(('|||||')); final filteredOut = List<Book>.empty(growable: true); for (var book in list) { for (final reading in book.readings) { if (reading.finishDate != null) { final year = reading.finishDate!.year.toString(); if (yearsList.contains(year)) { if (!filteredOut.contains(book)) { filteredOut.add(book); } } } } } return filteredOut; } List<Book> _filterTags({ required List<Book> list, required String tags, required bool filterTagsAsAnd, required bool filterOutSelectedTags, }) { if (filterOutSelectedTags) { return _filterOutSelectedTags(list, tags); } else { if (filterTagsAsAnd) { return _filterTagsModeAnd(list, tags); } else { return _filterTagsModeOr(list, tags); } } } List<Book> _filterTagsModeOr( List<Book> list, String tags, ) { final tagsList = tags.split(('|||||')); final filteredOut = List<Book>.empty(growable: true); for (var book in list) { if (book.tags != null) { final bookTags = book.tags!.split(('|||||')); bool addThisBookToList = false; for (var bookTag in bookTags) { if (tagsList.contains(bookTag)) { addThisBookToList = true; } } if (addThisBookToList) { filteredOut.add(book); } } } return filteredOut; } List<Book> _filterOutBookTypes( List<Book> list, BookFormat bookType, ) { final filteredOut = List<Book>.empty(growable: true); for (var book in list) { if (book.bookFormat == bookType) { filteredOut.add(book); } } return filteredOut; } List<Book> _filterTagsModeAnd( List<Book> list, String tags, ) { final tagsList = tags.split(('|||||')); final filteredOut = List<Book>.empty(growable: true); for (var book in list) { if (book.tags != null) { final bookTags = book.tags!.split(('|||||')); bool addThisBookToList = true; for (var tagFromList in tagsList) { if (!bookTags.contains(tagFromList)) { addThisBookToList = false; } } if (addThisBookToList) { filteredOut.add(book); } } } return filteredOut; } // Return list of books that do not have selected tags List<Book> _filterOutSelectedTags( List<Book> list, String tags, ) { final tagsList = tags.split(('|||||')); final filteredOut = List<Book>.empty(growable: true); for (var book in list) { if (book.tags == null) { filteredOut.add(book); } else { final bookTags = book.tags!.split(('|||||')); bool addThisBookToList = true; for (var tagFromList in tagsList) { if (bookTags.contains(tagFromList)) { addThisBookToList = false; } } if (addThisBookToList) { filteredOut.add(book); } } } return filteredOut; } List<Book> _sortByTitle({ required List<Book> list, required bool isAsc, }) { isAsc ? list.sort((a, b) => removeDiacritics(a.title.toString().toLowerCase()) .compareTo(removeDiacritics(b.title.toString().toLowerCase()))) : list.sort((b, a) => removeDiacritics(a.title.toString().toLowerCase()) .compareTo(removeDiacritics(b.title.toString().toLowerCase()))); // no secondary sorting return list; } List<Book> _sortByAuthor({ required List<Book> list, required bool isAsc, }) { list.sort((a, b) { int authorSorting = removeDiacritics(a.author.toString().toLowerCase()) .compareTo(removeDiacritics(b.author.toString().toLowerCase())); if (!isAsc) { authorSorting *= -1; } // descending if (authorSorting == 0) { // secondary sorting, by release date int releaseSorting = 0; if ((a.publicationYear != null) && (b.publicationYear != null)) { releaseSorting = a.publicationYear!.compareTo(b.publicationYear!); if (!isAsc) { releaseSorting *= -1; } } if (releaseSorting == 0) { // tertiary sorting, by title int titleSorting = removeDiacritics(a.title.toString().toLowerCase()) .compareTo(removeDiacritics(b.title.toString().toLowerCase())); if (!isAsc) { titleSorting *= -1; } return titleSorting; } return releaseSorting; } return authorSorting; }); return list; } List<Book> _sortByRating({ required List<Book> list, required bool isAsc, }) { List<Book> booksNotRated = List.empty(growable: true); List<Book> booksRated = List.empty(growable: true); for (Book book in list) { (book.rating != null) ? booksRated.add(book) : booksNotRated.add(book); } booksRated.sort((a, b) { int ratingSorting = removeDiacritics(a.rating!.toString().toLowerCase()) .compareTo(removeDiacritics(b.rating!.toString().toLowerCase())); if (!isAsc) { ratingSorting *= -1; } // descending if (ratingSorting == 0) { // secondary sorting, by release date int releaseSorting = 0; if ((a.publicationYear != null) && (b.publicationYear != null)) { releaseSorting = a.publicationYear!.compareTo(b.publicationYear!); if (!isAsc) { releaseSorting *= -1; } } if (releaseSorting == 0) { // tertiary sorting, by title int titleSorting = removeDiacritics(a.title.toString().toLowerCase()) .compareTo(removeDiacritics(b.title.toString().toLowerCase())); if (!isAsc) { titleSorting *= -1; } return titleSorting; } return releaseSorting; } return ratingSorting; }); return booksRated + booksNotRated; } List<Book> _sortByPages({ required List<Book> list, required bool isAsc, }) { List<Book> booksWithoutPages = List.empty(growable: true); List<Book> booksWithPages = List.empty(growable: true); for (Book book in list) { (book.pages != null) ? booksWithPages.add(book) : booksWithoutPages.add(book); } booksWithPages.sort((a, b) { int pagesSorting = a.pages!.compareTo(b.pages!); if (!isAsc) { pagesSorting *= -1; } // descending if (pagesSorting == 0) { // secondary sorting, by release date int releaseSorting = 0; if ((a.publicationYear != null) && (b.publicationYear != null)) { releaseSorting = a.publicationYear!.compareTo(b.publicationYear!); if (!isAsc) { releaseSorting *= -1; } } if (releaseSorting == 0) { // tertiary sorting, by title int titleSorting = removeDiacritics(a.title.toString().toLowerCase()) .compareTo(removeDiacritics(b.title.toString().toLowerCase())); if (!isAsc) { titleSorting *= -1; } return titleSorting; } return releaseSorting; } return pagesSorting; }); return booksWithPages + booksWithoutPages; } List<Book> _sortByDateAdded({ required List<Book> list, required bool isAsc, }) { list.sort((a, b) { int dateAddedSorting = a.dateAdded.millisecondsSinceEpoch .compareTo(b.dateAdded.millisecondsSinceEpoch); if (!isAsc) { dateAddedSorting *= -1; } // descending if (dateAddedSorting == 0) { // secondary sorting, by release date int releaseSorting = 0; if ((a.publicationYear != null) && (b.publicationYear != null)) { releaseSorting = a.publicationYear!.compareTo(b.publicationYear!); if (!isAsc) { releaseSorting *= -1; } } if (releaseSorting == 0) { // tertiary sorting, by title int titleSorting = removeDiacritics(a.title.toString().toLowerCase()) .compareTo(removeDiacritics(b.title.toString().toLowerCase())); if (!isAsc) { titleSorting *= -1; } return titleSorting; } return releaseSorting; } return dateAddedSorting; }); return list; } List<Book> _sortByDateModified({ required List<Book> list, required bool isAsc, }) { list.sort((a, b) { int dateModifiedSorting = a.dateModified.millisecondsSinceEpoch .compareTo(b.dateModified.millisecondsSinceEpoch); if (!isAsc) { dateModifiedSorting *= -1; } // descending if (dateModifiedSorting == 0) { // secondary sorting, by release date int releaseSorting = 0; if ((a.publicationYear != null) && (b.publicationYear != null)) { releaseSorting = a.publicationYear!.compareTo(b.publicationYear!); if (!isAsc) { releaseSorting *= -1; } } if (releaseSorting == 0) { // tertiary sorting, by title int titleSorting = removeDiacritics(a.title.toString().toLowerCase()) .compareTo(removeDiacritics(b.title.toString().toLowerCase())); if (!isAsc) { titleSorting *= -1; } return titleSorting; } return releaseSorting; } return dateModifiedSorting; }); return list; } List<Book> _sortByStartDate({ required List<Book> list, required bool isAsc, }) { List<Book> booksWithoutStartDate = List.empty(growable: true); List<Book> booksWithStartDate = List.empty(growable: true); for (Book book in list) { bool hasStartDate = false; for (final reading in book.readings) { if (reading.startDate != null) { hasStartDate = true; } } hasStartDate ? booksWithStartDate.add(book) : booksWithoutStartDate.add(book); } booksWithStartDate.sort((a, b) { final bookALatestStartDate = getLatestStartDate(a); final bookBLatestStartDate = getLatestStartDate(b); int startDateSorting = (bookALatestStartDate!.millisecondsSinceEpoch) .compareTo(bookBLatestStartDate!.millisecondsSinceEpoch); if (!isAsc) { startDateSorting *= -1; } // descending if (startDateSorting == 0) { // secondary sorting, by release date int releaseSorting = 0; if ((a.publicationYear != null) && (b.publicationYear != null)) { releaseSorting = a.publicationYear!.compareTo(b.publicationYear!); if (!isAsc) { releaseSorting *= -1; } } if (releaseSorting == 0) { // tertiary sorting, by title int titleSorting = removeDiacritics(a.title.toString().toLowerCase()) .compareTo(removeDiacritics(b.title.toString().toLowerCase())); if (!isAsc) { titleSorting *= -1; } return titleSorting; } return releaseSorting; } return startDateSorting; }); return booksWithStartDate + booksWithoutStartDate; } List<Book> _sortByFinishDate({ required List<Book> list, required bool isAsc, }) { List<Book> booksWithoutFinishDate = List.empty(growable: true); List<Book> booksWithFinishDate = List.empty(growable: true); for (Book book in list) { bool hasFinishDate = false; for (final reading in book.readings) { if (reading.finishDate != null) { hasFinishDate = true; } } hasFinishDate ? booksWithFinishDate.add(book) : booksWithoutFinishDate.add(book); } booksWithFinishDate.sort((a, b) { final bookALatestFinishDate = getLatestFinishDate(a); final bookBLatestFinishDate = getLatestFinishDate(b); int finishDateSorting = (bookALatestFinishDate!.millisecondsSinceEpoch) .compareTo(bookBLatestFinishDate!.millisecondsSinceEpoch); if (!isAsc) { finishDateSorting *= -1; } // descending if (finishDateSorting == 0) { // secondary sorting, by release date int releaseSorting = 0; if ((a.publicationYear != null) && (b.publicationYear != null)) { releaseSorting = a.publicationYear!.compareTo(b.publicationYear!); if (!isAsc) { releaseSorting *= -1; } } if (releaseSorting == 0) { // tertiary sorting, by title int titleSorting = removeDiacritics(a.title.toString().toLowerCase()) .compareTo(removeDiacritics(b.title.toString().toLowerCase())); if (!isAsc) { titleSorting *= -1; } return titleSorting; } return releaseSorting; } return finishDateSorting; }); return booksWithFinishDate + booksWithoutFinishDate; } List<Book> _sortByPublicationYear({ required List<Book> list, required bool isAsc, }) { List<Book> booksWithoutPublicationDate = List.empty(growable: true); List<Book> booksWithPublicationDate = List.empty(growable: true); for (Book book in list) { (book.publicationYear != null) ? booksWithPublicationDate.add(book) : booksWithoutPublicationDate.add(book); } booksWithPublicationDate.sort((a, b) { int publicationYearSorting = a.publicationYear!.compareTo(b.publicationYear!); if (!isAsc) { publicationYearSorting *= -1; } if (publicationYearSorting == 0) { int titleSorting = removeDiacritics(a.title.toString().toLowerCase()) .compareTo(removeDiacritics(b.title.toString().toLowerCase())); if (!isAsc) { titleSorting *= -1; } return titleSorting; } return publicationYearSorting; }); return booksWithPublicationDate + booksWithoutPublicationDate; } void openSortFilterSheet() { FocusManager.instance.primaryFocus?.unfocus(); showModalBottomSheet( context: context, isScrollControlled: true, elevation: 0, builder: (context) { return const SortBottomSheet(); }, ); } void goToStatisticsScreen() { FocusManager.instance.primaryFocus?.unfocus(); Navigator.push( context, MaterialPageRoute( builder: (context) => const StatisticsScreen(), ), ); } void goToSettingsScreen() { FocusManager.instance.primaryFocus?.unfocus(); Navigator.push( context, MaterialPageRoute( builder: (context) => const SettingsScreen(), ), ); } void goToUnfinishedBooksScreen() { FocusManager.instance.primaryFocus?.unfocus(); Navigator.push( context, MaterialPageRoute( builder: (context) => const UnfinishedScreen(), ), ); } BookStatus _getStatusForNewBook() { if (_tabController.index == 1) { return BookStatus.inProgress; } else if (_tabController.index == 2) { return BookStatus.forLater; } else { return BookStatus.read; } } _setEmptyBookForEditScreen() { final status = _getStatusForNewBook(); final defaultBookFormat = context.read<DefaultBooksFormatCubit>().state; context.read<EditBookCubit>().setBook( Book.empty(status: status, bookFormat: defaultBookFormat), ); } _goToSearchPage() { Navigator.of(context).push( MaterialPageRoute(builder: (_) => const SearchPage()), ); } _changeBooksDisplayType() { final state = context.read<DisplayBloc>().state; if (state is GridDisplayState) { BlocProvider.of<DisplayBloc>(context).add( const ChangeDisplayEvent(displayAsGrid: false), ); } else { BlocProvider.of<DisplayBloc>(context).add( const ChangeDisplayEvent(displayAsGrid: true), ); } } _invokeThreeDotMenuOption(String choice) async { await Future.delayed(const Duration(milliseconds: 0)); if (!mounted) return; if (choice == moreButtonOptions[0]) { openSortFilterSheet(); } else if (choice == moreButtonOptions[1]) { goToStatisticsScreen(); } else if (choice == moreButtonOptions[2]) { goToUnfinishedBooksScreen(); } else if (choice == moreButtonOptions[3]) { goToSettingsScreen(); } } _onFabPressed() { showModalBottomSheet( context: context, isScrollControlled: true, elevation: 0, builder: (_) { return AddBookSheet( addManually: _addBookManually, searchInOpenLibrary: _searchInOpenLibrary, scanBarcode: _scanBarcode, ); }, ); } _addBookManually() async { _setEmptyBookForEditScreen(); Navigator.pop(context); await Future.delayed(const Duration(milliseconds: 100)); if (!mounted) return; Navigator.of(context).push( MaterialPageRoute( builder: (_) => const AddBookScreen(), ), ); } _searchInOpenLibrary() async { _setEmptyBookForEditScreen(); Navigator.pop(context); await Future.delayed(const Duration(milliseconds: 100)); if (!mounted) return; Navigator.push( context, MaterialPageRoute( builder: (context) => SearchOLScreen( status: _getStatusForNewBook(), ), ), ); } _scanBarcode() async { _setEmptyBookForEditScreen(); Navigator.pop(context); await Future.delayed(const Duration(milliseconds: 100)); if (!mounted) return; Navigator.push( context, MaterialPageRoute( builder: (context) => SearchOLScreen( scan: true, status: _getStatusForNewBook(), ), ), ); } @override bool get wantKeepAlive => true; @override void initState() { appBarHeight = AppBar().preferredSize.height; super.initState(); _tabController = TabController(length: 3, vsync: this); } @override Widget build(BuildContext context) { super.build(context); moreButtonOptions = [ LocaleKeys.sort_filter.tr(), LocaleKeys.statistics.tr(), LocaleKeys.unfinished_books.tr(), LocaleKeys.settings.tr(), ]; return BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { if (state is SetThemeState) { AppTheme.init(state, context); return PopScope( canPop: selectedBookIds.isEmpty, onPopInvoked: (didPop) { if (didPop) { return; } _resetMultiselectMode(); }, child: Scaffold( extendBodyBehindAppBar: true, resizeToAvoidBottomInset: true, appBar: selectedBookIds.isNotEmpty ? _buildMultiSelectAppBar(context) : _buildAppBar(context), floatingActionButton: selectedBookIds.isNotEmpty ? _buildMultiSelectFAB(state) : _buildFAB(context), body: _buildScaffoldBody(), ), ); } else { return const SizedBox(); } }, ); } AppBar _buildMultiSelectAppBar(BuildContext context) { return AppBar( title: Row( children: [ IconButton( icon: const Icon(Icons.close), onPressed: () { _resetMultiselectMode(); }, ), Text( '${LocaleKeys.selected.tr()} ${selectedBookIds.length}', style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), ], )); } void _resetMultiselectMode() { setState(() { selectedBookIds = {}; }); } Widget? _buildMultiSelectFAB(SetThemeState state) { return selectedBookIds.isNotEmpty ? MultiSelectFAB( selectedBookIds: selectedBookIds, resetMultiselectMode: _resetMultiselectMode, ) : null; } BlocBuilder<ThemeBloc, ThemeState> _buildScaffoldBody() { return BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { if (state is SetThemeState) { return Column( children: [ Expanded( child: TabBarView( controller: _tabController, children: state.readTabFirst ? List.of([ _buildReadBooksTabView(), _buildInProgressBooksTabView(), _buildToReadBooksTabView(), ]) : List.of([ _buildInProgressBooksTabView(), _buildReadBooksTabView(), _buildToReadBooksTabView(), ]), ), ), Builder(builder: (context) { return Container( color: Theme.of(context).scaffoldBackgroundColor, child: SafeArea( top: false, child: TabBar( controller: _tabController, dividerColor: Colors.transparent, tabs: state.readTabFirst ? List.of([ BookTab( text: LocaleKeys.books_finished.tr(), ), BookTab( text: LocaleKeys.books_in_progress.tr(), ), BookTab( text: LocaleKeys.books_for_later.tr(), ), ]) : List.of([ BookTab( text: LocaleKeys.books_in_progress.tr(), ), BookTab( text: LocaleKeys.books_finished.tr(), ), BookTab( text: LocaleKeys.books_for_later.tr(), ), ]), ), ), ); }), ], ); } else { return const SizedBox(); } }, ); } Padding _buildFAB(BuildContext context) { return Padding( padding: const EdgeInsets.only(bottom: 50), child: FloatingActionButton( onPressed: _onFabPressed, child: const Icon(Icons.add), ), ); } PreferredSizeWidget _buildAppBar(BuildContext context) { AppBar appBar = AppBar( backgroundColor: Theme.of(context).colorScheme.surface.withOpacity(0.9), title: const Text( Constants.appName, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), actions: [ IconButton( onPressed: _goToSearchPage, icon: const Icon(Icons.search), ), IconButton( onPressed: _changeBooksDisplayType, icon: BlocBuilder<DisplayBloc, DisplayState>( builder: (context, state) { if (state is GridDisplayState) { return const Icon(Icons.list); } else { return const Icon(Icons.apps); } }, ), ), PopupMenuButton<String>( onSelected: (_) {}, itemBuilder: (_) { return moreButtonOptions.map((String choice) { return PopupMenuItem<String>( value: choice, child: Text( choice, ), onTap: () => _invokeThreeDotMenuOption(choice), ); }).toList(); }, ), ], ); return Platform.isAndroid ? appBar : PreferredSize( preferredSize: Size(double.infinity, appBarHeight), child: ClipRRect( child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 30, sigmaY: 30), child: appBar, ), ), ); } StreamBuilder<List<Book>> _buildToReadBooksTabView() { return StreamBuilder<List<Book>>( stream: bookCubit.toReadBooks, builder: (context, AsyncSnapshot<List<Book>> snapshot) { if (snapshot.hasData) { if (snapshot.data == null || snapshot.data!.isEmpty) { return Center( child: Padding( padding: const EdgeInsets.all(50), child: Text( '${LocaleKeys.this_list_is_empty_1.tr()}\n${LocaleKeys.this_list_is_empty_2.tr()}', textAlign: TextAlign.center, style: const TextStyle( letterSpacing: 1.5, fontSize: 16, ), ), ), ); } return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { return BlocBuilder<DisplayBloc, DisplayState>( builder: (context, displayState) { if (displayState is GridDisplayState) { return BooksGrid( books: _sortForLaterList( state: state, list: snapshot.data!, ), listNumber: 2, selectedBookIds: selectedBookIds, onBookSelectedForMultiSelect: _onItemSelected, allBooksCount: snapshot.data!.length, ); } else { return BooksList( books: _sortForLaterList( state: state, list: snapshot.data!, ), listNumber: 2, selectedBookIds: selectedBookIds, onBookSelected: _onItemSelected, allBooksCount: snapshot.data!.length, ); } }, ); } else { return const SizedBox(); } }, ); } else if (snapshot.hasError) { return Text( snapshot.error.toString(), ); } else { return const SizedBox(); } }, ); } StreamBuilder<List<Book>> _buildInProgressBooksTabView() { return StreamBuilder<List<Book>>( stream: bookCubit.inProgressBooks, builder: (context, AsyncSnapshot<List<Book>> snapshot) { if (snapshot.hasData) { if (snapshot.data == null || snapshot.data!.isEmpty) { return Center( child: Padding( padding: const EdgeInsets.all(50), child: Text( '${LocaleKeys.this_list_is_empty_1.tr()}\n${LocaleKeys.this_list_is_empty_2.tr()}', textAlign: TextAlign.center, style: const TextStyle( letterSpacing: 1.5, fontSize: 16, ), ), ), ); } return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { return BlocBuilder<DisplayBloc, DisplayState>( builder: (context, displayState) { if (displayState is GridDisplayState) { return BooksGrid( books: _sortInProgressList( state: state, list: snapshot.data!, ), listNumber: 1, selectedBookIds: selectedBookIds, onBookSelectedForMultiSelect: _onItemSelected, allBooksCount: snapshot.data!.length, ); } else { return BooksList( books: _sortInProgressList( state: state, list: snapshot.data!, ), listNumber: 1, selectedBookIds: selectedBookIds, onBookSelected: _onItemSelected, allBooksCount: snapshot.data!.length, ); } }, ); } else { return const SizedBox(); } }, ); } else if (snapshot.hasError) { return Text( snapshot.error.toString(), ); } else { return const SizedBox(); } }, ); } StreamBuilder<List<Book>> _buildReadBooksTabView() { return StreamBuilder<List<Book>>( stream: bookCubit.finishedBooks, builder: (context, AsyncSnapshot<List<Book>> snapshot) { if (snapshot.hasData) { if (snapshot.data == null || snapshot.data!.isEmpty) { return Center( child: Padding( padding: const EdgeInsets.all(50), child: Text( '${LocaleKeys.this_list_is_empty_1.tr()}\n${LocaleKeys.this_list_is_empty_2.tr()}', textAlign: TextAlign.center, style: const TextStyle( letterSpacing: 1.5, fontSize: 16, ), ), ), ); } return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { return BlocBuilder<DisplayBloc, DisplayState>( builder: (context, displayState) { if (displayState is GridDisplayState) { return BooksGrid( books: _sortReadList( state: state, list: snapshot.data!, ), listNumber: 0, selectedBookIds: selectedBookIds, onBookSelectedForMultiSelect: _onItemSelected, allBooksCount: snapshot.data!.length, ); } else { return BooksList( books: _sortReadList( state: state, list: snapshot.data!, ), listNumber: 0, selectedBookIds: selectedBookIds, onBookSelected: _onItemSelected, allBooksCount: snapshot.data!.length, ); } }, ); } else { return const SizedBox(); } }, ); } else if (snapshot.hasError) { return Text( snapshot.error.toString(), ); } else { return const Center( child: CircularProgressIndicator(), ); } }, ); } }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/tag_filter_chip.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; class TagFilterChip extends StatelessWidget { const TagFilterChip({ super.key, required this.tag, required this.selected, required this.onTagChipPressed, }); final String? tag; final bool selected; final Function(bool) onTagChipPressed; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 5), child: FilterChip( backgroundColor: Theme.of(context).colorScheme.surface, side: BorderSide(color: dividerColor, width: 1), label: Text( tag != null ? tag.toString() : LocaleKeys.select_all.tr(), style: TextStyle( color: selected ? Theme.of(context).colorScheme.onPrimary : Theme.of(context).colorScheme.onSurface, ), ), checkmarkColor: Theme.of(context).colorScheme.onPrimary, selected: selected, selectedColor: Theme.of(context).colorScheme.primary, onSelected: onTagChipPressed, ), ); } }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/book_tab.dart
import 'package:flutter/material.dart'; class BookTab extends StatelessWidget { const BookTab({ super.key, required this.text, }); final String text; @override Widget build(BuildContext context) { return Tab( child: Text( text, textAlign: TextAlign.center, ), ); } }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/books_grid.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/logic/cubit/current_book_cubit.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/book_screen/book_screen.dart'; import 'package:openreads/ui/books_screen/widgets/widgets.dart'; class BooksGrid extends StatefulWidget { const BooksGrid({ super.key, required this.books, required this.listNumber, this.selectedBookIds, this.onBookSelectedForMultiSelect, required this.allBooksCount, }); final List<Book> books; final int listNumber; final Set<int>? selectedBookIds; final Function(int id)? onBookSelectedForMultiSelect; final int allBooksCount; @override State<BooksGrid> createState() => _BooksGridState(); } class _BooksGridState extends State<BooksGrid> with AutomaticKeepAliveClientMixin { _onPressed(int index, bool multiSelectMode, String heroTag) { if (widget.books[index].id == null) return; if (multiSelectMode && widget.onBookSelectedForMultiSelect != null) { widget.onBookSelectedForMultiSelect!(widget.books[index].id!); return; } context.read<CurrentBookCubit>().setBook(widget.books[index]); Navigator.push( context, MaterialPageRoute( builder: (context) => BookScreen( id: widget.books[index].id!, heroTag: heroTag, ), ), ); } onLongPressed(int index) { if (widget.books[index].id == null) return; if (widget.onBookSelectedForMultiSelect != null) { widget.onBookSelectedForMultiSelect!(widget.books[index].id!); return; } } @override Widget build(BuildContext context) { super.build(context); var multiSelectMode = widget.selectedBookIds?.isNotEmpty ?? false; return CustomScrollView( slivers: [ SliverToBoxAdapter( child: SizedBox( height: MediaQuery.of(context).padding.top, ), ), SliverToBoxAdapter( child: Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 10), child: Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( '${widget.books.length} ', style: const TextStyle(fontSize: 13), ), Text( '(${widget.allBooksCount})', style: TextStyle( color: Theme.of(context) .colorScheme .onBackground .withOpacity(0.7), fontSize: 12, ), ), ], ), ), ), SliverPadding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 90), sliver: SliverGrid.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, childAspectRatio: 1 / 1.5, mainAxisSpacing: 4, crossAxisSpacing: 4, ), itemCount: widget.books.length, itemBuilder: (context, index) { final heroTag = 'tag_${widget.listNumber}_${widget.books[index].id}'; Color color = multiSelectMode && widget.selectedBookIds!.contains(widget.books[index].id) ? Theme.of(context).colorScheme.primaryContainer : Colors.transparent; return Container( decoration: multiSelectMode ? BoxDecoration( border: Border.all(color: color, width: 4), ) : null, child: BookGridCard( book: widget.books[index], heroTag: heroTag, addBottomPadding: (widget.books.length == index + 1), onPressed: () => _onPressed( index, multiSelectMode, heroTag, ), onLongPressed: () => onLongPressed(index), )); }, ), ), ], ); } @override bool get wantKeepAlive => true; }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/multi_select_fab.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_speed_dial/flutter_speed_dial.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/main.dart'; import 'package:openreads/ui/add_book_screen/widgets/book_text_field.dart'; import 'package:openreads/ui/add_book_screen/widgets/book_type_dropdown.dart'; class MultiSelectFAB extends StatelessWidget { MultiSelectFAB({ super.key, required this.selectedBookIds, required this.resetMultiselectMode, }); final Set<int> selectedBookIds; final Function resetMultiselectMode; final bookTypes = [ LocaleKeys.book_format_paperback.tr(), LocaleKeys.book_format_hardcover.tr(), LocaleKeys.book_format_ebook.tr(), LocaleKeys.book_format_audiobook.tr(), ]; final _authorCtrl = TextEditingController(); String _getLabel(BulkEditOption bulkEditOption) { String label = ''; switch (bulkEditOption) { case BulkEditOption.format: label = LocaleKeys.change_book_format.tr(); break; case BulkEditOption.author: label = LocaleKeys.change_books_author.tr(); break; default: label = ''; } return label; } showEditBooksBottomSheet( BuildContext context, Set<int> selectedBookIds, BulkEditOption bulkEditOption, ) { return showModalBottomSheet( isScrollControlled: true, context: context, builder: (context) { return SafeArea( child: AnimatedPadding( duration: const Duration(milliseconds: 150), curve: Curves.easeOut, padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom), child: Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 50), child: Column( mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 10), _buildTopLine(context), const SizedBox(height: 20), _buildHeader(bulkEditOption), const SizedBox(height: 20), bulkEditOption == BulkEditOption.format ? _buildEditFormat(selectedBookIds, context) : bulkEditOption == BulkEditOption.author ? _buildEditAuthor(selectedBookIds, context) : const SizedBox(), ], ), ), ), ); }); } void _updateBooksFormat(String bookType, Set<int> selectedIds) { BookFormat selectedBookType = BookFormat.paperback; if (bookType == bookTypes[0]) { selectedBookType = BookFormat.paperback; } else if (bookType == bookTypes[1]) { selectedBookType = BookFormat.hardcover; } else if (bookType == bookTypes[2]) { selectedBookType = BookFormat.ebook; } else if (bookType == bookTypes[3]) { selectedBookType = BookFormat.audiobook; } else { selectedBookType = BookFormat.paperback; } bookCubit.bulkUpdateBookFormat(selectedIds, selectedBookType); } bool _updateBooksAuthor(Set<int> selectedIds) { final author = _authorCtrl.text; if (author.isEmpty) return false; bookCubit.bulkUpdateBookAuthor(selectedIds, author); return true; } _showDeleteBooksDialog(BuildContext context) { showDialog( context: context, builder: (BuildContext dialogContext) { return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), title: Text( LocaleKeys.delete_books_question.tr(), style: const TextStyle(fontSize: 18), ), actionsAlignment: MainAxisAlignment.spaceBetween, actions: [ FilledButton.tonal( onPressed: () { Navigator.of(context).pop(); }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Text(LocaleKeys.no.tr()), ), ), FilledButton( onPressed: () => _bulkDeleteBooks(context), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Text(LocaleKeys.yes.tr()), ), ), ], ); }, ); } _bulkDeleteBooks(BuildContext context) async { for (final bookId in selectedBookIds) { final book = await bookCubit.getBook(bookId); if (book == null) continue; await bookCubit.updateBook(book.copyWith( deleted: true, )); } bookCubit.getDeletedBooks(); Navigator.of(context).pop(); resetMultiselectMode(); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(bottom: 50), child: SpeedDial( spacing: 3, dialRoot: (ctx, open, toggleChildren) { return FloatingActionButton( onPressed: toggleChildren, child: const Icon(Icons.create), ); }, childPadding: const EdgeInsets.all(5), spaceBetweenChildren: 4, children: [ SpeedDialChild( child: const Icon(Icons.menu_book_outlined), backgroundColor: Theme.of(context).colorScheme.secondaryContainer, label: LocaleKeys.change_book_format.tr(), onTap: () { showEditBooksBottomSheet( context, selectedBookIds, BulkEditOption.format, ); }, ), SpeedDialChild( child: const Icon(Icons.person), backgroundColor: Theme.of(context).colorScheme.secondaryContainer, label: LocaleKeys.change_books_author.tr(), onTap: () { showEditBooksBottomSheet( context, selectedBookIds, BulkEditOption.author, ); }, ), SpeedDialChild( child: const Icon(Icons.delete), backgroundColor: Theme.of(context).colorScheme.secondaryContainer, label: LocaleKeys.delete_books.tr(), onTap: () => _showDeleteBooksDialog(context), ), ], ), ); } Column _buildEditAuthor(Set<int> selectedBookIds, BuildContext context) { return Column( children: [ BookTextField( controller: _authorCtrl, hint: LocaleKeys.enter_author.tr(), icon: Icons.person, keyboardType: TextInputType.name, maxLines: 5, maxLength: 255, textCapitalization: TextCapitalization.words, ), const SizedBox(height: 20), Row( children: [ const SizedBox(width: 10), Expanded( child: FilledButton( onPressed: () { final result = _updateBooksAuthor(selectedBookIds); Navigator.pop(context); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( result ? LocaleKeys.update_successful_message.tr() : LocaleKeys.bulk_update_unsuccessful_message.tr(), ), ), ); }, child: Text(LocaleKeys.save.tr()), ), ), const SizedBox(width: 10), ], ), ], ); } BookTypeDropdown _buildEditFormat( Set<int> selectedBookIds, BuildContext context) { return BookTypeDropdown( bookTypes: bookTypes, changeBookType: (bookType) { if (bookType == null) return; _updateBooksFormat(bookType, selectedBookIds); Navigator.pop(context); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(LocaleKeys.update_successful_message.tr()), ), ); }, ); } Row _buildHeader(BulkEditOption bulkEditOption) { return Row( children: [ const SizedBox(width: 10), Text( _getLabel(bulkEditOption), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), const SizedBox(width: 10), ], ); } Container _buildTopLine(BuildContext context) { return Container( height: 3, width: MediaQuery.of(context).size.width / 4, decoration: BoxDecoration( color: Colors.grey.shade300, borderRadius: BorderRadius.circular(10), ), ); } }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/grid_card_cover.dart
import 'dart:io'; import 'package:flutter/material.dart'; class GridCardCover extends StatelessWidget { const GridCardCover({ super.key, required this.heroTag, required this.file, }); final String heroTag; final File file; @override Widget build(BuildContext context) { return Hero( tag: heroTag, child: Image.file( file, fit: BoxFit.cover, frameBuilder: ( BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded, ) { if (wasSynchronouslyLoaded) { return child; } return AnimatedOpacity( opacity: frame == null ? 0 : 1, duration: const Duration(milliseconds: 250), curve: Curves.easeOut, child: child, ); }, ), ); } }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/add_book_sheet.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/ui/books_screen/widgets/widgets.dart'; class AddBookSheet extends StatefulWidget { const AddBookSheet({ super.key, required this.addManually, required this.searchInOpenLibrary, required this.scanBarcode, }); final Function() addManually; final Function() searchInOpenLibrary; final Function() scanBarcode; @override State<AddBookSheet> createState() => _AddBookSheetState(); } class _AddBookSheetState extends State<AddBookSheet> { @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 10), Container( height: 3, width: MediaQuery.of(context).size.width / 4, decoration: BoxDecoration( color: Colors.grey.shade300, borderRadius: BorderRadius.circular(10), ), ), Container( padding: const EdgeInsets.fromLTRB(10, 20, 10, 40), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), ), child: IntrinsicHeight( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ const SizedBox(width: 10), Expanded( child: AddBookMethodButton( text: LocaleKeys.add_manually.tr(), icon: FontAwesomeIcons.solidKeyboard, onPressed: widget.addManually, ), ), const SizedBox(width: 20), Expanded( child: AddBookMethodButton( text: LocaleKeys.add_search.tr(), icon: FontAwesomeIcons.magnifyingGlass, onPressed: widget.searchInOpenLibrary, ), ), const SizedBox(width: 20), Expanded( child: AddBookMethodButton( text: LocaleKeys.add_scan.tr(), icon: FontAwesomeIcons.barcode, onPressed: widget.scanBarcode, ), ), const SizedBox(width: 10), ], ), ), ), ], ); } }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/sort_bottom_sheet.dart
import 'package:diacritic/diacritic.dart'; import 'package:dropdown_button2/dropdown_button2.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/sort_bloc/sort_bloc.dart'; import 'package:openreads/main.dart'; import 'package:openreads/ui/books_screen/widgets/widgets.dart'; class SortBottomSheet extends StatefulWidget { const SortBottomSheet({super.key}); @override State<SortBottomSheet> createState() => _SortBottomSheetState(); } final List<String> sortOptions = [ LocaleKeys.title.tr(), LocaleKeys.author.tr(), LocaleKeys.rating.tr(), LocaleKeys.pages_uppercase.tr(), LocaleKeys.start_date.tr(), LocaleKeys.finish_date.tr(), LocaleKeys.enter_publication_year.tr(), LocaleKeys.date_added.tr(), LocaleKeys.date_modified.tr(), ]; final List<String> bookTypeOptions = [ LocaleKeys.book_format_all.tr(), LocaleKeys.book_format_paperback_plural.tr(), LocaleKeys.book_format_hardcover_plural.tr(), LocaleKeys.book_format_ebook_plural.tr(), LocaleKeys.book_format_audiobook_plural.tr(), ]; String _getSortDropdownValue(SetSortState state) { if (state.sortType == SortType.byAuthor) { return sortOptions[1]; } else if (state.sortType == SortType.byRating) { return sortOptions[2]; } else if (state.sortType == SortType.byPages) { return sortOptions[3]; } else if (state.sortType == SortType.byStartDate) { return sortOptions[4]; } else if (state.sortType == SortType.byFinishDate) { return sortOptions[5]; } else if (state.sortType == SortType.byPublicationYear) { return sortOptions[6]; } else if (state.sortType == SortType.byDateAdded) { return sortOptions[7]; } else if (state.sortType == SortType.byDateModified) { return sortOptions[8]; } else { return sortOptions[0]; } } String _getBookTypeDropdownValue(SetSortState state) { if (state.bookType == BookFormat.paperback) { return bookTypeOptions[1]; } else if (state.bookType == BookFormat.hardcover) { return bookTypeOptions[2]; } else if (state.bookType == BookFormat.ebook) { return bookTypeOptions[3]; } else if (state.bookType == BookFormat.audiobook) { return bookTypeOptions[4]; } else { return bookTypeOptions[0]; } } Widget _getOrderButton(BuildContext context, SetSortState state) { return SizedBox( height: 40, width: 40, child: IconButton( icon: (state.isAsc) ? const Icon(Icons.arrow_upward) : const Icon(Icons.arrow_downward), onPressed: () => BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: !state.isAsc, onlyFavourite: state.onlyFavourite, years: state.years, tags: state.tags, displayTags: state.displayTags, filterTagsAsAnd: state.filterTagsAsAnd, bookType: state.bookType, filterOutTags: state.filterOutTags, ), ), ), ); } void _updateSort(BuildContext context, String? value, SetSortState state) { late SortType sortType; if (value == sortOptions[1]) { sortType = SortType.byAuthor; } else if (value == sortOptions[2]) { sortType = SortType.byRating; } else if (value == sortOptions[3]) { sortType = SortType.byPages; } else if (value == sortOptions[4]) { sortType = SortType.byStartDate; } else if (value == sortOptions[5]) { sortType = SortType.byFinishDate; } else if (value == sortOptions[6]) { sortType = SortType.byPublicationYear; } else if (value == sortOptions[7]) { sortType = SortType.byDateAdded; } else if (value == sortOptions[8]) { sortType = SortType.byDateModified; } else { sortType = SortType.byTitle; } BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: state.years, tags: state.tags, displayTags: state.displayTags, filterTagsAsAnd: state.filterTagsAsAnd, bookType: state.bookType, filterOutTags: state.filterOutTags, ), ); } void _updateBookType(BuildContext context, String? value, SetSortState state) { BookFormat? bookType; if (value == bookTypeOptions[1]) { bookType = BookFormat.paperback; } else if (value == bookTypeOptions[2]) { bookType = BookFormat.hardcover; } else if (value == bookTypeOptions[3]) { bookType = BookFormat.ebook; } else if (value == bookTypeOptions[4]) { bookType = BookFormat.audiobook; } else { bookType = null; } BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: state.years, tags: state.tags, displayTags: state.displayTags, filterTagsAsAnd: state.filterTagsAsAnd, bookType: bookType, filterOutTags: state.filterOutTags, ), ); } class _SortBottomSheetState extends State<SortBottomSheet> { Widget _getFavouriteSwitch( BuildContext context, SetSortState state, ) { return SizedBox( height: 40, child: Switch( value: state.onlyFavourite, onChanged: (value) => BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: value, years: state.years, tags: state.tags, displayTags: state.displayTags, filterTagsAsAnd: state.filterTagsAsAnd, bookType: state.bookType, filterOutTags: state.filterOutTags, ), ), ), ); } Widget _getTagsSwitch( BuildContext context, SetSortState state, ) { return Switch( value: state.displayTags, onChanged: (value) => BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: state.years, tags: state.tags, displayTags: value, filterTagsAsAnd: state.filterTagsAsAnd, bookType: state.bookType, filterOutTags: state.filterOutTags, ), ), ); } Widget _getTagsAsAndSwitch( BuildContext context, SetSortState state, ) { return Switch( value: state.filterTagsAsAnd, onChanged: (value) => BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: state.years, tags: state.tags, displayTags: state.displayTags, filterTagsAsAnd: value, bookType: state.bookType, filterOutTags: false, ), ), ); } Widget _getFilterOutTagsSwitch( BuildContext context, SetSortState state, ) { return Switch( value: state.filterOutTags, onChanged: (value) => BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: state.years, tags: state.tags, displayTags: state.displayTags, filterTagsAsAnd: false, bookType: state.bookType, filterOutTags: value, ), ), ); } _onYearChipPressed({ required bool selected, required List<String> selectedYearsList, required List<int> dbYears, required int dbYear, required SetSortState state, }) { if (selectedYearsList.isNotEmpty && selectedYearsList[0] == '') { selectedYearsList.removeAt(0); } if (selected) { selectedYearsList.add(dbYear.toString()); } else { bool deleteYear = true; while (deleteYear) { deleteYear = selectedYearsList.remove(dbYear.toString()); } } BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: (selectedYearsList.isEmpty) ? null : selectedYearsList.join('|||||'), tags: state.tags, displayTags: state.displayTags, filterTagsAsAnd: state.filterTagsAsAnd, bookType: state.bookType, filterOutTags: state.filterOutTags, ), ); } _onTagChipPressed({ required bool selected, required List<String> selectedTagsList, required String dbTag, required SetSortState state, }) { if (selectedTagsList.isNotEmpty && selectedTagsList[0] == '') { selectedTagsList.removeAt(0); } if (selected) { selectedTagsList.add(dbTag); } else { bool deleteYear = true; while (deleteYear) { deleteYear = selectedTagsList.remove(dbTag); } } BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: state.years, tags: (selectedTagsList.isEmpty) ? null : selectedTagsList.join('|||||'), displayTags: state.displayTags, filterTagsAsAnd: state.filterTagsAsAnd, bookType: state.bookType, filterOutTags: state.filterOutTags, ), ); } List<Widget> _buildYearChips( SetSortState state, List<int> dbYears, String? selectedYears, ) { final chips = List<Widget>.empty(growable: true); final inactiveChips = List<Widget>.empty(growable: true); late List<String> selectedYearsList; final uniqueDbYears = List<int>.empty(growable: true); for (var dbYear in dbYears) { if (!uniqueDbYears.contains(dbYear)) { uniqueDbYears.add(dbYear); } } if (selectedYears != null) { selectedYearsList = selectedYears.split('|||||'); } else { selectedYearsList = List<String>.empty(growable: true); } for (var selectedYear in selectedYearsList) { if (!uniqueDbYears.contains(int.parse(selectedYear))) { uniqueDbYears.add(int.parse(selectedYear)); } } for (var dbYear in uniqueDbYears) { bool isSelected = selectedYearsList.contains(dbYear.toString()); YearFilterChip chip = YearFilterChip( dbYear: dbYear, selected: isSelected, onYearChipPressed: (bool selected) { _onYearChipPressed( dbYear: dbYear, dbYears: uniqueDbYears, selected: selected, selectedYearsList: selectedYearsList, state: state, ); }, ); if (isSelected) { chips.add(chip); } else { inactiveChips.add(chip); } } chips.addAll(inactiveChips); // Last chip is to select all/none years chips.add( YearFilterChip( dbYear: null, selected: selectedYears == dbYears.join('|||||'), onYearChipPressed: (bool selected) { BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: selectedYears == dbYears.join('|||||') ? null : dbYears.join('|||||'), tags: state.tags, displayTags: state.displayTags, filterTagsAsAnd: state.filterTagsAsAnd, bookType: state.bookType, filterOutTags: state.filterOutTags, ), ); }, ), ); return chips; } List<Widget> _buildTagChips( SetSortState state, List<String> dbTags, String? selectedTags, ) { final chips = List<Widget>.empty(growable: true); final inactiveChips = List<Widget>.empty(growable: true); late List<String> selectedTagsList; if (selectedTags != null) { selectedTagsList = selectedTags.split('|||||'); } else { selectedTagsList = List<String>.empty(growable: true); } selectedTagsList.sort((a, b) => removeDiacritics(a.toLowerCase()) .compareTo(removeDiacritics(b.toLowerCase()))); for (var selectedTag in selectedTagsList) { if (!dbTags.contains(selectedTag)) { dbTags.add(selectedTag); } } dbTags.sort((a, b) => removeDiacritics(a.toLowerCase()) .compareTo(removeDiacritics(b.toLowerCase()))); for (var dbTag in dbTags) { bool isSelected = selectedTagsList.contains(dbTag.toString()); TagFilterChip chip = TagFilterChip( tag: dbTag, selected: isSelected, onTagChipPressed: (bool selected) { _onTagChipPressed( dbTag: dbTag, selected: selected, selectedTagsList: selectedTagsList, state: state, ); }, ); if (isSelected) { chips.add(chip); } else { inactiveChips.add(chip); } } chips.addAll(inactiveChips); // Last chip is to select all/none tags chips.add( TagFilterChip( tag: null, selected: selectedTags == dbTags.join('|||||'), onTagChipPressed: (bool selected) { BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: state.years, tags: selectedTags == dbTags.join('|||||') ? null : dbTags.join('|||||'), displayTags: state.displayTags, filterTagsAsAnd: state.filterTagsAsAnd, bookType: state.bookType, filterOutTags: state.filterOutTags, ), ); }, ), ); return chips; } @override Widget build(BuildContext context) { return SafeArea( child: Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 10), Container( height: 3, width: MediaQuery.of(context).size.width / 4, decoration: BoxDecoration( color: Colors.grey.shade300, borderRadius: BorderRadius.circular(10), ), ), Container( padding: const EdgeInsets.fromLTRB(20, 10, 20, 10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: Theme.of(context).colorScheme.surface, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 8), Text( LocaleKeys.sort_by.tr(), style: const TextStyle(fontSize: 16), ), const SizedBox(height: 4), _buildSortDropdown(), const SizedBox(height: 8), _buildOnlyFavouriteSwitch(), const SizedBox(height: 8), Text( LocaleKeys.filter_by_book_format.tr(), style: const TextStyle(fontSize: 16), ), const SizedBox(height: 4), _buildBookTypeFilter(), _buildFilterByFinishYears(), _buildFilterByTags(), _buildFilterTagsAsAnd(), _buildFilterOutTags(), const SizedBox(height: 8), _buildDisplayTags(), const SizedBox(height: 50), ], ), ), ], ), ); } BlocBuilder<SortBloc, SortState> _buildDisplayTags() { return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { return Row( children: [ Expanded( child: InkWell( onTap: () { BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: state.years, tags: state.tags, displayTags: !state.displayTags, filterTagsAsAnd: state.filterTagsAsAnd, bookType: state.bookType, filterOutTags: state.filterOutTags, ), ); }, child: Container( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(cornerRadius), border: Border.all( color: dividerColor, ), ), child: Row( children: [ _getTagsSwitch(context, state), const SizedBox(width: 10), Text( LocaleKeys.display_tags.tr(), style: const TextStyle(fontSize: 16), ), ], ), ), ), ), ], ); } else { return const SizedBox(); } }, ); } BlocBuilder<SortBloc, SortState> _buildFilterOutTags() { return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { return Row( children: [ Expanded( child: InkWell( onTap: () { BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: state.years, tags: state.tags, displayTags: state.displayTags, filterTagsAsAnd: false, bookType: state.bookType, filterOutTags: !state.filterOutTags, ), ); }, child: _buildBooksExceptTags(context, state), ), ), ], ); } else { return const SizedBox(); } }, ); } BlocBuilder<SortBloc, SortState> _buildFilterTagsAsAnd() { return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { return Row( children: [ Expanded( child: InkWell( onTap: () { BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: state.onlyFavourite, years: state.years, tags: state.tags, displayTags: state.displayTags, filterTagsAsAnd: !state.filterTagsAsAnd, bookType: state.bookType, filterOutTags: state.filterOutTags, ), ); }, child: _buildOnlyBooksWithAllTags(context, state), ), ), ], ); } else { return const SizedBox(); } }, ); } StreamBuilder<List<String>> _buildFilterByTags() { return StreamBuilder<List<String>>( stream: bookCubit.tags, builder: (context, AsyncSnapshot<List<String>> snapshot) { if (snapshot.hasData) { return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { if (snapshot.data!.isEmpty && state.tags == null) { return const SizedBox(); } return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 8), Text( LocaleKeys.filter_by_tags.tr(), style: const TextStyle(fontSize: 16), ), const SizedBox(height: 4), Row( children: [ Expanded( child: Container( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular( cornerRadius, ), border: Border.all( color: dividerColor, ), ), child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Padding( padding: const EdgeInsets.symmetric( vertical: 5, horizontal: 2.5, ), child: Row( children: _buildTagChips( state, snapshot.data!, state.tags, ), ), ), ), ), ), ], ), ], ); } else { return const SizedBox(); } }, ); } else if (snapshot.hasData && snapshot.data!.isEmpty) { return const SizedBox(); } else if (snapshot.hasError) { return Text( snapshot.error.toString(), ); } else { return const Center( child: CircularProgressIndicator(), ); } }, ); } StreamBuilder<List<int>> _buildFilterByFinishYears() { return StreamBuilder<List<int>>( stream: bookCubit.finishedYears, builder: (context, AsyncSnapshot<List<int>> snapshot) { if (snapshot.hasData) { return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { if (snapshot.data!.isEmpty && state.years == null) { return const SizedBox(); } return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 8), Text( LocaleKeys.filter_by_finish_year.tr(), style: const TextStyle(fontSize: 16), ), const SizedBox(height: 4), Row( children: [ Expanded( child: Container( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular( cornerRadius, ), border: Border.all( color: dividerColor, ), ), child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Padding( padding: const EdgeInsets.symmetric( vertical: 5, horizontal: 2.5, ), child: Row( children: _buildYearChips( state, snapshot.data!, state.years, ), ), ), ), ), ), ], ), ], ); } else { return const SizedBox(); } }, ); } else if (snapshot.hasData && snapshot.data!.isEmpty) { return const SizedBox(); } else if (snapshot.hasError) { return Text( snapshot.error.toString(), ); } else { return const Center( child: CircularProgressIndicator(), ); } }, ); } BlocBuilder<SortBloc, SortState> _buildOnlyFavouriteSwitch() { return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { return Row( children: [ Expanded( child: InkWell( onTap: () { BlocProvider.of<SortBloc>(context).add( ChangeSortEvent( sortType: state.sortType, isAsc: state.isAsc, onlyFavourite: !state.onlyFavourite, years: state.years, tags: state.tags, displayTags: state.displayTags, filterTagsAsAnd: state.filterTagsAsAnd, bookType: state.bookType, filterOutTags: state.filterOutTags, ), ); }, child: Container( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(cornerRadius), border: Border.all( color: dividerColor, ), ), child: Row( children: [ _getFavouriteSwitch(context, state), const SizedBox(width: 8), Text( LocaleKeys.only_favourite.tr(), style: const TextStyle(fontSize: 16), ), ], ), ), ), ), ], ); } else { return const SizedBox(); } }, ); } BlocBuilder<SortBloc, SortState> _buildSortDropdown() { return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { return Row( children: [ Expanded( child: DropdownButtonHideUnderline( child: DropdownButton2( isExpanded: true, buttonStyleData: ButtonStyleData( height: 42, decoration: BoxDecoration( border: Border.all( color: dividerColor, ), color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(cornerRadius), ), ), items: sortOptions .map((item) => DropdownMenuItem<String>( value: item, child: Text( item, overflow: TextOverflow.ellipsis, ), )) .toList(), value: _getSortDropdownValue(state), onChanged: (value) => _updateSort( context, value, state, ), ), ), ), const SizedBox(width: 8), Container( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(cornerRadius), border: Border.all( color: dividerColor, ), ), child: _getOrderButton(context, state), ) ], ); } else { return const SizedBox(); } }, ); } Widget _buildBookTypeFilter() { return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { return DropdownButtonHideUnderline( child: DropdownButton2( isExpanded: true, buttonStyleData: ButtonStyleData( height: 42, decoration: BoxDecoration( border: Border.all( color: dividerColor, ), color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(cornerRadius), ), ), items: bookTypeOptions .map( (item) => DropdownMenuItem<String>( value: item, child: Text( item, overflow: TextOverflow.ellipsis, ), ), ) .toList(), value: _getBookTypeDropdownValue(state), onChanged: (value) => _updateBookType( context, value, state, ), ), ); } else { return const SizedBox(); } }, ); } Widget _buildOnlyBooksWithAllTags(BuildContext context, SetSortState state) { return StreamBuilder<List<String>>( stream: bookCubit.tags, builder: (context, AsyncSnapshot<List<String>> snapshot) { if (snapshot.hasData && snapshot.data!.isNotEmpty) { return Padding( padding: const EdgeInsets.only(top: 10), child: Container( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: Row( children: [ _getTagsAsAndSwitch(context, state), const SizedBox(width: 10), Expanded( child: Text( LocaleKeys.only_books_with_all_tags.tr(), style: const TextStyle(fontSize: 16), ), ), ], ), ), ); } else if (snapshot.hasData && snapshot.data!.isEmpty) { return const SizedBox(); } else if (snapshot.hasError) { return Text( snapshot.error.toString(), ); } else { return const Center( child: CircularProgressIndicator(), ); } }, ); } Widget _buildBooksExceptTags(BuildContext context, SetSortState state) { return StreamBuilder<List<String>>( stream: bookCubit.tags, builder: (context, AsyncSnapshot<List<String>> snapshot) { if (snapshot.hasData && snapshot.data!.isNotEmpty) { return Padding( padding: const EdgeInsets.only(top: 10), child: Container( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: Row( children: [ _getFilterOutTagsSwitch(context, state), const SizedBox(width: 10), Expanded( child: Text( LocaleKeys.filter_out_selected_tags.tr(), style: const TextStyle(fontSize: 16), ), ), ], ), ), ); } else if (snapshot.hasData && snapshot.data!.isEmpty) { return const SizedBox(); } else if (snapshot.hasError) { return Text( snapshot.error.toString(), ); } else { return const Center( child: CircularProgressIndicator(), ); } }, ); } }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/widgets.dart
export 'book_card.dart'; export 'book_tab.dart'; export 'books_list.dart'; export 'sort_bottom_sheet.dart'; export 'add_book_sheet.dart'; export 'add_book_method_button.dart'; export 'year_filter_chip.dart'; export 'tag_filter_chip.dart'; export 'books_grid.dart'; export 'book_grid_card.dart'; export 'grid_card_cover.dart'; export 'grid_card_no_cover.dart'; export 'multi_select_fab.dart';
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/add_book_method_button.dart
import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; class AddBookMethodButton extends StatelessWidget { const AddBookMethodButton({ super.key, required this.text, required this.icon, required this.onPressed, }); final String text; final IconData icon; final Function() onPressed; @override Widget build(BuildContext context) { return Material( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), child: InkWell( customBorder: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), onTap: onPressed, child: Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: Theme.of(context).colorScheme.surfaceVariant, border: Border.all(color: dividerColor), ), child: Column( children: [ Icon( icon, size: 28, color: Theme.of(context).colorScheme.primary, ), const SizedBox(height: 10), Text( text, textAlign: TextAlign.center, style: const TextStyle(fontWeight: FontWeight.bold), ), ], ), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/book_grid_card.dart
import 'package:flutter/material.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/books_screen/widgets/widgets.dart'; class BookGridCard extends StatelessWidget { const BookGridCard({ super.key, required this.book, required this.onPressed, required this.heroTag, required this.addBottomPadding, this.onLongPressed, }); final Book book; final String heroTag; final bool addBottomPadding; final Function() onPressed; final Function()? onLongPressed; @override Widget build(BuildContext context) { final coverFile = book.getCoverFile(); return InkWell( onTap: onPressed, onLongPress: onLongPressed, child: ClipRRect( borderRadius: BorderRadius.circular(3), child: coverFile != null ? GridCardCover( heroTag: heroTag, file: coverFile, ) : GridCardNoCover(book: book)), ); } }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/book_card.dart
import 'package:diacritic/diacritic.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/helpers/helpers.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/rating_type_bloc/rating_type_bloc.dart'; import 'package:openreads/logic/bloc/sort_bloc/sort_bloc.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; class BookCard extends StatefulWidget { const BookCard({ super.key, required this.book, required this.onPressed, required this.heroTag, required this.addBottomPadding, this.onLongPressed, this.cardColor, }); final Book book; final String heroTag; final bool addBottomPadding; final Function() onPressed; final Function()? onLongPressed; final Color? cardColor; @override State<BookCard> createState() => _BookCardState(); } class _BookCardState extends State<BookCard> { Widget _buildSortAttribute() { return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { if (state.sortType == SortType.byPages) { return (widget.book.pages != null) ? _buildPagesAttribute() : const SizedBox(); } else if (state.sortType == SortType.byStartDate) { final latestStartDate = getLatestStartDate(widget.book); return (latestStartDate != null) ? _buildDateAttribute( latestStartDate, LocaleKeys.started_on_date.tr(), false, ) : const SizedBox(); } else if (state.sortType == SortType.byFinishDate) { final latestFinishDate = getLatestFinishDate(widget.book); return (latestFinishDate != null) ? _buildDateAttribute( latestFinishDate, LocaleKeys.finished_on_date.tr(), false, ) : const SizedBox(); } else if (state.sortType == SortType.byDateAdded) { return _buildDateAttribute( widget.book.dateAdded, LocaleKeys.added_on.tr(), true, ); } else if (state.sortType == SortType.byDateModified) { return _buildDateAttribute( widget.book.dateModified, LocaleKeys.modified_on.tr(), true, ); } else if (state.sortType == SortType.byPublicationYear) { return (widget.book.publicationYear != null) ? _buildPublicationYearAttribute() : const SizedBox(); } } return const SizedBox(); }, ); } Text _buildPagesAttribute() => Text('${widget.book.pages} ${LocaleKeys.pages_lowercase.tr()}'); Column _buildPublicationYearAttribute() { return Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( LocaleKeys.enter_publication_year.tr(), style: const TextStyle(fontSize: 12), ), Text( widget.book.publicationYear.toString(), style: const TextStyle( fontSize: 13, fontWeight: FontWeight.bold, ), ), ], ); } Column _buildDateAttribute( DateTime date, String label, bool includeTime, ) { const timeTextStyle = TextStyle( fontSize: 13, fontWeight: FontWeight.bold, ); return Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( label, style: const TextStyle(fontSize: 12), ), includeTime ? Text( '${dateFormat.format(date)} ${date.hour}:${date.minute.toString().padLeft(2, '0')}', style: timeTextStyle, ) : Text( dateFormat.format(date), style: timeTextStyle, ), ], ); } Widget _buildTags() { return BlocBuilder<SortBloc, SortState>( builder: (context, state) { if (state is SetSortState) { if (state.displayTags) { return (widget.book.tags == null) ? const SizedBox() : Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Expanded( child: Wrap( children: _generateTagChips( context: context, ), ), ), ], ); } } return const SizedBox(); }, ); } Widget _buildTagChip({ required String tag, required BuildContext context, }) { return Padding( padding: const EdgeInsets.only(right: 10), child: FilterChip( backgroundColor: Theme.of(context).colorScheme.secondary, padding: const EdgeInsets.all(5), side: BorderSide(color: dividerColor, width: 1), label: Text( tag, style: TextStyle( color: Theme.of(context).colorScheme.onSecondary, fontSize: 12, ), ), onSelected: (_) {}, ), ); } List<Widget> _generateTagChips({required BuildContext context}) { final chips = List<Widget>.empty(growable: true); if (widget.book.tags == null) { return []; } final tags = widget.book.tags!.split('|||||'); tags.sort((a, b) => removeDiacritics(a.toLowerCase()) .compareTo(removeDiacritics(b.toLowerCase()))); for (var tag in tags) { chips.add(_buildTagChip( tag: tag, context: context, )); } return chips; } @override Widget build(BuildContext context) { final coverFile = widget.book.getCoverFile(); return Padding( padding: EdgeInsets.fromLTRB(5, 0, 5, widget.addBottomPadding ? 90 : 0), child: Card( color: widget.cardColor, shadowColor: Colors.transparent, shape: RoundedRectangleBorder( side: BorderSide(color: dividerColor, width: 1), borderRadius: BorderRadius.circular(cornerRadius), ), child: ClipRRect( borderRadius: BorderRadius.circular(cornerRadius), child: InkWell( onTap: widget.onPressed, onLongPress: widget.onLongPressed, child: Padding( padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( width: (coverFile != null) ? 70 : 0, height: 70 * 1.5, child: (coverFile != null) ? ClipRRect( borderRadius: BorderRadius.circular(4), child: Hero( tag: widget.heroTag, child: Image.file( coverFile, width: 70, height: 70 * 1.5, fit: BoxFit.cover, frameBuilder: ( BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded, ) { if (wasSynchronouslyLoaded) { return child; } return AnimatedOpacity( opacity: frame == null ? 0 : 1, duration: const Duration(milliseconds: 250), curve: Curves.easeOut, child: child, ); }, ), ), ) : const SizedBox(), ), SizedBox(width: (coverFile != null) ? 15 : 0), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Text( widget.book.title, softWrap: true, overflow: TextOverflow.clip, style: const TextStyle( fontSize: 15, fontWeight: FontWeight.bold, ), ), ), widget.book.favourite ? Padding( padding: const EdgeInsets.only(left: 10), child: FaIcon( FontAwesomeIcons.solidHeart, size: 15, color: likeColor, ), ) : const SizedBox(), const SizedBox(width: 10), FaIcon( widget.book.bookFormat == BookFormat.audiobook ? FontAwesomeIcons.headphones : widget.book.bookFormat == BookFormat.ebook ? FontAwesomeIcons.tabletScreenButton : FontAwesomeIcons.bookOpen, size: 15, color: Theme.of(context) .colorScheme .onSurface .withOpacity(0.4), ), ], ), Text( widget.book.author, softWrap: true, overflow: TextOverflow.clip, style: TextStyle( fontSize: 14, color: Theme.of(context) .colorScheme .onSurface .withOpacity(0.8), ), ), widget.book.publicationYear != null ? Text( widget.book.publicationYear.toString(), softWrap: true, overflow: TextOverflow.clip, style: TextStyle( fontSize: 12, color: Theme.of(context) .colorScheme .onSurface .withOpacity(0.6), letterSpacing: 0.05, ), ) : const SizedBox(), const SizedBox(height: 5), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: [ widget.book.status == BookStatus.read ? _buildRating(context) : const SizedBox(), _buildSortAttribute(), ], ), _buildTags(), ], ), ), ], ), ), ), ), ), ); } Widget _buildRating(BuildContext context) { return BlocBuilder<RatingTypeBloc, RatingTypeState>( builder: (context, state) { if (state is RatingTypeBar) { return RatingBar.builder( initialRating: (widget.book.rating == null) ? 0 : (widget.book.rating! / 10), allowHalfRating: true, unratedColor: Theme.of(context).scaffoldBackgroundColor, glow: false, glowRadius: 1, itemSize: 20, ignoreGestures: true, itemBuilder: (context, _) => Icon( Icons.star_rounded, color: ratingColor, ), onRatingUpdate: (_) {}, ); } else { return Row( children: [ Text( (widget.book.rating == null) ? '0' : '${(widget.book.rating! / 10)}', ), const SizedBox(width: 5), Icon( Icons.star_rounded, color: ratingColor, size: 20, ), ], ); } }, ); } }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/books_list.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/logic/cubit/current_book_cubit.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/book_screen/book_screen.dart'; import 'package:openreads/ui/books_screen/widgets/widgets.dart'; class BooksList extends StatefulWidget { const BooksList({ super.key, required this.books, required this.listNumber, this.selectedBookIds, this.onBookSelected, this.allBooksCount, }); final List<Book> books; final int listNumber; final Set<int>? selectedBookIds; final Function(int id)? onBookSelected; final int? allBooksCount; @override State<BooksList> createState() => _BooksListState(); } class _BooksListState extends State<BooksList> with AutomaticKeepAliveClientMixin { onPressed(int index, bool multiSelectMode, String heroTag) { if (widget.books[index].id == null) return; if (multiSelectMode && widget.onBookSelected != null) { widget.onBookSelected!(widget.books[index].id!); return; } context.read<CurrentBookCubit>().setBook(widget.books[index]); Navigator.push( context, MaterialPageRoute( builder: (context) => BookScreen( id: widget.books[index].id!, heroTag: heroTag, ), ), ); } onLongPressed(int index) { if (widget.books[index].id == null) return; if (widget.onBookSelected != null) { widget.onBookSelected!(widget.books[index].id!); return; } } @override Widget build(BuildContext context) { super.build(context); var multiSelectMode = widget.selectedBookIds?.isNotEmpty ?? false; return CustomScrollView( slivers: [ SliverToBoxAdapter( child: SizedBox( height: MediaQuery.of(context).padding.top, ), ), SliverToBoxAdapter( child: widget.allBooksCount != null ? Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 10), child: Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( '${widget.books.length} ', style: const TextStyle(fontSize: 13), ), Text( '(${widget.allBooksCount})', style: TextStyle( color: Theme.of(context) .colorScheme .onBackground .withOpacity(0.7), fontSize: 12, ), ), ], ), ) : const SizedBox(), ), SliverList.builder( itemCount: widget.books.length, itemBuilder: (context, index) { final heroTag = 'tag_${widget.listNumber}_${widget.books[index].id}'; Color? color = multiSelectMode && widget.selectedBookIds!.contains(widget.books[index].id) ? Theme.of(context).colorScheme.secondaryContainer : null; return BookCard( book: widget.books[index], heroTag: heroTag, cardColor: color, addBottomPadding: (widget.books.length == index + 1), onPressed: () => onPressed(index, multiSelectMode, heroTag), onLongPressed: () => onLongPressed(index), ); }, ), ], ); } @override bool get wantKeepAlive => true; }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/year_filter_chip.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; class YearFilterChip extends StatelessWidget { const YearFilterChip({ super.key, required this.dbYear, required this.selected, required this.onYearChipPressed, }); final int? dbYear; final bool selected; final Function(bool) onYearChipPressed; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 5), child: FilterChip( backgroundColor: Theme.of(context).colorScheme.surface, side: BorderSide(color: dividerColor, width: 1), label: Text( dbYear != null ? dbYear.toString() : LocaleKeys.select_all.tr(), style: TextStyle( color: selected ? Theme.of(context).colorScheme.onPrimary : Theme.of(context).colorScheme.onSurface, ), ), checkmarkColor: Theme.of(context).colorScheme.onPrimary, selected: selected, selectedColor: Theme.of(context).colorScheme.primary, onSelected: onYearChipPressed, ), ); } }
0
mirrored_repositories/openreads/lib/ui/books_screen
mirrored_repositories/openreads/lib/ui/books_screen/widgets/grid_card_no_cover.dart
import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/model/book.dart'; class GridCardNoCover extends StatelessWidget { const GridCardNoCover({ super.key, required this.book, }); final Book book; @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: Theme.of(context).colorScheme.primaryContainer.withOpacity(0.5), borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor, width: 1), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Expanded( child: Text( book.title, softWrap: true, maxLines: 5, overflow: TextOverflow.ellipsis, textAlign: TextAlign.start, style: const TextStyle( fontSize: 15, fontWeight: FontWeight.bold, ), ), ), ], ), Row( children: [ Expanded( child: Text( book.author, softWrap: true, overflow: TextOverflow.ellipsis, textAlign: TextAlign.start, maxLines: 2, style: const TextStyle(fontSize: 13), ), ), ], ), ], ), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/search_ol_screen/search_ol_screen.dart.dart
import 'package:barcode_scan2/barcode_scan2.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/open_library_search_bloc/open_library_search_bloc.dart'; import 'package:openreads/logic/cubit/default_book_status_cubit.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/model/reading.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/model/ol_search_result.dart'; import 'package:openreads/resources/open_library_service.dart'; import 'package:openreads/ui/add_book_screen/add_book_screen.dart'; import 'package:openreads/ui/add_book_screen/widgets/widgets.dart'; import 'package:openreads/ui/common/keyboard_dismissable.dart'; import 'package:openreads/ui/search_ol_editions_screen/search_ol_editions_screen.dart'; import 'package:openreads/ui/search_ol_screen/widgets/widgets.dart'; class SearchOLScreen extends StatefulWidget { const SearchOLScreen({ super.key, this.scan = false, required this.status, }); final bool scan; final BookStatus status; @override State<SearchOLScreen> createState() => _SearchOLScreenState(); } class _SearchOLScreenState extends State<SearchOLScreen> with AutomaticKeepAliveClientMixin { final _searchController = TextEditingController(); int offset = 0; final _pageSize = 10; String? _searchTerm; int? numberOfResults; ScanResult? scanResult; int searchTimestamp = 0; bool searchActivated = false; final _pagingController = PagingController<int, OLSearchResultDoc>( firstPageKey: 0, ); void _saveNoEdition({ required List<String> editions, required String title, String? subtitle, required String author, int? firstPublishYear, int? pagesMedian, int? cover, List<String>? isbn, String? olid, }) { final defaultBookFormat = context.read<DefaultBooksFormatCubit>().state; final book = Book( title: title, subtitle: subtitle, author: author, status: widget.status, favourite: false, pages: pagesMedian, isbn: (isbn != null && isbn.isNotEmpty) ? isbn[0] : null, olid: (olid != null) ? olid.replaceAll('/works/', '') : null, publicationYear: firstPublishYear, bookFormat: defaultBookFormat, readings: List<Reading>.empty(growable: true), tags: LocaleKeys.owned_book_tag.tr(), dateAdded: DateTime.now(), dateModified: DateTime.now(), ); context.read<EditBookCubit>().setBook(book); Navigator.of(context).push( MaterialPageRoute( builder: (_) => AddBookScreen( fromOpenLibrary: true, coverOpenLibraryID: cover, work: olid, ), ), ); } Future<void> _fetchPage(int pageKey) async { final searchTimestampSaved = DateTime.now().millisecondsSinceEpoch; searchTimestamp = searchTimestampSaved; try { if (_searchTerm == null) return; final newItems = await OpenLibraryService().getResults( query: _searchTerm!, offset: pageKey * _pageSize, limit: _pageSize, searchType: _getOLSearchTypeEnum( context.read<OpenLibrarySearchBloc>().state, ), ); // Used to cancel the request if a new search is started // to avoid showing results from a previous search if (searchTimestamp != searchTimestampSaved) return; setState(() { numberOfResults = newItems.numFound; }); final isLastPage = newItems.docs.length < _pageSize; if (isLastPage) { if (!mounted) return; _pagingController.appendLastPage(newItems.docs); } else { final nextPageKey = pageKey + newItems.docs.length; if (!mounted) return; _pagingController.appendPage(newItems.docs, nextPageKey); } } catch (error) { if (!mounted) return; _pagingController.error = error; } } void _startNewSearch() { if (_searchController.text.isEmpty) return; FocusManager.instance.primaryFocus?.unfocus(); setState(() { searchActivated = true; }); _searchTerm = _searchController.text; _pagingController.refresh(); } void _startScanner() async { context.read<OpenLibrarySearchBloc>().add(const OpenLibrarySearchSetISBN()); var result = await BarcodeScanner.scan( options: ScanOptions( strings: { 'cancel': LocaleKeys.cancel.tr(), 'flash_on': LocaleKeys.flash_on.tr(), 'flash_off': LocaleKeys.flash_off.tr(), }, ), ); if (result.type == ResultType.Barcode) { setState(() { searchActivated = true; _searchController.text = result.rawContent; }); _searchTerm = result.rawContent; _pagingController.refresh(); } } OLSearchType _getOLSearchTypeEnum(OpenLibrarySearchState state) { if (state is OpenLibrarySearchGeneral) { return OLSearchType.general; } else if (state is OpenLibrarySearchAuthor) { return OLSearchType.author; } else if (state is OpenLibrarySearchTitle) { return OLSearchType.title; } else if (state is OpenLibrarySearchISBN) { return OLSearchType.isbn; } else { return OLSearchType.general; } } _changeSearchType(OLSearchType? value) async { context.read<OpenLibrarySearchBloc>().add( value == OLSearchType.general ? const OpenLibrarySearchSetGeneral() : value == OLSearchType.author ? const OpenLibrarySearchSetAuthor() : value == OLSearchType.title ? const OpenLibrarySearchSetTitle() : value == OLSearchType.isbn ? const OpenLibrarySearchSetISBN() : const OpenLibrarySearchSetGeneral(), ); // Delay for the state to be updated await Future.delayed(const Duration(milliseconds: 100)); _startNewSearch(); } // Used when search results are empty _addBookManually() { FocusManager.instance.primaryFocus?.unfocus(); final searchType = _getOLSearchTypeEnum( context.read<OpenLibrarySearchBloc>().state, ); final book = Book( title: searchType == OLSearchType.title ? _searchController.text : '', author: searchType == OLSearchType.author ? _searchController.text : '', status: BookStatus.read, isbn: searchType == OLSearchType.isbn ? _searchController.text : null, readings: List<Reading>.empty(growable: true), tags: 'owned', dateAdded: DateTime.now(), dateModified: DateTime.now(), ); context.read<EditBookCubit>().setBook(book); Navigator.of(context).push( MaterialPageRoute( builder: (_) => const AddBookScreen(fromOpenLibrary: true), ), ); } _onChooseEditionPressed(OLSearchResultDoc item) { FocusManager.instance.primaryFocus?.unfocus(); Navigator.push( context, MaterialPageRoute( builder: (context) => SearchOLEditionsScreen( status: widget.status, editions: item.editionKey!, title: item.title!, subtitle: item.subtitle, author: (item.authorName != null && item.authorName!.isNotEmpty) ? item.authorName![0] : '', pagesMedian: item.medianPages, isbn: item.isbn, olid: item.key, firstPublishYear: item.firstPublishYear, ), ), ); } @override void initState() { super.initState(); if (widget.scan) { _startScanner(); } _pagingController.addPageRequestListener((pageKey) { _fetchPage(pageKey); }); } @override void dispose() { _searchController.dispose(); _pagingController.dispose(); super.dispose(); } @override bool get wantKeepAlive => true; @override Widget build(BuildContext context) { super.build(context); return KeyboardDismissible( child: Scaffold( appBar: AppBar( title: Text( LocaleKeys.add_search.tr(), style: const TextStyle(fontSize: 18), ), ), body: Column( children: [ Padding( padding: const EdgeInsets.fromLTRB(0, 10, 10, 5), child: Row( children: [ Expanded( child: BookTextField( controller: _searchController, keyboardType: TextInputType.name, maxLength: 99, autofocus: true, textInputAction: TextInputAction.search, textCapitalization: TextCapitalization.sentences, onSubmitted: (_) => _startNewSearch(), ), ), const SizedBox(width: 10), SizedBox( height: 48, child: ElevatedButton( onPressed: _startNewSearch, style: ElevatedButton.styleFrom( elevation: 0, backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Theme.of(context).colorScheme.onPrimary, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), ), child: Text( LocaleKeys.search.tr(), style: const TextStyle(fontSize: 12), ), ), ), ], ), ), Align( alignment: Alignment.centerLeft, child: BlocBuilder<OpenLibrarySearchBloc, OpenLibrarySearchState>( builder: (context, state) { return Wrap( alignment: WrapAlignment.start, crossAxisAlignment: WrapCrossAlignment.center, children: [ for (var i = 0; i < 4; i++) ...[ if (i != 0) const SizedBox(width: 5), OLSearchRadio( searchType: OLSearchType.values[i], activeSearchType: _getOLSearchTypeEnum(state), onChanged: _changeSearchType, ), ], ], ); }, ), ), const Padding( padding: EdgeInsets.fromLTRB(10, 0, 10, 10), child: Divider(height: 3), ), (numberOfResults != null && numberOfResults! != 0) ? Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 20), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( '$numberOfResults ${LocaleKeys.results_lowercase.tr()}', style: const TextStyle(fontSize: 12), ), ], ), ], ), ) : const SizedBox(), Expanded( child: (!searchActivated) ? const SizedBox() : Scrollbar( child: PagedListView<int, OLSearchResultDoc>( pagingController: _pagingController, builderDelegate: PagedChildBuilderDelegate<OLSearchResultDoc>( firstPageProgressIndicatorBuilder: (_) => Center( child: LoadingAnimationWidget.staggeredDotsWave( color: Theme.of(context).colorScheme.primary, size: 42, ), ), newPageProgressIndicatorBuilder: (_) => Center( child: Padding( padding: const EdgeInsets.all(20.0), child: LoadingAnimationWidget.staggeredDotsWave( color: Theme.of(context).colorScheme.primary, size: 42, ), ), ), noItemsFoundIndicatorBuilder: (_) => Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( borderRadius: BorderRadius.circular( cornerRadius, ), onTap: _addBookManually, child: Padding( padding: const EdgeInsets.all(10), child: Column( children: [ Text( LocaleKeys.no_search_results.tr(), style: const TextStyle( fontSize: 18, ), ), const SizedBox(height: 10), Text( LocaleKeys.click_to_add_book_manually .tr(), style: const TextStyle( fontSize: 14, ), ), ], ), ), ), ], ), ), itemBuilder: (context, item, index) => Builder(builder: (context) { return BookCardOL( title: item.title ?? '', subtitle: item.subtitle, author: (item.authorName != null && item.authorName!.isNotEmpty) ? item.authorName![0] : '', coverKey: item.coverEditionKey, editions: item.editionKey, pagesMedian: item.medianPages, firstPublishYear: item.firstPublishYear, onAddBookPressed: () => _saveNoEdition( editions: item.editionKey!, title: item.title ?? '', subtitle: item.subtitle, author: (item.authorName != null && item.authorName!.isNotEmpty) ? item.authorName![0] : '', pagesMedian: item.medianPages, isbn: item.isbn, olid: item.key, firstPublishYear: item.firstPublishYear, cover: item.coverI, ), onChooseEditionPressed: () => _onChooseEditionPressed(item), ); }), ), ), ), ), ], ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/search_ol_screen
mirrored_repositories/openreads/lib/ui/search_ol_screen/widgets/ol_search_radio.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/generated/locale_keys.g.dart'; class OLSearchRadio extends StatelessWidget { const OLSearchRadio({ super.key, required this.searchType, required this.activeSearchType, required this.onChanged, }); final OLSearchType searchType; final OLSearchType activeSearchType; final Function(OLSearchType?) onChanged; @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: [ Radio<OLSearchType>( value: searchType, groupValue: activeSearchType, visualDensity: VisualDensity.compact, onChanged: onChanged, ), Text( searchType == OLSearchType.general ? LocaleKeys.general_search.tr() : searchType == OLSearchType.author ? LocaleKeys.author.tr() : searchType == OLSearchType.title ? LocaleKeys.title.tr() : searchType == OLSearchType.isbn ? LocaleKeys.isbn.tr() : '', style: const TextStyle(fontSize: 12), ), ], ); } }
0
mirrored_repositories/openreads/lib/ui/search_ol_screen
mirrored_repositories/openreads/lib/ui/search_ol_screen/widgets/widgets.dart
export 'book_card_ol.dart'; export 'ol_search_radio.dart';
0
mirrored_repositories/openreads/lib/ui/search_ol_screen
mirrored_repositories/openreads/lib/ui/search_ol_screen/widgets/book_card_ol.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; class BookCardOL extends StatelessWidget { BookCardOL({ super.key, required this.title, required this.subtitle, required this.author, required this.coverKey, required this.onChooseEditionPressed, required this.onAddBookPressed, required this.editions, required this.pagesMedian, required this.firstPublishYear, }); final String title; final String? subtitle; final String author; final String? coverKey; final Function() onChooseEditionPressed; final Function() onAddBookPressed; final List<String>? editions; final int? pagesMedian; final int? firstPublishYear; static const String coverBaseUrl = 'https://covers.openlibrary.org/'; late final String coverUrl = '${coverBaseUrl}b/olid/$coverKey-M.jpg'; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 10), child: Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: IntrinsicHeight( child: Row( children: [ SizedBox( width: 120, child: (coverKey != null) ? ClipRRect( borderRadius: BorderRadius.circular(2), child: CachedNetworkImage( imageUrl: coverUrl, placeholder: (context, url) => Center( child: Container( padding: const EdgeInsets.all(5), child: LoadingAnimationWidget.threeArchedCircle( color: Theme.of(context).colorScheme.primary, size: 24, ), ), ), errorWidget: (context, url, error) => const Icon(Icons.error), ), ) : Container( width: 100, height: 120, decoration: BoxDecoration( color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(cornerRadius), ), child: Center( child: Text(LocaleKeys.no_cover.tr()), ), ), ), const SizedBox(width: 20), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title, softWrap: true, overflow: TextOverflow.clip, style: const TextStyle( fontSize: 15, fontWeight: FontWeight.bold, ), ), subtitle != null ? Text( subtitle!, softWrap: true, overflow: TextOverflow.clip, style: const TextStyle(fontSize: 13), ) : const SizedBox(), const SizedBox(height: 5), Text( author, softWrap: true, overflow: TextOverflow.clip, style: const TextStyle(fontSize: 14), ), SizedBox( height: ((editions != null && editions!.isNotEmpty) || pagesMedian != null || firstPublishYear != null) ? 10 : 0, ), Row( children: [ (editions != null && editions!.isNotEmpty) ? Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '${editions!.length}', softWrap: true, overflow: TextOverflow.clip, style: const TextStyle( fontSize: 14, letterSpacing: 1, fontWeight: FontWeight.bold, ), ), Text( LocaleKeys.editions_lowercase.tr(), softWrap: true, overflow: TextOverflow.clip, style: const TextStyle( fontSize: 12, letterSpacing: 1, ), ) ], ) : const SizedBox(), const SizedBox(width: 10), (pagesMedian != null) ? Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '$pagesMedian', softWrap: true, overflow: TextOverflow.clip, style: const TextStyle( fontSize: 14, letterSpacing: 1, fontWeight: FontWeight.bold, ), ), Text( LocaleKeys.pages_lowercase.tr(), softWrap: true, overflow: TextOverflow.clip, style: const TextStyle( fontSize: 12, letterSpacing: 1, ), ) ], ) : const SizedBox(), const SizedBox(width: 10), (pagesMedian != null) ? Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '$firstPublishYear', softWrap: true, overflow: TextOverflow.clip, style: const TextStyle( fontSize: 14, letterSpacing: 1, fontWeight: FontWeight.bold, ), ), Text( LocaleKeys.published_lowercase.tr(), softWrap: true, overflow: TextOverflow.clip, style: const TextStyle( fontSize: 12, letterSpacing: 1, ), ) ], ) : const SizedBox(), ], ), SizedBox( height: ((editions != null && editions!.isNotEmpty) || pagesMedian != null || firstPublishYear != null) ? 10 : 0, ), ], ), Row( children: [ Expanded( child: Wrap( alignment: WrapAlignment.end, children: [ (editions != null && editions!.isNotEmpty) ? ElevatedButton( onPressed: onChooseEditionPressed, style: TextButton.styleFrom( elevation: 0, backgroundColor: Theme.of(context) .colorScheme .secondary, foregroundColor: Theme.of(context) .colorScheme .onSecondary, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular( cornerRadius), side: BorderSide( color: dividerColor, width: 1, ), ), ), child: Text( LocaleKeys.choose_edition.tr(), style: const TextStyle(fontSize: 12), ), ) : const SizedBox(), Padding( padding: EdgeInsets.only( left: (editions != null && editions!.isNotEmpty) ? 10 : 0, ), child: ElevatedButton( onPressed: onAddBookPressed, style: ElevatedButton.styleFrom( elevation: 0, backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Theme.of(context).colorScheme.onPrimary, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), ), child: Text( LocaleKeys.add_book.tr(), style: const TextStyle(fontSize: 12), ), ), ), ], ), ), ], ), ], ), ), ], ), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/similiar_books_screen/similiar_books_screen.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/books_screen/widgets/widgets.dart'; class SimiliarBooksScreen extends StatefulWidget { const SimiliarBooksScreen({ super.key, this.tag, this.author, }); final String? tag; final String? author; @override State<SimiliarBooksScreen> createState() => _SimiliarBooksScreenState(); } class _SimiliarBooksScreenState extends State<SimiliarBooksScreen> { @override void initState() { if (widget.tag != null) { bookCubit.getBooksWithSameTag(widget.tag!); } else if (widget.author != null) { bookCubit.getBooksWithSameAuthor(widget.author!); } super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( children: [ widget.tag != null ? const SizedBox() : widget.author != null ? Text( '${LocaleKeys.author.tr()}: ', style: const TextStyle(fontSize: 18), ) : const SizedBox(), widget.tag != null ? _buildTag(widget.tag!) : widget.author != null ? Text( widget.author!, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold), ) : const SizedBox(), ], ), ), body: StreamBuilder( stream: widget.tag != null ? bookCubit.booksWithSameTag : bookCubit.booksWithSameAuthor, builder: (context, AsyncSnapshot<List<Book>?> snapshot) { if (snapshot.hasData) { return BooksList( books: snapshot.data!, listNumber: 0, ); } else if (snapshot.hasError) { return Text( snapshot.error.toString(), ); } else { return const Center( child: CircularProgressIndicator(), ); } }), ); } Widget _buildTag(String tag) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 5), child: FilterChip( backgroundColor: Theme.of(context).colorScheme.secondary, side: BorderSide( color: dividerColor, width: 1, ), label: Text( tag, overflow: TextOverflow.fade, softWrap: true, maxLines: 5, style: TextStyle( color: Theme.of(context).colorScheme.onSecondary, ), ), clipBehavior: Clip.none, onSelected: (_) {}, ), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/add_book_screen/add_book_screen.dart
import 'dart:io'; import 'package:barcode_scan2/barcode_scan2.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/helpers/helpers.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/model/reading.dart'; import 'package:openreads/resources/open_library_service.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/add_book_screen/widgets/cover_view_edit.dart'; import 'package:openreads/ui/add_book_screen/widgets/widgets.dart'; import 'package:openreads/ui/common/keyboard_dismissable.dart'; class AddBookScreen extends StatefulWidget { const AddBookScreen({ super.key, this.fromOpenLibrary = false, this.fromOpenLibraryEdition = false, this.editingExistingBook = false, this.duplicatingBook = false, this.coverOpenLibraryID, this.work, }); final bool fromOpenLibrary; final bool fromOpenLibraryEdition; final bool editingExistingBook; final bool duplicatingBook; final int? coverOpenLibraryID; final String? work; @override State<AddBookScreen> createState() => _AddBookScreenState(); } class _AddBookScreenState extends State<AddBookScreen> { final _titleCtrl = TextEditingController(); final _subtitleCtrl = TextEditingController(); final _authorCtrl = TextEditingController(); final _pagesCtrl = TextEditingController(); final _pubYearCtrl = TextEditingController(); final _descriptionCtrl = TextEditingController(); final _isbnCtrl = TextEditingController(); final _olidCtrl = TextEditingController(); final _tagsCtrl = TextEditingController(); final _myReviewCtrl = TextEditingController(); final _notesCtrl = TextEditingController(); final _animDuration = const Duration(milliseconds: 250); bool _isCoverDownloading = false; static const String coverBaseUrl = 'https://covers.openlibrary.org/'; late final String coverUrl = '${coverBaseUrl}b/id/${widget.coverOpenLibraryID}-L.jpg'; List<String> bookTypes = [ LocaleKeys.book_format_paperback.tr(), LocaleKeys.book_format_hardcover.tr(), LocaleKeys.book_format_ebook.tr(), LocaleKeys.book_format_audiobook.tr(), ]; void _prefillBookDetails(Book book) { _titleCtrl.text = book.title; _subtitleCtrl.text = book.subtitle ?? ''; _authorCtrl.text = book.author; _pubYearCtrl.text = (book.publicationYear ?? '').toString(); _pagesCtrl.text = (book.pages ?? '').toString(); _descriptionCtrl.text = book.description ?? ''; _isbnCtrl.text = book.isbn ?? ''; _olidCtrl.text = book.olid ?? ''; _myReviewCtrl.text = book.myReview ?? ''; _notesCtrl.text = book.notes ?? ''; if (!widget.fromOpenLibrary && !widget.fromOpenLibraryEdition) { if (!widget.duplicatingBook) { context.read<EditBookCoverCubit>().setCover(book.getCoverBytes()); } } } void _showSnackbar(String message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( message, ), ), ); } bool _validate() { ScaffoldMessenger.of(context).removeCurrentSnackBar(); final book = context.read<EditBookCubit>().state; if (book.title.isEmpty) { _showSnackbar(LocaleKeys.title_cannot_be_empty.tr()); return false; } if (book.author.isEmpty) { _showSnackbar(LocaleKeys.author_cannot_be_empty.tr()); return false; } for (final reading in book.readings) { if (reading.startDate != null && reading.finishDate != null) { if (reading.finishDate!.isBefore(reading.startDate!)) { _showSnackbar(LocaleKeys.finish_date_before_start.tr()); return false; } } } return true; } void _saveBook(Book book) async { FocusManager.instance.primaryFocus?.unfocus(); if (!_validate()) return; if (await _checkIfWaitForCoverDownload(context) == true) return; if (!mounted) return; if (book.hasCover == false) { context.read<EditBookCoverCubit>().deleteCover(book.id); context.read<EditBookCubit>().addNewBook(null); } else { final cover = context.read<EditBookCoverCubit>().state; context.read<EditBookCubit>().addNewBook(cover); } if (!mounted) return; Navigator.pop(context); if (widget.duplicatingBook) { Navigator.pop(context); } if (widget.fromOpenLibrary) { Navigator.pop(context); if (!widget.fromOpenLibraryEdition) return; Navigator.pop(context); } } void _updateBook(Book book) async { FocusManager.instance.primaryFocus?.unfocus(); if (!_validate()) return; if (await _checkIfWaitForCoverDownload(context) == true) return; if (!mounted) return; context.read<EditBookCubit>().setBook(book.copyWith( dateModified: DateTime.now(), )); if (book.hasCover == false) { context.read<EditBookCoverCubit>().deleteCover(book.id); context.read<EditBookCubit>().updateBook(null, context); } else { final cover = context.read<EditBookCoverCubit>().state; context.read<EditBookCubit>().updateBook(cover, context); } if (!mounted) return; Navigator.pop(context); } Future<bool?> _checkIfWaitForCoverDownload(BuildContext context) { if (_isCoverDownloading) { return showDialog<bool>( context: context, builder: (context) { return AlertDialog.adaptive( title: Text( LocaleKeys.coverStillDownloaded.tr(), ), actionsAlignment: MainAxisAlignment.spaceBetween, actions: [ Platform.isIOS ? CupertinoDialogAction( isDefaultAction: true, child: Text(LocaleKeys.waitForDownloadingToFinish.tr()), onPressed: () { Navigator.of(context).pop(true); }, ) : TextButton( child: Text(LocaleKeys.waitForDownloadingToFinish.tr()), onPressed: () { Navigator.of(context).pop(true); }, ), Platform.isIOS ? CupertinoDialogAction( isDestructiveAction: true, child: Text(LocaleKeys.saveWithoutCover.tr()), onPressed: () { Navigator.of(context).pop(false); }, ) : TextButton( child: Text( LocaleKeys.saveWithoutCover.tr(), style: TextStyle( color: Theme.of(context).colorScheme.error), ), onPressed: () { Navigator.of(context).pop(false); }, ), ], ); }, ); } else { return Future.value(false); } } void _changeBookType(String? bookType) { if (bookType == null) return; if (bookType == bookTypes[0]) { context.read<EditBookCubit>().setBookFormat(BookFormat.paperback); } else if (bookType == bookTypes[1]) { context.read<EditBookCubit>().setBookFormat(BookFormat.hardcover); } else if (bookType == bookTypes[2]) { context.read<EditBookCubit>().setBookFormat(BookFormat.ebook); } else if (bookType == bookTypes[3]) { context.read<EditBookCubit>().setBookFormat(BookFormat.audiobook); } else { context.read<EditBookCubit>().setBookFormat(BookFormat.paperback); } FocusManager.instance.primaryFocus?.unfocus(); } void _downloadCover() async { setState(() { _isCoverDownloading = true; }); http.get(Uri.parse(coverUrl)).then((response) async { if (!mounted) return; if (!mounted) return; await generateBlurHash(response.bodyBytes, context); if (!mounted) return; context.read<EditBookCoverCubit>().setCover(response.bodyBytes); context.read<EditBookCubit>().setHasCover(true); setState(() { _isCoverDownloading = false; }); }); } void _downloadWork() async { if (widget.work != null) { final openLibraryWork = await OpenLibraryService().getWork(widget.work!); setState(() { if (openLibraryWork.description != null) { _descriptionCtrl.text = openLibraryWork.description ?? ''; } }); } } Widget _buildCover() { if (_isCoverDownloading) { return Padding( padding: const EdgeInsets.symmetric(vertical: 50), child: LoadingAnimationWidget.threeArchedCircle( color: Theme.of(context).colorScheme.primary, size: 36, ), ); } else { return const CoverViewEdit(); } } void _addNewTag() { final tag = _tagsCtrl.text; if (tag.isEmpty) { FocusManager.instance.primaryFocus?.unfocus(); return; } context.read<EditBookCubit>().addNewTag(_tagsCtrl.text); _tagsCtrl.clear(); } void _unselectTag(String tag) { context.read<EditBookCubit>().removeTag(tag); } _attachListeners() { _titleCtrl.addListener(() { context.read<EditBookCubit>().setTitle(_titleCtrl.text); }); _subtitleCtrl.addListener(() { context.read<EditBookCubit>().setSubtitle(_subtitleCtrl.text); }); _authorCtrl.addListener(() { context.read<EditBookCubit>().setAuthor(_authorCtrl.text); }); _pagesCtrl.addListener(() { context.read<EditBookCubit>().setPages(_pagesCtrl.text); }); _descriptionCtrl.addListener(() { context.read<EditBookCubit>().setDescription(_descriptionCtrl.text); }); _isbnCtrl.addListener(() { context.read<EditBookCubit>().setISBN(_isbnCtrl.text); }); _olidCtrl.addListener(() { context.read<EditBookCubit>().setOLID(_olidCtrl.text); }); _pubYearCtrl.addListener(() { context.read<EditBookCubit>().setPublicationYear(_pubYearCtrl.text); }); _myReviewCtrl.addListener(() { context.read<EditBookCubit>().setMyReview(_myReviewCtrl.text); }); _notesCtrl.addListener(() { context.read<EditBookCubit>().setNotes(_notesCtrl.text); }); } @override void initState() { _prefillBookDetails(context.read<EditBookCubit>().state); _attachListeners(); if (widget.fromOpenLibrary || widget.fromOpenLibraryEdition) { if (widget.coverOpenLibraryID != null) { _downloadCover(); } else { // Remove temp cover file if book/edition has no cover context.read<EditBookCoverCubit>().setCover(null); } if (widget.fromOpenLibrary) { _downloadWork(); } } super.initState(); } @override void dispose() { _titleCtrl.dispose(); _subtitleCtrl.dispose(); _authorCtrl.dispose(); _pagesCtrl.dispose(); _pubYearCtrl.dispose(); _descriptionCtrl.dispose(); _isbnCtrl.dispose(); _olidCtrl.dispose(); _tagsCtrl.dispose(); _myReviewCtrl.dispose(); _notesCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return KeyboardDismissible( child: Scaffold( appBar: AppBar( title: Text( widget.editingExistingBook ? LocaleKeys.edit_book.tr() : LocaleKeys.add_new_book.tr(), style: const TextStyle(fontSize: 18), ), actions: [ BlocBuilder<EditBookCubit, Book>( builder: (context, state) { return TextButton( onPressed: (state.id != null) ? () => _updateBook(state) : () => _saveBook(state), child: Text( LocaleKeys.save.tr(), style: const TextStyle(fontSize: 16), ), ); }, ) ], ), body: SafeArea( child: SingleChildScrollView( child: Column( children: <Widget>[ _buildCover(), const Padding( padding: EdgeInsets.all(10), child: Divider(), ), BookTextField( controller: _titleCtrl, hint: LocaleKeys.enter_title.tr(), icon: Icons.book, keyboardType: TextInputType.name, autofocus: (widget.fromOpenLibrary || widget.editingExistingBook) ? false : true, maxLines: 5, maxLength: 255, textCapitalization: TextCapitalization.sentences, ), const SizedBox(height: 10), BookTextField( controller: _subtitleCtrl, hint: LocaleKeys.enter_subtitle.tr(), icon: Icons.book, keyboardType: TextInputType.name, maxLines: 5, maxLength: 255, textCapitalization: TextCapitalization.sentences, ), const SizedBox(height: 10), StreamBuilder<List<String>>( stream: bookCubit.authors, builder: (context, AsyncSnapshot<List<String>?> snapshot) { return BookTextField( controller: _authorCtrl, hint: LocaleKeys.enter_author.tr(), icon: Icons.person, keyboardType: TextInputType.name, maxLines: 5, maxLength: 255, textCapitalization: TextCapitalization.words, suggestions: snapshot.data, ); }), const Padding( padding: EdgeInsets.all(10), child: Divider(), ), BookStatusRow( animDuration: _animDuration, defaultHeight: Constants.formHeight, ), const SizedBox(height: 10), BookRatingBar(animDuration: _animDuration), BlocBuilder<EditBookCubit, Book>( builder: (context, state) { return Column( children: [ ...state.readings.asMap().entries.map( (entry) { return ReadingRow( index: entry.key, reading: entry.value, ); }, ), ], ); }, ), _buildAddNewReadingButton(context), const Padding( padding: EdgeInsets.all(10), child: Divider(), ), BookTypeDropdown( bookTypes: bookTypes, changeBookType: _changeBookType, ), const SizedBox(height: 10), Row( children: [ Expanded( child: BookTextField( controller: _pagesCtrl, hint: LocaleKeys.enter_pages.tr(), icon: FontAwesomeIcons.solidFileLines, keyboardType: TextInputType.number, inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly ], maxLength: 10, padding: const EdgeInsets.fromLTRB(10, 0, 5, 0), ), ), Expanded( child: BookTextField( controller: _pubYearCtrl, hint: LocaleKeys.enter_publication_year.tr(), icon: FontAwesomeIcons.solidCalendar, keyboardType: TextInputType.number, inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly ], maxLength: 4, padding: const EdgeInsets.fromLTRB(5, 0, 10, 0), ), ), ], ), const SizedBox(height: 10), BookTextField( controller: _descriptionCtrl, hint: LocaleKeys.enter_description.tr(), icon: FontAwesomeIcons.solidKeyboard, keyboardType: TextInputType.multiline, maxLength: 5000, hideCounter: false, maxLines: 15, textCapitalization: TextCapitalization.sentences, ), const SizedBox(height: 10), Row( children: [ Expanded( child: BookTextField( controller: _isbnCtrl, hint: LocaleKeys.isbn.tr(), icon: FontAwesomeIcons.i, keyboardType: TextInputType.number, inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly ], maxLength: 20, ), ), InkWell( customBorder: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), onTap: () async { var result = await BarcodeScanner.scan( options: ScanOptions( strings: { 'cancel': LocaleKeys.cancel.tr(), 'flash_on': LocaleKeys.flash_on.tr(), 'flash_off': LocaleKeys.flash_off.tr(), }, ), ); if (result.type == ResultType.Barcode) { setState(() { _isbnCtrl.text = result.rawContent; }); } }, child: Container( height: 60, width: 60, padding: const EdgeInsets.all(10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: Theme.of(context) .colorScheme .surfaceVariant .withOpacity(0.5), border: Border.all(color: dividerColor), ), child: Icon( FontAwesomeIcons.barcode, size: 28, color: Theme.of(context).colorScheme.primary, ), ), ), const SizedBox(width: 10), ], ), const SizedBox(height: 10), BookTextField( controller: _olidCtrl, hint: LocaleKeys.open_library_ID.tr(), icon: FontAwesomeIcons.o, keyboardType: TextInputType.text, maxLength: 20, textCapitalization: TextCapitalization.characters, ), const SizedBox(height: 10), StreamBuilder<List<String>>( stream: bookCubit.tags, builder: (context, AsyncSnapshot<List<String>?> snapshot) { return TagsField( controller: _tagsCtrl, hint: LocaleKeys.enter_tags.tr(), icon: FontAwesomeIcons.tags, keyboardType: TextInputType.text, maxLength: Constants.maxTagLength, onSubmitted: (_) => _addNewTag(), onEditingComplete: () {}, unselectTag: (tag) => _unselectTag(tag), allTags: snapshot.data, ); }, ), const Padding( padding: EdgeInsets.all(10), child: Divider(), ), BookTextField( controller: _myReviewCtrl, hint: LocaleKeys.my_review.tr(), icon: FontAwesomeIcons.solidKeyboard, keyboardType: TextInputType.multiline, maxLength: 5000, hideCounter: false, maxLines: 15, textCapitalization: TextCapitalization.sentences, ), const SizedBox(height: 10), BookTextField( controller: _notesCtrl, hint: LocaleKeys.notes.tr(), icon: FontAwesomeIcons.noteSticky, keyboardType: TextInputType.multiline, maxLength: 5000, hideCounter: false, maxLines: 15, textCapitalization: TextCapitalization.sentences, ), const SizedBox(height: 30), Row( children: [ const SizedBox(width: 10), Expanded( flex: 10, child: FilledButton.tonal( onPressed: () => Navigator.pop(context), style: ButtonStyle( shape: MaterialStateProperty.all(RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), )), ), child: Center(child: Text(LocaleKeys.cancel.tr())), ), ), const SizedBox(width: 10), Expanded( flex: 19, child: BlocBuilder<EditBookCubit, Book>( builder: (context, state) { return FilledButton( onPressed: (state.id != null) ? () => _updateBook(state) : () => _saveBook(state), style: ButtonStyle( shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), )), ), child: Center(child: Text(LocaleKeys.save.tr())), ); }, ), ), const SizedBox(width: 10), ], ), const SizedBox(height: 50.0), ], ), ), ), ), ); } Padding _buildAddNewReadingButton(BuildContext context) { return Padding( padding: const EdgeInsets.fromLTRB(10, 10, 10, 0), child: FilledButton.tonal( onPressed: () { context.read<EditBookCubit>().addNewReading(Reading()); }, style: ButtonStyle( shape: MaterialStateProperty.all(RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), )), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon(Icons.add), const SizedBox(width: 10), Text(LocaleKeys.add_additional_reading_time.tr()), ], ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/book_type_dropdown.dart
import 'package:dropdown_button2/dropdown_button2.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/model/book.dart'; class BookTypeDropdown extends StatelessWidget { const BookTypeDropdown({ super.key, required this.bookTypes, required this.changeBookType, }); final List<String> bookTypes; final Function(String?) changeBookType; String _getBookTypeDropdownValue(BookFormat bookType) { switch (bookType) { case BookFormat.paperback: return bookTypes[0]; case BookFormat.hardcover: return bookTypes[1]; case BookFormat.ebook: return bookTypes[2]; case BookFormat.audiobook: return bookTypes[3]; default: return bookTypes[0]; } } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Container( decoration: BoxDecoration( border: Border.all( color: dividerColor, ), color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.5), borderRadius: BorderRadius.only( topLeft: Radius.circular(cornerRadius), bottomLeft: Radius.circular(cornerRadius), topRight: Radius.circular(cornerRadius), bottomRight: Radius.circular(cornerRadius), ), ), child: BlocBuilder<EditBookCubit, Book>( builder: (context, state) { return Row( children: [ Container( height: 60, padding: EdgeInsets.fromLTRB( 10, 0, state.bookFormat == BookFormat.audiobook ? 2 : state.bookFormat == BookFormat.ebook ? 4 : 0, 0, ), child: Center( child: FaIcon( state.bookFormat == BookFormat.audiobook ? FontAwesomeIcons.headphones : state.bookFormat == BookFormat.ebook ? FontAwesomeIcons.tabletScreenButton : FontAwesomeIcons.bookOpen, size: 20, color: Theme.of(context).colorScheme.primary, ), ), ), Expanded( child: DropdownButtonHideUnderline( child: DropdownButton2( isExpanded: true, buttonStyleData: const ButtonStyleData( height: 60, decoration: BoxDecoration( color: Colors.transparent, ), ), items: bookTypes .map((item) => DropdownMenuItem<String>( value: item, child: Text(item, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 14)), )) .toList(), value: _getBookTypeDropdownValue(state.bookFormat), onChanged: (value) { changeBookType(value); }, ), ), ), ], ); }, ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/cover_option_button.dart
import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; class CoverOptionButton extends StatelessWidget { const CoverOptionButton({ super.key, required this.icon, required this.text, required this.onPressed, }); final IconData icon; final String text; final Function() onPressed; @override Widget build(BuildContext context) { return Row( children: [ Expanded( child: InkWell( customBorder: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), onTap: onPressed, child: Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: Theme.of(context) .colorScheme .surfaceVariant .withOpacity(0.3), border: Border.all(color: dividerColor), ), child: Row( children: [ Icon( icon, size: 28, color: Theme.of(context).colorScheme.primary, ), const SizedBox(width: 20), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Expanded( child: Text( text, textAlign: TextAlign.start, style: const TextStyle( fontWeight: FontWeight.bold, ), ), ), ], ), ), ], ), ), ), ), ], ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/reading_row.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/model/reading.dart'; import 'package:openreads/model/reading_time.dart'; import 'package:openreads/ui/add_book_screen/widgets/reading_time_field.dart'; import 'package:openreads/ui/add_book_screen/widgets/widgets.dart'; class ReadingRow extends StatefulWidget { const ReadingRow({ super.key, required this.index, required this.reading, }); final int index; final Reading reading; @override State<ReadingRow> createState() => _ReadingRowState(); } class _ReadingRowState extends State<ReadingRow> { void _showStartDatePicker() async { FocusManager.instance.primaryFocus?.unfocus(); final startDate = await showDatePicker( context: context, initialDate: widget.reading.startDate ?? DateTime.now(), firstDate: DateTime(1970), lastDate: DateTime.now(), helpText: LocaleKeys.select_start_date.tr(), ); if (mounted && startDate != null) { context.read<EditBookCubit>().setReadingStartDate( startDate, widget.index, ); } } void _showFinishDatePicker() async { FocusManager.instance.primaryFocus?.unfocus(); final finishDate = await showDatePicker( context: context, initialDate: widget.reading.finishDate ?? DateTime.now(), firstDate: DateTime(1970), lastDate: DateTime.now(), helpText: LocaleKeys.select_finish_date.tr(), ); if (mounted && finishDate != null) { context.read<EditBookCubit>().setReadingFinishDate( finishDate, widget.index, ); } } void _clearStartDate() { context.read<EditBookCubit>().setReadingStartDate(null, widget.index); } void _clearFinishDate() { context.read<EditBookCubit>().setReadingFinishDate(null, widget.index); } void _changeReadingTime( String daysString, String hoursString, String minutesString, ) { int days = int.tryParse(daysString) ?? 0; int hours = int.tryParse(hoursString) ?? 0; int mins = int.tryParse(minutesString) ?? 0; context.read<EditBookCubit>().setCustomReadingTime( ReadingTime.toMilliSeconds(days, hours, mins), widget.index, ); Navigator.pop(context, 'OK'); } void _resetTime() { context.read<EditBookCubit>().setCustomReadingTime(null, widget.index); } @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.fromLTRB(0, 20, 0, 0), child: Row( children: [ Expanded( child: Column( children: [ const SizedBox(height: 0), Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), child: Container( clipBehavior: Clip.hardEdge, decoration: const BoxDecoration(), child: Row( children: [ Expanded( child: SetDateButton( defaultHeight: Constants.formHeight, icon: FontAwesomeIcons.play, date: widget.reading.startDate, text: LocaleKeys.start_date.tr(), onPressed: _showStartDatePicker, onClearPressed: _clearStartDate, showClearButton: (widget.reading.startDate != null) ? true : false, ), ), const SizedBox(width: 10), Expanded( child: SetDateButton( defaultHeight: Constants.formHeight, icon: FontAwesomeIcons.flagCheckered, date: widget.reading.finishDate, text: LocaleKeys.finish_date.tr(), onPressed: _showFinishDatePicker, onClearPressed: _clearFinishDate, showClearButton: (widget.reading.finishDate != null) ? true : false, ), ), ], ), ), ), Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Expanded( child: BookReadingTimeField( defaultHeight: Constants.formHeight, changeReadingTime: _changeReadingTime, resetTime: _resetTime, readingTime: widget.reading.customReadingTime, ), ), ], ), ], ), ), FilledButton.tonal( onPressed: () { context.read<EditBookCubit>().removeReading(widget.index); }, style: ButtonStyle( shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), ), ), child: const Padding( padding: EdgeInsets.symmetric(vertical: 20), child: Icon(Icons.delete), ), ), ], ), ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/book_status_row.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/add_book_screen/widgets/widgets.dart'; class BookStatusRow extends StatelessWidget { const BookStatusRow({ super.key, required this.animDuration, required this.defaultHeight, }); final Duration animDuration; final double defaultHeight; @override Widget build(BuildContext context) { return BlocBuilder<EditBookCubit, Book>( builder: (context, state) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Row( children: [ AnimatedStatusButton( duration: animDuration, height: defaultHeight, icon: Icons.done, text: LocaleKeys.book_status_finished.tr(), isSelected: state.status == BookStatus.read, currentStatus: state.status, onPressed: () { FocusManager.instance.primaryFocus?.unfocus(); context.read<EditBookCubit>().setStatus(BookStatus.read); }, ), const SizedBox(width: 10), AnimatedStatusButton( duration: animDuration, height: defaultHeight, icon: Icons.autorenew, text: LocaleKeys.book_status_in_progress.tr(), isSelected: state.status == BookStatus.inProgress, currentStatus: state.status, onPressed: () { FocusManager.instance.primaryFocus?.unfocus(); context .read<EditBookCubit>() .setStatus(BookStatus.inProgress); }, ), const SizedBox(width: 10), AnimatedStatusButton( duration: animDuration, height: defaultHeight, icon: Icons.timelapse, text: LocaleKeys.book_status_for_later.tr(), isSelected: state.status == BookStatus.forLater, currentStatus: state.status, onPressed: () { FocusManager.instance.primaryFocus?.unfocus(); context.read<EditBookCubit>().setStatus(BookStatus.forLater); }, ), const SizedBox(width: 10), AnimatedStatusButton( duration: animDuration, height: defaultHeight, icon: Icons.not_interested, text: LocaleKeys.book_status_unfinished.tr(), isSelected: state.status == BookStatus.unfinished, currentStatus: state.status, onPressed: () { FocusManager.instance.primaryFocus?.unfocus(); context .read<EditBookCubit>() .setStatus(BookStatus.unfinished); }, ), ], ), ); }, ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/reading_time_field.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/model/reading_time.dart'; class BookReadingTimeField extends StatefulWidget { const BookReadingTimeField({ super.key, required this.defaultHeight, required this.changeReadingTime, required this.resetTime, required this.readingTime, }); final double defaultHeight; final Function(String, String, String) changeReadingTime; final Function resetTime; final ReadingTime? readingTime; @override State<BookReadingTimeField> createState() => _BookReadingTimeField(); } class _BookReadingTimeField extends State<BookReadingTimeField> { final _day = TextEditingController(); final _hours = TextEditingController(); final _minutes = TextEditingController(); @override Widget build(BuildContext context) { String formattedText = widget.readingTime != null ? widget.readingTime.toString() : LocaleKeys.set_custom_reading_time.tr(); _setTextControllers(widget.readingTime); return Column(children: [ const SizedBox(height: 10), Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), child: SizedBox( height: widget.defaultHeight, child: Stack( children: [ InkWell( customBorder: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), onTap: () => buildShowDialog(context), child: Ink( decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: Theme.of(context) .colorScheme .surfaceVariant .withOpacity(0.5), border: Border.all(color: dividerColor), ), child: Padding( padding: const EdgeInsets.symmetric( horizontal: 10, vertical: 10, ), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( FontAwesomeIcons.solidClock, color: Theme.of(context).colorScheme.primary, ), const SizedBox(width: 15), FittedBox( child: Text( formattedText, maxLines: 1, style: const TextStyle(fontSize: 14), ), ), ], ), ), ), ), ), Center( child: Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.center, children: [ (widget.readingTime != null) ? IconButton( icon: const Icon( Icons.close, size: 20, ), onPressed: () => widget.resetTime(), ) : const SizedBox(), ], ), ), ], ), ), ) ]); } @override void dispose() { _day.dispose(); _minutes.dispose(); _hours.dispose(); super.dispose(); } Future<String?> buildShowDialog(BuildContext context) { return showDialog<String>( context: context, builder: (BuildContext context) => AlertDialog( title: Text(LocaleKeys.set_custom_reading_time.tr(), style: const TextStyle(fontSize: 20)), contentPadding: const EdgeInsets.symmetric(vertical: 25), actions: <Widget>[ TextButton( onPressed: () => Navigator.pop(context, 'Cancel'), child: Text(LocaleKeys.cancel.tr()), ), TextButton( onPressed: () => widget.changeReadingTime( _day.value.text, _hours.value.text, _minutes.value.text, ), child: Text(LocaleKeys.ok.tr()), ), ], content: SizedBox( width: MediaQuery.of(context).size.width, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ SizedBox( width: 70, child: TextField( inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly ], keyboardType: TextInputType.number, controller: _day, maxLength: 5, decoration: InputDecoration( labelText: LocaleKeys.daysSetCustomTimeTitle.tr(), border: const OutlineInputBorder(), counterText: "", ), )), SizedBox( width: 70, child: TextField( autofocus: true, keyboardType: TextInputType.number, controller: _hours, inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly ], maxLength: 2, decoration: InputDecoration( labelText: LocaleKeys.hoursSetCustomTimeTitle.tr(), border: const OutlineInputBorder(), counterText: "", ), )), SizedBox( width: 70, child: TextField( keyboardType: TextInputType.number, controller: _minutes, inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly ], maxLength: 2, decoration: InputDecoration( labelText: LocaleKeys.minutesSetCustomTimeTitle.tr(), border: const OutlineInputBorder(), counterText: "", ), ), ) ], ), ))); } void _setTextControllers(ReadingTime? readingTime) { if (readingTime == null) return; _day.text = readingTime.days.toString(); _hours.text = readingTime.hours.toString(); _minutes.text = readingTime.minutes.toString(); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/set_date_button.dart
import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/main.dart'; class SetDateButton extends StatefulWidget { const SetDateButton({ super.key, required this.defaultHeight, required this.icon, required this.text, required this.date, required this.onPressed, required this.onClearPressed, required this.showClearButton, }); final double defaultHeight; final IconData icon; final String text; final DateTime? date; final Function() onPressed; final Function() onClearPressed; final bool showClearButton; @override State<SetDateButton> createState() => _SetDateButtonState(); } class _SetDateButtonState extends State<SetDateButton> { @override Widget build(BuildContext context) { return SizedBox( height: widget.defaultHeight, child: Stack( children: [ InkWell( customBorder: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), onTap: widget.onPressed, child: Ink( decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: Theme.of(context) .colorScheme .surfaceVariant .withOpacity(0.5), border: Border.all(color: dividerColor), ), child: Padding( padding: const EdgeInsets.symmetric( horizontal: 8, vertical: 10, ), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( widget.icon, color: Theme.of(context).colorScheme.primary, ), const SizedBox(width: 10), FittedBox( child: Text( widget.date != null ? dateFormat.format(widget.date!) : widget.text, maxLines: 1, style: const TextStyle(fontSize: 12), ), ), ], ), ), ), ), ), Center( child: Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.center, children: [ (widget.showClearButton) ? IconButton( icon: const Icon( Icons.close, size: 20, ), onPressed: widget.onClearPressed, ) : const SizedBox(), ], ), ), ], ), ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/widgets.dart
export 'animated_status_button.dart'; export 'set_date_button.dart'; export 'book_text_field.dart'; export 'cover_placeholder.dart'; export 'book_status_row.dart'; export 'book_rating_bar.dart'; export 'tags_text_field.dart'; export 'book_type_dropdown.dart'; export 'reading_row.dart'; export 'cover_option_button.dart'; export 'duck_duck_go_alert.dart';
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/tags_text_field.dart
import 'package:diacritic/diacritic.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/model/book.dart'; class TagsField extends StatelessWidget { const TagsField({ super.key, this.controller, this.hint, this.icon, required this.keyboardType, required this.maxLength, this.inputFormatters, this.autofocus = false, this.maxLines = 1, this.hideCounter = true, this.textInputAction, this.textCapitalization = TextCapitalization.none, this.onSubmitted, this.onEditingComplete, this.unselectTag, this.allTags, }); final TextEditingController? controller; final String? hint; final IconData? icon; final TextInputType keyboardType; final List<TextInputFormatter>? inputFormatters; final bool autofocus; final int maxLines; final bool hideCounter; final int maxLength; final TextInputAction? textInputAction; final TextCapitalization textCapitalization; final Function(String)? onSubmitted; final Function()? onEditingComplete; final Function(String)? unselectTag; final List<String>? allTags; Widget _buildTagChip( BuildContext context, { required String tag, required bool selected, }) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 5), child: FilterChip( side: BorderSide(color: dividerColor, width: 1), label: Text( tag, style: TextStyle( color: selected ? Theme.of(context).colorScheme.onSecondary : null, ), overflow: TextOverflow.fade, softWrap: true, maxLines: 5, ), clipBehavior: Clip.none, checkmarkColor: selected ? Theme.of(context).colorScheme.onSecondary : null, selected: selected, selectedColor: Theme.of(context).colorScheme.secondary, onSelected: (_) { if (unselectTag == null) return; unselectTag!(tag); }, ), ); } List<Widget> _generateTagChips( BuildContext context, List<String> tags, ) { final chips = List<Widget>.empty(growable: true); tags.sort((a, b) => removeDiacritics(a.toLowerCase()) .compareTo(removeDiacritics(b.toLowerCase()))); for (var tag in tags) { chips.add(_buildTagChip( context, tag: tag, selected: true, )); } return chips; } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Container( padding: const EdgeInsets.symmetric(horizontal: 8), decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.5), borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: Column( children: [ Scrollbar( child: TypeAheadField( controller: controller, itemBuilder: (context, suggestion) { return Container( color: Theme.of(context).colorScheme.surfaceVariant, child: ListTile( title: Text(suggestion), ), ); }, suggestionsCallback: (pattern) => allTags?.where((String option) { return option .toLowerCase() .startsWith(pattern.toLowerCase()); }).toList() ?? [], onSelected: (suggestion) { controller?.text = suggestion; if (onSubmitted != null) { onSubmitted!(suggestion); } }, hideOnLoading: true, hideOnEmpty: true, decorationBuilder: (context, child) { return Container( padding: const EdgeInsets.symmetric(vertical: 5), decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: child, ); }, builder: (context, control, focusNode) { return TextField( focusNode: focusNode, autofocus: autofocus, keyboardType: keyboardType, inputFormatters: inputFormatters, textCapitalization: textCapitalization, controller: control, minLines: 1, maxLines: maxLines, maxLength: maxLength, textInputAction: textInputAction, style: const TextStyle(fontSize: 14), onSubmitted: onSubmitted, onEditingComplete: onEditingComplete, decoration: InputDecoration( labelText: hint, labelStyle: const TextStyle(fontSize: 14), icon: (icon != null) ? Icon( icon, color: Theme.of(context).colorScheme.primary, ) : null, border: InputBorder.none, counterText: hideCounter ? "" : null, ), ); }, ), ), Row( children: [ Expanded( child: Padding( padding: const EdgeInsets.symmetric( vertical: 5, horizontal: 2.5, ), child: BlocBuilder<EditBookCubit, Book>( builder: (context, state) { return state.tags != null ? Wrap( children: _generateTagChips( context, state.tags!.split('|||||'), ), ) : const SizedBox(); }, ), ), ), ], ) ], ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/book_rating_bar.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/model/book.dart'; class BookRatingBar extends StatelessWidget { const BookRatingBar({ super.key, required this.animDuration, }); final Duration animDuration; @override Widget build(BuildContext context) { return BlocBuilder<EditBookCubit, Book>( builder: (context, state) { return Column( children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: AnimatedContainer( duration: animDuration, height: (state.status == BookStatus.read) ? Constants.formHeight : 0, child: Container( width: double.infinity, clipBehavior: Clip.hardEdge, decoration: BoxDecoration( color: Theme.of(context) .colorScheme .surfaceVariant .withOpacity(0.5), borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: Center( child: RatingBar.builder( initialRating: (state.rating == null) ? 0.0 : state.rating! / 10, allowHalfRating: true, glow: false, glowRadius: 1, itemSize: 42, itemPadding: const EdgeInsets.all(5), wrapAlignment: WrapAlignment.center, itemBuilder: (_, __) => Icon( Icons.star_rounded, color: ratingColor, ), onRatingUpdate: (rating) { FocusManager.instance.primaryFocus?.unfocus(); context.read<EditBookCubit>().setRating(rating); }, ), ), ), ), ), ], ); }, ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/duck_duck_go_alert.dart
import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:shared_preferences/shared_preferences.dart'; class DuckDuckGoAlert extends StatelessWidget { const DuckDuckGoAlert({ super.key, required this.openDuckDuckGoSearchScreen, }); final Function(BuildContext) openDuckDuckGoSearchScreen; _yesButtonAction(BuildContext context) { Navigator.of(context).pop(); openDuckDuckGoSearchScreen(context); } _yesAndDontShowButtonAction(BuildContext context) async { Navigator.of(context).pop(); final SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setBool(SharedPreferencesKeys.duckDuckGoWarning, false); openDuckDuckGoSearchScreen(context); } _noButtonAction(BuildContext context) { Navigator.of(context).pop(); } @override Widget build(BuildContext context) { return AlertDialog.adaptive( title: Text( LocaleKeys.duckDuckGoWarning.tr(), style: Platform.isAndroid ? const TextStyle(fontSize: 16) : null, ), actionsAlignment: MainAxisAlignment.spaceBetween, actions: [ Platform.isAndroid ? _buildAndroidNoButton(context) : _buildIOSNoButton(context), Platform.isAndroid ? _buildAndroidYesButton(context) : _buildIOSYesButton(context), Platform.isAndroid ? _buildAndroidYesAndDontShowButton(context) : _buildIOSYesAndDontShowButton(context), ], ); } Widget _buildAndroidYesButton(BuildContext context) { return FilledButton.tonal( onPressed: () => _yesButtonAction(context), style: FilledButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Text( LocaleKeys.warningYes.tr(), textAlign: TextAlign.end, ), ), ); } Widget _buildAndroidYesAndDontShowButton(BuildContext context) { return FilledButton( onPressed: () => _yesAndDontShowButtonAction(context), style: FilledButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Text( LocaleKeys.warningYesAndDontShow.tr(), textAlign: TextAlign.end, ), ), ); } Widget _buildAndroidNoButton(BuildContext context) { return FilledButton( onPressed: () => _noButtonAction(context), style: TextButton.styleFrom( backgroundColor: Colors.transparent, foregroundColor: Theme.of(context).colorScheme.onSurface, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Text(LocaleKeys.warningNo.tr()), ), ); } Widget _buildIOSYesButton(BuildContext context) { return CupertinoDialogAction( isDefaultAction: false, onPressed: () => _yesButtonAction(context), child: Text(LocaleKeys.warningYes.tr()), ); } Widget _buildIOSYesAndDontShowButton(BuildContext context) { return CupertinoDialogAction( isDefaultAction: true, onPressed: () => _yesAndDontShowButtonAction(context), child: Text(LocaleKeys.warningYesAndDontShow.tr()), ); } Widget _buildIOSNoButton(BuildContext context) { return CupertinoDialogAction( isDefaultAction: false, onPressed: () => _noButtonAction(context), child: Text(LocaleKeys.warningNo.tr()), ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/cover_view_edit.dart
// ignore_for_file: use_build_context_synchronously import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:image/image.dart' as img; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:image_picker/image_picker.dart'; import 'package:blurhash_dart/blurhash_dart.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:openreads/core/helpers/helpers.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/resources/open_library_service.dart'; import 'package:openreads/core/constants/constants.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/main.dart'; import 'package:openreads/ui/add_book_screen/widgets/widgets.dart'; import 'package:openreads/ui/search_covers_screen/search_covers_screen.dart'; import 'package:shared_preferences/shared_preferences.dart'; class CoverViewEdit extends StatefulWidget { const CoverViewEdit({super.key}); static showInfoSnackbar(String message) { final snackBar = SnackBar(content: Text(message)); snackbarKey.currentState?.showSnackBar(snackBar); } @override State<CoverViewEdit> createState() => _CoverViewEditState(); } class _CoverViewEditState extends State<CoverViewEdit> { bool _isCoverLoading = false; void _setCoverLoading(bool value) { setState(() { _isCoverLoading = value; }); } void _loadCoverFromStorage(BuildContext context) async { _setCoverLoading(true); Navigator.of(context).pop(); final photoXFile = await ImagePicker().pickImage( source: ImageSource.gallery, ); if (photoXFile == null) { _setCoverLoading(false); return; } final croppedPhoto = await cropImage( context, await photoXFile.readAsBytes(), ); if (croppedPhoto == null) { _setCoverLoading(false); return; } final croppedPhotoBytes = await croppedPhoto.readAsBytes(); if (!context.mounted) { _setCoverLoading(false); return; } await generateBlurHash(croppedPhotoBytes, context); if (!context.mounted) { _setCoverLoading(false); return; } context.read<EditBookCoverCubit>().setCover(croppedPhotoBytes); context.read<EditBookCubit>().setHasCover(true); _setCoverLoading(false); } void _editCurrentCover({ required BuildContext context, bool pop = true, }) async { _setCoverLoading(true); if (pop) { Navigator.of(context).pop(); } final cover = context.read<EditBookCoverCubit>().state; if (cover == null) { _setCoverLoading(false); return; } final croppedPhoto = await cropImage(context, cover); if (croppedPhoto == null) { _setCoverLoading(false); return; } final croppedPhotoBytes = await croppedPhoto.readAsBytes(); if (!context.mounted) { _setCoverLoading(false); return; } await generateBlurHash(croppedPhotoBytes, context); if (!context.mounted) { _setCoverLoading(false); return; } context.read<EditBookCoverCubit>().setCover(croppedPhotoBytes); context.read<EditBookCubit>().setHasCover(true); _setCoverLoading(false); } _deleteCover(BuildContext context) async { _setCoverLoading(true); context.read<EditBookCubit>().setHasCover(false); context.read<EditBookCubit>().setBlurHash(null); context.read<EditBookCoverCubit>().setCover(null); _setCoverLoading(false); } _loadCoverFromOpenLibrary(BuildContext context) async { Navigator.of(context).pop(); final isbn = context.read<EditBookCubit>().state.isbn; if (isbn == null) { CoverViewEdit.showInfoSnackbar(LocaleKeys.isbn_cannot_be_empty.tr()); return; } _setCoverLoading(true); final cover = await OpenLibraryService().getCover(isbn); if (cover == null) { CoverViewEdit.showInfoSnackbar(LocaleKeys.cover_not_found_in_ol.tr()); _setCoverLoading(false); return; } if (!context.mounted) { _setCoverLoading(false); return; } await generateBlurHash(cover, context); if (!context.mounted) { _setCoverLoading(false); return; } context.read<EditBookCoverCubit>().setCover(cover); context.read<EditBookCubit>().setHasCover(true); _setCoverLoading(false); } _showDuckDuckGoWarning(BuildContext context) { showDialog( context: context, builder: (BuildContext _) { return DuckDuckGoAlert( openDuckDuckGoSearchScreen: _openDuckDuckGoSearchScreen, ); }); } _searchForCoverOnline(BuildContext context) async { Navigator.of(context).pop(); final SharedPreferences prefs = await SharedPreferences.getInstance(); final bool? showDuckDuckGoWarning = prefs.getBool(SharedPreferencesKeys.duckDuckGoWarning); if (showDuckDuckGoWarning == false) { _openDuckDuckGoSearchScreen(context); } else { _showDuckDuckGoWarning(context); } } _openDuckDuckGoSearchScreen(BuildContext context) { Navigator.push( context, MaterialPageRoute( builder: (context) => SearchCoversScreen( book: context.read<EditBookCubit>().state, ), ), ); } showCoverLoadBottomSheet(BuildContext context) { FocusManager.instance.primaryFocus?.unfocus(); showModalBottomSheet( context: context, isScrollControlled: true, elevation: 0, backgroundColor: Theme.of(context).colorScheme.surface, builder: (modalContext) { return Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 10), Container( height: 3, width: MediaQuery.of(context).size.width / 4, decoration: BoxDecoration( color: Colors.grey.shade300, borderRadius: BorderRadius.circular(10), ), ), Container( padding: const EdgeInsets.fromLTRB(10, 30, 10, 60), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ CoverOptionButton( text: LocaleKeys.load_cover_from_phone.tr(), icon: FontAwesomeIcons.mobile, onPressed: () => _loadCoverFromStorage(context), ), const SizedBox(height: 15), CoverOptionButton( text: LocaleKeys.searchOnlineForCover.tr(), icon: FontAwesomeIcons.magnifyingGlass, onPressed: () => _searchForCoverOnline(context), ), const SizedBox(height: 15), CoverOptionButton( text: LocaleKeys.get_cover_from_open_library.tr(), icon: FontAwesomeIcons.globe, onPressed: () => _loadCoverFromOpenLibrary(context), ), BlocBuilder<EditBookCubit, Book>( builder: (blocContext, state) { if (state.hasCover) { return Column( children: [ const SizedBox(height: 15), CoverOptionButton( text: LocaleKeys.edit_current_cover.tr(), icon: FontAwesomeIcons.image, onPressed: () => _editCurrentCover( context: context, ), ), ], ); } else { return const SizedBox(); } }, ), ], ), ), ], ); }, ); } @override Widget build(BuildContext context) { return Column( children: [ _isCoverLoading ? const LinearProgressIndicator(minHeight: 3) : const SizedBox(height: 3), const SizedBox(height: 5), Builder(builder: (context) { return BlocBuilder<EditBookCoverCubit, Uint8List?>( buildWhen: (p, c) { return p != c; }, builder: (context, state) { if (state != null) { return _buildCoverViewEdit( context, () => showCoverLoadBottomSheet(context), ); } else { return CoverPlaceholder( defaultHeight: Constants.formHeight, onPressed: () => showCoverLoadBottomSheet(context), ); } }, ); }), ], ); } Widget _buildCoverViewEdit( BuildContext context, Function() onTap, ) { return LayoutBuilder(builder: (context, boxConstraints) { return InkWell( onTap: onTap, child: Stack( children: [ SizedBox( width: boxConstraints.maxWidth, height: boxConstraints.maxWidth / 1.2, child: Stack( children: [ BlocBuilder<EditBookCoverCubit, Uint8List?>( builder: (context, state) { return _buildBlurHash( context, context.read<EditBookCubit>().state.blurHash, boxConstraints, ); }, ), ], ), ), Padding( padding: const EdgeInsets.all(20), child: Center( child: Container( height: (boxConstraints.maxWidth / 1.2) - 40, width: boxConstraints.maxWidth - 40, decoration: const BoxDecoration( color: Colors.transparent, ), child: Stack( children: [ BlocBuilder<EditBookCoverCubit, Uint8List?>( builder: (context, state) { return Center( child: ClipRRect( borderRadius: BorderRadius.circular(cornerRadius), child: (state != null) ? Image.memory( state, fit: BoxFit.contain, width: double.infinity, height: double.infinity, ) : const SizedBox(), ), ); }, ), Positioned( right: 1, bottom: 1, child: IconButton( style: IconButton.styleFrom( foregroundColor: Colors.white, backgroundColor: Colors.red.shade400, ), icon: const Icon(FontAwesomeIcons.trash), onPressed: () => _deleteCover(context), iconSize: 16, ), ) ], ), ), ), ), ], ), ); }); } Widget _buildBlurHash( BuildContext context, String? blurHashString, BoxConstraints boxConstraints, ) { if (blurHashString == null) { return const SizedBox(); } final image = BlurHash.decode(blurHashString).toImage(35, 20); return Image( image: MemoryImage(Uint8List.fromList(img.encodeJpg(image))), fit: BoxFit.cover, width: boxConstraints.maxWidth, height: boxConstraints.maxWidth / 1.2, ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/book_text_field.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; import 'package:openreads/core/themes/app_theme.dart'; class BookTextField extends StatefulWidget { const BookTextField({ super.key, required this.controller, this.hint, this.icon, required this.keyboardType, required this.maxLength, this.inputFormatters, this.autofocus = false, this.maxLines = 1, this.hideCounter = true, this.textInputAction, this.textCapitalization = TextCapitalization.none, this.padding = const EdgeInsets.symmetric(horizontal: 10), this.onSubmitted, this.suggestions, }); final TextEditingController controller; final String? hint; final IconData? icon; final TextInputType? keyboardType; final List<TextInputFormatter>? inputFormatters; final bool autofocus; final int maxLines; final bool hideCounter; final int maxLength; final TextInputAction? textInputAction; final TextCapitalization textCapitalization; final Function(String)? onSubmitted; final EdgeInsets padding; final List<String>? suggestions; @override State<BookTextField> createState() => _BookTextFieldState(); } class _BookTextFieldState extends State<BookTextField> { bool showClearButton = false; @override void initState() { super.initState(); if (widget.controller.text.isNotEmpty) { showClearButton = true; } widget.controller.addListener(() { setState(() { if (widget.controller.text.isNotEmpty) { showClearButton = true; } else { showClearButton = false; } }); }); } @override Widget build(BuildContext context) { return Padding( padding: widget.padding, child: Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0), decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.5), borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: Scrollbar( child: widget.suggestions != null && widget.suggestions!.isNotEmpty ? _buildTypeAheadField() : _buildTextField(context), ), ), ); } TypeAheadField<String> _buildTypeAheadField() { return TypeAheadField( controller: widget.controller, hideOnLoading: true, hideOnEmpty: true, itemBuilder: (context, suggestion) { return Container( color: Theme.of(context).colorScheme.surfaceVariant, child: ListTile( title: Text(suggestion), ), ); }, decorationBuilder: (context, child) { return Container( padding: const EdgeInsets.symmetric(vertical: 5), decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: child, ); }, suggestionsCallback: (pattern) { return widget.suggestions!.where((String option) { return option.toLowerCase().startsWith(pattern.toLowerCase()); }).toList(); }, onSelected: (suggestion) { widget.controller.text = suggestion; }, builder: (_, __, focusNode) { return _buildTextField(context, focusNode: focusNode); }); } TextField _buildTextField( BuildContext context, { FocusNode? focusNode, }) { return TextField( autofocus: widget.autofocus, keyboardType: widget.keyboardType, inputFormatters: widget.inputFormatters, textCapitalization: widget.textCapitalization, controller: widget.controller, focusNode: focusNode, minLines: 1, maxLines: widget.maxLines, maxLength: widget.maxLength, textInputAction: widget.textInputAction, style: const TextStyle(fontSize: 14), onSubmitted: widget.onSubmitted ?? (_) {}, decoration: InputDecoration( labelText: widget.hint, labelStyle: const TextStyle(fontSize: 14), icon: (widget.icon != null) ? Icon( widget.icon, color: Theme.of(context).colorScheme.primary, ) : null, border: InputBorder.none, counterText: widget.hideCounter ? "" : null, suffixIcon: showClearButton ? IconButton( onPressed: () { widget.controller.clear(); setState(() { showClearButton = false; }); focusNode?.requestFocus(); }, icon: const Icon(Icons.clear), ) : null, ), ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/animated_status_button.dart
import 'package:flutter/material.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/themes/app_theme.dart'; class AnimatedStatusButton extends StatelessWidget { const AnimatedStatusButton({ super.key, required Duration duration, required this.height, required this.onPressed, required this.icon, required this.text, required this.isSelected, required this.currentStatus, }) : _duration = duration; final Duration _duration; final double height; final Function() onPressed; final IconData icon; final String text; final bool isSelected; final BookStatus? currentStatus; @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width - 50; final selectedWidth = (2 / 5) * width; final unselectedWidth = (1 / 5) * width; final defaultWidth = (1 / 4) * width; return AnimatedContainer( duration: _duration, height: height, width: currentStatus == null ? defaultWidth : isSelected ? selectedWidth : unselectedWidth, alignment: Alignment.center, child: InkWell( customBorder: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), onTap: onPressed, child: Ink( decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: isSelected ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.5), border: Border.all(color: dividerColor), ), child: Padding( padding: const EdgeInsets.all(2), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( icon, color: isSelected ? Theme.of(context).colorScheme.onPrimary : null, ), FittedBox( child: Text( text, maxLines: 1, style: TextStyle( fontSize: 13, color: isSelected ? Theme.of(context).colorScheme.onPrimary : null, ), ), ), ], ), ), ), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/add_book_screen
mirrored_repositories/openreads/lib/ui/add_book_screen/widgets/cover_placeholder.dart
import 'package:dotted_border/dotted_border.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; class CoverPlaceholder extends StatelessWidget { const CoverPlaceholder({ super.key, required this.defaultHeight, required this.onPressed, }); final double defaultHeight; final Function() onPressed; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: DottedBorder( borderType: BorderType.RRect, radius: Radius.circular(cornerRadius), dashPattern: const [10, 8], color: Theme.of(context).colorScheme.onSurface.withOpacity(0.3), strokeWidth: 2, child: Padding( padding: const EdgeInsets.all(10), child: InkWell( customBorder: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), onTap: onPressed, child: Ink( height: defaultHeight + 40, decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), color: Theme.of(context).colorScheme.primary.withOpacity(0.1), border: Border.all(color: dividerColor), ), child: Padding( padding: const EdgeInsets.symmetric( horizontal: 0, vertical: 10, ), child: Center( child: Row( children: [ const SizedBox(width: 8), Icon( Icons.image, size: 24, color: Theme.of(context).colorScheme.primary, ), const SizedBox(width: 15), Text(LocaleKeys.click_to_add_cover.tr()), ], ), ), ), ), ), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/welcome_screen/welcome_screen.dart
import 'dart:io'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:openreads/core/helpers/backup/backup_general.dart'; import 'package:openreads/core/helpers/backup/backup_import.dart'; import 'package:openreads/core/helpers/backup/csv_import_bookwyrm.dart'; import 'package:openreads/core/helpers/backup/csv_import_goodreads.dart'; import 'package:openreads/core/helpers/backup/csv_import_openreads.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/logic/bloc/migration_v1_to_v2_bloc/migration_v1_to_v2_bloc.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/theme_bloc/theme_bloc.dart'; import 'package:openreads/logic/bloc/welcome_bloc/welcome_bloc.dart'; import 'package:openreads/ui/books_screen/books_screen.dart'; import 'package:openreads/ui/welcome_screen/widgets/widgets.dart'; import 'package:smooth_page_indicator/smooth_page_indicator.dart'; class WelcomeScreen extends StatefulWidget { const WelcomeScreen({ super.key, required this.themeData, }); final ThemeData themeData; @override State<WelcomeScreen> createState() => _WelcomeScreenState(); } class _WelcomeScreenState extends State<WelcomeScreen> { final _controller = PageController(); bool preparationTriggered = false; bool _checkIfMigrationIsOngoing() { if (context.read<MigrationV1ToV2Bloc>().state is MigrationOnging) { return true; } else { return false; } } _setWelcomeState() { BlocProvider.of<WelcomeBloc>(context).add( const ChangeWelcomeEvent(false), ); } _moveToBooksScreen() { Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => const BooksScreen()), (Route<dynamic> route) => false, ); } _restoreBackup() async { if (_checkIfMigrationIsOngoing()) return; _setWelcomeState(); if (Platform.isAndroid) { final androidInfo = await DeviceInfoPlugin().androidInfo; if (androidInfo.version.sdkInt < 30) { await BackupGeneral.requestStoragePermission(context); await BackupImport.restoreLocalBackupLegacyStorage(context); } else { await BackupImport.restoreLocalBackup(context); } } else if (Platform.isIOS) { await BackupImport.restoreLocalBackup(context); } } _importOpenreadsCsv() async { if (_checkIfMigrationIsOngoing()) return; _setWelcomeState(); if (Platform.isAndroid) { final androidInfo = await DeviceInfoPlugin().androidInfo; if (androidInfo.version.sdkInt < 30) { await BackupGeneral.requestStoragePermission(context); await CSVImportOpenreads.importCSVLegacyStorage(context); } else { await CSVImportOpenreads.importCSV(context); } } else if (Platform.isIOS) { await CSVImportOpenreads.importCSV(context); } } _importGoodreadsCsv() async { if (_checkIfMigrationIsOngoing()) return; _setWelcomeState(); if (Platform.isAndroid) { final androidInfo = await DeviceInfoPlugin().androidInfo; if (androidInfo.version.sdkInt < 30) { await BackupGeneral.requestStoragePermission(context); await CSVImportGoodreads.importCSVLegacyStorage(context); } else { await CSVImportGoodreads.importCSV(context); } } else if (Platform.isIOS) { await CSVImportGoodreads.importCSV(context); } } _importBookwyrmCsv() async { if (_checkIfMigrationIsOngoing()) return; _setWelcomeState(); if (Platform.isAndroid) { final androidInfo = await DeviceInfoPlugin().androidInfo; if (androidInfo.version.sdkInt < 30) { await BackupGeneral.requestStoragePermission(context); await CSVImportBookwyrm.importCSVLegacyStorage(context); } else { await CSVImportBookwyrm.importCSV(context); } } else if (Platform.isIOS) { await CSVImportBookwyrm.importCSV(context); } } _skipImportingBooks() { if (_checkIfMigrationIsOngoing()) return; _setWelcomeState(); _moveToBooksScreen(); } @override Widget build(BuildContext context) { return BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { if (state is SetThemeState) { AppTheme.init(state, context); return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, ), body: SafeArea( child: Column( children: [ Row( children: [ Expanded( child: Padding( padding: const EdgeInsets.fromLTRB(20, 0, 20, 20), child: Text( LocaleKeys.welcome_1.tr(), style: const TextStyle( fontSize: 36, fontWeight: FontWeight.bold, ), ), ), ), ], ), Expanded( child: PageView( controller: _controller, children: [ WelcomePageText( descriptions: [ LocaleKeys.welcome_1_description_1.tr(), LocaleKeys.welcome_1_description_2.tr(), ], image: Image.asset( 'assets/icons/icon_cropped.png', width: 100, height: 100, ), ), WelcomePageText( descriptions: [ LocaleKeys.welcome_2_description_1.tr(), LocaleKeys.welcome_2_description_2.tr(), ], image: const Icon( FontAwesomeIcons.chartSimple, size: 60, ), ), WelcomePageText( descriptions: [ LocaleKeys.welcome_3_description_1.tr(), LocaleKeys.welcome_3_description_2.tr(), LocaleKeys.welcome_3_description_3.tr(), ], image: const Icon( FontAwesomeIcons.code, size: 60, ), ), WelcomePageChoices( restoreBackup: _restoreBackup, importOpenreadsCsv: _importOpenreadsCsv, importGoodreadsCsv: _importGoodreadsCsv, importBookwyrmCsv: _importBookwyrmCsv, skipImportingBooks: _skipImportingBooks, ), ], ), ), SmoothPageIndicator( controller: _controller, count: 4, effect: ExpandingDotsEffect( activeDotColor: Theme.of(context).colorScheme.primary, dotColor: Theme.of(context).colorScheme.surfaceVariant, dotHeight: 12, dotWidth: 12, ), onDotClicked: (index) { _controller.animateToPage( index, duration: const Duration(milliseconds: 500), curve: Curves.ease, ); }, ), const SizedBox(height: 20), BlocBuilder<MigrationV1ToV2Bloc, MigrationV1ToV2State>( builder: (context, migrationState) { if (migrationState is MigrationNotStarted) { BlocProvider.of<MigrationV1ToV2Bloc>(context).add( StartMigration(context: context), ); } else if (migrationState is MigrationOnging) { return MigrationNotification( done: migrationState.done, total: migrationState.total, ); } else if (migrationState is MigrationFailed) { return MigrationNotification( error: migrationState.error, ); } else if (migrationState is MigrationSucceded) { return const MigrationNotification( success: true, ); } return const SizedBox(); }, ), SizedBox(height: MediaQuery.of(context).padding.bottom), ], ), ), ); } else { return const SizedBox(); } }, ); } }
0
mirrored_repositories/openreads/lib/ui/welcome_screen
mirrored_repositories/openreads/lib/ui/welcome_screen/widgets/welcome_page_text.dart
import 'package:flutter/material.dart'; class WelcomePageText extends StatelessWidget { const WelcomePageText({ super.key, required this.descriptions, required this.image, }); final List<String> descriptions; final Widget image; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ for (var description in descriptions) Padding( padding: const EdgeInsets.only(bottom: 40), child: Text( description, style: const TextStyle(fontSize: 20), ), ), ], ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [image], ), const SizedBox(height: 50), ], ), ); } }
0
mirrored_repositories/openreads/lib/ui/welcome_screen
mirrored_repositories/openreads/lib/ui/welcome_screen/widgets/welcome_choice_button.dart
import 'package:flutter/material.dart'; class WelcomeChoiceButton extends StatelessWidget { const WelcomeChoiceButton({ super.key, required this.description, required this.onPressed, this.isSkipImporting = false, }); final String description; final Function() onPressed; final bool isSkipImporting; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(bottom: 10), child: Row( children: [ Expanded( child: FilledButton.tonal( style: ButtonStyle( backgroundColor: isSkipImporting ? MaterialStateProperty.all( Theme.of(context).colorScheme.primary, ) : MaterialStateProperty.all( Theme.of(context) .colorScheme .surfaceVariant .withOpacity(0.3), ), foregroundColor: MaterialStateProperty.all( isSkipImporting ? Theme.of(context).colorScheme.onSecondary : Theme.of(context).colorScheme.onSurfaceVariant, ), shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), side: isSkipImporting ? BorderSide( color: Theme.of(context) .colorScheme .onSurfaceVariant .withOpacity(0.5), ) : BorderSide.none, ), ), ), onPressed: onPressed, child: Row( children: [ Expanded( child: Padding( padding: const EdgeInsets.fromLTRB( 0, 10, 0, 10, ), child: Text( description, style: TextStyle( fontSize: 16, fontWeight: isSkipImporting ? FontWeight.bold : FontWeight.normal, ), textAlign: isSkipImporting ? TextAlign.center : TextAlign.start, ), ), ), ], ), ), ), ], ), ); } }
0
mirrored_repositories/openreads/lib/ui/welcome_screen
mirrored_repositories/openreads/lib/ui/welcome_screen/widgets/widgets.dart
export 'migration_notification.dart'; export 'welcome_page_text.dart'; export 'welcome_page_choices.dart'; export 'welcome_choice_button.dart';
0
mirrored_repositories/openreads/lib/ui/welcome_screen
mirrored_repositories/openreads/lib/ui/welcome_screen/widgets/welcome_page_choices.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/ui/welcome_screen/widgets/widgets.dart'; class WelcomePageChoices extends StatelessWidget { const WelcomePageChoices({ super.key, required this.restoreBackup, required this.importOpenreadsCsv, required this.importGoodreadsCsv, required this.importBookwyrmCsv, required this.skipImportingBooks, }); final Function() restoreBackup; final Function() importOpenreadsCsv; final Function() importGoodreadsCsv; final Function() importBookwyrmCsv; final Function() skipImportingBooks; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Expanded( child: Text( LocaleKeys.help_to_get_started.tr(), style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), ), ], ), Expanded( child: SingleChildScrollView( child: Column( children: [ const SizedBox(height: 20), WelcomeChoiceButton( description: LocaleKeys.restore_backup.tr(), onPressed: restoreBackup, ), WelcomeChoiceButton( description: LocaleKeys.import_csv.tr(), onPressed: importOpenreadsCsv, ), WelcomeChoiceButton( description: LocaleKeys.import_goodreads_csv.tr(), onPressed: importGoodreadsCsv, ), WelcomeChoiceButton( description: LocaleKeys.import_bookwyrm_csv.tr(), onPressed: importBookwyrmCsv, ), ], ), ), ), WelcomeChoiceButton( description: LocaleKeys.start_adding_books.tr(), onPressed: skipImportingBooks, isSkipImporting: true, ), ], ), ), ], ), ); } }
0
mirrored_repositories/openreads/lib/ui/welcome_screen
mirrored_repositories/openreads/lib/ui/welcome_screen/widgets/migration_notification.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; class MigrationNotification extends StatelessWidget { const MigrationNotification({ super.key, this.total, this.done, this.error, this.success, }); final int? total; final int? done; final String? error; final bool? success; @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.all(15), decoration: BoxDecoration( color: primaryRed, borderRadius: const BorderRadius.only( topLeft: Radius.circular(15), topRight: Radius.circular(15), )), child: Column( children: [ Text( success == true ? LocaleKeys.migration_v1_to_v2_finished.tr() : LocaleKeys.migration_v1_to_v2_1.tr(), style: Theme.of(context).textTheme.headlineMedium, ), SizedBox(height: success == true ? 0 : 10), success == true ? const SizedBox() : Text( LocaleKeys.migration_v1_to_v2_2.tr(), style: Theme.of(context).textTheme.bodyMedium, ), SizedBox(height: success == true ? 0 : 10), success == true ? const SizedBox() : const SizedBox( height: 24, width: 24, child: CircularProgressIndicator( color: Colors.yellow, ), ), SizedBox(height: success == true ? 0 : 8), error != null ? Text( error!, style: Theme.of(context).textTheme.bodyLarge, ) : const SizedBox(), success == true ? const SizedBox() : Text( (total != null && done != null) ? '$done / $total ${LocaleKeys.restored.tr()}' : total != null ? '0 / $total ${LocaleKeys.restored.tr()}' : '', style: Theme.of(context).textTheme.bodyLarge, ), SizedBox(height: success == true ? 0 : 10), ], ), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/common/keyboard_dismissable.dart
import 'package:flutter/material.dart'; class KeyboardDismissible extends StatelessWidget { final Widget child; const KeyboardDismissible({super.key, required this.child}); @override Widget build(BuildContext context) { return GestureDetector( onTap: () => FocusScope.of(context).unfocus(), child: child, ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/search_page/search_page.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/cubit/current_book_cubit.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/add_book_screen/widgets/book_text_field.dart'; import 'package:openreads/ui/book_screen/book_screen.dart'; import 'package:openreads/ui/books_screen/widgets/widgets.dart'; import 'package:openreads/ui/common/keyboard_dismissable.dart'; class SearchPage extends StatefulWidget { const SearchPage({super.key}); @override State<SearchPage> createState() => _SearchPageState(); } class _SearchPageState extends State<SearchPage> { final _searchController = TextEditingController(); @override void initState() { _searchController.addListener(() { bookCubit.getSearchBooks(_searchController.text); }); super.initState(); } @override Widget build(BuildContext context) { return KeyboardDismissible( child: Scaffold( appBar: AppBar( title: Text( LocaleKeys.search_in_books.tr(), style: const TextStyle(fontSize: 18), ), ), body: Column( children: [ Padding( padding: const EdgeInsets.all(10), child: BookTextField( controller: _searchController, keyboardType: TextInputType.name, maxLength: 99, autofocus: true, textInputAction: TextInputAction.search, textCapitalization: TextCapitalization.sentences, ), ), Expanded( child: StreamBuilder<List<Book>>( stream: bookCubit.searchBooks, builder: (context, snapshot) { if (snapshot.hasData) { return ListView.builder( shrinkWrap: true, itemCount: snapshot.data!.length, itemBuilder: (context, index) { final heroTag = 'tag_$index'; return BookCard( book: snapshot.data![index], heroTag: heroTag, addBottomPadding: (snapshot.data!.length == index + 1), onPressed: () { if (snapshot.data![index].id == null) return; context .read<CurrentBookCubit>() .setBook(snapshot.data![index]); Navigator.push( context, MaterialPageRoute( builder: (context) => BookScreen( id: snapshot.data![index].id!, heroTag: heroTag, ), ), ); }, ); }, ); } else { return const SizedBox(); } }, ), ) ], ), ), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/statistics_screen/statistics_screen.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/challenge_bloc/challenge_bloc.dart'; import 'package:openreads/logic/bloc/stats_bloc/stats_bloc.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/statistics_screen/widgets/statistics.dart'; class StatisticsScreen extends StatefulWidget { const StatisticsScreen({super.key}); @override State<StatisticsScreen> createState() => _StatisticsScreenState(); } class _StatisticsScreenState extends State<StatisticsScreen> { late FocusNode _focusNode; void _setChallenge(int books, int pages, int year) { BlocProvider.of<ChallengeBloc>(context).add( ChangeChallengeEvent( books: (books == 0) ? null : books, pages: (pages == 0) ? null : pages, year: year, ), ); } @override void initState() { _focusNode = FocusNode(); super.initState(); } @override Widget build(BuildContext context) { return StreamBuilder<List<Book>>( stream: bookCubit.allBooks, builder: (context, snapshot) { if (snapshot.hasData) { return BlocProvider( create: (context) => StatsBloc()..add(StatsLoad(snapshot.data!)), child: SelectableRegion( selectionControls: materialTextSelectionControls, focusNode: _focusNode, child: Scaffold( appBar: AppBar( title: Text( LocaleKeys.statistics.tr(), style: const TextStyle(fontSize: 18), ), ), body: BlocBuilder<StatsBloc, StatsState>( builder: (context, state) { if (state is StatsLoaded) { return Statistics( state: state, setChallenge: _setChallenge, ); } else if (state is StatsError) { return Center( child: Padding( padding: const EdgeInsets.all(50), child: Text( state.msg, textAlign: TextAlign.center, style: const TextStyle( fontSize: 16, letterSpacing: 1.5, ), ), ), ); } else { return Center( child: LoadingAnimationWidget.fourRotatingDots( color: Theme.of(context).primaryColor, size: 42, ), ); } }, ), ), ), ); } else { return const SizedBox(); } }); } }
0
mirrored_repositories/openreads/lib/ui/statistics_screen
mirrored_repositories/openreads/lib/ui/statistics_screen/widgets/statistics.dart
import 'dart:convert'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/challenge_bloc/challenge_bloc.dart'; import 'package:openreads/logic/bloc/stats_bloc/stats_bloc.dart'; import 'package:openreads/model/yearly_challenge.dart'; import 'package:openreads/ui/statistics_screen/widgets/widgets.dart'; class Statistics extends StatelessWidget { final StatsLoaded state; final Function( int books, int pages, int year, ) setChallenge; const Statistics({ super.key, required this.state, required this.setChallenge, }); @override Widget build(BuildContext context) { return DefaultTabController( length: state.years.length + 1, child: Column( children: [ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), ), child: Row( children: [ Expanded( child: TabBar( isScrollable: true, tabs: _buildYearsTabBars(context, state.years), ), ), ], ), ), Expanded( child: TabBarView( children: _buildYearsTabBarViews(context, state), ), ), ], ), ); } List<Widget> _buildYearsTabBars(BuildContext context, List<int> years) { final tabs = List<Widget>.empty(growable: true); tabs.add(Tab( child: Text( LocaleKeys.all_years.tr(), ), )); for (var year in years) { tabs.add(Tab( child: Text( '$year', ), )); } return tabs; } List<Widget> _buildYearsTabBarViews( BuildContext context, StatsLoaded state, ) { final tabs = List<Widget>.empty(growable: true); tabs.add( Tab( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ _buildBooksChallenge(context, state, null), _buildPagesChallenge(context, state, null), _buildAllBooksPieChart(context), _buildFinishedBooksByMonth(context, state, null), _buildFinishedPagesByMonth(context, state, null), _buildNumberOfFinishedBooks(context, state, null), _buildNumberOfFinishedPages(context, state, null), _buildAverageRating(context, state, null), _buildAveragePages(context, state, null), _buildAverageReadingTime(context, state, null), _buildLongestBook(context, state, null), _buildShortestBook(context, state, null), _buildFastestRead(context, state, null), _buildSlowestRead(context, state, null), const SizedBox(height: 100) ], ), ), ), ), ); for (var year in state.years) { tabs.add(Tab( child: Column( children: [ Expanded( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(10.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ _buildBooksChallenge(context, state, year), _buildPagesChallenge(context, state, year), _buildFinishedBooksByMonth(context, state, year), _buildFinishedPagesByMonth(context, state, year), _buildNumberOfFinishedBooks(context, state, year), _buildNumberOfFinishedPages(context, state, year), _buildAverageRating(context, state, year), _buildAveragePages(context, state, year), _buildAverageReadingTime(context, state, year), _buildLongestBook(context, state, year), _buildShortestBook(context, state, year), _buildFastestRead(context, state, year), _buildSlowestRead(context, state, year), ], ), ), ), ), ], ), )); } return tabs; } BlocBuilder<dynamic, dynamic> _buildBooksChallenge( BuildContext context, StatsLoaded state, int? year, ) { return BlocBuilder<ChallengeBloc, ChallengeState>( builder: (context, challengeState) { if (challengeState is SetChallengeState && challengeState.yearlyChallenges != null) { final yearlyChallenges = List<YearlyChallenge>.empty( growable: true, ); final jsons = challengeState.yearlyChallenges!.split('|||||'); for (var json in jsons) { final decodedJson = jsonDecode(json); final yearlyChallenge = YearlyChallenge.fromJSON(decodedJson); yearlyChallenges.add(yearlyChallenge); } final selectedTarget = yearlyChallenges.where((element) { return (year == null) ? element.year == DateTime.now().year : element.year == year; }); final selectedValue = state.finishedBooksByMonthAllTypes.where((element) { return (year == null) ? element.year == DateTime.now().year : element.year == year; }); final value = selectedValue.isNotEmpty ? selectedValue.first.values.reduce((a, b) => a + b) : 0; if (selectedTarget.isEmpty || selectedTarget.first.books == null) { return (year == null) ? SetChallengeBox( setChallenge: setChallenge, year: year ?? DateTime.now().year, ) : const SizedBox(); } else { return ReadingChallenge( title: LocaleKeys.books_challenge.tr(), value: value, target: selectedTarget.first.books ?? 0, setChallenge: setChallenge, booksTarget: selectedTarget.first.books, pagesTarget: selectedTarget.first.pages, year: year ?? DateTime.now().year, ); } } else { return (year == null) ? SetChallengeBox( setChallenge: setChallenge, year: year ?? DateTime.now().year, ) : const SizedBox(); } }, ); } BlocBuilder<dynamic, dynamic> _buildPagesChallenge( BuildContext context, StatsLoaded state, int? year, ) { return BlocBuilder<ChallengeBloc, ChallengeState>( builder: (context, challengeState) { if (challengeState is SetChallengeState && challengeState.yearlyChallenges != null) { final yearlyChallenges = List<YearlyChallenge>.empty( growable: true, ); final jsons = challengeState.yearlyChallenges!.split('|||||'); for (var json in jsons) { final decodedJson = jsonDecode(json); final yearlyChallenge = YearlyChallenge.fromJSON(decodedJson); yearlyChallenges.add(yearlyChallenge); } final selectedTarget = yearlyChallenges.where((element) { return (year == null) ? element.year == DateTime.now().year : element.year == year; }); final selectedValue = state.finishedPagesByMonthAllTypes.where((element) { return (year == null) ? element.year == DateTime.now().year : element.year == year; }); final value = selectedValue.isNotEmpty ? selectedValue.first.values.reduce((a, b) => a + b) : 0; if (selectedTarget.isEmpty) { return const SizedBox(); } else if (selectedTarget.first.pages == null) { return const SizedBox(); } else { return ReadingChallenge( title: LocaleKeys.pages_challenge.tr(), value: value, target: selectedTarget.first.pages ?? 0, setChallenge: setChallenge, booksTarget: selectedTarget.first.books, pagesTarget: selectedTarget.first.pages, year: year ?? DateTime.now().year, ); } } else { return const SizedBox(); } }, ); } Widget _buildAllBooksPieChart(BuildContext context) { return BooksByStatus( title: LocaleKeys.all_books_by_status.tr(), list: [ state.finishedBooks.length, state.inProgressBooks.length, state.forLaterBooks.length, state.unfinishedBooks.length, ], ); } Widget _buildFinishedBooksByMonth( BuildContext context, StatsLoaded state, int? year, ) { final emptyList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; List<int> finishedBooksByMonthPaperbackBooks = emptyList; List<int> finishedBooksByMonthHardcoverBooks = emptyList; List<int> finishedBooksByMonthEbooks = emptyList; List<int> finishedBooksByMonthAudiobooks = emptyList; for (var bookReadStat in state.finishedBooksByMonthPaperbackBooks) { if (bookReadStat.year == year) { finishedBooksByMonthPaperbackBooks = bookReadStat.values; } } for (var bookReadStat in state.finishedBooksByMonthHardcoverBooks) { if (bookReadStat.year == year) { finishedBooksByMonthHardcoverBooks = bookReadStat.values; } } for (var bookReadStat in state.finishedBooksByMonthEbooks) { if (bookReadStat.year == year) { finishedBooksByMonthEbooks = bookReadStat.values; } } for (var bookReadStat in state.finishedBooksByMonthAudiobooks) { if (bookReadStat.year == year) { finishedBooksByMonthAudiobooks = bookReadStat.values; } } if (state.finishedBooksByMonthAllTypes.isEmpty) { return const SizedBox(); } return ReadStatsByMonth( title: LocaleKeys.finished_books_by_month.tr(), listPaperbackBooks: finishedBooksByMonthPaperbackBooks, listHardcoverBooks: finishedBooksByMonthHardcoverBooks, listEbooks: finishedBooksByMonthEbooks, listAudiobooks: finishedBooksByMonthAudiobooks, theme: Theme.of(context), ); } Widget _buildFinishedPagesByMonth( BuildContext context, StatsLoaded state, int? year, ) { final emptyList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; List<int> finishedPagesByMonthPaperbackBooks = emptyList; List<int> finishedPagesByMonthHardcoverBooks = emptyList; List<int> finishedPagesByMonthEbooks = emptyList; List<int> finishedPagesByMonthAudiobooks = emptyList; for (var bookReadStat in state.finishedPagesByMonthPaperbackBooks) { if (bookReadStat.year == year) { finishedPagesByMonthPaperbackBooks = bookReadStat.values; } } for (var bookReadStat in state.finishedPagesByMonthHardcoverBooks) { if (bookReadStat.year == year) { finishedPagesByMonthHardcoverBooks = bookReadStat.values; } } for (var bookReadStat in state.finishedPagesByMonthEbooks) { if (bookReadStat.year == year) { finishedPagesByMonthEbooks = bookReadStat.values; } } for (var bookReadStat in state.finishedPagesByMonthAudiobooks) { if (bookReadStat.year == year) { finishedPagesByMonthAudiobooks = bookReadStat.values; } } if (state.finishedPagesByMonthAllTypes.isEmpty) { return const SizedBox(); } return ReadStatsByMonth( title: LocaleKeys.finished_pages_by_month.tr(), listPaperbackBooks: finishedPagesByMonthPaperbackBooks, listHardcoverBooks: finishedPagesByMonthHardcoverBooks, listEbooks: finishedPagesByMonthEbooks, listAudiobooks: finishedPagesByMonthAudiobooks, theme: Theme.of(context), ); } Widget _buildNumberOfFinishedBooks( BuildContext context, StatsLoaded state, int? year, ) { if (year == null) { return ReadStats( title: LocaleKeys.finished_books.tr(), value: state.finishedBooksAll.toString(), ); } for (var bookReadStat in state.finishedBooksByMonthAllTypes) { if (bookReadStat.year == year) { return ReadStats( title: LocaleKeys.finished_books.tr(), value: bookReadStat.values.reduce((a, b) => a + b).toString(), ); } } return const SizedBox(); } Widget _buildNumberOfFinishedPages( BuildContext context, StatsLoaded state, int? year, ) { if (year == null) { return ReadStats( title: LocaleKeys.finished_pages.tr(), value: state.finishedPagesAll.toString(), ); } for (var bookReadStat in state.finishedPagesByMonthAllTypes) { if (bookReadStat.year == year) { return ReadStats( title: LocaleKeys.finished_pages.tr(), value: bookReadStat.values.reduce((a, b) => a + b).toString(), ); } } return const SizedBox(); } Widget _buildAverageRating( BuildContext context, StatsLoaded state, int? year, ) { for (var bookYearlyStat in state.averageRating) { if (bookYearlyStat.year == year) { return ReadStats( title: LocaleKeys.average_rating.tr(), value: bookYearlyStat.value, iconData: Icons.star_rounded, ); } } return const SizedBox(); } Widget _buildAveragePages( BuildContext context, StatsLoaded state, int? year, ) { for (var bookYearlyStat in state.averagePages) { if (bookYearlyStat.year == year) { return ReadStats( title: LocaleKeys.average_pages.tr(), value: (bookYearlyStat.value != '') ? '${bookYearlyStat.value} ${LocaleKeys.pages_lowercase.tr()}' : '0', ); } } return const SizedBox(); } Widget _buildAverageReadingTime( BuildContext context, StatsLoaded state, int? year, ) { for (var bookYearlyStat in state.averageReadingTime) { if (bookYearlyStat.year == year) { return ReadStats( title: LocaleKeys.average_reading_time.tr(), value: (bookYearlyStat.value != '') ? bookYearlyStat.value : '0', ); } } return const SizedBox(); } Widget _buildLongestBook( BuildContext context, StatsLoaded state, int? year, ) { for (var bookYearlyStat in state.longestBook) { if (bookYearlyStat.year == year) { return ReadStats( title: LocaleKeys.longest_book.tr(), value: bookYearlyStat.title.toString(), secondValue: '${bookYearlyStat.value} ${LocaleKeys.pages_lowercase.tr()}', book: bookYearlyStat.book, ); } } return const SizedBox(); } Widget _buildShortestBook( BuildContext context, StatsLoaded state, int? year, ) { for (var bookYearlyStat in state.shortestBook) { if (bookYearlyStat.year == year) { return ReadStats( title: LocaleKeys.shortest_book.tr(), value: bookYearlyStat.title.toString(), secondValue: (bookYearlyStat.value != '') ? '${bookYearlyStat.value} ${LocaleKeys.pages_lowercase.tr()}' : '', book: bookYearlyStat.book, ); } } return const SizedBox(); } Widget _buildFastestRead( BuildContext context, StatsLoaded state, int? year, ) { for (var bookYearlyStat in state.fastestBook) { if (bookYearlyStat.year == year) { return ReadStats( title: LocaleKeys.fastest_book.tr(), value: bookYearlyStat.title.toString(), secondValue: bookYearlyStat.value, book: bookYearlyStat.book, ); } } return const SizedBox(); } Widget _buildSlowestRead( BuildContext context, StatsLoaded state, int? year, ) { for (var bookYearlyStat in state.slowestBook) { if (bookYearlyStat.year == year) { return ReadStats( title: LocaleKeys.slowest_book.tr(), value: bookYearlyStat.title.toString(), secondValue: bookYearlyStat.value, book: bookYearlyStat.book, ); } } return const SizedBox(); } }
0
mirrored_repositories/openreads/lib/ui/statistics_screen
mirrored_repositories/openreads/lib/ui/statistics_screen/widgets/challenge_dialog.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; class ChallengeDialog extends StatefulWidget { const ChallengeDialog({ super.key, required this.setChallenge, required this.year, this.booksTarget, this.pagesTarget, }); final Function(int, int, int) setChallenge; final int? booksTarget; final int? pagesTarget; final int year; @override State<ChallengeDialog> createState() => _ChallengeDialogState(); } class _ChallengeDialogState extends State<ChallengeDialog> with TickerProviderStateMixin { static const double minBooks = 0; static const double maxBooks = 50; static const double minPages = 0; static const double maxPages = 15000; double _booksSliderValue = 0; double _pagesSliderValue = 0; bool _showPagesChallenge = false; int? _booksTarget; int? _pagesTarget; final _booksController = TextEditingController(); final _pagesController = TextEditingController(); late AnimationController _animController; late Animation<double> _animation; @override void dispose() { _booksController.dispose(); _pagesController.dispose(); _animController.dispose(); super.dispose(); } @override void initState() { super.initState(); _animController = AnimationController( duration: const Duration(milliseconds: 250), vsync: this, ); _animation = CurvedAnimation( parent: _animController, curve: Curves.easeIn, ); _booksController.addListener(() { try { final newValue = double.parse(_booksController.text); setState(() { if (newValue > maxBooks) { _booksSliderValue = maxBooks; } else if (newValue < minBooks) { _booksSliderValue = minBooks; } else { _booksSliderValue = newValue; } _booksTarget = newValue.toInt(); }); } catch (error) { return; } }); void prefillBooksTarget() { _booksTarget = widget.booksTarget; _booksController.text = widget.booksTarget.toString(); if (widget.booksTarget! > maxBooks.toInt()) { _booksSliderValue = maxBooks; } else if (widget.booksTarget! < minBooks.toInt()) { _booksSliderValue = minBooks; } else { _booksSliderValue = widget.booksTarget!.toDouble(); } } void prefillPagesTarget() { _showPagesChallenge = true; _animController.forward(); _pagesTarget = widget.pagesTarget; _pagesController.text = widget.pagesTarget.toString(); if (widget.pagesTarget! > maxPages.toInt()) { _pagesSliderValue = maxPages; } else if (widget.pagesTarget! < minPages.toInt()) { _pagesSliderValue = minPages; } else { _pagesSliderValue = widget.pagesTarget!.toDouble(); } } _pagesController.addListener(() { try { final newValue = double.parse(_pagesController.text); setState(() { if (newValue > maxPages) { _pagesSliderValue = maxPages; } else if (newValue < minPages) { _pagesSliderValue = minPages; } else { _pagesSliderValue = newValue; } _pagesTarget = newValue.toInt(); }); } catch (error) { return; } }); if (widget.booksTarget != null) { prefillBooksTarget(); } if (widget.pagesTarget != null) { prefillPagesTarget(); } } @override Widget build(BuildContext context) { return Dialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), backgroundColor: Theme.of(context).colorScheme.surface, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( '${LocaleKeys.set_books_goal_for_year.tr()} ${widget.year}:', textAlign: TextAlign.center, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), Slider( value: _booksSliderValue, min: minBooks, max: maxBooks, divisions: 50, label: _booksSliderValue.round().toString(), activeColor: Theme.of(context).colorScheme.primary, onChanged: (double value) { setState(() { _booksSliderValue = value; _booksController.text = _booksSliderValue.round().toString(); }); }, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: 100, padding: const EdgeInsets.symmetric( horizontal: 8, vertical: 0, ), decoration: BoxDecoration( color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: TextField( textAlign: TextAlign.center, keyboardType: TextInputType.number, controller: _booksController, style: const TextStyle(fontSize: 14), decoration: const InputDecoration( border: InputBorder.none, ), ), ), ], ), ), const SizedBox(height: 30), Container( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: Row( children: [ Switch( value: _showPagesChallenge, activeColor: Theme.of(context).colorScheme.primary, onChanged: (value) { setState(() { _showPagesChallenge = value; }); if (value) { _animController.forward(); } else { _animController.animateBack(0, duration: const Duration( milliseconds: 250, )); } }, ), const SizedBox(width: 10), Text( LocaleKeys.add_pages_goal.tr(), style: const TextStyle( fontSize: 16, ), ), ], ), ), const SizedBox(height: 30), SizeTransition( sizeFactor: _animation, child: Column( children: [ Text( LocaleKeys.set_pages_goal.tr(), textAlign: TextAlign.center, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), Slider( value: _pagesSliderValue, min: minPages, max: maxPages, divisions: 150, label: _pagesSliderValue.round().toString(), activeColor: Theme.of(context).colorScheme.primary, onChanged: (double value) { setState(() { _pagesSliderValue = value; _pagesController.text = _pagesSliderValue.round().toString(); }); }, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: 100, padding: const EdgeInsets.symmetric( horizontal: 8, vertical: 0, ), decoration: BoxDecoration( color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: TextField( textAlign: TextAlign.center, keyboardType: TextInputType.number, controller: _pagesController, style: const TextStyle( fontSize: 14, ), decoration: const InputDecoration( border: InputBorder.none, ), ), ), ], ), ), ], ), ), const SizedBox(height: 10), ElevatedButton( onPressed: () { widget.setChallenge(_booksTarget ?? 0, _showPagesChallenge ? _pagesTarget ?? 0 : 0, widget.year); if (mounted) { Navigator.of(context).pop(); } }, style: ElevatedButton.styleFrom( elevation: 0, backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Theme.of(context).colorScheme.onPrimary, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), ), child: const Center( child: Text("Save"), ), ) ], ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/statistics_screen
mirrored_repositories/openreads/lib/ui/statistics_screen/widgets/read_stats_by_month.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/ui/statistics_screen/widgets/widgets.dart'; import 'package:collection/collection.dart'; class ReadStatsByMonth extends StatelessWidget { ReadStatsByMonth({ super.key, required this.listPaperbackBooks, required this.listHardcoverBooks, required this.listEbooks, required this.listAudiobooks, required this.title, required this.theme, }); final List<int> listPaperbackBooks; final List<int> listHardcoverBooks; final List<int> listEbooks; final List<int> listAudiobooks; final String title; final ThemeData theme; final List<String> listOfMonthsShort = [ LocaleKeys.january_short.tr(), LocaleKeys.february_short.tr(), LocaleKeys.march_short.tr(), LocaleKeys.april_short.tr(), LocaleKeys.may_short.tr(), LocaleKeys.june_short.tr(), LocaleKeys.july_short.tr(), LocaleKeys.august_short.tr(), LocaleKeys.september_short.tr(), LocaleKeys.october_short.tr(), LocaleKeys.november_short.tr(), LocaleKeys.december_short.tr(), ]; FlTitlesData get titlesData => FlTitlesData( show: true, bottomTitles: AxisTitles( sideTitles: SideTitles( showTitles: true, reservedSize: 32, getTitlesWidget: getTitles, interval: 2, ), ), leftTitles: const AxisTitles( sideTitles: SideTitles(showTitles: false), ), topTitles: const AxisTitles( sideTitles: SideTitles(showTitles: false), ), rightTitles: const AxisTitles( sideTitles: SideTitles(showTitles: false), ), ); Widget getTitles(double value, TitleMeta meta) { String text; switch (value.toInt()) { case 0: text = listOfMonthsShort[value.toInt()]; break; case 1: text = listOfMonthsShort[value.toInt()]; break; case 2: text = listOfMonthsShort[value.toInt()]; break; case 3: text = listOfMonthsShort[value.toInt()]; break; case 4: text = listOfMonthsShort[value.toInt()]; break; case 5: text = listOfMonthsShort[value.toInt()]; break; case 6: text = listOfMonthsShort[value.toInt()]; break; case 7: text = listOfMonthsShort[value.toInt()]; break; case 8: text = listOfMonthsShort[value.toInt()]; break; case 9: text = listOfMonthsShort[value.toInt()]; break; case 10: text = listOfMonthsShort[value.toInt()]; break; case 11: text = listOfMonthsShort[value.toInt()]; break; default: text = ''; break; } return (value % meta.appliedInterval == 0) ? Builder(builder: (context) { return SideTitleWidget( axisSide: meta.axisSide, space: 8, child: Text( text, style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 12, ), ), ); }) : const SizedBox(); } FlBorderData get borderData => FlBorderData( show: false, ); List<BarChartGroupData> barGroups(BuildContext context) { final List<BarChartGroupData> barList = List.empty(growable: true); for (var i = 0; i < 12; i++) { barList.add( BarChartGroupData( x: i, barRods: [ BarChartRodData( toY: (listPaperbackBooks[i] + listHardcoverBooks[i] + listEbooks[i] + listAudiobooks[i]) .toDouble(), width: MediaQuery.of(context).size.width / 20, color: theme.colorScheme.primary, borderRadius: BorderRadius.circular(3), rodStackItems: [ listPaperbackBooks[i] != 0 ? BarChartRodStackItem( 0, (listPaperbackBooks[i] + listHardcoverBooks[i]) .toDouble(), theme.colorScheme.primary, ) : BarChartRodStackItem(0, 0, Colors.transparent), listEbooks[i] != 0 ? BarChartRodStackItem( (listPaperbackBooks[i] + listHardcoverBooks[i]) .toDouble(), (listPaperbackBooks[i] + listHardcoverBooks[i] + listEbooks[i]) .toDouble(), theme.colorScheme.primaryContainer, ) : BarChartRodStackItem(0, 0, Colors.transparent), listAudiobooks[i] != 0 ? BarChartRodStackItem( (listPaperbackBooks[i] + listHardcoverBooks[i] + listEbooks[i]) .toDouble(), (listPaperbackBooks[i] + listHardcoverBooks[i] + listEbooks[i] + listAudiobooks[i]) .toDouble(), theme.colorScheme.onSurfaceVariant, ) : BarChartRodStackItem(0, 0, Colors.transparent), ], ) ], showingTooltipIndicators: ((listPaperbackBooks[i] + listHardcoverBooks[i] + listEbooks[i] + listAudiobooks[i]) > 0) ? [0] : [1], ), ); } return barList; } double calculateMaxY() { int maxBooksInMonth = 0; for (var i = 0; i < 12; i++) { if ((listPaperbackBooks[i] + listHardcoverBooks[i] + listEbooks[i] + listAudiobooks[i]) > maxBooksInMonth) { maxBooksInMonth = (listPaperbackBooks[i] + listHardcoverBooks[i] + listEbooks[i] + listAudiobooks[i]); } } return maxBooksInMonth * 1.2; } @override Widget build(BuildContext context) { return Card( shadowColor: Colors.transparent, shape: RoundedRectangleBorder( side: BorderSide(color: dividerColor, width: 1), borderRadius: BorderRadius.circular(cornerRadius), ), child: Padding( padding: const EdgeInsets.all(10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 10), AspectRatio( aspectRatio: 2.2, child: BarChart( BarChartData( barTouchData: BarTouchData( enabled: false, touchTooltipData: BarTouchTooltipData( getTooltipColor: (_) => Colors.transparent, tooltipPadding: EdgeInsets.zero, tooltipMargin: 8, fitInsideHorizontally: true, fitInsideVertically: true, getTooltipItem: ( BarChartGroupData group, int groupIndex, BarChartRodData rod, int rodIndex, ) { return BarTooltipItem( rod.toY.round().toString(), const TextStyle( fontWeight: FontWeight.bold, fontSize: 10, ), ); }, ), ), titlesData: titlesData, borderData: borderData, barGroups: barGroups(context), gridData: const FlGridData(show: false), alignment: BarChartAlignment.spaceAround, maxY: calculateMaxY(), ), swapAnimationDuration: const Duration(milliseconds: 150), swapAnimationCurve: Curves.linear, ), ), Align( alignment: Alignment.centerRight, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 5), ChartLegendElement( color: theme.colorScheme.onSurfaceVariant, text: LocaleKeys.book_format_audiobook_plural.tr(), number: listAudiobooks.sum, reversed: true, ), const SizedBox(height: 5), ChartLegendElement( color: theme.colorScheme.primaryContainer, text: LocaleKeys.book_format_ebook_plural.tr(), number: listEbooks.sum, reversed: true, ), const SizedBox(height: 5), ChartLegendElement( color: theme.colorScheme.primary, text: LocaleKeys.book_format_paper_plural.tr(), number: listPaperbackBooks.sum + listHardcoverBooks.sum, reversed: true, ), ], ), ), ], ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/statistics_screen
mirrored_repositories/openreads/lib/ui/statistics_screen/widgets/set_challenge_box.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/ui/statistics_screen/widgets/widgets.dart'; class SetChallengeBox extends StatelessWidget { const SetChallengeBox({ super.key, required this.setChallenge, required this.year, this.booksTarget, this.pagesTarget, }); final Function(int, int, int) setChallenge; final int year; final int? booksTarget; final int? pagesTarget; @override Widget build(BuildContext context) { return Card( shadowColor: Colors.transparent, shape: RoundedRectangleBorder( side: BorderSide(color: dividerColor, width: 1), borderRadius: BorderRadius.circular(cornerRadius), ), color: Theme.of(context).colorScheme.surfaceVariant, child: InkWell( borderRadius: BorderRadius.circular(cornerRadius), onTap: () => showDialog( context: context, builder: (BuildContext context) { return ChallengeDialog( setChallenge: setChallenge, year: year, booksTarget: booksTarget, pagesTarget: pagesTarget, ); }), child: Padding( padding: const EdgeInsets.symmetric( vertical: 15, horizontal: 10, ), child: Row( children: [ Expanded( child: Text( LocaleKeys.click_here_to_set_challenge.tr(), style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.onSurface), ), ), ], ), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/statistics_screen
mirrored_repositories/openreads/lib/ui/statistics_screen/widgets/widgets.dart
export 'read_stats_by_month.dart'; export 'read_stats.dart'; export 'books_by_status.dart'; export 'chart_legend_element.dart'; export 'reading_challenge.dart'; export 'challenge_dialog.dart'; export 'set_challenge_box.dart';
0
mirrored_repositories/openreads/lib/ui/statistics_screen
mirrored_repositories/openreads/lib/ui/statistics_screen/widgets/books_by_status.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/ui/statistics_screen/widgets/widgets.dart'; class BooksByStatus extends StatefulWidget { const BooksByStatus({ super.key, required this.title, required this.list, }); final String title; final List<int>? list; @override State<StatefulWidget> createState() => BooksByStatusState(); } class BooksByStatusState extends State<BooksByStatus> { int touchedIndex = -1; @override Widget build(BuildContext context) { return Card( shadowColor: Colors.transparent, shape: RoundedRectangleBorder( side: BorderSide(color: dividerColor, width: 1), borderRadius: BorderRadius.circular(cornerRadius), ), child: Padding( padding: const EdgeInsets.fromLTRB(10, 10, 10, 30), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( widget.title, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 30), Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: AspectRatio( aspectRatio: 2, child: (widget.list == null) ? const SizedBox() : Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Flexible( flex: 5, child: PieChart( PieChartData( sectionsSpace: 1, sections: showingSections(), ), ), ), Flexible( flex: 4, child: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [ ChartLegendElement( color: Colors.green.shade400, text: LocaleKeys.books_finished.tr(), number: widget.list![0], ), const SizedBox( height: 5, ), ChartLegendElement( color: Colors.yellow.shade400, text: LocaleKeys.books_in_progress.tr(), number: widget.list![1], ), const SizedBox( height: 5, ), ChartLegendElement( color: Colors.blue.shade400, text: LocaleKeys.books_for_later.tr(), number: widget.list![2], ), SizedBox( height: (widget.list![3] != 0) ? 5 : 0, ), (widget.list![3] != 0) ? ChartLegendElement( color: Colors.red.shade400, text: LocaleKeys.books_unfinished.tr(), number: widget.list![3], ) : const SizedBox(), ], ), ), ], ), ), ), ], ), ), ); } List<PieChartSectionData> showingSections() { final sum = widget.list!.reduce((a, b) => a + b); return List.generate(4, (i) { final isTouched = i == touchedIndex; const fontSize = 14.0; final radius = isTouched ? 60.0 : 50.0; switch (i) { case 0: return PieChartSectionData( color: Colors.green.shade400, value: widget.list![0].toDouble(), title: '${((widget.list![0] / sum) * 100).toStringAsFixed(0)}%', radius: radius, titleStyle: const TextStyle( fontSize: fontSize, fontWeight: FontWeight.bold, color: Colors.black, ), ); case 1: return PieChartSectionData( color: Colors.yellow.shade400, value: widget.list![1].toDouble(), title: '${((widget.list![1] / sum) * 100).toStringAsFixed(0)}%', radius: radius, titleStyle: const TextStyle( fontSize: fontSize, fontWeight: FontWeight.bold, color: Colors.black, ), ); case 2: return PieChartSectionData( color: Colors.blue.shade400, value: widget.list![2].toDouble(), title: '${((widget.list![2] / sum) * 100).toStringAsFixed(0)}%', radius: radius, titleStyle: const TextStyle( fontSize: fontSize, fontWeight: FontWeight.bold, color: Colors.black, ), ); case 3: return PieChartSectionData( color: Colors.red.shade400, value: widget.list![3].toDouble(), title: '${((widget.list![3] / sum) * 100).toStringAsFixed(0)}%', radius: radius, titleStyle: const TextStyle( fontSize: fontSize, fontWeight: FontWeight.bold, color: Colors.black, ), ); default: throw Error(); } }); } }
0
mirrored_repositories/openreads/lib/ui/statistics_screen
mirrored_repositories/openreads/lib/ui/statistics_screen/widgets/chart_legend_element.dart
import 'package:flutter/material.dart'; class ChartLegendElement extends StatelessWidget { const ChartLegendElement({ super.key, required this.color, this.size = 14, required this.text, required this.number, this.reversed = false, }); final Color color; final double size; final String text; final int number; final bool reversed; @override Widget build(BuildContext context) { List<Widget> widgets = [ Flexible( child: Text( '$text ($number)', style: const TextStyle(fontSize: 9.5), ), ), const SizedBox(width: 8), Container( padding: const EdgeInsets.all(1), decoration: BoxDecoration( shape: BoxShape.circle, color: Theme.of(context).colorScheme.onSurfaceVariant, ), child: Container( width: size, height: size, decoration: BoxDecoration( shape: BoxShape.circle, color: color, ), ), ), ]; return Row( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: reversed ? widgets.reversed.toList() : widgets, ); } }
0
mirrored_repositories/openreads/lib/ui/statistics_screen
mirrored_repositories/openreads/lib/ui/statistics_screen/widgets/reading_challenge.dart
import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/ui/statistics_screen/widgets/widgets.dart'; class ReadingChallenge extends StatelessWidget { const ReadingChallenge({ super.key, required this.value, required this.target, required this.title, required this.setChallenge, required this.year, this.booksTarget, this.pagesTarget, }); final int value; final int target; final String title; final Function(int, int, int) setChallenge; final int? booksTarget; final int? pagesTarget; final int year; @override Widget build(BuildContext context) { return Card( shadowColor: Colors.transparent, shape: RoundedRectangleBorder( side: BorderSide(color: dividerColor, width: 1), borderRadius: BorderRadius.circular(cornerRadius), ), child: InkWell( onTap: () => showDialog( context: context, builder: (BuildContext context) { return ChallengeDialog( setChallenge: setChallenge, booksTarget: booksTarget, pagesTarget: pagesTarget, year: year, ); }), borderRadius: BorderRadius.circular(cornerRadius), child: Padding( padding: const EdgeInsets.all(10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 10), Row( children: [ Expanded( child: Container( padding: const EdgeInsets.symmetric(vertical: 3), decoration: BoxDecoration( color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(cornerRadius), ), child: Row( children: [ (target != 0) ? Expanded( flex: ((value / target) * 100).toInt(), child: Container( height: 15, decoration: BoxDecoration( color: Theme.of(context).colorScheme.primary, borderRadius: BorderRadius.circular(cornerRadius), ), ), ) : const SizedBox( height: 15, ), (target != 0 && (100 - ((value / target) * 100)).toInt() > 0) ? Spacer( flex: (100 - ((value / target) * 100)).toInt(), ) : const SizedBox() ], ), ), ), ], ), const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( '$value/$target', style: const TextStyle( fontSize: 16, ), ), Text( (target == 0) ? '' : '${((value / target * 100) <= 100) ? (value / target * 100).toStringAsFixed(2) : 100}%', style: const TextStyle( fontSize: 16, ), ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/statistics_screen
mirrored_repositories/openreads/lib/ui/statistics_screen/widgets/read_stats.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/logic/cubit/current_book_cubit.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/book_screen/book_screen.dart'; class ReadStats extends StatelessWidget { const ReadStats({ super.key, required this.title, required this.value, this.secondValue, this.iconData, this.book, }); final String title; final String value; final String? secondValue; final IconData? iconData; final Book? book; onTap(BuildContext context, int heroKey) { context.read<CurrentBookCubit>().setBook(book!); Navigator.push( context, MaterialPageRoute( builder: (context) => BookScreen( id: book!.id!, heroTag: '${book?.id}-$heroKey', ), ), ); } @override Widget build(BuildContext context) { final heroKey = Random().nextInt(1000000); return InkWell( borderRadius: BorderRadius.circular(cornerRadius), onTap: book != null && book!.id != null ? () => onTap(context, heroKey) : null, child: Card( shadowColor: Colors.transparent, shape: RoundedRectangleBorder( side: BorderSide(color: dividerColor, width: 1), borderRadius: BorderRadius.circular(cornerRadius), ), child: Padding( padding: const EdgeInsets.all(10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( title, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 5), Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ book != null && book!.getCoverFile() != null ? Padding( padding: const EdgeInsets.only(right: 10), child: Hero( tag: '${book?.id}-$heroKey', child: Image.file( book!.getCoverFile()!, fit: BoxFit.cover, width: 60, ), ), ) : const SizedBox(), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ (iconData == null) ? Text( value, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.normal, ), ) : Row( children: [ Text( value, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.normal, ), ), const SizedBox(width: 5), Icon( iconData, size: 16, color: ratingColor, ), ], ), (secondValue == null) ? const SizedBox() : Text( secondValue!, style: const TextStyle( fontSize: 14, fontWeight: FontWeight.normal, ), ), ], ), ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/openreads/lib/ui
mirrored_repositories/openreads/lib/ui/book_screen/book_screen.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/constants/enums/enums.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/cubit/current_book_cubit.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/model/reading.dart'; import 'package:openreads/ui/book_screen/widgets/widgets.dart'; class BookScreen extends StatelessWidget { const BookScreen({ super.key, required this.id, required this.heroTag, }); final int id; final String heroTag; _onLikeTap(BuildContext context, Book book) { book = book.copyWith(favourite: book.favourite == true ? false : true); bookCubit.updateBook(book); context.read<CurrentBookCubit>().setBook(book); } IconData? _decideStatusIcon(BookStatus? status) { if (status == BookStatus.read) { return Icons.done; } else if (status == BookStatus.inProgress) { return Icons.autorenew; } else if (status == BookStatus.forLater) { return Icons.timelapse; } else if (status == BookStatus.unfinished) { return Icons.not_interested; } else { return null; } } String _decideStatusText(BookStatus? status, BuildContext context) { if (status == BookStatus.read) { return LocaleKeys.book_status_finished.tr(); } else if (status == BookStatus.inProgress) { return LocaleKeys.book_status_in_progress.tr(); } else if (status == BookStatus.forLater) { return LocaleKeys.book_status_for_later.tr(); } else if (status == BookStatus.unfinished) { return LocaleKeys.book_status_unfinished.tr(); } else { return ''; } } String? _decideChangeStatusText(BookStatus? status, BuildContext context) { if (status == BookStatus.inProgress) { return LocaleKeys.finish_reading.tr(); } else if (status == BookStatus.forLater) { return LocaleKeys.start_reading.tr(); } else if (status == BookStatus.unfinished) { return LocaleKeys.start_reading.tr(); } else { return null; } } Future<int?> _getQuickRating(BuildContext context) async { late int? rating; await showDialog( context: context, builder: (BuildContext context) { return SimpleDialog( contentPadding: const EdgeInsets.all(20), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), title: Text( LocaleKeys.rate_book.tr(), style: const TextStyle(fontSize: 18), ), children: [ QuickRating( onRatingUpdate: (double newRating) { rating = (newRating * 10).toInt(); }, ), const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ FilledButton.tonal( onPressed: () { rating = null; Navigator.of(context).pop(); }, child: Text(LocaleKeys.skip.tr()), ), FilledButton( onPressed: () { Navigator.of(context).pop(); }, child: Text(LocaleKeys.save.tr()), ) ], ) ], ); }, ); return rating; } void _changeStatusAction( BuildContext context, BookStatus status, Book book, ) async { final dateNow = DateTime.now(); final date = DateTime(dateNow.year, dateNow.month, dateNow.day); // finishing the book if (status == BookStatus.inProgress) { final rating = await _getQuickRating(context); book = book.copyWith( status: BookStatus.read, rating: rating, readings: book.readings.isNotEmpty ? (book.readings..[0] = book.readings[0].copyWith(finishDate: date)) : [Reading(finishDate: date)], ); bookCubit.updateBook(book); // starting the book } else if (status == BookStatus.forLater) { book = book.copyWith( status: BookStatus.inProgress, readings: book.readings.isNotEmpty ? (book.readings..[0] = book.readings[0].copyWith(startDate: date)) : [Reading(startDate: date)], ); bookCubit.updateBook(book); // starting the book } else if (status == BookStatus.unfinished) { book = book.copyWith( status: BookStatus.inProgress, readings: book.readings.isNotEmpty ? (book.readings..[0] = book.readings[0].copyWith(startDate: date)) : [Reading(startDate: date)], ); bookCubit.updateBook(book); } if (!context.mounted) return; context.read<CurrentBookCubit>().setBook(book); } @override Widget build(BuildContext context) { final mediaQuery = MediaQuery.of(context); return SelectableRegion( selectionControls: materialTextSelectionControls, focusNode: FocusNode(), child: Scaffold( extendBodyBehindAppBar: true, appBar: const BookScreenAppBar(), body: BlocBuilder<CurrentBookCubit, Book>( builder: (context, state) { return SingleChildScrollView( child: Column( children: [ (state.hasCover == true) ? Center( child: CoverView( heroTag: heroTag, book: state, ), ) : SizedBox( height: mediaQuery.padding.top + AppBar().preferredSize.height, ), Padding( padding: const EdgeInsets.fromLTRB(5, 0, 5, 5), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ BookTitleDetail( title: state.title.toString(), subtitle: state.subtitle, author: state.author.toString(), publicationYear: (state.publicationYear ?? "").toString(), tags: state.tags?.split('|||||'), bookType: state.bookFormat, ), const SizedBox(height: 5), BookStatusDetail( book: state, statusIcon: _decideStatusIcon(state.status), statusText: _decideStatusText( state.status, context, ), onLikeTap: () => _onLikeTap(context, state), showChangeStatus: (state.status == BookStatus.inProgress || state.status == BookStatus.forLater || state.status == BookStatus.unfinished), changeStatusText: _decideChangeStatusText( state.status, context, ), changeStatusAction: () { _changeStatusAction( context, state.status, state, ); }, showRatingAndLike: state.status == BookStatus.read, ), SizedBox( height: (state.pages != null) ? 5 : 0, ), (state.pages != null) ? BookDetail( title: LocaleKeys.pages_uppercase.tr(), text: (state.pages ?? "").toString(), ) : const SizedBox(), SizedBox( height: (state.description != null && state.description!.isNotEmpty) ? 5 : 0, ), (state.description != null && state.description!.isNotEmpty) ? BookDetail( title: LocaleKeys.description.tr(), text: state.description!, ) : const SizedBox(), SizedBox( height: (state.isbn != null) ? 5 : 0, ), (state.isbn != null) ? BookDetail( title: LocaleKeys.isbn.tr(), text: (state.isbn ?? "").toString(), ) : const SizedBox(), SizedBox( height: (state.olid != null) ? 5 : 0, ), (state.olid != null) ? BookDetail( title: LocaleKeys.open_library_ID.tr(), text: (state.olid ?? "").toString(), ) : const SizedBox(), SizedBox( height: (state.myReview != null && state.myReview!.isNotEmpty) ? 5 : 0, ), (state.myReview != null && state.myReview!.isNotEmpty) ? BookDetail( title: LocaleKeys.my_review.tr(), text: state.myReview!, ) : const SizedBox(), SizedBox( height: (state.notes != null && state.notes!.isNotEmpty) ? 5 : 0, ), (state.notes != null && state.notes!.isNotEmpty) ? BookDetail( title: LocaleKeys.notes.tr(), text: state.notes!, ) : const SizedBox(), const SizedBox(height: 5), BookDetailDateAddedUpdated( dateAdded: state.dateAdded, dateModified: state.dateModified, ), const SizedBox(height: 50.0), ], ), ), ], ), ); }, ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/book_screen
mirrored_repositories/openreads/lib/ui/book_screen/widgets/cover_view.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/book_screen/widgets/widgets.dart'; class CoverView extends StatefulWidget { const CoverView({ super.key, this.heroTag, this.book, this.coverFile, this.blurHashString, }); final String? heroTag; final String? blurHashString; final Book? book; final File? coverFile; @override State<CoverView> createState() => _CoverViewState(); } class _CoverViewState extends State<CoverView> { File? coverFile; void _loadCoverFile() { if (widget.coverFile != null) { coverFile = widget.coverFile; } else if (widget.book != null) { coverFile = widget.book!.getCoverFile(); } } @override Widget build(BuildContext context) { _loadCoverFile(); final mediaQuery = MediaQuery.of(context); return Stack( children: [ SizedBox( width: mediaQuery.size.width, height: (mediaQuery.size.height / 2.5) + mediaQuery.padding.top, child: const Stack( children: [ CoverBackground(), ], ), ), Column( children: [ SizedBox(height: mediaQuery.padding.top), Center( child: SizedBox( height: mediaQuery.size.height / 2.5, child: Padding( padding: const EdgeInsets.fromLTRB(20, 0, 20, 20), child: Center( child: ClipRRect( borderRadius: BorderRadius.circular(cornerRadius), child: coverFile != null ? Hero( tag: widget.heroTag ?? "", child: Image.file( coverFile!, fit: BoxFit.cover, height: mediaQuery.size.height / 2.5, ), ) : const SizedBox(), ), ), ), ), ), const SizedBox(height: 10), ], ), ], ); } }
0
mirrored_repositories/openreads/lib/ui/book_screen
mirrored_repositories/openreads/lib/ui/book_screen/widgets/cover_background.dart
import 'package:blurhash_dart/blurhash_dart.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/logic/cubit/current_book_cubit.dart'; import 'package:openreads/model/book.dart'; import 'package:image/image.dart' as img; class CoverBackground extends StatelessWidget { const CoverBackground({super.key}); @override Widget build(BuildContext context) { return BlocBuilder<CurrentBookCubit, Book>( buildWhen: (previous, current) { return previous.blurHash != current.blurHash; }, builder: (context, state) { final image = BlurHash.decode(state.blurHash!).toImage(35, 20); return ClipRRect( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(cornerRadius), bottomRight: Radius.circular(cornerRadius), ), child: Image.memory( Uint8List.fromList( img.encodeJpg(image), ), fit: BoxFit.cover, width: MediaQuery.of(context).size.width, height: (MediaQuery.of(context).size.height / 2.5) + MediaQuery.of(context).padding.top, frameBuilder: ( BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded, ) { if (wasSynchronouslyLoaded) { return child; } return AnimatedOpacity( opacity: frame == null ? 0 : 0.8, duration: const Duration(milliseconds: 400), curve: Curves.easeIn, child: child, ); }, ), ); }, ); } }
0
mirrored_repositories/openreads/lib/ui/book_screen
mirrored_repositories/openreads/lib/ui/book_screen/widgets/book_status_detail.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/rating_type_bloc/rating_type_bloc.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/model/reading_time.dart'; class BookStatusDetail extends StatefulWidget { const BookStatusDetail({ super.key, required this.book, required this.statusIcon, required this.statusText, required this.onLikeTap, this.showChangeStatus = false, this.changeStatusText, this.changeStatusAction, this.showRatingAndLike = false, }); final Book book; final IconData? statusIcon; final String statusText; final Function() onLikeTap; final bool showChangeStatus; final String? changeStatusText; final Function()? changeStatusAction; final bool showRatingAndLike; @override State<BookStatusDetail> createState() => _BookStatusDetailState(); } class _BookStatusDetailState extends State<BookStatusDetail> { String _generateReadingTime({ DateTime? startDate, DateTime? finishDate, required BuildContext context, ReadingTime? readingTime, }) { if (readingTime != null) return '($readingTime)'; if (startDate == null || finishDate == null) return ''; final diff = finishDate.difference(startDate).inDays + 1; return '(${LocaleKeys.day.plural(diff).tr()})'; } Widget _buildLikeButton() { return Padding( padding: const EdgeInsets.only(right: 10, top: 0), child: GestureDetector( onTap: widget.onLikeTap, child: (widget.book.favourite) ? FaIcon( FontAwesomeIcons.solidHeart, size: 30, color: likeColor, ) : const FaIcon(FontAwesomeIcons.solidHeart, size: 30), ), ); } Widget _buildChangeStatusButton(BuildContext context) { return InkWell( onTap: widget.changeStatusAction, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), color: Theme.of(context).colorScheme.secondary, ), child: Padding( padding: const EdgeInsets.symmetric( vertical: 5, horizontal: 10, ), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ const SizedBox(height: 22), Text( widget.changeStatusText!, maxLines: 1, style: TextStyle( fontSize: 12, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.onSecondary, ), ), ], ), ), ), ), ); } @override Widget build(BuildContext context) { return Card( shadowColor: Colors.transparent, shape: RoundedRectangleBorder( side: BorderSide(color: dividerColor, width: 1), borderRadius: BorderRadius.circular(cornerRadius), ), child: Container( padding: const EdgeInsets.all(10), child: Column( children: [ const SizedBox(height: 5), Row( children: [ Expanded( child: Container( decoration: BoxDecoration( color: Theme.of(context).colorScheme.primary, borderRadius: BorderRadius.circular(cornerRadius), ), child: Padding( padding: const EdgeInsets.symmetric( vertical: 5, horizontal: 10, ), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( widget.statusIcon, size: 24, color: Theme.of(context).colorScheme.onPrimary, ), const SizedBox(width: 15), Text( widget.statusText, maxLines: 1, style: TextStyle( fontSize: 12, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.onPrimary, ), ), ], ), ), ), ), ), SizedBox(width: (widget.showChangeStatus) ? 10 : 0), (widget.showChangeStatus) ? _buildChangeStatusButton(context) : const SizedBox(), ], ), _generateHowManyTimesRead(context), SizedBox(height: (widget.showRatingAndLike) ? 10 : 0), (widget.showRatingAndLike) ? Column( children: [ Row( children: [ Text( LocaleKeys.your_rating.tr(), style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildRating(context), ], ), _buildLikeButton(), ], ), ], ) : const SizedBox(), const SizedBox(height: 10), ..._buildStartAndFinishDates(context), ], ), ), ); } Widget _buildRating(BuildContext context) { return BlocBuilder<RatingTypeBloc, RatingTypeState>( builder: (context, state) { if (state is RatingTypeBar) { return RatingBar.builder( initialRating: (widget.book.rating != null) ? widget.book.rating! / 10 : 0, allowHalfRating: true, unratedColor: Theme.of(context).scaffoldBackgroundColor, glow: false, itemSize: 45, ignoreGestures: true, itemBuilder: (context, _) => Icon( Icons.star_rounded, color: ratingColor, ), onRatingUpdate: (_) {}, ); } else { return Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( (widget.book.rating == null) ? '0' : '${(widget.book.rating! / 10)}', style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), const SizedBox(width: 5), Icon( Icons.star_rounded, color: ratingColor, size: 32, ), ], ); } }, ); } List<Widget> _buildStartAndFinishDates(BuildContext context) { final widgets = <Widget>[]; for (final reading in widget.book.readings) { late Widget widget; final startDate = reading.startDate; final finishDate = reading.finishDate; final readingTime = reading.customReadingTime; if (startDate != null && finishDate != null) { widget = _buildStartAndFinishDate( startDate, finishDate, readingTime, context, ); } else if (startDate == null && finishDate != null) { widget = _buildOnlyFinishDate( finishDate, readingTime, context, ); } else if (startDate != null && finishDate == null) { widget = _buildOnlyStartDate( startDate, context, ); } else { widget = const SizedBox(); } widgets.add( SizedBox( child: Row( children: [ Expanded(child: widget), ], ), ), ); } return widgets; } Widget _buildStartAndFinishDate( DateTime startDate, DateTime finishDate, ReadingTime? readingTime, BuildContext context, ) { final readingTimeText = ' ${_generateReadingTime( startDate: startDate, finishDate: finishDate, context: context, readingTime: readingTime, )}'; return RichText( selectionRegistrar: SelectionContainer.maybeOf(context), selectionColor: ThemeGetters.getSelectionColor(context), text: TextSpan( style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.onSurface, ), children: [ TextSpan( text: '${dateFormat.format(startDate)} - ${dateFormat.format(finishDate)}', ), TextSpan( text: readingTimeText, style: const TextStyle(fontWeight: FontWeight.normal), ), ], ), ); } Widget _buildOnlyFinishDate( DateTime finishDate, ReadingTime? readingTime, BuildContext context, ) { final readingTimeText = ' ${_generateReadingTime( startDate: null, finishDate: null, context: context, readingTime: readingTime, )}'; return RichText( selectionRegistrar: SelectionContainer.maybeOf(context), selectionColor: ThemeGetters.getSelectionColor(context), text: TextSpan( style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.onSurface, ), children: [ TextSpan( text: '${LocaleKeys.finished_on_date.tr()} ${dateFormat.format(finishDate)}', ), TextSpan( text: readingTimeText, style: const TextStyle(fontWeight: FontWeight.normal), ), ], ), ); } Widget _buildOnlyStartDate( DateTime startDate, BuildContext context, ) { return RichText( selectionRegistrar: SelectionContainer.maybeOf(context), selectionColor: ThemeGetters.getSelectionColor(context), text: TextSpan( style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.onSurface, ), children: [ TextSpan( text: '${LocaleKeys.started_on_date.tr()} ${dateFormat.format(startDate)}', ), ], ), ); } Widget _generateHowManyTimesRead(BuildContext context) { int timesRead = 0; for (final reading in widget.book.readings) { if (reading.finishDate != null) { timesRead++; } } return timesRead > 1 ? Padding( padding: const EdgeInsets.fromLTRB(0, 5, 0, 5), child: Text(LocaleKeys.read_x_times .plural(widget.book.readings.length) .tr()), ) : const SizedBox(); } }
0
mirrored_repositories/openreads/lib/ui/book_screen
mirrored_repositories/openreads/lib/ui/book_screen/widgets/book_screen_app_bar.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/logic/bloc/theme_bloc/theme_bloc.dart'; import 'package:openreads/logic/cubit/current_book_cubit.dart'; import 'package:openreads/logic/cubit/edit_book_cubit.dart'; import 'package:openreads/main.dart'; import 'package:openreads/model/book.dart'; import 'package:openreads/ui/add_book_screen/add_book_screen.dart'; class BookScreenAppBar extends StatelessWidget implements PreferredSizeWidget { const BookScreenAppBar({super.key}); static final _appBar = AppBar(); @override Size get preferredSize => _appBar.preferredSize; _showDeleteRestoreDialog( BuildContext context, bool deleted, bool? deletePermanently, Book book, ) { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(cornerRadius), ), title: Text( deleted ? deletePermanently == true ? LocaleKeys.delete_perm_question.tr() : LocaleKeys.delete_book_question.tr() : LocaleKeys.restore_book_question.tr(), style: const TextStyle(fontSize: 18), ), actionsAlignment: MainAxisAlignment.spaceBetween, actions: [ FilledButton.tonal( onPressed: () { Navigator.of(context).pop(); }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Text(LocaleKeys.no.tr()), ), ), FilledButton( onPressed: () { if (deletePermanently == true) { _deleteBookPermanently(book); } else { _changeDeleteStatus(deleted, book); } Navigator.of(context).pop(); Navigator.of(context).pop(); }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Text(LocaleKeys.yes.tr()), ), ), ], ); }); } Future<void> _changeDeleteStatus(bool deleted, Book book) async { await bookCubit.updateBook(book.copyWith( deleted: deleted, )); bookCubit.getDeletedBooks(); } _deleteBookPermanently(Book book) async { if (book.id != null) { await bookCubit.deleteBook(book.id!); } bookCubit.getDeletedBooks(); } @override Widget build(BuildContext context) { final moreButtonOptions = [ LocaleKeys.edit_book.tr(), LocaleKeys.duplicateBook.tr(), ]; // Needed to add BlocBuilder because the status bar was changing // to different color then in BooksScreen return BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { final themeMode = (state as SetThemeState).themeMode; return AppBar( backgroundColor: Colors.transparent, scrolledUnderElevation: 0, systemOverlayStyle: SystemUiOverlayStyle( statusBarColor: Colors.transparent, statusBarIconBrightness: themeMode == ThemeMode.system ? MediaQuery.platformBrightnessOf(context) == Brightness.dark ? Brightness.light : Brightness.dark : themeMode == ThemeMode.dark ? Brightness.light : Brightness.dark, ), actions: [ BlocBuilder<CurrentBookCubit, Book>( builder: (context, state) { if (moreButtonOptions.length == 2) { if (state.deleted == true) { moreButtonOptions.add(LocaleKeys.restore_book.tr()); moreButtonOptions.add( LocaleKeys.delete_permanently.tr(), ); } else { moreButtonOptions.add(LocaleKeys.delete_book.tr()); } } return PopupMenuButton<String>( onSelected: (_) {}, itemBuilder: (_) { return moreButtonOptions.map((String choice) { return PopupMenuItem<String>( value: choice, child: Text(choice), onTap: () async { context.read<EditBookCubit>().setBook(state); await Future.delayed(const Duration( milliseconds: 0, )); if (!context.mounted) return; if (choice == moreButtonOptions[0]) { Navigator.of(context).push( MaterialPageRoute( builder: (_) => const AddBookScreen( editingExistingBook: true, ), ), ); } else if (choice == moreButtonOptions[1]) { final cover = state.getCoverBytes(); context.read<EditBookCoverCubit>().setCover(cover); final newBook = state.copyWith( title: '${state.title} ${LocaleKeys.copyBook.tr()}', ); newBook.id = null; context.read<EditBookCubit>().setBook(newBook); context.read<EditBookCubit>().setHasCover(true); Navigator.of(context).push( MaterialPageRoute( builder: (_) => const AddBookScreen( duplicatingBook: true, ), ), ); } else if (choice == moreButtonOptions[2]) { if (state.deleted == false) { _showDeleteRestoreDialog( context, true, null, state); } else { _showDeleteRestoreDialog( context, false, null, state); } } else if (choice == moreButtonOptions[3]) { _showDeleteRestoreDialog( context, true, true, state, ); } }, ); }).toList(); }, ); }, ), ], ); }, ); } }
0
mirrored_repositories/openreads/lib/ui/book_screen
mirrored_repositories/openreads/lib/ui/book_screen/widgets/quick_rating.dart
import 'package:flutter/material.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:openreads/core/themes/app_theme.dart'; class QuickRating extends StatefulWidget { const QuickRating({ super.key, required this.onRatingUpdate, }); final Function(double) onRatingUpdate; @override State<QuickRating> createState() => _QuickRatingState(); } class _QuickRatingState extends State<QuickRating> { @override Widget build(BuildContext context) { return Container( width: double.infinity, clipBehavior: Clip.hardEdge, decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.5), borderRadius: BorderRadius.circular(cornerRadius), border: Border.all(color: dividerColor), ), child: Center( child: RatingBar.builder( initialRating: 0.0, allowHalfRating: true, glow: false, glowRadius: 1, itemSize: 42, itemPadding: const EdgeInsets.all(5), wrapAlignment: WrapAlignment.center, itemBuilder: (_, __) => Icon( Icons.star_rounded, color: ratingColor, ), onRatingUpdate: widget.onRatingUpdate, ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/book_screen
mirrored_repositories/openreads/lib/ui/book_screen/widgets/book_detail_date_added_updated.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:openreads/core/themes/app_theme.dart'; import 'package:openreads/generated/locale_keys.g.dart'; import 'package:openreads/main.dart'; class BookDetailDateAddedUpdated extends StatefulWidget { const BookDetailDateAddedUpdated({ super.key, required this.dateAdded, required this.dateModified, }); final DateTime dateAdded; final DateTime dateModified; @override State<BookDetailDateAddedUpdated> createState() => _BookDetailDateAddedUpdatedState(); } class _BookDetailDateAddedUpdatedState extends State<BookDetailDateAddedUpdated> { @override Widget build(BuildContext context) { return Card( shadowColor: Colors.transparent, shape: RoundedRectangleBorder( side: BorderSide(color: dividerColor, width: 1), borderRadius: BorderRadius.circular(cornerRadius), ), elevation: 0, child: Container( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( LocaleKeys.added_on.tr(), style: const TextStyle( fontSize: 12, fontWeight: FontWeight.normal, ), ), Text( '${dateFormat.format(widget.dateAdded)} ${widget.dateAdded.hour}:${widget.dateAdded.minute.toString().padLeft(2, '0')}', style: const TextStyle( fontSize: 14, fontWeight: FontWeight.normal, ), ), ], ), widget.dateAdded.millisecondsSinceEpoch != widget.dateModified.millisecondsSinceEpoch ? Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ const SizedBox(height: 10), Text( LocaleKeys.modified_on.tr(), style: const TextStyle( fontSize: 12, fontWeight: FontWeight.normal, ), ), Text( '${dateFormat.format(widget.dateModified)} ${widget.dateModified.hour}:${widget.dateModified.minute}', style: const TextStyle( fontSize: 14, fontWeight: FontWeight.normal, ), ), ], ) : const SizedBox(), ], ), ), ); } }
0
mirrored_repositories/openreads/lib/ui/book_screen
mirrored_repositories/openreads/lib/ui/book_screen/widgets/widgets.dart
export 'book_detail.dart'; export 'book_status_detail.dart'; export 'book_title_detail.dart'; export 'cover_view.dart'; export 'cover_background.dart'; export 'quick_rating.dart'; export 'book_screen_app_bar.dart'; export 'book_detail_date_added_updated.dart';
0