Skip to content

Commit

Permalink
Merge pull request #142 from ZhuJHua/dev
Browse files Browse the repository at this point in the history
feat(ui): optimize UI for desktop platform
  • Loading branch information
ZhuJHua authored Jan 25, 2025
2 parents feed024 + 00395a2 commit 042da7d
Show file tree
Hide file tree
Showing 126 changed files with 2,201 additions and 1,905 deletions.
6 changes: 4 additions & 2 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ linter:
prefer_const_constructors: true
prefer_const_literals_to_create_immutables: true
prefer_const_declarations: true
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
prefer_final_in_for_each: true
prefer_final_fields: true
prefer_final_locals: true

analyzer:
plugins:
- custom_lint
Expand Down
44 changes: 22 additions & 22 deletions lib/api/api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,37 +12,36 @@ import 'package:moodiary/common/models/hunyuan.dart';
import 'package:moodiary/common/models/image.dart';
import 'package:moodiary/common/models/weather.dart';
import 'package:moodiary/main.dart';
import 'package:moodiary/presentation/pref.dart';
import 'package:moodiary/utils/http_util.dart';
import 'package:moodiary/utils/notice_util.dart';
import 'package:moodiary/utils/signature_util.dart';
import 'package:refreshed/refreshed.dart';

import '../utils/data/pref.dart';

