Add more content to search results (#31)

* Add lots of new functionality to search results

* Fix jlpt level

* Make antonyms clickable

* Add kanji list

* Replace Blocof with BlocBuilder

* Make kanji widgets squared

* Add missing colons to headers

* add romaji under sentences

* Fix extensive search not showing

* Miscellaneous refactoring
add-search-buttons-and-explanations
Oystein Kristoffer Tveit 2022-01-23 18:27:00 +01:00 committed by GitHub
parent 25a58d6f59
commit 28f900c02e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 985 additions and 164 deletions

BIN
assets/images/dbpedia.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

View File

@ -19,18 +19,17 @@ class KanjiBox extends StatelessWidget {
final colors = state.theme.menuGreyLight;
return Container(
padding: const EdgeInsets.all(5),
alignment: Alignment.center,
decoration: BoxDecoration(
color: colors.background,
borderRadius: BorderRadius.circular(10.0),
),
child: Center(
child: FittedBox(
child: Text(
kanji,
style: TextStyle(
color: colors.foreground,
fontSize: 25,
),
child: FittedBox(
child: Text(
kanji,
style: TextStyle(
color: colors.foreground,
fontSize: 25,
),
),
),

View File

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

View File

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

View File

@ -0,0 +1,79 @@
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart' as ja;
import 'package:unofficial_jisho_api/api.dart';
import '../../../../bloc/theme/theme_bloc.dart';
class AudioPlayer extends StatefulWidget {
final AudioFile audio;
const AudioPlayer({
Key? key,
required this.audio,
}) : super(key: key);
@override
_AudioPlayerState createState() => _AudioPlayerState();
}
class _AudioPlayerState extends State<AudioPlayer> {
final ja.AudioPlayer player = ja.AudioPlayer();
double _calculateRelativePlayerPosition(Duration? position) {
if (position != null && player.duration != null)
return position.inMilliseconds / player.duration!.inMilliseconds;
return 0;
}
bool _isPlaying(ja.PlayerState? state) => state != null && state.playing;
@override
void initState() {
player.setUrl(widget.audio.uri);
super.initState();
}
@override
Widget build(BuildContext context) {
return BlocBuilder<ThemeBloc, ThemeState>(
builder: (_, state) {
final ColorSet colors = state.theme.menuGreyLight;
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100),
color: colors.background,
),
child: Row(
children: [
IconButton(
onPressed: () => player.play().then((_) {
player.stop();
player.seek(Duration.zero);
}),
iconSize: 30,
icon: StreamBuilder<ja.PlayerState>(
stream: player.playerStateStream,
builder: (_, snapshot) => Icon(
_isPlaying(snapshot.data) ? Icons.stop : Icons.play_arrow,
),
),
),
Expanded(
child: StreamBuilder<Duration>(
stream: player.positionStream,
builder: (_, snapshot) => LinearProgressIndicator(
backgroundColor: colors.foreground,
value: _calculateRelativePlayerPosition(snapshot.data),
),
),
),
IconButton(icon: const Icon(Icons.volume_up), onPressed: () {}),
],
),
);
},
);
}
}

View File

@ -4,8 +4,11 @@ class Badge extends StatelessWidget {
final Widget? child;
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
Widget build(BuildContext context) {
@ -18,10 +21,7 @@ class Badge extends StatelessWidget {
shape: BoxShape.circle,
color: color,
),
child: FittedBox(
child: Center(
child: child,
),
),
); }
child: FittedBox(child: child),
);
}
}

View File

