1
0
mirror of https://github.com/h7x4/Jisho-Study-Tool.git synced 2024-12-22 13:57:29 +01:00

Miscellaneous refactoring

This commit is contained in:
Oystein Kristoffer Tveit 2022-01-23 18:12:42 +01:00
parent 9e50221abd
commit 2251001a27
15 changed files with 209 additions and 212 deletions

View File

@ -33,8 +33,9 @@ class _LanguageSelectorState extends State<LanguageSelector> {
Widget _languageOption(String language) => Widget _languageOption(String language) =>
Container( Container(
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0), padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
child: Center(child: Text(language)), child: Text(language),
); );
@override @override

View File

@ -14,7 +14,9 @@ class SearchResultsBody extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ListView( return ListView(
children: results.map((result) => SearchResultCard(result: result)).toList(), children: [
for (final result in results) SearchResultCard(result: result)
],
); );
} }
} }

View File

@ -27,6 +27,12 @@ class _AudioPlayerState extends State<AudioPlayer> {
bool _isPlaying(ja.PlayerState? state) => state != null && state.playing; bool _isPlaying(ja.PlayerState? state) => state != null && state.playing;
@override
void initState() {
player.setUrl(widget.audio.uri);
super.initState();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocBuilder<ThemeBloc, ThemeState>( return BlocBuilder<ThemeBloc, ThemeState>(
@ -70,10 +76,4 @@ class _AudioPlayerState extends State<AudioPlayer> {
}, },
); );
} }
@override
void initState() {
player.setUrl(widget.audio.uri);
super.initState();
}
} }

View File

@ -4,8 +4,11 @@ class Badge extends StatelessWidget {
final Widget? child; final Widget? child;
final Color color; final Color color;
const Badge({this.child, required this.color, Key? key,}) : super(key: key); const Badge({
Key? key,
this.child,
required this.color,
}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -18,10 +21,7 @@ class Badge extends StatelessWidget {
shape: BoxShape.circle, shape: BoxShape.circle,
color: color, color: color,
), ),
child: FittedBox( child: FittedBox(child: child),
child: Center( );
child: child, }
),
),
); }
} }

View File

@ -55,18 +55,17 @@ class KanjiRow extends StatelessWidget {
Wrap( Wrap(
spacing: 10, spacing: 10,
runSpacing: 10, runSpacing: 10,
children: kanji children: [
.map( for (final k in kanji)
(k) => InkWell( InkWell(
onTap: () => Navigator.pushNamed( onTap: () => Navigator.pushNamed(
context, context,
Routes.kanjiSearch, Routes.kanjiSearch,
arguments: k, arguments: k,
),
child: _kanjiBox(k),
), ),
child: _kanjiBox(k),
) )
.toList(), ],
), ),
], ],
); );

View File

