repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/flowy_infra_ui.dart
|
// Basis
export 'basis.dart';
// Keyboard
export 'src/keyboard/keyboard_visibility_detector.dart';
// Overlay
export 'src/flowy_overlay/flowy_overlay.dart';
export 'src/flowy_overlay/list_overlay.dart';
export 'src/flowy_overlay/option_overlay.dart';
export 'src/flowy_overlay/flowy_dialog.dart';
export 'src/flowy_overlay/appflowy_popover.dart';
export 'style_widget/text.dart';
export 'style_widget/text_field.dart';
export 'style_widget/button.dart';
export 'style_widget/icon_button.dart';
export 'style_widget/scrolling/styled_scroll_bar.dart';
export '/widget/spacing.dart';
export '/widget/separated_flex.dart';
export 'style_widget/scrolling/styled_list.dart';
export 'style_widget/color_picker.dart';
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/basis.dart
|
import 'package:flutter/material.dart';
// MARK: - Shared Builder
typedef WidgetBuilder = Widget Function();
typedef IndexedCallback = void Function(int index);
typedef IndexedValueCallback<T> = void Function(T value, int index);
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/flowy_infra_ui_web.dart
|
// Basis
export 'basis.dart';
// Keyboard
export 'src/keyboard/keyboard_visibility_detector.dart';
// Overlay
export 'src/flowy_overlay/flowy_overlay.dart';
export 'src/flowy_overlay/list_overlay.dart';
export 'src/flowy_overlay/option_overlay.dart';
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src/flowy_overlay/option_overlay.dart
|
import 'package:flowy_infra_ui/flowy_infra_ui_web.dart';
import 'package:flutter/material.dart';
class OptionItem {
const OptionItem(this.icon, this.title);
final Icon? icon;
final String title;
}
class OptionOverlay<T> extends StatelessWidget {
const OptionOverlay({
super.key,
required this.items,
this.onHover,
this.onTap,
});
final List<T> items;
final IndexedValueCallback<T>? onHover;
final IndexedValueCallback<T>? onTap;
static void showWithAnchor<T>(
BuildContext context, {
required List<T> items,
required String identifier,
required BuildContext anchorContext,
IndexedValueCallback<T>? onHover,
IndexedValueCallback<T>? onTap,
AnchorDirection? anchorDirection,
OverlapBehaviour? overlapBehaviour,
FlowyOverlayDelegate? delegate,
}) {
FlowyOverlay.of(context).insertWithAnchor(
widget: OptionOverlay(
items: items,
onHover: onHover,
onTap: onTap,
),
identifier: identifier,
anchorContext: anchorContext,
anchorDirection: anchorDirection,
delegate: delegate,
overlapBehaviour: overlapBehaviour,
);
}
@override
Widget build(BuildContext context) {
final List<_OptionListItem> listItems =
items.map((e) => _OptionListItem(e)).toList();
return ListOverlay(
itemBuilder: (context, index) {
return MouseRegion(
cursor: SystemMouseCursors.click,
onHover:
onHover != null ? (_) => onHover!(items[index], index) : null,
child: GestureDetector(
onTap: onTap != null ? () => onTap!(items[index], index) : null,
child: listItems[index],
),
);
},
itemCount: listItems.length,
);
}
}
class _OptionListItem<T> extends StatelessWidget {
const _OptionListItem(
this.value, {
super.key,
});
final T value;
@override
Widget build(BuildContext context) {
if (T == String || T == OptionItem) {
var children = <Widget>[];
if (value is String) {
children = [
Text(value as String),
];
} else if (value is OptionItem) {
final optionItem = value as OptionItem;
children = [
if (optionItem.icon != null) optionItem.icon!,
Text(optionItem.title),
];
}
return Column(
mainAxisSize: MainAxisSize.min,
children: children,
);
}
throw UnimplementedError('The type $T is not supported by option list.');
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src/flowy_overlay/layout.dart
|
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'flowy_overlay.dart';
class OverlayLayoutDelegate extends SingleChildLayoutDelegate {
OverlayLayoutDelegate({
required this.anchorRect,
required this.anchorDirection,
required this.overlapBehaviour,
});
final Rect anchorRect;
final AnchorDirection anchorDirection;
final OverlapBehaviour overlapBehaviour;
@override
bool shouldRelayout(OverlayLayoutDelegate oldDelegate) {
return anchorRect != oldDelegate.anchorRect ||
anchorDirection != oldDelegate.anchorDirection ||
overlapBehaviour != oldDelegate.overlapBehaviour;
}
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
switch (overlapBehaviour) {
case OverlapBehaviour.none:
return constraints.loosen();
case OverlapBehaviour.stretch:
BoxConstraints childConstraints;
switch (anchorDirection) {
case AnchorDirection.topLeft:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
anchorRect.top,
));
break;
case AnchorDirection.topRight:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.right,
anchorRect.top,
));
break;
case AnchorDirection.bottomLeft:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
constraints.maxHeight - anchorRect.bottom,
));
break;
case AnchorDirection.bottomRight:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.right,
constraints.maxHeight - anchorRect.bottom,
));
break;
case AnchorDirection.center:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth,
constraints.maxHeight,
));
break;
case AnchorDirection.topWithLeftAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.left,
anchorRect.top,
));
break;
case AnchorDirection.topWithCenterAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth,
anchorRect.top,
));
break;
case AnchorDirection.topWithRightAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.right,
anchorRect.top,
));
break;
case AnchorDirection.rightWithTopAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.right,
constraints.maxHeight - anchorRect.top,
));
break;
case AnchorDirection.rightWithCenterAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.right,
constraints.maxHeight,
));
break;
case AnchorDirection.rightWithBottomAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.right,
anchorRect.bottom,
));
break;
case AnchorDirection.bottomWithLeftAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
constraints.maxHeight - anchorRect.bottom,
));
break;
case AnchorDirection.bottomWithCenterAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth,
constraints.maxHeight - anchorRect.bottom,
));
break;
case AnchorDirection.bottomWithRightAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.right,
constraints.maxHeight - anchorRect.bottom,
));
break;
case AnchorDirection.leftWithTopAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
constraints.maxHeight - anchorRect.top,
));
break;
case AnchorDirection.leftWithCenterAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
constraints.maxHeight,
));
break;
case AnchorDirection.leftWithBottomAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
anchorRect.bottom,
));
break;
case AnchorDirection.custom:
childConstraints = constraints.loosen();
break;
default:
throw UnimplementedError();
}
return childConstraints;
}
}
@override
Offset getPositionForChild(Size size, Size childSize) {
Offset position;
switch (anchorDirection) {
case AnchorDirection.topLeft:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.top - childSize.height,
);
break;
case AnchorDirection.topRight:
position = Offset(
anchorRect.right,
anchorRect.top - childSize.height,
);
break;
case AnchorDirection.bottomLeft:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.bottom,
);
break;
case AnchorDirection.bottomRight:
position = Offset(
anchorRect.right,
anchorRect.bottom,
);
break;
case AnchorDirection.center:
position = anchorRect.center;
break;
case AnchorDirection.topWithLeftAligned:
position = Offset(
anchorRect.left,
anchorRect.top - childSize.height,
);
break;
case AnchorDirection.topWithCenterAligned:
position = Offset(
anchorRect.left + anchorRect.width / 2.0 - childSize.width / 2.0,
anchorRect.top - childSize.height,
);
break;
case AnchorDirection.topWithRightAligned:
position = Offset(
anchorRect.right - childSize.width,
anchorRect.top - childSize.height,
);
break;
case AnchorDirection.rightWithTopAligned:
position = Offset(anchorRect.right, anchorRect.top);
break;
case AnchorDirection.rightWithCenterAligned:
position = Offset(
anchorRect.right,
anchorRect.top + anchorRect.height / 2.0 - childSize.height / 2.0,
);
break;
case AnchorDirection.rightWithBottomAligned:
position = Offset(
anchorRect.right,
anchorRect.bottom - childSize.height,
);
break;
case AnchorDirection.bottomWithLeftAligned:
position = Offset(
anchorRect.left,
anchorRect.bottom,
);
break;
case AnchorDirection.bottomWithCenterAligned:
position = Offset(
anchorRect.left + anchorRect.width / 2.0 - childSize.width / 2.0,
anchorRect.bottom,
);
break;
case AnchorDirection.bottomWithRightAligned:
position = Offset(
anchorRect.right - childSize.width,
anchorRect.bottom,
);
break;
case AnchorDirection.leftWithTopAligned:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.top,
);
break;
case AnchorDirection.leftWithCenterAligned:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.top + anchorRect.height / 2.0 - childSize.height / 2.0,
);
break;
case AnchorDirection.leftWithBottomAligned:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.bottom - childSize.height,
);
break;
default:
throw UnimplementedError();
}
return Offset(
math.max(0.0, math.min(size.width - childSize.width, position.dx)),
math.max(0.0, math.min(size.height - childSize.height, position.dy)),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src/flowy_overlay/appflowy_popover.dart
|
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:flowy_infra_ui/style_widget/decoration.dart';
import 'package:flutter/material.dart';
class AppFlowyPopover extends StatelessWidget {
final Widget child;
final PopoverController? controller;
final Widget Function(BuildContext context) popupBuilder;
final PopoverDirection direction;
final int triggerActions;
final BoxConstraints constraints;
final VoidCallback? onOpen;
final VoidCallback? onClose;
final Future<bool> Function()? canClose;
final PopoverMutex? mutex;
final Offset? offset;
final bool asBarrier;
final EdgeInsets margin;
final EdgeInsets windowPadding;
final Decoration? decoration;
/// The widget that will be used to trigger the popover.
///
/// Why do we need this?
/// Because if the parent widget of the popover is GestureDetector,
/// the conflict won't be resolve by using Listener, we want these two gestures exclusive.
final PopoverClickHandler clickHandler;
/// If true the popover will not participate in focus traversal.
///
final bool skipTraversal;
const AppFlowyPopover({
super.key,
required this.child,
required this.popupBuilder,
this.direction = PopoverDirection.rightWithTopAligned,
this.onOpen,
this.onClose,
this.canClose,
this.constraints = const BoxConstraints(maxWidth: 240, maxHeight: 600),
this.mutex,
this.triggerActions = PopoverTriggerFlags.click,
this.offset,
this.controller,
this.asBarrier = false,
this.margin = const EdgeInsets.all(6),
this.windowPadding = const EdgeInsets.all(8.0),
this.decoration,
this.clickHandler = PopoverClickHandler.listener,
this.skipTraversal = false,
});
@override
Widget build(BuildContext context) {
return Popover(
controller: controller,
onOpen: onOpen,
onClose: onClose,
canClose: canClose,
direction: direction,
mutex: mutex,
asBarrier: asBarrier,
triggerActions: triggerActions,
windowPadding: windowPadding,
offset: offset,
clickHandler: clickHandler,
skipTraversal: skipTraversal,
popupBuilder: (context) {
return _PopoverContainer(
constraints: constraints,
margin: margin,
decoration: decoration,
child: popupBuilder(context),
);
},
child: child,
);
}
}
class _PopoverContainer extends StatelessWidget {
const _PopoverContainer({
required this.child,
required this.margin,
required this.constraints,
required this.decoration,
});
final Widget child;
final BoxConstraints constraints;
final EdgeInsets margin;
final Decoration? decoration;
@override
Widget build(BuildContext context) {
final decoration = this.decoration ??
FlowyDecoration.decoration(
Theme.of(context).cardColor,
Theme.of(context).colorScheme.shadow,
);
return Material(
type: MaterialType.transparency,
child: Container(
padding: margin,
decoration: decoration,
constraints: constraints,
child: child,
),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src/flowy_overlay/flowy_overlay.dart
|
// ignore_for_file: unused_element
import 'dart:ui';
import 'package:flowy_infra_ui/src/flowy_overlay/layout.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Specifies how overlay are anchored to the SourceWidget
enum AnchorDirection {
// Corner aligned with a corner of the SourceWidget
topLeft,
topRight,
bottomLeft,
bottomRight,
center,
// Edge aligned with a edge of the SourceWidget
topWithLeftAligned,
topWithCenterAligned,
topWithRightAligned,
rightWithTopAligned,
rightWithCenterAligned,
rightWithBottomAligned,
bottomWithLeftAligned,
bottomWithCenterAligned,
bottomWithRightAligned,
leftWithTopAligned,
leftWithCenterAligned,
leftWithBottomAligned,
// Custom position
custom,
}
/// The behaviour of overlay when overlap with anchor widget
enum OverlapBehaviour {
/// Maintain overlay size, which may cover the anchor widget.
none,
/// Resize overlay to avoid overlapping the anchor widget.
stretch,
}
enum OnBackBehavior {
/// Won't handle the back action
none,
/// Animate to get the user's attention
alert,
/// Intercept the back action and abort directly
abort,
/// Intercept the back action and dismiss overlay
dismiss,
}
class FlowyOverlayStyle {
final Color barrierColor;
bool blur;
FlowyOverlayStyle(
{this.barrierColor = Colors.transparent, this.blur = false});
}
final GlobalKey<FlowyOverlayState> _key = GlobalKey<FlowyOverlayState>();
/// Invoke this method in app generation process
Widget overlayManagerBuilder(BuildContext context, Widget? child) {
assert(child != null, 'Child can\'t be null.');
return FlowyOverlay(key: _key, child: child!);
}
abstract mixin class FlowyOverlayDelegate {
bool asBarrier() => false;
void didRemove() => {};
}
class FlowyOverlay extends StatefulWidget {
const FlowyOverlay({super.key, required this.child});
final Widget child;
static FlowyOverlayState of(
BuildContext context, {
bool rootOverlay = false,
}) {
FlowyOverlayState? state = maybeOf(context, rootOverlay: rootOverlay);
assert(() {
if (state == null) {
throw FlutterError(
'Can\'t find overlay manager in current context, please check if already wrapped by overlay manager.',
);
}
return true;
}());
return state!;
}
static FlowyOverlayState? maybeOf(
BuildContext context, {
bool rootOverlay = false,
}) {
FlowyOverlayState? state;
if (rootOverlay) {
state = context.findRootAncestorStateOfType<FlowyOverlayState>();
} else {
state = context.findAncestorStateOfType<FlowyOverlayState>();
}
return state;
}
static Future<void> show({
required BuildContext context,
required WidgetBuilder builder,
}) async {
await showDialog(
context: context,
builder: builder,
);
}
static void pop(BuildContext context) {
Navigator.of(context).pop();
}
@override
FlowyOverlayState createState() => FlowyOverlayState();
}
class OverlayItem {
Widget widget;
String identifier;
FlowyOverlayDelegate? delegate;
FocusNode focusNode;
OverlayItem({
required this.widget,
required this.identifier,
required this.focusNode,
this.delegate,
});
void dispose() {
focusNode.dispose();
}
}
class FlowyOverlayState extends State<FlowyOverlay> {
final List<OverlayItem> _overlayList = [];
FlowyOverlayStyle style = FlowyOverlayStyle();
final Map<ShortcutActivator, void Function(String)>
_keyboardShortcutBindings = {};
/// Insert a overlay widget which frame is set by the widget, not the component.
/// Be sure to specify the offset and size using a anchorable widget (like `Position`, `CompositedTransformFollower`)
void insertCustom({
required Widget widget,
required String identifier,
FlowyOverlayDelegate? delegate,
}) {
_showOverlay(
widget: widget,
identifier: identifier,
shouldAnchor: false,
delegate: delegate,
);
}
void insertWithRect({
required Widget widget,
required String identifier,
required Offset anchorPosition,
required Size anchorSize,
AnchorDirection? anchorDirection,
FlowyOverlayDelegate? delegate,
OverlapBehaviour? overlapBehaviour,
FlowyOverlayStyle? style,
}) {
if (style != null) {
this.style = style;
}
_showOverlay(
widget: widget,
identifier: identifier,
shouldAnchor: true,
delegate: delegate,
anchorPosition: anchorPosition,
anchorSize: anchorSize,
anchorDirection: anchorDirection,
overlapBehaviour: overlapBehaviour,
);
}
void insertWithAnchor({
required Widget widget,
required String identifier,
required BuildContext anchorContext,
AnchorDirection? anchorDirection,
FlowyOverlayDelegate? delegate,
OverlapBehaviour? overlapBehaviour,
FlowyOverlayStyle? style,
Offset? anchorOffset,
}) {
this.style = style ?? FlowyOverlayStyle();
_showOverlay(
widget: widget,
identifier: identifier,
shouldAnchor: true,
delegate: delegate,
anchorContext: anchorContext,
anchorDirection: anchorDirection,
overlapBehaviour: overlapBehaviour,
anchorOffset: anchorOffset,
);
}
void remove(String identifier) {
setState(() {
final index =
_overlayList.indexWhere((item) => item.identifier == identifier);
if (index != -1) {
final OverlayItem item = _overlayList.removeAt(index);
item.delegate?.didRemove();
item.dispose();
}
});
}
void removeAll() {
setState(() {
if (_overlayList.isEmpty) {
return;
}
final reveredList = _overlayList.reversed.toList();
final firstItem = reveredList.removeAt(0);
_overlayList.remove(firstItem);
if (firstItem.delegate != null) {
firstItem.delegate!.didRemove();
firstItem.dispose();
if (firstItem.delegate!.asBarrier()) {
return;
}
}
for (final element in reveredList) {
if (element.delegate?.asBarrier() ?? false) {
return;
} else {
element.delegate?.didRemove();
element.dispose();
_overlayList.remove(element);
}
}
});
}
void _markDirty() {
if (mounted) {
setState(() {});
}
}
void _showOverlay({
required Widget widget,
required String identifier,
required bool shouldAnchor,
Offset? anchorPosition,
Size? anchorSize,
AnchorDirection? anchorDirection,
BuildContext? anchorContext,
Offset? anchorOffset,
OverlapBehaviour? overlapBehaviour,
FlowyOverlayDelegate? delegate,
}) {
Widget overlay = widget;
final offset = anchorOffset ?? Offset.zero;
final focusNode = FocusNode();
if (shouldAnchor) {
assert(
anchorPosition != null || anchorContext != null,
'Must provide `anchorPosition` or `anchorContext` to locating overlay.',
);
Offset targetAnchorPosition = anchorPosition ?? Offset.zero;
Size targetAnchorSize = anchorSize ?? Size.zero;
if (anchorContext != null) {
RenderObject renderObject = anchorContext.findRenderObject()!;
assert(
renderObject is RenderBox,
'Unexpecteded non-RenderBox render object caught.',
);
final renderBox = renderObject as RenderBox;
targetAnchorPosition = renderBox.localToGlobal(Offset.zero);
targetAnchorSize = renderBox.size;
}
final anchorRect = Rect.fromLTWH(
targetAnchorPosition.dx + offset.dx,
targetAnchorPosition.dy + offset.dy,
targetAnchorSize.width,
targetAnchorSize.height,
);
overlay = CustomSingleChildLayout(
delegate: OverlayLayoutDelegate(
anchorRect: anchorRect,
anchorDirection:
anchorDirection ?? AnchorDirection.rightWithTopAligned,
overlapBehaviour: overlapBehaviour ?? OverlapBehaviour.stretch,
),
child: Focus(
focusNode: focusNode,
onKeyEvent: (node, event) {
KeyEventResult result = KeyEventResult.ignored;
for (final ShortcutActivator activator
in _keyboardShortcutBindings.keys) {
if (activator.accepts(event, HardwareKeyboard.instance)) {
_keyboardShortcutBindings[activator]!.call(identifier);
result = KeyEventResult.handled;
}
}
return result;
},
child: widget),
);
}
setState(() {
_overlayList.add(OverlayItem(
widget: overlay,
identifier: identifier,
focusNode: focusNode,
delegate: delegate,
));
});
}
@override
void initState() {
_keyboardShortcutBindings.addAll({
LogicalKeySet(LogicalKeyboardKey.escape): (identifier) {
remove(identifier);
},
});
super.initState();
}
@override
Widget build(BuildContext context) {
final overlays = _overlayList.map((item) {
var widget = item.widget;
// requestFocus will cause the children weird focus behaviors.
// item.focusNode.requestFocus();
if (item.delegate?.asBarrier() ?? false) {
widget = Container(
color: style.barrierColor,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _handleTapOnBackground,
child: widget,
),
);
}
return widget;
}).toList();
List<Widget> children = <Widget>[widget.child];
Widget? child = _renderBackground(overlays);
if (child != null) {
children.add(child);
}
// Try to fix there is no overlay for editabletext widget. e.g. TextField.
// // Check out the TextSelectionOverlay class in text_selection.dart.
// // ...
// // final OverlayState? overlay = Overlay.of(context, rootOverlay: true);
// // assert(
// // overlay != null,
// // 'No Overlay widget exists above $context.\n'
// // 'Usually the Navigator created by WidgetsApp provides the overlay. Perhaps your '
// // 'app content was created above the Navigator with the WidgetsApp builder parameter.',
// // );
// // ...
return MaterialApp(
theme: Theme.of(context),
debugShowCheckedModeBanner: false,
home: Stack(
children: children..addAll(overlays),
),
);
}
void _handleTapOnBackground() {
removeAll();
}
Widget? _renderBackground(List<Widget> overlays) {
Widget? child;
if (overlays.isNotEmpty) {
child = Container(
color: style.barrierColor,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _handleTapOnBackground,
),
);
if (style.blur) {
child = BackdropFilter(
filter: ImageFilter.blur(sigmaX: 4, sigmaY: 4),
child: child,
);
}
}
return child;
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src/flowy_overlay/list_overlay.dart
|
import 'dart:math';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flowy_infra_ui/style_widget/decoration.dart';
class ListOverlayFooter {
Widget widget;
double height;
EdgeInsets padding;
ListOverlayFooter({
required this.widget,
required this.height,
this.padding = EdgeInsets.zero,
});
}
class ListOverlay extends StatelessWidget {
const ListOverlay({
super.key,
required this.itemBuilder,
this.itemCount = 0,
this.controller,
this.constraints = const BoxConstraints(),
this.footer,
});
final IndexedWidgetBuilder itemBuilder;
final int itemCount;
final ScrollController? controller;
final BoxConstraints constraints;
final ListOverlayFooter? footer;
@override
Widget build(BuildContext context) {
const padding = EdgeInsets.symmetric(horizontal: 6, vertical: 6);
double totalHeight = constraints.minHeight + padding.vertical;
if (footer != null) {
totalHeight = totalHeight + footer!.height + footer!.padding.vertical;
}
final innerConstraints = BoxConstraints(
minHeight: totalHeight,
maxHeight: max(constraints.maxHeight, totalHeight),
minWidth: constraints.minWidth,
maxWidth: constraints.maxWidth,
);
List<Widget> children = [];
for (var i = 0; i < itemCount; i++) {
children.add(itemBuilder(context, i));
}
return OverlayContainer(
constraints: innerConstraints,
padding: padding,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: IntrinsicWidth(
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
...children,
if (footer != null)
Padding(
padding: footer!.padding,
child: footer!.widget,
),
],
),
),
),
);
}
static void showWithAnchor(
BuildContext context, {
required String identifier,
required IndexedWidgetBuilder itemBuilder,
int itemCount = 0,
ScrollController? controller,
BoxConstraints constraints = const BoxConstraints(),
required BuildContext anchorContext,
AnchorDirection? anchorDirection,
FlowyOverlayDelegate? delegate,
OverlapBehaviour? overlapBehaviour,
FlowyOverlayStyle? style,
Offset? anchorOffset,
ListOverlayFooter? footer,
}) {
FlowyOverlay.of(context).insertWithAnchor(
widget: ListOverlay(
itemBuilder: itemBuilder,
itemCount: itemCount,
controller: controller,
constraints: constraints,
footer: footer,
),
identifier: identifier,
anchorContext: anchorContext,
anchorDirection: anchorDirection,
delegate: delegate,
overlapBehaviour: overlapBehaviour,
anchorOffset: anchorOffset,
style: style,
);
}
}
const overlayContainerPadding = EdgeInsets.all(12);
class OverlayContainer extends StatelessWidget {
final Widget child;
final BoxConstraints? constraints;
final EdgeInsets padding;
const OverlayContainer({
required this.child,
this.constraints,
this.padding = overlayContainerPadding,
super.key,
});
@override
Widget build(BuildContext context) {
return Material(
type: MaterialType.transparency,
child: Container(
padding: padding,
decoration: FlowyDecoration.decoration(
Theme.of(context).colorScheme.surface,
Theme.of(context).colorScheme.shadow.withOpacity(0.15),
),
constraints: constraints,
child: child,
),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src/flowy_overlay/flowy_popover_layout.dart
|
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'flowy_overlay.dart';
class PopoverLayoutDelegate extends SingleChildLayoutDelegate {
PopoverLayoutDelegate({
required this.anchorRect,
required this.anchorDirection,
required this.overlapBehaviour,
});
final Rect anchorRect;
final AnchorDirection anchorDirection;
final OverlapBehaviour overlapBehaviour;
@override
bool shouldRelayout(PopoverLayoutDelegate oldDelegate) {
return anchorRect != oldDelegate.anchorRect ||
anchorDirection != oldDelegate.anchorDirection ||
overlapBehaviour != oldDelegate.overlapBehaviour;
}
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
switch (overlapBehaviour) {
case OverlapBehaviour.none:
return constraints.loosen();
case OverlapBehaviour.stretch:
BoxConstraints childConstraints;
switch (anchorDirection) {
case AnchorDirection.topLeft:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
anchorRect.top,
));
break;
case AnchorDirection.topRight:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.right,
anchorRect.top,
));
break;
case AnchorDirection.bottomLeft:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
constraints.maxHeight - anchorRect.bottom,
));
break;
case AnchorDirection.bottomRight:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.right,
constraints.maxHeight - anchorRect.bottom,
));
break;
case AnchorDirection.center:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth,
constraints.maxHeight,
));
break;
case AnchorDirection.topWithLeftAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.left,
anchorRect.top,
));
break;
case AnchorDirection.topWithCenterAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth,
anchorRect.top,
));
break;
case AnchorDirection.topWithRightAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.right,
anchorRect.top,
));
break;
case AnchorDirection.rightWithTopAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.right,
constraints.maxHeight - anchorRect.top,
));
break;
case AnchorDirection.rightWithCenterAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.right,
constraints.maxHeight,
));
break;
case AnchorDirection.rightWithBottomAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth - anchorRect.right,
anchorRect.bottom,
));
break;
case AnchorDirection.bottomWithLeftAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
constraints.maxHeight - anchorRect.bottom,
));
break;
case AnchorDirection.bottomWithCenterAligned:
childConstraints = BoxConstraints.loose(Size(
constraints.maxWidth,
constraints.maxHeight - anchorRect.bottom,
));
break;
case AnchorDirection.bottomWithRightAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.right,
constraints.maxHeight - anchorRect.bottom,
));
break;
case AnchorDirection.leftWithTopAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
constraints.maxHeight - anchorRect.top,
));
break;
case AnchorDirection.leftWithCenterAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
constraints.maxHeight,
));
break;
case AnchorDirection.leftWithBottomAligned:
childConstraints = BoxConstraints.loose(Size(
anchorRect.left,
anchorRect.bottom,
));
break;
case AnchorDirection.custom:
childConstraints = constraints.loosen();
break;
default:
throw UnimplementedError();
}
return childConstraints;
}
}
@override
Offset getPositionForChild(Size size, Size childSize) {
Offset position;
switch (anchorDirection) {
case AnchorDirection.topLeft:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.top - childSize.height,
);
break;
case AnchorDirection.topRight:
position = Offset(
anchorRect.right,
anchorRect.top - childSize.height,
);
break;
case AnchorDirection.bottomLeft:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.bottom,
);
break;
case AnchorDirection.bottomRight:
position = Offset(
anchorRect.right,
anchorRect.bottom,
);
break;
case AnchorDirection.center:
position = anchorRect.center;
break;
case AnchorDirection.topWithLeftAligned:
position = Offset(
anchorRect.left,
anchorRect.top - childSize.height,
);
break;
case AnchorDirection.topWithCenterAligned:
position = Offset(
anchorRect.left + anchorRect.width / 2.0 - childSize.width / 2.0,
anchorRect.top - childSize.height,
);
break;
case AnchorDirection.topWithRightAligned:
position = Offset(
anchorRect.right - childSize.width,
anchorRect.top - childSize.height,
);
break;
case AnchorDirection.rightWithTopAligned:
position = Offset(anchorRect.right, anchorRect.top);
break;
case AnchorDirection.rightWithCenterAligned:
position = Offset(
anchorRect.right,
anchorRect.top + anchorRect.height / 2.0 - childSize.height / 2.0,
);
break;
case AnchorDirection.rightWithBottomAligned:
position = Offset(
anchorRect.right,
anchorRect.bottom - childSize.height,
);
break;
case AnchorDirection.bottomWithLeftAligned:
position = Offset(
anchorRect.left,
anchorRect.bottom,
);
break;
case AnchorDirection.bottomWithCenterAligned:
position = Offset(
anchorRect.left + anchorRect.width / 2.0 - childSize.width / 2.0,
anchorRect.bottom,
);
break;
case AnchorDirection.bottomWithRightAligned:
position = Offset(
anchorRect.right - childSize.width,
anchorRect.bottom,
);
break;
case AnchorDirection.leftWithTopAligned:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.top,
);
break;
case AnchorDirection.leftWithCenterAligned:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.top + anchorRect.height / 2.0 - childSize.height / 2.0,
);
break;
case AnchorDirection.leftWithBottomAligned:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.bottom - childSize.height,
);
break;
default:
throw UnimplementedError();
}
return Offset(
math.max(0.0, math.min(size.width - childSize.width, position.dx)),
math.max(0.0, math.min(size.height - childSize.height, position.dy)),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src/flowy_overlay/flowy_dialog.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
const _overlayContainerPadding = EdgeInsets.symmetric(vertical: 12);
const overlayContainerMaxWidth = 760.0;
const overlayContainerMinWidth = 320.0;
const _defaultInsetPadding =
EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0);
class FlowyDialog extends StatelessWidget {
const FlowyDialog({
super.key,
required this.child,
this.title,
this.shape,
this.constraints,
this.padding = _overlayContainerPadding,
this.backgroundColor,
this.expandHeight = true,
this.alignment,
this.insetPadding,
this.width,
});
final Widget? title;
final ShapeBorder? shape;
final Widget child;
final BoxConstraints? constraints;
final EdgeInsets padding;
final Color? backgroundColor;
final bool expandHeight;
// Position of the Dialog
final Alignment? alignment;
// Inset of the Dialog
final EdgeInsets? insetPadding;
final double? width;
@override
Widget build(BuildContext context) {
final windowSize = MediaQuery.of(context).size;
final size = windowSize * 0.7;
return SimpleDialog(
alignment: alignment,
insetPadding: insetPadding ?? _defaultInsetPadding,
contentPadding: EdgeInsets.zero,
backgroundColor: backgroundColor ?? Theme.of(context).cardColor,
title: title,
shape: shape ??
RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
clipBehavior: Clip.hardEdge,
children: [
Material(
type: MaterialType.transparency,
child: Container(
height: expandHeight ? size.height : null,
width: width ??
max(min(size.width, overlayContainerMaxWidth),
overlayContainerMinWidth),
constraints: constraints,
child: child,
),
)
],
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src/keyboard/keyboard_visibility_detector.dart
|
import 'dart:async';
import 'package:flowy_infra_ui_platform_interface/flowy_infra_ui_platform_interface.dart';
import 'package:flutter/material.dart';
class KeyboardVisibilityDetector extends StatefulWidget {
const KeyboardVisibilityDetector({
super.key,
required this.child,
this.onKeyboardVisibilityChange,
});
final Widget child;
final void Function(bool)? onKeyboardVisibilityChange;
@override
State<KeyboardVisibilityDetector> createState() =>
_KeyboardVisibilityDetectorState();
}
class _KeyboardVisibilityDetectorState
extends State<KeyboardVisibilityDetector> {
FlowyInfraUIPlatform get _platform => FlowyInfraUIPlatform.instance;
bool isObserving = false;
bool isKeyboardVisible = false;
late StreamSubscription _keyboardSubscription;
@override
void initState() {
super.initState();
_keyboardSubscription =
_platform.onKeyboardVisibilityChange.listen((newValue) {
setState(() {
isKeyboardVisible = newValue;
if (widget.onKeyboardVisibilityChange != null) {
widget.onKeyboardVisibilityChange!(newValue);
}
});
});
}
@override
void dispose() {
_keyboardSubscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return _KeyboardVisibilityDetectorInheritedWidget(
isKeyboardVisible: isKeyboardVisible,
child: widget.child,
);
}
}
class _KeyboardVisibilityDetectorInheritedWidget extends InheritedWidget {
const _KeyboardVisibilityDetectorInheritedWidget({
required this.isKeyboardVisible,
required super.child,
});
final bool isKeyboardVisible;
@override
bool updateShouldNotify(
_KeyboardVisibilityDetectorInheritedWidget oldWidget) {
return isKeyboardVisible != oldWidget.isKeyboardVisible;
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/src/focus/auto_unfocus_overlay.dart
|
import 'package:flutter/material.dart';
class AutoUnfocus extends StatelessWidget {
const AutoUnfocus({
super.key,
required this.child,
});
final Widget child;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => _unfocusWidget(context),
child: child,
);
}
void _unfocusWidget(BuildContext context) {
final focusing = FocusScope.of(context);
if (!focusing.hasPrimaryFocus && focusing.hasFocus) {
FocusManager.instance.primaryFocus?.unfocus();
}
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/constraint_flex_view.dart
|
import 'package:flutter/material.dart';
class ConstrainedFlexView extends StatelessWidget {
final Widget child;
final double minSize;
final Axis axis;
final EdgeInsets scrollPadding;
const ConstrainedFlexView(this.minSize,
{super.key,
required this.child,
this.axis = Axis.horizontal,
this.scrollPadding = EdgeInsets.zero});
bool get isHz => axis == Axis.horizontal;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (_, constraints) {
final viewSize = isHz ? constraints.maxWidth : constraints.maxHeight;
if (viewSize > minSize) return child;
return Padding(
padding: scrollPadding,
child: SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: isHz ? double.infinity : minSize,
maxWidth: isHz ? minSize : double.infinity),
child: child,
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/rounded_button.dart
|
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flutter/material.dart';
class RoundedTextButton extends StatelessWidget {
final VoidCallback? onPressed;
final String? title;
final double? width;
final double? height;
final BorderRadius? borderRadius;
final Color borderColor;
final Color? fillColor;
final Color? hoverColor;
final Color? textColor;
final double? fontSize;
final EdgeInsets padding;
const RoundedTextButton({
super.key,
this.onPressed,
this.title,
this.width,
this.height,
this.borderRadius,
this.borderColor = Colors.transparent,
this.fillColor,
this.hoverColor,
this.textColor,
this.fontSize,
this.padding = const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
});
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: BoxConstraints(
minWidth: 10,
maxWidth: width ?? double.infinity,
minHeight: 10,
maxHeight: height ?? 60,
),
child: SizedBox.expand(
child: FlowyTextButton(
title ?? '',
onPressed: onPressed,
fontSize: fontSize,
mainAxisAlignment: MainAxisAlignment.center,
radius: borderRadius ?? Corners.s6Border,
fontColor: textColor ?? Theme.of(context).colorScheme.onPrimary,
fillColor: fillColor ?? Theme.of(context).colorScheme.primary,
hoverColor:
hoverColor ?? Theme.of(context).colorScheme.primaryContainer,
padding: padding,
),
),
);
}
}
class RoundedImageButton extends StatelessWidget {
final VoidCallback? press;
final double size;
final BorderRadius borderRadius;
final Color borderColor;
final Color color;
final Widget child;
const RoundedImageButton({
super.key,
this.press,
required this.size,
this.borderRadius = BorderRadius.zero,
this.borderColor = Colors.transparent,
this.color = Colors.transparent,
required this.child,
});
@override
Widget build(BuildContext context) {
return SizedBox(
width: size,
height: size,
child: TextButton(
onPressed: press,
style: ButtonStyle(
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(borderRadius: borderRadius))),
child: child,
),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/rounded_input_field.dart
|
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/widget/rounded_button.dart';
import 'package:flutter/material.dart';
import 'package:flowy_infra/time/duration.dart';
import 'package:flutter/services.dart';
class RoundedInputField extends StatefulWidget {
final String? hintText;
final bool obscureText;
final Widget? obscureIcon;
final Widget? obscureHideIcon;
final Color? normalBorderColor;
final Color? errorBorderColor;
final Color? cursorColor;
final Color? focusBorderColor;
final String errorText;
final TextStyle? style;
final ValueChanged<String>? onChanged;
final Function(String)? onEditingComplete;
final String? initialValue;
final EdgeInsets margin;
final EdgeInsets padding;
final EdgeInsets contentPadding;
final double height;
final FocusNode? focusNode;
final TextEditingController? controller;
final bool autoFocus;
final int? maxLength;
final Function(String)? onFieldSubmitted;
const RoundedInputField({
super.key,
this.hintText,
this.errorText = "",
this.initialValue,
this.obscureText = false,
this.obscureIcon,
this.obscureHideIcon,
this.onChanged,
this.onEditingComplete,
this.normalBorderColor,
this.errorBorderColor,
this.focusBorderColor,
this.cursorColor,
this.style,
this.margin = EdgeInsets.zero,
this.padding = EdgeInsets.zero,
this.contentPadding = const EdgeInsets.symmetric(horizontal: 10),
this.height = 48,
this.focusNode,
this.controller,
this.autoFocus = false,
this.maxLength,
this.onFieldSubmitted,
});
@override
State<RoundedInputField> createState() => _RoundedInputFieldState();
}
class _RoundedInputFieldState extends State<RoundedInputField> {
String inputText = "";
bool obscuteText = false;
@override
void initState() {
obscuteText = widget.obscureText;
if (widget.controller != null) {
inputText = widget.controller!.text;
} else {
inputText = widget.initialValue ?? "";
}
super.initState();
}
String? _suffixText() {
if (widget.maxLength != null) {
return ' ${widget.controller!.text.length}/${widget.maxLength}';
} else {
return null;
}
}
@override
Widget build(BuildContext context) {
var borderColor =
widget.normalBorderColor ?? Theme.of(context).colorScheme.outline;
var focusBorderColor =
widget.focusBorderColor ?? Theme.of(context).colorScheme.primary;
if (widget.errorText.isNotEmpty) {
borderColor = Theme.of(context).colorScheme.error;
focusBorderColor = borderColor;
}
List<Widget> children = [
Container(
margin: widget.margin,
padding: widget.padding,
height: widget.height,
child: TextFormField(
controller: widget.controller,
initialValue: widget.initialValue,
focusNode: widget.focusNode,
autofocus: widget.autoFocus,
maxLength: widget.maxLength,
maxLengthEnforcement:
MaxLengthEnforcement.truncateAfterCompositionEnds,
onFieldSubmitted: widget.onFieldSubmitted,
onChanged: (value) {
inputText = value;
if (widget.onChanged != null) {
widget.onChanged!(value);
}
setState(() {});
},
onEditingComplete: () {
if (widget.onEditingComplete != null) {
widget.onEditingComplete!(inputText);
}
},
cursorColor:
widget.cursorColor ?? Theme.of(context).colorScheme.primary,
obscureText: obscuteText,
style: widget.style ?? Theme.of(context).textTheme.bodyMedium,
decoration: InputDecoration(
contentPadding: widget.contentPadding,
hintText: widget.hintText,
hintStyle: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(color: Theme.of(context).hintColor),
suffixText: _suffixText(),
counterText: "",
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: borderColor,
width: 1.0,
),
borderRadius: Corners.s10Border,
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: focusBorderColor,
width: 1.0,
),
borderRadius: Corners.s10Border,
),
suffixIcon: obscureIcon(),
),
),
),
];
if (widget.errorText.isNotEmpty) {
children.add(
Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Text(
widget.errorText,
style: widget.style,
),
),
),
);
}
return AnimatedSize(
duration: .4.seconds,
curve: Curves.easeInOut,
child: Column(children: children),
);
}
Widget? obscureIcon() {
if (widget.obscureText == false) {
return null;
}
const double iconWidth = 16;
if (inputText.isEmpty) {
return SizedBox.fromSize(size: const Size.square(iconWidth));
}
assert(widget.obscureIcon != null && widget.obscureHideIcon != null);
Widget? icon;
if (obscuteText) {
icon = widget.obscureIcon!;
} else {
icon = widget.obscureHideIcon!;
}
return RoundedImageButton(
size: iconWidth,
press: () {
obscuteText = !obscuteText;
setState(() {});
},
child: icon,
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/error_page.dart
|
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_svg/flowy_svg.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
class FlowyErrorPage extends StatelessWidget {
factory FlowyErrorPage.error(
Error e, {
required String howToFix,
Key? key,
List<Widget>? actions,
}) =>
FlowyErrorPage._(
e.toString(),
stackTrace: e.stackTrace?.toString(),
howToFix: howToFix,
key: key,
actions: actions,
);
factory FlowyErrorPage.message(
String message, {
required String howToFix,
String? stackTrace,
Key? key,
List<Widget>? actions,
}) =>
FlowyErrorPage._(
message,
key: key,
stackTrace: stackTrace,
howToFix: howToFix,
actions: actions,
);
factory FlowyErrorPage.exception(
Exception e, {
required String howToFix,
String? stackTrace,
Key? key,
List<Widget>? actions,
}) =>
FlowyErrorPage._(
e.toString(),
stackTrace: stackTrace,
key: key,
howToFix: howToFix,
actions: actions,
);
const FlowyErrorPage._(
this.message, {
required this.howToFix,
this.stackTrace,
super.key,
this.actions,
});
static const _titleFontSize = 24.0;
static const _titleToMessagePadding = 8.0;
final List<Widget>? actions;
final String howToFix;
final String message;
final String? stackTrace;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
// mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const FlowyText.medium(
"AppFlowy Error",
fontSize: _titleFontSize,
),
const SizedBox(
height: _titleToMessagePadding,
),
FlowyText.semibold(
message,
maxLines: 10,
),
const SizedBox(
height: _titleToMessagePadding,
),
FlowyText.regular(
howToFix,
maxLines: 10,
),
const SizedBox(
height: _titleToMessagePadding,
),
const GitHubRedirectButton(),
const SizedBox(
height: _titleToMessagePadding,
),
if (stackTrace != null) StackTracePreview(stackTrace!),
if (actions != null)
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: actions!,
),
],
),
);
}
}
class StackTracePreview extends StatelessWidget {
const StackTracePreview(
this.stackTrace, {
super.key,
});
final String stackTrace;
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 350,
maxWidth: 450,
),
child: Card(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
clipBehavior: Clip.antiAlias,
margin: EdgeInsets.zero,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
const Align(
alignment: Alignment.centerLeft,
child: FlowyText.semibold(
"Stack Trace",
),
),
Container(
height: 120,
padding: const EdgeInsets.symmetric(vertical: 8),
child: SingleChildScrollView(
child: Text(
stackTrace,
style: Theme.of(context).textTheme.bodySmall,
),
),
),
Align(
alignment: Alignment.centerRight,
child: FlowyButton(
hoverColor: Theme.of(context).colorScheme.onBackground,
text: const FlowyText(
"Copy",
),
useIntrinsicWidth: true,
onTap: () => Clipboard.setData(
ClipboardData(text: stackTrace),
),
),
),
],
),
),
),
);
}
}
class GitHubRedirectButton extends StatelessWidget {
const GitHubRedirectButton({super.key});
static const _height = 32.0;
Uri get _gitHubNewBugUri => Uri(
scheme: 'https',
host: 'github.com',
path: '/AppFlowy-IO/AppFlowy/issues/new',
query:
'assignees=&labels=&projects=&template=bug_report.yaml&title=%5BBug%5D+',
);
@override
Widget build(BuildContext context) {
return FlowyButton(
leftIconSize: const Size.square(_height),
text: const FlowyText(
"AppFlowy",
),
useIntrinsicWidth: true,
leftIcon: const Padding(
padding: EdgeInsets.all(4.0),
child: FlowySvg(FlowySvgData('login/github-mark')),
),
onTap: () async {
if (await canLaunchUrl(_gitHubNewBugUri)) {
await launchUrl(_gitHubNewBugUri);
}
},
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/ignore_parent_gesture.dart
|
import 'package:flutter/material.dart';
class IgnoreParentGestureWidget extends StatelessWidget {
const IgnoreParentGestureWidget({
super.key,
required this.child,
this.onPress,
});
final Widget child;
final VoidCallback? onPress;
@override
Widget build(BuildContext context) {
// https://docs.flutter.dev/development/ui/advanced/gestures#gesture-disambiguation
// https://github.com/AppFlowy-IO/AppFlowy/issues/1290
return Listener(
onPointerDown: (event) {
onPress?.call();
},
onPointerSignal: (event) {},
onPointerMove: (event) {},
onPointerUp: (event) {},
onPointerHover: (event) {},
onPointerPanZoomStart: (event) {},
onPointerPanZoomUpdate: (event) {},
onPointerPanZoomEnd: (event) {},
child: child,
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/flowy_tooltip.dart
|
import 'package:flutter/material.dart';
const _tooltipWaitDuration = Duration(milliseconds: 300);
class FlowyTooltip extends StatelessWidget {
const FlowyTooltip({
super.key,
this.message,
this.richMessage,
this.preferBelow,
this.showDuration,
this.margin,
this.child,
});
final String? message;
final InlineSpan? richMessage;
final bool? preferBelow;
final Duration? showDuration;
final EdgeInsetsGeometry? margin;
final Widget? child;
@override
Widget build(BuildContext context) {
return Tooltip(
margin: margin,
waitDuration: _tooltipWaitDuration,
message: message,
richMessage: richMessage,
showDuration: showDuration,
preferBelow: preferBelow,
child: child,
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/spacing.dart
|
import 'package:flutter/cupertino.dart';
class Space extends StatelessWidget {
final double width;
final double height;
const Space(this.width, this.height, {super.key});
@override
Widget build(BuildContext context) => SizedBox(width: width, height: height);
}
class VSpace extends StatelessWidget {
const VSpace(
this.size, {
super.key,
this.color,
});
final double size;
final Color? color;
@override
Widget build(BuildContext context) {
if (color != null) {
return SizedBox(
height: size,
width: double.infinity,
child: ColoredBox(
color: color!,
),
);
} else {
return Space(0, size);
}
}
}
class HSpace extends StatelessWidget {
const HSpace(
this.size, {
super.key,
this.color,
});
final double size;
final Color? color;
@override
Widget build(BuildContext context) {
if (color != null) {
return SizedBox(
height: double.infinity,
width: size,
child: ColoredBox(
color: color!,
),
);
} else {
return Space(size, 0);
}
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/mouse_hover_builder.dart
|
import 'package:flutter/material.dart';
typedef HoverBuilder = Widget Function(BuildContext context, bool onHover);
class MouseHoverBuilder extends StatefulWidget {
final bool isClickable;
const MouseHoverBuilder(
{super.key, required this.builder, this.isClickable = false});
final HoverBuilder builder;
@override
State<MouseHoverBuilder> createState() => _MouseHoverBuilderState();
}
class _MouseHoverBuilderState extends State<MouseHoverBuilder> {
bool _onHover = false;
@override
Widget build(BuildContext context) {
return MouseRegion(
cursor: widget.isClickable
? SystemMouseCursors.click
: SystemMouseCursors.basic,
onEnter: (p) => setOnHover(true),
onExit: (p) => setOnHover(false),
child: widget.builder(context, _onHover),
);
}
void setOnHover(bool value) => setState(() => _onHover = value);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/separated_flex.dart
|
import 'package:flutter/material.dart';
typedef SeparatorBuilder = Widget Function();
Widget _defaultColumnSeparatorBuilder() => const Divider();
Widget _defaultRowSeparatorBuilder() => const VerticalDivider();
class SeparatedColumn extends Column {
SeparatedColumn({
super.key,
super.mainAxisAlignment,
super.crossAxisAlignment,
super.mainAxisSize,
super.textBaseline,
super.textDirection,
super.verticalDirection,
SeparatorBuilder separatorBuilder = _defaultColumnSeparatorBuilder,
required List<Widget> children,
}) : super(children: _insertSeparators(children, separatorBuilder));
}
class SeparatedRow extends Row {
SeparatedRow({
super.key,
super.mainAxisAlignment,
super.crossAxisAlignment,
super.mainAxisSize,
super.textBaseline,
super.textDirection,
super.verticalDirection,
SeparatorBuilder separatorBuilder = _defaultRowSeparatorBuilder,
required List<Widget> children,
}) : super(children: _insertSeparators(children, separatorBuilder));
}
List<Widget> _insertSeparators(
List<Widget> children,
SeparatorBuilder separatorBuilder,
) {
if (children.length < 2) {
return children;
}
List<Widget> newChildren = [];
for (int i = 0; i < children.length - 1; i++) {
newChildren.add(children[i]);
newChildren.add(separatorBuilder());
}
return newChildren..add(children.last);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/route/animation.dart
|
import 'package:animations/animations.dart';
import 'package:flutter/material.dart';
typedef PageBuilder = Widget Function();
class PageRoutes {
static const double kDefaultDuration = .35;
static const Curve kDefaultEaseFwd = Curves.easeOut;
static const Curve kDefaultEaseReverse = Curves.easeOut;
static Route<T> fade<T>(PageBuilder pageBuilder, RouteSettings? settings,
[double duration = kDefaultDuration]) {
return PageRouteBuilder<T>(
settings: settings,
transitionDuration: Duration(milliseconds: (duration * 1000).round()),
pageBuilder: (context, animation, secondaryAnimation) => pageBuilder(),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return FadeTransition(opacity: animation, child: child);
},
);
}
static Route<T> fadeThrough<T>(PageBuilder pageBuilder,
[double duration = kDefaultDuration]) {
return PageRouteBuilder<T>(
transitionDuration: Duration(milliseconds: (duration * 1000).round()),
pageBuilder: (context, animation, secondaryAnimation) => pageBuilder(),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return FadeThroughTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
child: child);
},
);
}
static Route<T> fadeScale<T>(PageBuilder pageBuilder,
[double duration = kDefaultDuration]) {
return PageRouteBuilder<T>(
transitionDuration: Duration(milliseconds: (duration * 1000).round()),
pageBuilder: (context, animation, secondaryAnimation) => pageBuilder(),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return FadeScaleTransition(animation: animation, child: child);
},
);
}
static Route<T> sharedAxis<T>(PageBuilder pageBuilder,
[SharedAxisTransitionType type = SharedAxisTransitionType.scaled,
double duration = kDefaultDuration]) {
return PageRouteBuilder<T>(
transitionDuration: Duration(milliseconds: (duration * 1000).round()),
pageBuilder: (context, animation, secondaryAnimation) => pageBuilder(),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return SharedAxisTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
transitionType: type,
child: child,
);
},
);
}
static Route<T> slide<T>(PageBuilder pageBuilder,
{double duration = kDefaultDuration,
Offset startOffset = const Offset(1, 0),
Curve easeFwd = kDefaultEaseFwd,
Curve easeReverse = kDefaultEaseReverse}) {
return PageRouteBuilder<T>(
transitionDuration: Duration(milliseconds: (duration * 1000).round()),
pageBuilder: (context, animation, secondaryAnimation) => pageBuilder(),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
bool reverse = animation.status == AnimationStatus.reverse;
return SlideTransition(
position: Tween<Offset>(begin: startOffset, end: const Offset(0, 0))
.animate(CurvedAnimation(
parent: animation, curve: reverse ? easeReverse : easeFwd)),
child: child,
);
},
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/buttons/base_styled_button.dart
|
import 'package:flowy_infra/size.dart';
import 'package:flutter/material.dart';
class BaseStyledButton extends StatefulWidget {
final Widget child;
final VoidCallback? onPressed;
final Function(bool)? onFocusChanged;
final Function(bool)? onHighlightChanged;
final Color? bgColor;
final Color? focusColor;
final Color? hoverColor;
final Color? highlightColor;
final EdgeInsets? contentPadding;
final double? minWidth;
final double? minHeight;
final BorderRadius? borderRadius;
final bool useBtnText;
final bool autoFocus;
final ShapeBorder? shape;
final Color outlineColor;
const BaseStyledButton({
super.key,
required this.child,
this.onPressed,
this.onFocusChanged,
this.onHighlightChanged,
this.bgColor,
this.focusColor,
this.contentPadding,
this.minWidth,
this.minHeight,
this.borderRadius,
this.hoverColor,
this.highlightColor,
this.shape,
this.useBtnText = true,
this.autoFocus = false,
this.outlineColor = Colors.transparent,
});
@override
State<BaseStyledButton> createState() => BaseStyledBtnState();
}
class BaseStyledBtnState extends State<BaseStyledButton> {
late FocusNode _focusNode;
bool _isFocused = false;
@override
void initState() {
super.initState();
_focusNode = FocusNode(debugLabel: '', canRequestFocus: true);
_focusNode.addListener(() {
if (_focusNode.hasFocus != _isFocused) {
setState(() => _isFocused = _focusNode.hasFocus);
widget.onFocusChanged?.call(_isFocused);
}
});
}
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: widget.bgColor ?? Theme.of(context).colorScheme.surface,
borderRadius: widget.borderRadius ?? Corners.s10Border,
boxShadow: _isFocused
? [
BoxShadow(
color: Theme.of(context).colorScheme.shadow,
offset: Offset.zero,
blurRadius: 8.0,
spreadRadius: 0.0,
),
BoxShadow(
color:
widget.bgColor ?? Theme.of(context).colorScheme.surface,
offset: Offset.zero,
blurRadius: 8.0,
spreadRadius: -4.0,
),
]
: [],
),
foregroundDecoration: _isFocused
? ShapeDecoration(
shape: RoundedRectangleBorder(
side: BorderSide(
width: 1.8,
color: Theme.of(context).colorScheme.outline,
),
borderRadius: widget.borderRadius ?? Corners.s10Border,
),
)
: null,
child: RawMaterialButton(
focusNode: _focusNode,
autofocus: widget.autoFocus,
textStyle:
widget.useBtnText ? Theme.of(context).textTheme.bodyMedium : null,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
// visualDensity: VisualDensity.compact,
splashColor: Colors.transparent,
mouseCursor: SystemMouseCursors.click,
elevation: 0,
hoverElevation: 0,
highlightElevation: 0,
focusElevation: 0,
fillColor: Colors.transparent,
hoverColor: widget.hoverColor ?? Colors.transparent,
highlightColor: widget.highlightColor ?? Colors.transparent,
focusColor: widget.focusColor ?? Colors.grey.withOpacity(0.35),
constraints: BoxConstraints(
minHeight: widget.minHeight ?? 0, minWidth: widget.minWidth ?? 0),
onPressed: widget.onPressed,
shape: widget.shape ??
RoundedRectangleBorder(
side: BorderSide(color: widget.outlineColor, width: 1.5),
borderRadius: widget.borderRadius ?? Corners.s10Border,
),
child: Opacity(
opacity: widget.onPressed != null ? 1 : .7,
child: Padding(
padding: widget.contentPadding ?? EdgeInsets.all(Insets.m),
child: widget.child,
),
),
),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/buttons/primary_button.dart
|
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flutter/material.dart';
import 'base_styled_button.dart';
import 'secondary_button.dart';
class PrimaryTextButton extends StatelessWidget {
final String label;
final VoidCallback? onPressed;
final TextButtonMode mode;
const PrimaryTextButton(this.label,
{super.key, this.onPressed, this.mode = TextButtonMode.big});
@override
Widget build(BuildContext context) {
return PrimaryButton(
mode: mode,
onPressed: onPressed,
child: FlowyText.regular(
label,
color: Theme.of(context).colorScheme.onPrimary,
),
);
}
}
class PrimaryButton extends StatelessWidget {
const PrimaryButton({
super.key,
required this.child,
this.onPressed,
this.mode = TextButtonMode.big,
this.backgroundColor,
});
final Widget child;
final VoidCallback? onPressed;
final TextButtonMode mode;
final Color? backgroundColor;
@override
Widget build(BuildContext context) {
return BaseStyledButton(
minWidth: mode.size.width,
minHeight: mode.size.height,
contentPadding: EdgeInsets.zero,
bgColor: backgroundColor ?? Theme.of(context).colorScheme.primary,
hoverColor: Theme.of(context).colorScheme.primaryContainer,
borderRadius: mode.borderRadius,
onPressed: onPressed,
child: child,
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/buttons/secondary_button.dart
|
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flutter/material.dart';
import 'package:flowy_infra/size.dart';
import 'base_styled_button.dart';
enum TextButtonMode {
normal,
big,
small;
Size get size {
switch (this) {
case TextButtonMode.normal:
return const Size(80, 32);
case TextButtonMode.big:
return const Size(100, 40);
case TextButtonMode.small:
return const Size(100, 30);
}
}
BorderRadius get borderRadius {
switch (this) {
case TextButtonMode.normal:
return Corners.s8Border;
case TextButtonMode.big:
return Corners.s12Border;
case TextButtonMode.small:
return Corners.s6Border;
}
}
}
class SecondaryTextButton extends StatelessWidget {
const SecondaryTextButton(
this.label, {
super.key,
this.onPressed,
this.textColor,
this.outlineColor,
this.mode = TextButtonMode.normal,
});
final String label;
final VoidCallback? onPressed;
final TextButtonMode mode;
final Color? textColor;
final Color? outlineColor;
@override
Widget build(BuildContext context) {
return SecondaryButton(
mode: mode,
onPressed: onPressed,
outlineColor: outlineColor,
child: FlowyText.regular(
label,
color: textColor ?? Theme.of(context).colorScheme.primary,
),
);
}
}
class SecondaryButton extends StatelessWidget {
const SecondaryButton({
super.key,
required this.child,
this.onPressed,
this.outlineColor,
this.mode = TextButtonMode.normal,
});
final Widget child;
final VoidCallback? onPressed;
final TextButtonMode mode;
final Color? outlineColor;
@override
Widget build(BuildContext context) {
final size = mode.size;
return BaseStyledButton(
minWidth: size.width,
minHeight: size.height,
contentPadding: EdgeInsets.zero,
bgColor: Colors.transparent,
outlineColor: outlineColor ?? Theme.of(context).colorScheme.primary,
borderRadius: mode.borderRadius,
onPressed: onPressed,
child: child,
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/dialog/styled_dialogs.dart
|
import 'dart:ui';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/style_widget/scrolling/styled_list.dart';
import 'package:flowy_infra_ui/widget/dialog/dialog_size.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
extension IntoDialog on Widget {
Future<dynamic> show(BuildContext context) async {
FocusNode dialogFocusNode = FocusNode();
await Dialogs.show(
child: KeyboardListener(
focusNode: dialogFocusNode,
onKeyEvent: (event) {
if (event.logicalKey == LogicalKeyboardKey.escape) {
Navigator.of(context).pop();
}
},
child: this,
),
context,
);
dialogFocusNode.dispose();
}
}
class StyledDialog extends StatelessWidget {
final Widget child;
final double? maxWidth;
final double? maxHeight;
final EdgeInsets? padding;
final EdgeInsets? margin;
final BorderRadius? borderRadius;
final Color? bgColor;
final bool shrinkWrap;
const StyledDialog({
super.key,
required this.child,
this.maxWidth,
this.maxHeight,
this.padding,
this.margin,
this.bgColor,
this.borderRadius = const BorderRadius.all(Radius.circular(6)),
this.shrinkWrap = true,
});
@override
Widget build(BuildContext context) {
Widget innerContent = Container(
padding: padding ??
EdgeInsets.symmetric(horizontal: Insets.xxl, vertical: Insets.xl),
color: bgColor ?? Theme.of(context).colorScheme.surface,
child: child,
);
if (shrinkWrap) {
innerContent =
IntrinsicWidth(child: IntrinsicHeight(child: innerContent));
}
return FocusTraversalGroup(
child: Container(
margin: margin ?? EdgeInsets.all(Insets.sm * 2),
alignment: Alignment.center,
child: Container(
constraints: BoxConstraints(
minWidth: DialogSize.minDialogWidth,
maxHeight: maxHeight ?? double.infinity,
maxWidth: maxWidth ?? double.infinity,
),
child: ClipRRect(
borderRadius: borderRadius ?? BorderRadius.zero,
child: SingleChildScrollView(
physics: StyledScrollPhysics(),
//https://medium.com/saugo360/https-medium-com-saugo360-flutter-using-overlay-to-display-floating-widgets-2e6d0e8decb9
child: Material(
type: MaterialType.transparency,
child: innerContent,
),
),
),
),
),
);
}
}
class Dialogs {
static Future<dynamic> show(BuildContext context,
{required Widget child}) async {
return await Navigator.of(context).push(
StyledDialogRoute(
barrier: DialogBarrier(color: Colors.black.withOpacity(0.4)),
pageBuilder: (BuildContext buildContext, Animation<double> animation,
Animation<double> secondaryAnimation) {
return SafeArea(child: child);
},
),
);
}
}
class DialogBarrier {
String label;
Color color;
bool dismissible;
ImageFilter? filter;
DialogBarrier({
this.dismissible = true,
this.color = Colors.transparent,
this.label = '',
this.filter,
});
}
class StyledDialogRoute<T> extends PopupRoute<T> {
final RoutePageBuilder _pageBuilder;
final DialogBarrier barrier;
StyledDialogRoute({
required RoutePageBuilder pageBuilder,
required this.barrier,
Duration transitionDuration = const Duration(milliseconds: 300),
RouteTransitionsBuilder? transitionBuilder,
super.settings,
}) : _pageBuilder = pageBuilder,
_transitionDuration = transitionDuration,
_transitionBuilder = transitionBuilder,
super(filter: barrier.filter);
@override
bool get barrierDismissible {
return barrier.dismissible;
}
@override
String get barrierLabel => barrier.label;
@override
Color get barrierColor => barrier.color;
@override
Duration get transitionDuration => _transitionDuration;
final Duration _transitionDuration;
final RouteTransitionsBuilder? _transitionBuilder;
@override
Widget buildPage(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
return Semantics(
scopesRoute: true,
explicitChildNodes: true,
child: _pageBuilder(context, animation, secondaryAnimation),
);
}
@override
Widget buildTransitions(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation, Widget child) {
if (_transitionBuilder == null) {
return FadeTransition(
opacity: CurvedAnimation(parent: animation, curve: Curves.easeInOut),
child: child);
} else {
return _transitionBuilder!(context, animation, secondaryAnimation, child);
} // Some default transition
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/widget/dialog/dialog_size.dart
|
class DialogSize {
static double get minDialogWidth => 400;
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/extension.dart
|
import 'package:flutter/material.dart';
export 'package:styled_widget/styled_widget.dart';
class TopBorder extends StatelessWidget {
const TopBorder({
super.key,
this.width = 1.0,
this.color = Colors.grey,
required this.child,
});
final Widget child;
final double width;
final Color color;
@override
Widget build(BuildContext context) {
return DecoratedBox(
decoration: BoxDecoration(
border: Border(
top: BorderSide(width: width, color: color),
),
),
child: child,
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/text.dart
|
import 'dart:io';
import 'package:flutter/material.dart';
class FlowyText extends StatelessWidget {
final String text;
final TextOverflow? overflow;
final double? fontSize;
final FontWeight? fontWeight;
final TextAlign? textAlign;
final int? maxLines;
final Color? color;
final TextDecoration? decoration;
final bool selectable;
final String? fontFamily;
final List<String>? fallbackFontFamily;
final double? lineHeight;
final bool withTooltip;
const FlowyText(
this.text, {
super.key,
this.overflow = TextOverflow.clip,
this.fontSize,
this.fontWeight,
this.textAlign,
this.color,
this.maxLines = 1,
this.decoration,
this.selectable = false,
this.fontFamily,
this.fallbackFontFamily,
this.lineHeight,
this.withTooltip = false,
});
FlowyText.small(
this.text, {
super.key,
this.overflow,
this.color,
this.textAlign,
this.maxLines = 1,
this.decoration,
this.selectable = false,
this.fontFamily,
this.fallbackFontFamily,
this.lineHeight,
this.withTooltip = false,
}) : fontWeight = FontWeight.w400,
fontSize = (Platform.isIOS || Platform.isAndroid) ? 14 : 12;
const FlowyText.regular(
this.text, {
super.key,
this.fontSize,
this.overflow,
this.color,
this.textAlign,
this.maxLines = 1,
this.decoration,
this.selectable = false,
this.fontFamily,
this.fallbackFontFamily,
this.lineHeight,
this.withTooltip = false,
}) : fontWeight = FontWeight.w400;
const FlowyText.medium(
this.text, {
super.key,
this.fontSize,
this.overflow,
this.color,
this.textAlign,
this.maxLines = 1,
this.decoration,
this.selectable = false,
this.fontFamily,
this.fallbackFontFamily,
this.lineHeight,
this.withTooltip = false,
}) : fontWeight = FontWeight.w500;
const FlowyText.semibold(
this.text, {
super.key,
this.fontSize,
this.overflow,
this.color,
this.textAlign,
this.maxLines = 1,
this.decoration,
this.selectable = false,
this.fontFamily,
this.fallbackFontFamily,
this.lineHeight,
this.withTooltip = false,
}) : fontWeight = FontWeight.w600;
// Some emojis are not supported on Linux and Android, fallback to noto color emoji
const FlowyText.emoji(
this.text, {
super.key,
this.fontSize,
this.overflow,
this.color,
this.textAlign,
this.maxLines = 1,
this.decoration,
this.selectable = false,
this.lineHeight,
this.withTooltip = false,
}) : fontWeight = FontWeight.w400,
fontFamily = 'noto color emoji',
fallbackFontFamily = null;
@override
Widget build(BuildContext context) {
Widget child;
if (selectable) {
child = SelectableText(
text,
maxLines: maxLines,
textAlign: textAlign,
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
fontSize: fontSize,
fontWeight: fontWeight,
color: color,
decoration: decoration,
fontFamily: fontFamily,
fontFamilyFallback: fallbackFontFamily,
height: lineHeight,
),
);
} else {
child = Text(
text,
maxLines: maxLines,
textAlign: textAlign,
overflow: overflow ?? TextOverflow.clip,
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
fontSize: fontSize,
fontWeight: fontWeight,
color: color,
decoration: decoration,
fontFamily: fontFamily,
fontFamilyFallback: fallbackFontFamily,
height: lineHeight,
),
);
}
if (withTooltip) {
child = Tooltip(
message: text,
child: child,
);
}
return child;
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/icon_button.dart
|
import 'dart:io';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';
import 'package:flowy_svg/flowy_svg.dart';
import 'package:flutter/material.dart';
class FlowyIconButton extends StatelessWidget {
final double width;
final double? height;
final Widget icon;
final VoidCallback? onPressed;
final Color? fillColor;
final Color? hoverColor;
final Color? iconColorOnHover;
final EdgeInsets iconPadding;
final BorderRadius? radius;
final String? tooltipText;
final InlineSpan? richTooltipText;
final bool preferBelow;
final BoxDecoration? decoration;
final bool? isSelected;
const FlowyIconButton({
super.key,
this.width = 30,
this.height,
this.onPressed,
this.fillColor = Colors.transparent,
this.hoverColor,
this.iconColorOnHover,
this.iconPadding = EdgeInsets.zero,
this.radius,
this.decoration,
this.tooltipText,
this.richTooltipText,
this.preferBelow = true,
this.isSelected,
required this.icon,
}) : assert((richTooltipText != null && tooltipText == null) ||
(richTooltipText == null && tooltipText != null) ||
(richTooltipText == null && tooltipText == null));
@override
Widget build(BuildContext context) {
Widget child = icon;
final size = Size(width, height ?? width);
final tooltipMessage =
tooltipText == null && richTooltipText == null ? '' : tooltipText;
assert(size.width > iconPadding.horizontal);
assert(size.height > iconPadding.vertical);
child = Padding(
padding: iconPadding,
child: Center(child: child),
);
if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
child = FlowyHover(
isSelected: isSelected != null ? () => isSelected! : null,
style: HoverStyle(
hoverColor: hoverColor,
foregroundColorOnHover:
iconColorOnHover ?? Theme.of(context).iconTheme.color,
//Do not set background here. Use [fillColor] instead.
),
resetHoverOnRebuild: false,
child: child,
);
}
return Container(
constraints: BoxConstraints.tightFor(
width: size.width,
height: size.height,
),
decoration: decoration,
child: FlowyTooltip(
preferBelow: preferBelow,
message: tooltipMessage,
richMessage: richTooltipText,
showDuration: Duration.zero,
child: RawMaterialButton(
visualDensity: VisualDensity.compact,
hoverElevation: 0,
highlightElevation: 0,
shape:
RoundedRectangleBorder(borderRadius: radius ?? Corners.s6Border),
fillColor: fillColor,
hoverColor: Colors.transparent,
focusColor: Colors.transparent,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
elevation: 0,
onPressed: onPressed,
child: child,
),
),
);
}
}
class FlowyDropdownButton extends StatelessWidget {
const FlowyDropdownButton({super.key, this.onPressed});
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
return FlowyIconButton(
width: 16,
onPressed: onPressed,
icon: const FlowySvg(FlowySvgData("home/drop_down_show")),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/decoration.dart
|
import 'package:flutter/material.dart';
class FlowyDecoration {
static Decoration decoration(
Color boxColor,
Color boxShadow, {
double spreadRadius = 0,
double blurRadius = 20,
Offset offset = Offset.zero,
}) {
return BoxDecoration(
color: boxColor,
borderRadius: const BorderRadius.all(Radius.circular(6)),
boxShadow: [
BoxShadow(
color: boxShadow,
spreadRadius: spreadRadius,
blurRadius: blurRadius,
offset: offset,
),
],
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/progress_indicator.dart
|
import 'package:flutter/material.dart';
import 'package:loading_indicator/loading_indicator.dart';
List<Color> _kDefaultRainbowColors = const [
Colors.red,
Colors.orange,
Colors.yellow,
Colors.green,
Colors.blue,
Colors.indigo,
Colors.purple,
];
// CircularProgressIndicator()
class FlowyProgressIndicator extends StatelessWidget {
const FlowyProgressIndicator({super.key});
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: Center(
child: SizedBox(
width: 60,
child: LoadingIndicator(
indicatorType: Indicator.pacman,
colors: _kDefaultRainbowColors,
strokeWidth: 4.0,
),
),
),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/container.dart
|
import 'package:flowy_infra/time/duration.dart';
import 'package:flutter/material.dart';
class FlowyContainer extends StatelessWidget {
final Color color;
final BorderRadiusGeometry? borderRadius;
final List<BoxShadow>? shadows;
final Widget? child;
final double? width;
final double? height;
final Alignment? align;
final EdgeInsets? margin;
final Duration? duration;
final BoxBorder? border;
const FlowyContainer(this.color,
{super.key,
this.borderRadius,
this.shadows,
this.child,
this.width,
this.height,
this.align,
this.margin,
this.duration,
this.border});
@override
Widget build(BuildContext context) {
return AnimatedContainer(
width: width,
height: height,
margin: margin,
alignment: align,
duration: duration ?? FlowyDurations.medium,
decoration: BoxDecoration(
color: color,
borderRadius: borderRadius,
boxShadow: shadows,
border: border),
child: child);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/close_button.dart
|
import 'package:flutter/material.dart';
class FlowyCloseButton extends StatelessWidget {
final VoidCallback? onPressed;
const FlowyCloseButton({
super.key,
this.onPressed,
});
@override
Widget build(BuildContext context) {
return TextButton(onPressed: onPressed, child: const Icon(Icons.close));
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/button.dart
|
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';
import 'package:flowy_infra_ui/widget/ignore_parent_gesture.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
class FlowyButton extends StatelessWidget {
final Widget text;
final VoidCallback? onTap;
final VoidCallback? onSecondaryTap;
final void Function(bool)? onHover;
final EdgeInsets? margin;
final Widget? leftIcon;
final Widget? rightIcon;
final Color? hoverColor;
final bool isSelected;
final BorderRadius? radius;
final BoxDecoration? decoration;
final bool useIntrinsicWidth;
final bool disable;
final double disableOpacity;
final Size? leftIconSize;
final bool expandText;
final MainAxisAlignment mainAxisAlignment;
final bool showDefaultBoxDecorationOnMobile;
final double iconPadding;
final bool expand;
const FlowyButton({
super.key,
required this.text,
this.onTap,
this.onSecondaryTap,
this.onHover,
this.margin,
this.leftIcon,
this.rightIcon,
this.hoverColor,
this.isSelected = false,
this.radius,
this.decoration,
this.useIntrinsicWidth = false,
this.disable = false,
this.disableOpacity = 0.5,
this.leftIconSize = const Size.square(16),
this.expandText = true,
this.mainAxisAlignment = MainAxisAlignment.center,
this.showDefaultBoxDecorationOnMobile = false,
this.iconPadding = 6,
this.expand = false,
});
@override
Widget build(BuildContext context) {
final color = hoverColor ?? Theme.of(context).colorScheme.secondary;
final alpha = (255 * disableOpacity).toInt();
color.withAlpha(alpha);
if (Platform.isIOS || Platform.isAndroid) {
return InkWell(
onTap: disable ? null : onTap,
onSecondaryTap: disable ? null : onSecondaryTap,
borderRadius: radius ?? Corners.s6Border,
child: _render(context),
);
}
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: disable ? null : onTap,
onSecondaryTap: disable ? null : onSecondaryTap,
child: FlowyHover(
cursor:
disable ? SystemMouseCursors.forbidden : SystemMouseCursors.click,
style: HoverStyle(
borderRadius: radius ?? Corners.s6Border,
hoverColor: color,
),
onHover: disable ? null : onHover,
isSelected: () => isSelected,
builder: (context, onHover) => _render(context),
),
);
}
Widget _render(BuildContext context) {
final List<Widget> children = [];
if (leftIcon != null) {
children.add(
SizedBox.fromSize(
size: leftIconSize,
child: leftIcon!,
),
);
children.add(HSpace(iconPadding));
}
if (expandText) {
children.add(Expanded(child: text));
} else {
children.add(text);
}
if (rightIcon != null) {
children.add(const HSpace(6));
// No need to define the size of rightIcon. Just use its intrinsic width
children.add(rightIcon!);
}
Widget child = Row(
mainAxisAlignment: mainAxisAlignment,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: expand ? MainAxisSize.max : MainAxisSize.min,
children: children,
);
if (useIntrinsicWidth) {
child = IntrinsicWidth(child: child);
}
final decoration = this.decoration ??
(showDefaultBoxDecorationOnMobile &&
(Platform.isIOS || Platform.isAndroid)
? BoxDecoration(
border: Border.all(
color: Theme.of(context).colorScheme.surfaceVariant,
width: 1.0,
))
: null);
return Container(
decoration: decoration,
child: Padding(
padding:
margin ?? const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
child: child,
),
);
}
}
class FlowyTextButton extends StatelessWidget {
final String text;
final FontWeight? fontWeight;
final Color? fontColor;
final double? fontSize;
final TextOverflow overflow;
final VoidCallback? onPressed;
final EdgeInsets padding;
final Widget? heading;
final Color? hoverColor;
final Color? fillColor;
final BorderRadius? radius;
final MainAxisAlignment mainAxisAlignment;
final String? tooltip;
final BoxConstraints constraints;
final TextDecoration? decoration;
final String? fontFamily;
// final HoverDisplayConfig? hoverDisplay;
const FlowyTextButton(
this.text, {
super.key,
this.onPressed,
this.fontSize,
this.fontColor,
this.overflow = TextOverflow.ellipsis,
this.fontWeight,
this.padding = const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
this.hoverColor,
this.fillColor,
this.heading,
this.radius,
this.mainAxisAlignment = MainAxisAlignment.start,
this.tooltip,
this.constraints = const BoxConstraints(minWidth: 0.0, minHeight: 0.0),
this.decoration,
this.fontFamily,
});
@override
Widget build(BuildContext context) {
List<Widget> children = [];
if (heading != null) {
children.add(heading!);
children.add(const HSpace(8));
}
children.add(
FlowyText(
text,
overflow: overflow,
fontWeight: fontWeight,
fontSize: fontSize,
color: fontColor,
textAlign: TextAlign.center,
decoration: decoration,
fontFamily: fontFamily,
),
);
Widget child = Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: mainAxisAlignment,
children: children,
);
child = RawMaterialButton(
focusNode: FocusNode(skipTraversal: onPressed == null),
hoverElevation: 0,
highlightElevation: 0,
shape: RoundedRectangleBorder(borderRadius: radius ?? Corners.s6Border),
fillColor: fillColor ?? Theme.of(context).colorScheme.secondaryContainer,
hoverColor:
hoverColor ?? Theme.of(context).colorScheme.secondaryContainer,
focusColor: Colors.transparent,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
elevation: 0,
constraints: constraints,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
padding: padding,
onPressed: onPressed,
child: child,
);
if (tooltip != null) {
child = FlowyTooltip(
message: tooltip!,
child: child,
);
}
if (onPressed == null) {
child = ExcludeFocus(child: child);
}
return child;
}
}
class FlowyRichTextButton extends StatelessWidget {
final InlineSpan text;
final TextOverflow overflow;
final VoidCallback? onPressed;
final EdgeInsets padding;
final Widget? heading;
final Color? hoverColor;
final Color? fillColor;
final BorderRadius? radius;
final MainAxisAlignment mainAxisAlignment;
final String? tooltip;
final BoxConstraints constraints;
final TextDecoration? decoration;
// final HoverDisplayConfig? hoverDisplay;
const FlowyRichTextButton(
this.text, {
super.key,
this.onPressed,
this.overflow = TextOverflow.ellipsis,
this.padding = const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
this.hoverColor,
this.fillColor,
this.heading,
this.radius,
this.mainAxisAlignment = MainAxisAlignment.start,
this.tooltip,
this.constraints = const BoxConstraints(minWidth: 58.0, minHeight: 30.0),
this.decoration,
});
@override
Widget build(BuildContext context) {
List<Widget> children = [];
if (heading != null) {
children.add(heading!);
children.add(const HSpace(6));
}
children.add(
RichText(
text: text,
overflow: overflow,
textAlign: TextAlign.center,
),
);
Widget child = Padding(
padding: padding,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: mainAxisAlignment,
children: children,
),
);
child = RawMaterialButton(
visualDensity: VisualDensity.compact,
hoverElevation: 0,
highlightElevation: 0,
shape: RoundedRectangleBorder(borderRadius: radius ?? Corners.s6Border),
fillColor: fillColor ?? Theme.of(context).colorScheme.secondaryContainer,
hoverColor: hoverColor ?? Theme.of(context).colorScheme.secondary,
focusColor: Colors.transparent,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
elevation: 0,
constraints: constraints,
onPressed: () {},
child: child,
);
child = IgnoreParentGestureWidget(
onPress: onPressed,
child: child,
);
if (tooltip != null) {
child = FlowyTooltip(
message: tooltip!,
child: child,
);
}
return child;
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/hover.dart
|
import 'package:flutter/material.dart';
typedef HoverBuilder = Widget Function(BuildContext context, bool onHover);
class FlowyHover extends StatefulWidget {
final HoverStyle? style;
final HoverBuilder? builder;
final Widget? child;
final bool Function()? isSelected;
final void Function(bool)? onHover;
final MouseCursor? cursor;
/// Reset the hover state when the parent widget get rebuild.
/// Default to true.
final bool resetHoverOnRebuild;
/// Determined whether the [builder] should get called when onEnter/onExit
/// happened
///
/// [FlowyHover] show hover when [MouseRegion]'s onEnter get called
/// [FlowyHover] hide hover when [MouseRegion]'s onExit get called
///
final bool Function()? buildWhenOnHover;
const FlowyHover({
super.key,
this.builder,
this.child,
this.style,
this.isSelected,
this.onHover,
this.cursor,
this.resetHoverOnRebuild = true,
this.buildWhenOnHover,
});
@override
State<FlowyHover> createState() => _FlowyHoverState();
}
class _FlowyHoverState extends State<FlowyHover> {
bool _onHover = false;
@override
void didUpdateWidget(covariant FlowyHover oldWidget) {
if (widget.resetHoverOnRebuild) {
// Reset the _onHover to false when the parent widget get rebuild.
_onHover = false;
}
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
return MouseRegion(
cursor: widget.cursor != null ? widget.cursor! : SystemMouseCursors.click,
opaque: false,
onHover: (p) {
if (_onHover) return;
_setOnHover(true);
},
onEnter: (p) {
if (_onHover) return;
_setOnHover(true);
},
onExit: (p) {
if (!_onHover) return;
_setOnHover(false);
},
child: renderWidget(),
);
}
void _setOnHover(bool isHovering) {
if (widget.buildWhenOnHover?.call() ?? true) {
setState(() => _onHover = isHovering);
if (widget.onHover != null) {
widget.onHover!(isHovering);
}
}
}
Widget renderWidget() {
bool showHover = _onHover;
if (!showHover && widget.isSelected != null) {
showHover = widget.isSelected!();
}
final child = widget.child ?? widget.builder!(context, _onHover);
final style = widget.style ??
HoverStyle(hoverColor: Theme.of(context).colorScheme.secondary);
if (showHover) {
return FlowyHoverContainer(
style: style,
child: child,
);
} else {
return Container(color: style.backgroundColor, child: child);
}
}
}
class HoverStyle {
final Color borderColor;
final double borderWidth;
final Color? hoverColor;
final Color? foregroundColorOnHover;
final BorderRadius borderRadius;
final EdgeInsets contentMargin;
final Color backgroundColor;
const HoverStyle({
this.borderColor = Colors.transparent,
this.borderWidth = 0,
this.borderRadius = const BorderRadius.all(Radius.circular(6)),
this.contentMargin = EdgeInsets.zero,
this.backgroundColor = Colors.transparent,
this.hoverColor,
this.foregroundColorOnHover,
});
const HoverStyle.transparent({
this.borderColor = Colors.transparent,
this.borderWidth = 0,
this.borderRadius = const BorderRadius.all(Radius.circular(6)),
this.contentMargin = EdgeInsets.zero,
this.backgroundColor = Colors.transparent,
this.foregroundColorOnHover,
}) : hoverColor = Colors.transparent;
}
class FlowyHoverContainer extends StatelessWidget {
final HoverStyle style;
final Widget child;
const FlowyHoverContainer({
super.key,
required this.child,
required this.style,
});
@override
Widget build(BuildContext context) {
final hoverBorder = Border.all(
color: style.borderColor,
width: style.borderWidth,
);
final theme = Theme.of(context);
final textTheme = theme.textTheme;
final iconTheme = theme.iconTheme;
// override text's theme with foregroundColorOnHover when it is hovered
final hoverTheme = theme.copyWith(
textTheme: textTheme.copyWith(
bodyMedium: textTheme.bodyMedium?.copyWith(
color: style.foregroundColorOnHover ?? theme.colorScheme.onSurface,
),
),
iconTheme: iconTheme.copyWith(
color: style.foregroundColorOnHover ?? theme.colorScheme.onSurface,
),
);
return Container(
margin: style.contentMargin,
decoration: BoxDecoration(
border: hoverBorder,
color: style.hoverColor ?? Theme.of(context).colorScheme.secondary,
borderRadius: style.borderRadius,
),
child: Theme(
data: hoverTheme,
child: child,
),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/color_picker.dart
|
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_svg/flowy_svg.dart';
import 'package:flutter/material.dart';
class FlowyColorOption {
const FlowyColorOption({
required this.color,
required this.i18n,
required this.id,
});
final Color color;
final String i18n;
final String id;
}
class FlowyColorPicker extends StatelessWidget {
final List<FlowyColorOption> colors;
final Color? selected;
final Function(FlowyColorOption option, int index)? onTap;
final double separatorSize;
final double iconSize;
final double itemHeight;
final Border? border;
const FlowyColorPicker({
super.key,
required this.colors,
this.selected,
this.onTap,
this.separatorSize = 4,
this.iconSize = 16,
this.itemHeight = 32,
this.border,
});
@override
Widget build(BuildContext context) {
return ListView.separated(
shrinkWrap: true,
separatorBuilder: (context, index) {
return VSpace(separatorSize);
},
itemCount: colors.length,
physics: StyledScrollPhysics(),
itemBuilder: (BuildContext context, int index) {
return _buildColorOption(colors[index], index);
},
);
}
Widget _buildColorOption(
FlowyColorOption option,
int i,
) {
Widget? checkmark;
if (selected == option.color) {
checkmark = const FlowySvg(FlowySvgData("grid/checkmark"));
}
final colorIcon = SizedBox.square(
dimension: iconSize,
child: DecoratedBox(
decoration: BoxDecoration(
color: option.color,
shape: BoxShape.circle,
),
),
);
return SizedBox(
height: itemHeight,
child: FlowyButton(
text: FlowyText.medium(option.i18n),
leftIcon: colorIcon,
rightIcon: checkmark,
onTap: () {
onTap?.call(option, i);
},
),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/text_field.dart
|
import 'dart:async';
import 'package:flowy_infra/size.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class FlowyTextField extends StatefulWidget {
final String? hintText;
final String? text;
final TextStyle? textStyle;
final void Function(String)? onChanged;
final void Function()? onEditingComplete;
final void Function(String)? onSubmitted;
final void Function()? onCanceled;
final FocusNode? focusNode;
final bool autoFocus;
final int? maxLength;
final TextEditingController? controller;
final bool autoClearWhenDone;
final bool submitOnLeave;
final Duration? debounceDuration;
final String? errorText;
final Widget? error;
final int? maxLines;
final bool showCounter;
final Widget? prefixIcon;
final Widget? suffixIcon;
final BoxConstraints? prefixIconConstraints;
final BoxConstraints? suffixIconConstraints;
final BoxConstraints? hintTextConstraints;
final TextStyle? hintStyle;
final InputDecoration? decoration;
final TextAlignVertical? textAlignVertical;
final TextInputAction? textInputAction;
final TextInputType? keyboardType;
final List<TextInputFormatter>? inputFormatters;
const FlowyTextField({
super.key,
this.hintText = "",
this.text,
this.textStyle,
this.onChanged,
this.onEditingComplete,
this.onSubmitted,
this.onCanceled,
this.focusNode,
this.autoFocus = true,
this.maxLength,
this.controller,
this.autoClearWhenDone = false,
this.submitOnLeave = false,
this.debounceDuration,
this.errorText,
this.error,
this.maxLines = 1,
this.showCounter = true,
this.prefixIcon,
this.suffixIcon,
this.prefixIconConstraints,
this.suffixIconConstraints,
this.hintTextConstraints,
this.hintStyle,
this.decoration,
this.textAlignVertical,
this.textInputAction,
this.keyboardType = TextInputType.multiline,
this.inputFormatters,
});
@override
State<FlowyTextField> createState() => FlowyTextFieldState();
}
class FlowyTextFieldState extends State<FlowyTextField> {
late FocusNode focusNode;
late TextEditingController controller;
Timer? _debounceOnChanged;
@override
void initState() {
super.initState();
focusNode = widget.focusNode ?? FocusNode();
focusNode.addListener(notifyDidEndEditing);
controller = widget.controller ?? TextEditingController();
if (widget.text != null) {
controller.text = widget.text!;
}
if (widget.autoFocus) {
WidgetsBinding.instance.addPostFrameCallback((_) {
focusNode.requestFocus();
if (widget.controller == null) {
controller.selection = TextSelection.fromPosition(
TextPosition(offset: controller.text.length),
);
}
});
}
}
@override
void dispose() {
focusNode.removeListener(notifyDidEndEditing);
if (widget.focusNode == null) {
focusNode.dispose();
}
if (widget.controller == null) {
controller.dispose();
}
_debounceOnChanged?.cancel();
super.dispose();
}
void _debounceOnChangedText(Duration duration, String text) {
_debounceOnChanged?.cancel();
_debounceOnChanged = Timer(duration, () async {
if (mounted) {
_onChanged(text);
}
});
}
void _onChanged(String text) {
widget.onChanged?.call(text);
setState(() {});
}
void _onSubmitted(String text) {
widget.onSubmitted?.call(text);
if (widget.autoClearWhenDone) {
// using `controller.clear()` instead of `controller.text = ''` which will crash on Windows.
controller.clear();
}
}
@override
Widget build(BuildContext context) {
return TextField(
controller: controller,
focusNode: focusNode,
onChanged: (text) {
if (widget.debounceDuration != null) {
_debounceOnChangedText(widget.debounceDuration!, text);
} else {
_onChanged(text);
}
},
onSubmitted: (text) => _onSubmitted(text),
onEditingComplete: widget.onEditingComplete,
minLines: 1,
maxLines: widget.maxLines,
maxLength: widget.maxLength,
maxLengthEnforcement: MaxLengthEnforcement.truncateAfterCompositionEnds,
style: widget.textStyle ?? Theme.of(context).textTheme.bodySmall,
textAlignVertical: widget.textAlignVertical ?? TextAlignVertical.center,
keyboardType: widget.keyboardType,
inputFormatters: widget.inputFormatters,
decoration: widget.decoration ??
InputDecoration(
constraints: widget.hintTextConstraints ??
BoxConstraints(
maxHeight: widget.errorText?.isEmpty ?? true ? 32 : 58,
),
contentPadding: EdgeInsets.symmetric(
horizontal: 12,
vertical:
(widget.maxLines == null || widget.maxLines! > 1) ? 12 : 0,
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.outline,
width: 1.0,
),
borderRadius: Corners.s8Border,
),
isDense: false,
hintText: widget.hintText,
errorText: widget.errorText,
error: widget.error,
errorStyle: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(color: Theme.of(context).colorScheme.error),
hintStyle: widget.hintStyle ??
Theme.of(context)
.textTheme
.bodySmall!
.copyWith(color: Theme.of(context).hintColor),
suffixText: widget.showCounter ? _suffixText() : "",
counterText: "",
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.primary,
width: 1.0,
),
borderRadius: Corners.s8Border,
),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.error,
width: 1.0,
),
borderRadius: Corners.s8Border,
),
focusedErrorBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).colorScheme.error,
width: 1.0,
),
borderRadius: Corners.s8Border,
),
prefixIcon: widget.prefixIcon,
suffixIcon: widget.suffixIcon,
prefixIconConstraints: widget.prefixIconConstraints,
suffixIconConstraints: widget.suffixIconConstraints,
),
);
}
void notifyDidEndEditing() {
if (!focusNode.hasFocus) {
if (controller.text.isNotEmpty && widget.submitOnLeave) {
widget.onSubmitted?.call(controller.text);
} else {
widget.onCanceled?.call();
}
}
}
String? _suffixText() {
if (widget.maxLength != null) {
return ' ${controller.text.length}/${widget.maxLength}';
}
return null;
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/snap_bar.dart
|
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flutter/material.dart';
void showSnapBar(BuildContext context, String title, {VoidCallback? onClosed}) {
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context)
.showSnackBar(
SnackBar(
duration: const Duration(milliseconds: 8000),
content: PopScope(
canPop: () {
ScaffoldMessenger.of(context).removeCurrentSnackBar();
return true;
}(),
child: FlowyText.medium(
title,
fontSize: 12,
maxLines: 3,
),
),
backgroundColor: Theme.of(context).colorScheme.background,
),
)
.closed
.then((value) => onClosed?.call());
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/image_icon.dart
|
import 'package:flowy_infra/size.dart';
import 'package:flutter/material.dart';
class FlowyImageIcon extends StatelessWidget {
final AssetImage image;
final Color? color;
final double? size;
const FlowyImageIcon(this.image, {super.key, this.color, this.size});
@override
Widget build(BuildContext context) {
return ImageIcon(image,
size: size ?? Sizes.iconMed, color: color ?? Colors.white);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/bar_title.dart
|
import 'package:flutter/material.dart';
class FlowyBarTitle extends StatelessWidget {
final String title;
const FlowyBarTitle({
super.key,
required this.title,
});
@override
Widget build(BuildContext context) {
return Text(
title,
style: const TextStyle(fontSize: 24),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/text_input.dart
|
import 'dart:async';
import 'dart:math' as math;
import 'package:flowy_infra/size.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class FlowyFormTextInput extends StatelessWidget {
static EdgeInsets kDefaultTextInputPadding =
EdgeInsets.only(bottom: Insets.sm, top: 4);
final String? label;
final bool? autoFocus;
final String? initialValue;
final String? hintText;
final EdgeInsets? contentPadding;
final TextStyle? textStyle;
final TextAlign textAlign;
final int? maxLines;
final int? maxLength;
final bool showCounter;
final TextEditingController? controller;
final TextCapitalization? capitalization;
final Function(String)? onChanged;
final Function()? onEditingComplete;
final Function(bool)? onFocusChanged;
final Function(FocusNode)? onFocusCreated;
const FlowyFormTextInput({
super.key,
this.label,
this.autoFocus,
this.initialValue,
this.onChanged,
this.onEditingComplete,
this.hintText,
this.onFocusChanged,
this.onFocusCreated,
this.controller,
this.contentPadding,
this.capitalization,
this.textStyle,
this.textAlign = TextAlign.center,
this.maxLines,
this.maxLength,
this.showCounter = true,
});
@override
Widget build(BuildContext context) {
return StyledSearchTextInput(
capitalization: capitalization,
label: label,
autoFocus: autoFocus,
initialValue: initialValue,
onChanged: onChanged,
onFocusCreated: onFocusCreated,
style: textStyle ?? Theme.of(context).textTheme.bodyMedium,
textAlign: textAlign,
onEditingComplete: onEditingComplete,
onFocusChanged: onFocusChanged,
controller: controller,
maxLines: maxLines,
maxLength: maxLength,
showCounter: showCounter,
contentPadding: contentPadding ?? kDefaultTextInputPadding,
hintText: hintText,
hintStyle: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: Theme.of(context).hintColor.withOpacity(0.7)),
isDense: true,
inputBorder: const ThinUnderlineBorder(
borderSide: BorderSide(width: 5, color: Colors.red),
),
);
}
}
class StyledSearchTextInput extends StatefulWidget {
final String? label;
final TextStyle? style;
final TextAlign textAlign;
final EdgeInsets? contentPadding;
final bool? autoFocus;
final bool? obscureText;
final IconData? icon;
final String? initialValue;
final int? maxLines;
final int? maxLength;
final bool showCounter;
final TextEditingController? controller;
final TextCapitalization? capitalization;
final TextInputType? type;
final bool? enabled;
final bool? autoValidate;
final bool? enableSuggestions;
final bool? autoCorrect;
final bool isDense;
final String? errorText;
final String? hintText;
final TextStyle? hintStyle;
final Widget? prefixIcon;
final Widget? suffixIcon;
final InputDecoration? inputDecoration;
final InputBorder? inputBorder;
final Function(String)? onChanged;
final Function()? onEditingComplete;
final Function()? onEditingCancel;
final Function(bool)? onFocusChanged;
final Function(FocusNode)? onFocusCreated;
final Function(String)? onFieldSubmitted;
final Function(String?)? onSaved;
final VoidCallback? onTap;
const StyledSearchTextInput({
super.key,
this.label,
this.autoFocus = false,
this.obscureText = false,
this.type = TextInputType.text,
this.textAlign = TextAlign.center,
this.icon,
this.initialValue = '',
this.controller,
this.enabled,
this.autoValidate = false,
this.enableSuggestions = true,
this.autoCorrect = true,
this.isDense = false,
this.errorText,
this.style,
this.contentPadding,
this.prefixIcon,
this.suffixIcon,
this.inputDecoration,
this.onChanged,
this.onEditingComplete,
this.onEditingCancel,
this.onFocusChanged,
this.onFocusCreated,
this.onFieldSubmitted,
this.onSaved,
this.onTap,
this.hintText,
this.hintStyle,
this.capitalization,
this.maxLines,
this.maxLength,
this.showCounter = false,
this.inputBorder,
});
@override
StyledSearchTextInputState createState() => StyledSearchTextInputState();
}
class StyledSearchTextInputState extends State<StyledSearchTextInput> {
late TextEditingController _controller;
late FocusNode _focusNode;
@override
void initState() {
_controller =
widget.controller ?? TextEditingController(text: widget.initialValue);
_focusNode = FocusNode(
debugLabel: widget.label ?? '',
onKeyEvent: (node, event) {
if (event.logicalKey == LogicalKeyboardKey.escape) {
widget.onEditingCancel?.call();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
canRequestFocus: true,
);
// Listen for focus out events
_focusNode
.addListener(() => widget.onFocusChanged?.call(_focusNode.hasFocus));
widget.onFocusCreated?.call(_focusNode);
if (widget.autoFocus ?? false) {
scheduleMicrotask(() => _focusNode.requestFocus());
}
super.initState();
}
@override
void dispose() {
if (widget.controller == null) {
_controller.dispose();
}
_focusNode.dispose();
super.dispose();
}
void clear() => _controller.clear();
String get text => _controller.text;
set text(String value) => _controller.text = value;
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(vertical: Insets.sm),
child: TextFormField(
onChanged: widget.onChanged,
onEditingComplete: widget.onEditingComplete,
onFieldSubmitted: widget.onFieldSubmitted,
onSaved: widget.onSaved,
onTap: widget.onTap,
autofocus: widget.autoFocus ?? false,
focusNode: _focusNode,
keyboardType: widget.type,
obscureText: widget.obscureText ?? false,
autocorrect: widget.autoCorrect ?? false,
enableSuggestions: widget.enableSuggestions ?? false,
style: widget.style ?? Theme.of(context).textTheme.bodyMedium,
cursorColor: Theme.of(context).colorScheme.primary,
controller: _controller,
showCursor: true,
enabled: widget.enabled,
maxLines: widget.maxLines,
maxLength: widget.maxLength,
textCapitalization: widget.capitalization ?? TextCapitalization.none,
textAlign: widget.textAlign,
decoration: widget.inputDecoration ??
InputDecoration(
prefixIcon: widget.prefixIcon,
suffixIcon: widget.suffixIcon,
counterText: "",
suffixText: widget.showCounter ? _suffixText() : "",
contentPadding: widget.contentPadding ?? EdgeInsets.all(Insets.m),
border: widget.inputBorder ??
const OutlineInputBorder(borderSide: BorderSide.none),
isDense: widget.isDense,
icon: widget.icon == null ? null : Icon(widget.icon),
errorText: widget.errorText,
errorMaxLines: 2,
hintText: widget.hintText,
hintStyle: widget.hintStyle ??
Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: Theme.of(context).hintColor),
labelText: widget.label,
),
),
);
}
String? _suffixText() {
if (widget.controller != null && widget.maxLength != null) {
return ' ${widget.controller!.text.length}/${widget.maxLength}';
}
return null;
}
}
class ThinUnderlineBorder extends InputBorder {
/// Creates an underline border for an [InputDecorator].
///
/// The [borderSide] parameter defaults to [BorderSide.none] (it must not be
/// null). Applications typically do not specify a [borderSide] parameter
/// because the input decorator substitutes its own, using [copyWith], based
/// on the current theme and [InputDecorator.isFocused].
///
/// The [borderRadius] parameter defaults to a value where the top left
/// and right corners have a circular radius of 4.0. The [borderRadius]
/// parameter must not be null.
const ThinUnderlineBorder({
super.borderSide = const BorderSide(),
this.borderRadius = const BorderRadius.only(
topLeft: Radius.circular(4.0),
topRight: Radius.circular(4.0),
),
});
/// The radii of the border's rounded rectangle corners.
///
/// When this border is used with a filled input decorator, see
/// [InputDecoration.filled], the border radius defines the shape
/// of the background fill as well as the bottom left and right
/// edges of the underline itself.
///
/// By default the top right and top left corners have a circular radius
/// of 4.0.
final BorderRadius borderRadius;
@override
bool get isOutline => false;
@override
UnderlineInputBorder copyWith(
{BorderSide? borderSide, BorderRadius? borderRadius}) {
return UnderlineInputBorder(
borderSide: borderSide ?? this.borderSide,
borderRadius: borderRadius ?? this.borderRadius,
);
}
@override
EdgeInsetsGeometry get dimensions {
return EdgeInsets.only(bottom: borderSide.width);
}
@override
UnderlineInputBorder scale(double t) {
return UnderlineInputBorder(borderSide: borderSide.scale(t));
}
@override
Path getInnerPath(Rect rect, {TextDirection? textDirection}) {
return Path()
..addRect(Rect.fromLTWH(rect.left, rect.top, rect.width,
math.max(0.0, rect.height - borderSide.width)));
}
@override
Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
return Path()..addRRect(borderRadius.resolve(textDirection).toRRect(rect));
}
@override
ShapeBorder? lerpFrom(ShapeBorder? a, double t) {
if (a is UnderlineInputBorder) {
final newBorderRadius =
BorderRadius.lerp(a.borderRadius, borderRadius, t);
if (newBorderRadius != null) {
return UnderlineInputBorder(
borderSide: BorderSide.lerp(a.borderSide, borderSide, t),
borderRadius: newBorderRadius,
);
}
}
return super.lerpFrom(a, t);
}
@override
ShapeBorder? lerpTo(ShapeBorder? b, double t) {
if (b is UnderlineInputBorder) {
final newBorderRadius =
BorderRadius.lerp(b.borderRadius, borderRadius, t);
if (newBorderRadius != null) {
return UnderlineInputBorder(
borderSide: BorderSide.lerp(borderSide, b.borderSide, t),
borderRadius: newBorderRadius,
);
}
}
return super.lerpTo(b, t);
}
/// Draw a horizontal line at the bottom of [rect].
///
/// The [borderSide] defines the line's color and weight. The `textDirection`
/// `gap` and `textDirection` parameters are ignored.
/// @override
@override
void paint(
Canvas canvas,
Rect rect, {
double? gapStart,
double gapExtent = 0.0,
double gapPercentage = 0.0,
TextDirection? textDirection,
}) {
if (borderRadius.bottomLeft != Radius.zero ||
borderRadius.bottomRight != Radius.zero) {
canvas.clipPath(getOuterPath(rect, textDirection: textDirection));
}
canvas.drawLine(rect.bottomLeft, rect.bottomRight, borderSide.toPaint());
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
if (other.runtimeType != runtimeType) return false;
return other is InputBorder && other.borderSide == borderSide;
}
@override
int get hashCode => borderSide.hashCode;
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/scrolling/styled_scrollview.dart
|
import 'package:flutter/material.dart';
import 'styled_list.dart';
import 'styled_scroll_bar.dart';
class StyledSingleChildScrollView extends StatefulWidget {
const StyledSingleChildScrollView({
super.key,
required this.child,
this.contentSize,
this.axis = Axis.vertical,
this.trackColor,
this.handleColor,
this.controller,
this.scrollbarPadding,
this.barSize = 8,
this.autoHideScrollbar = true,
this.includeInsets = true,
});
final Widget? child;
final double? contentSize;
final Axis axis;
final Color? trackColor;
final Color? handleColor;
final ScrollController? controller;
final EdgeInsets? scrollbarPadding;
final double barSize;
final bool autoHideScrollbar;
final bool includeInsets;
@override
State<StyledSingleChildScrollView> createState() =>
StyledSingleChildScrollViewState();
}
class StyledSingleChildScrollViewState
extends State<StyledSingleChildScrollView> {
late final ScrollController scrollController =
widget.controller ?? ScrollController();
@override
void dispose() {
if (widget.controller == null) {
scrollController.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return ScrollbarListStack(
autoHideScrollbar: widget.autoHideScrollbar,
contentSize: widget.contentSize,
axis: widget.axis,
controller: scrollController,
scrollbarPadding: widget.scrollbarPadding,
barSize: widget.barSize,
trackColor: widget.trackColor,
handleColor: widget.handleColor,
includeInsets: widget.includeInsets,
child: SingleChildScrollView(
scrollDirection: widget.axis,
physics: StyledScrollPhysics(),
controller: scrollController,
child: widget.child,
),
);
}
}
class StyledCustomScrollView extends StatefulWidget {
const StyledCustomScrollView({
super.key,
this.axis = Axis.vertical,
this.trackColor,
this.handleColor,
this.verticalController,
this.slivers = const <Widget>[],
this.barSize = 8,
});
final Axis axis;
final Color? trackColor;
final Color? handleColor;
final ScrollController? verticalController;
final List<Widget> slivers;
final double barSize;
@override
StyledCustomScrollViewState createState() => StyledCustomScrollViewState();
}
class StyledCustomScrollViewState extends State<StyledCustomScrollView> {
late final ScrollController controller =
widget.verticalController ?? ScrollController();
@override
Widget build(BuildContext context) {
var child = ScrollConfiguration(
behavior: const ScrollBehavior().copyWith(scrollbars: false),
child: CustomScrollView(
scrollDirection: widget.axis,
physics: StyledScrollPhysics(),
controller: controller,
slivers: widget.slivers,
),
);
return ScrollbarListStack(
axis: widget.axis,
controller: controller,
barSize: widget.barSize,
trackColor: widget.trackColor,
handleColor: widget.handleColor,
child: child,
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/scrolling/styled_list.dart
|
import 'package:flutter/material.dart';
import 'styled_scroll_bar.dart';
class StyledScrollPhysics extends AlwaysScrollableScrollPhysics {}
/// Core ListView for the app.
/// Wraps a [ScrollbarListStack] + [ListView.builder] and assigns the 'Styled' scroll physics for the app
/// Exposes a controller so other widgets can manipulate the list
class StyledListView extends StatefulWidget {
final double? itemExtent;
final int? itemCount;
final Axis axis;
final EdgeInsets? padding;
final EdgeInsets? scrollbarPadding;
final double? barSize;
final IndexedWidgetBuilder itemBuilder;
StyledListView({
super.key,
required this.itemBuilder,
required this.itemCount,
this.itemExtent,
this.axis = Axis.vertical,
this.padding,
this.barSize,
this.scrollbarPadding,
}) {
assert(itemExtent != 0, 'Item extent should never be 0, null is ok.');
}
@override
StyledListViewState createState() => StyledListViewState();
}
/// State is public so this can easily be controlled externally
class StyledListViewState extends State<StyledListView> {
late ScrollController scrollController;
@override
void initState() {
scrollController = ScrollController();
super.initState();
}
@override
void dispose() {
scrollController.dispose();
super.dispose();
}
@override
void didUpdateWidget(StyledListView oldWidget) {
if (oldWidget.itemCount != widget.itemCount ||
oldWidget.itemExtent != widget.itemExtent) {
setState(() {});
}
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
final contentSize = (widget.itemCount ?? 0.0) * (widget.itemExtent ?? 00.0);
Widget listContent = ScrollbarListStack(
contentSize: contentSize,
axis: widget.axis,
controller: scrollController,
barSize: widget.barSize ?? 8,
scrollbarPadding: widget.scrollbarPadding,
child: ListView.builder(
padding: widget.padding,
scrollDirection: widget.axis,
physics: StyledScrollPhysics(),
controller: scrollController,
itemExtent: widget.itemExtent,
itemCount: widget.itemCount,
itemBuilder: (c, i) => widget.itemBuilder(c, i),
),
);
return listContent;
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/lib/style_widget/scrolling/styled_scroll_bar.dart
|
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:async/async.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/widget/mouse_hover_builder.dart';
import 'package:styled_widget/styled_widget.dart';
class StyledScrollbar extends StatefulWidget {
const StyledScrollbar({
super.key,
this.size,
required this.axis,
required this.controller,
this.onDrag,
this.contentSize,
this.showTrack = false,
this.autoHideScrollbar = true,
this.handleColor,
this.trackColor,
});
final double? size;
final Axis axis;
final ScrollController controller;
final Function(double)? onDrag;
final bool showTrack;
final bool autoHideScrollbar;
final Color? handleColor;
final Color? trackColor;
// ignore: todo
// TODO: Remove contentHeight if we can fix this issue
// https://stackoverflow.com/questions/60855712/flutter-how-to-force-scrollcontroller-to-recalculate-position-maxextents
final double? contentSize;
@override
ScrollbarState createState() => ScrollbarState();
}
class ScrollbarState extends State<StyledScrollbar> {
double _viewExtent = 100;
CancelableOperation? _hideScrollbarOperation;
bool hideHandler = false;
@override
void initState() {
super.initState();
widget.controller.addListener(_onScrollChanged);
widget.controller.position.isScrollingNotifier
.addListener(_hideScrollbarInTime);
}
@override
void dispose() {
if (widget.controller.hasClients) {
widget.controller.removeListener(_onScrollChanged);
widget.controller.position.isScrollingNotifier
.removeListener(_hideScrollbarInTime);
}
super.dispose();
}
void _onScrollChanged() => setState(() {});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (_, BoxConstraints constraints) {
double maxExtent;
final double? contentSize = widget.contentSize;
switch (widget.axis) {
case Axis.vertical:
// Use supplied contentSize if we have it, otherwise just fallback to maxScrollExtents
if (contentSize != null && contentSize > 0) {
maxExtent = contentSize - constraints.maxHeight;
} else {
maxExtent = widget.controller.position.maxScrollExtent;
}
_viewExtent = constraints.maxHeight;
break;
case Axis.horizontal:
// Use supplied contentSize if we have it, otherwise just fallback to maxScrollExtents
if (contentSize != null && contentSize > 0) {
maxExtent = contentSize - constraints.maxWidth;
} else {
maxExtent = widget.controller.position.maxScrollExtent;
}
_viewExtent = constraints.maxWidth;
break;
}
final contentExtent = maxExtent + _viewExtent;
// Calculate the alignment for the handle, this is a value between 0 and 1,
// it automatically takes the handle size into acct
// ignore: omit_local_variable_types
double handleAlignment =
maxExtent == 0 ? 0 : widget.controller.offset / maxExtent;
// Convert handle alignment from [0, 1] to [-1, 1]
handleAlignment *= 2.0;
handleAlignment -= 1.0;
// Calculate handleSize by comparing the total content size to our viewport
double handleExtent = _viewExtent;
if (contentExtent > _viewExtent) {
// Make sure handle is never small than the minSize
handleExtent = max(60, _viewExtent * _viewExtent / contentExtent);
}
// Hide the handle if content is < the viewExtent
var showHandle = hideHandler
? false
: contentExtent > _viewExtent && contentExtent > 0;
// Handle color
var handleColor = widget.handleColor ??
(Theme.of(context).brightness == Brightness.dark
? AFThemeExtension.of(context).lightGreyHover
: AFThemeExtension.of(context).greyHover);
// Track color
var trackColor = widget.trackColor ??
(Theme.of(context).brightness == Brightness.dark
? AFThemeExtension.of(context).lightGreyHover
: AFThemeExtension.of(context).greyHover);
// Layout the stack, it just contains a child, and
return Stack(
children: [
/// TRACK, thin strip, aligned along the end of the parent
if (widget.showTrack)
Align(
alignment: const Alignment(1, 1),
child: Container(
color: trackColor,
width: widget.axis == Axis.vertical
? widget.size
: double.infinity,
height: widget.axis == Axis.horizontal
? widget.size
: double.infinity,
),
),
/// HANDLE - Clickable shape that changes scrollController when dragged
Align(
// Use calculated alignment to position handle from -1 to 1, let Alignment do the rest of the work
alignment: Alignment(
widget.axis == Axis.vertical ? 1 : handleAlignment,
widget.axis == Axis.horizontal ? 1 : handleAlignment,
),
child: GestureDetector(
onVerticalDragUpdate: _handleVerticalDrag,
onHorizontalDragUpdate: _handleHorizontalDrag,
// HANDLE SHAPE
child: MouseHoverBuilder(
builder: (_, isHovered) => Container(
width: widget.axis == Axis.vertical
? widget.size
: handleExtent,
height: widget.axis == Axis.horizontal
? widget.size
: handleExtent,
decoration: BoxDecoration(
color: handleColor.withOpacity(isHovered ? 1 : .85),
borderRadius: Corners.s3Border,
),
),
),
),
)
],
).opacity(showHandle ? 1.0 : 0.0, animate: true);
},
);
}
void _hideScrollbarInTime() {
if (!mounted || !widget.autoHideScrollbar) return;
_hideScrollbarOperation?.cancel();
if (!widget.controller.position.isScrollingNotifier.value) {
_hideScrollbarOperation = CancelableOperation.fromFuture(
Future.delayed(const Duration(seconds: 2)),
).then((_) {
hideHandler = true;
if (mounted) {
setState(() {});
}
});
} else {
hideHandler = false;
}
}
void _handleHorizontalDrag(DragUpdateDetails details) {
var pos = widget.controller.offset;
var pxRatio = (widget.controller.position.maxScrollExtent + _viewExtent) /
_viewExtent;
widget.controller.jumpTo((pos + details.delta.dx * pxRatio)
.clamp(0.0, widget.controller.position.maxScrollExtent));
widget.onDrag?.call(details.delta.dx);
}
void _handleVerticalDrag(DragUpdateDetails details) {
var pos = widget.controller.offset;
var pxRatio = (widget.controller.position.maxScrollExtent + _viewExtent) /
_viewExtent;
widget.controller.jumpTo((pos + details.delta.dy * pxRatio)
.clamp(0.0, widget.controller.position.maxScrollExtent));
widget.onDrag?.call(details.delta.dy);
}
}
class ScrollbarListStack extends StatelessWidget {
const ScrollbarListStack({
super.key,
required this.barSize,
required this.axis,
required this.child,
required this.controller,
this.contentSize,
this.scrollbarPadding,
this.handleColor,
this.autoHideScrollbar = true,
this.trackColor,
this.showTrack = false,
this.includeInsets = true,
});
final double barSize;
final Axis axis;
final Widget child;
final ScrollController controller;
final double? contentSize;
final EdgeInsets? scrollbarPadding;
final Color? handleColor;
final Color? trackColor;
final bool showTrack;
final bool autoHideScrollbar;
final bool includeInsets;
@override
Widget build(BuildContext context) {
return Stack(
children: [
/// Wrap with a bit of padding on the right or bottom to make room for the scrollbar
Padding(
padding: !includeInsets
? EdgeInsets.zero
: EdgeInsets.only(
right: axis == Axis.vertical ? barSize + Insets.m : 0,
bottom: axis == Axis.horizontal ? barSize + Insets.m : 0,
),
child: child,
),
/// Display the scrollbar
Padding(
padding: scrollbarPadding ?? EdgeInsets.zero,
child: StyledScrollbar(
size: barSize,
axis: axis,
controller: controller,
contentSize: contentSize,
trackColor: trackColor,
handleColor: handleColor,
autoHideScrollbar: autoHideScrollbar,
showTrack: showTrack,
),
)
// The animate will be used by the children that are using styled_widget.
.animate(const Duration(milliseconds: 250), Curves.easeOut),
],
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/test/flowy_infra_ui_test.dart
|
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
const MethodChannel channel = MethodChannel('flowy_infra_ui');
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall methodCall) async {
return '42';
});
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
channel,
null,
);
});
test('getPlatformVersion', () async {});
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/flowy_infra_ui_web
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/flowy_infra_ui_web/lib/flowy_infra_ui_web.dart
|
library flowy_infra_ui_web;
import 'dart:html' as html show window;
import 'package:flowy_infra_ui_platform_interface/flowy_infra_ui_platform_interface.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
class FlowyInfraUIPlugin extends FlowyInfraUIPlatform {
static void registerWith(Registrar registrar) {
FlowyInfraUIPlatform.instance = FlowyInfraUIPlugin();
}
// MARK: - Keyboard
@override
Stream<bool> get onKeyboardVisibilityChange async* {
// suppose that keyboard won't show in web side
yield false;
}
@override
Future<String?> getPlatformVersion() async {
final version = html.window.navigator.userAgent;
return Future.value(version);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/flowy_infra_ui_web
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/flowy_infra_ui_web/test/flowy_infra_ui_web_test.dart
|
void main() {}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/flowy_infra_ui_platform_interface
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/flowy_infra_ui_platform_interface.dart
|
library flowy_infra_ui_platform_interface;
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'src/method_channel_flowy_infra_ui.dart';
abstract class FlowyInfraUIPlatform extends PlatformInterface {
FlowyInfraUIPlatform() : super(token: _token);
static final Object _token = Object();
static FlowyInfraUIPlatform _instance = MethodChannelFlowyInfraUI();
static FlowyInfraUIPlatform get instance => _instance;
static set instance(FlowyInfraUIPlatform instance) {
PlatformInterface.verifyToken(instance, _token);
_instance = instance;
}
Stream<bool> get onKeyboardVisibilityChange {
throw UnimplementedError(
'`onKeyboardChange` should be overridden by subclass.');
}
Future<String?> getPlatformVersion() {
throw UnimplementedError(
'`getPlatformVersion` should be overridden by subclass.');
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/lib/src/method_channel_flowy_infra_ui.dart
|
import 'package:flowy_infra_ui_platform_interface/flowy_infra_ui_platform_interface.dart';
import 'package:flutter/services.dart';
// ignore_for_file: constant_identifier_names
const INFRA_UI_METHOD_CHANNEL_NAME = 'flowy_infra_ui_method';
const INFRA_UI_KEYBOARD_EVENT_CHANNEL_NAME = 'flowy_infra_ui_event/keyboard';
const INFRA_UI_METHOD_GET_PLATFORM_VERSION = 'getPlatformVersion';
class MethodChannelFlowyInfraUI extends FlowyInfraUIPlatform {
final MethodChannel _methodChannel =
const MethodChannel(INFRA_UI_METHOD_CHANNEL_NAME);
final EventChannel _keyboardChannel =
const EventChannel(INFRA_UI_KEYBOARD_EVENT_CHANNEL_NAME);
late final Stream<bool> _onKeyboardVisibilityChange =
_keyboardChannel.receiveBroadcastStream().map((event) => event as bool);
@override
Stream<bool> get onKeyboardVisibilityChange => _onKeyboardVisibilityChange;
@override
Future<String> getPlatformVersion() async {
String? version = await _methodChannel
.invokeMethod<String>(INFRA_UI_METHOD_GET_PLATFORM_VERSION);
return version ?? 'unknow';
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/flowy_infra_ui_platform_interface
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/flowy_infra_ui_platform_interface/test/flowy_infra_ui_platform_interface_test.dart
|
void main() {}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example/lib/main.dart
|
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/flowy_infra_ui_web.dart';
import 'package:flutter/material.dart';
import 'home/home_screen.dart';
void main() {
runApp(const ExampleApp());
}
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
builder: overlayManagerBuilder,
title: "Flowy Infra Title",
home: HomeScreen(),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example/lib/keyboard/keyboard_screen.dart
|
import 'package:flowy_infra_ui/flowy_infra_ui_web.dart';
import 'package:flutter/material.dart';
import '../home/demo_item.dart';
class KeyboardItem extends DemoItem {
@override
String buildTitle() => 'Keyboard Listener';
@override
void handleTap(BuildContext context) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const KeyboardScreen();
},
),
);
}
}
class KeyboardScreen extends StatefulWidget {
const KeyboardScreen({super.key});
@override
State<KeyboardScreen> createState() => _KeyboardScreenState();
}
class _KeyboardScreenState extends State<KeyboardScreen> {
bool _isKeyboardVisible = false;
final TextEditingController _controller =
TextEditingController(text: 'Hello Flowy');
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Keyboard Visibility Demo'),
),
body: KeyboardVisibilityDetector(
onKeyboardVisibilityChange: (isKeyboardVisible) {
setState(() => _isKeyboardVisible = isKeyboardVisible);
},
child: GestureDetector(
onTap: () => _dismissKeyboard(context),
behavior: HitTestBehavior.translucent,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 36),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 12.0),
child: Text(
'Keyboard Visible: $_isKeyboardVisible',
style: const TextStyle(fontSize: 24.0),
),
),
TextField(
style: const TextStyle(fontSize: 20),
controller: _controller,
),
],
),
),
),
),
),
);
}
void _dismissKeyboard(BuildContext context) {
final currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus && currentFocus.hasFocus) {
FocusManager.instance.primaryFocus?.unfocus();
}
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example/lib/home/home_screen.dart
|
import 'package:flutter/material.dart';
import '../overlay/overlay_screen.dart';
import '../keyboard/keyboard_screen.dart';
import 'demo_item.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
static List<ListItem> items = [
SectionHeaderItem('Widget Demos'),
KeyboardItem(),
OverlayItem(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Demos'),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
if (item is SectionHeaderItem) {
return Container(
constraints: const BoxConstraints(maxHeight: 48.0),
color: Colors.grey[300],
alignment: Alignment.center,
child: ListTile(
title: Text(item.title),
),
);
} else if (item is DemoItem) {
return ListTile(
title: Text(item.buildTitle()),
onTap: () => item.handleTap(context),
);
}
return const ListTile(
title: Text('Unknow.'),
);
},
),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example/lib/home/demo_item.dart
|
import 'package:flutter/material.dart';
abstract class ListItem {}
abstract class DemoItem extends ListItem {
String buildTitle();
void handleTap(BuildContext context);
}
class SectionHeaderItem extends ListItem {
SectionHeaderItem(this.title);
final String title;
Widget buildWidget(BuildContext context) => Text(title);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example/lib/overlay/overlay_screen.dart
|
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/flowy_infra_ui_web.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../home/demo_item.dart';
class OverlayItem extends DemoItem {
@override
String buildTitle() => 'Overlay';
@override
void handleTap(BuildContext context) {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const OverlayScreen();
},
),
);
}
}
class OverlayDemoConfiguration extends ChangeNotifier {
OverlayDemoConfiguration(this._anchorDirection, this._overlapBehaviour);
AnchorDirection _anchorDirection;
AnchorDirection get anchorDirection => _anchorDirection;
set anchorDirection(AnchorDirection value) {
_anchorDirection = value;
notifyListeners();
}
OverlapBehaviour _overlapBehaviour;
OverlapBehaviour get overlapBehaviour => _overlapBehaviour;
set overlapBehaviour(OverlapBehaviour value) {
_overlapBehaviour = value;
notifyListeners();
}
}
class OverlayScreen extends StatelessWidget {
const OverlayScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Overlay Demo'),
),
body: ChangeNotifierProvider(
create: (context) => OverlayDemoConfiguration(
AnchorDirection.rightWithTopAligned, OverlapBehaviour.stretch),
child: Builder(builder: (providerContext) {
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints.tightFor(width: 500),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 48.0),
ElevatedButton(
onPressed: () {
final windowSize = MediaQuery.of(context).size;
FlowyOverlay.of(context).insertCustom(
widget: Positioned(
left: windowSize.width / 2.0 - 100,
top: 200,
child: SizedBox(
width: 200,
height: 100,
child: Card(
color: Colors.green[200],
child: GestureDetector(
// ignore: avoid_print
onTapDown: (_) => print('Hello Flutter'),
child:
const Center(child: FlutterLogo(size: 100)),
),
),
),
),
identifier: 'overlay_flutter_logo',
delegate: null,
);
},
child: const Text('Show Overlay'),
),
const SizedBox(height: 24.0),
DropdownButton<AnchorDirection>(
value: providerContext
.watch<OverlayDemoConfiguration>()
.anchorDirection,
onChanged: (AnchorDirection? newValue) {
if (newValue != null) {
providerContext
.read<OverlayDemoConfiguration>()
.anchorDirection = newValue;
}
},
items:
AnchorDirection.values.map((AnchorDirection classType) {
return DropdownMenuItem<AnchorDirection>(
value: classType, child: Text(classType.toString()));
}).toList(),
),
const SizedBox(height: 24.0),
DropdownButton<OverlapBehaviour>(
value: providerContext
.watch<OverlayDemoConfiguration>()
.overlapBehaviour,
onChanged: (OverlapBehaviour? newValue) {
if (newValue != null) {
providerContext
.read<OverlayDemoConfiguration>()
.overlapBehaviour = newValue;
}
},
items: OverlapBehaviour.values
.map((OverlapBehaviour classType) {
return DropdownMenuItem<OverlapBehaviour>(
value: classType, child: Text(classType.toString()));
}).toList(),
),
const SizedBox(height: 24.0),
Builder(builder: (buttonContext) {
return SizedBox(
height: 100,
child: ElevatedButton(
onPressed: () {
FlowyOverlay.of(context).insertWithAnchor(
widget: SizedBox(
width: 300,
height: 50,
child: Card(
color: Colors.grey[200],
child: GestureDetector(
// ignore: avoid_print
onTapDown: (_) => print('Hello Flutter'),
child: const Center(
child: FlutterLogo(size: 50)),
),
),
),
identifier: 'overlay_anchored_card',
delegate: null,
anchorContext: buttonContext,
anchorDirection: providerContext
.read<OverlayDemoConfiguration>()
.anchorDirection,
overlapBehaviour: providerContext
.read<OverlayDemoConfiguration>()
.overlapBehaviour,
);
},
child: const Text('Show Anchored Overlay'),
),
);
}),
const SizedBox(height: 24.0),
ElevatedButton(
onPressed: () {
final windowSize = MediaQuery.of(context).size;
FlowyOverlay.of(context).insertWithRect(
widget: SizedBox(
width: 200,
height: 100,
child: Card(
color: Colors.orange[200],
child: GestureDetector(
// ignore: avoid_print
onTapDown: (_) => debugPrint('Hello Flutter'),
child:
const Center(child: FlutterLogo(size: 100)),
),
),
),
identifier: 'overlay_positioned_card',
delegate: null,
anchorPosition: Offset(0, windowSize.height - 200),
anchorSize: Size.zero,
anchorDirection: providerContext
.read<OverlayDemoConfiguration>()
.anchorDirection,
overlapBehaviour: providerContext
.read<OverlayDemoConfiguration>()
.overlapBehaviour,
);
},
child: const Text('Show Positioned Overlay'),
),
const SizedBox(height: 24.0),
Builder(builder: (buttonContext) {
return ElevatedButton(
onPressed: () {
ListOverlay.showWithAnchor(
context,
itemBuilder: (_, index) => Card(
margin: const EdgeInsets.symmetric(
vertical: 8.0, horizontal: 12.0),
elevation: 0,
child: Text(
'Option $index',
style: const TextStyle(
fontSize: 20.0, color: Colors.black),
),
),
itemCount: 10,
identifier: 'overlay_list_menu',
anchorContext: buttonContext,
anchorDirection: providerContext
.read<OverlayDemoConfiguration>()
.anchorDirection,
overlapBehaviour: providerContext
.read<OverlayDemoConfiguration>()
.overlapBehaviour,
constraints:
BoxConstraints.tight(const Size(200, 200)),
);
},
child: const Text('Show List Overlay'),
);
}),
const SizedBox(height: 24.0),
Builder(builder: (buttonContext) {
return ElevatedButton(
onPressed: () {
OptionOverlay.showWithAnchor(
context,
items: <String>[
'Alpha',
'Beta',
'Charlie',
'Delta',
'Echo',
'Foxtrot',
'Golf',
'Hotel'
],
onHover: (value, index) => debugPrint(
'Did hover option $index, value $value'),
onTap: (value, index) =>
debugPrint('Did tap option $index, value $value'),
identifier: 'overlay_options',
anchorContext: buttonContext,
anchorDirection: providerContext
.read<OverlayDemoConfiguration>()
.anchorDirection,
overlapBehaviour: providerContext
.read<OverlayDemoConfiguration>()
.overlapBehaviour,
);
},
child: const Text('Show Options Overlay'),
);
}),
],
),
),
);
}),
),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra_ui/example/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
void main() {}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_result
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_result/lib/appflowy_result.dart
|
library appflowy_result;
export 'src/async_result.dart';
export 'src/result.dart';
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_result/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_result/lib/src/async_result.dart
|
import 'package:appflowy_result/appflowy_result.dart';
typedef FlowyAsyncResult<S, F extends Object> = Future<FlowyResult<S, F>>;
extension FlowyAsyncResultExtension<S, F extends Object>
on FlowyAsyncResult<S, F> {
Future<S> getOrElse(S Function(F f) onFailure) {
return then((result) => result.getOrElse(onFailure));
}
Future<S?> toNullable() {
return then((result) => result.toNullable());
}
Future<S> getOrThrow() {
return then((result) => result.getOrThrow());
}
Future<W> fold<W>(
W Function(S s) onSuccess,
W Function(F f) onFailure,
) {
return then<W>((result) => result.fold(onSuccess, onFailure));
}
Future<bool> isError() {
return then((result) => result.isFailure);
}
Future<bool> isSuccess() {
return then((result) => result.isSuccess);
}
FlowyAsyncResult<S, F> onFailure(void Function(F failure) onFailure) {
return then((result) => result..onFailure(onFailure));
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_result/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_result/lib/src/result.dart
|
abstract class FlowyResult<S, F extends Object> {
const FlowyResult();
factory FlowyResult.success(S s) => FlowySuccess(s);
factory FlowyResult.failure(F f) => FlowyFailure(f);
T fold<T>(T Function(S s) onSuccess, T Function(F f) onFailure);
FlowyResult<T, F> map<T>(T Function(S success) fn);
FlowyResult<S, T> mapError<T extends Object>(T Function(F failure) fn);
bool get isSuccess;
bool get isFailure;
S? toNullable();
void onSuccess(void Function(S s) onSuccess);
void onFailure(void Function(F f) onFailure);
S getOrElse(S Function(F failure) onFailure);
S getOrThrow();
F getFailure();
}
class FlowySuccess<S, F extends Object> implements FlowyResult<S, F> {
final S _value;
FlowySuccess(this._value);
S get value => _value;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is FlowySuccess &&
runtimeType == other.runtimeType &&
_value == other._value;
@override
int get hashCode => _value.hashCode;
@override
String toString() => 'Success(value: $_value)';
@override
T fold<T>(T Function(S s) onSuccess, T Function(F e) onFailure) =>
onSuccess(_value);
@override
map<T>(T Function(S success) fn) {
return FlowySuccess(fn(_value));
}
@override
FlowyResult<S, T> mapError<T extends Object>(T Function(F error) fn) {
return FlowySuccess(_value);
}
@override
bool get isSuccess => true;
@override
bool get isFailure => false;
@override
S? toNullable() {
return _value;
}
@override
void onSuccess(void Function(S success) onSuccess) {
onSuccess(_value);
}
@override
void onFailure(void Function(F failure) onFailure) {}
@override
S getOrElse(S Function(F failure) onFailure) {
return _value;
}
@override
S getOrThrow() {
return _value;
}
@override
F getFailure() {
throw UnimplementedError();
}
}
class FlowyFailure<S, F extends Object> implements FlowyResult<S, F> {
final F _value;
FlowyFailure(this._value);
F get error => _value;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is FlowyFailure &&
runtimeType == other.runtimeType &&
_value == other._value;
@override
int get hashCode => _value.hashCode;
@override
String toString() => 'Failure(error: $_value)';
@override
T fold<T>(T Function(S s) onSuccess, T Function(F e) onFailure) =>
onFailure(_value);
@override
map<T>(T Function(S success) fn) {
return FlowyFailure(_value);
}
@override
FlowyResult<S, T> mapError<T extends Object>(T Function(F error) fn) {
return FlowyFailure(fn(_value));
}
@override
bool get isSuccess => false;
@override
bool get isFailure => true;
@override
S? toNullable() {
return null;
}
@override
void onSuccess(void Function(S success) onSuccess) {}
@override
void onFailure(void Function(F failure) onFailure) {
onFailure(_value);
}
@override
S getOrElse(S Function(F failure) onFailure) {
return onFailure(_value);
}
@override
S getOrThrow() {
throw _value;
}
@override
F getFailure() {
return _value;
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/language.dart
|
import 'package:flutter/material.dart';
String languageFromLocale(Locale locale) {
switch (locale.languageCode) {
// Most often used languages
case "en":
return "English";
case "zh":
switch (locale.countryCode) {
case "CN":
return "简体中文";
case "TW":
return "繁體中文";
default:
return locale.languageCode;
}
// Then in alphabetical order
case "am":
return "አማርኛ";
case "ar":
return "العربية";
case "ca":
return "Català";
case "cs":
return "Čeština";
case "ckb":
switch (locale.countryCode) {
case "KU":
return "کوردی";
default:
return locale.languageCode;
}
case "de":
return "Deutsch";
case "es":
return "Español";
case "eu":
return "Euskera";
case "el":
return "Ελληνικά";
case "fr":
switch (locale.countryCode) {
case "CA":
return "Français (CA)";
case "FR":
return "Français (FR)";
default:
return locale.languageCode;
}
case "hu":
return "Magyar";
case "id":
return "Bahasa Indonesia";
case "it":
return "Italiano";
case "ja":
return "日本語";
case "ko":
return "한국어";
case "pl":
return "Polski";
case "pt":
return "Português";
case "ru":
return "русский";
case "sv":
return "Svenska";
case "th":
return "ไทย";
case "tr":
return "Türkçe";
case "fa":
return "فارسی";
case "uk":
return "українська";
case "ur":
return "اردو";
case "hin":
return "हिन्दी";
}
// If not found then the language code will be displayed
return locale.languageCode;
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/size.dart
|
import 'package:flutter/material.dart';
class PageBreaks {
static double get largePhone => 550;
static double get tabletPortrait => 768;
static double get tabletLandscape => 1024;
static double get desktop => 1440;
}
class Insets {
/// Dynamic insets, may get scaled with the device size
static double scale = 1;
static double get xs => 2 * scale;
static double get sm => 6 * scale;
static double get m => 12 * scale;
static double get l => 24 * scale;
static double get xl => 36 * scale;
static double get xxl => 64 * scale;
static double get xxxl => 80 * scale;
}
class FontSizes {
static double get scale => 1;
static double get s11 => 11 * scale;
static double get s12 => 12 * scale;
static double get s14 => 14 * scale;
static double get s16 => 16 * scale;
static double get s18 => 18 * scale;
static double get s20 => 20 * scale;
static double get s24 => 24 * scale;
static double get s32 => 32 * scale;
static double get s44 => 44 * scale;
}
class Sizes {
static double hitScale = 1;
static double get hit => 40 * hitScale;
static double get iconMed => 20;
static double get sideBarWidth => 250 * hitScale;
}
class Corners {
static const BorderRadius s3Border = BorderRadius.all(s3Radius);
static const Radius s3Radius = Radius.circular(3);
static const BorderRadius s4Border = BorderRadius.all(s4Radius);
static const Radius s4Radius = Radius.circular(4);
static const BorderRadius s5Border = BorderRadius.all(s5Radius);
static const Radius s5Radius = Radius.circular(5);
static const BorderRadius s6Border = BorderRadius.all(s6Radius);
static const Radius s6Radius = Radius.circular(6);
static const BorderRadius s8Border = BorderRadius.all(s8Radius);
static const Radius s8Radius = Radius.circular(8);
static const BorderRadius s10Border = BorderRadius.all(s10Radius);
static const Radius s10Radius = Radius.circular(10);
static const BorderRadius s12Border = BorderRadius.all(s12Radius);
static const Radius s12Radius = Radius.circular(12);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/notifier.dart
|
import 'package:flutter/material.dart';
abstract class Comparable<T> {
bool compare(T? previous, T? current);
}
class ObjectComparable<T> extends Comparable<T> {
@override
bool compare(T? previous, T? current) {
return previous == current;
}
}
class PublishNotifier<T> extends ChangeNotifier {
T? _value;
Comparable<T>? comparable = ObjectComparable();
PublishNotifier({this.comparable});
set value(T newValue) {
if (comparable != null) {
if (comparable!.compare(_value, newValue)) {
_value = newValue;
notifyListeners();
}
} else {
_value = newValue;
notifyListeners();
}
}
T? get currentValue => _value;
void addPublishListener(void Function(T) callback,
{bool Function()? listenWhen}) {
super.addListener(
() {
if (_value == null) {
return;
} else {}
if (listenWhen != null && listenWhen() == false) {
return;
}
callback(_value as T);
},
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/uuid.dart
|
import 'package:uuid/uuid.dart';
String uuid() {
return const Uuid().v4();
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/icon_data.dart
|
/// Flutter icons FlowyIconData
/// Copyright (C) 2021 by original authors @ fluttericon.com, fontello.com
/// This font was generated by FlutterIcon.com, which is derived from Fontello.
///
/// To use this font, place it in your fonts/ directory and include the
/// following in your pubspec.yaml
///
/// flutter:
/// fonts:
/// - family: FlowyIconData
/// fonts:
/// - asset: fonts/FlowyIconData.ttf
///
///
///
library;
// ignore_for_file: constant_identifier_names
import 'package:flutter/widgets.dart';
class FlowyIconData {
FlowyIconData._();
static const _kFontFam = 'FlowyIconData';
static const String? _kFontPkg = null;
static const IconData drop_down_hide =
IconData(0xe800, fontFamily: _kFontFam, fontPackage: _kFontPkg);
static const IconData drop_down_show =
IconData(0xe801, fontFamily: _kFontFam, fontPackage: _kFontPkg);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/theme.dart
|
import 'package:flowy_infra/colorscheme/colorscheme.dart';
import 'package:flowy_infra/colorscheme/default_colorscheme.dart';
import 'plugins/service/plugin_service.dart';
class BuiltInTheme {
static const String defaultTheme = 'Default';
static const String dandelion = 'Dandelion';
static const String lemonade = 'Lemonade';
static const String lavender = 'Lavender';
}
class AppTheme {
// metadata member
final bool builtIn;
final String themeName;
final FlowyColorScheme lightTheme;
final FlowyColorScheme darkTheme;
// static final Map<String, dynamic> _cachedJsonData = {};
const AppTheme({
required this.builtIn,
required this.themeName,
required this.lightTheme,
required this.darkTheme,
});
static const AppTheme fallback = AppTheme(
builtIn: true,
themeName: BuiltInTheme.defaultTheme,
lightTheme: DefaultColorScheme.light(),
darkTheme: DefaultColorScheme.dark(),
);
static Future<Iterable<AppTheme>> _plugins(FlowyPluginService service) async {
final plugins = await service.plugins;
return plugins.map((plugin) => plugin.theme).whereType<AppTheme>();
}
static Iterable<AppTheme> get builtins => themeMap.entries
.map(
(entry) => AppTheme(
builtIn: true,
themeName: entry.key,
lightTheme: entry.value[0],
darkTheme: entry.value[1],
),
)
.toList();
static Future<Iterable<AppTheme>> themes(FlowyPluginService service) async =>
[
...builtins,
...(await _plugins(service)),
];
static Future<AppTheme> fromName(
String themeName, {
FlowyPluginService? pluginService,
}) async {
pluginService ??= FlowyPluginService.instance;
for (final theme in await themes(pluginService)) {
if (theme.themeName == themeName) {
return theme;
}
}
throw ArgumentError('The theme $themeName does not exist.');
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/theme_extension.dart
|
import 'package:flutter/material.dart';
@immutable
class AFThemeExtension extends ThemeExtension<AFThemeExtension> {
final Color? warning;
final Color? success;
final Color tint1;
final Color tint2;
final Color tint3;
final Color tint4;
final Color tint5;
final Color tint6;
final Color tint7;
final Color tint8;
final Color tint9;
final Color textColor;
final Color greyHover;
final Color greySelect;
final Color lightGreyHover;
final Color toggleOffFill;
final Color progressBarBGColor;
final Color toggleButtonBGColor;
final Color calloutBGColor;
final Color tableCellBGColor;
final Color calendarWeekendBGColor;
final Color gridRowCountColor;
final TextStyle code;
final TextStyle callout;
final TextStyle caption;
const AFThemeExtension({
required this.warning,
required this.success,
required this.tint1,
required this.tint2,
required this.tint3,
required this.tint4,
required this.tint5,
required this.tint6,
required this.tint7,
required this.tint8,
required this.tint9,
required this.greyHover,
required this.greySelect,
required this.lightGreyHover,
required this.toggleOffFill,
required this.textColor,
required this.calloutBGColor,
required this.tableCellBGColor,
required this.calendarWeekendBGColor,
required this.code,
required this.callout,
required this.caption,
required this.progressBarBGColor,
required this.toggleButtonBGColor,
required this.gridRowCountColor,
});
static AFThemeExtension of(BuildContext context) {
return Theme.of(context).extension<AFThemeExtension>()!;
}
@override
AFThemeExtension copyWith({
Color? warning,
Color? success,
Color? tint1,
Color? tint2,
Color? tint3,
Color? tint4,
Color? tint5,
Color? tint6,
Color? tint7,
Color? tint8,
Color? tint9,
Color? textColor,
Color? calloutBGColor,
Color? tableCellBGColor,
Color? greyHover,
Color? greySelect,
Color? lightGreyHover,
Color? toggleOffFill,
Color? progressBarBGColor,
Color? toggleButtonBGColor,
Color? calendarWeekendBGColor,
Color? gridRowCountColor,
TextStyle? code,
TextStyle? callout,
TextStyle? caption,
}) {
return AFThemeExtension(
warning: warning ?? this.warning,
success: success ?? this.success,
tint1: tint1 ?? this.tint1,
tint2: tint2 ?? this.tint2,
tint3: tint3 ?? this.tint3,
tint4: tint4 ?? this.tint4,
tint5: tint5 ?? this.tint5,
tint6: tint6 ?? this.tint6,
tint7: tint7 ?? this.tint7,
tint8: tint8 ?? this.tint8,
tint9: tint9 ?? this.tint9,
textColor: textColor ?? this.textColor,
calloutBGColor: calloutBGColor ?? this.calloutBGColor,
tableCellBGColor: tableCellBGColor ?? this.tableCellBGColor,
greyHover: greyHover ?? this.greyHover,
greySelect: greySelect ?? this.greySelect,
lightGreyHover: lightGreyHover ?? this.lightGreyHover,
toggleOffFill: toggleOffFill ?? this.toggleOffFill,
progressBarBGColor: progressBarBGColor ?? this.progressBarBGColor,
toggleButtonBGColor: toggleButtonBGColor ?? this.toggleButtonBGColor,
calendarWeekendBGColor:
calendarWeekendBGColor ?? this.calendarWeekendBGColor,
gridRowCountColor: gridRowCountColor ?? this.gridRowCountColor,
code: code ?? this.code,
callout: callout ?? this.callout,
caption: caption ?? this.caption,
);
}
@override
ThemeExtension<AFThemeExtension> lerp(
ThemeExtension<AFThemeExtension>? other, double t) {
if (other is! AFThemeExtension) {
return this;
}
return AFThemeExtension(
warning: Color.lerp(warning, other.warning, t),
success: Color.lerp(success, other.success, t),
tint1: Color.lerp(tint1, other.tint1, t)!,
tint2: Color.lerp(tint2, other.tint2, t)!,
tint3: Color.lerp(tint3, other.tint3, t)!,
tint4: Color.lerp(tint4, other.tint4, t)!,
tint5: Color.lerp(tint5, other.tint5, t)!,
tint6: Color.lerp(tint6, other.tint6, t)!,
tint7: Color.lerp(tint7, other.tint7, t)!,
tint8: Color.lerp(tint8, other.tint8, t)!,
tint9: Color.lerp(tint9, other.tint9, t)!,
textColor: Color.lerp(textColor, other.textColor, t)!,
calloutBGColor: Color.lerp(calloutBGColor, other.calloutBGColor, t)!,
tableCellBGColor:
Color.lerp(tableCellBGColor, other.tableCellBGColor, t)!,
greyHover: Color.lerp(greyHover, other.greyHover, t)!,
greySelect: Color.lerp(greySelect, other.greySelect, t)!,
lightGreyHover: Color.lerp(lightGreyHover, other.lightGreyHover, t)!,
toggleOffFill: Color.lerp(toggleOffFill, other.toggleOffFill, t)!,
progressBarBGColor:
Color.lerp(progressBarBGColor, other.progressBarBGColor, t)!,
toggleButtonBGColor:
Color.lerp(toggleButtonBGColor, other.toggleButtonBGColor, t)!,
calendarWeekendBGColor:
Color.lerp(calendarWeekendBGColor, other.calendarWeekendBGColor, t)!,
gridRowCountColor:
Color.lerp(gridRowCountColor, other.gridRowCountColor, t)!,
code: other.code,
callout: other.callout,
caption: other.caption,
);
}
}
enum FlowyTint {
tint1,
tint2,
tint3,
tint4,
tint5,
tint6,
tint7,
tint8,
tint9;
String toJson() => name;
static FlowyTint fromJson(String json) {
try {
return FlowyTint.values.byName(json);
} catch (_) {
return FlowyTint.tint1;
}
}
Color color(BuildContext context) {
switch (this) {
case FlowyTint.tint1:
return AFThemeExtension.of(context).tint1;
case FlowyTint.tint2:
return AFThemeExtension.of(context).tint2;
case FlowyTint.tint3:
return AFThemeExtension.of(context).tint3;
case FlowyTint.tint4:
return AFThemeExtension.of(context).tint4;
case FlowyTint.tint5:
return AFThemeExtension.of(context).tint5;
case FlowyTint.tint6:
return AFThemeExtension.of(context).tint6;
case FlowyTint.tint7:
return AFThemeExtension.of(context).tint7;
case FlowyTint.tint8:
return AFThemeExtension.of(context).tint8;
case FlowyTint.tint9:
return AFThemeExtension.of(context).tint9;
}
}
String get id {
switch (this) {
// DON'T change this name because it's saved in the database!
case FlowyTint.tint1:
return 'appflowy_them_color_tint1';
case FlowyTint.tint2:
return 'appflowy_them_color_tint2';
case FlowyTint.tint3:
return 'appflowy_them_color_tint3';
case FlowyTint.tint4:
return 'appflowy_them_color_tint4';
case FlowyTint.tint5:
return 'appflowy_them_color_tint5';
case FlowyTint.tint6:
return 'appflowy_them_color_tint6';
case FlowyTint.tint7:
return 'appflowy_them_color_tint7';
case FlowyTint.tint8:
return 'appflowy_them_color_tint8';
case FlowyTint.tint9:
return 'appflowy_them_color_tint9';
}
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/file_picker/file_picker_service.dart
|
import 'package:file_picker/file_picker.dart';
export 'package:file_picker/file_picker.dart'
show FileType, FilePickerStatus, PlatformFile;
class FilePickerResult {
const FilePickerResult(this.files);
/// Picked files.
final List<PlatformFile> files;
}
/// Abstract file picker as a service to implement dependency injection.
abstract class FilePickerService {
Future<String?> getDirectoryPath({
String? title,
}) async =>
throw UnimplementedError('getDirectoryPath() has not been implemented.');
Future<FilePickerResult?> pickFiles({
String? dialogTitle,
String? initialDirectory,
FileType type = FileType.any,
List<String>? allowedExtensions,
Function(FilePickerStatus)? onFileLoading,
bool allowCompression = true,
bool allowMultiple = false,
bool withData = false,
bool withReadStream = false,
bool lockParentWindow = false,
}) async =>
throw UnimplementedError('pickFiles() has not been implemented.');
Future<String?> saveFile({
String? dialogTitle,
String? fileName,
String? initialDirectory,
FileType type = FileType.any,
List<String>? allowedExtensions,
bool lockParentWindow = false,
}) async =>
throw UnimplementedError('saveFile() has not been implemented.');
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/file_picker/file_picker_impl.dart
|
import 'package:flowy_infra/file_picker/file_picker_service.dart';
import 'package:file_picker/file_picker.dart' as fp;
class FilePicker implements FilePickerService {
@override
Future<String?> getDirectoryPath({String? title}) {
return fp.FilePicker.platform.getDirectoryPath();
}
@override
Future<FilePickerResult?> pickFiles({
String? dialogTitle,
String? initialDirectory,
fp.FileType type = fp.FileType.any,
List<String>? allowedExtensions,
Function(fp.FilePickerStatus p1)? onFileLoading,
bool allowCompression = true,
bool allowMultiple = false,
bool withData = false,
bool withReadStream = false,
bool lockParentWindow = false,
}) async {
final result = await fp.FilePicker.platform.pickFiles(
dialogTitle: dialogTitle,
initialDirectory: initialDirectory,
type: type,
allowedExtensions: allowedExtensions,
onFileLoading: onFileLoading,
allowCompression: allowCompression,
allowMultiple: allowMultiple,
withData: withData,
withReadStream: withReadStream,
lockParentWindow: lockParentWindow,
);
return FilePickerResult(result?.files ?? []);
}
@override
Future<String?> saveFile({
String? dialogTitle,
String? fileName,
String? initialDirectory,
FileType type = FileType.any,
List<String>? allowedExtensions,
bool lockParentWindow = false,
}) async {
final result = await fp.FilePicker.platform.saveFile(
dialogTitle: dialogTitle,
fileName: fileName,
initialDirectory: initialDirectory,
type: type,
allowedExtensions: allowedExtensions,
lockParentWindow: lockParentWindow,
);
return result;
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/colorscheme/default_colorscheme.dart
|
import 'package:flutter/material.dart';
import 'colorscheme.dart';
const _white = Color(0xFFFFFFFF);
const _lightHover = Color(0xFFe0f8ff);
const _lightSelector = Color(0xfff2fcff);
const _lightBg1 = Color(0xfff7f8fc);
const _lightBg2 = Color(0xffedeef2);
const _lightShader1 = Color(0xff333333);
const _lightShader3 = Color(0xff828282);
const _lightShader5 = Color(0xffe0e0e0);
const _lightShader6 = Color(0xfff2f2f2);
const _lightMain1 = Color(0xff00bcf0);
const _lightTint9 = Color(0xffe1fbff);
const _darkShader1 = Color(0xff131720);
const _darkShader2 = Color(0xff1A202C);
const _darkShader3 = Color(0xff363D49);
const _darkShader5 = Color(0xffBBC3CD);
const _darkShader6 = Color(0xffF2F2F2);
const _darkMain1 = Color(0xff00BCF0);
const _darkInput = Color(0xff282E3A);
class DefaultColorScheme extends FlowyColorScheme {
const DefaultColorScheme.light()
: super(
surface: _white,
hover: _lightHover,
selector: _lightSelector,
red: const Color(0xfffb006d),
yellow: const Color(0xffffd667),
green: const Color(0xff66cf80),
shader1: _lightShader1,
shader2: const Color(0xff4f4f4f),
shader3: _lightShader3,
shader4: const Color(0xffbdbdbd),
shader5: _lightShader5,
shader6: _lightShader6,
shader7: _lightShader1,
bg1: _lightBg1,
bg2: _lightBg2,
bg3: const Color(0xffe2e4eb),
bg4: const Color(0xff2c144b),
tint1: const Color(0xffe8e0ff),
tint2: const Color(0xffffe7fd),
tint3: const Color(0xffffe7ee),
tint4: const Color(0xffffefe3),
tint5: const Color(0xfffff2cd),
tint6: const Color(0xfff5ffdc),
tint7: const Color(0xffddffd6),
tint8: const Color(0xffdefff1),
tint9: _lightTint9,
main1: _lightMain1,
main2: const Color(0xff00b7ea),
shadow: const Color.fromRGBO(0, 0, 0, 0.15),
sidebarBg: _lightBg1,
divider: _lightShader6,
topbarBg: _white,
icon: _lightShader1,
text: _lightShader1,
input: _white,
hint: _lightShader3,
primary: _lightMain1,
onPrimary: _white,
hoverBG1: _lightBg2,
hoverBG2: _lightHover,
hoverBG3: _lightShader6,
hoverFG: _lightShader1,
questionBubbleBG: _lightSelector,
progressBarBGColor: _lightTint9,
toolbarColor: _lightShader1,
toggleButtonBGColor: _lightShader5,
calendarWeekendBGColor: const Color(0xFFFBFBFC),
gridRowCountColor: _lightShader1,
);
const DefaultColorScheme.dark()
: super(
surface: _darkShader2,
hover: _darkMain1,
selector: _darkShader2,
red: const Color(0xfffb006d),
yellow: const Color(0xffF7CF46),
green: const Color(0xff66CF80),
shader1: _darkShader1,
shader2: _darkShader2,
shader3: _darkShader3,
shader4: const Color(0xff505469),
shader5: _darkShader5,
shader6: _darkShader6,
shader7: _white,
bg1: const Color(0xffF7F8FC),
bg2: const Color(0xffEDEEF2),
bg3: _darkMain1,
bg4: const Color(0xff2C144B),
tint1: const Color(0x4d9327FF),
tint2: const Color(0x66FC0088),
tint3: const Color(0x4dFC00E2),
tint4: const Color(0x80BE5B00),
tint5: const Color(0x33F8EE00),
tint6: const Color(0x4d6DC300),
tint7: const Color(0x5900BD2A),
tint8: const Color(0x80008890),
tint9: const Color(0x4d0029FF),
main1: _darkMain1,
main2: const Color(0xff00B7EA),
shadow: const Color(0xff0F131C),
sidebarBg: const Color(0xff232B38),
divider: _darkShader3,
topbarBg: _darkShader1,
icon: _darkShader5,
text: _darkShader5,
input: _darkInput,
hint: const Color(0xff59647a),
primary: _darkMain1,
onPrimary: _darkShader1,
hoverBG1: _darkMain1,
hoverBG2: _darkMain1,
hoverBG3: _darkShader3,
hoverFG: _darkShader1,
questionBubbleBG: _darkShader3,
progressBarBGColor: _darkShader3,
toolbarColor: _darkInput,
toggleButtonBGColor: _darkShader1,
calendarWeekendBGColor: _darkShader1,
gridRowCountColor: _darkShader5,
);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/colorscheme/lavender.dart
|
import 'package:flutter/material.dart';
import 'colorscheme.dart';
const _black = Color(0xff000000);
const _white = Color(0xFFFFFFFF);
const _lightHover = Color(0xffd8d6fc);
const _lightSelector = Color(0xffe5e3f9);
const _lightBg1 = Color(0xfff2f0f6);
const _lightBg2 = Color(0xffd8d6fc);
const _lightShader1 = Color(0xff333333);
const _lightShader3 = Color(0xff828282);
const _lightShader5 = Color(0xffe0e0e0);
const _lightShader6 = Color(0xffd8d6fc);
const _lightMain1 = Color(0xffaba9e7);
const _lightTint9 = Color(0xffe1fbff);
const _darkShader1 = Color(0xff131720);
const _darkShader2 = Color(0xff1A202C);
const _darkShader3 = Color(0xff363D49);
const _darkShader5 = Color(0xffBBC3CD);
const _darkShader6 = Color(0xffF2F2F2);
const _darkMain1 = Color(0xffab00ff);
const _darkInput = Color(0xff282E3A);
class LavenderColorScheme extends FlowyColorScheme {
const LavenderColorScheme.light()
: super(
surface: Colors.white,
hover: _lightHover,
selector: _lightSelector,
red: const Color(0xfffb006d),
yellow: const Color(0xffffd667),
green: const Color(0xff66cf80),
shader1: const Color(0xff333333),
shader2: const Color(0xff4f4f4f),
shader3: const Color(0xff828282),
shader4: const Color(0xffbdbdbd),
shader5: _lightShader5,
shader6: const Color(0xfff2f2f2),
shader7: _black,
bg1: const Color(0xffAC59FF),
bg2: const Color(0xffedeef2),
bg3: _lightHover,
bg4: const Color(0xff2c144b),
tint1: const Color(0xffe8e0ff),
tint2: const Color(0xffffe7fd),
tint3: const Color(0xffffe7ee),
tint4: const Color(0xffffefe3),
tint5: const Color(0xfffff2cd),
tint6: const Color(0xfff5ffdc),
tint7: const Color(0xffddffd6),
tint8: const Color(0xffdefff1),
tint9: _lightMain1,
main1: _lightMain1,
main2: _lightMain1,
shadow: const Color.fromRGBO(0, 0, 0, 0.15),
sidebarBg: _lightBg1,
divider: _lightShader6,
topbarBg: _white,
icon: _lightShader1,
text: _lightShader1,
input: _white,
hint: _lightShader3,
primary: _lightMain1,
onPrimary: _lightShader1,
hoverBG1: _lightBg2,
hoverBG2: _lightHover,
hoverBG3: _lightShader6,
hoverFG: _lightShader1,
questionBubbleBG: _lightSelector,
progressBarBGColor: _lightTint9,
toolbarColor: _lightShader1,
toggleButtonBGColor: _lightSelector,
calendarWeekendBGColor: const Color(0xFFFBFBFC),
gridRowCountColor: _black,
);
const LavenderColorScheme.dark()
: super(
surface: const Color(0xFF1B1A1D),
hover: _darkMain1,
selector: _darkShader2,
red: const Color(0xfffb006d),
yellow: const Color(0xffffd667),
green: const Color(0xff66cf80),
shader1: _white,
shader2: _darkShader2,
shader3: const Color(0xff828282),
shader4: const Color(0xffbdbdbd),
shader5: _white,
shader6: _darkShader6,
shader7: _white,
bg1: const Color(0xff8C23F6),
bg2: _black,
bg3: _darkMain1,
bg4: const Color(0xff2c144b),
tint1: const Color(0x4d9327FF),
tint2: const Color(0x66FC0088),
tint3: const Color(0x4dFC00E2),
tint4: const Color(0x80BE5B00),
tint5: const Color(0x33F8EE00),
tint6: const Color(0x4d6DC300),
tint7: const Color(0x5900BD2A),
tint8: const Color(0x80008890),
tint9: const Color(0x4d0029FF),
main1: _darkMain1,
main2: _darkMain1,
shadow: const Color(0xff0F131C),
sidebarBg: const Color(0xff2D223B),
divider: _darkShader3,
topbarBg: _darkShader1,
icon: _darkShader5,
text: _darkShader5,
input: _darkInput,
hint: _darkShader5,
primary: _darkMain1,
onPrimary: _darkShader1,
hoverBG1: _darkMain1,
hoverBG2: _darkMain1,
hoverBG3: _darkShader3,
hoverFG: _darkShader1,
questionBubbleBG: _darkShader3,
progressBarBGColor: _darkShader3,
toolbarColor: _darkInput,
toggleButtonBGColor: _darkShader1,
calendarWeekendBGColor: const Color(0xff121212),
gridRowCountColor: _darkMain1,
);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/colorscheme/colorscheme.dart
|
import 'package:flowy_infra/utils/color_converter.dart';
import 'package:flutter/material.dart';
import 'package:flowy_infra/theme.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'default_colorscheme.dart';
import 'dandelion.dart';
import 'lavender.dart';
import 'lemonade.dart';
part 'colorscheme.g.dart';
/// A map of all the built-in themes.
///
/// The key is the theme name, and the value is a list of two color schemes:
/// the first is for light mode, and the second is for dark mode.
const Map<String, List<FlowyColorScheme>> themeMap = {
BuiltInTheme.defaultTheme: [
DefaultColorScheme.light(),
DefaultColorScheme.dark(),
],
BuiltInTheme.dandelion: [
DandelionColorScheme.light(),
DandelionColorScheme.dark(),
],
BuiltInTheme.lemonade: [
LemonadeColorScheme.light(),
LemonadeColorScheme.dark(),
],
BuiltInTheme.lavender: [
LavenderColorScheme.light(),
LavenderColorScheme.dark(),
],
};
@JsonSerializable(
converters: [
ColorConverter(),
],
)
class FlowyColorScheme {
final Color surface;
final Color hover;
final Color selector;
final Color red;
final Color yellow;
final Color green;
final Color shader1;
final Color shader2;
final Color shader3;
final Color shader4;
final Color shader5;
final Color shader6;
final Color shader7;
final Color bg1;
final Color bg2;
final Color bg3;
final Color bg4;
final Color tint1;
final Color tint2;
final Color tint3;
final Color tint4;
final Color tint5;
final Color tint6;
final Color tint7;
final Color tint8;
final Color tint9;
final Color main1;
final Color main2;
final Color shadow;
final Color sidebarBg;
final Color divider;
final Color topbarBg;
final Color icon;
final Color text;
final Color input;
final Color hint;
final Color primary;
final Color onPrimary;
//page title hover effect
final Color hoverBG1;
//action item hover effect
final Color hoverBG2;
final Color hoverBG3;
//the text color when it is hovered
final Color hoverFG;
final Color questionBubbleBG;
final Color progressBarBGColor;
//editor toolbar BG color
final Color toolbarColor;
final Color toggleButtonBGColor;
final Color calendarWeekendBGColor;
//grid bottom count color
final Color gridRowCountColor;
const FlowyColorScheme({
required this.surface,
required this.hover,
required this.selector,
required this.red,
required this.yellow,
required this.green,
required this.shader1,
required this.shader2,
required this.shader3,
required this.shader4,
required this.shader5,
required this.shader6,
required this.shader7,
required this.bg1,
required this.bg2,
required this.bg3,
required this.bg4,
required this.tint1,
required this.tint2,
required this.tint3,
required this.tint4,
required this.tint5,
required this.tint6,
required this.tint7,
required this.tint8,
required this.tint9,
required this.main1,
required this.main2,
required this.shadow,
required this.sidebarBg,
required this.divider,
required this.topbarBg,
required this.icon,
required this.text,
required this.input,
required this.hint,
required this.primary,
required this.onPrimary,
required this.hoverBG1,
required this.hoverBG2,
required this.hoverBG3,
required this.hoverFG,
required this.questionBubbleBG,
required this.progressBarBGColor,
required this.toolbarColor,
required this.toggleButtonBGColor,
required this.calendarWeekendBGColor,
required this.gridRowCountColor,
});
factory FlowyColorScheme.fromJson(Map<String, dynamic> json) =>
_$FlowyColorSchemeFromJson(json);
Map<String, dynamic> toJson() => _$FlowyColorSchemeToJson(this);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/colorscheme/lemonade.dart
|
import 'package:flutter/material.dart';
import 'colorscheme.dart';
const _black = Color(0xff000000);
const _white = Color(0xFFFFFFFF);
const _lightBg1 = Color(0xFFFFD13E);
const _lightShader1 = Color(0xff333333);
const _lightShader3 = Color(0xff828282);
const _lightShader5 = Color(0xffe0e0e0);
const _lightShader6 = Color(0xfff2f2f2);
const _lightDandelionYellow = Color(0xffffcb00);
const _lightDandelionLightYellow = Color(0xffffdf66);
const _lightTint9 = Color(0xffe1fbff);
const _darkShader1 = Color(0xff131720);
const _darkShader2 = Color(0xff1A202C);
const _darkShader3 = Color(0xff363D49);
const _darkShader5 = Color(0xffBBC3CD);
const _darkShader6 = Color(0xffF2F2F2);
const _darkMain1 = Color(0xffffcb00);
const _darkInput = Color(0xff282E3A);
// Derive from [DandelionColorScheme]
// Use a light yellow color in the sidebar intead of a green color in Dandelion
// Some field name are still included 'Dandelion' to indicate they are the same color as the one in Dandelion
class LemonadeColorScheme extends FlowyColorScheme {
const LemonadeColorScheme.light()
: super(
surface: Colors.white,
hover: const Color(0xFFe0f8ff),
// hover effect on setting value
selector: _lightDandelionLightYellow,
red: const Color(0xfffb006d),
yellow: const Color(0xffffd667),
green: const Color(0xff66cf80),
shader1: const Color(0xff333333),
shader2: const Color(0xff4f4f4f),
shader3: const Color(0xff828282),
// disable text color
shader4: const Color(0xffbdbdbd),
shader5: _lightShader5,
shader6: const Color(0xfff2f2f2),
shader7: _black,
bg1: _lightBg1,
bg2: const Color(0xffedeef2),
// Hover color on trash button
bg3: _lightDandelionYellow,
bg4: const Color(0xff2c144b),
tint1: const Color(0xffe8e0ff),
tint2: const Color(0xffffe7fd),
tint3: const Color(0xffffe7ee),
tint4: const Color(0xffffefe3),
tint5: const Color(0xfffff2cd),
tint6: const Color(0xfff5ffdc),
tint7: const Color(0xffddffd6),
tint8: const Color(0xffdefff1),
tint9: _lightTint9,
main1: _lightDandelionYellow,
// cursor color
main2: _lightDandelionYellow,
shadow: const Color.fromRGBO(0, 0, 0, 0.15),
sidebarBg: const Color(0xfffaf0c8),
divider: _lightShader6,
topbarBg: _white,
icon: _lightShader1,
text: _lightShader1,
input: _white,
hint: _lightShader3,
primary: _lightDandelionYellow,
onPrimary: _lightShader1,
// hover color in sidebar
hoverBG1: _lightDandelionYellow,
// tool bar hover color
hoverBG2: _lightDandelionLightYellow,
hoverBG3: _lightShader6,
hoverFG: _lightShader1,
questionBubbleBG: _lightDandelionLightYellow,
progressBarBGColor: _lightTint9,
toolbarColor: _lightShader1,
toggleButtonBGColor: _lightDandelionYellow,
calendarWeekendBGColor: const Color(0xFFFBFBFC),
gridRowCountColor: _black,
);
const LemonadeColorScheme.dark()
: super(
surface: const Color(0xff292929),
hover: const Color(0xff1f1f1f),
selector: _darkShader2,
red: const Color(0xfffb006d),
yellow: const Color(0xffffd667),
green: const Color(0xff66cf80),
shader1: _white,
shader2: _darkShader2,
shader3: const Color(0xff828282),
shader4: const Color(0xffbdbdbd),
shader5: _darkShader5,
shader6: _darkShader6,
shader7: _white,
bg1: const Color(0xFFD5A200),
bg2: _black,
bg3: _darkMain1,
bg4: const Color(0xff2c144b),
tint1: const Color(0x4d9327FF),
tint2: const Color(0x66FC0088),
tint3: const Color(0x4dFC00E2),
tint4: const Color(0x80BE5B00),
tint5: const Color(0x33F8EE00),
tint6: const Color(0x4d6DC300),
tint7: const Color(0x5900BD2A),
tint8: const Color(0x80008890),
tint9: const Color(0x4d0029FF),
main1: _darkMain1,
main2: _darkMain1,
shadow: _black,
sidebarBg: const Color(0xff232B38),
divider: _darkShader3,
topbarBg: _darkShader1,
icon: _darkShader5,
text: _darkShader5,
input: _darkInput,
hint: _darkShader5,
primary: _darkMain1,
onPrimary: _darkShader1,
hoverBG1: _darkMain1,
hoverBG2: _darkMain1,
hoverBG3: _darkShader3,
hoverFG: _darkShader1,
questionBubbleBG: _darkShader3,
progressBarBGColor: _darkShader3,
toolbarColor: _darkInput,
toggleButtonBGColor: _darkShader1,
calendarWeekendBGColor: const Color(0xff121212),
gridRowCountColor: _darkMain1,
);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/colorscheme/dandelion.dart
|
import 'package:flutter/material.dart';
import 'colorscheme.dart';
const _black = Color(0xff000000);
const _white = Color(0xFFFFFFFF);
const _lightBg1 = Color(0xFFFFD13E);
const _lightShader1 = Color(0xff333333);
const _lightShader3 = Color(0xff828282);
const _lightShader5 = Color(0xffe0e0e0);
const _lightShader6 = Color(0xfff2f2f2);
const _lightDandelionYellow = Color(0xffffcb00);
const _lightDandelionLightYellow = Color(0xffffdf66);
const _lightDandelionGreen = Color(0xff9bc53d);
const _lightTint9 = Color(0xffe1fbff);
const _darkShader1 = Color(0xff131720);
const _darkShader2 = Color(0xff1A202C);
const _darkShader3 = Color(0xff363D49);
const _darkShader5 = Color(0xffBBC3CD);
const _darkShader6 = Color(0xffF2F2F2);
const _darkMain1 = Color(0xffffcb00);
const _darkInput = Color(0xff282E3A);
class DandelionColorScheme extends FlowyColorScheme {
const DandelionColorScheme.light()
: super(
surface: Colors.white,
hover: const Color(0xFFe0f8ff),
// hover effect on setting value
selector: _lightDandelionLightYellow,
red: const Color(0xfffb006d),
yellow: const Color(0xffffd667),
green: const Color(0xff66cf80),
shader1: const Color(0xff333333),
shader2: const Color(0xff4f4f4f),
shader3: const Color(0xff828282),
// disable text color
shader4: const Color(0xffbdbdbd),
shader5: _lightShader5,
shader6: const Color(0xfff2f2f2),
shader7: _black,
bg1: _lightBg1,
bg2: const Color(0xffedeef2),
// Hover color on trash button
bg3: _lightDandelionYellow,
bg4: const Color(0xff2c144b),
tint1: const Color(0xffe8e0ff),
tint2: const Color(0xffffe7fd),
tint3: const Color(0xffffe7ee),
tint4: const Color(0xffffefe3),
tint5: const Color(0xfffff2cd),
tint6: const Color(0xfff5ffdc),
tint7: const Color(0xffddffd6),
tint8: const Color(0xffdefff1),
tint9: _lightTint9,
main1: _lightDandelionYellow,
// cursor color
main2: _lightDandelionYellow,
shadow: const Color.fromRGBO(0, 0, 0, 0.15),
sidebarBg: _lightDandelionGreen,
divider: _lightShader6,
topbarBg: _white,
icon: _lightShader1,
text: _lightShader1,
input: _white,
hint: _lightShader3,
primary: _lightDandelionYellow,
onPrimary: _lightShader1,
// hover color in sidebar
hoverBG1: _lightDandelionYellow,
// tool bar hover color
hoverBG2: _lightDandelionLightYellow,
hoverBG3: _lightShader6,
hoverFG: _lightShader1,
questionBubbleBG: _lightDandelionLightYellow,
progressBarBGColor: _lightTint9,
toolbarColor: _lightShader1,
toggleButtonBGColor: _lightDandelionYellow,
calendarWeekendBGColor: const Color(0xFFFBFBFC),
gridRowCountColor: _black,
);
const DandelionColorScheme.dark()
: super(
surface: const Color(0xff292929),
hover: const Color(0xff1f1f1f),
selector: _darkShader2,
red: const Color(0xfffb006d),
yellow: const Color(0xffffd667),
green: const Color(0xff66cf80),
shader1: _white,
shader2: _darkShader2,
shader3: const Color(0xff828282),
shader4: const Color(0xffbdbdbd),
shader5: _darkShader5,
shader6: _darkShader6,
shader7: _white,
bg1: const Color(0xFFD5A200),
bg2: _black,
bg3: _darkMain1,
bg4: const Color(0xff2c144b),
tint1: const Color(0x4d9327FF),
tint2: const Color(0x66FC0088),
tint3: const Color(0x4dFC00E2),
tint4: const Color(0x80BE5B00),
tint5: const Color(0x33F8EE00),
tint6: const Color(0x4d6DC300),
tint7: const Color(0x5900BD2A),
tint8: const Color(0x80008890),
tint9: const Color(0x4d0029FF),
main1: _darkMain1,
main2: _darkMain1,
shadow: const Color(0xff0F131C),
sidebarBg: const Color(0xff25300e),
divider: _darkShader3,
topbarBg: _darkShader1,
icon: _darkShader5,
text: _darkShader5,
input: _darkInput,
hint: _darkShader5,
primary: _darkMain1,
onPrimary: _darkShader1,
hoverBG1: _darkMain1,
hoverBG2: _darkMain1,
hoverBG3: _darkShader3,
hoverFG: _darkShader1,
questionBubbleBG: _darkShader3,
progressBarBGColor: _darkShader3,
toolbarColor: _darkInput,
toggleButtonBGColor: _darkShader1,
calendarWeekendBGColor: const Color(0xff121212),
gridRowCountColor: _darkMain1,
);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/time/duration.dart
|
import 'package:time/time.dart';
export 'package:time/time.dart';
class FlowyDurations {
static Duration get fastest => .15.seconds;
static Duration get fast => .25.seconds;
static Duration get medium => .35.seconds;
static Duration get slow => .7.seconds;
}
class RouteDurations {
static Duration get slow => .7.seconds;
static Duration get medium => .35.seconds;
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/time/prelude.dart
|
export "duration.dart";
export 'package:time/time.dart';
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/utils/color_converter.dart
|
import 'package:flutter/material.dart';
import 'package:json_annotation/json_annotation.dart';
class ColorConverter implements JsonConverter<Color, String> {
const ColorConverter();
static const Color fallback = Colors.transparent;
@override
Color fromJson(String radixString) {
final int? color = int.tryParse(radixString);
return color == null ? fallback : Color(color);
}
@override
String toJson(Color color) => "0x${color.value.toRadixString(16)}";
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins/bloc/dynamic_plugin_state.dart
|
import 'package:freezed_annotation/freezed_annotation.dart';
import '../service/models/flowy_dynamic_plugin.dart';
part 'dynamic_plugin_state.freezed.dart';
@freezed
class DynamicPluginState with _$DynamicPluginState {
const factory DynamicPluginState.uninitialized() = _Uninitialized;
const factory DynamicPluginState.ready({
required Iterable<FlowyDynamicPlugin> plugins,
}) = Ready;
const factory DynamicPluginState.processing() = _Processing;
const factory DynamicPluginState.compilationFailure(
{required String errorMessage}) = _CompilationFailure;
const factory DynamicPluginState.deletionFailure({
required String path,
}) = _DeletionFailure;
const factory DynamicPluginState.deletionSuccess() = _DeletionSuccess;
const factory DynamicPluginState.compilationSuccess() = _CompilationSuccess;
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins/bloc/dynamic_plugin_event.dart
|
import 'package:freezed_annotation/freezed_annotation.dart';
part 'dynamic_plugin_event.freezed.dart';
@freezed
class DynamicPluginEvent with _$DynamicPluginEvent {
factory DynamicPluginEvent.addPlugin() = _AddPlugin;
factory DynamicPluginEvent.removePlugin({required String name}) =
_RemovePlugin;
factory DynamicPluginEvent.load() = _Load;
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins/bloc/dynamic_plugin_bloc.dart
|
import 'package:bloc/bloc.dart';
import 'package:flowy_infra/plugins/service/models/exceptions.dart';
import 'package:flowy_infra/plugins/service/plugin_service.dart';
import '../../file_picker/file_picker_impl.dart';
import 'dynamic_plugin_event.dart';
import 'dynamic_plugin_state.dart';
class DynamicPluginBloc extends Bloc<DynamicPluginEvent, DynamicPluginState> {
DynamicPluginBloc({FilePicker? filePicker})
: super(const DynamicPluginState.uninitialized()) {
on<DynamicPluginEvent>(dispatch);
add(DynamicPluginEvent.load());
}
Future<void> dispatch(
DynamicPluginEvent event, Emitter<DynamicPluginState> emit) async {
await event.when(
addPlugin: () => addPlugin(emit),
removePlugin: (name) => removePlugin(emit, name),
load: () => onLoadRequested(emit),
);
}
Future<void> onLoadRequested(Emitter<DynamicPluginState> emit) async {
emit(DynamicPluginState.ready(
plugins: await FlowyPluginService.instance.plugins));
}
Future<void> addPlugin(Emitter<DynamicPluginState> emit) async {
emit(const DynamicPluginState.processing());
try {
final plugin = await FlowyPluginService.pick();
if (plugin == null) {
emit(DynamicPluginState.ready(
plugins: await FlowyPluginService.instance.plugins));
return;
}
await FlowyPluginService.instance.addPlugin(plugin);
} on PluginCompilationException catch (exception) {
return emit(DynamicPluginState.compilationFailure(
errorMessage: exception.message));
}
emit(const DynamicPluginState.compilationSuccess());
emit(DynamicPluginState.ready(
plugins: await FlowyPluginService.instance.plugins));
}
Future<void> removePlugin(
Emitter<DynamicPluginState> emit, String name) async {
emit(const DynamicPluginState.processing());
final plugin = await FlowyPluginService.instance.lookup(name: name);
if (plugin == null) {
emit(DynamicPluginState.ready(
plugins: await FlowyPluginService.instance.plugins));
return;
}
await FlowyPluginService.removePlugin(plugin);
emit(const DynamicPluginState.deletionSuccess());
emit(
DynamicPluginState.ready(
plugins: await FlowyPluginService.instance.plugins),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins/service/plugin_service.dart
|
import 'dart:async';
import 'dart:io';
import 'package:flowy_infra/file_picker/file_picker_impl.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'location_service.dart';
import 'models/flowy_dynamic_plugin.dart';
/// A service to maintain the state of the plugins for AppFlowy.
class FlowyPluginService {
FlowyPluginService._();
static final FlowyPluginService _instance = FlowyPluginService._();
static FlowyPluginService get instance => _instance;
PluginLocationService _locationService = PluginLocationService(
fallback: getApplicationDocumentsDirectory(),
);
void setLocation(PluginLocationService locationService) =>
_locationService = locationService;
Future<Iterable<Directory>> get _targets async {
final location = await _locationService.location;
final targets = location.listSync().where(FlowyDynamicPlugin.isPlugin);
return targets.map<Directory>((entity) => entity as Directory).toList();
}
/// Searches the [PluginLocationService.location] for plugins and compiles them.
Future<DynamicPluginLibrary> get plugins async {
final List<FlowyDynamicPlugin> compiled = [];
for (final src in await _targets) {
final plugin = await FlowyDynamicPlugin.decode(src: src);
compiled.add(plugin);
}
return compiled;
}
/// Chooses a plugin from the file system using FilePickerService and tries to compile it.
///
/// If the operation is cancelled or the plugin is invalid, this method will return null.
static Future<FlowyDynamicPlugin?> pick({FilePicker? service}) async {
service ??= FilePicker();
final result = await service.getDirectoryPath();
if (result == null) {
return null;
}
final directory = Directory(result);
return FlowyDynamicPlugin.decode(src: directory);
}
/// Searches the plugin registry for a plugin with the given name.
Future<FlowyDynamicPlugin?> lookup({required String name}) async {
final library = await plugins;
return library
// cast to nullable type to allow return of null if not found.
.cast<FlowyDynamicPlugin?>()
// null assert is fine here because the original list was non-nullable
.firstWhere((plugin) => plugin!.name == name, orElse: () => null);
}
/// Adds a plugin to the registry. To construct a [FlowyDynamicPlugin]
/// use [FlowyDynamicPlugin.encode()]
Future<void> addPlugin(FlowyDynamicPlugin plugin) async {
// try to compile the plugin before we add it to the registry.
final source = await plugin.encode();
// add the plugin to the registry
final destionation = [
(await _locationService.location).path,
p.basename(source.path),
].join(Platform.pathSeparator);
_copyDirectorySync(source, Directory(destionation));
}
/// Removes a plugin from the registry.
static Future<void> removePlugin(FlowyDynamicPlugin plugin) async {
final target = plugin.source;
await target.delete(recursive: true);
}
static void _copyDirectorySync(Directory source, Directory destination) {
if (!destination.existsSync()) {
destination.createSync(recursive: true);
}
for (final child in source.listSync(recursive: false)) {
final newPath = p.join(destination.path, p.basename(child.path));
if (child is File) {
File(newPath)
..createSync(recursive: true)
..writeAsStringSync(child.readAsStringSync());
} else if (child is Directory) {
_copyDirectorySync(child, Directory(newPath));
}
}
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins/service/location_service.dart
|
import 'dart:io';
class PluginLocationService {
const PluginLocationService({
required Future<Directory> fallback,
}) : _fallback = fallback;
final Future<Directory> _fallback;
Future<Directory> get fallback async => _fallback;
Future<Directory> get location async => fallback;
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins/service
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins/service/models/flowy_dynamic_plugin.dart
|
import 'dart:convert';
import 'dart:io';
import 'package:file/memory.dart';
import 'package:flowy_infra/colorscheme/colorscheme.dart';
import 'package:flowy_infra/plugins/service/models/exceptions.dart';
import 'package:flowy_infra/theme.dart';
import 'package:path/path.dart' as p;
import 'plugin_type.dart';
typedef DynamicPluginLibrary = Iterable<FlowyDynamicPlugin>;
/// A class that encapsulates dynamically loaded plugins for AppFlowy.
///
/// This class can be modified to support loading node widget builders and other
/// plugins that are dynamically loaded at runtime for the editor. For now,
/// it only supports loading app themes.
class FlowyDynamicPlugin {
FlowyDynamicPlugin._({
required String name,
required String path,
this.theme,
}) : _name = name,
_path = path;
/// The plugins should be loaded into a folder with the extension `.flowy_plugin`.
static bool isPlugin(FileSystemEntity entity) =>
entity is Directory && p.extension(entity.path).contains(ext);
/// The extension for the plugin folder.
static const String ext = 'flowy_plugin';
static String get lightExtension => ['light', 'json'].join('.');
static String get darkExtension => ['dark', 'json'].join('.');
String get name => _name;
late final String _name;
String get _fsPluginName => [name, ext].join('.');
final AppTheme? theme;
final String _path;
Directory get source {
return Directory(_path);
}
/// Loads and "compiles" loaded plugins.
///
/// If the plugin loaded does not contain the `.flowy_plugin` extension, this
/// this method will throw an error. Likewise, if the plugin does not follow
/// the expected format, this method will throw an error.
static Future<FlowyDynamicPlugin> decode({required Directory src}) async {
// throw an error if the plugin does not follow the proper format.
if (!isPlugin(src)) {
throw PluginCompilationException(
'The plugin directory must have the extension `.flowy_plugin`.',
);
}
// throws an error if the plugin does not follow the proper format.
final type = PluginType.from(src: src);
switch (type) {
case PluginType.theme:
return _theme(src: src);
}
}
/// Encodes the plugin in memory. The Directory given is not the actual
/// directory on the file system, but rather a virtual directory in memory.
///
/// Instances of this class should always have a path on disk, otherwise a
/// compilation error will be thrown during the construction of this object.
Future<Directory> encode() async {
final fs = MemoryFileSystem();
final directory = fs.directory(_fsPluginName)..createSync();
final lightThemeFileName = '$name.$lightExtension';
directory.childFile(lightThemeFileName).createSync();
directory
.childFile(lightThemeFileName)
.writeAsStringSync(jsonEncode(theme!.lightTheme.toJson()));
final darkThemeFileName = '$name.$darkExtension';
directory.childFile(darkThemeFileName).createSync();
directory
.childFile(darkThemeFileName)
.writeAsStringSync(jsonEncode(theme!.darkTheme.toJson()));
return directory;
}
/// Theme plugins should have the following format.
/// > directory.flowy_plugin // plugin root
/// > - theme.light.json // the light theme
/// > - theme.dark.json // the dark theme
///
/// If the theme does not adhere to that format, it is considered an error.
static Future<FlowyDynamicPlugin> _theme({required Directory src}) async {
late final String name;
try {
name = p.basenameWithoutExtension(src.path).split('.').first;
} catch (e) {
throw PluginCompilationException(
'The theme plugin does not adhere to the following format: `<plugin_name>.flowy_plugin`.',
);
}
final light = src
.listSync()
.where((event) =>
event is File && p.basename(event.path).contains(lightExtension))
.first as File;
final dark = src
.listSync()
.where((event) =>
event is File && p.basename(event.path).contains(darkExtension))
.first as File;
late final FlowyColorScheme lightTheme;
late final FlowyColorScheme darkTheme;
try {
lightTheme = FlowyColorScheme.fromJson(
await jsonDecode(await light.readAsString()));
} catch (e) {
throw PluginCompilationException(
'The light theme json file is not valid.',
);
}
try {
darkTheme = FlowyColorScheme.fromJson(
await jsonDecode(await dark.readAsString()));
} catch (e) {
throw PluginCompilationException(
'The dark theme json file is not valid.',
);
}
final theme = AppTheme(
themeName: name,
builtIn: false,
lightTheme: lightTheme,
darkTheme: darkTheme,
);
return FlowyDynamicPlugin._(
name: theme.themeName,
path: src.path,
theme: theme,
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins/service
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins/service/models/exceptions.dart
|
class PluginCompilationException implements Exception {
final String message;
PluginCompilationException(this.message);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins/service
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_infra/lib/plugins/service/models/plugin_type.dart
|
import 'dart:io';
import 'package:flowy_infra/plugins/service/models/exceptions.dart';
import 'package:flowy_infra/plugins/service/models/flowy_dynamic_plugin.dart';
import 'package:path/path.dart' as p;
enum PluginType {
theme._();
const PluginType._();
factory PluginType.from({required Directory src}) {
if (_isTheme(src)) {
return PluginType.theme;
}
throw PluginCompilationException(
'Could not determine the plugin type from source `$src`.');
}
static bool _isTheme(Directory plugin) {
final files = plugin.listSync();
return files.any((entity) =>
entity is File &&
p
.basename(entity.path)
.endsWith(FlowyDynamicPlugin.lightExtension)) &&
files.any((entity) =>
entity is File &&
p.basename(entity.path).endsWith(FlowyDynamicPlugin.darkExtension));
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/lib/ffi.dart
|
/// bindings for `libdart_ffi`
import 'dart:ffi';
import 'dart:io';
// ignore: import_of_legacy_library_into_null_safe
import 'package:ffi/ffi.dart' as ffi;
import 'package:flutter/foundation.dart' as Foundation;
// ignore_for_file: unused_import, camel_case_types, non_constant_identifier_names
final DynamicLibrary _dart_ffi_lib = _open();
/// Reference to the Dynamic Library, it should be only used for low-level access
final DynamicLibrary dl = _dart_ffi_lib;
DynamicLibrary _open() {
if (Platform.environment.containsKey('FLUTTER_TEST')) {
final prefix = "${Directory.current.path}/.sandbox";
if (Platform.isLinux)
return DynamicLibrary.open('${prefix}/libdart_ffi.so');
if (Platform.isAndroid)
return DynamicLibrary.open('${prefix}/libdart_ffi.so');
if (Platform.isMacOS)
return DynamicLibrary.open('${prefix}/libdart_ffi.dylib');
if (Platform.isIOS) return DynamicLibrary.open('${prefix}/libdart_ffi.a');
if (Platform.isWindows)
return DynamicLibrary.open('${prefix}/dart_ffi.dll');
} else {
if (Platform.isLinux) return DynamicLibrary.open('libdart_ffi.so');
if (Platform.isAndroid) return DynamicLibrary.open('libdart_ffi.so');
if (Platform.isMacOS) return DynamicLibrary.executable();
if (Platform.isIOS) return DynamicLibrary.executable();
if (Platform.isWindows) return DynamicLibrary.open('dart_ffi.dll');
}
throw UnsupportedError('This platform is not supported.');
}
/// C function `async_event`.
void async_event(
int port,
Pointer<Uint8> input,
int len,
) {
_invoke_async(port, input, len);
}
final _invoke_async_Dart _invoke_async = _dart_ffi_lib
.lookupFunction<_invoke_async_C, _invoke_async_Dart>('async_event');
typedef _invoke_async_C = Void Function(
Int64 port,
Pointer<Uint8> input,
Uint64 len,
);
typedef _invoke_async_Dart = void Function(
int port,
Pointer<Uint8> input,
int len,
);
/// C function `sync_event`.
Pointer<Uint8> sync_event(
Pointer<Uint8> input,
int len,
) {
return _invoke_sync(input, len);
}
final _invoke_sync_Dart _invoke_sync = _dart_ffi_lib
.lookupFunction<_invoke_sync_C, _invoke_sync_Dart>('sync_event');
typedef _invoke_sync_C = Pointer<Uint8> Function(
Pointer<Uint8> input,
Uint64 len,
);
typedef _invoke_sync_Dart = Pointer<Uint8> Function(
Pointer<Uint8> input,
int len,
);
/// C function `init_sdk`.
int init_sdk(
int port,
Pointer<ffi.Utf8> data,
) {
return _init_sdk(port, data);
}
final _init_sdk_Dart _init_sdk =
_dart_ffi_lib.lookupFunction<_init_sdk_C, _init_sdk_Dart>('init_sdk');
typedef _init_sdk_C = Int64 Function(
Int64 port,
Pointer<ffi.Utf8> path,
);
typedef _init_sdk_Dart = int Function(
int port,
Pointer<ffi.Utf8> path,
);
/// C function `init_stream`.
int set_stream_port(int port) {
return _set_stream_port(port);
}
final _set_stream_port_Dart _set_stream_port =
_dart_ffi_lib.lookupFunction<_set_stream_port_C, _set_stream_port_Dart>(
'set_stream_port');
typedef _set_stream_port_C = Int32 Function(
Int64 port,
);
typedef _set_stream_port_Dart = int Function(
int port,
);
/// C function `set log stream port`.
int set_log_stream_port(int port) {
return _set_log_stream_port(port);
}
final _set_log_stream_port_Dart _set_log_stream_port = _dart_ffi_lib
.lookupFunction<_set_log_stream_port_C, _set_log_stream_port_Dart>(
'set_log_stream_port');
typedef _set_log_stream_port_C = Int32 Function(
Int64 port,
);
typedef _set_log_stream_port_Dart = int Function(
int port,
);
/// C function `link_me_please`.
void link_me_please() {
_link_me_please();
}
final _link_me_please_Dart _link_me_please = _dart_ffi_lib
.lookupFunction<_link_me_please_C, _link_me_please_Dart>('link_me_please');
typedef _link_me_please_C = Void Function();
typedef _link_me_please_Dart = void Function();
/// Binding to `allo-isolate` crate
void store_dart_post_cobject(
Pointer<NativeFunction<Int8 Function(Int64, Pointer<Dart_CObject>)>> ptr,
) {
_store_dart_post_cobject(ptr);
}
final _store_dart_post_cobject_Dart _store_dart_post_cobject = _dart_ffi_lib
.lookupFunction<_store_dart_post_cobject_C, _store_dart_post_cobject_Dart>(
'store_dart_post_cobject');
typedef _store_dart_post_cobject_C = Void Function(
Pointer<NativeFunction<Int8 Function(Int64, Pointer<Dart_CObject>)>> ptr,
);
typedef _store_dart_post_cobject_Dart = void Function(
Pointer<NativeFunction<Int8 Function(Int64, Pointer<Dart_CObject>)>> ptr,
);
void rust_log(
int level,
Pointer<ffi.Utf8> data,
) {
_invoke_rust_log(level, data);
}
final _invoke_rust_log_Dart _invoke_rust_log = _dart_ffi_lib
.lookupFunction<_invoke_rust_log_C, _invoke_rust_log_Dart>('rust_log');
typedef _invoke_rust_log_C = Void Function(
Int64 level,
Pointer<ffi.Utf8> data,
);
typedef _invoke_rust_log_Dart = void Function(
int level,
Pointer<ffi.Utf8>,
);
/// C function `set_env`.
void set_env(
Pointer<ffi.Utf8> data,
) {
_set_env(data);
}
final _set_env_Dart _set_env =
_dart_ffi_lib.lookupFunction<_set_env_C, _set_env_Dart>('set_env');
typedef _set_env_C = Void Function(
Pointer<ffi.Utf8> data,
);
typedef _set_env_Dart = void Function(
Pointer<ffi.Utf8> data,
);
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/lib/rust_stream.dart
|
import 'dart:async';
import 'dart:ffi';
import 'dart:isolate';
import 'dart:typed_data';
import 'package:appflowy_backend/log.dart';
import 'protobuf/flowy-notification/subject.pb.dart';
typedef ObserverCallback = void Function(SubscribeObject observable);
class RustStreamReceiver {
static RustStreamReceiver shared = RustStreamReceiver._internal();
late RawReceivePort _ffiPort;
late StreamController<Uint8List> _streamController;
late StreamController<SubscribeObject> _observableController;
late StreamSubscription<Uint8List> _ffiSubscription;
int get port => _ffiPort.sendPort.nativePort;
StreamController<SubscribeObject> get observable => _observableController;
RustStreamReceiver._internal() {
_ffiPort = RawReceivePort();
_streamController = StreamController();
_observableController = StreamController.broadcast();
_ffiPort.handler = _streamController.add;
_ffiSubscription = _streamController.stream.listen(_streamCallback);
}
factory RustStreamReceiver() {
return shared;
}
static StreamSubscription<SubscribeObject> listen(
void Function(SubscribeObject subject) callback) {
return RustStreamReceiver.shared.observable.stream.listen(callback);
}
void _streamCallback(Uint8List bytes) {
try {
final observable = SubscribeObject.fromBuffer(bytes);
_observableController.add(observable);
} catch (e, s) {
Log.error(
'RustStreamReceiver SubscribeObject deserialize error: ${e.runtimeType}');
Log.error('Stack trace \n $s');
rethrow;
}
}
Future<void> dispose() async {
await _ffiSubscription.cancel();
await _streamController.close();
await _observableController.close();
_ffiPort.close();
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/lib/log.dart
|
// ignore: import_of_legacy_library_into_null_safe
import 'dart:ffi';
import 'package:ffi/ffi.dart' as ffi;
import 'package:flutter/foundation.dart';
import 'package:logger/logger.dart';
import 'ffi.dart';
class Log {
static final shared = Log();
// ignore: unused_field
late Logger _logger;
Log() {
_logger = Logger(
printer: PrettyPrinter(
methodCount: 2, // number of method calls to be displayed
errorMethodCount: 8, // number of method calls if stacktrace is provided
lineLength: 120, // width of the output
colors: true, // Colorful log messages
printEmojis: true, // Print an emoji for each log message
printTime: false, // Should each log print contain a timestamp
),
level: kDebugMode ? Level.trace : Level.info,
);
}
static void info(dynamic msg, [dynamic error, StackTrace? stackTrace]) {
rust_log(0, toNativeUtf8(msg));
}
static void debug(dynamic msg, [dynamic error, StackTrace? stackTrace]) {
rust_log(1, toNativeUtf8(msg));
}
static void warn(dynamic msg, [dynamic error, StackTrace? stackTrace]) {
rust_log(3, toNativeUtf8(msg));
}
static void trace(dynamic msg, [dynamic error, StackTrace? stackTrace]) {
rust_log(2, toNativeUtf8(msg));
}
static void error(dynamic msg, [dynamic error, StackTrace? stackTrace]) {
rust_log(4, toNativeUtf8(msg));
}
}
bool isReleaseVersion() {
return kReleaseMode;
}
Pointer<ffi.Utf8> toNativeUtf8(dynamic msg) {
return "$msg".toNativeUtf8();
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/lib/appflowy_backend_method_channel.dart
|
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'appflowy_backend_platform_interface.dart';
/// An implementation of [AppFlowyBackendPlatform] that uses method channels.
class MethodChannelFlowySdk extends AppFlowyBackendPlatform {
/// The method channel used to interact with the native platform.
@visibleForTesting
final methodChannel = const MethodChannel('appflowy_backend');
@override
Future<String?> getPlatformVersion() async {
final version =
await methodChannel.invokeMethod<String>('getPlatformVersion');
return version;
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/lib/appflowy_backend.dart
|
export 'package:async/async.dart';
import 'dart:async';
import 'dart:convert';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'dart:ffi';
import 'ffi.dart' as ffi;
import 'package:ffi/ffi.dart';
import 'dart:isolate';
import 'dart:io';
import 'package:logger/logger.dart';
enum ExceptionType {
AppearanceSettingsIsEmpty,
}
class FlowySDKException implements Exception {
ExceptionType type;
FlowySDKException(this.type);
}
class FlowySDK {
static const MethodChannel _channel = MethodChannel('appflowy_backend');
static Future<String> get platformVersion async {
final String version = await _channel.invokeMethod('getPlatformVersion');
return version;
}
FlowySDK();
Future<void> dispose() async {}
Future<void> init(String configuration) async {
ffi.set_stream_port(RustStreamReceiver.shared.port);
ffi.store_dart_post_cobject(NativeApi.postCObject);
// On iOS, VSCode can't print logs from Rust, so we need to use a different method to print logs.
// So we use a shared port to receive logs from Rust and print them using the logger. In release mode, we don't print logs.
if (Platform.isIOS && kDebugMode) {
ffi.set_log_stream_port(RustLogStreamReceiver.logShared.port);
}
// final completer = Completer<Uint8List>();
// // Create a SendPort that accepts only one message.
// final sendPort = singleCompletePort(completer);
final code = ffi.init_sdk(0, configuration.toNativeUtf8());
if (code != 0) {
throw Exception('Failed to initialize the SDK');
}
// return completer.future;
}
}
class RustLogStreamReceiver {
static RustLogStreamReceiver logShared = RustLogStreamReceiver._internal();
late RawReceivePort _ffiPort;
late StreamController<Uint8List> _streamController;
late StreamSubscription<Uint8List> _subscription;
int get port => _ffiPort.sendPort.nativePort;
late Logger _logger;
RustLogStreamReceiver._internal() {
_ffiPort = RawReceivePort();
_streamController = StreamController();
_ffiPort.handler = _streamController.add;
_logger = Logger(
printer: PrettyPrinter(
methodCount: 0, // number of method calls to be displayed
errorMethodCount: 8, // number of method calls if stacktrace is provided
lineLength: 120, // width of the output
colors: false, // Colorful log messages
printEmojis: false, // Print an emoji for each log message
printTime: false, // Should each log print contain a timestamp
),
level: kDebugMode ? Level.trace : Level.info,
);
_subscription = _streamController.stream.listen((data) {
String decodedString = utf8.decode(data);
_logger.i(decodedString);
});
}
factory RustLogStreamReceiver() {
return logShared;
}
Future<void> dispose() async {
await _streamController.close();
await _subscription.cancel();
_ffiPort.close();
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/lib/appflowy_backend_platform_interface.dart
|
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'appflowy_backend_method_channel.dart';
abstract class AppFlowyBackendPlatform extends PlatformInterface {
/// Constructs a FlowySdkPlatform.
AppFlowyBackendPlatform() : super(token: _token);
static final Object _token = Object();
static AppFlowyBackendPlatform _instance = MethodChannelFlowySdk();
/// The default instance of [AppFlowyBackendPlatform] to use.
///
/// Defaults to [MethodChannelFlowySdk].
static AppFlowyBackendPlatform get instance => _instance;
/// Platform-specific implementations should set this with their own
/// platform-specific class that extends [AppFlowyBackendPlatform] when
/// they register themselves.
static set instance(AppFlowyBackendPlatform instance) {
PlatformInterface.verifyToken(instance, _token);
_instance = instance;
}
Future<String?> getPlatformVersion() {
throw UnimplementedError('platformVersion() has not been implemented.');
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/lib/dispatch/error.dart
|
import 'package:appflowy_backend/protobuf/dart-ffi/protobuf.dart';
class FlowyInternalError {
late FFIStatusCode _statusCode;
late String _error;
FFIStatusCode get statusCode {
return _statusCode;
}
String get error {
return _error;
}
bool get has_error {
return _statusCode != FFIStatusCode.Ok;
}
String toString() {
return "$_statusCode: $_error";
}
FlowyInternalError(
{required FFIStatusCode statusCode, required String error}) {
_statusCode = statusCode;
_error = error;
}
factory FlowyInternalError.from(FFIResponse resp) {
return FlowyInternalError(statusCode: resp.code, error: "");
}
}
class StackTraceError {
Object error;
StackTrace trace;
StackTraceError(
this.error,
this.trace,
);
FlowyInternalError asFlowyError() {
return FlowyInternalError(
statusCode: FFIStatusCode.Err, error: this.toString());
}
String toString() {
return '${error.runtimeType}. Stack trace: $trace';
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/lib
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/lib/dispatch/dispatch.dart
|
import 'dart:async';
import 'dart:convert' show utf8;
import 'dart:ffi';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:appflowy_backend/ffi.dart' as ffi;
import 'package:appflowy_backend/log.dart';
// ignore: unnecessary_import
import 'package:appflowy_backend/protobuf/dart-ffi/ffi_response.pb.dart';
import 'package:appflowy_backend/protobuf/dart-ffi/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-document/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:ffi/ffi.dart';
import 'package:isolates/isolates.dart';
import 'package:isolates/ports.dart';
import 'package:protobuf/protobuf.dart';
import '../protobuf/flowy-config/entities.pb.dart';
import '../protobuf/flowy-config/event_map.pb.dart';
import '../protobuf/flowy-date/entities.pb.dart';
import '../protobuf/flowy-date/event_map.pb.dart';
import '../protobuf/flowy-search/entities.pb.dart';
import '../protobuf/flowy-search/event_map.pb.dart';
import 'error.dart';
part 'dart_event/flowy-folder/dart_event.dart';
part 'dart_event/flowy-user/dart_event.dart';
part 'dart_event/flowy-database2/dart_event.dart';
part 'dart_event/flowy-document/dart_event.dart';
part 'dart_event/flowy-config/dart_event.dart';
part 'dart_event/flowy-date/dart_event.dart';
part 'dart_event/flowy-search/dart_event.dart';
enum FFIException {
RequestIsEmpty,
}
class DispatchException implements Exception {
FFIException type;
DispatchException(this.type);
}
class Dispatch {
static Future<FlowyResult<Uint8List, Uint8List>> asyncRequest(
FFIRequest request) {
// FFIRequest => Rust SDK
final bytesFuture = _sendToRust(request);
// Rust SDK => FFIResponse
final responseFuture = _extractResponse(bytesFuture);
// FFIResponse's payload is the bytes of the Response object
final payloadFuture = _extractPayload(responseFuture);
return payloadFuture;
}
}
Future<FlowyResult<Uint8List, Uint8List>> _extractPayload(
Future<FlowyResult<FFIResponse, FlowyInternalError>> responseFuture) {
return responseFuture.then((result) {
return result.fold(
(response) {
switch (response.code) {
case FFIStatusCode.Ok:
return FlowySuccess(Uint8List.fromList(response.payload));
case FFIStatusCode.Err:
return FlowyFailure(Uint8List.fromList(response.payload));
case FFIStatusCode.Internal:
final error = utf8.decode(response.payload);
Log.error("Dispatch internal error: $error");
return FlowyFailure(emptyBytes());
default:
Log.error("Impossible to here");
return FlowyFailure(emptyBytes());
}
},
(error) {
Log.error("Response should not be empty $error");
return FlowyFailure(emptyBytes());
},
);
});
}
Future<FlowyResult<FFIResponse, FlowyInternalError>> _extractResponse(
Completer<Uint8List> bytesFuture) {
return bytesFuture.future.then((bytes) {
try {
final response = FFIResponse.fromBuffer(bytes);
return FlowySuccess(response);
} catch (e, s) {
final error = StackTraceError(e, s);
Log.error('Deserialize response failed. ${error.toString()}');
return FlowyFailure(error.asFlowyError());
}
});
}
Completer<Uint8List> _sendToRust(FFIRequest request) {
Uint8List bytes = request.writeToBuffer();
assert(bytes.isEmpty == false);
if (bytes.isEmpty) {
throw DispatchException(FFIException.RequestIsEmpty);
}
final Pointer<Uint8> input = calloc.allocate<Uint8>(bytes.length);
final list = input.asTypedList(bytes.length);
list.setAll(0, bytes);
final completer = Completer<Uint8List>();
final port = singleCompletePort(completer);
ffi.async_event(port.nativePort, input, bytes.length);
calloc.free(input);
return completer;
}
Uint8List requestToBytes<T extends GeneratedMessage>(T? message) {
try {
if (message != null) {
return message.writeToBuffer();
} else {
return emptyBytes();
}
} catch (e, s) {
final error = StackTraceError(e, s);
Log.error('Serial request failed. ${error.toString()}');
return emptyBytes();
}
}
Uint8List emptyBytes() {
return Uint8List.fromList([]);
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/test/appflowy_backend_test.dart
|
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:appflowy_backend/appflowy_backend.dart';
void main() {
const MethodChannel channel = MethodChannel('appflowy_backend');
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall methodCall) async {
return '42';
});
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
channel,
null,
);
});
test('getPlatformVersion', () async {
expect(await FlowySDK.platformVersion, '42');
});
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/test/appflowy_backend_method_channel_test.dart
|
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:appflowy_backend/appflowy_backend_method_channel.dart';
void main() {
MethodChannelFlowySdk platform = MethodChannelFlowySdk();
const MethodChannel channel = MethodChannel('appflowy_backend');
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
channel,
(MethodCall methodCall) async {
return '42';
},
);
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
channel,
null,
);
});
test('getPlatformVersion', () async {
expect(await platform.getPlatformVersion(), '42');
});
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/example
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/example/lib/main.dart
|
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:appflowy_backend/appflowy_backend.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
@override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await FlowySDK.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Text('Running on: $_platformVersion\n'),
),
),
);
}
}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/example
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/example/integration_test/driver.dart
|
// This file is provided as a convenience for running integration tests via the
// flutter drive command.
//
// flutter drive --driver integration_test/driver.dart --target integration_test/app_test.dart
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/example
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/example/integration_test/app_test.dart
|
// This is a basic Flutter integration test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
// import 'package:flutter/material.dart';
// import 'package:flutter_test/flutter_test.dart';
// import 'package:integration_test/integration_test.dart';
// import 'package:flowy_sdk_example/main.dart' as app;
// void main() => run(_testMain);
// void _testMain() {
// testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// // Build our app and trigger a frame.
// app.main();
// // Trigger a frame.
// await tester.pumpAndSettle();
// // Verify that platform version is retrieved.
// expect(
// find.byWidgetPredicate(
// (Widget widget) => widget is Text &&
// widget.data.startsWith('Running on:'),
// ),
// findsOneWidget,
// );
// });
// }
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/example
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_backend/example/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
void main() {}
| 0
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/lib/appflowy_popover.dart
|
/// AppFlowyBoard library
library appflowy_popover;
export 'src/mutex.dart';
export 'src/popover.dart';
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.