8 Commits

Author SHA1 Message Date
Rene Kievits
14ad880f79 fix error with browser view and levels 2025-11-02 19:53:10 +01:00
Rene Kievits
5f1b9ba12e finish v3 2025-11-02 19:00:17 +01:00
Rene Kievits
16da0f04ac possible to exclude levels and change how questions are served 2025-11-02 17:07:23 +01:00
Rene Kievits
e9f115a32a more cleanup and small fixes, new sound effects 2025-11-01 07:50:21 +01:00
Rene Kievits
d5ff5eb12f some cleanup and some fixes 2025-11-01 06:38:14 +01:00
732408997d Merge pull request 'themeing' (#7) from themeing into master
Reviewed-on: #7
2025-10-31 17:19:39 +01:00
Rene Kievits
de3501c3e4 themes and some refractoring 2025-10-31 17:18:33 +01:00
Rene Kievits
4eb488e28c themes 2025-10-31 13:40:14 +01:00
32 changed files with 2057 additions and 1074 deletions

Binary file not shown.

BIN
assets/sfx/correct.wav Normal file

Binary file not shown.

BIN
assets/sfx/incorrect.wav Normal file

Binary file not shown.

View File

@@ -1,24 +1,32 @@
import 'package:flutter/material.dart';
import 'package:hirameki_srs/src/models/theme_model.dart';
import 'package:hirameki_srs/src/services/vocab_deck_repository.dart';
import 'package:provider/provider.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'src/services/deck_repository.dart';
import 'src/screens/start_screen.dart';
import 'src/services/tts_service.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
try {
await dotenv.load(fileName: ".env");
} catch (e) {
// It's okay if the .env file is not found.
// This is expected in release builds.
}
} catch (_) {}
runApp(
MultiProvider(
providers: [
Provider<DeckRepository>(create: (_) => DeckRepository()),
Provider<VocabDeckRepository>(create: (_) => VocabDeckRepository()),
ChangeNotifierProvider<ThemeModel>(create: (_) => ThemeModel()),
Provider<TtsService>(
create: (_) {
final ttsService = TtsService();
ttsService.initTts();
return ttsService;
},
dispose: (_, ttsService) => ttsService.dispose(),
),
],
child: const WkApp(),
),
@@ -30,29 +38,15 @@ class WkApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hirameki SRS',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: const ColorScheme(
brightness: Brightness.dark,
primary: Color(0xFF90CAF9), // Light blue for primary elements
onPrimary: Colors.black,
secondary: Color(0xFFBBDEFB), // Slightly lighter blue for secondary elements
onSecondary: Colors.black,
tertiary: Color(0xFFA5D6A7), // Light green for success/correct states
onTertiary: Colors.black,
error: Color(0xFFEF9A9A), // Light red for error states
onError: Colors.black,
surface: Color(0xFF121212), // Very dark gray
onSurface: Colors.white,
surfaceContainer: Color(0xFF1E1E1E), // Slightly lighter dark gray
surfaceContainerHighest: Color(0xFF424242), // A distinct dark gray for surface variants
onSurfaceVariant: Colors.white70,
),
useMaterial3: true,
),
home: const StartScreen(),
return Consumer<ThemeModel>(
builder: (context, themeModel, child) {
return MaterialApp(
title: 'Hirameki SRS',
debugShowCheckedModeBanner: false,
theme: themeModel.currentTheme,
home: const StartScreen(),
);
},
);
}
}
}

View File

