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/lib/workspace/presentation/home/menu/sidebar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/import/import_panel.dart | import 'dart:convert';
import 'dart:io';
import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/migration/editor_migration.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/settings/share/import_service.dart';
import 'package:appflowy/workspace/presentation/home/menu/sidebar/import/import_type.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:flowy_infra/file_picker/file_picker_service.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/container.dart';
import 'package:flutter/material.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
typedef ImportCallback = void Function(
ImportType type,
String name,
List<int>? document,
);
Future<void> showImportPanel(
String parentViewId,
BuildContext context,
ImportCallback callback,
) async {
await FlowyOverlay.show(
context: context,
builder: (context) => FlowyDialog(
backgroundColor: Theme.of(context).colorScheme.surface,
title: FlowyText.semibold(
LocaleKeys.moreAction_import.tr(),
fontSize: 20,
color: Theme.of(context).colorScheme.tertiary,
),
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 20.0,
),
child: ImportPanel(
parentViewId: parentViewId,
importCallback: callback,
),
),
),
);
}
class ImportPanel extends StatefulWidget {
const ImportPanel({
super.key,
required this.parentViewId,
required this.importCallback,
});
final String parentViewId;
final ImportCallback importCallback;
@override
State<ImportPanel> createState() => _ImportPanelState();
}
class _ImportPanelState extends State<ImportPanel> {
final flowyContainerFocusNode = FocusNode();
@override
void dispose() {
flowyContainerFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width * 0.7;
final height = width * 0.5;
return KeyboardListener(
autofocus: true,
focusNode: flowyContainerFocusNode,
onKeyEvent: (event) {
if (event is KeyDownEvent &&
event.physicalKey == PhysicalKeyboardKey.escape) {
FlowyOverlay.pop(context);
}
},
child: FlowyContainer(
Theme.of(context).colorScheme.surface,
height: height,
width: width,
child: GridView.count(
childAspectRatio: 1 / .2,
crossAxisCount: 2,
children: ImportType.values
.where((element) => element.enableOnRelease)
.map(
(e) => Card(
child: FlowyButton(
leftIcon: e.icon(context),
leftIconSize: const Size.square(20),
text: FlowyText.medium(
e.toString(),
fontSize: 15,
overflow: TextOverflow.ellipsis,
color: Theme.of(context).colorScheme.tertiary,
),
onTap: () async {
await _importFile(widget.parentViewId, e);
if (context.mounted) {
FlowyOverlay.pop(context);
}
},
),
),
)
.toList(),
),
),
);
}
Future<void> _importFile(String parentViewId, ImportType importType) async {
final result = await getIt<FilePickerService>().pickFiles(
type: FileType.custom,
allowMultiple: importType.allowMultiSelect,
allowedExtensions: importType.allowedExtensions,
);
if (result == null || result.files.isEmpty) {
return;
}
for (final file in result.files) {
final path = file.path;
if (path == null) {
continue;
}
final data = await File(path).readAsString();
final name = p.basenameWithoutExtension(path);
switch (importType) {
case ImportType.markdownOrText:
case ImportType.historyDocument:
final bytes = _documentDataFrom(importType, data);
if (bytes != null) {
await ImportBackendService.importData(
bytes,
name,
parentViewId,
ImportTypePB.HistoryDocument,
);
}
break;
case ImportType.historyDatabase:
await ImportBackendService.importData(
utf8.encode(data),
name,
parentViewId,
ImportTypePB.HistoryDatabase,
);
break;
case ImportType.databaseRawData:
await ImportBackendService.importData(
utf8.encode(data),
name,
parentViewId,
ImportTypePB.RawDatabase,
);
break;
case ImportType.databaseCSV:
await ImportBackendService.importData(
utf8.encode(data),
name,
parentViewId,
ImportTypePB.CSV,
);
break;
default:
assert(false, 'Unsupported Type $importType');
}
}
widget.importCallback(importType, '', null);
}
}
Uint8List? _documentDataFrom(ImportType importType, String data) {
switch (importType) {
case ImportType.markdownOrText:
final document = markdownToDocument(data);
return DocumentDataPBFromTo.fromDocument(document)?.writeToBuffer();
case ImportType.historyDocument:
final document = EditorMigration.migrateDocument(data);
return DocumentDataPBFromTo.fromDocument(document)?.writeToBuffer();
default:
assert(false, 'Unsupported Type $importType');
return null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_actions.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/shared/af_role_pb_extension.dart';
import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/members/workspace_member_bloc.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
enum WorkspaceMoreAction {
rename,
delete,
leave,
}
class WorkspaceMoreActionList extends StatelessWidget {
const WorkspaceMoreActionList({
super.key,
required this.workspace,
});
final UserWorkspacePB workspace;
@override
Widget build(BuildContext context) {
final myRole = context.read<WorkspaceMemberBloc>().state.myRole;
final actions = [];
if (myRole.isOwner) {
actions.add(WorkspaceMoreAction.rename);
actions.add(WorkspaceMoreAction.delete);
} else if (myRole.canLeave) {
actions.add(WorkspaceMoreAction.leave);
}
if (actions.isEmpty) {
return const SizedBox.shrink();
}
return PopoverActionList<_WorkspaceMoreActionWrapper>(
direction: PopoverDirection.bottomWithCenterAligned,
actions: actions
.map((e) => _WorkspaceMoreActionWrapper(e, workspace))
.toList(),
buildChild: (controller) {
return FlowyButton(
margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
useIntrinsicWidth: true,
text: const FlowySvg(
FlowySvgs.three_dots_vertical_s,
),
onTap: () {
controller.show();
},
);
},
onSelected: (action, controller) {},
);
}
}
class _WorkspaceMoreActionWrapper extends CustomActionCell {
_WorkspaceMoreActionWrapper(this.inner, this.workspace);
final WorkspaceMoreAction inner;
final UserWorkspacePB workspace;
@override
Widget buildWithContext(BuildContext context) {
return FlowyButton(
text: FlowyText(
name,
color: inner == WorkspaceMoreAction.delete
? Theme.of(context).colorScheme.error
: null,
),
margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 6.0),
onTap: () async {
PopoverContainer.of(context).closeAll();
final workspaceBloc = context.read<UserWorkspaceBloc>();
switch (inner) {
case WorkspaceMoreAction.delete:
await NavigatorAlertDialog(
title: LocaleKeys.workspace_deleteWorkspaceHintText.tr(),
confirm: () {
workspaceBloc.add(
UserWorkspaceEvent.deleteWorkspace(workspace.workspaceId),
);
},
).show(context);
case WorkspaceMoreAction.rename:
await NavigatorTextFieldDialog(
title: LocaleKeys.workspace_create.tr(),
value: workspace.name,
hintText: '',
autoSelectAllText: true,
onConfirm: (name, context) async {
workspaceBloc.add(
UserWorkspaceEvent.renameWorkspace(
workspace.workspaceId,
name,
),
);
},
).show(context);
case WorkspaceMoreAction.leave:
await showDialog(
context: context,
builder: (_) => NavigatorOkCancelDialog(
message: LocaleKeys.workspace_leaveCurrentWorkspacePrompt.tr(),
onOkPressed: () {
workspaceBloc.add(
UserWorkspaceEvent.leaveWorkspace(workspace.workspaceId),
);
},
okTitle: LocaleKeys.button_yes.tr(),
),
);
}
},
);
}
String get name {
switch (inner) {
case WorkspaceMoreAction.delete:
return LocaleKeys.button_delete.tr();
case WorkspaceMoreAction.rename:
return LocaleKeys.button_rename.tr();
case WorkspaceMoreAction.leave:
return LocaleKeys.workspace_leaveCurrentWorkspace.tr();
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_menu.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_actions.dart';
import 'package:appflowy/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_icon.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/members/workspace_member_bloc.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@visibleForTesting
const createWorkspaceButtonKey = ValueKey('createWorkspaceButton');
class WorkspacesMenu extends StatelessWidget {
const WorkspacesMenu({
super.key,
required this.userProfile,
required this.currentWorkspace,
required this.workspaces,
});
final UserProfilePB userProfile;
final UserWorkspacePB currentWorkspace;
final List<UserWorkspacePB> workspaces;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// user email
Padding(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
child: Row(
children: [
Expanded(
child: FlowyText.medium(
_getUserInfo(),
fontSize: 12.0,
overflow: TextOverflow.ellipsis,
color: Theme.of(context).hintColor,
),
),
const HSpace(4.0),
FlowyButton(
key: createWorkspaceButtonKey,
useIntrinsicWidth: true,
text: const FlowySvg(FlowySvgs.add_m),
onTap: () {
_showCreateWorkspaceDialog(context);
PopoverContainer.of(context).closeAll();
},
),
],
),
),
for (final workspace in workspaces) ...[
WorkspaceMenuItem(
key: ValueKey(workspace.workspaceId),
workspace: workspace,
userProfile: userProfile,
isSelected: workspace.workspaceId == currentWorkspace.workspaceId,
),
const VSpace(4.0),
],
],
);
}
String _getUserInfo() {
if (userProfile.email.isNotEmpty) {
return userProfile.email;
}
if (userProfile.name.isNotEmpty) {
return userProfile.name;
}
return LocaleKeys.defaultUsername.tr();
}
Future<void> _showCreateWorkspaceDialog(BuildContext context) async {
if (context.mounted) {
final workspaceBloc = context.read<UserWorkspaceBloc>();
await CreateWorkspaceDialog(
onConfirm: (name) {
workspaceBloc.add(UserWorkspaceEvent.createWorkspace(name));
},
).show(context);
}
}
}
class WorkspaceMenuItem extends StatelessWidget {
const WorkspaceMenuItem({
super.key,
required this.workspace,
required this.userProfile,
required this.isSelected,
});
final UserProfilePB userProfile;
final UserWorkspacePB workspace;
final bool isSelected;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) =>
WorkspaceMemberBloc(userProfile: userProfile, workspace: workspace)
..add(const WorkspaceMemberEvent.initial()),
child: BlocBuilder<WorkspaceMemberBloc, WorkspaceMemberState>(
builder: (context, state) {
final members = state.members;
// settings right icon inside the flowy button will
// cause the popover dismiss intermediately when click the right icon.
// so using the stack to put the right icon on the flowy button.
return SizedBox(
height: 52,
child: Stack(
alignment: Alignment.center,
children: [
FlowyButton(
onTap: () {
if (!isSelected) {
context.read<UserWorkspaceBloc>().add(
UserWorkspaceEvent.openWorkspace(
workspace.workspaceId,
),
);
PopoverContainer.of(context).closeAll();
}
},
margin: const EdgeInsets.symmetric(
vertical: 8,
horizontal: 12,
),
iconPadding: 10.0,
leftIconSize: const Size.square(32),
leftIcon: const SizedBox.square(
dimension: 32,
),
rightIcon: const HSpace(42.0),
text: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlowyText.medium(
workspace.name,
fontSize: 14.0,
overflow: TextOverflow.ellipsis,
withTooltip: true,
),
FlowyText(
state.isLoading
? ''
: LocaleKeys
.settings_appearance_members_membersCount
.plural(
members.length,
),
fontSize: 10.0,
color: Theme.of(context).hintColor,
),
],
),
),
Positioned(
left: 8,
child: SizedBox.square(
dimension: 32,
child: FlowyTooltip(
message:
LocaleKeys.document_plugins_cover_changeIcon.tr(),
child: WorkspaceIcon(
workspace: workspace,
iconSize: 26,
enableEdit: true,
),
),
),
),
Positioned(
right: 12.0,
child: Align(
child: _buildRightIcon(context),
),
),
],
),
);
},
),
);
}
Widget _buildRightIcon(BuildContext context) {
// only the owner can update or delete workspace.
// only show the more action button when the workspace is selected.
if (!isSelected || context.read<WorkspaceMemberBloc>().state.isLoading) {
return const SizedBox.shrink();
}
return Row(
children: [
WorkspaceMoreActionList(workspace: workspace),
const FlowySvg(
FlowySvgs.blue_check_s,
),
],
);
}
}
class CreateWorkspaceDialog extends StatelessWidget {
const CreateWorkspaceDialog({
super.key,
required this.onConfirm,
});
final void Function(String name) onConfirm;
@override
Widget build(BuildContext context) {
return NavigatorTextFieldDialog(
title: LocaleKeys.workspace_create.tr(),
value: '',
hintText: '',
autoSelectAllText: true,
onConfirm: (name, _) => onConfirm(name),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/workspace/_sidebar_workspace_icon.dart | import 'dart:math';
import 'package:appflowy/plugins/base/icon/icon_picker.dart';
import 'package:appflowy/util/color_generator/color_generator.dart';
import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class WorkspaceIcon extends StatefulWidget {
const WorkspaceIcon({
super.key,
required this.enableEdit,
required this.iconSize,
required this.workspace,
});
final UserWorkspacePB workspace;
final double iconSize;
final bool enableEdit;
@override
State<WorkspaceIcon> createState() => _WorkspaceIconState();
}
class _WorkspaceIconState extends State<WorkspaceIcon> {
final controller = PopoverController();
@override
Widget build(BuildContext context) {
Widget child = widget.workspace.icon.isNotEmpty
? Container(
width: widget.iconSize,
alignment: Alignment.center,
child: FlowyText(
widget.workspace.icon,
fontSize: widget.iconSize,
),
)
: Container(
alignment: Alignment.center,
width: widget.iconSize,
height: max(widget.iconSize, 26),
decoration: BoxDecoration(
color: ColorGenerator(widget.workspace.name).toColor(),
borderRadius: BorderRadius.circular(4),
),
child: FlowyText(
widget.workspace.name.isEmpty
? ''
: widget.workspace.name.substring(0, 1),
fontSize: 16,
color: Colors.black,
),
);
if (widget.enableEdit) {
child = AppFlowyPopover(
offset: const Offset(0, 8),
controller: controller,
direction: PopoverDirection.bottomWithLeftAligned,
constraints: BoxConstraints.loose(const Size(360, 380)),
clickHandler: PopoverClickHandler.gestureDetector,
popupBuilder: (BuildContext popoverContext) {
return FlowyIconPicker(
onSelected: (result) {
context.read<UserWorkspaceBloc>().add(
UserWorkspaceEvent.updateWorkspaceIcon(
widget.workspace.workspaceId,
result.emoji,
),
);
controller.close();
},
);
},
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: child,
),
);
}
return child;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/folder/_favorite_folder.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/sidebar/folder/folder_bloc.dart';
import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart';
import 'package:appflowy/workspace/presentation/home/menu/view/view_item.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class FavoriteFolder extends StatelessWidget {
const FavoriteFolder({
super.key,
required this.views,
});
final List<ViewPB> views;
@override
Widget build(BuildContext context) {
if (views.isEmpty) {
return const SizedBox.shrink();
}
return BlocProvider<FolderBloc>(
create: (context) => FolderBloc(type: FolderCategoryType.favorite)
..add(
const FolderEvent.initial(),
),
child: BlocBuilder<FolderBloc, FolderState>(
builder: (context, state) {
return Column(
children: [
FavoriteHeader(
onPressed: () => context
.read<FolderBloc>()
.add(const FolderEvent.expandOrUnExpand()),
onAdded: () => context
.read<FolderBloc>()
.add(const FolderEvent.expandOrUnExpand(isExpanded: true)),
),
if (state.isExpanded)
...views.map(
(view) => ViewItem(
key: ValueKey(
'${FolderCategoryType.favorite.name} ${view.id}',
),
categoryType: FolderCategoryType.favorite,
isDraggable: false,
isFirstChild: view.id == views.first.id,
isFeedback: false,
view: view,
level: 0,
onSelected: (view) {
if (HardwareKeyboard.instance.isControlPressed) {
context.read<TabsBloc>().openTab(view);
}
context.read<TabsBloc>().openPlugin(view);
},
onTertiarySelected: (view) =>
context.read<TabsBloc>().openTab(view),
),
),
],
);
},
),
);
}
}
class FavoriteHeader extends StatefulWidget {
const FavoriteHeader({
super.key,
required this.onPressed,
required this.onAdded,
});
final VoidCallback onPressed;
final VoidCallback onAdded;
@override
State<FavoriteHeader> createState() => _FavoriteHeaderState();
}
class _FavoriteHeaderState extends State<FavoriteHeader> {
bool onHover = false;
@override
Widget build(BuildContext context) {
const iconSize = 26.0;
return MouseRegion(
onEnter: (event) => setState(() => onHover = true),
onExit: (event) => setState(() => onHover = false),
child: Row(
children: [
FlowyTextButton(
LocaleKeys.sideBar_favorites.tr(),
tooltip: LocaleKeys.sideBar_clickToHideFavorites.tr(),
constraints: const BoxConstraints(maxHeight: iconSize),
padding: const EdgeInsets.all(4),
fillColor: Colors.transparent,
onPressed: widget.onPressed,
),
],
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/folder/_section_folder.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/menu/sidebar_sections_bloc.dart';
import 'package:appflowy/workspace/application/sidebar/folder/folder_bloc.dart';
import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart';
import 'package:appflowy/workspace/application/user/user_workspace_bloc.dart';
import 'package:appflowy/workspace/presentation/home/menu/sidebar/folder/_folder_header.dart';
import 'package:appflowy/workspace/presentation/home/menu/sidebar/rename_view_dialog.dart';
import 'package:appflowy/workspace/presentation/home/menu/view/view_item.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SectionFolder extends StatelessWidget {
const SectionFolder({
super.key,
required this.title,
required this.categoryType,
required this.views,
this.isHoverEnabled = true,
required this.expandButtonTooltip,
required this.addButtonTooltip,
});
final String title;
final FolderCategoryType categoryType;
final List<ViewPB> views;
final bool isHoverEnabled;
final String expandButtonTooltip;
final String addButtonTooltip;
@override
Widget build(BuildContext context) {
return BlocProvider<FolderBloc>(
create: (context) => FolderBloc(type: categoryType)
..add(
const FolderEvent.initial(),
),
child: BlocBuilder<FolderBloc, FolderState>(
builder: (context, state) {
return Column(
children: [
FolderHeader(
title: title,
expandButtonTooltip: expandButtonTooltip,
addButtonTooltip: addButtonTooltip,
onPressed: () => context
.read<FolderBloc>()
.add(const FolderEvent.expandOrUnExpand()),
onAdded: () {
createViewAndShowRenameDialogIfNeeded(
context,
LocaleKeys.newPageText.tr(),
(viewName, _) {
if (viewName.isNotEmpty) {
context.read<SidebarSectionsBloc>().add(
SidebarSectionsEvent.createRootViewInSection(
name: viewName,
index: 0,
viewSection: categoryType.toViewSectionPB,
),
);
context.read<FolderBloc>().add(
const FolderEvent.expandOrUnExpand(
isExpanded: true,
),
);
}
},
);
},
),
if (state.isExpanded)
...views.map(
(view) => ViewItem(
key: ValueKey(
'${categoryType.name} ${view.id}',
),
categoryType: categoryType,
isFirstChild: view.id == views.first.id,
view: view,
level: 0,
leftPadding: 16,
isFeedback: false,
onSelected: (view) {
if (HardwareKeyboard.instance.isControlPressed) {
context.read<TabsBloc>().openTab(view);
}
context.read<TabsBloc>().openPlugin(view);
},
onTertiarySelected: (view) =>
context.read<TabsBloc>().openTab(view),
isHoverEnabled: isHoverEnabled,
),
),
if (views.isEmpty)
ViewItem(
categoryType: categoryType,
view: ViewPB(
parentViewId: context
.read<UserWorkspaceBloc>()
.state
.currentWorkspace
?.workspaceId ??
'',
),
level: 0,
leftPadding: 16,
isFeedback: false,
onSelected: (_) {},
onTertiarySelected: (_) {},
isHoverEnabled: isHoverEnabled,
isPlaceholder: true,
),
],
);
},
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/home/menu/sidebar/folder/_folder_header.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
class FolderHeader extends StatefulWidget {
const FolderHeader({
super.key,
required this.title,
required this.expandButtonTooltip,
required this.addButtonTooltip,
required this.onPressed,
required this.onAdded,
});
final String title;
final String expandButtonTooltip;
final String addButtonTooltip;
final VoidCallback onPressed;
final VoidCallback onAdded;
@override
State<FolderHeader> createState() => _FolderHeaderState();
}
class _FolderHeaderState extends State<FolderHeader> {
bool onHover = false;
@override
Widget build(BuildContext context) {
const iconSize = 26.0;
const textPadding = 4.0;
return MouseRegion(
onEnter: (event) => setState(() => onHover = true),
onExit: (event) => setState(() => onHover = false),
child: Row(
children: [
FlowyTextButton(
widget.title,
tooltip: widget.expandButtonTooltip,
constraints: const BoxConstraints(
minHeight: iconSize + textPadding * 2,
),
padding: const EdgeInsets.all(textPadding),
fillColor: Colors.transparent,
onPressed: widget.onPressed,
),
if (onHover) ...[
const Spacer(),
FlowyIconButton(
tooltipText: widget.addButtonTooltip,
hoverColor: Theme.of(context).colorScheme.secondaryContainer,
iconPadding: const EdgeInsets.all(2),
height: iconSize,
width: iconSize,
icon: const FlowySvg(FlowySvgs.add_s),
onPressed: widget.onAdded,
),
],
],
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/settings_dialog.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/settings/settings_dialog_bloc.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/feature_flags/feature_flag_page.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/members/workspace_member_page.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance_view.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_customize_shortcuts_view.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_file_system_view.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_language_view.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_menu.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_notifications_view.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_user_view.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'widgets/setting_cloud.dart';
const _dialogHorizontalPadding = EdgeInsets.symmetric(horizontal: 12);
const _contentInsetPadding = EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 16.0);
class SettingsDialog extends StatelessWidget {
SettingsDialog(
this.user, {
required this.dismissDialog,
required this.didLogout,
required this.restartApp,
}) : super(key: ValueKey(user.id));
final VoidCallback dismissDialog;
final VoidCallback didLogout;
final VoidCallback restartApp;
final UserProfilePB user;
@override
Widget build(BuildContext context) {
return BlocProvider<SettingsDialogBloc>(
create: (context) => getIt<SettingsDialogBloc>(param1: user)
..add(const SettingsDialogEvent.initial()),
child: BlocBuilder<SettingsDialogBloc, SettingsDialogState>(
builder: (context, state) => FlowyDialog(
title: Padding(
padding: _dialogHorizontalPadding + _contentInsetPadding,
child: FlowyText(
LocaleKeys.settings_title.tr(),
fontSize: 20,
fontWeight: FontWeight.w700,
color: Theme.of(context).colorScheme.tertiary,
),
),
width: MediaQuery.of(context).size.width * 0.7,
child: ScaffoldMessenger(
child: Scaffold(
backgroundColor: Colors.transparent,
body: Padding(
padding: _dialogHorizontalPadding,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 200,
child: SettingsMenu(
userProfile: user,
changeSelectedPage: (index) {
context
.read<SettingsDialogBloc>()
.add(SettingsDialogEvent.setSelectedPage(index));
},
currentPage:
context.read<SettingsDialogBloc>().state.page,
),
),
VerticalDivider(
color: Theme.of(context).dividerColor,
),
const SizedBox(width: 10),
Expanded(
child: getSettingsView(
context.read<SettingsDialogBloc>().state.page,
context.read<SettingsDialogBloc>().state.userProfile,
),
),
],
),
),
),
),
),
),
);
}
Widget getSettingsView(SettingsPage page, UserProfilePB user) {
switch (page) {
case SettingsPage.appearance:
return const SettingsAppearanceView();
case SettingsPage.language:
return const SettingsLanguageView();
case SettingsPage.files:
return const SettingsFileSystemView();
case SettingsPage.user:
return SettingsUserView(
user,
didLogin: () => dismissDialog(),
didLogout: didLogout,
didOpenUser: restartApp,
);
case SettingsPage.notifications:
return const SettingsNotificationsView();
case SettingsPage.cloud:
return SettingCloud(
restartAppFlowy: () => restartApp(),
);
case SettingsPage.shortcuts:
return const SettingsCustomizeShortcutsWrapper();
case SettingsPage.member:
return WorkspaceMembersPage(userProfile: user);
case SettingsPage.featureFlags:
return const FeatureFlagsPage();
default:
return const SizedBox.shrink();
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_language_view.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flowy_infra/language.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SettingsLanguageView extends StatelessWidget {
const SettingsLanguageView({super.key});
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: BlocBuilder<AppearanceSettingsCubit, AppearanceSettingsState>(
builder: (context, state) => Row(
children: [
Expanded(
child: FlowyText.medium(
LocaleKeys.settings_menu_language.tr(),
),
),
LanguageSelector(currentLocale: state.locale),
],
),
),
);
}
}
class LanguageSelector extends StatelessWidget {
const LanguageSelector({super.key, required this.currentLocale});
final Locale currentLocale;
@override
Widget build(BuildContext context) {
return AppFlowyPopover(
direction: PopoverDirection.bottomWithRightAligned,
child: FlowyTextButton(
languageFromLocale(currentLocale),
fontColor: Theme.of(context).colorScheme.onBackground,
fillColor: Colors.transparent,
onPressed: () {},
),
popupBuilder: (BuildContext context) {
final allLocales = EasyLocalization.of(context)!.supportedLocales;
return LanguageItemsListView(allLocales: allLocales);
},
);
}
}
class LanguageItemsListView extends StatelessWidget {
const LanguageItemsListView({
super.key,
required this.allLocales,
});
final List<Locale> allLocales;
@override
Widget build(BuildContext context) {
// get current locale from cubit
final state = context.watch<AppearanceSettingsCubit>().state;
return ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 400),
child: ListView.builder(
itemBuilder: (context, index) {
final locale = allLocales[index];
return LanguageItem(
locale: locale,
currentLocale: state.locale,
);
},
itemCount: allLocales.length,
),
);
}
}
class LanguageItem extends StatelessWidget {
const LanguageItem({
super.key,
required this.locale,
required this.currentLocale,
});
final Locale locale;
final Locale currentLocale;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 32,
child: FlowyButton(
text: FlowyText.medium(
languageFromLocale(locale),
),
rightIcon:
currentLocale == locale ? const FlowySvg(FlowySvgs.check_s) : null,
onTap: () {
if (currentLocale != locale) {
context.read<AppearanceSettingsCubit>().setLocale(context, locale);
}
PopoverContainer.of(context).close();
},
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/setting_cloud.dart | import 'package:appflowy/env/cloud_env.dart';
import 'package:appflowy/env/env.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/widgets/widgets.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/settings/cloud_setting_bloc.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/setting_local_cloud.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'setting_appflowy_cloud.dart';
import 'setting_supabase_cloud.dart';
class SettingCloud extends StatelessWidget {
const SettingCloud({required this.restartAppFlowy, super.key});
final VoidCallback restartAppFlowy;
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getAuthenticatorType(),
builder:
(BuildContext context, AsyncSnapshot<AuthenticatorType> snapshot) {
if (snapshot.hasData) {
final cloudType = snapshot.data!;
return BlocProvider(
create: (context) => CloudSettingBloc(cloudType),
child: BlocBuilder<CloudSettingBloc, CloudSettingState>(
builder: (context, state) {
return Column(
children: [
if (Env.enableCustomCloud)
Row(
children: [
Expanded(
child: FlowyText.medium(
LocaleKeys.settings_menu_cloudServerType.tr(),
),
),
CloudTypeSwitcher(
cloudType: state.cloudType,
onSelected: (newCloudType) {
context.read<CloudSettingBloc>().add(
CloudSettingEvent.updateCloudType(
newCloudType,
),
);
},
),
],
),
const VSpace(8),
_viewFromCloudType(state.cloudType),
],
);
},
),
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
);
}
Widget _viewFromCloudType(AuthenticatorType cloudType) {
switch (cloudType) {
case AuthenticatorType.local:
return SettingLocalCloud(
restartAppFlowy: restartAppFlowy,
);
case AuthenticatorType.supabase:
return SettingSupabaseCloudView(
restartAppFlowy: restartAppFlowy,
);
case AuthenticatorType.appflowyCloud:
return AppFlowyCloudViewSetting(
restartAppFlowy: restartAppFlowy,
);
case AuthenticatorType.appflowyCloudSelfHost:
return CustomAppFlowyCloudView(
restartAppFlowy: restartAppFlowy,
);
case AuthenticatorType.appflowyCloudDevelop:
return AppFlowyCloudViewSetting(
serverURL: "http://localhost",
authenticatorType: AuthenticatorType.appflowyCloudDevelop,
restartAppFlowy: restartAppFlowy,
);
}
}
}
class CloudTypeSwitcher extends StatelessWidget {
const CloudTypeSwitcher({
super.key,
required this.cloudType,
required this.onSelected,
});
final AuthenticatorType cloudType;
final Function(AuthenticatorType) onSelected;
@override
Widget build(BuildContext context) {
final isDevelopMode = integrationMode().isDevelop;
// Only show the appflowyCloudDevelop in develop mode
final values = AuthenticatorType.values.where((element) {
// Supabase will going to be removed in the future
if (element == AuthenticatorType.supabase) {
return false;
}
return isDevelopMode || element != AuthenticatorType.appflowyCloudDevelop;
}).toList();
return PlatformExtension.isDesktopOrWeb
? AppFlowyPopover(
direction: PopoverDirection.bottomWithRightAligned,
child: FlowyTextButton(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 6),
titleFromCloudType(cloudType),
fontColor: Theme.of(context).colorScheme.onBackground,
fillColor: Colors.transparent,
onPressed: () {},
),
popupBuilder: (BuildContext context) {
return ListView.builder(
shrinkWrap: true,
itemBuilder: (context, index) {
return CloudTypeItem(
cloudType: values[index],
currentCloudtype: cloudType,
onSelected: onSelected,
);
},
itemCount: values.length,
);
},
)
: FlowyButton(
text: FlowyText(
titleFromCloudType(cloudType),
),
useIntrinsicWidth: true,
rightIcon: const Icon(
Icons.chevron_right,
),
onTap: () {
showMobileBottomSheet(
context,
showHeader: true,
showDragHandle: true,
showDivider: false,
showCloseButton: false,
title: LocaleKeys.settings_menu_cloudServerType.tr(),
builder: (context) {
return Column(
children: values
.mapIndexed(
(i, e) => FlowyOptionTile.checkbox(
text: titleFromCloudType(values[i]),
isSelected: cloudType == values[i],
onTap: () {
onSelected(e);
context.pop();
},
showBottomBorder: i == values.length - 1,
),
)
.toList(),
);
},
);
},
);
}
}
class CloudTypeItem extends StatelessWidget {
const CloudTypeItem({
super.key,
required this.cloudType,
required this.currentCloudtype,
required this.onSelected,
});
final AuthenticatorType cloudType;
final AuthenticatorType currentCloudtype;
final Function(AuthenticatorType) onSelected;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 32,
child: FlowyButton(
text: FlowyText.medium(
titleFromCloudType(cloudType),
),
rightIcon: currentCloudtype == cloudType
? const FlowySvg(FlowySvgs.check_s)
: null,
onTap: () {
if (currentCloudtype != cloudType) {
NavigatorAlertDialog(
title: LocaleKeys.settings_menu_changeServerTip.tr(),
confirm: () async {
onSelected(cloudType);
},
hideCancelButton: true,
).show(context);
}
PopoverContainer.of(context).close();
},
),
);
}
}
String titleFromCloudType(AuthenticatorType cloudType) {
switch (cloudType) {
case AuthenticatorType.local:
return LocaleKeys.settings_menu_cloudLocal.tr();
case AuthenticatorType.supabase:
return LocaleKeys.settings_menu_cloudSupabase.tr();
case AuthenticatorType.appflowyCloud:
return LocaleKeys.settings_menu_cloudAppFlowy.tr();
case AuthenticatorType.appflowyCloudSelfHost:
return LocaleKeys.settings_menu_cloudAppFlowySelfHost.tr();
case AuthenticatorType.appflowyCloudDevelop:
return "AppFlowyCloud Develop";
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/setting_third_party_login.dart | import 'package:appflowy/env/cloud_env.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/sign_in_bloc.dart';
import 'package:appflowy/user/presentation/router.dart';
import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/widgets.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/snap_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SettingThirdPartyLogin extends StatelessWidget {
const SettingThirdPartyLogin({required this.didLogin, super.key});
final VoidCallback didLogin;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => getIt<SignInBloc>(),
child: BlocConsumer<SignInBloc, SignInState>(
listener: (context, state) {
final successOrFail = state.successOrFail;
if (successOrFail != null) {
_handleSuccessOrFail(successOrFail, context);
}
},
builder: (_, state) {
final indicator = state.isSubmitting
? const LinearProgressIndicator(minHeight: 1)
: const SizedBox.shrink();
final promptMessage = state.isSubmitting
? FlowyText.medium(
LocaleKeys.signIn_syncPromptMessage.tr(),
maxLines: null,
)
: const SizedBox.shrink();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
FlowyText.medium(
LocaleKeys.signIn_signInWith.tr(),
fontSize: 16,
),
const HSpace(6),
],
),
const VSpace(6),
promptMessage,
const VSpace(6),
indicator,
const VSpace(6),
if (isAuthEnabled) const ThirdPartySignInButtons(),
const VSpace(6),
],
);
},
),
);
}
Future<void> _handleSuccessOrFail(
FlowyResult<UserProfilePB, FlowyError> result,
BuildContext context,
) async {
result.fold(
(user) async {
if (user.encryptionType == EncryptionTypePB.Symmetric) {
getIt<AuthRouter>().pushEncryptionScreen(context, user);
} else {
didLogin();
await runAppFlowy();
}
},
(error) => showSnapBar(context, error.msg),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_user_view.dart | import 'dart:async';
import 'package:appflowy/env/cloud_env.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/base/emoji/emoji_picker.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy/util/debounce.dart';
import 'package:appflowy/workspace/application/user/settings_user_bloc.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy/workspace/presentation/widgets/user_avatar.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'setting_third_party_login.dart';
const defaultUserAvatar = '1F600';
const _iconSize = Size(60, 60);
class SettingsUserView extends StatelessWidget {
SettingsUserView(
this.user, {
required this.didLogin,
required this.didLogout,
required this.didOpenUser,
}) : super(key: ValueKey(user.id));
// Called when the user login in the setting dialog
final VoidCallback didLogin;
// Called when the user logout in the setting dialog
final VoidCallback didLogout;
// Called when the user open a historical user in the setting dialog
final VoidCallback didOpenUser;
final UserProfilePB user;
@override
Widget build(BuildContext context) {
return BlocProvider<SettingsUserViewBloc>(
create: (context) => getIt<SettingsUserViewBloc>(param1: user)
..add(const SettingsUserEvent.initial()),
child: BlocBuilder<SettingsUserViewBloc, SettingsUserState>(
builder: (context, state) => SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
_buildUserIconSetting(context),
if (isAuthEnabled &&
user.authenticator != AuthenticatorPB.Local) ...[
const VSpace(12),
UserEmailInput(user.email),
],
const VSpace(12),
_renderCurrentOpenaiKey(context),
const VSpace(12),
_renderCurrentStabilityAIKey(context),
const VSpace(12),
_renderLoginOrLogoutButton(context, state),
const VSpace(12),
],
),
),
),
);
}
Row _buildUserIconSetting(BuildContext context) {
return Row(
children: [
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => _showIconPickerDialog(context),
child: FlowyHover(
style: const HoverStyle.transparent(),
builder: (context, onHover) {
Widget avatar = UserAvatar(
iconUrl: user.iconUrl,
name: user.name,
isLarge: true,
);
if (onHover) {
avatar = _avatarOverlay(
context: context,
hasIcon: user.iconUrl.isNotEmpty,
child: avatar,
);
}
return avatar;
},
),
),
const HSpace(12),
Flexible(child: _renderUserNameInput(context)),
],
);
}
Future<void> _showIconPickerDialog(BuildContext context) {
return showDialog(
context: context,
builder: (dialogContext) => SimpleDialog(
title: FlowyText.medium(
LocaleKeys.settings_user_selectAnIcon.tr(),
fontSize: FontSizes.s16,
),
children: [
Container(
height: 380,
width: 360,
margin: const EdgeInsets.symmetric(horizontal: 12),
child: FlowyEmojiPicker(
onEmojiSelected: (_, emoji) {
context
.read<SettingsUserViewBloc>()
.add(SettingsUserEvent.updateUserIcon(iconUrl: emoji));
Navigator.of(dialogContext).pop();
},
),
),
],
),
);
}
/// Renders either a login or logout button based on the user's authentication status, or nothing if Supabase is not enabled.
///
/// This function checks the current user's authentication type and Supabase
/// configuration to determine whether to render a third-party login button
/// or a logout button.
Widget _renderLoginOrLogoutButton(
BuildContext context,
SettingsUserState state,
) {
if (!isAuthEnabled) {
return const SizedBox.shrink();
}
// If the user is logged in locally, render a third-party login button.
if (state.userProfile.authenticator == AuthenticatorPB.Local) {
return SettingThirdPartyLogin(didLogin: didLogin);
}
return SettingLogoutButton(user: user, didLogout: didLogout);
}
Widget _renderUserNameInput(BuildContext context) {
final String name =
context.read<SettingsUserViewBloc>().state.userProfile.name;
return UserNameInput(name);
}
Widget _renderCurrentOpenaiKey(BuildContext context) {
final String accessKey =
context.read<SettingsUserViewBloc>().state.userProfile.openaiKey;
return _AIAccessKeyInput(
accessKey: accessKey,
title: 'OpenAI Key',
hintText: LocaleKeys.settings_user_pleaseInputYourOpenAIKey.tr(),
callback: (key) => context
.read<SettingsUserViewBloc>()
.add(SettingsUserEvent.updateUserOpenAIKey(key)),
);
}
Widget _renderCurrentStabilityAIKey(BuildContext context) {
final String accessKey =
context.read<SettingsUserViewBloc>().state.userProfile.stabilityAiKey;
return _AIAccessKeyInput(
accessKey: accessKey,
title: 'Stability AI Key',
hintText: LocaleKeys.settings_user_pleaseInputYourStabilityAIKey.tr(),
callback: (key) => context
.read<SettingsUserViewBloc>()
.add(SettingsUserEvent.updateUserStabilityAIKey(key)),
);
}
Widget _avatarOverlay({
required BuildContext context,
required bool hasIcon,
required Widget child,
}) =>
FlowyTooltip(
message: LocaleKeys.settings_user_tooltipSelectIcon.tr(),
child: Stack(
children: [
Container(
width: 56,
height: 56,
foregroundDecoration: BoxDecoration(
color: Theme.of(context)
.colorScheme
.primary
.withOpacity(hasIcon ? 0.8 : 0.5),
shape: BoxShape.circle,
),
child: child,
),
const Positioned(
top: 0,
left: 0,
bottom: 0,
right: 0,
child: Center(
child: SizedBox(
width: 32,
height: 32,
child: FlowySvg(FlowySvgs.emoji_s),
),
),
),
],
),
);
}
@visibleForTesting
class UserNameInput extends StatefulWidget {
const UserNameInput(this.name, {super.key});
final String name;
@override
UserNameInputState createState() => UserNameInputState();
}
class UserNameInputState extends State<UserNameInput> {
late TextEditingController _controller;
Timer? _debounce;
final Duration _debounceDuration = const Duration(milliseconds: 500);
@override
void initState() {
super.initState();
_controller = TextEditingController(text: widget.name);
}
@override
void dispose() {
_controller.dispose();
_debounce?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
decoration: InputDecoration(
labelText: LocaleKeys.settings_user_name.tr(),
labelStyle: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(fontWeight: FontWeight.w500),
enabledBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: Theme.of(context).colorScheme.onBackground),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Theme.of(context).colorScheme.primary),
),
),
onChanged: (val) {
if (_debounce?.isActive ?? false) {
_debounce!.cancel();
}
_debounce = Timer(_debounceDuration, () {
context
.read<SettingsUserViewBloc>()
.add(SettingsUserEvent.updateUserName(val));
});
},
);
}
}
@visibleForTesting
class UserEmailInput extends StatefulWidget {
const UserEmailInput(this.email, {super.key});
final String email;
@override
UserEmailInputState createState() => UserEmailInputState();
}
class UserEmailInputState extends State<UserEmailInput> {
late TextEditingController _controller;
Timer? _debounce;
final Duration _debounceDuration = const Duration(milliseconds: 500);
@override
void initState() {
super.initState();
_controller = TextEditingController(text: widget.email);
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
decoration: InputDecoration(
labelText: LocaleKeys.settings_user_email.tr(),
labelStyle: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(fontWeight: FontWeight.w500),
enabledBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: Theme.of(context).colorScheme.onBackground),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Theme.of(context).colorScheme.primary),
),
),
onChanged: (val) {
if (_debounce?.isActive ?? false) {
_debounce!.cancel();
}
_debounce = Timer(_debounceDuration, () {
context
.read<SettingsUserViewBloc>()
.add(SettingsUserEvent.updateUserEmail(val));
});
},
);
}
@override
void dispose() {
_controller.dispose();
_debounce?.cancel();
super.dispose();
}
}
class _AIAccessKeyInput extends StatefulWidget {
const _AIAccessKeyInput({
required this.accessKey,
required this.title,
required this.hintText,
required this.callback,
});
final String accessKey;
final String title;
final String hintText;
final void Function(String key) callback;
@override
State<_AIAccessKeyInput> createState() => _AIAccessKeyInputState();
}
class _AIAccessKeyInputState extends State<_AIAccessKeyInput> {
bool visible = false;
final textEditingController = TextEditingController();
final debounce = Debounce();
@override
void initState() {
super.initState();
textEditingController.text = widget.accessKey;
}
@override
void dispose() {
textEditingController.dispose();
debounce.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: textEditingController,
obscureText: !visible,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: Theme.of(context).colorScheme.onBackground),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Theme.of(context).colorScheme.primary),
),
labelText: widget.title,
labelStyle: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(fontWeight: FontWeight.w500),
hintText: widget.hintText,
suffixIcon: FlowyIconButton(
width: 40,
height: 40,
hoverColor: Theme.of(context).colorScheme.secondaryContainer,
icon: Icon(
visible ? Icons.visibility : Icons.visibility_off,
),
onPressed: () {
setState(() {
visible = !visible;
});
},
),
),
onChanged: (value) {
debounce.call(() {
widget.callback(value);
});
},
);
}
}
typedef SelectIconCallback = void Function(String iconUrl, bool isSelected);
final builtInSVGIcons = [
'1F9CC',
'1F9DB',
'1F9DD-200D-2642-FE0F',
'1F9DE-200D-2642-FE0F',
'1F9DF',
'1F42F',
'1F43A',
'1F431',
'1F435',
'1F600',
'1F984',
];
// REMOVE this widget in next version 0.3.10
class IconGallery extends StatelessWidget {
const IconGallery({
super.key,
required this.selectedIcon,
required this.onSelectIcon,
this.defaultOption,
});
final String selectedIcon;
final SelectIconCallback onSelectIcon;
final Widget? defaultOption;
@override
Widget build(BuildContext context) {
return GridView.count(
padding: const EdgeInsets.all(20),
crossAxisCount: 5,
mainAxisSpacing: 4,
crossAxisSpacing: 4,
children: [
if (defaultOption != null) defaultOption!,
...builtInSVGIcons.mapIndexed(
(int index, String iconUrl) => IconOption(
emoji: FlowySvgData('emoji/$iconUrl'),
iconUrl: iconUrl,
onSelectIcon: onSelectIcon,
isSelected: iconUrl == selectedIcon,
),
),
],
);
}
}
class IconOption extends StatelessWidget {
IconOption({
required this.emoji,
required this.iconUrl,
required this.onSelectIcon,
required this.isSelected,
}) : super(key: ValueKey(emoji));
final FlowySvgData emoji;
final String iconUrl;
final SelectIconCallback onSelectIcon;
final bool isSelected;
@override
Widget build(BuildContext context) {
return InkWell(
borderRadius: Corners.s8Border,
hoverColor: Theme.of(context).colorScheme.tertiaryContainer,
onTap: () => onSelectIcon(iconUrl, isSelected),
child: DecoratedBox(
decoration: BoxDecoration(
color: isSelected
? Theme.of(context).colorScheme.primary
: Colors.transparent,
borderRadius: Corners.s8Border,
),
child: FlowySvg(
emoji,
size: _iconSize,
blendMode: null,
),
),
);
}
}
class SettingLogoutButton extends StatelessWidget {
const SettingLogoutButton({
super.key,
required this.user,
required this.didLogout,
});
final UserProfilePB user;
final VoidCallback didLogout;
@override
Widget build(BuildContext context) {
return Center(
child: SizedBox(
width: 160,
child: FlowyButton(
margin: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 2.0),
text: FlowyText.medium(
LocaleKeys.settings_menu_logout.tr(),
fontSize: 13,
textAlign: TextAlign.center,
),
onTap: () {
NavigatorAlertDialog(
title: logoutPromptMessage(),
confirm: () async {
await getIt<AuthService>().signOut();
didLogout();
},
).show(context);
},
),
),
);
}
String logoutPromptMessage() {
switch (user.encryptionType) {
case EncryptionTypePB.Symmetric:
return LocaleKeys.settings_menu_selfEncryptionLogoutPrompt.tr();
default:
return LocaleKeys.settings_menu_logoutPrompt.tr();
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_menu.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/shared/feature_flags.dart';
import 'package:appflowy/workspace/application/settings/settings_dialog_bloc.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_menu_element.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class SettingsMenu extends StatelessWidget {
const SettingsMenu({
super.key,
required this.changeSelectedPage,
required this.currentPage,
required this.userProfile,
});
final Function changeSelectedPage;
final SettingsPage currentPage;
final UserProfilePB userProfile;
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: SeparatedColumn(
separatorBuilder: () => const SizedBox(height: 10),
children: [
SettingsMenuElement(
page: SettingsPage.appearance,
selectedPage: currentPage,
label: LocaleKeys.settings_menu_appearance.tr(),
icon: Icons.brightness_4,
changeSelectedPage: changeSelectedPage,
),
SettingsMenuElement(
page: SettingsPage.language,
selectedPage: currentPage,
label: LocaleKeys.settings_menu_language.tr(),
icon: Icons.translate,
changeSelectedPage: changeSelectedPage,
),
SettingsMenuElement(
page: SettingsPage.files,
selectedPage: currentPage,
label: LocaleKeys.settings_menu_files.tr(),
icon: Icons.file_present_outlined,
changeSelectedPage: changeSelectedPage,
),
SettingsMenuElement(
page: SettingsPage.user,
selectedPage: currentPage,
label: LocaleKeys.settings_menu_user.tr(),
icon: Icons.account_box_outlined,
changeSelectedPage: changeSelectedPage,
),
SettingsMenuElement(
page: SettingsPage.notifications,
selectedPage: currentPage,
label: LocaleKeys.settings_menu_notifications.tr(),
icon: Icons.notifications_outlined,
changeSelectedPage: changeSelectedPage,
),
SettingsMenuElement(
page: SettingsPage.cloud,
selectedPage: currentPage,
label: LocaleKeys.settings_menu_cloudSettings.tr(),
icon: Icons.sync,
changeSelectedPage: changeSelectedPage,
),
SettingsMenuElement(
page: SettingsPage.shortcuts,
selectedPage: currentPage,
label: LocaleKeys.settings_shortcuts_shortcutsLabel.tr(),
icon: Icons.cut,
changeSelectedPage: changeSelectedPage,
),
if (FeatureFlag.membersSettings.isOn &&
userProfile.authenticator == AuthenticatorPB.AppFlowyCloud)
SettingsMenuElement(
page: SettingsPage.member,
selectedPage: currentPage,
label: LocaleKeys.settings_appearance_members_label.tr(),
icon: Icons.people,
changeSelectedPage: changeSelectedPage,
),
if (kDebugMode)
SettingsMenuElement(
// no need to translate this page
page: SettingsPage.featureFlags,
selectedPage: currentPage,
label: 'Feature Flags',
icon: Icons.flag,
changeSelectedPage: changeSelectedPage,
),
],
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_file_system_view.dart | import 'package:appflowy/workspace/presentation/settings/widgets/files/setting_file_import_appflowy_data_view.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/files/settings_export_file_widget.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/files/settings_file_cache_widget.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/files/settings_file_customize_location_view.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class SettingsFileSystemView extends StatefulWidget {
const SettingsFileSystemView({
super.key,
});
@override
State<SettingsFileSystemView> createState() => _SettingsFileSystemViewState();
}
class _SettingsFileSystemViewState extends State<SettingsFileSystemView> {
late final _items = [
const SettingsFileLocationCustomizer(),
// disable export data for v0.2.0 in release mode.
if (kDebugMode) const SettingsExportFileWidget(),
const ImportAppFlowyData(),
// clear the cache
const SettingsFileCacheWidget(),
];
@override
Widget build(BuildContext context) {
return SeparatedColumn(
separatorBuilder: () => const Divider(),
children: _items,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/setting_appflowy_cloud.dart | import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/env/cloud_env.dart';
import 'package:appflowy/env/env.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/settings/appflowy_cloud_setting_bloc.dart';
import 'package:appflowy/workspace/application/settings/appflowy_cloud_urls_bloc.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/_restart_app_button.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_setting.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/widget/error_page.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class AppFlowyCloudViewSetting extends StatelessWidget {
const AppFlowyCloudViewSetting({
super.key,
this.serverURL = kAppflowyCloudUrl,
this.authenticatorType = AuthenticatorType.appflowyCloud,
required this.restartAppFlowy,
});
final String serverURL;
final AuthenticatorType authenticatorType;
final VoidCallback restartAppFlowy;
@override
Widget build(BuildContext context) {
return FutureBuilder<FlowyResult<CloudSettingPB, FlowyError>>(
future: UserEventGetCloudConfig().send(),
builder: (context, snapshot) {
if (snapshot.data != null &&
snapshot.connectionState == ConnectionState.done) {
return snapshot.data!.fold(
(setting) => _renderContent(context, setting),
(err) => FlowyErrorPage.message(err.toString(), howToFix: ""),
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
);
}
BlocProvider<AppFlowyCloudSettingBloc> _renderContent(
BuildContext context,
CloudSettingPB setting,
) {
return BlocProvider(
create: (context) => AppFlowyCloudSettingBloc(setting)
..add(const AppFlowyCloudSettingEvent.initial()),
child: BlocBuilder<AppFlowyCloudSettingBloc, AppFlowyCloudSettingState>(
builder: (context, state) {
return Column(
children: [
const AppFlowyCloudEnableSync(),
const VSpace(12),
RestartButton(
onClick: () {
NavigatorAlertDialog(
title: LocaleKeys.settings_menu_restartAppTip.tr(),
confirm: () async {
await useAppFlowyBetaCloudWithURL(
serverURL,
authenticatorType,
);
restartAppFlowy();
},
).show(context);
},
showRestartHint: state.showRestartHint,
),
],
);
},
),
);
}
}
class CustomAppFlowyCloudView extends StatelessWidget {
const CustomAppFlowyCloudView({required this.restartAppFlowy, super.key});
final VoidCallback restartAppFlowy;
@override
Widget build(BuildContext context) {
return FutureBuilder<FlowyResult<CloudSettingPB, FlowyError>>(
future: UserEventGetCloudConfig().send(),
builder: (context, snapshot) {
if (snapshot.data != null &&
snapshot.connectionState == ConnectionState.done) {
return snapshot.data!.fold(
(setting) => _renderContent(setting),
(err) => FlowyErrorPage.message(err.toString(), howToFix: ""),
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
);
}
BlocProvider<AppFlowyCloudSettingBloc> _renderContent(
CloudSettingPB setting,
) {
final List<Widget> children = [];
children.addAll([
const AppFlowyCloudEnableSync(),
const VSpace(40),
]);
// If the enableCustomCloud flag is true, then the user can dynamically configure cloud settings. Otherwise, the user cannot dynamically configure cloud settings.
if (Env.enableCustomCloud) {
children.add(
AppFlowyCloudURLs(restartAppFlowy: () => restartAppFlowy()),
);
} else {
children.add(
Row(
children: [
FlowyText(LocaleKeys.settings_menu_cloudServerType.tr()),
const Spacer(),
const FlowyText(Env.afCloudUrl),
],
),
);
}
return BlocProvider(
create: (context) => AppFlowyCloudSettingBloc(setting)
..add(const AppFlowyCloudSettingEvent.initial()),
child: Column(
children: children,
),
);
}
}
class AppFlowyCloudURLs extends StatelessWidget {
const AppFlowyCloudURLs({super.key, required this.restartAppFlowy});
final VoidCallback restartAppFlowy;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) =>
AppFlowyCloudURLsBloc()..add(const AppFlowyCloudURLsEvent.initial()),
child: BlocListener<AppFlowyCloudURLsBloc, AppFlowyCloudURLsState>(
listener: (context, state) async {
if (state.restartApp) {
restartAppFlowy();
}
},
child: BlocBuilder<AppFlowyCloudURLsBloc, AppFlowyCloudURLsState>(
builder: (context, state) {
return Column(
children: [
const AppFlowySelfhostTip(),
CloudURLInput(
title: LocaleKeys.settings_menu_cloudURL.tr(),
url: state.config.base_url,
hint: LocaleKeys.settings_menu_cloudURLHint.tr(),
onChanged: (text) {
context.read<AppFlowyCloudURLsBloc>().add(
AppFlowyCloudURLsEvent.updateServerUrl(
text,
),
);
},
),
const VSpace(8),
RestartButton(
onClick: () {
NavigatorAlertDialog(
title: LocaleKeys.settings_menu_restartAppTip.tr(),
confirm: () {
context.read<AppFlowyCloudURLsBloc>().add(
const AppFlowyCloudURLsEvent.confirmUpdate(),
);
},
).show(context);
},
showRestartHint: state.showRestartHint,
),
],
);
},
),
),
);
}
}
class AppFlowySelfhostTip extends StatelessWidget {
const AppFlowySelfhostTip({super.key});
final url =
"https://docs.appflowy.io/docs/guides/appflowy/self-hosting-appflowy#build-appflowy-with-a-self-hosted-server";
@override
Widget build(BuildContext context) {
return Opacity(
opacity: 0.6,
child: RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(
text: LocaleKeys.settings_menu_selfHostStart.tr(),
style: Theme.of(context).textTheme.bodySmall!,
),
TextSpan(
text: " ${LocaleKeys.settings_menu_selfHostContent.tr()} ",
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
fontSize: FontSizes.s14,
color: Theme.of(context).colorScheme.primary,
decoration: TextDecoration.underline,
),
recognizer: TapGestureRecognizer()
..onTap = () => afLaunchUrlString(url),
),
TextSpan(
text: LocaleKeys.settings_menu_selfHostEnd.tr(),
style: Theme.of(context).textTheme.bodySmall!,
),
],
),
),
);
}
}
@visibleForTesting
class CloudURLInput extends StatefulWidget {
const CloudURLInput({
super.key,
required this.title,
required this.url,
required this.hint,
required this.onChanged,
});
final String title;
final String url;
final String hint;
final Function(String) onChanged;
@override
CloudURLInputState createState() => CloudURLInputState();
}
class CloudURLInputState extends State<CloudURLInput> {
late TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: widget.url);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
style: const TextStyle(fontSize: 12.0),
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 6),
labelText: widget.title,
labelStyle: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(fontWeight: FontWeight.w400, fontSize: 16),
enabledBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: Theme.of(context).colorScheme.onBackground),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Theme.of(context).colorScheme.primary),
),
hintText: widget.hint,
errorText: context.read<AppFlowyCloudURLsBloc>().state.urlError,
),
onChanged: widget.onChanged,
);
}
}
class AppFlowyCloudEnableSync extends StatelessWidget {
const AppFlowyCloudEnableSync({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<AppFlowyCloudSettingBloc, AppFlowyCloudSettingState>(
builder: (context, state) {
return Row(
children: [
FlowyText.medium(LocaleKeys.settings_menu_enableSync.tr()),
const Spacer(),
Switch.adaptive(
onChanged: (bool value) {
context.read<AppFlowyCloudSettingBloc>().add(
AppFlowyCloudSettingEvent.enableSync(value),
);
},
activeColor: Theme.of(context).colorScheme.primary,
value: state.setting.enableSync,
),
],
);
},
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_notifications_view.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/settings/notifications/notification_settings_cubit.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/theme_setting_entry_template.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SettingsNotificationsView extends StatelessWidget {
const SettingsNotificationsView({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<NotificationSettingsCubit, NotificationSettingsState>(
builder: (context, state) {
return SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
FlowySettingListTile(
label: LocaleKeys
.settings_notifications_enableNotifications_label
.tr(),
hint: LocaleKeys.settings_notifications_enableNotifications_hint
.tr(),
trailing: [
Switch(
value: state.isNotificationsEnabled,
splashRadius: 0,
activeColor: Theme.of(context).colorScheme.primary,
onChanged: (value) {
context
.read<NotificationSettingsCubit>()
.toggleNotificationsEnabled();
},
),
],
),
],
),
);
},
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance_view.dart | import 'package:appflowy/workspace/application/appearance_defaults.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/create_file_setting.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/date_format_setting.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/time_format_setting.dart';
import 'package:flowy_infra/plugins/bloc/dynamic_plugin_bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'settings_appearance/settings_appearance.dart';
class SettingsAppearanceView extends StatelessWidget {
const SettingsAppearanceView({super.key});
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: BlocProvider<DynamicPluginBloc>(
create: (_) => DynamicPluginBloc(),
child: BlocBuilder<AppearanceSettingsCubit, AppearanceSettingsState>(
builder: (context, state) {
return Column(
children: [
ColorSchemeSetting(
currentTheme: state.appTheme.themeName,
bloc: context.read<DynamicPluginBloc>(),
),
BrightnessSetting(
currentThemeMode: state.themeMode,
),
const Divider(),
ThemeFontFamilySetting(
currentFontFamily: state.font,
),
const Divider(),
DocumentCursorColorSetting(
currentCursorColor: state.documentCursorColor ??
DefaultAppearanceSettings.getDefaultDocumentCursorColor(
context,
),
),
DocumentSelectionColorSetting(
currentSelectionColor: state.documentSelectionColor ??
DefaultAppearanceSettings
.getDefaultDocumentSelectionColor(
context,
),
),
const Divider(),
LayoutDirectionSetting(
currentLayoutDirection: state.layoutDirection,
),
TextDirectionSetting(
currentTextDirection: state.textDirection,
),
const EnableRTLToolbarItemsSetting(),
const Divider(),
DateFormatSetting(
currentFormat: state.dateFormat,
),
TimeFormatSetting(
currentFormat: state.timeFormat,
),
const Divider(),
CreateFileSettings(),
],
);
},
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/_restart_app_button.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/user/presentation/screens/sign_in_screen/widgets/sign_in_or_logout_button.dart';
import 'package:appflowy_editor/appflowy_editor.dart' show PlatformExtension;
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
class RestartButton extends StatelessWidget {
const RestartButton({
super.key,
required this.showRestartHint,
required this.onClick,
});
final bool showRestartHint;
final VoidCallback onClick;
@override
Widget build(BuildContext context) {
final List<Widget> children = [_buildRestartButton()];
if (showRestartHint) {
children.add(
Padding(
padding: const EdgeInsets.only(top: 10),
child: FlowyText(
LocaleKeys.settings_menu_restartAppTip.tr(),
maxLines: null,
),
),
);
}
return Column(children: children);
}
Widget _buildRestartButton() {
if (PlatformExtension.isDesktopOrWeb) {
return Row(
children: [
FlowyButton(
isSelected: true,
useIntrinsicWidth: true,
margin: const EdgeInsets.symmetric(
horizontal: 30,
vertical: 10,
),
text: FlowyText(
LocaleKeys.settings_menu_restartApp.tr(),
),
onTap: onClick,
),
const Spacer(),
],
);
} else {
return MobileSignInOrLogoutButton(
labelText: LocaleKeys.settings_menu_restartApp.tr(),
onPressed: onClick,
);
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/setting_supabase_cloud.dart | import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/settings/supabase_cloud_setting_bloc.dart';
import 'package:appflowy/workspace/application/settings/supabase_cloud_urls_bloc.dart';
import 'package:appflowy/workspace/presentation/home/toast.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/_restart_app_button.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_setting.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/widget/error_page.dart';
import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SettingSupabaseCloudView extends StatelessWidget {
const SettingSupabaseCloudView({required this.restartAppFlowy, super.key});
final VoidCallback restartAppFlowy;
@override
Widget build(BuildContext context) {
return FutureBuilder<FlowyResult<CloudSettingPB, FlowyError>>(
future: UserEventGetCloudConfig().send(),
builder: (context, snapshot) {
if (snapshot.data != null &&
snapshot.connectionState == ConnectionState.done) {
return snapshot.data!.fold(
(setting) {
return BlocProvider(
create: (context) => SupabaseCloudSettingBloc(
setting: setting,
)..add(const SupabaseCloudSettingEvent.initial()),
child: Column(
children: [
BlocBuilder<SupabaseCloudSettingBloc,
SupabaseCloudSettingState>(
builder: (context, state) {
return const Column(
children: [
SupabaseEnableSync(),
EnableEncrypt(),
],
);
},
),
const VSpace(40),
const SupabaseSelfhostTip(),
SupabaseCloudURLs(
didUpdateUrls: restartAppFlowy,
),
],
),
);
},
(err) {
return FlowyErrorPage.message(err.toString(), howToFix: "");
},
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
);
}
}
class SupabaseCloudURLs extends StatelessWidget {
const SupabaseCloudURLs({super.key, required this.didUpdateUrls});
final VoidCallback didUpdateUrls;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => SupabaseCloudURLsBloc(),
child: BlocListener<SupabaseCloudURLsBloc, SupabaseCloudURLsState>(
listener: (context, state) async {
if (state.restartApp) {
didUpdateUrls();
}
},
child: BlocBuilder<SupabaseCloudURLsBloc, SupabaseCloudURLsState>(
builder: (context, state) {
return Column(
children: [
SupabaseInput(
title: LocaleKeys.settings_menu_cloudSupabaseUrl.tr(),
url: state.config.url,
hint: LocaleKeys.settings_menu_cloudURLHint.tr(),
onChanged: (text) {
context
.read<SupabaseCloudURLsBloc>()
.add(SupabaseCloudURLsEvent.updateUrl(text));
},
error: state.urlError,
),
SupabaseInput(
title: LocaleKeys.settings_menu_cloudSupabaseAnonKey.tr(),
url: state.config.anon_key,
hint: LocaleKeys.settings_menu_cloudURLHint.tr(),
onChanged: (text) {
context
.read<SupabaseCloudURLsBloc>()
.add(SupabaseCloudURLsEvent.updateAnonKey(text));
},
error: state.anonKeyError,
),
const VSpace(20),
RestartButton(
onClick: () => _restartApp(context),
showRestartHint: state.showRestartHint,
),
],
);
},
),
),
);
}
void _restartApp(BuildContext context) {
NavigatorAlertDialog(
title: LocaleKeys.settings_menu_restartAppTip.tr(),
confirm: () => context
.read<SupabaseCloudURLsBloc>()
.add(const SupabaseCloudURLsEvent.confirmUpdate()),
).show(context);
}
}
class EnableEncrypt extends StatelessWidget {
const EnableEncrypt({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<SupabaseCloudSettingBloc, SupabaseCloudSettingState>(
builder: (context, state) {
final indicator = state.loadingState.when(
loading: () => const CircularProgressIndicator.adaptive(),
finish: (successOrFail) => const SizedBox.shrink(),
idle: () => const SizedBox.shrink(),
);
return Column(
children: [
Row(
children: [
FlowyText.medium(LocaleKeys.settings_menu_enableEncrypt.tr()),
const Spacer(),
indicator,
const HSpace(3),
Switch.adaptive(
activeColor: Theme.of(context).colorScheme.primary,
onChanged: state.setting.enableEncrypt
? null
: (bool value) {
context.read<SupabaseCloudSettingBloc>().add(
SupabaseCloudSettingEvent.enableEncrypt(value),
);
},
value: state.setting.enableEncrypt,
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IntrinsicHeight(
child: Opacity(
opacity: 0.6,
child: FlowyText.medium(
LocaleKeys.settings_menu_enableEncryptPrompt.tr(),
maxLines: 13,
),
),
),
const VSpace(6),
SizedBox(
height: 40,
child: FlowyTooltip(
message: LocaleKeys.settings_menu_clickToCopySecret.tr(),
child: FlowyButton(
disable: !state.setting.enableEncrypt,
decoration: BoxDecoration(
borderRadius: Corners.s5Border,
border: Border.all(
color: Theme.of(context).colorScheme.secondary,
),
),
text: FlowyText.medium(state.setting.encryptSecret),
onTap: () async {
await Clipboard.setData(
ClipboardData(text: state.setting.encryptSecret),
);
showMessageToast(LocaleKeys.message_copy_success.tr());
},
),
),
),
],
),
],
);
},
);
}
}
class SupabaseEnableSync extends StatelessWidget {
const SupabaseEnableSync({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<SupabaseCloudSettingBloc, SupabaseCloudSettingState>(
builder: (context, state) {
return Row(
children: [
FlowyText.medium(LocaleKeys.settings_menu_enableSync.tr()),
const Spacer(),
Switch.adaptive(
activeColor: Theme.of(context).colorScheme.primary,
onChanged: (bool value) {
context.read<SupabaseCloudSettingBloc>().add(
SupabaseCloudSettingEvent.enableSync(value),
);
},
value: state.setting.enableSync,
),
],
);
},
);
}
}
@visibleForTesting
class SupabaseInput extends StatefulWidget {
const SupabaseInput({
super.key,
required this.title,
required this.url,
required this.hint,
required this.error,
required this.onChanged,
});
final String title;
final String url;
final String hint;
final String? error;
final Function(String) onChanged;
@override
SupabaseInputState createState() => SupabaseInputState();
}
class SupabaseInputState extends State<SupabaseInput> {
late TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: widget.url);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
style: const TextStyle(fontSize: 12.0),
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 6),
labelText: widget.title,
labelStyle: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(fontWeight: FontWeight.w400, fontSize: 16),
enabledBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: Theme.of(context).colorScheme.onBackground),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Theme.of(context).colorScheme.primary),
),
hintText: widget.hint,
errorText: widget.error,
),
onChanged: widget.onChanged,
);
}
}
class SupabaseSelfhostTip extends StatelessWidget {
const SupabaseSelfhostTip({super.key});
final url =
"https://docs.appflowy.io/docs/guides/appflowy/self-hosting-appflowy-using-supabase";
@override
Widget build(BuildContext context) {
return Opacity(
opacity: 0.6,
child: RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(
text: LocaleKeys.settings_menu_selfHostStart.tr(),
style: Theme.of(context).textTheme.bodySmall!,
),
TextSpan(
text: " ${LocaleKeys.settings_menu_selfHostContent.tr()} ",
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
fontSize: FontSizes.s14,
color: Theme.of(context).colorScheme.primary,
decoration: TextDecoration.underline,
),
recognizer: TapGestureRecognizer()
..onTap = () => afLaunchUrlString(url),
),
TextSpan(
text: LocaleKeys.settings_menu_selfHostEnd.tr(),
style: Theme.of(context).textTheme.bodySmall!,
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_customize_shortcuts_view.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/string_extension.dart';
import 'package:appflowy/workspace/application/settings/shortcuts/settings_shortcuts_cubit.dart';
import 'package:appflowy/workspace/application/settings/shortcuts/settings_shortcuts_service.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SettingsCustomizeShortcutsWrapper extends StatelessWidget {
const SettingsCustomizeShortcutsWrapper({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider<ShortcutsCubit>(
create: (_) =>
ShortcutsCubit(SettingsShortcutService())..fetchShortcuts(),
child: const SettingsCustomizeShortcutsView(),
);
}
}
class SettingsCustomizeShortcutsView extends StatelessWidget {
const SettingsCustomizeShortcutsView({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<ShortcutsCubit, ShortcutsState>(
builder: (context, state) {
switch (state.status) {
case ShortcutsStatus.initial:
case ShortcutsStatus.updating:
return const Center(child: CircularProgressIndicator());
case ShortcutsStatus.success:
return ShortcutsListView(shortcuts: state.commandShortcutEvents);
case ShortcutsStatus.failure:
return ShortcutsErrorView(
errorMessage: state.error,
);
}
},
);
}
}
class ShortcutsListView extends StatelessWidget {
const ShortcutsListView({
super.key,
required this.shortcuts,
});
final List<CommandShortcutEvent> shortcuts;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: FlowyText.semibold(
LocaleKeys.settings_shortcuts_command.tr(),
overflow: TextOverflow.ellipsis,
),
),
FlowyText.semibold(
LocaleKeys.settings_shortcuts_keyBinding.tr(),
overflow: TextOverflow.ellipsis,
),
],
),
const VSpace(10),
Expanded(
child: ListView.builder(
itemCount: shortcuts.length,
itemBuilder: (context, index) => ShortcutsListTile(
shortcutEvent: shortcuts[index],
),
),
),
const VSpace(10),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
const Spacer(),
FlowyTextButton(
LocaleKeys.settings_shortcuts_resetToDefault.tr(),
onPressed: () {
context.read<ShortcutsCubit>().resetToDefault();
},
),
],
),
const VSpace(10),
],
);
}
}
class ShortcutsListTile extends StatelessWidget {
const ShortcutsListTile({
super.key,
required this.shortcutEvent,
});
final CommandShortcutEvent shortcutEvent;
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
Expanded(
child: FlowyText.medium(
key: Key(shortcutEvent.key),
shortcutEvent.description!.capitalize(),
overflow: TextOverflow.ellipsis,
),
),
FlowyTextButton(
shortcutEvent.command,
fillColor: Colors.transparent,
onPressed: () {
showKeyListenerDialog(context);
},
),
],
),
Divider(
color: Theme.of(context).dividerColor,
),
],
);
}
void showKeyListenerDialog(BuildContext widgetContext) {
final controller = TextEditingController(text: shortcutEvent.command);
showDialog(
context: widgetContext,
builder: (builderContext) {
final formKey = GlobalKey<FormState>();
return AlertDialog(
title: Text(LocaleKeys.settings_shortcuts_updateShortcutStep.tr()),
content: KeyboardListener(
focusNode: FocusNode(),
onKeyEvent: (key) {
if (key.logicalKey == LogicalKeyboardKey.enter &&
!HardwareKeyboard.instance.isShiftPressed) {
if (controller.text == shortcutEvent.command) {
_dismiss(builderContext);
}
if (formKey.currentState!.validate()) {
_updateKey(widgetContext, controller.text);
_dismiss(builderContext);
}
} else if (key.logicalKey == LogicalKeyboardKey.escape) {
_dismiss(builderContext);
} else {
//extract the keybinding command from the key event.
controller.text = key.convertToCommand;
}
},
child: Form(
key: formKey,
child: TextFormField(
autofocus: true,
controller: controller,
readOnly: true,
maxLines: null,
decoration: const InputDecoration(
border: OutlineInputBorder(),
),
validator: (_) => _validateForConflicts(
widgetContext,
controller.text,
),
),
),
),
);
},
).then((_) => controller.dispose());
}
String? _validateForConflicts(BuildContext context, String command) {
final conflict = BlocProvider.of<ShortcutsCubit>(context).getConflict(
shortcutEvent,
command,
);
if (conflict.isEmpty) return null;
return LocaleKeys.settings_shortcuts_shortcutIsAlreadyUsed.tr(
namedArgs: {'conflict': conflict},
);
}
void _updateKey(BuildContext context, String command) {
shortcutEvent.updateCommand(command: command);
BlocProvider.of<ShortcutsCubit>(context).updateAllShortcuts();
}
void _dismiss(BuildContext context) => Navigator.of(context).pop();
}
extension on KeyEvent {
String get convertToCommand {
String command = '';
if (HardwareKeyboard.instance.isAltPressed) {
command += 'alt+';
}
if (HardwareKeyboard.instance.isControlPressed) {
command += 'ctrl+';
}
if (HardwareKeyboard.instance.isShiftPressed) {
command += 'shift+';
}
if (HardwareKeyboard.instance.isMetaPressed) {
command += 'meta+';
}
final keyPressed = keyToCodeMapping.keys.firstWhere(
(k) => keyToCodeMapping[k] == logicalKey.keyId,
orElse: () => '',
);
return command += keyPressed;
}
}
class ShortcutsErrorView extends StatelessWidget {
const ShortcutsErrorView({super.key, required this.errorMessage});
final String errorMessage;
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(
child: FlowyText.medium(
errorMessage,
overflow: TextOverflow.ellipsis,
),
),
FlowyIconButton(
icon: const Icon(Icons.replay_outlined),
onPressed: () {
BlocProvider.of<ShortcutsCubit>(context).fetchShortcuts();
},
),
],
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/setting_local_cloud.dart | import 'package:appflowy/env/cloud_env.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/_restart_app_button.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
class SettingLocalCloud extends StatelessWidget {
const SettingLocalCloud({super.key, required this.restartAppFlowy});
final VoidCallback restartAppFlowy;
@override
Widget build(BuildContext context) {
return RestartButton(
onClick: () => onPressed(context),
showRestartHint: true,
);
}
void onPressed(BuildContext context) {
NavigatorAlertDialog(
title: LocaleKeys.settings_menu_restartAppTip.tr(),
confirm: () async {
await useLocalServer();
restartAppFlowy();
},
).show(context);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_menu_element.dart | import 'package:appflowy/workspace/application/settings/settings_dialog_bloc.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:flutter/material.dart';
class SettingsMenuElement extends StatelessWidget {
const SettingsMenuElement({
super.key,
required this.page,
required this.label,
required this.icon,
required this.changeSelectedPage,
required this.selectedPage,
});
final SettingsPage page;
final SettingsPage selectedPage;
final String label;
final IconData icon;
final Function changeSelectedPage;
@override
Widget build(BuildContext context) {
return FlowyHover(
resetHoverOnRebuild: false,
style: HoverStyle(
hoverColor: Theme.of(context).colorScheme.primary,
),
child: ListTile(
leading: Icon(
icon,
size: 16,
color: page == selectedPage
? Theme.of(context).colorScheme.onSurface
: null,
),
onTap: () {
changeSelectedPage(page);
},
selected: page == selectedPage,
selectedColor: Theme.of(context).colorScheme.onSurface,
selectedTileColor: Theme.of(context).colorScheme.primary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
minLeadingWidth: 0,
title: FlowyText.semibold(
label,
fontSize: FontSizes.s14,
overflow: TextOverflow.ellipsis,
color: page == selectedPage
? Theme.of(context).colorScheme.onSurface
: null,
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/members/workspace_member_page.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/shared/af_role_pb_extension.dart';
import 'package:appflowy/workspace/presentation/home/toast.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/members/workspace_member_bloc.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:appflowy/workspace/presentation/widgets/pop_up_action.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/code.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';
import 'package:flowy_infra_ui/widget/rounded_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:string_validator/string_validator.dart';
class WorkspaceMembersPage extends StatelessWidget {
const WorkspaceMembersPage({
super.key,
required this.userProfile,
});
final UserProfilePB userProfile;
@override
Widget build(BuildContext context) {
return BlocProvider<WorkspaceMemberBloc>(
create: (context) => WorkspaceMemberBloc(userProfile: userProfile)
..add(const WorkspaceMemberEvent.initial()),
child: BlocConsumer<WorkspaceMemberBloc, WorkspaceMemberState>(
listener: _showResultDialog,
builder: (context, state) {
return SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// title
FlowyText.semibold(
LocaleKeys.settings_appearance_members_title.tr(),
fontSize: 20,
),
if (state.myRole.canInvite) const _InviteMember(),
if (state.members.isNotEmpty)
_MemberList(
members: state.members,
userProfile: userProfile,
myRole: state.myRole,
),
const VSpace(48.0),
],
),
);
},
),
);
}
void _showResultDialog(BuildContext context, WorkspaceMemberState state) {
final actionResult = state.actionResult;
if (actionResult == null) {
return;
}
final actionType = actionResult.actionType;
final result = actionResult.result;
// only show the result dialog when the action is WorkspaceMemberActionType.add
if (actionType == WorkspaceMemberActionType.add) {
result.fold(
(s) {
showSnackBarMessage(
context,
LocaleKeys.settings_appearance_members_addMemberSuccess.tr(),
);
},
(f) {
final message = f.code == ErrorCode.WorkspaceMemberLimitExceeded
? LocaleKeys.settings_appearance_members_memberLimitExceeded.tr()
: LocaleKeys.settings_appearance_members_failedToAddMember.tr();
showDialog(
context: context,
builder: (context) => NavigatorOkCancelDialog(message: message),
);
},
);
}
result.onFailure((f) {
Log.error(
'[Member] Failed to perform ${actionType.toString()} action: $f',
);
});
}
}
class _InviteMember extends StatefulWidget {
const _InviteMember();
@override
State<_InviteMember> createState() => _InviteMemberState();
}
class _InviteMemberState extends State<_InviteMember> {
final _emailController = TextEditingController();
@override
void dispose() {
_emailController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const VSpace(12.0),
FlowyText.semibold(
LocaleKeys.settings_appearance_members_inviteMembers.tr(),
fontSize: 16.0,
),
const VSpace(8.0),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: ConstrainedBox(
constraints: const BoxConstraints.tightFor(
height: 48.0,
),
child: FlowyTextField(
controller: _emailController,
onEditingComplete: _inviteMember,
),
),
),
const HSpace(10.0),
SizedBox(
height: 48.0,
child: IntrinsicWidth(
child: RoundedTextButton(
title: LocaleKeys.settings_appearance_members_sendInvite.tr(),
padding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
onPressed: _inviteMember,
),
),
),
],
),
const VSpace(16.0),
/* Enable this when the feature is ready
PrimaryButton(
backgroundColor: const Color(0xFFE0E0E0),
child: Padding(
padding: const EdgeInsets.only(
left: 20,
right: 24,
top: 8,
bottom: 8,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const FlowySvg(
FlowySvgs.invite_member_link_m,
color: Colors.black,
),
const HSpace(8.0),
FlowyText(
LocaleKeys.settings_appearance_members_copyInviteLink.tr(),
color: Colors.black,
),
],
),
),
onPressed: () {
showSnackBarMessage(context, 'not implemented');
},
),
const VSpace(16.0),
*/
const Divider(
height: 1.0,
thickness: 1.0,
),
],
);
}
void _inviteMember() {
final email = _emailController.text;
if (!isEmail(email)) {
showSnackBarMessage(
context,
LocaleKeys.settings_appearance_members_emailInvalidError.tr(),
);
return;
}
context
.read<WorkspaceMemberBloc>()
.add(WorkspaceMemberEvent.addWorkspaceMember(email));
}
}
class _MemberList extends StatelessWidget {
const _MemberList({
required this.members,
required this.myRole,
required this.userProfile,
});
final List<WorkspaceMemberPB> members;
final AFRolePB myRole;
final UserProfilePB userProfile;
@override
Widget build(BuildContext context) {
return Column(
children: [
const VSpace(16.0),
SeparatedColumn(
crossAxisAlignment: CrossAxisAlignment.start,
separatorBuilder: () => const Divider(),
children: [
const _MemberListHeader(),
...members.map(
(member) => _MemberItem(
member: member,
myRole: myRole,
userProfile: userProfile,
),
),
],
),
],
);
}
}
class _MemberListHeader extends StatelessWidget {
const _MemberListHeader();
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlowyText.semibold(
LocaleKeys.settings_appearance_members_label.tr(),
fontSize: 16.0,
),
const VSpace(16.0),
Row(
children: [
Expanded(
child: FlowyText.semibold(
LocaleKeys.settings_appearance_members_user.tr(),
fontSize: 14.0,
),
),
Expanded(
child: FlowyText.semibold(
LocaleKeys.settings_appearance_members_role.tr(),
fontSize: 14.0,
),
),
const HSpace(28.0),
],
),
],
);
}
}
class _MemberItem extends StatelessWidget {
const _MemberItem({
required this.member,
required this.myRole,
required this.userProfile,
});
final WorkspaceMemberPB member;
final AFRolePB myRole;
final UserProfilePB userProfile;
@override
Widget build(BuildContext context) {
final textColor = member.role.isOwner ? Theme.of(context).hintColor : null;
return Row(
children: [
Expanded(
child: FlowyText.medium(
member.name,
color: textColor,
fontSize: 14.0,
),
),
Expanded(
child: member.role.isOwner || !myRole.canUpdate
? FlowyText.medium(
member.role.description,
color: textColor,
fontSize: 14.0,
)
: _MemberRoleActionList(
member: member,
),
),
myRole.canDelete &&
member.email != userProfile.email // can't delete self
? _MemberMoreActionList(member: member)
: const HSpace(28.0),
],
);
}
}
enum _MemberMoreAction {
delete,
}
class _MemberMoreActionList extends StatelessWidget {
const _MemberMoreActionList({
required this.member,
});
final WorkspaceMemberPB member;
@override
Widget build(BuildContext context) {
return PopoverActionList<_MemberMoreActionWrapper>(
asBarrier: true,
direction: PopoverDirection.bottomWithCenterAligned,
actions: _MemberMoreAction.values
.map((e) => _MemberMoreActionWrapper(e, member))
.toList(),
buildChild: (controller) {
return FlowyButton(
useIntrinsicWidth: true,
text: const FlowySvg(
FlowySvgs.three_dots_vertical_s,
),
onTap: () {
controller.show();
},
);
},
onSelected: (action, controller) {
switch (action.inner) {
case _MemberMoreAction.delete:
showDialog(
context: context,
builder: (_) => NavigatorOkCancelDialog(
title: LocaleKeys.settings_appearance_members_removeMember.tr(),
message: LocaleKeys
.settings_appearance_members_areYouSureToRemoveMember
.tr(),
onOkPressed: () => context.read<WorkspaceMemberBloc>().add(
WorkspaceMemberEvent.removeWorkspaceMember(
action.member.email,
),
),
okTitle: LocaleKeys.button_yes.tr(),
),
);
break;
}
controller.close();
},
);
}
}
class _MemberMoreActionWrapper extends ActionCell {
_MemberMoreActionWrapper(this.inner, this.member);
final _MemberMoreAction inner;
final WorkspaceMemberPB member;
@override
String get name {
switch (inner) {
case _MemberMoreAction.delete:
return LocaleKeys.settings_appearance_members_removeFromWorkspace.tr();
}
}
}
class _MemberRoleActionList extends StatelessWidget {
const _MemberRoleActionList({
required this.member,
});
final WorkspaceMemberPB member;
@override
Widget build(BuildContext context) {
return PopoverActionList<_MemberRoleActionWrapper>(
asBarrier: true,
direction: PopoverDirection.bottomWithLeftAligned,
actions: [AFRolePB.Member]
.map((e) => _MemberRoleActionWrapper(e, member))
.toList(),
offset: const Offset(0, 10),
buildChild: (controller) {
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => controller.show(),
child: Row(
children: [
FlowyText.medium(
member.role.description,
fontSize: 14.0,
),
const HSpace(8.0),
const FlowySvg(
FlowySvgs.drop_menu_show_s,
),
],
),
),
);
},
onSelected: (action, controller) async {
switch (action.inner) {
case AFRolePB.Member:
case AFRolePB.Guest:
context.read<WorkspaceMemberBloc>().add(
WorkspaceMemberEvent.updateWorkspaceMember(
action.member.email,
action.inner,
),
);
break;
case AFRolePB.Owner:
break;
}
controller.close();
},
);
}
}
class _MemberRoleActionWrapper extends ActionCell {
_MemberRoleActionWrapper(this.inner, this.member);
final AFRolePB inner;
final WorkspaceMemberPB member;
@override
Widget? rightIcon(Color iconColor) {
return SizedBox(
width: 58.0,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
FlowyTooltip(
message: tooltip,
child: const FlowySvg(
FlowySvgs.information_s,
// color: iconColor,
),
),
const Spacer(),
if (member.role == inner)
const FlowySvg(
FlowySvgs.checkmark_tiny_s,
),
],
),
);
}
@override
String get name {
switch (inner) {
case AFRolePB.Guest:
return LocaleKeys.settings_appearance_members_guest.tr();
case AFRolePB.Member:
return LocaleKeys.settings_appearance_members_member.tr();
case AFRolePB.Owner:
return LocaleKeys.settings_appearance_members_owner.tr();
}
throw UnimplementedError('Unknown role: $inner');
}
String get tooltip {
switch (inner) {
case AFRolePB.Guest:
return LocaleKeys.settings_appearance_members_guestHintText.tr();
case AFRolePB.Member:
return LocaleKeys.settings_appearance_members_memberHintText.tr();
case AFRolePB.Owner:
return '';
}
throw UnimplementedError('Unknown role: $inner');
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/members/workspace_member_bloc.dart | import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:collection/collection.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:protobuf/protobuf.dart';
part 'workspace_member_bloc.freezed.dart';
// 1. get the workspace members
// 2. display the content based on the user role
// Owner:
// - invite member button
// - delete member button
// - member list
// Member:
// Guest:
// - member list
class WorkspaceMemberBloc
extends Bloc<WorkspaceMemberEvent, WorkspaceMemberState> {
WorkspaceMemberBloc({
required this.userProfile,
this.workspace,
}) : _userBackendService = UserBackendService(userId: userProfile.id),
super(WorkspaceMemberState.initial()) {
on<WorkspaceMemberEvent>((event, emit) async {
await event.when(
initial: () async {
await _setCurrentWorkspaceId();
final result = await _userBackendService.getWorkspaceMembers(
_workspaceId,
);
final members = result.fold<List<WorkspaceMemberPB>>(
(s) => s.items,
(e) => [],
);
final myRole = _getMyRole(members);
emit(
state.copyWith(
members: members,
myRole: myRole,
isLoading: false,
actionResult: WorkspaceMemberActionResult(
actionType: WorkspaceMemberActionType.get,
result: result,
),
),
);
},
getWorkspaceMembers: () async {
final result = await _userBackendService.getWorkspaceMembers(
_workspaceId,
);
final members = result.fold<List<WorkspaceMemberPB>>(
(s) => s.items,
(e) => [],
);
final myRole = _getMyRole(members);
emit(
state.copyWith(
members: members,
myRole: myRole,
actionResult: WorkspaceMemberActionResult(
actionType: WorkspaceMemberActionType.get,
result: result,
),
),
);
},
addWorkspaceMember: (email) async {
final result = await _userBackendService.addWorkspaceMember(
_workspaceId,
email,
);
emit(
state.copyWith(
actionResult: WorkspaceMemberActionResult(
actionType: WorkspaceMemberActionType.add,
result: result,
),
),
);
// the addWorkspaceMember doesn't return the updated members,
// so we need to get the members again
result.onSuccess((s) {
add(const WorkspaceMemberEvent.getWorkspaceMembers());
});
},
removeWorkspaceMember: (email) async {
final result = await _userBackendService.removeWorkspaceMember(
_workspaceId,
email,
);
final members = result.fold(
(s) => state.members.where((e) => e.email != email).toList(),
(e) => state.members,
);
emit(
state.copyWith(
members: members,
actionResult: WorkspaceMemberActionResult(
actionType: WorkspaceMemberActionType.remove,
result: result,
),
),
);
},
updateWorkspaceMember: (email, role) async {
final result = await _userBackendService.updateWorkspaceMember(
_workspaceId,
email,
role,
);
final members = result.fold(
(s) => state.members.map((e) {
if (e.email == email) {
e.freeze();
return e.rebuild((p0) {
p0.role = role;
});
}
return e;
}).toList(),
(e) => state.members,
);
emit(
state.copyWith(
members: members,
actionResult: WorkspaceMemberActionResult(
actionType: WorkspaceMemberActionType.updateRole,
result: result,
),
),
);
},
);
});
}
final UserProfilePB userProfile;
// if the workspace is null, use the current workspace
final UserWorkspacePB? workspace;
late final String _workspaceId;
final UserBackendService _userBackendService;
AFRolePB _getMyRole(List<WorkspaceMemberPB> members) {
final role = members
.firstWhereOrNull(
(e) => e.email == userProfile.email,
)
?.role;
if (role == null) {
Log.error('Failed to get my role');
return AFRolePB.Guest;
}
return role;
}
Future<void> _setCurrentWorkspaceId() async {
if (workspace != null) {
_workspaceId = workspace!.workspaceId;
} else {
final currentWorkspace = await FolderEventReadCurrentWorkspace().send();
currentWorkspace.fold((s) {
_workspaceId = s.id;
}, (e) {
assert(false, 'Failed to read current workspace: $e');
Log.error('Failed to read current workspace: $e');
_workspaceId = '';
});
}
}
}
@freezed
class WorkspaceMemberEvent with _$WorkspaceMemberEvent {
const factory WorkspaceMemberEvent.initial() = Initial;
const factory WorkspaceMemberEvent.getWorkspaceMembers() =
GetWorkspaceMembers;
const factory WorkspaceMemberEvent.addWorkspaceMember(String email) =
AddWorkspaceMember;
const factory WorkspaceMemberEvent.removeWorkspaceMember(String email) =
RemoveWorkspaceMember;
const factory WorkspaceMemberEvent.updateWorkspaceMember(
String email,
AFRolePB role,
) = UpdateWorkspaceMember;
}
enum WorkspaceMemberActionType {
none,
get,
add,
remove,
updateRole,
}
class WorkspaceMemberActionResult {
const WorkspaceMemberActionResult({
required this.actionType,
required this.result,
});
final WorkspaceMemberActionType actionType;
final FlowyResult<void, FlowyError> result;
}
@freezed
class WorkspaceMemberState with _$WorkspaceMemberState {
const WorkspaceMemberState._();
const factory WorkspaceMemberState({
@Default([]) List<WorkspaceMemberPB> members,
@Default(AFRolePB.Guest) AFRolePB myRole,
@Default(null) WorkspaceMemberActionResult? actionResult,
@Default(true) bool isLoading,
}) = _WorkspaceMemberState;
factory WorkspaceMemberState.initial() => const WorkspaceMemberState();
@override
int get hashCode => runtimeType.hashCode;
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is WorkspaceMemberState &&
other.members == members &&
other.myRole == myRole &&
identical(other.actionResult, actionResult);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/emoji_shortcut_event.dart | import 'package:appflowy/workspace/presentation/settings/widgets/emoji_picker/emoji_picker.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
final CommandShortcutEvent emojiShortcutEvent = CommandShortcutEvent(
key: 'Ctrl + Alt + E to show emoji picker',
command: 'ctrl+alt+e',
macOSCommand: 'cmd+alt+e',
getDescription: () => 'Show an emoji picker',
handler: _emojiShortcutHandler,
);
CommandShortcutEventHandler _emojiShortcutHandler = (editorState) {
final selection = editorState.selection;
if (selection == null) {
return KeyEventResult.ignored;
}
final context = editorState.getNodeAtPath(selection.start.path)?.context;
if (context == null) {
return KeyEventResult.ignored;
}
final container = Overlay.of(context);
Alignment alignment = Alignment.topLeft;
Offset offset = Offset.zero;
final selectionService = editorState.service.selectionService;
final selectionRects = selectionService.selectionRects;
if (selectionRects.isEmpty) {
return KeyEventResult.ignored;
}
final rect = selectionRects.first;
// Calculate the offset and alignment
// Don't like these values being hardcoded but unsure how to grab the
// values dynamically to match the /emoji command.
const menuHeight = 200.0;
const menuOffset = Offset(10, 10); // Tried (0, 10) but that looked off
final editorOffset =
editorState.renderBox?.localToGlobal(Offset.zero) ?? Offset.zero;
final editorHeight = editorState.renderBox!.size.height;
final editorWidth = editorState.renderBox!.size.width;
// show below default
alignment = Alignment.topLeft;
final bottomRight = rect.bottomRight;
final topRight = rect.topRight;
final newOffset = bottomRight + menuOffset;
offset = Offset(
newOffset.dx,
newOffset.dy,
);
// show above
if (newOffset.dy + menuHeight >= editorOffset.dy + editorHeight) {
offset = topRight - menuOffset;
alignment = Alignment.bottomLeft;
offset = Offset(
newOffset.dx,
MediaQuery.of(context).size.height - newOffset.dy,
);
}
// show on left
if (offset.dx - editorOffset.dx > editorWidth / 2) {
alignment = alignment == Alignment.topLeft
? Alignment.topRight
: Alignment.bottomRight;
offset = Offset(
editorWidth - offset.dx + editorOffset.dx,
offset.dy,
);
}
showEmojiPickerMenu(
container,
editorState,
alignment,
offset,
);
return KeyEventResult.handled;
};
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/emoji_menu_item.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/base/emoji/emoji_picker.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/base/selectable_svg_widget.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/style_widget/decoration.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
SelectionMenuItem emojiMenuItem = SelectionMenuItem(
getName: LocaleKeys.document_plugins_emoji.tr,
icon: (editorState, onSelected, style) => SelectableIconWidget(
icon: Icons.emoji_emotions_outlined,
isSelected: onSelected,
style: style,
),
keywords: ['emoji'],
handler: (editorState, menuService, context) {
final container = Overlay.of(context);
menuService.dismiss();
showEmojiPickerMenu(
container,
editorState,
menuService.alignment,
menuService.offset,
);
},
);
void showEmojiPickerMenu(
OverlayState container,
EditorState editorState,
Alignment alignment,
Offset offset,
) {
final top = alignment == Alignment.topLeft ? offset.dy : null;
final bottom = alignment == Alignment.bottomLeft ? offset.dy : null;
keepEditorFocusNotifier.increase();
late OverlayEntry emojiPickerMenuEntry;
emojiPickerMenuEntry = FullScreenOverlayEntry(
top: top,
bottom: bottom,
left: offset.dx,
dismissCallback: () => keepEditorFocusNotifier.decrease(),
builder: (context) => Material(
type: MaterialType.transparency,
child: Container(
width: 360,
height: 380,
padding: const EdgeInsets.all(4.0),
decoration: FlowyDecoration.decoration(
Theme.of(context).cardColor,
Theme.of(context).colorScheme.shadow,
),
child: EmojiSelectionMenu(
onSubmitted: (emoji) {
editorState.insertTextAtCurrentSelection(emoji);
},
onExit: () {
// close emoji panel
emojiPickerMenuEntry.remove();
},
),
),
),
).build();
container.insert(emojiPickerMenuEntry);
}
class EmojiSelectionMenu extends StatefulWidget {
const EmojiSelectionMenu({
super.key,
required this.onSubmitted,
required this.onExit,
});
final void Function(String emoji) onSubmitted;
final void Function() onExit;
@override
State<EmojiSelectionMenu> createState() => _EmojiSelectionMenuState();
}
class _EmojiSelectionMenuState extends State<EmojiSelectionMenu> {
@override
void initState() {
HardwareKeyboard.instance.addHandler(_handleGlobalKeyEvent);
super.initState();
}
bool _handleGlobalKeyEvent(KeyEvent event) {
if (event.logicalKey == LogicalKeyboardKey.escape &&
event is KeyDownEvent) {
//triggers on esc
widget.onExit();
return true;
} else {
return false;
}
}
@override
void deactivate() {
HardwareKeyboard.instance.removeHandler(_handleGlobalKeyEvent);
super.deactivate();
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return FlowyEmojiPicker(
onEmojiSelected: (_, emoji) {
widget.onSubmitted(emoji);
},
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/emoji_picker.dart | export 'emoji_menu_item.dart';
export 'emoji_shortcut_event.dart';
export 'src/emji_picker_config.dart';
export 'src/emoji_picker.dart';
export 'src/emoji_picker_builder.dart';
export 'src/flowy_emoji_picker_config.dart';
export 'src/models/emoji_model.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src/emoji_lists.dart | // Copyright information
// File originally from https://github.com/JeffG05/emoji_picker
// import 'emoji.dart';
// final List<Map<String, String>> temp = [smileys, animals, foods, activities, travel, objects, symbols, flags];
// final List<Emoji> emojiSearchList = temp
// .map((element) {
// return element.entries.map<Emoji>((entry) => Emoji(entry.key, entry.value)).toList();
// })
// .toList()
// .first;
/// Map of all possible emojis along with their names in [Category.SMILEYS]
final Map<String, String> smileys = Map.fromIterables([
'Grinning Face',
'Grinning Face With Big Eyes',
'Grinning Face With Smiling Eyes',
'Beaming Face With Smiling Eyes',
'Grinning Squinting Face',
'Grinning Face With Sweat',
'Rolling on the Floor Laughing',
'Face With Tears of Joy',
'Slightly Smiling Face',
'Upside-Down Face',
'Winking Face',
'Smiling Face With Smiling Eyes',
'Smiling Face With Halo',
'Smiling Face With Hearts',
'Smiling Face With Heart-Eyes',
'Star-Struck',
'Face Blowing a Kiss',
'Kissing Face',
'Smiling Face',
'Kissing Face With Closed Eyes',
'Kissing Face With Smiling Eyes',
'Face Savoring Food',
'Face With Tongue',
'Winking Face With Tongue',
'Zany Face',
'Squinting Face With Tongue',
'Money-Mouth Face',
'Hugging Face',
'Face With Hand Over Mouth',
'Shushing Face',
'Thinking Face',
'Zipper-Mouth Face',
'Face With Raised Eyebrow',
'Neutral Face',
'Expressionless Face',
'Face Without Mouth',
'Smirking Face',
'Unamused Face',
'Face With Rolling Eyes',
'Grimacing Face',
'Lying Face',
'Relieved Face',
'Pensive Face',
'Sleepy Face',
'Drooling Face',
'Sleeping Face',
'Face With Medical Mask',
'Face With Thermometer',
'Face With Head-Bandage',
'Nauseated Face',
'Face Vomiting',
'Sneezing Face',
'Hot Face',
'Cold Face',
'Woozy Face',
'Dizzy Face',
'Exploding Head',
'Cowboy Hat Face',
'Partying Face',
'Smiling Face With Sunglasses',
'Nerd Face',
'Face With Monocle',
'Confused Face',
'Worried Face',
'Slightly Frowning Face',
'Frowning Face',
'Face With Open Mouth',
'Hushed Face',
'Astonished Face',
'Flushed Face',
'Pleading Face',
'Frowning Face With Open Mouth',
'Anguished Face',
'Fearful Face',
'Anxious Face With Sweat',
'Sad but Relieved Face',
'Crying Face',
'Loudly Crying Face',
'Face Screaming in Fear',
'Confounded Face',
'Persevering Face',
'Disappointed Face',
'Downcast Face With Sweat',
'Weary Face',
'Tired Face',
'Face With Steam From Nose',
'Pouting Face',
'Angry Face',
'Face With Symbols on Mouth',
'Smiling Face With Horns',
'Angry Face With Horns',
'Skull',
'Skull and Crossbones',
'Pile of Poo',
'Clown Face',
'Ogre',
'Goblin',
'Ghost',
'Alien',
'Alien Monster',
'Robot Face',
'Grinning Cat Face',
'Grinning Cat Face With Smiling Eyes',
'Cat Face With Tears of Joy',
'Smiling Cat Face With Heart-Eyes',
'Cat Face With Wry Smile',
'Kissing Cat Face',
'Weary Cat Face',
'Crying Cat Face',
'Pouting Cat Face',
'Kiss Mark',
'Waving Hand',
'Raised Back of Hand',
'Hand With Fingers Splayed',
'Raised Hand',
'Vulcan Salute',
'OK Hand',
'Victory Hand',
'Crossed Fingers',
'Love-You Gesture',
'Sign of the Horns',
'Call Me Hand',
'Backhand Index Pointing Left',
'Backhand Index Pointing Right',
'Backhand Index Pointing Up',
'Middle Finger',
'Backhand Index Pointing Down',
'Index Pointing Up',
'Thumbs Up',
'Thumbs Down',
'Raised Fist',
'Oncoming Fist',
'Left-Facing Fist',
'Right-Facing Fist',
'Clapping Hands',
'Raising Hands',
'Open Hands',
'Palms Up Together',
'Handshake',
'Folded Hands',
'Writing Hand',
'Nail Polish',
'Selfie',
'Flexed Biceps',
'Leg',
'Foot',
'Ear',
'Nose',
'Brain',
'Tooth',
'Bone',
'Eyes',
'Eye',
'Tongue',
'Mouth',
'Baby',
'Child',
'Boy',
'Girl',
'Person',
'Man',
'Man: Beard',
'Man: Blond Hair',
'Man: Red Hair',
'Man: Curly Hair',
'Man: White Hair',
'Man: Bald',
'Woman',
'Woman: Blond Hair',
'Woman: Red Hair',
'Woman: Curly Hair',
'Woman: White Hair',
'Woman: Bald',
'Older Person',
'Old Man',
'Old Woman',
'Man Frowning',
'Woman Frowning',
'Man Pouting',
'Woman Pouting',
'Man Gesturing No',
'Woman Gesturing No',
'Man Gesturing OK',
'Woman Gesturing OK',
'Man Tipping Hand',
'Woman Tipping Hand',
'Man Raising Hand',
'Woman Raising Hand',
'Man Bowing',
'Woman Bowing',
'Man Facepalming',
'Woman Facepalming',
'Man Shrugging',
'Woman Shrugging',
'Man Health Worker',
'Woman Health Worker',
'Man Student',
'Woman Student',
'Man Teacher',
'Woman Teacher',
'Man Judge',
'Woman Judge',
'Man Farmer',
'Woman Farmer',
'Man Cook',
'Woman Cook',
'Man Mechanic',
'Woman Mechanic',
'Man Factory Worker',
'Woman Factory Worker',
'Man Office Worker',
'Woman Office Worker',
'Man Scientist',
'Woman Scientist',
'Man Technologist',
'Woman Technologist',
'Man Singer',
'Woman Singer',
'Man Artist',
'Woman Artist',
'Man Pilot',
'Woman Pilot',
'Man Astronaut',
'Woman Astronaut',
'Man Firefighter',
'Woman Firefighter',
'Man Police Officer',
'Woman Police Officer',
'Man Detective',
'Woman Detective',
'Man Guard',
'Woman Guard',
'Man Construction Worker',
'Woman Construction Worker',
'Prince',
'Princess',
'Man Wearing Turban',
'Woman Wearing Turban',
'Man With Chinese Cap',
'Woman With Headscarf',
'Man in Tuxedo',
'Bride With Veil',
'Pregnant Woman',
'Breast-Feeding',
'Baby Angel',
'Santa Claus',
'Mrs. Claus',
'Man Superhero',
'Woman Superhero',
'Man Supervillain',
'Woman Supervillain',
'Man Mage',
'Woman Mage',
'Man Fairy',
'Woman Fairy',
'Man Vampire',
'Woman Vampire',
'Merman',
'Mermaid',
'Man Elf',
'Woman Elf',
'Man Genie',
'Woman Genie',
'Man Zombie',
'Woman Zombie',
'Man Getting Massage',
'Woman Getting Massage',
'Man Getting Haircut',
'Woman Getting Haircut',
'Man Walking',
'Woman Walking',
'Man Running',
'Woman Running',
'Woman Dancing',
'Man Dancing',
'Man in Suit Levitating',
'Men With Bunny Ears',
'Women With Bunny Ears',
'Man in Steamy Room',
'Woman in Steamy Room',
'Person in Lotus Position',
'Women Holding Hands',
'Woman and Man Holding Hands',
'Men Holding Hands',
'Kiss',
'Kiss: Man, Man',
'Kiss: Woman, Woman',
'Couple With Heart',
'Couple With Heart: Man, Man',
'Couple With Heart: Woman, Woman',
'Family',
'Family: Man, Woman, Boy',
'Family: Man, Woman, Girl',
'Family: Man, Woman, Girl, Boy',
'Family: Man, Woman, Boy, Boy',
'Family: Man, Woman, Girl, Girl',
'Family: Man, Man, Boy',
'Family: Man, Man, Girl',
'Family: Man, Man, Girl, Boy',
'Family: Man, Man, Boy, Boy',
'Family: Man, Man, Girl, Girl',
'Family: Woman, Woman, Boy',
'Family: Woman, Woman, Girl',
'Family: Woman, Woman, Girl, Boy',
'Family: Woman, Woman, Boy, Boy',
'Family: Woman, Woman, Girl, Girl',
'Family: Man, Boy',
'Family: Man, Boy, Boy',
'Family: Man, Girl',
'Family: Man, Girl, Boy',
'Family: Man, Girl, Girl',
'Family: Woman, Boy',
'Family: Woman, Boy, Boy',
'Family: Woman, Girl',
'Family: Woman, Girl, Boy',
'Family: Woman, Girl, Girl',
'Speaking Head',
'Bust in Silhouette',
'Busts in Silhouette',
'Footprints',
'Luggage',
'Closed Umbrella',
'Umbrella',
'Thread',
'Yarn',
'Glasses',
'Sunglasses',
'Goggles',
'Lab Coat',
'Necktie',
'T-Shirt',
'Jeans',
'Scarf',
'Gloves',
'Coat',
'Socks',
'Dress',
'Kimono',
'Bikini',
'Woman’s Clothes',
'Purse',
'Handbag',
'Clutch Bag',
'Backpack',
'Man’s Shoe',
'Running Shoe',
'Hiking Boot',
'Flat Shoe',
'High-Heeled Shoe',
'Woman’s Sandal',
'Woman’s Boot',
'Crown',
'Woman’s Hat',
'Top Hat',
'Graduation Cap',
'Billed Cap',
'Rescue Worker’s Helmet',
'Lipstick',
'Ring',
'Briefcase',
], [
'😀',
'😃',
'😄',
'😁',
'😆',
'😅',
'🤣',
'😂',
'🙂',
'🙃',
'😉',
'😊',
'😇',
'🥰',
'😍',
'🤩',
'😘',
'😗',
'☺',
'😚',
'😙',
'😋',
'😛',
'😜',
'🤪',
'😝',
'🤑',
'🤗',
'🤭',
'🤫',
'🤔',
'🤐',
'🤨',
'😐',
'😑',
'😶',
'😏',
'😒',
'🙄',
'😬',
'🤥',
'😌',
'😔',
'😪',
'🤤',
'😴',
'😷',
'🤒',
'🤕',
'🤢',
'🤮',
'🤧',
'🥵',
'🥶',
'🥴',
'😵',
'🤯',
'🤠',
'🥳',
'😎',
'🤓',
'🧐',
'😕',
'😟',
'🙁',
'☹️',
'😮',
'😯',
'😲',
'😳',
'🥺',
'😦',
'😧',
'😨',
'😰',
'😥',
'😢',
'😭',
'😱',
'😖',
'😣',
'😞',
'😓',
'😩',
'😫',
'😤',
'😡',
'😠',
'🤬',
'😈',
'👿',
'💀',
'☠',
'💩',
'🤡',
'👹',
'👺',
'👻',
'👽',
'👾',
'🤖',
'😺',
'😸',
'😹',
'😻',
'😼',
'😽',
'🙀',
'😿',
'😾',
'💋',
'👋',
'🤚',
'🖐',
'✋',
'🖖',
'👌',
'✌',
'🤞',
'🤟',
'🤘',
'🤙',
'👈',
'👉',
'👆',
'🖕',
'👇',
'☝',
'👍',
'👎',
'✊',
'👊',
'🤛',
'🤜',
'👏',
'🙌',
'👐',
'🤲',
'🤝',
'🙏',
'✍',
'💅',
'🤳',
'💪',
'🦵',
'🦶',
'👂',
'👃',
'🧠',
'🦷',
'🦴',
'👀',
'👁',
'👅',
'👄',
'👶',
'🧒',
'👦',
'👧',
'🧑',
'👨',
'🧔',
'👱',
'👨🦰',
'👨🦱',
'👨🦳',
'👨🦲',
'👩',
'👱',
'👩🦰',
'👩🦱',
'👩🦳',
'👩🦲',
'🧓',
'👴',
'👵',
'🙍',
'🙍',
'🙎',
'🙎',
'🙅',
'🙅',
'🙆',
'🙆',
'💁',
'💁',
'🙋',
'🙋',
'🙇',
'🙇',
'🤦',
'🤦',
'🤷',
'🤷',
'👨⚕️',
'👩⚕️',
'👨🎓',
'👩🎓',
'👨🏫',
'👩🏫',
'👨⚖️',
'👩⚖️',
'👨🌾',
'👩🌾',
'👨🍳',
'👩🍳',
'👨🔧',
'👩🔧',
'👨🏭',
'👩🏭',
'👨💼',
'👩💼',
'👨🔬',
'👩🔬',
'👨💻',
'👩💻',
'👨🎤',
'👩🎤',
'👨🎨',
'👩🎨',
'👨✈️',
'👩✈️',
'👨🚀',
'👩🚀',
'👨🚒',
'👩🚒',
'👮',
'👮',
'🕵️',
'🕵️',
'💂',
'💂',
'👷',
'👷',
'🤴',
'👸',
'👳',
'👳',
'👲',
'🧕',
'🤵',
'👰',
'🤰',
'🤱',
'👼',
'🎅',
'🤶',
'🦸',
'🦸',
'🦹',
'🦹',
'🧙',
'🧙',
'🧚',
'🧚',
'🧛',
'🧛',
'🧜',
'🧜',
'🧝',
'🧝',
'🧞',
'🧞',
'🧟',
'🧟',
'💆',
'💆',
'💇',
'💇',
'🚶',
'🚶',
'🏃',
'🏃',
'💃',
'🕺',
'🕴',
'👯',
'👯',
'🧖',
'🧖',
'🧘',
'👭',
'👫',
'👬',
'💏',
'👨❤️💋👨',
'👩❤️💋👩',
'💑',
'👨❤️👨',
'👩❤️👩',
'👪',
'👨👩👦',
'👨👩👧',
'👨👩👧👦',
'👨👩👦👦',
'👨👩👧👧',
'👨👨👦',
'👨👨👧',
'👨👨👧👦',
'👨👨👦👦',
'👨👨👧👧',
'👩👩👦',
'👩👩👧',
'👩👩👧👦',
'👩👩👦👦',
'👩👩👧👧',
'👨👦',
'👨👦👦',
'👨👧',
'👨👧👦',
'👨👧👧',
'👩👦',
'👩👦👦',
'👩👧',
'👩👧👦',
'👩👧👧',
'🗣',
'👤',
'👥',
'👣',
'🧳',
'🌂',
'☂',
'🧵',
'🧶',
'👓',
'🕶',
'🥽',
'🥼',
'👔',
'👕',
'👖',
'🧣',
'🧤',
'🧥',
'🧦',
'👗',
'👘',
'👙',
'👚',
'👛',
'👜',
'👝',
'🎒',
'👞',
'👟',
'🥾',
'🥿',
'👠',
'👡',
'👢',
'👑',
'👒',
'🎩',
'🎓',
'🧢',
'⛑',
'💄',
'💍',
'💼',
]);
/// Map of all possible emojis along with their names in [Category.ANIMALS]
final Map<String, String> animals = Map.fromIterables([
'Dog Face',
'Cat Face',
'Mouse Face',
'Hamster Face',
'Rabbit Face',
'Fox Face',
'Bear Face',
'Panda Face',
'Koala Face',
'Tiger Face',
'Lion Face',
'Cow Face',
'Pig Face',
'Pig Nose',
'Frog Face',
'Monkey Face',
'See-No-Evil Monkey',
'Hear-No-Evil Monkey',
'Speak-No-Evil Monkey',
'Monkey',
'Collision',
'Dizzy',
'Sweat Droplets',
'Dashing Away',
'Gorilla',
'Dog',
'Poodle',
'Wolf Face',
'Raccoon',
'Cat',
'Tiger',
'Leopard',
'Horse Face',
'Horse',
'Unicorn Face',
'Zebra',
'Ox',
'Water Buffalo',
'Cow',
'Pig',
'Boar',
'Ram',
'Ewe',
'Goat',
'Camel',
'Two-Hump Camel',
'Llama',
'Giraffe',
'Elephant',
'Rhinoceros',
'Hippopotamus',
'Mouse',
'Rat',
'Rabbit',
'Chipmunk',
'Hedgehog',
'Bat',
'Kangaroo',
'Badger',
'Paw Prints',
'Turkey',
'Chicken',
'Rooster',
'Hatching Chick',
'Baby Chick',
'Front-Facing Baby Chick',
'Bird',
'Penguin',
'Dove',
'Eagle',
'Duck',
'Swan',
'Owl',
'Peacock',
'Parrot',
'Crocodile',
'Turtle',
'Lizard',
'Snake',
'Dragon Face',
'Dragon',
'Sauropod',
'T-Rex',
'Spouting Whale',
'Whale',
'Dolphin',
'Fish',
'Tropical Fish',
'Blowfish',
'Shark',
'Octopus',
'Spiral Shell',
'Snail',
'Butterfly',
'Bug',
'Ant',
'Honeybee',
'Lady Beetle',
'Cricket',
'Spider',
'Spider Web',
'Scorpion',
'Mosquito',
'Microbe',
'Bouquet',
'Cherry Blossom',
'White Flower',
'Rosette',
'Rose',
'Wilted Flower',
'Hibiscus',
'Sunflower',
'Blossom',
'Tulip',
'Seedling',
'Evergreen Tree',
'Deciduous Tree',
'Palm Tree',
'Cactus',
'Sheaf of Rice',
'Herb',
'Shamrock',
'Four Leaf Clover',
'Maple Leaf',
'Fallen Leaf',
'Leaf Fluttering in Wind',
'Mushroom',
'Chestnut',
'Crab',
'Lobster',
'Shrimp',
'Squid',
'Globe Showing Europe-Africa',
'Globe Showing Americas',
'Globe Showing Asia-Australia',
'Globe With Meridians',
'New Moon',
'Waxing Crescent Moon',
'First Quarter Moon',
'Waxing Gibbous Moon',
'Full Moon',
'Waning Gibbous Moon',
'Last Quarter Moon',
'Waning Crescent Moon',
'Crescent Moon',
'New Moon Face',
'First Quarter Moon Face',
'Last Quarter Moon Face',
'Sun',
'Full Moon Face',
'Sun With Face',
'Star',
'Glowing Star',
'Shooting Star',
'Cloud',
'Sun Behind Cloud',
'Cloud With Lightning and Rain',
'Sun Behind Small Cloud',
'Sun Behind Large Cloud',
'Sun Behind Rain Cloud',
'Cloud With Rain',
'Cloud With Snow',
'Cloud With Lightning',
'Tornado',
'Fog',
'Wind Face',
'Rainbow',
'Umbrella',
'Umbrella With Rain Drops',
'High Voltage',
'Snowflake',
'Snowman Without Snow',
'Snowman',
'Comet',
'Fire',
'Droplet',
'Water Wave',
'Christmas Tree',
'Sparkles',
'Tanabata Tree',
'Pine Decoration',
], [
'🐶',
'🐱',
'🐭',
'🐹',
'🐰',
'🦊',
'🐻',
'🐼',
'🐨',
'🐯',
'🦁',
'🐮',
'🐷',
'🐽',
'🐸',
'🐵',
'🙈',
'🙉',
'🙊',
'🐒',
'💥',
'💫',
'💦',
'💨',
'🦍',
'🐕',
'🐩',
'🐺',
'🦝',
'🐈',
'🐅',
'🐆',
'🐴',
'🐎',
'🦄',
'🦓',
'🐂',
'🐃',
'🐄',
'🐖',
'🐗',
'🐏',
'🐑',
'🐐',
'🐪',
'🐫',
'🦙',
'🦒',
'🐘',
'🦏',
'🦛',
'🐁',
'🐀',
'🐇',
'🐿',
'🦔',
'🦇',
'🦘',
'🦡',
'🐾',
'🦃',
'🐔',
'🐓',
'🐣',
'🐤',
'🐥',
'🐦',
'🐧',
'🕊',
'🦅',
'🦆',
'🦢',
'🦉',
'🦚',
'🦜',
'🐊',
'🐢',
'🦎',
'🐍',
'🐲',
'🐉',
'🦕',
'🦖',
'🐳',
'🐋',
'🐬',
'🐟',
'🐠',
'🐡',
'🦈',
'🐙',
'🐚',
'🐌',
'🦋',
'🐛',
'🐜',
'🐝',
'🐞',
'🦗',
'🕷',
'🕸',
'🦂',
'🦟',
'🦠',
'💐',
'🌸',
'💮',
'🏵',
'🌹',
'🥀',
'🌺',
'🌻',
'🌼',
'🌷',
'🌱',
'🌲',
'🌳',
'🌴',
'🌵',
'🌾',
'🌿',
'☘',
'🍀',
'🍁',
'🍂',
'🍃',
'🍄',
'🌰',
'🦀',
'🦞',
'🦐',
'🦑',
'🌍',
'🌎',
'🌏',
'🌐',
'🌑',
'🌒',
'🌓',
'🌔',
'🌕',
'🌖',
'🌗',
'🌘',
'🌙',
'🌚',
'🌛',
'🌜',
'☀',
'🌝',
'🌞',
'⭐',
'🌟',
'🌠',
'☁',
'⛅',
'⛈',
'🌤',
'🌥',
'🌦',
'🌧',
'🌨',
'🌩',
'🌪',
'🌫',
'🌬',
'🌈',
'☂',
'☔',
'⚡',
'❄',
'☃',
'⛄',
'☄',
'🔥',
'💧',
'🌊',
'🎄',
'✨',
'🎋',
'🎍',
]);
/// Map of all possible emojis along with their names in [Category.FOODS]
final Map<String, String> foods = Map.fromIterables([
'Grapes',
'Melon',
'Watermelon',
'Tangerine',
'Lemon',
'Banana',
'Pineapple',
'Mango',
'Red Apple',
'Green Apple',
'Pear',
'Peach',
'Cherries',
'Strawberry',
'Kiwi Fruit',
'Tomato',
'Coconut',
'Avocado',
'Eggplant',
'Potato',
'Carrot',
'Ear of Corn',
'Hot Pepper',
'Cucumber',
'Leafy Green',
'Broccoli',
'Mushroom',
'Peanuts',
'Chestnut',
'Bread',
'Croissant',
'Baguette Bread',
'Pretzel',
'Bagel',
'Pancakes',
'Cheese Wedge',
'Meat on Bone',
'Poultry Leg',
'Cut of Meat',
'Bacon',
'Hamburger',
'French Fries',
'Pizza',
'Hot Dog',
'Sandwich',
'Taco',
'Burrito',
'Stuffed Flatbread',
'Cooking',
'Shallow Pan of Food',
'Pot of Food',
'Bowl With Spoon',
'Green Salad',
'Popcorn',
'Salt',
'Canned Food',
'Bento Box',
'Rice Cracker',
'Rice Ball',
'Cooked Rice',
'Curry Rice',
'Steaming Bowl',
'Spaghetti',
'Roasted Sweet Potato',
'Oden',
'Sushi',
'Fried Shrimp',
'Fish Cake With Swirl',
'Moon Cake',
'Dango',
'Dumpling',
'Fortune Cookie',
'Takeout Box',
'Soft Ice Cream',
'Shaved Ice',
'Ice Cream',
'Doughnut',
'Cookie',
'Birthday Cake',
'Shortcake',
'Cupcake',
'Pie',
'Chocolate Bar',
'Candy',
'Lollipop',
'Custard',
'Honey Pot',
'Baby Bottle',
'Glass of Milk',
'Hot Beverage',
'Teacup Without Handle',
'Sake',
'Bottle With Popping Cork',
'Wine Glass',
'Cocktail Glass',
'Tropical Drink',
'Beer Mug',
'Clinking Beer Mugs',
'Clinking Glasses',
'Tumbler Glass',
'Cup With Straw',
'Chopsticks',
'Fork and Knife With Plate',
'Fork and Knife',
'Spoon',
], [
'🍇',
'🍈',
'🍉',
'🍊',
'🍋',
'🍌',
'🍍',
'🥭',
'🍎',
'🍏',
'🍐',
'🍑',
'🍒',
'🍓',
'🥝',
'🍅',
'🥥',
'🥑',
'🍆',
'🥔',
'🥕',
'🌽',
'🌶',
'🥒',
'🥬',
'🥦',
'🍄',
'🥜',
'🌰',
'🍞',
'🥐',
'🥖',
'🥨',
'🥯',
'🥞',
'🧀',
'🍖',
'🍗',
'🥩',
'🥓',
'🍔',
'🍟',
'🍕',
'🌭',
'🥪',
'🌮',
'🌯',
'🥙',
'🍳',
'🥘',
'🍲',
'🥣',
'🥗',
'🍿',
'🧂',
'🥫',
'🍱',
'🍘',
'🍙',
'🍚',
'🍛',
'🍜',
'🍝',
'🍠',
'🍢',
'🍣',
'🍤',
'🍥',
'🥮',
'🍡',
'🥟',
'🥠',
'🥡',
'🍦',
'🍧',
'🍨',
'🍩',
'🍪',
'🎂',
'🍰',
'🧁',
'🥧',
'🍫',
'🍬',
'🍭',
'🍮',
'🍯',
'🍼',
'🥛',
'☕',
'🍵',
'🍶',
'🍾',
'🍷',
'🍸',
'🍹',
'🍺',
'🍻',
'🥂',
'🥃',
'🥤',
'🥢',
'🍽',
'🍴',
'🥄',
]);
/// Map of all possible emojis along with their names in [Category.TRAVEL]
final Map<String, String> travel = Map.fromIterables([
'Person Rowing Boat',
'Map of Japan',
'Snow-Capped Mountain',
'Mountain',
'Volcano',
'Mount Fuji',
'Camping',
'Beach With Umbrella',
'Desert',
'Desert Island',
'National Park',
'Stadium',
'Classical Building',
'Building Construction',
'Houses',
'Derelict House',
'House',
'House With Garden',
'Office Building',
'Japanese Post Office',
'Post Office',
'Hospital',
'Bank',
'Hotel',
'Love Hotel',
'Convenience Store',
'School',
'Department Store',
'Factory',
'Japanese Castle',
'Castle',
'Wedding',
'Tokyo Tower',
'Statue of Liberty',
'Church',
'Mosque',
'Synagogue',
'Shinto Shrine',
'Kaaba',
'Fountain',
'Tent',
'Foggy',
'Night With Stars',
'Cityscape',
'Sunrise Over Mountains',
'Sunrise',
'Cityscape at Dusk',
'Sunset',
'Bridge at Night',
'Carousel Horse',
'Ferris Wheel',
'Roller Coaster',
'Locomotive',
'Railway Car',
'High-Speed Train',
'Bullet Train',
'Train',
'Metro',
'Light Rail',
'Station',
'Tram',
'Monorail',
'Mountain Railway',
'Tram Car',
'Bus',
'Oncoming Bus',
'Trolleybus',
'Minibus',
'Ambulance',
'Fire Engine',
'Police Car',
'Oncoming Police Car',
'Taxi',
'Oncoming Taxi',
'Automobile',
'Oncoming Automobile',
'Delivery Truck',
'Articulated Lorry',
'Tractor',
'Racing Car',
'Motorcycle',
'Motor Scooter',
'Bicycle',
'Kick Scooter',
'Bus Stop',
'Railway Track',
'Fuel Pump',
'Police Car Light',
'Horizontal Traffic Light',
'Vertical Traffic Light',
'Construction',
'Anchor',
'Sailboat',
'Speedboat',
'Passenger Ship',
'Ferry',
'Motor Boat',
'Ship',
'Airplane',
'Small Airplane',
'Airplane Departure',
'Airplane Arrival',
'Seat',
'Helicopter',
'Suspension Railway',
'Mountain Cableway',
'Aerial Tramway',
'Satellite',
'Rocket',
'Flying Saucer',
'Shooting Star',
'Milky Way',
'Umbrella on Ground',
'Fireworks',
'Sparkler',
'Moon Viewing Ceremony',
'Yen Banknote',
'Dollar Banknote',
'Euro Banknote',
'Pound Banknote',
'Moai',
'Passport Control',
'Customs',
'Baggage Claim',
'Left Luggage',
], [
'🚣',
'🗾',
'🏔',
'⛰',
'🌋',
'🗻',
'🏕',
'🏖',
'🏜',
'🏝',
'🏞',
'🏟',
'🏛',
'🏗',
'🏘',
'🏚',
'🏠',
'🏡',
'🏢',
'🏣',
'🏤',
'🏥',
'🏦',
'🏨',
'🏩',
'🏪',
'🏫',
'🏬',
'🏭',
'🏯',
'🏰',
'💒',
'🗼',
'🗽',
'⛪',
'🕌',
'🕍',
'⛩',
'🕋',
'⛲',
'⛺',
'🌁',
'🌃',
'🏙',
'🌄',
'🌅',
'🌆',
'🌇',
'🌉',
'🎠',
'🎡',
'🎢',
'🚂',
'🚃',
'🚄',
'🚅',
'🚆',
'🚇',
'🚈',
'🚉',
'🚊',
'🚝',
'🚞',
'🚋',
'🚌',
'🚍',
'🚎',
'🚐',
'🚑',
'🚒',
'🚓',
'🚔',
'🚕',
'🚖',
'🚗',
'🚘',
'🚚',
'🚛',
'🚜',
'🏎',
'🏍',
'🛵',
'🚲',
'🛴',
'🚏',
'🛤',
'⛽',
'🚨',
'🚥',
'🚦',
'🚧',
'⚓',
'⛵',
'🚤',
'🛳',
'⛴',
'🛥',
'🚢',
'✈',
'🛩',
'🛫',
'🛬',
'💺',
'🚁',
'🚟',
'🚠',
'🚡',
'🛰',
'🚀',
'🛸',
'🌠',
'🌌',
'⛱',
'🎆',
'🎇',
'🎑',
'💴',
'💵',
'💶',
'💷',
'🗿',
'🛂',
'🛃',
'🛄',
'🛅',
]);
/// Map of all possible emojis along with their names in [Category.ACTIVITIES]
final Map<String, String> activities = Map.fromIterables([
'Man in Suit Levitating',
'Man Climbing',
'Woman Climbing',
'Horse Racing',
'Skier',
'Snowboarder',
'Man Golfing',
'Woman Golfing',
'Man Surfing',
'Woman Surfing',
'Man Rowing Boat',
'Woman Rowing Boat',
'Man Swimming',
'Woman Swimming',
'Man Bouncing Ball',
'Woman Bouncing Ball',
'Man Lifting Weights',
'Woman Lifting Weights',
'Man Biking',
'Woman Biking',
'Man Mountain Biking',
'Woman Mountain Biking',
'Man Cartwheeling',
'Woman Cartwheeling',
'Men Wrestling',
'Women Wrestling',
'Man Playing Water Polo',
'Woman Playing Water Polo',
'Man Playing Handball',
'Woman Playing Handball',
'Man Juggling',
'Woman Juggling',
'Man in Lotus Position',
'Woman in Lotus Position',
'Circus Tent',
'Skateboard',
'Reminder Ribbon',
'Admission Tickets',
'Ticket',
'Military Medal',
'Trophy',
'Sports Medal',
'1st Place Medal',
'2nd Place Medal',
'3rd Place Medal',
'Soccer Ball',
'Baseball',
'Softball',
'Basketball',
'Volleyball',
'American Football',
'Rugby Football',
'Tennis',
'Flying Disc',
'Bowling',
'Cricket Game',
'FieldPB Hockey',
'Ice Hockey',
'Lacrosse',
'Ping Pong',
'Badminton',
'Boxing Glove',
'Martial Arts Uniform',
'Flag in Hole',
'Ice Skate',
'Fishing Pole',
'Running Shirt',
'Skis',
'Sled',
'Curling Stone',
'Direct Hit',
'Pool 8 Ball',
'Video Game',
'Slot Machine',
'Game Die',
'Jigsaw',
'Chess Pawn',
'Performing Arts',
'Artist Palette',
'Thread',
'Yarn',
'Musical Score',
'Microphone',
'Headphone',
'Saxophone',
'Guitar',
'Musical Keyboard',
'Trumpet',
'Violin',
'Drum',
'Clapper Board',
'Bow and Arrow',
], [
'🕴',
'🧗',
'🧗',
'🏇',
'⛷',
'🏂',
'🏌️',
'🏌️',
'🏄',
'🏄',
'🚣',
'🚣',
'🏊',
'🏊',
'⛹️',
'⛹️',
'🏋️',
'🏋️',
'🚴',
'🚴',
'🚵',
'🚵',
'🤸',
'🤸',
'🤼',
'🤼',
'🤽',
'🤽',
'🤾',
'🤾',
'🤹',
'🤹',
'🧘🏻♂️',
'🧘🏻♀️',
'🎪',
'🛹',
'🎗',
'🎟',
'🎫',
'🎖',
'🏆',
'🏅',
'🥇',
'🥈',
'🥉',
'⚽',
'⚾',
'🥎',
'🏀',
'🏐',
'🏈',
'🏉',
'🎾',
'🥏',
'🎳',
'🏏',
'🏑',
'🏒',
'🥍',
'🏓',
'🏸',
'🥊',
'🥋',
'⛳',
'⛸',
'🎣',
'🎽',
'🎿',
'🛷',
'🥌',
'🎯',
'🎱',
'🎮',
'🎰',
'🎲',
'🧩',
'♟',
'🎭',
'🎨',
'🧵',
'🧶',
'🎼',
'🎤',
'🎧',
'🎷',
'🎸',
'🎹',
'🎺',
'🎻',
'🥁',
'🎬',
'🏹',
]);
/// Map of all possible emojis along with their names in [Category.OBJECTS]
final Map<String, String> objects = Map.fromIterables([
'Love Letter',
'Hole',
'Bomb',
'Person Taking Bath',
'Person in Bed',
'Kitchen Knife',
'Amphora',
'World Map',
'Compass',
'Brick',
'Barber Pole',
'Oil Drum',
'Bellhop Bell',
'Luggage',
'Hourglass Done',
'Hourglass Not Done',
'Watch',
'Alarm Clock',
'Stopwatch',
'Timer Clock',
'Mantelpiece Clock',
'Thermometer',
'Umbrella on Ground',
'Firecracker',
'Balloon',
'Party Popper',
'Confetti Ball',
'Japanese Dolls',
'Carp Streamer',
'Wind Chime',
'Red Envelope',
'Ribbon',
'Wrapped Gift',
'Crystal Ball',
'Nazar Amulet',
'Joystick',
'Teddy Bear',
'Framed Picture',
'Thread',
'Yarn',
'Shopping Bags',
'Prayer Beads',
'Gem Stone',
'Postal Horn',
'Studio Microphone',
'Level Slider',
'Control Knobs',
'Radio',
'Mobile Phone',
'Mobile Phone With Arrow',
'Telephone',
'Telephone Receiver',
'Pager',
'Fax Machine',
'Battery',
'Electric Plug',
'Laptop Computer',
'Desktop Computer',
'Printer',
'Keyboard',
'Computer Mouse',
'Trackball',
'Computer Disk',
'Floppy Disk',
'Optical Disk',
'DVD',
'Abacus',
'Movie Camera',
'Film Frames',
'Film Projector',
'Television',
'Camera',
'Camera With Flash',
'Video Camera',
'Videocassette',
'Magnifying Glass Tilted Left',
'Magnifying Glass Tilted Right',
'Candle',
'Light Bulb',
'Flashlight',
'Red Paper Lantern',
'Notebook With Decorative Cover',
'Closed Book',
'Open Book',
'Green Book',
'Blue Book',
'Orange Book',
'Books',
'Notebook',
'Page With Curl',
'Scroll',
'Page Facing Up',
'Newspaper',
'Rolled-Up Newspaper',
'Bookmark Tabs',
'Bookmark',
'Label',
'Money Bag',
'Yen Banknote',
'Dollar Banknote',
'Euro Banknote',
'Pound Banknote',
'Money With Wings',
'Credit Card',
'Receipt',
'Envelope',
'E-Mail',
'Incoming Envelope',
'Envelope With Arrow',
'Outbox Tray',
'Inbox Tray',
'Package',
'Closed Mailbox With Raised Flag',
'Closed Mailbox With Lowered Flag',
'Open Mailbox With Raised Flag',
'Open Mailbox With Lowered Flag',
'Postbox',
'Ballot Box With Ballot',
'Pencil',
'Black Nib',
'Fountain Pen',
'Pen',
'Paintbrush',
'Crayon',
'Memo',
'File Folder',
'Open File Folder',
'Card Index Dividers',
'Calendar',
'Tear-Off Calendar',
'Spiral Notepad',
'Spiral Calendar',
'Card Index',
'Chart Increasing',
'Chart Decreasing',
'Bar Chart',
'Clipboard',
'Pushpin',
'Round Pushpin',
'Paperclip',
'Linked Paperclips',
'Straight Ruler',
'Triangular Ruler',
'Scissors',
'Card File Box',
'File Cabinet',
'Wastebasket',
'Locked',
'Unlocked',
'Locked With Pen',
'Locked With Key',
'Key',
'Old Key',
'Hammer',
'Pick',
'Hammer and Pick',
'Hammer and Wrench',
'Dagger',
'Crossed Swords',
'Pistol',
'Shield',
'Wrench',
'Nut and Bolt',
'Gear',
'Clamp',
'Balance Scale',
'Link',
'Chains',
'Toolbox',
'Magnet',
'Alembic',
'Test Tube',
'Petri Dish',
'DNA',
'Microscope',
'Telescope',
'Satellite Antenna',
'Syringe',
'Pill',
'Door',
'Bed',
'Couch and Lamp',
'Toilet',
'Shower',
'Bathtub',
'Lotion Bottle',
'Safety Pin',
'Broom',
'Basket',
'Roll of Paper',
'Soap',
'Sponge',
'Fire Extinguisher',
'Cigarette',
'Coffin',
'Funeral Urn',
'Moai',
'Potable Water',
], [
'💌',
'🕳',
'💣',
'🛀',
'🛌',
'🔪',
'🏺',
'🗺',
'🧭',
'🧱',
'💈',
'🛢',
'🛎',
'🧳',
'⌛',
'⏳',
'⌚',
'⏰',
'⏱',
'⏲',
'🕰',
'🌡',
'⛱',
'🧨',
'🎈',
'🎉',
'🎊',
'🎎',
'🎏',
'🎐',
'🧧',
'🎀',
'🎁',
'🔮',
'🧿',
'🕹',
'🧸',
'🖼',
'🧵',
'🧶',
'🛍',
'📿',
'💎',
'📯',
'🎙',
'🎚',
'🎛',
'📻',
'📱',
'📲',
'☎',
'📞',
'📟',
'📠',
'🔋',
'🔌',
'💻',
'🖥',
'🖨',
'⌨',
'🖱',
'🖲',
'💽',
'💾',
'💿',
'📀',
'🧮',
'🎥',
'🎞',
'📽',
'📺',
'📷',
'📸',
'📹',
'📼',
'🔍',
'🔎',
'🕯',
'💡',
'🔦',
'🏮',
'📔',
'📕',
'📖',
'📗',
'📘',
'📙',
'📚',
'📓',
'📃',
'📜',
'📄',
'📰',
'🗞',
'📑',
'🔖',
'🏷',
'💰',
'💴',
'💵',
'💶',
'💷',
'💸',
'💳',
'🧾',
'✉',
'📧',
'📨',
'📩',
'📤',
'📥',
'📦',
'📫',
'📪',
'📬',
'📭',
'📮',
'🗳',
'✏',
'✒',
'🖋',
'🖊',
'🖌',
'🖍',
'📝',
'📁',
'📂',
'🗂',
'📅',
'📆',
'🗒',
'🗓',
'📇',
'📈',
'📉',
'📊',
'📋',
'📌',
'📍',
'📎',
'🖇',
'📏',
'📐',
'✂',
'🗃',
'🗄',
'🗑',
'🔒',
'🔓',
'🔏',
'🔐',
'🔑',
'🗝',
'🔨',
'⛏',
'⚒',
'🛠',
'🗡',
'⚔',
'🔫',
'🛡',
'🔧',
'🔩',
'⚙',
'🗜',
'⚖',
'🔗',
'⛓',
'🧰',
'🧲',
'⚗',
'🧪',
'🧫',
'🧬',
'🔬',
'🔭',
'📡',
'💉',
'💊',
'🚪',
'🛏',
'🛋',
'🚽',
'🚿',
'🛁',
'🧴',
'🧷',
'🧹',
'🧺',
'🧻',
'🧼',
'🧽',
'🧯',
'🚬',
'⚰',
'⚱',
'🗿',
'🚰',
]);
/// Map of all possible emojis along with their names in [Category.SYMBOLS]
final Map<String, String> symbols = Map.fromIterables([
'Heart With Arrow',
'Heart With Ribbon',
'Sparkling Heart',
'Growing Heart',
'Beating Heart',
'Revolving Hearts',
'Two Hearts',
'Heart Decoration',
'Heavy Heart Exclamation',
'Broken Heart',
'Red Heart',
'Orange Heart',
'Yellow Heart',
'Green Heart',
'Blue Heart',
'Purple Heart',
'Black Heart',
'Hundred Points',
'Anger Symbol',
'Speech Balloon',
'Eye in Speech Bubble',
'Right Anger Bubble',
'Thought Balloon',
'Zzz',
'White Flower',
'Hot Springs',
'Barber Pole',
'Stop Sign',
'Twelve O’Clock',
'Twelve-Thirty',
'One O’Clock',
'One-Thirty',
'Two O’Clock',
'Two-Thirty',
'Three O’Clock',
'Three-Thirty',
'Four O’Clock',
'Four-Thirty',
'Five O’Clock',
'Five-Thirty',
'Six O’Clock',
'Six-Thirty',
'Seven O’Clock',
'Seven-Thirty',
'Eight O’Clock',
'Eight-Thirty',
'Nine O’Clock',
'Nine-Thirty',
'Ten O’Clock',
'Ten-Thirty',
'Eleven O’Clock',
'Eleven-Thirty',
'Cyclone',
'Spade Suit',
'Heart Suit',
'Diamond Suit',
'Club Suit',
'Joker',
'Mahjong Red Dragon',
'Flower Playing Cards',
'Muted Speaker',
'Speaker Low Volume',
'Speaker Medium Volume',
'Speaker High Volume',
'Loudspeaker',
'Megaphone',
'Postal Horn',
'Bell',
'Bell With Slash',
'Musical Note',
'Musical Notes',
'ATM Sign',
'Litter in Bin Sign',
'Potable Water',
'Wheelchair Symbol',
'Men’s Room',
'Women’s Room',
'Restroom',
'Baby Symbol',
'Water Closet',
'Warning',
'Children Crossing',
'No Entry',
'Prohibited',
'No Bicycles',
'No Smoking',
'No Littering',
'Non-Potable Water',
'No Pedestrians',
'No One Under Eighteen',
'Radioactive',
'Biohazard',
'Up Arrow',
'Up-Right Arrow',
'Right Arrow',
'Down-Right Arrow',
'Down Arrow',
'Down-Left Arrow',
'Left Arrow',
'Up-Left Arrow',
'Up-Down Arrow',
'Left-Right Arrow',
'Right Arrow Curving Left',
'Left Arrow Curving Right',
'Right Arrow Curving Up',
'Right Arrow Curving Down',
'Clockwise Vertical Arrows',
'Counterclockwise Arrows Button',
'Back Arrow',
'End Arrow',
'On! Arrow',
'Soon Arrow',
'Top Arrow',
'Place of Worship',
'Atom Symbol',
'Om',
'Star of David',
'Wheel of Dharma',
'Yin Yang',
'Latin Cross',
'Orthodox Cross',
'Star and Crescent',
'Peace Symbol',
'Menorah',
'Dotted Six-Pointed Star',
'Aries',
'Taurus',
'Gemini',
'Cancer',
'Leo',
'Virgo',
'Libra',
'Scorpio',
'Sagittarius',
'Capricorn',
'Aquarius',
'Pisces',
'Ophiuchus',
'Shuffle Tracks Button',
'Repeat Button',
'Repeat Single Button',
'Play Button',
'Fast-Forward Button',
'Reverse Button',
'Fast Reverse Button',
'Upwards Button',
'Fast Up Button',
'Downwards Button',
'Fast Down Button',
'Stop Button',
'Eject Button',
'Cinema',
'Dim Button',
'Bright Button',
'Antenna Bars',
'Vibration Mode',
'Mobile Phone Off',
'Infinity',
'Recycling Symbol',
'Trident Emblem',
'Name Badge',
'Japanese Symbol for Beginner',
'Heavy Large Circle',
'White Heavy Check Mark',
'Ballot Box With Check',
'Heavy Check Mark',
'Heavy Multiplication X',
'Cross Mark',
'Cross Mark Button',
'Heavy Plus Sign',
'Heavy Minus Sign',
'Heavy Division Sign',
'Curly Loop',
'Double Curly Loop',
'Part Alternation Mark',
'Eight-Spoked Asterisk',
'Eight-Pointed Star',
'Sparkle',
'Double Exclamation Mark',
'Exclamation Question Mark',
'Question Mark',
'White Question Mark',
'White Exclamation Mark',
'Exclamation Mark',
'Copyright',
'Registered',
'Trade Mark',
'Keycap Number Sign',
'Keycap Digit Zero',
'Keycap Digit One',
'Keycap Digit Two',
'Keycap Digit Three',
'Keycap Digit Four',
'Keycap Digit Five',
'Keycap Digit Six',
'Keycap Digit Seven',
'Keycap Digit Eight',
'Keycap Digit Nine',
'Keycap: 10',
'Input Latin Uppercase',
'Input Latin Lowercase',
'Input Numbers',
'Input Symbols',
'Input Latin Letters',
'A Button (Blood Type)',
'AB Button (Blood Type)',
'B Button (Blood Type)',
'CL Button',
'Cool Button',
'Free Button',
'Information',
'ID Button',
'Circled M',
'New Button',
'NG Button',
'O Button (Blood Type)',
'OK Button',
'P Button',
'SOS Button',
'Up! Button',
'Vs Button',
'Japanese “Here” Button',
'Japanese “Service Charge” Button',
'Japanese “Monthly Amount” Button',
'Japanese “Not Free of Charge” Button',
'Japanese “Reserved” Button',
'Japanese “Bargain” Button',
'Japanese “Discount” Button',
'Japanese “Free of Charge” Button',
'Japanese “Prohibited” Button',
'Japanese “Acceptable” Button',
'Japanese “Application” Button',
'Japanese “Passing Grade” Button',
'Japanese “Vacancy” Button',
'Japanese “Congratulations” Button',
'Japanese “Secret” Button',
'Japanese “Open for Business” Button',
'Japanese “No Vacancy” Button',
'Red Circle',
'Blue Circle',
'Black Circle',
'White Circle',
'Black Large Square',
'White Large Square',
'Black Medium Square',
'White Medium Square',
'Black Medium-Small Square',
'White Medium-Small Square',
'Black Small Square',
'White Small Square',
'Large Orange Diamond',
'Large Blue Diamond',
'Small Orange Diamond',
'Small Blue Diamond',
'Red Triangle Pointed Up',
'Red Triangle Pointed Down',
'Diamond With a Dot',
'White Square Button',
'Black Square Button',
], [
'💘',
'💝',
'💖',
'💗',
'💓',
'💞',
'💕',
'💟',
'❣',
'💔',
'❤',
'🧡',
'💛',
'💚',
'💙',
'💜',
'🖤',
'💯',
'💢',
'💬',
'👁️🗨️',
'🗯',
'💭',
'💤',
'💮',
'♨',
'💈',
'🛑',
'🕛',
'🕧',
'🕐',
'🕜',
'🕑',
'🕝',
'🕒',
'🕞',
'🕓',
'🕟',
'🕔',
'🕠',
'🕕',
'🕡',
'🕖',
'🕢',
'🕗',
'🕣',
'🕘',
'🕤',
'🕙',
'🕥',
'🕚',
'🕦',
'🌀',
'♠',
'♥',
'♦',
'♣',
'🃏',
'🀄',
'🎴',
'🔇',
'🔈',
'🔉',
'🔊',
'📢',
'📣',
'📯',
'🔔',
'🔕',
'🎵',
'🎶',
'🏧',
'🚮',
'🚰',
'♿',
'🚹',
'🚺',
'🚻',
'🚼',
'🚾',
'⚠',
'🚸',
'⛔',
'🚫',
'🚳',
'🚭',
'🚯',
'🚱',
'🚷',
'🔞',
'☢',
'☣',
'⬆',
'↗',
'➡',
'↘',
'⬇',
'↙',
'⬅',
'↖',
'↕',
'↔',
'↩',
'↪',
'⤴',
'⤵',
'🔃',
'🔄',
'🔙',
'🔚',
'🔛',
'🔜',
'🔝',
'🛐',
'⚛',
'🕉',
'✡',
'☸',
'☯',
'✝',
'☦',
'☪',
'☮',
'🕎',
'🔯',
'♈',
'♉',
'♊',
'♋',
'♌',
'♍',
'♎',
'♏',
'♐',
'♑',
'♒',
'♓',
'⛎',
'🔀',
'🔁',
'🔂',
'▶',
'⏩',
'◀',
'⏪',
'🔼',
'⏫',
'🔽',
'⏬',
'⏹',
'⏏',
'🎦',
'🔅',
'🔆',
'📶',
'📳',
'📴',
'♾',
'♻',
'🔱',
'📛',
'🔰',
'⭕',
'✅',
'☑',
'✔',
'✖',
'❌',
'❎',
'➕',
'➖',
'➗',
'➰',
'➿',
'〽',
'✳',
'✴',
'❇',
'‼',
'⁉',
'❓',
'❔',
'❕',
'❗',
'©',
'®',
'™',
'#️⃣',
'0️⃣',
'1️⃣',
'2️⃣',
'3️⃣',
'4️⃣',
'5️⃣',
'6️⃣',
'7️⃣',
'8️⃣',
'9️⃣',
'🔟',
'🔠',
'🔡',
'🔢',
'🔣',
'🔤',
'🅰',
'🆎',
'🅱',
'🆑',
'🆒',
'🆓',
'ℹ',
'🆔',
'Ⓜ',
'🆕',
'🆖',
'🅾',
'🆗',
'🅿',
'🆘',
'🆙',
'🆚',
'🈁',
'🈂',
'🈷',
'🈶',
'🈯',
'🉐',
'🈹',
'🈚',
'🈲',
'🉑',
'🈸',
'🈴',
'🈳',
'㊗',
'㊙',
'🈺',
'🈵',
'🔴',
'🔵',
'⚫',
'⚪',
'⬛',
'⬜',
'◼',
'◻',
'◾',
'◽',
'▪',
'▫',
'🔶',
'🔷',
'🔸',
'🔹',
'🔺',
'🔻',
'💠',
'🔳',
'🔲',
]);
/// Map of all possible emojis along with their names in [Category.FLAGS]
final Map<String, String> flags = Map.fromIterables([
'Chequered Flag',
'Triangular Flag',
'Crossed Flags',
'Black Flag',
'White Flag',
'Rainbow Flag',
'Pirate Flag',
'Flag: Ascension Island',
'Flag: Andorra',
'Flag: United Arab Emirates',
'Flag: Afghanistan',
'Flag: Antigua & Barbuda',
'Flag: Anguilla',
'Flag: Albania',
'Flag: Armenia',
'Flag: Angola',
'Flag: Antarctica',
'Flag: argentina',
'Flag: American Samoa',
'Flag: Austria',
'Flag: Australia',
'Flag: Aruba',
'Flag: Åland Islands',
'Flag: Azerbaijan',
'Flag: Bosnia & Herzegovina',
'Flag: Barbados',
'Flag: Bangladesh',
'Flag: Belgium',
'Flag: Burkina Faso',
'Flag: Bulgaria',
'Flag: Bahrain',
'Flag: Burundi',
'Flag: Benin',
'Flag: St. Barthélemy',
'Flag: Bermuda',
'Flag: Brunei',
'Flag: Bolivia',
'Flag: Caribbean Netherlands',
'Flag: Brazil',
'Flag: Bahamas',
'Flag: Bhutan',
'Flag: Bouvet Island',
'Flag: Botswana',
'Flag: Belarus',
'Flag: Belize',
'Flag: Canada',
'Flag: Cocos (Keeling) Islands',
'Flag: Congo - Kinshasa',
'Flag: Central African Republic',
'Flag: Congo - Brazzaville',
'Flag: Switzerland',
'Flag: Côte d’Ivoire',
'Flag: Cook Islands',
'Flag: Chile',
'Flag: Cameroon',
'Flag: China',
'Flag: Colombia',
'Flag: Clipperton Island',
'Flag: Costa Rica',
'Flag: Cuba',
'Flag: Cape Verde',
'Flag: Curaçao',
'Flag: Christmas Island',
'Flag: Cyprus',
'Flag: Czechia',
'Flag: Germany',
'Flag: Diego Garcia',
'Flag: Djibouti',
'Flag: Denmark',
'Flag: Dominica',
'Flag: Dominican Republic',
'Flag: Algeria',
'Flag: Ceuta & Melilla',
'Flag: Ecuador',
'Flag: Estonia',
'Flag: Egypt',
'Flag: Western Sahara',
'Flag: Eritrea',
'Flag: Spain',
'Flag: Ethiopia',
'Flag: European Union',
'Flag: Finland',
'Flag: Fiji',
'Flag: Falkland Islands',
'Flag: Micronesia',
'Flag: Faroe Islands',
'Flag: france',
'Flag: Gabon',
'Flag: United Kingdom',
'Flag: Grenada',
'Flag: Georgia',
'Flag: French Guiana',
'Flag: Guernsey',
'Flag: Ghana',
'Flag: Gibraltar',
'Flag: Greenland',
'Flag: Gambia',
'Flag: Guinea',
'Flag: Guadeloupe',
'Flag: Equatorial Guinea',
'Flag: Greece',
'Flag: South Georgia & South Sandwich Islands',
'Flag: Guatemala',
'Flag: Guam',
'Flag: Guinea-Bissau',
'Flag: Guyana',
'Flag: Hong Kong SAR China',
'Flag: Heard & McDonald Islands',
'Flag: Honduras',
'Flag: Croatia',
'Flag: Haiti',
'Flag: Hungary',
'Flag: Canary Islands',
'Flag: Indonesia',
'Flag: Ireland',
'Flag: Israel',
'Flag: Isle of Man',
'Flag: India',
'Flag: British Indian Ocean Territory',
'Flag: Iraq',
'Flag: Iran',
'Flag: Iceland',
'Flag: Italy',
'Flag: Jersey',
'Flag: Jamaica',
'Flag: Jordan',
'Flag: Japan',
'Flag: Kenya',
'Flag: Kyrgyzstan',
'Flag: Cambodia',
'Flag: Kiribati',
'Flag: Comoros',
'Flag: St. Kitts & Nevis',
'Flag: North Korea',
'Flag: South Korea',
'Flag: Kuwait',
'Flag: Cayman Islands',
'Flag: Kazakhstan',
'Flag: Laos',
'Flag: Lebanon',
'Flag: St. Lucia',
'Flag: Liechtenstein',
'Flag: Sri Lanka',
'Flag: Liberia',
'Flag: Lesotho',
'Flag: Lithuania',
'Flag: Luxembourg',
'Flag: Latvia',
'Flag: Libya',
'Flag: Morocco',
'Flag: Monaco',
'Flag: Moldova',
'Flag: Montenegro',
'Flag: St. Martin',
'Flag: Madagascar',
'Flag: Marshall Islands',
'Flag: North Macedonia',
'Flag: Mali',
'Flag: Myanmar (Burma)',
'Flag: Mongolia',
'Flag: Macau Sar China',
'Flag: Northern Mariana Islands',
'Flag: Martinique',
'Flag: Mauritania',
'Flag: Montserrat',
'Flag: Malta',
'Flag: Mauritius',
'Flag: Maldives',
'Flag: Malawi',
'Flag: Mexico',
'Flag: Malaysia',
'Flag: Mozambique',
'Flag: Namibia',
'Flag: New Caledonia',
'Flag: Niger',
'Flag: Norfolk Island',
'Flag: Nigeria',
'Flag: Nicaragua',
'Flag: Netherlands',
'Flag: Norway',
'Flag: Nepal',
'Flag: Nauru',
'Flag: Niue',
'Flag: New Zealand',
'Flag: Oman',
'Flag: Panama',
'Flag: Peru',
'Flag: French Polynesia',
'Flag: Papua New Guinea',
'Flag: Philippines',
'Flag: Pakistan',
'Flag: Poland',
'Flag: St. Pierre & Miquelon',
'Flag: Pitcairn Islands',
'Flag: Puerto Rico',
'Flag: Palestinian Territories',
'Flag: Portugal',
'Flag: Palau',
'Flag: Paraguay',
'Flag: Qatar',
'Flag: Réunion',
'Flag: Romania',
'Flag: Serbia',
'Flag: Russia',
'Flag: Rwanda',
'Flag: Saudi Arabia',
'Flag: Solomon Islands',
'Flag: Seychelles',
'Flag: Sudan',
'Flag: Sweden',
'Flag: Singapore',
'Flag: St. Helena',
'Flag: Slovenia',
'Flag: Svalbard & Jan Mayen',
'Flag: Slovakia',
'Flag: Sierra Leone',
'Flag: San Marino',
'Flag: Senegal',
'Flag: Somalia',
'Flag: Suriname',
'Flag: South Sudan',
'Flag: São Tomé & Príncipe',
'Flag: El Salvador',
'Flag: Sint Maarten',
'Flag: Syria',
'Flag: Swaziland',
'Flag: Tristan Da Cunha',
'Flag: Turks & Caicos Islands',
'Flag: Chad',
'Flag: French Southern Territories',
'Flag: Togo',
'Flag: Thailand',
'Flag: Tajikistan',
'Flag: Tokelau',
'Flag: Timor-Leste',
'Flag: Turkmenistan',
'Flag: Tunisia',
'Flag: Tonga',
'Flag: Turkey',
'Flag: Trinidad & Tobago',
'Flag: Tuvalu',
'Flag: Taiwan',
'Flag: Tanzania',
'Flag: Ukraine',
'Flag: Uganda',
'Flag: U.S. Outlying Islands',
'Flag: United Nations',
'Flag: United States',
'Flag: Uruguay',
'Flag: Uzbekistan',
'Flag: Vatican City',
'Flag: St. Vincent & Grenadines',
'Flag: Venezuela',
'Flag: British Virgin Islands',
'Flag: U.S. Virgin Islands',
'Flag: Vietnam',
'Flag: Vanuatu',
'Flag: Wallis & Futuna',
'Flag: Samoa',
'Flag: Kosovo',
'Flag: Yemen',
'Flag: Mayotte',
'Flag: South Africa',
'Flag: Zambia',
'Flag: Zimbabwe',
], [
'🏁',
'🚩',
'🎌',
'🏴',
'🏳',
'🏳️🌈',
'🏴☠️',
'🇦🇨',
'🇦🇩',
'🇦🇪',
'🇦🇫',
'🇦🇬',
'🇦🇮',
'🇦🇱',
'🇦🇲',
'🇦🇴',
'🇦🇶',
'🇦🇷',
'🇦🇸',
'🇦🇹',
'🇦🇺',
'🇦🇼',
'🇦🇽',
'🇦🇿',
'🇧🇦',
'🇧🇧',
'🇧🇩',
'🇧🇪',
'🇧🇫',
'🇧🇬',
'🇧🇭',
'🇧🇮',
'🇧🇯',
'🇧🇱',
'🇧🇲',
'🇧🇳',
'🇧🇴',
'🇧🇶',
'🇧🇷',
'🇧🇸',
'🇧🇹',
'🇧🇻',
'🇧🇼',
'🇧🇾',
'🇧🇿',
'🇨🇦',
'🇨🇨',
'🇨🇩',
'🇨🇫',
'🇨🇬',
'🇨🇭',
'🇨🇮',
'🇨🇰',
'🇨🇱',
'🇨🇲',
'🇨🇳',
'🇨🇴',
'🇨🇵',
'🇨🇷',
'🇨🇺',
'🇨🇻',
'🇨🇼',
'🇨🇽',
'🇨🇾',
'🇨🇿',
'🇩🇪',
'🇩🇬',
'🇩🇯',
'🇩🇰',
'🇩🇲',
'🇩🇴',
'🇩🇿',
'🇪🇦',
'🇪🇨',
'🇪🇪',
'🇪🇬',
'🇪🇭',
'🇪🇷',
'🇪🇸',
'🇪🇹',
'🇪🇺',
'🇫🇮',
'🇫🇯',
'🇫🇰',
'🇫🇲',
'🇫🇴',
'🇫🇷',
'🇬🇦',
'🇬🇧',
'🇬🇩',
'🇬🇪',
'🇬🇫',
'🇬🇬',
'🇬🇭',
'🇬🇮',
'🇬🇱',
'🇬🇲',
'🇬🇳',
'🇬🇵',
'🇬🇶',
'🇬🇷',
'🇬🇸',
'🇬🇹',
'🇬🇺',
'🇬🇼',
'🇬🇾',
'🇭🇰',
'🇭🇲',
'🇭🇳',
'🇭🇷',
'🇭🇹',
'🇭🇺',
'🇮🇨',
'🇮🇩',
'🇮🇪',
'🇮🇱',
'🇮🇲',
'🇮🇳',
'🇮🇴',
'🇮🇶',
'🇮🇷',
'🇮🇸',
'🇮🇹',
'🇯🇪',
'🇯🇲',
'🇯🇴',
'🇯🇵',
'🇰🇪',
'🇰🇬',
'🇰🇭',
'🇰🇮',
'🇰🇲',
'🇰🇳',
'🇰🇵',
'🇰🇷',
'🇰🇼',
'🇰🇾',
'🇰🇿',
'🇱🇦',
'🇱🇧',
'🇱🇨',
'🇱🇮',
'🇱🇰',
'🇱🇷',
'🇱🇸',
'🇱🇹',
'🇱🇺',
'🇱🇻',
'🇱🇾',
'🇲🇦',
'🇲🇨',
'🇲🇩',
'🇲🇪',
'🇲🇫',
'🇲🇬',
'🇲🇭',
'🇲🇰',
'🇲🇱',
'🇲🇲',
'🇲🇳',
'🇲🇴',
'🇲🇵',
'🇲🇶',
'🇲🇷',
'🇲🇸',
'🇲🇹',
'🇲🇺',
'🇲🇻',
'🇲🇼',
'🇲🇽',
'🇲🇾',
'🇲🇿',
'🇳🇦',
'🇳🇨',
'🇳🇪',
'🇳🇫',
'🇳🇬',
'🇳🇮',
'🇳🇱',
'🇳🇴',
'🇳🇵',
'🇳🇷',
'🇳🇺',
'🇳🇿',
'🇴🇲',
'🇵🇦',
'🇵🇪',
'🇵🇫',
'🇵🇬',
'🇵🇭',
'🇵🇰',
'🇵🇱',
'🇵🇲',
'🇵🇳',
'🇵🇷',
'🇵🇸',
'🇵🇹',
'🇵🇼',
'🇵🇾',
'🇶🇦',
'🇷🇪',
'🇷🇴',
'🇷🇸',
'🇷🇺',
'🇷🇼',
'🇸🇦',
'🇸🇧',
'🇸🇨',
'🇸🇩',
'🇸🇪',
'🇸🇬',
'🇸🇭',
'🇸🇮',
'🇸🇯',
'🇸🇰',
'🇸🇱',
'🇸🇲',
'🇸🇳',
'🇸🇴',
'🇸🇷',
'🇸🇸',
'🇸🇹',
'🇸🇻',
'🇸🇽',
'🇸🇾',
'🇸🇿',
'🇹🇦',
'🇹🇨',
'🇹🇩',
'🇹🇫',
'🇹🇬',
'🇹🇭',
'🇹🇯',
'🇹🇰',
'🇹🇱',
'🇹🇲',
'🇹🇳',
'🇹🇴',
'🇹🇷',
'🇹🇹',
'🇹🇻',
'🇹🇼',
'🇹🇿',
'🇺🇦',
'🇺🇬',
'🇺🇲',
'🇺🇳',
'🇺🇸',
'🇺🇾',
'🇺🇿',
'🇻🇦',
'🇻🇨',
'🇻🇪',
'🇻🇬',
'🇻🇮',
'🇻🇳',
'🇻🇺',
'🇼🇫',
'🇼🇸',
'🇽🇰',
'🇾🇪',
'🇾🇹',
'🇿🇦',
'🇿🇲',
'🇿🇼',
]);
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src/default_emoji_picker_view.dart | import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flutter/material.dart';
import 'emoji_picker.dart';
import 'emoji_picker_builder.dart';
import 'models/emoji_category_models.dart';
import 'models/emoji_model.dart';
class DefaultEmojiPickerView extends EmojiPickerBuilder {
const DefaultEmojiPickerView(
super.config,
super.state, {
super.key,
});
@override
DefaultEmojiPickerViewState createState() => DefaultEmojiPickerViewState();
}
class DefaultEmojiPickerViewState extends State<DefaultEmojiPickerView>
with TickerProviderStateMixin {
PageController? _pageController;
TabController? _tabController;
final TextEditingController _emojiController = TextEditingController();
final FocusNode _emojiFocusNode = FocusNode();
EmojiCategoryGroup searchEmojiList =
EmojiCategoryGroup(EmojiCategory.SEARCH, <Emoji>[]);
final scrollController = ScrollController();
@override
void initState() {
var initCategory = widget.state.emojiCategoryGroupList.indexWhere(
(element) => element.category == widget.config.initCategory,
);
if (initCategory == -1) {
initCategory = 0;
}
_tabController = TabController(
initialIndex: initCategory,
length: widget.state.emojiCategoryGroupList.length,
vsync: this,
);
_pageController = PageController(initialPage: initCategory);
_emojiFocusNode.requestFocus();
_emojiController.addListener(() {
final String query = _emojiController.text.toLowerCase();
if (query.isEmpty) {
searchEmojiList.emoji.clear();
_pageController!.jumpToPage(
_tabController!.index,
);
} else {
searchEmojiList.emoji.clear();
for (final element in widget.state.emojiCategoryGroupList) {
searchEmojiList.emoji.addAll(
element.emoji.where((item) {
return item.name.toLowerCase().contains(query);
}).toList(),
);
}
}
setState(() {});
});
super.initState();
}
@override
void dispose() {
_emojiController.dispose();
_emojiFocusNode.dispose();
_pageController?.dispose();
_tabController?.dispose();
scrollController.dispose();
super.dispose();
}
Widget _buildBackspaceButton() {
if (widget.state.onBackspacePressed != null) {
return Material(
type: MaterialType.transparency,
child: IconButton(
padding: const EdgeInsets.only(bottom: 2),
icon: Icon(
Icons.backspace,
color: widget.config.backspaceColor,
),
onPressed: () {
widget.state.onBackspacePressed!();
},
),
);
}
return const SizedBox.shrink();
}
bool isEmojiSearching() {
final bool result =
searchEmojiList.emoji.isNotEmpty || _emojiController.text.isNotEmpty;
return result;
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final emojiSize = widget.config.getEmojiSize(constraints.maxWidth);
final style = Theme.of(context);
return Container(
color: widget.config.bgColor,
padding: const EdgeInsets.all(4),
child: Column(
children: [
const VSpace(4),
// search bar
SizedBox(
height: 32.0,
child: TextField(
controller: _emojiController,
focusNode: _emojiFocusNode,
autofocus: true,
style: style.textTheme.bodyMedium,
cursorColor: style.textTheme.bodyMedium?.color,
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(8),
hintText: widget.config.searchHintText,
hintStyle: widget.config.serachHintTextStyle,
enabledBorder: widget.config.serachBarEnableBorder,
focusedBorder: widget.config.serachBarFocusedBorder,
),
),
),
const VSpace(4),
Row(
children: [
Expanded(
child: TabBar(
labelColor: widget.config.selectedCategoryIconColor,
unselectedLabelColor: widget.config.categoryIconColor,
controller: isEmojiSearching()
? TabController(length: 1, vsync: this)
: _tabController,
labelPadding: EdgeInsets.zero,
indicatorColor:
widget.config.selectedCategoryIconBackgroundColor,
padding: const EdgeInsets.symmetric(vertical: 4.0),
indicator: BoxDecoration(
border: Border.all(color: Colors.transparent),
borderRadius: BorderRadius.circular(4.0),
color: style.colorScheme.secondary,
),
onTap: (index) {
_pageController!.animateToPage(
index,
duration: widget.config.tabIndicatorAnimDuration,
curve: Curves.ease,
);
},
tabs: isEmojiSearching()
? [_buildCategory(EmojiCategory.SEARCH, emojiSize)]
: widget.state.emojiCategoryGroupList
.asMap()
.entries
.map<Widget>(
(item) => _buildCategory(
item.value.category,
emojiSize,
),
)
.toList(),
),
),
_buildBackspaceButton(),
],
),
Flexible(
child: PageView.builder(
itemCount: searchEmojiList.emoji.isNotEmpty
? 1
: widget.state.emojiCategoryGroupList.length,
controller: _pageController,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
final EmojiCategoryGroup emojiCategoryGroup =
isEmojiSearching()
? searchEmojiList
: widget.state.emojiCategoryGroupList[index];
return _buildPage(emojiSize, emojiCategoryGroup);
},
),
),
],
),
);
},
);
}
Widget _buildCategory(EmojiCategory category, double categorySize) {
return Tab(
height: categorySize,
child: Icon(
widget.config.getIconForCategory(category),
size: categorySize / 1.3,
),
);
}
Widget _buildButtonWidget({
required VoidCallback onPressed,
required Widget child,
}) {
if (widget.config.buttonMode == ButtonMode.MATERIAL) {
return InkWell(
onTap: onPressed,
child: child,
);
}
return GestureDetector(
onTap: onPressed,
child: child,
);
}
Widget _buildPage(double emojiSize, EmojiCategoryGroup emojiCategoryGroup) {
// Display notice if recent has no entries yet
if (emojiCategoryGroup.category == EmojiCategory.RECENT &&
emojiCategoryGroup.emoji.isEmpty) {
return _buildNoRecent();
} else if (emojiCategoryGroup.category == EmojiCategory.SEARCH &&
emojiCategoryGroup.emoji.isEmpty) {
return Center(child: Text(widget.config.noEmojiFoundText));
}
// Build page normally
return ScrollbarListStack(
axis: Axis.vertical,
controller: scrollController,
barSize: 4.0,
scrollbarPadding: const EdgeInsets.symmetric(horizontal: 4.0),
handleColor: widget.config.scrollBarHandleColor,
showTrack: true,
child: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: GridView.builder(
controller: scrollController,
padding: const EdgeInsets.all(0),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: widget.config.emojiNumberPerRow,
mainAxisSpacing: widget.config.verticalSpacing,
crossAxisSpacing: widget.config.horizontalSpacing,
),
itemCount: emojiCategoryGroup.emoji.length,
itemBuilder: (context, index) {
final item = emojiCategoryGroup.emoji[index];
return _buildEmoji(emojiSize, emojiCategoryGroup, item);
},
cacheExtent: 10,
),
),
);
}
Widget _buildEmoji(
double emojiSize,
EmojiCategoryGroup emojiCategoryGroup,
Emoji emoji,
) {
return _buildButtonWidget(
onPressed: () {
widget.state.onEmojiSelected(emojiCategoryGroup.category, emoji);
},
child: FlowyHover(
child: FittedBox(
child: Text(
emoji.emoji,
style: TextStyle(
fontSize: emojiSize,
),
),
),
),
);
}
Widget _buildNoRecent() {
return Center(
child: Text(
widget.config.noRecentsText,
style: widget.config.noRecentsStyle,
textAlign: TextAlign.center,
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src/flowy_emoji_picker_config.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/emoji_picker/src/emji_picker_config.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
EmojiPickerConfig buildFlowyEmojiPickerConfig(BuildContext context) {
final style = Theme.of(context);
return EmojiPickerConfig(
bgColor: style.cardColor,
categoryIconColor: style.iconTheme.color,
selectedCategoryIconColor: style.colorScheme.onSurface,
selectedCategoryIconBackgroundColor: style.colorScheme.primary,
progressIndicatorColor: style.colorScheme.primary,
backspaceColor: style.colorScheme.primary,
searchHintText: LocaleKeys.emoji_search.tr(),
serachHintTextStyle: style.textTheme.bodyMedium?.copyWith(
color: style.hintColor,
),
serachBarEnableBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(4),
borderSide: BorderSide(color: style.dividerColor),
),
serachBarFocusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(4),
borderSide: BorderSide(
color: style.colorScheme.primary,
),
),
noRecentsText: LocaleKeys.emoji_noRecent.tr(),
noRecentsStyle: style.textTheme.bodyMedium,
noEmojiFoundText: LocaleKeys.emoji_noEmojiFound.tr(),
scrollBarHandleColor: style.colorScheme.onBackground,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src/emoji_view_state.dart | import 'models/emoji_category_models.dart';
import 'emoji_picker.dart';
/// State that holds current emoji data
class EmojiViewState {
/// Constructor
EmojiViewState(
this.emojiCategoryGroupList,
this.onEmojiSelected,
this.onBackspacePressed,
);
/// List of all categories including their emojis
final List<EmojiCategoryGroup> emojiCategoryGroupList;
/// Callback when pressed on emoji
final OnEmojiSelected onEmojiSelected;
/// Callback when pressed on backspace
final OnBackspacePressed? onBackspacePressed;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src/emoji_picker_builder.dart | import 'package:flutter/material.dart';
import 'emji_picker_config.dart';
import 'emoji_view_state.dart';
/// Template class for custom implementation
/// Inherit this class to create your own EmojiPicker
abstract class EmojiPickerBuilder extends StatefulWidget {
/// Constructor
const EmojiPickerBuilder(this.config, this.state, {super.key});
/// Config for customizations
final EmojiPickerConfig config;
/// State that holds current emoji data
final EmojiViewState state;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src/emoji_picker.dart | // ignore_for_file: constant_identifier_names
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'models/emoji_category_models.dart';
import 'emji_picker_config.dart';
import 'default_emoji_picker_view.dart';
import 'models/emoji_model.dart';
import 'emoji_lists.dart' as emoji_list;
import 'emoji_view_state.dart';
import 'models/recent_emoji_model.dart';
/// The emoji category shown on the category tab
enum EmojiCategory {
/// Searched emojis
SEARCH,
/// Recent emojis
RECENT,
/// Smiley emojis
SMILEYS,
/// Animal emojis
ANIMALS,
/// Food emojis
FOODS,
/// Activity emojis
ACTIVITIES,
/// Travel emojis
TRAVEL,
/// Objects emojis
OBJECTS,
/// Sumbol emojis
SYMBOLS,
/// Flag emojis
FLAGS,
}
/// Enum to alter the keyboard button style
enum ButtonMode {
/// Android button style - gives the button a splash color with ripple effect
MATERIAL,
/// iOS button style - gives the button a fade out effect when pressed
CUPERTINO
}
/// Callback function for when emoji is selected
///
/// The function returns the selected [Emoji] as well
/// as the [EmojiCategory] from which it originated
typedef OnEmojiSelected = void Function(EmojiCategory category, Emoji emoji);
/// Callback function for backspace button
typedef OnBackspacePressed = void Function();
/// Callback function for custom view
typedef EmojiViewBuilder = Widget Function(
EmojiPickerConfig config,
EmojiViewState state,
);
/// The Emoji Keyboard widget
///
/// This widget displays a grid of [Emoji] sorted by [EmojiCategory]
/// which the user can horizontally scroll through.
///
/// There is also a bottombar which displays all the possible [EmojiCategory]
/// and allow the user to quickly switch to that [EmojiCategory]
class EmojiPicker extends StatefulWidget {
/// EmojiPicker for flutter
const EmojiPicker({
super.key,
required this.onEmojiSelected,
this.onBackspacePressed,
this.config = const EmojiPickerConfig(),
this.customWidget,
});
/// Custom widget
final EmojiViewBuilder? customWidget;
/// The function called when the emoji is selected
final OnEmojiSelected onEmojiSelected;
/// The function called when backspace button is pressed
final OnBackspacePressed? onBackspacePressed;
/// Config for customizations
final EmojiPickerConfig config;
@override
EmojiPickerState createState() => EmojiPickerState();
}
class EmojiPickerState extends State<EmojiPicker> {
static const platform = MethodChannel('emoji_picker_flutter');
List<EmojiCategoryGroup> emojiCategoryGroupList = List.empty(growable: true);
List<RecentEmoji> recentEmojiList = List.empty(growable: true);
late Future<void> updateEmojiFuture;
// Prevent emojis to be reloaded with every build
bool loaded = false;
@override
void initState() {
super.initState();
updateEmojiFuture = _updateEmojis();
}
@override
void didUpdateWidget(covariant EmojiPicker oldWidget) {
if (oldWidget.config != widget.config) {
// EmojiPickerConfig changed - rebuild EmojiPickerView completely
loaded = false;
updateEmojiFuture = _updateEmojis();
}
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
if (!loaded) {
// Load emojis
updateEmojiFuture.then(
(value) => WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
setState(() {
loaded = true;
});
}),
);
// Show loading indicator
return const Center(child: CircularProgressIndicator());
}
if (widget.config.showRecentsTab) {
emojiCategoryGroupList[0].emoji =
recentEmojiList.map((e) => e.emoji).toList().cast<Emoji>();
}
final state = EmojiViewState(
emojiCategoryGroupList,
_getOnEmojiListener(),
widget.onBackspacePressed,
);
// Build
return widget.customWidget == null
? DefaultEmojiPickerView(widget.config, state)
: widget.customWidget!(widget.config, state);
}
// Add recent emoji handling to tap listener
OnEmojiSelected _getOnEmojiListener() {
return (category, emoji) {
if (widget.config.showRecentsTab) {
_addEmojiToRecentlyUsed(emoji).then((value) {
if (category != EmojiCategory.RECENT && mounted) {
setState(() {
// rebuild to update recent emoji tab
// when it is not current tab
});
}
});
}
widget.onEmojiSelected(category, emoji);
};
}
// Initialize emoji data
Future<void> _updateEmojis() async {
emojiCategoryGroupList.clear();
if (widget.config.showRecentsTab) {
recentEmojiList = await _getRecentEmojis();
final List<Emoji> recentEmojiMap =
recentEmojiList.map((e) => e.emoji).toList().cast<Emoji>();
emojiCategoryGroupList
.add(EmojiCategoryGroup(EmojiCategory.RECENT, recentEmojiMap));
}
emojiCategoryGroupList.addAll([
EmojiCategoryGroup(
EmojiCategory.SMILEYS,
await _getAvailableEmojis(emoji_list.smileys, title: 'smileys'),
),
EmojiCategoryGroup(
EmojiCategory.ANIMALS,
await _getAvailableEmojis(emoji_list.animals, title: 'animals'),
),
EmojiCategoryGroup(
EmojiCategory.FOODS,
await _getAvailableEmojis(emoji_list.foods, title: 'foods'),
),
EmojiCategoryGroup(
EmojiCategory.ACTIVITIES,
await _getAvailableEmojis(
emoji_list.activities,
title: 'activities',
),
),
EmojiCategoryGroup(
EmojiCategory.TRAVEL,
await _getAvailableEmojis(emoji_list.travel, title: 'travel'),
),
EmojiCategoryGroup(
EmojiCategory.OBJECTS,
await _getAvailableEmojis(emoji_list.objects, title: 'objects'),
),
EmojiCategoryGroup(
EmojiCategory.SYMBOLS,
await _getAvailableEmojis(emoji_list.symbols, title: 'symbols'),
),
EmojiCategoryGroup(
EmojiCategory.FLAGS,
await _getAvailableEmojis(emoji_list.flags, title: 'flags'),
),
]);
}
// Get available emoji for given category title
Future<List<Emoji>> _getAvailableEmojis(
Map<String, String> map, {
required String title,
}) async {
Map<String, String>? newMap;
// Get Emojis cached locally if available
newMap = await _restoreFilteredEmojis(title);
if (newMap == null) {
// Check if emoji is available on this platform
newMap = await _getPlatformAvailableEmoji(map);
// Save available Emojis to local storage for faster loading next time
if (newMap != null) {
await _cacheFilteredEmojis(title, newMap);
}
}
// Map to Emoji Object
return newMap!.entries
.map<Emoji>((entry) => Emoji(entry.key, entry.value))
.toList();
}
// Check if emoji is available on current platform
Future<Map<String, String>?> _getPlatformAvailableEmoji(
Map<String, String> emoji,
) async {
if (Platform.isAndroid) {
Map<String, String>? filtered = {};
const delimiter = '|';
try {
final entries = emoji.values.join(delimiter);
final keys = emoji.keys.join(delimiter);
final result = (await platform.invokeMethod<String>(
'checkAvailability',
{'emojiKeys': keys, 'emojiEntries': entries},
)) as String;
final resultKeys = result.split(delimiter);
for (var i = 0; i < resultKeys.length; i++) {
filtered[resultKeys[i]] = emoji[resultKeys[i]]!;
}
} on PlatformException catch (_) {
filtered = null;
}
return filtered;
} else {
return emoji;
}
}
// Restore locally cached emoji
Future<Map<String, String>?> _restoreFilteredEmojis(String title) async {
final prefs = await SharedPreferences.getInstance();
final emojiJson = prefs.getString(title);
if (emojiJson == null) {
return null;
}
final emojis =
Map<String, String>.from(jsonDecode(emojiJson) as Map<String, dynamic>);
return emojis;
}
// Stores filtered emoji locally for faster access next time
Future<void> _cacheFilteredEmojis(
String title,
Map<String, String> emojis,
) async {
final prefs = await SharedPreferences.getInstance();
final emojiJson = jsonEncode(emojis);
await prefs.setString(title, emojiJson);
}
// Returns list of recently used emoji from cache
Future<List<RecentEmoji>> _getRecentEmojis() async {
final prefs = await SharedPreferences.getInstance();
final emojiJson = prefs.getString('recent');
if (emojiJson == null) {
return [];
}
final json = jsonDecode(emojiJson) as List<dynamic>;
return json.map<RecentEmoji>(RecentEmoji.fromJson).toList();
}
// Add an emoji to recently used list or increase its counter
Future<void> _addEmojiToRecentlyUsed(Emoji emoji) async {
final prefs = await SharedPreferences.getInstance();
final recentEmojiIndex = recentEmojiList
.indexWhere((element) => element.emoji.emoji == emoji.emoji);
if (recentEmojiIndex != -1) {
// Already exist in recent list
// Just update counter
recentEmojiList[recentEmojiIndex].counter++;
} else {
recentEmojiList.add(RecentEmoji(emoji, 1));
}
// Sort by counter desc
recentEmojiList.sort((a, b) => b.counter - a.counter);
// Limit entries to recentsLimit
recentEmojiList = recentEmojiList.sublist(
0,
min(widget.config.recentsLimit, recentEmojiList.length),
);
// save locally
await prefs.setString('recent', jsonEncode(recentEmojiList));
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src/emji_picker_config.dart | import 'dart:math';
import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'models/emoji_category_models.dart';
import 'emoji_picker.dart';
part 'emji_picker_config.freezed.dart';
@freezed
class EmojiPickerConfig with _$EmojiPickerConfig {
// private empty constructor is used to make method work in freezed
// https://pub.dev/packages/freezed#adding-getters-and-methods-to-our-models
const EmojiPickerConfig._();
const factory EmojiPickerConfig({
@Default(7) int emojiNumberPerRow,
// The maximum size(width and height) of emoji
// It also depaneds on the screen size and emojiNumberPerRow
@Default(32) double emojiSizeMax,
// Vertical spacing between emojis
@Default(0) double verticalSpacing,
// Horizontal spacing between emojis
@Default(0) double horizontalSpacing,
// The initial [EmojiCategory] that will be selected
@Default(EmojiCategory.RECENT) EmojiCategory initCategory,
// The background color of the Widget
@Default(Color(0xFFEBEFF2)) Color? bgColor,
// The color of the category icons
@Default(Colors.grey) Color? categoryIconColor,
// The color of the category icon when selected
@Default(Colors.blue) Color? selectedCategoryIconColor,
// The color of the category indicator
@Default(Colors.blue) Color? selectedCategoryIconBackgroundColor,
// The color of the loading indicator during initialization
@Default(Colors.blue) Color? progressIndicatorColor,
// The color of the backspace icon button
@Default(Colors.blue) Color? backspaceColor,
// Show extra tab with recently used emoji
@Default(true) bool showRecentsTab,
// Limit of recently used emoji that will be saved
@Default(28) int recentsLimit,
@Default('Search emoji') String searchHintText,
TextStyle? serachHintTextStyle,
InputBorder? serachBarEnableBorder,
InputBorder? serachBarFocusedBorder,
// The text to be displayed if no recent emojis to display
@Default('No recent emoji') String noRecentsText,
TextStyle? noRecentsStyle,
// The text to be displayed if no emoji found
@Default('No emoji found') String noEmojiFoundText,
Color? scrollBarHandleColor,
// Duration of tab indicator to animate to next category
@Default(kTabScrollDuration) Duration tabIndicatorAnimDuration,
// Determines the icon to display for each [EmojiCategory]
@Default(EmojiCategoryIcons()) EmojiCategoryIcons emojiCategoryIcons,
// Change between Material and Cupertino button style
@Default(ButtonMode.MATERIAL) ButtonMode buttonMode,
}) = _EmojiPickerConfig;
/// Get Emoji size based on properties and screen width
double getEmojiSize(double width) {
final maxSize = width / emojiNumberPerRow;
return min(maxSize, emojiSizeMax);
}
/// Returns the icon for the category
IconData getIconForCategory(EmojiCategory category) {
switch (category) {
case EmojiCategory.RECENT:
return emojiCategoryIcons.recentIcon;
case EmojiCategory.SMILEYS:
return emojiCategoryIcons.smileyIcon;
case EmojiCategory.ANIMALS:
return emojiCategoryIcons.animalIcon;
case EmojiCategory.FOODS:
return emojiCategoryIcons.foodIcon;
case EmojiCategory.TRAVEL:
return emojiCategoryIcons.travelIcon;
case EmojiCategory.ACTIVITIES:
return emojiCategoryIcons.activityIcon;
case EmojiCategory.OBJECTS:
return emojiCategoryIcons.objectIcon;
case EmojiCategory.SYMBOLS:
return emojiCategoryIcons.symbolIcon;
case EmojiCategory.FLAGS:
return emojiCategoryIcons.flagIcon;
case EmojiCategory.SEARCH:
return emojiCategoryIcons.searchIcon;
default:
throw Exception('Unsupported EmojiCategory');
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src/models/recent_emoji_model.dart | import 'emoji_model.dart';
/// Class that holds an recent emoji
/// Recent Emoji has an instance of the emoji
/// And a counter, which counts how often this emoji
/// has been used before
class RecentEmoji {
/// Constructor
RecentEmoji(this.emoji, this.counter);
/// Emoji instance
final Emoji emoji;
/// Counter how often emoji has been used before
int counter = 0;
/// Parse RecentEmoji from json
static RecentEmoji fromJson(dynamic json) {
return RecentEmoji(
Emoji.fromJson(json['emoji'] as Map<String, dynamic>),
json['counter'] as int,
);
}
/// Encode RecentEmoji to json
Map<String, dynamic> toJson() => {
'emoji': emoji,
'counter': counter,
};
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src/models/emoji_model.dart | /// A class to store data for each individual emoji
class Emoji {
/// Emoji constructor
const Emoji(this.name, this.emoji);
/// The name or description for this emoji
final String name;
/// The unicode string for this emoji
///
/// This is the string that should be displayed to view the emoji
final String emoji;
@override
String toString() {
// return 'Name: $name, Emoji: $emoji';
return name;
}
/// Parse Emoji from json
static Emoji fromJson(Map<String, dynamic> json) {
return Emoji(json['name'] as String, json['emoji'] as String);
}
/// Encode Emoji to json
Map<String, dynamic> toJson() {
return {
'name': name,
'emoji': emoji,
};
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/emoji_picker/src/models/emoji_category_models.dart | import 'package:flutter/material.dart';
import 'emoji_model.dart';
import '../emoji_picker.dart';
/// EmojiCategory with its emojis
class EmojiCategoryGroup {
EmojiCategoryGroup(this.category, this.emoji);
final EmojiCategory category;
/// List of emoji of this category
List<Emoji> emoji;
@override
String toString() {
return 'Name: $category, Emoji: $emoji';
}
}
/// Class that defines the icon representing a [EmojiCategory]
class EmojiCategoryIcon {
/// Icon of Category
const EmojiCategoryIcon({
required this.icon,
this.color = const Color(0xffd3d3d3),
this.selectedColor = const Color(0xffb2b2b2),
});
/// The icon to represent the category
final IconData icon;
/// The default color of the icon
final Color color;
/// The color of the icon once the category is selected
final Color selectedColor;
}
/// Class used to define all the [EmojiCategoryIcon] shown for each [EmojiCategory]
///
/// This allows the keyboard to be personalized by changing icons shown.
/// If a [EmojiCategoryIcon] is set as null or not defined during initialization,
/// the default icons will be used instead
class EmojiCategoryIcons {
/// Constructor
const EmojiCategoryIcons({
this.recentIcon = Icons.access_time,
this.smileyIcon = Icons.tag_faces,
this.animalIcon = Icons.pets,
this.foodIcon = Icons.fastfood,
this.activityIcon = Icons.directions_run,
this.travelIcon = Icons.location_city,
this.objectIcon = Icons.lightbulb_outline,
this.symbolIcon = Icons.emoji_symbols,
this.flagIcon = Icons.flag,
this.searchIcon = Icons.search,
});
/// Icon for [EmojiCategory.RECENT]
final IconData recentIcon;
/// Icon for [EmojiCategory.SMILEYS]
final IconData smileyIcon;
/// Icon for [EmojiCategory.ANIMALS]
final IconData animalIcon;
/// Icon for [EmojiCategory.FOODS]
final IconData foodIcon;
/// Icon for [EmojiCategory.ACTIVITIES]
final IconData activityIcon;
/// Icon for [EmojiCategory.TRAVEL]
final IconData travelIcon;
/// Icon for [EmojiCategory.OBJECTS]
final IconData objectIcon;
/// Icon for [EmojiCategory.SYMBOLS]
final IconData symbolIcon;
/// Icon for [EmojiCategory.FLAGS]
final IconData flagIcon;
/// Icon for [EmojiCategory.SEARCH]
final IconData searchIcon;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/files/settings_file_exporter_widget.dart | import 'dart:io';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/export/document_exporter.dart';
import 'package:appflowy/workspace/application/settings/settings_file_exporter_cubit.dart';
import 'package:appflowy/workspace/application/settings/share/export_service.dart';
import 'package:appflowy/workspace/presentation/home/toast.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pbserver.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/workspace.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/file_picker/file_picker_service.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart' hide WidgetBuilder;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:path/path.dart' as p;
import '../../../../../generated/locale_keys.g.dart';
class FileExporterWidget extends StatefulWidget {
const FileExporterWidget({super.key});
@override
State<FileExporterWidget> createState() => _FileExporterWidgetState();
}
class _FileExporterWidgetState extends State<FileExporterWidget> {
// Map<String, List<String>> _selectedPages = {};
SettingsFileExporterCubit? cubit;
@override
Widget build(BuildContext context) {
return FutureBuilder<FlowyResult<WorkspacePB, FlowyError>>(
future: FolderEventReadCurrentWorkspace().send(),
builder: (context, snapshot) {
if (snapshot.hasData &&
snapshot.connectionState == ConnectionState.done) {
final workspace = snapshot.data?.fold((s) => s, (e) => null);
if (workspace != null) {
final views = workspace.views;
cubit ??= SettingsFileExporterCubit(views: views);
return BlocProvider<SettingsFileExporterCubit>.value(
value: cubit!,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
FlowyText.medium(
LocaleKeys.settings_files_selectFiles.tr(),
fontSize: 16.0,
),
BlocBuilder<SettingsFileExporterCubit,
SettingsFileExportState>(
builder: (context, state) => FlowyTextButton(
state.selectedItems
.expand((element) => element)
.every((element) => element)
? LocaleKeys.settings_files_deselectAll.tr()
: LocaleKeys.settings_files_selectAll.tr(),
onPressed: () {
context
.read<SettingsFileExporterCubit>()
.selectOrDeselectAllItems();
},
),
),
],
),
const VSpace(8),
const Expanded(child: _ExpandedList()),
const VSpace(8),
_buildButtons(),
],
),
);
}
}
return const CircularProgressIndicator();
},
);
}
Widget _buildButtons() {
return Row(
children: [
const Spacer(),
FlowyTextButton(
LocaleKeys.button_cancel.tr(),
onPressed: () {
Navigator.of(context).pop();
},
),
const HSpace(8),
FlowyTextButton(
LocaleKeys.button_ok.tr(),
onPressed: () async {
await getIt<FilePickerService>()
.getDirectoryPath()
.then((exportPath) async {
if (exportPath != null && cubit != null) {
final views = cubit!.state.selectedViews;
final result =
await _AppFlowyFileExporter.exportToPath(exportPath, views);
if (mounted) {
if (result.$1) {
// success
showSnackBarMessage(
context,
LocaleKeys.settings_files_exportFileSuccess.tr(),
);
} else {
showSnackBarMessage(
context,
LocaleKeys.settings_files_exportFileFail.tr() +
result.$2.join('\n'),
);
}
}
} else {
showSnackBarMessage(
context,
LocaleKeys.settings_files_exportFileFail.tr(),
);
}
if (mounted) {
Navigator.of(context).popUntil(
(router) => router.settings.name == '/',
);
}
});
},
),
],
);
}
}
class _ExpandedList extends StatefulWidget {
const _ExpandedList();
// final List<AppPB> apps;
// final void Function(Map<String, List<String>> selectedPages) onChanged;
@override
State<_ExpandedList> createState() => _ExpandedListState();
}
class _ExpandedListState extends State<_ExpandedList> {
@override
Widget build(BuildContext context) {
return BlocBuilder<SettingsFileExporterCubit, SettingsFileExportState>(
builder: (context, state) {
return Material(
color: Colors.transparent,
child: SingleChildScrollView(
child: Column(
children: _buildChildren(context),
),
),
);
},
);
}
List<Widget> _buildChildren(BuildContext context) {
final apps = context.read<SettingsFileExporterCubit>().state.views;
final List<Widget> children = [];
for (var i = 0; i < apps.length; i++) {
children.add(_buildExpandedItem(context, i));
}
return children;
}
Widget _buildExpandedItem(BuildContext context, int index) {
final state = context.read<SettingsFileExporterCubit>().state;
final apps = state.views;
final expanded = state.expanded;
final selectedItems = state.selectedItems;
final isExpanded = expanded[index] == true;
final List<Widget> expandedChildren = [];
if (isExpanded) {
for (var i = 0; i < selectedItems[index].length; i++) {
final name = apps[index].childViews[i].name;
final checkbox = CheckboxListTile(
value: selectedItems[index][i],
onChanged: (value) {
// update selected item
context
.read<SettingsFileExporterCubit>()
.selectOrDeselectItem(index, i);
},
title: FlowyText.regular(' $name'),
);
expandedChildren.add(checkbox);
}
}
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () => context
.read<SettingsFileExporterCubit>()
.expandOrUnexpandApp(index),
child: ListTile(
title: FlowyText.medium(apps[index].name),
trailing: Icon(
isExpanded
? Icons.arrow_drop_down_rounded
: Icons.arrow_drop_up_rounded,
),
),
),
...expandedChildren,
],
);
}
}
class _AppFlowyFileExporter {
static Future<(bool result, List<String> failedNames)> exportToPath(
String path,
List<ViewPB> views,
) async {
final failedFileNames = <String>[];
final Map<String, int> names = {};
for (final view in views) {
String? content;
String? fileExtension;
switch (view.layout) {
case ViewLayoutPB.Document:
final documentExporter = DocumentExporter(view);
final result = await documentExporter.export(
DocumentExportType.json,
);
result.fold(
(json) {
content = json;
},
(e) => Log.error(e),
);
fileExtension = 'afdocument';
break;
default:
final result =
await BackendExportService.exportDatabaseAsCSV(view.id);
result.fold(
(l) => content = l.data,
(r) => Log.error(r),
);
fileExtension = 'csv';
break;
}
if (content != null) {
final count = names.putIfAbsent(view.name, () => 0);
final name = count == 0 ? view.name : '${view.name}($count)';
final file = File(p.join(path, '$name.$fileExtension'));
await file.writeAsString(content!);
names[view.name] = count + 1;
} else {
failedFileNames.add(view.name);
}
}
return (failedFileNames.isEmpty, failedFileNames);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/files/settings_export_file_widget.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/files/settings_file_exporter_widget.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:styled_widget/styled_widget.dart';
import '../../../../../generated/locale_keys.g.dart';
class SettingsExportFileWidget extends StatefulWidget {
const SettingsExportFileWidget({
super.key,
});
@override
State<SettingsExportFileWidget> createState() =>
SettingsExportFileWidgetState();
}
@visibleForTesting
class SettingsExportFileWidgetState extends State<SettingsExportFileWidget> {
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
FlowyText.medium(
LocaleKeys.settings_files_exportData.tr(),
fontSize: 13,
overflow: TextOverflow.ellipsis,
).padding(horizontal: 5.0),
const Spacer(),
_OpenExportedDirectoryButton(
onTap: () async {
await showDialog(
context: context,
builder: (context) {
return const FlowyDialog(
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 16,
vertical: 20,
),
child: FileExporterWidget(),
),
);
},
);
},
),
],
);
}
}
class _OpenExportedDirectoryButton extends StatelessWidget {
const _OpenExportedDirectoryButton({
required this.onTap,
});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return FlowyIconButton(
hoverColor: Theme.of(context).colorScheme.secondaryContainer,
tooltipText: LocaleKeys.settings_files_export.tr(),
icon: FlowySvg(
FlowySvgs.open_folder_lg,
color: Theme.of(context).iconTheme.color,
),
onPressed: onTap,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/files/settings_file_customize_location_view.dart | import 'dart:io';
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/workspace/application/settings/settings_location_cubit.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/file_picker/file_picker_service.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flowy_infra_ui/widget/buttons/secondary_button.dart';
import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:styled_widget/styled_widget.dart';
import '../../../../../generated/locale_keys.g.dart';
import '../../../../../startup/startup.dart';
import '../../../../../startup/tasks/prelude.dart';
class SettingsFileLocationCustomizer extends StatefulWidget {
const SettingsFileLocationCustomizer({
super.key,
});
@override
State<SettingsFileLocationCustomizer> createState() =>
SettingsFileLocationCustomizerState();
}
@visibleForTesting
class SettingsFileLocationCustomizerState
extends State<SettingsFileLocationCustomizer> {
@override
Widget build(BuildContext context) {
return BlocProvider<SettingsLocationCubit>(
create: (_) => SettingsLocationCubit(),
child: BlocBuilder<SettingsLocationCubit, SettingsLocationState>(
builder: (context, state) {
return state.when(
initial: () => const Center(
child: CircularProgressIndicator(),
),
didReceivedPath: (path) {
return Column(
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
// display file paths.
_path(path),
// display the icons
_buttons(path),
],
),
const VSpace(10),
IntrinsicHeight(
child: Opacity(
opacity: 0.6,
child: FlowyText.medium(
LocaleKeys.settings_menu_customPathPrompt.tr(),
maxLines: 13,
),
),
),
],
);
},
);
},
),
);
}
Widget _path(String path) {
return Flexible(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlowyText.medium(
LocaleKeys.settings_files_defaultLocation.tr(),
fontSize: 13,
overflow: TextOverflow.visible,
).padding(horizontal: 5),
const VSpace(5),
_CopyableText(
usingPath: path,
),
],
),
);
}
Widget _buttons(String path) {
final List<Widget> children = [];
children.addAll([
Flexible(
child: _ChangeStoragePathButton(
usingPath: path,
),
),
const HSpace(10),
]);
children.add(
_OpenStorageButton(
usingPath: path,
),
);
children.add(
_RecoverDefaultStorageButton(
usingPath: path,
),
);
return Flexible(
child: Row(mainAxisAlignment: MainAxisAlignment.end, children: children),
);
}
}
class _CopyableText extends StatelessWidget {
const _CopyableText({
required this.usingPath,
});
final String usingPath;
@override
Widget build(BuildContext context) {
return FlowyHover(
builder: (_, onHover) {
return GestureDetector(
onTap: () {
Clipboard.setData(ClipboardData(text: usingPath));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: FlowyText(
LocaleKeys.settings_files_pathCopiedSnackbar.tr(),
color: Theme.of(context).colorScheme.onSurface,
),
),
);
},
child: Container(
height: 20,
padding: const EdgeInsets.symmetric(horizontal: 5),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: FlowyText.regular(
usingPath,
fontSize: 12,
overflow: TextOverflow.ellipsis,
),
),
if (onHover) ...[
const HSpace(5),
FlowyText.regular(
LocaleKeys.settings_files_copy.tr(),
fontSize: 12,
color: Theme.of(context).colorScheme.primary,
),
],
],
),
),
);
},
);
}
}
class _ChangeStoragePathButton extends StatefulWidget {
const _ChangeStoragePathButton({
required this.usingPath,
});
final String usingPath;
@override
State<_ChangeStoragePathButton> createState() =>
_ChangeStoragePathButtonState();
}
class _ChangeStoragePathButtonState extends State<_ChangeStoragePathButton> {
@override
Widget build(BuildContext context) {
return FlowyTooltip(
message: LocaleKeys.settings_files_changeLocationTooltips.tr(),
child: SecondaryTextButton(
LocaleKeys.settings_files_change.tr(),
mode: TextButtonMode.small,
onPressed: () async {
// pick the new directory and reload app
final path = await getIt<FilePickerService>().getDirectoryPath();
if (path == null || widget.usingPath == path) {
return;
}
if (!context.mounted) {
return;
}
await context.read<SettingsLocationCubit>().setCustomPath(path);
await runAppFlowy(isAnon: true);
if (context.mounted) {
Navigator.of(context).pop();
}
},
),
);
}
}
class _OpenStorageButton extends StatelessWidget {
const _OpenStorageButton({
required this.usingPath,
});
final String usingPath;
@override
Widget build(BuildContext context) {
return FlowyIconButton(
hoverColor: Theme.of(context).colorScheme.secondaryContainer,
tooltipText: LocaleKeys.settings_files_openCurrentDataFolder.tr(),
icon: FlowySvg(
FlowySvgs.open_folder_lg,
color: Theme.of(context).iconTheme.color,
),
onPressed: () async {
final uri = Directory(usingPath).uri;
await afLaunchUrl(uri, context: context);
},
);
}
}
class _RecoverDefaultStorageButton extends StatefulWidget {
const _RecoverDefaultStorageButton({
required this.usingPath,
});
final String usingPath;
@override
State<_RecoverDefaultStorageButton> createState() =>
_RecoverDefaultStorageButtonState();
}
class _RecoverDefaultStorageButtonState
extends State<_RecoverDefaultStorageButton> {
@override
Widget build(BuildContext context) {
return FlowyIconButton(
hoverColor: Theme.of(context).colorScheme.secondaryContainer,
tooltipText: LocaleKeys.settings_files_recoverLocationTooltips.tr(),
icon: const FlowySvg(
FlowySvgs.restore_s,
size: Size.square(20),
),
onPressed: () async {
// reset to the default directory and reload app
final directory = await appFlowyApplicationDataDirectory();
final path = directory.path;
if (widget.usingPath == path) {
return;
}
if (!context.mounted) {
return;
}
await context
.read<SettingsLocationCubit>()
.resetDataStoragePathToApplicationDefault();
await runAppFlowy(isAnon: true);
if (context.mounted) {
Navigator.of(context).pop();
}
},
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/files/settings_file_cache_widget.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/shared/appflowy_cache_manager.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/presentation/home/toast.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
class SettingsFileCacheWidget extends StatelessWidget {
const SettingsFileCacheWidget({
super.key,
});
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 5.0),
child: FlowyText.medium(
LocaleKeys.settings_files_clearCache.tr(),
fontSize: 13,
overflow: TextOverflow.ellipsis,
),
),
const VSpace(8),
Opacity(
opacity: 0.6,
child: FlowyText(
LocaleKeys.settings_files_clearCacheDesc.tr(),
fontSize: 10,
maxLines: 3,
),
),
],
),
),
const _ClearCacheButton(),
],
);
}
}
class _ClearCacheButton extends StatelessWidget {
const _ClearCacheButton();
@override
Widget build(BuildContext context) {
return FlowyIconButton(
hoverColor: Theme.of(context).colorScheme.secondaryContainer,
tooltipText: LocaleKeys.settings_files_clearCache.tr(),
icon: FlowySvg(
FlowySvgs.delete_s,
size: const Size.square(18),
color: Theme.of(context).iconTheme.color,
),
onPressed: () {
NavigatorAlertDialog(
title: LocaleKeys.settings_files_areYouSureToClearCache.tr(),
confirm: () async {
await getIt<FlowyCacheManager>().clearAllCache();
if (context.mounted) {
showSnackBarMessage(
context,
LocaleKeys.settings_files_clearCacheSuccess.tr(),
);
}
},
).show(context);
},
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/files/setting_file_import_appflowy_data_view.dart | import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/settings/setting_file_importer_bloc.dart';
import 'package:appflowy/workspace/presentation/home/toast.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/file_picker/file_picker_service.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
class ImportAppFlowyData extends StatefulWidget {
const ImportAppFlowyData({super.key});
@override
State<ImportAppFlowyData> createState() => _ImportAppFlowyDataState();
}
class _ImportAppFlowyDataState extends State<ImportAppFlowyData> {
final _fToast = FToast();
@override
void initState() {
super.initState();
_fToast.init(context);
}
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => SettingFileImportBloc(),
child: BlocListener<SettingFileImportBloc, SettingFileImportState>(
listener: (context, state) {
state.successOrFail?.fold(
(_) {
_showToast(LocaleKeys.settings_menu_importSuccess.tr());
},
(_) {
_showToast(LocaleKeys.settings_menu_importFailed.tr());
},
);
},
child: BlocBuilder<SettingFileImportBloc, SettingFileImportState>(
builder: (context, state) {
final List<Widget> children = [
const ImportAppFlowyDataButton(),
const VSpace(6),
];
if (state.loadingState.isLoading()) {
children.add(const AppFlowyDataImportingTip());
} else {
children.add(const AppFlowyDataImportTip());
}
return Column(children: children);
},
),
),
);
}
void _showToast(String message) {
_fToast.showToast(
child: FlowyMessageToast(message: message),
gravity: ToastGravity.CENTER,
);
}
}
class AppFlowyDataImportTip extends StatelessWidget {
const AppFlowyDataImportTip({super.key});
final url = "https://docs.appflowy.io/docs/appflowy/product/data-storage";
@override
Widget build(BuildContext context) {
return Opacity(
opacity: 0.6,
child: RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(
text: LocaleKeys.settings_menu_importAppFlowyDataDescription.tr(),
style: Theme.of(context).textTheme.bodySmall!,
),
TextSpan(
text: " ${LocaleKeys.settings_menu_importGuide.tr()} ",
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: Theme.of(context).colorScheme.primary,
decoration: TextDecoration.underline,
),
recognizer: TapGestureRecognizer()
..onTap = () => afLaunchUrlString(url),
),
],
),
),
);
}
}
class ImportAppFlowyDataButton extends StatefulWidget {
const ImportAppFlowyDataButton({super.key});
@override
State<ImportAppFlowyDataButton> createState() =>
_ImportAppFlowyDataButtonState();
}
class _ImportAppFlowyDataButtonState extends State<ImportAppFlowyDataButton> {
@override
Widget build(BuildContext context) {
return BlocBuilder<SettingFileImportBloc, SettingFileImportState>(
builder: (context, state) {
return Column(
children: [
SizedBox(
height: 40,
child: FlowyButton(
disable: state.loadingState.isLoading(),
text:
FlowyText(LocaleKeys.settings_menu_importAppFlowyData.tr()),
onTap: () async {
final path =
await getIt<FilePickerService>().getDirectoryPath();
if (path == null || !context.mounted) {
return;
}
context.read<SettingFileImportBloc>().add(
SettingFileImportEvent.importAppFlowyDataFolder(path),
);
},
),
),
if (state.loadingState.isLoading())
const LinearProgressIndicator(minHeight: 1),
],
);
},
);
}
}
class AppFlowyDataImportingTip extends StatelessWidget {
const AppFlowyDataImportingTip({super.key});
@override
Widget build(BuildContext context) {
return Opacity(
opacity: 0.6,
child: RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(
text: LocaleKeys.settings_menu_importingAppFlowyDataTip.tr(),
style: Theme.of(context).textTheme.bodySmall!,
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/utils/hex_opacity_string_extension.dart | extension HexOpacityExtension on String {
/// Only used in a valid color String like '0xff00bcf0'
String extractHex() {
return substring(4);
}
/// Only used in a valid color String like '0xff00bcf0'
String extractOpacity() {
final opacityString = substring(2, 4);
final opacityInt = int.parse(opacityString, radix: 16) / 2.55;
return opacityInt.toStringAsFixed(0);
}
/// Apply on the hex string like '00bcf0', with opacity like '100'
String combineHexWithOpacity(String opacity) {
final opacityInt = (int.parse(opacity) * 2.55).round().toRadixString(16);
return '0x$opacityInt$this';
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/utils/form_factor.dart | enum FormFactor {
mobile._(600),
tablet._(840),
desktop._(1280);
const FormFactor._(this.width);
factory FormFactor.fromWidth(double width) {
if (width < FormFactor.mobile.width) {
return FormFactor.mobile;
} else if (width < FormFactor.tablet.width) {
return FormFactor.tablet;
} else {
return FormFactor.desktop;
}
}
final double width;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/document_selection_color_setting.dart | import 'package:flutter/material.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/document_appearance_cubit.dart';
import 'package:appflowy/workspace/application/appearance_defaults.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/document_color_setting_button.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/theme_setting_entry_template.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class DocumentSelectionColorSetting extends StatelessWidget {
const DocumentSelectionColorSetting({
super.key,
required this.currentSelectionColor,
});
final Color currentSelectionColor;
@override
Widget build(BuildContext context) {
final label =
LocaleKeys.settings_appearance_documentSettings_selectionColor.tr();
return FlowySettingListTile(
label: label,
resetButtonKey: const Key('DocumentSelectionColorResetButton'),
onResetRequested: () {
context.read<AppearanceSettingsCubit>().resetDocumentSelectionColor();
context.read<DocumentAppearanceCubit>().syncSelectionColor(null);
},
trailing: [
DocumentColorSettingButton(
currentColor: currentSelectionColor,
previewWidgetBuilder: (color) => _SelectionColorValueWidget(
selectionColor: color ??
DefaultAppearanceSettings.getDefaultDocumentSelectionColor(
context,
),
),
dialogTitle: label,
onApply: (selectedColorOnDialog) {
context
.read<AppearanceSettingsCubit>()
.setDocumentSelectionColor(selectedColorOnDialog);
// update the state of document appearance cubit with latest selection color
context
.read<DocumentAppearanceCubit>()
.syncSelectionColor(selectedColorOnDialog);
},
),
],
);
}
}
class _SelectionColorValueWidget extends StatelessWidget {
const _SelectionColorValueWidget({
required this.selectionColor,
});
final Color selectionColor;
@override
Widget build(BuildContext context) {
// To avoid the text color changes when it is hovered in dark mode
final textColor = Theme.of(context).colorScheme.onBackground;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
color: selectionColor,
child: FlowyText(
LocaleKeys.settings_appearance_documentSettings_app.tr(),
color: textColor,
),
),
FlowyText(
LocaleKeys.settings_appearance_documentSettings_flowy.tr(),
color: textColor,
),
],
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/font_family_setting.dart | import 'package:flutter/material.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/document_appearance_cubit.dart';
import 'package:appflowy/util/google_font_family_extension.dart';
import 'package:appflowy/workspace/application/appearance_defaults.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'levenshtein.dart';
import 'theme_setting_entry_template.dart';
class ThemeFontFamilySetting extends StatefulWidget {
const ThemeFontFamilySetting({
super.key,
required this.currentFontFamily,
});
final String currentFontFamily;
static Key textFieldKey = const Key('FontFamilyTextField');
static Key resetButtonkey = const Key('FontFamilyResetButton');
static Key popoverKey = const Key('FontFamilyPopover');
@override
State<ThemeFontFamilySetting> createState() => _ThemeFontFamilySettingState();
}
class _ThemeFontFamilySettingState extends State<ThemeFontFamilySetting> {
@override
Widget build(BuildContext context) {
return FlowySettingListTile(
label: LocaleKeys.settings_appearance_fontFamily_label.tr(),
resetButtonKey: ThemeFontFamilySetting.resetButtonkey,
onResetRequested: () {
context.read<AppearanceSettingsCubit>().resetFontFamily();
context
.read<DocumentAppearanceCubit>()
.syncFontFamily(DefaultAppearanceSettings.kDefaultFontFamily);
},
trailing: [
FontFamilyDropDown(
currentFontFamily: widget.currentFontFamily,
),
],
);
}
}
class FontFamilyDropDown extends StatefulWidget {
const FontFamilyDropDown({
super.key,
required this.currentFontFamily,
this.onOpen,
this.onClose,
this.onFontFamilyChanged,
this.child,
this.popoverController,
this.offset,
this.showResetButton = false,
this.onResetFont,
});
final String currentFontFamily;
final VoidCallback? onOpen;
final VoidCallback? onClose;
final void Function(String fontFamily)? onFontFamilyChanged;
final Widget? child;
final PopoverController? popoverController;
final Offset? offset;
final bool showResetButton;
final VoidCallback? onResetFont;
@override
State<FontFamilyDropDown> createState() => _FontFamilyDropDownState();
}
class _FontFamilyDropDownState extends State<FontFamilyDropDown> {
final List<String> availableFonts = GoogleFonts.asMap().keys.toList();
final ValueNotifier<String> query = ValueNotifier('');
@override
void dispose() {
query.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FlowySettingValueDropDown(
popoverKey: ThemeFontFamilySetting.popoverKey,
popoverController: widget.popoverController,
currentValue: widget.currentFontFamily.parseFontFamilyName(),
onClose: () {
query.value = '';
widget.onClose?.call();
},
offset: widget.offset,
child: widget.child,
popupBuilder: (_) {
widget.onOpen?.call();
return CustomScrollView(
shrinkWrap: true,
slivers: [
if (widget.showResetButton)
SliverPersistentHeader(
delegate: _ResetFontButton(
onPressed: widget.onResetFont,
),
pinned: true,
),
SliverPadding(
padding: const EdgeInsets.only(right: 8),
sliver: SliverToBoxAdapter(
child: FlowyTextField(
key: ThemeFontFamilySetting.textFieldKey,
hintText:
LocaleKeys.settings_appearance_fontFamily_search.tr(),
autoFocus: false,
debounceDuration: const Duration(milliseconds: 300),
onChanged: (value) {
query.value = value;
},
),
),
),
const SliverToBoxAdapter(
child: SizedBox(height: 4),
),
ValueListenableBuilder(
valueListenable: query,
builder: (context, value, child) {
var displayed = availableFonts;
if (value.isNotEmpty) {
displayed = availableFonts
.where(
(font) => font
.toLowerCase()
.contains(value.toLowerCase().toString()),
)
.sorted((a, b) => levenshtein(a, b))
.toList();
}
return SliverFixedExtentList.builder(
itemBuilder: (context, index) => _fontFamilyItemButton(
context,
GoogleFonts.getFont(displayed[index]),
),
itemCount: displayed.length,
itemExtent: 32,
);
},
),
],
);
},
);
}
Widget _fontFamilyItemButton(
BuildContext context,
TextStyle style,
) {
final buttonFontFamily = style.fontFamily!.parseFontFamilyName();
return Tooltip(
message: buttonFontFamily,
waitDuration: const Duration(milliseconds: 150),
child: SizedBox(
key: ValueKey(buttonFontFamily),
height: 32,
child: FlowyButton(
onHover: (_) => FocusScope.of(context).unfocus(),
text: FlowyText.medium(
buttonFontFamily,
fontFamily: style.fontFamily!,
),
rightIcon:
buttonFontFamily == widget.currentFontFamily.parseFontFamilyName()
? const FlowySvg(FlowySvgs.check_s)
: null,
onTap: () {
if (widget.onFontFamilyChanged != null) {
widget.onFontFamilyChanged!(style.fontFamily!);
} else {
final fontFamily = style.fontFamily!.parseFontFamilyName();
if (widget.currentFontFamily.parseFontFamilyName() !=
buttonFontFamily) {
context
.read<AppearanceSettingsCubit>()
.setFontFamily(fontFamily);
context
.read<DocumentAppearanceCubit>()
.syncFontFamily(fontFamily);
}
}
PopoverContainer.of(context).close();
},
),
),
);
}
}
class _ResetFontButton extends SliverPersistentHeaderDelegate {
_ResetFontButton({
this.onPressed,
});
final VoidCallback? onPressed;
@override
Widget build(
BuildContext context,
double shrinkOffset,
bool overlapsContent,
) {
return Padding(
padding: const EdgeInsets.only(right: 8, bottom: 8.0),
child: FlowyTextButton(
LocaleKeys.document_toolbar_resetToDefaultFont.tr(),
onPressed: onPressed,
),
);
}
@override
double get maxExtent => 35;
@override
double get minExtent => 35;
@override
bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) =>
true;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/document_color_setting_button.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/util/color_to_hex_string.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/utils/hex_opacity_string_extension.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/widget/dialog/styled_dialogs.dart';
import 'package:flowy_infra_ui/widget/rounded_button.dart';
import 'package:flutter/material.dart';
class DocumentColorSettingButton extends StatelessWidget {
const DocumentColorSettingButton({
super.key,
required this.currentColor,
required this.previewWidgetBuilder,
required this.dialogTitle,
required this.onApply,
});
/// current color from backend
final Color currentColor;
/// Build a preview widget with the given color
/// It shows both on the [DocumentColorSettingButton] and [_DocumentColorSettingDialog]
final Widget Function(Color? color) previewWidgetBuilder;
final String dialogTitle;
final void Function(Color selectedColorOnDialog) onApply;
@override
Widget build(BuildContext context) {
return FlowyButton(
margin: const EdgeInsets.all(8),
text: previewWidgetBuilder.call(currentColor),
hoverColor: Theme.of(context).colorScheme.secondaryContainer,
expandText: false,
onTap: () => Dialogs.show(
context,
child: _DocumentColorSettingDialog(
currentColor: currentColor,
previewWidgetBuilder: previewWidgetBuilder,
dialogTitle: dialogTitle,
onApply: onApply,
),
),
);
}
}
class _DocumentColorSettingDialog extends StatefulWidget {
const _DocumentColorSettingDialog({
required this.currentColor,
required this.previewWidgetBuilder,
required this.dialogTitle,
required this.onApply,
});
final Color currentColor;
final Widget Function(Color?) previewWidgetBuilder;
final String dialogTitle;
final void Function(Color selectedColorOnDialog) onApply;
@override
State<_DocumentColorSettingDialog> createState() =>
DocumentColorSettingDialogState();
}
class DocumentColorSettingDialogState
extends State<_DocumentColorSettingDialog> {
/// The color displayed in the dialog.
/// It is `null` when the user didn't enter a valid color value.
late Color? selectedColorOnDialog;
late String currentColorHexString;
late TextEditingController hexController;
late TextEditingController opacityController;
final _formKey = GlobalKey<FormState>(debugLabel: 'colorSettingForm');
void updateSelectedColor() {
if (_formKey.currentState!.validate()) {
setState(() {
final colorValue = int.tryParse(
hexController.text.combineHexWithOpacity(opacityController.text),
);
// colorValue has been validated in the _ColorSettingTextField for hex value and it won't be null as this point
selectedColorOnDialog = Color(colorValue!);
});
}
}
@override
void initState() {
super.initState();
selectedColorOnDialog = widget.currentColor;
currentColorHexString = widget.currentColor.toHexString();
hexController = TextEditingController(
text: currentColorHexString.extractHex(),
);
opacityController = TextEditingController(
text: currentColorHexString.extractOpacity(),
);
}
@override
void dispose() {
hexController.dispose();
opacityController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FlowyDialog(
constraints: const BoxConstraints(maxWidth: 360, maxHeight: 320),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
children: [
const Spacer(),
FlowyText(widget.dialogTitle),
const VSpace(8),
SizedBox(
width: 100,
height: 40,
child: Center(
child: widget.previewWidgetBuilder(
selectedColorOnDialog,
),
),
),
const VSpace(8),
SizedBox(
height: 160,
child: Form(
key: _formKey,
child: Column(
children: [
_ColorSettingTextField(
controller: hexController,
labelText: LocaleKeys.editor_hexValue.tr(),
hintText: '6fc9e7',
onFieldSubmitted: (_) => updateSelectedColor(),
validator: (hexValue) => validateHexValue(
hexValue,
opacityController.text,
),
),
const VSpace(8),
_ColorSettingTextField(
controller: opacityController,
labelText: LocaleKeys.editor_opacity.tr(),
hintText: '50',
onFieldSubmitted: (_) => updateSelectedColor(),
validator: (value) => validateOpacityValue(value),
),
],
),
),
),
const VSpace(8),
RoundedTextButton(
title: LocaleKeys.settings_appearance_documentSettings_apply.tr(),
width: 100,
height: 30,
onPressed: () {
if (_formKey.currentState!.validate()) {
if (selectedColorOnDialog != null &&
selectedColorOnDialog != widget.currentColor) {
widget.onApply.call(selectedColorOnDialog!);
}
} else {
// error message will be shown below the text field
return;
}
Navigator.of(context).pop();
},
),
],
),
),
);
}
}
class _ColorSettingTextField extends StatelessWidget {
const _ColorSettingTextField({
required this.controller,
required this.labelText,
required this.hintText,
required this.onFieldSubmitted,
required this.validator,
});
final TextEditingController controller;
final String labelText;
final String hintText;
final void Function(String) onFieldSubmitted;
final String? Function(String?)? validator;
@override
Widget build(BuildContext context) {
final style = Theme.of(context);
return TextFormField(
controller: controller,
decoration: InputDecoration(
labelText: labelText,
hintText: hintText,
border: OutlineInputBorder(
borderSide: BorderSide(
color: style.colorScheme.outline,
),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: style.colorScheme.outline,
),
),
),
style: style.textTheme.bodyMedium,
onFieldSubmitted: onFieldSubmitted,
validator: validator,
autovalidateMode: AutovalidateMode.onUserInteraction,
);
}
}
String? validateHexValue(
String? hexValue,
String opacityValue,
) {
if (hexValue == null || hexValue.isEmpty) {
return LocaleKeys.settings_appearance_documentSettings_hexEmptyError.tr();
}
if (hexValue.length != 6) {
return LocaleKeys.settings_appearance_documentSettings_hexLengthError.tr();
}
if (validateOpacityValue(opacityValue) == null) {
final colorValue =
int.tryParse(hexValue.combineHexWithOpacity(opacityValue));
if (colorValue == null) {
return LocaleKeys.settings_appearance_documentSettings_hexInvalidError
.tr();
}
}
return null;
}
String? validateOpacityValue(String? value) {
if (value == null || value.isEmpty) {
return LocaleKeys.settings_appearance_documentSettings_opacityEmptyError
.tr();
}
final opacityInt = int.tryParse(value);
if (opacityInt == null || opacityInt > 100 || opacityInt <= 0) {
return LocaleKeys.settings_appearance_documentSettings_opacityRangeError
.tr();
}
return null;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/time_format_setting.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy_backend/protobuf/flowy-user/date_time.pbenum.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'theme_setting_entry_template.dart';
class TimeFormatSetting extends StatelessWidget {
const TimeFormatSetting({
super.key,
required this.currentFormat,
});
final UserTimeFormatPB currentFormat;
@override
Widget build(BuildContext context) => FlowySettingListTile(
label: LocaleKeys.settings_appearance_timeFormat_label.tr(),
trailing: [
FlowySettingValueDropDown(
currentValue: _formatLabel(currentFormat),
popupBuilder: (_) => Column(
mainAxisSize: MainAxisSize.min,
children: [
_formatItem(context, UserTimeFormatPB.TwentyFourHour),
_formatItem(context, UserTimeFormatPB.TwelveHour),
],
),
),
],
);
Widget _formatItem(BuildContext context, UserTimeFormatPB format) {
return SizedBox(
height: 32,
child: FlowyButton(
text: FlowyText.medium(_formatLabel(format)),
rightIcon:
currentFormat == format ? const FlowySvg(FlowySvgs.check_s) : null,
onTap: () {
if (currentFormat != format) {
context.read<AppearanceSettingsCubit>().setTimeFormat(format);
}
},
),
);
}
String _formatLabel(UserTimeFormatPB format) {
switch (format) {
case (UserTimeFormatPB.TwentyFourHour):
return LocaleKeys.settings_appearance_timeFormat_twentyFourHour.tr();
case (UserTimeFormatPB.TwelveHour):
return LocaleKeys.settings_appearance_timeFormat_twelveHour.tr();
default:
return "";
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/color_scheme.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy/workspace/presentation/home/toast.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/theme_setting_entry_template.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/theme_upload/theme_upload_view.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/plugins/bloc/dynamic_plugin_bloc.dart';
import 'package:flowy_infra/plugins/bloc/dynamic_plugin_event.dart';
import 'package:flowy_infra/plugins/bloc/dynamic_plugin_state.dart';
import 'package:flowy_infra/theme.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/widget/dialog/styled_dialogs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class ColorSchemeSetting extends StatelessWidget {
const ColorSchemeSetting({
super.key,
required this.currentTheme,
required this.bloc,
});
final String currentTheme;
final DynamicPluginBloc bloc;
@override
Widget build(BuildContext context) {
return FlowySettingListTile(
label: LocaleKeys.settings_appearance_theme.tr(),
onResetRequested: context.read<AppearanceSettingsCubit>().resetTheme,
trailing: [
ColorSchemeUploadPopover(currentTheme: currentTheme, bloc: bloc),
ColorSchemeUploadOverlayButton(bloc: bloc),
],
);
}
}
class ColorSchemeUploadOverlayButton extends StatelessWidget {
const ColorSchemeUploadOverlayButton({super.key, required this.bloc});
final DynamicPluginBloc bloc;
@override
Widget build(BuildContext context) {
return FlowyIconButton(
width: 24,
icon: FlowySvg(
FlowySvgs.folder_m,
size: const Size.square(16),
color: Theme.of(context).iconTheme.color,
),
iconColorOnHover: Theme.of(context).colorScheme.onPrimary,
hoverColor: Theme.of(context).colorScheme.secondaryContainer,
tooltipText: LocaleKeys.settings_appearance_themeUpload_uploadTheme.tr(),
onPressed: () => Dialogs.show(
context,
child: BlocProvider<DynamicPluginBloc>.value(
value: bloc,
child: const FlowyDialog(
constraints: BoxConstraints(maxHeight: 300),
child: ThemeUploadWidget(),
),
),
).then((value) {
if (value == null) return;
showSnackBarMessage(
context,
LocaleKeys.settings_appearance_themeUpload_uploadSuccess.tr(),
);
}),
);
}
}
class ColorSchemeUploadPopover extends StatelessWidget {
const ColorSchemeUploadPopover({
super.key,
required this.currentTheme,
required this.bloc,
});
final String currentTheme;
final DynamicPluginBloc bloc;
@override
Widget build(BuildContext context) {
return AppFlowyPopover(
direction: PopoverDirection.bottomWithRightAligned,
child: FlowyTextButton(
currentTheme,
fontColor: Theme.of(context).colorScheme.onBackground,
fillColor: Colors.transparent,
onPressed: () {},
),
popupBuilder: (BuildContext context) {
return IntrinsicWidth(
child: BlocBuilder<DynamicPluginBloc, DynamicPluginState>(
bloc: bloc..add(DynamicPluginEvent.load()),
buildWhen: (previous, current) => current is Ready,
builder: (context, state) {
return state.maybeWhen(
ready: (plugins) => Column(
mainAxisSize: MainAxisSize.min,
children: [
...AppTheme.builtins.map(
(theme) => _themeItemButton(context, theme.themeName),
),
if (plugins.isNotEmpty) ...[
const Divider(),
...plugins
.map((plugin) => plugin.theme)
.whereType<AppTheme>()
.map(
(theme) => _themeItemButton(
context,
theme.themeName,
false,
),
),
],
],
),
orElse: () => const SizedBox.shrink(),
);
},
),
);
},
);
}
Widget _themeItemButton(
BuildContext context,
String theme, [
bool isBuiltin = true,
]) {
return SizedBox(
height: 32,
child: Row(
children: [
Expanded(
child: FlowyButton(
text: FlowyText.medium(theme),
rightIcon: currentTheme == theme
? const FlowySvg(
FlowySvgs.check_s,
)
: null,
onTap: () {
if (currentTheme != theme) {
context.read<AppearanceSettingsCubit>().setTheme(theme);
}
PopoverContainer.of(context).close();
},
),
),
// when the custom theme is not the current theme, show the remove button
if (!isBuiltin && currentTheme != theme)
FlowyIconButton(
icon: const FlowySvg(
FlowySvgs.close_s,
),
width: 20,
onPressed: () =>
bloc.add(DynamicPluginEvent.removePlugin(name: theme)),
),
],
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/document_cursor_color_setting.dart | import 'package:flutter/material.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/document_appearance_cubit.dart';
import 'package:appflowy/workspace/application/appearance_defaults.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/document_color_setting_button.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/theme_setting_entry_template.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class DocumentCursorColorSetting extends StatelessWidget {
const DocumentCursorColorSetting({
super.key,
required this.currentCursorColor,
});
final Color currentCursorColor;
@override
Widget build(BuildContext context) {
final label =
LocaleKeys.settings_appearance_documentSettings_cursorColor.tr();
return FlowySettingListTile(
label: label,
resetButtonKey: const Key('DocumentCursorColorResetButton'),
onResetRequested: () {
context.read<AppearanceSettingsCubit>().resetDocumentCursorColor();
context.read<DocumentAppearanceCubit>().syncCursorColor(null);
},
trailing: [
DocumentColorSettingButton(
key: const Key('DocumentCursorColorSettingButton'),
currentColor: currentCursorColor,
previewWidgetBuilder: (color) => _CursorColorValueWidget(
cursorColor: color ??
DefaultAppearanceSettings.getDefaultDocumentCursorColor(
context,
),
),
dialogTitle: label,
onApply: (selectedColorOnDialog) {
context
.read<AppearanceSettingsCubit>()
.setDocumentCursorColor(selectedColorOnDialog);
// update the state of document appearance cubit with latest cursor color
context
.read<DocumentAppearanceCubit>()
.syncCursorColor(selectedColorOnDialog);
},
),
],
);
}
}
class _CursorColorValueWidget extends StatelessWidget {
const _CursorColorValueWidget({
required this.cursorColor,
});
final Color cursorColor;
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
color: cursorColor,
width: 2,
height: 16,
),
FlowyText(
LocaleKeys.appName.tr(),
// To avoid the text color changes when it is hovered in dark mode
color: Theme.of(context).colorScheme.onBackground,
),
],
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/direction_setting.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/document_appearance_cubit.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'theme_setting_entry_template.dart';
class LayoutDirectionSetting extends StatelessWidget {
const LayoutDirectionSetting({
super.key,
required this.currentLayoutDirection,
});
final LayoutDirection currentLayoutDirection;
@override
Widget build(BuildContext context) {
return FlowySettingListTile(
label: LocaleKeys.settings_appearance_layoutDirection_label.tr(),
hint: LocaleKeys.settings_appearance_layoutDirection_hint.tr(),
trailing: [
FlowySettingValueDropDown(
currentValue: _layoutDirectionLabelText(currentLayoutDirection),
popupBuilder: (context) => Column(
mainAxisSize: MainAxisSize.min,
children: [
_layoutDirectionItemButton(context, LayoutDirection.ltrLayout),
_layoutDirectionItemButton(context, LayoutDirection.rtlLayout),
],
),
),
],
);
}
Widget _layoutDirectionItemButton(
BuildContext context,
LayoutDirection direction,
) {
return SizedBox(
height: 32,
child: FlowyButton(
text: FlowyText.medium(_layoutDirectionLabelText(direction)),
rightIcon: currentLayoutDirection == direction
? const FlowySvg(FlowySvgs.check_s)
: null,
onTap: () {
if (currentLayoutDirection != direction) {
context
.read<AppearanceSettingsCubit>()
.setLayoutDirection(direction);
}
PopoverContainer.of(context).close();
},
),
);
}
String _layoutDirectionLabelText(LayoutDirection direction) {
switch (direction) {
case (LayoutDirection.ltrLayout):
return LocaleKeys.settings_appearance_layoutDirection_ltr.tr();
case (LayoutDirection.rtlLayout):
return LocaleKeys.settings_appearance_layoutDirection_rtl.tr();
default:
return '';
}
}
}
class TextDirectionSetting extends StatelessWidget {
const TextDirectionSetting({
super.key,
required this.currentTextDirection,
});
final AppFlowyTextDirection? currentTextDirection;
@override
Widget build(BuildContext context) => FlowySettingListTile(
label: LocaleKeys.settings_appearance_textDirection_label.tr(),
hint: LocaleKeys.settings_appearance_textDirection_hint.tr(),
trailing: [
FlowySettingValueDropDown(
currentValue: _textDirectionLabelText(currentTextDirection),
popupBuilder: (context) => Column(
mainAxisSize: MainAxisSize.min,
children: [
_textDirectionItemButton(context, null),
_textDirectionItemButton(context, AppFlowyTextDirection.ltr),
_textDirectionItemButton(context, AppFlowyTextDirection.rtl),
_textDirectionItemButton(context, AppFlowyTextDirection.auto),
],
),
),
],
);
Widget _textDirectionItemButton(
BuildContext context,
AppFlowyTextDirection? textDirection,
) {
return SizedBox(
height: 32,
child: FlowyButton(
text: FlowyText.medium(_textDirectionLabelText(textDirection)),
rightIcon: currentTextDirection == textDirection
? const FlowySvg(FlowySvgs.check_s)
: null,
onTap: () {
if (currentTextDirection != textDirection) {
context
.read<AppearanceSettingsCubit>()
.setTextDirection(textDirection);
context
.read<DocumentAppearanceCubit>()
.syncDefaultTextDirection(textDirection?.name);
}
PopoverContainer.of(context).close();
},
),
);
}
String _textDirectionLabelText(AppFlowyTextDirection? textDirection) {
switch (textDirection) {
case (AppFlowyTextDirection.ltr):
return LocaleKeys.settings_appearance_textDirection_ltr.tr();
case (AppFlowyTextDirection.rtl):
return LocaleKeys.settings_appearance_textDirection_rtl.tr();
case (AppFlowyTextDirection.auto):
return LocaleKeys.settings_appearance_textDirection_auto.tr();
default:
return LocaleKeys.settings_appearance_textDirection_fallback.tr();
}
}
}
class EnableRTLToolbarItemsSetting extends StatelessWidget {
const EnableRTLToolbarItemsSetting({
super.key,
});
static const enableRTLSwitchKey = ValueKey('enable_rtl_toolbar_items_switch');
@override
Widget build(BuildContext context) {
return FlowySettingListTile(
label: LocaleKeys.settings_appearance_enableRTLToolbarItems.tr(),
trailing: [
Switch(
key: enableRTLSwitchKey,
value: context
.read<AppearanceSettingsCubit>()
.state
.enableRtlToolbarItems,
splashRadius: 0,
activeColor: Theme.of(context).colorScheme.primary,
onChanged: (value) {
context
.read<AppearanceSettingsCubit>()
.setEnableRTLToolbarItems(value);
},
),
],
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/create_file_setting.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/settings/prelude.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/settings_appearance/theme_setting_entry_template.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
bool _prevSetting = false;
class CreateFileSettings extends StatelessWidget {
CreateFileSettings({
super.key,
});
final cubit = CreateFileSettingsCubit(_prevSetting);
@override
Widget build(BuildContext context) {
return FlowySettingListTile(
label:
LocaleKeys.settings_appearance_showNamingDialogWhenCreatingPage.tr(),
trailing: [
BlocProvider.value(
value: cubit,
child: BlocBuilder<CreateFileSettingsCubit, bool>(
builder: (context, state) {
_prevSetting = state;
return Switch(
value: state,
splashRadius: 0,
activeColor: Theme.of(context).colorScheme.primary,
onChanged: (value) {
cubit.toggle(value: value);
_prevSetting = value;
},
);
},
),
),
],
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/levenshtein.dart | import 'dart:math';
int levenshtein(String s, String t, {bool caseSensitive = true}) {
if (!caseSensitive) {
s = s.toLowerCase();
t = t.toLowerCase();
}
if (s == t) return 0;
final v0 = List<int>.generate(t.length + 1, (i) => i);
final v1 = List<int>.filled(t.length + 1, 0);
for (var i = 0; i < s.length; i++) {
v1[0] = i + 1;
for (var j = 0; j < t.length; j++) {
final cost = (s[i] == t[j]) ? 0 : 1;
v1[j + 1] = min(v1[j] + 1, min(v0[j + 1] + 1, v0[j] + cost));
}
v0.setAll(0, v1);
}
return v1[t.length];
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/date_format_setting.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy_backend/protobuf/flowy-user/date_time.pbenum.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'theme_setting_entry_template.dart';
class DateFormatSetting extends StatelessWidget {
const DateFormatSetting({
super.key,
required this.currentFormat,
});
final UserDateFormatPB currentFormat;
@override
Widget build(BuildContext context) => FlowySettingListTile(
label: LocaleKeys.settings_appearance_dateFormat_label.tr(),
trailing: [
FlowySettingValueDropDown(
currentValue: _formatLabel(currentFormat),
popupBuilder: (_) => Column(
mainAxisSize: MainAxisSize.min,
children: [
_formatItem(context, UserDateFormatPB.Locally),
_formatItem(context, UserDateFormatPB.US),
_formatItem(context, UserDateFormatPB.ISO),
_formatItem(context, UserDateFormatPB.Friendly),
_formatItem(context, UserDateFormatPB.DayMonthYear),
],
),
),
],
);
Widget _formatItem(BuildContext context, UserDateFormatPB format) {
return SizedBox(
height: 32,
child: FlowyButton(
text: FlowyText.medium(_formatLabel(format)),
rightIcon:
currentFormat == format ? const FlowySvg(FlowySvgs.check_s) : null,
onTap: () {
if (currentFormat != format) {
context.read<AppearanceSettingsCubit>().setDateFormat(format);
}
},
),
);
}
String _formatLabel(UserDateFormatPB format) {
switch (format) {
case (UserDateFormatPB.Locally):
return LocaleKeys.settings_appearance_dateFormat_local.tr();
case (UserDateFormatPB.US):
return LocaleKeys.settings_appearance_dateFormat_us.tr();
case (UserDateFormatPB.ISO):
return LocaleKeys.settings_appearance_dateFormat_iso.tr();
case (UserDateFormatPB.Friendly):
return LocaleKeys.settings_appearance_dateFormat_friendly.tr();
case (UserDateFormatPB.DayMonthYear):
return LocaleKeys.settings_appearance_dateFormat_dmy.tr();
default:
return "";
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/theme_setting_entry_template.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
class FlowySettingListTile extends StatelessWidget {
const FlowySettingListTile({
super.key,
this.resetTooltipText,
this.resetButtonKey,
required this.label,
this.hint,
this.trailing,
this.onResetRequested,
});
final String label;
final String? hint;
final String? resetTooltipText;
final Key? resetButtonKey;
final List<Widget>? trailing;
final void Function()? onResetRequested;
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FlowyText.medium(
label,
fontSize: 14,
overflow: TextOverflow.ellipsis,
),
if (hint != null)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: FlowyText.regular(
hint!,
fontSize: 10,
color: Theme.of(context).hintColor,
),
),
],
),
),
if (trailing != null) ...trailing!,
if (onResetRequested != null)
FlowyIconButton(
hoverColor: Theme.of(context).colorScheme.secondaryContainer,
key: resetButtonKey,
width: 24,
icon: FlowySvg(
FlowySvgs.restore_s,
color: Theme.of(context).iconTheme.color,
),
iconColorOnHover: Theme.of(context).colorScheme.onPrimary,
tooltipText: resetTooltipText ??
LocaleKeys.settings_appearance_resetSetting.tr(),
onPressed: onResetRequested,
),
],
);
}
}
class FlowySettingValueDropDown extends StatefulWidget {
const FlowySettingValueDropDown({
super.key,
required this.currentValue,
required this.popupBuilder,
this.popoverKey,
this.onClose,
this.child,
this.popoverController,
this.offset,
});
final String currentValue;
final Key? popoverKey;
final Widget Function(BuildContext) popupBuilder;
final void Function()? onClose;
final Widget? child;
final PopoverController? popoverController;
final Offset? offset;
@override
State<FlowySettingValueDropDown> createState() =>
_FlowySettingValueDropDownState();
}
class _FlowySettingValueDropDownState extends State<FlowySettingValueDropDown> {
@override
Widget build(BuildContext context) {
return AppFlowyPopover(
key: widget.popoverKey,
controller: widget.popoverController,
direction: PopoverDirection.bottomWithCenterAligned,
popupBuilder: widget.popupBuilder,
constraints: const BoxConstraints(
minWidth: 80,
maxWidth: 160,
maxHeight: 400,
),
offset: widget.offset,
onClose: widget.onClose,
child: widget.child ??
FlowyTextButton(
widget.currentValue,
fontColor: Theme.of(context).colorScheme.onBackground,
fillColor: Colors.transparent,
onPressed: () {},
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/brightness_setting.dart | import 'dart:io';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/util/theme_mode_extension.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'theme_setting_entry_template.dart';
class BrightnessSetting extends StatelessWidget {
const BrightnessSetting({required this.currentThemeMode, super.key});
final ThemeMode currentThemeMode;
@override
Widget build(BuildContext context) {
return FlowySettingListTile(
label: LocaleKeys.settings_appearance_themeMode_label.tr(),
hint: hintText,
onResetRequested: context.read<AppearanceSettingsCubit>().resetThemeMode,
trailing: [
FlowySettingValueDropDown(
currentValue: currentThemeMode.labelText,
popupBuilder: (context) => Column(
mainAxisSize: MainAxisSize.min,
children: [
_themeModeItemButton(context, ThemeMode.light),
_themeModeItemButton(context, ThemeMode.dark),
_themeModeItemButton(context, ThemeMode.system),
],
),
),
],
);
}
String get hintText =>
'${LocaleKeys.settings_files_change.tr()} ${LocaleKeys.settings_appearance_themeMode_label.tr()} : ${Platform.isMacOS ? '⌘+Shift+L' : 'Ctrl+Shift+L'}';
Widget _themeModeItemButton(
BuildContext context,
ThemeMode themeMode,
) {
return SizedBox(
height: 32,
child: FlowyButton(
text: FlowyText.medium(themeMode.labelText),
rightIcon: currentThemeMode == themeMode
? const FlowySvg(
FlowySvgs.check_s,
)
: null,
onTap: () {
if (currentThemeMode != themeMode) {
context.read<AppearanceSettingsCubit>().setThemeMode(themeMode);
}
PopoverContainer.of(context).close();
},
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/settings_appearance/settings_appearance.dart | export 'brightness_setting.dart';
export 'font_family_setting.dart';
export 'color_scheme.dart';
export 'direction_setting.dart';
export 'document_cursor_color_setting.dart';
export 'document_selection_color_setting.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/theme_upload/theme_upload_button.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/plugins/bloc/dynamic_plugin_bloc.dart';
import 'package:flowy_infra/plugins/bloc/dynamic_plugin_event.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'theme_upload_view.dart';
class ThemeUploadButton extends StatelessWidget {
const ThemeUploadButton({super.key, this.color});
final Color? color;
@override
Widget build(BuildContext context) {
return SizedBox.fromSize(
size: ThemeUploadWidget.buttonSize,
child: FlowyButton(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: color ?? Theme.of(context).colorScheme.primary,
),
hoverColor: color,
text: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FlowyText.medium(
fontSize: ThemeUploadWidget.buttonFontSize,
color: Theme.of(context).colorScheme.onPrimary,
LocaleKeys.settings_appearance_themeUpload_button.tr(),
),
],
),
onTap: () => BlocProvider.of<DynamicPluginBloc>(context)
.add(DynamicPluginEvent.addPlugin()),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/theme_upload/upload_new_theme_widget.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/theme_upload/theme_upload.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
class UploadNewThemeWidget extends StatelessWidget {
const UploadNewThemeWidget({super.key});
@override
Widget build(BuildContext context) {
return Container(
color: Theme.of(context)
.colorScheme
.background
.withOpacity(ThemeUploadWidget.fadeOpacity),
padding: ThemeUploadWidget.padding,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Spacer(),
FlowySvg(
FlowySvgs.folder_m,
size: ThemeUploadWidget.iconSize,
color: Theme.of(context).colorScheme.onBackground,
),
FlowyText.medium(
LocaleKeys.settings_appearance_themeUpload_description.tr(),
overflow: TextOverflow.ellipsis,
),
ThemeUploadWidget.elementSpacer,
const ThemeUploadLearnMoreButton(),
ThemeUploadWidget.elementSpacer,
const Divider(),
ThemeUploadWidget.elementSpacer,
const ThemeUploadButton(),
ThemeUploadWidget.elementSpacer,
],
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/theme_upload/theme_confirm_delete_dialog.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'theme_upload_view.dart';
class ThemeConfirmDeleteDialog extends StatelessWidget {
const ThemeConfirmDeleteDialog({
super.key,
required this.theme,
});
final AppTheme theme;
void onConfirm(BuildContext context) => Navigator.of(context).pop(true);
void onCancel(BuildContext context) => Navigator.of(context).pop(false);
@override
Widget build(BuildContext context) {
return FlowyDialog(
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(
width: 300,
height: 100,
),
title: FlowyText.regular(
LocaleKeys.document_plugins_cover_alertDialogConfirmation.tr(),
textAlign: TextAlign.center,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
SizedBox(
width: ThemeUploadWidget.buttonSize.width,
child: FlowyButton(
text: FlowyText.semibold(
LocaleKeys.button_ok.tr(),
fontSize: ThemeUploadWidget.buttonFontSize,
),
onTap: () => onConfirm(context),
),
),
SizedBox(
width: ThemeUploadWidget.buttonSize.width,
child: FlowyButton(
text: FlowyText.semibold(
LocaleKeys.button_cancel.tr(),
fontSize: ThemeUploadWidget.buttonFontSize,
),
onTap: () => onCancel(context),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/theme_upload/theme_upload_view.dart | import 'package:flowy_infra/plugins/bloc/dynamic_plugin_bloc.dart';
import 'package:flowy_infra/plugins/bloc/dynamic_plugin_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'theme_upload_decoration.dart';
import 'theme_upload_failure_widget.dart';
import 'theme_upload_loading_widget.dart';
import 'upload_new_theme_widget.dart';
class ThemeUploadWidget extends StatefulWidget {
const ThemeUploadWidget({super.key});
static const double borderRadius = 8;
static const double buttonFontSize = 14;
static const Size buttonSize = Size(100, 32);
static const EdgeInsets padding = EdgeInsets.all(12.0);
static const Size iconSize = Size.square(48);
static const Widget elementSpacer = SizedBox(height: 12);
static const double fadeOpacity = 0.5;
static const Duration fadeDuration = Duration(milliseconds: 750);
@override
State<ThemeUploadWidget> createState() => _ThemeUploadWidgetState();
}
class _ThemeUploadWidgetState extends State<ThemeUploadWidget> {
void listen(BuildContext context, DynamicPluginState state) {
setState(() {
state.whenOrNull(
ready: (plugins) {
child =
const UploadNewThemeWidget(key: Key('upload_new_theme_widget'));
},
deletionSuccess: () {
child =
const UploadNewThemeWidget(key: Key('upload_new_theme_widget'));
},
processing: () {
child = const ThemeUploadLoadingWidget(
key: Key('upload_theme_loading_widget'),
);
},
compilationFailure: (errorMessage) {
child = ThemeUploadFailureWidget(
key: const Key('upload_theme_failure_widget'),
errorMessage: errorMessage,
);
},
compilationSuccess: () {
if (Navigator.of(context).canPop()) {
Navigator.of(context)
.pop(const DynamicPluginState.compilationSuccess());
}
},
);
});
}
Widget child =
const UploadNewThemeWidget(key: Key('upload_new_theme_widget'));
@override
Widget build(BuildContext context) {
return BlocListener<DynamicPluginBloc, DynamicPluginState>(
listener: listen,
child: ThemeUploadDecoration(
child: Center(
child: AnimatedSwitcher(
duration: ThemeUploadWidget.fadeDuration,
switchInCurve: Curves.easeInOutCubicEmphasized,
child: child,
),
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/theme_upload/theme_upload_learn_more_button.dart | import 'package:flutter/material.dart';
import 'package:appflowy/core/helpers/url_launcher.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/theme_upload/theme_upload_view.dart';
import 'package:appflowy/workspace/presentation/widgets/dialogs.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/widget/buttons/secondary_button.dart';
import 'package:flowy_infra_ui/widget/error_page.dart';
class ThemeUploadLearnMoreButton extends StatelessWidget {
const ThemeUploadLearnMoreButton({super.key});
static const learnMoreURL =
'https://docs.appflowy.io/docs/appflowy/product/themes';
@override
Widget build(BuildContext context) {
return SizedBox(
height: ThemeUploadWidget.buttonSize.height,
child: IntrinsicWidth(
child: SecondaryButton(
outlineColor: Theme.of(context).colorScheme.onBackground,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: FlowyText.medium(
fontSize: ThemeUploadWidget.buttonFontSize,
LocaleKeys.document_plugins_autoGeneratorLearnMore.tr(),
),
),
onPressed: () async {
final uri = Uri.parse(learnMoreURL);
await afLaunchUrl(
uri,
context: context,
onFailure: (_) async {
if (context.mounted) {
await Dialogs.show(
context,
child: FlowyDialog(
child: FlowyErrorPage.message(
LocaleKeys
.settings_appearance_themeUpload_urlUploadFailure
.tr()
.replaceAll(
'{}',
uri.toString(),
),
howToFix: LocaleKeys.errorDialog_howToFixFallback.tr(),
),
),
);
}
},
);
},
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/theme_upload/theme_upload_decoration.dart | import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'theme_upload_view.dart';
class ThemeUploadDecoration extends StatelessWidget {
const ThemeUploadDecoration({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(ThemeUploadWidget.borderRadius),
color: Theme.of(context).colorScheme.surface,
border: Border.all(
color: Theme.of(context).colorScheme.onBackground.withOpacity(
ThemeUploadWidget.fadeOpacity,
),
),
),
padding: ThemeUploadWidget.padding,
child: DottedBorder(
borderType: BorderType.RRect,
dashPattern: const [6, 6],
color: Theme.of(context)
.colorScheme
.onBackground
.withOpacity(ThemeUploadWidget.fadeOpacity),
radius: const Radius.circular(ThemeUploadWidget.borderRadius),
child: ClipRRect(
borderRadius: BorderRadius.circular(ThemeUploadWidget.borderRadius),
child: child,
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/theme_upload/theme_upload_failure_widget.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/theme_upload/theme_upload.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flutter/material.dart';
class ThemeUploadFailureWidget extends StatelessWidget {
const ThemeUploadFailureWidget({super.key, required this.errorMessage});
final String errorMessage;
@override
Widget build(BuildContext context) {
return Container(
color: Theme.of(context)
.colorScheme
.error
.withOpacity(ThemeUploadWidget.fadeOpacity),
constraints: const BoxConstraints.expand(),
padding: ThemeUploadWidget.padding,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Spacer(),
FlowySvg(
FlowySvgs.close_m,
size: ThemeUploadWidget.iconSize,
color: Theme.of(context).colorScheme.onBackground,
),
FlowyText.medium(
errorMessage,
overflow: TextOverflow.ellipsis,
),
ThemeUploadWidget.elementSpacer,
const ThemeUploadLearnMoreButton(),
ThemeUploadWidget.elementSpacer,
ThemeUploadButton(color: Theme.of(context).colorScheme.error),
ThemeUploadWidget.elementSpacer,
],
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/theme_upload/theme_upload.dart | export 'theme_confirm_delete_dialog.dart';
export 'theme_upload_button.dart';
export 'theme_upload_learn_more_button.dart';
export 'theme_upload_decoration.dart';
export 'theme_upload_failure_widget.dart';
export 'theme_upload_loading_widget.dart';
export 'theme_upload_view.dart';
export 'upload_new_theme_widget.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/theme_upload/theme_upload_loading_widget.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/presentation/settings/widgets/theme_upload/theme_upload_view.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
class ThemeUploadLoadingWidget extends StatelessWidget {
const ThemeUploadLoadingWidget({super.key});
@override
Widget build(BuildContext context) {
return Container(
padding: ThemeUploadWidget.padding,
color: Theme.of(context)
.colorScheme
.background
.withOpacity(ThemeUploadWidget.fadeOpacity),
constraints: const BoxConstraints.expand(),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(
color: Theme.of(context).colorScheme.primary,
),
ThemeUploadWidget.elementSpacer,
FlowyText.regular(
LocaleKeys.settings_appearance_themeUpload_loading.tr(),
),
],
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/feature_flags/mobile_feature_flag_screen.dart | import 'package:appflowy/workspace/presentation/settings/widgets/feature_flags/feature_flag_page.dart';
import 'package:flutter/material.dart';
class FeatureFlagScreen extends StatelessWidget {
const FeatureFlagScreen({
super.key,
});
static const routeName = '/feature_flag';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Feature Flags'),
),
body: const FeatureFlagsPage(),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/presentation/settings/widgets/feature_flags/feature_flag_page.dart | import 'package:appflowy/shared/feature_flags.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
class FeatureFlagsPage extends StatelessWidget {
const FeatureFlagsPage({
super.key,
});
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: SeparatedColumn(
children: [
...FeatureFlag.data.entries
.where((e) => e.key != FeatureFlag.unknown)
.map(
(e) => _FeatureFlagItem(featureFlag: e.key),
),
FlowyTextButton(
'Restart the app to apply changes',
fontSize: 16.0,
fontColor: Colors.red,
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 12.0,
),
onPressed: () async {
await runAppFlowy();
},
),
],
),
);
}
}
class _FeatureFlagItem extends StatefulWidget {
const _FeatureFlagItem({
required this.featureFlag,
});
final FeatureFlag featureFlag;
@override
State<_FeatureFlagItem> createState() => _FeatureFlagItemState();
}
class _FeatureFlagItemState extends State<_FeatureFlagItem> {
@override
Widget build(BuildContext context) {
return ListTile(
title: FlowyText(
widget.featureFlag.name,
fontSize: 16.0,
),
subtitle: FlowyText.small(
widget.featureFlag.description,
maxLines: 3,
),
trailing: Switch.adaptive(
value: widget.featureFlag.isOn,
onChanged: (value) {
setState(() {
widget.featureFlag.update(value);
});
},
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/env/cloud_env_test.dart | // lib/env/env.dart
// ignore_for_file: prefer_const_declarations
import 'package:envied/envied.dart';
part 'cloud_env_test.g.dart';
/// Follow the guide on https://supabase.com/docs/guides/auth/social-login/auth-google to setup the auth provider.
///
@Envied(path: '.env.cloud.test')
abstract class TestEnv {
/// AppFlowy Cloud Configuration
@EnviedField(
obfuscate: false,
varName: 'APPFLOWY_CLOUD_URL',
defaultValue: 'http://localhost',
)
static final String afCloudUrl = _TestEnv.afCloudUrl;
// Supabase Configuration:
@EnviedField(
obfuscate: false,
varName: 'SUPABASE_URL',
defaultValue: '',
)
static final String supabaseUrl = _TestEnv.supabaseUrl;
@EnviedField(
obfuscate: false,
varName: 'SUPABASE_ANON_KEY',
defaultValue: '',
)
static final String supabaseAnonKey = _TestEnv.supabaseAnonKey;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/env/env.dart | // lib/env/env.dart
import 'package:appflowy/env/cloud_env.dart';
import 'package:envied/envied.dart';
part 'env.g.dart';
@Envied(path: '.env')
abstract class Env {
// This flag is used to decide if users can dynamically configure cloud settings. It turns true when a .env file exists containing the APPFLOWY_CLOUD_URL variable. By default, this is set to false.
static bool get enableCustomCloud {
return Env.authenticatorType ==
AuthenticatorType.appflowyCloudSelfHost.value ||
Env.authenticatorType == AuthenticatorType.appflowyCloud.value ||
Env.authenticatorType == AuthenticatorType.appflowyCloudDevelop.value &&
_Env.afCloudUrl.isEmpty;
}
@EnviedField(
obfuscate: false,
varName: 'AUTHENTICATOR_TYPE',
defaultValue: 2,
)
static const int authenticatorType = _Env.authenticatorType;
/// AppFlowy Cloud Configuration
@EnviedField(
obfuscate: false,
varName: 'APPFLOWY_CLOUD_URL',
defaultValue: '',
)
static const String afCloudUrl = _Env.afCloudUrl;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/env/backend_env.dart | // ignore_for_file: non_constant_identifier_names
import 'package:json_annotation/json_annotation.dart';
part 'backend_env.g.dart';
@JsonSerializable()
class AppFlowyConfiguration {
AppFlowyConfiguration({
required this.root,
required this.app_version,
required this.custom_app_path,
required this.origin_app_path,
required this.device_id,
required this.platform,
required this.authenticator_type,
required this.supabase_config,
required this.appflowy_cloud_config,
required this.envs,
});
factory AppFlowyConfiguration.fromJson(Map<String, dynamic> json) =>
_$AppFlowyConfigurationFromJson(json);
final String root;
final String app_version;
final String custom_app_path;
final String origin_app_path;
final String device_id;
final String platform;
final int authenticator_type;
final SupabaseConfiguration supabase_config;
final AppFlowyCloudConfiguration appflowy_cloud_config;
final Map<String, String> envs;
Map<String, dynamic> toJson() => _$AppFlowyConfigurationToJson(this);
}
@JsonSerializable()
class SupabaseConfiguration {
SupabaseConfiguration({
required this.url,
required this.anon_key,
});
factory SupabaseConfiguration.fromJson(Map<String, dynamic> json) =>
_$SupabaseConfigurationFromJson(json);
/// Indicates whether the sync feature is enabled.
final String url;
final String anon_key;
Map<String, dynamic> toJson() => _$SupabaseConfigurationToJson(this);
static SupabaseConfiguration defaultConfig() {
return SupabaseConfiguration(
url: '',
anon_key: '',
);
}
bool get isValid {
return url.isNotEmpty && anon_key.isNotEmpty;
}
}
@JsonSerializable()
class AppFlowyCloudConfiguration {
AppFlowyCloudConfiguration({
required this.base_url,
required this.ws_base_url,
required this.gotrue_url,
});
factory AppFlowyCloudConfiguration.fromJson(Map<String, dynamic> json) =>
_$AppFlowyCloudConfigurationFromJson(json);
final String base_url;
final String ws_base_url;
final String gotrue_url;
Map<String, dynamic> toJson() => _$AppFlowyCloudConfigurationToJson(this);
static AppFlowyCloudConfiguration defaultConfig() {
return AppFlowyCloudConfiguration(
base_url: '',
ws_base_url: '',
gotrue_url: '',
);
}
bool get isValid {
return base_url.isNotEmpty &&
ws_base_url.isNotEmpty &&
gotrue_url.isNotEmpty;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/env/cloud_env.dart | import 'package:appflowy/core/config/kv.dart';
import 'package:appflowy/core/config/kv_keys.dart';
import 'package:appflowy/env/backend_env.dart';
import 'package:appflowy/env/env.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_backend/log.dart';
/// Sets the cloud type for the application.
///
/// This method updates the cloud type setting in the key-value storage
/// using the [KeyValueStorage] service. The cloud type is identified
/// by the [AuthenticatorType] enum.
///
/// [ty] - The type of cloud to be set. It must be one of the values from
/// [AuthenticatorType] enum. The corresponding integer value of the enum is stored:
/// - `CloudType.local` is stored as "0".
/// - `CloudType.supabase` is stored as "1".
/// - `CloudType.appflowyCloud` is stored as "2".
Future<void> _setAuthenticatorType(AuthenticatorType ty) async {
switch (ty) {
case AuthenticatorType.local:
await getIt<KeyValueStorage>().set(KVKeys.kCloudType, 0.toString());
break;
case AuthenticatorType.supabase:
await getIt<KeyValueStorage>().set(KVKeys.kCloudType, 1.toString());
break;
case AuthenticatorType.appflowyCloud:
await getIt<KeyValueStorage>().set(KVKeys.kCloudType, 2.toString());
break;
case AuthenticatorType.appflowyCloudSelfHost:
await getIt<KeyValueStorage>().set(KVKeys.kCloudType, 3.toString());
break;
case AuthenticatorType.appflowyCloudDevelop:
await getIt<KeyValueStorage>().set(KVKeys.kCloudType, 4.toString());
break;
}
}
const String kAppflowyCloudUrl = "https://beta.appflowy.cloud";
/// Retrieves the currently set cloud type.
///
/// This method fetches the cloud type setting from the key-value storage
/// using the [KeyValueStorage] service and returns the corresponding
/// [AuthenticatorType] enum value.
///
/// Returns:
/// A Future that resolves to a [AuthenticatorType] enum value representing the
/// currently set cloud type. The default return value is `CloudType.local`
/// if no valid setting is found.
///
Future<AuthenticatorType> getAuthenticatorType() async {
final value = await getIt<KeyValueStorage>().get(KVKeys.kCloudType);
if (value == null && !integrationMode().isUnitTest) {
// if the cloud type is not set, then set it to AppFlowy Cloud as default.
await useAppFlowyBetaCloudWithURL(
kAppflowyCloudUrl,
AuthenticatorType.appflowyCloud,
);
return AuthenticatorType.appflowyCloud;
}
switch (value ?? "0") {
case "0":
return AuthenticatorType.local;
case "1":
return AuthenticatorType.supabase;
case "2":
return AuthenticatorType.appflowyCloud;
case "3":
return AuthenticatorType.appflowyCloudSelfHost;
case "4":
return AuthenticatorType.appflowyCloudDevelop;
default:
await useAppFlowyBetaCloudWithURL(
kAppflowyCloudUrl,
AuthenticatorType.appflowyCloud,
);
return AuthenticatorType.appflowyCloud;
}
}
/// Determines whether authentication is enabled.
///
/// This getter evaluates if authentication should be enabled based on the
/// current integration mode and cloud type settings.
///
/// Returns:
/// A boolean value indicating whether authentication is enabled. It returns
/// `true` if the application is in release or develop mode, and the cloud type
/// is not set to `CloudType.local`. Additionally, it checks if either the
/// AppFlowy Cloud or Supabase configuration is valid.
/// Returns `false` otherwise.
bool get isAuthEnabled {
final env = getIt<AppFlowyCloudSharedEnv>();
if (env.authenticatorType == AuthenticatorType.supabase) {
return env.supabaseConfig.isValid;
}
if (env.authenticatorType.isAppFlowyCloudEnabled) {
return env.appflowyCloudConfig.isValid;
}
return false;
}
/// Checks if Supabase is enabled.
///
/// This getter evaluates if Supabase should be enabled based on the
/// current integration mode and cloud type setting.
///
/// Returns:
/// A boolean value indicating whether Supabase is enabled. It returns `true`
/// if the application is in release or develop mode and the current cloud type
/// is `CloudType.supabase`. Otherwise, it returns `false`.
bool get isSupabaseEnabled {
return currentCloudType().isSupabaseEnabled;
}
/// Determines if AppFlowy Cloud is enabled.
bool get isAppFlowyCloudEnabled {
return currentCloudType().isAppFlowyCloudEnabled;
}
enum AuthenticatorType {
local,
supabase,
appflowyCloud,
appflowyCloudSelfHost,
// The 'appflowyCloudDevelop' type is used for develop purposes only.
appflowyCloudDevelop;
bool get isLocal => this == AuthenticatorType.local;
bool get isAppFlowyCloudEnabled =>
this == AuthenticatorType.appflowyCloudSelfHost ||
this == AuthenticatorType.appflowyCloudDevelop ||
this == AuthenticatorType.appflowyCloud;
bool get isSupabaseEnabled => this == AuthenticatorType.supabase;
int get value {
switch (this) {
case AuthenticatorType.local:
return 0;
case AuthenticatorType.supabase:
return 1;
case AuthenticatorType.appflowyCloud:
return 2;
case AuthenticatorType.appflowyCloudSelfHost:
return 3;
case AuthenticatorType.appflowyCloudDevelop:
return 4;
}
}
static AuthenticatorType fromValue(int value) {
switch (value) {
case 0:
return AuthenticatorType.local;
case 1:
return AuthenticatorType.supabase;
case 2:
return AuthenticatorType.appflowyCloud;
case 3:
return AuthenticatorType.appflowyCloudSelfHost;
case 4:
return AuthenticatorType.appflowyCloudDevelop;
default:
return AuthenticatorType.local;
}
}
}
AuthenticatorType currentCloudType() {
return getIt<AppFlowyCloudSharedEnv>().authenticatorType;
}
Future<void> _setAppFlowyCloudUrl(String? url) async {
await getIt<KeyValueStorage>().set(KVKeys.kAppflowyCloudBaseURL, url ?? '');
}
Future<void> useSelfHostedAppFlowyCloudWithURL(String url) async {
await _setAuthenticatorType(AuthenticatorType.appflowyCloudSelfHost);
await _setAppFlowyCloudUrl(url);
}
Future<void> useAppFlowyBetaCloudWithURL(
String url,
AuthenticatorType authenticatorType,
) async {
await _setAuthenticatorType(authenticatorType);
await _setAppFlowyCloudUrl(url);
}
Future<void> useLocalServer() async {
await _setAuthenticatorType(AuthenticatorType.local);
}
Future<void> useSupabaseCloud({
required String url,
required String anonKey,
}) async {
await _setAuthenticatorType(AuthenticatorType.supabase);
await setSupabaseServer(url, anonKey);
}
/// Use getIt<AppFlowyCloudSharedEnv>() to get the shared environment.
class AppFlowyCloudSharedEnv {
AppFlowyCloudSharedEnv({
required AuthenticatorType authenticatorType,
required this.appflowyCloudConfig,
required this.supabaseConfig,
}) : _authenticatorType = authenticatorType;
final AuthenticatorType _authenticatorType;
final AppFlowyCloudConfiguration appflowyCloudConfig;
final SupabaseConfiguration supabaseConfig;
AuthenticatorType get authenticatorType => _authenticatorType;
static Future<AppFlowyCloudSharedEnv> fromEnv() async {
// If [Env.enableCustomCloud] is true, then use the custom cloud configuration.
if (Env.enableCustomCloud) {
// Use the custom cloud configuration.
var authenticatorType = await getAuthenticatorType();
final appflowyCloudConfig = authenticatorType.isAppFlowyCloudEnabled
? await getAppFlowyCloudConfig(authenticatorType)
: AppFlowyCloudConfiguration.defaultConfig();
final supabaseCloudConfig = authenticatorType.isSupabaseEnabled
? await getSupabaseCloudConfig()
: SupabaseConfiguration.defaultConfig();
// In the backend, the value '2' represents the use of AppFlowy Cloud. However, in the frontend,
// we distinguish between [AuthenticatorType.appflowyCloudSelfHost] and [AuthenticatorType.appflowyCloud].
// When the cloud type is [AuthenticatorType.appflowyCloudSelfHost] in the frontend, it should be
// converted to [AuthenticatorType.appflowyCloud] to align with the backend representation,
// where both types are indicated by the value '2'.
if (authenticatorType.isAppFlowyCloudEnabled) {
authenticatorType = AuthenticatorType.appflowyCloud;
}
return AppFlowyCloudSharedEnv(
authenticatorType: authenticatorType,
appflowyCloudConfig: appflowyCloudConfig,
supabaseConfig: supabaseCloudConfig,
);
} else {
// Using the cloud settings from the .env file.
final appflowyCloudConfig = AppFlowyCloudConfiguration(
base_url: Env.afCloudUrl,
ws_base_url: await _getAppFlowyCloudWSUrl(Env.afCloudUrl),
gotrue_url: await _getAppFlowyCloudGotrueUrl(Env.afCloudUrl),
);
return AppFlowyCloudSharedEnv(
authenticatorType: AuthenticatorType.fromValue(Env.authenticatorType),
appflowyCloudConfig: appflowyCloudConfig,
supabaseConfig: SupabaseConfiguration.defaultConfig(),
);
}
}
@override
String toString() {
return 'authenticator: $_authenticatorType\n'
'appflowy: ${appflowyCloudConfig.toJson()}\n'
'supabase: ${supabaseConfig.toJson()})\n';
}
}
Future<AppFlowyCloudConfiguration> configurationFromUri(
Uri baseUri,
String baseUrl,
AuthenticatorType authenticatorType,
) async {
// In development mode, the app is configured to access the AppFlowy cloud server directly through specific ports.
// This setup bypasses the need for Nginx, meaning that the AppFlowy cloud should be running without an Nginx server
// in the development environment.
if (authenticatorType == AuthenticatorType.appflowyCloudDevelop) {
return AppFlowyCloudConfiguration(
base_url: "$baseUrl:8000",
ws_base_url: "ws://${baseUri.host}:8000/ws/v1",
gotrue_url: "$baseUrl:9999",
);
} else {
return AppFlowyCloudConfiguration(
base_url: baseUrl,
ws_base_url: await _getAppFlowyCloudWSUrl(baseUrl),
gotrue_url: await _getAppFlowyCloudGotrueUrl(baseUrl),
);
}
}
Future<AppFlowyCloudConfiguration> getAppFlowyCloudConfig(
AuthenticatorType authenticatorType,
) async {
final baseURL = await getAppFlowyCloudUrl();
try {
final uri = Uri.parse(baseURL);
return await configurationFromUri(uri, baseURL, authenticatorType);
} catch (e) {
Log.error("Failed to parse AppFlowy Cloud URL: $e");
return AppFlowyCloudConfiguration.defaultConfig();
}
}
Future<String> getAppFlowyCloudUrl() async {
final result =
await getIt<KeyValueStorage>().get(KVKeys.kAppflowyCloudBaseURL);
return result ?? kAppflowyCloudUrl;
}
Future<String> _getAppFlowyCloudWSUrl(String baseURL) async {
try {
final uri = Uri.parse(baseURL);
// Construct the WebSocket URL directly from the parsed URI.
final wsScheme = uri.isScheme('HTTPS') ? 'wss' : 'ws';
final wsUrl = Uri(scheme: wsScheme, host: uri.host, path: '/ws/v1');
return wsUrl.toString();
} catch (e) {
Log.error("Failed to get WebSocket URL: $e");
return "";
}
}
Future<String> _getAppFlowyCloudGotrueUrl(String baseURL) async {
return "$baseURL/gotrue";
}
Future<void> setSupabaseServer(
String? url,
String? anonKey,
) async {
assert(
(url != null && anonKey != null) || (url == null && anonKey == null),
"Either both Supabase URL and anon key must be set, or both should be unset",
);
if (url == null) {
await getIt<KeyValueStorage>().remove(KVKeys.kSupabaseURL);
} else {
await getIt<KeyValueStorage>().set(KVKeys.kSupabaseURL, url);
}
if (anonKey == null) {
await getIt<KeyValueStorage>().remove(KVKeys.kSupabaseAnonKey);
} else {
await getIt<KeyValueStorage>().set(KVKeys.kSupabaseAnonKey, anonKey);
}
}
Future<SupabaseConfiguration> getSupabaseCloudConfig() async {
final url = await _getSupabaseUrl();
final anonKey = await _getSupabaseAnonKey();
return SupabaseConfiguration(
url: url,
anon_key: anonKey,
);
}
Future<String> _getSupabaseUrl() async {
final result = await getIt<KeyValueStorage>().get(KVKeys.kSupabaseURL);
return result ?? '';
}
Future<String> _getSupabaseAnonKey() async {
final result = await getIt<KeyValueStorage>().get(KVKeys.kSupabaseAnonKey);
return result ?? '';
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/network_monitor.dart | import 'dart:async';
import 'package:appflowy_backend/protobuf/flowy-user/user_setting.pb.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:flutter/services.dart';
class NetworkListener {
NetworkListener() {
_connectivitySubscription =
_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
}
final Connectivity _connectivity = Connectivity();
late StreamSubscription<ConnectivityResult> _connectivitySubscription;
Future<void> start() async {
late ConnectivityResult result;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await _connectivity.checkConnectivity();
} on PlatformException catch (e) {
Log.error("Couldn't check connectivity status. $e");
return;
}
return _updateConnectionStatus(result);
}
Future<void> stop() async {
await _connectivitySubscription.cancel();
}
Future<void> _updateConnectionStatus(ConnectivityResult result) async {
final networkType = () {
switch (result) {
case ConnectivityResult.wifi:
return NetworkTypePB.Wifi;
case ConnectivityResult.ethernet:
return NetworkTypePB.Ethernet;
case ConnectivityResult.mobile:
return NetworkTypePB.Cell;
case ConnectivityResult.bluetooth:
return NetworkTypePB.Bluetooth;
case ConnectivityResult.vpn:
return NetworkTypePB.VPN;
case ConnectivityResult.none:
case ConnectivityResult.other:
return NetworkTypePB.NetworkUnknown;
}
}();
final state = NetworkStatePB.create()..ty = networkType;
return UserEventUpdateNetworkState(state).send().then((result) {
result.fold((l) {}, (e) => Log.error(e));
});
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/frameless_window.dart | import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'dart:io' show Platform;
class CocoaWindowChannel {
CocoaWindowChannel._();
final MethodChannel _channel = const MethodChannel("flutter/cocoaWindow");
static final CocoaWindowChannel instance = CocoaWindowChannel._();
Future<void> setWindowPosition(Offset offset) async {
await _channel.invokeMethod("setWindowPosition", [offset.dx, offset.dy]);
}
Future<List<double>> getWindowPosition() async {
final raw = await _channel.invokeMethod("getWindowPosition");
final arr = raw as List<dynamic>;
final List<double> result = arr.map((s) => s as double).toList();
return result;
}
Future<void> zoom() async {
await _channel.invokeMethod("zoom");
}
}
class MoveWindowDetector extends StatefulWidget {
const MoveWindowDetector({super.key, this.child});
final Widget? child;
@override
MoveWindowDetectorState createState() => MoveWindowDetectorState();
}
class MoveWindowDetectorState extends State<MoveWindowDetector> {
double winX = 0;
double winY = 0;
@override
Widget build(BuildContext context) {
if (!Platform.isMacOS) {
return widget.child ?? const SizedBox.shrink();
}
return GestureDetector(
// https://stackoverflow.com/questions/52965799/flutter-gesturedetector-not-working-with-containers-in-stack
behavior: HitTestBehavior.translucent,
onDoubleTap: () async {
await CocoaWindowChannel.instance.zoom();
},
onPanStart: (DragStartDetails details) {
winX = details.globalPosition.dx;
winY = details.globalPosition.dy;
},
onPanUpdate: (DragUpdateDetails details) async {
final windowPos = await CocoaWindowChannel.instance.getWindowPosition();
final double dx = windowPos[0];
final double dy = windowPos[1];
final deltaX = details.globalPosition.dx - winX;
final deltaY = details.globalPosition.dy - winY;
await CocoaWindowChannel.instance
.setWindowPosition(Offset(dx + deltaX, dy - deltaY));
},
child: widget.child,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/notification/search_notification.dart | import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-search/entities.pbenum.dart';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'notification_helper.dart';
// This value must be identical to the value in the backend (SEARCH_OBSERVABLE_SOURCE)
const _source = 'Search';
typedef SearchNotificationCallback = void Function(
SearchNotification,
FlowyResult<Uint8List, FlowyError>,
);
class SearchNotificationParser
extends NotificationParser<SearchNotification, FlowyError> {
SearchNotificationParser({
super.id,
required super.callback,
}) : super(
tyParser: (ty, source) =>
source == _source ? SearchNotification.valueOf(ty) : null,
errorParser: (bytes) => FlowyError.fromBuffer(bytes),
);
}
typedef SearchNotificationHandler = Function(
SearchNotification ty,
FlowyResult<Uint8List, FlowyError> result,
);
class SearchNotificationListener {
SearchNotificationListener({
required String objectId,
required SearchNotificationHandler handler,
}) : _parser = SearchNotificationParser(id: objectId, callback: handler) {
_subscription =
RustStreamReceiver.listen((observable) => _parser?.parse(observable));
}
StreamSubscription<SubscribeObject>? _subscription;
SearchNotificationParser? _parser;
Future<void> stop() async {
_parser = null;
await _subscription?.cancel();
_subscription = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/notification/user_notification.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'notification_helper.dart';
// This value should be the same as the USER_OBSERVABLE_SOURCE value
const String _source = 'User';
// User
typedef UserNotificationCallback = void Function(
UserNotification,
FlowyResult<Uint8List, FlowyError>,
);
class UserNotificationParser
extends NotificationParser<UserNotification, FlowyError> {
UserNotificationParser({
required String super.id,
required super.callback,
}) : super(
tyParser: (ty, source) =>
source == _source ? UserNotification.valueOf(ty) : null,
errorParser: (bytes) => FlowyError.fromBuffer(bytes),
);
}
typedef UserNotificationHandler = Function(
UserNotification ty,
FlowyResult<Uint8List, FlowyError> result,
);
class UserNotificationListener {
UserNotificationListener({
required String objectId,
required UserNotificationHandler handler,
}) : _parser = UserNotificationParser(id: objectId, callback: handler) {
_subscription =
RustStreamReceiver.listen((observable) => _parser?.parse(observable));
}
UserNotificationParser? _parser;
StreamSubscription<SubscribeObject>? _subscription;
Future<void> stop() async {
_parser = null;
await _subscription?.cancel();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/notification/folder_notification.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'notification_helper.dart';
// This value should be the same as the FOLDER_OBSERVABLE_SOURCE value
const String _source = 'Workspace';
// Folder
typedef FolderNotificationCallback = void Function(
FolderNotification,
FlowyResult<Uint8List, FlowyError>,
);
class FolderNotificationParser
extends NotificationParser<FolderNotification, FlowyError> {
FolderNotificationParser({
super.id,
required super.callback,
}) : super(
tyParser: (ty, source) =>
source == _source ? FolderNotification.valueOf(ty) : null,
errorParser: (bytes) => FlowyError.fromBuffer(bytes),
);
}
typedef FolderNotificationHandler = Function(
FolderNotification ty,
FlowyResult<Uint8List, FlowyError> result,
);
class FolderNotificationListener {
FolderNotificationListener({
required String objectId,
required FolderNotificationHandler handler,
}) : _parser = FolderNotificationParser(
id: objectId,
callback: handler,
) {
_subscription =
RustStreamReceiver.listen((observable) => _parser?.parse(observable));
}
FolderNotificationParser? _parser;
StreamSubscription<SubscribeObject>? _subscription;
Future<void> stop() async {
_parser = null;
await _subscription?.cancel();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/notification/document_notification.dart | import 'dart:typed_data';
import 'package:appflowy/core/notification/notification_helper.dart';
import 'package:appflowy_backend/protobuf/flowy-document/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
// This value should be the same as the DOCUMENT_OBSERVABLE_SOURCE value
const String _source = 'Document';
typedef DocumentNotificationCallback = void Function(
DocumentNotification,
FlowyResult<Uint8List, FlowyError>,
);
class DocumentNotificationParser
extends NotificationParser<DocumentNotification, FlowyError> {
DocumentNotificationParser({
super.id,
required super.callback,
}) : super(
tyParser: (ty, source) =>
source == _source ? DocumentNotification.valueOf(ty) : null,
errorParser: (bytes) => FlowyError.fromBuffer(bytes),
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/notification/notification_helper.dart | import 'dart:typed_data';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
class NotificationParser<T, E extends Object> {
NotificationParser({
this.id,
required this.callback,
required this.errorParser,
required this.tyParser,
});
String? id;
void Function(T, FlowyResult<Uint8List, E>) callback;
E Function(Uint8List) errorParser;
T? Function(int, String) tyParser;
void parse(SubscribeObject subject) {
if (id != null) {
if (subject.id != id) {
return;
}
}
final ty = tyParser(subject.ty, subject.source);
if (ty == null) {
return;
}
if (subject.hasError()) {
final bytes = Uint8List.fromList(subject.error);
final error = errorParser(bytes);
callback(ty, FlowyResult.failure(error));
} else {
final bytes = Uint8List.fromList(subject.payload);
callback(ty, FlowyResult.success(bytes));
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/notification/grid_notification.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'notification_helper.dart';
// This value should be the same as the DATABASE_OBSERVABLE_SOURCE value
const String _source = 'Database';
// DatabasePB
typedef DatabaseNotificationCallback = void Function(
DatabaseNotification,
FlowyResult<Uint8List, FlowyError>,
);
class DatabaseNotificationParser
extends NotificationParser<DatabaseNotification, FlowyError> {
DatabaseNotificationParser({
super.id,
required super.callback,
}) : super(
tyParser: (ty, source) =>
source == _source ? DatabaseNotification.valueOf(ty) : null,
errorParser: (bytes) => FlowyError.fromBuffer(bytes),
);
}
typedef DatabaseNotificationHandler = Function(
DatabaseNotification ty,
FlowyResult<Uint8List, FlowyError> result,
);
class DatabaseNotificationListener {
DatabaseNotificationListener({
required String objectId,
required DatabaseNotificationHandler handler,
}) : _parser = DatabaseNotificationParser(id: objectId, callback: handler) {
_subscription =
RustStreamReceiver.listen((observable) => _parser?.parse(observable));
}
DatabaseNotificationParser? _parser;
StreamSubscription<SubscribeObject>? _subscription;
Future<void> stop() async {
_parser = null;
await _subscription?.cancel();
_subscription = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/config/kv_keys.dart | class KVKeys {
const KVKeys._();
static const String prefix = 'io.appflowy.appflowy_flutter';
/// The key for the path location of the local data for the whole app.
static const String pathLocation = '$prefix.path_location';
/// The key for saving the window size
///
/// The value is a json string with the following format:
/// {'height': 600.0, 'width': 800.0}
static const String windowSize = 'windowSize';
/// The key for saving the window position
///
/// The value is a json string with the following format:
/// {'dx': 10.0, 'dy': 10.0}
static const String windowPosition = 'windowPosition';
static const String kDocumentAppearanceFontSize =
'kDocumentAppearanceFontSize';
static const String kDocumentAppearanceFontFamily =
'kDocumentAppearanceFontFamily';
static const String kDocumentAppearanceDefaultTextDirection =
'kDocumentAppearanceDefaultTextDirection';
static const String kDocumentAppearanceCursorColor =
'kDocumentAppearanceCursorColor';
static const String kDocumentAppearanceSelectionColor =
'kDocumentAppearanceSelectionColor';
/// The key for saving the expanded views
///
/// The value is a json string with the following format:
/// {'viewId': true, 'viewId2': false}
static const String expandedViews = 'expandedViews';
/// The key for saving the expanded folder
///
/// The value is a json string with the following format:
/// {'SidebarFolderCategoryType.value': true}
static const String expandedFolders = 'expandedFolders';
/// The key for saving if showing the rename dialog when creating a new file
///
/// The value is a boolean string.
static const String showRenameDialogWhenCreatingNewFile =
'showRenameDialogWhenCreatingNewFile';
static const String kCloudType = 'kCloudType';
static const String kAppflowyCloudBaseURL = 'kAppFlowyCloudBaseURL';
static const String kSupabaseURL = 'kSupabaseURL';
static const String kSupabaseAnonKey = 'kSupabaseAnonKey';
/// The key for saving the text scale factor.
///
/// The value is a double string.
/// The value range is from 0.8 to 1.0. If it's greater than 1.0, it will cause
/// the text to be too large and not aligned with the icon
static const String textScaleFactor = 'textScaleFactor';
/// The key for saving the feature flags
///
/// The value is a json string with the following format:
/// {'feature_flag_1': true, 'feature_flag_2': false}
static const String featureFlag = 'featureFlag';
/// The key for saving the last opened workspace id
///
/// The workspace id is a string.
static const String lastOpenedWorkspaceId = 'lastOpenedWorkspaceId';
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/config/kv.dart | import 'package:shared_preferences/shared_preferences.dart';
abstract class KeyValueStorage {
Future<void> set(String key, String value);
Future<String?> get(String key);
Future<T?> getWithFormat<T>(
String key,
T Function(String value) formatter,
);
Future<void> remove(String key);
Future<void> clear();
}
class DartKeyValue implements KeyValueStorage {
SharedPreferences? _sharedPreferences;
SharedPreferences get sharedPreferences => _sharedPreferences!;
@override
Future<String?> get(String key) async {
await _initSharedPreferencesIfNeeded();
final value = sharedPreferences.getString(key);
if (value != null) {
return value;
}
return null;
}
@override
Future<T?> getWithFormat<T>(
String key,
T Function(String value) formatter,
) async {
final value = await get(key);
if (value == null) {
return null;
}
return formatter(value);
}
@override
Future<void> remove(String key) async {
await _initSharedPreferencesIfNeeded();
await sharedPreferences.remove(key);
}
@override
Future<void> set(String key, String value) async {
await _initSharedPreferencesIfNeeded();
await sharedPreferences.setString(key, value);
}
@override
Future<void> clear() async {
await _initSharedPreferencesIfNeeded();
await sharedPreferences.clear();
}
Future<void> _initSharedPreferencesIfNeeded() async {
_sharedPreferences ??= await SharedPreferences.getInstance();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/helpers/helpers.dart | export 'target_platform.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/helpers/url_launcher.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/presentation/home/toast.dart';
import 'package:appflowy_backend/log.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:string_validator/string_validator.dart';
import 'package:url_launcher/url_launcher.dart' as launcher;
typedef OnFailureCallback = void Function(Uri uri);
Future<bool> afLaunchUrl(
Uri uri, {
BuildContext? context,
OnFailureCallback? onFailure,
launcher.LaunchMode mode = launcher.LaunchMode.platformDefault,
String? webOnlyWindowName,
bool addingHttpSchemeWhenFailed = false,
}) async {
// try to launch the uri directly
bool result;
try {
result = await launcher.launchUrl(
uri,
mode: mode,
webOnlyWindowName: webOnlyWindowName,
);
} on PlatformException catch (e) {
Log.error('Failed to open uri: $e');
return false;
}
// if the uri is not a valid url, try to launch it with http scheme
final url = uri.toString();
if (addingHttpSchemeWhenFailed &&
!result &&
!isURL(url, {'require_protocol': true})) {
try {
final uriWithScheme = Uri.parse('http://$url');
result = await launcher.launchUrl(
uriWithScheme,
mode: mode,
webOnlyWindowName: webOnlyWindowName,
);
} on PlatformException catch (e) {
Log.error('Failed to open uri: $e');
if (context != null && context.mounted) {
_errorHandler(uri, context: context, onFailure: onFailure, e: e);
}
}
}
return result;
}
Future<bool> afLaunchUrlString(
String url, {
bool addingHttpSchemeWhenFailed = false,
}) async {
final Uri uri;
try {
uri = Uri.parse(url);
} on FormatException catch (e) {
Log.error('Failed to parse url: $e');
return false;
}
// try to launch the uri directly
return afLaunchUrl(
uri,
addingHttpSchemeWhenFailed: addingHttpSchemeWhenFailed,
);
}
void _errorHandler(
Uri uri, {
BuildContext? context,
OnFailureCallback? onFailure,
PlatformException? e,
}) {
Log.error('Failed to open uri: $e');
if (onFailure != null) {
onFailure(uri);
} else {
showMessageToast(
LocaleKeys.failedToOpenUrl.tr(args: [e?.message ?? "PlatformException"]),
context: context,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/core/helpers/target_platform.dart | import 'package:flutter/foundation.dart' show TargetPlatform, kIsWeb;
extension TargetPlatformHelper on TargetPlatform {
/// Convenience function to check if the app is running on a desktop computer.
///
/// Easily check if on desktop by checking `defaultTargetPlatform.isDesktop`.
bool get isDesktop =>
!kIsWeb &&
(this == TargetPlatform.linux ||
this == TargetPlatform.macOS ||
this == TargetPlatform.windows);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/user_auth_listener.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy/core/notification/user_notification.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-user/auth.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/notification.pb.dart'
as user;
import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
class UserAuthStateListener {
void Function(String)? _onInvalidAuth;
void Function()? _didSignIn;
StreamSubscription<SubscribeObject>? _subscription;
UserNotificationParser? _userParser;
void start({
void Function(String)? onInvalidAuth,
void Function()? didSignIn,
}) {
_onInvalidAuth = onInvalidAuth;
_didSignIn = didSignIn;
_userParser = UserNotificationParser(
id: "auth_state_change_notification",
callback: _userNotificationCallback,
);
_subscription = RustStreamReceiver.listen((observable) {
_userParser?.parse(observable);
});
}
Future<void> stop() async {
_userParser = null;
await _subscription?.cancel();
_onInvalidAuth = null;
}
void _userNotificationCallback(
user.UserNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case user.UserNotification.UserAuthStateChanged:
result.fold(
(payload) {
final pb = AuthStateChangedPB.fromBuffer(payload);
switch (pb.state) {
case AuthStatePB.AuthStateSignIn:
_didSignIn?.call();
break;
case AuthStatePB.InvalidAuth:
_onInvalidAuth?.call(pb.message);
break;
default:
break;
}
},
(r) => Log.error(r),
);
break;
default:
break;
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/sign_in_bloc.dart | import 'package:appflowy/env/cloud_env.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/startup/tasks/appflowy_cloud_task.dart';
import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy_backend/protobuf/flowy-error/code.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'
show UserProfilePB;
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'sign_in_bloc.freezed.dart';
class SignInBloc extends Bloc<SignInEvent, SignInState> {
SignInBloc(this.authService) : super(SignInState.initial()) {
if (isAppFlowyCloudEnabled) {
deepLinkStateListener =
getIt<AppFlowyCloudDeepLink>().subscribeDeepLinkLoadingState((value) {
if (isClosed) return;
add(SignInEvent.deepLinkStateChange(value));
});
}
on<SignInEvent>(
(event, emit) async {
await event.when(
signedInWithUserEmailAndPassword: () async => _onSignIn(emit),
signedInWithOAuth: (platform) async => _onSignInWithOAuth(
emit,
platform,
),
signedInAsGuest: () async => _onSignInAsGuest(emit),
signedWithMagicLink: (email) async => _onSignInWithMagicLink(
emit,
email,
),
deepLinkStateChange: (result) => _onDeepLinkStateChange(
emit,
result,
),
cancel: () {
emit(
state.copyWith(
isSubmitting: false,
emailError: null,
passwordError: null,
successOrFail: null,
),
);
},
emailChanged: (email) async {
emit(
state.copyWith(
email: email,
emailError: null,
successOrFail: null,
),
);
},
passwordChanged: (password) async {
emit(
state.copyWith(
password: password,
passwordError: null,
successOrFail: null,
),
);
},
);
},
);
}
final AuthService authService;
VoidCallback? deepLinkStateListener;
@override
Future<void> close() {
deepLinkStateListener?.call();
if (isAppFlowyCloudEnabled && deepLinkStateListener != null) {
getIt<AppFlowyCloudDeepLink>().unsubscribeDeepLinkLoadingState(
deepLinkStateListener!,
);
}
return super.close();
}
Future<void> _onDeepLinkStateChange(
Emitter<SignInState> emit,
DeepLinkResult result,
) async {
final deepLinkState = result.state;
switch (deepLinkState) {
case DeepLinkState.none:
break;
case DeepLinkState.loading:
emit(
state.copyWith(
isSubmitting: true,
emailError: null,
passwordError: null,
successOrFail: null,
),
);
case DeepLinkState.finish:
final newState = result.result?.fold(
(s) => state.copyWith(
isSubmitting: false,
successOrFail: FlowyResult.success(s),
),
(f) => _stateFromCode(f),
);
if (newState != null) {
emit(newState);
}
}
}
Future<void> _onSignIn(
Emitter<SignInState> emit,
) async {
final result = await authService.signInWithEmailPassword(
email: state.email ?? '',
password: state.password ?? '',
);
emit(
result.fold(
(userProfile) => state.copyWith(
isSubmitting: false,
successOrFail: FlowyResult.success(userProfile),
),
(error) => _stateFromCode(error),
),
);
}
Future<void> _onSignInWithOAuth(
Emitter<SignInState> emit,
String platform,
) async {
emit(
state.copyWith(
isSubmitting: true,
emailError: null,
passwordError: null,
successOrFail: null,
),
);
final result = await authService.signUpWithOAuth(
platform: platform,
);
emit(
result.fold(
(userProfile) => state.copyWith(
isSubmitting: false,
successOrFail: FlowyResult.success(userProfile),
),
(error) => _stateFromCode(error),
),
);
}
Future<void> _onSignInWithMagicLink(
Emitter<SignInState> emit,
String email,
) async {
emit(
state.copyWith(
isSubmitting: true,
emailError: null,
passwordError: null,
successOrFail: null,
),
);
final result = await authService.signInWithMagicLink(
email: email,
);
emit(
result.fold(
(userProfile) => state.copyWith(
isSubmitting: true,
),
(error) => _stateFromCode(error),
),
);
}
Future<void> _onSignInAsGuest(
Emitter<SignInState> emit,
) async {
emit(
state.copyWith(
isSubmitting: true,
emailError: null,
passwordError: null,
successOrFail: null,
),
);
final result = await authService.signUpAsGuest();
emit(
result.fold(
(userProfile) => state.copyWith(
isSubmitting: false,
successOrFail: FlowyResult.success(userProfile),
),
(error) => _stateFromCode(error),
),
);
}
SignInState _stateFromCode(FlowyError error) {
switch (error.code) {
case ErrorCode.EmailFormatInvalid:
return state.copyWith(
isSubmitting: false,
emailError: error.msg,
passwordError: null,
);
case ErrorCode.PasswordFormatInvalid:
return state.copyWith(
isSubmitting: false,
passwordError: error.msg,
emailError: null,
);
default:
return state.copyWith(
isSubmitting: false,
successOrFail: FlowyResult.failure(error),
);
}
}
}
@freezed
class SignInEvent with _$SignInEvent {
const factory SignInEvent.signedInWithUserEmailAndPassword() =
SignedInWithUserEmailAndPassword;
const factory SignInEvent.signedInWithOAuth(String platform) =
SignedInWithOAuth;
const factory SignInEvent.signedInAsGuest() = SignedInAsGuest;
const factory SignInEvent.signedWithMagicLink(String email) =
SignedWithMagicLink;
const factory SignInEvent.emailChanged(String email) = EmailChanged;
const factory SignInEvent.passwordChanged(String password) = PasswordChanged;
const factory SignInEvent.deepLinkStateChange(DeepLinkResult result) =
DeepLinkStateChange;
const factory SignInEvent.cancel() = _Cancel;
}
@freezed
class SignInState with _$SignInState {
const factory SignInState({
String? email,
String? password,
required bool isSubmitting,
required String? passwordError,
required String? emailError,
required FlowyResult<UserProfilePB, FlowyError>? successOrFail,
}) = _SignInState;
factory SignInState.initial() => const SignInState(
isSubmitting: false,
passwordError: null,
emailError: null,
successOrFail: null,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/prelude.dart | export 'auth/backend_auth_service.dart';
export './sign_in_bloc.dart';
export './sign_up_bloc.dart';
export './splash_bloc.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/anon_user_bloc.dart | import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/code.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'anon_user_bloc.freezed.dart';
class AnonUserBloc extends Bloc<AnonUserEvent, AnonUserState> {
AnonUserBloc() : super(AnonUserState.initial()) {
on<AnonUserEvent>((event, emit) async {
await event.when(
initial: () async {
await _loadHistoricalUsers();
},
didLoadAnonUsers: (List<UserProfilePB> anonUsers) {
emit(state.copyWith(anonUsers: anonUsers));
},
openAnonUser: (anonUser) async {
await UserBackendService.openAnonUser();
emit(state.copyWith(openedAnonUser: anonUser));
},
);
});
}
Future<void> _loadHistoricalUsers() async {
final result = await UserBackendService.getAnonUser();
result.fold(
(anonUser) {
add(AnonUserEvent.didLoadAnonUsers([anonUser]));
},
(error) {
if (error.code != ErrorCode.RecordNotFound) {
Log.error(error);
}
},
);
}
}
@freezed
class AnonUserEvent with _$AnonUserEvent {
const factory AnonUserEvent.initial() = _Initial;
const factory AnonUserEvent.didLoadAnonUsers(
List<UserProfilePB> historicalUsers,
) = _DidLoadHistoricalUsers;
const factory AnonUserEvent.openAnonUser(UserProfilePB anonUser) =
_OpenHistoricalUser;
}
@freezed
class AnonUserState with _$AnonUserState {
const factory AnonUserState({
required List<UserProfilePB> anonUsers,
required UserProfilePB? openedAnonUser,
}) = _AnonUserState;
factory AnonUserState.initial() => const AnonUserState(
anonUsers: [],
openedAnonUser: null,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/user_settings_service.dart | import 'package:appflowy_backend/appflowy_backend.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_setting.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
class UserSettingsBackendService {
Future<AppearanceSettingsPB> getAppearanceSetting() async {
final result = await UserEventGetAppearanceSetting().send();
return result.fold(
(AppearanceSettingsPB setting) => setting,
(error) =>
throw FlowySDKException(ExceptionType.AppearanceSettingsIsEmpty),
);
}
Future<FlowyResult<UserSettingPB, FlowyError>> getUserSetting() {
return UserEventGetUserSetting().send();
}
Future<FlowyResult<void, FlowyError>> setAppearanceSetting(
AppearanceSettingsPB setting,
) {
return UserEventSetAppearanceSetting(setting).send();
}
Future<DateTimeSettingsPB> getDateTimeSettings() async {
final result = await UserEventGetDateTimeSettings().send();
return result.fold(
(DateTimeSettingsPB setting) => setting,
(error) =>
throw FlowySDKException(ExceptionType.AppearanceSettingsIsEmpty),
);
}
Future<FlowyResult<void, FlowyError>> setDateTimeSettings(
DateTimeSettingsPB settings,
) async {
return UserEventSetDateTimeSettings(settings).send();
}
Future<FlowyResult<void, FlowyError>> setNotificationSettings(
NotificationSettingsPB settings,
) async {
return UserEventSetNotificationSettings(settings).send();
}
Future<NotificationSettingsPB> getNotificationSettings() async {
final result = await UserEventGetNotificationSettings().send();
return result.fold(
(NotificationSettingsPB setting) => setting,
(error) =>
throw FlowySDKException(ExceptionType.AppearanceSettingsIsEmpty),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/user_service.dart | import 'dart:async';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/workspace.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:fixnum/fixnum.dart';
class UserBackendService {
UserBackendService({
required this.userId,
});
final Int64 userId;
static Future<FlowyResult<UserProfilePB, FlowyError>>
getCurrentUserProfile() async {
final result = await UserEventGetUserProfile().send();
return result;
}
Future<FlowyResult<void, FlowyError>> updateUserProfile({
String? name,
String? password,
String? email,
String? iconUrl,
String? openAIKey,
String? stabilityAiKey,
}) {
final payload = UpdateUserProfilePayloadPB.create()..id = userId;
if (name != null) {
payload.name = name;
}
if (password != null) {
payload.password = password;
}
if (email != null) {
payload.email = email;
}
if (iconUrl != null) {
payload.iconUrl = iconUrl;
}
if (openAIKey != null) {
payload.openaiKey = openAIKey;
}
if (stabilityAiKey != null) {
payload.stabilityAiKey = stabilityAiKey;
}
return UserEventUpdateUserProfile(payload).send();
}
Future<FlowyResult<void, FlowyError>> deleteWorkspace({
required String workspaceId,
}) {
throw UnimplementedError();
}
static Future<FlowyResult<UserProfilePB, FlowyError>> signInWithMagicLink(
String email,
String redirectTo,
) async {
final payload = MagicLinkSignInPB(email: email, redirectTo: redirectTo);
return UserEventMagicLinkSignIn(payload).send();
}
static Future<FlowyResult<void, FlowyError>> signOut() {
return UserEventSignOut().send();
}
Future<FlowyResult<void, FlowyError>> initUser() async {
return UserEventInitUser().send();
}
static Future<FlowyResult<UserProfilePB, FlowyError>> getAnonUser() async {
return UserEventGetAnonUser().send();
}
static Future<FlowyResult<void, FlowyError>> openAnonUser() async {
return UserEventOpenAnonUser().send();
}
Future<FlowyResult<List<UserWorkspacePB>, FlowyError>> getWorkspaces() {
return UserEventGetAllWorkspace().send().then((value) {
return value.fold(
(workspaces) => FlowyResult.success(workspaces.items),
(error) => FlowyResult.failure(error),
);
});
}
Future<FlowyResult<void, FlowyError>> openWorkspace(String workspaceId) {
final payload = UserWorkspaceIdPB.create()..workspaceId = workspaceId;
return UserEventOpenWorkspace(payload).send();
}
Future<FlowyResult<WorkspacePB, FlowyError>> getCurrentWorkspace() {
return FolderEventReadCurrentWorkspace().send().then((result) {
return result.fold(
(workspace) => FlowyResult.success(workspace),
(error) => FlowyResult.failure(error),
);
});
}
Future<FlowyResult<WorkspacePB, FlowyError>> createWorkspace(
String name,
String desc,
) {
final request = CreateWorkspacePayloadPB.create()
..name = name
..desc = desc;
return FolderEventCreateFolderWorkspace(request).send().then((result) {
return result.fold(
(workspace) => FlowyResult.success(workspace),
(error) => FlowyResult.failure(error),
);
});
}
Future<FlowyResult<UserWorkspacePB, FlowyError>> createUserWorkspace(
String name,
) {
final request = CreateWorkspacePB.create()..name = name;
return UserEventCreateWorkspace(request).send();
}
Future<FlowyResult<void, FlowyError>> deleteWorkspaceById(
String workspaceId,
) {
final request = UserWorkspaceIdPB.create()..workspaceId = workspaceId;
return UserEventDeleteWorkspace(request).send();
}
Future<FlowyResult<void, FlowyError>> renameWorkspace(
String workspaceId,
String name,
) {
final request = RenameWorkspacePB()
..workspaceId = workspaceId
..newName = name;
return UserEventRenameWorkspace(request).send();
}
Future<FlowyResult<void, FlowyError>> updateWorkspaceIcon(
String workspaceId,
String icon,
) {
final request = ChangeWorkspaceIconPB()
..workspaceId = workspaceId
..newIcon = icon;
return UserEventChangeWorkspaceIcon(request).send();
}
Future<FlowyResult<RepeatedWorkspaceMemberPB, FlowyError>>
getWorkspaceMembers(
String workspaceId,
) async {
final data = QueryWorkspacePB()..workspaceId = workspaceId;
return UserEventGetWorkspaceMember(data).send();
}
Future<FlowyResult<void, FlowyError>> addWorkspaceMember(
String workspaceId,
String email,
) async {
final data = AddWorkspaceMemberPB()
..workspaceId = workspaceId
..email = email;
return UserEventAddWorkspaceMember(data).send();
}
Future<FlowyResult<void, FlowyError>> removeWorkspaceMember(
String workspaceId,
String email,
) async {
final data = RemoveWorkspaceMemberPB()
..workspaceId = workspaceId
..email = email;
return UserEventRemoveWorkspaceMember(data).send();
}
Future<FlowyResult<void, FlowyError>> updateWorkspaceMember(
String workspaceId,
String email,
AFRolePB role,
) async {
final data = UpdateWorkspaceMemberPB()
..workspaceId = workspaceId
..email = email
..role = role;
return UserEventUpdateWorkspaceMember(data).send();
}
Future<FlowyResult<void, FlowyError>> leaveWorkspace(
String workspaceId,
) async {
final data = UserWorkspaceIdPB.create()..workspaceId = workspaceId;
return UserEventLeaveWorkspace(data).send();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/workspace_error_bloc.dart | import 'package:appflowy/plugins/database/application/defines.dart';
import 'package:appflowy_backend/dispatch/dispatch.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-folder/workspace.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'workspace_error_bloc.freezed.dart';
class WorkspaceErrorBloc
extends Bloc<WorkspaceErrorEvent, WorkspaceErrorState> {
WorkspaceErrorBloc({required this.userFolder, required FlowyError error})
: super(WorkspaceErrorState.initial(error)) {
_dispatch();
}
final UserFolderPB userFolder;
void _dispatch() {
on<WorkspaceErrorEvent>(
(event, emit) async {
await event.when(
init: () {
// _loadSnapshots();
},
resetWorkspace: () async {
emit(state.copyWith(loadingState: const LoadingState.loading()));
final payload = ResetWorkspacePB.create()
..workspaceId = userFolder.workspaceId
..uid = userFolder.uid;
final result = await UserEventResetWorkspace(payload).send();
if (!isClosed) {
add(WorkspaceErrorEvent.didResetWorkspace(result));
}
},
didResetWorkspace: (result) {
result.fold(
(_) {
emit(
state.copyWith(
loadingState: LoadingState.finish(result),
workspaceState: const WorkspaceState.reset(),
),
);
},
(err) {
emit(state.copyWith(loadingState: LoadingState.finish(result)));
},
);
},
logout: () {
emit(
state.copyWith(
workspaceState: const WorkspaceState.logout(),
),
);
},
);
},
);
}
}
@freezed
class WorkspaceErrorEvent with _$WorkspaceErrorEvent {
const factory WorkspaceErrorEvent.init() = _Init;
const factory WorkspaceErrorEvent.logout() = _DidLogout;
const factory WorkspaceErrorEvent.resetWorkspace() = _ResetWorkspace;
const factory WorkspaceErrorEvent.didResetWorkspace(
FlowyResult<void, FlowyError> result,
) = _DidResetWorkspace;
}
@freezed
class WorkspaceErrorState with _$WorkspaceErrorState {
const factory WorkspaceErrorState({
required FlowyError initialError,
LoadingState? loadingState,
required WorkspaceState workspaceState,
}) = _WorkspaceErrorState;
factory WorkspaceErrorState.initial(FlowyError error) => WorkspaceErrorState(
initialError: error,
workspaceState: const WorkspaceState.initial(),
);
}
@freezed
class WorkspaceState with _$WorkspaceState {
const factory WorkspaceState.initial() = _Initial;
const factory WorkspaceState.logout() = _Logout;
const factory WorkspaceState.reset() = _Reset;
const factory WorkspaceState.createNewWorkspace() = _NewWorkspace;
const factory WorkspaceState.restoreFromSnapshot() = _RestoreFromSnapshot;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/splash_bloc.dart | import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy/user/domain/auth_state.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'splash_bloc.freezed.dart';
class SplashBloc extends Bloc<SplashEvent, SplashState> {
SplashBloc() : super(SplashState.initial()) {
on<SplashEvent>((event, emit) async {
await event.map(
getUser: (val) async {
final response = await getIt<AuthService>().getUser();
final authState = response.fold(
(user) => AuthState.authenticated(user),
(error) => AuthState.unauthenticated(error),
);
emit(state.copyWith(auth: authState));
},
);
});
}
}
@freezed
class SplashEvent with _$SplashEvent {
const factory SplashEvent.getUser() = _GetUser;
}
@freezed
class SplashState with _$SplashState {
const factory SplashState({
required AuthState auth,
}) = _SplashState;
factory SplashState.initial() => const SplashState(
auth: AuthState.initial(),
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/sign_up_bloc.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy_backend/protobuf/flowy-error/code.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'
show UserProfilePB;
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'sign_up_bloc.freezed.dart';
class SignUpBloc extends Bloc<SignUpEvent, SignUpState> {
SignUpBloc(this.authService) : super(SignUpState.initial()) {
_dispatch();
}
final AuthService authService;
void _dispatch() {
on<SignUpEvent>(
(event, emit) async {
await event.map(
signUpWithUserEmailAndPassword: (e) async {
await _performActionOnSignUp(emit);
},
emailChanged: (_EmailChanged value) async {
emit(
state.copyWith(
email: value.email,
emailError: null,
successOrFail: null,
),
);
},
passwordChanged: (_PasswordChanged value) async {
emit(
state.copyWith(
password: value.password,
passwordError: null,
successOrFail: null,
),
);
},
repeatPasswordChanged: (_RepeatPasswordChanged value) async {
emit(
state.copyWith(
repeatedPassword: value.password,
repeatPasswordError: null,
successOrFail: null,
),
);
},
);
},
);
}
Future<void> _performActionOnSignUp(Emitter<SignUpState> emit) async {
emit(
state.copyWith(
isSubmitting: true,
successOrFail: null,
),
);
final password = state.password;
final repeatedPassword = state.repeatedPassword;
if (password == null) {
emit(
state.copyWith(
isSubmitting: false,
passwordError: LocaleKeys.signUp_emptyPasswordError.tr(),
),
);
return;
}
if (repeatedPassword == null) {
emit(
state.copyWith(
isSubmitting: false,
repeatPasswordError: LocaleKeys.signUp_repeatPasswordEmptyError.tr(),
),
);
return;
}
if (password != repeatedPassword) {
emit(
state.copyWith(
isSubmitting: false,
repeatPasswordError: LocaleKeys.signUp_unmatchedPasswordError.tr(),
),
);
return;
}
emit(
state.copyWith(
passwordError: null,
repeatPasswordError: null,
),
);
final result = await authService.signUp(
name: state.email ?? '',
password: state.password ?? '',
email: state.email ?? '',
);
emit(
result.fold(
(profile) => state.copyWith(
isSubmitting: false,
successOrFail: FlowyResult.success(profile),
emailError: null,
passwordError: null,
repeatPasswordError: null,
),
(error) => stateFromCode(error),
),
);
}
SignUpState stateFromCode(FlowyError error) {
switch (error.code) {
case ErrorCode.EmailFormatInvalid:
return state.copyWith(
isSubmitting: false,
emailError: error.msg,
passwordError: null,
successOrFail: null,
);
case ErrorCode.PasswordFormatInvalid:
return state.copyWith(
isSubmitting: false,
passwordError: error.msg,
emailError: null,
successOrFail: null,
);
default:
return state.copyWith(
isSubmitting: false,
successOrFail: FlowyResult.failure(error),
);
}
}
}
@freezed
class SignUpEvent with _$SignUpEvent {
const factory SignUpEvent.signUpWithUserEmailAndPassword() =
SignUpWithUserEmailAndPassword;
const factory SignUpEvent.emailChanged(String email) = _EmailChanged;
const factory SignUpEvent.passwordChanged(String password) = _PasswordChanged;
const factory SignUpEvent.repeatPasswordChanged(String password) =
_RepeatPasswordChanged;
}
@freezed
class SignUpState with _$SignUpState {
const factory SignUpState({
String? email,
String? password,
String? repeatedPassword,
required bool isSubmitting,
required String? passwordError,
required String? repeatPasswordError,
required String? emailError,
required FlowyResult<UserProfilePB, FlowyError>? successOrFail,
}) = _SignUpState;
factory SignUpState.initial() => const SignUpState(
isSubmitting: false,
passwordError: null,
repeatPasswordError: null,
emailError: null,
successOrFail: null,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/user_listener.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy/core/notification/folder_notification.dart';
import 'package:appflowy/core/notification/user_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/workspace.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-user/notification.pb.dart'
as user;
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef DidUserWorkspaceUpdateCallback = void Function(
RepeatedUserWorkspacePB workspaces,
);
typedef UserProfileNotifyValue = FlowyResult<UserProfilePB, FlowyError>;
typedef AuthNotifyValue = FlowyResult<void, FlowyError>;
class UserListener {
UserListener({
required UserProfilePB userProfile,
}) : _userProfile = userProfile;
final UserProfilePB _userProfile;
UserNotificationParser? _userParser;
StreamSubscription<SubscribeObject>? _subscription;
PublishNotifier<UserProfileNotifyValue>? _profileNotifier = PublishNotifier();
DidUserWorkspaceUpdateCallback? didUpdateUserWorkspaces;
void start({
void Function(UserProfileNotifyValue)? onProfileUpdated,
void Function(RepeatedUserWorkspacePB)? didUpdateUserWorkspaces,
}) {
if (onProfileUpdated != null) {
_profileNotifier?.addPublishListener(onProfileUpdated);
}
if (didUpdateUserWorkspaces != null) {
this.didUpdateUserWorkspaces = didUpdateUserWorkspaces;
}
_userParser = UserNotificationParser(
id: _userProfile.id.toString(),
callback: _userNotificationCallback,
);
_subscription = RustStreamReceiver.listen((observable) {
_userParser?.parse(observable);
});
}
Future<void> stop() async {
_userParser = null;
await _subscription?.cancel();
_profileNotifier?.dispose();
_profileNotifier = null;
}
void _userNotificationCallback(
user.UserNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case user.UserNotification.DidUpdateUserProfile:
result.fold(
(payload) => _profileNotifier?.value =
FlowyResult.success(UserProfilePB.fromBuffer(payload)),
(error) => _profileNotifier?.value = FlowyResult.failure(error),
);
break;
case user.UserNotification.DidUpdateUserWorkspaces:
result.map(
(r) {
final value = RepeatedUserWorkspacePB.fromBuffer(r);
didUpdateUserWorkspaces?.call(value);
},
);
break;
default:
break;
}
}
}
typedef WorkspaceSettingNotifyValue
= FlowyResult<WorkspaceSettingPB, FlowyError>;
class UserWorkspaceListener {
UserWorkspaceListener();
PublishNotifier<WorkspaceSettingNotifyValue>? _settingChangedNotifier =
PublishNotifier();
FolderNotificationListener? _listener;
void start({
void Function(WorkspaceSettingNotifyValue)? onSettingUpdated,
}) {
if (onSettingUpdated != null) {
_settingChangedNotifier?.addPublishListener(onSettingUpdated);
}
// The "current-workspace" is predefined in the backend. Do not try to
// modify it
_listener = FolderNotificationListener(
objectId: "current-workspace",
handler: _handleObservableType,
);
}
void _handleObservableType(
FolderNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case FolderNotification.DidUpdateWorkspaceSetting:
result.fold(
(payload) => _settingChangedNotifier?.value =
FlowyResult.success(WorkspaceSettingPB.fromBuffer(payload)),
(error) =>
_settingChangedNotifier?.value = FlowyResult.failure(error),
);
break;
default:
break;
}
}
Future<void> stop() async {
await _listener?.stop();
_settingChangedNotifier?.dispose();
_settingChangedNotifier = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/supabase_realtime.dart | import 'dart:async';
import 'dart:convert';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/user_auth_listener.dart';
import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
/// A service to manage realtime interactions with Supabase.
///
/// `SupabaseRealtimeService` handles subscribing to table changes in Supabase
/// based on the authentication state of a user. The service is initialized with
/// a reference to a Supabase instance and sets up the necessary subscriptions
/// accordingly.
class SupabaseRealtimeService {
SupabaseRealtimeService({required this.supabase}) {
_subscribeAuthState();
_subscribeTablesChanges();
_authStateListener.start(
didSignIn: () {
_subscribeTablesChanges();
isLoggingOut = false;
},
onInvalidAuth: (message) async {
Log.error(message);
await channel?.unsubscribe();
channel = null;
if (!isLoggingOut) {
isLoggingOut = true;
await runAppFlowy();
}
},
);
}
final Supabase supabase;
final _authStateListener = UserAuthStateListener();
bool isLoggingOut = false;
RealtimeChannel? channel;
StreamSubscription<AuthState>? authStateSubscription;
void _subscribeAuthState() {
final auth = Supabase.instance.client.auth;
authStateSubscription = auth.onAuthStateChange.listen((state) async {
Log.info("Supabase auth state change: ${state.event}");
});
}
Future<void> _subscribeTablesChanges() async {
final result = await UserBackendService.getCurrentUserProfile();
result.fold(
(userProfile) {
Log.info("Start listening supabase table changes");
// https://supabase.com/docs/guides/realtime/postgres-changes
const ops = RealtimeChannelConfig(ack: true);
channel?.unsubscribe();
channel = supabase.client.channel("table-db-changes", opts: ops);
for (final name in [
"document",
"folder",
"database",
"database_row",
"w_database",
]) {
channel?.onPostgresChanges(
event: PostgresChangeEvent.insert,
schema: 'public',
table: 'af_collab_update_$name',
filter: PostgresChangeFilter(
type: PostgresChangeFilterType.eq,
column: 'uid',
value: userProfile.id,
),
callback: _onPostgresChangesCallback,
);
}
channel?.onPostgresChanges(
event: PostgresChangeEvent.update,
schema: 'public',
table: 'af_user',
filter: PostgresChangeFilter(
type: PostgresChangeFilterType.eq,
column: 'uid',
value: userProfile.id,
),
callback: _onPostgresChangesCallback,
);
channel?.subscribe(
(status, [err]) {
Log.info(
"subscribe channel statue: $status, err: $err",
);
},
);
},
(_) => null,
);
}
Future<void> dispose() async {
await _authStateListener.stop();
await authStateSubscription?.cancel();
await channel?.unsubscribe();
}
void _onPostgresChangesCallback(PostgresChangePayload payload) {
try {
final jsonStr = jsonEncode(payload);
final pb = RealtimePayloadPB.create()..jsonStr = jsonStr;
UserEventPushRealtimeEvent(pb).send();
} catch (e) {
Log.error(e);
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/encrypt_secret_bloc.dart | import 'package:appflowy/plugins/database/application/defines.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'auth/auth_service.dart';
part 'encrypt_secret_bloc.freezed.dart';
class EncryptSecretBloc extends Bloc<EncryptSecretEvent, EncryptSecretState> {
EncryptSecretBloc({required this.user})
: super(EncryptSecretState.initial()) {
_dispatch();
}
final UserProfilePB user;
void _dispatch() {
on<EncryptSecretEvent>((event, emit) async {
await event.when(
setEncryptSecret: (secret) async {
if (isLoading()) {
return;
}
final payload = UserSecretPB.create()
..encryptionSecret = secret
..encryptionSign = user.encryptionSign
..encryptionType = user.encryptionType
..userId = user.id;
final result = await UserEventSetEncryptionSecret(payload).send();
if (!isClosed) {
add(EncryptSecretEvent.didFinishCheck(result));
}
emit(
state.copyWith(
loadingState: const LoadingState.loading(),
successOrFail: null,
),
);
},
cancelInputSecret: () async {
await getIt<AuthService>().signOut();
emit(
state.copyWith(
successOrFail: null,
isSignOut: true,
),
);
},
didFinishCheck: (result) {
result.fold(
(unit) {
emit(
state.copyWith(
loadingState: const LoadingState.loading(),
successOrFail: result,
),
);
},
(err) {
emit(
state.copyWith(
loadingState: LoadingState.finish(FlowyResult.failure(err)),
successOrFail: result,
),
);
},
);
},
);
});
}
bool isLoading() {
final loadingState = state.loadingState;
if (loadingState != null) {
return loadingState.when(
loading: () => true,
finish: (_) => false,
idle: () => false,
);
}
return false;
}
}
@freezed
class EncryptSecretEvent with _$EncryptSecretEvent {
const factory EncryptSecretEvent.setEncryptSecret(String secret) =
_SetEncryptSecret;
const factory EncryptSecretEvent.didFinishCheck(
FlowyResult<void, FlowyError> result,
) = _DidFinishCheck;
const factory EncryptSecretEvent.cancelInputSecret() = _CancelInputSecret;
}
@freezed
class EncryptSecretState with _$EncryptSecretState {
const factory EncryptSecretState({
required FlowyResult<void, FlowyError>? successOrFail,
required bool isSignOut,
LoadingState? loadingState,
}) = _EncryptSecretState;
factory EncryptSecretState.initial() => const EncryptSecretState(
successOrFail: null,
isSignOut: false,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/reminder/reminder_service.dart | import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/reminder.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
/// Interface for a Reminder Service that handles
/// communication to the backend
///
abstract class IReminderService {
Future<FlowyResult<List<ReminderPB>, FlowyError>> fetchReminders();
Future<FlowyResult<void, FlowyError>> removeReminder({
required String reminderId,
});
Future<FlowyResult<void, FlowyError>> addReminder({
required ReminderPB reminder,
});
Future<FlowyResult<void, FlowyError>> updateReminder({
required ReminderPB reminder,
});
}
class ReminderService implements IReminderService {
const ReminderService();
@override
Future<FlowyResult<void, FlowyError>> addReminder({
required ReminderPB reminder,
}) async {
final unitOrFailure = await UserEventCreateReminder(reminder).send();
return unitOrFailure;
}
@override
Future<FlowyResult<void, FlowyError>> updateReminder({
required ReminderPB reminder,
}) async {
final unitOrFailure = await UserEventUpdateReminder(reminder).send();
return unitOrFailure;
}
@override
Future<FlowyResult<List<ReminderPB>, FlowyError>> fetchReminders() async {
final resultOrFailure = await UserEventGetAllReminders().send();
return resultOrFailure.fold(
(s) => FlowyResult.success(s.items),
(e) => FlowyResult.failure(e),
);
}
@override
Future<FlowyResult<void, FlowyError>> removeReminder({
required String reminderId,
}) async {
final request = ReminderIdentifierPB(id: reminderId);
final unitOrFailure = await UserEventRemoveReminder(request).send();
return unitOrFailure;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/reminder/reminder_bloc.dart | import 'dart:async';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/reminder/reminder_extension.dart';
import 'package:appflowy/user/application/reminder/reminder_service.dart';
import 'package:appflowy/user/application/user_settings_service.dart';
import 'package:appflowy/util/int64_extension.dart';
import 'package:appflowy/workspace/application/action_navigation/action_navigation_bloc.dart';
import 'package:appflowy/workspace/application/action_navigation/navigation_action.dart';
import 'package:appflowy/workspace/application/notification/notification_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:bloc/bloc.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:fixnum/fixnum.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'reminder_bloc.freezed.dart';
class ReminderBloc extends Bloc<ReminderEvent, ReminderState> {
ReminderBloc() : super(ReminderState()) {
_actionBloc = getIt<ActionNavigationBloc>();
_reminderService = const ReminderService();
timer = _periodicCheck();
_dispatch();
}
late final ActionNavigationBloc _actionBloc;
late final ReminderService _reminderService;
late final Timer timer;
void _dispatch() {
on<ReminderEvent>(
(event, emit) async {
await event.when(
markAllRead: () async {
final unreadReminders =
state.pastReminders.where((reminder) => !reminder.isRead);
final reminders = [...state.reminders];
final updatedReminders = <ReminderPB>[];
for (final reminder in unreadReminders) {
reminders.remove(reminder);
reminder.isRead = true;
await _reminderService.updateReminder(reminder: reminder);
updatedReminders.add(reminder);
}
reminders.addAll(updatedReminders);
emit(state.copyWith(reminders: reminders));
},
started: () async {
final remindersOrFailure = await _reminderService.fetchReminders();
remindersOrFailure.fold(
(reminders) => emit(state.copyWith(reminders: reminders)),
(error) => Log.error(error),
);
},
remove: (reminderId) async {
final unitOrFailure =
await _reminderService.removeReminder(reminderId: reminderId);
unitOrFailure.fold(
(_) {
final reminders = [...state.reminders];
reminders.removeWhere((e) => e.id == reminderId);
emit(state.copyWith(reminders: reminders));
},
(error) => Log.error(error),
);
},
add: (reminder) async {
final unitOrFailure =
await _reminderService.addReminder(reminder: reminder);
return unitOrFailure.fold(
(_) {
final reminders = [...state.reminders, reminder];
emit(state.copyWith(reminders: reminders));
},
(error) => Log.error(error),
);
},
addById: (reminderId, objectId, scheduledAt, meta) async => add(
ReminderEvent.add(
reminder: ReminderPB(
id: reminderId,
objectId: objectId,
title: LocaleKeys.reminderNotification_title.tr(),
message: LocaleKeys.reminderNotification_message.tr(),
scheduledAt: scheduledAt,
isAck: scheduledAt.toDateTime().isBefore(DateTime.now()),
meta: meta,
),
),
),
update: (updateObject) async {
final reminder = state.reminders
.firstWhereOrNull((r) => r.id == updateObject.id);
if (reminder == null) {
return;
}
final newReminder = updateObject.merge(a: reminder);
final failureOrUnit = await _reminderService.updateReminder(
reminder: updateObject.merge(a: reminder),
);
failureOrUnit.fold(
(_) {
final index =
state.reminders.indexWhere((r) => r.id == reminder.id);
final reminders = [...state.reminders];
reminders.replaceRange(index, index + 1, [newReminder]);
emit(state.copyWith(reminders: reminders));
},
(error) => Log.error(error),
);
},
pressReminder: (reminderId, path, view) {
final reminder =
state.reminders.firstWhereOrNull((r) => r.id == reminderId);
if (reminder == null) {
return;
}
add(
ReminderEvent.update(
ReminderUpdate(
id: reminderId,
isRead: state.pastReminders.contains(reminder),
),
),
);
String? rowId;
if (view?.layout != ViewLayoutPB.Document) {
rowId = reminder.meta[ReminderMetaKeys.rowId];
}
final action = NavigationAction(
objectId: reminder.objectId,
arguments: {
ActionArgumentKeys.view: view,
ActionArgumentKeys.nodePath: path,
ActionArgumentKeys.rowId: rowId,
},
);
if (!isClosed) {
_actionBloc.add(
ActionNavigationEvent.performAction(
action: action,
nextActions: [
action.copyWith(
type: rowId != null
? ActionType.openRow
: ActionType.jumpToBlock,
),
],
),
);
}
},
);
},
);
}
Timer _periodicCheck() {
return Timer.periodic(
const Duration(minutes: 1),
(_) async {
final now = DateTime.now();
for (final reminder in state.upcomingReminders) {
if (reminder.isAck) {
continue;
}
final scheduledAt = reminder.scheduledAt.toDateTime();
if (scheduledAt.isBefore(now)) {
final notificationSettings =
await UserSettingsBackendService().getNotificationSettings();
if (notificationSettings.notificationsEnabled) {
NotificationMessage(
identifier: reminder.id,
title: LocaleKeys.reminderNotification_title.tr(),
body: LocaleKeys.reminderNotification_message.tr(),
onClick: () => _actionBloc.add(
ActionNavigationEvent.performAction(
action: NavigationAction(objectId: reminder.objectId),
),
),
);
}
add(
ReminderEvent.update(
ReminderUpdate(id: reminder.id, isAck: true),
),
);
}
}
},
);
}
}
@freezed
class ReminderEvent with _$ReminderEvent {
// On startup we fetch all reminders and upcoming ones
const factory ReminderEvent.started() = _Started;
// Remove a reminder
const factory ReminderEvent.remove({required String reminderId}) = _Remove;
// Add a reminder
const factory ReminderEvent.add({required ReminderPB reminder}) = _Add;
// Add a reminder
const factory ReminderEvent.addById({
required String reminderId,
required String objectId,
required Int64 scheduledAt,
@Default(null) Map<String, String>? meta,
}) = _AddById;
// Update a reminder (eg. isAck, isRead, etc.)
const factory ReminderEvent.update(ReminderUpdate update) = _Update;
// Mark all unread reminders as read
const factory ReminderEvent.markAllRead() = _MarkAllRead;
const factory ReminderEvent.pressReminder({
required String reminderId,
@Default(null) int? path,
@Default(null) ViewPB? view,
}) = _PressReminder;
}
/// Object used to merge updates with
/// a [ReminderPB]
///
class ReminderUpdate {
ReminderUpdate({
required this.id,
this.isAck,
this.isRead,
this.scheduledAt,
this.includeTime,
});
final String id;
final bool? isAck;
final bool? isRead;
final DateTime? scheduledAt;
final bool? includeTime;
ReminderPB merge({required ReminderPB a}) {
final isAcknowledged = isAck == null && scheduledAt != null
? scheduledAt!.isBefore(DateTime.now())
: a.isAck;
final meta = a.meta;
if (includeTime != a.includeTime) {
meta[ReminderMetaKeys.includeTime] = includeTime.toString();
}
return ReminderPB(
id: a.id,
objectId: a.objectId,
scheduledAt: scheduledAt != null
? Int64(scheduledAt!.millisecondsSinceEpoch ~/ 1000)
: a.scheduledAt,
isAck: isAcknowledged,
isRead: isRead ?? a.isRead,
title: a.title,
message: a.message,
meta: meta,
);
}
}
class ReminderState {
ReminderState({List<ReminderPB>? reminders}) {
_reminders = reminders ?? [];
pastReminders = [];
upcomingReminders = [];
if (_reminders.isEmpty) {
hasUnreads = false;
return;
}
final now = DateTime.now();
bool hasUnreadReminders = false;
for (final reminder in _reminders) {
final scheduledDate = DateTime.fromMillisecondsSinceEpoch(
reminder.scheduledAt.toInt() * 1000,
);
if (scheduledDate.isBefore(now)) {
pastReminders.add(reminder);
if (!hasUnreadReminders && !reminder.isRead) {
hasUnreadReminders = true;
}
} else {
upcomingReminders.add(reminder);
}
}
hasUnreads = hasUnreadReminders;
}
late final List<ReminderPB> _reminders;
List<ReminderPB> get reminders => _reminders;
late final List<ReminderPB> pastReminders;
late final List<ReminderPB> upcomingReminders;
late final bool hasUnreads;
ReminderState copyWith({List<ReminderPB>? reminders}) =>
ReminderState(reminders: reminders ?? _reminders);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/user/application/reminder/reminder_extension.dart | import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
class ReminderMetaKeys {
static String includeTime = "include_time";
static String blockId = "block_id";
static String rowId = "row_id";
}
extension ReminderExtension on ReminderPB {
bool? get includeTime {
final String? includeTimeStr = meta[ReminderMetaKeys.includeTime];
return includeTimeStr != null ? includeTimeStr == true.toString() : null;
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.