@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import './badge.dart';
class JLPTBadge extends StatelessWidget {
final String jlptLevel;
final String? jlptLevel;
const JLPTBadge({
required this.jlptLevel,
@ -10,12 +10,12 @@ class JLPTBadge extends StatelessWidget {
}) : super(key: key);
String get formattedJlptLevel =>
jlptLevel.isNotEmpty ? jlptLevel.substring(5).toUpperCase() : '';
jlptLevel != null ? jlptLevel!.substring(5).toUpperCase() : '';
@override
Widget build(BuildContext context) {
return Badge(
color: jlptLevel.isNotEmpty ? Colors.blue : Colors.transparent,
color: jlptLevel != null ? Colors.blue : Colors.transparent,
child: Text(
formattedJlptLevel,
style: const TextStyle(color: Colors.white),

View File

@ -0,0 +1,73 @@
import 'package:flutter/material.dart';
import '../../../../bloc/theme/theme_bloc.dart';
import '../../../../routing/routes.dart';
class KanjiRow extends StatelessWidget {
final List<String> kanji;
final double fontSize;
const KanjiRow({
Key? key,
required this.kanji,
this.fontSize = 20,
}) : super(key: key);
Widget _kanjiBox(String kanji) => UnconstrainedBox(
child: IntrinsicHeight(
child: AspectRatio(
aspectRatio: 1,
child: BlocBuilder<ThemeBloc, ThemeState>(
builder: (context, state) {
final colors = state.theme.menuGreyLight;
return Container(
padding: const EdgeInsets.all(10),
alignment: Alignment.center,
decoration: BoxDecoration(
color: colors.background,
borderRadius: BorderRadius.circular(10),
),
child: FittedBox(
child: Text(
kanji,
style: TextStyle(
color: colors.foreground,
fontSize: fontSize,
),
),
),
);
},
),
),
),
);
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Kanji:',
style: TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 5),
Wrap(
spacing: 10,
runSpacing: 10,
children: [
for (final k in kanji)
InkWell(
onTap: () => Navigator.pushNamed(
context,
Routes.kanjiSearch,
arguments: k,
),
child: _kanjiBox(k),
)
],
),
],
);
}
}

View File

@ -0,0 +1,94 @@
import 'package:flutter/material.dart';
import 'package:unofficial_jisho_api/api.dart';
import '../../../../models/themes/theme.dart';
import '../../../../services/romaji_transliteration.dart';
import '../../../../settings.dart';
class KanjiKanaBox extends StatelessWidget {
final JishoJapaneseWord word;
final bool showRomajiBelow;
final ColorSet colors;
final bool autoTransliterateRomaji;
final bool centerFurigana;
final double? furiganaFontsize;
final double? kanjiFontsize;
final EdgeInsets margin;
final EdgeInsets padding;
const KanjiKanaBox({
Key? key,
required this.word,
this.showRomajiBelow = false,
this.colors = LightTheme.defaultMenuGreyNormal,
this.autoTransliterateRomaji = true,
this.centerFurigana = true,
this.furiganaFontsize,
this.kanjiFontsize,
this.margin = const EdgeInsets.symmetric(
horizontal: 5.0,
vertical: 5.0,
),
this.padding = const EdgeInsets.all(5.0),
}) : super(key: key);
bool get hasFurigana => word.reading != null;
String get kana => '${word.reading ?? ""}${word.word ?? ""}'
.replaceAll(RegExp(r'\p{Script=Hani}', unicode: true), '');
@override
Widget build(BuildContext context) {
final String? wordReading = word.reading == null
? null
: (romajiEnabled && autoTransliterateRomaji
? transliterateKanaToLatin(word.reading!)
: word.reading!);
final fFontsize = furiganaFontsize ??
((kanjiFontsize != null) ? 0.8 * kanjiFontsize! : null);
return Container(
margin: margin,
padding: padding,
color: colors.background,
child: DefaultTextStyle.merge(
child: Column(
crossAxisAlignment: centerFurigana
? CrossAxisAlignment.center
: CrossAxisAlignment.start,
children: [
// See header.dart for more details about this logic
hasFurigana
? Text(
wordReading!,
style: TextStyle(
fontSize: fFontsize,
color: colors.foreground,
),
)
: Text(
'',
style: TextStyle(
color: Colors.transparent,
fontSize: fFontsize,
),
),
DefaultTextStyle.merge(
child: hasFurigana
? Text(word.word!)
: Text(wordReading ?? word.word!),
style: TextStyle(fontSize: kanjiFontsize),
),
if (romajiEnabled && showRomajiBelow)
Text(
transliterateKanaToLatin(kana),
)
],
),
style: TextStyle(color: colors.foreground),
),
);
}
}

View File

@ -0,0 +1,131 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:unofficial_jisho_api/api.dart';
import 'package:url_launcher/url_launcher.dart';
Future<void> _launch(String url) async {
if (await canLaunch(url)) {
launch(url);
} else {
debugPrint('Could not open url: $url');
}
}
final BoxDecoration _iconStyle = BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.all(Radius.circular(10)),
border: Border.all(),
);
Widget _wiki({
required String link,
required bool isJapanese,
}) =>
Container(
margin: const EdgeInsets.only(right: 10),
child: Stack(
alignment: Alignment.bottomRight,
children: [
Container(
decoration: _iconStyle,
margin: EdgeInsets.fromLTRB(0, 0, 10, isJapanese ? 12 : 10),
child: IconButton(
onPressed: () => _launch(link),
icon: SvgPicture.asset('assets/images/wikipedia.svg'),
),
),
Container(
padding: EdgeInsets.all(isJapanese ? 10 : 8),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
border: Border.all(),
),
child: Text(
isJapanese ? 'J' : 'E',
style: const TextStyle(
color: Colors.black,
fontFamily: 'serif',
),
),
),
],
),
);
Widget _dbpedia(String link) => Container(
decoration: _iconStyle,
child: IconButton(
onPressed: () => _launch(link),
icon: Image.asset(
'assets/images/dbpedia.png',
),
),
);
final Map<RegExp, Widget Function(String)> _patterns = {
RegExp(r'^Read “.+” on English Wikipedia$'): (l) =>
_wiki(link: l, isJapanese: false),
RegExp(r'^Read “.+” on Japanese Wikipedia$'): (l) =>
_wiki(link: l, isJapanese: true),
// DBpedia comes through attribution.
// RegExp(r'^Read “.+” on DBpedia$'): _dbpedia,
};
class Links extends StatelessWidget {
final List<JishoSenseLink> links;
final JishoAttribution attribution;
const Links({
Key? key,
required this.links,
required this.attribution,
}) : super(key: key);
List<Widget> get _body {
if (links.isEmpty) return [];
// Copy sense.links so that it doesn't need to be modified.
final List<JishoSenseLink> newLinks = List.from(links);
final List<String> newStringLinks = [for (final l in newLinks) l.url];
final Map<RegExp, int> matches = {};
for (int i = 0; i < newLinks.length; i++)
for (final RegExp p in _patterns.keys)
if (p.hasMatch(newLinks[i].text)) matches[p] = i;
final List<Widget> icons = [
...[
for (final match in matches.entries)
_patterns[match.key]!(newStringLinks[match.value])
],
if (attribution.dbpedia != null) _dbpedia(attribution.dbpedia!)
];
(matches.values.toList()..sort()).reversed.forEach(newLinks.removeAt);
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 [
const Text('Links:', style: TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(height: 5),
Row(crossAxisAlignment: CrossAxisAlignment.start, children: icons),
const SizedBox(height: 5),
if (otherLinks.isNotEmpty) ...otherLinks,
];
}
@override
Widget build(BuildContext context) =>
Column(crossAxisAlignment: CrossAxisAlignment.start, children: _body);
}

View File

@ -0,0 +1,18 @@
import 'package:flutter/material.dart';
class Notes extends StatelessWidget {
final List<String> notes;
const Notes({Key? key, required this.notes}) : super(key: key);
@override
Widget build(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Notes:',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(notes.join(', ')),
],
);
}

