Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Revamp Auth UI with Ente components

Neeraj Gupta68bfe8ad89d7
diff --git a/mobile/apps/auth/changes/auth-ui-refresh.md b/mobile/apps/auth/changes/auth-ui-refresh.md
new file mode 100644
index 0000000000..3fb9faba22
--- /dev/null
+++ b/mobile/apps/auth/changes/auth-ui-refresh.md
@@ -0,0 +1,2 @@
+- Refreshed settings, setup, imports, and code management with a consistent Ente design.
+- Improved Google Authenticator imports by completing multi-part migrations before returning to your codes.
diff --git a/mobile/apps/auth/lib/main.dart b/mobile/apps/auth/lib/main.dart
index 391e343a9f..1ca8af3042 100644
--- a/mobile/apps/auth/lib/main.dart
+++ b/mobile/apps/auth/lib/main.dart
@@ -22,6 +22,7 @@ import 'package:ente_auth/store/code_display_store.dart';
import 'package:ente_auth/store/code_store.dart';
import 'package:ente_auth/ui/home_page.dart';
import 'package:ente_auth/ui/utils/icon_utils.dart';
+import 'package:ente_auth/utils/debug_build_flags.dart';
import 'package:ente_auth/utils/directory_utils.dart' as auth_dir_utils;
import 'package:ente_auth/utils/gallery_import_util.dart';
import 'package:ente_auth/utils/window_protocol_handler.dart';
@@ -120,6 +121,7 @@ Future<void> _runInForeground() async {
runApp(
AppLock(
builder: (args) => App(locale: locale, savedThemeMode: savedThemeMode),
+ debugShowCheckedModeBanner: false,
lockScreen: LockScreen(configuration),
enabled: await LockScreenSettings.instance.shouldShowLockScreen(),
locale: locale,
@@ -188,6 +190,9 @@ Future<void> _init(bool bool, {String? via}) async {
hasOptedForOfflineMode: Configuration.instance.hasOptedForOfflineMode(),
hideAppContentDefault: true,
);
+ if (shouldAllowAuthScreenCapture) {
+ await LockScreenSettings.instance.setHideAppContent(false, persist: false);
+ }
AccountDeletionSettings.instance.init(
host: Configuration.instance,
enteDio: Network.instance.enteDio,
diff --git a/mobile/apps/auth/lib/models/code.dart b/mobile/apps/auth/lib/models/code.dart
index 82751d265e..a8af147a54 100644
--- a/mobile/apps/auth/lib/models/code.dart
+++ b/mobile/apps/auth/lib/models/code.dart
@@ -161,14 +161,17 @@ class Code {
_getType(uri),
_getCounter(uri),
rawData,
- display: CodeDisplay.fromUri(uri) ?? CodeDisplay(),
+ display: display ?? CodeDisplay.fromUri(uri) ?? CodeDisplay(),
);
return code;
} catch (e) {
// if account name contains # without encoding,
// rest of the url are treated as url fragment
if (rawData.contains("#")) {
- return Code.fromOTPAuthUrl(rawData.replaceAll("#", '%23'));
+ return Code.fromOTPAuthUrl(
+ rawData.replaceAll("#", '%23'),
+ display: display,
+ );
} else {
Logger(
"Code",
diff --git a/mobile/apps/auth/lib/onboarding/view/common/add_chip.dart b/mobile/apps/auth/lib/onboarding/view/common/add_chip.dart
deleted file mode 100644
index 84e07bbc1f..0000000000
--- a/mobile/apps/auth/lib/onboarding/view/common/add_chip.dart
+++ /dev/null
@@ -1,23 +0,0 @@
-import "package:ente_auth/theme/ente_theme.dart";
-import "package:flutter/material.dart";
-
-class AddChip extends StatelessWidget {
- final VoidCallback? onTap;
-
- const AddChip({super.key, this.onTap});
-
- @override
- Widget build(BuildContext context) {
- return GestureDetector(
- onTap: onTap,
- child: Padding(
- padding: const EdgeInsets.symmetric(vertical: 8.0),
- child: Icon(
- Icons.add_circle_outline,
- size: 30,
- color: getEnteColorScheme(context).iconButtonColor,
- ),
- ),
- );
- }
-}
diff --git a/mobile/apps/auth/lib/onboarding/view/common/add_tag.dart b/mobile/apps/auth/lib/onboarding/view/common/add_tag.dart
deleted file mode 100644
index 4148e2624d..0000000000
--- a/mobile/apps/auth/lib/onboarding/view/common/add_tag.dart
+++ /dev/null
@@ -1,69 +0,0 @@
-import "package:ente_auth/l10n/l10n.dart";
-import "package:flutter/material.dart";
-
-class AddTagDialog extends StatefulWidget {
- const AddTagDialog({super.key, required this.onTap});
-
- final void Function(String) onTap;
-
- @override
- State<AddTagDialog> createState() => _AddTagDialogState();
-}
-
-class _AddTagDialogState extends State<AddTagDialog> {
- String _tag = "";
-
- @override
- Widget build(BuildContext context) {
- final l10n = context.l10n;
- return AlertDialog(
- title: Text(l10n.createNewTag),
- content: SingleChildScrollView(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.start,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- TextFormField(
- maxLength: 100,
- decoration: InputDecoration(
- hintText: l10n.tag,
- hintStyle: const TextStyle(color: Colors.white30),
- contentPadding: const EdgeInsets.all(12),
- ),
- onChanged: (value) {
- setState(() {
- _tag = value;
- });
- },
- autocorrect: false,
- initialValue: _tag,
- autofocus: true,
- ),
- ],
- ),
- ),
- actions: [
- TextButton(
- child: Text(
- l10n.cancel,
- style: const TextStyle(color: Colors.redAccent),
- ),
- onPressed: () {
- Navigator.pop(context);
- },
- ),
- TextButton(
- child: Text(
- l10n.create,
- style: const TextStyle(color: Colors.purple),
- ),
- onPressed: () {
- if (_tag.trim().isEmpty) return;
-
- widget.onTap(_tag);
- },
- ),
- ],
- );
- }
-}
diff --git a/mobile/apps/auth/lib/onboarding/view/common/edit_tag.dart b/mobile/apps/auth/lib/onboarding/view/common/edit_tag.dart
deleted file mode 100644
index 05aa83596c..0000000000
--- a/mobile/apps/auth/lib/onboarding/view/common/edit_tag.dart
+++ /dev/null
@@ -1,82 +0,0 @@
-import "package:ente_auth/l10n/l10n.dart";
-import 'package:ente_auth/store/code_display_store.dart';
-import 'package:ente_auth/utils/dialog_util.dart';
-import 'package:flutter/material.dart';
-
-class EditTagDialog extends StatefulWidget {
- const EditTagDialog({super.key, required this.tag});
-
- final String tag;
-
- @override
- State<EditTagDialog> createState() => _EditTagDialogState();
-}
-
-class _EditTagDialogState extends State<EditTagDialog> {
- late String _tag = widget.tag;
-
- @override
- Widget build(BuildContext context) {
- final l10n = context.l10n;
- return AlertDialog(
- title: Text(l10n.editTag),
- content: SingleChildScrollView(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.start,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- TextFormField(
- maxLength: 100,
- decoration: InputDecoration(
- hintText: l10n.tag,
- hintStyle: const TextStyle(color: Colors.white30),
- contentPadding: const EdgeInsets.all(12),
- ),
- onChanged: (value) {
- setState(() {
- _tag = value;
- });
- },
- autocorrect: false,
- initialValue: _tag,
- autofocus: true,
- ),
- ],
- ),
- ),
- actions: [
- TextButton(
- child: Text(
- l10n.cancel,
- style: const TextStyle(color: Colors.redAccent),
- ),
- onPressed: () {
- Navigator.pop(context);
- },
- ),
- TextButton(
- child: Text(
- l10n.saveAction,
- style: const TextStyle(color: Colors.purple),
- ),
- onPressed: () async {
- if (_tag.trim().isEmpty) return;
-
- final dialog = createProgressDialog(
- context,
- context.l10n.pleaseWait,
- );
- await dialog.show();
-
- await CodeDisplayStore.instance.editTag(widget.tag, _tag);
-
- await dialog.hide();
-
- if (!context.mounted) return;
- Navigator.pop(context);
- },
- ),
- ],
- );
- }
-}
diff --git a/mobile/apps/auth/lib/onboarding/view/common/field_label.dart b/mobile/apps/auth/lib/onboarding/view/common/field_label.dart
deleted file mode 100644
index fd337513e2..0000000000
--- a/mobile/apps/auth/lib/onboarding/view/common/field_label.dart
+++ /dev/null
@@ -1,20 +0,0 @@
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:flutter/material.dart';
-
-class FieldLabel extends StatelessWidget {
- final String label;
- final double width;
-
- const FieldLabel(this.label, {super.key, this.width = 80});
-
- @override
- Widget build(BuildContext context) {
- return Padding(
- padding: const EdgeInsets.only(right: 12.0),
- child: SizedBox(
- width: width,
- child: Text(label, style: getEnteTextTheme(context).miniBoldMuted),
- ),
- );
- }
-}
diff --git a/mobile/apps/auth/lib/onboarding/view/common/tag_chip.dart b/mobile/apps/auth/lib/onboarding/view/common/tag_chip.dart
index 33230593fe..12dc9a5e73 100644
--- a/mobile/apps/auth/lib/onboarding/view/common/tag_chip.dart
+++ b/mobile/apps/auth/lib/onboarding/view/common/tag_chip.dart
@@ -2,6 +2,7 @@ import "package:ente_auth/l10n/l10n.dart";
import "package:ente_auth/onboarding/model/tag_enums.dart";
import "package:ente_auth/store/code_display_store.dart";
import "package:ente_auth/theme/ente_theme.dart";
+import 'package:ente_components/ente_components.dart';
import "package:flutter/material.dart";
import "package:flutter/services.dart";
@@ -111,61 +112,19 @@ class _TagChipState extends State<TagChip> {
widget.action == TagChipAction.menu) ...[
SizedBox(
width: 48,
- child: PopupMenuButton<int>(
- iconSize: 16,
- padding: const EdgeInsets.symmetric(horizontal: 16),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(8),
+ child: Semantics(
+ button: true,
+ label: context.l10n.editTag,
+ identifier: 'auth_tag_menu',
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => _showTagActions(context),
+ child: const Icon(
+ Icons.more_horiz,
+ size: IconSizes.small,
+ color: Colors.white,
+ ),
),
- surfaceTintColor: Theme.of(context).cardColor,
- iconColor: Colors.white,
- initialValue: -1,
- onSelected: (value) {
- if (value == 0) {
- CodeDisplayStore.instance.showEditDialog(
- context,
- widget.label,
- );
- } else if (value == 1) {
- CodeDisplayStore.instance.showDeleteTagDialog(
- context,
- widget.label,
- );
- }
- },
- itemBuilder: (BuildContext context) {
- return [
- PopupMenuItem(
- value: 0,
- child: Row(
- children: [
- const Icon(Icons.edit_outlined, size: 16),
- const SizedBox(width: 12),
- Text(context.l10n.edit),
- ],
- ),
- ),
- PopupMenuItem(
- value: 1,
- child: Row(
- children: [
- Icon(
- Icons.delete_outline,
- size: 16,
- color: colorScheme.deleteTagIconColor,
- ),
- const SizedBox(width: 12),
- Text(
- context.l10n.delete,
- style: TextStyle(
- color: colorScheme.deleteTagTextColor,
- ),
- ),
- ],
- ),
- ),
- ];
- },
),
),
] else ...[
@@ -178,4 +137,47 @@ class _TagChipState extends State<TagChip> {
),
);
}
+
+ Future<void> _showTagActions(BuildContext context) {
+ final l10n = context.l10n;
+ return showBottomSheetComponent<void>(
+ context: context,
+ builder: (sheetContext) => Semantics(
+ identifier: 'auth_tag_actions_sheet',
+ child: BottomSheetComponent(
+ title: widget.label,
+ closeTooltip: l10n.close,
+ content: MenuGroupComponent(
+ showDividers: true,
+ items: [
+ MenuComponent(
+ title: l10n.edit,
+ leading: const Icon(Icons.edit_outlined),
+ onTap: () {
+ Navigator.of(sheetContext).pop();
+ CodeDisplayStore.instance.showEditDialog(
+ context,
+ widget.label,
+ );
+ },
+ ),
+ MenuComponent(
+ title: l10n.delete,
+ titleColor: context.componentColors.warning,
+ iconColor: context.componentColors.warning,
+ leading: const Icon(Icons.delete_outline),
+ onTap: () {
+ Navigator.of(sheetContext).pop();
+ CodeDisplayStore.instance.showDeleteTagDialog(
+ context,
+ widget.label,
+ );
+ },
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
}
diff --git a/mobile/apps/auth/lib/onboarding/view/onboarding_page.dart b/mobile/apps/auth/lib/onboarding/view/onboarding_page.dart
index 2516930784..04fd05b72b 100644
--- a/mobile/apps/auth/lib/onboarding/view/onboarding_page.dart
+++ b/mobile/apps/auth/lib/onboarding/view/onboarding_page.dart
@@ -21,6 +21,7 @@ import 'package:ente_auth/ui/home/widgets/rounded_action_buttons.dart';
import 'package:ente_auth/ui/home_page.dart';
import 'package:ente_auth/ui/settings/developer_settings_widget.dart';
import 'package:ente_auth/ui/settings/language_picker.dart';
+import 'package:ente_auth/utils/debug_build_flags.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_auth/utils/navigation_util.dart';
import 'package:ente_auth/utils/toast_util.dart';
@@ -254,7 +255,7 @@ class _OnboardingPageState extends State<OnboardingPage> {
}
final bool hasOptedBefore = Configuration.instance.hasOptedForOfflineMode();
ButtonResult? result;
- if (!hasOptedBefore) {
+ if (!hasOptedBefore && !shouldSkipAuthGuidance) {
if (!mounted) return;
result = await showChoiceActionSheet(
context,
@@ -264,7 +265,9 @@ class _OnboardingPageState extends State<OnboardingPage> {
firstButtonLabel: context.l10n.ok,
);
}
- if (hasOptedBefore || result?.action == ButtonAction.first) {
+ if (hasOptedBefore ||
+ shouldSkipAuthGuidance ||
+ result?.action == ButtonAction.first) {
if (!context.mounted) return;
await Configuration.instance.optForOfflineMode();
if (!mounted) return;
diff --git a/mobile/apps/auth/lib/onboarding/view/setup_enter_secret_key_page.dart b/mobile/apps/auth/lib/onboarding/view/setup_enter_secret_key_page.dart
index 9ecc26a801..5af44a14db 100644
--- a/mobile/apps/auth/lib/onboarding/view/setup_enter_secret_key_page.dart
+++ b/mobile/apps/auth/lib/onboarding/view/setup_enter_secret_key_page.dart
@@ -5,32 +5,39 @@ import "package:ente_auth/l10n/l10n.dart";
import 'package:ente_auth/models/all_icon_data.dart';
import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/models/code_display.dart';
-import 'package:ente_auth/onboarding/model/tag_enums.dart';
-import 'package:ente_auth/onboarding/view/common/add_chip.dart';
-import 'package:ente_auth/onboarding/view/common/add_tag.dart';
-import 'package:ente_auth/onboarding/view/common/field_label.dart';
-import 'package:ente_auth/onboarding/view/common/tag_chip.dart';
import 'package:ente_auth/store/code_display_store.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/algorithm_selector_widget.dart';
import 'package:ente_auth/ui/components/buttons/button_widget.dart';
import 'package:ente_auth/ui/components/custom_icon_widget.dart';
import 'package:ente_auth/ui/components/models/button_result.dart';
import 'package:ente_auth/ui/custom_icon_page.dart';
-import 'package:ente_auth/ui/topt_selector_widget.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
import 'package:ente_auth/ui/utils/icon_utils.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_auth/utils/toast_util.dart';
import 'package:ente_auth/utils/totp_util.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:ente_events/event_bus.dart';
import "package:flutter/material.dart";
+import 'package:flutter/services.dart';
import 'package:logging/logging.dart';
class SetupEnterSecretKeyPage extends StatefulWidget {
+ static const manualCodeTextLimit = 200;
+
final Code? code;
SetupEnterSecretKeyPage({this.code, super.key});
+ static int? manualCodeTextLimitFor(Code? code) {
+ if (code == null ||
+ (code.issuer.length < manualCodeTextLimit &&
+ code.account.length < manualCodeTextLimit &&
+ code.secret.length < manualCodeTextLimit)) {
+ return manualCodeTextLimit;
+ }
+ return null;
+ }
+
@override
State<SetupEnterSecretKeyPage> createState() =>
_SetupEnterSecretKeyPageState();
@@ -39,16 +46,15 @@ class SetupEnterSecretKeyPage extends StatefulWidget {
class _SetupEnterSecretKeyPageState extends State<SetupEnterSecretKeyPage> {
final Logger _logger = Logger('_SetupEnterSecretKeyPageState');
final int _notesLimit = 500;
- final int _otherTextLimit = 200;
final int defaultDigits = 6;
final int defaultPeriodInSeconds = 30;
+ late final int? _textLimit;
late TextEditingController _issuerController;
late TextEditingController _accountController;
late TextEditingController _secretController;
late TextEditingController _notesController;
late TextEditingController _digitsController;
late TextEditingController _periodController;
- late bool _secretKeyObscured;
late List<String> selectedTags = [...?widget.code?.display.tags];
List<String> allTags = [];
StreamSubscription<CodesUpdatedEvent>? _streamSubscription;
@@ -61,6 +67,7 @@ class _SetupEnterSecretKeyPageState extends State<SetupEnterSecretKeyPage> {
@override
void initState() {
+ _textLimit = SetupEnterSecretKeyPage.manualCodeTextLimitFor(widget.code);
_issuerController = TextEditingController(
text: widget.code != null ? safeDecode(widget.code!.issuer).trim() : null,
);
@@ -82,7 +89,6 @@ class _SetupEnterSecretKeyPageState extends State<SetupEnterSecretKeyPage> {
: defaultPeriodInSeconds.toString(),
);
- _secretKeyObscured = widget.code != null;
_loadTags();
_streamSubscription = Bus.instance.on<CodesUpdatedEvent>().listen((event) {
_loadTags();
@@ -97,15 +103,6 @@ class _SetupEnterSecretKeyPageState extends State<SetupEnterSecretKeyPage> {
}
});
- if (widget.code == null ||
- (widget.code!.issuer.length < _otherTextLimit &&
- widget.code!.account.length < _otherTextLimit &&
- widget.code!.secret.length < _otherTextLimit)) {
- _limitTextLength(_issuerController, _otherTextLimit);
- _limitTextLength(_accountController, _otherTextLimit);
- _limitTextLength(_secretController, _otherTextLimit);
- }
-
isCustomIcon = widget.code?.display.isCustomIcon ?? false;
if (isCustomIcon) {
_customIconID = widget.code?.display.iconID ?? "ente";
@@ -124,25 +121,16 @@ class _SetupEnterSecretKeyPageState extends State<SetupEnterSecretKeyPage> {
super.initState();
}
- void _limitTextLength(TextEditingController controller, int limit) {
- controller.addListener(() {
- if (controller.text.length > limit) {
- controller.text = controller.text.substring(0, limit);
- controller.selection = TextSelection.fromPosition(
- TextPosition(offset: controller.text.length),
- );
- }
- });
- }
-
@override
void dispose() {
_streamSubscription?.cancel();
_issuerController.dispose();
_accountController.dispose();
+ _secretController.dispose();
_notesController.dispose();
_digitsController.dispose();
_periodController.dispose();
+ showAdvancedOptions.dispose();
super.dispose();
}
@@ -156,270 +144,382 @@ class _SetupEnterSecretKeyPageState extends State<SetupEnterSecretKeyPage> {
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
- return Scaffold(
- appBar: AppBar(title: Text(l10n.importAccountPageTitle)),
- body: SingleChildScrollView(
- child: Padding(
- padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 20),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- if (widget.code != null)
- GestureDetector(
- onTap: () async {
- await navigateToCustomIconPage();
- },
- child: CustomIconWidget(iconData: _customIconID),
- ),
- const SizedBox(height: 20),
- Column(
- crossAxisAlignment: CrossAxisAlignment.start,
+ return AuthSettingsPageScaffold(
+ title: l10n.importAccountPageTitle,
+ children: [
+ Semantics(
+ identifier: 'auth_manual_code_page',
+ child: Align(
+ alignment: Alignment.topCenter,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 520),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Row(
- children: [
- FieldLabel(l10n.codeIssuerHint),
- Expanded(
- child: TextFormField(
- // The validator receives the text that the user has entered.
- validator: (value) {
- if (value == null || value.isEmpty) {
- return "Please enter some text";
- }
- return null;
- },
- decoration: const InputDecoration(
- contentPadding: EdgeInsets.symmetric(
- vertical: 12.0,
- ),
- ),
- style: getEnteTextTheme(context).small,
- controller: _issuerController,
- autofocus: true,
- ),
- ),
- ],
- ),
- Row(
- children: [
- FieldLabel(l10n.secret),
- Expanded(
- child: TextFormField(
- // The validator receives the text that the user has entered.
- validator: (value) {
- if (value == null || value.isEmpty) {
- return "Please enter some text";
- }
- return null;
- },
- style: getEnteTextTheme(context).small,
- decoration: InputDecoration(
- contentPadding: const EdgeInsets.symmetric(
- vertical: 12.0,
- ),
- suffixIcon: GestureDetector(
- // padding: EdgeInsets.zero,
- onTap: () {
- setState(() {
- _secretKeyObscured = !_secretKeyObscured;
- });
- },
- child: _secretKeyObscured
- ? const Icon(
- Icons.visibility_off_rounded,
- size: 18,
- )
- : const Icon(
- Icons.visibility_rounded,
- size: 18,
- ),
- ),
+ if (widget.code != null) ...[
+ Semantics(
+ identifier: 'auth_manual_code_icon',
+ button: true,
+ label: l10n.appIcon,
+ child: Center(
+ child: InkWell(
+ borderRadius: BorderRadius.circular(Radii.sheet),
+ onTap: navigateToCustomIconPage,
+ child: Padding(
+ padding: const EdgeInsets.all(Spacing.sm),
+ child: CustomIconWidget(iconData: _customIconID),
),
- obscureText: _secretKeyObscured,
- controller: _secretController,
),
),
- ],
+ ),
+ const SizedBox(height: Spacing.xl),
+ ],
+ Semantics(
+ identifier: 'auth_manual_issuer',
+ child: TextInputComponent(
+ controller: _issuerController,
+ label: l10n.codeIssuerHint,
+ isClearable: true,
+ maxLength: _textLimit,
+ textInputAction: TextInputAction.next,
+ ),
),
- Row(
- children: [
- FieldLabel(l10n.account),
- Expanded(
- child: TextFormField(
- // The validator receives the text that the user has entered.
- validator: (value) {
- if (value == null || value.isEmpty) {
- return "Please enter some text";
- }
- return null;
- },
- decoration: const InputDecoration(
- contentPadding: EdgeInsets.symmetric(
- vertical: 12.0,
- ),
- ),
- style: getEnteTextTheme(context).small,
- controller: _accountController,
- ),
- ),
- ],
+ const SizedBox(height: Spacing.lg),
+ Semantics(
+ identifier: 'auth_manual_secret',
+ child: TextInputComponent(
+ controller: _secretController,
+ label: l10n.secret,
+ isRequired: true,
+ isPasswordInput: true,
+ maxLength: _textLimit,
+ autocorrect: false,
+ enableSuggestions: false,
+ textInputAction: TextInputAction.next,
+ ),
),
- const SizedBox(height: 12),
- Row(
- children: [
- FieldLabel(l10n.notes),
- Expanded(
- child: TextFormField(
- // The validator receives the text that the user has entered.
- validator: (value) {
- if (value == null || value.isEmpty) {
- return "Please enter some text";
- }
- if (value.length > _notesLimit) {
- return "Notes can't be more than 1000 characters";
- }
- return null;
- },
- maxLength: _notesLimit,
- minLines: 1,
- maxLines: 5,
- decoration: const InputDecoration(
- contentPadding: EdgeInsets.symmetric(
- vertical: 12.0,
- ),
- ),
- style: getEnteTextTheme(context).small,
- controller: _notesController,
- ),
- ),
- ],
+ const SizedBox(height: Spacing.lg),
+ Semantics(
+ identifier: 'auth_manual_account',
+ child: TextInputComponent(
+ controller: _accountController,
+ label: l10n.account,
+ isClearable: true,
+ maxLength: _textLimit,
+ textInputAction: TextInputAction.next,
+ ),
),
- const SizedBox(height: 12),
- Wrap(
- spacing: 12,
- runSpacing: 8,
- alignment: WrapAlignment.start,
- children: [
- ...allTags.map(
- (e) => TagChip(
- label: e,
- action: TagChipAction.check,
- state: selectedTags.contains(e)
- ? TagChipState.selected
- : TagChipState.unselected,
- onTap: () {
- if (selectedTags.contains(e)) {
- selectedTags.remove(e);
- } else {
- selectedTags.add(e);
- }
- setState(() {});
- },
- ),
- ),
- AddChip(
- onTap: () {
- showDialog(
- context: context,
- builder: (BuildContext context) {
- return AddTagDialog(
- onTap: (tag) {
- final exist = allTags.contains(tag);
- if (exist && selectedTags.contains(tag)) {
- return Navigator.pop(context);
- }
- if (!exist) allTags.add(tag);
- selectedTags.add(tag);
- setState(() {});
- Navigator.pop(context);
- },
- );
- },
- barrierColor: Colors.black.withValues(alpha: 0.85),
- barrierDismissible: false,
- );
- },
- ),
- ],
+ const SizedBox(height: Spacing.lg),
+ Semantics(
+ identifier: 'auth_manual_notes',
+ child: TextInputComponent(
+ controller: _notesController,
+ label: l10n.notes,
+ isClearable: true,
+ maxLength: _notesLimit,
+ minLines: 3,
+ maxLines: 5,
+ textInputAction: TextInputAction.newline,
+ ),
),
- const SizedBox(height: 12),
- widget.code == null
- ? advanceOptionWidget()
- : const SizedBox.shrink(),
- const SizedBox(height: 40),
- SizedBox(
- width: 400,
- child: OutlinedButton(
- style: OutlinedButton.styleFrom(
- padding: const EdgeInsets.symmetric(vertical: 0),
- ),
- onPressed: () async {
- final digits = int.tryParse(
- _digitsController.text.trim(),
- );
- if (digits != null && (digits < 1 || digits > 10)) {
- String message = "Digits must be between 1 and 10";
- _showIncorrectDetailsDialog(
- context,
- message: message,
- );
- return;
- }
-
- final period = int.tryParse(
- _periodController.text.trim(),
- );
- if (period != null && (period < 10 || period > 60)) {
- String message =
- "Period must be between 10 and 60 seconds";
- _showIncorrectDetailsDialog(
- context,
- message: message,
- );
- return;
- }
-
- if ((_accountController.text.trim().isEmpty &&
- _issuerController.text.trim().isEmpty) ||
- _secretController.text.trim().isEmpty ||
- _digitsController.text.trim().isEmpty ||
- digits == null ||
- _periodController.text.trim().isEmpty ||
- period == null) {
- String message;
- if (_secretController.text.trim().isEmpty) {
- message = context.l10n.secretCanNotBeEmpty;
- } else if (_digitsController.text.isEmpty) {
- message = "Digits cannot be empty";
- } else if (digits == null) {
- message = "Digits is not a integer";
- } else if (_periodController.text.isEmpty) {
- message = "Period cannot be empty";
- } else if (period == null) {
- message = "Period is not a integer";
- } else {
- message =
- context.l10n.bothIssuerAndAccountCanNotBeEmpty;
- }
- _showIncorrectDetailsDialog(
- context,
- message: message,
- );
- return;
- }
- await _saveCode();
- },
- child: Text(l10n.saveAction),
+ const SizedBox(height: Spacing.xl),
+ _buildTags(context),
+ if (widget.code == null) ...[
+ const SizedBox(height: Spacing.xl),
+ _buildAdvancedOptions(context),
+ ],
+ const SizedBox(height: Spacing.xxl),
+ Semantics(
+ identifier: 'auth_manual_save',
+ child: ButtonComponent(
+ label: l10n.saveAction,
+ onTap: _validateAndSave,
),
),
+ const SizedBox(height: Spacing.xl),
],
),
- ],
+ ),
),
),
+ ],
+ );
+ }
+
+ Widget _buildTags(BuildContext context) {
+ final colors = context.componentColors;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ context.l10n.tags,
+ style: TextStyles.bodyBold.copyWith(color: colors.textBase),
+ ),
+ const SizedBox(height: Spacing.sm),
+ Wrap(
+ spacing: Spacing.sm,
+ runSpacing: Spacing.sm,
+ children: [
+ for (final tag in allTags)
+ TagChipComponent(
+ label: tag,
+ state: selectedTags.contains(tag)
+ ? TagChipComponentState.selected
+ : TagChipComponentState.unselected,
+ onTap: () => _toggleTag(tag),
+ ),
+ Semantics(
+ button: true,
+ label: context.l10n.addTag,
+ identifier: 'auth_manual_add_tag',
+ child: TagChipComponent(
+ label: context.l10n.addTag,
+ leading: const Icon(Icons.add, size: IconSizes.small),
+ onTap: _createTag,
+ ),
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+
+ void _toggleTag(String tag) {
+ setState(() {
+ selectedTags.contains(tag)
+ ? selectedTags.remove(tag)
+ : selectedTags.add(tag);
+ });
+ }
+
+ Future<void> _createTag() async {
+ await showTextInputDialog(
+ context,
+ title: context.l10n.createNewTag,
+ label: context.l10n.tag,
+ submitButtonLabel: context.l10n.create,
+ maxLength: 100,
+ onSubmit: (value) async {
+ final tag = value.trim();
+ if (tag.isEmpty) return;
+ if (!allTags.contains(tag)) allTags.add(tag);
+ if (!selectedTags.contains(tag)) selectedTags.add(tag);
+ if (mounted) setState(() {});
+ },
+ );
+ }
+
+ Widget _buildAdvancedOptions(BuildContext context) {
+ return ValueListenableBuilder<bool>(
+ valueListenable: showAdvancedOptions,
+ builder: (context, isExpanded, _) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Semantics(
+ button: true,
+ label: context.l10n.advanced,
+ identifier: 'auth_manual_advanced',
+ child: MenuGroupComponent(
+ items: [
+ MenuComponent(
+ title: context.l10n.advanced,
+ trailing: Icon(
+ isExpanded
+ ? Icons.keyboard_arrow_up
+ : Icons.keyboard_arrow_down,
+ size: IconSizes.medium,
+ ),
+ onTap: () => showAdvancedOptions.value = !isExpanded,
+ ),
+ ],
+ ),
+ ),
+ AnimatedSize(
+ duration: const Duration(milliseconds: 250),
+ curve: Curves.easeOutCubic,
+ child: !isExpanded
+ ? const SizedBox.shrink()
+ : Padding(
+ padding: const EdgeInsets.only(top: Spacing.lg),
+ child: Column(
+ children: [
+ MenuGroupComponent(
+ showDividers: true,
+ dividerPadding: const EdgeInsets.only(
+ left: Spacing.lg,
+ ),
+ items: [
+ Semantics(
+ button: true,
+ label: context.l10n.algorithm,
+ identifier: 'auth_manual_algorithm',
+ child: MenuComponent(
+ title: context.l10n.algorithm,
+ subtitle: _algorithm.name.toUpperCase(),
+ trailing: const Icon(
+ Icons.chevron_right_outlined,
+ ),
+ onTap: _selectAlgorithm,
+ ),
+ ),
+ Semantics(
+ button: true,
+ label: context.l10n.type,
+ identifier: 'auth_manual_type',
+ child: MenuComponent(
+ title: context.l10n.type,
+ subtitle: _type.name.toUpperCase(),
+ trailing: const Icon(
+ Icons.chevron_right_outlined,
+ ),
+ onTap: _selectType,
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: Spacing.lg),
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: Semantics(
+ textField: true,
+ identifier: 'auth_manual_period',
+ child: TextInputComponent(
+ controller: _periodController,
+ label: context.l10n.period,
+ keyboardType: TextInputType.number,
+ inputFormatters: [
+ FilteringTextInputFormatter.digitsOnly,
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(width: Spacing.lg),
+ Expanded(
+ child: Semantics(
+ textField: true,
+ identifier: 'auth_manual_digits',
+ child: TextInputComponent(
+ controller: _digitsController,
+ label: context.l10n.digits,
+ keyboardType: TextInputType.number,
+ inputFormatters: [
+ FilteringTextInputFormatter.digitsOnly,
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ );
+ },
+ );
+ }
+
+ Future<void> _selectAlgorithm() async {
+ final selected = await _showOptionPicker<Algorithm>(
+ title: context.l10n.algorithm,
+ values: Algorithm.values,
+ selected: _algorithm,
+ labelFor: (value) => value.name.toUpperCase(),
+ );
+ if (selected != null && mounted) setState(() => _algorithm = selected);
+ }
+
+ Future<void> _selectType() async {
+ final selected = await _showOptionPicker<Type>(
+ title: context.l10n.type,
+ values: Type.values,
+ selected: _type,
+ labelFor: (value) => value.name.toUpperCase(),
+ );
+ if (selected != null && mounted) setState(() => _type = selected);
+ }
+
+ Future<T?> _showOptionPicker<T>({
+ required String title,
+ required List<T> values,
+ required T selected,
+ required String Function(T value) labelFor,
+ }) {
+ return showBottomSheetComponent<T>(
+ context: context,
+ builder: (sheetContext) => BottomSheetComponent(
+ title: title,
+ closeTooltip: context.l10n.close,
+ content: MenuGroupComponent(
+ showDividers: true,
+ items: [
+ for (final value in values)
+ MenuComponent(
+ title: labelFor(value),
+ selected: value == selected,
+ trailing: RadioComponent(
+ selected: value == selected,
+ onChanged: (_) => Navigator.of(sheetContext).pop(value),
+ ),
+ onTap: () => Navigator.of(sheetContext).pop(value),
+ ),
+ ],
+ ),
),
);
}
+ Future<void> _validateAndSave() async {
+ final digits = int.tryParse(_digitsController.text.trim());
+ if (digits != null && (digits < 1 || digits > 10)) {
+ _showIncorrectDetailsDialog(
+ context,
+ message: 'Digits must be between 1 and 10',
+ );
+ return;
+ }
+
+ final period = int.tryParse(_periodController.text.trim());
+ if (period != null && (period < 10 || period > 60)) {
+ _showIncorrectDetailsDialog(
+ context,
+ message: 'Period must be between 10 and 60 seconds',
+ );
+ return;
+ }
+
+ if ((_accountController.text.trim().isEmpty &&
+ _issuerController.text.trim().isEmpty) ||
+ _secretController.text.trim().isEmpty ||
+ _digitsController.text.trim().isEmpty ||
+ digits == null ||
+ _periodController.text.trim().isEmpty ||
+ period == null) {
+ final String message;
+ if (_secretController.text.trim().isEmpty) {
+ message = context.l10n.secretCanNotBeEmpty;
+ } else if (_digitsController.text.isEmpty) {
+ message = 'Digits cannot be empty';
+ } else if (digits == null) {
+ message = 'Digits is not an integer';
+ } else if (_periodController.text.isEmpty) {
+ message = 'Period cannot be empty';
+ } else if (period == null) {
+ message = 'Period is not an integer';
+ } else {
+ message = context.l10n.bothIssuerAndAccountCanNotBeEmpty;
+ }
+ _showIncorrectDetailsDialog(context, message: message);
+ return;
+ }
+
+ await _saveCode();
+ }
+
Future<void> _saveCode() async {
try {
if (!mounted) return;
@@ -512,161 +612,17 @@ class _SetupEnterSecretKeyPageState extends State<SetupEnterSecretKeyPage> {
} else {
currentIcon = widget.code!.issuer;
}
- final AllIconData newCustomIcon = await Navigator.of(context).push(
- MaterialPageRoute(
+ final AllIconData? newCustomIcon = await Navigator.of(context).push(
+ MaterialPageRoute<AllIconData>(
builder: (context) {
return CustomIconPage(currentIcon: currentIcon, allIcons: allIcons);
},
),
);
+ if (newCustomIcon == null || !mounted) return;
setState(() {
_customIconID = newCustomIcon.title;
_iconSrc = newCustomIcon.type;
});
}
-
- Widget advanceOptionWidget() {
- final l10n = context.l10n;
- return Padding(
- padding: const EdgeInsets.only(top: 16.0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- GestureDetector(
- onTap: () {
- showAdvancedOptions.value = !showAdvancedOptions.value;
- },
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text(l10n.advanced),
- ValueListenableBuilder<bool>(
- valueListenable: showAdvancedOptions,
- builder: (context, isExpanded, child) {
- return Icon(
- isExpanded
- ? Icons.keyboard_arrow_up
- : Icons.keyboard_arrow_down,
- size: 24,
- );
- },
- ),
- ],
- ),
- ),
- ValueListenableBuilder<bool>(
- valueListenable: showAdvancedOptions,
- builder: (context, isExpanded, child) {
- return AnimatedSwitcher(
- duration: const Duration(milliseconds: 300),
- transitionBuilder: (child, animation) {
- return SizeTransition(sizeFactor: animation, child: child);
- },
- child: isExpanded
- ? SizedBox(
- width: 400,
- child: Padding(
- padding: const EdgeInsets.only(top: 16),
- child: GridView.count(
- crossAxisCount: 2,
- shrinkWrap: true,
- childAspectRatio: 2.5,
- crossAxisSpacing: 16,
- mainAxisSpacing: 14,
- physics: const NeverScrollableScrollPhysics(),
- children: [
- Row(
- mainAxisAlignment: MainAxisAlignment.start,
- children: [
- FieldLabel(l10n.algorithm, width: 60),
- AlgorithmSelectorWidget(
- currentAlgorithm: _algorithm,
- onSelected: (newAlgorithm) async {
- setState(() {
- _algorithm = newAlgorithm;
- });
- },
- ),
- ],
- ),
- Row(
- mainAxisAlignment: MainAxisAlignment.start,
- children: [
- FieldLabel(l10n.type, width: 60),
- ToptSelectorWidget(
- currentTopt: _type,
- onSelected: (newTopt) async {
- setState(() {
- _type = newTopt;
- });
- },
- ),
- ],
- ),
- Row(
- children: [
- FieldLabel(l10n.period, width: 60),
- Expanded(
- child: TextFormField(
- keyboardType: TextInputType.number,
- // The validator receives the text that the user has entered.
- validator: (value) {
- if (value == null || value.isEmpty) {
- return "Please enter a number";
- }
- final intValue = int.tryParse(value);
- if (intValue == null) {
- return "Only integers are allowed";
- }
- if (intValue < 1 || intValue > 60) {
- return "Period must be between 1 and 60";
- }
- return null;
- },
- maxLines: 1,
- style: getEnteTextTheme(context).small,
- controller: _periodController,
- ),
- ),
- ],
- ),
- Row(
- children: [
- FieldLabel(l10n.digits, width: 60),
- Expanded(
- child: TextFormField(
- keyboardType: TextInputType.number,
- // The validator receives the text that the user has entered.
- validator: (value) {
- if (value == null || value.isEmpty) {
- return "Please enter a number";
- }
- final intValue = int.tryParse(value);
- if (intValue == null) {
- return "Only integers are allowed";
- }
- if (intValue < 1 || intValue > 10) {
- return "OTP digits must be between 1 and 10";
- }
- return null;
- },
- maxLines: 1,
- style: getEnteTextTheme(context).small,
- controller: _digitsController,
- ),
- ),
- ],
- ),
- ],
- ),
- ),
- )
- : const SizedBox.shrink(),
- );
- },
- ),
- ],
- ),
- );
- }
}
diff --git a/mobile/apps/auth/lib/services/preference_service.dart b/mobile/apps/auth/lib/services/preference_service.dart
index 2f7c65a25b..53eb82401b 100644
--- a/mobile/apps/auth/lib/services/preference_service.dart
+++ b/mobile/apps/auth/lib/services/preference_service.dart
@@ -1,4 +1,5 @@
import 'package:ente_auth/events/icons_changed_event.dart';
+import 'package:ente_auth/utils/debug_build_flags.dart';
import 'package:ente_events/event_bus.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -33,6 +34,9 @@ class PreferenceService {
}
bool hasShownCoachMark() {
+ if (shouldSkipAuthGuidance) {
+ return true;
+ }
if (_prefs.containsKey(kHasShownCoachMarkKey)) {
return _prefs.getBool(kHasShownCoachMarkKey)!;
} else {
diff --git a/mobile/apps/auth/lib/store/code_display_store.dart b/mobile/apps/auth/lib/store/code_display_store.dart
index 3040710c61..e3576840f0 100644
--- a/mobile/apps/auth/lib/store/code_display_store.dart
+++ b/mobile/apps/auth/lib/store/code_display_store.dart
@@ -1,6 +1,5 @@
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/code.dart';
-import 'package:ente_auth/onboarding/view/common/edit_tag.dart';
import 'package:ente_auth/services/authenticator_service.dart';
import 'package:ente_auth/store/code_store.dart';
import 'package:ente_auth/utils/dialog_util.dart';
@@ -165,13 +164,18 @@ class CodeDisplayStore {
}
Future<void> showEditDialog(BuildContext context, String tag) async {
- await showDialog(
- context: context,
- builder: (BuildContext context) {
- return EditTagDialog(tag: tag);
+ await showTextInputDialog(
+ context,
+ title: context.l10n.editTag,
+ label: context.l10n.tag,
+ initialValue: tag,
+ submitButtonLabel: context.l10n.saveAction,
+ maxLength: 100,
+ onSubmit: (value) async {
+ final updatedTag = value.trim();
+ if (updatedTag.isEmpty || updatedTag == tag) return;
+ await editTag(tag, updatedTag);
},
- barrierColor: Colors.black.withValues(alpha: 0.85),
- barrierDismissible: false,
);
}
diff --git a/mobile/apps/auth/lib/ui/algorithm_selector_widget.dart b/mobile/apps/auth/lib/ui/algorithm_selector_widget.dart
deleted file mode 100644
index 0076384d0f..0000000000
--- a/mobile/apps/auth/lib/ui/algorithm_selector_widget.dart
+++ /dev/null
@@ -1,69 +0,0 @@
-import 'package:ente_auth/models/code.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:flutter/material.dart';
-
-class AlgorithmSelectorWidget extends StatelessWidget {
- final Algorithm currentAlgorithm;
- final void Function(Algorithm) onSelected;
- const AlgorithmSelectorWidget({
- super.key,
- required this.currentAlgorithm,
- required this.onSelected,
- });
-
- @override
- Widget build(BuildContext context) {
- Text algorithmOptionText(Algorithm algorithm) {
- return Text(
- algorithm.name.toUpperCase(),
- style: getEnteTextTheme(context).small,
- );
- }
-
- return GestureDetector(
- onTapDown: (TapDownDetails details) async {
- final int? selectedValue = await showMenu<int>(
- context: context,
- position: RelativeRect.fromLTRB(
- details.globalPosition.dx,
- details.globalPosition.dy,
- details.globalPosition.dx,
- details.globalPosition.dy + 300,
- ),
- items: List.generate(Algorithm.values.length, (index) {
- return PopupMenuItem(
- value: index,
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- algorithmOptionText(Algorithm.values[index]),
- if (Algorithm.values[index] == currentAlgorithm)
- Icon(Icons.check, color: Theme.of(context).iconTheme.color),
- ],
- ),
- );
- }),
- );
- if (selectedValue != null) {
- onSelected(Algorithm.values[selectedValue]);
- }
- },
- child: Container(
- padding: const EdgeInsets.only(bottom: 4),
- decoration: BoxDecoration(
- border: Border(
- bottom: BorderSide(color: Theme.of(context).dividerColor),
- ),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- algorithmOptionText(currentAlgorithm),
- const SizedBox(width: 8),
- const Icon(Icons.arrow_drop_down),
- ],
- ),
- ),
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/code_widget.dart b/mobile/apps/auth/lib/ui/code_widget.dart
index 923969e489..93171393d3 100644
--- a/mobile/apps/auth/lib/ui/code_widget.dart
+++ b/mobile/apps/auth/lib/ui/code_widget.dart
@@ -24,6 +24,7 @@ import 'package:ente_auth/ui/utils/icon_utils.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_auth/utils/toast_util.dart';
import 'package:ente_auth/utils/totp_util.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:ente_events/event_bus.dart';
import 'package:ente_lock_screen/local_authentication_service.dart';
import 'package:ente_pure_utils/ente_pure_utils.dart';
@@ -152,14 +153,6 @@ class _CodeWidgetState extends State<CodeWidget> {
: const Size(39, 39),
),
),
- if (widget.code.isTrashed && kDebugMode)
- Align(
- alignment: Alignment.topLeft,
- child: CustomPaint(
- painter: PinBgPainter(color: colorScheme.warning700),
- size: const Size(39, 39),
- ),
- ),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
@@ -368,15 +361,29 @@ class _CodeWidgetState extends State<CodeWidget> {
},
),
);
- if (!isIOS) return content;
- final double scale = capCodeWidgetTextScaleForIOS(
- MediaQuery.textScalerOf(context).scale(1.0),
- );
- return MediaQuery(
- data: MediaQuery.of(
- context,
- ).copyWith(textScaler: TextScaler.linear(scale)),
- child: content,
+ final Widget scaledContent;
+ if (isIOS) {
+ final double scale = capCodeWidgetTextScaleForIOS(
+ MediaQuery.textScalerOf(context).scale(1.0),
+ );
+ scaledContent = MediaQuery(
+ data: MediaQuery.of(
+ context,
+ ).copyWith(textScaler: TextScaler.linear(scale)),
+ child: content,
+ );
+ } else {
+ scaledContent = content;
+ }
+
+ return Semantics(
+ container: true,
+ identifier: 'auth_code_item',
+ label: [
+ widget.code.issuer,
+ widget.code.account,
+ ].where((value) => value.isNotEmpty).join(', '),
+ child: scaledContent,
);
}
@@ -947,9 +954,10 @@ class _CodeWidgetState extends State<CodeWidget> {
.replaceAll('algorithm=sha512', 'algorithm=SHA512');
if (!mounted) return;
- await showDialog(
+ await showBottomSheetComponent<void>(
context: context,
- builder: (BuildContext dialogContext) {
+ useRootNavigator: true,
+ builder: (_) {
return AuthQrDialog(
data: qrData,
title: widget.code.issuer,
diff --git a/mobile/apps/auth/lib/ui/common/dynamic_fab.dart b/mobile/apps/auth/lib/ui/common/dynamic_fab.dart
index c26724120b..449f729e48 100644
--- a/mobile/apps/auth/lib/ui/common/dynamic_fab.dart
+++ b/mobile/apps/auth/lib/ui/common/dynamic_fab.dart
@@ -35,23 +35,30 @@ class DynamicFAB extends StatelessWidget {
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
- FloatingActionButton(
- heroTag: 'FAB',
- backgroundColor: Theme.of(
- context,
- ).colorScheme.dynamicFABBackgroundColor,
- foregroundColor: Theme.of(
- context,
- ).colorScheme.dynamicFABTextColor,
- onPressed: isFormValid!
- ? onPressedFunction as void Function()?
- : () {
- FocusScope.of(context).unfocus();
- },
- child: Transform.rotate(
- angle: isFormValid! ? 0 : math.pi / 2,
- child: const Icon(Icons.chevron_right, size: 36),
- ), //keypad down here
+ Semantics(
+ button: true,
+ container: true,
+ excludeSemantics: true,
+ identifier: 'auth_dynamic_fab',
+ label: buttonText,
+ child: FloatingActionButton(
+ heroTag: 'FAB',
+ backgroundColor: Theme.of(
+ context,
+ ).colorScheme.dynamicFABBackgroundColor,
+ foregroundColor: Theme.of(
+ context,
+ ).colorScheme.dynamicFABTextColor,
+ onPressed: isFormValid!
+ ? onPressedFunction as void Function()?
+ : () {
+ FocusScope.of(context).unfocus();
+ },
+ child: Transform.rotate(
+ angle: isFormValid! ? 0 : math.pi / 2,
+ child: const Icon(Icons.chevron_right, size: 36),
+ ), //keypad down here
+ ),
),
],
),
diff --git a/mobile/apps/auth/lib/ui/components/action_sheet_widget.dart b/mobile/apps/auth/lib/ui/components/action_sheet_widget.dart
index c478f76b7f..b5705a24e9 100644
--- a/mobile/apps/auth/lib/ui/components/action_sheet_widget.dart
+++ b/mobile/apps/auth/lib/ui/components/action_sheet_widget.dart
@@ -1,18 +1,20 @@
-import 'dart:ui';
+import 'dart:io';
-import 'package:ente_auth/theme/colors.dart';
-import 'package:ente_auth/theme/effects.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/ui/components/buttons/button_component_adapter.dart';
import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/components_constants.dart';
import 'package:ente_auth/ui/components/models/button_result.dart';
-import 'package:ente_auth/ui/components/separators.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
enum ActionSheetType { defaultActionSheet, iconOnly }
-///Returns null if dismissed
+/// Compatibility adapter for legacy Auth action sheets.
+///
+/// Existing callers keep their [ButtonWidget] result contract while the sheet
+/// renders through Ente components. New surfaces should use
+/// [BottomSheetComponent] directly.
Future<ButtonResult?> showActionSheet({
required BuildContext context,
required List<ButtonWidget> buttons,
@@ -25,10 +27,11 @@ Future<ButtonResult?> showActionSheet({
String? body,
String? bodyHighlight,
}) {
- return showMaterialModalBottomSheet(
+ final colors = context.componentColors;
+ return showMaterialModalBottomSheet<ButtonResult>(
backgroundColor: Colors.transparent,
- barrierColor: backdropFaintDark,
- useRootNavigator: true,
+ barrierColor: colors.specialScrim.withValues(alpha: 0.55),
+ useRootNavigator: Platform.isIOS,
context: context,
isDismissible: isDismissible,
enableDrag: enableDrag,
@@ -47,14 +50,6 @@ Future<ButtonResult?> showActionSheet({
}
class ActionSheetWidget extends StatelessWidget {
- final String? title;
- final Widget? bodyWidget;
- final String? body;
- final String? bodyHighlight;
- final List<ButtonWidget> actionButtons;
- final ActionSheetType actionSheetType;
- final bool isCheckIconGreen;
-
const ActionSheetWidget({
required this.actionButtons,
required this.actionSheetType,
@@ -66,154 +61,83 @@ class ActionSheetWidget extends StatelessWidget {
super.key,
});
- @override
- Widget build(BuildContext context) {
- final isTitleAndBodyNull =
- title == null && bodyWidget == null && body == null;
- final blur = MediaQuery.of(context).platformBrightness == Brightness.light
- ? blurMuted
- : blurBase;
- final extraWidth = MediaQuery.of(context).size.width - restrictedMaxWidth;
- final double? horizontalPadding = extraWidth > 0 ? extraWidth / 2 : null;
- return Padding(
- padding: EdgeInsets.fromLTRB(
- horizontalPadding ?? 12,
- 12,
- horizontalPadding ?? 12,
- 32,
- ),
- child: Container(
- decoration: BoxDecoration(boxShadow: shadowMenuLight),
- child: ClipRRect(
- borderRadius: const BorderRadius.all(Radius.circular(8)),
- child: BackdropFilter(
- filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur),
- child: Container(
- color: backdropMutedDark,
- child: Padding(
- padding: EdgeInsets.fromLTRB(
- 24,
- 24,
- 24,
- isTitleAndBodyNull ? 24 : 28,
- ),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- isTitleAndBodyNull
- ? const SizedBox.shrink()
- : Padding(
- padding: const EdgeInsets.only(bottom: 36),
- child: ContentContainerWidget(
- title: title,
- bodyWidget: bodyWidget,
- body: body,
- bodyHighlight: bodyHighlight,
- actionSheetType: actionSheetType,
- isCheckIconGreen: isCheckIconGreen,
- ),
- ),
- ActionButtons(actionButtons),
- ],
- ),
- ),
- ),
- ),
- ),
- ),
- );
- }
-}
-
-class ContentContainerWidget extends StatelessWidget {
final String? title;
final Widget? bodyWidget;
final String? body;
final String? bodyHighlight;
+ final List<ButtonWidget> actionButtons;
final ActionSheetType actionSheetType;
final bool isCheckIconGreen;
- const ContentContainerWidget({
- required this.actionSheetType,
- required this.isCheckIconGreen,
- this.title,
- this.bodyWidget,
- this.body,
- this.bodyHighlight,
- super.key,
- });
-
@override
Widget build(BuildContext context) {
- final textTheme = getEnteTextTheme(context);
- final bool bodyMissing = body == null && bodyWidget == null;
- debugPrint("body missing $bodyMissing");
- return Column(
- mainAxisSize: MainAxisSize.min,
- //todo: set cross axis to center when icon should be shown in place of body
- crossAxisAlignment: actionSheetType == ActionSheetType.defaultActionSheet
- ? CrossAxisAlignment.stretch
- : CrossAxisAlignment.center,
- children: [
- title == null
- ? const SizedBox.shrink()
- : Text(
- title!,
- style: textTheme.largeBold.copyWith(
- color: textBaseDark,
- ), //constant color
- ),
- title == null || bodyMissing
- ? const SizedBox.shrink()
- : const SizedBox(height: 19),
- actionSheetType == ActionSheetType.defaultActionSheet
- ? bodyMissing
- ? const SizedBox.shrink()
- : (bodyWidget != null
- ? bodyWidget!
- : Text(
- body!,
- style: textTheme.body.copyWith(
- color: textMutedDark,
- ), //constant color
- ))
- : Icon(
- Icons.check_outlined,
- size: 48,
- color: isCheckIconGreen
- ? getEnteColorScheme(context).primary700
- : strokeBaseDark,
- ),
+ final hasDefaultContent =
actionSheetType == ActionSheetType.defaultActionSheet &&
- bodyHighlight != null
- ? Padding(
- padding: const EdgeInsets.only(top: 19.0),
- child: Text(
- bodyHighlight!,
- style: textTheme.body.copyWith(
- color: textBaseDark,
- ), //constant color
- ),
- )
- : const SizedBox.shrink(),
- ],
+ (bodyWidget != null || body != null || bodyHighlight != null);
+ final hasContent =
+ title != null ||
+ hasDefaultContent ||
+ actionSheetType == ActionSheetType.iconOnly;
+ final colors = context.componentColors;
+ final buttons = LegacySheetButtonConfiguration.from(context, actionButtons);
+ final illustration = actionSheetType == ActionSheetType.iconOnly
+ ? Icon(
+ Icons.check_outlined,
+ size: 48,
+ color: isCheckIconGreen ? colors.primary : colors.iconColor,
+ )
+ : null;
+
+ return BottomSheetComponent(
+ title: title,
+ illustration: illustration,
+ content: hasDefaultContent
+ ? _ActionSheetContent(
+ bodyWidget: bodyWidget,
+ body: body,
+ bodyHighlight: bodyHighlight,
+ )
+ : null,
+ actions: buttons.actions,
+ showCloseButton: buttons.showCloseButton,
+ closeTooltip: context.l10n.close,
+ closeResult: buttons.closeResult,
+ onClose: buttons.onClose(context),
+ actionsTopSpacing: hasContent ? Spacing.lg : 0,
);
}
}
-class ActionButtons extends StatelessWidget {
- final List<Widget> actionButtons;
- const ActionButtons(this.actionButtons, {super.key});
+class _ActionSheetContent extends StatelessWidget {
+ const _ActionSheetContent({this.bodyWidget, this.body, this.bodyHighlight});
+
+ final Widget? bodyWidget;
+ final String? body;
+ final String? bodyHighlight;
@override
Widget build(BuildContext context) {
- final actionButtonsWithSeparators = actionButtons;
+ final colors = context.componentColors;
+ final hasBody = body != null || bodyWidget != null;
+
return Column(
- children:
- //Separator height is 8pts in figma. -2pts here as the action
- //buttons are 2pts extra in height in code compared to figma because
- //of the border(1pt top + 1pt bottom) of action buttons.
- addSeparators(actionButtonsWithSeparators, const SizedBox(height: 6)),
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (hasBody)
+ bodyWidget ??
+ Text(
+ body!,
+ style: TextStyles.body.copyWith(color: colors.textLight),
+ ),
+ if (bodyHighlight != null) ...[
+ if (hasBody) const SizedBox(height: Spacing.lg),
+ Text(
+ bodyHighlight!,
+ style: TextStyles.body.copyWith(color: colors.textBase),
+ ),
+ ],
+ ],
);
}
}
diff --git a/mobile/apps/auth/lib/ui/components/auth_qr_dialog.dart b/mobile/apps/auth/lib/ui/components/auth_qr_dialog.dart
index 0f37fbe8da..0f8b3a192d 100644
--- a/mobile/apps/auth/lib/ui/components/auth_qr_dialog.dart
+++ b/mobile/apps/auth/lib/ui/components/auth_qr_dialog.dart
@@ -3,8 +3,10 @@ import 'dart:math';
import 'dart:typed_data';
import 'dart:ui' as ui;
+import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/theme/colors.dart';
import 'package:ente_auth/theme/ente_theme.dart';
+import 'package:ente_components/ente_components.dart' hide textBaseLight;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_svg/flutter_svg.dart';
@@ -80,207 +82,117 @@ class _AuthQrDialogState extends State<AuthQrDialog> {
final screenWidth = MediaQuery.of(context).size.width;
final double qrSize = min(screenWidth - 80, 300.0);
final enteTextTheme = getEnteTextTheme(context);
- final theme = Theme.of(context);
- final isDark = theme.brightness == Brightness.dark;
// QR text color - always black for scanability
const qrTextColor = textBaseLight;
- final dialogBackgroundColor = isDark
- ? const Color(0xFF212121)
- : theme.colorScheme.surface;
- final closeBgColor = isDark
- ? const Color(0xFF292929)
- : const Color(0xFFF5F5F7);
- final closeIconColor = isDark ? theme.colorScheme.onSurface : qrTextColor;
-
- final dialogTitleStyle = theme.textTheme.titleLarge?.copyWith(
- fontSize: 20,
- fontWeight: FontWeight.w700,
- color: theme.colorScheme.onSurface,
- );
- final shareButtonStyle = theme.textTheme.labelLarge?.copyWith(
- fontSize: 16,
- fontWeight: FontWeight.w600,
- color: Colors.white,
- );
-
- return Dialog(
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
- shadowColor: isDark
- ? Colors.black.withValues(alpha: 0.7)
- : Colors.grey.withValues(alpha: 0.5),
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 400),
- child: Container(
- decoration: BoxDecoration(
- color: dialogBackgroundColor,
- borderRadius: BorderRadius.circular(24),
- border: isDark
- ? Border.all(
- color: Colors.white.withValues(alpha: 0.1),
- width: 1,
- )
- : null,
+ return Semantics(
+ identifier: 'auth_qr_sheet',
+ child: BottomSheetComponent(
+ title: widget.dialogTitle,
+ closeTooltip: context.l10n.close,
+ content: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.sizeOf(context).height * 0.62,
),
child: SingleChildScrollView(
- padding: const EdgeInsets.all(20),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Padding(
- padding: const EdgeInsets.only(left: 6, bottom: 4),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ child: RepaintBoundary(
+ key: _qrKey,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(Radii.sheet),
+ child: Container(
+ width: double.infinity,
+ decoration: const BoxDecoration(color: qrBoxColor),
+ child: Stack(
+ clipBehavior: Clip.none,
+ alignment: Alignment.center,
children: [
- Text(widget.dialogTitle, style: dialogTitleStyle),
- GestureDetector(
- onTap: () => Navigator.of(context).pop(),
- child: Container(
- width: 36,
- height: 36,
- decoration: BoxDecoration(
- color: closeBgColor,
- borderRadius: BorderRadius.circular(18),
- ),
- child: Icon(
- Icons.close,
- size: 20,
- color: closeIconColor,
+ Positioned(
+ top: 2,
+ right: 2,
+ child: Transform.rotate(
+ angle: -4 * pi / 180,
+ child: Image.asset(
+ 'assets/qr_logo.png',
+ height: qrSize * 0.19,
+ width: qrSize * 0.19,
),
),
),
- ],
- ),
- ),
- const SizedBox(height: 8),
- RepaintBoundary(
- key: _qrKey,
- child: ClipRRect(
- borderRadius: BorderRadius.circular(22),
- child: Container(
- width: double.infinity,
- decoration: const BoxDecoration(color: qrBoxColor),
- child: Stack(
- clipBehavior: Clip.none,
- alignment: Alignment.center,
- children: [
- // Ente Auth icon at top right - positioned at corner
- Positioned(
- top: 2,
- right: 2,
- child: Transform.rotate(
- angle: -4 * 3.14159 / 180, // -4 degrees
- child: Image.asset(
- 'assets/qr_logo.png',
- height: qrSize * 0.19,
- width: qrSize * 0.19,
+ Padding(
+ padding: EdgeInsets.all(qrSize * 0.07),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ SizedBox(height: qrSize * 0.03),
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: qrSize - 72,
),
- ),
- ),
- Padding(
- padding: EdgeInsets.all(qrSize * 0.07),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- SizedBox(height: qrSize * 0.03),
- // Issuer at top center
- // Leave space for the logo (64px) + some padding
- ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: qrSize - 72,
- ),
- child: Text(
- widget.title,
- style: enteTextTheme.largeBold.copyWith(
- color: qrTextColor,
- fontSize: 20,
- ),
- textAlign: TextAlign.center,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
+ child: Text(
+ widget.title,
+ style: enteTextTheme.largeBold.copyWith(
+ color: qrTextColor,
+ fontSize: 20,
),
- if (widget.subtitle != null &&
- widget.subtitle!.isNotEmpty) ...[
- const SizedBox(height: 4),
- ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: qrSize,
- ),
- child: Text(
- widget.subtitle!,
- style: enteTextTheme.small.copyWith(
- color: qrTextColor.withValues(
- alpha: 0.7,
- ),
- fontSize: 14,
- ),
- textAlign: TextAlign.center,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ),
- ],
- SizedBox(height: qrSize * 0.07),
-
- // QR Code with square style and purple corners
- QrImageView(
- data: widget.data,
- eyeStyle: const QrEyeStyle(
- eyeShape: QrEyeShape.square,
- color: accentColor,
- ),
- dataModuleStyle: const QrDataModuleStyle(
- dataModuleShape: QrDataModuleShape.square,
- color: qrTextColor,
- ),
- version: QrVersions.auto,
- size: qrSize,
+ textAlign: TextAlign.center,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ if (widget.subtitle?.isNotEmpty == true) ...[
+ const SizedBox(height: Spacing.xs),
+ Text(
+ widget.subtitle!,
+ style: enteTextTheme.small.copyWith(
+ color: qrTextColor.withValues(alpha: 0.7),
+ fontSize: 14,
),
- SizedBox(height: qrSize * 0.07),
- // Auth branding at bottom right
- Align(
- alignment: Alignment.centerRight,
- child: SvgPicture.asset(
- 'assets/svg/app-logo.svg',
- height: 16,
- colorFilter: const ColorFilter.mode(
- accentColor,
- BlendMode.srcIn,
- ),
- ),
+ textAlign: TextAlign.center,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ],
+ SizedBox(height: qrSize * 0.07),
+ QrImageView(
+ data: widget.data,
+ eyeStyle: const QrEyeStyle(
+ eyeShape: QrEyeShape.square,
+ color: accentColor,
+ ),
+ dataModuleStyle: const QrDataModuleStyle(
+ dataModuleShape: QrDataModuleShape.square,
+ color: qrTextColor,
+ ),
+ version: QrVersions.auto,
+ size: qrSize,
+ ),
+ SizedBox(height: qrSize * 0.07),
+ Align(
+ alignment: Alignment.centerRight,
+ child: SvgPicture.asset(
+ 'assets/svg/app-logo.svg',
+ height: 16,
+ colorFilter: const ColorFilter.mode(
+ accentColor,
+ BlendMode.srcIn,
),
- ],
+ ),
),
- ),
- ],
+ ],
+ ),
),
- ),
- ),
- ),
- const SizedBox(height: 24),
- GestureDetector(
- onTap: _shareQrCode,
- child: Container(
- width: double.infinity,
- padding: const EdgeInsets.symmetric(vertical: 14),
- decoration: BoxDecoration(
- color: accentColor,
- borderRadius: BorderRadius.circular(12),
- ),
- child: Text(
- widget.shareButtonText,
- textAlign: TextAlign.center,
- style: shareButtonStyle,
- ),
+ ],
),
),
- ],
+ ),
),
),
),
+ actions: [
+ ButtonComponent(label: widget.shareButtonText, onTap: _shareQrCode),
+ ],
),
);
}
diff --git a/mobile/apps/auth/lib/ui/components/auth_selection_action_button.dart b/mobile/apps/auth/lib/ui/components/auth_selection_action_button.dart
new file mode 100644
index 0000000000..ed50ed577a
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/components/auth_selection_action_button.dart
@@ -0,0 +1,67 @@
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+
+/// Auth-local selection action composed from Ente design tokens.
+class AuthSelectionActionButton extends StatelessWidget {
+ const AuthSelectionActionButton({
+ super.key,
+ required this.label,
+ required this.icon,
+ required this.onTap,
+ this.isDestructive = false,
+ this.semanticsIdentifier,
+ });
+
+ final String label;
+ final Widget icon;
+ final VoidCallback onTap;
+ final bool isDestructive;
+ final String? semanticsIdentifier;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.componentColors;
+ final foreground = isDestructive ? colors.warning : colors.textBase;
+
+ return Semantics(
+ button: true,
+ label: label,
+ identifier: semanticsIdentifier,
+ child: Material(
+ color: colors.fillLight,
+ borderRadius: BorderRadius.circular(Radii.sheet),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: onTap,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: Spacing.sm,
+ vertical: Spacing.lg,
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ ColorFiltered(
+ colorFilter: ColorFilter.mode(foreground, BlendMode.srcIn),
+ child: SizedBox.square(
+ dimension: IconSizes.medium,
+ child: Center(child: icon),
+ ),
+ ),
+ const SizedBox(height: Spacing.sm),
+ Text(
+ label,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ textAlign: TextAlign.center,
+ style: TextStyles.mini.copyWith(color: foreground),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/components/buttons/button_component_adapter.dart b/mobile/apps/auth/lib/ui/components/buttons/button_component_adapter.dart
new file mode 100644
index 0000000000..87da542527
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/components/buttons/button_component_adapter.dart
@@ -0,0 +1,158 @@
+import 'dart:async';
+
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/ui/components/buttons/button_widget.dart';
+import 'package:ente_auth/ui/components/models/button_result.dart';
+import 'package:ente_auth/ui/components/models/button_type.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
+
+const _loadingSurfaceDelay = Duration(milliseconds: 300);
+const _successDisplayDuration = Duration(seconds: 1);
+
+/// Preserves legacy Auth button behavior while rendering an Ente component.
+class ButtonComponentAdapter extends StatelessWidget {
+ const ButtonComponentAdapter({required this.button, super.key});
+
+ final ButtonWidget button;
+
+ @override
+ Widget build(BuildContext context) {
+ return ButtonComponent(
+ label: button.labelText ?? '',
+ leading: button.icon == null
+ ? null
+ : Icon(button.icon, color: button.iconColor),
+ onTap: button.isDisabled ? null : () => _handleTap(context),
+ variant: _variantFor(button.buttonType),
+ size: _sizeFor(button.buttonSize),
+ isDisabled: button.isDisabled,
+ shouldSurfaceExecutionStates: button.shouldSurfaceExecutionStates,
+ shouldShowSuccessConfirmation: button.shouldShowSuccessConfirmation,
+ progressStatus: button.progressStatus,
+ );
+ }
+
+ Future<void> _handleTap(BuildContext context) async {
+ final stopwatch = Stopwatch()..start();
+ try {
+ await _invokeButtonAction(context, button);
+ } finally {
+ stopwatch.stop();
+ }
+
+ if (!button.isInAlert) return;
+
+ final delay = _popDelay(button, stopwatch.elapsed);
+ unawaited(
+ Future<void>.delayed(delay, () {
+ if (context.mounted) {
+ _popWithResult(context, ButtonResult(button.buttonAction));
+ }
+ }),
+ );
+ }
+}
+
+ButtonComponentVariant _variantFor(ButtonType buttonType) {
+ return switch (buttonType) {
+ ButtonType.primary ||
+ ButtonType.trailingIconPrimary => ButtonComponentVariant.primary,
+ ButtonType.secondary ||
+ ButtonType.trailingIconSecondary => ButtonComponentVariant.secondary,
+ ButtonType.critical => ButtonComponentVariant.critical,
+ ButtonType.tertiaryCritical => ButtonComponentVariant.tertiaryCritical,
+ ButtonType.tertiary => ButtonComponentVariant.link,
+ ButtonType.neutral ||
+ ButtonType.trailingIcon => ButtonComponentVariant.neutral,
+ };
+}
+
+ButtonComponentSize _sizeFor(ButtonSize buttonSize) {
+ return switch (buttonSize) {
+ ButtonSize.small => ButtonComponentSize.small,
+ ButtonSize.large => ButtonComponentSize.large,
+ };
+}
+
+Duration _popDelay(ButtonWidget button, Duration elapsed) {
+ if (!button.shouldSurfaceExecutionStates) return Duration.zero;
+ if (button.shouldShowSuccessConfirmation || elapsed >= _loadingSurfaceDelay) {
+ return _successDisplayDuration;
+ }
+ return Duration.zero;
+}
+
+void _popWithResult(BuildContext context, ButtonResult result) {
+ final route = ModalRoute.of(context);
+ if (route != null &&
+ route.isCurrent &&
+ (route is PopupRoute || route is ModalSheetRoute)) {
+ Navigator.of(context).pop(result);
+ }
+}
+
+Exception _toException(Object error) {
+ return error is Exception ? error : Exception(error.toString());
+}
+
+Future<void> _invokeButtonAction(
+ BuildContext context,
+ ButtonWidget button,
+) async {
+ try {
+ await button.onTap?.call();
+ } catch (error) {
+ if (button.isInAlert && context.mounted) {
+ _popWithResult(
+ context,
+ ButtonResult(ButtonAction.error, _toException(error)),
+ );
+ }
+ rethrow;
+ }
+}
+
+class LegacySheetButtonConfiguration {
+ LegacySheetButtonConfiguration._({
+ required this.actions,
+ required this.cancelButton,
+ });
+
+ factory LegacySheetButtonConfiguration.from(
+ BuildContext context,
+ List<ButtonWidget> buttons,
+ ) {
+ final cancelLabels = {context.l10n.cancel, 'Cancel'};
+ final cancelButtonIndex = buttons.indexWhere(
+ (button) =>
+ button.isInAlert &&
+ !button.isDisabled &&
+ cancelLabels.contains(button.labelText),
+ );
+ return LegacySheetButtonConfiguration._(
+ actions: [
+ for (var index = 0; index < buttons.length; index++)
+ if (index != cancelButtonIndex)
+ ButtonComponentAdapter(button: buttons[index]),
+ ],
+ cancelButton: cancelButtonIndex == -1 ? null : buttons[cancelButtonIndex],
+ );
+ }
+
+ final List<Widget> actions;
+ final ButtonWidget? cancelButton;
+
+ bool get showCloseButton => cancelButton != null;
+
+ ButtonResult? get closeResult {
+ final button = cancelButton;
+ return button == null ? null : ButtonResult(button.buttonAction);
+ }
+
+ FutureOr<void> Function()? onClose(BuildContext context) {
+ final button = cancelButton;
+ return button == null ? null : () => _invokeButtonAction(context, button);
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/components/captioned_text_widget.dart b/mobile/apps/auth/lib/ui/components/captioned_text_widget.dart
deleted file mode 100644
index 3d8a9068b6..0000000000
--- a/mobile/apps/auth/lib/ui/components/captioned_text_widget.dart
+++ /dev/null
@@ -1,56 +0,0 @@
-import 'package:ente_auth/ente_theme_data.dart';
-import 'package:flutter/material.dart';
-
-class CaptionedTextWidget extends StatelessWidget {
- final String title;
- final String? subTitle;
- final TextStyle? textStyle;
- final bool makeTextBold;
- final Color? textColor;
- const CaptionedTextWidget({
- required this.title,
- this.subTitle,
- this.textStyle,
- this.makeTextBold = false,
- this.textColor,
- super.key,
- });
-
- @override
- Widget build(BuildContext context) {
- final enteColorScheme = Theme.of(context).colorScheme.enteTheme.colorScheme;
- final enteTextTheme = Theme.of(context).colorScheme.enteTheme.textTheme;
-
- return Flexible(
- child: Padding(
- padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 2),
- child: Row(
- children: [
- Flexible(
- child: RichText(
- text: TextSpan(
- style:
- textStyle ??
- (makeTextBold
- ? enteTextTheme.bodyBold.copyWith(color: textColor)
- : enteTextTheme.body.copyWith(color: textColor)),
- children: [
- TextSpan(text: title),
- subTitle != null
- ? TextSpan(
- text: ' \u2022 $subTitle',
- style: enteTextTheme.small.copyWith(
- color: enteColorScheme.textMuted,
- ),
- )
- : const TextSpan(text: ''),
- ],
- ),
- ),
- ),
- ],
- ),
- ),
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/components/dialog_widget.dart b/mobile/apps/auth/lib/ui/components/dialog_widget.dart
index e3dcea1f41..075d17d71a 100644
--- a/mobile/apps/auth/lib/ui/components/dialog_widget.dart
+++ b/mobile/apps/auth/lib/ui/components/dialog_widget.dart
@@ -1,17 +1,13 @@
-import 'dart:math';
+import 'dart:async';
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/colors.dart';
-import 'package:ente_auth/theme/effects.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
+import 'package:ente_auth/ui/components/buttons/button_component_adapter.dart';
import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/components_constants.dart';
import 'package:ente_auth/ui/components/models/button_result.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
-import 'package:ente_auth/ui/components/separators.dart';
-import 'package:ente_auth/ui/components/text_input_widget.dart';
import 'package:ente_base/typedefs.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
///Will return null if dismissed by tapping outside
Future<ButtonResult?> showDialogWidget({
@@ -23,25 +19,17 @@ Future<ButtonResult?> showDialogWidget({
bool isDismissible = true,
bool useRootNavigator = false,
}) {
- return showDialog(
- useRootNavigator: useRootNavigator,
- barrierDismissible: isDismissible,
- barrierColor: backdropFaintDark,
+ return showBottomSheetComponent<ButtonResult>(
context: context,
- builder: (context) {
- final widthOfScreen = MediaQuery.of(context).size.width;
- final isMobileSmall = widthOfScreen <= mobileSmallThreshold;
- return Padding(
- padding: EdgeInsets.symmetric(horizontal: isMobileSmall ? 8 : 0),
- child: Dialog(
- insetPadding: EdgeInsets.zero,
- child: DialogWidget(
- title: title,
- body: body,
- buttons: buttons,
- icon: icon,
- ),
- ),
+ isDismissible: isDismissible,
+ enableDrag: isDismissible,
+ useRootNavigator: useRootNavigator,
+ builder: (_) {
+ return DialogWidget(
+ title: title,
+ body: body,
+ buttons: buttons,
+ icon: icon,
);
},
);
@@ -62,91 +50,43 @@ class DialogWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
- final widthOfScreen = MediaQuery.of(context).size.width;
- final isMobileSmall = widthOfScreen <= mobileSmallThreshold;
- final colorScheme = getEnteColorScheme(context);
- return Container(
- width: min(widthOfScreen, 320),
- padding: isMobileSmall
- ? const EdgeInsets.all(0)
- : const EdgeInsets.fromLTRB(6, 8, 6, 6),
- decoration: BoxDecoration(
- color: colorScheme.backgroundElevated,
- boxShadow: shadowFloatLight,
- borderRadius: const BorderRadius.all(Radius.circular(8)),
- ),
- child: Material(
- color: Colors.transparent,
- child: Padding(
- padding: const EdgeInsets.all(16),
- child: SingleChildScrollView(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- ContentContainer(title: title, body: body, icon: icon),
- const SizedBox(height: 36),
- Actions(buttons),
- ],
- ),
- ),
- ),
- ),
- );
- }
-}
-
-class ContentContainer extends StatelessWidget {
- final String title;
- final String? body;
- final IconData? icon;
- const ContentContainer({
- required this.title,
- this.body,
- this.icon,
- super.key,
- });
+ final colors = context.componentColors;
+ final hasTitle = title.isNotEmpty;
+ final hasBody = body?.isNotEmpty == true;
+ final hasContent = hasTitle || hasBody || icon != null;
+ final sheetButtons = LegacySheetButtonConfiguration.from(context, buttons);
- @override
- Widget build(BuildContext context) {
- final textTheme = getEnteTextTheme(context);
- final colorScheme = getEnteColorScheme(context);
- return Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- icon == null
- ? const SizedBox.shrink()
- : Row(children: [Icon(icon, size: 32)]),
- icon == null ? const SizedBox.shrink() : const SizedBox(height: 19),
- Text(title, style: textTheme.largeBold),
- body != null ? const SizedBox(height: 19) : const SizedBox.shrink(),
- body != null
- ? Text(
- body!,
- style: textTheme.body.copyWith(color: colorScheme.textMuted),
- )
- : const SizedBox.shrink(),
- ],
+ return BottomSheetComponent(
+ title: hasTitle ? title : null,
+ illustration: icon == null
+ ? null
+ : Icon(icon, size: 48, color: colors.iconColor),
+ content: hasBody ? _DialogBody(body!) : null,
+ actions: sheetButtons.actions,
+ showCloseButton: sheetButtons.showCloseButton,
+ closeTooltip: context.l10n.close,
+ closeResult: sheetButtons.closeResult,
+ onClose: sheetButtons.onClose(context),
+ actionsTopSpacing: hasContent ? Spacing.xl : 0,
);
}
}
-class Actions extends StatelessWidget {
- final List<ButtonWidget> buttons;
- const Actions(this.buttons, {super.key});
+class _DialogBody extends StatelessWidget {
+ const _DialogBody(this.body);
+
+ final String body;
@override
Widget build(BuildContext context) {
- return Column(
- children: addSeparators(
- buttons,
- const SizedBox(
- // In figma this white space is of height 8pts. But the Button
- // component has 1pts of invisible border by default in code. So two
- // 1pts borders will visually make the whitespace 8pts.
- // Height of button component in figma = 48, in code = 50 (2pts for
- // top + bottom border)
- height: 6,
+ final colors = context.componentColors;
+ final maxHeight = MediaQuery.sizeOf(context).height * 0.45;
+ return ConstrainedBox(
+ constraints: BoxConstraints(maxHeight: maxHeight),
+ child: SingleChildScrollView(
+ child: Text(
+ body,
+ style: TextStyles.body.copyWith(color: colors.textLight),
),
),
);
@@ -195,88 +135,179 @@ class TextInputDialog extends StatefulWidget {
}
class _TextInputDialogState extends State<TextInputDialog> {
- //the value of this ValueNotifier has no significance
- final _submitNotifier = ValueNotifier(false);
+ static const _loadingSurfaceDelay = Duration(milliseconds: 300);
+ static const _successDisplayDuration = Duration(seconds: 1);
+
+ late final TextEditingController _textController;
+ Timer? _inputErrorResetTimer;
+ var _hasInput = false;
+ var _hasInputError = false;
+ var _isSubmitting = false;
+
+ @override
+ void initState() {
+ super.initState();
+ _textController = TextEditingController(text: widget.initialValue);
+ _hasInput = _textController.text.isNotEmpty;
+ _textController.addListener(_onTextChanged);
+ }
@override
void dispose() {
- _submitNotifier.dispose();
+ _inputErrorResetTimer?.cancel();
+ _textController
+ ..removeListener(_onTextChanged)
+ ..dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
- final widthOfScreen = MediaQuery.of(context).size.width;
- final isMobileSmall = widthOfScreen <= mobileSmallThreshold;
- final colorScheme = getEnteColorScheme(context);
- return Container(
- width: min(widthOfScreen, 320),
- padding: isMobileSmall
- ? const EdgeInsets.all(0)
- : const EdgeInsets.fromLTRB(6, 8, 6, 6),
- decoration: BoxDecoration(
- color: colorScheme.backgroundElevated,
- boxShadow: shadowFloatLight,
- borderRadius: const BorderRadius.all(Radius.circular(8)),
- ),
- child: Padding(
- padding: const EdgeInsets.all(16),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- ContentContainer(
- title: widget.title,
- body: widget.body,
- icon: widget.icon,
- ),
- Padding(
- padding: const EdgeInsets.only(top: 19),
- child: TextInputWidget(
- label: widget.label,
- message: widget.message,
- hintText: widget.hintText,
- prefixIcon: widget.prefixIcon,
- initialValue: widget.initialValue,
- alignMessage: widget.alignMessage,
- autoFocus: true,
- maxLength: widget.maxLength,
- submitNotifier: _submitNotifier,
- onSubmit: widget.onSubmit,
- popNavAfterSubmission: true,
- showOnlyLoadingState: widget.showOnlyLoadingState,
- textCapitalization: widget.textCapitalization,
- alwaysShowSuccessState: widget.alwaysShowSuccessState,
- isPasswordInput: widget.isPasswordInput,
- ),
- ),
- const SizedBox(height: 36),
- Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Expanded(
- child: ButtonWidget(
- buttonType: ButtonType.secondary,
- buttonSize: ButtonSize.small,
- labelText: context.l10n.cancel,
- isInAlert: true,
- ),
- ),
- const SizedBox(width: 8),
- Expanded(
- child: ButtonWidget(
- buttonSize: ButtonSize.small,
- buttonType: ButtonType.neutral,
- labelText: widget.submitButtonLabel,
- onTap: () async {
- _submitNotifier.value = !_submitNotifier.value;
- },
- ),
- ),
- ],
- ),
- ],
+ final colors = context.componentColors;
+ return BottomSheetComponent(
+ title: widget.title,
+ illustration: widget.icon == null
+ ? null
+ : Icon(widget.icon, size: 48, color: colors.iconColor),
+ content: _TextInputDialogContent(
+ body: widget.body,
+ input: TextInputComponent(
+ controller: _textController,
+ label: widget.label,
+ message: widget.alignMessage == null ? widget.message : null,
+ messageType: _hasInputError
+ ? TextInputComponentMessageType.error
+ : TextInputComponentMessageType.helper,
+ hintText: widget.hintText,
+ autofocus: true,
+ maxLength: widget.maxLength,
+ onSubmit: (_) => _submit(),
+ textCapitalization:
+ widget.textCapitalization ?? TextCapitalization.none,
+ isPasswordInput: widget.isPasswordInput,
+ isClearable: !widget.isPasswordInput,
+ prefix: widget.prefixIcon == null
+ ? null
+ : Icon(widget.prefixIcon, size: IconSizes.small),
),
+ alignedMessage: widget.alignMessage == null ? null : widget.message,
+ alignedMessageAlignment: widget.alignMessage,
),
+ actions: [
+ ButtonComponent(
+ label: widget.submitButtonLabel,
+ isDisabled: !_hasInput,
+ shouldShowSuccessState: !widget.showOnlyLoadingState,
+ shouldShowSuccessConfirmation:
+ !widget.showOnlyLoadingState && widget.alwaysShowSuccessState,
+ onTap: _hasInput ? () => _submit(throwOnError: true) : null,
+ ),
+ ],
+ isKeyboardAware: true,
+ showCloseButton: true,
+ closeTooltip: context.l10n.close,
+ closeResult: ButtonResult(),
+ );
+ }
+
+ void _onTextChanged() {
+ final hasInput = _textController.text.isNotEmpty;
+ if (hasInput != _hasInput || _hasInputError) {
+ setState(() {
+ _hasInput = hasInput;
+ _hasInputError = false;
+ });
+ }
+ }
+
+ Future<void> _submit({bool throwOnError = false}) async {
+ if (_isSubmitting || !_hasInput) return;
+
+ _isSubmitting = true;
+ final stopwatch = Stopwatch()..start();
+ try {
+ await widget.onSubmit(_textController.text);
+ } catch (error) {
+ final exception = error is Exception
+ ? error
+ : Exception(error.toString());
+ _isSubmitting = false;
+ if (error.toString().contains('Incorrect password') && mounted) {
+ _surfaceInputError();
+ }
+ if (mounted) Navigator.of(context).pop(exception);
+ if (throwOnError) throw exception;
+ return;
+ } finally {
+ stopwatch.stop();
+ }
+
+ if (!mounted) {
+ _isSubmitting = false;
+ return;
+ }
+
+ unawaited(
+ Future<void>.delayed(_popDelay(stopwatch.elapsed), () {
+ if (mounted) Navigator.of(context).pop();
+ }),
+ );
+ }
+
+ Duration _popDelay(Duration elapsed) {
+ if (widget.showOnlyLoadingState) return Duration.zero;
+ if (widget.alwaysShowSuccessState || elapsed >= _loadingSurfaceDelay) {
+ return _successDisplayDuration;
+ }
+ return Duration.zero;
+ }
+
+ void _surfaceInputError() {
+ HapticFeedback.vibrate();
+ setState(() => _hasInputError = true);
+ _inputErrorResetTimer?.cancel();
+ _inputErrorResetTimer = Timer(const Duration(seconds: 1), () {
+ if (mounted) setState(() => _hasInputError = false);
+ });
+ }
+}
+
+class _TextInputDialogContent extends StatelessWidget {
+ const _TextInputDialogContent({
+ required this.input,
+ this.body,
+ this.alignedMessage,
+ this.alignedMessageAlignment,
+ });
+
+ final Widget input;
+ final String? body;
+ final String? alignedMessage;
+ final Alignment? alignedMessageAlignment;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.componentColors;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (body != null) ...[
+ Text(body!, style: TextStyles.body.copyWith(color: colors.textLight)),
+ const SizedBox(height: Spacing.lg),
+ ],
+ input,
+ if (alignedMessage != null) ...[
+ const SizedBox(height: Spacing.sm),
+ Align(
+ alignment: alignedMessageAlignment ?? Alignment.centerLeft,
+ child: Text(
+ alignedMessage!,
+ style: TextStyles.mini.copyWith(color: colors.textLight),
+ ),
+ ),
+ ],
+ ],
);
}
}
diff --git a/mobile/apps/auth/lib/ui/components/expandable_menu_item_widget.dart b/mobile/apps/auth/lib/ui/components/expandable_menu_item_widget.dart
deleted file mode 100644
index e14d75fb8a..0000000000
--- a/mobile/apps/auth/lib/ui/components/expandable_menu_item_widget.dart
+++ /dev/null
@@ -1,78 +0,0 @@
-import 'package:ente_auth/ente_theme_data.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/settings/common_settings.dart';
-import 'package:expandable/expandable.dart';
-import 'package:flutter/material.dart';
-
-class ExpandableMenuItemWidget extends StatefulWidget {
- final String title;
- final Widget selectionOptionsWidget;
- final IconData leadingIcon;
- const ExpandableMenuItemWidget({
- required this.title,
- required this.selectionOptionsWidget,
- required this.leadingIcon,
- super.key,
- });
-
- @override
- State<ExpandableMenuItemWidget> createState() =>
- _ExpandableMenuItemWidgetState();
-}
-
-class _ExpandableMenuItemWidgetState extends State<ExpandableMenuItemWidget> {
- final expandableController = ExpandableController(initialExpanded: false);
- @override
- void initState() {
- expandableController.addListener(() {
- setState(() {});
- });
- super.initState();
- }
-
- @override
- void dispose() {
- expandableController.removeListener(() {});
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- final enteColorScheme = Theme.of(context).colorScheme.enteTheme.colorScheme;
- final backgroundColor =
- MediaQuery.of(context).platformBrightness == Brightness.light
- ? enteColorScheme.backgroundElevated2
- : enteColorScheme.backgroundElevated;
- return AnimatedContainer(
- curve: Curves.ease,
- duration: const Duration(milliseconds: 200),
- decoration: BoxDecoration(
- color: expandableController.value ? backgroundColor : null,
- borderRadius: BorderRadius.circular(4),
- ),
- child: ExpandableNotifier(
- controller: expandableController,
- child: ScrollOnExpand(
- child: ExpandablePanel(
- header: MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: widget.title,
- makeTextBold: true,
- ),
- isExpandable: true,
- leadingIcon: widget.leadingIcon,
- trailingIcon: Icons.expand_more,
- menuItemColor: enteColorScheme.fillFaint,
- expandableController: expandableController,
- ),
- collapsed: const SizedBox.shrink(),
- expanded: widget.selectionOptionsWidget,
- theme: getExpandableTheme(),
- controller: expandableController,
- ),
- ),
- ),
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/components/menu_item_child_widgets.dart b/mobile/apps/auth/lib/ui/components/menu_item_child_widgets.dart
deleted file mode 100644
index b43395a2de..0000000000
--- a/mobile/apps/auth/lib/ui/components/menu_item_child_widgets.dart
+++ /dev/null
@@ -1,164 +0,0 @@
-import 'package:ente_auth/models/execution_states.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/common/loading_widget.dart';
-import 'package:flutter/material.dart';
-
-class TrailingWidget extends StatefulWidget {
- final ValueNotifier executionStateNotifier;
- final IconData? trailingIcon;
- final Color? trailingIconColor;
- final Widget? trailingWidget;
- final bool trailingIconIsMuted;
- final double trailingExtraMargin;
- final bool showExecutionStates;
- const TrailingWidget({
- super.key,
- required this.executionStateNotifier,
- this.trailingIcon,
- this.trailingIconColor,
- this.trailingWidget,
- required this.trailingIconIsMuted,
- required this.trailingExtraMargin,
- required this.showExecutionStates,
- });
- @override
- State<TrailingWidget> createState() => _TrailingWidgetState();
-}
-
-class _TrailingWidgetState extends State<TrailingWidget> {
- Widget? trailingWidget;
- @override
- void initState() {
- widget.showExecutionStates
- ? widget.executionStateNotifier.addListener(_executionStateListener)
- : null;
- super.initState();
- }
-
- @override
- void dispose() {
- widget.executionStateNotifier.removeListener(_executionStateListener);
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- if (trailingWidget == null || !widget.showExecutionStates) {
- _setTrailingIcon();
- }
- return AnimatedSwitcher(
- duration: const Duration(milliseconds: 175),
- switchInCurve: Curves.easeInExpo,
- switchOutCurve: Curves.easeOutExpo,
- child: trailingWidget,
- );
- }
-
- void _executionStateListener() {
- final colorScheme = getEnteColorScheme(context);
- setState(() {
- if (widget.executionStateNotifier.value == ExecutionState.idle) {
- _setTrailingIcon();
- } else if (widget.executionStateNotifier.value ==
- ExecutionState.inProgress) {
- trailingWidget = EnteLoadingWidget(color: colorScheme.strokeMuted);
- } else if (widget.executionStateNotifier.value ==
- ExecutionState.successful) {
- trailingWidget = Icon(
- Icons.check_outlined,
- size: 22,
- color: colorScheme.primary500,
- );
- } else {
- trailingWidget = const SizedBox.shrink();
- }
- });
- }
-
- void _setTrailingIcon() {
- if (widget.trailingIcon != null) {
- trailingWidget = Padding(
- padding: EdgeInsets.only(right: widget.trailingExtraMargin),
- child: Icon(
- widget.trailingIcon,
- color: widget.trailingIconIsMuted
- ? getEnteColorScheme(context).strokeMuted
- : widget.trailingIconColor,
- ),
- );
- } else {
- trailingWidget = widget.trailingWidget ?? const SizedBox.shrink();
- }
- }
-}
-
-class ExpansionTrailingIcon extends StatelessWidget {
- final bool isExpanded;
- final IconData? trailingIcon;
- final Color? trailingIconColor;
- const ExpansionTrailingIcon({
- super.key,
- required this.isExpanded,
- this.trailingIcon,
- this.trailingIconColor,
- });
-
- @override
- Widget build(BuildContext context) {
- return AnimatedOpacity(
- duration: const Duration(milliseconds: 100),
- curve: Curves.easeInOut,
- opacity: isExpanded ? 0 : 1,
- child: AnimatedSwitcher(
- transitionBuilder: (child, animation) {
- return ScaleTransition(scale: animation, child: child);
- },
- duration: const Duration(milliseconds: 200),
- switchInCurve: Curves.easeOut,
- child: isExpanded
- ? const SizedBox.shrink()
- : Icon(trailingIcon, color: trailingIconColor),
- ),
- );
- }
-}
-
-class LeadingWidget extends StatelessWidget {
- final IconData? leadingIcon;
- final Color? leadingIconColor;
-
- final Widget? leadingIconWidget;
- // leadIconSize deafult value is 20.
- final double leadingIconSize;
- const LeadingWidget({
- super.key,
- required this.leadingIconSize,
- this.leadingIcon,
- this.leadingIconColor,
- this.leadingIconWidget,
- });
-
- @override
- Widget build(BuildContext context) {
- return Padding(
- padding: const EdgeInsets.only(right: 10),
- child: SizedBox(
- height: leadingIconSize,
- width: leadingIconSize,
- child: leadingIcon == null
- ? (leadingIconWidget != null
- ? FittedBox(fit: BoxFit.contain, child: leadingIconWidget)
- : const SizedBox.shrink())
- : FittedBox(
- fit: BoxFit.contain,
- child: Icon(
- leadingIcon,
- color:
- leadingIconColor ??
- getEnteColorScheme(context).strokeBase,
- ),
- ),
- ),
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/components/menu_item_widget.dart b/mobile/apps/auth/lib/ui/components/menu_item_widget.dart
deleted file mode 100644
index a3965c5389..0000000000
--- a/mobile/apps/auth/lib/ui/components/menu_item_widget.dart
+++ /dev/null
@@ -1,288 +0,0 @@
-import 'package:ente_auth/models/execution_states.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/menu_item_child_widgets.dart';
-import 'package:ente_auth/utils/debouncer.dart';
-import 'package:ente_base/typedefs.dart';
-import 'package:expandable/expandable.dart';
-import 'package:flutter/material.dart';
-
-class MenuItemWidget extends StatefulWidget {
- final Widget captionedTextWidget;
- final bool isExpandable;
-
- /// leading icon can be passed without specifing size of icon,
- /// this component sets size to 20x20 irrespective of passed icon's size
- final IconData? leadingIcon;
- final Color? leadingIconColor;
-
- final Widget? leadingIconWidget;
-
- // leadIconSize deafult value is 20.
- final double leadingIconSize;
-
- /// trailing icon can be passed without size as default size set by
- /// flutter is what this component expects
- final IconData? trailingIcon;
- final Color? trailingIconColor;
- final Widget? trailingWidget;
- final bool trailingIconIsMuted;
-
- /// If provided, add this much extra spacing to the right of the trailing icon.
- final double trailingExtraMargin;
- final FutureVoidCallback? onTap;
- final VoidCallback? onDoubleTap;
- final Color? menuItemColor;
- final bool alignCaptionedTextToLeft;
-
- // singleBorderRadius is applied to the border when it's a standalone menu item.
- // Widget will apply singleBorderRadius if value of both isTopBorderRadiusRemoved
- // and isBottomBorderRadiusRemoved is false. Otherwise, multipleBorderRadius will
- // be applied
- final double singleBorderRadius;
- final double multipleBorderRadius;
- final Color? pressedColor;
- final ExpandableController? expandableController;
- final bool isBottomBorderRadiusRemoved;
- final bool isTopBorderRadiusRemoved;
-
- /// disable gesture detector if not used
- final bool isGestureDetectorDisabled;
-
- ///Success state will not be shown if this flag is set to true, only idle and
- ///loading state
- final bool showOnlyLoadingState;
-
- final bool surfaceExecutionStates;
-
- ///To show success state even when execution time < debouce time, set this
- ///flag to true. If the loading state needs to be shown and success state not,
- ///set the showOnlyLoadingState flag to true, setting this flag to false won't
- ///help.
- final bool alwaysShowSuccessState;
-
- const MenuItemWidget({
- required this.captionedTextWidget,
- this.isExpandable = false,
- this.leadingIcon,
- this.leadingIconColor,
- this.leadingIconSize = 20.0,
- this.leadingIconWidget,
- this.trailingIcon,
- this.trailingIconColor,
- this.trailingWidget,
- this.trailingIconIsMuted = false,
- this.trailingExtraMargin = 0.0,
- this.onTap,
- this.onDoubleTap,
- this.menuItemColor,
- this.alignCaptionedTextToLeft = false,
- this.singleBorderRadius = 4.0,
- this.multipleBorderRadius = 8.0,
- this.pressedColor,
- this.expandableController,
- this.isBottomBorderRadiusRemoved = false,
- this.isTopBorderRadiusRemoved = false,
- this.isGestureDetectorDisabled = false,
- this.showOnlyLoadingState = false,
- this.surfaceExecutionStates = true,
- this.alwaysShowSuccessState = false,
- super.key,
- });
-
- @override
- State<MenuItemWidget> createState() => _MenuItemWidgetState();
-}
-
-class _MenuItemWidgetState extends State<MenuItemWidget> {
- final _debouncer = Debouncer(const Duration(milliseconds: 300));
- ValueNotifier<ExecutionState> executionStateNotifier = ValueNotifier(
- ExecutionState.idle,
- );
-
- Color? menuItemColor;
- late double borderRadius;
-
- @override
- void initState() {
- menuItemColor = widget.menuItemColor;
- borderRadius =
- (widget.isBottomBorderRadiusRemoved || widget.isTopBorderRadiusRemoved)
- ? widget.multipleBorderRadius
- : widget.singleBorderRadius;
- if (widget.expandableController != null) {
- widget.expandableController!.addListener(() {
- setState(() {});
- });
- }
- super.initState();
- }
-
- @override
- void didChangeDependencies() {
- menuItemColor = widget.menuItemColor;
- super.didChangeDependencies();
- }
-
- @override
- void didUpdateWidget(covariant MenuItemWidget oldWidget) {
- menuItemColor = widget.menuItemColor;
- super.didUpdateWidget(oldWidget);
- }
-
- @override
- void dispose() {
- if (widget.expandableController != null) {
- widget.expandableController!.dispose();
- }
- executionStateNotifier.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- return widget.isExpandable || widget.isGestureDetectorDisabled
- ? menuItemWidget(context)
- : GestureDetector(
- onTap: _onTap,
- onDoubleTap: widget.onDoubleTap,
- onTapDown: _onTapDown,
- onTapUp: _onTapUp,
- onTapCancel: _onCancel,
- child: menuItemWidget(context),
- );
- }
-
- Widget menuItemWidget(BuildContext context) {
- final circularRadius = Radius.circular(borderRadius);
- final isExpanded = widget.expandableController?.value;
- final bottomBorderRadius =
- (isExpanded != null && isExpanded) || widget.isBottomBorderRadiusRemoved
- ? const Radius.circular(0)
- : circularRadius;
- final topBorderRadius = widget.isTopBorderRadiusRemoved
- ? const Radius.circular(0)
- : circularRadius;
- return AnimatedContainer(
- duration: const Duration(milliseconds: 20),
- width: double.infinity,
- padding: const EdgeInsets.only(left: 16, right: 12),
- decoration: BoxDecoration(
- borderRadius: BorderRadius.only(
- topLeft: topBorderRadius,
- topRight: topBorderRadius,
- bottomLeft: bottomBorderRadius,
- bottomRight: bottomBorderRadius,
- ),
- color: menuItemColor,
- ),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- widget.alignCaptionedTextToLeft && widget.leadingIcon == null
- ? const SizedBox.shrink()
- : LeadingWidget(
- leadingIconSize: widget.leadingIconSize,
- leadingIcon: widget.leadingIcon,
- leadingIconColor: widget.leadingIconColor,
- leadingIconWidget: widget.leadingIconWidget,
- ),
- widget.captionedTextWidget,
- if (widget.expandableController != null)
- ExpansionTrailingIcon(
- isExpanded: isExpanded!,
- trailingIcon: widget.trailingIcon,
- trailingIconColor: widget.trailingIconColor,
- )
- else
- TrailingWidget(
- executionStateNotifier: executionStateNotifier,
- trailingIcon: widget.trailingIcon,
- trailingIconColor: widget.trailingIconColor,
- trailingWidget: widget.trailingWidget,
- trailingIconIsMuted: widget.trailingIconIsMuted,
- trailingExtraMargin: widget.trailingExtraMargin,
- showExecutionStates: widget.surfaceExecutionStates,
- key: ValueKey(widget.trailingIcon.hashCode),
- ),
- ],
- ),
- );
- }
-
- Future<void> _onTap() async {
- if (executionStateNotifier.value == ExecutionState.inProgress ||
- executionStateNotifier.value == ExecutionState.successful) {
- return;
- }
- _debouncer.run(
- () => Future(() {
- executionStateNotifier.value = ExecutionState.inProgress;
- }),
- );
- await widget.onTap?.call().then((value) {
- widget.alwaysShowSuccessState
- ? executionStateNotifier.value = ExecutionState.successful
- : null;
- }, onError: (error, stackTrace) => _debouncer.cancelDebounce());
- _debouncer.cancelDebounce();
- if (widget.alwaysShowSuccessState) {
- Future.delayed(const Duration(seconds: 2), () {
- executionStateNotifier.value = ExecutionState.idle;
- });
- return;
- }
- if (executionStateNotifier.value == ExecutionState.inProgress) {
- if (widget.showOnlyLoadingState) {
- executionStateNotifier.value = ExecutionState.idle;
- } else {
- executionStateNotifier.value = ExecutionState.successful;
- Future.delayed(const Duration(seconds: 2), () {
- executionStateNotifier.value = ExecutionState.idle;
- });
- }
- }
- }
-
- void _onTapDown(TapDownDetails details) {
- if (executionStateNotifier.value == ExecutionState.inProgress ||
- executionStateNotifier.value == ExecutionState.successful) {
- return;
- }
- setState(() {
- if (widget.pressedColor == null) {
- hasPassedGestureCallbacks()
- ? menuItemColor = getEnteColorScheme(context).fillFaintPressed
- : menuItemColor = widget.menuItemColor;
- } else {
- menuItemColor = widget.pressedColor;
- }
- });
- }
-
- bool hasPassedGestureCallbacks() {
- return widget.onDoubleTap != null || widget.onTap != null;
- }
-
- void _onTapUp(TapUpDetails details) {
- if (executionStateNotifier.value == ExecutionState.inProgress ||
- executionStateNotifier.value == ExecutionState.successful) {
- return;
- }
- Future.delayed(
- const Duration(milliseconds: 100),
- () => setState(() {
- menuItemColor = widget.menuItemColor;
- }),
- );
- }
-
- void _onCancel() {
- if (executionStateNotifier.value == ExecutionState.inProgress ||
- executionStateNotifier.value == ExecutionState.successful) {
- return;
- }
- setState(() {
- menuItemColor = widget.menuItemColor;
- });
- }
-}
diff --git a/mobile/apps/auth/lib/ui/components/note_dialog.dart b/mobile/apps/auth/lib/ui/components/note_dialog.dart
index 14ce5ac2dc..8524fcd587 100644
--- a/mobile/apps/auth/lib/ui/components/note_dialog.dart
+++ b/mobile/apps/auth/lib/ui/components/note_dialog.dart
@@ -1,175 +1,79 @@
import 'package:clipboard/clipboard.dart';
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/effects.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
import 'package:ente_auth/utils/toast_util.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
import 'package:hugeicons/hugeicons.dart';
Future<void> showNotesDialog(BuildContext context, String note) async {
final trimmedNote = note.trim();
- if (trimmedNote.isEmpty) {
- return;
- }
+ if (trimmedNote.isEmpty) return;
- await showDialog(
+ await showBottomSheetComponent<void>(
context: context,
- barrierDismissible: true,
- builder: (dialogContext) {
- final theme = Theme.of(dialogContext);
- final colorScheme = getEnteColorScheme(dialogContext);
- final bool isDark = theme.brightness == Brightness.dark;
- final Color noteBackground = isDark
- ? const Color(0x29A75CFF)
- : const Color(0x0AA75CFF);
- return Dialog(
- backgroundColor: Colors.transparent,
- insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24),
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: () => Navigator.of(dialogContext).pop(),
- child: Center(
- child: GestureDetector(
- onTap: () {},
- child: Container(
- constraints: const BoxConstraints(
- maxWidth: 360,
- maxHeight: 700,
- ),
- decoration: BoxDecoration(
- color: colorScheme.backgroundElevated,
- borderRadius: BorderRadius.circular(20),
- boxShadow: shadowFloatLight,
- ),
- child: Material(
- color: Colors.transparent,
- borderRadius: BorderRadius.circular(20),
- child: Padding(
- padding: const EdgeInsets.fromLTRB(24, 20, 24, 20),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Text(
- dialogContext.l10n.notes,
- style: TextStyle(
- color: colorScheme.textBase,
- fontSize: 18,
- fontWeight: FontWeight.w600,
- height: 1.22,
- ),
- ),
- const Spacer(),
- IconButton(
- icon: const Icon(Icons.close),
- onPressed: () =>
- Navigator.of(dialogContext).pop(),
- ),
- ],
- ),
- const SizedBox(height: 8),
- Container(
- width: double.infinity,
- constraints: const BoxConstraints(maxHeight: 520),
- decoration: ShapeDecoration(
- color: noteBackground,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(8),
- ),
- ),
- child: Stack(
- children: [
- Scrollbar(
- thumbVisibility: true,
- child: SingleChildScrollView(
- padding: const EdgeInsets.fromLTRB(
- 20,
- 20,
- 20,
- 72,
- ),
- child: SelectableText(
- trimmedNote,
- contextMenuBuilder:
- (context, EditableTextState state) {
- return AdaptiveTextSelectionToolbar.buttonItems(
- anchors: state.contextMenuAnchors,
- buttonItems:
- <ContextMenuButtonItem>[
- ContextMenuButtonItem(
- onPressed: () {
- state.copySelection(
- SelectionChangedCause
- .toolbar,
- );
- },
- type: ContextMenuButtonType
- .copy,
- ),
- ContextMenuButtonItem(
- onPressed: () {
- state.selectAll(
- SelectionChangedCause
- .toolbar,
- );
- },
- type: ContextMenuButtonType
- .selectAll,
- ),
- ],
- );
- },
- style: TextStyle(
- color: colorScheme.textBase,
- fontSize: 14,
- fontWeight: FontWeight.w500,
- height: 1.64,
- ),
- ),
- ),
- ),
- Positioned(
- right: 8,
- bottom: 8,
- child: Material(
- color: Theme.of(dialogContext)
- .colorScheme
- .surfaceContainerHighest
- .withValues(alpha: 0.7),
- shape: const CircleBorder(),
- child: InkWell(
- customBorder: const CircleBorder(),
- onTap: () async {
- await FlutterClipboard.copy(trimmedNote);
- if (!dialogContext.mounted) return;
- Navigator.of(dialogContext).pop();
- showToast(
- dialogContext,
- dialogContext.l10n.copiedToClipboard,
- );
- },
- child: const Padding(
- padding: EdgeInsets.all(8.0),
- child: HugeIcon(
- icon: HugeIcons.strokeRoundedCopy01,
- size: 22,
- ),
- ),
- ),
- ),
- ),
- ],
+ useRootNavigator: true,
+ builder: (sheetContext) {
+ final colors = sheetContext.componentColors;
+ return Semantics(
+ identifier: 'auth_notes_sheet',
+ child: BottomSheetComponent(
+ title: sheetContext.l10n.notes,
+ closeTooltip: sheetContext.l10n.close,
+ content: Container(
+ width: double.infinity,
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.sizeOf(sheetContext).height * 0.55,
+ ),
+ padding: const EdgeInsets.all(Spacing.xl),
+ decoration: BoxDecoration(
+ color: colors.fillLight,
+ borderRadius: BorderRadius.circular(Radii.lg),
+ ),
+ child: Scrollbar(
+ thumbVisibility: true,
+ child: SingleChildScrollView(
+ child: SelectableText(
+ trimmedNote,
+ contextMenuBuilder: (context, state) {
+ return AdaptiveTextSelectionToolbar.buttonItems(
+ anchors: state.contextMenuAnchors,
+ buttonItems: <ContextMenuButtonItem>[
+ ContextMenuButtonItem(
+ onPressed: () => state.copySelection(
+ SelectionChangedCause.toolbar,
),
+ type: ContextMenuButtonType.copy,
+ ),
+ ContextMenuButtonItem(
+ onPressed: () =>
+ state.selectAll(SelectionChangedCause.toolbar),
+ type: ContextMenuButtonType.selectAll,
),
],
- ),
- ),
+ );
+ },
+ style: TextStyles.body.copyWith(color: colors.textBase),
),
),
),
),
+ actions: [
+ ButtonComponent(
+ label: MaterialLocalizations.of(sheetContext).copyButtonLabel,
+ variant: ButtonComponentVariant.secondary,
+ leading: const HugeIcon(
+ icon: HugeIcons.strokeRoundedCopy01,
+ size: IconSizes.small,
+ ),
+ onTap: () async {
+ await FlutterClipboard.copy(trimmedNote);
+ if (!sheetContext.mounted) return;
+ Navigator.of(sheetContext).pop();
+ if (!context.mounted) return;
+ showToast(context, context.l10n.copiedToClipboard);
+ },
+ ),
+ ],
),
);
},
diff --git a/mobile/apps/auth/lib/ui/components/notification_warning_widget.dart b/mobile/apps/auth/lib/ui/components/notification_warning_widget.dart
deleted file mode 100644
index 317ad8d640..0000000000
--- a/mobile/apps/auth/lib/ui/components/notification_warning_widget.dart
+++ /dev/null
@@ -1,111 +0,0 @@
-import "package:ente_auth/ente_theme_data.dart";
-import 'package:ente_auth/theme/colors.dart';
-import "package:ente_auth/theme/ente_theme.dart";
-import 'package:ente_auth/theme/text_style.dart';
-import 'package:ente_auth/ui/components/buttons/icon_button_widget.dart';
-import 'package:flutter/material.dart';
-
-// CreateNotificationType enum
-enum NotificationType { warning, banner, notice }
-
-class NotificationWidget extends StatelessWidget {
- final IconData startIcon;
- final IconData actionIcon;
- final String text;
- final String? subText;
- final GestureTapCallback onTap;
- final NotificationType type;
-
- const NotificationWidget({
- super.key,
- required this.startIcon,
- required this.actionIcon,
- required this.text,
- required this.onTap,
- this.subText,
- this.type = NotificationType.warning,
- });
-
- @override
- Widget build(BuildContext context) {
- EnteColorScheme colorScheme = getEnteColorScheme(context);
- EnteTextTheme textTheme = getEnteTextTheme(context);
- TextStyle mainTextStyle = darkTextTheme.bodyBold;
- TextStyle subTextStyle = darkTextTheme.miniMuted;
- LinearGradient? backgroundGradient;
- Color? backgroundColor;
- EnteColorScheme strokeColorScheme = darkScheme;
- List<BoxShadow>? boxShadow;
- switch (type) {
- case NotificationType.warning:
- backgroundColor = warning500;
- break;
- case NotificationType.banner:
- colorScheme = getEnteColorScheme(context);
- textTheme = getEnteTextTheme(context);
- backgroundColor = colorScheme.backgroundElevated2;
- mainTextStyle = textTheme.bodyBold;
- subTextStyle = textTheme.miniMuted;
- strokeColorScheme = colorScheme;
- boxShadow = [
- BoxShadow(color: Colors.black.withValues(alpha: 0.25), blurRadius: 1),
- ];
- break;
-
- case NotificationType.notice:
- backgroundColor = colorScheme.backgroundElevated2;
- mainTextStyle = textTheme.bodyBold;
- subTextStyle = textTheme.miniMuted;
- strokeColorScheme = colorScheme;
- boxShadow = Theme.of(context).colorScheme.enteTheme.shadowMenu;
- break;
- }
- return Center(
- child: GestureDetector(
- onTap: onTap,
- child: Container(
- decoration: BoxDecoration(
- borderRadius: const BorderRadius.all(Radius.circular(8)),
- boxShadow: boxShadow,
- color: backgroundColor,
- gradient: backgroundGradient,
- ),
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Icon(startIcon, size: 36, color: strokeColorScheme.strokeBase),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- text,
- style: mainTextStyle,
- textAlign: TextAlign.left,
- ),
- subText != null
- ? Text(subText!, style: subTextStyle)
- : const SizedBox.shrink(),
- ],
- ),
- ),
- const SizedBox(width: 12),
- IconButtonWidget(
- icon: actionIcon,
- iconButtonType: IconButtonType.rounded,
- iconColor: strokeColorScheme.strokeBase,
- defaultColor: strokeColorScheme.fillFaint,
- pressedColor: strokeColorScheme.fillMuted,
- onTap: onTap,
- ),
- ],
- ),
- ),
- ),
- ),
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/components/separators.dart b/mobile/apps/auth/lib/ui/components/separators.dart
deleted file mode 100644
index bc4b1346ad..0000000000
--- a/mobile/apps/auth/lib/ui/components/separators.dart
+++ /dev/null
@@ -1,13 +0,0 @@
-//This method returns a newly declared list with separators. It will not
-//modify the original list
-import 'package:flutter/widgets.dart';
-
-List<Widget> addSeparators(List<Widget> listOfWidgets, Widget separator) {
- final int initialLength = listOfWidgets.length;
- final listOfWidgetsWithSeparators = <Widget>[];
- listOfWidgetsWithSeparators.addAll(listOfWidgets);
- for (var i = 1; i < initialLength; i++) {
- listOfWidgetsWithSeparators.insert((2 * i) - 1, separator);
- }
- return listOfWidgetsWithSeparators;
-}
diff --git a/mobile/apps/auth/lib/ui/components/text_input_widget.dart b/mobile/apps/auth/lib/ui/components/text_input_widget.dart
deleted file mode 100644
index ce2a8a26f5..0000000000
--- a/mobile/apps/auth/lib/ui/components/text_input_widget.dart
+++ /dev/null
@@ -1,409 +0,0 @@
-import 'package:ente_auth/models/execution_states.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/common/loading_widget.dart';
-import 'package:ente_auth/ui/components/separators.dart';
-import 'package:ente_auth/utils/debouncer.dart';
-import 'package:ente_base/typedefs.dart';
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import 'package:logging/logging.dart';
-
-class TextInputWidget extends StatefulWidget {
- final String? label;
- final String? message;
- final String? hintText;
- final IconData? prefixIcon;
- final String? initialValue;
- final Alignment? alignMessage;
- final bool? autoFocus;
- final int? maxLength;
-
- ///TextInputWidget will listen to this notifier and executes onSubmit when
- ///notified.
- final ValueNotifier? submitNotifier;
- final bool alwaysShowSuccessState;
- final bool showOnlyLoadingState;
- final FutureVoidCallbackParamStr? onSubmit;
- final VoidCallbackParamStr? onChange;
- final bool popNavAfterSubmission;
- final bool shouldSurfaceExecutionStates;
- final TextCapitalization? textCapitalization;
- final bool isPasswordInput;
- final Iterable<String>? autofillHints;
- final bool cancellable;
- final bool shouldUnfocusOnCancelOrSubmit;
- const TextInputWidget({
- this.onSubmit,
- this.onChange,
- this.label,
- this.message,
- this.hintText,
- this.prefixIcon,
- this.initialValue,
- this.alignMessage,
- this.autoFocus,
- this.maxLength,
- this.submitNotifier,
- this.alwaysShowSuccessState = false,
- this.showOnlyLoadingState = false,
- this.popNavAfterSubmission = false,
- this.shouldSurfaceExecutionStates = true,
- this.textCapitalization = TextCapitalization.none,
- this.isPasswordInput = false,
- this.autofillHints,
- this.cancellable = false,
- this.shouldUnfocusOnCancelOrSubmit = false,
- super.key,
- });
-
- @override
- State<TextInputWidget> createState() => _TextInputWidgetState();
-}
-
-class _TextInputWidgetState extends State<TextInputWidget> {
- final _logger = Logger("TextInputWidget");
- ExecutionState executionState = ExecutionState.idle;
- final _textController = TextEditingController();
- final _debouncer = Debouncer(const Duration(milliseconds: 300));
- late final ValueNotifier<bool> _obscureTextNotifier;
-
- ///This is to pass if the TextInputWidget is in a dialog and an error is
- ///thrown in executing onSubmit by passing it as arg in Navigator.pop()
- Exception? _exception;
- bool _incorrectPassword = false;
- @override
- void initState() {
- widget.submitNotifier?.addListener(_onSubmit);
-
- if (widget.initialValue != null) {
- _textController.value = TextEditingValue(
- text: widget.initialValue!,
- selection: TextSelection.collapsed(offset: widget.initialValue!.length),
- );
- }
- if (widget.onChange != null) {
- _textController.addListener(() {
- widget.onChange!.call(_textController.text);
- });
- }
- _obscureTextNotifier = ValueNotifier(widget.isPasswordInput);
- _obscureTextNotifier.addListener(_safeRefresh);
- super.initState();
- }
-
- @override
- void dispose() {
- widget.submitNotifier?.removeListener(_onSubmit);
- _obscureTextNotifier.dispose();
- _textController.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- if (executionState == ExecutionState.successful) {
- Future.delayed(
- Duration(seconds: widget.popNavAfterSubmission ? 1 : 2),
- () {
- setState(() {
- executionState = ExecutionState.idle;
- });
- },
- );
- }
- final colorScheme = getEnteColorScheme(context);
- final textTheme = getEnteTextTheme(context);
- var textInputChildren = <Widget>[];
- if (widget.label != null) {
- textInputChildren.add(Text(widget.label!));
- }
- textInputChildren.add(
- ClipRRect(
- borderRadius: const BorderRadius.all(Radius.circular(8)),
- child: Material(
- child: TextFormField(
- textCapitalization: widget.textCapitalization!,
- autofocus: widget.autoFocus ?? false,
- controller: _textController,
- inputFormatters: widget.maxLength != null
- ? [LengthLimitingTextInputFormatter(50)]
- : null,
- autofillHints:
- widget.autofillHints ??
- (widget.isPasswordInput
- ? const [AutofillHints.password]
- : null),
- obscureText: _obscureTextNotifier.value,
- decoration: InputDecoration(
- hintText: widget.hintText,
- hintStyle: textTheme.body.copyWith(color: colorScheme.textMuted),
- filled: true,
- fillColor: colorScheme.fillFaint,
- contentPadding: const EdgeInsets.fromLTRB(12, 12, 0, 12),
- border: const UnderlineInputBorder(borderSide: BorderSide.none),
- focusedBorder: OutlineInputBorder(
- borderSide: BorderSide(
- color: _incorrectPassword
- ? const Color.fromRGBO(245, 42, 42, 1)
- : colorScheme.strokeFaint,
- ),
- borderRadius: BorderRadius.circular(8),
- ),
- suffixIcon: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 12),
- child: AnimatedSwitcher(
- duration: const Duration(milliseconds: 175),
- switchInCurve: Curves.easeInExpo,
- switchOutCurve: Curves.easeOutExpo,
- child: SuffixIconWidget(
- key: ValueKey(executionState),
- executionState: executionState,
- shouldSurfaceExecutionStates:
- widget.shouldSurfaceExecutionStates,
- obscureTextNotifier: _obscureTextNotifier,
- isPasswordInput: widget.isPasswordInput,
- textController: _textController,
- isCancellable: widget.cancellable,
- shouldUnfocusOnCancelOrSubmit:
- widget.shouldUnfocusOnCancelOrSubmit,
- ),
- ),
- ),
- prefixIconConstraints: const BoxConstraints(
- maxHeight: 44,
- maxWidth: 44,
- minHeight: 44,
- minWidth: 44,
- ),
- suffixIconConstraints: const BoxConstraints(
- maxHeight: 24,
- maxWidth: 48,
- minHeight: 24,
- minWidth: 48,
- ),
- prefixIcon: widget.prefixIcon != null
- ? Icon(widget.prefixIcon, color: colorScheme.strokeMuted)
- : null,
- ),
- onEditingComplete: () {
- _onSubmit();
- },
- ),
- ),
- ),
- );
- if (widget.message != null) {
- textInputChildren.add(
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 8),
- child: Align(
- alignment: widget.alignMessage ?? Alignment.centerLeft,
- child: Text(
- widget.message!,
- style: textTheme.small.copyWith(color: colorScheme.textMuted),
- ),
- ),
- ),
- );
- }
- textInputChildren = addSeparators(
- textInputChildren,
- const SizedBox(height: 4),
- );
- return Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: textInputChildren,
- );
- }
-
- void _safeRefresh() {
- if (mounted) {
- setState(() {});
- }
- }
-
- void _onSubmit() async {
- _debouncer.run(
- () => Future(() {
- setState(() {
- executionState = ExecutionState.inProgress;
- });
- }),
- );
- if (widget.shouldUnfocusOnCancelOrSubmit) {
- FocusScope.of(context).unfocus();
- }
- try {
- await widget.onSubmit!.call(_textController.text);
- } catch (e) {
- executionState = ExecutionState.error;
- _debouncer.cancelDebounce();
- _exception = e as Exception;
- if (e.toString().contains("Incorrect password")) {
- _logger.warning("Incorrect password");
- _surfaceWrongPasswordState();
- }
- if (!widget.popNavAfterSubmission) {
- rethrow;
- }
- }
- widget.alwaysShowSuccessState && _debouncer.isActive()
- ? executionState = ExecutionState.successful
- : null;
- _debouncer.cancelDebounce();
- if (executionState == ExecutionState.successful) {
- setState(() {});
- }
-
- // when the time taken by widget.onSubmit is approximately equal to the debounce
- // time, the callback is getting executed when/after the if condition
- // below is executing/executed which results in execution state stuck at
- // idle state. This Future is for delaying the execution of the if
- // condition so that the calback in the debouncer finishes execution before.
- await Future.delayed(const Duration(milliseconds: 5));
- if (executionState == ExecutionState.inProgress ||
- executionState == ExecutionState.error) {
- if (!mounted) return;
- if (executionState == ExecutionState.inProgress) {
- if (mounted) {
- if (widget.showOnlyLoadingState) {
- setState(() {
- executionState = ExecutionState.idle;
- });
- _popNavigatorStack(context);
- } else {
- setState(() {
- executionState = ExecutionState.successful;
- Future.delayed(
- Duration(
- seconds: widget.shouldSurfaceExecutionStates
- ? (widget.popNavAfterSubmission ? 1 : 2)
- : 0,
- ),
- () {
- if (!mounted) return;
- widget.popNavAfterSubmission
- ? _popNavigatorStack(context)
- : null;
- if (mounted) {
- setState(() {
- executionState = ExecutionState.idle;
- });
- }
- },
- );
- });
- }
- }
- }
- if (executionState == ExecutionState.error) {
- setState(() {
- executionState = ExecutionState.idle;
- widget.popNavAfterSubmission
- ? Future.delayed(const Duration(seconds: 0), () {
- if (!mounted) return;
- _popNavigatorStack(context, e: _exception);
- })
- : null;
- });
- }
- } else {
- if (widget.popNavAfterSubmission) {
- Future.delayed(
- Duration(seconds: widget.alwaysShowSuccessState ? 1 : 0),
- () {
- if (!mounted) return;
- _popNavigatorStack(context);
- },
- );
- }
- }
- }
-
- void _popNavigatorStack(BuildContext context, {Exception? e}) {
- Navigator.of(context).canPop() ? Navigator.of(context).pop(e) : null;
- }
-
- void _surfaceWrongPasswordState() {
- setState(() {
- _incorrectPassword = true;
- HapticFeedback.vibrate();
- Future.delayed(const Duration(seconds: 1), () {
- if (mounted) {
- setState(() {
- _incorrectPassword = false;
- });
- }
- });
- });
- }
-}
-
-//todo: Add clear and custom icon for suffic icon
-class SuffixIconWidget extends StatelessWidget {
- final ExecutionState executionState;
- final bool shouldSurfaceExecutionStates;
- final TextEditingController textController;
- final ValueNotifier? obscureTextNotifier;
- final bool isPasswordInput;
- final bool isCancellable;
- final bool shouldUnfocusOnCancelOrSubmit;
-
- const SuffixIconWidget({
- required this.executionState,
- required this.shouldSurfaceExecutionStates,
- required this.textController,
- this.obscureTextNotifier,
- this.isPasswordInput = false,
- this.isCancellable = false,
- this.shouldUnfocusOnCancelOrSubmit = false,
- super.key,
- });
-
- @override
- Widget build(BuildContext context) {
- final Widget trailingWidget;
- final colorScheme = getEnteColorScheme(context);
- if (executionState == ExecutionState.idle ||
- !shouldSurfaceExecutionStates) {
- if (isCancellable) {
- trailingWidget = GestureDetector(
- onTap: () {
- textController.clear();
- if (shouldUnfocusOnCancelOrSubmit) {
- FocusScope.of(context).unfocus();
- }
- },
- child: Icon(Icons.cancel_rounded, color: colorScheme.strokeMuted),
- );
- } else if (isPasswordInput) {
- assert(obscureTextNotifier != null);
- trailingWidget = GestureDetector(
- onTap: () {
- obscureTextNotifier!.value = !obscureTextNotifier!.value;
- },
- child: Icon(
- obscureTextNotifier!.value
- ? Icons.visibility_off_outlined
- : Icons.visibility,
- color: obscureTextNotifier!.value ? colorScheme.strokeMuted : null,
- ),
- );
- } else {
- trailingWidget = const SizedBox.shrink();
- }
- } else if (executionState == ExecutionState.inProgress) {
- trailingWidget = EnteLoadingWidget(color: colorScheme.strokeMuted);
- } else if (executionState == ExecutionState.successful) {
- trailingWidget = Icon(
- Icons.check_outlined,
- size: 22,
- color: colorScheme.primary500,
- );
- } else {
- trailingWidget = const SizedBox.shrink();
- }
- return trailingWidget;
- }
-}
diff --git a/mobile/apps/auth/lib/ui/components/title_bar_title_widget.dart b/mobile/apps/auth/lib/ui/components/title_bar_title_widget.dart
deleted file mode 100644
index 0aa2534aa2..0000000000
--- a/mobile/apps/auth/lib/ui/components/title_bar_title_widget.dart
+++ /dev/null
@@ -1,55 +0,0 @@
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:flutter/material.dart';
-
-class TitleBarTitleWidget extends StatelessWidget {
- final String? title;
- final bool isTitleH2;
- final IconData? icon;
- const TitleBarTitleWidget({
- super.key,
- this.title,
- this.isTitleH2 = false,
- this.icon,
- });
-
- @override
- Widget build(BuildContext context) {
- final textTheme = getEnteTextTheme(context);
- final colorTheme = getEnteColorScheme(context);
- if (title != null) {
- if (icon != null) {
- return Row(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: <Widget>[
- Text(
- title!,
- style: textTheme.h3Bold,
- overflow: TextOverflow.ellipsis,
- maxLines: 1,
- ),
- const SizedBox(width: 8),
- Icon(icon, size: 20, color: colorTheme.strokeMuted),
- ],
- );
- }
- if (isTitleH2) {
- return Text(
- title!,
- style: textTheme.h2Bold,
- overflow: TextOverflow.ellipsis,
- maxLines: 1,
- );
- } else {
- return Text(
- title!,
- style: textTheme.h3Bold,
- overflow: TextOverflow.ellipsis,
- maxLines: 1,
- );
- }
- }
-
- return const SizedBox.shrink();
- }
-}
diff --git a/mobile/apps/auth/lib/ui/components/title_bar_widget.dart b/mobile/apps/auth/lib/ui/components/title_bar_widget.dart
deleted file mode 100644
index ca1115658c..0000000000
--- a/mobile/apps/auth/lib/ui/components/title_bar_widget.dart
+++ /dev/null
@@ -1,150 +0,0 @@
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/buttons/icon_button_widget.dart';
-import 'package:flutter/material.dart';
-
-class TitleBarWidget extends StatelessWidget {
- final IconButtonWidget? leading;
- final String? title;
- final String? caption;
- final Widget? flexibleSpaceTitle;
- final String? flexibleSpaceCaption;
- final List<Widget>? actionIcons;
- final bool isTitleH2WithoutLeading;
- final bool isFlexibleSpaceDisabled;
- final bool isOnTopOfScreen;
- final Color? backgroundColor;
- const TitleBarWidget({
- super.key,
- this.leading,
- this.title,
- this.caption,
- this.flexibleSpaceTitle,
- this.flexibleSpaceCaption,
- this.actionIcons,
- this.isTitleH2WithoutLeading = false,
- this.isFlexibleSpaceDisabled = false,
- this.isOnTopOfScreen = true,
- this.backgroundColor,
- });
-
- @override
- Widget build(BuildContext context) {
- const toolbarHeight = 48.0;
- final textTheme = getEnteTextTheme(context);
- final colorTheme = getEnteColorScheme(context);
- return SliverAppBar(
- backgroundColor: backgroundColor,
- primary: isOnTopOfScreen ? true : false,
- toolbarHeight: toolbarHeight,
- leadingWidth: 48,
- automaticallyImplyLeading: false,
- pinned: true,
- expandedHeight: isFlexibleSpaceDisabled ? toolbarHeight : 102,
- centerTitle: false,
- titleSpacing: 4,
- title: Padding(
- padding: EdgeInsets.only(left: isTitleH2WithoutLeading ? 16 : 0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisAlignment: MainAxisAlignment.start,
- children: [
- title == null
- ? const SizedBox.shrink()
- : Text(
- title!,
- style: isTitleH2WithoutLeading
- ? textTheme.h2Bold
- : textTheme.largeBold,
- ),
- caption == null || isTitleH2WithoutLeading
- ? const SizedBox.shrink()
- : Text(
- caption!,
- style: textTheme.mini.copyWith(color: colorTheme.textMuted),
- ),
- ],
- ),
- ),
- actions: [
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 4),
- child: Row(children: _actionsWithPaddingInBetween()),
- ),
- ],
- leading: isTitleH2WithoutLeading
- ? null
- : leading ??
- IconButtonWidget(
- icon: Icons.arrow_back_outlined,
- iconButtonType: IconButtonType.primary,
- onTap: () {
- Navigator.pop(context);
- },
- ),
- flexibleSpace: isFlexibleSpaceDisabled
- ? null
- : FlexibleSpaceBar(
- background: SafeArea(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: <Widget>[
- const SizedBox(height: toolbarHeight),
- Padding(
- padding: const EdgeInsets.symmetric(
- vertical: 4,
- horizontal: 16,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- flexibleSpaceTitle == null
- ? const SizedBox.shrink()
- : flexibleSpaceTitle!,
- flexibleSpaceCaption == null
- ? const SizedBox.shrink()
- : Text(
- flexibleSpaceCaption!,
- style: textTheme.small.copyWith(
- color: colorTheme.textMuted,
- ),
- overflow: TextOverflow.ellipsis,
- maxLines: 1,
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- ),
- );
- }
-
- List<Widget> _actionsWithPaddingInBetween() {
- if (actionIcons == null) {
- return <Widget>[const SizedBox.shrink()];
- }
- final actions = <Widget>[];
- bool addWhiteSpace = false;
- final length = actionIcons!.length;
- int index = 0;
- if (length == 0) {
- return <Widget>[const SizedBox.shrink()];
- }
- if (length == 1) {
- return actionIcons!;
- }
- while (index < length) {
- if (!addWhiteSpace) {
- actions.add(actionIcons![index]);
- index++;
- addWhiteSpace = true;
- } else {
- actions.add(const SizedBox(width: 4));
- addWhiteSpace = false;
- }
- }
- return actions;
- }
-}
diff --git a/mobile/apps/auth/lib/ui/custom_icon_page.dart b/mobile/apps/auth/lib/ui/custom_icon_page.dart
index c2c176c768..e4dd4744db 100644
--- a/mobile/apps/auth/lib/ui/custom_icon_page.dart
+++ b/mobile/apps/auth/lib/ui/custom_icon_page.dart
@@ -3,45 +3,43 @@ import 'dart:io';
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/all_icon_data.dart';
import 'package:ente_auth/services/preference_service.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
import 'package:ente_auth/ui/utils/icon_utils.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class CustomIconPage extends StatefulWidget {
- final Map<String, AllIconData> allIcons;
- final String currentIcon;
-
const CustomIconPage({
super.key,
required this.allIcons,
required this.currentIcon,
});
+ final Map<String, AllIconData> allIcons;
+ final String currentIcon;
+
@override
State<CustomIconPage> createState() => _CustomIconPageState();
}
class _CustomIconPageState extends State<CustomIconPage> {
- Map<String, AllIconData> _filteredIcons = {};
- bool _showSearchBox = false;
final bool _autoFocusSearch = PreferenceService.instance
.shouldAutoFocusOnSearchBar();
- final TextEditingController _textController = TextEditingController();
- String _searchText = "";
-
- // Used to request focus on the search box when clicked the search icon
- late FocusNode searchBoxFocusNode;
final Set<LogicalKeyboardKey> _pressedKeys = <LogicalKeyboardKey>{};
final ScrollController _scrollController = ScrollController();
+ final TextEditingController _textController = TextEditingController();
+ late final FocusNode searchBoxFocusNode;
+ late Map<String, AllIconData> _filteredIcons;
+ bool _showSearchBox = false;
+ String _searchText = '';
@override
void initState() {
+ super.initState();
_filteredIcons = widget.allIcons;
_showSearchBox = _autoFocusSearch;
searchBoxFocusNode = FocusNode();
ServicesBinding.instance.keyboard.addHandler(_handleKeyEvent);
- super.initState();
}
@override
@@ -53,241 +51,242 @@ class _CustomIconPageState extends State<CustomIconPage> {
super.dispose();
}
- bool _handleKeyEvent(KeyEvent event) {
- if (!mounted) return false;
-
- // Always keep our pressed key state in sync.
- if (event is KeyDownEvent) {
- _pressedKeys.add(event.logicalKey);
- } else if (event is KeyUpEvent) {
- _pressedKeys.remove(event.logicalKey);
- }
-
- // This handler is registered globally via ServicesBinding; only act when
- // this page is the current route.
- final route = ModalRoute.of(context);
- if (route != null && !route.isCurrent) {
- return false;
- }
-
- // Don't hijack keystrokes while the user is typing into some other text
- // field (e.g. if a dialog is open).
- final primaryFocus = FocusManager.instance.primaryFocus;
- final bool isEditableTextFocused =
- primaryFocus?.context?.widget is EditableText;
- final bool isSearchFocused = searchBoxFocusNode.hasFocus;
- if (isEditableTextFocused && !isSearchFocused) {
- return false;
- }
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.componentColors;
+ return Semantics(
+ container: true,
+ identifier: 'auth_custom_icon_page',
+ child: Scaffold(
+ backgroundColor: colors.backgroundBase,
+ body: Scrollbar(
+ controller: _scrollController,
+ thumbVisibility: true,
+ interactive: true,
+ child: AppBarComponent(
+ title: context.l10n.chooseIcon,
+ controller: _scrollController,
+ actions: [
+ Padding(
+ padding: const EdgeInsets.only(right: Spacing.sm),
+ child: Semantics(
+ button: true,
+ identifier: 'auth_icon_search_toggle',
+ child: IconButtonComponent(
+ variant: IconButtonComponentVariant.unfilled,
+ tooltip: context.l10n.search,
+ icon: Icon(
+ _showSearchBox ? Icons.close : Icons.search,
+ size: IconSizes.medium,
+ ),
+ onTap: _toggleSearch,
+ ),
+ ),
+ ),
+ ],
+ slivers: [
+ if (_showSearchBox)
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Spacing.lg,
+ 0,
+ Spacing.lg,
+ Spacing.xl,
+ ),
+ child: Semantics(
+ textField: true,
+ identifier: 'auth_icon_search',
+ child: TextInputComponent(
+ controller: _textController,
+ focusNode: searchBoxFocusNode,
+ hintText: context.l10n.searchHint,
+ autofocus: _autoFocusSearch,
+ isClearable: true,
+ autocorrect: false,
+ enableSuggestions: false,
+ prefix: Icon(
+ Icons.search,
+ size: IconSizes.small,
+ color: colors.textLight,
+ ),
+ onChanged: (value) {
+ _searchText = value;
+ _applyFilteringAndRefresh();
+ },
+ ),
+ ),
+ ),
+ ),
+ if (_filteredIcons.isEmpty)
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(
+ child: Text(
+ context.l10n.noResult,
+ style: TextStyles.body.copyWith(color: colors.textLight),
+ ),
+ ),
+ )
+ else
+ SliverPadding(
+ padding: const EdgeInsets.fromLTRB(
+ Spacing.lg,
+ 0,
+ Spacing.lg,
+ Spacing.xl,
+ ),
+ sliver: SliverGrid.builder(
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: (MediaQuery.sizeOf(context).width ~/ 104)
+ .clamp(2, 8),
+ crossAxisSpacing: Spacing.sm,
+ mainAxisSpacing: Spacing.sm,
+ mainAxisExtent: 104,
+ ),
+ itemCount: _filteredIcons.length,
+ itemBuilder: _buildIconChoice,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
- if (event is KeyDownEvent) {
- final pressed = HardwareKeyboard.instance.logicalKeysPressed;
+ Widget _buildIconChoice(BuildContext context, int index) {
+ final colors = context.componentColors;
+ final title = _filteredIcons.keys.elementAt(index);
+ final iconData = _filteredIcons[title]!;
+ final selected = title.toLowerCase() == widget.currentIcon.toLowerCase();
+ final iconWidget = _buildIcon(context, title, iconData);
- final bool isMetaKeyPressed = Platform.isMacOS || Platform.isIOS
- ? (pressed.contains(LogicalKeyboardKey.metaLeft) ||
- pressed.contains(LogicalKeyboardKey.meta) ||
- pressed.contains(LogicalKeyboardKey.metaRight))
- : (pressed.contains(LogicalKeyboardKey.controlLeft) ||
- pressed.contains(LogicalKeyboardKey.control) ||
- pressed.contains(LogicalKeyboardKey.controlRight));
+ return Semantics(
+ button: true,
+ selected: selected,
+ label: title,
+ identifier: 'auth_icon_choice',
+ child: Material(
+ color: selected ? colors.primaryLight : colors.fillLight,
+ borderRadius: BorderRadius.circular(Radii.button),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () => Navigator.of(context).pop(iconData),
+ child: Container(
+ padding: const EdgeInsets.all(Spacing.sm),
+ decoration: BoxDecoration(
+ border: Border.all(
+ color: selected ? colors.primary : Colors.transparent,
+ ),
+ borderRadius: BorderRadius.circular(Radii.button),
+ ),
+ child: Column(
+ children: [
+ Expanded(child: Center(child: iconWidget)),
+ const SizedBox(height: Spacing.sm),
+ Text(
+ '${title[0].toUpperCase()}${title.substring(1)}',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ textAlign: TextAlign.center,
+ style: TextStyles.mini.copyWith(color: colors.textBase),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
- if (isMetaKeyPressed && event.logicalKey == LogicalKeyboardKey.keyF) {
- setState(() {
- _showSearchBox = true;
- searchBoxFocusNode.requestFocus();
- _textController.clear();
- _searchText = "";
- });
- return true;
- }
+ Widget _buildIcon(BuildContext context, String title, AllIconData iconData) {
+ final iconPath = iconData.type == IconType.simpleIcon
+ ? 'assets/simple-icons/icons/${simpleIconAssetStem(title, iconData.slug)}.svg'
+ : 'assets/custom-icons/icons/${iconData.slug ?? title}.svg';
+ return IconUtils.instance.getSVGIcon(
+ iconPath,
+ title,
+ iconData.color,
+ 40,
+ context,
+ );
+ }
- // Only use Escape for the page search UI.
- if (event.logicalKey == LogicalKeyboardKey.escape && _showSearchBox) {
- setState(() {
- _textController.clear();
- _searchText = "";
- _showSearchBox = false;
- _applyFilteringAndRefresh();
- });
- return true;
+ void _toggleSearch() {
+ setState(() {
+ _showSearchBox = !_showSearchBox;
+ if (_showSearchBox) {
+ searchBoxFocusNode.requestFocus();
+ } else {
+ _textController.clear();
+ _searchText = '';
+ _applyFiltering();
}
- }
-
- return false;
+ });
}
void _applyFilteringAndRefresh() {
+ setState(_applyFiltering);
+ }
+
+ void _applyFiltering() {
if (_searchText.isEmpty) {
- setState(() {
- _filteredIcons = widget.allIcons;
- });
+ _filteredIcons = widget.allIcons;
return;
}
+ final query = _searchText.toLowerCase();
+ _filteredIcons = {
+ for (final entry in widget.allIcons.entries)
+ if (entry.key.toLowerCase().contains(query)) entry.key: entry.value,
+ };
+ }
- final filteredIcons = <String, AllIconData>{};
- widget.allIcons.forEach((title, iconData) {
- if (title.toLowerCase().contains(_searchText.toLowerCase())) {
- filteredIcons[title] = iconData;
- }
- });
+ bool _handleKeyEvent(KeyEvent event) {
+ if (!mounted) return false;
+ if (event is KeyDownEvent) {
+ _pressedKeys.add(event.logicalKey);
+ } else if (event is KeyUpEvent) {
+ _pressedKeys.remove(event.logicalKey);
+ }
- setState(() {
- _filteredIcons = filteredIcons;
- });
- }
+ final route = ModalRoute.of(context);
+ if (route != null && !route.isCurrent) return false;
- @override
- Widget build(BuildContext context) {
- final l10n = context.l10n;
- return Scaffold(
- appBar: AppBar(
- title: !_showSearchBox
- ? Text(l10n.chooseIcon)
- : TextField(
- autocorrect: false,
- enableSuggestions: false,
- autofocus: _autoFocusSearch,
- controller: _textController,
- onChanged: (value) {
- _searchText = value;
- _applyFilteringAndRefresh();
- },
- decoration: InputDecoration(
- hintText: l10n.searchHint,
- border: InputBorder.none,
- focusedBorder: InputBorder.none,
- ),
- focusNode: searchBoxFocusNode,
- ),
- actions: [
- IconButton(
- icon: _showSearchBox
- ? const Icon(Icons.clear)
- : const Icon(Icons.search),
- tooltip: l10n.search,
- onPressed: () {
- setState(() {
- _showSearchBox = !_showSearchBox;
- if (!_showSearchBox) {
- _textController.clear();
- _searchText = "";
- } else {
- _searchText = _textController.text;
+ final primaryFocus = FocusManager.instance.primaryFocus;
+ final isEditableTextFocused = primaryFocus?.context?.widget is EditableText;
+ if (isEditableTextFocused && !searchBoxFocusNode.hasFocus) return false;
- // Request focus on the search box
- searchBoxFocusNode.requestFocus();
- }
- _applyFilteringAndRefresh();
- });
- },
- ),
- ],
- ),
- body: SafeArea(
- child: Padding(
- padding: const EdgeInsets.all(8.0),
- child: Column(
- children: [
- Expanded(
- child: Scrollbar(
- controller: _scrollController,
- thumbVisibility: true,
- interactive: true,
- child: GridView.builder(
- controller: _scrollController,
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- crossAxisCount: (MediaQuery.sizeOf(context).width ~/ 90)
- .clamp(1, double.infinity)
- .toInt(),
- crossAxisSpacing: 14,
- mainAxisSpacing: 14,
- childAspectRatio: 1,
- ),
- itemCount: _filteredIcons.length,
- itemBuilder: (context, index) {
- final title = _filteredIcons.keys.elementAt(index);
- final iconData = _filteredIcons[title]!;
- IconType iconType = iconData.type;
- String? color = iconData.color;
- String? slug = iconData.slug;
- Widget iconWidget;
- if (iconType == IconType.simpleIcon) {
- final simpleIconPath = simpleIconAssetStem(title, slug);
- iconWidget = IconUtils.instance.getSVGIcon(
- "assets/simple-icons/icons/$simpleIconPath.svg",
- title,
- color,
- 40,
- context,
- );
- } else {
- iconWidget = IconUtils.instance.getSVGIcon(
- "assets/custom-icons/icons/${slug ?? title}.svg",
- title,
- color,
- 40,
- context,
- );
- }
+ if (event is! KeyDownEvent) return false;
+ final pressed = HardwareKeyboard.instance.logicalKeysPressed;
+ final isModifierPressed = Platform.isMacOS || Platform.isIOS
+ ? pressed.any(
+ {
+ LogicalKeyboardKey.metaLeft,
+ LogicalKeyboardKey.meta,
+ LogicalKeyboardKey.metaRight,
+ }.contains,
+ )
+ : pressed.any(
+ {
+ LogicalKeyboardKey.controlLeft,
+ LogicalKeyboardKey.control,
+ LogicalKeyboardKey.controlRight,
+ }.contains,
+ );
- return GestureDetector(
- key: ValueKey(title),
- onTap: () {
- final newIcon = AllIconData(
- title: title,
- type: iconType,
- color: color,
- slug: slug,
- );
- Navigator.of(context).pop(newIcon);
- },
- child: Container(
- decoration: BoxDecoration(
- border: Border.all(
- width: 1.5,
- color:
- title.toLowerCase() ==
- widget.currentIcon.toLowerCase()
- ? getEnteColorScheme(
- context,
- ).tagChipSelectedColor
- : Colors.transparent,
- ),
- borderRadius: const BorderRadius.all(
- Radius.circular(12.0),
- ),
- ),
- child: Column(
- children: [
- const SizedBox(height: 8),
- Expanded(child: iconWidget),
- const SizedBox(height: 12),
- Padding(
- padding:
- title.toLowerCase() ==
- widget.currentIcon.toLowerCase()
- ? const EdgeInsets.only(left: 2, right: 2)
- : const EdgeInsets.all(0.0),
- child: Text(
- '${title[0].toUpperCase()}${title.substring(1)}',
- style: getEnteTextTheme(context).mini,
- overflow: TextOverflow.ellipsis,
- maxLines: 1,
- ),
- ),
- const SizedBox(height: 4),
- ],
- ),
- ),
- );
- },
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- );
+ if (isModifierPressed && event.logicalKey == LogicalKeyboardKey.keyF) {
+ if (!_showSearchBox) _toggleSearch();
+ _textController.clear();
+ _searchText = '';
+ _applyFilteringAndRefresh();
+ searchBoxFocusNode.requestFocus();
+ return true;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.escape && _showSearchBox) {
+ _toggleSearch();
+ return true;
+ }
+ return false;
}
}
diff --git a/mobile/apps/auth/lib/ui/home/add_tag_sheet.dart b/mobile/apps/auth/lib/ui/home/add_tag_sheet.dart
index 9a7483d131..453a2865ea 100644
--- a/mobile/apps/auth/lib/ui/home/add_tag_sheet.dart
+++ b/mobile/apps/auth/lib/ui/home/add_tag_sheet.dart
@@ -7,11 +7,10 @@ import 'package:ente_auth/onboarding/view/common/tag_chip.dart';
import 'package:ente_auth/services/authenticator_service.dart';
import 'package:ente_auth/store/code_display_store.dart';
import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
import 'package:ente_auth/ui/components/horizontal_scroll_area.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/utils/icon_utils.dart';
+import 'package:ente_auth/utils/dialog_util.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
class AddTagSheet extends StatefulWidget {
@@ -86,198 +85,140 @@ class _AddTagSheetState extends State<AddTagSheet> {
}
Future<void> _showCreateTagDialog() async {
- final textController = TextEditingController();
- final newTag = await showDialog<String>(
- context: context,
- builder: (context) {
- return StatefulBuilder(
- builder: (context, setState) {
- return AlertDialog(
- title: Text(context.l10n.createNewTag),
- content: TextField(
- controller: textController,
- autofocus: true,
- onChanged: (_) => setState(() {}),
- ),
- actions: [
- Row(
- children: [
- Expanded(
- child: ButtonWidget(
- buttonType: ButtonType.secondary,
- labelText: context.l10n.cancel,
- onTap: () async => Navigator.of(context).pop(),
- ),
- ),
- const SizedBox(width: 8),
- Expanded(
- child: ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: context.l10n.create,
- isDisabled: textController.text.trim().isEmpty,
- onTap: () async => Navigator.of(
- context,
- ).pop(textController.text.trim()),
- ),
- ),
- ],
- ),
- ],
- );
- },
- );
- },
+ String? newTag;
+ await showTextInputDialog(
+ context,
+ title: context.l10n.createNewTag,
+ submitButtonLabel: context.l10n.create,
+ useRootNavigator: true,
+ onSubmit: (value) async => newTag = value.trim(),
);
- if (newTag != null && newTag.isNotEmpty) {
+ if (newTag?.isNotEmpty == true) {
setState(() {
- if (!_allTags.contains(newTag)) {
- _allTags.add(newTag);
+ if (!_allTags.contains(newTag!)) {
+ _allTags.add(newTag!);
_allTags.sort();
}
- _selectedTagsInSheet.add(newTag);
+ _selectedTagsInSheet.add(newTag!);
});
}
}
@override
Widget build(BuildContext context) {
- final colorScheme = getEnteColorScheme(context);
- final textTheme = getEnteTextTheme(context);
- final bottomPadding = MediaQuery.of(context).padding.bottom;
-
- return Padding(
- padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + bottomPadding),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text(
- '${widget.selectedCodes.length} ${context.l10n.selected}',
- style: textTheme.large,
- ),
- IconButton(
- icon: const Icon(Icons.close),
- onPressed: () => Navigator.of(context).pop(),
- style: IconButton.styleFrom(
- backgroundColor: colorScheme.fillFaint.withValues(
- alpha: 0.025,
- ),
- ),
- ),
- ],
- ),
- const SizedBox(height: 16),
- SizedBox(
- height: 80,
- child: HorizontalScrollArea(
- builder: (context, scrollController) => ListView.separated(
- controller: scrollController,
- scrollDirection: Axis.horizontal,
- itemCount: widget.selectedCodes.length,
- separatorBuilder: (_, _) => const SizedBox(width: 16),
- itemBuilder: (context, index) {
- final code = widget.selectedCodes[index];
- final iconData = code.display.isCustomIcon
- ? code.display.iconID
- : code.issuer;
-
- return SizedBox(
- width: 60,
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Container(
- width: 50,
- height: 50,
- decoration: BoxDecoration(
- color: colorScheme.fillFaint.withValues(
- alpha: 0.02,
+ final colors = context.componentColors;
+
+ return Semantics(
+ identifier: 'auth_add_tag_sheet',
+ child: BottomSheetComponent(
+ title: '${widget.selectedCodes.length} ${context.l10n.selected}',
+ closeTooltip: context.l10n.close,
+ content: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ SizedBox(
+ height: 80,
+ child: HorizontalScrollArea(
+ builder: (context, scrollController) => ListView.separated(
+ controller: scrollController,
+ scrollDirection: Axis.horizontal,
+ itemCount: widget.selectedCodes.length,
+ separatorBuilder: (_, _) => const SizedBox(width: Spacing.lg),
+ itemBuilder: (context, index) {
+ final code = widget.selectedCodes[index];
+ final iconData = code.display.isCustomIcon
+ ? code.display.iconID
+ : code.issuer;
+
+ return SizedBox(
+ width: 60,
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Container(
+ width: 50,
+ height: 50,
+ decoration: BoxDecoration(
+ color: colors.fillLight,
+ borderRadius: BorderRadius.circular(Radii.md),
),
- borderRadius: BorderRadius.circular(8),
- ),
- child: Center(
- child: IconUtils.instance.getIcon(
- context,
- iconData.trim(),
- width: 28,
+ child: Center(
+ child: IconUtils.instance.getIcon(
+ context,
+ iconData.trim(),
+ width: 28,
+ ),
),
),
- ),
- const SizedBox(height: 8),
- Text(
- code.issuer,
- overflow: TextOverflow.ellipsis,
- style: textTheme.mini.copyWith(
- color: colorScheme.textMuted,
+ const SizedBox(height: Spacing.sm),
+ Text(
+ code.issuer,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyles.mini.copyWith(
+ color: colors.textLight,
+ ),
),
- ),
- ],
- ),
- );
- },
+ ],
+ ),
+ );
+ },
+ ),
),
),
- ),
- const SizedBox(height: 24),
- Text(context.l10n.tags, style: textTheme.body),
- const SizedBox(height: 12),
- Flexible(
- child: SingleChildScrollView(
- child: _isLoading
- ? const Center(child: CircularProgressIndicator())
- : Wrap(
- spacing: 8.0,
- runSpacing: 4.0,
- children: [
- ..._allTags.map((tag) {
- final isSelected = _selectedTagsInSheet.contains(tag);
- return TagChip(
- label: tag,
- action: TagChipAction.check,
- state: isSelected
- ? TagChipState.selected
- : TagChipState.unselected,
- onTap: () {
- setState(() {
- if (isSelected) {
- _selectedTagsInSheet.remove(tag);
- } else {
- _selectedTagsInSheet.add(tag);
- }
- });
- },
- );
- }),
- TagChip(
- label: context.l10n.addNew,
- iconData: Icons.add,
- state: TagChipState.unselected,
- onTap: _showCreateTagDialog,
- ),
- ],
- ),
+ const SizedBox(height: Spacing.xl),
+ Text(
+ context.l10n.tags,
+ style: TextStyles.bodyBold.copyWith(color: colors.textBase),
),
- ),
- const SizedBox(height: 24),
- SizedBox(
- width: double.infinity,
- child: ElevatedButton(
- style: ElevatedButton.styleFrom(
- backgroundColor: colorScheme.fillBase,
- foregroundColor: colorScheme.backgroundBase,
- padding: const EdgeInsets.symmetric(vertical: 16),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(12),
- ),
+ const SizedBox(height: Spacing.md),
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.sizeOf(context).height * 0.25,
+ ),
+ child: SingleChildScrollView(
+ child: _isLoading
+ ? const Center(child: CircularProgressIndicator())
+ : Wrap(
+ spacing: Spacing.sm,
+ runSpacing: Spacing.sm,
+ children: [
+ ..._allTags.map((tag) {
+ final isSelected = _selectedTagsInSheet.contains(
+ tag,
+ );
+ return TagChip(
+ label: tag,
+ action: TagChipAction.check,
+ state: isSelected
+ ? TagChipState.selected
+ : TagChipState.unselected,
+ onTap: () {
+ setState(() {
+ if (isSelected) {
+ _selectedTagsInSheet.remove(tag);
+ } else {
+ _selectedTagsInSheet.add(tag);
+ }
+ });
+ },
+ );
+ }),
+ TagChip(
+ label: context.l10n.addNew,
+ iconData: Icons.add,
+ state: TagChipState.unselected,
+ onTap: _showCreateTagDialog,
+ ),
+ ],
+ ),
),
- onPressed: _onDonePressed,
- child: Text(context.l10n.done),
),
- ),
+ ],
+ ),
+ actions: [
+ ButtonComponent(label: context.l10n.done, onTap: _onDonePressed),
],
),
);
diff --git a/mobile/apps/auth/lib/ui/home/coach_mark_widget.dart b/mobile/apps/auth/lib/ui/home/coach_mark_widget.dart
index f57621d536..22591c5282 100644
--- a/mobile/apps/auth/lib/ui/home/coach_mark_widget.dart
+++ b/mobile/apps/auth/lib/ui/home/coach_mark_widget.dart
@@ -3,6 +3,7 @@ import 'dart:ui';
import 'package:ente_auth/events/codes_updated_event.dart';
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/services/preference_service.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:ente_events/event_bus.dart';
import 'package:ente_pure_utils/ente_pure_utils.dart';
import 'package:flutter/material.dart';
@@ -13,57 +14,81 @@ class CoachMarkWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
+ final colors = context.componentColors;
return GestureDetector(
- onTap: () async {
- await PreferenceService.instance.setHasShownCoachMark(true);
- Bus.instance.fire(CodesUpdatedEvent());
- },
- child: Row(
- children: [
- Expanded(
- child: Container(
- width: double.infinity,
- color: Theme.of(
- context,
- ).colorScheme.surface.withValues(alpha: 0.1),
- child: BackdropFilter(
- filter: ImageFilter.blur(sigmaX: 8, sigmaY: 8),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Column(
- mainAxisAlignment: MainAxisAlignment.center,
+ behavior: HitTestBehavior.opaque,
+ onTap: _dismiss,
+ child: BackdropFilter(
+ filter: ImageFilter.blur(sigmaX: 8, sigmaY: 8),
+ child: ColoredBox(
+ color: colors.specialScrim,
+ child: SafeArea(
+ minimum: const EdgeInsets.all(Spacing.lg),
+ child: Align(
+ alignment: Alignment.bottomCenter,
+ child: Semantics(
+ container: true,
+ identifier: 'auth_code_coach_mark',
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () {},
+ child: Container(
+ width: double.infinity,
+ constraints: const BoxConstraints(maxWidth: 520),
+ padding: const EdgeInsets.all(Spacing.xl),
+ decoration: BoxDecoration(
+ color: colors.backgroundBase,
+ borderRadius: BorderRadius.circular(Radii.sheet),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
children: [
- const Icon(Icons.info_outline, size: 42),
- const SizedBox(height: 24),
+ Container(
+ width: 48,
+ height: 48,
+ decoration: BoxDecoration(
+ color: colors.primaryLight,
+ shape: BoxShape.circle,
+ ),
+ child: Icon(
+ Icons.touch_app_outlined,
+ size: IconSizes.medium,
+ color: colors.primary,
+ ),
+ ),
+ const SizedBox(height: Spacing.lg),
Text(
PlatformDetector.isDesktop()
? l10n.hintForDesktop
: l10n.hintForMobile,
- style: Theme.of(context).textTheme.titleLarge,
+ textAlign: TextAlign.center,
+ style: TextStyles.bodyBold.copyWith(
+ color: colors.textBase,
+ ),
),
- const SizedBox(height: 36),
- SizedBox(
- width: 160,
- child: OutlinedButton(
- onPressed: () async {
- await PreferenceService.instance
- .setHasShownCoachMark(true);
- Bus.instance.fire(CodesUpdatedEvent());
- },
- child: Text(l10n.ok),
+ const SizedBox(height: Spacing.xl),
+ Semantics(
+ button: true,
+ identifier: 'auth_code_coach_mark_dismiss',
+ child: ButtonComponent(
+ label: l10n.ok,
+ onTap: _dismiss,
),
),
],
),
- ],
+ ),
),
),
),
),
- ],
+ ),
),
);
}
+
+ Future<void> _dismiss() async {
+ await PreferenceService.instance.setHasShownCoachMark(true);
+ Bus.instance.fire(CodesUpdatedEvent());
+ }
}
diff --git a/mobile/apps/auth/lib/ui/home/home_empty_state.dart b/mobile/apps/auth/lib/ui/home/home_empty_state.dart
index b48a373b1c..d74ab60951 100644
--- a/mobile/apps/auth/lib/ui/home/home_empty_state.dart
+++ b/mobile/apps/auth/lib/ui/home/home_empty_state.dart
@@ -1,9 +1,8 @@
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/home/widgets/rounded_action_buttons.dart';
import 'package:ente_auth/ui/settings/data/import_page.dart';
import 'package:ente_auth/utils/navigation_util.dart' as auth_nav;
import 'package:ente_auth/utils/platform_util.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:ente_pure_utils/ente_pure_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
@@ -23,8 +22,8 @@ class HomeEmptyStateWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
- final colorScheme = getEnteColorScheme(context);
- final isDarkTheme = !colorScheme.isLightTheme;
+ final colors = context.componentColors;
+ final isDarkTheme = Theme.of(context).brightness == Brightness.dark;
final bgSvgPath = isDarkTheme
? 'assets/svg/empty-state-bg-dark.svg'
: 'assets/svg/empty-state-bg-light.svg';
@@ -33,128 +32,136 @@ class HomeEmptyStateWidget extends StatelessWidget {
? (bottomPadding > 0 ? bottomPadding : 24.0)
: 24.0;
- return CustomScrollView(
- physics: const BouncingScrollPhysics(),
- slivers: [
- SliverFillRemaining(
- hasScrollBody: false,
- child: Padding(
- padding: EdgeInsets.only(
- left: 24,
- right: 24,
- top: 24,
- bottom: extraBottomPadding,
- ),
- child: Column(
- children: [
- Expanded(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- SizedBox(
- height: 188,
- child: Stack(
- alignment: Alignment.center,
- clipBehavior: Clip.none,
- children: [
- Positioned(
- bottom: 6,
- child: SvgPicture.asset(
- bgSvgPath,
- width: 224,
- height: 142,
+ return Semantics(
+ container: true,
+ identifier: 'auth_empty_state',
+ child: CustomScrollView(
+ physics: const BouncingScrollPhysics(),
+ slivers: [
+ SliverFillRemaining(
+ hasScrollBody: false,
+ child: Padding(
+ padding: EdgeInsets.only(
+ left: Spacing.xl,
+ right: Spacing.xl,
+ top: Spacing.xl,
+ bottom: extraBottomPadding,
+ ),
+ child: Column(
+ children: [
+ Expanded(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ SizedBox(
+ height: 188,
+ child: Stack(
+ alignment: Alignment.center,
+ clipBehavior: Clip.none,
+ children: [
+ Positioned(
+ bottom: 6,
+ child: SvgPicture.asset(
+ bgSvgPath,
+ width: 224,
+ height: 142,
+ ),
),
- ),
- Image.asset('assets/onboarding-2.png', height: 188),
- ],
+ Image.asset(
+ 'assets/onboarding-2.png',
+ height: 188,
+ ),
+ ],
+ ),
),
- ),
- const SizedBox(height: 32),
- SizedBox(
- width: 221,
- child: Text(
- l10n.setupFirstAccount,
- textAlign: TextAlign.center,
- style: TextStyle(
- color: colorScheme.textBase,
- fontSize: 20,
- fontFamily: 'Inter',
- fontWeight: FontWeight.w700,
- height: 1.05,
- letterSpacing: -1,
+ const SizedBox(height: Spacing.xxl),
+ SizedBox(
+ width: 240,
+ child: Text(
+ l10n.setupFirstAccount,
+ textAlign: TextAlign.center,
+ style: TextStyles.h1.copyWith(
+ color: colors.textBase,
+ ),
),
),
- ),
- ],
+ ],
+ ),
),
- ),
- const SizedBox(height: 48),
- Center(
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 360),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- if (PlatformDetector.isMobile()) ...[
- RoundedButton(
- label: l10n.importScanQrCode,
- onPressed: onScanTap,
- width: double.infinity,
- ),
- const SizedBox(height: 12),
- RoundedButton(
- label: l10n.importEnterSetupKey,
- onPressed: onManuallySetupTap,
- width: double.infinity,
- type: RoundedButtonType.secondary,
- ),
- ] else ...[
- RoundedButton(
- label: l10n.importFromGallery,
- onPressed: onImportImageTap,
- width: double.infinity,
- ),
- const SizedBox(height: 12),
- RoundedButton(
- label: l10n.importEnterSetupKey,
- onPressed: onManuallySetupTap,
- width: double.infinity,
- type: RoundedButtonType.secondary,
- ),
- ],
- const SizedBox(height: 16),
- Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- TextLinkButton(
- label: l10n.importCodes,
- onTap: () {
- auth_nav.routeToPage(
- context,
- const ImportCodePage(),
- );
- },
+ const SizedBox(height: Spacing.xxl),
+ Center(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 360),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (PlatformDetector.isMobile()) ...[
+ Semantics(
+ button: true,
+ identifier: 'auth_empty_scan',
+ child: ButtonComponent(
+ label: l10n.importScanQrCode,
+ onTap: onScanTap,
+ ),
),
- TextLinkButton(
- label: l10n.faq,
- onTap: () {
- PlatformUtil.openUrlInBrowser(
- 'https://ente.com/help/auth/faq',
- );
- },
+ ] else ...[
+ Semantics(
+ button: true,
+ identifier: 'auth_empty_gallery',
+ child: ButtonComponent(
+ label: l10n.importFromGallery,
+ onTap: onImportImageTap,
+ ),
),
],
- ),
- ],
+ const SizedBox(height: Spacing.md),
+ Semantics(
+ button: true,
+ identifier: 'auth_empty_manual_setup',
+ child: ButtonComponent(
+ label: l10n.importEnterSetupKey,
+ variant: ButtonComponentVariant.secondary,
+ onTap: onManuallySetupTap,
+ ),
+ ),
+ const SizedBox(height: Spacing.sm),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ ButtonComponent(
+ label: l10n.importCodes,
+ size: ButtonComponentSize.small,
+ variant: ButtonComponentVariant.link,
+ onTap: () {
+ auth_nav.routeToPage(
+ context,
+ const ImportCodePage(),
+ );
+ },
+ ),
+ ButtonComponent(
+ label: l10n.faq,
+ size: ButtonComponentSize.small,
+ variant: ButtonComponentVariant.link,
+ onTap: () {
+ PlatformUtil.openUrlInBrowser(
+ 'https://ente.com/help/auth/faq',
+ );
+ },
+ ),
+ ],
+ ),
+ ],
+ ),
),
),
- ),
- ],
+ ],
+ ),
),
),
- ),
- ],
+ ],
+ ),
);
}
}
diff --git a/mobile/apps/auth/lib/ui/home/widgets/rounded_action_buttons.dart b/mobile/apps/auth/lib/ui/home/widgets/rounded_action_buttons.dart
index 896128eb51..3c90de3e8f 100644
--- a/mobile/apps/auth/lib/ui/home/widgets/rounded_action_buttons.dart
+++ b/mobile/apps/auth/lib/ui/home/widgets/rounded_action_buttons.dart
@@ -62,31 +62,3 @@ class RoundedButton extends StatelessWidget {
);
}
}
-
-class TextLinkButton extends StatelessWidget {
- final String label;
- final VoidCallback? onTap;
-
- const TextLinkButton({super.key, required this.label, required this.onTap});
-
- @override
- Widget build(BuildContext context) {
- final textTheme = getEnteTextTheme(context);
- final colorScheme = getEnteColorScheme(context);
-
- return GestureDetector(
- onTap: onTap,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 18),
- child: Text(
- label,
- style: textTheme.small.copyWith(
- color: colorScheme.textBase,
- fontWeight: FontWeight.w600,
- decoration: TextDecoration.underline,
- ),
- ),
- ),
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/home_page.dart b/mobile/apps/auth/lib/ui/home_page.dart
index 46b34d0201..d3c5ee384c 100644
--- a/mobile/apps/auth/lib/ui/home_page.dart
+++ b/mobile/apps/auth/lib/ui/home_page.dart
@@ -26,11 +26,13 @@ import 'package:ente_auth/ui/code_error_widget.dart';
import 'package:ente_auth/ui/code_widget.dart';
import 'package:ente_auth/ui/common/loading_widget.dart';
import 'package:ente_auth/ui/components/auth_qr_dialog.dart';
+import 'package:ente_auth/ui/components/auth_selection_action_button.dart';
import 'package:ente_auth/ui/components/buttons/button_widget.dart';
import 'package:ente_auth/ui/components/dialog_widget.dart';
import 'package:ente_auth/ui/components/horizontal_scroll_area.dart';
import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/components/note_dialog.dart';
+import 'package:ente_auth/ui/custom_icon_page.dart';
import 'package:ente_auth/ui/home/add_tag_sheet.dart';
import 'package:ente_auth/ui/home/coach_mark_widget.dart';
import 'package:ente_auth/ui/home/home_empty_state.dart';
@@ -45,11 +47,13 @@ import 'package:ente_auth/ui/settings_page.dart';
import 'package:ente_auth/ui/share/code_share.dart';
import 'package:ente_auth/ui/sort_option_menu.dart';
import 'package:ente_auth/ui/utils/icon_utils.dart';
+import 'package:ente_auth/utils/debug_code_deep_link.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_auth/utils/gallery_import_util.dart';
import 'package:ente_auth/utils/platform_util.dart';
import 'package:ente_auth/utils/toast_util.dart';
import 'package:ente_auth/utils/totp_util.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:ente_events/event_bus.dart';
import 'package:ente_lock_screen/local_authentication_service.dart';
import 'package:ente_lock_screen/lock_screen_settings.dart';
@@ -158,9 +162,8 @@ class _HomePageState extends State<HomePage> {
if (selectedCodes.isEmpty) return;
- showModalBottomSheet(
+ showBottomSheetComponent<void>(
context: context,
- isScrollControlled: true,
builder: (_) {
return AddTagSheet(selectedCodes: selectedCodes);
},
@@ -255,32 +258,34 @@ class _HomePageState extends State<HomePage> {
}
Widget _buildTrashSelectActions() {
+ final colors = context.componentColors;
return Container(
decoration: BoxDecoration(
- color: Theme.of(context).brightness == Brightness.light
- ? const Color(0xFFF7F7F7)
- : const Color(0xFF1E1E1E),
- borderRadius: BorderRadius.circular(12),
+ color: colors.fillLight,
+ borderRadius: BorderRadius.circular(Radii.sheet),
),
child: Row(
children: [
- _buildClearActionButton(
+ _buildActionButton(
context.l10n.restore,
_onRestoreSelectedPressed,
+ semanticsIdentifier: 'auth_selection_restore',
iconWidget: HugeIcon(
icon: HugeIcons.strokeRoundedRestoreBin,
size: 21,
color: getEnteColorScheme(context).textBase,
),
),
- _buildClearActionButton(
+ _buildActionButton(
context.l10n.delete,
_onDeleteForeverPressed,
+ semanticsIdentifier: 'auth_selection_delete_forever',
iconWidget: HugeIcon(
icon: HugeIcons.strokeRoundedDelete04,
size: 21,
color: getEnteColorScheme(context).textBase,
),
+ isDestructive: true,
),
],
),
@@ -514,6 +519,10 @@ class _HomePageState extends State<HomePage> {
if (!isAuthSuccessful) return;
_codeDisplayStore.clearSelection();
+ await _showQrSheet(code);
+ }
+
+ Future<void> _showQrSheet(Code code) async {
final qrData = code.rawData
.replaceAll('algorithm=Algorithm.', 'algorithm=')
.replaceAll('algorithm=sha1', 'algorithm=SHA1')
@@ -521,9 +530,10 @@ class _HomePageState extends State<HomePage> {
.replaceAll('algorithm=sha512', 'algorithm=SHA512');
if (!mounted) return;
- await showDialog(
+ await showBottomSheetComponent<void>(
context: context,
- builder: (BuildContext dialogContext) {
+ useRootNavigator: true,
+ builder: (_) {
return AuthQrDialog(
data: qrData,
title: code.issuer,
@@ -537,44 +547,27 @@ class _HomePageState extends State<HomePage> {
);
}
- Widget _buildClearActionButton(
+ Widget _buildActionButton(
String label,
VoidCallback onTap, {
IconData? icon,
Widget? iconWidget,
+ bool isDestructive = false,
+ String? semanticsIdentifier,
}) {
- final colorScheme = getEnteColorScheme(context);
- final textTheme = getEnteTextTheme(context);
-
return Expanded(
- child: InkWell(
+ child: AuthSelectionActionButton(
+ label: label,
onTap: onTap,
- borderRadius: BorderRadius.circular(12),
- highlightColor: colorScheme.textBase.withValues(alpha: 0.1),
- splashColor: colorScheme.textBase.withValues(alpha: 0.1),
- child: Padding(
- padding: const EdgeInsets.symmetric(vertical: 12.0),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- iconWidget ?? Icon(icon!, color: colorScheme.textBase, size: 21),
- const SizedBox(height: 8),
- Text(
- label,
- style: textTheme.small.copyWith(
- color: colorScheme.textBase,
- fontSize: 11,
- ),
- ),
- ],
- ),
- ),
+ icon: iconWidget ?? Icon(icon, size: IconSizes.medium),
+ isDestructive: isDestructive,
+ semanticsIdentifier: semanticsIdentifier,
),
);
}
Widget _buildSingleSelectActions(Code code) {
- final colorScheme = getEnteColorScheme(context);
+ final colors = context.componentColors;
return Column(
key: const ValueKey('single_select_actions'),
mainAxisSize: MainAxisSize.min,
@@ -617,10 +610,8 @@ class _HomePageState extends State<HomePage> {
const SizedBox(height: 16),
Container(
decoration: BoxDecoration(
- color: Theme.of(context).brightness == Brightness.dark
- ? colorScheme.backgroundElevated2
- : const Color(0xFFF7F7F7),
- borderRadius: BorderRadius.circular(12),
+ color: colors.fillLight,
+ borderRadius: BorderRadius.circular(Radii.sheet),
),
child: Row(
children: [
@@ -642,7 +633,7 @@ class _HomePageState extends State<HomePage> {
(code) => code.isPinned,
);
- return _buildClearActionButton(
+ return _buildActionButton(
allArePinned
? context.l10n.unpinText
: context.l10n.pinText,
@@ -657,16 +648,17 @@ class _HomePageState extends State<HomePage> {
);
},
),
- _buildClearActionButton(
+ _buildActionButton(
context.l10n.addTag,
_onAddTagPressed,
+ semanticsIdentifier: 'auth_selection_add_tag',
iconWidget: HugeIcon(
icon: HugeIcons.strokeRoundedTags,
size: 21,
color: getEnteColorScheme(context).textBase,
),
),
- _buildClearActionButton(
+ _buildActionButton(
context.l10n.trash,
_onTrashSelectedPressed,
iconWidget: HugeIcon(
@@ -674,6 +666,7 @@ class _HomePageState extends State<HomePage> {
size: 21,
color: getEnteColorScheme(context).textBase,
),
+ isDestructive: true,
),
],
),
@@ -683,14 +676,12 @@ class _HomePageState extends State<HomePage> {
}
Widget _buildMultiSelectActions(Set<String> selectedIds) {
- final colorScheme = getEnteColorScheme(context);
+ final colors = context.componentColors;
return Container(
key: const ValueKey('multi_select_actions'),
decoration: BoxDecoration(
- color: Theme.of(context).brightness == Brightness.dark
- ? colorScheme.backgroundElevated2
- : const Color(0xFFF7F7F7),
- borderRadius: BorderRadius.circular(12),
+ color: colors.fillLight,
+ borderRadius: BorderRadius.circular(Radii.sheet),
),
child: ValueListenableBuilder<Set<String>>(
valueListenable: _codeDisplayStore.selectedCodeIds,
@@ -714,7 +705,7 @@ class _HomePageState extends State<HomePage> {
// Mixed state: when selection contains both pinned and unpinned codes
return Row(
children: [
- _buildClearActionButton(
+ _buildActionButton(
context.l10n.pinText,
_onPinSelectedPressed,
iconWidget: HugeIcon(
@@ -723,7 +714,7 @@ class _HomePageState extends State<HomePage> {
color: getEnteColorScheme(context).textBase,
),
),
- _buildClearActionButton(
+ _buildActionButton(
context.l10n.unpinText,
_onUnpinSelectedPressed,
iconWidget: HugeIcon(
@@ -732,16 +723,17 @@ class _HomePageState extends State<HomePage> {
color: getEnteColorScheme(context).textBase,
),
),
- _buildClearActionButton(
+ _buildActionButton(
context.l10n.addTag,
_onAddTagPressed,
+ semanticsIdentifier: 'auth_selection_add_tag',
iconWidget: HugeIcon(
icon: HugeIcons.strokeRoundedTags,
size: 21,
color: getEnteColorScheme(context).textBase,
),
),
- _buildClearActionButton(
+ _buildActionButton(
context.l10n.trash,
_onTrashSelectedPressed,
iconWidget: HugeIcon(
@@ -749,6 +741,7 @@ class _HomePageState extends State<HomePage> {
size: 21,
color: getEnteColorScheme(context).textBase,
),
+ isDestructive: true,
),
],
);
@@ -756,7 +749,7 @@ class _HomePageState extends State<HomePage> {
// When selection contains either only pinned OR only unpinned codes
return Row(
children: [
- _buildClearActionButton(
+ _buildActionButton(
allArePinned ? context.l10n.unpinText : context.l10n.pinText,
_onPinSelectedPressed,
iconWidget: HugeIcon(
@@ -767,16 +760,17 @@ class _HomePageState extends State<HomePage> {
color: getEnteColorScheme(context).textBase,
),
),
- _buildClearActionButton(
+ _buildActionButton(
context.l10n.addTag,
_onAddTagPressed,
+ semanticsIdentifier: 'auth_selection_add_tag',
iconWidget: HugeIcon(
icon: HugeIcons.strokeRoundedTags,
size: 21,
color: getEnteColorScheme(context).textBase,
),
),
- _buildClearActionButton(
+ _buildActionButton(
context.l10n.trash,
_onTrashSelectedPressed,
iconWidget: HugeIcon(
@@ -784,6 +778,7 @@ class _HomePageState extends State<HomePage> {
size: 21,
color: getEnteColorScheme(context).textBase,
),
+ isDestructive: true,
),
],
);
@@ -793,53 +788,6 @@ class _HomePageState extends State<HomePage> {
);
}
- Widget _buildActionButton(
- String label,
- VoidCallback onTap, {
- IconData? icon,
- Widget? iconWidget,
- }) {
- final colorScheme = getEnteColorScheme(context);
- final textTheme = getEnteTextTheme(context);
-
- return Expanded(
- child: Container(
- decoration: BoxDecoration(
- color: Theme.of(context).brightness == Brightness.dark
- ? colorScheme.backgroundElevated2
- : const Color(0xFFF7F7F7),
- borderRadius: BorderRadius.circular(12),
- ),
- child: InkWell(
- onTap: onTap,
- borderRadius: BorderRadius.circular(12),
- highlightColor: colorScheme.textBase.withValues(alpha: 0.7),
- splashColor: colorScheme.textBase.withValues(alpha: 0.7),
- child: Padding(
- padding: const EdgeInsets.symmetric(vertical: 12.0),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- mainAxisSize: MainAxisSize.min,
- children: [
- iconWidget ??
- Icon(icon!, color: colorScheme.textBase, size: 21),
- const SizedBox(height: 8),
- Text(
- label,
- style: textTheme.small.copyWith(
- color: colorScheme.textBase,
- fontSize: 11,
- ),
- textAlign: TextAlign.center,
- ),
- ],
- ),
- ),
- ),
- ),
- );
- }
-
Widget _buildActionButtons() {
if (_isTrashOpen) {
return _buildTrashSelectActions();
@@ -861,29 +809,10 @@ class _HomePageState extends State<HomePage> {
} else {
actionWidget = _buildMultiSelectActions(selectedIds);
}
- final double containerHeight;
- if (selectedIds.isEmpty) {
- containerHeight = 0.0;
- } else if (selectedIds.length == 1) {
- containerHeight = 160.0;
- } else {
- containerHeight = 80.0;
- }
-
- return AnimatedContainer(
+ return AnimatedSize(
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOut,
- height: containerHeight,
- child: SingleChildScrollView(
- physics: const NeverScrollableScrollPhysics(),
- child: ConstrainedBox(
- constraints: BoxConstraints(
- minHeight: containerHeight,
- maxHeight: containerHeight,
- ),
- child: actionWidget,
- ),
- ),
+ child: actionWidget,
);
},
);
@@ -891,195 +820,146 @@ class _HomePageState extends State<HomePage> {
Widget _buildSelectionActionBar() {
final bottomPadding = MediaQuery.of(context).padding.bottom;
- final colorScheme = getEnteColorScheme(context);
- final isDarkMode = Theme.of(context).brightness == Brightness.dark;
+ final colors = context.componentColors;
- return ConstrainedBox(
- constraints: BoxConstraints(
- maxHeight: MediaQuery.of(context).size.height * 0.4,
- ),
- child: Card(
- margin: EdgeInsets.zero,
- shape: RoundedRectangleBorder(
- borderRadius: const BorderRadius.only(
- topLeft: Radius.circular(16),
- topRight: Radius.circular(16),
- ),
- side: BorderSide(
- color: colorScheme.strokeMuted.withValues(alpha: 0.1),
- width: 1,
- ),
+ return Semantics(
+ identifier: 'auth_selection_action_bar',
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.of(context).size.height * 0.4,
),
- shadowColor: isDarkMode
- ? Colors.black.withValues(alpha: 0.7)
- : Colors.grey.withValues(alpha: 0.5),
- elevation: 4,
- color: isDarkMode
- ? colorScheme.fillFaint
- : colorScheme.backgroundElevated2,
- child: Padding(
- padding: EdgeInsets.fromLTRB(16, 16, 16, 28 + bottomPadding),
- child: SingleChildScrollView(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Row(
- children: [
- //Select all pill
- Material(
- shape: StadiumBorder(
- side: BorderSide(
- color: colorScheme.strokeMuted,
- width: 0.5,
+ child: Card(
+ margin: EdgeInsets.zero,
+ shape: RoundedRectangleBorder(
+ borderRadius: const BorderRadius.only(
+ topLeft: Radius.circular(Radii.bottomSheet),
+ topRight: Radius.circular(Radii.bottomSheet),
+ ),
+ side: BorderSide(color: colors.strokeFaint),
+ ),
+ shadowColor: colors.specialScrim.withValues(alpha: 0.35),
+ elevation: 4,
+ color: colors.backgroundBase,
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(
+ Spacing.lg,
+ Spacing.lg,
+ Spacing.lg,
+ Spacing.xl + bottomPadding,
+ ),
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Row(
+ children: [
+ FilterChipComponent(
+ label: context.l10n.selectAll,
+ trailing: const HugeIcon(
+ icon: HugeIcons.strokeRoundedTickDouble02,
+ size: IconSizes.small,
),
- ),
- color: colorScheme.backgroundElevated2,
- clipBehavior: Clip.antiAlias,
- child: InkWell(
- onTap: () {
+ onChanged: (_) {
final allVisibleCodeIds = _filteredCodes
- .map((c) => c.selectionKey)
+ .map((code) => code.selectionKey)
.toSet();
_codeDisplayStore.selectedCodeIds.value =
allVisibleCodeIds;
},
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 12.0,
- vertical: 8.0,
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- context.l10n.selectAll,
- style: const TextStyle(fontSize: 11),
- ),
- const SizedBox(width: 6),
- const HugeIcon(
- icon: HugeIcons.strokeRoundedTickDouble02,
- color: Colors.grey,
- size: 15,
- ),
- ],
- ),
- ),
),
- ),
-
- // Center code logo icon
- Expanded(
- child: ValueListenableBuilder<Set<String>>(
- valueListenable: _codeDisplayStore.selectedCodeIds,
- builder: (context, selectedIds, child) {
- if (selectedIds.isEmpty) {
- return const SizedBox.shrink();
- }
- final selectedCodes =
- _allCodes
- ?.where(
- (c) => selectedIds.contains(c.selectionKey),
- )
- .toList() ??
- [];
- final codesToShow = selectedCodes.take(3).toList();
- return Row(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- ...codesToShow.map((code) {
- final iconData = code.display.isCustomIcon
- ? code.display.iconID
- : code.issuer;
- return Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 4.0,
- ),
- child: IconUtils.instance.getIcon(
- context,
- iconData.trim(),
- width: 17,
- ),
- );
- }),
- if (selectedIds.length > 3)
- Padding(
- padding: const EdgeInsets.only(left: 4.0),
- child: Text(
- '+${selectedIds.length - 3}',
- style: const TextStyle(),
+ Expanded(
+ child: ValueListenableBuilder<Set<String>>(
+ valueListenable: _codeDisplayStore.selectedCodeIds,
+ builder: (context, selectedIds, child) {
+ if (selectedIds.isEmpty) {
+ return const SizedBox.shrink();
+ }
+ final selectedCodes =
+ _allCodes
+ ?.where(
+ (code) => selectedIds.contains(
+ code.selectionKey,
+ ),
+ )
+ .toList() ??
+ [];
+ final codesToShow = selectedCodes.take(3).toList();
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ ...codesToShow.map((code) {
+ final iconData = code.display.isCustomIcon
+ ? code.display.iconID
+ : code.issuer;
+ return Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: Spacing.xs,
+ ),
+ child: IconUtils.instance.getIcon(
+ context,
+ iconData.trim(),
+ width: IconSizes.small,
+ ),
+ );
+ }),
+ if (selectedIds.length > 3)
+ Padding(
+ padding: const EdgeInsets.only(
+ left: Spacing.xs,
+ ),
+ child: Text(
+ '+${selectedIds.length - 3}',
+ style: TextStyles.mini.copyWith(
+ color: colors.textLight,
+ ),
+ ),
),
- ),
- ],
- );
- },
+ ],
+ );
+ },
+ ),
),
- ),
-
- // N selected pill
- ValueListenableBuilder<Set<String>>(
- valueListenable: _codeDisplayStore.selectedCodeIds,
- builder: (context, selectedIds, child) {
- return Material(
- shape: StadiumBorder(
- side: BorderSide(
- color: colorScheme.strokeMuted,
- width: 0.5,
- ),
- ),
- color: colorScheme.backgroundElevated2,
- clipBehavior: Clip.antiAlias,
- child: InkWell(
- onTap: () {
- _codeDisplayStore.clearSelection();
- },
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 12.0,
- vertical: 8.0,
+ Semantics(
+ identifier: 'auth_selection_count',
+ child: ValueListenableBuilder<Set<String>>(
+ valueListenable: _codeDisplayStore.selectedCodeIds,
+ builder: (context, selectedIds, child) {
+ return FilterChipComponent(
+ label: context.l10n.nSelected(selectedIds.length),
+ trailing: const Icon(
+ Icons.close,
+ size: IconSizes.small,
),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- context.l10n.nSelected(selectedIds.length),
- style: const TextStyle(fontSize: 11),
- ),
- const SizedBox(width: 6),
- const Icon(
- Icons.close,
- size: 15,
- color: Colors.grey,
- ),
- ],
- ),
- ),
- ),
- );
- },
- ),
- ],
- ),
- ValueListenableBuilder<Set<String>>(
- valueListenable: _codeDisplayStore.selectedCodeIds,
- builder: (context, selectedIds, _) {
- final Code? code = _getSingleSelectedCodeWithNote(
- selectedIds,
- );
- if (code == null) {
- return const SizedBox.shrink();
- }
- return Padding(
- padding: const EdgeInsets.only(top: 12),
- child: _buildMultiSelectNotePreview(
- note: code.note.trim(),
- isDesktop: false,
+ onChanged: (_) =>
+ _codeDisplayStore.clearSelection(),
+ );
+ },
+ ),
),
- );
- },
- ),
- const SizedBox(height: 16),
- _buildActionButtons(),
- ],
+ ],
+ ),
+ ValueListenableBuilder<Set<String>>(
+ valueListenable: _codeDisplayStore.selectedCodeIds,
+ builder: (context, selectedIds, _) {
+ final Code? code = _getSingleSelectedCodeWithNote(
+ selectedIds,
+ );
+ if (code == null) {
+ return const SizedBox.shrink();
+ }
+ return Padding(
+ padding: const EdgeInsets.only(top: Spacing.md),
+ child: _buildMultiSelectNotePreview(
+ note: code.note.trim(),
+ isDesktop: false,
+ ),
+ );
+ },
+ ),
+ const SizedBox(height: Spacing.lg),
+ _buildActionButtons(),
+ ],
+ ),
),
),
),
@@ -1340,7 +1220,7 @@ class _HomePageState extends State<HomePage> {
try {
if (!mounted) return;
- final GalleryImportResult? importResult = await pickCodeFromGallery(
+ final GalleryImportResult? importResult = await pickCodeFromImage(
context,
logger: _logger,
);
@@ -1837,36 +1717,44 @@ class _HomePageState extends State<HomePage> {
itemCount: itemCount,
itemBuilder: (context, index) {
if (showAllChip && index == 0) {
- return TagChip(
- label: l10n.all,
- state: selectedTag == "" && _isTrashOpen == false
- ? TagChipState.selected
- : TagChipState.unselected,
- onTap: () {
- _codeDisplayStore.clearSelection();
- selectedTag = "";
- _isTrashOpen = false;
+ return Semantics(
+ button: true,
+ identifier: 'auth_filter_all',
+ child: TagChip(
+ label: l10n.all,
+ state: selectedTag == "" && _isTrashOpen == false
+ ? TagChipState.selected
+ : TagChipState.unselected,
+ onTap: () {
+ _codeDisplayStore.clearSelection();
+ selectedTag = "";
+ _isTrashOpen = false;
- setState(() {});
- _applyFilteringAndRefresh();
- },
+ setState(() {});
+ _applyFilteringAndRefresh();
+ },
+ ),
);
}
if (showTrashChip && index == itemCount - 1) {
- return TagChip(
- label: l10n.trash,
- state: _isTrashOpen
- ? TagChipState.selected
- : TagChipState.unselected,
- onTap: () {
- _codeDisplayStore.clearSelection();
- selectedTag = "";
- _isTrashOpen = !_isTrashOpen;
- setState(() {});
- _applyFilteringAndRefresh();
- },
- iconData: Icons.delete,
+ return Semantics(
+ button: true,
+ identifier: 'auth_filter_trash',
+ child: TagChip(
+ label: l10n.trash,
+ state: _isTrashOpen
+ ? TagChipState.selected
+ : TagChipState.unselected,
+ onTap: () {
+ _codeDisplayStore.clearSelection();
+ selectedTag = "";
+ _isTrashOpen = !_isTrashOpen;
+ setState(() {});
+ _applyFilteringAndRefresh();
+ },
+ iconData: Icons.delete,
+ ),
);
}
final customTagIndex = index - (showAllChip ? 1 : 0);
@@ -2064,7 +1952,10 @@ class _HomePageState extends State<HomePage> {
return;
}
final lowerLink = link.toLowerCase();
- if (mounted && lowerLink.startsWith("enteauth://search")) {
+ final debugCodeLink = parseDebugCodeDeepLink(link);
+ if (mounted && debugCodeLink != null) {
+ _handleDebugCodeLink(debugCodeLink);
+ } else if (mounted && lowerLink.startsWith("enteauth://search")) {
try {
final uri = Uri.parse(link);
final searchQuery = uri.queryParameters['query'];
@@ -2083,15 +1974,46 @@ class _HomePageState extends State<HomePage> {
return;
}
lastScanTime = DateTime.now().millisecondsSinceEpoch;
- try {
- final newCode = Code.fromOTPAuthUrl(link);
- getNextTotp(newCode);
- CodeStore.instance.addCode(newCode, shouldSync: false);
- _focusNewCode(newCode);
- } catch (e, s) {
- showGenericErrorDialog(context: context, error: e);
- _logger.severe("error while handling deeplink", e, s);
- }
+ _addCodeFromDeepLink(link);
+ }
+ }
+
+ void _addCodeFromDeepLink(String link) {
+ try {
+ final newCode = Code.fromOTPAuthUrl(link);
+ getNextTotp(newCode);
+ CodeStore.instance.addCode(newCode, shouldSync: false);
+ _focusNewCode(newCode);
+ } catch (e, s) {
+ showGenericErrorDialog(context: context, error: e);
+ _logger.severe("error while handling deeplink", e, s);
+ }
+ }
+
+ void _handleDebugCodeLink(DebugCodeDeepLink link) {
+ switch (link.action) {
+ case DebugCodeDeepLinkAction.addCode:
+ _addCodeFromDeepLink(link.codeUri);
+ return;
+ case DebugCodeDeepLinkAction.showQr:
+ unawaited(_showQrSheet(Code.fromOTPAuthUrl(link.codeUri)));
+ return;
+ case DebugCodeDeepLinkAction.shareCode:
+ showShareDialog(context, Code.fromOTPAuthUrl(link.codeUri));
+ return;
+ case DebugCodeDeepLinkAction.showIcons:
+ final code = Code.fromOTPAuthUrl(link.codeUri);
+ unawaited(
+ Navigator.of(context).push(
+ MaterialPageRoute<void>(
+ builder: (_) => CustomIconPage(
+ currentIcon: code.issuer,
+ allIcons: IconUtils.instance.getAllIcons(),
+ ),
+ ),
+ ),
+ );
+ return;
}
}
diff --git a/mobile/apps/auth/lib/ui/reorder_codes_page.dart b/mobile/apps/auth/lib/ui/reorder_codes_page.dart
index 5689d2599f..9fc8ba5992 100644
--- a/mobile/apps/auth/lib/ui/reorder_codes_page.dart
+++ b/mobile/apps/auth/lib/ui/reorder_codes_page.dart
@@ -1,15 +1,17 @@
import 'dart:ui';
+
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/services/preference_service.dart';
import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
import 'package:ente_auth/ui/code_widget.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
class ReorderCodesPage extends StatefulWidget {
const ReorderCodesPage({super.key, required this.codes});
+
final List<Code> codes;
@override
@@ -17,10 +19,9 @@ class ReorderCodesPage extends StatefulWidget {
}
class _ReorderCodesPageState extends State<ReorderCodesPage> {
- bool hasChanged = false;
final logger = Logger('ReorderCodesPage');
-
final ScrollController _scrollController = ScrollController();
+ bool hasChanged = false;
@override
void dispose() {
@@ -30,94 +31,149 @@ class _ReorderCodesPageState extends State<ReorderCodesPage> {
@override
Widget build(BuildContext context) {
- final bool isCompactMode = PreferenceService.instance.isCompactMode();
+ final colors = context.componentColors;
+ final isCompactMode = PreferenceService.instance.isCompactMode();
- return Scaffold(
- appBar: AppBar(
- title: Text(context.l10n.customOrder),
- leading: IconButton(
- icon: const Icon(Icons.arrow_back),
- onPressed: () async {
- Navigator.of(context).pop();
- },
- ),
- actions: [
- GestureDetector(
- onTap: () async {
- final hasSaved = await saveUpadedIndexes();
- if (hasSaved) {
- if (!context.mounted) return;
- Navigator.of(context).pop();
- }
- },
- child: Padding(
- padding: const EdgeInsets.only(right: 20),
- child: Text(
- context.l10n.save,
- style: TextStyle(
- color: hasChanged
- ? getEnteColorScheme(context).textBase
- : getEnteColorScheme(context).strokeMuted,
+ return Semantics(
+ container: true,
+ identifier: 'auth_reorder_codes_page',
+ child: Scaffold(
+ backgroundColor: colors.backgroundBase,
+ body: Scrollbar(
+ controller: _scrollController,
+ thumbVisibility: true,
+ interactive: true,
+ child: AppBarComponent(
+ title: context.l10n.customOrder,
+ controller: _scrollController,
+ actions: [
+ Padding(
+ padding: const EdgeInsets.only(right: Spacing.sm),
+ child: Semantics(
+ button: true,
+ identifier: 'auth_reorder_save',
+ child: IconButtonComponent(
+ icon: const Icon(
+ Icons.check_rounded,
+ size: IconSizes.medium,
+ ),
+ variant: IconButtonComponentVariant.unfilled,
+ tooltip: context.l10n.save,
+ onTap: hasChanged ? _save : null,
+ ),
),
),
- ),
- ),
- ],
- ),
- body: Scrollbar(
- controller: _scrollController,
- thumbVisibility: true,
- interactive: true,
- child: ReorderableListView(
- scrollController: _scrollController,
- buildDefaultDragHandles: false,
- proxyDecorator:
- (Widget child, int index, Animation<double> animation) {
- return AnimatedBuilder(
- animation: animation,
- builder: (BuildContext context, _) {
- final animValue = Curves.easeInOut.transform(
- animation.value,
+ ],
+ slivers: [
+ SliverSafeArea(
+ top: false,
+ sliver: SliverReorderableList(
+ itemCount: widget.codes.length,
+ proxyDecorator: _proxyDecorator,
+ itemBuilder: (context, index) {
+ final code = widget.codes[index];
+ return _ReorderableCodeRow(
+ key: ValueKey('${code.hashCode}_${code.generatedID}'),
+ code: code,
+ index: index,
+ isCompactMode: isCompactMode,
);
- final scale = lerpDouble(1, 1.05, animValue)!;
- return Transform.scale(scale: scale, child: child);
},
- );
- },
- children: [
- for (final code in widget.codes)
- ReorderableDragStartListener(
- key: ValueKey('${code.hashCode}_${code.generatedID}'),
- index: widget.codes.indexOf(code),
- child: CodeWidget(
- key: ValueKey(code.generatedID),
- code,
- isCompactMode: isCompactMode,
- isReordering: true,
+ onReorder: updateCodeIndex,
),
),
- ],
- onReorder: (oldIndex, newIndex) {
- updateCodeIndex(oldIndex, newIndex);
- },
+ ],
+ ),
),
),
);
}
- Future<bool> saveUpadedIndexes() async {
- final result = await CodeStore.instance.saveUpadedIndexes(widget.codes);
- return result;
+ Widget _proxyDecorator(Widget child, int index, Animation<double> animation) {
+ return AnimatedBuilder(
+ animation: animation,
+ builder: (context, _) {
+ final scale = lerpDouble(
+ 1,
+ 1.03,
+ Curves.easeInOut.transform(animation.value),
+ )!;
+ return Transform.scale(scale: scale, child: child);
+ },
+ );
+ }
+
+ Future<void> _save() async {
+ if (!hasChanged) return;
+ final hasSaved = await saveUpdatedIndexes();
+ if (hasSaved && mounted) Navigator.of(context).pop();
+ }
+
+ Future<bool> saveUpdatedIndexes() {
+ return CodeStore.instance.saveUpadedIndexes(widget.codes);
}
void updateCodeIndex(int oldIndex, int newIndex) {
setState(() {
- // Adjust index when moving down the list
- // oldIndex = 2, newIndex = 0
if (oldIndex < newIndex) newIndex -= 1;
- final Code code = widget.codes.removeAt(oldIndex);
+ final code = widget.codes.removeAt(oldIndex);
widget.codes.insert(newIndex, code);
hasChanged = true;
});
}
}
+
+class _ReorderableCodeRow extends StatelessWidget {
+ const _ReorderableCodeRow({
+ super.key,
+ required this.code,
+ required this.index,
+ required this.isCompactMode,
+ });
+
+ final Code code;
+ final int index;
+ final bool isCompactMode;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.componentColors;
+ return Row(
+ children: [
+ Expanded(
+ child: CodeWidget(
+ key: ValueKey(code.generatedID),
+ code,
+ isCompactMode: isCompactMode,
+ isReordering: true,
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.only(right: Spacing.lg),
+ child: ReorderableDragStartListener(
+ index: index,
+ child: Semantics(
+ button: true,
+ label: '${code.issuer}, ${code.account}',
+ identifier: 'auth_reorder_handle',
+ child: Container(
+ width: 44,
+ height: 44,
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: colors.fillLight,
+ borderRadius: BorderRadius.circular(Radii.button),
+ ),
+ child: Icon(
+ Icons.drag_handle_rounded,
+ size: IconSizes.medium,
+ color: colors.textLight,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/scanner_gauth_page.dart b/mobile/apps/auth/lib/ui/scanner_gauth_page.dart
index 16d1a1ca75..657d3cfe34 100644
--- a/mobile/apps/auth/lib/ui/scanner_gauth_page.dart
+++ b/mobile/apps/auth/lib/ui/scanner_gauth_page.dart
@@ -2,7 +2,6 @@ import 'dart:async';
import 'dart:io';
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/theme/ente_theme.dart';
import 'package:ente_auth/ui/components/scanner_camera_view.dart';
import 'package:ente_auth/ui/settings/data/import/google_auth_import.dart';
@@ -76,14 +75,14 @@ class ScannerGoogleAuthPageState extends State<ScannerGoogleAuthPage> {
}
try {
- final codes = parseGoogleAuth(qrCode);
- _completeWithCodes(codes);
+ final migration = parseGoogleAuthMigration(qrCode);
+ _completeWithMigration(migration);
} catch (e) {
_completeWithError(e);
}
}
- void _completeWithCodes(List<Code> codes) {
+ void _completeWithMigration(GoogleAuthMigration migration) {
if (_hasCompletedScan) {
return;
}
@@ -92,7 +91,7 @@ class ScannerGoogleAuthPageState extends State<ScannerGoogleAuthPage> {
if (!mounted) {
return;
}
- Navigator.of(context).pop(codes);
+ Navigator.of(context).pop(migration);
}
void _completeWithError(Object error) {
diff --git a/mobile/apps/auth/lib/ui/scanner_page.dart b/mobile/apps/auth/lib/ui/scanner_page.dart
index 7fb9e18816..0f22d2567f 100644
--- a/mobile/apps/auth/lib/ui/scanner_page.dart
+++ b/mobile/apps/auth/lib/ui/scanner_page.dart
@@ -320,7 +320,7 @@ class ScannerPageState extends State<ScannerPage> {
if (!mounted) return;
await controller?.pause();
if (!mounted) return;
- final GalleryImportResult? importResult = await pickCodeFromGallery(
+ final GalleryImportResult? importResult = await pickCodeFromImage(
context,
logger: _logger,
);
diff --git a/mobile/apps/auth/lib/ui/settings/about_section_widget.dart b/mobile/apps/auth/lib/ui/settings/about_section_widget.dart
deleted file mode 100644
index ac5b89cccc..0000000000
--- a/mobile/apps/auth/lib/ui/settings/about_section_widget.dart
+++ /dev/null
@@ -1,124 +0,0 @@
-import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/services/update_service.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/expandable_menu_item_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/settings/app_update_dialog.dart';
-import 'package:ente_auth/ui/settings/common_settings.dart';
-import 'package:ente_auth/utils/dialog_util.dart';
-import 'package:ente_auth/utils/platform_util.dart';
-import 'package:ente_auth/utils/toast_util.dart';
-import 'package:flutter/material.dart';
-
-class AboutSectionWidget extends StatelessWidget {
- const AboutSectionWidget({super.key});
-
- @override
- Widget build(BuildContext context) {
- return ExpandableMenuItemWidget(
- title: context.l10n.about,
- selectionOptionsWidget: _getSectionOptions(context),
- leadingIcon: Icons.info_outline,
- );
- }
-
- Widget _getSectionOptions(BuildContext context) {
- return Column(
- children: [
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: context.l10n.weAreOpenSource,
- ),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- await PlatformUtil.openUrlInBrowser("https://github.com/ente/ente");
- },
- ),
- sectionOptionSpacing,
- AboutMenuItemWidget(
- title: context.l10n.privacy,
- url: "https://ente.com/privacy",
- ),
- sectionOptionSpacing,
- AboutMenuItemWidget(
- title: context.l10n.termsOfServicesTitle,
- url: "https://ente.com/terms",
- ),
- sectionOptionSpacing,
- UpdateService.instance.supportsInAppUpdates()
- ? Column(
- children: [
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: context.l10n.checkForUpdates,
- ),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- final dialog = createProgressDialog(
- context,
- context.l10n.checking,
- );
- await dialog.show();
- final shouldUpdate = await UpdateService.instance
- .shouldUpdate();
- await dialog.hide();
- if (shouldUpdate) {
- if (!context.mounted) return;
- // ignore: unawaited_futures
- showDialog(
- context: context,
- builder: (BuildContext context) {
- return AppUpdateDialog(
- UpdateService.instance.getLatestVersionInfo(),
- );
- },
- barrierColor: Colors.black.withValues(alpha: 0.85),
- );
- } else {
- if (!context.mounted) return;
- showShortToast(
- context,
- context.l10n.youAreOnTheLatestVersion,
- );
- }
- },
- ),
- sectionOptionSpacing,
- ],
- )
- : const SizedBox.shrink(),
- ],
- );
- }
-}
-
-class AboutMenuItemWidget extends StatelessWidget {
- final String title;
- final String url;
- final String? webPageTitle;
- const AboutMenuItemWidget({
- required this.title,
- required this.url,
- this.webPageTitle,
- super.key,
- });
-
- @override
- Widget build(BuildContext context) {
- return MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: title),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- await PlatformUtil.openUrlInBrowser(url);
- },
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/settings/about_settings_page.dart b/mobile/apps/auth/lib/ui/settings/about_settings_page.dart
new file mode 100644
index 0000000000..930edb477f
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/about_settings_page.dart
@@ -0,0 +1,88 @@
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/services/update_service.dart';
+import 'package:ente_auth/ui/settings/app_update_dialog.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_item.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
+import 'package:ente_auth/utils/dialog_util.dart';
+import 'package:ente_auth/utils/platform_util.dart';
+import 'package:ente_auth/utils/toast_util.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
+
+class AboutSettingsPage extends StatelessWidget {
+ const AboutSettingsPage({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final l10n = context.l10n;
+ return AuthSettingsPageScaffold(
+ title: l10n.about,
+ children: [
+ AuthSettingsItem(
+ title: l10n.weAreOpenSource,
+ icon: HugeIcons.strokeRoundedGithub,
+ showOnlyLoadingState: true,
+ onTap: () =>
+ PlatformUtil.openUrlInBrowser('https://github.com/ente/ente'),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.blog,
+ icon: HugeIcons.strokeRoundedPencilEdit01,
+ showOnlyLoadingState: true,
+ onTap: () => PlatformUtil.openUrlInBrowser('https://ente.com/blog'),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.merchandise,
+ icon: HugeIcons.strokeRoundedShoppingBag01,
+ showOnlyLoadingState: true,
+ onTap: () => PlatformUtil.openUrlInBrowser('https://shop.ente.com'),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.privacy,
+ icon: HugeIcons.strokeRoundedShield01,
+ showOnlyLoadingState: true,
+ onTap: () =>
+ PlatformUtil.openUrlInBrowser('https://ente.com/privacy'),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.termsOfServicesTitle,
+ icon: HugeIcons.strokeRoundedFile01,
+ showOnlyLoadingState: true,
+ onTap: () => PlatformUtil.openUrlInBrowser('https://ente.com/terms'),
+ ),
+ if (UpdateService.instance.supportsInAppUpdates()) ...[
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.checkForUpdates,
+ icon: HugeIcons.strokeRoundedDownload04,
+ showOnlyLoadingState: true,
+ onTap: () => _checkForUpdates(context),
+ ),
+ ],
+ ],
+ );
+ }
+
+ Future<void> _checkForUpdates(BuildContext context) async {
+ final dialog = createProgressDialog(context, context.l10n.checking);
+ await dialog.show();
+ final shouldUpdate = await UpdateService.instance.shouldUpdate();
+ await dialog.hide();
+ if (!context.mounted) return;
+ if (shouldUpdate) {
+ await showDialog<void>(
+ context: context,
+ builder: (_) =>
+ AppUpdateDialog(UpdateService.instance.getLatestVersionInfo()),
+ barrierColor: Colors.black.withValues(alpha: 0.85),
+ );
+ return;
+ }
+ showShortToast(context, context.l10n.youAreOnTheLatestVersion);
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/settings/account_section_widget.dart b/mobile/apps/auth/lib/ui/settings/account_section_widget.dart
deleted file mode 100644
index 1ad6f90060..0000000000
--- a/mobile/apps/auth/lib/ui/settings/account_section_widget.dart
+++ /dev/null
@@ -1,171 +0,0 @@
-import 'dart:async';
-
-import 'package:ente_account_deletion/account_deletion.dart';
-import 'package:ente_accounts/pages/change_email_dialog.dart';
-import 'package:ente_accounts/pages/password_entry_page.dart';
-import 'package:ente_accounts/services/user_service.dart';
-import 'package:ente_auth/core/configuration.dart';
-import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/expandable_menu_item_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/components/recovery_key_sheet.dart';
-import 'package:ente_auth/ui/home_page.dart';
-import 'package:ente_auth/ui/settings/common_settings.dart';
-import 'package:ente_auth/utils/dialog_util.dart';
-import 'package:ente_crypto_api/ente_crypto_api.dart';
-import 'package:ente_lock_screen/local_authentication_service.dart';
-import 'package:flutter/material.dart';
-
-class AccountSectionWidget extends StatelessWidget {
- AccountSectionWidget({super.key});
-
- @override
- Widget build(BuildContext context) {
- final l10n = context.l10n;
- return ExpandableMenuItemWidget(
- title: l10n.account,
- selectionOptionsWidget: _getSectionOptions(context),
- leadingIcon: Icons.account_circle_outlined,
- );
- }
-
- Column _getSectionOptions(BuildContext context) {
- final l10n = context.l10n;
- List<Widget> children = [];
- children.addAll([
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.changeEmail),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- final hasAuthenticated = await LocalAuthenticationService.instance
- .requestLocalAuthentication(context, l10n.authToChangeYourEmail);
- if (hasAuthenticated) {
- if (!context.mounted) return;
- // ignore: unawaited_futures
- showChangeEmailDialog(context);
- }
- },
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.changePassword),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- final hasAuthenticated = await LocalAuthenticationService.instance
- .requestLocalAuthentication(
- context,
- l10n.authToChangeYourPassword,
- );
- if (hasAuthenticated) {
- if (!context.mounted) return;
- // ignore: unawaited_futures
- Navigator.of(context).push(
- MaterialPageRoute(
- builder: (BuildContext context) {
- return PasswordEntryPage(
- Configuration.instance,
- PasswordEntryMode.update,
- const HomePage(),
- );
- },
- ),
- );
- }
- },
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.recoveryKey),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- final hasAuthenticated = await LocalAuthenticationService.instance
- .requestLocalAuthentication(
- context,
- l10n.authToViewYourRecoveryKey,
- );
- if (hasAuthenticated) {
- if (!context.mounted) return;
- String recoveryKey;
- try {
- recoveryKey = CryptoUtil.bin2hex(
- Configuration.instance.getRecoveryKey(),
- );
- } catch (e) {
- // ignore: unawaited_futures
- showGenericErrorDialog(context: context, error: e);
- return;
- }
- // ignore: unawaited_futures
- showRecoveryKeySheet(context, recoveryKey: recoveryKey);
- }
- },
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: context.l10n.logout),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- _onLogoutTapped(context);
- },
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: context.l10n.deleteAccount,
- ),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- final hasAuthenticated = await LocalAuthenticationService.instance
- .requestLocalAuthentication(
- context,
- l10n.authToInitiateAccountDeletion,
- );
- if (!context.mounted || !hasAuthenticated) {
- return;
- }
- final deleted = await Navigator.of(context).push<bool>(
- MaterialPageRoute(
- builder: (BuildContext context) {
- return const DeleteAccountPage();
- },
- ),
- );
- if (deleted == true && context.mounted) {
- unawaited(
- Navigator.of(
- context,
- ).pushNamedAndRemoveUntil('/', (route) => false),
- );
- }
- },
- ),
- sectionOptionSpacing,
- ]);
- return Column(children: children);
- }
-
- void _onLogoutTapped(BuildContext context) {
- showChoiceActionSheet(
- context,
- title: context.l10n.areYouSureYouWantToLogout,
- firstButtonLabel: context.l10n.yesLogout,
- isCritical: true,
- firstButtonOnTap: () async {
- await UserService.instance.logout(context);
- },
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/settings/account_settings_page.dart b/mobile/apps/auth/lib/ui/settings/account_settings_page.dart
new file mode 100644
index 0000000000..98b76bc5b6
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/account_settings_page.dart
@@ -0,0 +1,119 @@
+import 'dart:async';
+
+import 'package:ente_account_deletion/account_deletion.dart';
+import 'package:ente_accounts/pages/change_email_dialog.dart';
+import 'package:ente_accounts/pages/password_entry_page.dart';
+import 'package:ente_auth/core/configuration.dart';
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/ui/components/recovery_key_sheet.dart';
+import 'package:ente_auth/ui/home_page.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_item.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
+import 'package:ente_auth/utils/dialog_util.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:ente_crypto_api/ente_crypto_api.dart';
+import 'package:ente_lock_screen/local_authentication_service.dart';
+import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
+
+class AccountSettingsPage extends StatelessWidget {
+ const AccountSettingsPage({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final l10n = context.l10n;
+ return AuthSettingsPageScaffold(
+ title: l10n.account,
+ children: [
+ AuthSettingsItem(
+ title: l10n.changeEmail,
+ icon: HugeIcons.strokeRoundedMailEdit01,
+ onTap: () => _changeEmail(context),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.changePassword,
+ icon: HugeIcons.strokeRoundedLockPassword,
+ onTap: () => _changePassword(context),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.recoveryKey,
+ icon: HugeIcons.strokeRoundedKey01,
+ onTap: () => _showRecoveryKey(context),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.deleteAccount,
+ icon: HugeIcons.strokeRoundedDelete02,
+ isDestructive: true,
+ onTap: () => _deleteAccount(context),
+ ),
+ ],
+ );
+ }
+
+ Future<void> _changeEmail(BuildContext context) async {
+ final authenticated = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(
+ context,
+ context.l10n.authToChangeYourEmail,
+ );
+ if (authenticated && context.mounted) {
+ await showChangeEmailDialog(context);
+ }
+ }
+
+ Future<void> _changePassword(BuildContext context) async {
+ final authenticated = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(
+ context,
+ context.l10n.authToChangeYourPassword,
+ );
+ if (!authenticated || !context.mounted) return;
+ await Navigator.of(context).push<void>(
+ MaterialPageRoute(
+ builder: (_) => PasswordEntryPage(
+ Configuration.instance,
+ PasswordEntryMode.update,
+ const HomePage(),
+ ),
+ ),
+ );
+ }
+
+ Future<void> _showRecoveryKey(BuildContext context) async {
+ final authenticated = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(
+ context,
+ context.l10n.authToViewYourRecoveryKey,
+ );
+ if (!authenticated || !context.mounted) return;
+ try {
+ final recoveryKey = CryptoUtil.bin2hex(
+ Configuration.instance.getRecoveryKey(),
+ );
+ await showRecoveryKeySheet(context, recoveryKey: recoveryKey);
+ } catch (error) {
+ if (!context.mounted) return;
+ unawaited(showGenericErrorDialog(context: context, error: error));
+ }
+ }
+
+ Future<void> _deleteAccount(BuildContext context) async {
+ final authenticated = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(
+ context,
+ context.l10n.authToInitiateAccountDeletion,
+ );
+ if (!authenticated || !context.mounted) return;
+ final deleted = await Navigator.of(
+ context,
+ ).push<bool>(MaterialPageRoute(builder: (_) => const DeleteAccountPage()));
+ if (deleted == true && context.mounted) {
+ unawaited(
+ Navigator.of(context).pushNamedAndRemoveUntil('/', (_) => false),
+ );
+ }
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/settings/app_icon_selection_screen.dart b/mobile/apps/auth/lib/ui/settings/app_icon_selection_screen.dart
index 3de639b24d..c9ff3963ba 100644
--- a/mobile/apps/auth/lib/ui/settings/app_icon_selection_screen.dart
+++ b/mobile/apps/auth/lib/ui/settings/app_icon_selection_screen.dart
@@ -1,8 +1,6 @@
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/common/loading_widget.dart';
-import 'package:ente_auth/ui/components/title_bar_title_widget.dart';
-import 'package:ente_auth/ui/components/title_bar_widget.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:figma_squircle/figma_squircle.dart';
import 'package:flutter/material.dart';
import 'package:launcher_icon_switcher/launcher_icon_switcher.dart';
@@ -49,6 +47,7 @@ class _AppIconSelectionScreenState extends State<AppIconSelectionScreen> {
.getCurrentIcon()
.then((icon) {
_logger.info("Current icon is $icon");
+ if (!mounted) return;
setState(() {
_currentIcon = icon;
});
@@ -61,43 +60,33 @@ class _AppIconSelectionScreenState extends State<AppIconSelectionScreen> {
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
- return Scaffold(
- body: Center(
- child: Container(
- constraints: const BoxConstraints.tightFor(width: 450),
- child: CustomScrollView(
- primary: false,
- slivers: <Widget>[
- TitleBarWidget(
- flexibleSpaceTitle: TitleBarTitleWidget(title: l10n.appIcon),
- ),
- _currentIcon != null
- ? SliverPadding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- sliver: SliverList(
- delegate: SliverChildBuilderDelegate((
- delegateBuildContext,
- index,
- ) {
- final icon = AppIcon.values[index];
- final isCurrentIcon = icon.id == _currentIcon;
- return _AppIconTile(icon, isCurrentIcon, () {
- if (!isCurrentIcon) {
- _changeIcon(icon.id);
- }
- });
- }, childCount: AppIcon.values.length),
- ),
- )
- : SliverToBoxAdapter(
- child: EnteLoadingWidget(
- color: getEnteColorScheme(context).strokeMuted,
- ),
- ),
- ],
+ return AuthSettingsPageScaffold(
+ title: l10n.appIcon,
+ children: [
+ if (_currentIcon == null)
+ const Padding(
+ padding: EdgeInsets.all(Spacing.xxl),
+ child: Center(child: CircularProgressIndicator()),
+ )
+ else
+ Semantics(
+ identifier: 'auth_app_icon_list',
+ child: MenuGroupComponent(
+ showDividers: true,
+ dividerPadding: const EdgeInsets.only(left: 64),
+ items: [
+ for (final icon in AppIcon.values)
+ _AppIconTile(
+ icon,
+ icon.id == _currentIcon,
+ () => icon.id == _currentIcon
+ ? Future<void>.value()
+ : _changeIcon(icon.id),
+ ),
+ ],
+ ),
),
- ),
- ),
+ ],
);
}
@@ -110,15 +99,14 @@ class _AppIconSelectionScreenState extends State<AppIconSelectionScreen> {
_logger.info("Changing icon to $icon");
await _iconSwitcher.setIcon(icon);
_logger.info("Icon changed to $icon");
+ if (!mounted) return;
setState(() {
_currentIcon = icon;
});
} catch (error, stackTrace) {
_logger.severe("Error changing icon", error, stackTrace);
} finally {
- setState(() {
- _isChangingIcon = false;
- });
+ if (mounted) setState(() => _isChangingIcon = false);
}
}
}
@@ -126,79 +114,23 @@ class _AppIconSelectionScreenState extends State<AppIconSelectionScreen> {
class _AppIconTile extends StatelessWidget {
final AppIcon appIcon;
final bool isSelected;
- final Function() onSelect;
+ final Future<void> Function() onSelect;
const _AppIconTile(this.appIcon, this.isSelected, this.onSelect);
@override
Widget build(BuildContext context) {
- return Padding(
- padding: const EdgeInsets.symmetric(vertical: 8),
- child: GestureDetector(
- onTap: () {
- onSelect();
- },
- child: Container(
- decoration: BoxDecoration(
- color: getEnteColorScheme(context).fillFaint,
- borderRadius: const BorderRadius.all(Radius.circular(8)),
- ),
- padding: const EdgeInsets.symmetric(horizontal: 8),
- child: Row(
- children: [
- RadioGroup<bool>(
- groupValue: true,
- onChanged: (_) {
- onSelect();
- },
- child: Radio<bool>(
- value: isSelected,
- fillColor: WidgetStateProperty.resolveWith<Color>((states) {
- if (isSelected) {
- return getEnteColorScheme(context).primary700;
- } else {
- return getEnteColorScheme(context).fillMuted;
- }
- }),
- visualDensity: VisualDensity.compact,
- splashRadius: 0,
- ),
- ),
- const SizedBox(width: 8),
- Padding(
- padding: const EdgeInsets.symmetric(vertical: 12),
- child: Row(
- children: [
- ClipSmoothRect(
- radius: SmoothBorderRadius(
- cornerRadius: 12,
- cornerSmoothing: 1,
- ),
- child: Image(
- width: 60,
- height: 60,
- image: AssetImage(appIcon.path),
- ),
- ),
- const SizedBox(width: 12),
- AnimatedSwitcher(
- duration: const Duration(milliseconds: 200),
- switchInCurve: Curves.easeOutQuart,
- switchOutCurve: Curves.easeInQuart,
- child: Text(
- key: ValueKey(isSelected),
- appIcon.name,
- style: isSelected
- ? getEnteTextTheme(context).bodyBold
- : getEnteTextTheme(context).bodyFaint,
- ),
- ),
- ],
- ),
- ),
- ],
- ),
- ),
+ return MenuComponent(
+ title: appIcon.name,
+ selected: isSelected,
+ leading: ClipSmoothRect(
+ radius: SmoothBorderRadius(cornerRadius: 8, cornerSmoothing: 1),
+ child: Image(width: 36, height: 36, image: AssetImage(appIcon.path)),
+ ),
+ trailing: RadioComponent(
+ selected: isSelected,
+ onChanged: (_) => onSelect(),
),
+ onTap: onSelect,
);
}
}
diff --git a/mobile/apps/auth/lib/ui/settings/app_version_widget.dart b/mobile/apps/auth/lib/ui/settings/app_version_widget.dart
index 1426815865..fb12d1e93f 100644
--- a/mobile/apps/auth/lib/ui/settings/app_version_widget.dart
+++ b/mobile/apps/auth/lib/ui/settings/app_version_widget.dart
@@ -45,11 +45,19 @@ class _AppVersionWidgetState extends State<AppVersionWidget> {
future: _getAppVersion(),
builder: (context, snapshot) {
if (snapshot.hasData) {
- return Padding(
- padding: const EdgeInsets.all(20),
- child: Text(
- "Version: ${snapshot.data!}",
- style: Theme.of(context).textTheme.bodySmall,
+ return SizedBox(
+ width: double.infinity,
+ child: Padding(
+ padding: const EdgeInsets.all(20),
+ child: Semantics(
+ identifier: 'auth_settings_app_version',
+ child: Center(
+ child: Text(
+ "Version: ${snapshot.data!}",
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
+ ),
+ ),
),
);
}
diff --git a/mobile/apps/auth/lib/ui/settings/common_settings.dart b/mobile/apps/auth/lib/ui/settings/common_settings.dart
deleted file mode 100644
index 4299c1cca3..0000000000
--- a/mobile/apps/auth/lib/ui/settings/common_settings.dart
+++ /dev/null
@@ -1,15 +0,0 @@
-import 'package:expandable/expandable.dart';
-import 'package:flutter/cupertino.dart';
-import 'package:flutter/material.dart';
-
-Widget sectionOptionSpacing = const SizedBox(height: 6);
-
-ExpandableThemeData getExpandableTheme() {
- return const ExpandableThemeData(
- hasIcon: false,
- useInkWell: false,
- tapBodyToCollapse: true,
- tapBodyToExpand: true,
- animationDuration: Duration(milliseconds: 400),
- );
-}
diff --git a/mobile/apps/auth/lib/ui/settings/components/auth_settings_item.dart b/mobile/apps/auth/lib/ui/settings/components/auth_settings_item.dart
new file mode 100644
index 0000000000..a16616805d
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/components/auth_settings_item.dart
@@ -0,0 +1,77 @@
+import 'dart:async';
+
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
+
+/// Auth-local settings composition built from Ente's shared menu primitive.
+///
+/// Keep this local until the team decides whether the Photos and Locker
+/// settings wrappers should be consolidated in `ente_components`.
+class AuthSettingsItem extends StatelessWidget {
+ const AuthSettingsItem({
+ super.key,
+ required this.title,
+ this.subtitle,
+ this.icon,
+ this.trailing,
+ this.onTap,
+ this.onDoubleTap,
+ this.showChevron = true,
+ this.isDestructive = false,
+ this.showOnlyLoadingState = false,
+ this.semanticsIdentifier,
+ });
+
+ final String title;
+ final String? subtitle;
+ final List<List<dynamic>>? icon;
+ final Widget? trailing;
+ final FutureOr<void> Function()? onTap;
+ final FutureOr<void> Function()? onDoubleTap;
+ final bool showChevron;
+ final bool isDestructive;
+ final bool showOnlyLoadingState;
+ final String? semanticsIdentifier;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.componentColors;
+ final foregroundColor = isDestructive ? colors.warning : colors.textBase;
+ final iconColor = isDestructive ? colors.warning : colors.textLight;
+
+ final item = MenuComponent(
+ title: title,
+ subtitle: subtitle,
+ titleColor: foregroundColor,
+ iconColor: iconColor,
+ leading: _leadingIcon(iconColor),
+ trailing: trailing ?? (showChevron ? _chevron(colors) : null),
+ showOnlyLoadingState: showOnlyLoadingState,
+ onTap: onTap,
+ onDoubleTap: onDoubleTap,
+ );
+ final identifier = semanticsIdentifier;
+ return identifier == null
+ ? item
+ : Semantics(identifier: identifier, child: item);
+ }
+
+ Widget? _leadingIcon(Color color) {
+ if (icon == null) return null;
+ return HugeIcon(
+ icon: icon!,
+ color: color,
+ size: IconSizes.small,
+ strokeWidth: 1.6,
+ );
+ }
+
+ Widget _chevron(ColorTokens colors) {
+ return Icon(
+ Icons.chevron_right_outlined,
+ color: colors.textLight,
+ size: IconSizes.medium,
+ );
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/settings/components/auth_settings_navigation.dart b/mobile/apps/auth/lib/ui/settings/components/auth_settings_navigation.dart
new file mode 100644
index 0000000000..c65d62140f
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/components/auth_settings_navigation.dart
@@ -0,0 +1,7 @@
+import 'package:flutter/material.dart';
+
+Future<void> pushAuthSettingsPage(BuildContext context, Widget page) async {
+ await Navigator.of(
+ context,
+ ).push<void>(MaterialPageRoute<void>(builder: (_) => page));
+}
diff --git a/mobile/apps/auth/lib/ui/settings/components/auth_settings_page_scaffold.dart b/mobile/apps/auth/lib/ui/settings/components/auth_settings_page_scaffold.dart
new file mode 100644
index 0000000000..c07587ad59
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/components/auth_settings_page_scaffold.dart
@@ -0,0 +1,40 @@
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+
+/// Auth-local settings scaffold composed from [AppBarComponent].
+class AuthSettingsPageScaffold extends StatelessWidget {
+ const AuthSettingsPageScaffold({
+ super.key,
+ required this.title,
+ required this.children,
+ this.subtitle,
+ this.backButton,
+ });
+
+ final String title;
+ final String? subtitle;
+ final Widget? backButton;
+ final List<Widget> children;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = context.componentColors;
+ return Scaffold(
+ backgroundColor: colors.backgroundBase,
+ body: AppBarComponent(
+ title: title,
+ subtitle: subtitle,
+ backButton: backButton,
+ slivers: [
+ SliverSafeArea(
+ top: false,
+ sliver: SliverPadding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
+ sliver: SliverList.list(children: children),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/settings/data/data_section_widget.dart b/mobile/apps/auth/lib/ui/settings/data/data_section_widget.dart
deleted file mode 100644
index 9b985e5ed5..0000000000
--- a/mobile/apps/auth/lib/ui/settings/data/data_section_widget.dart
+++ /dev/null
@@ -1,110 +0,0 @@
-import 'dart:async';
-
-import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/services/deduplication_service.dart';
-import 'package:ente_auth/services/flagservice.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/expandable_menu_item_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/settings/common_settings.dart';
-import 'package:ente_auth/ui/settings/data/duplicate_code_page.dart';
-import 'package:ente_auth/ui/settings/data/export_widget.dart';
-import 'package:ente_auth/ui/settings/data/import_page.dart';
-import 'package:ente_auth/ui/settings/data/local_backup_settings_page.dart'; //for local backup
-import 'package:ente_auth/utils/dialog_util.dart';
-import 'package:ente_auth/utils/navigation_util.dart';
-import 'package:flutter/material.dart';
-
-class DataSectionWidget extends StatelessWidget {
- // final _logger = Logger("AccountSectionWidget");
-
- DataSectionWidget({super.key});
-
- @override
- Widget build(BuildContext context) {
- final l10n = context.l10n;
- return ExpandableMenuItemWidget(
- title: l10n.data,
- selectionOptionsWidget: _getSectionOptions(context),
- leadingIcon: Icons.key_outlined,
- );
- }
-
- Future<void> _handleLocalBackupClick(BuildContext context) async {
- await routeToPage(context, const LocalBackupSettingsPage());
- }
-
- Column _getSectionOptions(BuildContext context) {
- final l10n = context.l10n;
- List<Widget> children = [];
- children.addAll([
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.importCodes),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- await routeToPage(context, const ImportCodePage());
- },
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.exportCodes),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- await handleExportClick(context);
- },
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.duplicateCodes),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- final List<DuplicateCodes> duplicateCodes = await DeduplicationService
- .instance
- .getDuplicateCodes();
- if (duplicateCodes.isEmpty) {
- if (!context.mounted) return;
- unawaited(
- showChoiceDialog(
- context,
- title: l10n.noDuplicates,
- firstButtonLabel: "OK",
- secondButtonLabel: null,
- body: l10n.youveNoDuplicateCodesThatCanBeCleared,
- ),
- );
- return;
- }
- if (!context.mounted) return;
- await routeToPage(
- context,
- DuplicateCodePage(duplicateCodes: duplicateCodes),
- );
- },
- ),
- if (FeatureFlagService.isLocalBackupEnabled()) ...[
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: l10n.localBackupSidebarTitle,
- ),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- await _handleLocalBackupClick(context);
- },
- ),
- sectionOptionSpacing,
- ],
- ]);
- return Column(children: children);
- }
-}
diff --git a/mobile/apps/auth/lib/ui/settings/data/data_settings_page.dart b/mobile/apps/auth/lib/ui/settings/data/data_settings_page.dart
new file mode 100644
index 0000000000..b80c3cdd5b
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/data/data_settings_page.dart
@@ -0,0 +1,90 @@
+import 'dart:async';
+
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/services/deduplication_service.dart';
+import 'package:ente_auth/services/flagservice.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_item.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_navigation.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
+import 'package:ente_auth/ui/settings/data/duplicate_code_page.dart';
+import 'package:ente_auth/ui/settings/data/export_widget.dart';
+import 'package:ente_auth/ui/settings/data/import_page.dart';
+import 'package:ente_auth/ui/settings/data/local_backup_settings_page.dart';
+import 'package:ente_auth/utils/dialog_util.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
+
+class DataSettingsPage extends StatelessWidget {
+ const DataSettingsPage({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final l10n = context.l10n;
+ return AuthSettingsPageScaffold(
+ title: l10n.data,
+ children: [
+ AuthSettingsItem(
+ title: l10n.importCodes,
+ icon: HugeIcons.strokeRoundedFileImport,
+ onTap: () => _openImportCodes(context),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.exportCodes,
+ icon: HugeIcons.strokeRoundedFileExport,
+ showOnlyLoadingState: true,
+ onTap: () => handleExportClick(context),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.duplicateCodes,
+ icon: HugeIcons.strokeRoundedCopy01,
+ showOnlyLoadingState: true,
+ onTap: () => _openDuplicateCodes(context),
+ ),
+ if (FeatureFlagService.isLocalBackupEnabled()) ...[
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.localBackupSidebarTitle,
+ icon: HugeIcons.strokeRoundedHardDrive,
+ onTap: () =>
+ pushAuthSettingsPage(context, const LocalBackupSettingsPage()),
+ ),
+ ],
+ ],
+ );
+ }
+
+ Future<void> _openImportCodes(BuildContext context) async {
+ final completed = await Navigator.of(
+ context,
+ ).push<bool>(MaterialPageRoute(builder: (_) => const ImportCodePage()));
+ if (completed == true && context.mounted) {
+ Navigator.of(context).pop(true);
+ }
+ }
+
+ Future<void> _openDuplicateCodes(BuildContext context) async {
+ final l10n = context.l10n;
+ final duplicateCodes = await DeduplicationService.instance
+ .getDuplicateCodes();
+ if (!context.mounted) return;
+ if (duplicateCodes.isEmpty) {
+ unawaited(
+ showChoiceDialog(
+ context,
+ title: l10n.noDuplicates,
+ firstButtonLabel: l10n.ok,
+ secondButtonLabel: null,
+ body: l10n.youveNoDuplicateCodesThatCanBeCleared,
+ ),
+ );
+ return;
+ }
+ await pushAuthSettingsPage(
+ context,
+ DuplicateCodePage(duplicateCodes: duplicateCodes),
+ );
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/settings/data/duplicate_code_page.dart b/mobile/apps/auth/lib/ui/settings/data/duplicate_code_page.dart
index 863cfafb5a..25129dbaec 100644
--- a/mobile/apps/auth/lib/ui/settings/data/duplicate_code_page.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/duplicate_code_page.dart
@@ -1,238 +1,219 @@
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/services/deduplication_service.dart';
import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
import 'package:ente_auth/ui/code_widget.dart';
import 'package:ente_auth/utils/dialog_util.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:ente_lock_screen/local_authentication_service.dart';
-import 'package:ente_ui/components/centered_constrained_widget.dart';
import 'package:flutter/material.dart';
-import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:logging/logging.dart';
class DuplicateCodePage extends StatefulWidget {
- final List<DuplicateCodes> duplicateCodes;
const DuplicateCodePage({super.key, required this.duplicateCodes});
+ final List<DuplicateCodes> duplicateCodes;
+
@override
State<DuplicateCodePage> createState() => _DuplicateCodePageState();
}
class _DuplicateCodePageState extends State<DuplicateCodePage> {
- final Logger _logger = Logger("DuplicateCodePage");
- late List<DuplicateCodes> _duplicateCodes;
- final Set<int> selectedGrids = <int>{};
+ final Logger _logger = Logger('DuplicateCodePage');
+ final Set<int> selectedGroups = <int>{};
+ late final List<DuplicateCodes> _duplicateCodes;
@override
void initState() {
- _duplicateCodes = widget.duplicateCodes;
super.initState();
+ _duplicateCodes = widget.duplicateCodes;
}
@override
Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(title: Text(context.l10n.deduplicateCodes), elevation: 0),
- body: CenteredConstrainedWidget(child: _getBody()),
+ final colors = context.componentColors;
+ return Semantics(
+ container: true,
+ identifier: 'auth_duplicate_codes_page',
+ child: Scaffold(
+ backgroundColor: colors.backgroundBase,
+ body: AppBarComponent(
+ title: context.l10n.deduplicateCodes,
+ slivers: [
+ SliverSafeArea(
+ top: false,
+ sliver: SliverList.list(children: _buildChildren(context)),
+ ),
+ ],
+ ),
+ ),
);
}
- Widget _getBody() {
+ List<Widget> _buildChildren(BuildContext context) {
final l10n = context.l10n;
- return SafeArea(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisAlignment: MainAxisAlignment.start,
- children: [
- AnimatedContainer(
- duration: const Duration(milliseconds: 200),
- curve: Curves.easeOut,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.end,
- children: [
- GestureDetector(
- onTap: () {
- if (selectedGrids.length == _duplicateCodes.length) {
- _removeAllGrids();
- } else {
- _selectAllGrids();
- }
- setState(() {});
- },
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text(
- selectedGrids.length == _duplicateCodes.length
- ? l10n.deselectAll
- : l10n.selectAll,
- style: Theme.of(context).textTheme.titleMedium!
- .copyWith(
- fontSize: 14,
- color: Theme.of(
- context,
- ).iconTheme.color!.withValues(alpha: 0.7),
- ),
- ),
- const Padding(padding: EdgeInsets.only(left: 4)),
- selectedGrids.length == _duplicateCodes.length
- ? const Icon(Icons.check_circle, size: 24)
- : Icon(
- Icons.check_circle_outlined,
- color: getEnteColorScheme(context).strokeMuted,
- size: 24,
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- ),
- const SizedBox(height: 8),
- Expanded(
- child: ListView.builder(
- itemCount: _duplicateCodes.length,
- shrinkWrap: true,
- itemBuilder: (context, index) {
- final List<Code> codes = _duplicateCodes[index].codes;
- return _getGridView(codes, index);
- },
+ final allSelected = selectedGroups.length == _duplicateCodes.length;
+ final children = <Widget>[
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Spacing.lg,
+ 0,
+ Spacing.lg,
+ Spacing.lg,
+ ),
+ child: Align(
+ alignment: AlignmentDirectional.centerEnd,
+ child: Semantics(
+ button: true,
+ identifier: 'auth_duplicate_select_all',
+ child: FilterChipComponent(
+ label: allSelected ? l10n.deselectAll : l10n.selectAll,
+ state: allSelected
+ ? FilterChipComponentState.selected
+ : FilterChipComponentState.unselected,
+ onChanged: (_) => _toggleAll(),
),
),
- selectedGrids.isEmpty ? const SizedBox.shrink() : _getDeleteButton(),
- ],
+ ),
),
- );
- }
+ ];
- Widget _getGridView(List<Code> code, int itemIndex) {
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
+ for (
+ var groupIndex = 0;
+ groupIndex < _duplicateCodes.length;
+ groupIndex++
+ ) {
+ final codes = _duplicateCodes[groupIndex].codes;
+ final isSelected = selectedGroups.contains(groupIndex);
+ children.addAll([
Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
- child: GestureDetector(
- onTap: () {
- if (selectedGrids.contains(itemIndex)) {
- selectedGrids.remove(itemIndex);
- } else {
- selectedGrids.add(itemIndex);
- }
- setState(() {});
- },
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- Text("${code[0].issuer}, ${code.length} items"),
- !selectedGrids.contains(itemIndex)
- ? Icon(
- Icons.check_circle_outlined,
- color: getEnteColorScheme(context).strokeMuted,
- size: 24,
- )
- : const Icon(Icons.check_circle, size: 24),
+ padding: const EdgeInsets.symmetric(horizontal: Spacing.lg),
+ child: Semantics(
+ button: true,
+ identifier: 'auth_duplicate_group_$groupIndex',
+ child: MenuGroupComponent(
+ items: [
+ MenuComponent(
+ title: '${codes.first.issuer} (${codes.length})',
+ selected: isSelected,
+ trailing: CheckboxComponent(
+ selected: isSelected,
+ onChanged: (_) => _toggleGroup(groupIndex),
+ ),
+ onTap: () => _toggleGroup(groupIndex),
+ ),
],
),
),
),
- AlignedGridView.count(
- crossAxisCount: (MediaQuery.sizeOf(context).width ~/ 400)
- .clamp(1, double.infinity)
- .toInt(),
- padding: const EdgeInsets.only(bottom: 40),
- shrinkWrap: true,
- physics: const NeverScrollableScrollPhysics(),
- itemBuilder: (context, index) {
- return CodeWidget(
- key: ValueKey('${code.hashCode}_$index'),
- code[index],
- isCompactMode: false,
- );
- },
- itemCount: code.length,
+ const SizedBox(height: Spacing.sm),
+ for (final code in codes) CodeWidget(code, isCompactMode: false),
+ const SizedBox(height: Spacing.xl),
+ ]);
+ }
+
+ final selectedItemsCount = _selectedItemsCount();
+ if (selectedItemsCount > 0) {
+ children.add(
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Spacing.lg,
+ 0,
+ Spacing.lg,
+ Spacing.xl,
+ ),
+ child: Semantics(
+ button: true,
+ identifier: 'auth_duplicate_trash',
+ child: ButtonComponent(
+ label: '${l10n.trash} ($selectedItemsCount)',
+ variant: ButtonComponentVariant.critical,
+ onTap: () => deleteDuplicates(selectedItemsCount),
+ ),
+ ),
),
- ],
- );
+ );
+ }
+ return children;
}
- Widget _getDeleteButton() {
- int selectedItemsCount = 0;
- for (int idx = 0; idx < _duplicateCodes.length; idx++) {
- if (selectedGrids.contains(idx)) {
- selectedItemsCount += _duplicateCodes[idx].codes.length - 1;
+ void _toggleAll() {
+ setState(() {
+ if (selectedGroups.length == _duplicateCodes.length) {
+ selectedGroups.clear();
+ } else {
+ selectedGroups
+ ..clear()
+ ..addAll(List.generate(_duplicateCodes.length, (index) => index));
}
- }
- return Padding(
- padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 20),
- child: SizedBox(
- width: 400,
- child: OutlinedButton(
- onPressed: () async {
- await deleteDuplicates(selectedItemsCount);
- },
- child: Text("Delete $selectedItemsCount items"),
- ),
- ),
- );
+ });
}
- void _selectAllGrids() {
- selectedGrids.clear();
- for (int idx = 0; idx < _duplicateCodes.length; idx++) {
- selectedGrids.add(idx);
- }
+ void _toggleGroup(int groupIndex) {
+ setState(() {
+ if (!selectedGroups.remove(groupIndex)) selectedGroups.add(groupIndex);
+ });
}
- void _removeAllGrids() {
- selectedGrids.clear();
+ int _selectedItemsCount() {
+ var count = 0;
+ for (final index in selectedGroups) {
+ count += _duplicateCodes[index].codes.length - 1;
+ }
+ return count;
}
Future<void> deleteDuplicates(int itemCount) async {
- bool isAuthSuccessful = await LocalAuthenticationService.instance
+ final isAuthSuccessful = await LocalAuthenticationService.instance
.requestLocalAuthentication(
context,
context.l10n.deleteCodeAuthMessage,
);
- if (!isAuthSuccessful) {
- return;
- }
- if (!mounted) return;
- FocusScope.of(context).requestFocus();
- final l10n = context.l10n;
- final String message = "Are you sure you want to trash $itemCount items?";
- if (!mounted) return;
- await showChoiceActionSheet(
- context,
- title: l10n.deleteDuplicates,
- body: message,
- firstButtonLabel: l10n.trash,
- isCritical: true,
- firstButtonOnTap: () async {
- try {
- if (!mounted) return;
- for (int idx = 0; idx < _duplicateCodes.length; idx++) {
- if (selectedGrids.contains(idx)) {
- final List<Code> codes = _duplicateCodes[idx].codes;
- for (int i = 1; i < codes.length; i++) {
- final display = codes[i].display;
- final Code code = codes[i].copyWith(
- display: display.copyWith(trashed: true),
- );
- await CodeStore.instance.addCode(code);
- }
- }
- }
- if (!mounted) return;
- Navigator.of(context).pop();
- } catch (e) {
- _logger.severe('Failed to trash duplicate codes: ${e.toString()}');
- showGenericErrorDialog(context: context, error: e).ignore();
- }
- },
+ if (!isAuthSuccessful || !mounted) return;
+
+ final trashed = await showBottomSheetComponent<bool>(
+ context: context,
+ builder: (sheetContext) => Semantics(
+ identifier: 'auth_duplicate_confirm_sheet',
+ child: BottomSheetComponent(
+ title: context.l10n.deleteDuplicates,
+ message: context.l10n.moveMultipleToTrashMessage(itemCount),
+ closeTooltip: context.l10n.close,
+ actions: [
+ ButtonComponent(
+ label: context.l10n.trash,
+ variant: ButtonComponentVariant.critical,
+ onTap: () async {
+ final didTrash = await _trashSelectedDuplicates();
+ if (didTrash && sheetContext.mounted) {
+ Navigator.of(sheetContext).pop(true);
+ }
+ },
+ ),
+ ],
+ ),
+ ),
);
+ if (trashed == true && mounted) Navigator.of(context).pop();
+ }
+
+ Future<bool> _trashSelectedDuplicates() async {
+ try {
+ for (final index in selectedGroups) {
+ final codes = _duplicateCodes[index].codes;
+ for (var codeIndex = 1; codeIndex < codes.length; codeIndex++) {
+ final code = codes[codeIndex];
+ await CodeStore.instance.addCode(
+ code.copyWith(display: code.display.copyWith(trashed: true)),
+ );
+ }
+ }
+ return true;
+ } catch (error, stackTrace) {
+ _logger.severe('Failed to trash duplicate codes', error, stackTrace);
+ if (mounted) {
+ showGenericErrorDialog(context: context, error: error).ignore();
+ }
+ return false;
+ }
}
}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/aegis_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/aegis_import.dart
index 5300d2ff2a..db6e417df9 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/aegis_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/aegis_import.dart
@@ -1,4 +1,3 @@
-import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
@@ -6,16 +5,10 @@ import 'package:convert/convert.dart';
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/models/code_display.dart';
-import 'package:ente_auth/services/authenticator_service.dart';
-import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/dialog_widget.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/settings/data/import/import_file_cleanup.dart';
-import 'package:ente_auth/ui/settings/data/import/import_success.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_ui/components/progress_dialog.dart';
-import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
@@ -26,68 +19,25 @@ import 'package:pointycastle/pointycastle.dart';
Future<void> showAegisImportInstruction(BuildContext context) async {
final l10n = context.l10n;
- final result = await showDialogWidget(
+ await showFileImportInstruction(
context: context,
- title: l10n.importFromApp("Aegis Authenticator"),
+ title: "Aegis Authenticator",
body: l10n.importAegisGuide,
- buttons: [
- ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: l10n.importSelectJsonFile,
- isInAlert: true,
- buttonSize: ButtonSize.large,
- buttonAction: ButtonAction.first,
- ),
- ButtonWidget(
- buttonType: ButtonType.secondary,
- labelText: context.l10n.cancel,
- buttonSize: ButtonSize.large,
- isInAlert: true,
- buttonAction: ButtonAction.second,
- ),
- ],
+ actionLabel: l10n.importSelectJsonFile,
+ semanticsIdentifier: 'auth_import_instruction_aegis',
+ onImport: () => _pickAegisJsonFile(context),
);
- if (result?.action != null && result!.action != ButtonAction.cancel) {
- if (!context.mounted) return;
- if (result.action == ButtonAction.first) {
- await _pickAegisJsonFile(context);
- } else {}
- }
}
Future<void> _pickAegisJsonFile(BuildContext context) async {
- final l10n = context.l10n;
- FilePickerResult? result = await FilePicker.platform.pickFiles(
- dialogTitle: l10n.importSelectJsonFile,
- );
- if (result == null) {
- return;
- }
- if (!context.mounted) return;
- final ProgressDialog progressDialog = createProgressDialog(
- context,
- l10n.pleaseWait,
+ await pickAndProcessImportFile(
+ context: context,
+ dialogTitle: context.l10n.importSelectJsonFile,
+ logger: Logger('AegisImport'),
+ logMessage: 'Exception while processing Aegis import',
+ process: (path, progressDialog) =>
+ _processAegisExportFile(context, path, progressDialog),
);
- await progressDialog.show();
- try {
- if (!context.mounted) return;
- String path = result.files.single.path!;
- int? count = await _processAegisExportFile(context, path, progressDialog);
- await progressDialog.hide();
- if (count != null) {
- if (!context.mounted) return;
- await importSuccessDialog(context, count);
- }
- } catch (e, s) {
- Logger('AegisImport').severe('exception while processing for aegis', e, s);
- await progressDialog.hide();
- if (!context.mounted) return;
- await showErrorDialog(
- context,
- context.l10n.sorry,
- "${context.l10n.importFailureDesc}\n Error: ${e.toString()}",
- );
- }
}
Future<int?> _processAegisExportFile(
@@ -105,21 +55,16 @@ Future<int?> _processAegisExportFile(
String? password;
try {
if (!context.mounted) return null;
- await showTextInputDialog(
+ password = await promptForImportPassword(
context,
title: context.l10n.enterPasswordToAegisVault,
- submitButtonLabel: context.l10n.submit,
- isPasswordInput: true,
- onSubmit: (value) async {
- password = value;
- },
);
if (password == null) {
await dialog.hide();
return null;
}
await dialog.show();
- final content = decryptAegisVault(decodedJson, password: password!);
+ final content = decryptAegisVault(decodedJson, password: password);
aegisDB = jsonDecode(content);
} catch (e, s) {
Logger(
@@ -150,7 +95,7 @@ Future<int?> _processAegisExportFile(
Logger("AegisImport").warning("Failed to parse groups", e);
}
- final parsedCodes = [];
+ final parsedCodes = <Code>[];
for (var item in aegisDB?['entries']) {
bool isFavorite = item['favorite'] ?? false;
List<String> tags = [];
@@ -170,32 +115,25 @@ Future<int?> _processAegisExportFile(
}
}
}
- // Build the OTP URL
- String otpUrl;
-
- if (kind.toLowerCase() == 'totp' || kind.toLowerCase() == 'steam') {
- otpUrl =
- 'otpauth://$kind/$issuer:$account?secret=$secret&issuer=$issuer&algorithm=$algorithm&digits=$digits&period=$timer';
- } else if (kind.toLowerCase() == 'hotp') {
- otpUrl =
- 'otpauth://$kind/$issuer:$account?secret=$secret&issuer=$issuer&algorithm=$algorithm&digits=$digits&counter=$counter';
- } else {
- throw Exception('Invalid OTP type: $kind');
- }
-
- Code code = Code.fromOTPAuthUrl(otpUrl);
+ Code code = Code.fromOTPAuthUrl(
+ buildImportOtpUri(
+ kind: kind,
+ issuer: issuer,
+ account: account,
+ secret: secret,
+ algorithm: algorithm,
+ digits: digits,
+ period: timer,
+ counter: counter,
+ ),
+ );
code = code.copyWith(
display: CodeDisplay(pinned: isFavorite, tags: tags),
);
parsedCodes.add(code);
}
- for (final code in parsedCodes) {
- await CodeStore.instance.addCode(code, shouldSync: false);
- }
- unawaited(AuthenticatorService.instance.onlineSync());
- int count = parsedCodes.length;
- return count;
+ return saveImportedCodes(parsedCodes);
}
String decryptAegisVault(dynamic data, {required String password}) {
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart
index b679ef50c2..4b026a2141 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/andotp_import.dart
@@ -1,16 +1,10 @@
-import 'dart:async';
import 'dart:convert';
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/models/code_display.dart';
-import 'package:ente_auth/services/authenticator_service.dart';
-import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/dialog_widget.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/settings/data/import/import_file_cleanup.dart';
-import 'package:ente_auth/ui/settings/data/import/import_success.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_ui/components/progress_dialog.dart';
import 'package:file_picker/file_picker.dart';
@@ -23,71 +17,28 @@ final _logger = Logger('AndOTPImport');
Future<void> showAndOTPImportInstruction(BuildContext context) async {
final l10n = context.l10n;
- final result = await showDialogWidget(
+ await showFileImportInstruction(
context: context,
- title: l10n.importFromApp("andOTP"),
+ title: "andOTP",
body: l10n.importAndOTPGuide,
- buttons: [
- ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: l10n.importSelectAppExport("andOTP"),
- isInAlert: true,
- buttonSize: ButtonSize.large,
- buttonAction: ButtonAction.first,
- ),
- ButtonWidget(
- buttonType: ButtonType.secondary,
- labelText: l10n.cancel,
- buttonSize: ButtonSize.large,
- isInAlert: true,
- buttonAction: ButtonAction.second,
- ),
- ],
+ actionLabel: l10n.importSelectAppExport("andOTP"),
+ semanticsIdentifier: 'auth_import_instruction_andotp',
+ onImport: () => _pickAndOTPFile(context),
);
- if (result?.action != null && result!.action != ButtonAction.cancel) {
- if (!context.mounted) return;
- if (result.action == ButtonAction.first) {
- await _pickAndOTPFile(context);
- }
- }
}
Future<void> _pickAndOTPFile(BuildContext context) async {
- final l10n = context.l10n;
- FilePickerResult? result = await FilePicker.platform.pickFiles(
- dialogTitle: l10n.importSelectAppExport("andOTP"),
- allowMultiple: false,
+ await pickAndProcessImportFile(
+ context: context,
+ dialogTitle: context.l10n.importSelectAppExport("andOTP"),
type: FileType.custom,
allowedExtensions: ['json', 'aes'],
+ showProgressBeforeProcessing: false,
+ logger: _logger,
+ logMessage: 'Exception while processing andOTP import',
+ process: (path, progressDialog) =>
+ _processAndOTPFile(context, path, progressDialog),
);
- if (result == null) {
- return;
- }
- if (!context.mounted) return;
- final ProgressDialog progressDialog = createProgressDialog(
- context,
- l10n.pleaseWait,
- );
-
- try {
- if (!context.mounted) return;
- String path = result.files.single.path!;
- final count = await _processAndOTPFile(context, path, progressDialog);
- await progressDialog.hide();
- if (count != null) {
- if (!context.mounted) return;
- await importSuccessDialog(context, count);
- }
- } catch (e, s) {
- _logger.severe('Exception while processing andOTP import', e, s);
- await progressDialog.hide();
- if (!context.mounted) return;
- await showErrorDialog(
- context,
- l10n.sorry,
- "${l10n.importFailureDesc}\n Error: ${e.toString()}",
- );
- }
}
class _DecryptParams {
@@ -118,14 +69,9 @@ Future<int?> _processAndOTPFile(
// If JSON parsing fails, assume it's encrypted
String? password;
try {
- await showTextInputDialog(
+ password = await promptForImportPassword(
context,
title: context.l10n.enterPasswordToDecryptAndOTP,
- submitButtonLabel: context.l10n.submit,
- isPasswordInput: true,
- onSubmit: (value) async {
- password = value;
- },
);
if (password == null) {
return null;
@@ -133,7 +79,7 @@ Future<int?> _processAndOTPFile(
await dialog.show();
final decryptedContent = await compute(
_decryptAndOTPBackup,
- _DecryptParams(fileBytes: fileBytes, password: password!),
+ _DecryptParams(fileBytes: fileBytes, password: password),
);
entries = jsonDecode(decryptedContent) as List<dynamic>;
} catch (e, s) {
@@ -180,18 +126,18 @@ Future<int?> _processAndOTPFile(
final String encodedIssuer = Uri.encodeComponent(issuer);
final String encodedLabel = Uri.encodeComponent(label);
- String otpUrl;
- if (type == 'TOTP' || type == 'STEAM') {
- final String otpType = type.toLowerCase();
- otpUrl =
- 'otpauth://$otpType/$encodedIssuer:$encodedLabel?secret=$secret&issuer=$encodedIssuer&algorithm=$algorithm&digits=$digits&period=$period';
- } else {
- // HOTP
- otpUrl =
- 'otpauth://hotp/$encodedIssuer:$encodedLabel?secret=$secret&issuer=$encodedIssuer&algorithm=$algorithm&digits=$digits&counter=$counter';
- }
-
- Code code = Code.fromOTPAuthUrl(otpUrl);
+ Code code = Code.fromOTPAuthUrl(
+ buildImportOtpUri(
+ kind: type,
+ issuer: encodedIssuer,
+ account: encodedLabel,
+ secret: secret,
+ algorithm: algorithm,
+ digits: digits,
+ period: period,
+ counter: counter,
+ ),
+ );
if (tags.isNotEmpty) {
code = code.copyWith(display: CodeDisplay(tags: tags));
}
@@ -201,12 +147,7 @@ Future<int?> _processAndOTPFile(
}
}
- for (final code in parsedCodes) {
- await CodeStore.instance.addCode(code, shouldSync: false);
- }
- unawaited(AuthenticatorService.instance.onlineSync());
-
- return parsedCodes.length;
+ return saveImportedCodes(parsedCodes);
}
/// Top-level function for decrypting andOTP backup in a separate isolate.
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/bitwarden_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/bitwarden_import.dart
index b7cbb4bb3f..c5ea3c8792 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/bitwarden_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/bitwarden_import.dart
@@ -1,81 +1,33 @@
-import 'dart:async';
import 'dart:convert';
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/models/code_display.dart';
-import 'package:ente_auth/services/authenticator_service.dart';
-import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/dialog_widget.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/settings/data/import/import_file_cleanup.dart';
-import 'package:ente_auth/ui/settings/data/import/import_success.dart';
-import 'package:ente_auth/utils/dialog_util.dart';
-import 'package:file_picker/file_picker.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
Future<void> showBitwardenImportInstruction(BuildContext context) async {
final l10n = context.l10n;
- final result = await showDialogWidget(
+ await showFileImportInstruction(
context: context,
- title: l10n.importFromApp("Bitwarden"),
+ title: "Bitwarden",
body: l10n.importBitwardenGuide,
- buttons: [
- ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: l10n.importSelectJsonFile,
- isInAlert: true,
- buttonSize: ButtonSize.large,
- buttonAction: ButtonAction.first,
- ),
- ButtonWidget(
- buttonType: ButtonType.secondary,
- labelText: context.l10n.cancel,
- buttonSize: ButtonSize.large,
- isInAlert: true,
- buttonAction: ButtonAction.second,
- ),
- ],
+ actionLabel: l10n.importSelectJsonFile,
+ semanticsIdentifier: 'auth_import_instruction_bitwarden',
+ onImport: () => _pickBitwardenJsonFile(context),
);
- if (result?.action != null && result!.action != ButtonAction.cancel) {
- if (!context.mounted) return;
- if (result.action == ButtonAction.first) {
- await _pickBitwardenJsonFile(context);
- }
- }
}
Future<void> _pickBitwardenJsonFile(BuildContext context) async {
- final l10n = context.l10n;
- FilePickerResult? result = await FilePicker.platform.pickFiles();
- if (result == null) {
- return;
- }
- if (!context.mounted) return;
- final progressDialog = createProgressDialog(context, l10n.pleaseWait);
- await progressDialog.show();
- try {
- if (!context.mounted) return;
- String path = result.files.single.path!;
- int? count = await _processBitwardenExportFile(context, path);
- await progressDialog.hide();
- if (count != null) {
- if (!context.mounted) return;
- await importSuccessDialog(context, count);
- }
- } catch (e, s) {
- Logger("BitwardenImport").severe('Failed to import', e, s);
- await progressDialog.hide();
- if (!context.mounted) return;
- await showErrorDialog(
- context,
- context.l10n.sorry,
- "${context.l10n.importFailureDesc}\n Error: ${e.toString()}",
- );
- }
+ await pickAndProcessImportFile(
+ context: context,
+ logger: Logger('BitwardenImport'),
+ logMessage: 'Failed to import Bitwarden export',
+ process: (path, _) => _processBitwardenExportFile(context, path),
+ );
}
Future<int?> _processBitwardenExportFile(
@@ -93,7 +45,7 @@ Future<int?> _processBitwardenExportFile(
} catch (e) {
debugPrint("Failed to get folder details $e");
}
- final parsedCodes = [];
+ final parsedCodes = <Code>[];
for (var item in jsonArray) {
if (item['login'] != null && item['login']['totp'] != null) {
var totp = item['login']['totp'];
@@ -134,9 +86,5 @@ Future<int?> _processBitwardenExportFile(
}
}
- for (final code in parsedCodes) {
- await CodeStore.instance.addCode(code, shouldSync: false);
- }
- unawaited(AuthenticatorService.instance.onlineSync());
- return parsedCodes.length;
+ return saveImportedCodes(parsedCodes);
}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/encrypted_ente_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/encrypted_ente_import.dart
index 3380fc9445..a83622e1df 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/encrypted_ente_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/encrypted_ente_import.dart
@@ -1,15 +1,10 @@
-import 'dart:async';
import 'dart:convert';
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/models/export/ente.dart';
-import 'package:ente_auth/services/authenticator_service.dart';
-import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/dialog_widget.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/settings/data/import/import_file_cleanup.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
import 'package:ente_auth/ui/settings/data/import/import_success.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_auth/utils/toast_util.dart';
@@ -22,33 +17,14 @@ import 'package:logging/logging.dart';
Future<void> showEncryptedImportInstruction(BuildContext context) async {
final l10n = context.l10n;
- final result = await showDialogWidget(
+ await showFileImportInstruction(
context: context,
- title: l10n.importFromApp("Ente Auth"),
+ title: "Ente Auth",
body: l10n.importEnteEncGuide,
- buttons: [
- ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: l10n.importSelectJsonFile,
- isInAlert: true,
- buttonSize: ButtonSize.large,
- buttonAction: ButtonAction.first,
- ),
- ButtonWidget(
- buttonType: ButtonType.secondary,
- labelText: context.l10n.cancel,
- buttonSize: ButtonSize.large,
- isInAlert: true,
- buttonAction: ButtonAction.second,
- ),
- ],
+ actionLabel: l10n.importSelectJsonFile,
+ semanticsIdentifier: 'auth_import_instruction_encrypted',
+ onImport: () => _pickEnteJsonFile(context),
);
- if (result?.action != null && result!.action != ButtonAction.cancel) {
- if (!context.mounted) return;
- if (result.action == ButtonAction.first) {
- await _pickEnteJsonFile(context);
- } else {}
- }
}
Future<void> _decryptExportData(
@@ -99,7 +75,7 @@ Future<void> _decryptExportData(
}
String content = utf8.decode(decryptedContent);
List<String> splitCodes = content.split("\n");
- final parsedCodes = [];
+ final parsedCodes = <Code>[];
for (final code in splitCodes) {
try {
parsedCodes.add(Code.fromOTPAuthUrl(code));
@@ -107,11 +83,7 @@ Future<void> _decryptExportData(
Logger('EncryptedText').severe("Could not parse code", e);
}
}
- for (final code in parsedCodes) {
- await CodeStore.instance.addCode(code, shouldSync: false);
- }
- unawaited(AuthenticatorService.instance.onlineSync());
- importedCodeCount = parsedCodes.length;
+ importedCodeCount = await saveImportedCodes(parsedCodes);
await progressDialog.hide();
} catch (e, s) {
await progressDialog.hide();
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/google_auth_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/google_auth_import.dart
index ba0a0e81c2..0aa46a4ed8 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/google_auth_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/google_auth_import.dart
@@ -4,104 +4,106 @@ import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/services/authenticator_service.dart';
import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/dialog_widget.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/scanner_gauth_page.dart';
+import 'package:ente_auth/ui/settings/data/import/google_auth_migration_tracker.dart';
+import 'package:ente_auth/ui/settings/data/import/google_auth_qr_parser.dart';
+import 'package:ente_auth/ui/settings/data/import/import_instruction_sheet.dart';
import 'package:ente_auth/ui/settings/data/import/import_success.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_auth/utils/gallery_import_util.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:ente_pure_utils/ente_pure_utils.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
export 'package:ente_auth/ui/settings/data/import/google_auth_qr_parser.dart';
-Future<void> showGoogleAuthInstruction(BuildContext context) async {
+final _migrationTracker = GoogleAuthMigrationTracker();
+
+Future<bool> showGoogleAuthInstruction(BuildContext context) async {
final l10n = context.l10n;
final isMobile = PlatformDetector.isMobile();
- final result = await showDialogWidget(
+ final result = await showImportInstructionSheet(
context: context,
- title: l10n.importFromApp("Google Authenticator"),
+ title: "Google Authenticator",
body: l10n.importGoogleAuthGuide,
- buttons: [
+ cancelLabel: l10n.cancel,
+ semanticsIdentifier: 'auth_import_instruction_google_authenticator',
+ actions: [
if (isMobile)
- ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: l10n.scanAQrCode,
- isInAlert: true,
- buttonSize: ButtonSize.large,
- buttonAction: ButtonAction.first,
+ ImportInstructionAction(
+ label: l10n.scanAQrCode,
+ result: ImportInstructionResult.primary,
),
- ButtonWidget(
- buttonType: isMobile ? ButtonType.secondary : ButtonType.primary,
- labelText: l10n.importFromGallery,
- buttonSize: ButtonSize.large,
- isInAlert: true,
- buttonAction: ButtonAction.second,
- ),
- ButtonWidget(
- buttonType: ButtonType.secondary,
- labelText: context.l10n.cancel,
- buttonSize: ButtonSize.large,
- isInAlert: true,
- buttonAction: ButtonAction.cancel,
+ ImportInstructionAction(
+ label: l10n.selectFile,
+ result: ImportInstructionResult.secondary,
+ variant: isMobile
+ ? ButtonComponentVariant.secondary
+ : ButtonComponentVariant.primary,
),
],
);
- final action = result?.action;
- if (action == null || action == ButtonAction.cancel) {
- return;
+ if (result == null) {
+ return false;
}
- if (action == ButtonAction.first) {
- if (!context.mounted) return;
- final List<Code>? codes = await Navigator.of(context).push(
- MaterialPageRoute(
- builder: (BuildContext context) {
- return const ScannerGoogleAuthPage();
- },
- ),
- );
- if (codes == null || codes.isEmpty) {
- return;
- }
- final importedCount = await importGoogleAuthCodes(codes);
- if (!context.mounted) return;
- // ignore: unawaited_futures
- importSuccessDialog(context, importedCount);
- } else if (action == ButtonAction.second) {
- if (!context.mounted) return;
- await _importGoogleAuthFromImage(context);
+ if (!context.mounted) return false;
+ switch (result) {
+ case ImportInstructionResult.primary:
+ final GoogleAuthMigration? migration = await Navigator.of(context).push(
+ MaterialPageRoute(
+ builder: (BuildContext context) {
+ return const ScannerGoogleAuthPage();
+ },
+ ),
+ );
+ if (!context.mounted || migration == null || migration.codes.isEmpty) {
+ return false;
+ }
+ return _completeGoogleAuthImport(context, migration);
+ case ImportInstructionResult.secondary:
+ return _importGoogleAuthFromImage(context);
}
}
-Future<void> _importGoogleAuthFromImage(BuildContext context) async {
- final importResult = await pickCodeFromGallery(
+Future<bool> _importGoogleAuthFromImage(BuildContext context) async {
+ final importResult = await pickCodeFromImage(
context,
logger: Logger("GoogleAuthImport"),
+ pickFromFiles: true,
);
if (importResult == null) {
- return;
+ return false;
}
- final codes = importResult.googleAuthCodes;
- if (codes == null || codes.isEmpty) {
- if (!context.mounted) return;
+ final migration = importResult.googleAuthMigration;
+ if (migration == null || migration.codes.isEmpty) {
+ if (!context.mounted) return false;
await showErrorDialog(
context,
context.l10n.errorInvalidQRCode,
context.l10n.errorInvalidQRCodeBody,
);
- return;
+ return false;
}
- if (!context.mounted) return;
- final shouldImport = await confirmGoogleAuthImport(context, codes.length);
- if (!shouldImport) {
- return;
+ if (!context.mounted) return false;
+ final shouldImport = await confirmGoogleAuthImport(
+ context,
+ migration.codes.length,
+ );
+ if (!shouldImport || !context.mounted) {
+ return false;
}
- final importedCount = await importGoogleAuthCodes(codes);
- if (!context.mounted) return;
- // ignore: unawaited_futures
- importSuccessDialog(context, importedCount);
+ return _completeGoogleAuthImport(context, migration);
+}
+
+Future<bool> _completeGoogleAuthImport(
+ BuildContext context,
+ GoogleAuthMigration migration,
+) async {
+ final importedCount = await importGoogleAuthCodes(migration.codes);
+ if (!context.mounted) return false;
+ await importSuccessDialog(context, importedCount);
+ return _migrationTracker.record(migration);
}
Future<bool> confirmGoogleAuthImport(
@@ -109,28 +111,20 @@ Future<bool> confirmGoogleAuthImport(
int codeCount,
) async {
final l10n = context.l10n;
- final result = await showDialogWidget(
+ final result = await showImportInstructionSheet(
context: context,
- title: l10n.importFromApp("Google Authenticator"),
+ title: "Google Authenticator",
body: l10n.importGoogleAuthConfirmation(codeCount),
- buttons: [
- ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: l10n.importLabel,
- isInAlert: true,
- buttonSize: ButtonSize.large,
- buttonAction: ButtonAction.first,
- ),
- ButtonWidget(
- buttonType: ButtonType.secondary,
- labelText: l10n.cancel,
- buttonSize: ButtonSize.large,
- isInAlert: true,
- buttonAction: ButtonAction.cancel,
+ cancelLabel: l10n.cancel,
+ semanticsIdentifier: 'auth_import_confirm_google_authenticator',
+ actions: [
+ ImportInstructionAction(
+ label: l10n.importLabel,
+ result: ImportInstructionResult.primary,
),
],
);
- return result?.action == ButtonAction.first;
+ return result == ImportInstructionResult.primary;
}
Future<int> importGoogleAuthCodes(List<Code> codes) async {
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/google_auth_migration_tracker.dart b/mobile/apps/auth/lib/ui/settings/data/import/google_auth_migration_tracker.dart
new file mode 100644
index 0000000000..7dd83465e5
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/data/import/google_auth_migration_tracker.dart
@@ -0,0 +1,22 @@
+import 'package:ente_auth/ui/settings/data/import/google_auth_qr_parser.dart';
+
+class GoogleAuthMigrationTracker {
+ final Map<(int, int), Set<int>> _importedBatchIndices = {};
+
+ bool record(GoogleAuthMigration migration) {
+ if (!migration.hasValidBatchMetadata) return false;
+ if (migration.batchSize == 1) return true;
+ if (migration.batchId == 0) return false;
+
+ final key = (migration.batchId, migration.batchSize);
+ final importedIndices = _importedBatchIndices.putIfAbsent(
+ key,
+ () => <int>{},
+ );
+ importedIndices.add(migration.batchIndex);
+ if (importedIndices.length != migration.batchSize) return false;
+
+ _importedBatchIndices.remove(key);
+ return true;
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/google_auth_qr_parser.dart b/mobile/apps/auth/lib/ui/settings/data/import/google_auth_qr_parser.dart
index 657a859b6f..71ccf94ae3 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/google_auth_qr_parser.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/google_auth_qr_parser.dart
@@ -12,7 +12,28 @@ bool isGoogleAuthExportQr(String qrCodeData) {
return qrCodeData.startsWith(kGoogleAuthExportPrefix);
}
+class GoogleAuthMigration {
+ final List<Code> codes;
+ final int batchId;
+ final int batchSize;
+ final int batchIndex;
+
+ const GoogleAuthMigration({
+ required this.codes,
+ required this.batchId,
+ required this.batchSize,
+ required this.batchIndex,
+ });
+
+ bool get hasValidBatchMetadata =>
+ batchSize > 0 && batchIndex >= 0 && batchIndex < batchSize;
+}
+
List<Code> parseGoogleAuth(String qrCodeData) {
+ return parseGoogleAuthMigration(qrCodeData).codes;
+}
+
+GoogleAuthMigration parseGoogleAuthMigration(String qrCodeData) {
try {
List<Code> codes = <Code>[];
final String payload = qrCodeData.substring(kGoogleAuthExportPrefix.length);
@@ -75,7 +96,12 @@ List<Code> parseGoogleAuth(String qrCodeData) {
}
codes.add(Code.fromOTPAuthUrl(otpUrl));
}
- return codes;
+ return GoogleAuthMigration(
+ codes: codes,
+ batchId: mPayload.batchId,
+ batchSize: mPayload.batchSize,
+ batchIndex: mPayload.batchIndex,
+ );
} catch (e, s) {
Logger(
"GoogleAuthImport",
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/import_flow.dart b/mobile/apps/auth/lib/ui/settings/data/import/import_flow.dart
new file mode 100644
index 0000000000..a5e91c4fed
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/data/import/import_flow.dart
@@ -0,0 +1,133 @@
+import 'dart:async';
+
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/models/code.dart';
+import 'package:ente_auth/services/authenticator_service.dart';
+import 'package:ente_auth/store/code_store.dart';
+import 'package:ente_auth/ui/settings/data/import/import_instruction_sheet.dart';
+import 'package:ente_auth/ui/settings/data/import/import_success.dart';
+import 'package:ente_auth/utils/dialog_util.dart';
+import 'package:ente_ui/components/progress_dialog.dart';
+import 'package:file_picker/file_picker.dart';
+import 'package:flutter/material.dart';
+import 'package:logging/logging.dart';
+
+typedef ImportFileProcessor =
+ Future<int?> Function(String path, ProgressDialog progressDialog);
+
+Future<void> showFileImportInstruction({
+ required BuildContext context,
+ required String title,
+ required String actionLabel,
+ required String semanticsIdentifier,
+ required Future<void> Function() onImport,
+ String? body,
+ Widget? content,
+}) async {
+ final result = await showImportInstructionSheet(
+ context: context,
+ title: title,
+ body: body,
+ content: content,
+ cancelLabel: context.l10n.cancel,
+ semanticsIdentifier: semanticsIdentifier,
+ actions: [
+ ImportInstructionAction(
+ label: actionLabel,
+ result: ImportInstructionResult.primary,
+ ),
+ ],
+ );
+ if (result != ImportInstructionResult.primary || !context.mounted) return;
+ await onImport();
+}
+
+Future<void> pickAndProcessImportFile({
+ required BuildContext context,
+ required Logger logger,
+ required String logMessage,
+ required ImportFileProcessor process,
+ String? dialogTitle,
+ FileType type = FileType.any,
+ List<String>? allowedExtensions,
+ bool showProgressBeforeProcessing = true,
+ String Function(BuildContext context, Object error)? errorMessage,
+}) async {
+ final result = await FilePicker.platform.pickFiles(
+ dialogTitle: dialogTitle,
+ allowMultiple: false,
+ type: type,
+ allowedExtensions: allowedExtensions,
+ );
+ if (result == null || !context.mounted) return;
+
+ final progressDialog = createProgressDialog(context, context.l10n.pleaseWait);
+ try {
+ if (showProgressBeforeProcessing) {
+ await progressDialog.show();
+ }
+ if (!context.mounted) return;
+ final count = await process(result.files.single.path!, progressDialog);
+ await progressDialog.hide();
+ if (count != null && context.mounted) {
+ await importSuccessDialog(context, count);
+ }
+ } catch (error, stackTrace) {
+ logger.severe(logMessage, error, stackTrace);
+ await progressDialog.hide();
+ if (!context.mounted) return;
+ await showErrorDialog(
+ context,
+ context.l10n.sorry,
+ errorMessage?.call(context, error) ??
+ '${context.l10n.importFailureDesc}\n Error: $error',
+ );
+ }
+}
+
+Future<String?> promptForImportPassword(
+ BuildContext context, {
+ required String title,
+}) async {
+ String? password;
+ await showTextInputDialog(
+ context,
+ title: title,
+ submitButtonLabel: context.l10n.submit,
+ isPasswordInput: true,
+ onSubmit: (value) async {
+ password = value;
+ },
+ );
+ return password;
+}
+
+String buildImportOtpUri({
+ required String kind,
+ required Object issuer,
+ required Object account,
+ required Object secret,
+ required Object algorithm,
+ required Object digits,
+ Object? period,
+ Object? counter,
+ bool allowSteam = true,
+}) {
+ final normalizedKind = kind.toLowerCase();
+ if (normalizedKind == 'totp' || (allowSteam && normalizedKind == 'steam')) {
+ return 'otpauth://$normalizedKind/$issuer:$account?secret=$secret&issuer=$issuer&algorithm=$algorithm&digits=$digits&period=$period';
+ }
+ if (normalizedKind == 'hotp') {
+ return 'otpauth://hotp/$issuer:$account?secret=$secret&issuer=$issuer&algorithm=$algorithm&digits=$digits&counter=$counter';
+ }
+ throw FormatException('Invalid OTP type: $kind');
+}
+
+Future<int> saveImportedCodes(Iterable<Code> codes) async {
+ final importedCodes = codes.toList(growable: false);
+ for (final code in importedCodes) {
+ await CodeStore.instance.addCode(code, shouldSync: false);
+ }
+ unawaited(AuthenticatorService.instance.onlineSync());
+ return importedCodes.length;
+}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/import_instruction_sheet.dart b/mobile/apps/auth/lib/ui/settings/data/import/import_instruction_sheet.dart
new file mode 100644
index 0000000000..cf7e3fe783
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/data/import/import_instruction_sheet.dart
@@ -0,0 +1,62 @@
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+
+enum ImportInstructionResult { primary, secondary }
+
+class ImportInstructionAction {
+ const ImportInstructionAction({
+ required this.label,
+ required this.result,
+ this.variant = ButtonComponentVariant.primary,
+ });
+
+ final String label;
+ final ImportInstructionResult result;
+ final ButtonComponentVariant variant;
+}
+
+Future<ImportInstructionResult?> showImportInstructionSheet({
+ required BuildContext context,
+ required String title,
+ required String cancelLabel,
+ required List<ImportInstructionAction> actions,
+ String? body,
+ Widget? content,
+ String? semanticsIdentifier,
+}) {
+ assert(body != null || content != null);
+ return showBottomSheetComponent<ImportInstructionResult>(
+ context: context,
+ builder: (sheetContext) {
+ final colors = sheetContext.componentColors;
+ final sheetContent =
+ content ??
+ Text(body!, style: TextStyles.body.copyWith(color: colors.textLight));
+ final sheet = BottomSheetComponent(
+ title: title,
+ closeTooltip: cancelLabel,
+ content: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: MediaQuery.sizeOf(sheetContext).height * 0.45,
+ ),
+ child: SizedBox(
+ width: double.infinity,
+ child: SingleChildScrollView(child: sheetContent),
+ ),
+ ),
+ actions: [
+ for (final action in actions)
+ ButtonComponent(
+ label: action.label,
+ variant: action.variant,
+ shouldSurfaceExecutionStates: false,
+ onTap: () => Navigator.of(sheetContext).pop(action.result),
+ ),
+ ],
+ );
+ return semanticsIdentifier == null
+ ? sheet
+ : Semantics(identifier: semanticsIdentifier, child: sheet);
+ },
+ );
+}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/import_service.dart b/mobile/apps/auth/lib/ui/settings/data/import/import_service.dart
index 3656569c12..8f411eb41f 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/import_service.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/import_service.dart
@@ -18,39 +18,37 @@ class ImportService {
ImportService._internal();
- Future<void> initiateImport(BuildContext context, ImportType type) async {
+ Future<bool> initiateImport(BuildContext context, ImportType type) async {
switch (type) {
case ImportType.plainText:
await showImportInstructionDialog(context);
- break;
+ return false;
case ImportType.encrypted:
await showEncryptedImportInstruction(context);
- break;
+ return false;
case ImportType.ravio:
await showRaivoImportInstruction(context);
- break;
+ return false;
case ImportType.googleAuthenticator:
- await showGoogleAuthInstruction(context);
- // showToast(context, 'coming soon');
- break;
+ return showGoogleAuthInstruction(context);
case ImportType.aegis:
await showAegisImportInstruction(context);
- break;
+ return false;
case ImportType.twoFas:
await show2FasImportInstruction(context);
- break;
+ return false;
case ImportType.bitwarden:
await showBitwardenImportInstruction(context);
- break;
+ return false;
case ImportType.lastpass:
await showLastpassImportInstruction(context);
- break;
+ return false;
case ImportType.proton:
await showProtonImportInstruction(context);
- break;
+ return false;
case ImportType.andOTP:
await showAndOTPImportInstruction(context);
- break;
+ return false;
}
}
}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/import_success.dart b/mobile/apps/auth/lib/ui/settings/data/import/import_success.dart
index 21bb758841..73e8ec9071 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/import_success.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/import_success.dart
@@ -1,26 +1,25 @@
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/dialog_widget.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
-import 'package:ente_auth/utils/dialog_util.dart';
-import 'package:flutter/cupertino.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
Future<void> importSuccessDialog(BuildContext context, int count) async {
- final DialogWidget dialog = DialogWidget(
- title: context.l10n.importSuccessTitle,
- body: context.l10n.importSuccessDesc(count),
- buttons: [
- ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: context.l10n.ok,
- isInAlert: true,
- ),
- ],
- );
- await showConfettiDialog(
+ final l10n = context.l10n;
+ await showBottomSheetComponent<void>(
context: context,
- dialogBuilder: (BuildContext context) {
- return dialog;
- },
+ builder: (sheetContext) => Semantics(
+ identifier: 'auth_import_success',
+ child: BottomSheetComponent(
+ title: l10n.importSuccessTitle,
+ message: l10n.importSuccessDesc(count),
+ closeTooltip: l10n.close,
+ actions: [
+ ButtonComponent(
+ label: l10n.ok,
+ shouldSurfaceExecutionStates: false,
+ onTap: () => Navigator.of(sheetContext).pop(),
+ ),
+ ],
+ ),
+ ),
);
}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/lastpass_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/lastpass_import.dart
index 59d30abc75..6b414675ae 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/lastpass_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/lastpass_import.dart
@@ -1,80 +1,32 @@
-import 'dart:async';
import 'dart:convert';
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/code.dart';
-import 'package:ente_auth/services/authenticator_service.dart';
-import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/dialog_widget.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/settings/data/import/import_file_cleanup.dart';
-import 'package:ente_auth/ui/settings/data/import/import_success.dart';
-import 'package:ente_auth/utils/dialog_util.dart';
-import 'package:file_picker/file_picker.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
Future<void> showLastpassImportInstruction(BuildContext context) async {
final l10n = context.l10n;
- final result = await showDialogWidget(
+ await showFileImportInstruction(
context: context,
- title: l10n.importFromApp("LastPass"),
+ title: "LastPass Authenticator",
body: l10n.importLastpassGuide,
- buttons: [
- ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: l10n.importSelectJsonFile,
- isInAlert: true,
- buttonSize: ButtonSize.large,
- buttonAction: ButtonAction.first,
- ),
- ButtonWidget(
- buttonType: ButtonType.secondary,
- labelText: context.l10n.cancel,
- buttonSize: ButtonSize.large,
- isInAlert: true,
- buttonAction: ButtonAction.second,
- ),
- ],
+ actionLabel: l10n.importSelectJsonFile,
+ semanticsIdentifier: 'auth_import_instruction_lastpass',
+ onImport: () => _pickLastpassJsonFile(context),
);
- if (result?.action != null && result!.action != ButtonAction.cancel) {
- if (!context.mounted) return;
- if (result.action == ButtonAction.first) {
- await _pickLastpassJsonFile(context);
- }
- }
}
Future<void> _pickLastpassJsonFile(BuildContext context) async {
- final l10n = context.l10n;
- FilePickerResult? result = await FilePicker.platform.pickFiles();
- if (result == null) {
- return;
- }
- if (!context.mounted) return;
- final progressDialog = createProgressDialog(context, l10n.pleaseWait);
- await progressDialog.show();
- try {
- if (!context.mounted) return;
- String path = result.files.single.path!;
- int? count = await _processLastpassExportFile(context, path);
- await progressDialog.hide();
- if (count != null) {
- if (!context.mounted) return;
- await importSuccessDialog(context, count);
- }
- } catch (e, s) {
- Logger('LastPassImport').severe('exception while processing import', e, s);
- await progressDialog.hide();
- if (!context.mounted) return;
- await showErrorDialog(
- context,
- context.l10n.sorry,
- "${context.l10n.importFailureDesc}\n Error: ${e.toString()}",
- );
- }
+ await pickAndProcessImportFile(
+ context: context,
+ logger: Logger('LastPassImport'),
+ logMessage: 'Exception while processing LastPass import',
+ process: (path, _) => _processLastpassExportFile(context, path),
+ );
}
Future<int?> _processLastpassExportFile(
@@ -84,7 +36,7 @@ Future<int?> _processLastpassExportFile(
final jsonString = await readPickedImportFileAsString(path);
Map<String, dynamic> jsonData = json.decode(jsonString);
List<dynamic> accounts = jsonData["accounts"];
- final parsedCodes = [];
+ final parsedCodes = <Code>[];
for (var item in accounts) {
var algorithm = item['algorithm'];
var timer = item['timeStep'];
@@ -99,10 +51,5 @@ Future<int?> _processLastpassExportFile(
parsedCodes.add(Code.fromOTPAuthUrl(otpUrl));
}
- for (final code in parsedCodes) {
- await CodeStore.instance.addCode(code, shouldSync: false);
- }
- unawaited(AuthenticatorService.instance.onlineSync());
- int count = parsedCodes.length;
- return count;
+ return saveImportedCodes(parsedCodes);
}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/plain_text_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/plain_text_import.dart
index eb95f889f2..1d68d773f4 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/plain_text_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/plain_text_import.dart
@@ -1,21 +1,11 @@
-import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:ente_auth/ente_theme_data.dart';
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/models/code.dart';
-import 'package:ente_auth/services/authenticator_service.dart';
-import 'package:ente_auth/store/code_store.dart';
import 'package:ente_auth/ui/settings/data/import/import_file_cleanup.dart';
-import 'package:ente_auth/ui/settings/data/import/import_success.dart';
-import 'package:ente_auth/utils/dialog_util.dart';
-import 'package:file_picker/file_picker.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
+import 'package:ente_auth/ui/settings/data/import/plain_text_import_parser.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
-final _logger = Logger('PlainText');
-
class PlainTextImport extends StatelessWidget {
const PlainTextImport({super.key});
@@ -24,25 +14,38 @@ class PlainTextImport extends StatelessWidget {
final l10n = context.l10n;
return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text(l10n.importInstruction),
- const SizedBox(height: 20),
+ Text(
+ l10n.importInstruction,
+ style: TextStyles.body.copyWith(
+ color: context.componentColors.textLight,
+ ),
+ ),
+ const SizedBox(height: Spacing.lg),
Container(
- color: Theme.of(context).colorScheme.gNavBackgroundColor,
- child: Padding(
- padding: const EdgeInsets.all(8),
+ decoration: BoxDecoration(
+ color: context.componentColors.fillLight,
+ borderRadius: BorderRadius.circular(Radii.md),
+ ),
+ child: const Padding(
+ padding: EdgeInsets.all(Spacing.md),
child: Text(
"otpauth://totp/provider.com:[email protected]?secret=YOUR_SECRET",
style: TextStyle(
- fontFeatures: const [FontFeature.tabularFigures()],
- fontFamily: Platform.isIOS ? "Courier" : "monospace",
+ fontFeatures: [FontFeature.tabularFigures()],
fontSize: 13,
),
),
),
),
- const SizedBox(height: 20),
- Text(l10n.importCodeDelimiterInfo),
+ const SizedBox(height: Spacing.lg),
+ Text(
+ l10n.importCodeDelimiterInfo,
+ style: TextStyles.body.copyWith(
+ color: context.componentColors.textLight,
+ ),
+ ),
],
);
}
@@ -50,93 +53,25 @@ class PlainTextImport extends StatelessWidget {
Future<void> showImportInstructionDialog(BuildContext context) async {
final l10n = context.l10n;
- final AlertDialog alert = AlertDialog(
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
- title: Text(
- l10n.importCodes,
- style: Theme.of(context).textTheme.titleLarge,
- ),
- content: const SingleChildScrollView(child: PlainTextImport()),
- actions: [
- TextButton(
- child: Text(l10n.cancel, style: const TextStyle(color: Colors.red)),
- onPressed: () {
- Navigator.of(context, rootNavigator: true).pop('dialog');
- },
- ),
- TextButton(
- child: Text(l10n.selectFile),
- onPressed: () {
- Navigator.of(context, rootNavigator: true).pop('dialog');
- _pickImportFile(context);
- },
- ),
- ],
- );
-
- return showDialog(
+ await showFileImportInstruction(
context: context,
- builder: (BuildContext context) {
- return alert;
- },
- barrierColor: Colors.black12,
+ title: l10n.importCodes,
+ actionLabel: l10n.selectFile,
+ semanticsIdentifier: 'auth_import_instruction_plain_text',
+ content: const PlainTextImport(),
+ onImport: () => _pickImportFile(context),
);
}
Future<void> _pickImportFile(BuildContext context) async {
- final l10n = context.l10n;
- FilePickerResult? result = await FilePicker.platform.pickFiles();
- if (result == null) {
- return;
- }
- if (!context.mounted) return;
- final progressDialog = createProgressDialog(context, l10n.pleaseWait);
- await progressDialog.show();
- try {
- if (!context.mounted) return;
- final parsedCodes = [];
- final codes = await readPickedImportFileAsString(result.files.single.path!);
-
- if (codes.startsWith('otpauth://')) {
- List<String> splitCodes = codes.split(",");
- if (splitCodes.length == 1) {
- splitCodes = const LineSplitter().convert(codes);
- }
- for (final code in splitCodes) {
- try {
- parsedCodes.add(Code.fromOTPAuthUrl(code));
- } catch (e) {
- Logger('PlainText').severe("Could not parse code", e);
- }
- }
- } else {
- final decodedCodes = jsonDecode(codes);
- List<Map> splitCodes = List.from(decodedCodes["items"]);
-
- for (final code in splitCodes) {
- try {
- parsedCodes.add(Code.fromExportJson(code));
- } catch (e) {
- _logger.severe("Could not parse code", e);
- }
- }
- }
-
- for (final code in parsedCodes) {
- await CodeStore.instance.addCode(code, shouldSync: false);
- }
- unawaited(AuthenticatorService.instance.onlineSync());
- await progressDialog.hide();
- if (!context.mounted) return;
- await importSuccessDialog(context, parsedCodes.length);
- } catch (e) {
- await progressDialog.hide();
- if (!context.mounted) return;
- if (!context.mounted) return;
- await showErrorDialog(
- context,
- context.l10n.sorry,
- context.l10n.importFailureDesc,
- );
- }
+ await pickAndProcessImportFile(
+ context: context,
+ logger: Logger('PlainTextImport'),
+ logMessage: 'Failed to import plain-text codes',
+ errorMessage: (context, _) => context.l10n.importFailureDesc,
+ process: (path, _) async {
+ final contents = await readPickedImportFileAsString(path);
+ return saveImportedCodes(parsePlainTextImport(contents));
+ },
+ );
}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/plain_text_import_parser.dart b/mobile/apps/auth/lib/ui/settings/data/import/plain_text_import_parser.dart
new file mode 100644
index 0000000000..3beffa9d2a
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/data/import/plain_text_import_parser.dart
@@ -0,0 +1,47 @@
+import 'dart:convert';
+
+import 'package:ente_auth/models/code.dart';
+import 'package:logging/logging.dart';
+
+final _logger = Logger('PlainTextImportParser');
+
+List<Code> parsePlainTextImport(String content) {
+ final trimmedContent = content.trim();
+ if (trimmedContent.startsWith('otpauth://')) {
+ return _parseOTPAuthCodes(trimmedContent);
+ }
+
+ final decoded = jsonDecode(trimmedContent);
+ if (decoded is! Map || decoded['items'] is! List) {
+ throw const FormatException('Expected an export object containing items');
+ }
+
+ return _parseEntries(
+ (decoded['items'] as List).whereType<Map>(),
+ Code.fromExportJson,
+ );
+}
+
+List<Code> _parseOTPAuthCodes(String content) {
+ final entries = content.contains(',')
+ ? content.split(',')
+ : const LineSplitter().convert(content);
+ return _parseEntries(
+ entries.map((entry) => entry.trim()).where((entry) => entry.isNotEmpty),
+ Code.fromOTPAuthUrl,
+ );
+}
+
+List<Code> _parseEntries<T>(Iterable<T> entries, Code Function(T entry) parse) {
+ final codes = <Code>[];
+ for (final entry in entries) {
+ try {
+ codes.add(parse(entry));
+ } catch (error, stackTrace) {
+ // Match the import UI's existing behavior: preserve valid entries when
+ // one entry in a multi-code export is malformed.
+ _logger.severe('Could not parse import entry', error, stackTrace);
+ }
+ }
+ return codes;
+}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/proton_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/proton_import.dart
index c2e080630d..9c05874395 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/proton_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/proton_import.dart
@@ -1,17 +1,9 @@
-import 'dart:async';
-
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/services/authenticator_service.dart';
-import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/dialog_widget.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/settings/data/import/import_file_cleanup.dart';
-import 'package:ente_auth/ui/settings/data/import/import_success.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
import 'package:ente_auth/ui/settings/data/import/proton_import_parser.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_ui/components/progress_dialog.dart';
-import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
@@ -19,67 +11,26 @@ import 'package:logging/logging.dart';
Future<void> showProtonImportInstruction(BuildContext context) async {
final l10n = context.l10n;
- final result = await showDialogWidget(
+ await showFileImportInstruction(
context: context,
- title: l10n.importFromApp("Proton Authenticator"),
+ title: "Proton Authenticator",
body: l10n.importProtonAuthGuide,
- buttons: [
- ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: l10n.importSelectJsonFile,
- isInAlert: true,
- buttonSize: ButtonSize.large,
- buttonAction: ButtonAction.first,
- ),
- ButtonWidget(
- buttonType: ButtonType.secondary,
- labelText: context.l10n.cancel,
- buttonSize: ButtonSize.large,
- isInAlert: true,
- buttonAction: ButtonAction.second,
- ),
- ],
+ actionLabel: l10n.importSelectJsonFile,
+ semanticsIdentifier: 'auth_import_instruction_proton',
+ onImport: () => _pickProtonJsonFile(context),
);
- if (result?.action != null && result!.action != ButtonAction.cancel) {
- if (!context.mounted) return;
- if (result.action == ButtonAction.first) {
- await _pickProtonJsonFile(context);
- }
- }
}
Future<void> _pickProtonJsonFile(BuildContext context) async {
- final l10n = context.l10n;
- final result = await FilePicker.platform.pickFiles(
- dialogTitle: l10n.importSelectJsonFile,
+ await pickAndProcessImportFile(
+ context: context,
+ dialogTitle: context.l10n.importSelectJsonFile,
+ showProgressBeforeProcessing: false,
+ logger: Logger('ProtonImport'),
+ logMessage: 'Exception while processing Proton import',
+ process: (path, progressDialog) =>
+ _processProtonExportFile(context, path, progressDialog),
);
- if (result == null) {
- return;
- }
-
- if (!context.mounted) return;
- final progressDialog = createProgressDialog(context, l10n.pleaseWait);
- try {
- if (!context.mounted) return;
- final path = result.files.single.path!;
- final count = await _processProtonExportFile(context, path, progressDialog);
- await progressDialog.hide();
- if (count != null) {
- if (!context.mounted) return;
- await importSuccessDialog(context, count);
- }
- } catch (e, s) {
- Logger(
- 'ProtonImport',
- ).severe('Exception while processing Proton import', e, s);
- await progressDialog.hide();
- if (!context.mounted) return;
- await showErrorDialog(
- context,
- context.l10n.sorry,
- "${context.l10n.importFailureDesc}\n Error: ${e.toString()}",
- );
- }
}
Future<int?> _processProtonExportFile(
@@ -108,7 +59,10 @@ Future<int?> _processProtonExportFile(
if (!context.mounted) return null;
while (true) {
if (!context.mounted) return null;
- final password = await _promptForProtonExportPassword(context);
+ final password = await promptForImportPassword(
+ context,
+ title: context.l10n.passwordForDecryptingExport,
+ );
if (password == null) {
return null;
}
@@ -148,12 +102,7 @@ Future<int?> _processProtonExportFile(
}
final parsedCodes = parseProtonExport(decodedJson);
- for (final code in parsedCodes) {
- await CodeStore.instance.addCode(code, shouldSync: false);
- }
-
- unawaited(AuthenticatorService.instance.onlineSync());
- return parsedCodes.length;
+ return saveImportedCodes(parsedCodes);
}
Map<String, String> _decryptProtonExportInBackground(
@@ -175,17 +124,3 @@ Map<String, String> _decryptProtonExportInBackground(
return {'status': 'incorrect_password'};
}
}
-
-Future<String?> _promptForProtonExportPassword(BuildContext context) async {
- String? password;
- await showTextInputDialog(
- context,
- title: context.l10n.passwordForDecryptingExport,
- submitButtonLabel: context.l10n.submit,
- isPasswordInput: true,
- onSubmit: (value) async {
- password = value;
- },
- );
- return password;
-}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/raivo_plain_text_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/raivo_plain_text_import.dart
index 544d1c2117..3cb4cbc014 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/raivo_plain_text_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/raivo_plain_text_import.dart
@@ -1,80 +1,33 @@
-import 'dart:async';
import 'dart:convert';
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/code.dart';
-import 'package:ente_auth/services/authenticator_service.dart';
-import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/dialog_widget.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/settings/data/import/import_file_cleanup.dart';
-import 'package:ente_auth/ui/settings/data/import/import_success.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
import 'package:ente_auth/utils/dialog_util.dart';
-import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
Future<void> showRaivoImportInstruction(BuildContext context) async {
final l10n = context.l10n;
- final result = await showDialogWidget(
+ await showFileImportInstruction(
context: context,
- title: l10n.importFromApp("Raivo OTP"),
+ title: "Raivo OTP",
body: l10n.importRaivoGuide,
- buttons: [
- ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: l10n.importSelectJsonFile,
- isInAlert: true,
- buttonSize: ButtonSize.large,
- buttonAction: ButtonAction.first,
- ),
- ButtonWidget(
- buttonType: ButtonType.secondary,
- labelText: context.l10n.cancel,
- buttonSize: ButtonSize.large,
- isInAlert: true,
- buttonAction: ButtonAction.second,
- ),
- ],
+ actionLabel: l10n.importSelectJsonFile,
+ semanticsIdentifier: 'auth_import_instruction_raivo',
+ onImport: () => _pickRaivoJsonFile(context),
);
- if (result?.action != null && result!.action != ButtonAction.cancel) {
- if (!context.mounted) return;
- if (result.action == ButtonAction.first) {
- await _pickRaivoJsonFile(context);
- } else {}
- }
}
Future<void> _pickRaivoJsonFile(BuildContext context) async {
- final l10n = context.l10n;
- FilePickerResult? result = await FilePicker.platform.pickFiles();
- if (result == null) {
- return;
- }
- if (!context.mounted) return;
- final progressDialog = createProgressDialog(context, l10n.pleaseWait);
- await progressDialog.show();
- try {
- if (!context.mounted) return;
- String path = result.files.single.path!;
- int? count = await _processRaivoExportFile(context, path);
- await progressDialog.hide();
- if (count != null) {
- if (!context.mounted) return;
- await importSuccessDialog(context, count);
- }
- } catch (e, s) {
- Logger("RaivoImport").severe('Failed to import', e, s);
- await progressDialog.hide();
- if (!context.mounted) return;
- await showErrorDialog(
- context,
- context.l10n.sorry,
- "${context.l10n.importFailureDesc}\n Error: ${e.toString()}",
- );
- }
+ await pickAndProcessImportFile(
+ context: context,
+ logger: Logger('RaivoImport'),
+ logMessage: 'Failed to import Raivo export',
+ process: (path, _) => _processRaivoExportFile(context, path),
+ );
}
Future<int?> _processRaivoExportFile(BuildContext context, String path) async {
@@ -91,7 +44,7 @@ Future<int?> _processRaivoExportFile(BuildContext context, String path) async {
}
final jsonString = await readPickedImportFileAsString(path);
List<dynamic> jsonArray = jsonDecode(jsonString);
- final parsedCodes = [];
+ final parsedCodes = <Code>[];
for (var item in jsonArray) {
var kind = item['kind'];
var algorithm = item['algorithm'];
@@ -102,25 +55,22 @@ Future<int?> _processRaivoExportFile(BuildContext context, String path) async {
var account = item['account'];
var counter = item['counter'];
- // Build the OTP URL
- String otpUrl;
-
- if (kind.toLowerCase() == 'totp') {
- otpUrl =
- 'otpauth://$kind/$issuer:$account?secret=$secret&issuer=$issuer&algorithm=$algorithm&digits=$digits&period=$timer';
- } else if (kind.toLowerCase() == 'hotp') {
- otpUrl =
- 'otpauth://$kind/$issuer:$account?secret=$secret&issuer=$issuer&algorithm=$algorithm&digits=$digits&counter=$counter';
- } else {
- throw Exception('Invalid OTP type $kind');
- }
- parsedCodes.add(Code.fromOTPAuthUrl(otpUrl));
+ parsedCodes.add(
+ Code.fromOTPAuthUrl(
+ buildImportOtpUri(
+ kind: kind,
+ issuer: issuer,
+ account: account,
+ secret: secret,
+ algorithm: algorithm,
+ digits: digits,
+ period: timer,
+ counter: counter,
+ allowSteam: false,
+ ),
+ ),
+ );
}
- for (final code in parsedCodes) {
- await CodeStore.instance.addCode(code, shouldSync: false);
- }
- unawaited(AuthenticatorService.instance.onlineSync());
- int count = parsedCodes.length;
- return count;
+ return saveImportedCodes(parsedCodes);
}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/two_fas_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/two_fas_import.dart
index a17aff831a..adba2a59a0 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/two_fas_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/two_fas_import.dart
@@ -1,20 +1,13 @@
-import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/models/code_display.dart';
-import 'package:ente_auth/services/authenticator_service.dart';
-import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/dialog_widget.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/settings/data/import/import_file_cleanup.dart';
-import 'package:ente_auth/ui/settings/data/import/import_success.dart';
+import 'package:ente_auth/ui/settings/data/import/import_flow.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_ui/components/progress_dialog.dart';
-import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
@@ -22,68 +15,26 @@ import 'package:pointycastle/export.dart';
Future<void> show2FasImportInstruction(BuildContext context) async {
final l10n = context.l10n;
- final result = await showDialogWidget(
+ await showFileImportInstruction(
context: context,
- title: l10n.importFromApp("2FAS Authenticator"),
+ title: "2FAS Authenticator",
body: l10n.import2FasGuide,
- buttons: [
- ButtonWidget(
- buttonType: ButtonType.primary,
- labelText: l10n.importSelectAppExport("2FAS Authenticator"),
- isInAlert: true,
- buttonSize: ButtonSize.large,
- buttonAction: ButtonAction.first,
- ),
- ButtonWidget(
- buttonType: ButtonType.secondary,
- labelText: context.l10n.cancel,
- buttonSize: ButtonSize.large,
- isInAlert: true,
- buttonAction: ButtonAction.second,
- ),
- ],
+ actionLabel: l10n.importSelectAppExport("2FAS Authenticator"),
+ semanticsIdentifier: 'auth_import_instruction_two_fas',
+ onImport: () => _pick2FasFile(context),
);
- if (result?.action != null && result!.action != ButtonAction.cancel) {
- if (!context.mounted) return;
- if (result.action == ButtonAction.first) {
- await _pick2FasFile(context);
- } else {}
- }
}
Future<void> _pick2FasFile(BuildContext context) async {
- final l10n = context.l10n;
- FilePickerResult? result = await FilePicker.platform.pickFiles(
- dialogTitle: l10n.importSelectJsonFile,
- );
- if (result == null) {
- return;
- }
- if (!context.mounted) return;
- final ProgressDialog progressDialog = createProgressDialog(
- context,
- l10n.pleaseWait,
+ await pickAndProcessImportFile(
+ context: context,
+ dialogTitle: context.l10n.importSelectJsonFile,
+ showProgressBeforeProcessing: false,
+ logger: Logger('2FASImport'),
+ logMessage: 'Exception while processing 2FAS import',
+ process: (path, progressDialog) =>
+ _process2FasExportFile(context, path, progressDialog),
);
-
- try {
- if (!context.mounted) return;
- String path = result.files.single.path!;
- int? count = await _process2FasExportFile(context, path, progressDialog);
- await progressDialog.hide();
- if (count != null) {
- if (!context.mounted) return;
- await importSuccessDialog(context, count);
- }
- } catch (e, s) {
- Logger('2FASImport').severe('exception while processing import', e, s);
- await progressDialog.hide();
- if (!context.mounted) return;
- await showErrorDialog(
- context,
- context.l10n.sorry,
- "${context.l10n.importFailureDesc}\n Error: ${e.toString()}",
- );
- }
}
Future<int?> _process2FasExportFile(
@@ -124,21 +75,16 @@ Future<int?> _process2FasExportFile(
if (!context.mounted) return null;
String? password;
try {
- await showTextInputDialog(
+ password = await promptForImportPassword(
context,
title: context.l10n.enterPasswordToDecrypt2FASBackup,
- submitButtonLabel: context.l10n.submit,
- isPasswordInput: true,
- onSubmit: (value) async {
- password = value;
- },
);
if (password == null) {
await dialog.hide();
return null;
}
await dialog.show();
- final content = decrypt2FasVault(decodedJson, password: password!);
+ final content = decrypt2FasVault(decodedJson, password: password);
decodedServices = jsonDecode(content);
} catch (e, s) {
Logger("2FASImport").warning("exception while decrypting backup", e, s);
@@ -156,7 +102,7 @@ Future<int?> _process2FasExportFile(
} else {
await dialog.show();
}
- final parsedCodes = [];
+ final parsedCodes = <Code>[];
for (var item in decodedServices) {
var kind = item['otp']['tokenType'];
var account = item['otp']['account'] ?? '';
@@ -171,19 +117,18 @@ Future<int?> _process2FasExportFile(
var digits = item['otp']['digits'];
var counter = item['otp']['counter'];
- // Build the OTP URL
- String otpUrl;
-
- if (kind.toLowerCase() == 'totp' || kind.toLowerCase() == 'steam') {
- otpUrl =
- 'otpauth://$kind/$issuer:$account?secret=$secret&issuer=$issuer&algorithm=$algorithm&digits=$digits&period=$timer';
- } else if (kind.toLowerCase() == 'hotp') {
- otpUrl =
- 'otpauth://$kind/$issuer:$account?secret=$secret&issuer=$issuer&algorithm=$algorithm&digits=$digits&counter=$counter';
- } else {
- throw Exception('Invalid OTP type ${kind.toLowerCase()}');
- }
- Code code = Code.fromOTPAuthUrl(otpUrl);
+ Code code = Code.fromOTPAuthUrl(
+ buildImportOtpUri(
+ kind: kind,
+ issuer: issuer,
+ account: account,
+ secret: secret,
+ algorithm: algorithm,
+ digits: digits,
+ period: timer,
+ counter: counter,
+ ),
+ );
if (groupID != null && groupIdToName.containsKey(groupID)) {
code = code.copyWith(
display: CodeDisplay(tags: [groupIdToName[groupID]]),
@@ -192,12 +137,7 @@ Future<int?> _process2FasExportFile(
parsedCodes.add(code);
}
- for (final code in parsedCodes) {
- await CodeStore.instance.addCode(code, shouldSync: false);
- }
- unawaited(AuthenticatorService.instance.onlineSync());
- int count = parsedCodes.length;
- return count;
+ return saveImportedCodes(parsedCodes);
}
String decrypt2FasVault(dynamic data, {required String password}) {
diff --git a/mobile/apps/auth/lib/ui/settings/data/import_page.dart b/mobile/apps/auth/lib/ui/settings/data/import_page.dart
index e54923c7e7..b2a62437d3 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import_page.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import_page.dart
@@ -1,12 +1,8 @@
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/divider_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/components/title_bar_title_widget.dart';
-import 'package:ente_auth/ui/components/title_bar_widget.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_item.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
import 'package:ente_auth/ui/settings/data/import/import_service.dart';
-import 'package:ente_ui/components/constrained_custom_scroll_view.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
enum ImportType {
@@ -65,59 +61,28 @@ class ImportCodePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
- return Material(
- color: Colors.transparent,
- child: Scaffold(
- body: ConstrainedCustomScrollView(
- slivers: <Widget>[
- TitleBarWidget(
- flexibleSpaceTitle: TitleBarTitleWidget(
- title: context.l10n.importCodes,
+ return AuthSettingsPageScaffold(
+ title: context.l10n.importCodes,
+ children: [
+ MenuGroupComponent(
+ showDividers: true,
+ items: [
+ for (final type in importOptions)
+ AuthSettingsItem(
+ title: getTitle(context, type),
+ semanticsIdentifier: 'auth_import_${type.name}',
+ onTap: () => _import(context, type),
),
- flexibleSpaceCaption: "Import source",
- actionIcons: const [],
- ),
- SliverList(
- delegate: SliverChildBuilderDelegate((
- delegateBuildContext,
- index,
- ) {
- final type = importOptions[index];
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16.0),
- child: Column(
- children: [
- if (index == 0) const SizedBox(height: 24),
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: getTitle(context, type),
- ),
- alignCaptionedTextToLeft: true,
- menuItemColor: getEnteColorScheme(context).fillFaint,
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- isBottomBorderRadiusRemoved:
- index != importOptions.length - 1,
- isTopBorderRadiusRemoved: index != 0,
- onTap: () async {
- await ImportService().initiateImport(context, type);
- // routeToPage(context, ImportCodePage());
- // _showImportInstructionDialog(context);
- },
- ),
- if (index != importOptions.length - 1)
- DividerWidget(
- dividerType: DividerType.menu,
- bgColor: getEnteColorScheme(context).fillFaint,
- ),
- ],
- ),
- );
- }, childCount: importOptions.length),
- ),
],
),
- ),
+ ],
);
}
+
+ Future<void> _import(BuildContext context, ImportType type) async {
+ final completed = await ImportService().initiateImport(context, type);
+ if (completed && context.mounted) {
+ Navigator.of(context).pop(true);
+ }
+ }
}
diff --git a/mobile/apps/auth/lib/ui/settings/data/local_backup_settings_page.dart b/mobile/apps/auth/lib/ui/settings/data/local_backup_settings_page.dart
index 0924cc1b55..e244e9e626 100644
--- a/mobile/apps/auth/lib/ui/settings/data/local_backup_settings_page.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/local_backup_settings_page.dart
@@ -1,12 +1,8 @@
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/components/title_bar_title_widget.dart';
-import 'package:ente_auth/ui/components/title_bar_widget.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_item.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
import 'package:ente_auth/ui/settings/data/local_backup/local_backup_experience.dart';
-import 'package:ente_ui/components/constrained_custom_scroll_view.dart';
-import 'package:ente_ui/components/toggle_switch_widget.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
@@ -18,272 +14,134 @@ class LocalBackupSettingsPage extends StatelessWidget {
return LocalBackupExperience(
builder: (context, controller) {
final l10n = context.l10n;
- final textTheme = getEnteTextTheme(context);
- final colorScheme = getEnteColorScheme(context);
- return _LocalBackupVariantShell(
- controller: controller,
- title: l10n.localBackupSettingsTitle,
- body: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- const SizedBox(height: 24),
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: l10n.enableAutomaticBackups,
- ),
- alignCaptionedTextToLeft: true,
- singleBorderRadius: 12,
- menuItemColor: colorScheme.fillFaint,
- trailingWidget: ToggleSwitchWidget(
- value: () => controller.isBackupEnabled,
- onChanged: () async {
- await controller.toggleBackup(
- !controller.isBackupEnabled,
- );
- },
- ),
- ),
- Padding(
- padding: const EdgeInsets.only(top: 12, left: 12, right: 12),
- child: Text(
- l10n.localBackupDailyManualCopy,
- style: textTheme.miniFaint,
- ),
- ),
- const SizedBox(height: 28),
- AnimatedSwitcher(
- duration: const Duration(milliseconds: 250),
- switchInCurve: Curves.easeOut,
- switchOutCurve: Curves.easeIn,
- child: controller.isBackupEnabled
- ? Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- FutureBuilder<bool>(
- future: controller.hasPasswordConfigured(),
- builder: (context, snapshot) {
- final hasPassword = snapshot.data ?? false;
- final tileTitle = hasPassword
- ? l10n.updateBackupPassword
- : l10n.setBackupPassword;
- return MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: tileTitle,
- ),
- singleBorderRadius: 12,
- alignCaptionedTextToLeft: true,
- menuItemColor: colorScheme.fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- await controller.updatePassword(context);
- },
- );
- },
- ),
- const SizedBox(height: 16),
- Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: l10n.setBackupFolder,
- ),
- alignCaptionedTextToLeft: true,
- singleBorderRadius: 12,
- menuItemColor: colorScheme.fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- await controller.changeLocation();
- },
- ),
- Padding(
- padding: const EdgeInsets.only(
- top: 12,
- left: 12,
- right: 12,
- ),
- child: _LocationPreview(
- controller: controller,
- ),
- ),
- ],
- ),
- const SizedBox(height: 12),
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: l10n.createBackupNow,
- ),
- alignCaptionedTextToLeft: true,
- singleBorderRadius: 12,
- menuItemColor: colorScheme.fillFaint,
- trailingWidget: controller.isManualBackupRunning
- ? const SizedBox(
- width: 20,
- height: 20,
- child: CircularProgressIndicator(
- strokeWidth: 2,
- ),
- )
- : const Icon(
- Icons.chevron_right_outlined,
- color: Colors.grey,
- ),
- onTap: () async {
- if (controller.isManualBackupRunning) return;
- await controller.runManualBackup();
- },
- ),
- ],
- )
- : (kDebugMode
- ? Padding(
- padding: const EdgeInsets.only(top: 12),
- child: Column(
- children: [
- _BackupButton(
- onPressed: controller.resetBackupLocation,
- label: l10n.clearBackupFolder,
- colorScheme: colorScheme,
- textTheme: textTheme,
- ),
- const SizedBox(height: 10),
- _BackupButton(
- onPressed: controller.clearBackupPassword,
- label: l10n.clearBackupPassword,
- colorScheme: colorScheme,
- textTheme: textTheme,
- ),
- ],
- ),
- )
- : const SizedBox.shrink()),
- ),
- ],
- ),
+ return Semantics(
+ identifier: 'auth_local_backup_settings',
+ child: AuthSettingsPageScaffold(
+ title: l10n.localBackupSettingsTitle,
+ children: controller.hasLoaded
+ ? _settings(context, controller)
+ : const [
+ Padding(
+ padding: EdgeInsets.all(Spacing.xxl),
+ child: Center(child: CircularProgressIndicator()),
+ ),
+ ],
),
);
},
);
}
-}
-
-class _LocalBackupVariantShell extends StatelessWidget {
- const _LocalBackupVariantShell({
- required this.controller,
- required this.title,
- required this.body,
- });
- final LocalBackupExperienceController controller;
- final String title;
- final Widget body;
-
- @override
- Widget build(BuildContext context) {
- return Material(
- color: Colors.transparent,
- child: Scaffold(
- body: Stack(
- children: [
- AnimatedSwitcher(
- duration: const Duration(milliseconds: 200),
- child: controller.hasLoaded
- ? ConstrainedCustomScrollView(
- slivers: <Widget>[
- TitleBarWidget(
- flexibleSpaceTitle: TitleBarTitleWidget(title: title),
- actionIcons: const [],
- ),
- SliverList(
- delegate: SliverChildBuilderDelegate((
- context,
- index,
- ) {
- return body;
- }, childCount: 1),
- ),
- ],
- )
- : const _LocalBackupLoading(),
+ List<Widget> _settings(
+ BuildContext context,
+ LocalBackupExperienceController controller,
+ ) {
+ final l10n = context.l10n;
+ return [
+ MenuGroupComponent(
+ items: [
+ AuthSettingsItem(
+ title: l10n.enableAutomaticBackups,
+ showChevron: false,
+ trailing: Semantics(
+ identifier: 'auth_local_backup_toggle',
+ child: ToggleSwitchComponent.async(
+ value: () => controller.isBackupEnabled,
+ onChanged: () =>
+ controller.toggleBackup(!controller.isBackupEnabled),
+ ),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: Spacing.sm),
+ _Description(l10n.localBackupDailyManualCopy),
+ if (controller.isBackupEnabled) ...[
+ const SizedBox(height: Spacing.xl),
+ MenuGroupComponent(
+ showDividers: true,
+ dividerPadding: const EdgeInsets.only(left: Spacing.lg),
+ items: [
+ FutureBuilder<bool>(
+ future: controller.hasPasswordConfigured(),
+ builder: (context, snapshot) {
+ final title = snapshot.data == true
+ ? l10n.updateBackupPassword
+ : l10n.setBackupPassword;
+ return AuthSettingsItem(
+ title: title,
+ semanticsIdentifier: 'auth_local_backup_password',
+ onTap: () => controller.updatePassword(context),
+ );
+ },
+ ),
+ AuthSettingsItem(
+ title: l10n.setBackupFolder,
+ subtitle: _locationDescription(context, controller),
+ semanticsIdentifier: 'auth_local_backup_folder',
+ onTap: controller.changeLocation,
+ ),
+ AuthSettingsItem(
+ title: l10n.createBackupNow,
+ semanticsIdentifier: 'auth_local_backup_create_now',
+ showOnlyLoadingState: true,
+ onTap: controller.isManualBackupRunning
+ ? null
+ : controller.runManualBackup,
),
],
),
- ),
- );
- }
-}
-
-class _LocalBackupLoading extends StatelessWidget {
- const _LocalBackupLoading();
-
- @override
- Widget build(BuildContext context) {
- return const Center(child: CircularProgressIndicator());
+ ] else if (kDebugMode) ...[
+ const SizedBox(height: Spacing.xl),
+ MenuGroupComponent(
+ showDividers: true,
+ dividerPadding: const EdgeInsets.only(left: Spacing.lg),
+ items: [
+ AuthSettingsItem(
+ title: l10n.clearBackupFolder,
+ showChevron: false,
+ showOnlyLoadingState: true,
+ onTap: controller.resetBackupLocation,
+ ),
+ AuthSettingsItem(
+ title: l10n.clearBackupPassword,
+ showChevron: false,
+ showOnlyLoadingState: true,
+ onTap: controller.clearBackupPassword,
+ ),
+ ],
+ ),
+ ],
+ ];
}
-}
-class _LocationPreview extends StatelessWidget {
- const _LocationPreview({required this.controller});
-
- final LocalBackupExperienceController controller;
-
- @override
- Widget build(BuildContext context) {
- final textTheme = getEnteTextTheme(context);
+ String _locationDescription(
+ BuildContext context,
+ LocalBackupExperienceController controller,
+ ) {
final l10n = context.l10n;
- final path = controller.backupPath;
- final treeUri = controller.backupTreeUri;
- final muted = textTheme.miniFaint.copyWith(color: Colors.grey);
-
- if (path != null) {
- return Text(
- '${l10n.backupFolderLabel} ${controller.simplifyPath(path)}',
- style: textTheme.miniFaint,
- );
- }
- if (treeUri != null) {
- return Text(
- '${l10n.backupFolderLabel} ${controller.simplifyPath(treeUri)}',
- style: textTheme.miniFaint,
- );
+ final location = controller.backupPath ?? controller.backupTreeUri;
+ if (location == null || location.isEmpty) {
+ return l10n.selectBackupFolder;
}
-
- return Text(l10n.selectBackupFolder, style: muted);
+ return '${l10n.backupFolderLabel} ${controller.simplifyPath(location)}';
}
}
-class _BackupButton extends StatelessWidget {
- const _BackupButton({
- required this.onPressed,
- required this.label,
- required this.colorScheme,
- required this.textTheme,
- });
+class _Description extends StatelessWidget {
+ const _Description(this.text);
- final Future<void> Function() onPressed;
- final String label;
- final dynamic colorScheme;
- final dynamic textTheme;
+ final String text;
@override
Widget build(BuildContext context) {
- return SizedBox(
- width: double.infinity,
- child: TextButton(
- onPressed: onPressed,
- style: TextButton.styleFrom(
- foregroundColor: colorScheme.textBase,
- backgroundColor: colorScheme.fillFaint,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(12),
- ),
- padding: const EdgeInsets.symmetric(vertical: 12),
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: Spacing.md),
+ child: Text(
+ text,
+ style: TextStyles.mini.copyWith(
+ color: context.componentColors.textLight,
),
- child: Text(label, style: textTheme.bodyBold),
),
);
}
diff --git a/mobile/apps/auth/lib/ui/settings/general_section_widget.dart b/mobile/apps/auth/lib/ui/settings/general_section_widget.dart
deleted file mode 100644
index 173ca05e64..0000000000
--- a/mobile/apps/auth/lib/ui/settings/general_section_widget.dart
+++ /dev/null
@@ -1,192 +0,0 @@
-import 'dart:io';
-
-import 'package:ente_auth/app/view/app.dart';
-import 'package:ente_auth/events/icons_changed_event.dart';
-import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/locale.dart';
-import 'package:ente_auth/services/preference_service.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/expandable_menu_item_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/settings/app_icon_selection_screen.dart';
-import 'package:ente_auth/ui/settings/common_settings.dart';
-import 'package:ente_auth/ui/settings/language_picker.dart';
-import 'package:ente_auth/utils/navigation_util.dart' as auth_nav;
-import 'package:ente_auth/utils/toast_util.dart';
-import 'package:ente_events/event_bus.dart';
-import 'package:ente_logging/logging.dart';
-import 'package:ente_pure_utils/ente_pure_utils.dart';
-import 'package:ente_ui/components/toggle_switch_widget.dart';
-import 'package:flutter/material.dart';
-
-class AdvancedSectionWidget extends StatefulWidget {
- const AdvancedSectionWidget({super.key});
-
- @override
- State<AdvancedSectionWidget> createState() => _AdvancedSectionWidgetState();
-}
-
-class _AdvancedSectionWidgetState extends State<AdvancedSectionWidget> {
- @override
- Widget build(BuildContext context) {
- final l10n = context.l10n;
- return ExpandableMenuItemWidget(
- title: l10n.general,
- selectionOptionsWidget: _getSectionOptions(context),
- leadingIcon: Icons.graphic_eq,
- );
- }
-
- Widget _getSectionOptions(BuildContext context) {
- final l10n = context.l10n;
- return Column(
- children: [
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.language),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- final locale = (await getLocale())!;
- if (!context.mounted) return;
- // ignore: unawaited_futures
- auth_nav.routeToPage(
- context,
- LanguageSelectorPage(appSupportedLocales, (locale) async {
- await setLocale(locale);
- if (!context.mounted) return;
- App.setLocale(context, locale);
- }, locale),
- );
- },
- ),
- sectionOptionSpacing,
- if (Platform.isIOS || Platform.isAndroid) ...[
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.appIcon),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- // ignore: unawaited_futures
- auth_nav.routeToPage(context, const AppIconSelectionScreen());
- },
- ),
- sectionOptionSpacing,
- ],
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.showLargeIcons),
- trailingWidget: ToggleSwitchWidget(
- value: () => PreferenceService.instance.shouldShowLargeIcons(),
- onChanged: () async {
- await PreferenceService.instance.setShowLargeIcons(
- !PreferenceService.instance.shouldShowLargeIcons(),
- );
- setState(() {});
- },
- ),
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.compactMode),
- trailingWidget: ToggleSwitchWidget(
- value: () => PreferenceService.instance.isCompactMode(),
- onChanged: () async {
- await PreferenceService.instance.setCompactMode(
- !PreferenceService.instance.isCompactMode(),
- );
- Bus.instance.fire(IconsChangedEvent());
- setState(() {});
- },
- ),
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.shouldHideCode),
- trailingWidget: ToggleSwitchWidget(
- value: () => PreferenceService.instance.shouldHideCodes(),
- onChanged: () async {
- await PreferenceService.instance.setHideCodes(
- !PreferenceService.instance.shouldHideCodes(),
- );
- if (PreferenceService.instance.shouldHideCodes()) {
- if (!context.mounted) return;
- showToast(context, context.l10n.doubleTapToViewHiddenCode);
- }
- setState(() {});
- },
- ),
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: l10n.focusOnSearchBar,
- ),
- trailingWidget: ToggleSwitchWidget(
- value: () =>
- PreferenceService.instance.shouldAutoFocusOnSearchBar(),
- onChanged: () async {
- await PreferenceService.instance.setAutoFocusOnSearchBar(
- !PreferenceService.instance.shouldAutoFocusOnSearchBar(),
- );
- setState(() {});
- },
- ),
- ),
- sectionOptionSpacing,
- if (Platform.isAndroid) ...[
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: l10n.minimizeAppOnCopy,
- ),
- trailingWidget: ToggleSwitchWidget(
- value: () => PreferenceService.instance.shouldMinimizeOnCopy(),
- onChanged: () async {
- await PreferenceService.instance.setShouldMinimizeOnCopy(
- !PreferenceService.instance.shouldMinimizeOnCopy(),
- );
- setState(() {});
- },
- ),
- ),
- sectionOptionSpacing,
- ],
- if (PlatformDetector.isDesktop()) ...[
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: l10n.minimizeToTrayOnClose,
- ),
- trailingWidget: ToggleSwitchWidget(
- value: () =>
- PreferenceService.instance.shouldMinimizeToTrayOnClose(),
- onChanged: () async {
- await PreferenceService.instance.setShouldMinimizeToTrayOnClose(
- !PreferenceService.instance.shouldMinimizeToTrayOnClose(),
- );
- setState(() {});
- },
- ),
- ),
- sectionOptionSpacing,
- ],
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: l10n.crashAndErrorReporting,
- ),
- trailingWidget: ToggleSwitchWidget(
- value: () => SuperLogging.shouldReportErrors(),
- onChanged: () async {
- await SuperLogging.setShouldReportErrors(
- !SuperLogging.shouldReportErrors(),
- );
- setState(() {});
- },
- ),
- ),
- sectionOptionSpacing,
- ],
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/settings/general_settings_page.dart b/mobile/apps/auth/lib/ui/settings/general_settings_page.dart
new file mode 100644
index 0000000000..356e594e4e
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/general_settings_page.dart
@@ -0,0 +1,143 @@
+import 'dart:io';
+
+import 'package:ente_auth/app/view/app.dart';
+import 'package:ente_auth/events/icons_changed_event.dart';
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/locale.dart';
+import 'package:ente_auth/services/preference_service.dart';
+import 'package:ente_auth/ui/settings/app_icon_selection_screen.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_item.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_navigation.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
+import 'package:ente_auth/ui/settings/language_picker.dart';
+import 'package:ente_auth/utils/toast_util.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:ente_events/event_bus.dart';
+import 'package:ente_logging/logging.dart';
+import 'package:ente_pure_utils/ente_pure_utils.dart';
+import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
+
+class GeneralSettingsPage extends StatelessWidget {
+ const GeneralSettingsPage({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final l10n = context.l10n;
+ return AuthSettingsPageScaffold(
+ title: l10n.general,
+ children: [
+ AuthSettingsItem(
+ title: l10n.language,
+ icon: HugeIcons.strokeRoundedLanguageSquare,
+ onTap: () => _openLanguage(context),
+ ),
+ if (Platform.isIOS || Platform.isAndroid) ...[
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.appIcon,
+ icon: HugeIcons.strokeRoundedImage01,
+ onTap: () =>
+ pushAuthSettingsPage(context, const AppIconSelectionScreen()),
+ ),
+ ],
+ const SizedBox(height: Spacing.lg),
+ MenuGroupComponent(
+ showDividers: true,
+ dividerPadding: const EdgeInsets.only(left: Spacing.lg),
+ items: [
+ _toggleItem(
+ title: l10n.showLargeIcons,
+ value: PreferenceService.instance.shouldShowLargeIcons,
+ onChanged: () => PreferenceService.instance.setShowLargeIcons(
+ !PreferenceService.instance.shouldShowLargeIcons(),
+ ),
+ ),
+ _toggleItem(
+ title: l10n.compactMode,
+ value: PreferenceService.instance.isCompactMode,
+ onChanged: () async {
+ await PreferenceService.instance.setCompactMode(
+ !PreferenceService.instance.isCompactMode(),
+ );
+ Bus.instance.fire(IconsChangedEvent());
+ },
+ ),
+ _toggleItem(
+ title: l10n.shouldHideCode,
+ value: PreferenceService.instance.shouldHideCodes,
+ onChanged: () async {
+ await PreferenceService.instance.setHideCodes(
+ !PreferenceService.instance.shouldHideCodes(),
+ );
+ if (PreferenceService.instance.shouldHideCodes() &&
+ context.mounted) {
+ showToast(context, l10n.doubleTapToViewHiddenCode);
+ }
+ },
+ ),
+ _toggleItem(
+ title: l10n.focusOnSearchBar,
+ value: PreferenceService.instance.shouldAutoFocusOnSearchBar,
+ onChanged: () =>
+ PreferenceService.instance.setAutoFocusOnSearchBar(
+ !PreferenceService.instance.shouldAutoFocusOnSearchBar(),
+ ),
+ ),
+ if (Platform.isAndroid)
+ _toggleItem(
+ title: l10n.minimizeAppOnCopy,
+ value: PreferenceService.instance.shouldMinimizeOnCopy,
+ onChanged: () =>
+ PreferenceService.instance.setShouldMinimizeOnCopy(
+ !PreferenceService.instance.shouldMinimizeOnCopy(),
+ ),
+ ),
+ if (PlatformDetector.isDesktop())
+ _toggleItem(
+ title: l10n.minimizeToTrayOnClose,
+ value: PreferenceService.instance.shouldMinimizeToTrayOnClose,
+ onChanged: () =>
+ PreferenceService.instance.setShouldMinimizeToTrayOnClose(
+ !PreferenceService.instance.shouldMinimizeToTrayOnClose(),
+ ),
+ ),
+ _toggleItem(
+ title: l10n.crashAndErrorReporting,
+ value: SuperLogging.shouldReportErrors,
+ onChanged: () => SuperLogging.setShouldReportErrors(
+ !SuperLogging.shouldReportErrors(),
+ ),
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+
+ AuthSettingsItem _toggleItem({
+ required String title,
+ required ValueGetter<bool> value,
+ required Future<void> Function() onChanged,
+ }) {
+ return AuthSettingsItem(
+ title: title,
+ showChevron: false,
+ trailing: ToggleSwitchComponent.async(value: value, onChanged: onChanged),
+ );
+ }
+
+ Future<void> _openLanguage(BuildContext context) async {
+ final locale = (await getLocale())!;
+ if (!context.mounted) return;
+ await pushAuthSettingsPage(
+ context,
+ LanguageSelectorPage(appSupportedLocales, (newLocale) async {
+ await setLocale(newLocale);
+ if (context.mounted) {
+ App.setLocale(context, newLocale);
+ }
+ }, locale),
+ );
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/settings/language_picker.dart b/mobile/apps/auth/lib/ui/settings/language_picker.dart
index 585ae7f587..8653869da4 100644
--- a/mobile/apps/auth/lib/ui/settings/language_picker.dart
+++ b/mobile/apps/auth/lib/ui/settings/language_picker.dart
@@ -1,11 +1,6 @@
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/divider_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/components/separators.dart';
-import 'package:ente_auth/ui/components/title_bar_title_widget.dart';
-import 'package:ente_auth/ui/components/title_bar_widget.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:ente_pure_utils/ente_pure_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
@@ -24,52 +19,9 @@ class LanguageSelectorPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
- final l10n = context.l10n;
- return Scaffold(
- body: Center(
- child: Container(
- constraints: const BoxConstraints.tightFor(width: 450),
- child: CustomScrollView(
- primary: false,
- slivers: <Widget>[
- TitleBarWidget(
- flexibleSpaceTitle: TitleBarTitleWidget(
- title: l10n.selectLanguage,
- ),
- ),
- SliverList(
- delegate: SliverChildBuilderDelegate((context, index) {
- return Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- vertical: 20,
- ),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- ClipRRect(
- borderRadius: const BorderRadius.all(
- Radius.circular(8),
- ),
- child: ItemsWidget(
- supportedLocales,
- onLocaleChanged,
- currentLocale,
- ),
- ),
- // MenuSectionDescriptionWidget(
- // content: context.l10n.maxDeviceLimitSpikeHandling(50),
- // )
- ],
- ),
- );
- }, childCount: 1),
- ),
- const SliverPadding(padding: EdgeInsets.symmetric(vertical: 12)),
- ],
- ),
- ),
- ),
+ return AuthSettingsPageScaffold(
+ title: context.l10n.selectLanguage,
+ children: [ItemsWidget(supportedLocales, onLocaleChanged, currentLocale)],
);
}
}
@@ -92,47 +44,63 @@ class ItemsWidget extends StatefulWidget {
class _ItemsWidgetState extends State<ItemsWidget> {
late Locale currentLocale;
- List<Widget> items = [];
@override
void initState() {
- currentLocale = widget.currentLocale;
+ currentLocale = _resolvedCurrentLocale(
+ widget.currentLocale,
+ widget.supportedLocales,
+ );
super.initState();
}
@override
Widget build(BuildContext context) {
- items.clear();
- for (Locale locale in widget.supportedLocales) {
- items.add(_menuItemForPicker(locale));
- }
- items = addSeparators(
- items,
- DividerWidget(
- dividerType: DividerType.menuNoIcon,
- bgColor: getEnteColorScheme(context).fillFaint,
+ return Semantics(
+ identifier: 'auth_language_list',
+ child: MenuGroupComponent(
+ showDividers: true,
+ dividerPadding: const EdgeInsets.only(left: Spacing.lg),
+ items: [
+ for (final locale in widget.supportedLocales)
+ _menuItemForPicker(locale),
+ ],
),
);
- return Column(mainAxisSize: MainAxisSize.min, children: items);
}
- Widget _menuItemForPicker(Locale locale) {
- return MenuItemWidget(
+ MenuComponent _menuItemForPicker(Locale locale) {
+ final selected = currentLocale == locale;
+ return MenuComponent(
key: ValueKey(locale.toString()),
- menuItemColor: getEnteColorScheme(context).fillFaint,
- captionedTextWidget: CaptionedTextWidget(
- title: getLocaleDisplayName(locale) + (kDebugMode ? ' ($locale)' : ''),
+ title: getLocaleDisplayName(locale) + (kDebugMode ? ' ($locale)' : ''),
+ selected: selected,
+ trailing: RadioComponent(
+ selected: selected,
+ onChanged: (_) => _selectLocale(locale),
),
- trailingIcon: currentLocale == locale ? Icons.check : null,
- alignCaptionedTextToLeft: true,
- isTopBorderRadiusRemoved: true,
- isBottomBorderRadiusRemoved: true,
showOnlyLoadingState: true,
- onTap: () async {
- widget.onLocaleChanged(locale);
- currentLocale = locale;
- setState(() {});
- },
+ onTap: () => _selectLocale(locale),
);
}
+
+ void _selectLocale(Locale locale) {
+ widget.onLocaleChanged(locale);
+ currentLocale = locale;
+ setState(() {});
+ }
+}
+
+Locale _resolvedCurrentLocale(Locale current, List<Locale> supported) {
+ if (supported.contains(current)) return current;
+
+ final languageMatches = supported
+ .where((locale) => locale.languageCode == current.languageCode)
+ .toList();
+ if (languageMatches.isEmpty) return current;
+
+ return languageMatches.firstWhere(
+ (locale) => locale.countryCode == null,
+ orElse: () => languageMatches.first,
+ );
}
diff --git a/mobile/apps/auth/lib/ui/settings/security_section_widget.dart b/mobile/apps/auth/lib/ui/settings/security_section_widget.dart
deleted file mode 100644
index 26afb11e32..0000000000
--- a/mobile/apps/auth/lib/ui/settings/security_section_widget.dart
+++ /dev/null
@@ -1,262 +0,0 @@
-import 'dart:async';
-import 'dart:typed_data';
-
-import 'package:ente_accounts/models/user_details.dart';
-import 'package:ente_accounts/pages/request_pwd_verification_page.dart';
-import 'package:ente_accounts/pages/sessions_page.dart';
-import 'package:ente_accounts/services/passkey_service.dart';
-import 'package:ente_accounts/services/user_service.dart';
-import 'package:ente_auth/core/configuration.dart';
-import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/expandable_menu_item_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/components/models/button_result.dart';
-import 'package:ente_auth/ui/settings/common_settings.dart';
-import 'package:ente_auth/utils/dialog_util.dart';
-import 'package:ente_auth/utils/navigation_util.dart';
-import 'package:ente_auth/utils/toast_util.dart';
-import 'package:ente_crypto_api/ente_crypto_api.dart';
-import 'package:ente_lock_screen/local_authentication_service.dart';
-import 'package:ente_lock_screen/lock_screen_settings.dart';
-import 'package:ente_lock_screen/ui/lock_screen_options.dart';
-import 'package:ente_ui/components/toggle_switch_widget.dart';
-import 'package:flutter/material.dart';
-import 'package:logging/logging.dart';
-
-class SecuritySectionWidget extends StatefulWidget {
- const SecuritySectionWidget({super.key});
-
- @override
- State<SecuritySectionWidget> createState() => _SecuritySectionWidgetState();
-}
-
-class _SecuritySectionWidgetState extends State<SecuritySectionWidget> {
- final _config = Configuration.instance;
- late bool _hasLoggedIn;
- final Logger _logger = Logger('SecuritySectionWidget');
-
- @override
- void initState() {
- _hasLoggedIn = _config.hasConfiguredAccount();
- super.initState();
- }
-
- @override
- void dispose() {
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- final l10n = context.l10n;
- return ExpandableMenuItemWidget(
- title: l10n.security,
- selectionOptionsWidget: _getSectionOptions(context),
- leadingIcon: Icons.local_police_outlined,
- );
- }
-
- Widget _getSectionOptions(BuildContext context) {
- final l10n = context.l10n;
- final List<Widget> children = [];
- if (_hasLoggedIn) {
- final bool? canDisableMFA = UserService.instance.canDisableEmailMFA();
- if (canDisableMFA == null) {
- // We don't know if the user can disable MFA yet, so we fetch the info
- UserService.instance.getUserDetailsV2().ignore();
- }
- children.addAll([
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: l10n.emailVerificationToggle,
- ),
- trailingWidget: ToggleSwitchWidget(
- value: () => UserService.instance.hasEmailMFAEnabled(),
- onChanged: () async {
- final hasAuthenticated = await LocalAuthenticationService.instance
- .requestLocalAuthentication(
- context,
- l10n.authToChangeEmailVerificationSetting,
- );
- final isEmailMFAEnabled = UserService.instance
- .hasEmailMFAEnabled();
- if (hasAuthenticated) {
- await updateEmailMFA(!isEmailMFAEnabled);
- if (mounted) {
- setState(() {});
- }
- }
- },
- ),
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.passkey),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- await onPasskeyClick(context);
- },
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: context.l10n.viewActiveSessions,
- ),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- final hasAuthenticated = await LocalAuthenticationService.instance
- .requestLocalAuthentication(
- context,
- context.l10n.authToViewYourActiveSessions,
- );
- if (hasAuthenticated) {
- if (!context.mounted) return;
- // ignore: unawaited_futures
- Navigator.of(context).push(
- MaterialPageRoute(
- builder: (BuildContext context) {
- return SessionsPage(Configuration.instance);
- },
- ),
- );
- }
- },
- ),
- ]);
- } else {
- children.add(sectionOptionSpacing);
- }
- children.addAll([
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: context.l10n.appLock),
- surfaceExecutionStates: false,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- ButtonResult? result;
- if (_config.hasOptedForOfflineMode() &&
- LockScreenSettings.instance.getOfflineModeWarningStatus()) {
- result = await showChoiceActionSheet(
- context,
- title: context.l10n.warning,
- body: context.l10n.appLockOfflineModeWarning,
- secondButtonLabel: context.l10n.cancel,
- firstButtonLabel: context.l10n.ok,
- );
- if (result?.action == ButtonAction.first) {
- await LockScreenSettings.instance.setOfflineModeWarningStatus(
- false,
- );
- } else {
- return;
- }
- }
- if (!context.mounted) return;
- final hasAuthenticated = await LocalAuthenticationService.instance
- .requestLocalAuthentication(
- context,
- context.l10n.authToChangeLockscreenSetting,
- );
- if (hasAuthenticated) {
- if (!context.mounted) return;
- await Navigator.of(context).push(
- MaterialPageRoute(
- builder: (BuildContext context) {
- return const LockScreenOptions();
- },
- ),
- );
- }
- },
- ),
- sectionOptionSpacing,
- ]);
- return Column(children: children);
- }
-
- Future<void> onPasskeyClick(BuildContext buildContext) async {
- try {
- if (!buildContext.mounted) return;
- final hasAuthenticated = await LocalAuthenticationService.instance
- .requestLocalAuthentication(
- context,
- context.l10n.authenticateGeneric,
- refocusWindows: false,
- );
- if (!hasAuthenticated) {
- return;
- }
- final isPassKeyResetEnabled = await PasskeyService.instance
- .isPasskeyRecoveryEnabled();
- if (!isPassKeyResetEnabled) {
- final Uint8List recoveryKey = Configuration.instance.getRecoveryKey();
- final resetKey = CryptoUtil.generateKey();
- final resetKeyBase64 = CryptoUtil.bin2base64(resetKey);
- final encryptionResult = CryptoUtil.encryptSync(resetKey, recoveryKey);
- await PasskeyService.instance.configurePasskeyRecovery(
- resetKeyBase64,
- CryptoUtil.bin2base64(encryptionResult.encryptedData!),
- CryptoUtil.bin2base64(encryptionResult.nonce!),
- );
- }
- if (!buildContext.mounted) return;
- await PasskeyService.instance.openPasskeyPage(buildContext);
- } catch (e, s) {
- _logger.severe("failed to open passkey page", e, s);
- if (!mounted) return;
- await showGenericErrorDialog(context: context, error: e);
- }
- }
-
- Future<void> updateEmailMFA(bool enableEmailMFA) async {
- try {
- if (!context.mounted) return;
- final UserDetails details = await UserService.instance.getUserDetailsV2(
- memoryCount: false,
- );
- if (details.profileData?.canDisableEmailMFA == false) {
- if (!mounted) return;
- await routeToPage(
- context,
- RequestPasswordVerificationPage(
- Configuration.instance,
- onPasswordVerified: (Uint8List keyEncryptionKey) async {
- final Uint8List loginKey = await CryptoUtil.deriveLoginKey(
- keyEncryptionKey,
- );
- await UserService.instance.registerOrUpdateSrp(loginKey);
- },
- ),
- );
- }
- if (enableEmailMFA) {
- if (!mounted) return;
- await showChoiceActionSheet(
- context,
- title: context.l10n.warning,
- body: context.l10n.emailVerificationEnableWarning,
- isCritical: true,
- firstButtonOnTap: () async {
- await UserService.instance.updateEmailMFA(enableEmailMFA);
- },
- secondButtonLabel: context.l10n.cancel,
- firstButtonLabel: context.l10n.iUnderStand,
- );
- } else {
- await UserService.instance.updateEmailMFA(enableEmailMFA);
- }
- } catch (e) {
- if (!mounted) return;
- showToast(context, context.l10n.somethingWentWrongMessage);
- }
- }
-}
diff --git a/mobile/apps/auth/lib/ui/settings/security_settings_page.dart b/mobile/apps/auth/lib/ui/settings/security_settings_page.dart
new file mode 100644
index 0000000000..7f3e3e0024
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/security_settings_page.dart
@@ -0,0 +1,209 @@
+import 'dart:typed_data';
+
+import 'package:ente_accounts/models/user_details.dart';
+import 'package:ente_accounts/pages/request_pwd_verification_page.dart';
+import 'package:ente_accounts/pages/sessions_page.dart';
+import 'package:ente_accounts/services/passkey_service.dart';
+import 'package:ente_accounts/services/user_service.dart';
+import 'package:ente_auth/core/configuration.dart';
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/ui/components/buttons/button_widget.dart';
+import 'package:ente_auth/ui/components/models/button_result.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_item.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
+import 'package:ente_auth/utils/dialog_util.dart';
+import 'package:ente_auth/utils/toast_util.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:ente_crypto_api/ente_crypto_api.dart';
+import 'package:ente_lock_screen/local_authentication_service.dart';
+import 'package:ente_lock_screen/lock_screen_settings.dart';
+import 'package:ente_lock_screen/ui/lock_screen_options.dart';
+import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
+import 'package:logging/logging.dart';
+
+class SecuritySettingsPage extends StatefulWidget {
+ const SecuritySettingsPage({super.key});
+
+ @override
+ State<SecuritySettingsPage> createState() => _SecuritySettingsPageState();
+}
+
+class _SecuritySettingsPageState extends State<SecuritySettingsPage> {
+ final _config = Configuration.instance;
+ final _logger = Logger('SecuritySettingsPage');
+ late final bool _hasLoggedIn;
+
+ @override
+ void initState() {
+ super.initState();
+ _hasLoggedIn = _config.hasConfiguredAccount();
+ if (_hasLoggedIn && UserService.instance.canDisableEmailMFA() == null) {
+ UserService.instance.getUserDetailsV2().ignore();
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return AuthSettingsPageScaffold(
+ title: context.l10n.security,
+ children: [
+ if (_hasLoggedIn) ...[
+ AuthSettingsItem(
+ title: context.l10n.emailVerificationToggle,
+ icon: HugeIcons.strokeRoundedMailSecure01,
+ showChevron: false,
+ trailing: ToggleSwitchComponent.async(
+ value: UserService.instance.hasEmailMFAEnabled,
+ onChanged: _toggleEmailMFA,
+ ),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: context.l10n.passkey,
+ icon: HugeIcons.strokeRoundedFingerAccess,
+ showOnlyLoadingState: true,
+ onTap: _openPasskey,
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: context.l10n.viewActiveSessions,
+ icon: HugeIcons.strokeRoundedSmartPhone01,
+ showOnlyLoadingState: true,
+ onTap: _openActiveSessions,
+ ),
+ const SizedBox(height: Spacing.sm),
+ ],
+ AuthSettingsItem(
+ title: context.l10n.appLock,
+ icon: HugeIcons.strokeRoundedSquareLock02,
+ showOnlyLoadingState: true,
+ onTap: _openAppLock,
+ ),
+ ],
+ );
+ }
+
+ Future<void> _toggleEmailMFA() async {
+ final hasAuthenticated = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(
+ context,
+ context.l10n.authToChangeEmailVerificationSetting,
+ );
+ if (!hasAuthenticated) return;
+ await _updateEmailMFA(!UserService.instance.hasEmailMFAEnabled());
+ }
+
+ Future<void> _openPasskey() async {
+ try {
+ final hasAuthenticated = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(
+ context,
+ context.l10n.authenticateGeneric,
+ refocusWindows: false,
+ );
+ if (!hasAuthenticated) return;
+ final isPassKeyResetEnabled = await PasskeyService.instance
+ .isPasskeyRecoveryEnabled();
+ if (!isPassKeyResetEnabled) {
+ final Uint8List recoveryKey = Configuration.instance.getRecoveryKey();
+ final resetKey = CryptoUtil.generateKey();
+ final resetKeyBase64 = CryptoUtil.bin2base64(resetKey);
+ final encryptionResult = CryptoUtil.encryptSync(resetKey, recoveryKey);
+ await PasskeyService.instance.configurePasskeyRecovery(
+ resetKeyBase64,
+ CryptoUtil.bin2base64(encryptionResult.encryptedData!),
+ CryptoUtil.bin2base64(encryptionResult.nonce!),
+ );
+ }
+ if (!mounted) return;
+ await PasskeyService.instance.openPasskeyPage(context);
+ } catch (error, stackTrace) {
+ _logger.severe('Failed to open passkey page', error, stackTrace);
+ if (mounted) {
+ await showGenericErrorDialog(context: context, error: error);
+ }
+ }
+ }
+
+ Future<void> _openActiveSessions() async {
+ final hasAuthenticated = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(
+ context,
+ context.l10n.authToViewYourActiveSessions,
+ );
+ if (!hasAuthenticated || !mounted) return;
+ await Navigator.of(context).push<void>(
+ MaterialPageRoute(builder: (_) => SessionsPage(Configuration.instance)),
+ );
+ }
+
+ Future<void> _openAppLock() async {
+ ButtonResult? result;
+ if (_config.hasOptedForOfflineMode() &&
+ LockScreenSettings.instance.getOfflineModeWarningStatus()) {
+ result = await showChoiceActionSheet(
+ context,
+ title: context.l10n.warning,
+ body: context.l10n.appLockOfflineModeWarning,
+ secondButtonLabel: context.l10n.cancel,
+ firstButtonLabel: context.l10n.ok,
+ );
+ if (result?.action != ButtonAction.first) return;
+ await LockScreenSettings.instance.setOfflineModeWarningStatus(false);
+ }
+ if (!mounted) return;
+ final hasAuthenticated = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(
+ context,
+ context.l10n.authToChangeLockscreenSetting,
+ );
+ if (!hasAuthenticated || !mounted) return;
+ await Navigator.of(
+ context,
+ ).push<void>(MaterialPageRoute(builder: (_) => const LockScreenOptions()));
+ }
+
+ Future<void> _updateEmailMFA(bool enableEmailMFA) async {
+ try {
+ final UserDetails details = await UserService.instance.getUserDetailsV2(
+ memoryCount: false,
+ );
+ if (details.profileData?.canDisableEmailMFA == false) {
+ if (!mounted) return;
+ await Navigator.of(context).push<void>(
+ MaterialPageRoute(
+ builder: (_) => RequestPasswordVerificationPage(
+ Configuration.instance,
+ onPasswordVerified: (keyEncryptionKey) async {
+ final loginKey = await CryptoUtil.deriveLoginKey(
+ keyEncryptionKey,
+ );
+ await UserService.instance.registerOrUpdateSrp(loginKey);
+ },
+ ),
+ ),
+ );
+ }
+ if (enableEmailMFA) {
+ if (!mounted) return;
+ await showChoiceActionSheet(
+ context,
+ title: context.l10n.warning,
+ body: context.l10n.emailVerificationEnableWarning,
+ isCritical: true,
+ firstButtonOnTap: () => UserService.instance.updateEmailMFA(true),
+ secondButtonLabel: context.l10n.cancel,
+ firstButtonLabel: context.l10n.iUnderStand,
+ );
+ } else {
+ await UserService.instance.updateEmailMFA(false);
+ }
+ if (mounted) setState(() {});
+ } catch (_) {
+ if (mounted) {
+ showToast(context, context.l10n.somethingWentWrongMessage);
+ }
+ }
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/settings/social_icons_row.dart b/mobile/apps/auth/lib/ui/settings/social_icons_row.dart
new file mode 100644
index 0000000000..975316cfd9
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/social_icons_row.dart
@@ -0,0 +1,106 @@
+import 'dart:io';
+
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/services/update_service.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:ente_pure_utils/ente_pure_utils.dart';
+import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
+import 'package:url_launcher/url_launcher_string.dart';
+
+class SocialIconsRow extends StatelessWidget {
+ const SocialIconsRow({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final rateDetails = UpdateService.instance.getRateDetails();
+ final links = <_SocialLink>[
+ if (PlatformDetector.isMobile())
+ _SocialLink(
+ label: context.l10n.rateUsOnStore(rateDetails.item1),
+ identifier: 'auth_settings_rate',
+ icon: HugeIcons.strokeRoundedStar,
+ url: rateDetails.item2,
+ ),
+ const _SocialLink(
+ label: 'Discord',
+ identifier: 'auth_settings_social_discord',
+ icon: HugeIcons.strokeRoundedDiscord,
+ url: 'https://ente.com/discord',
+ ),
+ const _SocialLink(
+ label: 'GitHub',
+ identifier: 'auth_settings_social_github',
+ icon: HugeIcons.strokeRoundedGithub,
+ url: 'https://github.com/ente/ente',
+ ),
+ const _SocialLink(
+ label: 'X',
+ identifier: 'auth_settings_social_x',
+ icon: HugeIcons.strokeRoundedNewTwitter,
+ url: 'https://twitter.com/enteio',
+ ),
+ const _SocialLink(
+ label: 'Mastodon',
+ identifier: 'auth_settings_social_mastodon',
+ icon: HugeIcons.strokeRoundedMastodon,
+ url: 'https://fosstodon.org/@ente',
+ ),
+ const _SocialLink(
+ label: 'Reddit',
+ identifier: 'auth_settings_social_reddit',
+ icon: HugeIcons.strokeRoundedReddit,
+ url: 'https://reddit.com/r/enteio',
+ ),
+ ];
+
+ return Wrap(
+ alignment: WrapAlignment.center,
+ spacing: Spacing.sm,
+ runSpacing: Spacing.sm,
+ children: links.map((link) => _SocialIconButton(link: link)).toList(),
+ );
+ }
+}
+
+class _SocialIconButton extends StatelessWidget {
+ const _SocialIconButton({required this.link});
+
+ final _SocialLink link;
+
+ @override
+ Widget build(BuildContext context) {
+ return Semantics(
+ identifier: link.identifier,
+ child: IconButtonComponent(
+ tooltip: link.label,
+ shouldSurfaceExecutionStates: false,
+ icon: HugeIcon(
+ icon: link.icon,
+ size: IconSizes.small,
+ strokeWidth: 1.6,
+ ),
+ onTap: () => launchUrlString(
+ link.url,
+ mode: Platform.isAndroid
+ ? LaunchMode.externalApplication
+ : LaunchMode.platformDefault,
+ ),
+ ),
+ );
+ }
+}
+
+class _SocialLink {
+ const _SocialLink({
+ required this.label,
+ required this.identifier,
+ required this.icon,
+ required this.url,
+ });
+
+ final String label;
+ final String identifier;
+ final List<List<dynamic>> icon;
+ final String url;
+}
diff --git a/mobile/apps/auth/lib/ui/settings/social_section_widget.dart b/mobile/apps/auth/lib/ui/settings/social_section_widget.dart
deleted file mode 100644
index 775b2ff653..0000000000
--- a/mobile/apps/auth/lib/ui/settings/social_section_widget.dart
+++ /dev/null
@@ -1,94 +0,0 @@
-import 'dart:io';
-
-import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/services/update_service.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/expandable_menu_item_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/settings/common_settings.dart';
-import 'package:ente_pure_utils/ente_pure_utils.dart';
-import 'package:flutter/material.dart';
-import 'package:url_launcher/url_launcher_string.dart';
-
-class SocialSectionWidget extends StatelessWidget {
- const SocialSectionWidget({super.key});
-
- @override
- Widget build(BuildContext context) {
- final l10n = context.l10n;
- return ExpandableMenuItemWidget(
- title: l10n.social,
- selectionOptionsWidget: _getSectionOptions(context),
- leadingIcon: Icons.interests_outlined,
- );
- }
-
- Widget _getSectionOptions(BuildContext context) {
- final l10n = context.l10n;
- final result = UpdateService.instance.getRateDetails();
- final String ratePlace = result.item1;
- final String rateUrl = result.item2;
-
- final List<Widget> options = [
- sectionOptionSpacing,
- if (PlatformDetector.isMobile()) ...[
- SocialsMenuItemWidget(l10n.rateUsOnStore(ratePlace), rateUrl),
- sectionOptionSpacing,
- ],
- SocialsMenuItemWidget(
- l10n.blog,
- "https://ente.com/blog",
- launchInExternalApp: !Platform.isAndroid,
- ),
- sectionOptionSpacing,
- SocialsMenuItemWidget(
- l10n.merchandise,
- "https://shop.ente.com",
- launchInExternalApp: !Platform.isAndroid,
- ),
- sectionOptionSpacing,
- const SocialsMenuItemWidget("Mastodon", "https://fosstodon.org/@ente"),
- sectionOptionSpacing,
- const SocialsMenuItemWidget("Twitter", "https://twitter.com/enteio"),
- sectionOptionSpacing,
- const SocialsMenuItemWidget("Discord", "https://ente.com/discord"),
- sectionOptionSpacing,
- const SocialsMenuItemWidget("Reddit", "https://reddit.com/r/enteio"),
- sectionOptionSpacing,
- ];
- return Column(children: options);
- }
-}
-
-class SocialsMenuItemWidget extends StatelessWidget {
- final String text;
- final String url;
- final bool launchInExternalApp;
-
- const SocialsMenuItemWidget(
- this.text,
- this.url, {
- super.key,
- this.launchInExternalApp = true,
- });
-
- @override
- Widget build(BuildContext context) {
- return MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: text),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- // ignore: unawaited_futures
- launchUrlString(
- url,
- mode: launchInExternalApp
- ? LaunchMode.externalApplication
- : LaunchMode.platformDefault,
- );
- },
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/settings/support_section_widget.dart b/mobile/apps/auth/lib/ui/settings/support_section_widget.dart
deleted file mode 100644
index 9dc0cfdf4f..0000000000
--- a/mobile/apps/auth/lib/ui/settings/support_section_widget.dart
+++ /dev/null
@@ -1,106 +0,0 @@
-import 'package:ente_auth/core/constants.dart';
-import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/expandable_menu_item_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/settings/common_settings.dart';
-import 'package:ente_auth/utils/email_util.dart';
-import 'package:ente_auth/utils/platform_util.dart';
-import 'package:flutter/material.dart';
-import 'package:logging/logging.dart';
-import 'package:url_launcher/url_launcher.dart';
-
-class SupportSectionWidget extends StatefulWidget {
- const SupportSectionWidget({super.key});
-
- @override
- State<SupportSectionWidget> createState() => _SupportSectionWidgetState();
-}
-
-class _SupportSectionWidgetState extends State<SupportSectionWidget> {
- @override
- Widget build(BuildContext context) {
- final l10n = context.l10n;
- return ExpandableMenuItemWidget(
- title: l10n.support,
- selectionOptionsWidget: _getSectionOptions(context),
- leadingIcon: Icons.help_outline_outlined,
- );
- }
-
- Widget _getSectionOptions(BuildContext context) {
- final l10n = context.l10n;
- return Column(
- children: [
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.faq),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- try {
- await PlatformUtil.openUrlInBrowser(
- "https://ente.com/help/auth/faq",
- );
- } catch (e) {
- Logger("SupportSection").severe("Failed to open FAQ", e);
- }
- },
- ),
- sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.suggestFeatures),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- final launched = await launchUrl(
- githubFeatureRequestUri,
- mode: LaunchMode.externalApplication,
- );
- if (!launched) {
- Logger(
- "SupportSection",
- ).warning("Failed to open feature request discussions");
- }
- },
- ),
- sectionOptionSpacing,
- // MenuItemWidget(
- // captionedTextWidget: CaptionedTextWidget(
- // title: l10n.email,
- // ),
- // pressedColor: getEnteColorScheme(context).fillFaint,
- // trailingIcon: Icons.chevron_right_outlined,
- // trailingIconIsMuted: true,
- // onTap: () async {
- // await sendEmail(context, to: supportEmail);
- // },
- // ),
- // sectionOptionSpacing,
- MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(title: l10n.reportABug),
- pressedColor: getEnteColorScheme(context).fillFaint,
- trailingIcon: Icons.chevron_right_outlined,
- trailingIconIsMuted: true,
- onTap: () async {
- await sendLogs(context, l10n.reportBug);
- },
- onDoubleTap: () async {
- try {
- if (!context.mounted) return;
- final zipFilePath = await getZippedLogsFile(context);
- if (!context.mounted) return;
- await shareLogs(context, "[email protected]", zipFilePath);
- } catch (e) {
- Logger("SupportSectionWidget").severe("failed to export logs", e);
- }
- },
- ),
- sectionOptionSpacing,
- ],
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/settings/support_settings_page.dart b/mobile/apps/auth/lib/ui/settings/support_settings_page.dart
new file mode 100644
index 0000000000..55de16d884
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/support_settings_page.dart
@@ -0,0 +1,80 @@
+import 'package:ente_auth/core/constants.dart';
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_item.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
+import 'package:ente_auth/utils/email_util.dart';
+import 'package:ente_auth/utils/platform_util.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
+import 'package:logging/logging.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+class SupportSettingsPage extends StatelessWidget {
+ const SupportSettingsPage({super.key});
+
+ @override
+ Widget build(BuildContext context) {
+ final l10n = context.l10n;
+ return AuthSettingsPageScaffold(
+ title: l10n.support,
+ children: [
+ AuthSettingsItem(
+ title: l10n.faq,
+ icon: HugeIcons.strokeRoundedHelpCircle,
+ showOnlyLoadingState: true,
+ onTap: () => _openFaq(),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.suggestFeatures,
+ icon: HugeIcons.strokeRoundedIdea01,
+ showOnlyLoadingState: true,
+ onTap: _suggestFeatures,
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.reportABug,
+ icon: HugeIcons.strokeRoundedBug01,
+ showOnlyLoadingState: true,
+ onTap: () => sendLogs(context, l10n.reportBug),
+ onDoubleTap: () => _shareLogs(context),
+ ),
+ ],
+ );
+ }
+
+ Future<void> _openFaq() async {
+ try {
+ await PlatformUtil.openUrlInBrowser('https://ente.com/help/auth/faq');
+ } catch (error, stackTrace) {
+ Logger(
+ 'SupportSettingsPage',
+ ).severe('Failed to open FAQ', error, stackTrace);
+ }
+ }
+
+ Future<void> _suggestFeatures() async {
+ final launched = await launchUrl(
+ githubFeatureRequestUri,
+ mode: LaunchMode.externalApplication,
+ );
+ if (!launched) {
+ Logger(
+ 'SupportSettingsPage',
+ ).warning('Failed to open feature request discussions');
+ }
+ }
+
+ Future<void> _shareLogs(BuildContext context) async {
+ try {
+ final zipFilePath = await getZippedLogsFile(context);
+ if (!context.mounted) return;
+ await shareLogs(context, '[email protected]', zipFilePath);
+ } catch (error, stackTrace) {
+ Logger(
+ 'SupportSettingsPage',
+ ).severe('Failed to export logs', error, stackTrace);
+ }
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/settings/theme_settings_page.dart b/mobile/apps/auth/lib/ui/settings/theme_settings_page.dart
new file mode 100644
index 0000000000..c45abe04d7
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/theme_settings_page.dart
@@ -0,0 +1,84 @@
+import 'package:ente_auth/app/view/app.dart';
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_item.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:ente_lock_screen/ui/app_lock.dart';
+import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
+
+class ThemeSettingsPage extends StatefulWidget {
+ const ThemeSettingsPage({super.key});
+
+ @override
+ State<ThemeSettingsPage> createState() => _ThemeSettingsPageState();
+}
+
+class _ThemeSettingsPageState extends State<ThemeSettingsPage> {
+ @override
+ Widget build(BuildContext context) {
+ final l10n = context.l10n;
+ final colors = context.componentColors;
+ final currentThemeMode = App.themeModeOf(context);
+
+ return AuthSettingsPageScaffold(
+ title: l10n.theme,
+ children: [
+ MenuGroupComponent(
+ showDividers: true,
+ dividerPadding: const EdgeInsets.only(left: 68),
+ items: [
+ _themeItem(
+ label: l10n.systemTheme,
+ icon: HugeIcons.strokeRoundedSmartPhone01,
+ mode: ThemeMode.system,
+ currentMode: currentThemeMode,
+ checkColor: colors.primary,
+ ),
+ _themeItem(
+ label: l10n.lightTheme,
+ icon: HugeIcons.strokeRoundedSun03,
+ mode: ThemeMode.light,
+ currentMode: currentThemeMode,
+ checkColor: colors.primary,
+ ),
+ _themeItem(
+ label: l10n.darkTheme,
+ icon: HugeIcons.strokeRoundedMoon02,
+ mode: ThemeMode.dark,
+ currentMode: currentThemeMode,
+ checkColor: colors.primary,
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+
+ Widget _themeItem({
+ required String label,
+ required List<List<dynamic>> icon,
+ required ThemeMode mode,
+ required ThemeMode currentMode,
+ required Color checkColor,
+ }) {
+ return AuthSettingsItem(
+ title: label,
+ icon: icon,
+ showChevron: false,
+ trailing: currentMode == mode
+ ? Icon(Icons.check, color: checkColor)
+ : null,
+ onTap: () => _setTheme(mode),
+ );
+ }
+
+ Future<void> _setTheme(ThemeMode themeMode) async {
+ final appLock = AppLock.of(context);
+ await App.setThemeMode(context, themeMode);
+ appLock?.setThemeMode(themeMode);
+ if (mounted) {
+ setState(() {});
+ }
+ }
+}
diff --git a/mobile/apps/auth/lib/ui/settings/theme_switch_widget.dart b/mobile/apps/auth/lib/ui/settings/theme_switch_widget.dart
deleted file mode 100644
index f5c31e3d8c..0000000000
--- a/mobile/apps/auth/lib/ui/settings/theme_switch_widget.dart
+++ /dev/null
@@ -1,77 +0,0 @@
-import 'package:ente_auth/app/view/app.dart';
-import 'package:ente_auth/ente_theme_data.dart';
-import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:ente_auth/ui/components/captioned_text_widget.dart';
-import 'package:ente_auth/ui/components/expandable_menu_item_widget.dart';
-import 'package:ente_auth/ui/components/menu_item_widget.dart';
-import 'package:ente_auth/ui/settings/common_settings.dart';
-import 'package:ente_lock_screen/ui/app_lock.dart';
-import 'package:flutter/material.dart';
-
-class ThemeSwitchWidget extends StatefulWidget {
- const ThemeSwitchWidget({super.key});
-
- @override
- State<ThemeSwitchWidget> createState() => _ThemeSwitchWidgetState();
-}
-
-class _ThemeSwitchWidgetState extends State<ThemeSwitchWidget> {
- @override
- Widget build(BuildContext context) {
- return ExpandableMenuItemWidget(
- title: context.l10n.theme,
- selectionOptionsWidget: _getSectionOptions(context),
- leadingIcon: Theme.of(context).brightness == Brightness.light
- ? Icons.light_mode_outlined
- : Icons.dark_mode_outlined,
- );
- }
-
- Widget _getSectionOptions(BuildContext context) {
- return Column(
- children: [
- sectionOptionSpacing,
- _menuItem(context, ThemeMode.light),
- sectionOptionSpacing,
- _menuItem(context, ThemeMode.dark),
- sectionOptionSpacing,
- _menuItem(context, ThemeMode.system),
- sectionOptionSpacing,
- ],
- );
- }
-
- String _name(BuildContext ctx, ThemeMode mode) {
- switch (mode) {
- case ThemeMode.light:
- return ctx.l10n.lightTheme;
- case ThemeMode.dark:
- return ctx.l10n.darkTheme;
- case ThemeMode.system:
- return ctx.l10n.systemTheme;
- }
- }
-
- Widget _menuItem(BuildContext context, ThemeMode themeMode) {
- final currentThemeMode = App.themeModeOf(context);
- return MenuItemWidget(
- captionedTextWidget: CaptionedTextWidget(
- title: _name(context, themeMode),
- textStyle: Theme.of(context).colorScheme.enteTheme.textTheme.body,
- ),
- pressedColor: getEnteColorScheme(context).fillFaint,
- isExpandable: false,
- trailingIcon: currentThemeMode == themeMode ? Icons.check : null,
- trailingExtraMargin: 4,
- onTap: () async {
- final appLock = AppLock.of(context);
- await App.setThemeMode(context, themeMode);
- appLock?.setThemeMode(themeMode);
- if (mounted) {
- setState(() {});
- }
- },
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/settings/title_bar_widget.dart b/mobile/apps/auth/lib/ui/settings/title_bar_widget.dart
deleted file mode 100644
index 3cd79684ee..0000000000
--- a/mobile/apps/auth/lib/ui/settings/title_bar_widget.dart
+++ /dev/null
@@ -1,32 +0,0 @@
-import 'package:ente_auth/l10n/l10n.dart';
-import 'package:flutter/material.dart';
-
-class SettingsTitleBarWidget extends StatelessWidget {
- const SettingsTitleBarWidget({super.key, required this.scaffoldKey});
-
- final GlobalKey<ScaffoldState> scaffoldKey;
-
- @override
- Widget build(BuildContext context) {
- final l10n = context.l10n;
- return Container(
- padding: const EdgeInsets.symmetric(vertical: 4),
- child: Padding(
- padding: const EdgeInsets.fromLTRB(8, 0, 20, 0),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- IconButton(
- visualDensity: const VisualDensity(horizontal: -2, vertical: -2),
- onPressed: () {
- scaffoldKey.currentState?.closeDrawer();
- },
- icon: const Icon(Icons.keyboard_double_arrow_left_outlined),
- ),
- Text(l10n.settings),
- ],
- ),
- ),
- );
- }
-}
diff --git a/mobile/apps/auth/lib/ui/settings_page.dart b/mobile/apps/auth/lib/ui/settings_page.dart
index f138bf0256..dffc85f66a 100644
--- a/mobile/apps/auth/lib/ui/settings_page.dart
+++ b/mobile/apps/auth/lib/ui/settings_page.dart
@@ -5,177 +5,235 @@ import 'package:ente_auth/core/configuration.dart';
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/onboarding/view/onboarding_page.dart';
import 'package:ente_auth/store/code_store.dart';
-import 'package:ente_auth/theme/colors.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/models/button_result.dart';
-import 'package:ente_auth/ui/components/notification_warning_widget.dart';
-import 'package:ente_auth/ui/settings/about_section_widget.dart';
-import 'package:ente_auth/ui/settings/account_section_widget.dart';
+import 'package:ente_auth/ui/settings/about_settings_page.dart';
+import 'package:ente_auth/ui/settings/account_settings_page.dart';
import 'package:ente_auth/ui/settings/app_version_widget.dart';
-import 'package:ente_auth/ui/settings/data/data_section_widget.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_item.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_navigation.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
+import 'package:ente_auth/ui/settings/data/data_settings_page.dart';
import 'package:ente_auth/ui/settings/data/export_widget.dart';
import 'package:ente_auth/ui/settings/developer_settings_widget.dart';
-import 'package:ente_auth/ui/settings/general_section_widget.dart';
+import 'package:ente_auth/ui/settings/general_settings_page.dart';
import 'package:ente_auth/ui/settings/notification_banner_widget.dart';
-import 'package:ente_auth/ui/settings/security_section_widget.dart';
-import 'package:ente_auth/ui/settings/social_section_widget.dart';
-import 'package:ente_auth/ui/settings/support_section_widget.dart';
-import 'package:ente_auth/ui/settings/theme_switch_widget.dart';
-import 'package:ente_auth/ui/settings/title_bar_widget.dart';
+import 'package:ente_auth/ui/settings/security_settings_page.dart';
+import 'package:ente_auth/ui/settings/social_icons_row.dart';
+import 'package:ente_auth/ui/settings/support_settings_page.dart';
+import 'package:ente_auth/ui/settings/theme_settings_page.dart';
import 'package:ente_auth/utils/dialog_util.dart';
-import 'package:ente_auth/utils/navigation_util.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:ente_lock_screen/local_authentication_service.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
+import 'package:hugeicons/hugeicons.dart';
class SettingsPage extends StatelessWidget {
- final ValueNotifier<String?> emailNotifier;
- final GlobalKey<ScaffoldState> scaffoldKey;
-
- SettingsPage({
+ const SettingsPage({
super.key,
required this.emailNotifier,
required this.scaffoldKey,
});
+ final ValueNotifier<String?> emailNotifier;
+ final GlobalKey<ScaffoldState> scaffoldKey;
+
@override
Widget build(BuildContext context) {
final hasLoggedIn = Configuration.instance.hasConfiguredAccount();
if (hasLoggedIn) {
UserService.instance.getUserDetailsV2().ignore();
}
- final enteColorScheme = getEnteColorScheme(context);
- return Scaffold(
- body: Container(
- color: enteColorScheme.backdropBase,
- child: _getBody(context, enteColorScheme),
+ return ValueListenableBuilder<String?>(
+ valueListenable: emailNotifier,
+ builder: (context, email, _) => _buildSettings(
+ context,
+ hasLoggedIn: hasLoggedIn,
+ email: hasLoggedIn ? email : null,
),
);
}
- Widget _getBody(BuildContext context, EnteColorScheme colorScheme) {
- final hasLoggedIn = Configuration.instance.hasConfiguredAccount();
- final enteTextTheme = getEnteTextTheme(context);
- const sectionSpacing = SizedBox(height: 8);
- final List<Widget> contents = [];
+ Widget _buildSettings(
+ BuildContext context, {
+ required bool hasLoggedIn,
+ required String? email,
+ }) {
+ final l10n = context.l10n;
+ final contents = <Widget>[];
if (hasLoggedIn) {
contents.add(
- Container(
- padding: const EdgeInsets.symmetric(horizontal: 8),
- child: Align(
- alignment: Alignment.centerLeft,
- child: AnimatedBuilder(
- // [AnimatedBuilder] accepts any [Listenable] subtype.
- animation: emailNotifier,
- builder: (BuildContext context, Widget? child) {
- return Text(
- emailNotifier.value!,
- style: enteTextTheme.body.copyWith(
- color: colorScheme.textMuted,
- overflow: TextOverflow.ellipsis,
- ),
- );
- },
- ),
- ),
+ AuthSettingsItem(
+ title: l10n.account,
+ icon: HugeIcons.strokeRoundedUser,
+ semanticsIdentifier: 'auth_settings_account',
+ onTap: () =>
+ pushAuthSettingsPage(context, const AccountSettingsPage()),
),
);
- contents.addAll([
- const SizedBox(height: 12),
- AccountSectionWidget(),
- sectionSpacing,
- ]);
+ contents.add(const SizedBox(height: Spacing.sm));
} else {
- contents.addAll([
- NotificationWidget(
- startIcon: Icons.account_circle_sharp,
- actionIcon: Icons.arrow_forward,
- text: context.l10n.signInToBackup,
- type: NotificationType.notice,
- onTap: () async {
- ButtonResult? result = await showChoiceActionSheet(
- context,
- title: context.l10n.note,
- body: context.l10n.sigInBackupReminder,
- secondButtonLabel: context.l10n.singIn,
- secondButtonAction: ButtonAction.second,
- firstButtonLabel: context.l10n.exportCodes,
- );
- if (result == null) return;
- if (result.action == ButtonAction.first) {
- if (!context.mounted) return;
- await handleExportClick(context);
- } else {
- if (!context.mounted) return;
- if (result.action == ButtonAction.second) {
- bool hasCodes = (await CodeStore.instance.getAllCodes())
- .where((element) => !element.hasError)
- .isNotEmpty;
- if (hasCodes) {
- if (!context.mounted) return;
- final hasAuthenticated = await LocalAuthenticationService
- .instance
- .requestLocalAuthentication(
- context,
- context.l10n.authToInitiateSignIn,
- );
- if (!hasAuthenticated) {
- return;
- }
- }
- if (!context.mounted) return;
- await routeToPage(context, const OnboardingPage());
- }
- }
- },
+ contents.add(
+ BannerComponent(
+ title: l10n.signInToBackup,
+ leadingIcon: HugeIcons.strokeRoundedCloudUpload,
+ state: BannerComponentState.informative,
+ onTap: () => _showBackupReminder(context),
),
- sectionSpacing,
- sectionSpacing,
- ]);
+ );
+ contents.add(const SizedBox(height: Spacing.lg));
}
+
contents.addAll([
- DataSectionWidget(),
- sectionSpacing,
- const SecuritySectionWidget(),
- sectionSpacing,
+ AuthSettingsItem(
+ title: l10n.data,
+ icon: HugeIcons.strokeRoundedDatabase01,
+ semanticsIdentifier: 'auth_settings_data',
+ onTap: () => _openDataSettings(context),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.security,
+ icon: HugeIcons.strokeRoundedSecurityCheck,
+ semanticsIdentifier: 'auth_settings_security',
+ onTap: () =>
+ pushAuthSettingsPage(context, const SecuritySettingsPage()),
+ ),
]);
if (Platform.isAndroid ||
Platform.isWindows ||
Platform.isLinux ||
kDebugMode) {
- contents.addAll([const ThemeSwitchWidget(), sectionSpacing]);
+ contents.addAll([
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.theme,
+ icon: Theme.of(context).brightness == Brightness.light
+ ? HugeIcons.strokeRoundedSun03
+ : HugeIcons.strokeRoundedMoon02,
+ semanticsIdentifier: 'auth_settings_theme',
+ onTap: () => pushAuthSettingsPage(context, const ThemeSettingsPage()),
+ ),
+ ]);
+ }
+
+ contents.addAll([
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.general,
+ icon: HugeIcons.strokeRoundedSettings01,
+ semanticsIdentifier: 'auth_settings_general',
+ onTap: () => pushAuthSettingsPage(context, const GeneralSettingsPage()),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.support,
+ icon: HugeIcons.strokeRoundedHelpCircle,
+ semanticsIdentifier: 'auth_settings_support',
+ onTap: () => pushAuthSettingsPage(context, const SupportSettingsPage()),
+ ),
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.about,
+ icon: HugeIcons.strokeRoundedInformationCircle,
+ semanticsIdentifier: 'auth_settings_about',
+ onTap: () => pushAuthSettingsPage(context, const AboutSettingsPage()),
+ ),
+ ]);
+
+ if (hasLoggedIn) {
+ contents.addAll([
+ const SizedBox(height: Spacing.sm),
+ AuthSettingsItem(
+ title: l10n.logout,
+ icon: HugeIcons.strokeRoundedLogout05,
+ semanticsIdentifier: 'auth_settings_logout',
+ isDestructive: true,
+ onTap: () => _logout(context),
+ ),
+ ]);
}
contents.addAll([
- const AdvancedSectionWidget(),
- sectionSpacing,
- const SupportSectionWidget(),
- sectionSpacing,
- const SocialSectionWidget(),
- sectionSpacing,
- const AboutSectionWidget(),
+ const SizedBox(height: Spacing.xxl),
+ const SocialIconsRow(),
const AppVersionWidget(),
const DeveloperSettingsWidget(),
const NotificationBannerWidget(),
- const Padding(padding: EdgeInsets.only(bottom: 60)),
+ const SizedBox(height: 60),
]);
- return SafeArea(
- bottom: false,
- child: SingleChildScrollView(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- SettingsTitleBarWidget(scaffoldKey: scaffoldKey),
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
- child: Column(children: contents),
- ),
- ],
- ),
+ return AuthSettingsPageScaffold(
+ title: l10n.settings,
+ subtitle: email,
+ backButton: _closeButton(context),
+ children: contents,
+ );
+ }
+
+ Widget _closeButton(BuildContext context) {
+ return Semantics(
+ identifier: 'auth_settings_close',
+ child: IconButtonComponent(
+ tooltip: context.l10n.close,
+ variant: IconButtonComponentVariant.unfilled,
+ shouldSurfaceExecutionStates: false,
+ icon: const HugeIcon(icon: HugeIcons.strokeRoundedCancel01),
+ onTap: () => scaffoldKey.currentState?.closeDrawer(),
),
);
}
+
+ Future<void> _openDataSettings(BuildContext context) async {
+ final completed = await Navigator.of(
+ context,
+ ).push<bool>(MaterialPageRoute(builder: (_) => const DataSettingsPage()));
+ if (completed == true) {
+ scaffoldKey.currentState?.closeDrawer();
+ }
+ }
+
+ Future<void> _showBackupReminder(BuildContext context) async {
+ final l10n = context.l10n;
+ final result = await showChoiceActionSheet(
+ context,
+ title: l10n.note,
+ body: l10n.sigInBackupReminder,
+ secondButtonLabel: l10n.singIn,
+ secondButtonAction: ButtonAction.second,
+ firstButtonLabel: l10n.exportCodes,
+ );
+ if (result == null || !context.mounted) return;
+ if (result.action == ButtonAction.first) {
+ await handleExportClick(context);
+ return;
+ }
+ if (result.action != ButtonAction.second) return;
+ final hasCodes = (await CodeStore.instance.getAllCodes()).any(
+ (code) => !code.hasError,
+ );
+ if (!context.mounted) return;
+ if (hasCodes) {
+ final authenticated = await LocalAuthenticationService.instance
+ .requestLocalAuthentication(context, l10n.authToInitiateSignIn);
+ if (!authenticated) return;
+ }
+ if (context.mounted) {
+ await pushAuthSettingsPage(context, const OnboardingPage());
+ }
+ }
+
+ Future<void> _logout(BuildContext context) {
+ final l10n = context.l10n;
+ return showChoiceActionSheet(
+ context,
+ title: l10n.logout,
+ body: l10n.areYouSureYouWantToLogout,
+ firstButtonLabel: l10n.yesLogout,
+ secondButtonLabel: l10n.cancel,
+ isCritical: true,
+ firstButtonOnTap: () => UserService.instance.logout(context),
+ );
+ }
}
diff --git a/mobile/apps/auth/lib/ui/share/code_share.dart b/mobile/apps/auth/lib/ui/share/code_share.dart
index e279ae9c63..58fc4bfcc9 100644
--- a/mobile/apps/auth/lib/ui/share/code_share.dart
+++ b/mobile/apps/auth/lib/ui/share/code_share.dart
@@ -2,14 +2,12 @@ import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
-import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/models/code.dart';
-import 'package:ente_auth/ui/components/buttons/button_widget.dart';
-import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_auth/utils/share_utils.dart';
import 'package:ente_auth/utils/totp_util.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:ente_crypto_api/ente_crypto_api.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
@@ -46,68 +44,63 @@ class _ShareCodeDialogState extends State<ShareCodeDialog> {
@override
Widget build(BuildContext context) {
- return AlertDialog(
- title: Text(context.l10n.shareCodes),
- content: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(context.l10n.shareCodesDuration),
- const SizedBox(height: 10),
- DropdownButtonHideUnderline(
- child: DropdownButton2(
- hint: Text(context.l10n.selectAnOption),
- items: _durationInMins
- .map(
- (item) => DropdownMenuItem<int>(
- value: item,
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(getItemLabel(item)),
- ),
+ final colors = context.componentColors;
+ return Semantics(
+ identifier: 'auth_share_code_sheet',
+ child: BottomSheetComponent(
+ title: context.l10n.shareCodes,
+ closeTooltip: context.l10n.close,
+ content: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ context.l10n.shareCodesDuration,
+ style: TextStyles.body.copyWith(color: colors.textLight),
+ ),
+ const SizedBox(height: Spacing.lg),
+ MenuGroupComponent(
+ showDividers: true,
+ items: [
+ for (final duration in _durationInMins)
+ MenuComponent(
+ title: getItemLabel(duration),
+ selected: selectedValue == duration,
+ trailing: RadioComponent(
+ selected: selectedValue == duration,
+ onChanged: (_) => _selectDuration(duration),
),
- )
- .toList(),
- value: selectedValue,
- onChanged: (value) {
- setState(() {
- selectedValue = value ?? 2;
- });
- },
+ onTap: () => _selectDuration(duration),
+ ),
+ ],
),
+ ],
+ ),
+ actions: [
+ ButtonComponent(
+ label: context.l10n.share,
+ onTap: () async {
+ try {
+ await shareCode(selectedValue);
+ if (context.mounted) Navigator.of(context).pop();
+ } catch (e, s) {
+ logger.severe('Failed to generate shared codes', e, s);
+ if (!context.mounted) return;
+ showGenericErrorDialog(context: context, error: e).ignore();
+ }
+ },
),
],
),
- actions: [
- ButtonWidget(
- buttonType: ButtonType.primary,
- buttonSize: ButtonSize.large,
- labelText: context.l10n.share,
- onTap: () async {
- try {
- if (!context.mounted) return;
- await shareCode(selectedValue);
- if (!context.mounted) return;
- Navigator.of(context).pop();
- } catch (e, s) {
- logger.severe('Failed to generate shared codes', e, s);
- showGenericErrorDialog(context: context, error: e).ignore();
- }
- },
- ),
- const SizedBox(height: 8),
- ButtonWidget(
- buttonType: ButtonType.secondary,
- buttonSize: ButtonSize.large,
- labelText: context.l10n.cancel,
- onTap: () async {
- Navigator.of(context).pop();
- },
- ),
- ],
);
}
+ void _selectDuration(int duration) {
+ if (selectedValue != duration) {
+ setState(() => selectedValue = duration);
+ }
+ }
+
Future<void> shareCode(int durationInMin) async {
final int count = ((durationInMin * 60.0) / widget.code.period).ceil();
final result = generateFutureTotpCodes(widget.code, count);
@@ -150,10 +143,9 @@ void showShareDialog(BuildContext context, Code code) {
if (!code.type.canShareCodes) {
return;
}
- showDialog(
+ showBottomSheetComponent<void>(
context: context,
- builder: (BuildContext context) {
- return ShareCodeDialog(code: code);
- },
+ useRootNavigator: true,
+ builder: (_) => ShareCodeDialog(code: code),
);
}
diff --git a/mobile/apps/auth/lib/ui/sort_option_menu.dart b/mobile/apps/auth/lib/ui/sort_option_menu.dart
index e820286066..69b381a0e2 100644
--- a/mobile/apps/auth/lib/ui/sort_option_menu.dart
+++ b/mobile/apps/auth/lib/ui/sort_option_menu.dart
@@ -1,13 +1,10 @@
import 'package:ente_auth/l10n/l10n.dart';
import 'package:ente_auth/services/preference_service.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
class SortCodeMenuWidget extends StatelessWidget {
- final CodeSortKey currentKey;
- final void Function(CodeSortKey) onSelected;
- final Color? iconColor;
-
const SortCodeMenuWidget({
super.key,
required this.currentKey,
@@ -15,72 +12,76 @@ class SortCodeMenuWidget extends StatelessWidget {
this.iconColor,
});
+ final CodeSortKey currentKey;
+ final void Function(CodeSortKey) onSelected;
+ final Color? iconColor;
+
@override
Widget build(BuildContext context) {
- Text sortOptionText(CodeSortKey key) {
- String text = key.toString();
- switch (key) {
- case CodeSortKey.issuerName:
- text = context.l10n.codeIssuerHint;
- break;
- case CodeSortKey.accountName:
- text = context.l10n.account;
- break;
- case CodeSortKey.mostFrequentlyUsed:
- text = context.l10n.mostFrequentlyUsed;
- break;
- case CodeSortKey.recentlyUsed:
- text = context.l10n.mostRecentlyUsed;
- break;
- case CodeSortKey.manual:
- text = context.l10n.manualSort;
- }
- return Text(
- text,
- style: Theme.of(context).textTheme.titleMedium!.copyWith(
- fontSize: 14,
- color: Theme.of(context).iconTheme.color!.withValues(alpha: 0.7),
+ final l10n = context.l10n;
+ return Semantics(
+ button: true,
+ label: l10n.editOrder,
+ identifier: 'auth_sort_codes',
+ child: IconButtonComponent(
+ variant: IconButtonComponentVariant.unfilled,
+ shouldSurfaceExecutionStates: false,
+ tooltip: l10n.editOrder,
+ icon: SvgPicture.asset(
+ 'assets/svg/filter-icon.svg',
+ width: IconSizes.medium,
+ height: IconSizes.medium,
+ colorFilter: ColorFilter.mode(
+ iconColor ?? context.componentColors.textBase,
+ BlendMode.srcIn,
+ ),
),
- );
- }
+ onTap: () => _showSortOptions(context),
+ ),
+ );
+ }
- return GestureDetector(
- onTapDown: (TapDownDetails details) async {
- final int? selectedValue = await showMenu<int>(
- context: context,
- position: RelativeRect.fromLTRB(
- details.globalPosition.dx,
- details.globalPosition.dy,
- details.globalPosition.dx,
- details.globalPosition.dy + 300,
+ Future<void> _showSortOptions(BuildContext context) {
+ final l10n = context.l10n;
+ return showBottomSheetComponent<void>(
+ context: context,
+ builder: (sheetContext) => Semantics(
+ identifier: 'auth_sort_sheet',
+ child: BottomSheetComponent(
+ title: l10n.editOrder,
+ closeTooltip: l10n.close,
+ content: MenuGroupComponent(
+ showDividers: true,
+ items: [
+ for (final key in CodeSortKey.values)
+ MenuComponent(
+ title: _labelFor(l10n, key),
+ selected: key == currentKey,
+ trailing: RadioComponent(
+ selected: key == currentKey,
+ onChanged: (_) => _select(sheetContext, key),
+ ),
+ onTap: () => _select(sheetContext, key),
+ ),
+ ],
),
- items: List.generate(CodeSortKey.values.length, (index) {
- return PopupMenuItem(
- value: index,
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- sortOptionText(CodeSortKey.values[index]),
- if (CodeSortKey.values[index] == currentKey)
- Icon(Icons.check, color: Theme.of(context).iconTheme.color),
- ],
- ),
- );
- }),
- );
- if (selectedValue != null) {
- onSelected(CodeSortKey.values[selectedValue]);
- }
- },
- child: SvgPicture.asset(
- 'assets/svg/filter-icon.svg',
- width: 26,
- height: 26,
- colorFilter: ColorFilter.mode(
- iconColor ?? Theme.of(context).iconTheme.color!,
- BlendMode.srcIn,
),
),
);
}
+
+ void _select(BuildContext sheetContext, CodeSortKey key) {
+ Navigator.of(sheetContext).pop();
+ onSelected(key);
+ }
+
+ String _labelFor(AppLocalizations l10n, CodeSortKey key) {
+ return switch (key) {
+ CodeSortKey.issuerName => l10n.codeIssuerHint,
+ CodeSortKey.accountName => l10n.account,
+ CodeSortKey.mostFrequentlyUsed => l10n.mostFrequentlyUsed,
+ CodeSortKey.recentlyUsed => l10n.mostRecentlyUsed,
+ CodeSortKey.manual => l10n.manualSort,
+ };
+ }
}
diff --git a/mobile/apps/auth/lib/ui/topt_selector_widget.dart b/mobile/apps/auth/lib/ui/topt_selector_widget.dart
deleted file mode 100644
index f84935d8f7..0000000000
--- a/mobile/apps/auth/lib/ui/topt_selector_widget.dart
+++ /dev/null
@@ -1,69 +0,0 @@
-import 'package:ente_auth/models/code.dart';
-import 'package:ente_auth/theme/ente_theme.dart';
-import 'package:flutter/material.dart';
-
-class ToptSelectorWidget extends StatelessWidget {
- final Type currentTopt;
- final void Function(Type) onSelected;
- const ToptSelectorWidget({
- super.key,
- required this.currentTopt,
- required this.onSelected,
- });
-
- @override
- Widget build(BuildContext context) {
- Text toptOptionText(Type type) {
- return Text(
- type.name.toUpperCase(),
- style: getEnteTextTheme(context).small,
- );
- }
-
- return GestureDetector(
- onTapDown: (TapDownDetails details) async {
- final int? selectedValue = await showMenu<int>(
- context: context,
- position: RelativeRect.fromLTRB(
- details.globalPosition.dx,
- details.globalPosition.dy,
- details.globalPosition.dx,
- details.globalPosition.dy + 300,
- ),
- items: List.generate(Type.values.length, (index) {
- return PopupMenuItem(
- value: index,
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- toptOptionText(Type.values[index]),
- if (Type.values[index] == currentTopt)
- Icon(Icons.check, color: Theme.of(context).iconTheme.color),
- ],
- ),
- );
- }),
- );
- if (selectedValue != null) {
- onSelected(Type.values[selectedValue]);
- }
- },
- child: Container(
- padding: const EdgeInsets.only(bottom: 4),
- decoration: BoxDecoration(
- border: Border(
- bottom: BorderSide(color: Theme.of(context).dividerColor),
- ),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- toptOptionText(currentTopt),
- const SizedBox(width: 8),
- const Icon(Icons.arrow_drop_down),
- ],
- ),
- ),
- );
- }
-}
diff --git a/mobile/apps/auth/lib/utils/debug_build_flags.dart b/mobile/apps/auth/lib/utils/debug_build_flags.dart
new file mode 100644
index 0000000000..519f10cfbd
--- /dev/null
+++ b/mobile/apps/auth/lib/utils/debug_build_flags.dart
@@ -0,0 +1,10 @@
+import 'package:flutter/foundation.dart';
+
+const _skipGuidance = bool.fromEnvironment('ENTE_AUTH_SKIP_GUIDANCE');
+const _allowScreenCapture = bool.fromEnvironment(
+ 'ENTE_AUTH_ALLOW_SCREEN_CAPTURE',
+);
+
+bool get shouldSkipAuthGuidance => kDebugMode && _skipGuidance;
+
+bool get shouldAllowAuthScreenCapture => kDebugMode && _allowScreenCapture;
diff --git a/mobile/apps/auth/lib/utils/debug_code_deep_link.dart b/mobile/apps/auth/lib/utils/debug_code_deep_link.dart
new file mode 100644
index 0000000000..b92d2fd46d
--- /dev/null
+++ b/mobile/apps/auth/lib/utils/debug_code_deep_link.dart
@@ -0,0 +1,41 @@
+import 'package:flutter/foundation.dart';
+
+enum DebugCodeDeepLinkAction { addCode, showQr, shareCode, showIcons }
+
+class DebugCodeDeepLink {
+ const DebugCodeDeepLink({required this.action, required this.codeUri});
+
+ final DebugCodeDeepLinkAction action;
+ final String codeUri;
+}
+
+/// Parses debug-only code links used by offline UI automation.
+///
+/// iOS may route `otpauth://` links to the system Passwords app, even when
+/// Ente Auth is installed. Wrapping the URI in Ente Auth's own scheme keeps
+/// deterministic Maestro setup and visual previews out of release builds.
+DebugCodeDeepLink? parseDebugCodeDeepLink(String link) {
+ if (!kDebugMode) return null;
+
+ final uri = Uri.tryParse(link);
+ if (uri == null ||
+ uri.scheme.toLowerCase() != 'enteauth' ||
+ uri.host.toLowerCase() != 'debug') {
+ return null;
+ }
+
+ final action = switch (uri.path) {
+ '/add-code' => DebugCodeDeepLinkAction.addCode,
+ '/show-qr' => DebugCodeDeepLinkAction.showQr,
+ '/share-code' => DebugCodeDeepLinkAction.shareCode,
+ '/show-icons' => DebugCodeDeepLinkAction.showIcons,
+ _ => null,
+ };
+ final codeUri = uri.queryParameters['uri'];
+ if (action == null ||
+ codeUri == null ||
+ !codeUri.toLowerCase().startsWith('otpauth://')) {
+ return null;
+ }
+ return DebugCodeDeepLink(action: action, codeUri: codeUri);
+}
diff --git a/mobile/apps/auth/lib/utils/dialog_util.dart b/mobile/apps/auth/lib/utils/dialog_util.dart
index 12d3d157a0..b95cef4f8b 100644
--- a/mobile/apps/auth/lib/utils/dialog_util.dart
+++ b/mobile/apps/auth/lib/utils/dialog_util.dart
@@ -4,7 +4,6 @@ import 'dart:math';
import 'package:confetti/confetti.dart';
import "package:dio/dio.dart";
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/theme/colors.dart';
import 'package:ente_auth/ui/common/loading_widget.dart';
import 'package:ente_auth/ui/components/action_sheet_widget.dart';
import 'package:ente_auth/ui/components/buttons/button_widget.dart';
@@ -15,6 +14,7 @@ import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/utils/email_util.dart';
import 'package:ente_auth/utils/platform_util.dart';
import 'package:ente_base/typedefs.dart';
+import 'package:ente_components/ente_components.dart';
import 'package:ente_ui/components/progress_dialog.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
@@ -415,38 +415,27 @@ Future<dynamic> showTextInputDialog(
bool useRootNavigator = false,
VoidCallback? onCancel,
}) {
- return showDialog(
- barrierColor: backdropFaintDark,
+ return showBottomSheetComponent<dynamic>(
useRootNavigator: useRootNavigator,
context: context,
- builder: (context) {
- final bottomInset = MediaQuery.of(context).viewInsets.bottom;
- final isKeyboardUp = bottomInset > 100;
- return Material(
- color: Colors.transparent,
- child: Center(
- child: Padding(
- padding: EdgeInsets.only(bottom: isKeyboardUp ? bottomInset : 0),
- child: TextInputDialog(
- title: title,
- message: message,
- label: label,
- body: body,
- icon: icon,
- submitButtonLabel: submitButtonLabel,
- onSubmit: onSubmit,
- hintText: hintText,
- prefixIcon: prefixIcon,
- initialValue: initialValue,
- alignMessage: alignMessage,
- maxLength: maxLength,
- showOnlyLoadingState: showOnlyLoadingState,
- textCapitalization: textCapitalization,
- alwaysShowSuccessState: alwaysShowSuccessState,
- isPasswordInput: isPasswordInput,
- ),
- ),
- ),
+ builder: (_) {
+ return TextInputDialog(
+ title: title,
+ message: message,
+ label: label,
+ body: body,
+ icon: icon,
+ submitButtonLabel: submitButtonLabel,
+ onSubmit: onSubmit,
+ hintText: hintText,
+ prefixIcon: prefixIcon,
+ initialValue: initialValue,
+ alignMessage: alignMessage,
+ maxLength: maxLength,
+ showOnlyLoadingState: showOnlyLoadingState,
+ textCapitalization: textCapitalization,
+ alwaysShowSuccessState: alwaysShowSuccessState,
+ isPasswordInput: isPasswordInput,
);
},
);
diff --git a/mobile/apps/auth/lib/utils/gallery_import_util.dart b/mobile/apps/auth/lib/utils/gallery_import_util.dart
index 9a0a120586..5cbde3d993 100644
--- a/mobile/apps/auth/lib/utils/gallery_import_util.dart
+++ b/mobile/apps/auth/lib/utils/gallery_import_util.dart
@@ -16,12 +16,15 @@ const _pickedImagesDirectoryName = 'picked_images';
class GalleryImportResult {
final Code? code;
- final List<Code>? googleAuthCodes;
+ final GoogleAuthMigration? googleAuthMigration;
- const GalleryImportResult.code(Code this.code) : googleAuthCodes = null;
+ const GalleryImportResult.code(Code this.code) : googleAuthMigration = null;
- const GalleryImportResult.googleAuthCodes(List<Code> this.googleAuthCodes)
- : code = null;
+ const GalleryImportResult.googleAuthMigration(
+ GoogleAuthMigration this.googleAuthMigration,
+ ) : code = null;
+
+ List<Code>? get googleAuthCodes => googleAuthMigration?.codes;
}
Future<Directory> _getPickedImagesDirectory({
@@ -32,9 +35,19 @@ Future<Directory> _getPickedImagesDirectory({
return Directory(p.join(documentsDirectory.path, _pickedImagesDirectoryName));
}
-Future<File?> _getManagedPickedGalleryImage(
+class _PickedImageCleanup {
+ const _PickedImageCleanup(this.file, {required this.excludeParentFromBackup});
+
+ final File file;
+ final bool excludeParentFromBackup;
+}
+
+Future<_PickedImageCleanup?> _getPickedImageCleanup(
String imagePath, {
+ bool includeTemporaryDirectory = false,
Future<Directory> Function()? documentsDirectoryProvider,
+ Future<Directory> Function()? temporaryDirectoryProvider,
+ Directory? systemTemporaryDirectory,
}) async {
if (!Platform.isIOS) {
return null;
@@ -43,13 +56,30 @@ Future<File?> _getManagedPickedGalleryImage(
final pickedImagesDirectory = await _getPickedImagesDirectory(
documentsDirectoryProvider: documentsDirectoryProvider,
);
- if (!p.isWithin(
+ if (p.isWithin(
p.normalize(pickedImagesDirectory.path),
p.normalize(imagePath),
)) {
- return null;
+ return _PickedImageCleanup(File(imagePath), excludeParentFromBackup: true);
}
- return File(imagePath);
+
+ if (!includeTemporaryDirectory) return null;
+ final temporaryDirectories = <Directory>[
+ await (temporaryDirectoryProvider ?? getTemporaryDirectory)(),
+ systemTemporaryDirectory ?? Directory.systemTemp,
+ ];
+ for (final temporaryDirectory in temporaryDirectories) {
+ if (p.isWithin(
+ p.normalize(temporaryDirectory.path),
+ p.normalize(imagePath),
+ )) {
+ return _PickedImageCleanup(
+ File(imagePath),
+ excludeParentFromBackup: false,
+ );
+ }
+ }
+ return null;
}
Future<void> _clearPickedImagesDirectoryContents(
@@ -103,27 +133,31 @@ Future<void> cleanupPickedImagesOnStartup({Logger? logger}) async {
GalleryImportResult parseQrImportPayload(String qrCodeData) {
if (isGoogleAuthExportQr(qrCodeData)) {
- final codes = parseGoogleAuth(qrCodeData);
- if (codes.isEmpty) {
+ final migration = parseGoogleAuthMigration(qrCodeData);
+ if (migration.codes.isEmpty) {
throw const FormatException('No Google Authenticator codes found');
}
- return GalleryImportResult.googleAuthCodes(codes);
+ return GalleryImportResult.googleAuthMigration(migration);
}
return GalleryImportResult.code(Code.fromOTPAuthUrl(qrCodeData));
}
/// Prompts the user to pick an image and tries to extract auth codes from it.
/// Returns the parsed QR import result when successful, otherwise null.
-Future<GalleryImportResult?> pickCodeFromGallery(
+Future<GalleryImportResult?> pickCodeFromImage(
BuildContext context, {
Logger? logger,
+ bool pickFromFiles = false,
}) async {
final l10n = context.l10n;
try {
if (!context.mounted) return null;
final FilePickerResult? result = await FilePicker.platform.pickFiles(
- type: FileType.image,
+ type: pickFromFiles ? FileType.custom : FileType.image,
+ allowedExtensions: pickFromFiles
+ ? const ['png', 'jpg', 'jpeg', 'webp', 'heic']
+ : null,
);
if (result == null || result.files.single.path == null) {
@@ -131,9 +165,12 @@ Future<GalleryImportResult?> pickCodeFromGallery(
}
final String imagePath = result.files.single.path!;
- final managedPickedImage = await _getManagedPickedGalleryImage(imagePath);
- if (managedPickedImage != null) {
- await excludeFromBackup(managedPickedImage.parent.path);
+ final pickedImageCleanup = await _getPickedImageCleanup(
+ imagePath,
+ includeTemporaryDirectory: pickFromFiles,
+ );
+ if (pickedImageCleanup?.excludeParentFromBackup ?? false) {
+ await excludeFromBackup(pickedImageCleanup!.file.parent.path);
}
try {
@@ -177,9 +214,9 @@ Future<GalleryImportResult?> pickCodeFromGallery(
);
return null;
} finally {
- if (managedPickedImage != null) {
+ if (pickedImageCleanup != null) {
await _cleanupPickedGalleryImageIfNeeded(
- managedPickedImage,
+ pickedImageCleanup.file,
logger: logger,
);
}
diff --git a/mobile/apps/auth/pubspec.yaml b/mobile/apps/auth/pubspec.yaml
index c5408d8401..e14d0753b6 100644
--- a/mobile/apps/auth/pubspec.yaml
+++ b/mobile/apps/auth/pubspec.yaml
@@ -143,6 +143,7 @@ dev_dependencies:
flutter_lints: 6.0.0
flutter_test:
sdk: flutter
+ qr: 3.0.2
shared_preferences_platform_interface: 2.4.2
# The following section is specific to Flutter.
diff --git a/mobile/apps/auth/test/onboarding/setup_enter_secret_key_page_test.dart b/mobile/apps/auth/test/onboarding/setup_enter_secret_key_page_test.dart
new file mode 100644
index 0000000000..b0c417615c
--- /dev/null
+++ b/mobile/apps/auth/test/onboarding/setup_enter_secret_key_page_test.dart
@@ -0,0 +1,84 @@
+import 'package:ente_auth/models/code.dart';
+import 'package:ente_auth/onboarding/view/setup_enter_secret_key_page.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ test('new and short manual codes retain the entry limit', () {
+ expect(
+ SetupEnterSecretKeyPage.manualCodeTextLimitFor(null),
+ SetupEnterSecretKeyPage.manualCodeTextLimit,
+ );
+ expect(
+ SetupEnterSecretKeyPage.manualCodeTextLimitFor(_code()),
+ SetupEnterSecretKeyPage.manualCodeTextLimit,
+ );
+ });
+
+ test('legacy manual codes at the limit remain unrestricted', () {
+ final boundaryValue = _repeated(
+ 'a',
+ SetupEnterSecretKeyPage.manualCodeTextLimit,
+ );
+
+ expect(
+ SetupEnterSecretKeyPage.manualCodeTextLimitFor(
+ _code(issuer: boundaryValue),
+ ),
+ isNull,
+ );
+ expect(
+ SetupEnterSecretKeyPage.manualCodeTextLimitFor(
+ _code(account: boundaryValue),
+ ),
+ isNull,
+ );
+ expect(
+ SetupEnterSecretKeyPage.manualCodeTextLimitFor(
+ _code(secret: boundaryValue),
+ ),
+ isNull,
+ );
+ });
+
+ testWidgets('editing a long legacy value does not truncate it', (
+ tester,
+ ) async {
+ final existingValue = _repeated(
+ 'a',
+ SetupEnterSecretKeyPage.manualCodeTextLimit + 1,
+ );
+ final updatedValue = '${existingValue}b';
+ final controller = TextEditingController(text: existingValue);
+ addTearDown(controller.dispose);
+
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ComponentTheme.lightTheme(app: ComponentApp.auth),
+ home: Scaffold(
+ body: TextInputComponent(
+ controller: controller,
+ maxLength: SetupEnterSecretKeyPage.manualCodeTextLimitFor(
+ _code(secret: existingValue),
+ ),
+ ),
+ ),
+ ),
+ );
+
+ await tester.enterText(find.byType(TextField), updatedValue);
+
+ expect(controller.text, updatedValue);
+ });
+}
+
+Code _code({
+ String issuer = 'Ente',
+ String account = '[email protected]',
+ String secret = 'JBSWY3DPEHPK3PXP',
+}) {
+ return Code.fromAccountAndSecret(Type.totp, account, issuer, secret, null, 6);
+}
+
+String _repeated(String value, int count) => List.filled(count, value).join();
diff --git a/mobile/apps/auth/test/ui/components/component_dialog_adapters_test.dart b/mobile/apps/auth/test/ui/components/component_dialog_adapters_test.dart
new file mode 100644
index 0000000000..ab85348fed
--- /dev/null
+++ b/mobile/apps/auth/test/ui/components/component_dialog_adapters_test.dart
@@ -0,0 +1,155 @@
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/ui/components/action_sheet_widget.dart';
+import 'package:ente_auth/ui/components/buttons/button_widget.dart';
+import 'package:ente_auth/ui/components/dialog_widget.dart';
+import 'package:ente_auth/ui/components/models/button_result.dart';
+import 'package:ente_auth/ui/components/models/button_type.dart';
+import 'package:ente_auth/utils/dialog_util.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ testWidgets('legacy action sheets render with Ente components', (
+ tester,
+ ) async {
+ await _pumpLauncher(
+ tester,
+ (context) => showActionSheet(
+ context: context,
+ title: 'Trash code?',
+ body: 'The code can be restored later.',
+ buttons: const [
+ ButtonWidget(
+ buttonType: ButtonType.critical,
+ labelText: 'Trash',
+ isInAlert: true,
+ buttonAction: ButtonAction.first,
+ ),
+ ButtonWidget(
+ buttonType: ButtonType.secondary,
+ labelText: 'Cancel',
+ isInAlert: true,
+ buttonAction: ButtonAction.cancel,
+ ),
+ ],
+ ),
+ );
+
+ await _openLauncher(tester);
+
+ expect(find.byType(BottomSheetComponent), findsOneWidget);
+ expect(find.byType(ButtonWidget), findsNothing);
+ expect(find.text('Trash code?'), findsOneWidget);
+ expect(find.text('The code can be restored later.'), findsOneWidget);
+ expect(find.text('Cancel'), findsNothing);
+ expect(find.byTooltip('Close'), findsOneWidget);
+ final button = tester.widget<ButtonComponent>(
+ find.widgetWithText(ButtonComponent, 'Trash'),
+ );
+ expect(button.variant, ButtonComponentVariant.critical);
+ });
+
+ testWidgets('legacy dialog returns its component button action', (
+ tester,
+ ) async {
+ ButtonResult? result;
+ await _pumpLauncher(tester, (context) async {
+ result = await showDialogWidget(
+ context: context,
+ title: 'Continue?',
+ buttons: const [
+ ButtonWidget(
+ buttonType: ButtonType.neutral,
+ labelText: 'Continue',
+ isInAlert: true,
+ buttonAction: ButtonAction.first,
+ ),
+ ],
+ );
+ });
+
+ await _openLauncher(tester);
+ expect(find.byType(BottomSheetComponent), findsOneWidget);
+ expect(find.byType(Dialog), findsNothing);
+
+ await tester.tap(find.text('Continue'));
+ await tester.pumpAndSettle();
+
+ expect(result?.action, ButtonAction.first);
+ expect(find.byType(BottomSheetComponent), findsNothing);
+ });
+
+ testWidgets('text input dialogs use component input and submit button', (
+ tester,
+ ) async {
+ String? submittedValue;
+ await _pumpLauncher(
+ tester,
+ (context) => showTextInputDialog(
+ context,
+ title: 'Create tag',
+ submitButtonLabel: 'Create',
+ onSubmit: (value) async => submittedValue = value,
+ ),
+ );
+
+ await _openLauncher(tester);
+
+ expect(find.byType(BottomSheetComponent), findsOneWidget);
+ expect(find.byType(TextInputComponent), findsOneWidget);
+ expect(
+ tester
+ .widget<ButtonComponent>(
+ find.widgetWithText(ButtonComponent, 'Create'),
+ )
+ .isDisabled,
+ isTrue,
+ );
+
+ await tester.enterText(find.byType(TextField), 'Work');
+ await tester.pump();
+ expect(
+ tester
+ .widget<ButtonComponent>(
+ find.widgetWithText(ButtonComponent, 'Create'),
+ )
+ .isDisabled,
+ isFalse,
+ );
+
+ await tester.tap(find.text('Create'));
+ await tester.pumpAndSettle();
+
+ expect(submittedValue, 'Work');
+ expect(find.byType(BottomSheetComponent), findsNothing);
+ });
+}
+
+Future<void> _pumpLauncher(
+ WidgetTester tester,
+ Future<dynamic> Function(BuildContext context) onOpen,
+) {
+ return tester.pumpWidget(
+ MaterialApp(
+ theme: ComponentTheme.lightTheme(app: ComponentApp.auth),
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: Center(
+ child: ElevatedButton(
+ onPressed: () => onOpen(context),
+ child: const Text('Open'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+}
+
+Future<void> _openLauncher(WidgetTester tester) async {
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+}
diff --git a/mobile/apps/auth/test/ui/settings/components/auth_settings_components_test.dart b/mobile/apps/auth/test/ui/settings/components/auth_settings_components_test.dart
new file mode 100644
index 0000000000..c8892148ee
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/components/auth_settings_components_test.dart
@@ -0,0 +1,87 @@
+import 'package:ente_auth/ui/settings/components/auth_settings_item.dart';
+import 'package:ente_auth/ui/settings/components/auth_settings_page_scaffold.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:hugeicons/hugeicons.dart';
+
+void main() {
+ testWidgets('settings item exposes its identifier and handles taps', (
+ tester,
+ ) async {
+ var tapped = false;
+
+ await _pump(
+ tester,
+ AuthSettingsItem(
+ title: 'Security',
+ icon: HugeIcons.strokeRoundedSquareLock02,
+ semanticsIdentifier: 'auth_settings_security',
+ onTap: () => tapped = true,
+ ),
+ );
+
+ expect(find.text('Security'), findsOneWidget);
+ expect(find.byType(HugeIcon), findsOneWidget);
+ expect(find.byIcon(Icons.chevron_right_outlined), findsOneWidget);
+
+ final semantics = tester.widget<Semantics>(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is Semantics &&
+ widget.properties.identifier == 'auth_settings_security',
+ ),
+ );
+ expect(semantics.properties.identifier, 'auth_settings_security');
+
+ await tester.tap(find.text('Security'));
+ await tester.pump();
+ expect(tapped, isTrue);
+ });
+
+ testWidgets('settings item supports destructive and non-navigation rows', (
+ tester,
+ ) async {
+ await _pump(
+ tester,
+ const AuthSettingsItem(
+ title: 'Delete account',
+ isDestructive: true,
+ showChevron: false,
+ trailing: Switch(value: true, onChanged: null),
+ ),
+ );
+
+ final title = tester.widget<Text>(find.text('Delete account'));
+ expect(title.style?.color, ColorTokens.light.warning);
+ expect(find.byIcon(Icons.chevron_right_outlined), findsNothing);
+ expect(find.byType(Switch), findsOneWidget);
+ });
+
+ testWidgets('settings scaffold uses the component surface and renders body', (
+ tester,
+ ) async {
+ await _pump(
+ tester,
+ const AuthSettingsPageScaffold(
+ title: 'Data',
+ children: [Text('Import codes')],
+ ),
+ );
+
+ expect(find.text('Data'), findsOneWidget);
+ expect(find.text('Import codes'), findsOneWidget);
+ expect(find.byType(AppBarComponent), findsOneWidget);
+ final scaffold = tester.widget<Scaffold>(find.byType(Scaffold));
+ expect(scaffold.backgroundColor, ColorTokens.light.backgroundBase);
+ });
+}
+
+Future<void> _pump(WidgetTester tester, Widget child) {
+ return tester.pumpWidget(
+ MaterialApp(
+ theme: ComponentTheme.lightTheme(app: ComponentApp.auth),
+ home: child,
+ ),
+ );
+}
diff --git a/mobile/apps/auth/test/ui/settings/data/import/fixtures/plain_text_import.txt b/mobile/apps/auth/test/ui/settings/data/import/fixtures/plain_text_import.txt
new file mode 100644
index 0000000000..2efbc467dc
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/data/import/fixtures/plain_text_import.txt
@@ -0,0 +1,2 @@
+otpauth://totp/GitHub:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=GitHub&algorithm=SHA1&digits=6&period=30
+otpauth://hotp/Yubico:[email protected]?secret=ASKZNWOU6SVYAMVS&issuer=Yubico&algorithm=SHA1&digits=6&counter=1
diff --git a/mobile/apps/auth/test/ui/settings/data/import/fixtures/rich_display_import.txt b/mobile/apps/auth/test/ui/settings/data/import/fixtures/rich_display_import.txt
new file mode 100644
index 0000000000..b979079a06
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/data/import/fixtures/rich_display_import.txt
@@ -0,0 +1,74 @@
+{
+ "items": [
+ {
+ "rawData": "otpauth://totp/GitHub:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=GitHub&algorithm=SHA1&digits=6&period=30",
+ "display": {
+ "pinned": true,
+ "trashed": false,
+ "lastUsedAt": 1720000000,
+ "tapCount": 12,
+ "tags": ["Work", "Admin"],
+ "note": "Primary admin account. Keep recovery contacts current.",
+ "position": 0,
+ "iconSrc": "",
+ "iconID": ""
+ }
+ },
+ {
+ "rawData": "otpauth://totp/Dropbox:[email protected]?secret=KRSXG5DSNFXGOIDB&issuer=Dropbox&algorithm=SHA1&digits=6&period=30",
+ "display": {
+ "pinned": false,
+ "trashed": true,
+ "lastUsedAt": 0,
+ "tapCount": 0,
+ "tags": ["Time capsule", "Archived"],
+ "note": "Intentionally kept in trash for restore testing.",
+ "position": 4,
+ "iconSrc": "",
+ "iconID": ""
+ }
+ },
+ {
+ "rawData": "otpauth://totp/Stripe:treasury%[email protected]?secret=MFRGGZDFMZTWQ2LK&issuer=Stripe&algorithm=SHA256&digits=8&period=45",
+ "display": {
+ "pinned": false,
+ "trashed": false,
+ "lastUsedAt": 1710000000,
+ "tapCount": 5,
+ "tags": ["Money moves", "Finance"],
+ "note": "Eight-digit SHA-256 code for the demo treasury.",
+ "position": 1,
+ "iconSrc": "",
+ "iconID": ""
+ }
+ },
+ {
+ "rawData": "otpauth://steam/Steam:[email protected]?secret=ONSWG4TFOQXG64RA&issuer=Steam",
+ "display": {
+ "pinned": true,
+ "trashed": false,
+ "lastUsedAt": 1700000000,
+ "tapCount": 20,
+ "tags": ["Game night"],
+ "note": "Steam-compatible five-character code.",
+ "position": 2,
+ "iconSrc": "",
+ "iconID": ""
+ }
+ },
+ {
+ "rawData": "otpauth://hotp/Yubico:[email protected]?secret=ORSXG5AAMFZGK3TH&issuer=Yubico&algorithm=SHA512&digits=6&counter=42",
+ "display": {
+ "pinned": false,
+ "trashed": false,
+ "lastUsedAt": 0,
+ "tapCount": 0,
+ "tags": ["Hardware keys", "Lab"],
+ "note": "HOTP fixture for counter advancement.",
+ "position": 3,
+ "iconSrc": "",
+ "iconID": ""
+ }
+ }
+ ]
+}
diff --git a/mobile/apps/auth/test/ui/settings/data/import/google_auth_import_test.dart b/mobile/apps/auth/test/ui/settings/data/import/google_auth_import_test.dart
index f1815814eb..8dc05d7f2b 100644
--- a/mobile/apps/auth/test/ui/settings/data/import/google_auth_import_test.dart
+++ b/mobile/apps/auth/test/ui/settings/data/import/google_auth_import_test.dart
@@ -5,6 +5,7 @@ import 'package:base32/base32.dart';
import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/models/protos/googleauth.pb.dart';
import 'package:ente_auth/ui/settings/data/import/google_auth_import.dart';
+import 'package:ente_auth/ui/settings/data/import/google_auth_migration_tracker.dart';
import 'package:ente_auth/utils/gallery_import_util.dart';
import 'package:fixnum/fixnum.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -30,6 +31,86 @@ void main() {
expect(codes[1].type, Type.hotp);
});
+ test('parses Google Authenticator migration batch metadata', () {
+ final migration = parseGoogleAuthMigration(
+ _testGoogleAuthQrCode(
+ _testSecret(),
+ batchId: 42,
+ batchSize: 3,
+ batchIndex: 2,
+ ),
+ );
+
+ expect(migration.batchId, 42);
+ expect(migration.batchSize, 3);
+ expect(migration.batchIndex, 2);
+ expect(migration.hasValidBatchMetadata, true);
+ });
+
+ test('completes a single-batch Google Authenticator migration', () {
+ final tracker = GoogleAuthMigrationTracker();
+
+ expect(
+ tracker.record(_testMigration(batchId: 42, batchSize: 1, batchIndex: 0)),
+ true,
+ );
+ });
+
+ test('waits for every Google Authenticator migration batch', () {
+ final tracker = GoogleAuthMigrationTracker();
+
+ expect(
+ tracker.record(_testMigration(batchId: 42, batchSize: 3, batchIndex: 2)),
+ false,
+ );
+ expect(
+ tracker.record(_testMigration(batchId: 42, batchSize: 3, batchIndex: 0)),
+ false,
+ );
+ expect(
+ tracker.record(_testMigration(batchId: 42, batchSize: 3, batchIndex: 1)),
+ true,
+ );
+ });
+
+ test('does not count duplicate or unrelated migration batches', () {
+ final tracker = GoogleAuthMigrationTracker();
+
+ expect(
+ tracker.record(_testMigration(batchId: 42, batchSize: 2, batchIndex: 0)),
+ false,
+ );
+ expect(
+ tracker.record(_testMigration(batchId: 42, batchSize: 2, batchIndex: 0)),
+ false,
+ );
+ expect(
+ tracker.record(_testMigration(batchId: 7, batchSize: 2, batchIndex: 1)),
+ false,
+ );
+ expect(
+ tracker.record(_testMigration(batchId: 42, batchSize: 2, batchIndex: 1)),
+ true,
+ );
+ });
+
+ test('does not complete without valid migration batch metadata', () {
+ final tracker = GoogleAuthMigrationTracker();
+
+ expect(
+ tracker.record(_testMigration(batchId: 0, batchSize: 2, batchIndex: 1)),
+ false,
+ );
+ expect(
+ tracker.record(_testMigration(batchId: 42, batchSize: 0, batchIndex: 0)),
+ false,
+ );
+ expect(
+ tracker.record(_testMigration(batchId: 42, batchSize: 2, batchIndex: 2)),
+ false,
+ );
+ });
+
test('classifies Google Authenticator QR payloads from images', () {
final qrCode = _testGoogleAuthQrCode(_testSecret());
@@ -38,6 +119,7 @@ void main() {
expect(result.code, isNull);
expect(result.googleAuthCodes, hasLength(2));
expect(result.googleAuthCodes![0].issuer, 'GitHub');
+ expect(result.googleAuthMigration?.batchSize, 0);
});
test('classifies standard OTP QR payloads from images', () {
@@ -56,8 +138,16 @@ Uint8List _testSecret() {
return Uint8List.fromList([1, 2, 3, 4, 5, 6, 7, 8]);
}
-String _testGoogleAuthQrCode(Uint8List secret) {
+String _testGoogleAuthQrCode(
+ Uint8List secret, {
+ int batchId = 0,
+ int batchSize = 0,
+ int batchIndex = 0,
+}) {
final payload = MigrationPayload()
+ ..batchId = batchId
+ ..batchSize = batchSize
+ ..batchIndex = batchIndex
..otpParameters.add(
MigrationPayload_OtpParameters()
..issuer = 'GitHub'
@@ -79,3 +169,16 @@ String _testGoogleAuthQrCode(Uint8List secret) {
);
return '$kGoogleAuthExportPrefix${Uri.encodeComponent(base64Encode(payload.writeToBuffer()))}';
}
+
+GoogleAuthMigration _testMigration({
+ required int batchId,
+ required int batchSize,
+ required int batchIndex,
+}) {
+ return GoogleAuthMigration(
+ codes: const [],
+ batchId: batchId,
+ batchSize: batchSize,
+ batchIndex: batchIndex,
+ );
+}
diff --git a/mobile/apps/auth/test/ui/settings/data/import/import_page_test.dart b/mobile/apps/auth/test/ui/settings/data/import/import_page_test.dart
new file mode 100644
index 0000000000..f19ff4bc5e
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/data/import/import_page_test.dart
@@ -0,0 +1,66 @@
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/ui/settings/data/import_page.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ testWidgets(
+ 'import page uses a grouped source list with stable identifiers',
+ (tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ComponentTheme.lightTheme(app: ComponentApp.auth),
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: const ImportCodePage(),
+ ),
+ );
+
+ expect(find.text('Import codes'), findsOneWidget);
+ expect(find.byType(MenuGroupComponent), findsOneWidget);
+ expect(find.text('Plain text'), findsOneWidget);
+ expect(find.text('Ente Encrypted export'), findsOneWidget);
+ expect(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is Semantics &&
+ widget.properties.identifier == 'auth_import_plainText',
+ ),
+ findsOneWidget,
+ );
+ },
+ );
+
+ testWidgets('plain text source opens an Ente instruction sheet', (
+ tester,
+ ) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ComponentTheme.lightTheme(app: ComponentApp.auth),
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: const ImportCodePage(),
+ ),
+ );
+
+ await tester.tap(find.text('Plain text'));
+ await tester.pumpAndSettle();
+
+ expect(find.text('Select file'), findsOneWidget);
+ expect(find.byTooltip('Cancel'), findsOneWidget);
+ expect(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is Semantics &&
+ widget.properties.identifier ==
+ 'auth_import_instruction_plain_text',
+ ),
+ findsOneWidget,
+ );
+
+ await tester.tap(find.byTooltip('Cancel'));
+ await tester.pumpAndSettle();
+ expect(find.text('Select file'), findsNothing);
+ });
+}
diff --git a/mobile/apps/auth/test/ui/settings/data/import/plain_text_import_parser_test.dart b/mobile/apps/auth/test/ui/settings/data/import/plain_text_import_parser_test.dart
new file mode 100644
index 0000000000..cf67e77fb9
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/data/import/plain_text_import_parser_test.dart
@@ -0,0 +1,77 @@
+import 'dart:io';
+
+import 'package:ente_auth/models/code.dart';
+import 'package:ente_auth/ui/settings/data/import/plain_text_import_parser.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ group('plain text import parser', () {
+ test('parses the offline Maestro fixture', () async {
+ final content = await File(
+ 'test/ui/settings/data/import/fixtures/plain_text_import.txt',
+ ).readAsString();
+
+ final codes = parsePlainTextImport(content);
+
+ expect(codes, hasLength(2));
+ expect(codes[0].type, Type.totp);
+ expect(codes[0].issuer, 'GitHub');
+ expect(codes[0].account, '[email protected]');
+ expect(codes[1].type, Type.hotp);
+ expect(codes[1].issuer, 'Yubico');
+ expect(codes[1].account, '[email protected]');
+ expect(codes[1].counter, 1);
+ });
+
+ test('keeps valid OTP entries when one entry is malformed', () {
+ const content = '''
+otpauth://totp/Example:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Example
+not-an-otp-uri
+''';
+
+ final codes = parsePlainTextImport(content);
+
+ expect(codes, hasLength(1));
+ expect(codes.single.account, '[email protected]');
+ });
+
+ test('preserves display properties from the rich fixture', () async {
+ final content = await File(
+ 'test/ui/settings/data/import/fixtures/rich_display_import.txt',
+ ).readAsString();
+
+ final codes = parsePlainTextImport(content);
+
+ expect(codes, hasLength(5));
+ expect(codes[0].display.pinned, isTrue);
+ expect(codes[0].display.tags, ['Work', 'Admin']);
+ expect(
+ codes[0].display.note,
+ 'Primary admin account. Keep recovery contacts current.',
+ );
+ expect(codes[1].display.trashed, isTrue);
+ expect(codes[1].issuer, 'Dropbox');
+ expect(codes[1].account, '[email protected]');
+ expect(codes[1].display.tags, ['Time capsule', 'Archived']);
+ expect(codes[2].digits, 8);
+ expect(codes[2].issuer, 'Stripe');
+ expect(codes[2].algorithm, Algorithm.sha256);
+ expect(codes[2].period, 45);
+ expect(codes[2].display.position, 1);
+ expect(codes[3].type, Type.steam);
+ expect(codes[3].account, '[email protected]');
+ expect(codes[3].display.pinned, isTrue);
+ expect(codes[4].type, Type.hotp);
+ expect(codes[4].issuer, 'Yubico');
+ expect(codes[4].counter, 42);
+ expect(codes[4].algorithm, Algorithm.sha512);
+ });
+
+ test('rejects JSON without an items list', () {
+ expect(
+ () => parsePlainTextImport('{"unexpected": []}'),
+ throwsFormatException,
+ );
+ });
+ });
+}
diff --git a/mobile/apps/auth/test/ui/settings/settings_subpages_test.dart b/mobile/apps/auth/test/ui/settings/settings_subpages_test.dart
new file mode 100644
index 0000000000..7398fdfd40
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/settings_subpages_test.dart
@@ -0,0 +1,85 @@
+import 'package:ente_auth/l10n/l10n.dart';
+import 'package:ente_auth/ui/settings/data/local_backup_settings_page.dart';
+import 'package:ente_auth/ui/settings/language_picker.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+
+void main() {
+ testWidgets(
+ 'language picker normalizes a device locale to its supported row',
+ (tester) async {
+ await _pumpPage(
+ tester,
+ LanguageSelectorPage(
+ const [Locale('en'), Locale('fr')],
+ (_) {},
+ const Locale('en', 'US'),
+ ),
+ );
+
+ final englishRow = find.widgetWithText(MenuComponent, 'English (en)');
+ final radio = tester.widget<RadioComponent>(
+ find.descendant(of: englishRow, matching: find.byType(RadioComponent)),
+ );
+
+ expect(radio.selected, isTrue);
+ expect(find.byType(MenuGroupComponent), findsOneWidget);
+ },
+ );
+
+ testWidgets('local backup uses component settings controls', (tester) async {
+ SharedPreferences.setMockInitialValues({
+ 'isAutoBackupEnabled': true,
+ 'autoBackupPath': '/tmp/EnteAuthBackups',
+ });
+
+ await _pumpPage(tester, const LocalBackupSettingsPage());
+ await tester.pumpAndSettle();
+
+ expect(find.text('Automatic backups'), findsOneWidget);
+ expect(find.byType(ToggleSwitchComponent), findsOneWidget);
+ expect(find.byType(MenuGroupComponent), findsNWidgets(2));
+ expect(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is Semantics &&
+ widget.properties.identifier == 'auth_local_backup_settings',
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is Semantics &&
+ widget.properties.identifier == 'auth_local_backup_toggle',
+ ),
+ findsOneWidget,
+ );
+ for (final identifier in [
+ 'auth_local_backup_password',
+ 'auth_local_backup_folder',
+ 'auth_local_backup_create_now',
+ ]) {
+ expect(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is Semantics && widget.properties.identifier == identifier,
+ ),
+ findsOneWidget,
+ );
+ }
+ });
+}
+
+Future<void> _pumpPage(WidgetTester tester, Widget page) {
+ return tester.pumpWidget(
+ MaterialApp(
+ theme: ComponentTheme.lightTheme(app: ComponentApp.auth),
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: page,
+ ),
+ );
+}
diff --git a/mobile/apps/auth/test/utils/debug_build_flags_test.dart b/mobile/apps/auth/test/utils/debug_build_flags_test.dart
new file mode 100644
index 0000000000..481c9875ae
--- /dev/null
+++ b/mobile/apps/auth/test/utils/debug_build_flags_test.dart
@@ -0,0 +1,8 @@
+import 'package:ente_auth/utils/debug_build_flags.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ test('screen capture stays disabled without the debug build flag', () {
+ expect(shouldAllowAuthScreenCapture, isFalse);
+ });
+}
diff --git a/mobile/apps/auth/test/utils/debug_code_deep_link_test.dart b/mobile/apps/auth/test/utils/debug_code_deep_link_test.dart
new file mode 100644
index 0000000000..c1b82a5180
--- /dev/null
+++ b/mobile/apps/auth/test/utils/debug_code_deep_link_test.dart
@@ -0,0 +1,53 @@
+import 'package:ente_auth/utils/debug_code_deep_link.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ test('unwraps a debug add-code link', () {
+ const codeUri =
+ 'otpauth://totp/Example:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Example';
+ final link = Uri(
+ scheme: 'enteauth',
+ host: 'debug',
+ path: '/add-code',
+ queryParameters: {'uri': codeUri},
+ ).toString();
+
+ final result = parseDebugCodeDeepLink(link);
+ expect(result?.action, DebugCodeDeepLinkAction.addCode);
+ expect(result?.codeUri, codeUri);
+ });
+
+ test('parses debug visual preview links', () {
+ const encodedCode =
+ 'otpauth%3A%2F%2Ftotp%2FExample%3Fsecret%3DJBSWY3DPEHPK3PXP';
+
+ expect(
+ parseDebugCodeDeepLink(
+ 'enteauth://debug/show-qr?uri=$encodedCode',
+ )?.action,
+ DebugCodeDeepLinkAction.showQr,
+ );
+ expect(
+ parseDebugCodeDeepLink(
+ 'enteauth://debug/share-code?uri=$encodedCode',
+ )?.action,
+ DebugCodeDeepLinkAction.shareCode,
+ );
+ expect(
+ parseDebugCodeDeepLink(
+ 'enteauth://debug/show-icons?uri=$encodedCode',
+ )?.action,
+ DebugCodeDeepLinkAction.showIcons,
+ );
+ });
+
+ test('rejects unrelated and non-OTP links', () {
+ expect(parseDebugCodeDeepLink('enteauth://search?query=Example'), isNull);
+ expect(
+ parseDebugCodeDeepLink(
+ 'enteauth://debug/add-code?uri=https%3A%2F%2Fexample.com',
+ ),
+ isNull,
+ );
+ });
+}
diff --git a/mobile/packages/lock_screen/lib/lock_screen_settings.dart b/mobile/packages/lock_screen/lib/lock_screen_settings.dart
index c809de958f..adb533c150 100644
--- a/mobile/packages/lock_screen/lib/lock_screen_settings.dart
+++ b/mobile/packages/lock_screen/lib/lock_screen_settings.dart
@@ -108,10 +108,15 @@ class LockScreenSettings {
}
}
- Future<void> setHideAppContent(bool hideContent) async {
+ Future<void> setHideAppContent(
+ bool hideContent, {
+ bool persist = true,
+ }) async {
if (PlatformDetector.isDesktop()) return;
!hideContent ? EnteScreenCover.disable() : await EnteScreenCover.enable();
- await _preferences.setBool(keyHideAppContent, hideContent);
+ if (persist) {
+ await _preferences.setBool(keyHideAppContent, hideContent);
+ }
}
bool getShouldHideAppContent() {
diff --git a/mobile/packages/lock_screen/lib/ui/app_lock.dart b/mobile/packages/lock_screen/lib/ui/app_lock.dart
index fc54671f3d..3eb2ca4a12 100644
--- a/mobile/packages/lock_screen/lib/ui/app_lock.dart
+++ b/mobile/packages/lock_screen/lib/ui/app_lock.dart
@@ -37,6 +37,7 @@ class AppLock extends StatefulWidget {
final List<Locale>? supportedLocales;
final List<LocalizationsDelegate<dynamic>> localizationsDelegates;
final LocaleListResolutionCallback? localeListResolutionCallback;
+ final bool debugShowCheckedModeBanner;
/// Invoked on each successful unlock (launch, resume, or manual).
final VoidCallback? onUnlock;
@@ -49,6 +50,7 @@ class AppLock extends StatefulWidget {
required this.supportedLocales,
required this.localizationsDelegates,
required this.localeListResolutionCallback,
+ this.debugShowCheckedModeBanner = true,
this.enabled = true,
this.locale,
this.backgroundLockLatency = const Duration(seconds: 0),
@@ -127,6 +129,7 @@ class _AppLockState extends State<AppLock> with WidgetsBindingObserver {
@override
Widget build(BuildContext context) {
return MaterialApp(
+ debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner,
home: this.widget.enabled ? this._lockScreen : this.widget.builder(null),
navigatorKey: _navigatorKey,
themeMode: this._themeMode,
diff --git a/mobile/packages/lock_screen/test/app_lock_test.dart b/mobile/packages/lock_screen/test/app_lock_test.dart
index a7fbf6b0b2..4caddb2ef6 100644
--- a/mobile/packages/lock_screen/test/app_lock_test.dart
+++ b/mobile/packages/lock_screen/test/app_lock_test.dart
@@ -40,9 +40,22 @@ void main() {
expect(find.text('light'), findsOneWidget);
});
+
+ testWidgets('can hide the debug banner', (tester) async {
+ await tester.pumpWidget(
+ _buildAppLock(ThemeMode.system, debugShowCheckedModeBanner: false),
+ );
+
+ final materialApp = tester.widget<MaterialApp>(find.byType(MaterialApp));
+ expect(materialApp.debugShowCheckedModeBanner, isFalse);
+ });
}
-Widget _buildAppLock(ThemeMode savedThemeMode, {Widget? child}) {
+Widget _buildAppLock(
+ ThemeMode savedThemeMode, {
+ Widget? child,
+ bool debugShowCheckedModeBanner = true,
+}) {
return AppLock(
builder: (_) =>
child ??
@@ -52,6 +65,7 @@ Widget _buildAppLock(ThemeMode savedThemeMode, {Widget? child}) {
savedThemeMode: savedThemeMode,
lightTheme: ThemeData(brightness: Brightness.light),
darkTheme: ThemeData(brightness: Brightness.dark),
+ debugShowCheckedModeBanner: debugShowCheckedModeBanner,
supportedLocales: const [Locale('en')],
localizationsDelegates: const <LocalizationsDelegate<dynamic>>[],
localeListResolutionCallback: (_, supportedLocales) =>