feat: New onboarding design

This commit is contained in:
Christian Pauly 2022-04-15 11:42:59 +02:00
commit 87afa8ac3d
18 changed files with 862 additions and 699 deletions

View file

@ -1,19 +1,12 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:flutter_web_auth/flutter_web_auth.dart';
import 'package:future_loading_dialog/future_loading_dialog.dart';
import 'package:matrix/matrix.dart';
import 'package:universal_html/html.dart' as html;
import 'package:vrouter/vrouter.dart';
import 'package:fluffychat/config/app_config.dart';
import 'package:fluffychat/pages/homeserver_picker/homeserver_picker_view.dart';
import 'package:fluffychat/utils/famedlysdk_store.dart';
import 'package:fluffychat/utils/platform_infos.dart';
import 'package:fluffychat/widgets/matrix.dart';
import '../../utils/localized_exception_extension.dart';
@ -26,182 +19,58 @@ class HomeserverPicker extends StatefulWidget {
class HomeserverPickerController extends State<HomeserverPicker> {
bool isLoading = false;
String domain = AppConfig.defaultHomeserver;
final TextEditingController homeserverController =
TextEditingController(text: AppConfig.defaultHomeserver);
StreamSubscription? _intentDataStreamSubscription;
String? error;
Timer? _coolDown;
void setDomain(String domain) {
this.domain = domain;
_coolDown?.cancel();
if (domain.isNotEmpty) {
_coolDown =
Timer(const Duration(milliseconds: 500), checkHomeserverAction);
}
}
void _loginWithToken(String token) {
if (token.isEmpty) return;
showFutureLoadingDialog(
context: context,
future: () async {
if (Matrix.of(context).getLoginClient().homeserver == null) {
await Matrix.of(context).getLoginClient().checkHomeserver(
await Store()
.getItem(HomeserverPickerController.ssoHomeserverKey),
);
}
await Matrix.of(context).getLoginClient().login(
LoginType.mLoginToken,
token: token,
initialDeviceDisplayName: PlatformInfos.clientName,
);
},
);
}
@override
void initState() {
super.initState();
checkHomeserverAction();
}
@override
void dispose() {
super.dispose();
_intentDataStreamSubscription?.cancel();
}
String? _lastCheckedHomeserver;
/// Starts an analysis of the given homeserver. It uses the current domain and
/// makes sure that it is prefixed with https. Then it searches for the
/// well-known information and forwards to the login page depending on the
/// login type.
Future<void> checkHomeserverAction() async {
_coolDown?.cancel();
if (_lastCheckedHomeserver == domain) return;
if (domain.isEmpty) throw L10n.of(context)!.changeTheHomeserver;
var homeserver = domain;
if (!homeserver.startsWith('https://')) {
homeserver = 'https://$homeserver';
}
setState(() {
error = _rawLoginTypes = registrationSupported = null;
error = null;
isLoading = true;
});
try {
await Matrix.of(context).getLoginClient().checkHomeserver(homeserver);
homeserverController.text =
homeserverController.text.trim().toLowerCase().replaceAll(' ', '-');
var homeserver = Uri.parse(homeserverController.text);
if (homeserver.scheme.isEmpty) {
homeserver = Uri.https(homeserverController.text, '');
}
final matrix = Matrix.of(context);
matrix.loginHomeserverSummary =
await matrix.getLoginClient().checkHomeserver(homeserver);
final ssoSupported = matrix.loginHomeserverSummary!.loginFlows
.any((flow) => flow.type == 'm.login.sso');
_rawLoginTypes = await Matrix.of(context).getLoginClient().request(
RequestType.GET,
'/client/r0/login',
);
try {
await Matrix.of(context).getLoginClient().register();
registrationSupported = true;
matrix.loginRegistrationSupported = true;
} on MatrixException catch (e) {
registrationSupported = e.requireAdditionalAuthentication;
matrix.loginRegistrationSupported = e.requireAdditionalAuthentication;
}
if (!ssoSupported && matrix.loginRegistrationSupported == false) {
// Server does not support SSO or registration. We can skip to login page:
VRouter.of(context).to('login');
} else {
VRouter.of(context).to('connect');
}
} catch (e) {
setState(() => error = (e).toLocalizedString(context));
} finally {
_lastCheckedHomeserver = domain;
if (mounted) {
setState(() => isLoading = false);
}
}
}
Map<String, dynamic>? _rawLoginTypes;
bool? registrationSupported;
List<IdentityProvider> get identityProviders {
if (!ssoLoginSupported) return [];
final rawProviders = _rawLoginTypes!.tryGetList('flows')!.singleWhere(
(flow) =>
flow['type'] == AuthenticationTypes.sso)['identity_providers'];
final list = (rawProviders as List)
.map((json) => IdentityProvider.fromJson(json))
.toList();
if (PlatformInfos.isCupertinoStyle) {
list.sort((a, b) => a.brand == 'apple' ? -1 : 1);
}
return list;
}
bool get passwordLoginSupported =>
Matrix.of(context)
.client
.supportedLoginTypes
.contains(AuthenticationTypes.password) &&
_rawLoginTypes!
.tryGetList('flows')!
.any((flow) => flow['type'] == AuthenticationTypes.password);
bool get ssoLoginSupported =>
Matrix.of(context)
.client
.supportedLoginTypes
.contains(AuthenticationTypes.sso) &&
_rawLoginTypes!
.tryGetList('flows')!
.any((flow) => flow['type'] == AuthenticationTypes.sso);
static const String ssoHomeserverKey = 'sso-homeserver';
void ssoLoginAction(String id) async {
if (kIsWeb) {
// We store the homserver in the local storage instead of a redirect
// parameter because of possible CSRF attacks.
Store().setItem(ssoHomeserverKey,
Matrix.of(context).getLoginClient().homeserver.toString());
}
final redirectUrl = kIsWeb
? html.window.origin! + '/web/auth.html'
: AppConfig.appOpenUrlScheme.toLowerCase() + '://login';
final url =
'${Matrix.of(context).getLoginClient().homeserver?.toString()}/_matrix/client/r0/login/sso/redirect/${Uri.encodeComponent(id)}?redirectUrl=${Uri.encodeQueryComponent(redirectUrl)}';
final urlScheme = Uri.parse(redirectUrl).scheme;
final result = await FlutterWebAuth.authenticate(
url: url,
callbackUrlScheme: urlScheme,
);
final token = Uri.parse(result).queryParameters['loginToken'];
if (token != null) _loginWithToken(token);
}
void signUpAction() => VRouter.of(context).to(
'signup',
queryParameters: {'domain': domain},
);
@override
Widget build(BuildContext context) {
Matrix.of(context).navigatorContext = context;
return HomeserverPickerView(this);
}
}
class IdentityProvider {
final String? id;
final String? name;
final String? icon;
final String? brand;
IdentityProvider({this.id, this.name, this.icon, this.brand});
factory IdentityProvider.fromJson(Map<String, dynamic> json) =>
IdentityProvider(
id: json['id'],
name: json['name'],
icon: json['icon'],
brand: json['brand'],
);
}

View file

@ -1,17 +1,13 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:matrix/matrix.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vrouter/vrouter.dart';
import 'package:fluffychat/config/app_config.dart';
import 'package:fluffychat/config/themes.dart';
import 'package:fluffychat/utils/platform_infos.dart';
import 'package:fluffychat/widgets/default_app_bar_search_field.dart';
import 'package:fluffychat/widgets/layouts/one_page_card.dart';
import 'package:fluffychat/widgets/matrix.dart';
import 'package:fluffychat/widgets/layouts/login_scaffold.dart';
import 'homeserver_picker.dart';
class HomeserverPickerView extends StatelessWidget {
@ -21,237 +17,86 @@ class HomeserverPickerView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return OnePageCard(
child: Scaffold(
appBar: AppBar(
titleSpacing: 8,
title: DefaultAppBarSearchField(
prefixText: 'https://',
hintText: L10n.of(context)!.enterYourHomeserver,
searchController: controller.homeserverController,
suffix: const Icon(Icons.edit_outlined),
padding: EdgeInsets.zero,
onChanged: controller.setDomain,
readOnly: !AppConfig.allowOtherHomeservers,
onSubmit: (_) => controller.checkHomeserverAction(),
unfocusOnClear: false,
autocorrect: false,
labelText: L10n.of(context)!.homeserver,
),
elevation: 0,
),
body: ListView(children: [
Image.asset(
Theme.of(context).brightness == Brightness.dark
? 'assets/banner_dark.png'
: 'assets/banner.png',
),
if (controller.isLoading)
const Center(
child: CircularProgressIndicator.adaptive(strokeWidth: 2))
else if (controller.error != null)
Center(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
controller.error!,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
color: Colors.red[900],
return LoginScaffold(
appBar: VRouter.of(context).path == '/home'
? null
: AppBar(title: Text(L10n.of(context)!.addAccount)),
body: Column(
children: [
Expanded(
child: ListView(
children: [
Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 256),
child: Image.asset(
'assets/info-logo.png',
),
),
),
),
)
else
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12.0,
vertical: 4.0,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (controller.ssoLoginSupported)
Row(children: [
const Expanded(child: Divider()),
Padding(
padding: const EdgeInsets.all(12.0),
child: Text(L10n.of(context)!.loginWithOneClick),
),
const Expanded(child: Divider()),
]),
Wrap(
children: [
if (controller.ssoLoginSupported) ...{
for (final identityProvider
in controller.identityProviders)
_SsoButton(
onPressed: () =>
controller.ssoLoginAction(identityProvider.id!),
identityProvider: identityProvider,
),
},
].toList(),
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
controller: controller.homeserverController,
decoration: FluffyThemes.loginTextFieldDecoration(
labelText: L10n.of(context)!.homeserver,
hintText: L10n.of(context)!.enterYourHomeserver,
suffixIcon: const Icon(Icons.search),
errorText: controller.error,
),
readOnly: !AppConfig.allowOtherHomeservers,
onSubmitted: (_) => controller.checkHomeserverAction(),
autocorrect: false,
),
if (controller.ssoLoginSupported &&
(controller.registrationSupported! ||
controller.passwordLoginSupported))
Row(children: [
const Expanded(child: Divider()),
Padding(
padding: const EdgeInsets.all(12.0),
child: Text(L10n.of(context)!.or),
),
const Expanded(child: Divider()),
]),
if (controller.passwordLoginSupported) ...[
Center(
child: _LoginButton(
onPressed: () => VRouter.of(context).to('login'),
icon: Icon(
CupertinoIcons.lock_open_fill,
color: Theme.of(context).textTheme.bodyText1!.color,
),
Wrap(
alignment: WrapAlignment.center,
children: [
TextButton(
onPressed: () => launch(AppConfig.privacyUrl),
child: Text(
L10n.of(context)!.privacy,
style: const TextStyle(
decoration: TextDecoration.underline,
color: Colors.white,
),
),
),
TextButton(
onPressed: () => PlatformInfos.showDialog(context),
child: Text(
L10n.of(context)!.about,
style: const TextStyle(
decoration: TextDecoration.underline,
color: Colors.white,
),
labelText: L10n.of(context)!.login,
),
),
const SizedBox(height: 12),
],
if (controller.registrationSupported!)
Center(
child: _LoginButton(
onPressed: controller.signUpAction,
icon: Icon(
CupertinoIcons.person_add,
color: Theme.of(context).textTheme.bodyText1!.color,
),
labelText: L10n.of(context)!.register,
),
),
],
),
),
],
),
]),
bottomNavigationBar: Material(
elevation: 6,
color: Theme.of(context).scaffoldBackgroundColor,
child: Wrap(
alignment: WrapAlignment.center,
children: [
TextButton(
onPressed: () => launch(AppConfig.privacyUrl),
child: Text(
L10n.of(context)!.privacy,
style: const TextStyle(
decoration: TextDecoration.underline,
color: Colors.blueGrey,
),
),
),
TextButton(
onPressed: () => PlatformInfos.showDialog(context),
child: Text(
L10n.of(context)!.about,
style: const TextStyle(
decoration: TextDecoration.underline,
color: Colors.blueGrey,
),
),
),
],
),
),
),
);
}
}
class _SsoButton extends StatelessWidget {
final IdentityProvider identityProvider;
final void Function()? onPressed;
const _SsoButton({
Key? key,
required this.identityProvider,
this.onPressed,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onPressed,
borderRadius: BorderRadius.circular(7),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Material(
color: Colors.white,
borderRadius: BorderRadius.circular(7),
clipBehavior: Clip.hardEdge,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: identityProvider.icon == null
? const Icon(Icons.web_outlined)
: CachedNetworkImage(
imageUrl: Uri.parse(identityProvider.icon!)
.getDownloadLink(
Matrix.of(context).getLoginClient())
.toString(),
width: 32,
height: 32,
),
Padding(
padding: const EdgeInsets.all(16),
child: Hero(
tag: 'loginButton',
child: ElevatedButton(
onPressed: controller.isLoading
? () {}
: controller.checkHomeserverAction,
style: ElevatedButton.styleFrom(
primary: Colors.white.withAlpha(200),
onPrimary: Colors.black,
shadowColor: Colors.white,
),
child: controller.isLoading
? const LinearProgressIndicator()
: Text(L10n.of(context)!.connect),
),
),
const SizedBox(height: 8),
Text(
identityProvider.name ??
identityProvider.brand ??
L10n.of(context)!.singlesignon,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: Theme.of(context).textTheme.subtitle2!.color,
),
),
],
),
),
);
}
}
class _LoginButton extends StatelessWidget {
final String? labelText;
final Widget? icon;
final void Function()? onPressed;
const _LoginButton({
Key? key,
this.labelText,
this.icon,
this.onPressed,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return OutlinedButton.icon(
style: OutlinedButton.styleFrom(
minimumSize: const Size(256, 56),
textStyle: const TextStyle(fontWeight: FontWeight.bold),
backgroundColor: Theme.of(context).backgroundColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppConfig.borderRadius),
),
),
onPressed: onPressed,
icon: icon!,
label: Text(
labelText!,
style: TextStyle(
color: Theme.of(context).textTheme.bodyText1!.color,
),
),
],
),
);
}