Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avatar #103

Merged
merged 19 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions docs/pages/docs/avatar.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Tabs } from 'nextra/components';
import { Widget } from "../../components/widget";

# Avatar
An image element with a fallback for representing the user.

<Tabs items={['Preview', 'Code']}>
<Tabs.Tab>
<Widget name='avatar' query={{}}/>
</Tabs.Tab>
<Tabs.Tab>
```dart
FAvatar(
image: const NetworkImage('https://picsum.photos/250?image=9'),
placeholderBuilder: (_) => const Text('MN'),
),
```
</Tabs.Tab>
</Tabs>

## Usage

### `FAvatar(...)`

```dart
FAvatar(
image: const NetworkImage('https://picsum.photos/250?image=9'),
size: 60,
placeholderBuilder: (_) => const Text('MN'),
),
```

1 change: 1 addition & 0 deletions forui/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## Next

### Additions
* Add `FAvatar`
* Add `FResizable`


Expand Down
12 changes: 11 additions & 1 deletion forui/lib/src/theme/theme_data.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ final class FThemeData with Diagnosticable {
/// The alert styles.
final FAlertStyles alertStyles;

/// The avatar style.
final FAvatarStyle avatarStyle;

/// The badge styles.
final FBadgeStyles badgeStyles;

Expand Down Expand Up @@ -78,12 +81,13 @@ final class FThemeData with Diagnosticable {
/// widget styles.
FThemeData({
required this.colorScheme,
required this.alertStyles,
required this.avatarStyle,
required this.badgeStyles,
required this.bottomNavigationBarStyle,
required this.buttonStyles,
required this.calendarStyle,
required this.cardStyle,
required this.alertStyles,
required this.checkboxStyle,
required this.dialogStyle,
required this.headerStyle,
Expand All @@ -110,6 +114,7 @@ final class FThemeData with Diagnosticable {
typography: typography,
style: style,
alertStyles: FAlertStyles.inherit(colorScheme: colorScheme, typography: typography, style: style),
avatarStyle: FAvatarStyle.inherit(colorScheme: colorScheme, typography: typography),
badgeStyles: FBadgeStyles.inherit(colorScheme: colorScheme, typography: typography, style: style),
bottomNavigationBarStyle: FBottomNavigationBarStyle.inherit(colorScheme: colorScheme, typography: typography),
buttonStyles: FButtonStyles.inherit(colorScheme: colorScheme, typography: typography, style: style),
Expand Down Expand Up @@ -149,6 +154,7 @@ final class FThemeData with Diagnosticable {
FTypography? typography,
FStyle? style,
FAlertStyles? alertStyles,
FAvatarStyle? avatarStyle,
FBadgeStyles? badgeStyles,
FBottomNavigationBarStyle? bottomNavigationBarStyle,
FButtonStyles? buttonStyles,
Expand All @@ -169,6 +175,7 @@ final class FThemeData with Diagnosticable {
typography: typography ?? this.typography,
style: style ?? this.style,
alertStyles: alertStyles ?? this.alertStyles,
avatarStyle: avatarStyle ?? this.avatarStyle,
badgeStyles: badgeStyles ?? this.badgeStyles,
bottomNavigationBarStyle: bottomNavigationBarStyle ?? this.bottomNavigationBarStyle,
buttonStyles: buttonStyles ?? this.buttonStyles,
Expand All @@ -193,6 +200,7 @@ final class FThemeData with Diagnosticable {
..add(DiagnosticsProperty('typography', typography, level: DiagnosticLevel.debug))
..add(DiagnosticsProperty('style', style, level: DiagnosticLevel.debug))
..add(DiagnosticsProperty('alertStyles', alertStyles, level: DiagnosticLevel.debug))
..add(DiagnosticsProperty('avatarStyle', avatarStyle))
..add(DiagnosticsProperty('badgeStyles', badgeStyles, level: DiagnosticLevel.debug))
..add(DiagnosticsProperty('bottomNavigationBarStyle', bottomNavigationBarStyle, level: DiagnosticLevel.debug))
..add(DiagnosticsProperty('buttonStyles', buttonStyles, level: DiagnosticLevel.debug))
Expand All @@ -218,6 +226,7 @@ final class FThemeData with Diagnosticable {
typography == other.typography &&
style == other.style &&
alertStyles == other.alertStyles &&
avatarStyle == other.avatarStyle &&
badgeStyles == other.badgeStyles &&
bottomNavigationBarStyle == other.bottomNavigationBarStyle &&
buttonStyles == other.buttonStyles &&
Expand All @@ -239,6 +248,7 @@ final class FThemeData with Diagnosticable {
typography.hashCode ^
style.hashCode ^
alertStyles.hashCode ^
avatarStyle.hashCode ^
badgeStyles.hashCode ^
bottomNavigationBarStyle.hashCode ^
buttonStyles.hashCode ^
Expand Down
198 changes: 198 additions & 0 deletions forui/lib/src/widgets/avatar.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';

import 'package:meta/meta.dart';

import 'package:forui/forui.dart';

/// An image element with a fallback for representing the user.
///
/// Typically used with a user's profile image. If the image fails to load,
/// [placeholderBuilder] is used instead, which usually displays the user's initials.
///
/// If the user's profile has no image, use [placeholderBuilder] to provide
/// the initials using a [Text] widget styled with [FAvatarStyle.backgroundColor].
class FAvatar extends StatelessWidget {
/// The style. Defaults to [FThemeData.avatarStyle].
final FAvatarStyle? style;

/// The profile image displayed within the circle.
///
/// If the user's initials are used, use [placeholderBuilder] instead.
final ImageProvider image;

/// The circle's size.
final double size;

/// The fallback widget displayed if [image] fails to load.
///
/// Typically used to display the user's initials using a [Text] widget
/// styled with [FAvatarStyle.backgroundColor].
///
/// Use [image] to display an image; use [placeholderBuilder] for initials.
final Widget Function(BuildContext)? placeholderBuilder;

/// Creates an [FAvatar].
const FAvatar({
required this.image,
this.style,
this.size = 40.0,
this.placeholderBuilder,
super.key,
});

@override
Widget build(BuildContext context) {
final style = this.style ?? context.theme.avatarStyle;

return Container(
height: size,
width: size,
decoration: BoxDecoration(
color: style.backgroundColor,
shape: BoxShape.circle,
),
clipBehavior: Clip.hardEdge,
child: Center(
child: Image(
filterQuality: FilterQuality.medium,
image: image,
errorBuilder: (context, exception, stacktrace) => DefaultTextStyle(
style: style.text,
child: placeholderBuilder != null ? placeholderBuilder!(context) : _Placeholder(size: size),
),
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
if (wasSynchronouslyLoaded) {
return child;
}
return AnimatedSwitcher(
duration: const Duration(milliseconds: 500),
child: frame == null
? DefaultTextStyle(
style: style.text,
child: placeholderBuilder != null ? placeholderBuilder!(context) : _Placeholder(size: size),
)
: child,
);
},
loadingBuilder: (context, child, loadingProgress) {
if (loadingProgress == null) {
return child;
}
return DefaultTextStyle(
style: style.text,
child: placeholderBuilder != null ? placeholderBuilder!(context) : _Placeholder(size: size),
);
},
fit: BoxFit.cover,
),
),
);
}

@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties
..add(DiagnosticsProperty('image', image))
..add(DoubleProperty('size', size))
..add(DiagnosticsProperty('style', style))
..add(ObjectFlagProperty.has('placeholderBuilder', placeholderBuilder));
}
}

/// [FAvatar]'s style.
final class FAvatarStyle with Diagnosticable {
/// The placeholder's background color.
final Color backgroundColor;

/// Duration for the transition animation.
final Duration fadeInDuration;

/// The text style for the placeholder text.
final TextStyle text;

/// Creates a [FAvatarStyle].
FAvatarStyle({
required this.backgroundColor,
required this.fadeInDuration,
required this.text,
});

/// Creates a [FCardStyle] that inherits its properties from [colorScheme] and [typography].
FAvatarStyle.inherit({required FColorScheme colorScheme, required FTypography typography})
: backgroundColor = colorScheme.muted,
fadeInDuration = const Duration(milliseconds: 500),
text = typography.base.copyWith(
color: colorScheme.mutedForeground,
height: 0,
);

/// Returns a copy of this [FAvatarStyle] with the given properties replaced.
///
/// ```dart
/// final style = FAvatarStyle(
/// backgroundColor: ...,
/// fadeInDuration: ...,
/// );
///
/// final copy = style.copyWith(fadeInDuration: ...);
///
/// print(style.backgroundColor == copy.backgroundColor); // true
/// print(style.fadeInDuration == copy.fadeInDuration); // false
/// ```
@useResult
FAvatarStyle copyWith({
Color? backgroundColor,
Duration? fadeInDuration,
TextStyle? text,
}) =>
FAvatarStyle(
backgroundColor: backgroundColor ?? this.backgroundColor,
fadeInDuration: fadeInDuration ?? this.fadeInDuration,
text: text ?? this.text,
);

@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties
..add(ColorProperty('backgroundColor', backgroundColor))
..add(DiagnosticsProperty('fadeInDuration', fadeInDuration))
..add(DiagnosticsProperty('text', text));
}

@override
bool operator ==(Object other) =>
identical(this, other) ||
other is FAvatarStyle &&
runtimeType == other.runtimeType &&
backgroundColor == other.backgroundColor &&
fadeInDuration == other.fadeInDuration &&
text == other.text;

@override
int get hashCode => backgroundColor.hashCode ^ fadeInDuration.hashCode ^ text.hashCode;
}

class _Placeholder extends StatelessWidget {
final double size;

const _Placeholder({required this.size});

@override
Widget build(BuildContext context) {
final style = context.theme;

return FAssets.icons.userRound(
height: size / 2,
colorFilter: ColorFilter.mode(style.colorScheme.mutedForeground, BlendMode.srcIn),
);
}

@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DoubleProperty('size', size));
}
}
1 change: 1 addition & 0 deletions forui/lib/widgets.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ library forui.widgets;
import 'package:forui/forui.dart';

export 'src/widgets/alert/alert.dart' hide Variant;
export 'src/widgets/avatar.dart';
export 'src/widgets/badge/badge.dart' hide Variant;
export 'src/widgets/bottom_navigation_bar/bottom_navigation_bar.dart';
export 'src/widgets/button/button.dart' hide Variant;
Expand Down
Binary file added forui/test/golden/avatar/zinc-dark-with-image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added forui/test/resources/pante.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
54 changes: 54 additions & 0 deletions forui/test/src/widgets/avatar_golden_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
@Tags(['golden'])
library;

import 'dart:io';

import 'package:flutter/material.dart';

import 'package:flutter_test/flutter_test.dart';

import 'package:forui/forui.dart';
import '../test_scaffold.dart';

void main() {
group(
'FAvatar',
() {
for (final (name, theme, _) in TestScaffold.themes) {
testWidgets('$name with image', (tester) async {
final testWidget = MaterialApp(
home: TestScaffold(
data: theme,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: FAvatar(
image: FileImage(File('./test/resources/pante.jpg')),
placeholderBuilder: (_) => const Text('MN'),
),
),
),
);

/// current workaround for flaky image asset testing.
/// https://github.com/flutter/flutter/issues/38997
await tester.runAsync(() async {
await tester.pumpWidget(testWidget);
for (final element in find.byType(Image).evaluate()) {
final Image widget = element.widget as Image;
final ImageProvider image = widget.image;
await precacheImage(image, element);
await tester.pumpAndSettle();
}
});
await expectLater(
find.byType(TestScaffold),
matchesGoldenFile('avatar/$name-with-image.png'),
);
});

/// We will not be testing for the fallback behavior due to this issue on flutter
/// https://github.com/flutter/flutter/issues/107416
}
},
);
}
Binary file added samples/assets/avatar.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions samples/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ class _AppRouter extends $_AppRouter {
path: '/alert/default',
page: AlertRoute.page,
),
AutoRoute(
path: '/avatar/default',
page: AvatarRoute.page,
),
AutoRoute(
path: '/badge/default',
page: BadgeRoute.page,
Expand Down
Loading