@ -68,7 +68,8 @@ final Map<RegExp, Widget Function(String)> _patterns = {
_wiki(link: l, isJapanese: false), _wiki(link: l, isJapanese: false),
RegExp(r'^Read “.+” on Japanese Wikipedia$'): (l) => RegExp(r'^Read “.+” on Japanese Wikipedia$'): (l) =>
_wiki(link: l, isJapanese: true), _wiki(link: l, isJapanese: true),
RegExp(r'^Read “.+” on DBpedia$'): _dbpedia, // DBpedia comes through attribution.
// RegExp(r'^Read “.+” on DBpedia$'): _dbpedia,
}; };
class Links extends StatelessWidget { class Links extends StatelessWidget {
@ -86,24 +87,34 @@ class Links extends StatelessWidget {
// Copy sense.links so that it doesn't need to be modified. // Copy sense.links so that it doesn't need to be modified.
final List<JishoSenseLink> newLinks = List.from(links); final List<JishoSenseLink> newLinks = List.from(links);
final List<String> newStringLinks = [for (final l in newLinks) l.url];
final Map<RegExp, int> matches = {}; final Map<RegExp, int> matches = {};
for (int i = 0; i < newLinks.length; i++) for (int i = 0; i < newLinks.length; i++)
for (final RegExp p in _patterns.keys) for (final RegExp p in _patterns.keys)
if (p.hasMatch(newLinks[i].text)) matches[p] = i; if (p.hasMatch(newLinks[i].text)) matches[p] = i;
final List<String> newStringLinks = newLinks.map((l) => l.url).toList();
final List<Widget> icons = [ final List<Widget> icons = [
...matches.entries ...[
.map((m) => _patterns[m.key]!(newStringLinks[m.value])) for (final match in matches.entries)
.toList(), _patterns[match.key]!(newStringLinks[match.value])
],
if (attribution.dbpedia != null) _dbpedia(attribution.dbpedia!) if (attribution.dbpedia != null) _dbpedia(attribution.dbpedia!)
]; ];
(matches.values.toList()..sort()).reversed.forEach(newLinks.removeAt); (matches.values.toList()..sort()).reversed.forEach(newLinks.removeAt);
final List<Widget> otherLinks =
newLinks.map((e) => Text('[${e.text} -> ${e.url}]')).toList(); final List<Widget> otherLinks = [
for (final link in newLinks) ...[
InkWell(
onTap: () => _launch(link.url),
child: Text(
link.text,
style: const TextStyle(color: Colors.blue),
),
)
]
];
return [ return [
const Text('Links:', style: TextStyle(fontWeight: FontWeight.bold)), const Text('Links:', style: TextStyle(fontWeight: FontWeight.bold)),

View File

@ -5,16 +5,14 @@ class Notes extends StatelessWidget {
const Notes({Key? key, required this.notes}) : super(key: key); const Notes({Key? key, required this.notes}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Column(
return Column( crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, children: [
children: [ const Text(
const Text( 'Notes:',
'Notes:', style: TextStyle(fontWeight: FontWeight.bold),
style: TextStyle(fontWeight: FontWeight.bold), ),
), Text(notes.join(', ')),
Text(notes.join(', ')), ],
], );
);
}
} }

View File

@ -10,19 +10,18 @@ class OtherForms extends StatelessWidget {
const OtherForms({required this.forms, Key? key}) : super(key: key); const OtherForms({required this.forms, Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Column(
return Column( crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, children: forms.isNotEmpty
children: forms.isNotEmpty ? [
? [ const Text(
const Text( 'Other Forms:',
'Other Forms:', style: TextStyle(fontWeight: FontWeight.bold),
style: TextStyle(fontWeight: FontWeight.bold), ),
), Wrap(
Wrap( children: [
children: forms for (final form in forms)
.map( BlocBuilder<ThemeBloc, ThemeState>(
(form) => BlocBuilder<ThemeBloc, ThemeState>(
builder: (context, state) { builder: (context, state) {
return KanjiKanaBox( return KanjiKanaBox(
word: form, word: form,
@ -30,11 +29,9 @@ class OtherForms extends StatelessWidget {
); );
}, },
), ),
) ],
.toList(), ),
), ]
] : [],
: [], );
);
}
} }

View File

@ -1,15 +1,20 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:jisho_study_tool/routing/routes.dart';
import '../../../../../models/themes/theme.dart'; import '../../../../../models/themes/theme.dart';
import '../../../../../routing/routes.dart';
import 'search_chip.dart'; import 'search_chip.dart';
class Antonyms extends StatelessWidget { class Antonyms extends StatelessWidget {
final List<String> antonyms; final List<String> antonyms;
final ColorSet colors;
const Antonyms({ const Antonyms({
Key? key, Key? key,
required this.antonyms, required this.antonyms,
this.colors = const ColorSet(
foreground: Colors.white,
background: Colors.blue,
),
}) : super(key: key); }) : super(key: key);
@override @override
@ -25,20 +30,20 @@ class Antonyms extends StatelessWidget {
Wrap( Wrap(
spacing: 5, spacing: 5,
runSpacing: 5, runSpacing: 5,
children: antonyms children: [
.map( for (final antonym in antonyms)
(a) => InkWell( InkWell(
onTap: () => Navigator.pushNamed(context, Routes.search, arguments: a), onTap: () => Navigator.pushNamed(
child: SearchChip( context,
text: a, Routes.search,
colors: const ColorSet( arguments: antonym,
foreground: Colors.white,
background: Colors.blue,
),
),
), ),
) child: SearchChip(
.toList(), text: antonym,
colors: colors,
),
),
],
) )
], ],
); );

View File

@ -18,8 +18,9 @@ class EnglishDefinitions extends StatelessWidget {
runSpacing: 10.0, runSpacing: 10.0,
spacing: 5, spacing: 5,
crossAxisAlignment: WrapCrossAlignment.center, crossAxisAlignment: WrapCrossAlignment.center,
children: englishDefinitions children: [
.map((def) => SearchChip(text: def, colors: colors)) for (final def in englishDefinitions)
.toList(), SearchChip(text: def, colors: colors)
],
); );
} }

View File

@ -20,6 +20,9 @@ class Sense extends StatelessWidget {
this.meaning, this.meaning,
}) : super(key: key); }) : super(key: key);
// TODO: This assumes that there is only one antonym. However, the
// antonym system is made with the case of multiple antonyms
// in mind.
List<String> _removeAntonyms(List<String> supplementalInfo) { List<String> _removeAntonyms(List<String> supplementalInfo) {
for (int i = 0; i < supplementalInfo.length; i++) { for (int i = 0; i < supplementalInfo.length; i++) {
if (RegExp(r'^Antonym: .*$').hasMatch(supplementalInfo[i])) { if (RegExp(r'^Antonym: .*$').hasMatch(supplementalInfo[i])) {
@ -30,9 +33,9 @@ class Sense extends StatelessWidget {
return supplementalInfo; return supplementalInfo;
} }
List<String>? get _supplementalWithoutAntonyms => List<String>? get _supplementalWithoutAntonyms => meaning == null
(meaning == null) ? null : ? null
_removeAntonyms(List.from(meaning!.supplemental)); : _removeAntonyms(List.from(meaning!.supplemental));
bool get hasSupplementalInfo => bool get hasSupplementalInfo =>
sense.info.isNotEmpty || sense.info.isNotEmpty ||
@ -42,50 +45,47 @@ class Sense extends StatelessWidget {
@override @override
Widget build(BuildContext context) => BlocBuilder<ThemeBloc, ThemeState>( Widget build(BuildContext context) => BlocBuilder<ThemeBloc, ThemeState>(
builder: (context, state) { builder: (context, state) => Container(
return Container( margin: const EdgeInsets.symmetric(vertical: 5),
margin: const EdgeInsets.symmetric(vertical: 5), padding: const EdgeInsets.all(10),
padding: const EdgeInsets.all(10), decoration: BoxDecoration(
decoration: BoxDecoration( color: state.theme.menuGreyLight.background,
color: state.theme.menuGreyLight.background, borderRadius: BorderRadius.circular(10.0),
borderRadius: BorderRadius.circular(10.0), ),
), child: Column(
child: Column( crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
children: <Widget>[ Text(
Text( '${index + 1}. ${sense.partsOfSpeech.join(', ')}',
'${index + 1}. ${sense.partsOfSpeech.join(', ')}', style: const TextStyle(fontWeight: FontWeight.bold),
style: const TextStyle(fontWeight: FontWeight.bold), textAlign: TextAlign.left,
textAlign: TextAlign.left, ),
EnglishDefinitions(
englishDefinitions: sense.englishDefinitions,
colors: state.theme.menuGreyNormal,
),
if (hasSupplementalInfo)
SupplementalInfo(
sense: sense,
supplementalInfo: _supplementalWithoutAntonyms,
), ),
EnglishDefinitions( if (meaning?.definitionAbstract != null)
englishDefinitions: sense.englishDefinitions, DefinitionAbstract(
colors: state.theme.menuGreyNormal, text: meaning!.definitionAbstract!,
color: state.theme.foreground,
), ),
if (hasSupplementalInfo) if (sense.antonyms.isNotEmpty) Antonyms(antonyms: sense.antonyms),
SupplementalInfo( if (meaning != null && meaning!.sentences.isNotEmpty)
sense: sense, Sentences(sentences: meaning!.sentences)
supplementalInfo: _supplementalWithoutAntonyms, ]
.map(
(e) => Container(
margin: const EdgeInsets.symmetric(vertical: 5),
child: e,
), ),
if (meaning?.definitionAbstract != null) )
DefinitionAbstract( .toList(),
text: meaning!.definitionAbstract!, ),
color: state.theme.foreground, ),
),
if (sense.antonyms.isNotEmpty)
Antonyms(antonyms: sense.antonyms),
if (meaning != null && meaning!.sentences.isNotEmpty)
Sentences(sentences: meaning!.sentences)
]
.map(
(e) => Container(
margin: const EdgeInsets.symmetric(vertical: 5),
child: e,
),
)
.toList(),
),
);
},
); );
} }

View File

@ -25,29 +25,27 @@ class Sentences extends StatelessWidget {
children: [ children: [
Wrap( Wrap(
runSpacing: 10, runSpacing: 10,
children: [ children: sentence.pieces
...sentence.pieces .map(
.map( (p) => JishoJapaneseWord(
(p) => JishoJapaneseWord( word: p.unlifted,
word: p.unlifted, reading: p.lifted,
reading: p.lifted, ),
), )
) .map(
.map( (word) => KanjiKanaBox(
(word) => KanjiKanaBox( word: word,
word: word, showRomajiBelow: true,
showRomajiBelow: true, margin: EdgeInsets.zero,
margin: EdgeInsets.zero, padding: EdgeInsets.zero,
padding: EdgeInsets.zero, centerFurigana: false,
centerFurigana: false, autoTransliterateRomaji: false,
autoTransliterateRomaji: false, kanjiFontsize: 15,
kanjiFontsize: 15, furiganaFontsize: 12,
furiganaFontsize: 12, colors: colors,
colors: colors, ),
), )
) .toList(),
.toList(),
],
), ),
Divider( Divider(
height: 20, height: 20,
@ -63,9 +61,6 @@ class Sentences extends StatelessWidget {
); );
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) =>
return Column( Column(children: [for (final s in sentences) _sentence(s)]);
children: sentences.map((s) => _sentence(s)).toList(),
);
}
} }

View File

@ -18,7 +18,7 @@ class SupplementalInfo extends StatelessWidget {
if (restrictions.isNotEmpty) if (restrictions.isNotEmpty)
restrictions[0] = 'Only applies to ${restrictions[0]}'; restrictions[0] = 'Only applies to ${restrictions[0]}';
final List<String> combinedInfo = sense.tags + restrictions; final List<String> combinedInfo = sense.tags + sense.info + restrictions;
return Text( return Text(
combinedInfo.join(', '), combinedInfo.join(', '),
@ -32,8 +32,10 @@ class SupplementalInfo extends StatelessWidget {
return [ return [
if (sense.source.isNotEmpty) if (sense.source.isNotEmpty)
Text('From ${sense.source[0].language} ${sense.source[0].word}'), Text('From ${sense.source[0].language} ${sense.source[0].word}'),
if (sense.tags.isNotEmpty || sense.restrictions.isNotEmpty) _info(sense), if (sense.tags.isNotEmpty ||
if (sense.info.isNotEmpty) Text(sense.info.join(', ')) sense.restrictions.isNotEmpty ||
sense.info.isNotEmpty)
_info(sense),
]; ];
} }

View File

@ -14,34 +14,20 @@ class Senses extends StatelessWidget {
Key? key, Key? key,
}) : super(key: key); }) : super(key: key);
@override List<Widget> get _senseWidgets => [
Widget build(BuildContext context) { for (int i = 0; i < senses.length; i++)
final List<Widget> senseWidgets = senses Sense(
.asMap() index: i,
.map( sense: senses[i],
(k, v) => MapEntry( meaning: extraData?.firstWhereOrNull(
v, (m) => m.definition == senses[i].englishDefinitions.join('; '),
extraData?.firstWhereOrNull(
(m) => m.definition == v.englishDefinitions.join('; '),
), ),
), ),
) ];
.entries
.toList()
.asMap()
.entries
.map(
(e) => Sense(
index: e.key,
sense: e.value.key,
meaning: e.value.value,
),
)
.toList();
return Column( @override
crossAxisAlignment: CrossAxisAlignment.stretch, Widget build(BuildContext context) => Column(
children: senseWidgets, crossAxisAlignment: CrossAxisAlignment.stretch,
); children: _senseWidgets,
} );
} }