@@ -1,14 +1,24 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/subject.dart';
import '../models/kanji_item.dart';
import '../models/vocabulary_item.dart';
class WkClient {
final String apiKey;
final Map<String, String> headers;
final String base = 'https://api.wanikani.com/v2';
WkClient(this.apiKey) : headers = {'Authorization': 'Bearer $apiKey', 'Wanikani-Revision': '20170710', 'Accept': 'application/json'};
WkClient(this.apiKey)
: headers = {
'Authorization': 'Bearer $apiKey',
'Wanikani-Revision': '20170710',
'Accept': 'application/json',
};
Future<List<Map<String, dynamic>>> fetchAllAssignments({List<String>? subjectTypes}) async {
Future<List<Map<String, dynamic>>> fetchAllAssignments({
List<String>? subjectTypes,
}) async {
final out = <Map<String, dynamic>>[];
String url = '$base/assignments?page=1';
if (subjectTypes != null && subjectTypes.isNotEmpty) {
@@ -30,13 +40,15 @@ class WkClient {
return out;
}
Future<List<Map<String, dynamic>>> fetchAllSubjects({List<String>? types}) async {
Future<List<Map<String, dynamic>>> fetchAllSubjects({
List<String>? types,
}) async {
final out = <Map<String, dynamic>>[];
String url = '$base/subjects';
if (types != null && types.isNotEmpty) {
url += '?types=${types.join(',')}';
}
while (url.isNotEmpty) {
final resp = await http.get(Uri.parse(url), headers: headers);
if (resp.statusCode != 200) throw Exception('API ${resp.statusCode}');
@@ -56,7 +68,10 @@ class WkClient {
final out = <Map<String, dynamic>>[];
const batch = 100;
for (var i = 0; i < ids.length; i += batch) {
final chunk = ids.sublist(i, i + batch > ids.length ? ids.length : i + batch);
final chunk = ids.sublist(
i,
i + batch > ids.length ? ids.length : i + batch,
);
String url = '$base/subjects?ids=${chunk.join(',')}&page=1';
while (true) {
final resp = await http.get(Uri.parse(url), headers: headers);
@@ -73,4 +88,14 @@ class WkClient {
}
return out;
}
static Subject createSubjectFromMap(Map<String, dynamic> map) {
final String object = map['object'];
if (object == 'kanji') {
return KanjiItem.fromSubject(map);
} else if (object == 'vocabulary') {
return VocabularyItem.fromSubject(map);
}
throw Exception('Unknown subject type: $object');
}
}

View File

@@ -1,4 +1,3 @@
class CustomKanjiItem {
final String characters;
final String meaning;
@@ -25,7 +24,9 @@ class CustomKanjiItem {
srsData.listeningComprehensionNextReview ??= oldNextReview;
}
} else {
DateTime? nextReview = json['nextReview'] != null ? DateTime.parse(json['nextReview'] as String) : null;
DateTime? nextReview = json['nextReview'] != null
? DateTime.parse(json['nextReview'] as String)
: null;
srsData = SrsData(
japaneseToEnglish: json['srsLevel'] as int? ?? 0,
japaneseToEnglishNextReview: nextReview,
@@ -76,22 +77,32 @@ class SrsData {
factory SrsData.fromJson(Map<String, dynamic> json) {
return SrsData(
japaneseToEnglish: json['japaneseToEnglish'] as int? ?? 0,
japaneseToEnglishNextReview: json['japaneseToEnglishNextReview'] != null ? DateTime.parse(json['japaneseToEnglishNextReview'] as String) : null,
japaneseToEnglishNextReview: json['japaneseToEnglishNextReview'] != null
? DateTime.parse(json['japaneseToEnglishNextReview'] as String)
: null,
englishToJapanese: json['englishToJapanese'] as int? ?? 0,
englishToJapaneseNextReview: json['englishToJapaneseNextReview'] != null ? DateTime.parse(json['englishToJapaneseNextReview'] as String) : null,
englishToJapaneseNextReview: json['englishToJapaneseNextReview'] != null
? DateTime.parse(json['englishToJapaneseNextReview'] as String)
: null,
listeningComprehension: json['listeningComprehension'] as int? ?? 0,
listeningComprehensionNextReview: json['listeningComprehensionNextReview'] != null ? DateTime.parse(json['listeningComprehensionNextReview'] as String) : null,
listeningComprehensionNextReview:
json['listeningComprehensionNextReview'] != null
? DateTime.parse(json['listeningComprehensionNextReview'] as String)
: null,
);
}
Map<String, dynamic> toJson() {
return {
'japaneseToEnglish': japaneseToEnglish,
'japaneseToEnglishNextReview': japaneseToEnglishNextReview?.toIso8601String(),
'japaneseToEnglishNextReview': japaneseToEnglishNextReview
?.toIso8601String(),
'englishToJapanese': englishToJapanese,
'englishToJapaneseNextReview': englishToJapaneseNextReview?.toIso8601String(),
'englishToJapaneseNextReview': englishToJapaneseNextReview
?.toIso8601String(),
'listeningComprehension': listeningComprehension,
'listeningComprehensionNextReview': listeningComprehensionNextReview?.toIso8601String(),
'listeningComprehensionNextReview': listeningComprehensionNextReview
?.toIso8601String(),
};
}
}

View File

@@ -1,54 +1,24 @@
enum QuizMode { kanjiToEnglish, englishToKanji, reading }
import 'subject.dart';
class SrsItem {
final int kanjiId;
final QuizMode quizMode;
final String? readingType; // 'onyomi' or 'kunyomi'
int srsStage;
DateTime lastAsked;
SrsItem({
required this.kanjiId,
required this.quizMode,
this.readingType,
this.srsStage = 0,
DateTime? lastAsked,
}) : lastAsked = lastAsked ?? DateTime.now();
}
class KanjiItem {
final int id;
final int level;
final String characters;
final List<String> meanings;
class KanjiItem extends Subject {
final List<String> onyomi;
final List<String> kunyomi;
final Map<String, SrsItem> srsItems = {};
KanjiItem({
required this.id,
required this.level,
required this.characters,
required this.meanings,
required super.id,
required super.level,
required super.characters,
required super.meanings,
required this.onyomi,
required this.kunyomi,
});
factory KanjiItem.fromSubject(Map<String, dynamic> subj) {
final int id = subj['id'] as int;
final data = subj['data'] as Map<String, dynamic>;
final int level = data['level'] as int;
final String characters = (data['characters'] ?? '') as String;
final List<String> meanings = <String>[];
final commonFields = Subject.parseCommonFields(subj);
final data = commonFields['data'] as Map<String, dynamic>;
final List<String> onyomi = <String>[];
final List<String> kunyomi = <String>[];
if (data['meanings'] != null) {
for (final m in data['meanings'] as List) {
meanings.add((m['meaning'] as String).toLowerCase());
}
}
if (data['readings'] != null) {
for (final r in data['readings'] as List) {
final typ = r['type'] as String? ?? '';
@@ -62,10 +32,10 @@ class KanjiItem {
}
return KanjiItem(
id: id,
level: level,
characters: characters,
meanings: meanings,
id: commonFields['id'] as int,
level: commonFields['level'] as int,
characters: commonFields['characters'] as String,
meanings: commonFields['meanings'] as List<String>,
onyomi: onyomi,
kunyomi: kunyomi,
);
@@ -83,89 +53,3 @@ String _katakanaToHiragana(String input) {
}
return buf.toString();
}
enum VocabQuizMode { vocabToEnglish, englishToVocab, audioToEnglish }
class VocabSrsItem {
final int vocabId;
final VocabQuizMode quizMode;
int srsStage;
DateTime lastAsked;
VocabSrsItem({
required this.vocabId,
required this.quizMode,
this.srsStage = 0,
DateTime? lastAsked,
}) : lastAsked = lastAsked ?? DateTime.now();
}
class PronunciationAudio {
final String url;
final String gender;
PronunciationAudio({required this.url, required this.gender});
}
class VocabularyItem {
final int id;
final int level;
final String characters;
final List<String> meanings;
final List<String> readings;
final List<PronunciationAudio> pronunciationAudios;
final Map<String, VocabSrsItem> srsItems = {};
VocabularyItem(
{required this.id,
required this.level,
required this.characters,
required this.meanings,
required this.readings,
required this.pronunciationAudios});
factory VocabularyItem.fromSubject(Map<String, dynamic> subj) {
final int id = subj['id'] as int;
final data = subj['data'] as Map<String, dynamic>;
final int level = data['level'] as int;
final String characters = (data['characters'] ?? '') as String;
final List<String> meanings = <String>[];
final List<String> readings = <String>[];
final List<PronunciationAudio> pronunciationAudios = <PronunciationAudio>[];
if (data['meanings'] != null) {
for (final m in data['meanings'] as List) {
meanings.add((m['meaning'] as String).toLowerCase());
}
}
if (data['readings'] != null) {
for (final r in data['readings'] as List) {
readings.add(r['reading'] as String);
}
}
if (data['pronunciation_audios'] != null) {
for (final audio in data['pronunciation_audios'] as List) {
final url = audio['url'] as String?;
final metadata = audio['metadata'] as Map<String, dynamic>?;
final gender = metadata?['gender'] as String?;
if (url != null && gender != null) {
pronunciationAudios.add(PronunciationAudio(
url: url,
gender: gender,
));
}
}
}
return VocabularyItem(
id: id,
level: level,
characters: characters,
meanings: meanings,
readings: readings,
pronunciationAudios: pronunciationAudios);
}
}

View File

@@ -0,0 +1,19 @@
enum QuizMode { kanjiToEnglish, englishToKanji, reading, vocabToEnglish, englishToVocab, audioToEnglish }
class SrsItem {
final int subjectId;
final QuizMode quizMode;
final String? readingType;
int srsStage;
DateTime lastAsked;
bool disabled;
SrsItem({
required this.subjectId,
required this.quizMode,
this.readingType,
this.srsStage = 0,
DateTime? lastAsked,
this.disabled = false,
}) : lastAsked = lastAsked ?? DateTime.now();
}

View File

@@ -0,0 +1,38 @@
import 'srs_item.dart';
abstract class Subject {
final int id;
final int level;
final String characters;
final List<String> meanings;
final Map<String, SrsItem> srsItems = {};
Subject({
required this.id,
required this.level,
required this.characters,
required this.meanings,
});
static Map<String, dynamic> parseCommonFields(Map<String, dynamic> subj) {
final int id = subj['id'] as int;
final data = subj['data'] as Map<String, dynamic>;
final int level = data['level'] as int;
final String characters = (data['characters'] ?? '') as String;
final List<String> meanings = <String>[];
if (data['meanings'] != null) {
for (final m in data['meanings'] as List) {
meanings.add((m['meaning'] as String).toLowerCase());
}
}
return {
'id': id,
'level': level,
'characters': characters,
'meanings': meanings,
'data': data,
};
}
}

View File

@@ -0,0 +1,15 @@
import 'kanji_item.dart';
import 'vocabulary_item.dart';
import 'subject.dart';
class SubjectFactory {
static Subject fromMap(Map<String, dynamic> map) {
final String object = map['object'];
if (object == 'kanji') {
return KanjiItem.fromSubject(map);
} else if (object == 'vocabulary') {
return VocabularyItem.fromSubject(map);
}
throw Exception('Unknown subject type: $object');
}
}

View File

@@ -0,0 +1,13 @@
import 'package:flutter/material.dart';
import 'package:hirameki_srs/src/themes.dart';
class ThemeModel extends ChangeNotifier {
ThemeData _currentTheme = Themes.dark;
ThemeData get currentTheme => _currentTheme;
void setTheme(ThemeData theme) {
_currentTheme = theme;
notifyListeners();
}
}

View File

@@ -0,0 +1,56 @@
import 'subject.dart';
class PronunciationAudio {
final String url;
final String gender;
PronunciationAudio({required this.url, required this.gender});
}
class VocabularyItem extends Subject {
final List<String> readings;
final List<PronunciationAudio> pronunciationAudios;
VocabularyItem({
required super.id,
required super.level,
required super.characters,
required super.meanings,
required this.readings,
required this.pronunciationAudios,
});
factory VocabularyItem.fromSubject(Map<String, dynamic> subj) {
final commonFields = Subject.parseCommonFields(subj);
final data = commonFields['data'] as Map<String, dynamic>;
final List<String> readings = <String>[];
final List<PronunciationAudio> pronunciationAudios = <PronunciationAudio>[];
if (data['readings'] != null) {
for (final r in data['readings'] as List) {
readings.add(r['reading'] as String);
}
}
if (data['pronunciation_audios'] != null) {
for (final audio in data['pronunciation_audios'] as List) {
final url = audio['url'] as String?;
final metadata = audio['metadata'] as Map<String, dynamic>?;
final gender = metadata?['gender'] as String?;
if (url != null && gender != null) {
pronunciationAudios.add(PronunciationAudio(url: url, gender: gender));
}
}
}
return VocabularyItem(
id: commonFields['id'] as int,
level: commonFields['level'] as int,
characters: commonFields['characters'] as String,
meanings: commonFields['meanings'] as List<String>,
readings: readings,
pronunciationAudios: pronunciationAudios,
);
}
}

View File

@@ -1,4 +1,3 @@
import 'package:flutter/material.dart';
import 'package:kana_kit/kana_kit.dart';
import '../models/custom_kanji_item.dart';
@@ -19,11 +18,14 @@ class _AddCardScreenState extends State<AddCardScreen> {
final _kanaKit = const KanaKit();
final _deckRepository = CustomDeckRepository();
bool _useInterval = false;
late FocusNode _japaneseFocusNode;
@override
void initState() {
super.initState();
_japaneseController.addListener(_convertToKana);
_japaneseFocusNode = FocusNode();
_japaneseFocusNode.addListener(_onJapaneseFocusChange);
}
@override
@@ -32,13 +34,24 @@ class _AddCardScreenState extends State<AddCardScreen> {
_japaneseController.dispose();
_englishController.dispose();
_kanjiController.dispose();
_japaneseFocusNode.removeListener(_onJapaneseFocusChange);
_japaneseFocusNode.dispose();
super.dispose();
}
void _convertToKana() {
final text = _japaneseController.text;
final selection = _japaneseController.selection;
final offset = selection.baseOffset;
if ((offset > 1 && text[offset - 1] == 'n' && text[offset - 2] != 'n') ||
(offset == 1 && text[offset - 1] == 'n')) {
return;
}
final converted = _kanaKit.toKana(text);
if (text != converted) {
if (converted != text) {
_japaneseController.value = _japaneseController.value.copyWith(
text: converted,
selection: TextSelection.fromPosition(
@@ -48,6 +61,21 @@ class _AddCardScreenState extends State<AddCardScreen> {
}
}
void _onJapaneseFocusChange() {
if (!_japaneseFocusNode.hasFocus) {
_forceNConversion();
}
}
void _forceNConversion() {
final text = _japaneseController.text;
if (text.isNotEmpty &&
text.endsWith('n') &&
_kanaKit.toKana(text) != text) {
_japaneseController.text = _kanaKit.toKana(text);
}
}
void _saveCard() {
if (_formKey.currentState!.validate()) {
final srsData = _useInterval
@@ -61,7 +89,9 @@ class _AddCardScreenState extends State<AddCardScreen> {
final newItem = CustomKanjiItem(
characters: _japaneseController.text,
meaning: _englishController.text,
kanji: _kanjiController.text.trim().isNotEmpty ? _kanjiController.text.trim() : null,
kanji: _kanjiController.text.trim().isNotEmpty
? _kanjiController.text.trim()
: null,
useInterval: _useInterval,
srsData: srsData,
);
@@ -73,9 +103,7 @@ class _AddCardScreenState extends State<AddCardScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Add New Card'),
),
appBar: AppBar(title: const Text('Add New Card')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
@@ -84,6 +112,7 @@ class _AddCardScreenState extends State<AddCardScreen> {
children: [
TextFormField(
controller: _japaneseController,
focusNode: _japaneseFocusNode,
decoration: const InputDecoration(
labelText: 'Japanese (Kana)',
hintText: 'Enter Japanese vocabulary or kanji',

View File

@@ -1,8 +1,11 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:hirameki_srs/src/themes.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;
import '../models/kanji_item.dart';
import '../models/vocabulary_item.dart';
import '../models/srs_item.dart';
import '../services/deck_repository.dart';
import 'package:hirameki_srs/src/services/vocab_deck_repository.dart';
import '../services/custom_deck_repository.dart';
@@ -18,7 +21,8 @@ class BrowseScreen extends StatefulWidget {
State<BrowseScreen> createState() => _BrowseScreenState();
}
class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderStateMixin {
class _BrowseScreenState extends State<BrowseScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
late PageController _kanjiPageController;
late PageController _vocabPageController;
@@ -50,7 +54,7 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
_vocabPageController = PageController();
_tabController.addListener(() {
setState(() {}); // Rebuild to update the level selector
setState(() {});
});
_kanjiPageController.addListener(() {
@@ -94,13 +98,17 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('WaniKani API key is not set.', style: TextStyle(color: Colors.white)),
Text(
'WaniKani API key is not set.',
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () async {
await Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const SettingsScreen()),
);
if (!mounted) return;
_loadDecks();
},
child: const Text('Go to Settings'),
@@ -115,9 +123,14 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(color: Colors.blueAccent),
CircularProgressIndicator(
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(height: 16),
Text(_status, style: const TextStyle(color: Colors.white)),
Text(
_status,
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
),
],
),
);
@@ -128,22 +141,29 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
Widget _buildCustomSrsTab() {
if (_customDeck.isEmpty) {
return const Center(
child: Text('No custom cards yet.', style: TextStyle(color: Colors.white)),
return Center(
child: Text(
'No custom cards yet.',
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
),
);
}
return _buildCustomGridView(_customDeck);
}
Widget _buildPaginatedView(
Map<int, List<dynamic>> groupedItems,
List<int> sortedLevels,
PageController pageController,
Widget Function(List<dynamic>) buildPageContent) {
Map<int, List<dynamic>> groupedItems,
List<int> sortedLevels,
PageController pageController,
Widget Function(List<dynamic>) buildPageContent,
dynamic repository,
) {
if (sortedLevels.isEmpty) {
return const Center(
child:
Text('No items to display.', style: TextStyle(color: Colors.white)),
return Center(
child: Text(
'No items to display.',
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
),
);
}
@@ -153,17 +173,45 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
itemBuilder: (context, index) {
final level = sortedLevels[index];
final levelItems = groupedItems[level]!;
final bool isDisabled;
if (repository is DeckRepository) {
isDisabled = levelItems.every(
(item) => (item as KanjiItem).srsItems.values.isNotEmpty && (item as KanjiItem).srsItems.values.cast<SrsItem>().every(
(srs) => srs.disabled,
),
);
} else if (repository is VocabDeckRepository) {
isDisabled = levelItems.every(
(item) => (item as VocabularyItem).srsItems.values.isNotEmpty && (item as VocabularyItem).srsItems.values.cast<SrsItem>().every(
(srs) => srs.disabled,
),
);
} else {
isDisabled = false; // Default to false if repository type is unknown
}
return Column(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'Level $level',
style: const TextStyle(
fontSize: 24,
color: Colors.white,
fontWeight: FontWeight.bold),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Level $level',
style: TextStyle(
fontSize: 24,
color: Theme.of(context).colorScheme.onSurface,
fontWeight: FontWeight.bold,
),
),
Checkbox(
value: !isDisabled,
onChanged: (value) {
_toggleLevelExclusion(level, repository, index, pageController);
},
),
],
),
),
Expanded(child: buildPageContent(levelItems)),
@@ -183,32 +231,68 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
return Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
color: const Color(0xFF1F1F1F),
height: 60,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(levels.length, (index) {
final level = levels[index];
final isSelected = index == currentPage;
return Padding(
color: Theme.of(context).colorScheme.surfaceContainer,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: List.generate(levels.length, (index) {
final level = levels[index];
final isSelected = index == currentPage;
final items = isKanji ? _kanjiByLevel[level] : _vocabByLevel[level];
final bool isDisabled;
if (isKanji) {
isDisabled = items?.every(
(item) => (item as KanjiItem).srsItems.values.isNotEmpty && (item as KanjiItem).srsItems.values.cast<SrsItem>().every(
(srs) => srs.disabled,
), ) ??
false;
} else {
isDisabled = items?.every(
(item) => (item as VocabularyItem).srsItems.values.isNotEmpty && (item as VocabularyItem).srsItems.values.cast<SrsItem>().every(
(srs) => srs.disabled,
), ) ??
false;
}
return Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4.0),
child: ElevatedButton(
onPressed: () {
controller.animateToPage(index, duration: const Duration(milliseconds: 300), curve: Curves.easeInOut);
controller.animateToPage(
index,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
},
style: ElevatedButton.styleFrom(
backgroundColor: isSelected ? Colors.blueAccent : const Color(0xFF333333),
foregroundColor: Colors.white,
shape: const CircleBorder(),
backgroundColor: isSelected
? Theme.of(context).colorScheme.primary
: isDisabled
? Theme.of(context).colorScheme.surfaceContainerHighest
: Theme.of(context).colorScheme.surfaceContainerHighest,
foregroundColor: isSelected
? Theme.of(context).colorScheme.onPrimary
: isDisabled
? Theme.of(context).colorScheme.onSurfaceVariant
: Theme.of(context).colorScheme.onSurface,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
padding: const EdgeInsets.all(12),
),
child: Text(level.toString()),
),
);
}),
),
),
);
}),
),
);
}
@@ -245,9 +329,9 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
Widget _buildVocabListTile(VocabularyItem item) {
final requiredModes = <String>[
VocabQuizMode.vocabToEnglish.toString(),
VocabQuizMode.englishToVocab.toString(),
VocabQuizMode.audioToEnglish.toString(),
QuizMode.vocabToEnglish.toString(),
QuizMode.englishToVocab.toString(),
QuizMode.audioToEnglish.toString(),
];
int minSrsStage = 9;
@@ -266,7 +350,7 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
return GestureDetector(
onTap: () => _showVocabDetailsDialog(context, item),
child: Card(
color: const Color(0xFF1E1E1E),
color: Theme.of(context).colorScheme.surfaceContainer,
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Padding(
padding: const EdgeInsets.all(12.0),
@@ -275,7 +359,10 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
Expanded(
child: Text(
item.characters,
style: const TextStyle(fontSize: 24, color: Colors.white),
style: TextStyle(
fontSize: 24,
color: Theme.of(context).colorScheme.onSurface,
),
),
),
const SizedBox(width: 16),
@@ -286,7 +373,9 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
children: [
Text(
item.meanings.join(', '),
style: const TextStyle(color: Colors.grey),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 8),
@@ -327,7 +416,7 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
}
return Card(
color: const Color(0xFF1E1E1E),
color: Theme.of(context).colorScheme.surfaceContainer,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
@@ -335,7 +424,10 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
children: [
Text(
item.characters,
style: const TextStyle(fontSize: 32, color: Colors.white),
style: TextStyle(
fontSize: 32,
color: Theme.of(context).colorScheme.onSurface,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
@@ -354,8 +446,10 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
child: SizedBox(
height: 10,
child: LinearProgressIndicator(
value: level / 9.0, // Max SRS level is 9
backgroundColor: Colors.grey[800],
value: level / 9.0,
backgroundColor: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
valueColor: AlwaysStoppedAnimation<Color>(
_getColorForSrsLevel(level),
),
@@ -366,13 +460,17 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
}
Color _getColorForSrsLevel(int level) {
if (level >= 9) return Colors.purple;
if (level >= 8) return Colors.blue;
if (level >= 7) return Colors.lightBlue;
if (level >= 5) return Colors.green;
if (level >= 3) return Colors.yellow;
if (level >= 1) return Colors.orange;
return Colors.red;
final srsColors = Theme.of(context).srsColors;
if (level >= 9) return srsColors.level9;
if (level >= 8) return srsColors.level8;
if (level >= 7) return srsColors.level7;
if (level >= 6) return srsColors.level6;
if (level >= 5) return srsColors.level5;
if (level >= 4) return srsColors.level4;
if (level >= 3) return srsColors.level3;
if (level >= 2) return srsColors.level2;
if (level >= 1) return srsColors.level1;
return Colors.grey;
}
void _showReadingsDialog(KanjiItem kanji) {
@@ -399,17 +497,19 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
srsScores['Reading (kunyomi)'] = srsItem.srsStage;
}
break;
default:
break;
}
}
showDialog(
context: context,
builder: (context) {
builder: (dialogContext) {
return AlertDialog(
backgroundColor: const Color(0xFF1E1E1E),
backgroundColor: Theme.of(context).colorScheme.surfaceContainer,
title: Text(
'Details for ${kanji.characters}',
style: const TextStyle(color: Colors.white),
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
),
content: SingleChildScrollView(
child: Column(
@@ -418,50 +518,68 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
children: [
Text(
'Level: ${kanji.level}',
style: const TextStyle(color: Colors.white),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
const SizedBox(height: 16),
if (kanji.meanings.isNotEmpty)
Text(
'Meanings: ${kanji.meanings.join(', ')}',
style: const TextStyle(color: Colors.white),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
const SizedBox(height: 16),
if (kanji.onyomi.isNotEmpty)
Text(
'On\'yomi: ${kanji.onyomi.join(', ')}',
style: const TextStyle(color: Colors.white),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
if (kanji.kunyomi.isNotEmpty)
Text(
'Kun\'yomi: ${kanji.kunyomi.join(', ')}',
style: const TextStyle(color: Colors.white),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
if (kanji.onyomi.isEmpty && kanji.kunyomi.isEmpty)
const Text(
Text(
'No readings available.',
style: TextStyle(color: Colors.white),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
const SizedBox(height: 16),
const Divider(color: Colors.grey),
Divider(color: Theme.of(context).colorScheme.onSurfaceVariant),
const SizedBox(height: 16),
const Text(
Text(
'SRS Scores:',
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
color: Theme.of(context).colorScheme.onSurface,
fontWeight: FontWeight.bold,
),
),
...srsScores.entries.map(
(entry) => Text(
' ${entry.key}: ${entry.value}',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
),
...srsScores.entries.map((entry) => Text(
' ${entry.key}: ${entry.value}',
style: const TextStyle(color: Colors.white),
)),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close',
style: TextStyle(color: Colors.blueAccent)),
onPressed: () => Navigator.of(dialogContext).pop(),
child: Text(
'Close',
style: TextStyle(color: Theme.of(context).colorScheme.primary),
),
),
],
);
@@ -473,8 +591,10 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
setState(() => _loading = true);
try {
final kanjiRepo = Provider.of<DeckRepository>(context, listen: false);
final vocabRepo =
Provider.of<VocabDeckRepository>(context, listen: false);
final vocabRepo = Provider.of<VocabDeckRepository>(
context,
listen: false,
);
await kanjiRepo.loadApiKey();
final apiKey = kanjiRepo.apiKey;
@@ -534,12 +654,112 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
_vocabSortedLevels = _vocabByLevel.keys.toList()..sort();
}
Future<void> _toggleLevelExclusion(
int level,
dynamic repository,
int currentPageIndex,
PageController pageController,
) async {
final List<SrsItem> itemsToUpdate = [];
List<dynamic> items = [];
bool currentlyDisabled = false;
if (repository is DeckRepository) {
items = _kanjiByLevel[level] ?? [];
currentlyDisabled = items.every(
(item) => (item as KanjiItem).srsItems.values.isNotEmpty && (item as KanjiItem).srsItems.values.cast<SrsItem>().every((srs) => srs.disabled),
);
for (final item in items) {
for (final srsItem in item.srsItems.values) {
itemsToUpdate.add(srsItem);
}
}
} else if (repository is VocabDeckRepository) {
items = _vocabByLevel[level] ?? [];
currentlyDisabled = items.every(
(item) => (item as VocabularyItem).srsItems.values.isNotEmpty && (item as VocabularyItem).srsItems.values.cast<SrsItem>().every((srs) => srs.disabled),
);
for (final item in items) {
for (final srsItem in item.srsItems.values) {
itemsToUpdate.add(srsItem);
}
}
} else {
return;
}
if (itemsToUpdate.isEmpty) {
// No SrsItems exist for this level, so create them and set their disabled status
for (final item in items) { // 'items' contains KanjiItem or VocabularyItem
// Determine quiz modes based on repository type
List<QuizMode> quizModes = [];
if (repository is DeckRepository) {
quizModes = [QuizMode.kanjiToEnglish, QuizMode.englishToKanji, QuizMode.reading];
} else if (repository is VocabDeckRepository) {
quizModes = [QuizMode.vocabToEnglish, QuizMode.englishToVocab, QuizMode.audioToEnglish];
}
for (final mode in quizModes) {
String? readingType;
if (mode == QuizMode.reading && repository is DeckRepository) {
// For reading mode, create SrsItems for both onyomi and kunyomi if they exist
if ((item as KanjiItem).onyomi.isNotEmpty) {
readingType = 'onyomi';
itemsToUpdate.add(SrsItem(
subjectId: item.id,
quizMode: mode,
readingType: readingType,
disabled: !currentlyDisabled,
));
}
if ((item as KanjiItem).kunyomi.isNotEmpty) {
readingType = 'kunyomi';
itemsToUpdate.add(SrsItem(
subjectId: item.id,
quizMode: mode,
readingType: readingType,
disabled: !currentlyDisabled,
));
}
} else {
itemsToUpdate.add(SrsItem(
subjectId: item.id,
quizMode: mode,
disabled: !currentlyDisabled,
));
}
}
}
// Now insert these newly created SrsItems
if (repository is DeckRepository) {
for (final srsItem in itemsToUpdate) {
await (repository as DeckRepository).insertSrsItem(srsItem);
}
} else if (repository is VocabDeckRepository) {
for (final srsItem in itemsToUpdate) {
await (repository as VocabDeckRepository).insertVocabSrsItem(srsItem);
}
}
} else {
// Existing SrsItems, so update them
for (final item in itemsToUpdate) {
item.disabled = !currentlyDisabled;
}
await repository.updateSrsItems(itemsToUpdate);
}
setState(() {});
if (pageController.hasClients) {
pageController.jumpToPage(currentPageIndex);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:
_isSelectionMode ? _buildSelectionAppBar() : _buildDefaultAppBar(),
backgroundColor: const Color(0xFF121212),
appBar: _isSelectionMode
? _buildSelectionAppBar()
: _buildDefaultAppBar(),
body: Column(
children: [
Expanded(
@@ -548,18 +768,21 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
children: [
_buildWaniKaniTab(
_buildPaginatedView(
_kanjiByLevel,
_kanjiSortedLevels,
_kanjiPageController,
(items) => _buildGridView(items.cast<KanjiItem>())),
_kanjiByLevel,
_kanjiSortedLevels,
_kanjiPageController,
(items) => _buildGridView(items.cast<KanjiItem>()),
Provider.of<DeckRepository>(context, listen: false),
),
),
_buildWaniKaniTab(
_buildPaginatedView(
_vocabByLevel,
_vocabSortedLevels,
_vocabPageController,
(items) =>
_buildListView(items.cast<VocabularyItem>())),
_vocabByLevel,
_vocabSortedLevels,
_vocabPageController,
(items) => _buildListView(items.cast<VocabularyItem>()),
Provider.of<VocabDeckRepository>(context, listen: false),
),
),
_buildCustomSrsTab(),
],
@@ -577,9 +800,10 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
floatingActionButton: _tabController.index == 2
? FloatingActionButton(
onPressed: () async {
await Navigator.of(context).push(
MaterialPageRoute(builder: (_) => AddCardScreen()),
);
await Navigator.of(
context,
).push(MaterialPageRoute(builder: (_) => AddCardScreen()));
if (!mounted) return;
_loadCustomDeck();
},
child: const Icon(Icons.add),
@@ -615,14 +839,8 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
),
title: Text('${_selectedItems.length} selected'),
actions: [
IconButton(
icon: const Icon(Icons.select_all),
onPressed: _selectAll,
),
IconButton(
icon: const Icon(Icons.delete),
onPressed: _deleteSelected,
),
IconButton(icon: const Icon(Icons.select_all), onPressed: _selectAll),
IconButton(icon: const Icon(Icons.delete), onPressed: _deleteSelected),
IconButton(
icon: Icon(_toggleIntervalIcon),
onPressed: _toggleIntervalForSelected,
@@ -652,28 +870,30 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
void _deleteSelected() {
showDialog(
context: context,
builder: (context) => AlertDialog(
builder: (dialogContext) => AlertDialog(
title: const Text('Delete Selected'),
content:
Text('Are you sure you want to delete ${_selectedItems.length} cards?'),
content: Text(
'Are you sure you want to delete ${_selectedItems.length} cards?',
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('Cancel'),
),
TextButton(
onPressed: () async {
final navigator = Navigator.of(context);
for (final item in _selectedItems) {
await _customDeckRepository.deleteCard(item);
}
setState(() {
_isSelectionMode = false;
_selectedItems.clear();
});
await _loadCustomDeck();
if (!mounted) return;
navigator.pop();
onPressed: () {
Navigator.of(dialogContext).pop();
() async {
for (final item in _selectedItems) {
await _customDeckRepository.deleteCard(item);
}
if (!mounted) return;
setState(() {
_isSelectionMode = false;
_selectedItems.clear();
});
_loadCustomDeck();
}();
},
child: const Text('Delete'),
),
@@ -688,8 +908,9 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
}
final bool targetState = _selectedItems.any((item) => !item.useInterval);
final selectedCharacters =
_selectedItems.map((item) => item.characters).toSet();
final selectedCharacters = _selectedItems
.map((item) => item.characters)
.toSet();
final List<CustomKanjiItem> updatedItems = [];
for (final item in _selectedItems) {
@@ -765,13 +986,18 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
child: Card(
shape: RoundedRectangleBorder(
side: isSelected
? const BorderSide(color: Colors.blue, width: 2.0)
? BorderSide(
color: Theme.of(context).colorScheme.primary,
width: 2.0,
)
: BorderSide.none,
borderRadius: BorderRadius.circular(12.0),
),
color: isSelected
? Colors.blue.withAlpha((255 * 0.5).round())
: const Color(0xFF1E1E1E),
? Theme.of(
context,
).colorScheme.primary.withAlpha((255 * 0.5).round())
: Theme.of(context).colorScheme.surfaceContainer,
child: Stack(
children: [
Padding(
@@ -785,27 +1011,34 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
item.kanji?.isNotEmpty == true
? item.kanji!
: item.characters,
style:
const TextStyle(fontSize: 32, color: Colors.white),
style: TextStyle(
fontSize: 32,
color: Theme.of(context).colorScheme.onSurface,
),
textAlign: TextAlign.center,
),
),
const SizedBox(height: 8),
Text(
item.meaning,
style:
const TextStyle(color: Colors.grey, fontSize: 16),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontSize: 16,
),
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 8),
Builder(builder: (context) {
final avgSrs = (item.srsData.japaneseToEnglish +
item.srsData.englishToJapanese +
item.srsData.listeningComprehension) /
3;
return _buildSrsIndicator(avgSrs.round());
}),
Builder(
builder: (context) {
final avgSrs =
(item.srsData.japaneseToEnglish +
item.srsData.englishToJapanese +
item.srsData.listeningComprehension) /
3;
return _buildSrsIndicator(avgSrs.round());
},
),
],
),
),
@@ -815,7 +1048,7 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
right: 4,
child: Icon(
Icons.timer,
color: Colors.green,
color: Theme.of(context).colorScheme.tertiary,
size: 16,
),
),
@@ -831,8 +1064,9 @@ class _BrowseScreenState extends State<BrowseScreen> with SingleTickerProviderSt
class _VocabDetailsDialog extends StatefulWidget {
final VocabularyItem vocab;
final ThemeData theme;
const _VocabDetailsDialog({required this.vocab});
const _VocabDetailsDialog({required this.vocab, required this.theme});
@override
State<_VocabDetailsDialog> createState() => _VocabDetailsDialogState();
@@ -850,7 +1084,8 @@ class _VocabDetailsDialogState extends State<_VocabDetailsDialog> {
Future<void> _fetchExampleSentences() async {
try {
final uri = Uri.parse(
'https://jisho.org/api/v1/search/words?keyword=${Uri.encodeComponent(widget.vocab.characters)}');
'https://jisho.org/api/v1/search/words?keyword=${Uri.encodeComponent(widget.vocab.characters)}',
);
final response = await http.get(uri);
if (response.statusCode == 200) {
final data = jsonDecode(utf8.decode(response.bodyBytes));
@@ -861,15 +1096,28 @@ class _VocabDetailsDialogState extends State<_VocabDetailsDialog> {
(result['japanese'] as List).isNotEmpty &&
result['senses'] != null &&
(result['senses'] as List).isNotEmpty) {
final japaneseWord = result['japanese'][0]['word'] ?? result['japanese'][0]['reading'];
final englishDefinition = result['senses'][0]['english_definitions'].join(', ');
final japaneseWord =
result['japanese'][0]['word'] ??
result['japanese'][0]['reading'];
final englishDefinition =
result['senses'][0]['english_definitions'].join(', ');
if (japaneseWord != null && englishDefinition != null) {
sentences.add(
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(japaneseWord, style: const TextStyle(color: Colors.white)),
Text(englishDefinition, style: const TextStyle(color: Colors.grey)),
Text(
japaneseWord,
style: TextStyle(
color: widget.theme.colorScheme.onSurface,
),
),
Text(
englishDefinition,
style: TextStyle(
color: widget.theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 8),
],
),
@@ -879,7 +1127,12 @@ class _VocabDetailsDialogState extends State<_VocabDetailsDialog> {
}
}
if (sentences.isEmpty) {
sentences.add(const Text('No example sentences found.', style: TextStyle(color: Colors.white)));
sentences.add(
Text(
'No example sentences found.',
style: TextStyle(color: widget.theme.colorScheme.onSurface),
),
);
}
if (mounted) {
setState(() {
@@ -890,7 +1143,10 @@ class _VocabDetailsDialogState extends State<_VocabDetailsDialog> {
if (mounted) {
setState(() {
_exampleSentences = [
const Text('Failed to load example sentences.', style: TextStyle(color: Colors.red))
Text(
'Failed to load example sentences.',
style: TextStyle(color: widget.theme.colorScheme.error),
),
];
});
}
@@ -899,7 +1155,10 @@ class _VocabDetailsDialogState extends State<_VocabDetailsDialog> {
if (mounted) {
setState(() {
_exampleSentences = [
const Text('Error loading example sentences.', style: TextStyle(color: Colors.red))
Text(
'Error loading example sentences.',
style: TextStyle(color: widget.theme.colorScheme.error),
),
];
});
}
@@ -908,24 +1167,22 @@ class _VocabDetailsDialogState extends State<_VocabDetailsDialog> {
@override
Widget build(BuildContext context) {
final srsScores = <String, int>{
'JP -> EN': 0,
'EN -> JP': 0,
'Audio': 0,
};
final srsScores = <String, int>{'JP -> EN': 0, 'EN -> JP': 0, 'Audio': 0};
for (final entry in widget.vocab.srsItems.entries) {
final srsItem = entry.value;
switch (srsItem.quizMode) {
case VocabQuizMode.vocabToEnglish:
case QuizMode.vocabToEnglish:
srsScores['JP -> EN'] = srsItem.srsStage;
break;
case VocabQuizMode.englishToVocab:
case QuizMode.englishToVocab:
srsScores['EN -> JP'] = srsItem.srsStage;
break;
case VocabQuizMode.audioToEnglish:
case QuizMode.audioToEnglish:
srsScores['Audio'] = srsItem.srsStage;
break;
default:
break;
}
}
@@ -936,37 +1193,45 @@ class _VocabDetailsDialogState extends State<_VocabDetailsDialog> {
children: [
Text(
'Level: ${widget.vocab.level}',
style: const TextStyle(color: Colors.white),
style: TextStyle(color: widget.theme.colorScheme.onSurface),
),
const SizedBox(height: 16),
if (widget.vocab.meanings.isNotEmpty)
Text(
'Meanings: ${widget.vocab.meanings.join(', ')}',
style: const TextStyle(color: Colors.white),
style: TextStyle(color: widget.theme.colorScheme.onSurface),
),
const SizedBox(height: 16),
if (widget.vocab.readings.isNotEmpty)
Text(
'Readings: ${widget.vocab.readings.join(', ')}',
style: const TextStyle(color: Colors.white),
style: TextStyle(color: widget.theme.colorScheme.onSurface),
),
const SizedBox(height: 16),
const Divider(color: Colors.grey),
Divider(color: widget.theme.colorScheme.onSurfaceVariant),
const SizedBox(height: 16),
const Text(
Text(
'SRS Scores:',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
style: TextStyle(
color: widget.theme.colorScheme.onSurface,
fontWeight: FontWeight.bold,
),
),
...srsScores.entries.map(
(entry) => Text(
' ${entry.key}: ${entry.value}',
style: TextStyle(color: widget.theme.colorScheme.onSurface),
),
),
...srsScores.entries.map((entry) => Text(
' ${entry.key}: ${entry.value}',
style: const TextStyle(color: Colors.white),
)),
const SizedBox(height: 16),
const Divider(color: Colors.grey),
Divider(color: widget.theme.colorScheme.onSurfaceVariant),
const SizedBox(height: 16),
const Text(
Text(
'Example Sentences:',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
style: TextStyle(
color: widget.theme.colorScheme.onSurface,
fontWeight: FontWeight.bold,
),
),
..._exampleSentences,
],
@@ -976,23 +1241,27 @@ class _VocabDetailsDialogState extends State<_VocabDetailsDialog> {
}
void _showVocabDetailsDialog(BuildContext context, VocabularyItem vocab) {
final currentTheme = Theme.of(context);
showDialog(
context: context,
builder: (context) {
builder: (dialogContext) {
return AlertDialog(
backgroundColor: const Color(0xFF1E1E1E),
backgroundColor: currentTheme.colorScheme.surfaceContainer,
title: Text(
'Details for ${vocab.characters}',
style: const TextStyle(color: Colors.white),
style: TextStyle(color: currentTheme.colorScheme.onSurface),
),
content: _VocabDetailsDialog(vocab: vocab),
content: _VocabDetailsDialog(vocab: vocab, theme: currentTheme),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close', style: TextStyle(color: Colors.blueAccent)),
onPressed: () => Navigator.of(dialogContext).pop(),
child: Text(
'Close',
style: TextStyle(color: currentTheme.colorScheme.primary),
),
),
],
);
},
);
}
}

View File

@@ -6,8 +6,11 @@ class CustomCardDetailsScreen extends StatefulWidget {
final CustomKanjiItem item;
final CustomDeckRepository repository;
const CustomCardDetailsScreen(
{super.key, required this.item, required this.repository});
const CustomCardDetailsScreen({
super.key,
required this.item,
required this.repository,
});
@override
State<CustomCardDetailsScreen> createState() =>
@@ -41,7 +44,9 @@ class _CustomCardDetailsScreenState extends State<CustomCardDetailsScreen> {
final updatedItem = CustomKanjiItem(
characters: _japaneseController.text,
meaning: _englishController.text,
kanji: _kanjiController.text.trim().isNotEmpty ? _kanjiController.text.trim() : null,
kanji: _kanjiController.text.trim().isNotEmpty
? _kanjiController.text.trim()
: null,
useInterval: _useInterval,
srsData: widget.item.srsData,
);
@@ -79,10 +84,7 @@ class _CustomCardDetailsScreenState extends State<CustomCardDetailsScreen> {
appBar: AppBar(
title: const Text('Edit Card'),
actions: [
IconButton(
icon: const Icon(Icons.delete),
onPressed: _deleteCard,
),
IconButton(icon: const Icon(Icons.delete), onPressed: _deleteCard),
],
),
body: Padding(
@@ -111,10 +113,19 @@ class _CustomCardDetailsScreenState extends State<CustomCardDetailsScreen> {
},
),
const SizedBox(height: 20),
const Text('SRS Levels', style: TextStyle(fontWeight: FontWeight.bold)),
Text('Jpn→Eng: ${widget.item.srsData.japaneseToEnglish} (Next review: ${widget.item.srsData.japaneseToEnglishNextReview?.toString() ?? 'N/A'})'),
Text('Eng→Jpn: ${widget.item.srsData.englishToJapanese} (Next review: ${widget.item.srsData.englishToJapaneseNextReview?.toString() ?? 'N/A'})'),
Text('Listening: ${widget.item.srsData.listeningComprehension} (Next review: ${widget.item.srsData.listeningComprehensionNextReview?.toString() ?? 'N/A'})'),
const Text(
'SRS Levels',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
'Jpn→Eng: ${widget.item.srsData.japaneseToEnglish} (Next review: ${widget.item.srsData.japaneseToEnglishNextReview?.toString() ?? 'N/A'})',
),
Text(
'Eng→Jpn: ${widget.item.srsData.englishToJapanese} (Next review: ${widget.item.srsData.englishToJapaneseNextReview?.toString() ?? 'N/A'})',
),
Text(
'Listening: ${widget.item.srsData.listeningComprehension} (Next review: ${widget.item.srsData.listeningComprehensionNextReview?.toString() ?? 'N/A'})',
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _saveChanges,

View File

@@ -1,11 +1,18 @@
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:flutter_tts/flutter_tts.dart';
import '../models/custom_kanji_item.dart';
import '../widgets/options_grid.dart';
import '../widgets/kanji_card.dart';
import 'package:provider/provider.dart';
import '../services/tts_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:audioplayers/audioplayers.dart';
enum CustomQuizMode { japaneseToEnglish, englishToJapanese, listeningComprehension }
enum CustomQuizMode {
japaneseToEnglish,
englishToJapanese,
listeningComprehension,
}
class CustomQuizScreen extends StatefulWidget {
final List<CustomKanjiItem> deck;
@@ -27,265 +34,375 @@ class CustomQuizScreen extends StatefulWidget {
State<CustomQuizScreen> createState() => CustomQuizScreenState();
}
class _CustomQuizState {
CustomKanjiItem? current;
List<String> options = [];
List<String> correctAnswers = [];
int score = 0;
int asked = 0;
Key key = UniqueKey();
String? selectedOption;
bool showResult = false;
Set<String> wrongItems = {};
}
class CustomQuizScreenState extends State<CustomQuizScreen>
with TickerProviderStateMixin {
int _currentIndex = 0;
final _quizState = _CustomQuizState();
List<CustomKanjiItem> _shuffledDeck = [];
List<String> _options = [];
bool _answered = false;
bool? _correct;
late FlutterTts _flutterTts;
int _sessionDeckSize = 0;
bool _isAnswering = false;
late AnimationController _shakeController;
late Animation<double> _shakeAnimation;
final List<String> _incorrectlyAnsweredItems = [];
final _audioPlayer = AudioPlayer();
bool _playIncorrectSound = true;
bool _playCorrectSound = true;
bool _playNarrator = true;
@override
void initState() {
super.initState();
_shuffledDeck = widget.deck.toList()..shuffle();
_initTts();
if (_shuffledDeck.isNotEmpty) {
_generateOptions();
}
_sessionDeckSize = _shuffledDeck.length;
_shakeController = AnimationController(
duration: const Duration(milliseconds: 500),
vsync: this,
);
_shakeAnimation = Tween<double>(begin: 0, end: 1).animate(
CurvedAnimation(
parent: _shakeController,
curve: Curves.elasticIn,
),
CurvedAnimation(parent: _shakeController, curve: Curves.elasticIn),
);
_loadSettings();
_nextQuestion();
}
Future<void> _loadSettings() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_playIncorrectSound = prefs.getBool('playIncorrectSound') ?? true;
_playCorrectSound = prefs.getBool('playCorrectSound') ?? true;
_playNarrator = prefs.getBool('playNarrator') ?? true;
});
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
}
@override
void didUpdateWidget(CustomQuizScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.deck != oldWidget.deck && !widget.isActive) {
setState(() {
_shuffledDeck = widget.deck.toList()..shuffle();
_currentIndex = 0;
_answered = false;
_correct = null;
if (_shuffledDeck.isNotEmpty) {
_generateOptions();
}
});
_shuffledDeck = widget.deck.toList()..shuffle();
_sessionDeckSize = _shuffledDeck.length;
_nextQuestion();
}
if (widget.useKanji != oldWidget.useKanji) {
setState(() {
_generateOptions();
});
_nextQuestion();
}
}
void playAudio() {
if (widget.quizMode == CustomQuizMode.listeningComprehension && _currentIndex < _shuffledDeck.length) {
_speak(_shuffledDeck[_currentIndex].characters);
void playAudio() async {
final quizState = _quizState;
if (widget.quizMode == CustomQuizMode.listeningComprehension &&
quizState.current != null &&
_playNarrator) {
final ttsService = Provider.of<TtsService>(context, listen: false);
await ttsService.speak(quizState.current!.characters);
}
}
void _initTts() async {
_flutterTts = FlutterTts();
await _flutterTts.setLanguage("ja-JP");
}
@override
void dispose() {
_flutterTts.stop();
_shakeController.dispose();
super.dispose();
}
void _generateOptions() {
final currentItem = _shuffledDeck[_currentIndex];
if (widget.quizMode == CustomQuizMode.listeningComprehension || widget.quizMode == CustomQuizMode.japaneseToEnglish) {
_options = [currentItem.meaning];
} else {
_options = [widget.useKanji && currentItem.kanji != null ? currentItem.kanji! : currentItem.characters];
}
final otherItems = widget.deck
.where((item) => item.characters != currentItem.characters)
.toList();
otherItems.shuffle();
for (var i = 0; i < min(3, otherItems.length); i++) {
if (widget.quizMode == CustomQuizMode.listeningComprehension || widget.quizMode == CustomQuizMode.japaneseToEnglish) {
_options.add(otherItems[i].meaning);
} else {
_options.add(widget.useKanji && otherItems[i].kanji != null ? otherItems[i].kanji! : otherItems[i].characters);
}
}
_options.shuffle();
}
void _answer(String option) async {
final quizState = _quizState;
final current = quizState.current!;
final isCorrect = quizState.correctAnswers
.map((a) => a.toLowerCase().trim())
.contains(option.toLowerCase().trim());
void _checkAnswer(String answer) async {
final currentItem = _shuffledDeck[_currentIndex];
final correctAnswer = (widget.quizMode == CustomQuizMode.englishToJapanese)
? (widget.useKanji && currentItem.kanji != null ? currentItem.kanji! : currentItem.characters)
: currentItem.meaning;
final isCorrect = answer == correctAnswer;
setState(() {
quizState.selectedOption = option;
quizState.showResult = true;
_isAnswering = true;
});
if (currentItem.useInterval) {
int currentSrsLevel;
switch (widget.quizMode) {
case CustomQuizMode.japaneseToEnglish:
currentSrsLevel = currentItem.srsData.japaneseToEnglish;
break;
case CustomQuizMode.englishToJapanese:
currentSrsLevel = currentItem.srsData.englishToJapanese;
break;
case CustomQuizMode.listeningComprehension:
currentSrsLevel = currentItem.srsData.listeningComprehension;
break;
}
if (isCorrect) {
if (_incorrectlyAnsweredItems.contains(currentItem.characters)) {
_incorrectlyAnsweredItems.remove(currentItem.characters);
} else {
currentSrsLevel++;
}
final interval = pow(2, currentSrsLevel).toInt();
final newNextReview = DateTime.now().add(Duration(hours: interval));
switch (widget.quizMode) {
case CustomQuizMode.japaneseToEnglish:
currentItem.srsData.japaneseToEnglishNextReview = newNextReview;
break;
case CustomQuizMode.englishToJapanese:
currentItem.srsData.englishToJapaneseNextReview = newNextReview;
break;
case CustomQuizMode.listeningComprehension:
currentItem.srsData.listeningComprehensionNextReview = newNextReview;
break;
}
} else {
if (!_incorrectlyAnsweredItems.contains(currentItem.characters)) {
_incorrectlyAnsweredItems.add(currentItem.characters);
}
currentSrsLevel = max(0, currentSrsLevel - 1);
final newNextReview = DateTime.now().add(const Duration(hours: 1));
switch (widget.quizMode) {
case CustomQuizMode.japaneseToEnglish:
currentItem.srsData.japaneseToEnglishNextReview = newNextReview;
break;
case CustomQuizMode.englishToJapanese:
currentItem.srsData.englishToJapaneseNextReview = newNextReview;
break;
case CustomQuizMode.listeningComprehension:
currentItem.srsData.listeningComprehensionNextReview = newNextReview;
break;
}
}
switch (widget.quizMode) {
case CustomQuizMode.japaneseToEnglish:
currentItem.srsData.japaneseToEnglish = currentSrsLevel;
break;
case CustomQuizMode.englishToJapanese:
currentItem.srsData.englishToJapanese = currentSrsLevel;
break;
case CustomQuizMode.listeningComprehension:
currentItem.srsData.listeningComprehension = currentSrsLevel;
break;
}
widget.onCardReviewed(currentItem);
if (current.useInterval) {
_updateSrsLevel(current, isCorrect);
}
// --- SnackBar Logic (new) ---
final correctDisplay = (widget.quizMode == CustomQuizMode.englishToJapanese)
? (widget.useKanji && currentItem.kanji != null ? currentItem.kanji! : currentItem.characters)
: currentItem.meaning;
? (widget.useKanji && current.kanji != null
? current.kanji!
: current.characters)
: current.meaning;
final snack = SnackBar(
content: Text(
isCorrect ? 'Correct!' : 'Wrong — correct: $correctDisplay',
style: TextStyle(
color: isCorrect ? Colors.greenAccent : Colors.redAccent,
color: isCorrect
? Theme.of(context).colorScheme.secondary
: Theme.of(context).colorScheme.error,
fontWeight: FontWeight.bold,
),
),
backgroundColor: const Color(0xFF222222),
backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest,
duration: const Duration(milliseconds: 900),
);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(snack);
}
// --- End SnackBar Logic ---
if (isCorrect) {
if (widget.quizMode == CustomQuizMode.japaneseToEnglish) {
await _speak(currentItem.characters);
quizState.asked += 1;
if (!quizState.wrongItems.contains(current.characters)) {
quizState.score += 1;
}
await Future.delayed(const Duration(milliseconds: 500)); // Small delay after correct answer
if (_playCorrectSound && !_playNarrator) {
await _audioPlayer.play(AssetSource('sfx/correct.wav'));
} else if (_playNarrator) {
if (widget.quizMode == CustomQuizMode.japaneseToEnglish ||
widget.quizMode == CustomQuizMode.englishToJapanese) {
await _speak(current.characters);
}
}
await Future.delayed(const Duration(milliseconds: 500));
} else {
quizState.wrongItems.add(current.characters);
_shuffledDeck.add(current);
_shuffledDeck.shuffle();
if (_playIncorrectSound) {
await _audioPlayer.play(AssetSource('sfx/incorrect.wav'));
}
_shakeController.forward(from: 0);
await Future.delayed(const Duration(milliseconds: 900)); // Delay for shake animation
await Future.delayed(const Duration(milliseconds: 900));
}
_nextQuestion();
}
void _nextQuestion() {
setState(() {
_currentIndex++;
_answered = false;
_correct = null;
if (_currentIndex < _shuffledDeck.length) {
_generateOptions();
if (widget.quizMode == CustomQuizMode.listeningComprehension) {
_speak(_shuffledDeck[_currentIndex].characters);
}
Future.delayed(const Duration(milliseconds: 900), () {
if (mounted) {
_nextQuestion();
}
});
}
void _updateSrsLevel(CustomKanjiItem item, bool isCorrect) {
int currentSrsLevel = 0;
switch (widget.quizMode) {
case CustomQuizMode.japaneseToEnglish:
currentSrsLevel = item.srsData.japaneseToEnglish;
break;
case CustomQuizMode.englishToJapanese:
currentSrsLevel = item.srsData.englishToJapanese;
break;
case CustomQuizMode.listeningComprehension:
currentSrsLevel = item.srsData.listeningComprehension;
break;
}
if (isCorrect) {
currentSrsLevel++;
final interval = pow(2, currentSrsLevel).toInt();
final newNextReview = DateTime.now().add(Duration(hours: interval));
switch (widget.quizMode) {
case CustomQuizMode.japaneseToEnglish:
item.srsData.japaneseToEnglishNextReview = newNextReview;
break;
case CustomQuizMode.englishToJapanese:
item.srsData.englishToJapaneseNextReview = newNextReview;
break;
case CustomQuizMode.listeningComprehension:
item.srsData.listeningComprehensionNextReview = newNextReview;
break;
}
} else {
currentSrsLevel = max(0, currentSrsLevel - 1);
final newNextReview = DateTime.now().add(const Duration(hours: 1));
switch (widget.quizMode) {
case CustomQuizMode.japaneseToEnglish:
item.srsData.japaneseToEnglishNextReview = newNextReview;
break;
case CustomQuizMode.englishToJapanese:
item.srsData.englishToJapaneseNextReview = newNextReview;
break;
case CustomQuizMode.listeningComprehension:
item.srsData.listeningComprehensionNextReview = newNextReview;
break;
}
}
switch (widget.quizMode) {
case CustomQuizMode.japaneseToEnglish:
item.srsData.japaneseToEnglish = currentSrsLevel;
break;
case CustomQuizMode.englishToJapanese:
item.srsData.englishToJapanese = currentSrsLevel;
break;
case CustomQuizMode.listeningComprehension:
item.srsData.listeningComprehension = currentSrsLevel;
break;
}
widget.onCardReviewed(item);
}
void _nextQuestion() {
final quizState = _quizState;
if (_shuffledDeck.isEmpty) {
setState(() {
quizState.current = null;
});
return;
}
quizState.current = _shuffledDeck.removeAt(0);
quizState.key = UniqueKey();
quizState.correctAnswers = [];
quizState.options = [];
quizState.selectedOption = null;
quizState.showResult = false;
if (widget.quizMode == CustomQuizMode.japaneseToEnglish ||
widget.quizMode == CustomQuizMode.listeningComprehension) {
quizState.correctAnswers = [quizState.current!.meaning];
quizState.options = [quizState.correctAnswers.first];
} else {
quizState.correctAnswers = [
widget.useKanji && quizState.current!.kanji != null
? quizState.current!.kanji!
: quizState.current!.characters,
];
quizState.options = [quizState.correctAnswers.first];
}
final otherItems = widget.deck
.where((item) => item.characters != quizState.current!.characters)
.toList();
otherItems.shuffle();
for (var i = 0; i < min(3, otherItems.length); i++) {
if (widget.quizMode == CustomQuizMode.japaneseToEnglish ||
widget.quizMode == CustomQuizMode.listeningComprehension) {
quizState.options.add(otherItems[i].meaning);
} else {
quizState.options.add(
widget.useKanji && otherItems[i].kanji != null
? otherItems[i].kanji!
: otherItems[i].characters,
);
}
}
while (quizState.options.length < 4) {
quizState.options.add('---');
}
quizState.options.shuffle();
setState(() {
_isAnswering = false;
});
if (widget.quizMode == CustomQuizMode.listeningComprehension) {
_speak(quizState.current!.characters);
}
}
Future<void> _speak(String text) async {
await _flutterTts.speak(text);
final ttsService = Provider.of<TtsService>(context, listen: false);
await ttsService.speak(text);
}
void _onOptionSelected(String option) {
if (!(_answered && _correct!)) {
_checkAnswer(option);
if (!_isAnswering) {
_answer(option);
}
}
@override
Widget build(BuildContext context) {
if (_shuffledDeck.isEmpty || _currentIndex >= _shuffledDeck.length) {
return const Center(
child: Text('Review session complete!'),
final quizState = _quizState;
if (quizState.current == null) {
return Center(
child: Text(
'Review session complete!',
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
),
);
}
final currentItem = _shuffledDeck[_currentIndex];
final question = (widget.quizMode == CustomQuizMode.englishToJapanese)
? currentItem.meaning
: (widget.useKanji && currentItem.kanji != null ? currentItem.kanji! : currentItem.characters);
final currentItem = quizState.current!;
Widget promptWidget;
String subtitle = '';
if (widget.quizMode == CustomQuizMode.listeningComprehension) {
promptWidget = IconButton(
icon: const Icon(Icons.volume_up, size: 64),
onPressed: () => _speak(currentItem.characters),
);
} else if (widget.quizMode == CustomQuizMode.englishToJapanese) {
promptWidget = Text(
currentItem.meaning,
style: TextStyle(
fontSize: 48,
color: Theme.of(context).colorScheme.onSurface,
),
textAlign: TextAlign.center,
);
} else {
final promptText = widget.useKanji && currentItem.kanji != null
? currentItem.kanji!
: currentItem.characters;
promptWidget = GestureDetector(
onTap: () => _speak(question),
onTap: () => _speak(promptText),
child: Text(
question,
style: const TextStyle(fontSize: 48),
promptText,
style: TextStyle(
fontSize: 48,
color: Theme.of(context).colorScheme.onSurface,
),
textAlign: TextAlign.center,
),
);
}
return Padding(
key: quizState.key,
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${quizState.asked} / $_sessionDeckSize',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
LinearProgressIndicator(
value: _sessionDeckSize > 0
? quizState.asked / _sessionDeckSize
: 0,
backgroundColor: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).colorScheme.primary,
),
),
],
),
const SizedBox(height: 18),
Expanded(
flex: 3,
@@ -298,7 +415,7 @@ class CustomQuizScreenState extends State<CustomQuizScreen>
),
child: KanjiCard(
characterWidget: promptWidget,
subtitle: '',
subtitle: subtitle,
),
),
),
@@ -317,11 +434,18 @@ class CustomQuizScreenState extends State<CustomQuizScreen>
);
},
child: OptionsGrid(
options: _options,
onSelected: _onOptionSelected,
correctAnswers: [],
showResult: false,
isDisabled: false,
options: quizState.options,
onSelected: _isAnswering ? (option) {} : _onOptionSelected,
selectedOption: quizState.selectedOption,
correctAnswers: quizState.correctAnswers,
showResult: quizState.showResult,
),
),
const SizedBox(height: 8),
Text(
'Score: ${quizState.score} / ${quizState.asked}',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
],
@@ -331,4 +455,4 @@ class CustomQuizScreenState extends State<CustomQuizScreen>
),
);
}
}
}

View File

@@ -10,7 +10,8 @@ class CustomSrsScreen extends StatefulWidget {
State<CustomSrsScreen> createState() => _CustomSrsScreenState();
}
class _CustomSrsScreenState extends State<CustomSrsScreen> with SingleTickerProviderStateMixin {
class _CustomSrsScreenState extends State<CustomSrsScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
final _deckRepository = CustomDeckRepository();
List<CustomKanjiItem> _deck = [];
@@ -49,7 +50,9 @@ class _CustomSrsScreenState extends State<CustomSrsScreen> with SingleTickerProv
}
Future<void> _updateCard(CustomKanjiItem item) async {
final index = _deck.indexWhere((element) => element.characters == item.characters);
final index = _deck.indexWhere(
(element) => element.characters == item.characters,
);
if (index != -1) {
setState(() {
_deck[index] = item;
@@ -79,7 +82,8 @@ class _CustomSrsScreenState extends State<CustomSrsScreen> with SingleTickerProv
item.srsData.listeningComprehensionNextReview!.isBefore(now);
}).toList();
final allDecksEmpty = jpnToEngReviewDeck.isEmpty &&
final allDecksEmpty =
jpnToEngReviewDeck.isEmpty &&
engToJpnReviewDeck.isEmpty &&
listeningReviewDeck.isEmpty;
@@ -114,8 +118,8 @@ class _CustomSrsScreenState extends State<CustomSrsScreen> with SingleTickerProv
body: _deck.isEmpty
? const Center(child: Text('Add cards to start quizzing!'))
: allDecksEmpty
? const Center(child: Text('No cards due for review.'))
: TabBarView(
? const Center(child: Text('No cards due for review.'))
: TabBarView(
controller: _tabController,
children: [
CustomQuizScreen(

View File

@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/kanji_item.dart';
import '../models/srs_item.dart';
import '../services/deck_repository.dart';
import '../services/distractor_generator.dart';
import '../widgets/kanji_card.dart';
@@ -28,6 +29,7 @@ class _QuizState {
Key key = UniqueKey();
String? selectedOption;
bool showResult = false;
Set<int> wrongItems = {};
}
class HomeScreen extends StatefulWidget {
@@ -39,7 +41,8 @@ class HomeScreen extends StatefulWidget {
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMixin {
class _HomeScreenState extends State<HomeScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
List<KanjiItem> _deck = [];
bool _loading = false;
@@ -50,8 +53,11 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
final _audioPlayer = AudioPlayer();
final _quizStates = [_QuizState(), _QuizState(), _QuizState()];
final _sessionDecks = <int, List<KanjiItem>>{};
final _sessionDeckSizes = <int, int>{};
_QuizState get _currentQuizState => _quizStates[_tabController.index];
bool _playIncorrectSound = true;
bool _playCorrectSound = true;
bool _apiKeyMissing = false;
@@ -60,9 +66,6 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
super.initState();
_tabController = TabController(length: 3, vsync: this);
_tabController.addListener(() {
if (_tabController.indexIsChanging) {
_nextQuestion();
}
setState(() {});
});
_dg = widget.distractorGenerator ?? DistractorGenerator();
@@ -79,6 +82,7 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
Future<void> _loadSettings() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_playIncorrectSound = prefs.getBool('playIncorrectSound') ?? true;
_playCorrectSound = prefs.getBool('playCorrectSound') ?? true;
});
}
@@ -117,6 +121,49 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
_apiKeyMissing = false;
});
final disabledLevels = <int>{};
final itemsByLevel = <int, List<KanjiItem>>{};
for (final item in _deck) {
(itemsByLevel[item.level] ??= []).add(item);
}
itemsByLevel.forEach((level, items) {
final allSrsItems = items
.expand((item) => item.srsItems.values)
.toList();
if (allSrsItems.isNotEmpty &&
allSrsItems.every((srs) => srs.disabled)) {
disabledLevels.add(level);
}
});
for (var i = 0; i < _tabController.length; i++) {
final mode = _modeForIndex(i);
final filteredDeck = _deck.where((item) {
if (disabledLevels.contains(item.level)) {
return false;
}
if (mode == QuizMode.reading) {
final onyomiSrs = item.srsItems['${QuizMode.reading}onyomi'];
final kunyomiSrs = item.srsItems['${QuizMode.reading}kunyomi'];
final hasOnyomi =
item.onyomi.isNotEmpty &&
(onyomiSrs == null || !onyomiSrs.disabled);
final hasKunyomi =
item.kunyomi.isNotEmpty &&
(kunyomiSrs == null || !kunyomiSrs.disabled);
return hasOnyomi || hasKunyomi;
}
final srsItem = item.srsItems[mode.toString()];
return srsItem == null || !srsItem.disabled;
}).toList();
filteredDeck.shuffle(_random);
_sessionDecks[i] = filteredDeck;
_sessionDeckSizes[i] = filteredDeck.length;
}
for (var i = 0; i < _tabController.length; i++) {
_nextQuestion(i);
}
@@ -163,57 +210,20 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
}
void _nextQuestion([int? index]) {
if (_deck.isEmpty) return;
final tabIndex = index ?? _tabController.index;
final quizState = _quizStates[tabIndex];
final sessionDeck = _sessionDecks[tabIndex];
final mode = _modeForIndex(tabIndex);
final quizState = _quizStates[index ?? _tabController.index];
final mode = _modeForIndex(index ?? _tabController.index);
if (sessionDeck == null || sessionDeck.isEmpty) {
setState(() {
quizState.current = null;
_status = 'Quiz complete!';
});
return;
}
_deck.sort((a, b) {
int getSrsStage(KanjiItem item) {
if (mode == QuizMode.reading) {
final onyomiStage = item.srsItems['${QuizMode.reading}onyomi']?.srsStage;
final kunyomiStage = item.srsItems['${QuizMode.reading}kunyomi']?.srsStage;
if (onyomiStage != null && kunyomiStage != null) {
return min(onyomiStage, kunyomiStage);
}
return onyomiStage ?? kunyomiStage ?? 0;
}
return item.srsItems[mode.toString()]?.srsStage ?? 0;
}
DateTime getLastAsked(KanjiItem item) {
if (mode == QuizMode.reading) {
final onyomiLastAsked = item.srsItems['${QuizMode.reading}onyomi']?.lastAsked;
final kunyomiLastAsked = item.srsItems['${QuizMode.reading}kunyomi']?.lastAsked;
if (onyomiLastAsked != null && kunyomiLastAsked != null) {
return onyomiLastAsked.isBefore(kunyomiLastAsked)
? onyomiLastAsked
: kunyomiLastAsked;
}
return onyomiLastAsked ??
kunyomiLastAsked ??
DateTime.fromMillisecondsSinceEpoch(0);
}
return item.srsItems[mode.toString()]?.lastAsked ??
DateTime.fromMillisecondsSinceEpoch(0);
}
final aStage = getSrsStage(a);
final bStage = getSrsStage(b);
if (aStage != bStage) {
return aStage.compareTo(bStage);
}
final aLastAsked = getLastAsked(a);
final bLastAsked = getLastAsked(b);
return aLastAsked.compareTo(bLastAsked);
});
quizState.current = _deck.first;
quizState.current = sessionDeck.removeAt(0);
quizState.key = UniqueKey();
quizState.correctAnswers = [];
@@ -227,16 +237,15 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
quizState.correctAnswers = [quizState.current!.meanings.first];
quizState.options = [
quizState.correctAnswers.first,
..._dg.generateMeanings(quizState.current!, _deck, 3)
].map(_toTitleCase).toList()
..shuffle();
..._dg.generateMeanings(quizState.current!, _deck, 3),
].map(_toTitleCase).toList()..shuffle();
break;
case QuizMode.englishToKanji:
quizState.correctAnswers = [quizState.current!.characters];
quizState.options = [
quizState.correctAnswers.first,
..._dg.generateKanji(quizState.current!, _deck, 3)
..._dg.generateKanji(quizState.current!, _deck, 3),
]..shuffle();
break;
@@ -249,16 +258,20 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
? _deck.expand((k) => k.onyomi)
: _deck.expand((k) => k.kunyomi);
final distractors = readingsSource
.where((r) => !quizState.correctAnswers.contains(r))
.toSet()
.toList()
final distractors =
readingsSource
.where((r) => !quizState.correctAnswers.contains(r))
.toSet()
.toList()
..shuffle();
quizState.options = ([
quizState.correctAnswers[_random.nextInt(quizState.correctAnswers.length)],
...distractors.take(3)
])
..shuffle();
quizState.correctAnswers[_random.nextInt(
quizState.correctAnswers.length,
)],
...distractors.take(3),
])..shuffle();
break;
default:
break;
}
@@ -276,40 +289,55 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
final repo = Provider.of<DeckRepository>(context, listen: false);
final current = quizState.current!;
final tabIndex = _tabController.index;
final sessionDeck = _sessionDecks[tabIndex]!;
String readingType = '';
if (mode == QuizMode.reading) {
readingType = quizState.readingHint.contains("on'yomi") ? 'onyomi' : 'kunyomi';
readingType = quizState.readingHint.contains("on'yomi")
? 'onyomi'
: 'kunyomi';
}
final srsKey = mode.toString() + readingType;
var srsItem = current.srsItems[srsKey];
final isNew = srsItem == null;
final srsItemForUpdate = srsItem ??=
SrsItem(kanjiId: current.id, quizMode: mode, readingType: readingType);
quizState.asked += 1;
quizState.selectedOption = option;
quizState.showResult = true;
setState(() {}); // Trigger UI rebuild to show selected/correct colors
if (isCorrect) {
quizState.score += 1;
final srsItemForUpdate = srsItem ??= SrsItem(
subjectId: current.id,
quizMode: mode,
readingType: readingType,
);
quizState.selectedOption = option;
quizState.showResult = true;
setState(() {});
if (isCorrect) {
quizState.asked += 1;
if (!quizState.wrongItems.contains(current.id)) {
quizState.score += 1;
}
srsItemForUpdate.srsStage += 1;
if (_playCorrectSound) {
_audioPlayer.play(AssetSource('sfx/confirm.mp3'));
_audioPlayer.play(AssetSource('sfx/correct.wav'));
}
} else {
srsItemForUpdate.srsStage = max(0, srsItemForUpdate.srsStage - 1);
sessionDeck.add(current);
sessionDeck.shuffle(_random);
quizState.wrongItems.add(current.id);
if (_playIncorrectSound) {
_audioPlayer.play(AssetSource('sfx/incorrect.wav'));
}
}
srsItemForUpdate.lastAsked = DateTime.now();
current.srsItems[srsKey] = srsItemForUpdate;
final scaffoldMessenger = ScaffoldMessenger.of(context);
final theme = Theme.of(context);
if (isNew) {
await repo.insertSrsItem(srsItemForUpdate);
} else {
@@ -319,26 +347,28 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
final correctDisplay = (mode == QuizMode.kanjiToEnglish)
? _toTitleCase(quizState.correctAnswers.first)
: (mode == QuizMode.reading
? quizState.correctAnswers.join(', ')
: quizState.correctAnswers.first);
? quizState.correctAnswers.join(', ')
: quizState.correctAnswers.first);
final snack = SnackBar(
content: Text(
isCorrect ? 'Correct!' : 'Wrong — correct: $correctDisplay',
style: TextStyle(
color: isCorrect ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.error,
color: isCorrect
? theme.colorScheme.primary
: theme.colorScheme.error,
fontWeight: FontWeight.bold,
),
),
backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest,
backgroundColor: theme.colorScheme.surfaceContainerHighest,
duration: const Duration(milliseconds: 900),
);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(snack);
scaffoldMessenger.showSnackBar(snack);
}
setState(() {
_isAnswering = true; // Disable input after showing result
_isAnswering = true;
});
Future.delayed(const Duration(milliseconds: 900), () {
@@ -357,7 +387,12 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('WaniKani API key is not set.', style: TextStyle(color: Theme.of(context).colorScheme.onSurface)),
Text(
'WaniKani API key is not set.',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () async {
@@ -374,6 +409,23 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
);
}
if (_loading) {
return Scaffold(
appBar: AppBar(
title: const Text('Kanji Quiz'),
bottom: TabBar(
controller: _tabController,
tabs: const [
Tab(text: 'Kanji→English'),
Tab(text: 'English→Kanji'),
Tab(text: 'Reading'),
],
),
),
body: const Center(child: CircularProgressIndicator()),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Kanji Quiz'),
@@ -389,11 +441,7 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
backgroundColor: Theme.of(context).colorScheme.surface,
body: TabBarView(
controller: _tabController,
children: [
_buildQuizPage(0),
_buildQuizPage(1),
_buildQuizPage(2),
],
children: [_buildQuizPage(0), _buildQuizPage(1), _buildQuizPage(2)],
),
);
}
@@ -402,6 +450,18 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
final quizState = _quizStates[index];
final mode = _modeForIndex(index);
if (quizState.current == null) {
return Center(
child: Text(
_status,
style: TextStyle(
fontSize: 24,
color: Theme.of(context).colorScheme.onSurface,
),
),
);
}
String prompt = '';
String subtitle = '';
@@ -417,6 +477,8 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
prompt = quizState.current!.characters;
subtitle = quizState.readingHint;
break;
default:
break;
}
}
@@ -425,16 +487,29 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Row(
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text(
_status,
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
Text(
'${quizState.asked} / ${_sessionDeckSizes[index] ?? 0}',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
LinearProgressIndicator(
value: (_sessionDeckSizes[index] ?? 0) > 0
? quizState.asked / (_sessionDeckSizes[index] ?? 1)
: 0,
backgroundColor: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).colorScheme.primary,
),
),
if (_loading)
CircularProgressIndicator(color: Theme.of(context).colorScheme.primary),
],
),
const SizedBox(height: 18),
@@ -464,15 +539,16 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
OptionsGrid(
options: quizState.options,
onSelected: _isAnswering ? (option) {} : _answer,
isDisabled: false,
selectedOption: null,
correctAnswers: [],
showResult: false,
showResult: quizState.showResult,
selectedOption: quizState.selectedOption,
correctAnswers: quizState.correctAnswers,
),
const SizedBox(height: 8),
Text(
'Score: ${quizState.score} / ${quizState.asked}',
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
],
),
@@ -481,4 +557,4 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
),
);
}
}
}

View File

@@ -1,4 +1,6 @@
import 'package:flutter/material.dart';
import 'package:hirameki_srs/src/models/theme_model.dart';
import 'package:hirameki_srs/src/themes.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/deck_repository.dart';
@@ -13,8 +15,9 @@ class SettingsScreen extends StatefulWidget {
class _SettingsScreenState extends State<SettingsScreen> {
final TextEditingController _apiKeyController = TextEditingController();
bool _playAudio = true;
bool _playIncorrectSound = true;
bool _playCorrectSound = true;
bool _playNarrator = true;
@override
void dispose() {
@@ -37,8 +40,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
Future<void> _loadSettings() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_playAudio = prefs.getBool('playAudio') ?? true;
_playIncorrectSound = prefs.getBool('playIncorrectSound') ?? true;
_playCorrectSound = prefs.getBool('playCorrectSound') ?? true;
_playNarrator = prefs.getBool('playNarrator') ?? true;
});
}
@@ -50,24 +54,26 @@ class _SettingsScreenState extends State<SettingsScreen> {
await repo.setApiKey(apiKey);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('API key saved!')),
);
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('API key saved!')));
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const HomeScreen()),
);
Navigator.of(
context,
).pushReplacement(MaterialPageRoute(builder: (_) => const HomeScreen()));
}
}
@override
Widget build(BuildContext context) {
final themeModel = Provider.of<ThemeModel>(context);
return Scaffold(
backgroundColor: const Color(0xFF121212),
backgroundColor: Theme.of(context).colorScheme.surface,
appBar: AppBar(
title: const Text('Settings'),
backgroundColor: const Color(0xFF1F1F1F),
foregroundColor: Colors.white,
backgroundColor: Theme.of(context).colorScheme.surfaceContainer,
foregroundColor: Theme.of(context).colorScheme.onSurface,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
@@ -76,15 +82,19 @@ class _SettingsScreenState extends State<SettingsScreen> {
TextField(
controller: _apiKeyController,
obscureText: true,
style: const TextStyle(color: Colors.white),
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
decoration: InputDecoration(
labelText: 'WaniKani API Key',
labelStyle: const TextStyle(color: Colors.grey),
labelStyle: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
filled: true,
fillColor: const Color(0xFF1E1E1E),
fillColor: Theme.of(context).colorScheme.surfaceContainer,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(6),
borderSide: const BorderSide(color: Colors.grey),
borderSide: BorderSide(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
),
@@ -92,37 +102,43 @@ class _SettingsScreenState extends State<SettingsScreen> {
ElevatedButton(
onPressed: _saveApiKey,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blueAccent,
foregroundColor: Colors.white,
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Theme.of(context).colorScheme.onPrimary,
),
child: const Text('Save & Start Quiz'),
),
const SizedBox(height: 24),
SwitchListTile(
title: const Text(
'Play audio for vocabulary',
style: TextStyle(color: Colors.white),
title: Text(
'Play incorrect sound',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
value: _playAudio,
value: _playIncorrectSound,
onChanged: (value) async {
final prefs = await SharedPreferences.getInstance();
prefs.setBool('playAudio', value);
prefs.setBool('playIncorrectSound', value);
setState(() {
_playAudio = value;
_playIncorrectSound = value;
});
},
activeThumbColor: Colors.blueAccent,
inactiveThumbColor: Colors.grey,
tileColor: const Color(0xFF1E1E1E),
activeThumbColor: Theme.of(context).colorScheme.primary,
inactiveThumbColor: Theme.of(
context,
).colorScheme.onSurfaceVariant,
tileColor: Theme.of(context).colorScheme.surfaceContainer,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
),
const SizedBox(height: 12),
SwitchListTile(
title: const Text(
'Play sound on correct answer',
style: TextStyle(color: Colors.white),
title: Text(
'Play correct sound',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
value: _playCorrectSound,
onChanged: (value) async {
@@ -132,9 +148,75 @@ class _SettingsScreenState extends State<SettingsScreen> {
_playCorrectSound = value;
});
},
activeThumbColor: Colors.blueAccent,
inactiveThumbColor: Colors.grey,
tileColor: const Color(0xFF1E1E1E),
activeThumbColor: Theme.of(context).colorScheme.primary,
inactiveThumbColor: Theme.of(
context,
).colorScheme.onSurfaceVariant,
tileColor: Theme.of(context).colorScheme.surfaceContainer,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
),
const SizedBox(height: 12),
SwitchListTile(
title: Text(
'Play narrator (TTS)',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
value: _playNarrator,
onChanged: (value) async {
final prefs = await SharedPreferences.getInstance();
prefs.setBool('playNarrator', value);
setState(() {
_playNarrator = value;
});
},
activeThumbColor: Theme.of(context).colorScheme.primary,
inactiveThumbColor: Theme.of(
context,
).colorScheme.onSurfaceVariant,
tileColor: Theme.of(context).colorScheme.surfaceContainer,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
),
const SizedBox(height: 12),
ListTile(
title: Text(
'Theme',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
trailing: DropdownButton<ThemeData>(
value: themeModel.currentTheme,
dropdownColor: Theme.of(context).colorScheme.surfaceContainer,
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
items: [
DropdownMenuItem(
value: Themes.dark,
child: const Text('Dark'),
),
DropdownMenuItem(
value: Themes.light,
child: const Text('Light'),
),
DropdownMenuItem(
value: Themes.nier,
child: const Text('Nier'),
),
],
onChanged: (theme) {
if (theme != null) {
themeModel.setTheme(theme);
}
},
),
tileColor: Theme.of(context).colorScheme.surfaceContainer,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),

View File

@@ -17,9 +17,9 @@ class StartScreen extends StatelessWidget {
IconButton(
icon: const Icon(Icons.settings),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const SettingsScreen()),
);
Navigator.of(
context,
).push(MaterialPageRoute(builder: (_) => const SettingsScreen()));
},
),
],
@@ -48,9 +48,9 @@ class StartScreen extends StatelessWidget {
icon: Icons.extension,
description: 'Test your knowledge of kanji characters.',
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const HomeScreen()),
);
Navigator.of(
context,
).push(MaterialPageRoute(builder: (_) => const HomeScreen()));
},
),
_buildModeCard(
@@ -59,9 +59,9 @@ class StartScreen extends StatelessWidget {
icon: Icons.school,
description: 'Practice vocabulary from your WaniKani deck.',
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const VocabScreen()),
);
Navigator.of(
context,
).push(MaterialPageRoute(builder: (_) => const VocabScreen()));
},
),
_buildModeCard(
@@ -70,9 +70,9 @@ class StartScreen extends StatelessWidget {
icon: Icons.grid_view,
description: 'Look through your kanji and vocabulary decks.',
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const BrowseScreen()),
);
Navigator.of(
context,
).push(MaterialPageRoute(builder: (_) => const BrowseScreen()));
},
),
_buildModeCard(
@@ -92,7 +92,8 @@ class StartScreen extends StatelessWidget {
);
}
Widget _buildModeCard(BuildContext context, {
Widget _buildModeCard(
BuildContext context, {
required String title,
required IconData icon,
required String description,
@@ -109,13 +110,17 @@ class StartScreen extends StatelessWidget {
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 48, color: Theme.of(context).colorScheme.primary),
Icon(
icon,
size: 48,
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(height: 16),
Text(
title,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
@@ -135,4 +140,4 @@ class StartScreen extends StatelessWidget {
),
);
}
}
}

View File

@@ -3,7 +3,8 @@ import 'dart:math';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/kanji_item.dart';
import '../models/vocabulary_item.dart';
import '../models/srs_item.dart';
import 'package:hirameki_srs/src/services/vocab_deck_repository.dart';
import '../services/distractor_generator.dart';
import '../widgets/kanji_card.dart';
@@ -20,8 +21,7 @@ class _QuizState {
Key key = UniqueKey();
String? selectedOption;
bool showResult = false;
List<VocabularyItem> shuffledDeck = [];
int currentIndex = 0;
Set<int> wrongItems = {};
}
class VocabScreen extends StatefulWidget {
@@ -31,20 +31,25 @@ class VocabScreen extends StatefulWidget {
State<VocabScreen> createState() => _VocabScreenState();
}
class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStateMixin {
class _VocabScreenState extends State<VocabScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
List<VocabularyItem> _deck = [];
bool _loading = false;
bool _isAnswering = false;
String _status = 'Loading deck...';
final DistractorGenerator _dg = DistractorGenerator();
final Random _random = Random();
final _audioPlayer = AudioPlayer();
final _quizStates = [_QuizState(), _QuizState(), _QuizState()];
_QuizState get _currentQuizState => _quizStates[_tabController.index];
final _sessionDecks = <int, List<VocabularyItem>>{};
final _sessionDeckSizes = <int, int>{};
bool _playAudio = true;
bool _playIncorrectSound = true;
bool _playCorrectSound = true;
bool _playNarrator = true;
bool _apiKeyMissing = false;
@override
@@ -52,8 +57,8 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
super.initState();
_tabController = TabController(length: 3, vsync: this);
_tabController.addListener(() {
if (_tabController.indexIsChanging) {
_nextQuestion();
if (_tabController.index == 2 && !_tabController.indexIsChanging) {
_playCurrentAudio();
}
setState(() {});
});
@@ -70,8 +75,9 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
Future<void> _loadSettings() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_playAudio = prefs.getBool('playAudio') ?? true;
_playIncorrectSound = prefs.getBool('playIncorrectSound') ?? true;
_playCorrectSound = prefs.getBool('playCorrectSound') ?? true;
_playNarrator = prefs.getBool('playNarrator') ?? true;
});
}
@@ -110,6 +116,43 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
_apiKeyMissing = false;
});
final disabledLevels = <int>{};
final itemsByLevel = <int, List<VocabularyItem>>{};
for (final item in _deck) {
(itemsByLevel[item.level] ??= []).add(item);
}
itemsByLevel.forEach((level, items) {
final allSrsItems = items
.expand((item) => item.srsItems.values)
.toList();
if (allSrsItems.isNotEmpty &&
allSrsItems.every((srs) => srs.disabled)) {
disabledLevels.add(level);
}
});
for (var i = 0; i < _tabController.length; i++) {
final mode = _modeForIndex(i);
var filteredDeck = _deck.where((item) {
if (disabledLevels.contains(item.level)) {
return false;
}
final srsItem = item.srsItems[mode.toString()];
return srsItem == null || !srsItem.disabled;
}).toList();
if (mode == QuizMode.audioToEnglish) {
filteredDeck = filteredDeck
.where((item) => item.pronunciationAudios.isNotEmpty)
.toList();
}
filteredDeck.shuffle(_random);
_sessionDecks[i] = filteredDeck;
_sessionDeckSizes[i] = filteredDeck.length;
}
for (var i = 0; i < _tabController.length; i++) {
_nextQuestion(i);
}
@@ -129,103 +172,86 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
.join(' ');
}
VocabQuizMode _modeForIndex(int index) {
QuizMode _modeForIndex(int index) {
switch (index) {
case 0:
return VocabQuizMode.vocabToEnglish;
return QuizMode.vocabToEnglish;
case 1:
return VocabQuizMode.englishToVocab;
return QuizMode.englishToVocab;
case 2:
return VocabQuizMode.audioToEnglish;
return QuizMode.audioToEnglish;
default:
return VocabQuizMode.vocabToEnglish;
return QuizMode.vocabToEnglish;
}
}
void _nextQuestion([int? index]) {
if (_deck.isEmpty) return;
final tabIndex = index ?? _tabController.index;
final quizState = _quizStates[tabIndex];
final sessionDeck = _sessionDecks[tabIndex];
final mode = _modeForIndex(tabIndex);
final quizState = _quizStates[index ?? _tabController.index];
final mode = _modeForIndex(index ?? _tabController.index);
List<VocabularyItem> currentDeckForMode = _deck;
if (mode == VocabQuizMode.audioToEnglish) {
currentDeckForMode = _deck.where((item) => item.pronunciationAudios.isNotEmpty).toList();
if (currentDeckForMode.isEmpty) {
setState(() {
_status = 'No vocabulary with audio found.';
quizState.current = null;
});
return;
}
}
// If it's a new session or we've gone through all shuffled items, re-shuffle
if (quizState.shuffledDeck.isEmpty || quizState.currentIndex >= quizState.shuffledDeck.length) {
quizState.shuffledDeck = currentDeckForMode.toList(); // Start with a fresh copy
// Apply sorting based on SRS stages here, but only once per shuffle
quizState.shuffledDeck.sort((a, b) {
final aSrsItem = a.srsItems[mode.toString()] ?? VocabSrsItem(vocabId: a.id, quizMode: mode);
final bSrsItem = b.srsItems[mode.toString()] ?? VocabSrsItem(vocabId: b.id, quizMode: mode);
final stageComparison = aSrsItem.srsStage.compareTo(bSrsItem.srsStage);
if (stageComparison != 0) {
return stageComparison;
}
return aSrsItem.lastAsked.compareTo(bSrsItem.lastAsked);
if (sessionDeck == null || sessionDeck.isEmpty) {
setState(() {
quizState.current = null;
_status = 'Quiz complete!';
});
quizState.currentIndex = 0;
return;
}
quizState.current = quizState.shuffledDeck[quizState.currentIndex]; // Pick from shuffled deck
quizState.currentIndex++; // Advance index
quizState.current = sessionDeck.removeAt(0);
quizState.key = UniqueKey();
if (mode == VocabQuizMode.audioToEnglish) {
_playCurrentAudio();
}
quizState.correctAnswers = [];
quizState.options = [];
quizState.selectedOption = null;
quizState.showResult = false;
switch (mode) {
case VocabQuizMode.vocabToEnglish:
case VocabQuizMode.audioToEnglish:
case QuizMode.vocabToEnglish:
case QuizMode.audioToEnglish:
quizState.correctAnswers = [quizState.current!.meanings.first];
quizState.options = [
quizState.correctAnswers.first,
..._dg.generateVocabMeanings(quizState.current!, _deck, 3)
].map(_toTitleCase).toList()
..shuffle();
..._dg.generateVocabMeanings(quizState.current!, _deck, 3),
].map(_toTitleCase).toList()..shuffle();
break;
case VocabQuizMode.englishToVocab:
case QuizMode.englishToVocab:
quizState.correctAnswers = [quizState.current!.characters];
quizState.options = [
quizState.correctAnswers.first,
..._dg.generateVocab(quizState.current!, _deck, 3)
..._dg.generateVocab(quizState.current!, _deck, 3),
]..shuffle();
break;
default:
break;
}
setState(() {
_isAnswering = false;
});
if (mode == QuizMode.audioToEnglish) {
_playCurrentAudio(playOnLoad: true);
}
}
Future<void> _playCurrentAudio() async {
Future<void> _playCurrentAudio({bool playOnLoad = false}) async {
final current = _currentQuizState.current;
if (current == null || current.pronunciationAudios.isEmpty) return;
final maleAudios = current.pronunciationAudios.where((a) => a.gender == 'male');
final audioUrl = (maleAudios.isNotEmpty ? maleAudios.first.url : current.pronunciationAudios.first.url);
if (playOnLoad && !_playNarrator) return;
final maleAudios = current.pronunciationAudios.where(
(a) => a.gender == 'male',
);
final audioUrl = (maleAudios.isNotEmpty
? maleAudios.first.url
: current.pronunciationAudios.first.url);
try {
await _audioPlayer.play(UrlSource(audioUrl));
} catch (e) {
// Ignore player errors
}
} finally {}
}
void _answer(String option) async {
@@ -237,24 +263,34 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
final repo = Provider.of<VocabDeckRepository>(context, listen: false);
final current = quizState.current!;
final tabIndex = _tabController.index;
final sessionDeck = _sessionDecks[tabIndex]!;
final srsKey = mode.toString();
var srsItemNullable = current.srsItems[srsKey];
final isNew = srsItemNullable == null;
final srsItem =
srsItemNullable ?? VocabSrsItem(vocabId: current.id, quizMode: mode);
srsItemNullable ?? SrsItem(subjectId: current.id, quizMode: mode);
quizState.asked += 1;
quizState.selectedOption = option;
quizState.showResult = true;
setState(() {}); // Trigger UI rebuild to show selected/correct colors
setState(() {});
if (isCorrect) {
quizState.score += 1;
quizState.asked += 1;
if (!quizState.wrongItems.contains(current.id)) {
quizState.score += 1;
}
srsItem.srsStage += 1;
} else {
srsItem.srsStage = max(0, srsItem.srsStage - 1);
sessionDeck.add(current);
sessionDeck.shuffle(_random);
quizState.wrongItems.add(current.id);
if (_playIncorrectSound) {
await _audioPlayer.play(AssetSource('sfx/incorrect.wav'));
}
}
srsItem.lastAsked = DateTime.now();
current.srsItems[srsKey] = srsItem;
@@ -265,32 +301,33 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
await repo.updateVocabSrsItem(srsItem);
}
final correctDisplay = (mode == VocabQuizMode.vocabToEnglish)
final correctDisplay = (mode == QuizMode.vocabToEnglish)
? _toTitleCase(quizState.correctAnswers.first)
: quizState.correctAnswers.first;
if (!mounted) return;
final snack = SnackBar(
content: Text(
isCorrect ? 'Correct!' : 'Wrong — correct: $correctDisplay',
style: TextStyle(
color: isCorrect ? Colors.greenAccent : Colors.redAccent,
color: isCorrect
? Theme.of(context).colorScheme.tertiary
: Theme.of(context).colorScheme.error,
fontWeight: FontWeight.bold,
),
),
backgroundColor: const Color(0xFF222222),
backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest,
duration: const Duration(milliseconds: 900),
);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(snack);
}
ScaffoldMessenger.of(context).showSnackBar(snack);
if (isCorrect) {
if (_playCorrectSound) {
await _audioPlayer.play(AssetSource('sfx/confirm.mp3'));
}
if (_playAudio && mode != VocabQuizMode.audioToEnglish) {
final maleAudios =
current.pronunciationAudios.where((a) => a.gender == 'male');
if (_playCorrectSound && !_playNarrator) {
await _audioPlayer.play(AssetSource('sfx/correct.wav'));
} else if (_playNarrator) {
final maleAudios = current.pronunciationAudios.where(
(a) => a.gender == 'male',
);
if (maleAudios.isNotEmpty) {
final completer = Completer<void>();
final sub = _audioPlayer.onPlayerComplete.listen((event) {
@@ -300,22 +337,22 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
try {
await _audioPlayer.play(UrlSource(maleAudios.first.url));
await completer.future.timeout(const Duration(seconds: 5));
} catch (e) {
// Ignore player errors
} finally {
await sub.cancel();
}
}
}
} else {
// No fixed delay for incorrect answers
}
setState(() {
_isAnswering = true; // Disable input after showing result
_isAnswering = true;
});
_nextQuestion();
Future.delayed(const Duration(milliseconds: 900), () {
if (mounted) {
_nextQuestion();
}
});
}
@override
@@ -327,13 +364,19 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('WaniKani API key is not set.'),
Text(
'WaniKani API key is not set.',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () async {
await Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const SettingsScreen()),
);
if (!mounted) return;
_loadDeck();
},
child: const Text('Go to Settings'),
@@ -344,6 +387,23 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
);
}
if (_loading) {
return Scaffold(
appBar: AppBar(
title: const Text('Vocabulary Quiz'),
bottom: TabBar(
controller: _tabController,
tabs: const [
Tab(text: 'Vocab→English'),
Tab(text: 'English→Vocab'),
Tab(text: 'Listening'),
],
),
),
body: const Center(child: CircularProgressIndicator()),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Vocabulary Quiz'),
@@ -358,11 +418,7 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
),
body: TabBarView(
controller: _tabController,
children: [
_buildQuizPage(0),
_buildQuizPage(1),
_buildQuizPage(2),
],
children: [_buildQuizPage(0), _buildQuizPage(1), _buildQuizPage(2)],
),
);
}
@@ -371,29 +427,52 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
final quizState = _quizStates[index];
final mode = _modeForIndex(index);
if (quizState.current == null) {
return Center(
child: Text(
_status,
style: TextStyle(
fontSize: 24,
color: Theme.of(context).colorScheme.onSurface,
),
),
);
}
Widget promptWidget;
if (quizState.current == null) {
promptWidget = const SizedBox.shrink();
} else if (mode == VocabQuizMode.audioToEnglish) {
} else if (mode == QuizMode.audioToEnglish) {
promptWidget = IconButton(
icon: const Icon(Icons.volume_up, color: Colors.white, size: 64),
icon: Icon(
Icons.volume_up,
color: Theme.of(context).colorScheme.onSurface,
size: 64,
),
onPressed: _playCurrentAudio,
);
} else {
String promptText = '';
switch (mode) {
case VocabQuizMode.vocabToEnglish:
case QuizMode.vocabToEnglish:
promptText = quizState.current!.characters;
break;
case VocabQuizMode.englishToVocab:
case QuizMode.englishToVocab:
promptText = _toTitleCase(quizState.current!.meanings.first);
break;
case VocabQuizMode.audioToEnglish:
// Handled above
case QuizMode.audioToEnglish:
break;
default:
break;
}
promptWidget = Text(promptText, style: const TextStyle(fontSize: 48, color: Colors.white));
promptWidget = Text(
promptText,
style: TextStyle(
fontSize: 48,
color: Theme.of(context).colorScheme.onSurface,
),
);
}
return Padding(
@@ -401,15 +480,29 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Row(
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text(
_status,
Text(
'${quizState.asked} / ${_sessionDeckSizes[index] ?? 0}',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
LinearProgressIndicator(
value: (_sessionDeckSizes[index] ?? 0) > 0
? quizState.asked / (_sessionDeckSizes[index] ?? 1)
: 0,
backgroundColor: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).colorScheme.primary,
),
),
if (_loading)
const CircularProgressIndicator(color: Colors.blueAccent),
],
),
const SizedBox(height: 18),
@@ -422,10 +515,7 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
maxWidth: 500,
minHeight: 150,
),
child: KanjiCard(
characterWidget: promptWidget,
subtitle: '',
),
child: KanjiCard(characterWidget: promptWidget, subtitle: ''),
),
),
),
@@ -437,15 +527,16 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
OptionsGrid(
options: quizState.options,
onSelected: _isAnswering ? (option) {} : _answer,
isDisabled: false,
selectedOption: null,
correctAnswers: [],
showResult: false,
showResult: quizState.showResult,
selectedOption: quizState.selectedOption,
correctAnswers: quizState.correctAnswers,
),
const SizedBox(height: 8),
Text(
'Score: ${quizState.score} / ${quizState.asked}',
style: const TextStyle(color: Colors.white),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
],
),
@@ -454,4 +545,4 @@ class _VocabScreenState extends State<VocabScreen> with SingleTickerProviderStat
),
);
}
}
}

View File

@@ -1,4 +1,3 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/custom_kanji_item.dart';
@@ -23,18 +22,15 @@ class CustomDeckRepository {
}
Future<void> updateCard(CustomKanjiItem item) async {
final deck = await getCustomDeck();
final index = deck.indexWhere((element) => element.characters == item.characters);
if (index != -1) {
deck[index] = item;
await saveDeck(deck);
}
await updateCards([item]);
}
Future<void> updateCards(List<CustomKanjiItem> itemsToUpdate) async {
final deck = await getCustomDeck();
for (var item in itemsToUpdate) {
final index = deck.indexWhere((element) => element.characters == item.characters);
final index = deck.indexWhere(
(element) => element.characters == item.characters,
);
if (index != -1) {
deck[index] = item;
}

View File

@@ -0,0 +1,27 @@
class DbConstants {
static const String settingsTable = 'settings';
static const String kanjiTable = 'kanji';
static const String srsItemsTable = 'srs_items';
static const String vocabularyTable = 'vocabulary';
static const String srsVocabItemsTable = 'srs_vocab_items';
static const String keyColumn = 'key';
static const String valueColumn = 'value';
static const String idColumn = 'id';
static const String levelColumn = 'level';
static const String charactersColumn = 'characters';
static const String meaningsColumn = 'meanings';
static const String onyomiColumn = 'onyomi';
static const String kunyomiColumn = 'kunyomi';
static const String readingsColumn = 'readings';
static const String pronunciationAudiosColumn = 'pronunciation_audios';
static const String kanjiIdColumn = 'kanjiId';
static const String vocabIdColumn = 'vocabId';
static const String quizModeColumn = 'quizMode';
static const String readingTypeColumn = 'readingType';
static const String srsStageColumn = 'srsStage';
static const String lastAskedColumn = 'lastAsked';
static const String disabledColumn = 'disabled';
}

View File

@@ -0,0 +1,65 @@
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'database_constants.dart';
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
static Database? _db;
factory DatabaseHelper() {
return _instance;
}
DatabaseHelper._internal();
Future<Database> get db async {
if (_db != null) return _db!;
_db = await _openDb();
return _db!;
}
Future<void> close() async {
if (_db != null) {
await _db!.close();
_db = null;
}
}
Future<Database> _openDb() async {
final dir = await getApplicationDocumentsDirectory();
final path = join(dir.path, 'wanikani_srs.db');
return openDatabase(
path,
version: 8,
onCreate: (db, version) async {
await db.execute(
'''CREATE TABLE ${DbConstants.kanjiTable} (${DbConstants.idColumn} INTEGER PRIMARY KEY, ${DbConstants.levelColumn} INTEGER, ${DbConstants.charactersColumn} TEXT, ${DbConstants.meaningsColumn} TEXT, ${DbConstants.onyomiColumn} TEXT, ${DbConstants.kunyomiColumn} TEXT)''',
);
await db.execute(
'''CREATE TABLE ${DbConstants.settingsTable} (${DbConstants.keyColumn} TEXT PRIMARY KEY, ${DbConstants.valueColumn} TEXT)''',
);
await db.execute(
'''CREATE TABLE ${DbConstants.srsItemsTable} (${DbConstants.kanjiIdColumn} INTEGER, ${DbConstants.quizModeColumn} TEXT, ${DbConstants.readingTypeColumn} TEXT, ${DbConstants.srsStageColumn} INTEGER, ${DbConstants.lastAskedColumn} TEXT, ${DbConstants.disabledColumn} INTEGER DEFAULT 0, PRIMARY KEY (${DbConstants.kanjiIdColumn}, ${DbConstants.quizModeColumn}, ${DbConstants.readingTypeColumn}))''',
);
await db.execute(
'''CREATE TABLE ${DbConstants.vocabularyTable} (${DbConstants.idColumn} INTEGER PRIMARY KEY, ${DbConstants.levelColumn} INTEGER, ${DbConstants.charactersColumn} TEXT, ${DbConstants.meaningsColumn} TEXT, ${DbConstants.readingsColumn} TEXT, ${DbConstants.pronunciationAudiosColumn} TEXT)''',
);
await db.execute(
'''CREATE TABLE ${DbConstants.srsVocabItemsTable} (${DbConstants.vocabIdColumn} INTEGER, ${DbConstants.quizModeColumn} TEXT, ${DbConstants.srsStageColumn} INTEGER, ${DbConstants.lastAskedColumn} TEXT, ${DbConstants.disabledColumn} INTEGER DEFAULT 0, PRIMARY KEY (${DbConstants.vocabIdColumn}, ${DbConstants.quizModeColumn}))''',
);
},
onUpgrade: (db, oldVersion, newVersion) async {
if (oldVersion < 8) {
await db.execute(
'ALTER TABLE ${DbConstants.srsItemsTable} ADD COLUMN ${DbConstants.disabledColumn} INTEGER DEFAULT 0',
);
await db.execute(
'ALTER TABLE ${DbConstants.srsVocabItemsTable} ADD COLUMN ${DbConstants.disabledColumn} INTEGER DEFAULT 0',
);
}
},
);
}
}

View File

@@ -1,14 +1,14 @@
import 'dart:async';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import '../models/kanji_item.dart';
import '../models/srs_item.dart';
import '../api/wk_client.dart';
import 'database_constants.dart';
import 'database_helper.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
class DeckRepository {
Database? _db;
String? _apiKey;
Future<void> setApiKey(String apiKey) async {
@@ -18,148 +18,73 @@ class DeckRepository {
String? get apiKey => _apiKey;
Future<Database> _openDb() async {
if (_db != null) return _db!;
final dir = await getApplicationDocumentsDirectory();
final path = join(dir.path, 'wanikani_srs.db');
_db = await openDatabase(
path,
version: 7,
onCreate: (db, version) async {
await db.execute(
'''CREATE TABLE kanji (id INTEGER PRIMARY KEY, level INTEGER, characters TEXT, meanings TEXT, onyomi TEXT, kunyomi TEXT)''',
);
await db.execute(
'''CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT)''',
);
await db.execute(
'''CREATE TABLE srs_items (kanjiId INTEGER, quizMode TEXT, readingType TEXT, srsStage INTEGER, lastAsked TEXT, PRIMARY KEY (kanjiId, quizMode, readingType))''',
);
await db.execute(
'''CREATE TABLE vocabulary (id INTEGER PRIMARY KEY, level INTEGER, characters TEXT, meanings TEXT, readings TEXT, pronunciation_audios TEXT)''',
);
await db.execute(
'''CREATE TABLE srs_vocab_items (vocabId INTEGER, quizMode TEXT, srsStage INTEGER, lastAsked TEXT, PRIMARY KEY (vocabId, quizMode))''',
);
},
onUpgrade: (db, oldVersion, newVersion) async {
if (oldVersion < 2) {
await db.execute(
'''CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)''',
);
}
if (oldVersion < 3) {
// Migration from version 2 to 3 was flawed, so we just drop the columns if they exist
}
if (oldVersion < 4) {
await db.execute(
'''CREATE TABLE srs_items (kanjiId INTEGER, quizMode TEXT, readingType TEXT, srsStage INTEGER, lastAsked TEXT, PRIMARY KEY (kanjiId, quizMode, readingType))''',
);
// We are not migrating the old srs data, as it was not mode-specific.
// Old columns will be dropped.
}
if (oldVersion < 5) {
await db.execute(
'''CREATE TABLE vocabulary (id INTEGER PRIMARY KEY, characters TEXT, meanings TEXT, readings TEXT)''',
);
await db.execute(
'''CREATE TABLE srs_vocab_items (vocabId INTEGER, quizMode TEXT, srsStage INTEGER, lastAsked TEXT, PRIMARY KEY (vocabId, quizMode))''',
);
}
if (oldVersion < 6) {
try {
await db.execute(
'ALTER TABLE vocabulary ADD COLUMN pronunciation_audios TEXT',
);
} catch (_) {
// Ignore error, column might already exist
}
}
if (oldVersion < 7) {
try {
await db.execute('ALTER TABLE kanji ADD COLUMN level INTEGER');
await db.execute('ALTER TABLE vocabulary ADD COLUMN level INTEGER');
} catch (_) {
// Ignore error, column might already exist
}
}
},
);
return _db!;
}
Future<void> saveApiKey(String apiKey) async {
final db = await _openDb();
await db.insert('settings', {
'key': 'apiKey',
'value': apiKey,
final db = await DatabaseHelper().db;
await db.insert(DbConstants.settingsTable, {
DbConstants.keyColumn: 'apiKey',
DbConstants.valueColumn: apiKey,
}, conflictAlgorithm: ConflictAlgorithm.replace);
}
Future<String?> loadApiKey() async {
String? envApiKey;
try {
envApiKey = dotenv.env['WANIKANI_API_KEY'];
} catch (e) {
// dotenv is not initialized, so we can't get the key.
// This is expected in release builds.
envApiKey = null;
}
if (envApiKey != null && envApiKey.isNotEmpty) {
_apiKey = envApiKey;
return _apiKey;
}
final db = await _openDb();
final db = await DatabaseHelper().db;
final rows = await db.query(
'settings',
where: 'key = ?',
DbConstants.settingsTable,
where: '${DbConstants.keyColumn} = ?',
whereArgs: ['apiKey'],
);
if (rows.isNotEmpty) {
_apiKey = rows.first['value'] as String;
_apiKey = rows.first[DbConstants.valueColumn] as String;
return _apiKey;
}
try {
final envApiKey = dotenv.env['WANIKANI_API_KEY'];
if (envApiKey != null && envApiKey.isNotEmpty) {
await saveApiKey(envApiKey);
_apiKey = envApiKey;
return _apiKey;
}
} catch (_) {}
return null;
}
Future<void> saveKanji(List<KanjiItem> items) async {
final db = await _openDb();
final db = await DatabaseHelper().db;
final batch = db.batch();
for (final it in items) {
batch.insert('kanji', {
'id': it.id,
'level': it.level,
'characters': it.characters,
'meanings': it.meanings.join('|'),
'onyomi': it.onyomi.join('|'),
'kunyomi': it.kunyomi.join('|'),
batch.insert(DbConstants.kanjiTable, {
DbConstants.idColumn: it.id,
DbConstants.levelColumn: it.level,
DbConstants.charactersColumn: it.characters,
DbConstants.meaningsColumn: it.meanings.join('|'),
DbConstants.onyomiColumn: it.onyomi.join('|'),
DbConstants.kunyomiColumn: it.kunyomi.join('|'),
}, conflictAlgorithm: ConflictAlgorithm.replace);
}
await batch.commit(noResult: true);
}
Future<List<KanjiItem>> loadKanji() async {
final db = await _openDb();
final rows = await db.query('kanji');
final db = await DatabaseHelper().db;
final rows = await db.query(DbConstants.kanjiTable);
final kanjiItems = rows
.map(
(r) => KanjiItem(
id: r['id'] as int,
level: r['level'] as int? ?? 0,
characters: r['characters'] as String,
meanings: (r['meanings'] as String)
id: r[DbConstants.idColumn] as int,
level: r[DbConstants.levelColumn] as int? ?? 0,
characters: r[DbConstants.charactersColumn] as String,
meanings: (r[DbConstants.meaningsColumn] as String)
.split('|')
.where((s) => s.isNotEmpty)
.toList(),
onyomi: (r['onyomi'] as String)
onyomi: (r[DbConstants.onyomiColumn] as String)
.split('|')
.where((s) => s.isNotEmpty)
.toList(),
kunyomi: (r['kunyomi'] as String)
kunyomi: (r[DbConstants.kunyomiColumn] as String)
.split('|')
.where((s) => s.isNotEmpty)
.toList(),
@@ -167,8 +92,24 @@ class DeckRepository {
)
.toList();
final srsRows = await db.query(DbConstants.srsItemsTable);
final srsItemsByKanjiId = <int, List<SrsItem>>{};
for (final r in srsRows) {
final srsItem = SrsItem(
subjectId: r[DbConstants.kanjiIdColumn] as int,
quizMode: QuizMode.values.firstWhere(
(e) => e.toString() == r[DbConstants.quizModeColumn] as String,
),
readingType: r[DbConstants.readingTypeColumn] as String?,
srsStage: r[DbConstants.srsStageColumn] as int,
lastAsked: DateTime.parse(r[DbConstants.lastAskedColumn] as String),
disabled: (r[DbConstants.disabledColumn] as int? ?? 0) == 1,
);
srsItemsByKanjiId.putIfAbsent(srsItem.subjectId, () => []).add(srsItem);
}
for (final item in kanjiItems) {
final srsItems = await getSrsItems(item.id);
final srsItems = srsItemsByKanjiId[item.id] ?? [];
for (final srsItem in srsItems) {
final key = srsItem.quizMode.toString() + (srsItem.readingType ?? '');
item.srsItems[key] = srsItem;
@@ -178,47 +119,67 @@ class DeckRepository {
return kanjiItems;
}
Future<List<SrsItem>> getSrsItems(int kanjiId) async {
final db = await _openDb();
final rows = await db.query(
'srs_items',
where: 'kanjiId = ?',
whereArgs: [kanjiId],
);
return rows.map((r) {
return SrsItem(
kanjiId: r['kanjiId'] as int,
quizMode: QuizMode.values.firstWhere(
(e) => e.toString() == r['quizMode'] as String,
),
readingType: r['readingType'] as String?,
srsStage: r['srsStage'] as int,
lastAsked: DateTime.parse(r['lastAsked'] as String),
Future<void> updateSrsItems(List<SrsItem> items) async {
final db = await DatabaseHelper().db;
final batch = db.batch();
for (final item in items) {
var where =
'${DbConstants.kanjiIdColumn} = ? AND ${DbConstants.quizModeColumn} = ?';
final whereArgs = [item.subjectId, item.quizMode.toString()];
if (item.readingType != null) {
where += ' AND ${DbConstants.readingTypeColumn} = ?';
whereArgs.add(item.readingType!);
} else {
where += ' AND ${DbConstants.readingTypeColumn} IS NULL';
}
batch.update(
DbConstants.srsItemsTable,
{
DbConstants.srsStageColumn: item.srsStage,
DbConstants.lastAskedColumn: item.lastAsked.toIso8601String(),
DbConstants.disabledColumn: item.disabled ? 1 : 0,
},
where: where,
whereArgs: whereArgs,
);
}).toList();
}
await batch.commit(noResult: true);
}
Future<void> updateSrsItem(SrsItem item) async {
final db = await _openDb();
final db = await DatabaseHelper().db;
var where =
'${DbConstants.kanjiIdColumn} = ? AND ${DbConstants.quizModeColumn} = ?';
final whereArgs = [item.subjectId, item.quizMode.toString()];
if (item.readingType != null) {
where += ' AND ${DbConstants.readingTypeColumn} = ?';
whereArgs.add(item.readingType!);
} else {
where += ' AND ${DbConstants.readingTypeColumn} IS NULL';
}
await db.update(
'srs_items',
DbConstants.srsItemsTable,
{
'srsStage': item.srsStage,
'lastAsked': item.lastAsked.toIso8601String(),
DbConstants.srsStageColumn: item.srsStage,
DbConstants.lastAskedColumn: item.lastAsked.toIso8601String(),
DbConstants.disabledColumn: item.disabled ? 1 : 0,
},
where: 'kanjiId = ? AND quizMode = ? AND readingType = ?',
whereArgs: [item.kanjiId, item.quizMode.toString(), item.readingType],
where: where,
whereArgs: whereArgs,
);
}
Future<void> insertSrsItem(SrsItem item) async {
final db = await _openDb();
await db.insert('srs_items', {
'kanjiId': item.kanjiId,
'quizMode': item.quizMode.toString(),
'readingType': item.readingType,
'srsStage': item.srsStage,
'lastAsked': item.lastAsked.toIso8601String(),
final db = await DatabaseHelper().db;
await db.insert(DbConstants.srsItemsTable, {
DbConstants.kanjiIdColumn: item.subjectId,
DbConstants.quizModeColumn: item.quizMode.toString(),
DbConstants.readingTypeColumn: item.readingType,
DbConstants.srsStageColumn: item.srsStage,
DbConstants.lastAskedColumn: item.lastAsked.toIso8601String(),
DbConstants.disabledColumn: item.disabled ? 1 : 0,
}, conflictAlgorithm: ConflictAlgorithm.replace);
}
@@ -261,6 +222,4 @@ class DeckRepository {
await saveKanji(items);
return items;
}
}
}

View File

@@ -1,17 +1,30 @@
import '../models/kanji_item.dart';
import '../models/vocabulary_item.dart';
import 'dart:math';
class DistractorGenerator {
final Random _rnd = Random();
List<String> generateMeanings(KanjiItem correct, List<KanjiItem> pool, int needed) {
List<String> generateMeanings(
KanjiItem correct,
List<KanjiItem> pool,
int needed,
) {
final correctMeaning = correct.meanings.first;
final tokens = correctMeaning.split(RegExp(r'\s+')).map((s) => s.trim()).where((s) => s.isNotEmpty).toSet();
final tokens = correctMeaning
.split(RegExp(r'\s+'))
.map((s) => s.trim())
.where((s) => s.isNotEmpty)
.toSet();
final candidates = <String>[];
for (final k in pool) {
if (k.id == correct.id) continue;
for (final m in k.meanings) {
final mTokens = m.split(RegExp(r'\s+')).map((s) => s.trim()).where((s) => s.isNotEmpty).toSet();
final mTokens = m
.split(RegExp(r'\s+'))
.map((s) => s.trim())
.where((s) => s.isNotEmpty)
.toSet();
if (mTokens.intersection(tokens).isNotEmpty) {
candidates.add(m);
}
@@ -38,8 +51,15 @@ class DistractorGenerator {
return out;
}
List<String> generateKanji(KanjiItem correct, List<KanjiItem> pool, int needed) {
final others = pool.map((k) => k.characters).where((c) => c != correct.characters).toList();
List<String> generateKanji(
KanjiItem correct,
List<KanjiItem> pool,
int needed,
) {
final others = pool
.map((k) => k.characters)
.where((c) => c != correct.characters)
.toList();
others.shuffle(_rnd);
final out = <String>[];
for (final o in others) {
@@ -52,7 +72,11 @@ class DistractorGenerator {
return out;
}
List<String> generateReadings(String correct, List<KanjiItem> pool, int needed) {
List<String> generateReadings(
String correct,
List<KanjiItem> pool,
int needed,
) {
final poolReadings = <String>[];
for (final k in pool) {
poolReadings.addAll(k.onyomi);
@@ -71,14 +95,26 @@ class DistractorGenerator {
return out;
}
List<String> generateVocabMeanings(VocabularyItem correct, List<VocabularyItem> pool, int needed) {
List<String> generateVocabMeanings(
VocabularyItem correct,
List<VocabularyItem> pool,
int needed,
) {
final correctMeaning = correct.meanings.first;
final tokens = correctMeaning.split(RegExp(r'\s+')).map((s) => s.trim()).where((s) => s.isNotEmpty).toSet();
final tokens = correctMeaning
.split(RegExp(r'\s+'))
.map((s) => s.trim())
.where((s) => s.isNotEmpty)
.toSet();
final candidates = <String>[];
for (final k in pool) {
if (k.id == correct.id) continue;
for (final m in k.meanings) {
final mTokens = m.split(RegExp(r'\s+')).map((s) => s.trim()).where((s) => s.isNotEmpty).toSet();
final mTokens = m
.split(RegExp(r'\s+'))
.map((s) => s.trim())
.where((s) => s.isNotEmpty)
.toSet();
if (mTokens.intersection(tokens).isNotEmpty) {
candidates.add(m);
}
@@ -105,8 +141,15 @@ class DistractorGenerator {
return out;
}
List<String> generateVocab(VocabularyItem correct, List<VocabularyItem> pool, int needed) {
final others = pool.map((k) => k.characters).where((c) => c != correct.characters).toList();
List<String> generateVocab(
VocabularyItem correct,
List<VocabularyItem> pool,
int needed,
) {
final others = pool
.map((k) => k.characters)
.where((c) => c != correct.characters)
.toList();
others.shuffle(_rnd);
final out = <String>[];
for (final o in others) {
@@ -120,4 +163,7 @@ class DistractorGenerator {
}
}
String _toTitleCase(String s) => s.split(' ').map((w) => w.isEmpty ? w : (w[0].toUpperCase() + w.substring(1))).join(' ');
String _toTitleCase(String s) => s
.split(' ')
.map((w) => w.isEmpty ? w : (w[0].toUpperCase() + w.substring(1)))
.join(' ');

View File

@@ -0,0 +1,56 @@
import 'package:flutter_tts/flutter_tts.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
class TtsService {
FlutterTts? _flutterTts;
bool _isInitialized = false;
Future<void> initTts() async {
if (_isInitialized) return;
_flutterTts = FlutterTts();
if (_flutterTts != null) {
final isAvailable = await _flutterTts!.isLanguageAvailable("ja-JP");
if (isAvailable == true) {
await _flutterTts?.setLanguage("ja-JP");
} else {
debugPrint('Japanese (ja-JP) TTS language not available.');
}
}
_isInitialized = true;
}
Future<bool> isLanguageAvailable(String language) async {
if (_flutterTts == null) {
await initTts();
}
return await _flutterTts?.isLanguageAvailable(language) ?? false;
}
Future<void> speak(String text) async {
const int maxRetries = 3;
for (int i = 0; i < maxRetries; i++) {
try {
if (_flutterTts == null || !_isInitialized) {
await initTts();
}
await _flutterTts?.speak(text);
return;
} on PlatformException catch (_) {
debugPrint('TTS speak failed, retrying...');
await _flutterTts?.stop();
_flutterTts = null;
_isInitialized = false;
await Future.delayed(const Duration(milliseconds: 500));
}
}
debugPrint('Failed to speak after $maxRetries retries.');
}
void dispose() {
_flutterTts?.stop();
_flutterTts = null;
_isInitialized = false;
}
}

View File

@@ -1,15 +1,14 @@
import 'dart:async';
import 'dart:convert';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import '../models/kanji_item.dart';
import '../models/vocabulary_item.dart';
import '../models/srs_item.dart';
import '../api/wk_client.dart';
import 'database_helper.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
class VocabDeckRepository {
Database? _db;
String? _apiKey;
Future<void> setApiKey(String apiKey) async {
@@ -19,80 +18,8 @@ class VocabDeckRepository {
String? get apiKey => _apiKey;
Future<Database> _openDb() async {
if (_db != null) return _db!;
final dir = await getApplicationDocumentsDirectory();
final path = join(dir.path, 'wanikani_srs.db');
_db = await openDatabase(
path,
version: 7,
onCreate: (db, version) async {
await db.execute(
'''CREATE TABLE kanji (id INTEGER PRIMARY KEY, level INTEGER, characters TEXT, meanings TEXT, onyomi TEXT, kunyomi TEXT)''',
);
await db.execute(
'''CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT)''',
);
await db.execute(
'''CREATE TABLE srs_items (kanjiId INTEGER, quizMode TEXT, readingType TEXT, srsStage INTEGER, lastAsked TEXT, PRIMARY KEY (kanjiId, quizMode, readingType))''',
);
await db.execute(
'''CREATE TABLE vocabulary (id INTEGER PRIMARY KEY, level INTEGER, characters TEXT, meanings TEXT, readings TEXT, pronunciation_audios TEXT)''',
);
await db.execute(
'''CREATE TABLE srs_vocab_items (vocabId INTEGER, quizMode TEXT, srsStage INTEGER, lastAsked TEXT, PRIMARY KEY (vocabId, quizMode))''',
);
},
onUpgrade: (db, oldVersion, newVersion) async {
if (oldVersion < 2) {
await db.execute(
'''CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)''',
);
}
if (oldVersion < 3) {
// Migration from version 2 to 3 was flawed, so we just drop the columns if they exist
}
if (oldVersion < 4) {
await db.execute(
'''CREATE TABLE srs_items (kanjiId INTEGER, quizMode TEXT, readingType TEXT, srsStage INTEGER, lastAsked TEXT, PRIMARY KEY (kanjiId, quizMode, readingType))''',
);
// We are not migrating the old srs data, as it was not mode-specific.
// Old columns will be dropped.
}
if (oldVersion < 5) {
await db.execute(
'''CREATE TABLE vocabulary (id INTEGER PRIMARY KEY, characters TEXT, meanings TEXT, readings TEXT)''',
);
await db.execute(
'''CREATE TABLE srs_vocab_items (vocabId INTEGER, quizMode TEXT, srsStage INTEGER, lastAsked TEXT, PRIMARY KEY (vocabId, quizMode))''',
);
}
if (oldVersion < 6) {
try {
await db.execute(
'ALTER TABLE vocabulary ADD COLUMN pronunciation_audios TEXT',
);
} catch (_) {
// Ignore error, column might already exist
}
}
if (oldVersion < 7) {
try {
await db.execute('ALTER TABLE kanji ADD COLUMN level INTEGER');
await db.execute('ALTER TABLE vocabulary ADD COLUMN level INTEGER');
} catch (_) {
// Ignore error, column might already exist
}
}
},
);
return _db!;
}
Future<void> saveApiKey(String apiKey) async {
final db = await _openDb();
final db = await DatabaseHelper().db;
await db.insert('settings', {
'key': 'apiKey',
'value': apiKey,
@@ -104,8 +31,6 @@ class VocabDeckRepository {
try {
envApiKey = dotenv.env['WANIKANI_API_KEY'];
} catch (e) {
// dotenv is not initialized, so we can't get the key.
// This is expected in release builds.
envApiKey = null;
}
@@ -114,7 +39,7 @@ class VocabDeckRepository {
return _apiKey;
}
final db = await _openDb();
final db = await DatabaseHelper().db;
final rows = await db.query(
'settings',
where: 'key = ?',
@@ -127,50 +52,71 @@ class VocabDeckRepository {
return null;
}
Future<List<VocabSrsItem>> getVocabSrsItems(int vocabId) async {
final db = await _openDb();
Future<List<SrsItem>> getVocabSrsItems(int vocabId) async {
final db = await DatabaseHelper().db;
final rows = await db.query(
'srs_vocab_items',
where: 'vocabId = ?',
whereArgs: [vocabId],
);
return rows.map((r) {
return VocabSrsItem(
vocabId: r['vocabId'] as int,
quizMode: VocabQuizMode.values.firstWhere(
return SrsItem(
subjectId: r['vocabId'] as int,
quizMode: QuizMode.values.firstWhere(
(e) => e.toString() == r['quizMode'] as String,
),
srsStage: r['srsStage'] as int,
lastAsked: DateTime.parse(r['lastAsked'] as String),
disabled: (r['disabled'] as int? ?? 0) == 1,
);
}).toList();
}
Future<void> updateVocabSrsItem(VocabSrsItem item) async {
final db = await _openDb();
Future<void> updateSrsItems(List<SrsItem> items) async {
final db = await DatabaseHelper().db;
final batch = db.batch();
for (final item in items) {
batch.update(
'srs_vocab_items',
{
'srsStage': item.srsStage,
'lastAsked': item.lastAsked.toIso8601String(),
'disabled': item.disabled ? 1 : 0,
},
where: 'vocabId = ? AND quizMode = ?',
whereArgs: [item.subjectId, item.quizMode.toString()],
);
}
await batch.commit(noResult: true);
}
Future<void> updateVocabSrsItem(SrsItem item) async {
final db = await DatabaseHelper().db;
await db.update(
'srs_vocab_items',
{
'srsStage': item.srsStage,
'lastAsked': item.lastAsked.toIso8601String(),
'disabled': item.disabled ? 1 : 0,
},
where: 'vocabId = ? AND quizMode = ?',
whereArgs: [item.vocabId, item.quizMode.toString()],
whereArgs: [item.subjectId, item.quizMode.toString()],
);
}
Future<void> insertVocabSrsItem(VocabSrsItem item) async {
final db = await _openDb();
Future<void> insertVocabSrsItem(SrsItem item) async {
final db = await DatabaseHelper().db;
await db.insert('srs_vocab_items', {
'vocabId': item.vocabId,
'vocabId': item.subjectId,
'quizMode': item.quizMode.toString(),
'srsStage': item.srsStage,
'lastAsked': item.lastAsked.toIso8601String(),
'disabled': item.disabled ? 1 : 0,
}, conflictAlgorithm: ConflictAlgorithm.replace);
}
Future<void> saveVocabulary(List<VocabularyItem> items) async {
final db = await _openDb();
final db = await DatabaseHelper().db;
final batch = db.batch();
for (final it in items) {
final audios = it.pronunciationAudios
@@ -189,7 +135,7 @@ class VocabDeckRepository {
}
Future<List<VocabularyItem>> loadVocabulary() async {
final db = await _openDb();
final db = await DatabaseHelper().db;
final rows = await db.query('vocabulary');
final vocabItems = rows.map((r) {
final audiosRaw = r['pronunciation_audios'] as String?;
@@ -205,9 +151,7 @@ class VocabDeckRepository {
),
);
}
} catch (e) {
// Error decoding, so we'll just have no audio for this item
}
} finally {}
}
return VocabularyItem(
id: r['id'] as int,

131
lib/src/themes.dart Normal file
View File

@@ -0,0 +1,131 @@
import 'package:flutter/material.dart';
class SrsColors {
final Color level1;
final Color level2;
final Color level3;
final Color level4;
final Color level5;
final Color level6;
final Color level7;
final Color level8;
final Color level9;
const SrsColors({
required this.level1,
required this.level2,
required this.level3,
required this.level4,
required this.level5,
required this.level6,
required this.level7,
required this.level8,
required this.level9,
});
}
extension CustomTheme on ThemeData {
SrsColors get srsColors {
if (brightness == Brightness.dark) {
return const SrsColors(
level1: Color(0xFFE57373), // red
level2: Color(0xFFFFB74D), // orange
level3: Color(0xFFFFD54F), // yellow
level4: Color(0xFFDCE775), // lime
level5: Color(0xFFAED581), // light green
level6: Color(0xFF81C784), // green
level7: Color(0xFF4DB6AC), // teal
level8: Color(0xFF4FC3F7), // light blue
level9: Color(0xFF7986CB), // indigo
);
} else if (colorScheme.primary == const Color(0xFF7B6D53)) {
// Nier theme
return const SrsColors(
level1: Color(0xFFB71C1C), // dark red
level2: Color(0xFFD84315), // deep orange
level3: Color(0xFFF57F17), // yellow
level4: Color(0xFF9E9D24), // lime
level5: Color(0xFF558B2F), // light green
level6: Color(0xFF2E7D32), // green
level7: Color(0xFF00695C), // teal
level8: Color(0xFF0277BD), // light blue
level9: Color(0xFF283593), // indigo
);
} else {
// Light theme
return const SrsColors(
level1: Colors.red,
level2: Colors.orange,
level3: Colors.yellow,
level4: Colors.lightGreen,
level5: Colors.green,
level6: Colors.teal,
level7: Colors.cyan,
level8: Colors.blue,
level9: Colors.purple,
);
}
}
}
class Themes {
static final dark = ThemeData(
colorScheme: const ColorScheme(
brightness: Brightness.dark,
primary: Color(0xFF90CAF9),
onPrimary: Colors.black,
secondary: Color(0xFFBBDEFB),
onSecondary: Colors.black,
tertiary: Color(0xFFA5D6A7),
onTertiary: Colors.black,
error: Color(0xFFEF9A9A),
onError: Colors.black,
surface: Color(0xFF121212),
onSurface: Colors.white,
surfaceContainer: Color(0xFF1E1E1E),
surfaceContainerHighest: Color(0xFF424242),
onSurfaceVariant: Colors.white70,
),
useMaterial3: true,
);
static final light = ThemeData(
colorScheme: const ColorScheme(
brightness: Brightness.light,
primary: Color(0xFF1976D2),
onPrimary: Colors.white,
secondary: Color(0xFF42A5F5),
onSecondary: Colors.white,
tertiary: Color(0xFF66BB6A),
onTertiary: Colors.white,
error: Color(0xFFE57373),
onError: Colors.white,
surface: Color(0xFFFFFFFF),
onSurface: Colors.black,
surfaceContainer: Color(0xFFF5F5F5),
surfaceContainerHighest: Color(0xFFE0E0E0),
onSurfaceVariant: Colors.black54,
),
useMaterial3: true,
);
static final nier = ThemeData(
colorScheme: const ColorScheme(
brightness: Brightness.light,
primary: Color(0xFF7B6D53),
onPrimary: Colors.white,
secondary: Color(0xFFA99A7E),
onSecondary: Colors.white,
tertiary: Color(0xFFA99A7E),
onTertiary: Colors.white,
error: Color(0xFFD32F2F),
onError: Colors.white,
surface: Color(0xFFCFCBAA),
onSurface: Color(0xFF333333),
surfaceContainer: Color(0xFFBDB898),
surfaceContainerHighest: Color(0xFFA8A388),
onSurfaceVariant: Color(0xFF545454),
),
useMaterial3: true,
);
}

View File

@@ -19,13 +19,19 @@ class KanjiCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final bgColor = backgroundColor ?? theme.cardTheme.color ?? theme.colorScheme.surface;
final fgColor = textColor ?? theme.textTheme.bodyMedium?.color ?? theme.colorScheme.onSurface;
final bgColor =
backgroundColor ?? theme.cardTheme.color ?? theme.colorScheme.surface;
final fgColor =
textColor ??
theme.textTheme.bodyMedium?.color ??
theme.colorScheme.onSurface;
return Card(
elevation: theme.cardTheme.elevation ?? 12,
color: bgColor,
shape: theme.cardTheme.shape ?? RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
shape:
theme.cardTheme.shape ??
RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: SizedBox(
width: 360,
height: 240,

View File

@@ -39,20 +39,24 @@ class OptionsGrid extends StatelessWidget {
Color currentTextColor = fg;
if (showResult) {
if (correctAnswers != null && correctAnswers!.contains(o)) {
final normalizedOption = o.trim().toLowerCase();
if (correctAnswers != null &&
correctAnswers!
.map((e) => e.trim().toLowerCase())
.contains(normalizedOption)) {
currentButtonColor = theme.colorScheme.tertiary;
} else if (o == selectedOption) {
currentButtonColor = theme.colorScheme.error;
}
}
return SizedBox(
width: 160,
child: ElevatedButton(
onPressed: isDisabled ? null : () => onSelected(o),
onPressed: isDisabled || o == '---' ? null : () => onSelected(o),
style: ElevatedButton.styleFrom(
backgroundColor: currentButtonColor,
foregroundColor: currentTextColor,
disabledBackgroundColor:
theme.colorScheme.surfaceContainerHighest,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
@@ -60,7 +64,9 @@ class OptionsGrid extends StatelessWidget {
),
child: Text(
o,
style: theme.textTheme.titleMedium?.copyWith(color: currentTextColor),
style: theme.textTheme.titleMedium?.copyWith(
color: currentTextColor,
),
textAlign: TextAlign.center,
),
),
@@ -68,4 +74,4 @@ class OptionsGrid extends StatelessWidget {
}).toList(),
);
}
}
}

View File

@@ -34,4 +34,5 @@ flutter_icons:
flutter:
uses-material-design: true
assets:
- assets/sfx/confirm.mp3
- assets/sfx/correct.wav
- assets/sfx/incorrect.wav