View File

@ -2,8 +2,7 @@ import 'package:flutter/material.dart';
import 'package:unofficial_jisho_api/api.dart';
import '../../../../bloc/theme/theme_bloc.dart';
import '../../../../services/romaji_transliteration.dart';
import '../../../../settings.dart';
import 'kanji_kana_box.dart';
class OtherForms extends StatelessWidget {
final List<JishoJapaneseWord> forms;
@ -11,68 +10,28 @@ class OtherForms extends StatelessWidget {
const OtherForms({required this.forms, Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: forms.isNotEmpty
? [
const Text(
'Other Forms',
style: TextStyle(fontWeight: FontWeight.bold),
),
Row(
children: forms.map((form) => _KanaBox(form)).toList(),
),
]
: [],
);
}
}
class _KanaBox extends StatelessWidget {
final JishoJapaneseWord word;
const _KanaBox(this.word);
bool get hasFurigana => word.word != null;
@override
Widget build(BuildContext context) {
final _menuColors =
BlocProvider.of<ThemeBloc>(context).state.theme.menuGreyLight;
final String? wordReading = word.reading == null
? null
: (romajiEnabled
? transliterateKanaToLatin(word.reading!)
: word.reading!);
return Container(
margin: const EdgeInsets.symmetric(
horizontal: 5.0,
vertical: 5.0,
),
padding: const EdgeInsets.all(5.0),
decoration: BoxDecoration(
color: _menuColors.background,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 1,
blurRadius: 0.5,
offset: const Offset(1, 1),
),
],
),
child: DefaultTextStyle.merge(
child: Column(
children: [
// See header.dart for more details about this logic
hasFurigana ? Text(wordReading ?? '') : const Text(''),
hasFurigana ? Text(word.word!) : Text(wordReading ?? word.word!),
],
),
style: TextStyle(color: _menuColors.foreground),
),
);
}
Widget build(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: forms.isNotEmpty
? [
const Text(
'Other Forms:',
style: TextStyle(fontWeight: FontWeight.bold),
),
Wrap(
children: [
for (final form in forms)
BlocBuilder<ThemeBloc, ThemeState>(
builder: (context, state) {
return KanjiKanaBox(
word: form,
colors: state.theme.menuGreyLight,
);
},
),
],
),
]
: [],
);
}