View File

@ -41,7 +41,7 @@ class _SearchResultCardState extends State<SearchResultCard> {
: Future(() => null); : Future(() => null);
List<JishoSenseLink> get links => List<JishoSenseLink> get links =>
widget.result.senses.map((s) => s.links).expand((l) => l).toList(); [for (final sense in widget.result.senses) ...sense.links];
bool get hasAttribution => bool get hasAttribution =>
widget.result.attribution.jmdict || widget.result.attribution.jmdict ||
@ -55,12 +55,15 @@ class _SearchResultCardState extends State<SearchResultCard> {
return jlpt.last; return jlpt.last;
} }
List<String> get kanji => List<String> get kanji => RegExp(r'(\p{Script=Hani})', unicode: true)
RegExp(r'(\p{Script=Hani})', unicode: true) .allMatches(
.allMatches(widget.result.japanese.map((w) => '${w.word ?? ""}${w.reading ?? ""}').join()) widget.result.japanese
.map((match) => match.group(0)!) .map((w) => '${w.word ?? ""}${w.reading ?? ""}')
.toSet() .join(),
.toList(); )
.map((match) => match.group(0)!)
.toSet()
.toList();
Widget get _header => IntrinsicWidth( Widget get _header => IntrinsicWidth(
child: Row( child: Row(
@ -83,6 +86,10 @@ class _SearchResultCardState extends State<SearchResultCard> {
), ),
); );
static const _margin = SizedBox(height: 20);
List<Widget> _withMargin(Widget w) => [_margin, w];
Widget _body({PhrasePageScrapeResultData? extendedData}) => Container( Widget _body({PhrasePageScrapeResultData? extendedData}) => Container(
padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 10), padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 10),
child: Column( child: Column(
@ -98,25 +105,18 @@ class _SearchResultCardState extends State<SearchResultCard> {
senses: widget.result.senses, senses: widget.result.senses,
extraData: extendedData?.meanings, extraData: extendedData?.meanings,
), ),
if (widget.otherForms.isNotEmpty) ...[ if (widget.otherForms.isNotEmpty)
const SizedBox(height: 20), ..._withMargin(OtherForms(forms: widget.otherForms)),
OtherForms(forms: widget.otherForms), if (extendedData != null && extendedData.notes.isNotEmpty)
], ..._withMargin(Notes(notes: extendedData.notes)),
if (extendedData != null && extendedData.notes.isNotEmpty) ...[ if (kanji.isNotEmpty) ..._withMargin(KanjiRow(kanji: kanji)),
const SizedBox(height: 20), if (links.isNotEmpty || hasAttribution)
Notes(notes: extendedData.notes), ..._withMargin(
], Links(
if (kanji.isNotEmpty) ...[ links: links,
const SizedBox(height: 20), attribution: widget.result.attribution,
KanjiRow(kanji: kanji), ),
], )
if (links.isNotEmpty || hasAttribution) ...[
const SizedBox(height: 20),
Links(
links: links,
attribution: widget.result.attribution,
),
]
], ],
), ),
); );