class Api {
static Future<Stream<String>?> getHunYuan(
String id, String key, List<Message> messages, int model) async {
//获取时间戳
var timestamp = DateTime.now().millisecondsSinceEpoch;
var hunyuanModel = switch (model) {
final timestamp = DateTime.now().millisecondsSinceEpoch;
final hunyuanModel = switch (model) {
0 => 'hunyuan-lite',
1 => 'hunyuan-standard',
2 => 'hunyuan-pro',
3 => 'hunyuan-turbo',
_ => 'hunyuan-lite',
};
//请求正文
var body = {
final body = {
'Model': hunyuanModel,
'Messages': messages.map((value) => value.toMap()).toList(),
'Stream': true,
};

//获取签名
var authorization =
final authorization =
SignatureUtil.generateSignature(id, key, timestamp, body);
//构造请求头
var header = PublicHeader(
final header = PublicHeader(
'ChatCompletions', timestamp ~/ 1000, '2023-09-01', authorization);
//发起请求
return await HttpUtil().postStream('https://hunyuan.tencentcloudapi.com',
Expand Down Expand Up @@ -74,20 +73,20 @@ class Api {
locationSettings: AndroidSettings(forceLocationManager: true));
}
if (position != null) {
var local = Localizations.localeOf(Get.context!);
var parameters = {
final local = Localizations.localeOf(Get.context!);
final parameters = {
'location':
'${double.parse(position.longitude.toStringAsFixed(2))},${double.parse(position.latitude.toStringAsFixed(2))}',
'key': PrefUtil.getValue<String>('qweatherKey'),
'lang': local
};
var res = await HttpUtil().get(
final res = await HttpUtil().get(
'https://geoapi.qweather.com/v2/city/lookup',
parameters: parameters);
var geo =
final geo =
await compute(GeoResponse.fromJson, res.data as Map<String, dynamic>);
if (geo.location != null && geo.location!.isNotEmpty) {
var city = geo.location!.first;
final city = geo.location!.first;
return [
position.latitude.toString(),
position.longitude.toString(),
Expand All @@ -102,16 +101,17 @@ class Api {
}

static Future<List<String>?> updateWeather({required LatLng position}) async {
var local = Localizations.localeOf(Get.context!);
var parameters = {
final local = Localizations.localeOf(Get.context!);
final parameters = {
'location':
'${double.parse(position.longitude.toStringAsFixed(2))},${double.parse(position.latitude.toStringAsFixed(2))}',
'key': PrefUtil.getValue<String>('qweatherKey'),
'lang': local
};
var res = await HttpUtil().get('https://devapi.qweather.com/v7/weather/now',
final res = await HttpUtil().get(
'https://devapi.qweather.com/v7/weather/now',
parameters: parameters);
var weather = await compute(
final weather = await compute(
WeatherResponse.fromJson, res.data as Map<String, dynamic>);
if (weather.now != null) {
return [
Expand All @@ -125,27 +125,27 @@ class Api {
}

static Future<GithubRelease?> getGithubRelease() async {
var res = await HttpUtil()
final res = await HttpUtil()
.get('https://api.github.com/repos/ZhuJHua/moodiary/releases/latest');
if (res.data != null) {
var githubRelease = await compute(
final githubRelease = await compute(
GithubRelease.fromJson, res.data as Map<String, dynamic>);
return githubRelease;
}
return null;
}

static Future<List<String>?> updateHitokoto() async {
var res = await HttpUtil().get('https://v1.hitokoto.cn');
var hitokoto = await compute(
final res = await HttpUtil().get('https://v1.hitokoto.cn');
final hitokoto = await compute(
HitokotoResponse.fromJson, res.data as Map<String, dynamic>);
return [hitokoto.hitokoto!];
}

static Future<List<String>?> updateImageUrl() async {
var res = await HttpUtil()
final res = await HttpUtil()
.get('https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1');
BingImage bingImage =
final BingImage bingImage =
await compute(BingImage.fromJson, res.data as Map<String, dynamic>);
return ['https://cn.bing.com${bingImage.images?[0].url}'];
}
Expand Down
7 changes: 4 additions & 3 deletions lib/common/models/tflite.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class SquadExample {
String toString() => _repr();

String _repr() {
var s = StringBuffer();
final s = StringBuffer();
s.write('qas_id: ${_printableText(qasId)}, ');
s.write('question_text: ${_printableText(questionText)}, ');
s.write('doc_tokens: [${docTokens.join(' ')}]');
Expand Down Expand Up @@ -104,9 +104,10 @@ class RawResult {
});

List<int> getAnswerIndices() {
int startIndex =
final int startIndex =
startLogits.indexOf(startLogits.reduce((a, b) => a > b ? a : b));
int endIndex = endLogits.indexOf(endLogits.reduce((a, b) => a > b ? a : b));
final int endIndex =
endLogits.indexOf(endLogits.reduce((a, b) => a > b ? a : b));
return [startIndex, endIndex];
}

Expand Down
6 changes: 3 additions & 3 deletions lib/components/ask_question/ask_question_logic.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class AskQuestionLogic extends GetxController with WidgetsBindingObserver {
@override
void didChangeMetrics() {
WidgetsBinding.instance.addPostFrameCallback((_) {
var height = MediaQuery.viewInsetsOf(Get.context!).bottom;
final height = MediaQuery.viewInsetsOf(Get.context!).bottom;
if (heightList.isNotEmpty && height != heightList.last) {
if (height > heightList.last &&
state.keyboardState != KeyboardState.opening) {
Expand Down Expand Up @@ -85,7 +85,7 @@ class AskQuestionLogic extends GetxController with WidgetsBindingObserver {
// 添加提问
state.qaList.add(question);

var answer = await liteRunner.ask(content, question);
final answer = await liteRunner.ask(content, question);
// 添加回答
if (answer != null) {
state.qaList.add(answer);
Expand All @@ -103,7 +103,7 @@ class AskQuestionLogic extends GetxController with WidgetsBindingObserver {
}

Future<void> ask(String content) async {
var text = textEditingController.text;
final text = textEditingController.text;
if (text.isNotEmpty) {
//await getAnswer(content, text);
}
Expand Down
27 changes: 27 additions & 0 deletions lib/components/base/modal.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import 'package:flutter/material.dart';

class Modal extends StatelessWidget {
final Animation<double> animation;
final Function() onTap;

const Modal({super.key, required this.animation, required this.onTap});

@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return AnimatedBuilder(
animation: animation,
builder: (context, child) {
return Visibility(
visible: animation.value > 0,
child: ModalBarrier(
color: colorScheme.surfaceContainer
.withValues(alpha: 0.6 * animation.value),
barrierSemanticsDismissible: false,
onDismiss: onTap,
),
);
},
);
}
}
5 changes: 3 additions & 2 deletions lib/components/base/tab.dart
Original file line number Diff line number Diff line change
Expand Up @@ -229,9 +229,10 @@ class _TabStyle extends AnimatedWidget {
// Calculate adjusted height based on isSelected state.
double adjustedHeight(
double fontSize, double? currentHeight, bool isSelected) {
double effectiveHeight =
final double effectiveHeight =
currentHeight ?? 1.0; // Default height is 1.0 if null.
double actualLineHeight = fixPrecision(fontSize * effectiveHeight, 6);
final double actualLineHeight =
fixPrecision(fontSize * effectiveHeight, 6);
double adjustedLineHeight;
if (isSelected) {
// Use ceil for selected state to round up.
Expand Down
94 changes: 62 additions & 32 deletions lib/components/base/text.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import 'package:flutter/material.dart';
import 'package:moodiary/components/base/marquee.dart';
import 'package:moodiary/utils/data/pref.dart';
import 'package:moodiary/presentation/pref.dart';

Widget buildAdaptiveText({
required String text,
Expand Down Expand Up @@ -66,62 +66,92 @@ Widget buildAdaptiveText({
Widget getEllipsisText({
required String text,
required int maxLine,
required TextStyle textStyle,
required BuildContext context,
TextStyle? textStyle,
required TextScaler textScaler,
String ellipsis = '...',
}) {
return LayoutBuilder(builder: (context, constraints) {
if (text.isEmpty) {
return const SizedBox.shrink();
}
final maxAllowedWidth = constraints.maxWidth;
final fullTextWidth = _calculateTextWidth(text, textStyle, maxLine);
if (fullTextWidth <= maxAllowedWidth) {

double calculateTextWidth(String text) {
final span = TextSpan(text: text.fixAutoLines(), style: textStyle);
final tp = TextPainter(
text: span,
maxLines: 1,
textDirection: TextDirection.ltr,
textScaler: textScaler,
)..layout();
return tp.width;
}

TextPainter createTextPainter(String displayText) {
return TextPainter(
text: TextSpan(text: displayText.fixAutoLines(), style: textStyle),
maxLines: maxLine,
textDirection: TextDirection.ltr,
textScaler: textScaler,
)..layout(maxWidth: constraints.maxWidth);
}

if (!createTextPainter(text).didExceedMaxLines) {
return Text(
text,
text.fixAutoLines(),
maxLines: maxLine,
overflow: TextOverflow.ellipsis,
style: textStyle,
textScaler: textScaler,
);
}
final ellipsisWidth = _calculateTextWidth('...', textStyle, maxLine);

int leftIndex = 0;
int rightIndex = text.length;
double leftWidth = 0;
double rightWidth = 0;

String truncatedText = text;

int lastValidLeftIndex = 0;
int lastValidRightIndex = text.length;

while (leftIndex < rightIndex) {
final nextLeftWidth =
_calculateTextWidth(text[leftIndex], textStyle, maxLine) + leftWidth;
final nextLeftWidth = calculateTextWidth(text[leftIndex]) + leftWidth;
final nextRightWidth =
_calculateTextWidth(text[rightIndex - 1], textStyle, maxLine) +
rightWidth;
if (nextLeftWidth + rightWidth + ellipsisWidth > maxAllowedWidth) {
calculateTextWidth(text[rightIndex - 1]) + rightWidth;
final currentText =
'${text.substring(0, leftIndex)}$ellipsis${text.substring(rightIndex)}';
if (createTextPainter(currentText).didExceedMaxLines) {
break;
}
if (leftWidth <= rightWidth) {
leftWidth = nextLeftWidth;
leftIndex++;
} else {
rightWidth = nextRightWidth;
rightIndex--;
lastValidLeftIndex = leftIndex;
lastValidRightIndex = rightIndex;
if (leftWidth <= rightWidth) {
leftWidth = nextLeftWidth;
leftIndex++;
} else {
rightWidth = nextRightWidth;
rightIndex--;
}
}
}
final leftText = text.substring(0, leftIndex);
final rightText = text.substring(rightIndex);
final realText = '$leftText...$rightText';

final leftText = text.substring(0, lastValidLeftIndex);
final rightText = text.substring(lastValidRightIndex);

truncatedText = '$leftText$ellipsis$rightText';

return Text(
realText,
truncatedText.fixAutoLines(),
maxLines: maxLine,
style: textStyle,
textScaler: textScaler,
);
});
}

double _calculateTextWidth(String text, TextStyle style, int maxLines) {
final span = TextSpan(text: text, style: style);
final tp = TextPainter(
text: span,
maxLines: maxLines,
textDirection: TextDirection.ltr,
);
tp.layout();
return tp.width;
extension FixAutoLines on String {
String fixAutoLines() {
return Characters(this).join('\u{200B}');
}
}
5 changes: 3 additions & 2 deletions lib/components/category_add/category_add_logic.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import 'package:moodiary/common/models/isar/category.dart';
import 'package:moodiary/pages/edit/edit_logic.dart';
import 'package:moodiary/pages/home/diary/diary_logic.dart';
import 'package:moodiary/utils/data/isar.dart';
import 'package:moodiary/presentation/isar.dart';
import 'package:moodiary/utils/notice_util.dart';
import 'package:refreshed/refreshed.dart';

Expand All @@ -25,7 +25,8 @@ class CategoryAddLogic extends GetxController {

Future<void> addCategory({required String text}) async {
if (text.isNotEmpty) {
var res = await IsarUtil.insertACategory(Category()..categoryName = text);
final res =
await IsarUtil.insertACategory(Category()..categoryName = text);
if (res == false) {
NoticeUtil.showToast('已经存在同名分类,已自动重命名');
}
Expand Down
2 changes: 1 addition & 1 deletion lib/components/category_add/category_add_view.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class CategoryAddComponent extends StatelessWidget {
icon: const Icon(Icons.add),
label: Text(l10n.categoryManageAdd),
onPressed: () async {
var res = await showTextInputDialog(
final res = await showTextInputDialog(
context: context,
title: l10n.categoryManageAdd,
textFields: [
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:moodiary/pages/home/diary/diary_logic.dart';
import 'package:moodiary/presentation/isar.dart';
import 'package:moodiary/router/app_routes.dart';
import 'package:moodiary/utils/data/isar.dart';
import 'package:refreshed/refreshed.dart';

import 'category_choice_sheet_state.dart';
Expand Down
Loading

0 comments on commit 042da7d

Please sign in to comment.