View File

@ -0,0 +1,51 @@
import 'package:flutter/material.dart';
import '../../../../../models/themes/theme.dart';
import '../../../../../routing/routes.dart';
import 'search_chip.dart';
class Antonyms extends StatelessWidget {
final List<String> antonyms;
final ColorSet colors;
const Antonyms({
Key? key,
required this.antonyms,
this.colors = const ColorSet(
foreground: Colors.white,
background: Colors.blue,
),
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'Antonyms:',
style: TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 5),
Wrap(
spacing: 5,
runSpacing: 5,
children: [
for (final antonym in antonyms)
InkWell(
onTap: () => Navigator.pushNamed(
context,
Routes.search,
arguments: antonym,
),
child: SearchChip(
text: antonym,
colors: colors,
),
),
],
)
],
);
}
}

View File

@ -0,0 +1,20 @@
import 'package:flutter/material.dart';
class DefinitionAbstract extends StatelessWidget {
final String text;
final Color? color;
const DefinitionAbstract({
Key? key,
required this.text,
this.color,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(
text,
style: TextStyle(color: color),
);
}
}

View File

@ -0,0 +1,26 @@
import 'package:flutter/material.dart';
import '../../../../../bloc/theme/theme_bloc.dart';
import 'search_chip.dart';
class EnglishDefinitions extends StatelessWidget {
final List<String> englishDefinitions;
final ColorSet colors;
const EnglishDefinitions({
Key? key,
required this.englishDefinitions,
this.colors = LightTheme.defaultMenuGreyNormal,
}) : super(key: key);
@override
Widget build(BuildContext context) => Wrap(
runSpacing: 10.0,
spacing: 5,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
for (final def in englishDefinitions)
SearchChip(text: def, colors: colors)
],
);
}

View File

@ -0,0 +1,27 @@
import 'package:flutter/material.dart';
import '../../../../../models/themes/theme.dart';
class SearchChip extends StatelessWidget {
final String text;
final ColorSet colors;
const SearchChip({
Key? key,
required this.text,
this.colors = LightTheme.defaultMenuGreyNormal,
}) : super(key: key);
@override
Widget build(BuildContext context) => Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: colors.background,
borderRadius: BorderRadius.circular(10.0),
),
child: Text(
text,
style: TextStyle(color: colors.foreground),
),
);
}

View File

@ -0,0 +1,91 @@
import 'package:flutter/material.dart';
import 'package:unofficial_jisho_api/api.dart';
import '../../../../../bloc/theme/theme_bloc.dart';
import 'antonyms.dart';
import 'definition_abstract.dart';
import 'english_definitions.dart';
import 'sentences.dart';
import 'supplemental_info.dart';
class Sense extends StatelessWidget {
final int index;
final JishoWordSense sense;
final PhraseScrapeMeaning? meaning;
const Sense({
Key? key,
required this.index,
required this.sense,
this.meaning,
}) : 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) {
for (int i = 0; i < supplementalInfo.length; i++) {
if (RegExp(r'^Antonym: .*$').hasMatch(supplementalInfo[i])) {
supplementalInfo.removeAt(i);
break;
}
}
return supplementalInfo;
}
List<String>? get _supplementalWithoutAntonyms => meaning == null
? null
: _removeAntonyms(List.from(meaning!.supplemental));
bool get hasSupplementalInfo =>
sense.info.isNotEmpty ||
sense.source.isNotEmpty ||
sense.tags.isNotEmpty ||
(_supplementalWithoutAntonyms?.isNotEmpty ?? false);
@override
Widget build(BuildContext context) => BlocBuilder<ThemeBloc, ThemeState>(
builder: (context, state) => Container(
margin: const EdgeInsets.symmetric(vertical: 5),
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: state.theme.menuGreyLight.background,
borderRadius: BorderRadius.circular(10.0),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'${index + 1}. ${sense.partsOfSpeech.join(', ')}',
style: const TextStyle(fontWeight: FontWeight.bold),
textAlign: TextAlign.left,
),
EnglishDefinitions(
englishDefinitions: sense.englishDefinitions,
colors: state.theme.menuGreyNormal,
),
if (hasSupplementalInfo)
SupplementalInfo(
sense: sense,
supplementalInfo: _supplementalWithoutAntonyms,
),
if (meaning?.definitionAbstract != null)
DefinitionAbstract(
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

@ -0,0 +1,66 @@
import 'package:flutter/material.dart';
import 'package:unofficial_jisho_api/api.dart';
import '../../../../../models/themes/theme.dart';
import '../kanji_kana_box.dart';
class Sentences extends StatelessWidget {
final List<PhraseScrapeSentence> sentences;
final ColorSet colors;
const Sentences({
Key? key,
required this.sentences,
this.colors = LightTheme.defaultMenuGreyNormal,
}) : super(key: key);
Widget _sentence(PhraseScrapeSentence sentence) => Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: colors.background,
borderRadius: BorderRadius.circular(10),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
runSpacing: 10,
children: sentence.pieces
.map(
(p) => JishoJapaneseWord(
word: p.unlifted,
reading: p.lifted,
),
)
.map(
(word) => KanjiKanaBox(
word: word,
showRomajiBelow: true,
margin: EdgeInsets.zero,
padding: EdgeInsets.zero,
centerFurigana: false,
autoTransliterateRomaji: false,
kanjiFontsize: 15,
furiganaFontsize: 12,
colors: colors,
),
)
.toList(),
),
Divider(
height: 20,
color: Colors.grey[400],
thickness: 3,
),
Text(
sentence.english,
style: TextStyle(color: colors.foreground),
),
],
),
);
@override
Widget build(BuildContext context) =>
Column(children: [for (final s in sentences) _sentence(s)]);
}

View File

@ -0,0 +1,47 @@
import 'package:flutter/material.dart';
import 'package:unofficial_jisho_api/api.dart';
class SupplementalInfo extends StatelessWidget {
final JishoWordSense sense;
final List<String>? supplementalInfo;
final Color? color;
const SupplementalInfo({
Key? key,
required this.sense,
this.supplementalInfo,
this.color,
}) : super(key: key);
Widget _info(JishoWordSense sense) {
final List<String> restrictions = List.from(sense.restrictions);
if (restrictions.isNotEmpty)
restrictions[0] = 'Only applies to ${restrictions[0]}';
final List<String> combinedInfo = sense.tags + sense.info + restrictions;
return Text(
combinedInfo.join(', '),
style: TextStyle(color: color),
);
}
List<Widget> get _body {
if (supplementalInfo != null) return [Text(supplementalInfo!.join(', '))];
return [
if (sense.source.isNotEmpty)
Text('From ${sense.source[0].language} ${sense.source[0].word}'),
if (sense.tags.isNotEmpty ||
sense.restrictions.isNotEmpty ||
sense.info.isNotEmpty)
_info(sense),
];
}
@override
Widget build(BuildContext context) => DefaultTextStyle.merge(
child: Column(children: _body),
style: TextStyle(color: color),
);
}

View File

@ -1,62 +1,33 @@
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:unofficial_jisho_api/parser.dart';
import 'package:unofficial_jisho_api/api.dart';
import 'sense/sense.dart';
class Senses extends StatelessWidget {
final List<JishoWordSense> senses;
final List<PhraseScrapeMeaning>? extraData;
const Senses({
required this.senses,
this.extraData,
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final List<Widget> senseWidgets =
senses.asMap().entries.map((e) => _Sense(e.key, e.value)).toList();
return Column(
children: senseWidgets,
);
}
}
class _Sense extends StatelessWidget {
final int index;
final JishoWordSense sense;
const _Sense(this.index, this.sense);
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
Text(
'${index + 1}. ',
style: const TextStyle(color: Colors.grey),
List<Widget> get _senseWidgets => [
for (int i = 0; i < senses.length; i++)
Sense(
index: i,
sense: senses[i],
meaning: extraData?.firstWhereOrNull(
(m) => m.definition == senses[i].englishDefinitions.join('; '),
),
Text(
sense.partsOfSpeech.join(', '),
style: const TextStyle(fontWeight: FontWeight.bold),
textAlign: TextAlign.left,
),
],
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
margin: const EdgeInsets.fromLTRB(0, 5, 0, 15),
child: Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children:
sense.englishDefinitions.map((def) => Text(def)).toList(),
),
],
),
),
],
);
}
];
@override
Widget build(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: _senseWidgets,
);
}

View File

@ -7,8 +7,13 @@ import './parts/jlpt_badge.dart';
import './parts/other_forms.dart';
import './parts/senses.dart';
import './parts/wanikani_badge.dart';
import '../../../settings.dart';
import 'parts/audio_player.dart';
import 'parts/kanji.dart';
import 'parts/links.dart';
import 'parts/notes.dart';
class SearchResultCard extends StatelessWidget {
class SearchResultCard extends StatefulWidget {
final JishoResult result;
late final JishoJapaneseWord mainWord;
late final List<JishoJapaneseWord> otherForms;
@ -21,46 +26,127 @@ class SearchResultCard extends StatelessWidget {
super(key: key);
@override
Widget build(BuildContext context) {
final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
return ExpansionTile(
collapsedBackgroundColor: backgroundColor,
backgroundColor: backgroundColor,
title: IntrinsicWidth(
_SearchResultCardState createState() => _SearchResultCardState();
}
class _SearchResultCardState extends State<SearchResultCard> {
PhrasePageScrapeResultData? extraData;
Future<PhrasePageScrapeResult?> _scrape(JishoResult result) =>
(!(result.japanese[0].word == null && result.japanese[0].reading == null))
? scrapeForPhrase(
widget.result.japanese[0].word ??
widget.result.japanese[0].reading!,
)
: Future(() => null);
List<JishoSenseLink> get links =>
[for (final sense in widget.result.senses) ...sense.links];
bool get hasAttribution =>
widget.result.attribution.jmdict ||
widget.result.attribution.jmnedict ||
(widget.result.attribution.dbpedia != null);
String? get jlptLevel {
if (widget.result.jlpt.isEmpty) return null;
final jlpt = List.from(widget.result.jlpt);
jlpt.sort();
return jlpt.last;
}
List<String> get kanji => RegExp(r'(\p{Script=Hani})', unicode: true)
.allMatches(
widget.result.japanese
.map((w) => '${w.word ?? ""}${w.reading ?? ""}')
.join(),
)
.map((match) => match.group(0)!)
.toSet()
.toList();
Widget get _header => IntrinsicWidth(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
JapaneseHeader(word: mainWord),
JapaneseHeader(word: widget.mainWord),
Row(
children: [
WKBadge(
level: result.tags.firstWhere(
level: widget.result.tags.firstWhere(
(tag) => tag.contains('wanikani'),
orElse: () => '',
),
),
JLPTBadge(
jlptLevel: result.jlpt.isNotEmpty ? result.jlpt[0] : '',
),
CommonBadge(isCommon: result.isCommon ?? false)
JLPTBadge(jlptLevel: jlptLevel),
CommonBadge(isCommon: widget.result.isCommon ?? false)
],
)
],
),
),
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: Column(
children: [
Senses(senses: result.senses),
OtherForms(forms: otherForms),
// Text(result.toJson().toString()),
// Text(result.attribution.toJson().toString()),
// Text(result.japanese.map((e) => e.toJson().toString()).toList().toString()),
);
static const _margin = SizedBox(height: 20);
List<Widget> _withMargin(Widget w) => [_margin, w];
Widget _body({PhrasePageScrapeResultData? extendedData}) => Container(
padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (extendedData != null && extendedData.audio.isNotEmpty) ...[
// TODO: There's usually multiple mimetypes in the data.
// If one mimetype fails, the app should try to use another one.
AudioPlayer(audio: extendedData.audio.first),
const SizedBox(height: 10),
],
),
)
Senses(
senses: widget.result.senses,
extraData: extendedData?.meanings,
),
if (widget.otherForms.isNotEmpty)
..._withMargin(OtherForms(forms: widget.otherForms)),
if (extendedData != null && extendedData.notes.isNotEmpty)
..._withMargin(Notes(notes: extendedData.notes)),
if (kanji.isNotEmpty) ..._withMargin(KanjiRow(kanji: kanji)),
if (links.isNotEmpty || hasAttribution)
..._withMargin(
Links(
links: links,
attribution: widget.result.attribution,
),
)
],
),
);
@override
Widget build(BuildContext context) {
final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
return ExpansionTile(
collapsedBackgroundColor: backgroundColor,
backgroundColor: backgroundColor,
onExpansionChanged: (b) async {
if (extensiveSearchEnabled && extraData == null) {
final data = await _scrape(widget.result);
setState(() {
extraData = (data != null && data.found) ? data.data : null;
});
}
},
title: _header,
children: [
if (extensiveSearchEnabled && extraData == null)
const Padding(
padding: EdgeInsets.symmetric(vertical: 10),
child: Center(child: CircularProgressIndicator()),
)
else if (extraData != null)
_body(extendedData: extraData)
else
_body()
],
);
}

View File

@ -60,6 +60,17 @@ class _SettingsViewState extends State<SettingsView> {
switchValue: romajiEnabled,
switchActiveColor: AppTheme.jishoGreen.background,
),
SettingsTile.switchTile(
title: 'Extensive search',
onToggle: (b) {
setState(() => extensiveSearchEnabled = b);
},
switchValue: extensiveSearchEnabled,
switchActiveColor: AppTheme.jishoGreen.background,
subtitle:
'Gathers extra data when searching for words, at the expense of having to wait for extra word details',
subtitleMaxLines: 3,
),
],
),
SettingsSection(

View File

@ -5,6 +5,7 @@ final SharedPreferences _prefs = GetIt.instance.get<SharedPreferences>();
const Map<String, dynamic> _defaults = {
'romajiEnabled': false,
'extensiveSearch': true,
'darkThemeEnabled': false,
'autoThemeEnabled': false,
};
@ -13,9 +14,11 @@ bool _getSettingOrDefault(String settingName) =>
_prefs.getBool(settingName) ?? _defaults[settingName];
bool get romajiEnabled => _getSettingOrDefault('romajiEnabled');
bool get extensiveSearchEnabled => _getSettingOrDefault('extensiveSearch');
bool get darkThemeEnabled => _getSettingOrDefault('darkThemeEnabled');
bool get autoThemeEnabled => _getSettingOrDefault('autoThemeEnabled');
set romajiEnabled(b) => _prefs.setBool('romajiEnabled', b);
set extensiveSearchEnabled(b) => _prefs.setBool('extensiveSearch', b);
set darkThemeEnabled(b) => _prefs.setBool('darkThemeEnabled', b);
set autoThemeEnabled(b) => _prefs.setBool('autoThemeEnabled', b);

View File

@ -43,6 +43,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "2.8.2"
audio_session:
dependency: transitive
description:
name: audio_session
url: "https://pub.dartlang.org"
source: hosted
version: "0.1.6+1"
bloc:
dependency: transitive
description:
@ -156,7 +163,7 @@ packages:
source: hosted
version: "4.1.0"
collection:
dependency: transitive
dependency: "direct main"
description:
name: collection
url: "https://pub.dartlang.org"
@ -272,6 +279,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "1.2.0"
flutter_svg:
dependency: "direct main"
description:
name: flutter_svg
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.2"
flutter_test:
dependency: "direct dev"
description: flutter
@ -373,6 +387,27 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "4.4.0"
just_audio:
dependency: "direct main"
description:
name: just_audio
url: "https://pub.dartlang.org"
source: hosted
version: "0.9.18"
just_audio_platform_interface:
dependency: transitive
description:
name: just_audio_platform_interface
url: "https://pub.dartlang.org"
source: hosted
version: "4.0.0"
just_audio_web:
dependency: transitive
description:
name: just_audio_web
url: "https://pub.dartlang.org"
source: hosted
version: "0.4.2"
logging:
dependency: transitive
description:
@ -429,6 +464,20 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "1.8.0"
path_drawing:
dependency: transitive
description:
name: path_drawing
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.0"
path_parsing:
dependency: transitive
description:
name: path_parsing
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.0"
path_provider:
dependency: "direct main"
description:
@ -534,6 +583,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "1.2.0"
rxdart:
dependency: transitive
description:
name: rxdart
url: "https://pub.dartlang.org"
source: hosted
version: "0.27.3"
sembast:
dependency: "direct main"
description:
@ -763,6 +819,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.2"
uuid:
dependency: transitive
description:
name: uuid
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.5"
vector_math:
dependency: transitive
description:

View File

@ -7,14 +7,17 @@ environment:
dependencies:
animated_size_and_fade: ^3.0.0
collection: ^1.15.0
confirm_dialog: ^1.0.0
division: ^0.9.0
flutter:
sdk: flutter
flutter_bloc: ^8.0.0
flutter_slidable: ^1.1.0
flutter_svg: ^1.0.2
get_it: ^7.2.0
http: ^0.13.4
just_audio: ^0.9.18
mdi: ^5.0.0-nullsafety.0
path: ^1.8.0
path_provider: ^2.0.2
@ -41,7 +44,7 @@ flutter:
uses-material-design: true
assets:
- assets/images/denshi_jisho_background_overlay.png
- assets/images/
- assets/images/logo/
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg