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/plugins/database/widgets/row | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/row/accessory/cell_accessory.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_backend/protobuf/flowy-database2/field_entities.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/style_widget/hover.dart';
import 'package:flowy_infra_ui/widget/flowy_tooltip.dart';
import 'package:styled_widget/styled_widget.dart';
import '../../cell/editable_cell_builder.dart';
class GridCellAccessoryBuildContext {
GridCellAccessoryBuildContext({
required this.anchorContext,
required this.isCellEditing,
});
final BuildContext anchorContext;
final bool isCellEditing;
}
class GridCellAccessoryBuilder<T extends State<StatefulWidget>> {
GridCellAccessoryBuilder({required Widget Function(Key key) builder})
: _builder = builder;
final GlobalKey<T> _key = GlobalKey();
final Widget Function(Key key) _builder;
Widget build() => _builder(_key);
void onTap() {
(_key.currentState as GridCellAccessoryState).onTap();
}
bool enable() {
if (_key.currentState == null) {
return true;
}
return (_key.currentState as GridCellAccessoryState).enable();
}
}
abstract mixin class GridCellAccessoryState {
void onTap();
// The accessory will be hidden if enable() return false;
bool enable() => true;
}
class PrimaryCellAccessory extends StatefulWidget {
const PrimaryCellAccessory({
super.key,
required this.onTap,
required this.isCellEditing,
});
final VoidCallback onTap;
final bool isCellEditing;
@override
State<StatefulWidget> createState() => _PrimaryCellAccessoryState();
}
class _PrimaryCellAccessoryState extends State<PrimaryCellAccessory>
with GridCellAccessoryState {
@override
Widget build(BuildContext context) {
return FlowyTooltip(
message: LocaleKeys.tooltip_openAsPage.tr(),
child: SizedBox(
width: 26,
height: 26,
child: Padding(
padding: const EdgeInsets.all(3.0),
child: FlowySvg(
FlowySvgs.full_view_s,
color: Theme.of(context).colorScheme.primary,
),
),
),
);
}
@override
void onTap() => widget.onTap();
@override
bool enable() => !widget.isCellEditing;
}
class AccessoryHover extends StatefulWidget {
const AccessoryHover({
super.key,
required this.child,
required this.fieldType,
});
final CellAccessory child;
final FieldType fieldType;
@override
State<AccessoryHover> createState() => _AccessoryHoverState();
}
class _AccessoryHoverState extends State<AccessoryHover> {
bool _isHover = false;
@override
Widget build(BuildContext context) {
final List<Widget> children = [
DecoratedBox(
decoration: BoxDecoration(
color: _isHover && widget.fieldType != FieldType.Checklist
? AFThemeExtension.of(context).lightGreyHover
: Colors.transparent,
borderRadius: Corners.s6Border,
),
child: widget.child,
),
];
final accessoryBuilder = widget.child.accessoryBuilder;
if (accessoryBuilder != null && _isHover) {
final accessories = accessoryBuilder(
GridCellAccessoryBuildContext(
anchorContext: context,
isCellEditing: false,
),
);
children.add(
Padding(
padding: const EdgeInsets.only(right: 6),
child: CellAccessoryContainer(accessories: accessories),
).positioned(right: 0),
);
}
return MouseRegion(
cursor: SystemMouseCursors.click,
opaque: false,
onEnter: (p) => setState(() => _isHover = true),
onExit: (p) => setState(() => _isHover = false),
child: Stack(
alignment: AlignmentDirectional.center,
children: children,
),
);
}
}
class CellAccessoryContainer extends StatelessWidget {
const CellAccessoryContainer({required this.accessories, super.key});
final List<GridCellAccessoryBuilder> accessories;
@override
Widget build(BuildContext context) {
final children =
accessories.where((accessory) => accessory.enable()).map((accessory) {
final hover = FlowyHover(
style:
HoverStyle(hoverColor: AFThemeExtension.of(context).lightGreyHover),
builder: (_, onHover) => accessory.build(),
);
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => accessory.onTap(),
child: hover,
);
}).toList();
return Wrap(spacing: 6, children: children);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/widgets/group/database_group.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/application/setting/group_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/common/type_option_separator.dart';
import 'package:appflowy/util/field_type_extension.dart';
import 'package:appflowy/workspace/presentation/widgets/toggle/toggle.dart';
import 'package:appflowy/workspace/presentation/widgets/toggle/toggle_style.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/board_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:protobuf/protobuf.dart' hide FieldInfo;
class DatabaseGroupList extends StatelessWidget {
const DatabaseGroupList({
super.key,
required this.viewId,
required this.databaseController,
required this.onDismissed,
});
final String viewId;
final DatabaseController databaseController;
final VoidCallback onDismissed;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => DatabaseGroupBloc(
viewId: viewId,
databaseController: databaseController,
)..add(const DatabaseGroupEvent.initial()),
child: BlocBuilder<DatabaseGroupBloc, DatabaseGroupState>(
builder: (context, state) {
final showHideUngroupedToggle = state.fieldInfos.any(
(field) =>
field.canBeGroup &&
field.isGroupField &&
field.fieldType != FieldType.Checkbox,
);
final children = [
if (showHideUngroupedToggle) ...[
SizedBox(
height: GridSize.popoverItemHeight,
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: Row(
children: [
Expanded(
child: FlowyText.medium(
LocaleKeys.board_showUngrouped.tr(),
),
),
Toggle(
value: !state.layoutSettings.hideUngroupedColumn,
onChanged: (value) =>
_updateLayoutSettings(state.layoutSettings, value),
style: ToggleStyle.big,
padding: EdgeInsets.zero,
),
],
),
),
),
const TypeOptionSeparator(spacing: 0),
],
SizedBox(
height: GridSize.popoverItemHeight,
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: FlowyText.medium(
LocaleKeys.board_groupBy.tr(),
textAlign: TextAlign.left,
color: Theme.of(context).hintColor,
),
),
),
...state.fieldInfos.where((fieldInfo) => fieldInfo.canBeGroup).map(
(fieldInfo) => _GridGroupCell(
fieldInfo: fieldInfo,
onSelected: onDismissed,
key: ValueKey(fieldInfo.id),
),
),
];
return ListView.separated(
shrinkWrap: true,
itemCount: children.length,
itemBuilder: (BuildContext context, int index) => children[index],
separatorBuilder: (BuildContext context, int index) =>
VSpace(GridSize.typeOptionSeparatorHeight),
padding: const EdgeInsets.symmetric(vertical: 6.0),
);
},
),
);
}
Future<void> _updateLayoutSettings(
BoardLayoutSettingPB layoutSettings,
bool hideUngrouped,
) {
layoutSettings.freeze();
final newLayoutSetting = layoutSettings.rebuild((message) {
message.hideUngroupedColumn = hideUngrouped;
});
return databaseController.updateLayoutSetting(
boardLayoutSetting: newLayoutSetting,
);
}
}
class _GridGroupCell extends StatelessWidget {
const _GridGroupCell({
super.key,
required this.fieldInfo,
required this.onSelected,
});
final FieldInfo fieldInfo;
final VoidCallback onSelected;
@override
Widget build(BuildContext context) {
Widget? rightIcon;
if (fieldInfo.isGroupField) {
rightIcon = const Padding(
padding: EdgeInsets.all(2.0),
child: FlowySvg(FlowySvgs.check_s),
);
}
return SizedBox(
height: GridSize.popoverItemHeight,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 6.0),
child: FlowyButton(
hoverColor: AFThemeExtension.of(context).lightGreyHover,
text: FlowyText.medium(
fieldInfo.name,
color: AFThemeExtension.of(context).textColor,
),
leftIcon: FlowySvg(
fieldInfo.fieldType.svgData,
color: Theme.of(context).iconTheme.color,
),
rightIcon: rightIcon,
onTap: () {
context.read<DatabaseGroupBloc>().add(
DatabaseGroupEvent.setGroupByField(
fieldInfo.id,
fieldInfo.fieldType,
),
);
onSelected();
},
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/database_controller.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/view/view_cache.dart';
import 'package:appflowy/plugins/database/domain/database_view_service.dart';
import 'package:appflowy/plugins/database/domain/group_listener.dart';
import 'package:appflowy/plugins/database/domain/layout_service.dart';
import 'package:appflowy/plugins/database/domain/layout_setting_listener.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'defines.dart';
import 'row/row_cache.dart';
typedef OnGroupConfigurationChanged = void Function(List<GroupSettingPB>);
typedef OnGroupByField = void Function(List<GroupPB>);
typedef OnUpdateGroup = void Function(List<GroupPB>);
typedef OnDeleteGroup = void Function(List<String>);
typedef OnInsertGroup = void Function(InsertedGroupPB);
class GroupCallbacks {
GroupCallbacks({
this.onGroupConfigurationChanged,
this.onGroupByField,
this.onUpdateGroup,
this.onDeleteGroup,
this.onInsertGroup,
});
final OnGroupConfigurationChanged? onGroupConfigurationChanged;
final OnGroupByField? onGroupByField;
final OnUpdateGroup? onUpdateGroup;
final OnDeleteGroup? onDeleteGroup;
final OnInsertGroup? onInsertGroup;
}
class DatabaseLayoutSettingCallbacks {
DatabaseLayoutSettingCallbacks({required this.onLayoutSettingsChanged});
final void Function(DatabaseLayoutSettingPB) onLayoutSettingsChanged;
}
class DatabaseCallbacks {
DatabaseCallbacks({
this.onDatabaseChanged,
this.onNumOfRowsChanged,
this.onFieldsChanged,
this.onFiltersChanged,
this.onSortsChanged,
this.onRowsUpdated,
this.onRowsDeleted,
this.onRowsCreated,
});
OnDatabaseChanged? onDatabaseChanged;
OnFieldsChanged? onFieldsChanged;
OnFiltersChanged? onFiltersChanged;
OnSortsChanged? onSortsChanged;
OnNumOfRowsChanged? onNumOfRowsChanged;
OnRowsDeleted? onRowsDeleted;
OnRowsUpdated? onRowsUpdated;
OnRowsCreated? onRowsCreated;
}
class DatabaseController {
DatabaseController({required ViewPB view})
: viewId = view.id,
_databaseViewBackendSvc = DatabaseViewBackendService(viewId: view.id),
fieldController = FieldController(viewId: view.id),
_groupListener = DatabaseGroupListener(view.id),
databaseLayout = databaseLayoutFromViewLayout(view.layout),
_layoutListener = DatabaseLayoutSettingListener(view.id) {
_viewCache = DatabaseViewCache(
viewId: viewId,
fieldController: fieldController,
);
_listenOnRowsChanged();
_listenOnFieldsChanged();
_listenOnGroupChanged();
_listenOnLayoutChanged();
}
final String viewId;
final DatabaseViewBackendService _databaseViewBackendSvc;
final FieldController fieldController;
DatabaseLayoutPB databaseLayout;
DatabaseLayoutSettingPB? databaseLayoutSetting;
late DatabaseViewCache _viewCache;
// Callbacks
final List<DatabaseCallbacks> _databaseCallbacks = [];
final List<GroupCallbacks> _groupCallbacks = [];
final List<DatabaseLayoutSettingCallbacks> _layoutCallbacks = [];
// Getters
RowCache get rowCache => _viewCache.rowCache;
// Listener
final DatabaseGroupListener _groupListener;
final DatabaseLayoutSettingListener _layoutListener;
final ValueNotifier<bool> _isLoading = ValueNotifier(true);
void setIsLoading(bool isLoading) {
_isLoading.value = isLoading;
}
ValueNotifier<bool> get isLoading => _isLoading;
void addListener({
DatabaseCallbacks? onDatabaseChanged,
DatabaseLayoutSettingCallbacks? onLayoutSettingsChanged,
GroupCallbacks? onGroupChanged,
}) {
if (onLayoutSettingsChanged != null) {
_layoutCallbacks.add(onLayoutSettingsChanged);
}
if (onDatabaseChanged != null) {
_databaseCallbacks.add(onDatabaseChanged);
}
if (onGroupChanged != null) {
_groupCallbacks.add(onGroupChanged);
}
}
Future<FlowyResult<void, FlowyError>> open() async {
return _databaseViewBackendSvc.openDatabase().then((result) {
return result.fold(
(DatabasePB database) async {
databaseLayout = database.layoutType;
// Load the actual database field data.
final fieldsOrFail = await fieldController.loadFields(
fieldIds: database.fields,
);
return fieldsOrFail.fold(
(fields) {
// Notify the database is changed after the fields are loaded.
// The database won't can't be used until the fields are loaded.
for (final callback in _databaseCallbacks) {
callback.onDatabaseChanged?.call(database);
}
_viewCache.rowCache.setInitialRows(database.rows);
return Future(() async {
await _loadGroups();
await _loadLayoutSetting();
return FlowyResult.success(fields);
});
},
(err) {
Log.error(err);
return FlowyResult.failure(err);
},
);
},
(err) => FlowyResult.failure(err),
);
});
}
Future<FlowyResult<void, FlowyError>> moveGroupRow({
required RowMetaPB fromRow,
required String fromGroupId,
required String toGroupId,
RowMetaPB? toRow,
}) {
return _databaseViewBackendSvc.moveGroupRow(
fromRowId: fromRow.id,
fromGroupId: fromGroupId,
toGroupId: toGroupId,
toRowId: toRow?.id,
);
}
Future<FlowyResult<void, FlowyError>> moveRow({
required String fromRowId,
required String toRowId,
}) {
return _databaseViewBackendSvc.moveRow(
fromRowId: fromRowId,
toRowId: toRowId,
);
}
Future<FlowyResult<void, FlowyError>> moveGroup({
required String fromGroupId,
required String toGroupId,
}) {
return _databaseViewBackendSvc.moveGroup(
fromGroupId: fromGroupId,
toGroupId: toGroupId,
);
}
Future<void> updateLayoutSetting({
BoardLayoutSettingPB? boardLayoutSetting,
CalendarLayoutSettingPB? calendarLayoutSetting,
}) async {
await _databaseViewBackendSvc
.updateLayoutSetting(
boardLayoutSetting: boardLayoutSetting,
calendarLayoutSetting: calendarLayoutSetting,
layoutType: databaseLayout,
)
.then((result) {
result.fold((l) => null, (r) => Log.error(r));
});
}
Future<void> dispose() async {
await _databaseViewBackendSvc.closeView();
await fieldController.dispose();
await _groupListener.stop();
await _viewCache.dispose();
_databaseCallbacks.clear();
_groupCallbacks.clear();
_layoutCallbacks.clear();
}
Future<void> _loadGroups() async {
final groupsResult = await _databaseViewBackendSvc.loadGroups();
groupsResult.fold(
(groups) {
for (final callback in _groupCallbacks) {
callback.onGroupByField?.call(groups.items);
}
},
(err) => Log.error(err),
);
}
Future<void> _loadLayoutSetting() {
return _databaseViewBackendSvc
.getLayoutSetting(databaseLayout)
.then((result) {
result.fold(
(newDatabaseLayoutSetting) {
databaseLayoutSetting = newDatabaseLayoutSetting;
for (final callback in _layoutCallbacks) {
callback.onLayoutSettingsChanged(newDatabaseLayoutSetting);
}
},
(r) => Log.error(r),
);
});
}
void _listenOnRowsChanged() {
final callbacks = DatabaseViewCallbacks(
onNumOfRowsChanged: (rows, rowByRowId, reason) {
for (final callback in _databaseCallbacks) {
callback.onNumOfRowsChanged?.call(rows, rowByRowId, reason);
}
},
onRowsDeleted: (ids) {
for (final callback in _databaseCallbacks) {
callback.onRowsDeleted?.call(ids);
}
},
onRowsUpdated: (ids, reason) {
for (final callback in _databaseCallbacks) {
callback.onRowsUpdated?.call(ids, reason);
}
},
onRowsCreated: (ids) {
for (final callback in _databaseCallbacks) {
callback.onRowsCreated?.call(ids);
}
},
);
_viewCache.addListener(callbacks);
}
void _listenOnFieldsChanged() {
fieldController.addListener(
onReceiveFields: (fields) {
for (final callback in _databaseCallbacks) {
callback.onFieldsChanged?.call(UnmodifiableListView(fields));
}
},
onSorts: (sorts) {
for (final callback in _databaseCallbacks) {
callback.onSortsChanged?.call(sorts);
}
},
onFilters: (filters) {
for (final callback in _databaseCallbacks) {
callback.onFiltersChanged?.call(filters);
}
},
);
}
void _listenOnGroupChanged() {
_groupListener.start(
onNumOfGroupsChanged: (result) {
result.fold(
(changeset) {
if (changeset.updateGroups.isNotEmpty) {
for (final callback in _groupCallbacks) {
callback.onUpdateGroup?.call(changeset.updateGroups);
}
}
if (changeset.deletedGroups.isNotEmpty) {
for (final callback in _groupCallbacks) {
callback.onDeleteGroup?.call(changeset.deletedGroups);
}
}
for (final insertedGroup in changeset.insertedGroups) {
for (final callback in _groupCallbacks) {
callback.onInsertGroup?.call(insertedGroup);
}
}
},
(r) => Log.error(r),
);
},
onGroupByNewField: (result) {
result.fold(
(groups) {
for (final callback in _groupCallbacks) {
callback.onGroupByField?.call(groups);
}
},
(r) => Log.error(r),
);
},
);
}
void _listenOnLayoutChanged() {
_layoutListener.start(
onLayoutChanged: (result) {
result.fold(
(newLayout) {
databaseLayoutSetting = newLayout;
databaseLayoutSetting?.freeze();
for (final callback in _layoutCallbacks) {
callback.onLayoutSettingsChanged(newLayout);
}
},
(r) => Log.error(r),
);
},
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/tab_bar_bloc.dart | import 'package:appflowy/plugins/database/domain/database_view_service.dart';
import 'package:appflowy/plugins/database/tab_bar/tab_bar_view.dart';
import 'package:appflowy/plugins/database/widgets/database_layout_ext.dart';
import 'package:appflowy/workspace/application/view/prelude.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart' hide Log;
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'database_controller.dart';
part 'tab_bar_bloc.freezed.dart';
class DatabaseTabBarBloc
extends Bloc<DatabaseTabBarEvent, DatabaseTabBarState> {
DatabaseTabBarBloc({required ViewPB view})
: super(DatabaseTabBarState.initial(view)) {
on<DatabaseTabBarEvent>(
(event, emit) async {
await event.when(
initial: () {
_listenInlineViewChanged();
_loadChildView();
},
didLoadChildViews: (List<ViewPB> childViews) {
emit(
state.copyWith(
tabBars: [
...state.tabBars,
...childViews.map(
(newChildView) => DatabaseTabBar(view: newChildView),
),
],
tabBarControllerByViewId: _extendsTabBarController(childViews),
),
);
},
selectView: (String viewId) {
final index =
state.tabBars.indexWhere((element) => element.viewId == viewId);
if (index != -1) {
emit(
state.copyWith(selectedIndex: index),
);
}
},
createView: (layout, name) {
_createLinkedView(layout.layoutType, name ?? layout.layoutName);
},
deleteView: (String viewId) async {
final result = await ViewBackendService.delete(viewId: viewId);
result.fold(
(l) {},
(r) => Log.error(r),
);
},
renameView: (String viewId, String newName) {
ViewBackendService.updateView(viewId: viewId, name: newName);
},
didUpdateChildViews: (updatePB) async {
if (updatePB.createChildViews.isNotEmpty) {
final allTabBars = [
...state.tabBars,
...updatePB.createChildViews
.map((e) => DatabaseTabBar(view: e)),
];
emit(
state.copyWith(
tabBars: allTabBars,
selectedIndex: state.tabBars.length,
tabBarControllerByViewId:
_extendsTabBarController(updatePB.createChildViews),
),
);
}
if (updatePB.deleteChildViews.isNotEmpty) {
final allTabBars = [...state.tabBars];
final tabBarControllerByViewId = {
...state.tabBarControllerByViewId,
};
var newSelectedIndex = state.selectedIndex;
for (final viewId in updatePB.deleteChildViews) {
final index = allTabBars.indexWhere(
(element) => element.viewId == viewId,
);
if (index != -1) {
final tabBar = allTabBars.removeAt(index);
// Dispose the controller when the tab is removed.
final controller =
tabBarControllerByViewId.remove(tabBar.viewId);
await controller?.dispose();
}
if (index == state.selectedIndex) {
if (index > 0 && allTabBars.isNotEmpty) {
newSelectedIndex = index - 1;
}
}
}
emit(
state.copyWith(
tabBars: allTabBars,
selectedIndex: newSelectedIndex,
tabBarControllerByViewId: tabBarControllerByViewId,
),
);
}
},
viewDidUpdate: (ViewPB updatedView) {
final index = state.tabBars.indexWhere(
(element) => element.viewId == updatedView.id,
);
if (index != -1) {
final allTabBars = [...state.tabBars];
final updatedTabBar = DatabaseTabBar(view: updatedView);
allTabBars[index] = updatedTabBar;
emit(state.copyWith(tabBars: allTabBars));
}
},
);
},
);
}
@override
Future<void> close() async {
for (final tabBar in state.tabBars) {
await state.tabBarControllerByViewId[tabBar.viewId]?.dispose();
tabBar.dispose();
}
return super.close();
}
void _listenInlineViewChanged() {
final controller = state.tabBarControllerByViewId[state.parentView.id];
controller?.onViewUpdated = (newView) {
add(DatabaseTabBarEvent.viewDidUpdate(newView));
};
// Only listen the child view changes when the parent view is inline.
controller?.onViewChildViewChanged = (update) {
add(DatabaseTabBarEvent.didUpdateChildViews(update));
};
}
/// Create tab bar controllers for the new views and return the updated map.
Map<String, DatabaseTabBarController> _extendsTabBarController(
List<ViewPB> newViews,
) {
final tabBarControllerByViewId = {...state.tabBarControllerByViewId};
for (final view in newViews) {
final controller = DatabaseTabBarController(view: view);
controller.onViewUpdated = (newView) {
add(DatabaseTabBarEvent.viewDidUpdate(newView));
};
tabBarControllerByViewId[view.id] = controller;
}
return tabBarControllerByViewId;
}
Future<void> _createLinkedView(ViewLayoutPB layoutType, String name) async {
final viewId = state.parentView.id;
final databaseIdOrError =
await DatabaseViewBackendService(viewId: viewId).getDatabaseId();
databaseIdOrError.fold(
(databaseId) async {
final linkedViewOrError =
await ViewBackendService.createDatabaseLinkedView(
parentViewId: viewId,
databaseId: databaseId,
layoutType: layoutType,
name: name,
);
linkedViewOrError.fold(
(linkedView) {},
(err) => Log.error(err),
);
},
(r) => Log.error(r),
);
}
void _loadChildView() async {
final viewsOrFail =
await ViewBackendService.getChildViews(viewId: state.parentView.id);
viewsOrFail.fold(
(views) {
if (!isClosed) {
add(DatabaseTabBarEvent.didLoadChildViews(views));
}
},
(err) => Log.error(err),
);
}
}
@freezed
class DatabaseTabBarEvent with _$DatabaseTabBarEvent {
const factory DatabaseTabBarEvent.initial() = _Initial;
const factory DatabaseTabBarEvent.didLoadChildViews(
List<ViewPB> childViews,
) = _DidLoadChildViews;
const factory DatabaseTabBarEvent.selectView(String viewId) = _DidSelectView;
const factory DatabaseTabBarEvent.createView(
DatabaseLayoutPB layout,
String? name,
) = _CreateView;
const factory DatabaseTabBarEvent.renameView(String viewId, String newName) =
_RenameView;
const factory DatabaseTabBarEvent.deleteView(String viewId) = _DeleteView;
const factory DatabaseTabBarEvent.didUpdateChildViews(
ChildViewUpdatePB updatePB,
) = _DidUpdateChildViews;
const factory DatabaseTabBarEvent.viewDidUpdate(ViewPB view) = _ViewDidUpdate;
}
@freezed
class DatabaseTabBarState with _$DatabaseTabBarState {
const factory DatabaseTabBarState({
required ViewPB parentView,
required int selectedIndex,
required List<DatabaseTabBar> tabBars,
required Map<String, DatabaseTabBarController> tabBarControllerByViewId,
}) = _DatabaseTabBarState;
factory DatabaseTabBarState.initial(ViewPB view) {
final tabBar = DatabaseTabBar(view: view);
return DatabaseTabBarState(
parentView: view,
selectedIndex: 0,
tabBars: [tabBar],
tabBarControllerByViewId: {
view.id: DatabaseTabBarController(
view: view,
),
},
);
}
}
class DatabaseTabBar extends Equatable {
DatabaseTabBar({
required this.view,
}) : _builder = PlatformExtension.isMobile
? view.mobileTabBarItem()
: view.tabBarItem();
final ViewPB view;
final DatabaseTabBarItemBuilder _builder;
String get viewId => view.id;
DatabaseTabBarItemBuilder get builder => _builder;
ViewLayoutPB get layout => view.layout;
@override
List<Object?> get props => [view.hashCode];
void dispose() {
_builder.dispose();
}
}
typedef OnViewUpdated = void Function(ViewPB newView);
typedef OnViewChildViewChanged = void Function(
ChildViewUpdatePB childViewUpdate,
);
class DatabaseTabBarController {
DatabaseTabBarController({required this.view})
: controller = DatabaseController(view: view),
viewListener = ViewListener(viewId: view.id) {
viewListener.start(
onViewChildViewsUpdated: (update) => onViewChildViewChanged?.call(update),
onViewUpdated: (newView) {
view = newView;
onViewUpdated?.call(newView);
},
);
}
ViewPB view;
final DatabaseController controller;
final ViewListener viewListener;
OnViewUpdated? onViewUpdated;
OnViewChildViewChanged? onViewChildViewChanged;
Future<void> dispose() async {
await viewListener.stop();
await controller.dispose();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/share_bloc.dart | import 'dart:io';
import 'package:appflowy/workspace/application/settings/share/export_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-document/entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'share_bloc.freezed.dart';
class DatabaseShareBloc extends Bloc<DatabaseShareEvent, DatabaseShareState> {
DatabaseShareBloc({
required this.view,
}) : super(const DatabaseShareState.initial()) {
on<ShareCSV>(_onShareCSV);
}
final ViewPB view;
Future<void> _onShareCSV(
ShareCSV event,
Emitter<DatabaseShareState> emit,
) async {
emit(const DatabaseShareState.loading());
final result = await BackendExportService.exportDatabaseAsCSV(view.id);
result.fold(
(l) => _saveCSVToPath(l.data, event.path),
(r) => Log.error(r),
);
emit(
DatabaseShareState.finish(
result.fold(
(l) {
_saveCSVToPath(l.data, event.path);
return FlowyResult.success(null);
},
(r) => FlowyResult.failure(r),
),
),
);
}
ExportDataPB _saveCSVToPath(String markdown, String path) {
File(path).writeAsStringSync(markdown);
return ExportDataPB()
..data = markdown
..exportType = ExportType.Markdown;
}
}
@freezed
class DatabaseShareEvent with _$DatabaseShareEvent {
const factory DatabaseShareEvent.shareCSV(String path) = ShareCSV;
}
@freezed
class DatabaseShareState with _$DatabaseShareState {
const factory DatabaseShareState.initial() = _Initial;
const factory DatabaseShareState.loading() = _Loading;
const factory DatabaseShareState.finish(
FlowyResult<void, FlowyError> successOrFail,
) = _Finish;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/defines.dart | import 'dart:collection';
// TODO(RS): remove dependency on presentation code
import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/filter_info.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/sort_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'field/field_info.dart';
import 'row/row_cache.dart';
import 'row/row_service.dart';
part 'defines.freezed.dart';
typedef OnFieldsChanged = void Function(UnmodifiableListView<FieldInfo>);
typedef OnFiltersChanged = void Function(List<FilterInfo>);
typedef OnSortsChanged = void Function(List<SortInfo>);
typedef OnDatabaseChanged = void Function(DatabasePB);
typedef OnRowsCreated = void Function(List<RowId> rowIds);
typedef OnRowsUpdated = void Function(
List<RowId> rowIds,
ChangedReason reason,
);
typedef OnRowsDeleted = void Function(List<RowId> rowIds);
typedef OnNumOfRowsChanged = void Function(
UnmodifiableListView<RowInfo> rows,
UnmodifiableMapView<RowId, RowInfo> rowById,
ChangedReason reason,
);
typedef OnError = void Function(FlowyError);
@freezed
class LoadingState with _$LoadingState {
const factory LoadingState.idle() = _Idle;
const factory LoadingState.loading() = _Loading;
const factory LoadingState.finish(
FlowyResult<void, FlowyError> successOrFail,
) = _Finish;
const LoadingState._();
bool isLoading() => this is _Loading;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/view/view_cache.dart | import 'dart:async';
import 'dart:collection';
import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy_backend/log.dart';
import '../defines.dart';
import '../field/field_controller.dart';
import '../row/row_cache.dart';
import 'view_listener.dart';
class DatabaseViewCallbacks {
const DatabaseViewCallbacks({
this.onNumOfRowsChanged,
this.onRowsCreated,
this.onRowsUpdated,
this.onRowsDeleted,
});
/// Will get called when number of rows were changed that includes
/// update/delete/insert rows. The [onNumOfRowsChanged] will return all
/// the rows of the current database
final OnNumOfRowsChanged? onNumOfRowsChanged;
// Will get called when creating new rows
final OnRowsCreated? onRowsCreated;
/// Will get called when rows were updated
final OnRowsUpdated? onRowsUpdated;
/// Will get called when number of rows were deleted
final OnRowsDeleted? onRowsDeleted;
}
/// Read https://docs.appflowy.io/docs/documentation/software-contributions/architecture/frontend/frontend/grid for more information
class DatabaseViewCache {
DatabaseViewCache({
required this.viewId,
required FieldController fieldController,
}) : _databaseViewListener = DatabaseViewListener(viewId: viewId) {
final depsImpl = RowCacheDependenciesImpl(fieldController);
_rowCache = RowCache(
viewId: viewId,
fieldsDelegate: depsImpl,
rowLifeCycle: depsImpl,
);
_databaseViewListener.start(
onRowsChanged: (result) => result.fold(
(changeset) {
// Update the cache
_rowCache.applyRowsChanged(changeset);
if (changeset.deletedRows.isNotEmpty) {
for (final callback in _callbacks) {
callback.onRowsDeleted?.call(changeset.deletedRows);
}
}
if (changeset.updatedRows.isNotEmpty) {
for (final callback in _callbacks) {
callback.onRowsUpdated?.call(
changeset.updatedRows.map((e) => e.rowId).toList(),
_rowCache.changeReason,
);
}
}
if (changeset.insertedRows.isNotEmpty) {
for (final callback in _callbacks) {
callback.onRowsCreated?.call(
changeset.insertedRows
.map((insertedRow) => insertedRow.rowMeta.id)
.toList(),
);
}
}
},
(err) => Log.error(err),
),
onRowsVisibilityChanged: (result) => result.fold(
(changeset) => _rowCache.applyRowsVisibility(changeset),
(err) => Log.error(err),
),
onReorderAllRows: (result) => result.fold(
(rowIds) => _rowCache.reorderAllRows(rowIds),
(err) => Log.error(err),
),
onReorderSingleRow: (result) => result.fold(
(reorderRow) => _rowCache.reorderSingleRow(reorderRow),
(err) => Log.error(err),
),
);
_rowCache.onRowsChanged(
(reason) {
for (final callback in _callbacks) {
callback.onNumOfRowsChanged
?.call(rowInfos, _rowCache.rowByRowId, reason);
}
},
);
}
final String viewId;
late RowCache _rowCache;
final DatabaseViewListener _databaseViewListener;
final List<DatabaseViewCallbacks> _callbacks = [];
UnmodifiableListView<RowInfo> get rowInfos => _rowCache.rowInfos;
RowCache get rowCache => _rowCache;
RowInfo? getRow(RowId rowId) => _rowCache.getRow(rowId);
Future<void> dispose() async {
await _databaseViewListener.stop();
_rowCache.dispose();
_callbacks.clear();
}
void addListener(DatabaseViewCallbacks callbacks) {
_callbacks.add(callbacks);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/view/view_listener.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/view_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef RowsVisibilityNotifierValue
= FlowyResult<RowsVisibilityChangePB, FlowyError>;
typedef NumberOfRowsNotifierValue = FlowyResult<RowsChangePB, FlowyError>;
typedef ReorderAllRowsNotifierValue = FlowyResult<List<String>, FlowyError>;
typedef SingleRowNotifierValue = FlowyResult<ReorderSingleRowPB, FlowyError>;
class DatabaseViewListener {
DatabaseViewListener({required this.viewId});
final String viewId;
PublishNotifier<NumberOfRowsNotifierValue>? _rowsNotifier = PublishNotifier();
PublishNotifier<ReorderAllRowsNotifierValue>? _reorderAllRows =
PublishNotifier();
PublishNotifier<SingleRowNotifierValue>? _reorderSingleRow =
PublishNotifier();
PublishNotifier<RowsVisibilityNotifierValue>? _rowsVisibility =
PublishNotifier();
DatabaseNotificationListener? _listener;
void start({
required void Function(NumberOfRowsNotifierValue) onRowsChanged,
required void Function(ReorderAllRowsNotifierValue) onReorderAllRows,
required void Function(SingleRowNotifierValue) onReorderSingleRow,
required void Function(RowsVisibilityNotifierValue) onRowsVisibilityChanged,
}) {
if (_listener != null) {
_listener?.stop();
}
_listener = DatabaseNotificationListener(
objectId: viewId,
handler: _handler,
);
_rowsNotifier?.addPublishListener(onRowsChanged);
_rowsVisibility?.addPublishListener(onRowsVisibilityChanged);
_reorderAllRows?.addPublishListener(onReorderAllRows);
_reorderSingleRow?.addPublishListener(onReorderSingleRow);
}
void _handler(
DatabaseNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case DatabaseNotification.DidUpdateViewRowsVisibility:
result.fold(
(payload) => _rowsVisibility?.value =
FlowyResult.success(RowsVisibilityChangePB.fromBuffer(payload)),
(error) => _rowsVisibility?.value = FlowyResult.failure(error),
);
break;
case DatabaseNotification.DidUpdateViewRows:
result.fold(
(payload) => _rowsNotifier?.value =
FlowyResult.success(RowsChangePB.fromBuffer(payload)),
(error) => _rowsNotifier?.value = FlowyResult.failure(error),
);
break;
case DatabaseNotification.DidReorderRows:
result.fold(
(payload) => _reorderAllRows?.value = FlowyResult.success(
ReorderAllRowsPB.fromBuffer(payload).rowOrders,
),
(error) => _reorderAllRows?.value = FlowyResult.failure(error),
);
break;
case DatabaseNotification.DidReorderSingleRow:
result.fold(
(payload) => _reorderSingleRow?.value =
FlowyResult.success(ReorderSingleRowPB.fromBuffer(payload)),
(error) => _reorderSingleRow?.value = FlowyResult.failure(error),
);
break;
default:
break;
}
}
Future<void> stop() async {
await _listener?.stop();
_rowsVisibility?.dispose();
_rowsVisibility = null;
_rowsNotifier?.dispose();
_rowsNotifier = null;
_reorderAllRows?.dispose();
_reorderAllRows = null;
_reorderSingleRow?.dispose();
_reorderSingleRow = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/sync/database_sync_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/sync/database_sync_state_listener.dart';
import 'package:appflowy/plugins/database/domain/database_view_service.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'database_sync_bloc.freezed.dart';
class DatabaseSyncBloc extends Bloc<DatabaseSyncEvent, DatabaseSyncBlocState> {
DatabaseSyncBloc({
required this.view,
}) : super(DatabaseSyncBlocState.initial()) {
on<DatabaseSyncEvent>(
(event, emit) async {
await event.when(
initial: () async {
final userProfile = await getIt<AuthService>().getUser().then(
(value) => value.fold((s) => s, (f) => null),
);
final databaseId = await DatabaseViewBackendService(viewId: view.id)
.getDatabaseId()
.then((value) => value.fold((s) => s, (f) => null));
emit(
state.copyWith(
shouldShowIndicator: userProfile?.authenticator ==
AuthenticatorPB.AppFlowyCloud &&
databaseId != null,
),
);
if (databaseId != null) {
_syncStateListener =
DatabaseSyncStateListener(databaseId: databaseId)
..start(
didReceiveSyncState: (syncState) {
Log.info(
'database sync state changed, from ${state.syncState} to $syncState',
);
add(DatabaseSyncEvent.syncStateChanged(syncState));
},
);
}
final isNetworkConnected = await _connectivity
.checkConnectivity()
.then((value) => value != ConnectivityResult.none);
emit(state.copyWith(isNetworkConnected: isNetworkConnected));
connectivityStream =
_connectivity.onConnectivityChanged.listen((result) {
add(DatabaseSyncEvent.networkStateChanged(result));
});
},
syncStateChanged: (syncState) {
emit(state.copyWith(syncState: syncState.value));
},
networkStateChanged: (result) {
emit(
state.copyWith(
isNetworkConnected: result != ConnectivityResult.none,
),
);
},
);
},
);
}
final ViewPB view;
final _connectivity = Connectivity();
StreamSubscription? connectivityStream;
DatabaseSyncStateListener? _syncStateListener;
@override
Future<void> close() async {
await connectivityStream?.cancel();
await _syncStateListener?.stop();
return super.close();
}
}
@freezed
class DatabaseSyncEvent with _$DatabaseSyncEvent {
const factory DatabaseSyncEvent.initial() = Initial;
const factory DatabaseSyncEvent.syncStateChanged(
DatabaseSyncStatePB syncState,
) = syncStateChanged;
const factory DatabaseSyncEvent.networkStateChanged(
ConnectivityResult result,
) = NetworkStateChanged;
}
@freezed
class DatabaseSyncBlocState with _$DatabaseSyncBlocState {
const factory DatabaseSyncBlocState({
required DatabaseSyncState syncState,
@Default(true) bool isNetworkConnected,
@Default(false) bool shouldShowIndicator,
}) = _DatabaseSyncState;
factory DatabaseSyncBlocState.initial() => const DatabaseSyncBlocState(
syncState: DatabaseSyncState.Syncing,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/sync/database_sync_state_listener.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/subject.pb.dart';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
typedef DatabaseSyncStateCallback = void Function(
DatabaseSyncStatePB syncState,
);
class DatabaseSyncStateListener {
DatabaseSyncStateListener({
// NOTE: NOT the view id.
required this.databaseId,
});
final String databaseId;
StreamSubscription<SubscribeObject>? _subscription;
DatabaseNotificationParser? _parser;
DatabaseSyncStateCallback? didReceiveSyncState;
void start({
DatabaseSyncStateCallback? didReceiveSyncState,
}) {
this.didReceiveSyncState = didReceiveSyncState;
_parser = DatabaseNotificationParser(
id: databaseId,
callback: _callback,
);
_subscription = RustStreamReceiver.listen(
(observable) => _parser?.parse(observable),
);
}
void _callback(
DatabaseNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case DatabaseNotification.DidUpdateDatabaseSyncUpdate:
result.map(
(r) {
final value = DatabaseSyncStatePB.fromBuffer(r);
didReceiveSyncState?.call(value);
},
);
break;
default:
break;
}
}
Future<void> stop() async {
await _subscription?.cancel();
_subscription = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/setting/property_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/domain/field_service.dart';
import 'package:appflowy/plugins/database/domain/field_settings_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/field_settings_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'property_bloc.freezed.dart';
class DatabasePropertyBloc
extends Bloc<DatabasePropertyEvent, DatabasePropertyState> {
DatabasePropertyBloc({
required String viewId,
required FieldController fieldController,
}) : _fieldController = fieldController,
super(
DatabasePropertyState.initial(
viewId,
fieldController.fieldInfos,
),
) {
_dispatch();
}
final FieldController _fieldController;
Function(List<FieldInfo>)? _onFieldsFn;
@override
Future<void> close() async {
if (_onFieldsFn != null) {
_fieldController.removeListener(onFieldsListener: _onFieldsFn!);
_onFieldsFn = null;
}
return super.close();
}
void _dispatch() {
on<DatabasePropertyEvent>(
(event, emit) async {
await event.when(
initial: () {
_startListening();
},
setFieldVisibility: (fieldId, visibility) async {
final fieldSettingsSvc =
FieldSettingsBackendService(viewId: state.viewId);
final result = await fieldSettingsSvc.updateFieldSettings(
fieldId: fieldId,
fieldVisibility: visibility,
);
result.fold((l) => null, (err) => Log.error(err));
},
didReceiveFieldUpdate: (fields) {
emit(state.copyWith(fieldContexts: fields));
},
moveField: (fromIndex, toIndex) async {
if (fromIndex < toIndex) {
toIndex--;
}
final fromId = state.fieldContexts[fromIndex].field.id;
final toId = state.fieldContexts[toIndex].field.id;
final fieldContexts = List<FieldInfo>.from(state.fieldContexts);
fieldContexts.insert(toIndex, fieldContexts.removeAt(fromIndex));
emit(state.copyWith(fieldContexts: fieldContexts));
final result = await FieldBackendService.moveField(
viewId: state.viewId,
fromFieldId: fromId,
toFieldId: toId,
);
result.fold((l) => null, (r) => Log.error(r));
},
);
},
);
}
void _startListening() {
_onFieldsFn =
(fields) => add(DatabasePropertyEvent.didReceiveFieldUpdate(fields));
_fieldController.addListener(
onReceiveFields: _onFieldsFn,
listenWhen: () => !isClosed,
);
}
}
@freezed
class DatabasePropertyEvent with _$DatabasePropertyEvent {
const factory DatabasePropertyEvent.initial() = _Initial;
const factory DatabasePropertyEvent.setFieldVisibility(
String fieldId,
FieldVisibility visibility,
) = _SetFieldVisibility;
const factory DatabasePropertyEvent.didReceiveFieldUpdate(
List<FieldInfo> fields,
) = _DidReceiveFieldUpdate;
const factory DatabasePropertyEvent.moveField(int fromIndex, int toIndex) =
_MoveField;
}
@freezed
class DatabasePropertyState with _$DatabasePropertyState {
const factory DatabasePropertyState({
required String viewId,
required List<FieldInfo> fieldContexts,
}) = _GridPropertyState;
factory DatabasePropertyState.initial(
String viewId,
List<FieldInfo> fieldContexts,
) =>
DatabasePropertyState(
viewId: viewId,
fieldContexts: fieldContexts,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/setting/setting_listener.dart | import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef UpdateSettingNotifiedValue
= FlowyResult<DatabaseViewSettingPB, FlowyError>;
class DatabaseSettingListener {
DatabaseSettingListener({required this.viewId});
final String viewId;
DatabaseNotificationListener? _listener;
PublishNotifier<UpdateSettingNotifiedValue>? _updateSettingNotifier =
PublishNotifier();
void start({
required void Function(UpdateSettingNotifiedValue) onSettingUpdated,
}) {
_updateSettingNotifier?.addPublishListener(onSettingUpdated);
_listener =
DatabaseNotificationListener(objectId: viewId, handler: _handler);
}
void _handler(
DatabaseNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case DatabaseNotification.DidUpdateSettings:
result.fold(
(payload) => _updateSettingNotifier?.value = FlowyResult.success(
DatabaseViewSettingPB.fromBuffer(payload),
),
(error) => _updateSettingNotifier?.value = FlowyResult.failure(error),
);
break;
default:
break;
}
}
Future<void> stop() async {
await _listener?.stop();
_updateSettingNotifier?.dispose();
_updateSettingNotifier = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/setting/group_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/domain/group_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/board_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'group_bloc.freezed.dart';
class DatabaseGroupBloc extends Bloc<DatabaseGroupEvent, DatabaseGroupState> {
DatabaseGroupBloc({
required String viewId,
required DatabaseController databaseController,
}) : _databaseController = databaseController,
_groupBackendSvc = GroupBackendService(viewId),
super(
DatabaseGroupState.initial(
viewId,
databaseController.fieldController.fieldInfos,
databaseController.databaseLayoutSetting!.board,
),
) {
_dispatch();
}
final DatabaseController _databaseController;
final GroupBackendService _groupBackendSvc;
Function(List<FieldInfo>)? _onFieldsFn;
DatabaseLayoutSettingCallbacks? _layoutSettingCallbacks;
@override
Future<void> close() async {
if (_onFieldsFn != null) {
_databaseController.fieldController
.removeListener(onFieldsListener: _onFieldsFn!);
_onFieldsFn = null;
}
_layoutSettingCallbacks = null;
return super.close();
}
void _dispatch() {
on<DatabaseGroupEvent>(
(event, emit) async {
await event.when(
initial: () {
_startListening();
},
didReceiveFieldUpdate: (fieldInfos) {
emit(state.copyWith(fieldInfos: fieldInfos));
},
setGroupByField: (String fieldId, FieldType fieldType) async {
final result = await _groupBackendSvc.groupByField(
fieldId: fieldId,
);
result.fold((l) => null, (err) => Log.error(err));
},
didUpdateLayoutSettings: (layoutSettings) {
emit(state.copyWith(layoutSettings: layoutSettings));
},
);
},
);
}
void _startListening() {
_onFieldsFn = (fieldInfos) =>
add(DatabaseGroupEvent.didReceiveFieldUpdate(fieldInfos));
_databaseController.fieldController.addListener(
onReceiveFields: _onFieldsFn,
listenWhen: () => !isClosed,
);
_layoutSettingCallbacks = DatabaseLayoutSettingCallbacks(
onLayoutSettingsChanged: (layoutSettings) {
if (isClosed || !layoutSettings.hasBoard()) {
return;
}
add(
DatabaseGroupEvent.didUpdateLayoutSettings(layoutSettings.board),
);
},
);
_databaseController.addListener(
onLayoutSettingsChanged: _layoutSettingCallbacks,
);
}
}
@freezed
class DatabaseGroupEvent with _$DatabaseGroupEvent {
const factory DatabaseGroupEvent.initial() = _Initial;
const factory DatabaseGroupEvent.setGroupByField(
String fieldId,
FieldType fieldType,
) = _DatabaseGroupEvent;
const factory DatabaseGroupEvent.didReceiveFieldUpdate(
List<FieldInfo> fields,
) = _DidReceiveFieldUpdate;
const factory DatabaseGroupEvent.didUpdateLayoutSettings(
BoardLayoutSettingPB layoutSettings,
) = _DidUpdateLayoutSettings;
}
@freezed
class DatabaseGroupState with _$DatabaseGroupState {
const factory DatabaseGroupState({
required String viewId,
required List<FieldInfo> fieldInfos,
required BoardLayoutSettingPB layoutSettings,
}) = _DatabaseGroupState;
factory DatabaseGroupState.initial(
String viewId,
List<FieldInfo> fieldInfos,
BoardLayoutSettingPB layoutSettings,
) =>
DatabaseGroupState(
viewId: viewId,
fieldInfos: fieldInfos,
layoutSettings: layoutSettings,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/setting/setting_service.dart | import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/database_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
class SettingBackendService {
const SettingBackendService({required this.viewId});
final String viewId;
Future<FlowyResult<DatabaseViewSettingPB, FlowyError>> getSetting() {
final payload = DatabaseViewIdPB.create()..value = viewId;
return DatabaseEventGetDatabaseSetting(payload).send();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/cell_controller_builder.dart | import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'cell_controller.dart';
import 'cell_data_loader.dart';
import 'cell_data_persistence.dart';
typedef TextCellController = CellController<String, String>;
typedef CheckboxCellController = CellController<CheckboxCellDataPB, String>;
typedef NumberCellController = CellController<String, String>;
typedef SelectOptionCellController
= CellController<SelectOptionCellDataPB, String>;
typedef ChecklistCellController = CellController<ChecklistCellDataPB, String>;
typedef DateCellController = CellController<DateCellDataPB, String>;
typedef TimestampCellController = CellController<TimestampCellDataPB, String>;
typedef URLCellController = CellController<URLCellDataPB, String>;
typedef RelationCellController = CellController<RelationCellDataPB, String>;
CellController makeCellController(
DatabaseController databaseController,
CellContext cellContext,
) {
final DatabaseController(:viewId, :rowCache, :fieldController) =
databaseController;
final fieldType = fieldController.getField(cellContext.fieldId)!.fieldType;
switch (fieldType) {
case FieldType.Checkbox:
return CheckboxCellController(
viewId: viewId,
fieldController: fieldController,
cellContext: cellContext,
rowCache: rowCache,
cellDataLoader: CellDataLoader(
parser: CheckboxCellDataParser(),
),
cellDataPersistence: TextCellDataPersistence(),
);
case FieldType.DateTime:
return DateCellController(
viewId: viewId,
fieldController: fieldController,
cellContext: cellContext,
rowCache: rowCache,
cellDataLoader: CellDataLoader(
parser: DateCellDataParser(),
reloadOnFieldChange: true,
),
cellDataPersistence: TextCellDataPersistence(),
);
case FieldType.LastEditedTime:
case FieldType.CreatedTime:
return TimestampCellController(
viewId: viewId,
fieldController: fieldController,
cellContext: cellContext,
rowCache: rowCache,
cellDataLoader: CellDataLoader(
parser: TimestampCellDataParser(),
reloadOnFieldChange: true,
),
cellDataPersistence: TextCellDataPersistence(),
);
case FieldType.Number:
return NumberCellController(
viewId: viewId,
fieldController: fieldController,
cellContext: cellContext,
rowCache: rowCache,
cellDataLoader: CellDataLoader(
parser: NumberCellDataParser(),
reloadOnFieldChange: true,
),
cellDataPersistence: TextCellDataPersistence(),
);
case FieldType.RichText:
return TextCellController(
viewId: viewId,
fieldController: fieldController,
cellContext: cellContext,
rowCache: rowCache,
cellDataLoader: CellDataLoader(
parser: StringCellDataParser(),
),
cellDataPersistence: TextCellDataPersistence(),
);
case FieldType.MultiSelect:
case FieldType.SingleSelect:
return SelectOptionCellController(
viewId: viewId,
fieldController: fieldController,
cellContext: cellContext,
rowCache: rowCache,
cellDataLoader: CellDataLoader(
parser: SelectOptionCellDataParser(),
reloadOnFieldChange: true,
),
cellDataPersistence: TextCellDataPersistence(),
);
case FieldType.Checklist:
return ChecklistCellController(
viewId: viewId,
fieldController: fieldController,
cellContext: cellContext,
rowCache: rowCache,
cellDataLoader: CellDataLoader(
parser: ChecklistCellDataParser(),
reloadOnFieldChange: true,
),
cellDataPersistence: TextCellDataPersistence(),
);
case FieldType.URL:
return URLCellController(
viewId: viewId,
fieldController: fieldController,
cellContext: cellContext,
rowCache: rowCache,
cellDataLoader: CellDataLoader(
parser: URLCellDataParser(),
),
cellDataPersistence: TextCellDataPersistence(),
);
case FieldType.Relation:
return RelationCellController(
viewId: viewId,
fieldController: fieldController,
cellContext: cellContext,
rowCache: rowCache,
cellDataLoader: CellDataLoader(
parser: RelationCellDataParser(),
reloadOnFieldChange: true,
),
cellDataPersistence: TextCellDataPersistence(),
);
}
throw UnimplementedError;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/cell_controller.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/domain/cell_listener.dart';
import 'package:appflowy/plugins/database/application/field/type_option/type_option_data_parser.dart';
import 'package:appflowy/plugins/database/application/row/row_cache.dart';
import 'package:appflowy/plugins/database/domain/row_meta_listener.dart';
import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'cell_cache.dart';
import 'cell_data_loader.dart';
import 'cell_data_persistence.dart';
part 'cell_controller.freezed.dart';
@freezed
class CellContext with _$CellContext {
const factory CellContext({
required String fieldId,
required RowId rowId,
}) = _DatabaseCellContext;
}
/// [CellController] is used to manipulate the cell and receive notifications.
/// The cell data is stored in the [RowCache]'s [CellMemCache].
///
/// * Read/write cell data
/// * Listen on field/cell notifications.
///
/// T represents the type of the cell data.
/// D represents the type of data that will be saved to the disk.
class CellController<T, D> {
CellController({
required this.viewId,
required FieldController fieldController,
required CellContext cellContext,
required RowCache rowCache,
required CellDataLoader<T> cellDataLoader,
required CellDataPersistence<D> cellDataPersistence,
}) : _fieldController = fieldController,
_cellContext = cellContext,
_rowCache = rowCache,
_cellDataLoader = cellDataLoader,
_cellDataPersistence = cellDataPersistence,
_cellDataNotifier =
CellDataNotifier(value: rowCache.cellCache.get(cellContext)) {
_startListening();
}
final String viewId;
final FieldController _fieldController;
final CellContext _cellContext;
final RowCache _rowCache;
final CellDataLoader<T> _cellDataLoader;
final CellDataPersistence<D> _cellDataPersistence;
CellListener? _cellListener;
RowMetaListener? _rowMetaListener;
CellDataNotifier<T?>? _cellDataNotifier;
VoidCallback? _onRowMetaChanged;
Timer? _loadDataOperation;
Timer? _saveDataOperation;
RowId get rowId => _cellContext.rowId;
String get fieldId => _cellContext.fieldId;
FieldInfo get fieldInfo => _fieldController.getField(_cellContext.fieldId)!;
FieldType get fieldType =>
_fieldController.getField(_cellContext.fieldId)!.fieldType;
RowMetaPB? get rowMeta => _rowCache.getRow(rowId)?.rowMeta;
String? get icon => rowMeta?.icon;
CellMemCache get _cellCache => _rowCache.cellCache;
/// casting method for painless type coersion
CellController<A, B> as<A, B>() => this as CellController<A, B>;
/// Start listening to backend changes
void _startListening() {
_cellListener = CellListener(
rowId: _cellContext.rowId,
fieldId: _cellContext.fieldId,
);
// 1. Listen on user edit event and load the new cell data if needed.
// For example:
// user input: 12
// cell display: $12
_cellListener?.start(
onCellChanged: (result) {
result.fold(
(_) => _loadData(),
(err) => Log.error(err),
);
},
);
// 2. Listen on the field event and load the cell data if needed.
_fieldController.addSingleFieldListener(
fieldId,
onFieldChanged: _onFieldChangedListener,
);
// 3. If the field is primary listen to row meta changes.
if (fieldInfo.field.isPrimary) {
_rowMetaListener = RowMetaListener(_cellContext.rowId);
_rowMetaListener?.start(
callback: (newRowMeta) {
_onRowMetaChanged?.call();
},
);
}
}
/// Add a new listener
VoidCallback? addListener({
required void Function(T?) onCellChanged,
void Function(FieldInfo fieldInfo)? onFieldChanged,
VoidCallback? onRowMetaChanged,
}) {
/// an adaptor for the onCellChanged listener
void onCellChangedFn() => onCellChanged(_cellDataNotifier?.value);
_cellDataNotifier?.addListener(onCellChangedFn);
if (onFieldChanged != null) {
_fieldController.addSingleFieldListener(
fieldId,
onFieldChanged: onFieldChanged,
);
}
_onRowMetaChanged = onRowMetaChanged;
// Return the function pointer that can be used when calling removeListener.
return onCellChangedFn;
}
void removeListener({
required VoidCallback onCellChanged,
void Function(FieldInfo fieldInfo)? onFieldChanged,
VoidCallback? onRowMetaChanged,
}) {
_cellDataNotifier?.removeListener(onCellChanged);
if (onFieldChanged != null) {
_fieldController.removeSingleFieldListener(
fieldId: fieldId,
onFieldChanged: onFieldChanged,
);
}
}
void _onFieldChangedListener(FieldInfo fieldInfo) {
// reloadOnFieldChanged should be true if you want to reload the cell
// data when the corresponding field is changed.
// For example:
// ¥12 -> $12
if (_cellDataLoader.reloadOnFieldChange) {
_loadData();
}
}
/// Get the cell data. The cell data will be read from the cache first,
/// and load from disk if it doesn't exist. You can set [loadIfNotExist] to
/// false to disable this behavior.
T? getCellData({bool loadIfNotExist = true}) {
final T? data = _cellCache.get(_cellContext);
if (data == null && loadIfNotExist) {
_loadData();
}
return data;
}
/// Return the TypeOptionPB that can be parsed into corresponding class using the [parser].
/// [PD] is the type that the parser return.
PD getTypeOption<PD>(TypeOptionParser parser) {
return parser.fromBuffer(fieldInfo.field.typeOptionData);
}
/// Saves the cell data to disk. You can set [debounce] to reduce the amount
/// of save operations, which is useful when editing a [TextField].
Future<void> saveCellData(
D data, {
bool debounce = false,
void Function(FlowyError?)? onFinish,
}) async {
_loadDataOperation?.cancel();
if (debounce) {
_saveDataOperation?.cancel();
_saveDataOperation = Timer(const Duration(milliseconds: 300), () async {
final result = await _cellDataPersistence.save(
viewId: viewId,
cellContext: _cellContext,
data: data,
);
onFinish?.call(result);
});
} else {
final result = await _cellDataPersistence.save(
viewId: viewId,
cellContext: _cellContext,
data: data,
);
onFinish?.call(result);
}
}
void _loadData() {
_saveDataOperation?.cancel();
_loadDataOperation?.cancel();
_loadDataOperation = Timer(const Duration(milliseconds: 10), () {
_cellDataLoader
.loadData(viewId: viewId, cellContext: _cellContext)
.then((data) {
if (data != null) {
_cellCache.insert(_cellContext, data);
} else {
_cellCache.remove(_cellContext);
}
_cellDataNotifier?.value = data;
});
});
}
Future<void> dispose() async {
await _rowMetaListener?.stop();
_rowMetaListener = null;
await _cellListener?.stop();
_cellListener = null;
_fieldController.removeSingleFieldListener(
fieldId: fieldId,
onFieldChanged: _onFieldChangedListener,
);
_loadDataOperation?.cancel();
_saveDataOperation?.cancel();
_cellDataNotifier?.dispose();
_cellDataNotifier = null;
_onRowMetaChanged = null;
}
}
class CellDataNotifier<T> extends ChangeNotifier {
CellDataNotifier({required T value, this.listenWhen}) : _value = value;
T _value;
bool Function(T? oldValue, T? newValue)? listenWhen;
set value(T newValue) {
if (listenWhen?.call(_value, newValue) ?? false) {
_value = newValue;
notifyListeners();
} else {
if (_value != newValue) {
_value = newValue;
notifyListeners();
}
}
}
T get value => _value;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/cell_cache.dart | import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'cell_controller.dart';
/// CellMemCache is used to cache cell data of each block.
/// We use CellContext to index the cell in the cache.
/// Read https://docs.appflowy.io/docs/documentation/software-contributions/architecture/frontend/frontend/grid
/// for more information
class CellMemCache {
CellMemCache();
/// fieldId: {rowId: cellData}
final Map<String, Map<RowId, dynamic>> _cellByFieldId = {};
void removeCellWithFieldId(String fieldId) {
_cellByFieldId.remove(fieldId);
}
void remove(CellContext context) {
_cellByFieldId[context.fieldId]?.remove(context.rowId);
}
void insert<T>(CellContext context, T data) {
_cellByFieldId.putIfAbsent(context.fieldId, () => {});
_cellByFieldId[context.fieldId]![context.rowId] = data;
}
T? get<T>(CellContext context) {
final value = _cellByFieldId[context.fieldId]?[context.rowId];
return value is T ? value : null;
}
void dispose() {
_cellByFieldId.clear();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/cell_data_loader.dart | import 'dart:convert';
import 'package:appflowy/plugins/database/domain/cell_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'cell_controller.dart';
abstract class IGridCellDataConfig {
// The cell data will reload if it receives the field's change notification.
bool get reloadOnFieldChanged;
}
abstract class CellDataParser<T> {
T? parserData(List<int> data);
}
class CellDataLoader<T> {
CellDataLoader({
required this.parser,
this.reloadOnFieldChange = false,
});
final CellDataParser<T> parser;
/// Reload the cell data if the field is changed.
final bool reloadOnFieldChange;
Future<T?> loadData({
required String viewId,
required CellContext cellContext,
}) {
return CellBackendService.getCell(
viewId: viewId,
cellContext: cellContext,
).then(
(result) => result.fold(
(CellPB cell) {
try {
return parser.parserData(cell.data);
} catch (e, s) {
Log.error('$parser parser cellData failed, $e');
Log.error('Stack trace \n $s');
return null;
}
},
(err) {
Log.error(err);
return null;
},
),
);
}
}
class StringCellDataParser implements CellDataParser<String> {
@override
String? parserData(List<int> data) {
final s = utf8.decode(data);
return s;
}
}
class CheckboxCellDataParser implements CellDataParser<CheckboxCellDataPB> {
@override
CheckboxCellDataPB? parserData(List<int> data) {
if (data.isEmpty) {
return null;
}
return CheckboxCellDataPB.fromBuffer(data);
}
}
class NumberCellDataParser implements CellDataParser<String> {
@override
String? parserData(List<int> data) {
return utf8.decode(data);
}
}
class DateCellDataParser implements CellDataParser<DateCellDataPB> {
@override
DateCellDataPB? parserData(List<int> data) {
if (data.isEmpty) {
return null;
}
return DateCellDataPB.fromBuffer(data);
}
}
class TimestampCellDataParser implements CellDataParser<TimestampCellDataPB> {
@override
TimestampCellDataPB? parserData(List<int> data) {
if (data.isEmpty) {
return null;
}
return TimestampCellDataPB.fromBuffer(data);
}
}
class SelectOptionCellDataParser
implements CellDataParser<SelectOptionCellDataPB> {
@override
SelectOptionCellDataPB? parserData(List<int> data) {
if (data.isEmpty) {
return null;
}
return SelectOptionCellDataPB.fromBuffer(data);
}
}
class ChecklistCellDataParser implements CellDataParser<ChecklistCellDataPB> {
@override
ChecklistCellDataPB? parserData(List<int> data) {
if (data.isEmpty) {
return null;
}
return ChecklistCellDataPB.fromBuffer(data);
}
}
class URLCellDataParser implements CellDataParser<URLCellDataPB> {
@override
URLCellDataPB? parserData(List<int> data) {
if (data.isEmpty) {
return null;
}
return URLCellDataPB.fromBuffer(data);
}
}
class RelationCellDataParser implements CellDataParser<RelationCellDataPB> {
@override
RelationCellDataPB? parserData(List<int> data) {
return data.isEmpty ? null : RelationCellDataPB.fromBuffer(data);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/cell_data_persistence.dart | import 'package:appflowy/plugins/database/domain/cell_service.dart';
import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart';
import 'cell_controller.dart';
/// Save the cell data to disk
/// You can extend this class to do custom operations.
abstract class CellDataPersistence<D> {
Future<FlowyError?> save({
required String viewId,
required CellContext cellContext,
required D data,
});
}
class TextCellDataPersistence implements CellDataPersistence<String> {
TextCellDataPersistence();
@override
Future<FlowyError?> save({
required String viewId,
required CellContext cellContext,
required String data,
}) async {
final fut = CellBackendService.updateCell(
viewId: viewId,
cellContext: cellContext,
data: data,
);
return fut.then((result) {
return result.fold(
(l) => null,
(err) => err,
);
});
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/url_cell_bloc.dart | import 'dart:async';
import 'dart:io';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/url_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'url_cell_bloc.freezed.dart';
class URLCellBloc extends Bloc<URLCellEvent, URLCellState> {
URLCellBloc({
required this.cellController,
}) : super(URLCellState.initial(cellController)) {
_dispatch();
_startListening();
}
final URLCellController cellController;
void Function()? _onCellChangedFn;
@override
Future<void> close() async {
if (_onCellChangedFn != null) {
cellController.removeListener(
onCellChanged: _onCellChangedFn!,
onFieldChanged: _onFieldChangedListener,
);
}
await cellController.dispose();
return super.close();
}
void _dispatch() {
on<URLCellEvent>(
(event, emit) async {
await event.when(
didUpdateCell: (cellData) async {
final content = cellData?.content ?? "";
final isValid = await _isUrlValid(content);
emit(
state.copyWith(
content: content,
isValid: isValid,
),
);
},
didUpdateField: (fieldInfo) {
final wrap = fieldInfo.wrapCellContent;
if (wrap != null) {
emit(state.copyWith(wrap: wrap));
}
},
updateURL: (String url) {
cellController.saveCellData(url, debounce: true);
},
);
},
);
}
void _startListening() {
_onCellChangedFn = cellController.addListener(
onCellChanged: (cellData) {
if (!isClosed) {
add(URLCellEvent.didUpdateCell(cellData));
}
},
onFieldChanged: _onFieldChangedListener,
);
}
void _onFieldChangedListener(FieldInfo fieldInfo) {
if (!isClosed) {
add(URLCellEvent.didUpdateField(fieldInfo));
}
}
Future<bool> _isUrlValid(String content) async {
if (content.isEmpty) {
return true;
}
try {
// check protocol is provided
const linkPrefix = [
'http://',
'https://',
];
final shouldAddScheme =
!linkPrefix.any((pattern) => content.startsWith(pattern));
final url = shouldAddScheme ? 'http://$content' : content;
// get hostname and check validity
final uri = Uri.parse(url);
final hostName = uri.host;
await InternetAddress.lookup(hostName);
} catch (_) {
return false;
}
return true;
}
}
@freezed
class URLCellEvent with _$URLCellEvent {
const factory URLCellEvent.updateURL(String url) = _UpdateURL;
const factory URLCellEvent.didUpdateCell(URLCellDataPB? cell) =
_DidUpdateCell;
const factory URLCellEvent.didUpdateField(FieldInfo fieldInfo) =
_DidUpdateField;
}
@freezed
class URLCellState with _$URLCellState {
const factory URLCellState({
required String content,
required bool isValid,
required bool wrap,
}) = _URLCellState;
factory URLCellState.initial(URLCellController cellController) {
final cellData = cellController.getCellData();
final wrap = cellController.fieldInfo.wrapCellContent;
return URLCellState(
content: cellData?.content ?? "",
isValid: true,
wrap: wrap ?? true,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/date_cell_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'date_cell_bloc.freezed.dart';
class DateCellBloc extends Bloc<DateCellEvent, DateCellState> {
DateCellBloc({required this.cellController})
: super(DateCellState.initial(cellController)) {
_dispatch();
_startListening();
}
final DateCellController cellController;
void Function()? _onCellChangedFn;
@override
Future<void> close() async {
if (_onCellChangedFn != null) {
cellController.removeListener(
onCellChanged: _onCellChangedFn!,
onFieldChanged: _onFieldChangedListener,
);
}
await cellController.dispose();
return super.close();
}
void _dispatch() {
on<DateCellEvent>(
(event, emit) async {
event.when(
didReceiveCellUpdate: (DateCellDataPB? cellData) {
emit(
state.copyWith(
data: cellData,
dateStr: _dateStrFromCellData(cellData),
),
);
},
didUpdateField: (fieldInfo) {
emit(state.copyWith(fieldInfo: fieldInfo));
},
);
},
);
}
void _startListening() {
_onCellChangedFn = cellController.addListener(
onCellChanged: (data) {
if (!isClosed) {
add(DateCellEvent.didReceiveCellUpdate(data));
}
},
onFieldChanged: _onFieldChangedListener,
);
}
void _onFieldChangedListener(FieldInfo fieldInfo) {
if (!isClosed) {
add(DateCellEvent.didUpdateField(fieldInfo));
}
}
}
@freezed
class DateCellEvent with _$DateCellEvent {
const factory DateCellEvent.didReceiveCellUpdate(DateCellDataPB? data) =
_DidReceiveCellUpdate;
const factory DateCellEvent.didUpdateField(FieldInfo fieldInfo) =
_DidUpdateField;
}
@freezed
class DateCellState with _$DateCellState {
const factory DateCellState({
required DateCellDataPB? data,
required String dateStr,
required FieldInfo fieldInfo,
}) = _DateCellState;
factory DateCellState.initial(DateCellController context) {
final cellData = context.getCellData();
return DateCellState(
fieldInfo: context.fieldInfo,
data: cellData,
dateStr: _dateStrFromCellData(cellData),
);
}
}
String _dateStrFromCellData(DateCellDataPB? cellData) {
if (cellData == null || !cellData.hasTimestamp()) {
return "";
}
String dateStr = "";
if (cellData.isRange) {
if (cellData.includeTime) {
dateStr =
"${cellData.date} ${cellData.time} → ${cellData.endDate} ${cellData.endTime}";
} else {
dateStr = "${cellData.date} → ${cellData.endDate}";
}
} else {
if (cellData.includeTime) {
dateStr = "${cellData.date} ${cellData.time}";
} else {
dateStr = cellData.date;
}
}
return dateStr.trim();
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/select_option_cell_editor_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/application/field/type_option/select_type_option_actions.dart';
import 'package:appflowy/plugins/database/application/field/type_option/type_option_data_parser.dart';
import 'package:appflowy/plugins/database/domain/field_service.dart';
import 'package:appflowy/plugins/database/domain/select_option_cell_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:collection/collection.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'select_option_cell_editor_bloc.freezed.dart';
const String createSelectOptionSuggestionId =
"create_select_option_suggestion_id";
class SelectOptionCellEditorBloc
extends Bloc<SelectOptionCellEditorEvent, SelectOptionCellEditorState> {
SelectOptionCellEditorBloc({
required this.cellController,
}) : _selectOptionService = SelectOptionCellBackendService(
viewId: cellController.viewId,
fieldId: cellController.fieldId,
rowId: cellController.rowId,
),
_typeOptionAction = cellController.fieldType == FieldType.SingleSelect
? SingleSelectAction(
viewId: cellController.viewId,
fieldId: cellController.fieldId,
onTypeOptionUpdated: (typeOptionData) =>
FieldBackendService.updateFieldTypeOption(
viewId: cellController.viewId,
fieldId: cellController.fieldId,
typeOptionData: typeOptionData,
),
)
: MultiSelectAction(
viewId: cellController.viewId,
fieldId: cellController.fieldId,
onTypeOptionUpdated: (typeOptionData) =>
FieldBackendService.updateFieldTypeOption(
viewId: cellController.viewId,
fieldId: cellController.fieldId,
typeOptionData: typeOptionData,
),
),
super(SelectOptionCellEditorState.initial(cellController)) {
_dispatch();
_startListening();
final loadedOptions = _loadAllOptions(cellController);
add(SelectOptionCellEditorEvent.didUpdateOptions(loadedOptions));
}
final SelectOptionCellBackendService _selectOptionService;
final ISelectOptionAction _typeOptionAction;
final SelectOptionCellController cellController;
VoidCallback? _onCellChangedFn;
final List<SelectOptionPB> allOptions = [];
String filter = "";
void _dispatch() {
on<SelectOptionCellEditorEvent>(
(event, emit) async {
await event.when(
didUpdateCell: (selectedOptions) {
emit(state.copyWith(selectedOptions: selectedOptions));
},
didUpdateOptions: (options) {
allOptions
..clear()
..addAll(options);
final result = _getVisibleOptions(options);
emit(
state.copyWith(
options: result.options,
createSelectOptionSuggestion:
result.createSelectOptionSuggestion,
),
);
},
createOption: () async {
if (state.createSelectOptionSuggestion == null) {
return;
}
filter = "";
await _createOption(
name: state.createSelectOptionSuggestion!.name,
color: state.createSelectOptionSuggestion!.color,
);
emit(state.copyWith(clearFilter: true));
},
deleteOption: (option) async {
await _deleteOption([option]);
},
deleteAllOptions: () async {
if (allOptions.isNotEmpty) {
await _deleteOption(allOptions);
}
},
updateOption: (option) async {
await _updateOption(option);
},
selectOption: (optionId) async {
await _selectOptionService.select(optionIds: [optionId]);
},
unSelectOption: (optionId) async {
await _selectOptionService.unSelect(optionIds: [optionId]);
},
unSelectLastOption: () async {
if (state.selectedOptions.isEmpty) {
return;
}
final lastSelectedOptionId = state.selectedOptions.last.id;
await _selectOptionService
.unSelect(optionIds: [lastSelectedOptionId]);
},
submitTextField: () {
_submitTextFieldValue(emit);
},
selectMultipleOptions: (optionNames, remainder) {
if (optionNames.isNotEmpty) {
_selectMultipleOptions(optionNames);
}
_filterOption(remainder, emit);
},
reorderOption: (fromOptionId, toOptionId) {
final options = _typeOptionAction.reorderOption(
allOptions,
fromOptionId,
toOptionId,
);
allOptions
..clear()
..addAll(options);
final result = _getVisibleOptions(options);
emit(state.copyWith(options: result.options));
},
filterOption: (filterText) {
_filterOption(filterText, emit);
},
focusPreviousOption: () {
_focusOption(true, emit);
},
focusNextOption: () {
_focusOption(false, emit);
},
updateFocusedOption: (optionId) {
emit(state.copyWith(focusedOptionId: optionId));
},
resetClearFilterFlag: () {
emit(state.copyWith(clearFilter: false));
},
);
},
);
}
@override
Future<void> close() async {
if (_onCellChangedFn != null) {
cellController.removeListener(
onCellChanged: _onCellChangedFn!,
onFieldChanged: _onFieldChangedListener,
);
}
return super.close();
}
void _startListening() {
_onCellChangedFn = cellController.addListener(
onCellChanged: (cellData) {
if (!isClosed) {
add(
SelectOptionCellEditorEvent.didUpdateCell(
cellData == null ? [] : cellData.selectOptions,
),
);
}
},
onFieldChanged: _onFieldChangedListener,
);
}
void _onFieldChangedListener(FieldInfo fieldInfo) {
if (!isClosed) {
final loadedOptions = _loadAllOptions(cellController);
add(SelectOptionCellEditorEvent.didUpdateOptions(loadedOptions));
}
}
Future<void> _createOption({
required String name,
required SelectOptionColorPB color,
}) async {
final result = await _selectOptionService.create(
name: name,
color: color,
);
result.fold((l) => {}, (err) => Log.error(err));
}
Future<void> _deleteOption(List<SelectOptionPB> options) async {
final result = await _selectOptionService.delete(options: options);
result.fold((l) => null, (err) => Log.error(err));
}
Future<void> _updateOption(SelectOptionPB option) async {
final result = await _selectOptionService.update(
option: option,
);
result.fold((l) => null, (err) => Log.error(err));
}
void _submitTextFieldValue(Emitter<SelectOptionCellEditorState> emit) {
if (state.focusedOptionId == null) {
return;
}
final focusedOptionId = state.focusedOptionId!;
if (focusedOptionId == createSelectOptionSuggestionId) {
filter = "";
_createOption(
name: state.createSelectOptionSuggestion!.name,
color: state.createSelectOptionSuggestion!.color,
);
emit(
state.copyWith(
createSelectOptionSuggestion: null,
clearFilter: true,
),
);
} else if (!state.selectedOptions
.any((option) => option.id == focusedOptionId)) {
_selectOptionService.select(optionIds: [focusedOptionId]);
}
}
void _selectMultipleOptions(List<String> optionNames) {
final optionIds = optionNames
.map(
(name) => allOptions.firstWhereOrNull(
(option) => option.name.toLowerCase() == name.toLowerCase(),
),
)
.nonNulls
.map((option) => option.id)
.toList();
_selectOptionService.select(optionIds: optionIds);
}
void _filterOption(
String filterText,
Emitter<SelectOptionCellEditorState> emit,
) {
filter = filterText;
final _MakeOptionResult result = _getVisibleOptions(
allOptions,
);
final focusedOptionId = result.options.isEmpty
? result.createSelectOptionSuggestion == null
? null
: createSelectOptionSuggestionId
: result.options.any((option) => option.id == state.focusedOptionId)
? state.focusedOptionId
: result.options.first.id;
emit(
state.copyWith(
options: result.options,
createSelectOptionSuggestion: result.createSelectOptionSuggestion,
focusedOptionId: focusedOptionId,
),
);
}
_MakeOptionResult _getVisibleOptions(
List<SelectOptionPB> allOptions,
) {
final List<SelectOptionPB> options = List.from(allOptions);
String newOptionName = filter;
if (filter.isNotEmpty) {
options.retainWhere((option) {
final name = option.name.toLowerCase();
final lFilter = filter.toLowerCase();
if (name == lFilter) {
newOptionName = "";
}
return name.contains(lFilter);
});
}
return _MakeOptionResult(
options: options,
createSelectOptionSuggestion: newOptionName.isEmpty
? null
: CreateSelectOptionSuggestion(
name: newOptionName,
color: newSelectOptionColor(allOptions),
),
);
}
void _focusOption(bool previous, Emitter<SelectOptionCellEditorState> emit) {
if (state.options.isEmpty && state.createSelectOptionSuggestion == null) {
return;
}
final optionIds = [
...state.options.map((e) => e.id),
if (state.createSelectOptionSuggestion != null)
createSelectOptionSuggestionId,
];
if (state.focusedOptionId == null) {
emit(
state.copyWith(
focusedOptionId: previous ? optionIds.last : optionIds.first,
),
);
return;
}
final currentIndex =
optionIds.indexWhere((id) => id == state.focusedOptionId);
final newIndex = currentIndex == -1
? 0
: (currentIndex + (previous ? -1 : 1)) % optionIds.length;
emit(state.copyWith(focusedOptionId: optionIds[newIndex]));
}
}
@freezed
class SelectOptionCellEditorEvent with _$SelectOptionCellEditorEvent {
const factory SelectOptionCellEditorEvent.didUpdateCell(
List<SelectOptionPB> selectedOptions,
) = _DidUpdateCell;
const factory SelectOptionCellEditorEvent.didUpdateOptions(
List<SelectOptionPB> options,
) = _DidUpdateOptions;
const factory SelectOptionCellEditorEvent.createOption() = _CreateOption;
const factory SelectOptionCellEditorEvent.selectOption(String optionId) =
_SelectOption;
const factory SelectOptionCellEditorEvent.unSelectOption(String optionId) =
_UnSelectOption;
const factory SelectOptionCellEditorEvent.unSelectLastOption() =
_UnSelectLastOption;
const factory SelectOptionCellEditorEvent.updateOption(
SelectOptionPB option,
) = _UpdateOption;
const factory SelectOptionCellEditorEvent.deleteOption(
SelectOptionPB option,
) = _DeleteOption;
const factory SelectOptionCellEditorEvent.deleteAllOptions() =
_DeleteAllOptions;
const factory SelectOptionCellEditorEvent.reorderOption(
String fromOptionId,
String toOptionId,
) = _ReorderOption;
const factory SelectOptionCellEditorEvent.filterOption(String filterText) =
_SelectOptionFilter;
const factory SelectOptionCellEditorEvent.submitTextField() =
_SubmitTextField;
const factory SelectOptionCellEditorEvent.selectMultipleOptions(
List<String> optionNames,
String remainder,
) = _SelectMultipleOptions;
const factory SelectOptionCellEditorEvent.focusPreviousOption() =
_FocusPreviousOption;
const factory SelectOptionCellEditorEvent.focusNextOption() =
_FocusNextOption;
const factory SelectOptionCellEditorEvent.updateFocusedOption(
String? optionId,
) = _UpdateFocusedOption;
const factory SelectOptionCellEditorEvent.resetClearFilterFlag() =
_ResetClearFilterFlag;
}
@freezed
class SelectOptionCellEditorState with _$SelectOptionCellEditorState {
const factory SelectOptionCellEditorState({
required List<SelectOptionPB> options,
required List<SelectOptionPB> selectedOptions,
required CreateSelectOptionSuggestion? createSelectOptionSuggestion,
required String? focusedOptionId,
required bool clearFilter,
}) = _SelectOptionEditorState;
factory SelectOptionCellEditorState.initial(
SelectOptionCellController cellController,
) {
final allOptions = _loadAllOptions(cellController);
final data = cellController.getCellData();
return SelectOptionCellEditorState(
options: allOptions,
selectedOptions: data?.selectOptions ?? [],
createSelectOptionSuggestion: null,
focusedOptionId: null,
clearFilter: false,
);
}
}
class _MakeOptionResult {
_MakeOptionResult({
required this.options,
required this.createSelectOptionSuggestion,
});
List<SelectOptionPB> options;
CreateSelectOptionSuggestion? createSelectOptionSuggestion;
}
class CreateSelectOptionSuggestion {
CreateSelectOptionSuggestion({
required this.name,
required this.color,
});
final String name;
final SelectOptionColorPB color;
}
List<SelectOptionPB> _loadAllOptions(
SelectOptionCellController cellController,
) {
if (cellController.fieldType == FieldType.SingleSelect) {
return cellController
.getTypeOption<SingleSelectTypeOptionPB>(
SingleSelectTypeOptionDataParser(),
)
.options;
} else {
return cellController
.getTypeOption<MultiSelectTypeOptionPB>(
MultiSelectTypeOptionDataParser(),
)
.options;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/relation_cell_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/application/field/type_option/relation_type_option_cubit.dart';
import 'package:appflowy/plugins/database/application/field/type_option/type_option_data_parser.dart';
import 'package:appflowy/plugins/database/domain/field_service.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:collection/collection.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'relation_cell_bloc.freezed.dart';
class RelationCellBloc extends Bloc<RelationCellEvent, RelationCellState> {
RelationCellBloc({required this.cellController})
: super(RelationCellState.initial(cellController)) {
_dispatch();
_startListening();
_init();
}
final RelationCellController cellController;
void Function()? _onCellChangedFn;
@override
Future<void> close() async {
if (_onCellChangedFn != null) {
cellController.removeListener(
onCellChanged: _onCellChangedFn!,
onFieldChanged: _onFieldChangedListener,
);
}
return super.close();
}
void _dispatch() {
on<RelationCellEvent>(
(event, emit) async {
await event.when(
didUpdateCell: (cellData) async {
if (cellData == null ||
cellData.rowIds.isEmpty ||
state.relatedDatabaseMeta == null) {
emit(state.copyWith(rows: const []));
return;
}
final payload = RepeatedRowIdPB(
databaseId: state.relatedDatabaseMeta!.databaseId,
rowIds: cellData.rowIds,
);
final result =
await DatabaseEventGetRelatedRowDatas(payload).send();
final rows = result.fold(
(data) => data.rows,
(err) {
Log.error(err);
return const <RelatedRowDataPB>[];
},
);
emit(state.copyWith(rows: rows));
},
didUpdateField: (FieldInfo fieldInfo) async {
final wrap = fieldInfo.wrapCellContent;
if (wrap != null) {
emit(state.copyWith(wrap: wrap));
}
final RelationTypeOptionPB typeOption =
cellController.getTypeOption(RelationTypeOptionDataParser());
if (typeOption.databaseId.isEmpty) {
return;
}
final meta = await _loadDatabaseMeta(typeOption.databaseId);
emit(state.copyWith(relatedDatabaseMeta: meta));
_loadCellData();
},
selectDatabaseId: (databaseId) async {
await _updateTypeOption(databaseId);
},
selectRow: (rowId) async {
await _handleSelectRow(rowId);
},
);
},
);
}
void _startListening() {
_onCellChangedFn = cellController.addListener(
onCellChanged: (data) {
if (!isClosed) {
add(RelationCellEvent.didUpdateCell(data));
}
},
onFieldChanged: _onFieldChangedListener,
);
}
void _onFieldChangedListener(FieldInfo fieldInfo) {
if (!isClosed) {
add(RelationCellEvent.didUpdateField(fieldInfo));
}
}
void _init() {
add(RelationCellEvent.didUpdateField(cellController.fieldInfo));
}
void _loadCellData() {
final cellData = cellController.getCellData();
if (!isClosed && cellData != null) {
add(RelationCellEvent.didUpdateCell(cellData));
}
}
Future<void> _handleSelectRow(String rowId) async {
final payload = RelationCellChangesetPB(
viewId: cellController.viewId,
cellId: CellIdPB(
viewId: cellController.viewId,
fieldId: cellController.fieldId,
rowId: cellController.rowId,
),
);
if (state.rows.any((row) => row.rowId == rowId)) {
payload.removedRowIds.add(rowId);
} else {
payload.insertedRowIds.add(rowId);
}
final result = await DatabaseEventUpdateRelationCell(payload).send();
result.fold((l) => null, (err) => Log.error(err));
}
Future<DatabaseMeta?> _loadDatabaseMeta(String databaseId) async {
final getDatabaseResult = await DatabaseEventGetDatabases().send();
final databaseMeta = getDatabaseResult.fold<DatabaseMetaPB?>(
(s) => s.items.firstWhereOrNull(
(metaPB) => metaPB.databaseId == databaseId,
),
(f) => null,
);
if (databaseMeta != null) {
final result =
await ViewBackendService.getView(databaseMeta.inlineViewId);
return result.fold(
(s) => DatabaseMeta(
databaseId: databaseId,
inlineViewId: databaseMeta.inlineViewId,
databaseName: s.name,
),
(f) => null,
);
}
return null;
}
Future<void> _updateTypeOption(String databaseId) async {
final newDateTypeOption = RelationTypeOptionPB(
databaseId: databaseId,
);
final result = await FieldBackendService.updateFieldTypeOption(
viewId: cellController.viewId,
fieldId: cellController.fieldInfo.id,
typeOptionData: newDateTypeOption.writeToBuffer(),
);
result.fold((s) => null, (err) => Log.error(err));
}
}
@freezed
class RelationCellEvent with _$RelationCellEvent {
const factory RelationCellEvent.didUpdateCell(RelationCellDataPB? data) =
_DidUpdateCell;
const factory RelationCellEvent.didUpdateField(FieldInfo fieldInfo) =
_DidUpdateField;
const factory RelationCellEvent.selectDatabaseId(
String databaseId,
) = _SelectDatabaseId;
const factory RelationCellEvent.selectRow(String rowId) = _SelectRowId;
}
@freezed
class RelationCellState with _$RelationCellState {
const factory RelationCellState({
required DatabaseMeta? relatedDatabaseMeta,
required List<RelatedRowDataPB> rows,
required bool wrap,
}) = _RelationCellState;
factory RelationCellState.initial(RelationCellController cellController) {
final wrap = cellController.fieldInfo.wrapCellContent;
return RelationCellState(
relatedDatabaseMeta: null,
rows: [],
wrap: wrap ?? true,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/checklist_cell_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/domain/checklist_cell_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/checklist_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'checklist_cell_bloc.freezed.dart';
class ChecklistSelectOption {
ChecklistSelectOption({required this.isSelected, required this.data});
final bool isSelected;
final SelectOptionPB data;
}
class ChecklistCellBloc extends Bloc<ChecklistCellEvent, ChecklistCellState> {
ChecklistCellBloc({required this.cellController})
: _checklistCellService = ChecklistCellBackendService(
viewId: cellController.viewId,
fieldId: cellController.fieldId,
rowId: cellController.rowId,
),
super(ChecklistCellState.initial(cellController)) {
_dispatch();
_startListening();
}
final ChecklistCellController cellController;
final ChecklistCellBackendService _checklistCellService;
void Function()? _onCellChangedFn;
@override
Future<void> close() async {
if (_onCellChangedFn != null) {
cellController.removeListener(onCellChanged: _onCellChangedFn!);
}
await cellController.dispose();
return super.close();
}
void _dispatch() {
on<ChecklistCellEvent>(
(event, emit) async {
await event.when(
didUpdateCell: (data) {
if (data == null) {
emit(
const ChecklistCellState(
tasks: [],
percent: 0,
newTask: false,
),
);
return;
}
emit(
state.copyWith(
tasks: _makeChecklistSelectOptions(data),
percent: data.percentage,
),
);
},
updateTaskName: (option, name) {
_updateOption(option, name);
},
selectTask: (id) async {
await _checklistCellService.select(optionId: id);
},
createNewTask: (name) async {
final result = await _checklistCellService.create(name: name);
result.fold(
(l) => emit(state.copyWith(newTask: true)),
(err) => Log.error(err),
);
},
deleteTask: (id) async {
await _deleteOption([id]);
},
);
},
);
}
void _startListening() {
_onCellChangedFn = cellController.addListener(
onCellChanged: (data) {
if (!isClosed) {
add(ChecklistCellEvent.didUpdateCell(data));
}
},
);
}
void _updateOption(SelectOptionPB option, String name) async {
final result =
await _checklistCellService.updateName(option: option, name: name);
result.fold((l) => null, (err) => Log.error(err));
}
Future<void> _deleteOption(List<String> options) async {
final result = await _checklistCellService.delete(optionIds: options);
result.fold((l) => null, (err) => Log.error(err));
}
}
@freezed
class ChecklistCellEvent with _$ChecklistCellEvent {
const factory ChecklistCellEvent.didUpdateCell(
ChecklistCellDataPB? data,
) = _DidUpdateCell;
const factory ChecklistCellEvent.updateTaskName(
SelectOptionPB option,
String name,
) = _UpdateTaskName;
const factory ChecklistCellEvent.selectTask(String taskId) = _SelectTask;
const factory ChecklistCellEvent.createNewTask(String description) =
_CreateNewTask;
const factory ChecklistCellEvent.deleteTask(String taskId) = _DeleteTask;
}
@freezed
class ChecklistCellState with _$ChecklistCellState {
const factory ChecklistCellState({
required List<ChecklistSelectOption> tasks,
required double percent,
required bool newTask,
}) = _ChecklistCellState;
factory ChecklistCellState.initial(ChecklistCellController cellController) {
final cellData = cellController.getCellData(loadIfNotExist: true);
return ChecklistCellState(
tasks: _makeChecklistSelectOptions(cellData),
percent: cellData?.percentage ?? 0,
newTask: false,
);
}
}
List<ChecklistSelectOption> _makeChecklistSelectOptions(
ChecklistCellDataPB? data,
) {
if (data == null) {
return [];
}
return data.options
.map(
(option) => ChecklistSelectOption(
isSelected: data.selectedOptions.any(
(selected) => selected.id == option.id,
),
data: option,
),
)
.toList();
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/number_cell_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'number_cell_bloc.freezed.dart';
class NumberCellBloc extends Bloc<NumberCellEvent, NumberCellState> {
NumberCellBloc({
required this.cellController,
}) : super(NumberCellState.initial(cellController)) {
_dispatch();
_startListening();
}
final NumberCellController cellController;
void Function()? _onCellChangedFn;
@override
Future<void> close() async {
if (_onCellChangedFn != null) {
cellController.removeListener(
onCellChanged: _onCellChangedFn!,
onFieldChanged: _onFieldChangedListener,
);
}
await cellController.dispose();
return super.close();
}
void _dispatch() {
on<NumberCellEvent>(
(event, emit) async {
await event.when(
didReceiveCellUpdate: (cellData) {
emit(state.copyWith(content: cellData ?? ""));
},
didUpdateField: (fieldInfo) {
final wrap = fieldInfo.wrapCellContent;
if (wrap != null) {
emit(state.copyWith(wrap: wrap));
}
},
updateCell: (text) async {
if (state.content != text) {
emit(state.copyWith(content: text));
await cellController.saveCellData(text);
// If the input content is "abc" that can't parsered as number then the data stored in the backend will be an empty string.
// So for every cell data that will be formatted in the backend.
// It needs to get the formatted data after saving.
add(
NumberCellEvent.didReceiveCellUpdate(
cellController.getCellData(),
),
);
}
},
);
},
);
}
void _startListening() {
_onCellChangedFn = cellController.addListener(
onCellChanged: (cellContent) {
if (!isClosed) {
add(NumberCellEvent.didReceiveCellUpdate(cellContent));
}
},
onFieldChanged: _onFieldChangedListener,
);
}
void _onFieldChangedListener(FieldInfo fieldInfo) {
if (!isClosed) {
add(NumberCellEvent.didUpdateField(fieldInfo));
}
}
}
@freezed
class NumberCellEvent with _$NumberCellEvent {
const factory NumberCellEvent.didReceiveCellUpdate(String? cellContent) =
_DidReceiveCellUpdate;
const factory NumberCellEvent.didUpdateField(FieldInfo fieldInfo) =
_DidUpdateField;
const factory NumberCellEvent.updateCell(String text) = _UpdateCell;
}
@freezed
class NumberCellState with _$NumberCellState {
const factory NumberCellState({
required String content,
required bool wrap,
}) = _NumberCellState;
factory NumberCellState.initial(TextCellController cellController) {
final wrap = cellController.fieldInfo.wrapCellContent;
return NumberCellState(
content: cellController.getCellData() ?? "",
wrap: wrap ?? true,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/timestamp_cell_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/timestamp_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'timestamp_cell_bloc.freezed.dart';
class TimestampCellBloc extends Bloc<TimestampCellEvent, TimestampCellState> {
TimestampCellBloc({
required this.cellController,
}) : super(TimestampCellState.initial(cellController)) {
_dispatch();
_startListening();
}
final TimestampCellController cellController;
void Function()? _onCellChangedFn;
@override
Future<void> close() async {
if (_onCellChangedFn != null) {
cellController.removeListener(
onCellChanged: _onCellChangedFn!,
onFieldChanged: _onFieldChangedListener,
);
}
await cellController.dispose();
return super.close();
}
void _dispatch() {
on<TimestampCellEvent>(
(event, emit) async {
event.when(
didReceiveCellUpdate: (TimestampCellDataPB? cellData) {
emit(
state.copyWith(
data: cellData,
dateStr: cellData?.dateTime ?? "",
),
);
},
didUpdateField: (fieldInfo) {
final wrap = fieldInfo.wrapCellContent;
if (wrap != null) {
emit(state.copyWith(wrap: wrap));
}
},
);
},
);
}
void _startListening() {
_onCellChangedFn = cellController.addListener(
onCellChanged: (data) {
if (!isClosed) {
add(TimestampCellEvent.didReceiveCellUpdate(data));
}
},
onFieldChanged: _onFieldChangedListener,
);
}
void _onFieldChangedListener(FieldInfo fieldInfo) {
if (!isClosed) {
add(TimestampCellEvent.didUpdateField(fieldInfo));
}
}
}
@freezed
class TimestampCellEvent with _$TimestampCellEvent {
const factory TimestampCellEvent.didReceiveCellUpdate(
TimestampCellDataPB? data,
) = _DidReceiveCellUpdate;
const factory TimestampCellEvent.didUpdateField(FieldInfo fieldInfo) =
_DidUpdateField;
}
@freezed
class TimestampCellState with _$TimestampCellState {
const factory TimestampCellState({
required TimestampCellDataPB? data,
required String dateStr,
required FieldInfo fieldInfo,
required bool wrap,
}) = _TimestampCellState;
factory TimestampCellState.initial(TimestampCellController cellController) {
final cellData = cellController.getCellData();
final wrap = cellController.fieldInfo.wrapCellContent;
return TimestampCellState(
fieldInfo: cellController.fieldInfo,
data: cellData,
dateStr: cellData?.dateTime ?? "",
wrap: wrap ?? true,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/checkbox_cell_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'checkbox_cell_bloc.freezed.dart';
class CheckboxCellBloc extends Bloc<CheckboxCellEvent, CheckboxCellState> {
CheckboxCellBloc({
required this.cellController,
}) : super(CheckboxCellState.initial(cellController)) {
_dispatch();
}
final CheckboxCellController cellController;
void Function()? _onCellChangedFn;
@override
Future<void> close() async {
if (_onCellChangedFn != null) {
cellController.removeListener(
onCellChanged: _onCellChangedFn!,
onFieldChanged: _onFieldChangedListener,
);
}
await cellController.dispose();
return super.close();
}
void _dispatch() {
on<CheckboxCellEvent>(
(event, emit) {
event.when(
initial: () => _startListening(),
didUpdateCell: (isSelected) {
emit(state.copyWith(isSelected: isSelected));
},
didUpdateField: (fieldName) {
emit(state.copyWith(fieldName: fieldName));
},
select: () {
cellController.saveCellData(state.isSelected ? "No" : "Yes");
},
);
},
);
}
void _startListening() {
_onCellChangedFn = cellController.addListener(
onCellChanged: (cellData) {
if (!isClosed) {
add(CheckboxCellEvent.didUpdateCell(_isSelected(cellData)));
}
},
onFieldChanged: _onFieldChangedListener,
);
}
void _onFieldChangedListener(FieldInfo fieldInfo) {
if (!isClosed) {
add(CheckboxCellEvent.didUpdateField(fieldInfo.name));
}
}
}
@freezed
class CheckboxCellEvent with _$CheckboxCellEvent {
const factory CheckboxCellEvent.initial() = _Initial;
const factory CheckboxCellEvent.select() = _Selected;
const factory CheckboxCellEvent.didUpdateCell(bool isSelected) =
_DidUpdateCell;
const factory CheckboxCellEvent.didUpdateField(String fieldName) =
_DidUpdateField;
}
@freezed
class CheckboxCellState with _$CheckboxCellState {
const factory CheckboxCellState({
required bool isSelected,
required String fieldName,
}) = _CheckboxCellState;
factory CheckboxCellState.initial(CheckboxCellController cellController) {
return CheckboxCellState(
isSelected: _isSelected(cellController.getCellData()),
fieldName: cellController.fieldInfo.field.name,
);
}
}
bool _isSelected(CheckboxCellDataPB? cellData) {
return cellData != null && cellData.isChecked;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/select_option_cell_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'select_option_cell_bloc.freezed.dart';
class SelectOptionCellBloc
extends Bloc<SelectOptionCellEvent, SelectOptionCellState> {
SelectOptionCellBloc({
required this.cellController,
}) : super(SelectOptionCellState.initial(cellController)) {
_dispatch();
_startListening();
}
final SelectOptionCellController cellController;
void Function()? _onCellChangedFn;
@override
Future<void> close() async {
if (_onCellChangedFn != null) {
cellController.removeListener(
onCellChanged: _onCellChangedFn!,
onFieldChanged: _onFieldChangedListener,
);
}
await cellController.dispose();
return super.close();
}
void _dispatch() {
on<SelectOptionCellEvent>(
(event, emit) {
event.when(
didReceiveOptions: (List<SelectOptionPB> selectedOptions) {
emit(
state.copyWith(
selectedOptions: selectedOptions,
),
);
},
didUpdateField: (fieldInfo) {
final wrap = fieldInfo.wrapCellContent;
if (wrap != null) {
emit(state.copyWith(wrap: wrap));
}
},
);
},
);
}
void _startListening() {
_onCellChangedFn = cellController.addListener(
onCellChanged: (selectOptionCellData) {
if (!isClosed) {
add(
SelectOptionCellEvent.didReceiveOptions(
selectOptionCellData?.selectOptions ?? [],
),
);
}
},
onFieldChanged: _onFieldChangedListener,
);
}
void _onFieldChangedListener(FieldInfo fieldInfo) {
if (!isClosed) {
add(SelectOptionCellEvent.didUpdateField(fieldInfo));
}
}
}
@freezed
class SelectOptionCellEvent with _$SelectOptionCellEvent {
const factory SelectOptionCellEvent.didReceiveOptions(
List<SelectOptionPB> selectedOptions,
) = _DidReceiveOptions;
const factory SelectOptionCellEvent.didUpdateField(FieldInfo fieldInfo) =
_DidUpdateField;
}
@freezed
class SelectOptionCellState with _$SelectOptionCellState {
const factory SelectOptionCellState({
required List<SelectOptionPB> selectedOptions,
required bool wrap,
}) = _SelectOptionCellState;
factory SelectOptionCellState.initial(
SelectOptionCellController cellController,
) {
final data = cellController.getCellData();
final wrap = cellController.fieldInfo.wrapCellContent;
return SelectOptionCellState(
selectedOptions: data?.selectOptions ?? [],
wrap: wrap ?? true,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/text_cell_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'text_cell_bloc.freezed.dart';
class TextCellBloc extends Bloc<TextCellEvent, TextCellState> {
TextCellBloc({required this.cellController})
: super(TextCellState.initial(cellController)) {
_dispatch();
_startListening();
}
final TextCellController cellController;
void Function()? _onCellChangedFn;
@override
Future<void> close() async {
if (_onCellChangedFn != null) {
cellController.removeListener(
onCellChanged: _onCellChangedFn!,
onFieldChanged: _onFieldChangedListener,
);
}
await cellController.dispose();
return super.close();
}
void _dispatch() {
on<TextCellEvent>(
(event, emit) {
event.when(
didReceiveCellUpdate: (String content) {
emit(state.copyWith(content: content));
},
didUpdateField: (fieldInfo) {
final wrap = fieldInfo.wrapCellContent;
if (wrap != null) {
emit(state.copyWith(wrap: wrap));
}
},
didUpdateEmoji: (String emoji) {
emit(state.copyWith(emoji: emoji));
},
updateText: (String text) {
if (state.content != text) {
cellController.saveCellData(text, debounce: true);
}
},
enableEdit: (bool enabled) {
emit(state.copyWith(enableEdit: enabled));
},
);
},
);
}
void _startListening() {
_onCellChangedFn = cellController.addListener(
onCellChanged: (cellContent) {
if (!isClosed) {
add(TextCellEvent.didReceiveCellUpdate(cellContent ?? ""));
}
},
onFieldChanged: _onFieldChangedListener,
onRowMetaChanged: cellController.fieldInfo.isPrimary
? () {
if (!isClosed) {
add(TextCellEvent.didUpdateEmoji(cellController.icon ?? ""));
}
}
: null,
);
}
void _onFieldChangedListener(FieldInfo fieldInfo) {
if (!isClosed) {
add(TextCellEvent.didUpdateField(fieldInfo));
}
}
}
@freezed
class TextCellEvent with _$TextCellEvent {
const factory TextCellEvent.didReceiveCellUpdate(String cellContent) =
_DidReceiveCellUpdate;
const factory TextCellEvent.didUpdateField(FieldInfo fieldInfo) =
_DidUpdateField;
const factory TextCellEvent.updateText(String text) = _UpdateText;
const factory TextCellEvent.enableEdit(bool enabled) = _EnableEdit;
const factory TextCellEvent.didUpdateEmoji(String emoji) = _UpdateEmoji;
}
@freezed
class TextCellState with _$TextCellState {
const factory TextCellState({
required String content,
required String emoji,
required bool enableEdit,
required bool wrap,
}) = _TextCellState;
factory TextCellState.initial(TextCellController cellController) {
final cellData = cellController.getCellData() ?? "";
final wrap = cellController.fieldInfo.wrapCellContent ?? false;
final emoji =
cellController.fieldInfo.isPrimary ? cellController.icon ?? "" : "";
return TextCellState(
content: cellData,
emoji: emoji,
enableEdit: false,
wrap: wrap,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/relation_row_search_bloc.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:bloc/bloc.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'relation_row_search_bloc.freezed.dart';
class RelationRowSearchBloc
extends Bloc<RelationRowSearchEvent, RelationRowSearchState> {
RelationRowSearchBloc({
required this.databaseId,
}) : super(RelationRowSearchState.initial()) {
_dispatch();
_init();
}
final String databaseId;
final List<RelatedRowDataPB> allRows = [];
void _dispatch() {
on<RelationRowSearchEvent>(
(event, emit) {
event.when(
didUpdateRowList: (List<RelatedRowDataPB> rowList) {
allRows
..clear()
..addAll(rowList);
emit(
state.copyWith(
filteredRows: allRows,
focusedRowId: state.focusedRowId ?? allRows.firstOrNull?.rowId,
),
);
},
updateFilter: (String filter) => _updateFilter(filter, emit),
updateFocusedOption: (String rowId) {
emit(state.copyWith(focusedRowId: rowId));
},
focusPreviousOption: () => _focusOption(true, emit),
focusNextOption: () => _focusOption(false, emit),
);
},
);
}
Future<void> _init() async {
final payload = DatabaseIdPB(value: databaseId);
final result = await DatabaseEventGetRelatedDatabaseRows(payload).send();
result.fold(
(data) => add(RelationRowSearchEvent.didUpdateRowList(data.rows)),
(err) => Log.error(err),
);
}
void _updateFilter(String filter, Emitter<RelationRowSearchState> emit) {
final rows = [...allRows];
if (filter.isNotEmpty) {
rows.retainWhere(
(row) =>
row.name.toLowerCase().contains(filter.toLowerCase()) ||
(row.name.isEmpty &&
LocaleKeys.grid_row_titlePlaceholder
.tr()
.toLowerCase()
.contains(filter.toLowerCase())),
);
}
final focusedRowId = rows.isEmpty
? null
: rows.any((row) => row.rowId == state.focusedRowId)
? state.focusedRowId
: rows.first.rowId;
emit(
state.copyWith(
filteredRows: rows,
focusedRowId: focusedRowId,
),
);
}
void _focusOption(bool previous, Emitter<RelationRowSearchState> emit) {
if (state.filteredRows.isEmpty) {
return;
}
final rowIds = state.filteredRows.map((e) => e.rowId).toList();
final currentIndex = state.focusedRowId == null
? -1
: rowIds.indexWhere((id) => id == state.focusedRowId);
// If the current index is -1, it means that the focused row is not in the list of row ids.
// In this case, we set the new index to the last index if previous is true, otherwise to 0.
final newIndex = currentIndex == -1
? (previous ? rowIds.length - 1 : 0)
: (currentIndex + (previous ? -1 : 1)) % rowIds.length;
emit(state.copyWith(focusedRowId: rowIds[newIndex]));
}
}
@freezed
class RelationRowSearchEvent with _$RelationRowSearchEvent {
const factory RelationRowSearchEvent.didUpdateRowList(
List<RelatedRowDataPB> rowList,
) = _DidUpdateRowList;
const factory RelationRowSearchEvent.updateFilter(String filter) =
_UpdateFilter;
const factory RelationRowSearchEvent.updateFocusedOption(
String rowId,
) = _UpdateFocusedOption;
const factory RelationRowSearchEvent.focusPreviousOption() =
_FocusPreviousOption;
const factory RelationRowSearchEvent.focusNextOption() = _FocusNextOption;
}
@freezed
class RelationRowSearchState with _$RelationRowSearchState {
const factory RelationRowSearchState({
required List<RelatedRowDataPB> filteredRows,
required String? focusedRowId,
}) = _RelationRowSearchState;
factory RelationRowSearchState.initial() => const RelationRowSearchState(
filteredRows: [],
focusedRowId: null,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/date_cell_editor_bloc.dart | import 'dart:async';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/domain/date_cell_service.dart';
import 'package:appflowy/plugins/database/domain/field_service.dart';
import 'package:appflowy/plugins/database/application/field/type_option/type_option_data_parser.dart';
import 'package:appflowy/user/application/reminder/reminder_bloc.dart';
import 'package:appflowy/user/application/reminder/reminder_extension.dart';
import 'package:appflowy/util/int64_extension.dart';
import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/code.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:calendar_view/calendar_view.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart'
show StringTranslateExtension;
import 'package:fixnum/fixnum.dart';
import 'package:flowy_infra/time/duration.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:nanoid/non_secure.dart';
import 'package:protobuf/protobuf.dart';
part 'date_cell_editor_bloc.freezed.dart';
class DateCellEditorBloc
extends Bloc<DateCellEditorEvent, DateCellEditorState> {
DateCellEditorBloc({
required this.cellController,
required ReminderBloc reminderBloc,
}) : _reminderBloc = reminderBloc,
_dateCellBackendService = DateCellBackendService(
viewId: cellController.viewId,
fieldId: cellController.fieldId,
rowId: cellController.rowId,
),
super(DateCellEditorState.initial(cellController, reminderBloc)) {
_dispatch();
_startListening();
}
final DateCellBackendService _dateCellBackendService;
final DateCellController cellController;
final ReminderBloc _reminderBloc;
void Function()? _onCellChangedFn;
void _dispatch() {
on<DateCellEditorEvent>(
(event, emit) async {
await event.when(
didReceiveCellUpdate: (DateCellDataPB? cellData) {
final dateCellData = _dateDataFromCellData(cellData);
final endDay =
dateCellData.isRange == state.isRange && dateCellData.isRange
? dateCellData.endDateTime
: null;
ReminderOption option = state.reminderOption;
if (dateCellData.dateTime != null &&
(state.reminderId?.isEmpty ?? true) &&
(dateCellData.reminderId?.isNotEmpty ?? false) &&
state.reminderOption != ReminderOption.none) {
final date = state.reminderOption.withoutTime
? dateCellData.dateTime!.withoutTime
: dateCellData.dateTime!;
// Add Reminder
_reminderBloc.add(
ReminderEvent.addById(
reminderId: dateCellData.reminderId!,
objectId: cellController.viewId,
meta: {
ReminderMetaKeys.includeTime: true.toString(),
ReminderMetaKeys.rowId: cellController.rowId,
},
scheduledAt: Int64(
state.reminderOption
.fromDate(date)
.millisecondsSinceEpoch ~/
1000,
),
),
);
}
if ((dateCellData.reminderId?.isNotEmpty ?? false) &&
dateCellData.dateTime != null) {
if (option.requiresNoTime && dateCellData.includeTime) {
option = ReminderOption.atTimeOfEvent;
} else if (!option.withoutTime && !dateCellData.includeTime) {
option = ReminderOption.onDayOfEvent;
}
final date = option.withoutTime
? dateCellData.dateTime!.withoutTime
: dateCellData.dateTime!;
final scheduledAt = option.fromDate(date);
// Update Reminder
_reminderBloc.add(
ReminderEvent.update(
ReminderUpdate(
id: dateCellData.reminderId!,
scheduledAt: scheduledAt,
includeTime: true,
),
),
);
}
emit(
state.copyWith(
dateTime: dateCellData.dateTime,
timeStr: dateCellData.timeStr,
endDateTime: dateCellData.endDateTime,
endTimeStr: dateCellData.endTimeStr,
includeTime: dateCellData.includeTime,
isRange: dateCellData.isRange,
startDay: dateCellData.isRange ? dateCellData.dateTime : null,
endDay: endDay,
dateStr: dateCellData.dateStr,
endDateStr: dateCellData.endDateStr,
reminderId: dateCellData.reminderId,
reminderOption: option,
),
);
},
didReceiveTimeFormatError: (
String? parseTimeError,
String? parseEndTimeError,
) {
emit(
state.copyWith(
parseTimeError: parseTimeError,
parseEndTimeError: parseEndTimeError,
),
);
},
selectDay: (date) async {
if (!state.isRange) {
await _updateDateData(date: date);
}
},
setIncludeTime: (includeTime) async =>
_updateDateData(includeTime: includeTime),
setIsRange: (isRange) async => _updateDateData(isRange: isRange),
setTime: (timeStr) async {
emit(state.copyWith(timeStr: timeStr));
await _updateDateData(timeStr: timeStr);
},
selectDateRange: (DateTime? start, DateTime? end) async {
if (end == null && state.startDay != null && state.endDay == null) {
final (newStart, newEnd) = state.startDay!.isBefore(start!)
? (state.startDay!, start)
: (start, state.startDay!);
emit(state.copyWith(startDay: null, endDay: null));
await _updateDateData(date: newStart.date, endDate: newEnd.date);
} else if (end == null) {
emit(state.copyWith(startDay: start, endDay: null));
} else {
await _updateDateData(date: start!.date, endDate: end.date);
}
},
setStartDay: (DateTime startDay) async {
if (state.endDay == null) {
emit(state.copyWith(startDay: startDay));
} else if (startDay.isAfter(state.endDay!)) {
emit(state.copyWith(startDay: startDay, endDay: null));
} else {
emit(state.copyWith(startDay: startDay));
await _updateDateData(
date: startDay.date,
endDate: state.endDay!.date,
);
}
},
setEndDay: (DateTime endDay) {
if (state.startDay == null) {
emit(state.copyWith(endDay: endDay));
} else if (endDay.isBefore(state.startDay!)) {
emit(state.copyWith(startDay: null, endDay: endDay));
} else {
emit(state.copyWith(endDay: endDay));
_updateDateData(date: state.startDay!.date, endDate: endDay.date);
}
},
setEndTime: (String? endTime) async {
emit(state.copyWith(endTimeStr: endTime));
await _updateDateData(endTimeStr: endTime);
},
setDateFormat: (DateFormatPB dateFormat) async =>
await _updateTypeOption(emit, dateFormat: dateFormat),
setTimeFormat: (TimeFormatPB timeFormat) async =>
await _updateTypeOption(emit, timeFormat: timeFormat),
clearDate: () async {
// Remove reminder if neccessary
if (state.reminderId != null) {
_reminderBloc
.add(ReminderEvent.remove(reminderId: state.reminderId!));
}
await _clearDate();
},
setReminderOption: (
ReminderOption option,
DateTime? selectedDay,
) async {
if (state.reminderId?.isEmpty ??
true &&
(state.dateTime != null || selectedDay != null) &&
option != ReminderOption.none) {
// New Reminder
final reminderId = nanoid();
await _updateDateData(reminderId: reminderId, date: selectedDay);
emit(
state.copyWith(reminderOption: option, dateTime: selectedDay),
);
} else if (option == ReminderOption.none &&
(state.reminderId?.isNotEmpty ?? false)) {
// Remove reminder
_reminderBloc
.add(ReminderEvent.remove(reminderId: state.reminderId!));
await _updateDateData(reminderId: "");
emit(state.copyWith(reminderOption: option));
} else if (state.dateTime != null &&
(state.reminderId?.isNotEmpty ?? false)) {
final scheduledAt = option.fromDate(state.dateTime!);
// Update reminder
_reminderBloc.add(
ReminderEvent.update(
ReminderUpdate(
id: state.reminderId!,
scheduledAt: scheduledAt,
includeTime: true,
),
),
);
}
},
// Empty String signifies no reminder
removeReminder: () async => _updateDateData(reminderId: ""),
);
},
);
}
Future<void> _updateDateData({
DateTime? date,
String? timeStr,
DateTime? endDate,
String? endTimeStr,
bool? includeTime,
bool? isRange,
String? reminderId,
}) async {
// make sure that not both date and time are updated at the same time
assert(
!(date != null && timeStr != null) ||
!(endDate != null && endTimeStr != null),
);
// if not updating the time, use the old time in the state
final String? newTime = timeStr ?? state.timeStr;
final DateTime? newDate = timeStr != null && timeStr.isNotEmpty
? state.dateTime ?? DateTime.now()
: _utcToLocalAndAddCurrentTime(date);
// if not updating the time, use the old time in the state
final String? newEndTime = endTimeStr ?? state.endTimeStr;
final DateTime? newEndDate = endTimeStr != null && endTimeStr.isNotEmpty
? state.endDateTime ?? DateTime.now()
: _utcToLocalAndAddCurrentTime(endDate);
final result = await _dateCellBackendService.update(
date: newDate,
time: newTime,
endDate: newEndDate,
endTime: newEndTime,
includeTime: includeTime ?? state.includeTime,
isRange: isRange ?? state.isRange,
reminderId: reminderId ?? state.reminderId,
);
result.fold(
(_) {
if (!isClosed &&
(state.parseEndTimeError != null || state.parseTimeError != null)) {
add(const DateCellEditorEvent.didReceiveTimeFormatError(null, null));
}
},
(err) {
switch (err.code) {
case ErrorCode.InvalidDateTimeFormat:
if (isClosed) {
return;
}
// to determine which textfield should show error
final (startError, endError) = newDate != null
? (timeFormatPrompt(err), null)
: (null, timeFormatPrompt(err));
add(
DateCellEditorEvent.didReceiveTimeFormatError(
startError,
endError,
),
);
break;
default:
Log.error(err);
}
},
);
}
Future<void> _clearDate() async {
final result = await _dateCellBackendService.clear();
result.fold(
(_) {
if (!isClosed) {
add(const DateCellEditorEvent.didReceiveTimeFormatError(null, null));
}
},
(err) => Log.error(err),
);
}
DateTime? _utcToLocalAndAddCurrentTime(DateTime? date) {
if (date == null) {
return null;
}
final now = DateTime.now();
// the incoming date is Utc. This trick converts it into Local
// and add the current time. The time may be overwritten by
// explicitly provided time string in the backend though
return DateTime(
date.year,
date.month,
date.day,
now.hour,
now.minute,
now.second,
);
}
String timeFormatPrompt(FlowyError error) {
return switch (state.dateTypeOptionPB.timeFormat) {
TimeFormatPB.TwelveHour =>
"${LocaleKeys.grid_field_invalidTimeFormat.tr()}. e.g. 01:00 PM",
TimeFormatPB.TwentyFourHour =>
"${LocaleKeys.grid_field_invalidTimeFormat.tr()}. e.g. 13:00",
_ => "",
};
}
@override
Future<void> close() async {
if (_onCellChangedFn != null) {
cellController.removeListener(
onCellChanged: _onCellChangedFn!,
);
}
return super.close();
}
void _startListening() {
_onCellChangedFn = cellController.addListener(
onCellChanged: (cell) {
if (!isClosed) {
add(DateCellEditorEvent.didReceiveCellUpdate(cell));
}
},
);
}
Future<void>? _updateTypeOption(
Emitter<DateCellEditorState> emit, {
DateFormatPB? dateFormat,
TimeFormatPB? timeFormat,
}) async {
state.dateTypeOptionPB.freeze();
final newDateTypeOption = state.dateTypeOptionPB.rebuild((typeOption) {
if (dateFormat != null) {
typeOption.dateFormat = dateFormat;
}
if (timeFormat != null) {
typeOption.timeFormat = timeFormat;
}
});
final result = await FieldBackendService.updateFieldTypeOption(
viewId: cellController.viewId,
fieldId: cellController.fieldInfo.id,
typeOptionData: newDateTypeOption.writeToBuffer(),
);
result.fold(
(_) => emit(
state.copyWith(
dateTypeOptionPB: newDateTypeOption,
timeHintText: _timeHintText(newDateTypeOption),
),
),
(err) => Log.error(err),
);
}
}
@freezed
class DateCellEditorEvent with _$DateCellEditorEvent {
// notification that cell is updated in the backend
const factory DateCellEditorEvent.didReceiveCellUpdate(
DateCellDataPB? data,
) = _DidReceiveCellUpdate;
const factory DateCellEditorEvent.didReceiveTimeFormatError(
String? parseTimeError,
String? parseEndTimeError,
) = _DidReceiveTimeFormatError;
// date cell data is modified
const factory DateCellEditorEvent.selectDay(DateTime day) = _SelectDay;
const factory DateCellEditorEvent.selectDateRange(
DateTime? start,
DateTime? end,
) = _SelectDateRange;
const factory DateCellEditorEvent.setStartDay(
DateTime startDay,
) = _SetStartDay;
const factory DateCellEditorEvent.setEndDay(
DateTime endDay,
) = _SetEndDay;
const factory DateCellEditorEvent.setTime(String time) = _SetTime;
const factory DateCellEditorEvent.setEndTime(String endTime) = _SetEndTime;
const factory DateCellEditorEvent.setIncludeTime(bool includeTime) =
_IncludeTime;
const factory DateCellEditorEvent.setIsRange(bool isRange) = _SetIsRange;
const factory DateCellEditorEvent.setReminderOption({
required ReminderOption option,
@Default(null) DateTime? selectedDay,
}) = _SetReminderOption;
const factory DateCellEditorEvent.removeReminder() = _RemoveReminder;
// date field type options are modified
const factory DateCellEditorEvent.setTimeFormat(TimeFormatPB timeFormat) =
_SetTimeFormat;
const factory DateCellEditorEvent.setDateFormat(DateFormatPB dateFormat) =
_SetDateFormat;
const factory DateCellEditorEvent.clearDate() = _ClearDate;
}
@freezed
class DateCellEditorState with _$DateCellEditorState {
const factory DateCellEditorState({
// the date field's type option
required DateTypeOptionPB dateTypeOptionPB,
// used when selecting a date range
required DateTime? startDay,
required DateTime? endDay,
// cell data from the backend
required DateTime? dateTime,
required DateTime? endDateTime,
required String? timeStr,
required String? endTimeStr,
required bool includeTime,
required bool isRange,
required String? dateStr,
required String? endDateStr,
required String? reminderId,
// error and hint text
required String? parseTimeError,
required String? parseEndTimeError,
required String timeHintText,
@Default(ReminderOption.none) ReminderOption reminderOption,
}) = _DateCellEditorState;
factory DateCellEditorState.initial(
DateCellController controller,
ReminderBloc reminderBloc,
) {
final typeOption = controller.getTypeOption(DateTypeOptionDataParser());
final cellData = controller.getCellData();
final dateCellData = _dateDataFromCellData(cellData);
ReminderOption reminderOption = ReminderOption.none;
if ((dateCellData.reminderId?.isNotEmpty ?? false) &&
dateCellData.dateTime != null) {
final reminder = reminderBloc.state.reminders
.firstWhereOrNull((r) => r.id == dateCellData.reminderId);
if (reminder != null) {
final eventDate = dateCellData.includeTime
? dateCellData.dateTime!
: dateCellData.dateTime!.withoutTime;
reminderOption = ReminderOption.fromDateDifference(
eventDate,
reminder.scheduledAt.toDateTime(),
);
}
}
return DateCellEditorState(
dateTypeOptionPB: typeOption,
startDay: dateCellData.isRange ? dateCellData.dateTime : null,
endDay: dateCellData.isRange ? dateCellData.endDateTime : null,
dateTime: dateCellData.dateTime,
endDateTime: dateCellData.endDateTime,
timeStr: dateCellData.timeStr,
endTimeStr: dateCellData.endTimeStr,
dateStr: dateCellData.dateStr,
endDateStr: dateCellData.endDateStr,
includeTime: dateCellData.includeTime,
isRange: dateCellData.isRange,
parseTimeError: null,
parseEndTimeError: null,
timeHintText: _timeHintText(typeOption),
reminderId: dateCellData.reminderId,
reminderOption: reminderOption,
);
}
}
String _timeHintText(DateTypeOptionPB typeOption) {
switch (typeOption.timeFormat) {
case TimeFormatPB.TwelveHour:
return LocaleKeys.document_date_timeHintTextInTwelveHour.tr();
case TimeFormatPB.TwentyFourHour:
return LocaleKeys.document_date_timeHintTextInTwentyFourHour.tr();
default:
return "";
}
}
_DateCellData _dateDataFromCellData(
DateCellDataPB? cellData,
) {
// a null DateCellDataPB may be returned, indicating that all the fields are
// their default values: empty strings and false booleans
if (cellData == null) {
return _DateCellData(
dateTime: null,
endDateTime: null,
timeStr: null,
endTimeStr: null,
includeTime: false,
isRange: false,
dateStr: null,
endDateStr: null,
reminderId: null,
);
}
DateTime? dateTime;
String? timeStr;
DateTime? endDateTime;
String? endTimeStr;
String? endDateStr;
if (cellData.hasTimestamp()) {
final timestamp = cellData.timestamp * 1000;
dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp.toInt());
timeStr = cellData.time;
if (cellData.hasEndTimestamp()) {
final endTimestamp = cellData.endTimestamp * 1000;
endDateTime = DateTime.fromMillisecondsSinceEpoch(endTimestamp.toInt());
endTimeStr = cellData.endTime;
}
}
final bool includeTime = cellData.includeTime;
final bool isRange = cellData.isRange;
if (cellData.isRange) {
endDateStr = cellData.endDate;
}
final String dateStr = cellData.date;
return _DateCellData(
dateTime: dateTime,
endDateTime: endDateTime,
timeStr: timeStr,
endTimeStr: endTimeStr,
includeTime: includeTime,
isRange: isRange,
dateStr: dateStr,
endDateStr: endDateStr,
reminderId: cellData.reminderId,
);
}
class _DateCellData {
_DateCellData({
required this.dateTime,
required this.endDateTime,
required this.timeStr,
required this.endTimeStr,
required this.includeTime,
required this.isRange,
required this.dateStr,
required this.endDateStr,
required this.reminderId,
});
final DateTime? dateTime;
final DateTime? endDateTime;
final String? timeStr;
final String? endTimeStr;
final bool includeTime;
final bool isRange;
final String? dateStr;
final String? endDateStr;
final String? reminderId;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field/field_controller.dart | import 'dart:collection';
import 'package:appflowy/plugins/database/domain/database_view_service.dart';
import 'package:appflowy/plugins/database/domain/field_listener.dart';
import 'package:appflowy/plugins/database/domain/field_settings_listener.dart';
import 'package:appflowy/plugins/database/domain/field_settings_service.dart';
import 'package:appflowy/plugins/database/domain/filter_listener.dart';
import 'package:appflowy/plugins/database/domain/filter_service.dart';
import 'package:appflowy/plugins/database/application/row/row_cache.dart';
import 'package:appflowy/plugins/database/application/setting/setting_listener.dart';
import 'package:appflowy/plugins/database/domain/sort_listener.dart';
import 'package:appflowy/plugins/database/domain/sort_service.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/filter_info.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/sort_info.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import '../setting/setting_service.dart';
import 'field_info.dart';
class _GridFieldNotifier extends ChangeNotifier {
List<FieldInfo> _fieldInfos = [];
set fieldInfos(List<FieldInfo> fieldInfos) {
_fieldInfos = fieldInfos;
notifyListeners();
}
void notify() {
notifyListeners();
}
UnmodifiableListView<FieldInfo> get fieldInfos =>
UnmodifiableListView(_fieldInfos);
}
class _GridFilterNotifier extends ChangeNotifier {
List<FilterInfo> _filters = [];
set filters(List<FilterInfo> filters) {
_filters = filters;
notifyListeners();
}
void notify() {
notifyListeners();
}
List<FilterInfo> get filters => _filters;
}
class _GridSortNotifier extends ChangeNotifier {
List<SortInfo> _sorts = [];
set sorts(List<SortInfo> sorts) {
_sorts = sorts;
notifyListeners();
}
void notify() {
notifyListeners();
}
List<SortInfo> get sorts => _sorts;
}
typedef OnReceiveUpdateFields = void Function(List<FieldInfo>);
typedef OnReceiveField = void Function(FieldInfo);
typedef OnReceiveFields = void Function(List<FieldInfo>);
typedef OnReceiveFilters = void Function(List<FilterInfo>);
typedef OnReceiveSorts = void Function(List<SortInfo>);
typedef OnReceiveFieldSettings = void Function(List<FieldInfo>);
class FieldController {
FieldController({required this.viewId})
: _fieldListener = FieldsListener(viewId: viewId),
_settingListener = DatabaseSettingListener(viewId: viewId),
_filterBackendSvc = FilterBackendService(viewId: viewId),
_filtersListener = FiltersListener(viewId: viewId),
_databaseViewBackendSvc = DatabaseViewBackendService(viewId: viewId),
_sortBackendSvc = SortBackendService(viewId: viewId),
_sortsListener = SortsListener(viewId: viewId),
_fieldSettingsListener = FieldSettingsListener(viewId: viewId),
_fieldSettingsBackendSvc = FieldSettingsBackendService(viewId: viewId) {
// Start listeners
_listenOnFieldChanges();
_listenOnSettingChanges();
_listenOnFilterChanges();
_listenOnSortChanged();
_listenOnFieldSettingsChanged();
}
final String viewId;
// Listeners
final FieldsListener _fieldListener;
final DatabaseSettingListener _settingListener;
final FiltersListener _filtersListener;
final SortsListener _sortsListener;
final FieldSettingsListener _fieldSettingsListener;
// FFI services
final DatabaseViewBackendService _databaseViewBackendSvc;
final FilterBackendService _filterBackendSvc;
final SortBackendService _sortBackendSvc;
final FieldSettingsBackendService _fieldSettingsBackendSvc;
bool _isDisposed = false;
// Field callbacks
final Map<OnReceiveFields, VoidCallback> _fieldCallbacks = {};
final _GridFieldNotifier _fieldNotifier = _GridFieldNotifier();
// Field updated callbacks
final Map<OnReceiveUpdateFields, void Function(List<FieldInfo>)>
_updatedFieldCallbacks = {};
// Filter callbacks
final Map<OnReceiveFilters, VoidCallback> _filterCallbacks = {};
_GridFilterNotifier? _filterNotifier = _GridFilterNotifier();
// Sort callbacks
final Map<OnReceiveSorts, VoidCallback> _sortCallbacks = {};
_GridSortNotifier? _sortNotifier = _GridSortNotifier();
// Database settings temporary storage
final Map<String, GroupSettingPB> _groupConfigurationByFieldId = {};
final List<FieldSettingsPB> _fieldSettings = [];
// Getters
List<FieldInfo> get fieldInfos => [..._fieldNotifier.fieldInfos];
List<FilterInfo> get filterInfos => [..._filterNotifier?.filters ?? []];
List<SortInfo> get sortInfos => [..._sortNotifier?.sorts ?? []];
FieldInfo? getField(String fieldId) {
return _fieldNotifier.fieldInfos
.firstWhereOrNull((element) => element.id == fieldId);
}
FilterInfo? getFilterByFilterId(String filterId) {
return _filterNotifier?.filters
.firstWhereOrNull((element) => element.filterId == filterId);
}
FilterInfo? getFilterByFieldId(String fieldId) {
return _filterNotifier?.filters
.firstWhereOrNull((element) => element.fieldId == fieldId);
}
SortInfo? getSortBySortId(String sortId) {
return _sortNotifier?.sorts
.firstWhereOrNull((element) => element.sortId == sortId);
}
SortInfo? getSortByFieldId(String fieldId) {
return _sortNotifier?.sorts
.firstWhereOrNull((element) => element.fieldId == fieldId);
}
/// Listen for filter changes in the backend.
void _listenOnFilterChanges() {
_filtersListener.start(
onFilterChanged: (result) {
if (_isDisposed) {
return;
}
result.fold(
(FilterChangesetNotificationPB changeset) {
final List<FilterInfo> filters = [];
for (final filter in changeset.filters.items) {
final fieldInfo = _findFieldInfo(
fieldInfos: fieldInfos,
fieldId: filter.data.fieldId,
fieldType: filter.data.fieldType,
);
if (fieldInfo != null) {
final filterInfo = FilterInfo(viewId, filter, fieldInfo);
filters.add(filterInfo);
}
}
_filterNotifier?.filters = filters;
_updateFieldInfos();
},
(err) => Log.error(err),
);
},
);
}
/// Listen for sort changes in the backend.
void _listenOnSortChanged() {
void deleteSortFromChangeset(
List<SortInfo> newSortInfos,
SortChangesetNotificationPB changeset,
) {
final deleteSortIds = changeset.deleteSorts.map((e) => e.id).toList();
if (deleteSortIds.isNotEmpty) {
newSortInfos.retainWhere(
(element) => !deleteSortIds.contains(element.sortId),
);
}
}
void insertSortFromChangeset(
List<SortInfo> newSortInfos,
SortChangesetNotificationPB changeset,
) {
for (final newSortPB in changeset.insertSorts) {
final sortIndex = newSortInfos
.indexWhere((element) => element.sortId == newSortPB.sort.id);
if (sortIndex == -1) {
final fieldInfo = _findFieldInfo(
fieldInfos: fieldInfos,
fieldId: newSortPB.sort.fieldId,
fieldType: null,
);
if (fieldInfo != null) {
newSortInfos.insert(
newSortPB.index,
SortInfo(sortPB: newSortPB.sort, fieldInfo: fieldInfo),
);
}
}
}
}
void updateSortFromChangeset(
List<SortInfo> newSortInfos,
SortChangesetNotificationPB changeset,
) {
for (final updatedSort in changeset.updateSorts) {
final sortIndex = newSortInfos.indexWhere(
(element) => element.sortId == updatedSort.id,
);
// Remove the old filter
if (sortIndex != -1) {
newSortInfos.removeAt(sortIndex);
}
final fieldInfo = _findFieldInfo(
fieldInfos: fieldInfos,
fieldId: updatedSort.fieldId,
fieldType: null,
);
if (fieldInfo != null) {
final newSortInfo = SortInfo(
sortPB: updatedSort,
fieldInfo: fieldInfo,
);
if (sortIndex != -1) {
newSortInfos.insert(sortIndex, newSortInfo);
} else {
newSortInfos.add(newSortInfo);
}
}
}
}
void updateFieldInfos(
List<SortInfo> newSortInfos,
SortChangesetNotificationPB changeset,
) {
final changedFieldIds = HashSet<String>.from([
...changeset.insertSorts.map((sort) => sort.sort.fieldId),
...changeset.updateSorts.map((sort) => sort.fieldId),
...changeset.deleteSorts.map((sort) => sort.fieldId),
...?_sortNotifier?.sorts.map((sort) => sort.fieldId),
]);
final newFieldInfos = [...fieldInfos];
for (final fieldId in changedFieldIds) {
final index =
newFieldInfos.indexWhere((fieldInfo) => fieldInfo.id == fieldId);
if (index == -1) {
continue;
}
newFieldInfos[index] = newFieldInfos[index].copyWith(
hasSort: newSortInfos.any((sort) => sort.fieldId == fieldId),
);
}
_fieldNotifier.fieldInfos = newFieldInfos;
}
_sortsListener.start(
onSortChanged: (result) {
if (_isDisposed) {
return;
}
result.fold(
(SortChangesetNotificationPB changeset) {
final List<SortInfo> newSortInfos = sortInfos;
deleteSortFromChangeset(newSortInfos, changeset);
insertSortFromChangeset(newSortInfos, changeset);
updateSortFromChangeset(newSortInfos, changeset);
updateFieldInfos(newSortInfos, changeset);
_sortNotifier?.sorts = newSortInfos;
},
(err) => Log.error(err),
);
},
);
}
/// Listen for database setting changes in the backend.
void _listenOnSettingChanges() {
_settingListener.start(
onSettingUpdated: (result) {
if (_isDisposed) {
return;
}
result.fold(
(setting) => _updateSetting(setting),
(r) => Log.error(r),
);
},
);
}
/// Listen for field changes in the backend.
void _listenOnFieldChanges() {
Future<FieldInfo> attachFieldSettings(FieldInfo fieldInfo) async {
return _fieldSettingsBackendSvc
.getFieldSettings(fieldInfo.id)
.then((result) {
final fieldSettings = result.fold(
(fieldSettings) => fieldSettings,
(err) => null,
);
if (fieldSettings == null) {
return fieldInfo;
}
final updatedFieldInfo =
fieldInfo.copyWith(fieldSettings: fieldSettings);
final index = _fieldSettings
.indexWhere((element) => element.fieldId == fieldInfo.id);
if (index != -1) {
_fieldSettings.removeAt(index);
}
_fieldSettings.add(fieldSettings);
return updatedFieldInfo;
});
}
List<FieldInfo> deleteFields(List<FieldIdPB> deletedFields) {
if (deletedFields.isEmpty) {
return fieldInfos;
}
final List<FieldInfo> newFields = fieldInfos;
final Map<String, FieldIdPB> deletedFieldMap = {
for (final fieldOrder in deletedFields) fieldOrder.fieldId: fieldOrder,
};
newFields.retainWhere((field) => deletedFieldMap[field.id] == null);
return newFields;
}
Future<List<FieldInfo>> insertFields(
List<IndexFieldPB> insertedFields,
List<FieldInfo> fieldInfos,
) async {
if (insertedFields.isEmpty) {
return fieldInfos;
}
final List<FieldInfo> newFieldInfos = fieldInfos;
for (final indexField in insertedFields) {
final initial = FieldInfo.initial(indexField.field_1);
final fieldInfo = await attachFieldSettings(initial);
if (newFieldInfos.length > indexField.index) {
newFieldInfos.insert(indexField.index, fieldInfo);
} else {
newFieldInfos.add(fieldInfo);
}
}
return newFieldInfos;
}
Future<(List<FieldInfo>, List<FieldInfo>)> updateFields(
List<FieldPB> updatedFieldPBs,
List<FieldInfo> fieldInfos,
) async {
if (updatedFieldPBs.isEmpty) {
return (<FieldInfo>[], fieldInfos);
}
final List<FieldInfo> newFieldInfo = fieldInfos;
final List<FieldInfo> updatedFields = [];
for (final updatedFieldPB in updatedFieldPBs) {
final index =
newFieldInfo.indexWhere((field) => field.id == updatedFieldPB.id);
if (index != -1) {
newFieldInfo.removeAt(index);
final initial = FieldInfo.initial(updatedFieldPB);
final fieldInfo = await attachFieldSettings(initial);
newFieldInfo.insert(index, fieldInfo);
updatedFields.add(fieldInfo);
}
}
return (updatedFields, newFieldInfo);
}
// Listen on field's changes
_fieldListener.start(
onFieldsChanged: (result) async {
result.fold(
(changeset) async {
if (_isDisposed) {
return;
}
List<FieldInfo> updatedFields;
List<FieldInfo> fieldInfos = deleteFields(changeset.deletedFields);
fieldInfos =
await insertFields(changeset.insertedFields, fieldInfos);
(updatedFields, fieldInfos) =
await updateFields(changeset.updatedFields, fieldInfos);
_fieldNotifier.fieldInfos = fieldInfos;
for (final listener in _updatedFieldCallbacks.values) {
listener(updatedFields);
}
},
(err) => Log.error(err),
);
},
);
}
/// Listen for field setting changes in the backend.
void _listenOnFieldSettingsChanged() {
FieldInfo updateFieldSettings(FieldSettingsPB updatedFieldSettings) {
final List<FieldInfo> newFields = fieldInfos;
FieldInfo updatedField = newFields[0];
final index = newFields
.indexWhere((field) => field.id == updatedFieldSettings.fieldId);
if (index != -1) {
newFields[index] =
newFields[index].copyWith(fieldSettings: updatedFieldSettings);
updatedField = newFields[index];
}
_fieldNotifier.fieldInfos = newFields;
return updatedField;
}
_fieldSettingsListener.start(
onFieldSettingsChanged: (result) {
if (_isDisposed) {
return;
}
result.fold(
(fieldSettings) {
final updatedFieldInfo = updateFieldSettings(fieldSettings);
for (final listener in _updatedFieldCallbacks.values) {
listener([updatedFieldInfo]);
}
},
(err) => Log.error(err),
);
},
);
}
/// Updates sort, filter, group and field info from `DatabaseViewSettingPB`
void _updateSetting(DatabaseViewSettingPB setting) {
_groupConfigurationByFieldId.clear();
for (final configuration in setting.groupSettings.items) {
_groupConfigurationByFieldId[configuration.fieldId] = configuration;
}
_filterNotifier?.filters = _filterInfoListFromPBs(setting.filters.items);
_sortNotifier?.sorts = _sortInfoListFromPBs(setting.sorts.items);
_fieldSettings.clear();
_fieldSettings.addAll(setting.fieldSettings.items);
_updateFieldInfos();
}
/// Attach sort, filter, group information and field settings to `FieldInfo`
void _updateFieldInfos() {
final List<FieldInfo> newFieldInfos = [];
for (final field in _fieldNotifier.fieldInfos) {
newFieldInfos.add(
field.copyWith(
fieldSettings: _fieldSettings
.firstWhereOrNull((setting) => setting.fieldId == field.id),
isGroupField: _groupConfigurationByFieldId[field.id] != null,
hasFilter: getFilterByFieldId(field.id) != null,
hasSort: getSortByFieldId(field.id) != null,
),
);
}
_fieldNotifier.fieldInfos = newFieldInfos;
}
/// Load all of the fields. This is required when opening the database
Future<FlowyResult<void, FlowyError>> loadFields({
required List<FieldIdPB> fieldIds,
}) async {
final result = await _databaseViewBackendSvc.getFields(fieldIds: fieldIds);
return Future(
() => result.fold(
(newFields) async {
if (_isDisposed) {
return FlowyResult.success(null);
}
_fieldNotifier.fieldInfos =
newFields.map((field) => FieldInfo.initial(field)).toList();
await Future.wait([
_loadFilters(),
_loadSorts(),
_loadAllFieldSettings(),
_loadSettings(),
]);
_updateFieldInfos();
return FlowyResult.success(null);
},
(err) => FlowyResult.failure(err),
),
);
}
/// Load all the filters from the backend. Required by `loadFields`
Future<FlowyResult<void, FlowyError>> _loadFilters() async {
return _filterBackendSvc.getAllFilters().then((result) {
return result.fold(
(filterPBs) {
_filterNotifier?.filters = _filterInfoListFromPBs(filterPBs);
return FlowyResult.success(null);
},
(err) => FlowyResult.failure(err),
);
});
}
/// Load all the sorts from the backend. Required by `loadFields`
Future<FlowyResult<void, FlowyError>> _loadSorts() async {
return _sortBackendSvc.getAllSorts().then((result) {
return result.fold(
(sortPBs) {
_sortNotifier?.sorts = _sortInfoListFromPBs(sortPBs);
return FlowyResult.success(null);
},
(err) => FlowyResult.failure(err),
);
});
}
/// Load all the field settings from the backend. Required by `loadFields`
Future<FlowyResult<void, FlowyError>> _loadAllFieldSettings() async {
return _fieldSettingsBackendSvc.getAllFieldSettings().then((result) {
return result.fold(
(fieldSettingsList) {
_fieldSettings.clear();
_fieldSettings.addAll(fieldSettingsList);
return FlowyResult.success(null);
},
(err) => FlowyResult.failure(err),
);
});
}
Future<FlowyResult<void, FlowyError>> _loadSettings() async {
return SettingBackendService(viewId: viewId).getSetting().then(
(result) => result.fold(
(setting) {
_groupConfigurationByFieldId.clear();
for (final configuration in setting.groupSettings.items) {
_groupConfigurationByFieldId[configuration.fieldId] =
configuration;
}
return FlowyResult.success(null);
},
(err) => FlowyResult.failure(err),
),
);
}
/// Attach corresponding `FieldInfo`s to the `FilterPB`s
List<FilterInfo> _filterInfoListFromPBs(List<FilterPB> filterPBs) {
FilterInfo? getFilterInfo(FilterPB filterPB) {
final fieldInfo = _findFieldInfo(
fieldInfos: fieldInfos,
fieldId: filterPB.data.fieldId,
fieldType: filterPB.data.fieldType,
);
return fieldInfo != null ? FilterInfo(viewId, filterPB, fieldInfo) : null;
}
return filterPBs
.map((filterPB) => getFilterInfo(filterPB))
.whereType<FilterInfo>()
.toList();
}
/// Attach corresponding `FieldInfo`s to the `SortPB`s
List<SortInfo> _sortInfoListFromPBs(List<SortPB> sortPBs) {
SortInfo? getSortInfo(SortPB sortPB) {
final fieldInfo = _findFieldInfo(
fieldInfos: fieldInfos,
fieldId: sortPB.fieldId,
fieldType: null,
);
return fieldInfo != null
? SortInfo(sortPB: sortPB, fieldInfo: fieldInfo)
: null;
}
return sortPBs
.map((sortPB) => getSortInfo(sortPB))
.whereType<SortInfo>()
.toList();
}
void addListener({
OnReceiveFields? onReceiveFields,
OnReceiveUpdateFields? onFieldsChanged,
OnReceiveFilters? onFilters,
OnReceiveSorts? onSorts,
bool Function()? listenWhen,
}) {
if (onFieldsChanged != null) {
void callback(List<FieldInfo> updateFields) {
if (listenWhen != null && listenWhen() == false) {
return;
}
onFieldsChanged(updateFields);
}
_updatedFieldCallbacks[onFieldsChanged] = callback;
}
if (onReceiveFields != null) {
void callback() {
if (listenWhen != null && listenWhen() == false) {
return;
}
onReceiveFields(fieldInfos);
}
_fieldCallbacks[onReceiveFields] = callback;
_fieldNotifier.addListener(callback);
}
if (onFilters != null) {
void callback() {
if (listenWhen != null && listenWhen() == false) {
return;
}
onFilters(filterInfos);
}
_filterCallbacks[onFilters] = callback;
_filterNotifier?.addListener(callback);
}
if (onSorts != null) {
void callback() {
if (listenWhen != null && listenWhen() == false) {
return;
}
onSorts(sortInfos);
}
_sortCallbacks[onSorts] = callback;
_sortNotifier?.addListener(callback);
}
}
void addSingleFieldListener(
String fieldId, {
required OnReceiveField onFieldChanged,
bool Function()? listenWhen,
}) {
void key(List<FieldInfo> fieldInfos) {
final fieldInfo = fieldInfos.firstWhereOrNull(
(fieldInfo) => fieldInfo.id == fieldId,
);
if (fieldInfo != null) {
onFieldChanged(fieldInfo);
}
}
void callback() {
if (listenWhen != null && listenWhen() == false) {
return;
}
key(fieldInfos);
}
_fieldCallbacks[key] = callback;
_fieldNotifier.addListener(callback);
}
void removeListener({
OnReceiveFields? onFieldsListener,
OnReceiveSorts? onSortsListener,
OnReceiveFilters? onFiltersListener,
OnReceiveUpdateFields? onChangesetListener,
}) {
if (onFieldsListener != null) {
final callback = _fieldCallbacks.remove(onFieldsListener);
if (callback != null) {
_fieldNotifier.removeListener(callback);
}
}
if (onFiltersListener != null) {
final callback = _filterCallbacks.remove(onFiltersListener);
if (callback != null) {
_filterNotifier?.removeListener(callback);
}
}
if (onSortsListener != null) {
final callback = _sortCallbacks.remove(onSortsListener);
if (callback != null) {
_sortNotifier?.removeListener(callback);
}
}
}
void removeSingleFieldListener({
required String fieldId,
required OnReceiveField onFieldChanged,
}) {
void key(List<FieldInfo> fieldInfos) {
final fieldInfo = fieldInfos.firstWhereOrNull(
(fieldInfo) => fieldInfo.id == fieldId,
);
if (fieldInfo != null) {
onFieldChanged(fieldInfo);
}
}
final callback = _fieldCallbacks.remove(key);
if (callback != null) {
_fieldNotifier.removeListener(callback);
}
}
/// Stop listeners, dispose notifiers and clear listener callbacks
Future<void> dispose() async {
if (_isDisposed) {
Log.warn('FieldController is already disposed');
return;
}
_isDisposed = true;
await _fieldListener.stop();
await _filtersListener.stop();
await _settingListener.stop();
await _sortsListener.stop();
await _fieldSettingsListener.stop();
for (final callback in _fieldCallbacks.values) {
_fieldNotifier.removeListener(callback);
}
_fieldNotifier.dispose();
for (final callback in _filterCallbacks.values) {
_filterNotifier?.removeListener(callback);
}
_filterNotifier?.dispose();
_filterNotifier = null;
for (final callback in _sortCallbacks.values) {
_sortNotifier?.removeListener(callback);
}
_sortNotifier?.dispose();
_sortNotifier = null;
}
}
class RowCacheDependenciesImpl extends RowFieldsDelegate with RowLifeCycle {
RowCacheDependenciesImpl(FieldController cache) : _fieldController = cache;
final FieldController _fieldController;
OnReceiveFields? _onFieldFn;
@override
UnmodifiableListView<FieldInfo> get fieldInfos =>
UnmodifiableListView(_fieldController.fieldInfos);
@override
void onFieldsChanged(void Function(List<FieldInfo>) callback) {
if (_onFieldFn != null) {
_fieldController.removeListener(onFieldsListener: _onFieldFn!);
}
_onFieldFn = (fieldInfos) => callback(fieldInfos);
_fieldController.addListener(onReceiveFields: _onFieldFn);
}
@override
void onRowDisposed() {
if (_onFieldFn != null) {
_fieldController.removeListener(onFieldsListener: _onFieldFn!);
_onFieldFn = null;
}
}
}
FieldInfo? _findFieldInfo({
required List<FieldInfo> fieldInfos,
required String fieldId,
required FieldType? fieldType,
}) {
return fieldInfos.firstWhereOrNull(
(element) =>
element.id == fieldId &&
(fieldType == null || element.fieldType == fieldType),
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field/field_info.dart | import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'field_info.freezed.dart';
@freezed
class FieldInfo with _$FieldInfo {
const FieldInfo._();
factory FieldInfo.initial(FieldPB field) => FieldInfo(
field: field,
fieldSettings: null,
hasFilter: false,
hasSort: false,
isGroupField: false,
);
const factory FieldInfo({
required FieldPB field,
required FieldSettingsPB? fieldSettings,
required bool isGroupField,
required bool hasFilter,
required bool hasSort,
}) = _FieldInfo;
String get id => field.id;
FieldType get fieldType => field.fieldType;
String get name => field.name;
bool get isPrimary => field.isPrimary;
double? get width => fieldSettings?.width.toDouble();
FieldVisibility? get visibility => fieldSettings?.visibility;
bool? get wrapCellContent => fieldSettings?.wrapCellContent;
bool get canBeGroup {
switch (field.fieldType) {
case FieldType.URL:
case FieldType.Checkbox:
case FieldType.MultiSelect:
case FieldType.SingleSelect:
case FieldType.DateTime:
return true;
default:
return false;
}
}
bool get canCreateFilter {
if (isGroupField) {
return false;
}
switch (field.fieldType) {
case FieldType.Number:
case FieldType.Checkbox:
case FieldType.MultiSelect:
case FieldType.RichText:
case FieldType.SingleSelect:
case FieldType.Checklist:
case FieldType.URL:
return true;
default:
return false;
}
}
bool get canCreateSort {
if (hasSort) {
return false;
}
switch (field.fieldType) {
case FieldType.RichText:
case FieldType.Checkbox:
case FieldType.Number:
case FieldType.DateTime:
case FieldType.SingleSelect:
case FieldType.MultiSelect:
case FieldType.LastEditedTime:
case FieldType.CreatedTime:
case FieldType.Checklist:
return true;
default:
return false;
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field/field_cell_bloc.dart | import 'dart:math';
import 'package:appflowy/plugins/database/domain/field_settings_service.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'field_info.dart';
part 'field_cell_bloc.freezed.dart';
class FieldCellBloc extends Bloc<FieldCellEvent, FieldCellState> {
FieldCellBloc({required String viewId, required FieldInfo fieldInfo})
: _fieldSettingsService = FieldSettingsBackendService(viewId: viewId),
super(FieldCellState.initial(fieldInfo)) {
_dispatch();
}
final FieldSettingsBackendService _fieldSettingsService;
void _dispatch() {
on<FieldCellEvent>(
(event, emit) async {
event.when(
onFieldChanged: (newFieldInfo) =>
emit(FieldCellState.initial(newFieldInfo)),
onResizeStart: () =>
emit(state.copyWith(isResizing: true, resizeStart: state.width)),
startUpdateWidth: (offset) {
final width = max(offset + state.resizeStart, 50).toDouble();
emit(state.copyWith(width: width));
},
endUpdateWidth: () {
if (state.width != state.fieldInfo.width) {
_fieldSettingsService.updateFieldSettings(
fieldId: state.fieldInfo.id,
width: state.width,
);
}
emit(state.copyWith(isResizing: false, resizeStart: 0));
},
);
},
);
}
}
@freezed
class FieldCellEvent with _$FieldCellEvent {
const factory FieldCellEvent.onFieldChanged(FieldInfo newFieldInfo) =
_OnFieldChanged;
const factory FieldCellEvent.onResizeStart() = _OnResizeStart;
const factory FieldCellEvent.startUpdateWidth(double offset) =
_StartUpdateWidth;
const factory FieldCellEvent.endUpdateWidth() = _EndUpdateWidth;
}
@freezed
class FieldCellState with _$FieldCellState {
factory FieldCellState.initial(FieldInfo fieldInfo) => FieldCellState(
fieldInfo: fieldInfo,
isResizing: false,
width: fieldInfo.fieldSettings!.width.toDouble(),
resizeStart: 0,
);
const factory FieldCellState({
required FieldInfo fieldInfo,
required double width,
required bool isResizing,
required double resizeStart,
}) = _FieldCellState;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field/field_editor_bloc.dart | import 'dart:typed_data';
import 'package:appflowy/plugins/database/domain/field_service.dart';
import 'package:appflowy/plugins/database/domain/field_settings_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'field_controller.dart';
import 'field_info.dart';
part 'field_editor_bloc.freezed.dart';
class FieldEditorBloc extends Bloc<FieldEditorEvent, FieldEditorState> {
FieldEditorBloc({
required this.viewId,
required this.fieldController,
this.onFieldInserted,
required FieldPB field,
}) : fieldId = field.id,
fieldService = FieldBackendService(
viewId: viewId,
fieldId: field.id,
),
fieldSettingsService = FieldSettingsBackendService(viewId: viewId),
super(FieldEditorState(field: FieldInfo.initial(field))) {
_dispatch();
_startListening();
_init();
}
final String viewId;
final String fieldId;
final FieldController fieldController;
final FieldBackendService fieldService;
final FieldSettingsBackendService fieldSettingsService;
final void Function(String newFieldId)? onFieldInserted;
late final OnReceiveField _listener;
@override
Future<void> close() {
fieldController.removeSingleFieldListener(
fieldId: fieldId,
onFieldChanged: _listener,
);
return super.close();
}
void _dispatch() {
on<FieldEditorEvent>(
(event, emit) async {
await event.when(
didUpdateField: (fieldInfo) {
emit(state.copyWith(field: fieldInfo));
},
switchFieldType: (fieldType) async {
await fieldService.updateType(fieldType: fieldType);
},
renameField: (newName) async {
final result = await fieldService.updateField(name: newName);
_logIfError(result);
},
updateTypeOption: (typeOptionData) async {
final result = await FieldBackendService.updateFieldTypeOption(
viewId: viewId,
fieldId: fieldId,
typeOptionData: typeOptionData,
);
_logIfError(result);
},
insertLeft: () async {
final result = await fieldService.createBefore();
result.fold(
(newField) => onFieldInserted?.call(newField.id),
(err) => Log.error("Failed creating field $err"),
);
},
insertRight: () async {
final result = await fieldService.createAfter();
result.fold(
(newField) => onFieldInserted?.call(newField.id),
(err) => Log.error("Failed creating field $err"),
);
},
toggleFieldVisibility: () async {
final currentVisibility =
state.field.visibility ?? FieldVisibility.AlwaysShown;
final newVisibility =
currentVisibility == FieldVisibility.AlwaysHidden
? FieldVisibility.AlwaysShown
: FieldVisibility.AlwaysHidden;
final result = await fieldSettingsService.updateFieldSettings(
fieldId: state.field.id,
fieldVisibility: newVisibility,
);
_logIfError(result);
},
toggleWrapCellContent: () async {
final currentWrap = state.field.wrapCellContent ?? false;
final result = await fieldSettingsService.updateFieldSettings(
fieldId: state.field.id,
wrapCellContent: !currentWrap,
);
_logIfError(result);
},
);
},
);
}
void _startListening() {
_listener = (field) {
if (!isClosed) {
add(FieldEditorEvent.didUpdateField(field));
}
};
fieldController.addSingleFieldListener(
fieldId,
onFieldChanged: _listener,
);
}
void _init() async {
await Future.delayed(const Duration(milliseconds: 50));
if (!isClosed) {
final field = fieldController.getField(fieldId);
if (field != null) {
add(FieldEditorEvent.didUpdateField(field));
}
}
}
void _logIfError(FlowyResult<void, FlowyError> result) {
result.fold(
(l) => null,
(err) => Log.error(err),
);
}
}
@freezed
class FieldEditorEvent with _$FieldEditorEvent {
const factory FieldEditorEvent.didUpdateField(final FieldInfo fieldInfo) =
_DidUpdateField;
const factory FieldEditorEvent.switchFieldType(final FieldType fieldType) =
_SwitchFieldType;
const factory FieldEditorEvent.updateTypeOption(
final Uint8List typeOptionData,
) = _UpdateTypeOption;
const factory FieldEditorEvent.renameField(final String name) = _RenameField;
const factory FieldEditorEvent.insertLeft() = _InsertLeft;
const factory FieldEditorEvent.insertRight() = _InsertRight;
const factory FieldEditorEvent.toggleFieldVisibility() =
_ToggleFieldVisiblity;
const factory FieldEditorEvent.toggleWrapCellContent() =
_ToggleWrapCellContent;
}
@freezed
class FieldEditorState with _$FieldEditorState {
const factory FieldEditorState({
required final FieldInfo field,
}) = _FieldEditorState;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field/type_option/edit_select_option_bloc.dart | import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:protobuf/protobuf.dart';
part 'edit_select_option_bloc.freezed.dart';
class EditSelectOptionBloc
extends Bloc<EditSelectOptionEvent, EditSelectOptionState> {
EditSelectOptionBloc({required SelectOptionPB option})
: super(EditSelectOptionState.initial(option)) {
on<EditSelectOptionEvent>(
(event, emit) async {
event.when(
updateName: (name) {
emit(state.copyWith(option: _updateName(name)));
},
updateColor: (color) {
emit(state.copyWith(option: _updateColor(color)));
},
delete: () {
emit(state.copyWith(deleted: true));
},
);
},
);
}
SelectOptionPB _updateColor(SelectOptionColorPB color) {
state.option.freeze();
return state.option.rebuild((option) {
option.color = color;
});
}
SelectOptionPB _updateName(String name) {
state.option.freeze();
return state.option.rebuild((option) {
option.name = name;
});
}
}
@freezed
class EditSelectOptionEvent with _$EditSelectOptionEvent {
const factory EditSelectOptionEvent.updateName(String name) = _UpdateName;
const factory EditSelectOptionEvent.updateColor(SelectOptionColorPB color) =
_UpdateColor;
const factory EditSelectOptionEvent.delete() = _Delete;
}
@freezed
class EditSelectOptionState with _$EditSelectOptionState {
const factory EditSelectOptionState({
required SelectOptionPB option,
required bool deleted,
}) = _EditSelectOptionState;
factory EditSelectOptionState.initial(SelectOptionPB option) =>
EditSelectOptionState(
option: option,
deleted: false,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field/type_option/select_type_option_actions.dart | import 'package:appflowy/plugins/database/domain/type_option_service.dart';
import 'package:appflowy/plugins/database/widgets/field/type_option_editor/builder.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart';
import 'package:nanoid/nanoid.dart';
abstract class ISelectOptionAction {
ISelectOptionAction({
required this.onTypeOptionUpdated,
required String viewId,
required String fieldId,
}) : service = TypeOptionBackendService(viewId: viewId, fieldId: fieldId);
final TypeOptionBackendService service;
final TypeOptionDataCallback onTypeOptionUpdated;
void updateTypeOption(List<SelectOptionPB> options) {
final newTypeOption = MultiSelectTypeOptionPB()..options.addAll(options);
onTypeOptionUpdated(newTypeOption.writeToBuffer());
}
List<SelectOptionPB> insertOption(
List<SelectOptionPB> options,
String optionName,
) {
if (options.any((element) => element.name == optionName)) {
return options;
}
final newOptions = List<SelectOptionPB>.from(options);
final newSelectOption = SelectOptionPB()
..id = nanoid(4)
..color = newSelectOptionColor(options)
..name = optionName;
newOptions.insert(0, newSelectOption);
updateTypeOption(newOptions);
return newOptions;
}
List<SelectOptionPB> deleteOption(
List<SelectOptionPB> options,
SelectOptionPB deletedOption,
) {
final newOptions = List<SelectOptionPB>.from(options);
final index =
newOptions.indexWhere((option) => option.id == deletedOption.id);
if (index != -1) {
newOptions.removeAt(index);
}
updateTypeOption(newOptions);
return newOptions;
}
List<SelectOptionPB> updateOption(
List<SelectOptionPB> options,
SelectOptionPB option,
) {
final newOptions = List<SelectOptionPB>.from(options);
final index = newOptions.indexWhere((element) => element.id == option.id);
if (index != -1) {
newOptions[index] = option;
}
updateTypeOption(newOptions);
return newOptions;
}
List<SelectOptionPB> reorderOption(
List<SelectOptionPB> options,
String fromOptionId,
String toOptionId,
) {
final newOptions = List<SelectOptionPB>.from(options);
final fromIndex =
newOptions.indexWhere((element) => element.id == fromOptionId);
final toIndex =
newOptions.indexWhere((element) => element.id == toOptionId);
if (fromIndex != -1 && toIndex != -1) {
newOptions.insert(toIndex, newOptions.removeAt(fromIndex));
}
updateTypeOption(newOptions);
return newOptions;
}
}
class MultiSelectAction extends ISelectOptionAction {
MultiSelectAction({
required super.viewId,
required super.fieldId,
required super.onTypeOptionUpdated,
});
@override
void updateTypeOption(List<SelectOptionPB> options) {
final newTypeOption = MultiSelectTypeOptionPB()..options.addAll(options);
onTypeOptionUpdated(newTypeOption.writeToBuffer());
}
}
class SingleSelectAction extends ISelectOptionAction {
SingleSelectAction({
required super.viewId,
required super.fieldId,
required super.onTypeOptionUpdated,
});
@override
void updateTypeOption(List<SelectOptionPB> options) {
final newTypeOption = SingleSelectTypeOptionPB()..options.addAll(options);
onTypeOptionUpdated(newTypeOption.writeToBuffer());
}
}
SelectOptionColorPB newSelectOptionColor(List<SelectOptionPB> options) {
final colorFrequency = List.filled(SelectOptionColorPB.values.length, 0);
for (final option in options) {
colorFrequency[option.color.value]++;
}
final minIndex = colorFrequency
.asMap()
.entries
.reduce((a, b) => a.value <= b.value ? a : b)
.key;
return SelectOptionColorPB.valueOf(minIndex) ?? SelectOptionColorPB.Purple;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field/type_option/number_format_bloc.dart | import 'package:appflowy_backend/protobuf/flowy-database2/number_entities.pbenum.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'number_format_bloc.freezed.dart';
class NumberFormatBloc extends Bloc<NumberFormatEvent, NumberFormatState> {
NumberFormatBloc() : super(NumberFormatState.initial()) {
on<NumberFormatEvent>(
(event, emit) async {
event.map(
setFilter: (_SetFilter value) {
final List<NumberFormatPB> formats =
List.from(NumberFormatPB.values);
if (value.filter.isNotEmpty) {
formats.retainWhere(
(element) => element
.title()
.toLowerCase()
.contains(value.filter.toLowerCase()),
);
}
emit(state.copyWith(formats: formats, filter: value.filter));
},
);
},
);
}
}
@freezed
class NumberFormatEvent with _$NumberFormatEvent {
const factory NumberFormatEvent.setFilter(String filter) = _SetFilter;
}
@freezed
class NumberFormatState with _$NumberFormatState {
const factory NumberFormatState({
required List<NumberFormatPB> formats,
required String filter,
}) = _NumberFormatState;
factory NumberFormatState.initial() {
return const NumberFormatState(
formats: NumberFormatPB.values,
filter: "",
);
}
}
extension NumberFormatExtension on NumberFormatPB {
String title() {
switch (this) {
case NumberFormatPB.ArgentinePeso:
return "Argentine peso";
case NumberFormatPB.Baht:
return "Baht";
case NumberFormatPB.CanadianDollar:
return "Canadian dollar";
case NumberFormatPB.ChileanPeso:
return "Chilean peso";
case NumberFormatPB.ColombianPeso:
return "Colombian peso";
case NumberFormatPB.DanishKrone:
return "Danish crown";
case NumberFormatPB.Dirham:
return "Dirham";
case NumberFormatPB.EUR:
return "Euro";
case NumberFormatPB.Forint:
return "Forint";
case NumberFormatPB.Franc:
return "Franc";
case NumberFormatPB.HongKongDollar:
return "Hone Kong dollar";
case NumberFormatPB.Koruna:
return "Koruna";
case NumberFormatPB.Krona:
return "Krona";
case NumberFormatPB.Leu:
return "Leu";
case NumberFormatPB.Lira:
return "Lira";
case NumberFormatPB.MexicanPeso:
return "Mexican peso";
case NumberFormatPB.NewTaiwanDollar:
return "New Taiwan dollar";
case NumberFormatPB.NewZealandDollar:
return "New Zealand dollar";
case NumberFormatPB.NorwegianKrone:
return "Norwegian krone";
case NumberFormatPB.Num:
return "Number";
case NumberFormatPB.Percent:
return "Percent";
case NumberFormatPB.PhilippinePeso:
return "Philippine peso";
case NumberFormatPB.Pound:
return "Pound";
case NumberFormatPB.Rand:
return "Rand";
case NumberFormatPB.Real:
return "Real";
case NumberFormatPB.Ringgit:
return "Ringgit";
case NumberFormatPB.Riyal:
return "Riyal";
case NumberFormatPB.Ruble:
return "Ruble";
case NumberFormatPB.Rupee:
return "Rupee";
case NumberFormatPB.Rupiah:
return "Rupiah";
case NumberFormatPB.Shekel:
return "Skekel";
case NumberFormatPB.USD:
return "US dollar";
case NumberFormatPB.UruguayanPeso:
return "Uruguayan peso";
case NumberFormatPB.Won:
return "Won";
case NumberFormatPB.Yen:
return "Yen";
case NumberFormatPB.Yuan:
return "Yuan";
default:
throw UnimplementedError;
}
}
String iconSymbol([bool defaultPrefixInc = true]) {
switch (this) {
case NumberFormatPB.ArgentinePeso:
return "\$";
case NumberFormatPB.Baht:
return "฿";
case NumberFormatPB.CanadianDollar:
return "C\$";
case NumberFormatPB.ChileanPeso:
return "\$";
case NumberFormatPB.ColombianPeso:
return "\$";
case NumberFormatPB.DanishKrone:
return "kr";
case NumberFormatPB.Dirham:
return "د.إ";
case NumberFormatPB.EUR:
return "€";
case NumberFormatPB.Forint:
return "Ft";
case NumberFormatPB.Franc:
return "Fr";
case NumberFormatPB.HongKongDollar:
return "HK\$";
case NumberFormatPB.Koruna:
return "Kč";
case NumberFormatPB.Krona:
return "kr";
case NumberFormatPB.Leu:
return "lei";
case NumberFormatPB.Lira:
return "₺";
case NumberFormatPB.MexicanPeso:
return "\$";
case NumberFormatPB.NewTaiwanDollar:
return "NT\$";
case NumberFormatPB.NewZealandDollar:
return "NZ\$";
case NumberFormatPB.NorwegianKrone:
return "kr";
case NumberFormatPB.Num:
return defaultPrefixInc ? "#" : "";
case NumberFormatPB.Percent:
return "%";
case NumberFormatPB.PhilippinePeso:
return "₱";
case NumberFormatPB.Pound:
return "£";
case NumberFormatPB.Rand:
return "R";
case NumberFormatPB.Real:
return "R\$";
case NumberFormatPB.Ringgit:
return "RM";
case NumberFormatPB.Riyal:
return "ر.س";
case NumberFormatPB.Ruble:
return "₽";
case NumberFormatPB.Rupee:
return "₹";
case NumberFormatPB.Rupiah:
return "Rp";
case NumberFormatPB.Shekel:
return "₪";
case NumberFormatPB.USD:
return "\$";
case NumberFormatPB.UruguayanPeso:
return "\$U";
case NumberFormatPB.Won:
return "₩";
case NumberFormatPB.Yen:
return "JPY ¥";
case NumberFormatPB.Yuan:
return "¥";
default:
throw UnimplementedError;
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field/type_option/type_option_data_parser.dart | import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
abstract class TypeOptionParser<T> {
T fromBuffer(List<int> buffer);
}
class RichTextTypeOptionDataParser
extends TypeOptionParser<RichTextTypeOptionPB> {
@override
RichTextTypeOptionPB fromBuffer(List<int> buffer) {
return RichTextTypeOptionPB.fromBuffer(buffer);
}
}
class NumberTypeOptionDataParser extends TypeOptionParser<NumberTypeOptionPB> {
@override
NumberTypeOptionPB fromBuffer(List<int> buffer) {
return NumberTypeOptionPB.fromBuffer(buffer);
}
}
class CheckboxTypeOptionDataParser
extends TypeOptionParser<CheckboxTypeOptionPB> {
@override
CheckboxTypeOptionPB fromBuffer(List<int> buffer) {
return CheckboxTypeOptionPB.fromBuffer(buffer);
}
}
class URLTypeOptionDataParser extends TypeOptionParser<URLTypeOptionPB> {
@override
URLTypeOptionPB fromBuffer(List<int> buffer) {
return URLTypeOptionPB.fromBuffer(buffer);
}
}
class DateTypeOptionDataParser extends TypeOptionParser<DateTypeOptionPB> {
@override
DateTypeOptionPB fromBuffer(List<int> buffer) {
return DateTypeOptionPB.fromBuffer(buffer);
}
}
class TimestampTypeOptionDataParser
extends TypeOptionParser<TimestampTypeOptionPB> {
@override
TimestampTypeOptionPB fromBuffer(List<int> buffer) {
return TimestampTypeOptionPB.fromBuffer(buffer);
}
}
class SingleSelectTypeOptionDataParser
extends TypeOptionParser<SingleSelectTypeOptionPB> {
@override
SingleSelectTypeOptionPB fromBuffer(List<int> buffer) {
return SingleSelectTypeOptionPB.fromBuffer(buffer);
}
}
class MultiSelectTypeOptionDataParser
extends TypeOptionParser<MultiSelectTypeOptionPB> {
@override
MultiSelectTypeOptionPB fromBuffer(List<int> buffer) {
return MultiSelectTypeOptionPB.fromBuffer(buffer);
}
}
class ChecklistTypeOptionDataParser
extends TypeOptionParser<ChecklistTypeOptionPB> {
@override
ChecklistTypeOptionPB fromBuffer(List<int> buffer) {
return ChecklistTypeOptionPB.fromBuffer(buffer);
}
}
class RelationTypeOptionDataParser
extends TypeOptionParser<RelationTypeOptionPB> {
@override
RelationTypeOptionPB fromBuffer(List<int> buffer) {
return RelationTypeOptionPB.fromBuffer(buffer);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field/type_option/select_option_type_option_bloc.dart | import 'package:appflowy_backend/protobuf/flowy-database2/select_option_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'select_type_option_actions.dart';
part 'select_option_type_option_bloc.freezed.dart';
class SelectOptionTypeOptionBloc
extends Bloc<SelectOptionTypeOptionEvent, SelectOptionTypeOptionState> {
SelectOptionTypeOptionBloc({
required List<SelectOptionPB> options,
required this.typeOptionAction,
}) : super(SelectOptionTypeOptionState.initial(options)) {
_dispatch();
}
final ISelectOptionAction typeOptionAction;
void _dispatch() {
on<SelectOptionTypeOptionEvent>(
(event, emit) async {
event.when(
createOption: (optionName) {
final List<SelectOptionPB> options =
typeOptionAction.insertOption(state.options, optionName);
emit(state.copyWith(options: options));
},
addingOption: () {
emit(state.copyWith(isEditingOption: true, newOptionName: null));
},
endAddingOption: () {
emit(state.copyWith(isEditingOption: false, newOptionName: null));
},
updateOption: (option) {
final options =
typeOptionAction.updateOption(state.options, option);
emit(state.copyWith(options: options));
},
deleteOption: (option) {
final options =
typeOptionAction.deleteOption(state.options, option);
emit(state.copyWith(options: options));
},
reorderOption: (fromOptionId, toOptionId) {
final options = typeOptionAction.reorderOption(
state.options,
fromOptionId,
toOptionId,
);
emit(state.copyWith(options: options));
},
);
},
);
}
}
@freezed
class SelectOptionTypeOptionEvent with _$SelectOptionTypeOptionEvent {
const factory SelectOptionTypeOptionEvent.createOption(String optionName) =
_CreateOption;
const factory SelectOptionTypeOptionEvent.addingOption() = _AddingOption;
const factory SelectOptionTypeOptionEvent.endAddingOption() =
_EndAddingOption;
const factory SelectOptionTypeOptionEvent.updateOption(
SelectOptionPB option,
) = _UpdateOption;
const factory SelectOptionTypeOptionEvent.deleteOption(
SelectOptionPB option,
) = _DeleteOption;
const factory SelectOptionTypeOptionEvent.reorderOption(
String fromOptionId,
String toOptionId,
) = _ReorderOption;
}
@freezed
class SelectOptionTypeOptionState with _$SelectOptionTypeOptionState {
const factory SelectOptionTypeOptionState({
required List<SelectOptionPB> options,
required bool isEditingOption,
required String? newOptionName,
}) = _SelectOptionTypeOptionState;
factory SelectOptionTypeOptionState.initial(List<SelectOptionPB> options) =>
SelectOptionTypeOptionState(
options: options,
isEditingOption: false,
newOptionName: null,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/field/type_option/relation_type_option_cubit.dart | import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'relation_type_option_cubit.freezed.dart';
class RelationDatabaseListCubit extends Cubit<RelationDatabaseListState> {
RelationDatabaseListCubit() : super(RelationDatabaseListState.initial()) {
_loadDatabaseMetas();
}
void _loadDatabaseMetas() async {
final getDatabaseResult = await DatabaseEventGetDatabases().send();
final metaPBs = getDatabaseResult.fold<List<DatabaseMetaPB>>(
(s) => s.items,
(f) => [],
);
final futures = metaPBs.map((meta) {
return ViewBackendService.getView(meta.inlineViewId).then(
(result) => result.fold(
(s) => DatabaseMeta(
databaseId: meta.databaseId,
inlineViewId: meta.inlineViewId,
databaseName: s.name,
),
(f) => null,
),
);
});
final databaseMetas = await Future.wait(futures);
emit(
RelationDatabaseListState(
databaseMetas: databaseMetas.nonNulls.toList(),
),
);
}
}
@freezed
class DatabaseMeta with _$DatabaseMeta {
factory DatabaseMeta({
/// id of the database
required String databaseId,
/// id of the inline view
required String inlineViewId,
/// name of the database, currently identical to the name of the inline view
required String databaseName,
}) = _DatabaseMeta;
}
@freezed
class RelationDatabaseListState with _$RelationDatabaseListState {
factory RelationDatabaseListState({
required List<DatabaseMeta> databaseMetas,
}) = _RelationDatabaseListState;
factory RelationDatabaseListState.initial() =>
RelationDatabaseListState(databaseMetas: []);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/row/row_cache.dart | import 'dart:collection';
import 'package:flutter/foundation.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../cell/cell_cache.dart';
import '../cell/cell_controller.dart';
import 'row_list.dart';
import 'row_service.dart';
part 'row_cache.freezed.dart';
typedef RowUpdateCallback = void Function();
/// A delegate that provides the fields of the row.
abstract class RowFieldsDelegate {
UnmodifiableListView<FieldInfo> get fieldInfos;
void onFieldsChanged(void Function(List<FieldInfo>) callback);
}
abstract mixin class RowLifeCycle {
void onRowDisposed();
}
/// Read https://docs.appflowy.io/docs/documentation/software-contributions/architecture/frontend/frontend/grid for more information.
class RowCache {
RowCache({
required this.viewId,
required RowFieldsDelegate fieldsDelegate,
required RowLifeCycle rowLifeCycle,
}) : _cellMemCache = CellMemCache(),
_changedNotifier = RowChangesetNotifier(),
_rowLifeCycle = rowLifeCycle,
_fieldDelegate = fieldsDelegate {
// Listen to field changes. If a field is deleted, we can safely remove the
// cells corresponding to that field from our cache.
fieldsDelegate.onFieldsChanged((fieldInfos) {
for (final fieldInfo in fieldInfos) {
_cellMemCache.removeCellWithFieldId(fieldInfo.id);
}
_changedNotifier.receive(const ChangedReason.fieldDidChange());
});
}
final String viewId;
final RowList _rowList = RowList();
final CellMemCache _cellMemCache;
final RowLifeCycle _rowLifeCycle;
final RowFieldsDelegate _fieldDelegate;
final RowChangesetNotifier _changedNotifier;
/// Returns a unmodifiable list of RowInfo
UnmodifiableListView<RowInfo> get rowInfos {
final visibleRows = [..._rowList.rows];
return UnmodifiableListView(visibleRows);
}
/// Returns a unmodifiable map of RowInfo
UnmodifiableMapView<RowId, RowInfo> get rowByRowId {
return UnmodifiableMapView(_rowList.rowInfoByRowId);
}
CellMemCache get cellCache => _cellMemCache;
ChangedReason get changeReason => _changedNotifier.reason;
RowInfo? getRow(RowId rowId) {
return _rowList.get(rowId);
}
void setInitialRows(List<RowMetaPB> rows) {
for (final row in rows) {
final rowInfo = buildGridRow(row);
_rowList.add(rowInfo);
}
_changedNotifier.receive(const ChangedReason.setInitialRows());
}
void dispose() {
_rowLifeCycle.onRowDisposed();
_changedNotifier.dispose();
_cellMemCache.dispose();
}
void applyRowsChanged(RowsChangePB changeset) {
_deleteRows(changeset.deletedRows);
_insertRows(changeset.insertedRows);
_updateRows(changeset.updatedRows);
}
void applyRowsVisibility(RowsVisibilityChangePB changeset) {
_hideRows(changeset.invisibleRows);
_showRows(changeset.visibleRows);
}
void reorderAllRows(List<String> rowIds) {
_rowList.reorderWithRowIds(rowIds);
_changedNotifier.receive(const ChangedReason.reorderRows());
}
void reorderSingleRow(ReorderSingleRowPB reorderRow) {
final rowInfo = _rowList.get(reorderRow.rowId);
if (rowInfo != null) {
_rowList.moveRow(
reorderRow.rowId,
reorderRow.oldIndex,
reorderRow.newIndex,
);
_changedNotifier.receive(
ChangedReason.reorderSingleRow(
reorderRow,
rowInfo,
),
);
}
}
void _deleteRows(List<RowId> deletedRowIds) {
for (final rowId in deletedRowIds) {
final deletedRow = _rowList.remove(rowId);
if (deletedRow != null) {
_changedNotifier.receive(ChangedReason.delete(deletedRow));
}
}
}
void _insertRows(List<InsertedRowPB> insertRows) {
for (final insertedRow in insertRows) {
final insertedIndex =
_rowList.insert(insertedRow.index, buildGridRow(insertedRow.rowMeta));
if (insertedIndex != null) {
_changedNotifier.receive(ChangedReason.insert(insertedIndex));
}
}
}
void _updateRows(List<UpdatedRowPB> updatedRows) {
if (updatedRows.isEmpty) return;
final List<RowMetaPB> updatedList = [];
for (final updatedRow in updatedRows) {
for (final fieldId in updatedRow.fieldIds) {
final key = CellContext(
fieldId: fieldId,
rowId: updatedRow.rowId,
);
_cellMemCache.remove(key);
}
if (updatedRow.hasRowMeta()) {
updatedList.add(updatedRow.rowMeta);
}
}
final updatedIndexs =
_rowList.updateRows(updatedList, (rowId) => buildGridRow(rowId));
if (updatedIndexs.isNotEmpty) {
_changedNotifier.receive(ChangedReason.update(updatedIndexs));
}
}
void _hideRows(List<RowId> invisibleRows) {
for (final rowId in invisibleRows) {
final deletedRow = _rowList.remove(rowId);
if (deletedRow != null) {
_changedNotifier.receive(ChangedReason.delete(deletedRow));
}
}
}
void _showRows(List<InsertedRowPB> visibleRows) {
for (final insertedRow in visibleRows) {
final insertedIndex =
_rowList.insert(insertedRow.index, buildGridRow(insertedRow.rowMeta));
if (insertedIndex != null) {
_changedNotifier.receive(ChangedReason.insert(insertedIndex));
}
}
}
void onRowsChanged(void Function(ChangedReason) onRowChanged) {
_changedNotifier.addListener(() {
onRowChanged(_changedNotifier.reason);
});
}
RowUpdateCallback addListener({
required RowId rowId,
void Function(List<CellContext>, ChangedReason)? onRowChanged,
}) {
void listenerHandler() async {
if (onRowChanged != null) {
final rowInfo = _rowList.get(rowId);
if (rowInfo != null) {
final cellDataMap = _makeCells(rowInfo.rowMeta);
onRowChanged(cellDataMap, _changedNotifier.reason);
}
}
}
_changedNotifier.addListener(listenerHandler);
return listenerHandler;
}
void removeRowListener(VoidCallback callback) {
_changedNotifier.removeListener(callback);
}
List<CellContext> loadCells(RowMetaPB rowMeta) {
final rowInfo = _rowList.get(rowMeta.id);
if (rowInfo == null) {
_loadRow(rowMeta.id);
}
return _makeCells(rowMeta);
}
Future<void> _loadRow(RowId rowId) async {
final result = await RowBackendService.getRow(viewId: viewId, rowId: rowId);
result.fold(
(rowMetaPB) {
final rowInfo = _rowList.get(rowMetaPB.id);
final rowIndex = _rowList.indexOfRow(rowMetaPB.id);
if (rowInfo != null && rowIndex != null) {
final updatedRowInfo = rowInfo.copyWith(rowMeta: rowMetaPB);
_rowList.remove(rowMetaPB.id);
_rowList.insert(rowIndex, updatedRowInfo);
final UpdatedIndexMap updatedIndexs = UpdatedIndexMap();
updatedIndexs[rowMetaPB.id] = UpdatedIndex(
index: rowIndex,
rowId: rowMetaPB.id,
);
_changedNotifier.receive(ChangedReason.update(updatedIndexs));
}
},
(err) => Log.error(err),
);
}
List<CellContext> _makeCells(RowMetaPB rowMeta) {
return _fieldDelegate.fieldInfos
.map(
(fieldInfo) => CellContext(
rowId: rowMeta.id,
fieldId: fieldInfo.id,
),
)
.toList();
}
RowInfo buildGridRow(RowMetaPB rowMetaPB) {
return RowInfo(
viewId: viewId,
fields: _fieldDelegate.fieldInfos,
rowId: rowMetaPB.id,
rowMeta: rowMetaPB,
);
}
}
class RowChangesetNotifier extends ChangeNotifier {
RowChangesetNotifier();
ChangedReason reason = const InitialListState();
void receive(ChangedReason newReason) {
reason = newReason;
reason.map(
insert: (_) => notifyListeners(),
delete: (_) => notifyListeners(),
update: (_) => notifyListeners(),
fieldDidChange: (_) => notifyListeners(),
initial: (_) {},
reorderRows: (_) => notifyListeners(),
reorderSingleRow: (_) => notifyListeners(),
setInitialRows: (_) => notifyListeners(),
);
}
}
@unfreezed
class RowInfo with _$RowInfo {
factory RowInfo({
required String rowId,
required String viewId,
required UnmodifiableListView<FieldInfo> fields,
required RowMetaPB rowMeta,
}) = _RowInfo;
}
typedef InsertedIndexs = List<InsertedIndex>;
typedef DeletedIndexs = List<DeletedIndex>;
// key: id of the row
// value: UpdatedIndex
typedef UpdatedIndexMap = LinkedHashMap<RowId, UpdatedIndex>;
@freezed
class ChangedReason with _$ChangedReason {
const factory ChangedReason.insert(InsertedIndex item) = _Insert;
const factory ChangedReason.delete(DeletedIndex item) = _Delete;
const factory ChangedReason.update(UpdatedIndexMap indexs) = _Update;
const factory ChangedReason.fieldDidChange() = _FieldDidChange;
const factory ChangedReason.initial() = InitialListState;
const factory ChangedReason.reorderRows() = _ReorderRows;
const factory ChangedReason.reorderSingleRow(
ReorderSingleRowPB reorderRow,
RowInfo rowInfo,
) = _ReorderSingleRow;
const factory ChangedReason.setInitialRows() = _SetInitialRows;
}
class InsertedIndex {
InsertedIndex({
required this.index,
required this.rowId,
});
final int index;
final RowId rowId;
}
class DeletedIndex {
DeletedIndex({
required this.index,
required this.rowInfo,
});
final int index;
final RowInfo rowInfo;
}
class UpdatedIndex {
UpdatedIndex({
required this.index,
required this.rowId,
});
final int index;
final RowId rowId;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/row/related_row_detail_bloc.dart | import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:bloc/bloc.dart';
import 'package:collection/collection.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../database_controller.dart';
import 'row_controller.dart';
part 'related_row_detail_bloc.freezed.dart';
class RelatedRowDetailPageBloc
extends Bloc<RelatedRowDetailPageEvent, RelatedRowDetailPageState> {
RelatedRowDetailPageBloc({
required String databaseId,
required String initialRowId,
}) : super(const RelatedRowDetailPageState.loading()) {
_dispatch();
_init(databaseId, initialRowId);
}
@override
Future<void> close() {
state.whenOrNull(
ready: (databaseController, rowController) {
rowController.dispose();
databaseController.dispose();
},
);
return super.close();
}
void _dispatch() {
on<RelatedRowDetailPageEvent>((event, emit) async {
event.when(
didInitialize: (databaseController, rowController) {
state.maybeWhen(
ready: (_, oldRowController) {
oldRowController.dispose();
emit(
RelatedRowDetailPageState.ready(
databaseController: databaseController,
rowController: rowController,
),
);
},
orElse: () {
emit(
RelatedRowDetailPageState.ready(
databaseController: databaseController,
rowController: rowController,
),
);
},
);
},
);
});
}
/// initialize bloc through the `database_id` and `row_id`. The process is as
/// follows:
/// 1. use the `database_id` to get the database meta, which contains the
/// `inline_view_id`
/// 2. use the `inline_view_id` to instantiate a `DatabaseController`.
/// 3. use the `row_id` with the DatabaseController` to create `RowController`
void _init(String databaseId, String initialRowId) async {
final databaseMeta = await DatabaseEventGetDatabases()
.send()
.fold<DatabaseMetaPB?>(
(s) => s.items
.firstWhereOrNull((metaPB) => metaPB.databaseId == databaseId),
(f) => null,
);
if (databaseMeta == null) {
return;
}
final inlineView =
await ViewBackendService.getView(databaseMeta.inlineViewId)
.fold((viewPB) => viewPB, (f) => null);
if (inlineView == null) {
return;
}
final databaseController = DatabaseController(view: inlineView);
await databaseController.open().fold(
(s) => databaseController.setIsLoading(false),
(f) => null,
);
final rowInfo = databaseController.rowCache.getRow(initialRowId);
if (rowInfo == null) {
return;
}
final rowController = RowController(
rowMeta: rowInfo.rowMeta,
viewId: inlineView.id,
rowCache: databaseController.rowCache,
);
add(
RelatedRowDetailPageEvent.didInitialize(
databaseController,
rowController,
),
);
}
}
@freezed
class RelatedRowDetailPageEvent with _$RelatedRowDetailPageEvent {
const factory RelatedRowDetailPageEvent.didInitialize(
DatabaseController databaseController,
RowController rowController,
) = _DidInitialize;
}
@freezed
class RelatedRowDetailPageState with _$RelatedRowDetailPageState {
const factory RelatedRowDetailPageState.loading() = _LoadingState;
const factory RelatedRowDetailPageState.ready({
required DatabaseController databaseController,
required RowController rowController,
}) = _ReadyState;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/row/row_service.dart | import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import '../field/field_info.dart';
typedef RowId = String;
class RowBackendService {
RowBackendService({required this.viewId});
final String viewId;
static Future<FlowyResult<RowMetaPB, FlowyError>> createRow({
required String viewId,
String? groupId,
void Function(RowDataBuilder builder)? withCells,
OrderObjectPositionTypePB? position,
String? targetRowId,
}) {
final payload = CreateRowPayloadPB(
viewId: viewId,
groupId: groupId,
rowPosition: OrderObjectPositionPB(
position: position,
objectId: targetRowId,
),
);
if (withCells != null) {
final rowBuilder = RowDataBuilder();
withCells(rowBuilder);
payload.data.addAll(rowBuilder.build());
}
return DatabaseEventCreateRow(payload).send();
}
Future<FlowyResult<RowMetaPB, FlowyError>> createRowBefore(RowId rowId) {
return createRow(
viewId: viewId,
position: OrderObjectPositionTypePB.Before,
targetRowId: rowId,
);
}
Future<FlowyResult<RowMetaPB, FlowyError>> createRowAfter(RowId rowId) {
return createRow(
viewId: viewId,
position: OrderObjectPositionTypePB.After,
targetRowId: rowId,
);
}
static Future<FlowyResult<RowMetaPB, FlowyError>> getRow({
required String viewId,
required String rowId,
}) {
final payload = RowIdPB()
..viewId = viewId
..rowId = rowId;
return DatabaseEventGetRowMeta(payload).send();
}
Future<FlowyResult<RowMetaPB, FlowyError>> getRowMeta(RowId rowId) {
final payload = RowIdPB.create()
..viewId = viewId
..rowId = rowId;
return DatabaseEventGetRowMeta(payload).send();
}
Future<FlowyResult<void, FlowyError>> updateMeta({
required String rowId,
String? iconURL,
String? coverURL,
bool? isDocumentEmpty,
}) {
final payload = UpdateRowMetaChangesetPB.create()
..viewId = viewId
..id = rowId;
if (iconURL != null) {
payload.iconUrl = iconURL;
}
if (coverURL != null) {
payload.coverUrl = coverURL;
}
if (isDocumentEmpty != null) {
payload.isDocumentEmpty = isDocumentEmpty;
}
return DatabaseEventUpdateRowMeta(payload).send();
}
static Future<FlowyResult<void, FlowyError>> deleteRow(
String viewId,
RowId rowId,
) {
final payload = RowIdPB.create()
..viewId = viewId
..rowId = rowId;
return DatabaseEventDeleteRow(payload).send();
}
static Future<FlowyResult<void, FlowyError>> duplicateRow(
String viewId,
RowId rowId,
) {
final payload = RowIdPB(
viewId: viewId,
rowId: rowId,
);
return DatabaseEventDuplicateRow(payload).send();
}
}
class RowDataBuilder {
final _cellDataByFieldId = <String, String>{};
void insertText(FieldInfo fieldInfo, String text) {
assert(fieldInfo.fieldType == FieldType.RichText);
_cellDataByFieldId[fieldInfo.field.id] = text;
}
void insertNumber(FieldInfo fieldInfo, int num) {
assert(fieldInfo.fieldType == FieldType.Number);
_cellDataByFieldId[fieldInfo.field.id] = num.toString();
}
void insertDate(FieldInfo fieldInfo, DateTime date) {
assert(fieldInfo.fieldType == FieldType.DateTime);
final timestamp = date.millisecondsSinceEpoch ~/ 1000;
_cellDataByFieldId[fieldInfo.field.id] = timestamp.toString();
}
Map<String, String> build() {
return _cellDataByFieldId;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/row/row_list.dart | import 'dart:collection';
import 'package:appflowy_backend/protobuf/flowy-database2/row_entities.pb.dart';
import 'row_cache.dart';
import 'row_service.dart';
class RowList {
/// Use List to reverse the order of the row.
List<RowInfo> _rowInfos = [];
List<RowInfo> get rows => List.from(_rowInfos);
/// Use Map for faster access the raw row data.
final HashMap<RowId, RowInfo> rowInfoByRowId = HashMap();
RowInfo? get(RowId rowId) {
return rowInfoByRowId[rowId];
}
int? indexOfRow(RowId rowId) {
final rowInfo = rowInfoByRowId[rowId];
if (rowInfo != null) {
return _rowInfos.indexOf(rowInfo);
}
return null;
}
void add(RowInfo rowInfo) {
final rowId = rowInfo.rowId;
if (contains(rowId)) {
final index = _rowInfos.indexWhere((element) => element.rowId == rowId);
_rowInfos.removeAt(index);
_rowInfos.insert(index, rowInfo);
} else {
_rowInfos.add(rowInfo);
}
rowInfoByRowId[rowId] = rowInfo;
}
InsertedIndex? insert(int index, RowInfo rowInfo) {
final rowId = rowInfo.rowId;
var insertedIndex = index;
if (_rowInfos.length <= insertedIndex) {
insertedIndex = _rowInfos.length;
}
final oldRowInfo = get(rowId);
if (oldRowInfo != null) {
_rowInfos.insert(insertedIndex, rowInfo);
_rowInfos.remove(oldRowInfo);
rowInfoByRowId[rowId] = rowInfo;
return null;
} else {
_rowInfos.insert(insertedIndex, rowInfo);
rowInfoByRowId[rowId] = rowInfo;
return InsertedIndex(index: insertedIndex, rowId: rowId);
}
}
DeletedIndex? remove(RowId rowId) {
final rowInfo = rowInfoByRowId[rowId];
if (rowInfo != null) {
final index = _rowInfos.indexOf(rowInfo);
if (index != -1) {
rowInfoByRowId.remove(rowInfo.rowId);
_rowInfos.remove(rowInfo);
}
return DeletedIndex(index: index, rowInfo: rowInfo);
} else {
return null;
}
}
InsertedIndexs insertRows(
List<InsertedRowPB> insertedRows,
RowInfo Function(RowMetaPB) builder,
) {
final InsertedIndexs insertIndexs = [];
for (final insertRow in insertedRows) {
final isContains = contains(insertRow.rowMeta.id);
var index = insertRow.index;
if (_rowInfos.length < index) {
index = _rowInfos.length;
}
insert(index, builder(insertRow.rowMeta));
if (!isContains) {
insertIndexs.add(
InsertedIndex(
index: index,
rowId: insertRow.rowMeta.id,
),
);
}
}
return insertIndexs;
}
DeletedIndexs removeRows(List<String> rowIds) {
final List<RowInfo> newRows = [];
final DeletedIndexs deletedIndex = [];
final Map<String, String> deletedRowByRowId = {
for (final rowId in rowIds) rowId: rowId,
};
_rowInfos.asMap().forEach((index, RowInfo rowInfo) {
if (deletedRowByRowId[rowInfo.rowId] == null) {
newRows.add(rowInfo);
} else {
rowInfoByRowId.remove(rowInfo.rowId);
deletedIndex.add(DeletedIndex(index: index, rowInfo: rowInfo));
}
});
_rowInfos = newRows;
return deletedIndex;
}
UpdatedIndexMap updateRows(
List<RowMetaPB> rowMetas,
RowInfo Function(RowMetaPB) builder,
) {
final UpdatedIndexMap updatedIndexs = UpdatedIndexMap();
for (final rowMeta in rowMetas) {
final index = _rowInfos.indexWhere(
(rowInfo) => rowInfo.rowId == rowMeta.id,
);
if (index != -1) {
final rowInfo = builder(rowMeta);
insert(index, rowInfo);
updatedIndexs[rowMeta.id] = UpdatedIndex(
index: index,
rowId: rowMeta.id,
);
}
}
return updatedIndexs;
}
void reorderWithRowIds(List<String> rowIds) {
_rowInfos.clear();
for (final rowId in rowIds) {
final rowInfo = rowInfoByRowId[rowId];
if (rowInfo != null) {
_rowInfos.add(rowInfo);
}
}
}
void moveRow(RowId rowId, int oldIndex, int newIndex) {
final index = _rowInfos.indexWhere(
(rowInfo) => rowInfo.rowId == rowId,
);
if (index != -1) {
final rowInfo = remove(rowId)!.rowInfo;
insert(newIndex, rowInfo);
}
}
bool contains(RowId rowId) {
return rowInfoByRowId[rowId] != null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/row/row_controller.dart | import 'package:appflowy_backend/protobuf/flowy-database2/row_entities.pb.dart';
import 'package:flutter/material.dart';
import '../cell/cell_cache.dart';
import '../cell/cell_controller.dart';
import 'row_cache.dart';
typedef OnRowChanged = void Function(List<CellContext>, ChangedReason);
class RowController {
RowController({
required this.rowMeta,
required this.viewId,
required RowCache rowCache,
this.groupId,
}) : _rowCache = rowCache;
final RowMetaPB rowMeta;
final String? groupId;
final String viewId;
final List<VoidCallback> _onRowChangedListeners = [];
final RowCache _rowCache;
CellMemCache get cellCache => _rowCache.cellCache;
String get rowId => rowMeta.id;
List<CellContext> loadData() => _rowCache.loadCells(rowMeta);
void addListener({OnRowChanged? onRowChanged}) {
final fn = _rowCache.addListener(
rowId: rowMeta.id,
onRowChanged: onRowChanged,
);
// Add the listener to the list so that we can remove it later.
_onRowChangedListeners.add(fn);
}
void dispose() {
for (final fn in _onRowChangedListeners) {
_rowCache.removeRowListener(fn);
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/row/row_banner_bloc.dart | import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/domain/field_service.dart';
import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../domain/row_meta_listener.dart';
part 'row_banner_bloc.freezed.dart';
class RowBannerBloc extends Bloc<RowBannerEvent, RowBannerState> {
RowBannerBloc({
required this.viewId,
required this.fieldController,
required RowMetaPB rowMeta,
}) : _rowBackendSvc = RowBackendService(viewId: viewId),
_metaListener = RowMetaListener(rowMeta.id),
super(RowBannerState.initial(rowMeta)) {
_dispatch();
}
final String viewId;
final FieldController fieldController;
final RowBackendService _rowBackendSvc;
final RowMetaListener _metaListener;
@override
Future<void> close() async {
await _metaListener.stop();
return super.close();
}
void _dispatch() {
on<RowBannerEvent>(
(event, emit) {
event.when(
initial: () {
_loadPrimaryField();
_listenRowMetaChanged();
},
didReceiveRowMeta: (RowMetaPB rowMeta) {
emit(state.copyWith(rowMeta: rowMeta));
},
setCover: (String coverURL) => _updateMeta(coverURL: coverURL),
setIcon: (String iconURL) => _updateMeta(iconURL: iconURL),
didReceiveFieldUpdate: (updatedField) {
emit(
state.copyWith(
primaryField: updatedField,
loadingState: const LoadingState.finish(),
),
);
},
);
},
);
}
Future<void> _loadPrimaryField() async {
final fieldOrError =
await FieldBackendService.getPrimaryField(viewId: viewId);
fieldOrError.fold(
(primaryField) {
if (!isClosed) {
fieldController.addSingleFieldListener(
primaryField.id,
onFieldChanged: (updatedField) {
if (!isClosed) {
add(RowBannerEvent.didReceiveFieldUpdate(updatedField.field));
}
},
);
add(RowBannerEvent.didReceiveFieldUpdate(primaryField));
}
},
(r) => Log.error(r),
);
}
/// Listen the changes of the row meta and then update the banner
void _listenRowMetaChanged() {
_metaListener.start(
callback: (rowMeta) {
if (!isClosed) {
add(RowBannerEvent.didReceiveRowMeta(rowMeta));
}
},
);
}
/// Update the meta of the row and the view
Future<void> _updateMeta({String? iconURL, String? coverURL}) async {
final result = await _rowBackendSvc.updateMeta(
iconURL: iconURL,
coverURL: coverURL,
rowId: state.rowMeta.id,
);
result.fold((l) => null, (err) => Log.error(err));
}
}
@freezed
class RowBannerEvent with _$RowBannerEvent {
const factory RowBannerEvent.initial() = _Initial;
const factory RowBannerEvent.didReceiveRowMeta(RowMetaPB rowMeta) =
_DidReceiveRowMeta;
const factory RowBannerEvent.didReceiveFieldUpdate(FieldPB field) =
_DidReceiveFieldUpdate;
const factory RowBannerEvent.setIcon(String iconURL) = _SetIcon;
const factory RowBannerEvent.setCover(String coverURL) = _SetCover;
}
@freezed
class RowBannerState with _$RowBannerState {
const factory RowBannerState({
required FieldPB? primaryField,
required RowMetaPB rowMeta,
required LoadingState loadingState,
}) = _RowBannerState;
factory RowBannerState.initial(RowMetaPB rowMetaPB) => RowBannerState(
primaryField: null,
rowMeta: rowMetaPB,
loadingState: const LoadingState.loading(),
);
}
@freezed
class LoadingState with _$LoadingState {
const factory LoadingState.loading() = _Loading;
const factory LoadingState.finish() = _Finish;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/calculations/calculations_listener.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy/core/notification/grid_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef UpdateCalculationValue
= FlowyResult<CalculationChangesetNotificationPB, FlowyError>;
class CalculationsListener {
CalculationsListener({required this.viewId});
final String viewId;
PublishNotifier<UpdateCalculationValue>? _calculationNotifier =
PublishNotifier();
DatabaseNotificationListener? _listener;
void start({
required void Function(UpdateCalculationValue) onCalculationChanged,
}) {
_calculationNotifier?.addPublishListener(onCalculationChanged);
_listener = DatabaseNotificationListener(
objectId: viewId,
handler: _handler,
);
}
void _handler(
DatabaseNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case DatabaseNotification.DidUpdateCalculation:
_calculationNotifier?.value = result.fold(
(payload) => FlowyResult.success(
CalculationChangesetNotificationPB.fromBuffer(payload),
),
(err) => FlowyResult.failure(err),
);
default:
break;
}
}
Future<void> stop() async {
await _listener?.stop();
_calculationNotifier?.dispose();
_calculationNotifier = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/calculations/calculations_service.dart | import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
class CalculationsBackendService {
const CalculationsBackendService({required this.viewId});
final String viewId;
// Get Calculations (initial fetch)
Future<FlowyResult<RepeatedCalculationsPB, FlowyError>>
getCalculations() async {
final payload = DatabaseViewIdPB()..value = viewId;
return DatabaseEventGetAllCalculations(payload).send();
}
Future<void> updateCalculation(
String fieldId,
CalculationType type, {
String? calculationId,
}) async {
final payload = UpdateCalculationChangesetPB()
..viewId = viewId
..fieldId = fieldId
..calculationType = type;
if (calculationId != null) {
payload.calculationId = calculationId;
}
await DatabaseEventUpdateCalculation(payload).send();
}
Future<void> removeCalculation(
String fieldId,
String calculationId,
) async {
final payload = RemoveCalculationChangesetPB()
..viewId = viewId
..fieldId = fieldId
..calculationId = calculationId;
await DatabaseEventRemoveCalculation(payload).send();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/calculations/calculation_type_ext.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
extension CalcTypeLabel on CalculationType {
String get label => switch (this) {
CalculationType.Average =>
LocaleKeys.grid_calculationTypeLabel_average.tr(),
CalculationType.Max => LocaleKeys.grid_calculationTypeLabel_max.tr(),
CalculationType.Median =>
LocaleKeys.grid_calculationTypeLabel_median.tr(),
CalculationType.Min => LocaleKeys.grid_calculationTypeLabel_min.tr(),
CalculationType.Sum => LocaleKeys.grid_calculationTypeLabel_sum.tr(),
CalculationType.Count =>
LocaleKeys.grid_calculationTypeLabel_count.tr(),
CalculationType.CountEmpty =>
LocaleKeys.grid_calculationTypeLabel_countEmpty.tr(),
CalculationType.CountNonEmpty =>
LocaleKeys.grid_calculationTypeLabel_countNonEmpty.tr(),
_ => throw UnimplementedError(
'Label for $this has not been implemented',
),
};
String get shortLabel => switch (this) {
CalculationType.CountEmpty =>
LocaleKeys.grid_calculationTypeLabel_countEmptyShort.tr(),
CalculationType.CountNonEmpty =>
LocaleKeys.grid_calculationTypeLabel_countNonEmptyShort.tr(),
_ => label,
};
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/application/layout/layout_bloc.dart | import 'package:appflowy/plugins/database/domain/database_view_service.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/setting_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'layout_bloc.freezed.dart';
class DatabaseLayoutBloc
extends Bloc<DatabaseLayoutEvent, DatabaseLayoutState> {
DatabaseLayoutBloc({
required String viewId,
required DatabaseLayoutPB databaseLayout,
}) : super(DatabaseLayoutState.initial(viewId, databaseLayout)) {
on<DatabaseLayoutEvent>(
(event, emit) async {
event.when(
initial: () {},
updateLayout: (DatabaseLayoutPB layout) {
DatabaseViewBackendService.updateLayout(
viewId: viewId,
layout: layout,
);
emit(state.copyWith(databaseLayout: layout));
},
);
},
);
}
}
@freezed
class DatabaseLayoutEvent with _$DatabaseLayoutEvent {
const factory DatabaseLayoutEvent.initial() = _Initial;
const factory DatabaseLayoutEvent.updateLayout(DatabaseLayoutPB layout) =
_UpdateLayout;
}
@freezed
class DatabaseLayoutState with _$DatabaseLayoutState {
const factory DatabaseLayoutState({
required String viewId,
required DatabaseLayoutPB databaseLayout,
}) = _DatabaseLayoutState;
factory DatabaseLayoutState.initial(
String viewId,
DatabaseLayoutPB databaseLayout,
) =>
DatabaseLayoutState(
viewId: viewId,
databaseLayout: databaseLayout,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/calendar.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/tab_bar/tab_bar_view.dart';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
class CalendarPluginBuilder extends PluginBuilder {
@override
Plugin build(dynamic data) {
if (data is ViewPB) {
return DatabaseTabBarViewPlugin(pluginType: pluginType, view: data);
} else {
throw FlowyPluginException.invalidData;
}
}
@override
String get menuName => LocaleKeys.calendar_menuName.tr();
@override
FlowySvgData get icon => FlowySvgs.date_s;
@override
PluginType get pluginType => PluginType.calendar;
@override
ViewLayoutPB? get layoutType => ViewLayoutPB.Calendar;
}
class CalendarPluginConfig implements PluginConfig {
@override
bool get creatable => true;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/application/calendar_event_editor_bloc.dart | import 'package:appflowy/plugins/database/application/cell/cell_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/row/row_controller.dart';
import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy/plugins/database/widgets/setting/field_visibility_extension.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/calendar_entities.pb.dart';
import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'calendar_event_editor_bloc.freezed.dart';
class CalendarEventEditorBloc
extends Bloc<CalendarEventEditorEvent, CalendarEventEditorState> {
CalendarEventEditorBloc({
required this.fieldController,
required this.rowController,
required this.layoutSettings,
}) : super(CalendarEventEditorState.initial()) {
_dispatch();
}
final FieldController fieldController;
final RowController rowController;
final CalendarLayoutSettingPB layoutSettings;
void _dispatch() {
on<CalendarEventEditorEvent>(
(event, emit) async {
await event.when(
initial: () {
_startListening();
final primaryFieldId = fieldController.fieldInfos
.firstWhere((fieldInfo) => fieldInfo.isPrimary)
.id;
final cells = rowController
.loadData()
.where(
(cellContext) =>
_filterCellContext(cellContext, primaryFieldId),
)
.toList();
add(CalendarEventEditorEvent.didReceiveCellDatas(cells));
},
didReceiveCellDatas: (cells) {
emit(state.copyWith(cells: cells));
},
delete: () async {
final result = await RowBackendService.deleteRow(
rowController.viewId,
rowController.rowId,
);
result.fold((l) => null, (err) => Log.error(err));
},
);
},
);
}
void _startListening() {
rowController.addListener(
onRowChanged: (cells, reason) {
if (isClosed) {
return;
}
final primaryFieldId = fieldController.fieldInfos
.firstWhere((fieldInfo) => fieldInfo.isPrimary)
.id;
final cellData = cells
.where(
(cellContext) => _filterCellContext(cellContext, primaryFieldId),
)
.toList();
add(CalendarEventEditorEvent.didReceiveCellDatas(cellData));
},
);
}
bool _filterCellContext(CellContext cellContext, String primaryFieldId) {
return fieldController
.getField(cellContext.fieldId)!
.fieldSettings!
.visibility
.isVisibleState() ||
cellContext.fieldId == layoutSettings.fieldId ||
cellContext.fieldId == primaryFieldId;
}
@override
Future<void> close() async {
rowController.dispose();
return super.close();
}
}
@freezed
class CalendarEventEditorEvent with _$CalendarEventEditorEvent {
const factory CalendarEventEditorEvent.initial() = _Initial;
const factory CalendarEventEditorEvent.didReceiveCellDatas(
List<CellContext> cells,
) = _DidReceiveCellDatas;
const factory CalendarEventEditorEvent.delete() = _Delete;
}
@freezed
class CalendarEventEditorState with _$CalendarEventEditorState {
const factory CalendarEventEditorState({
required List<CellContext> cells,
}) = _CalendarEventEditorState;
factory CalendarEventEditorState.initial() =>
const CalendarEventEditorState(cells: []);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/application/calendar_setting_bloc.dart | import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/domain/layout_setting_listener.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:protobuf/protobuf.dart';
part 'calendar_setting_bloc.freezed.dart';
typedef DayOfWeek = int;
class CalendarSettingBloc
extends Bloc<CalendarSettingEvent, CalendarSettingState> {
CalendarSettingBloc({required DatabaseController databaseController})
: _databaseController = databaseController,
_listener = DatabaseLayoutSettingListener(databaseController.viewId),
super(
CalendarSettingState.initial(
databaseController.databaseLayoutSetting?.calendar,
),
) {
_dispatch();
}
final DatabaseController _databaseController;
final DatabaseLayoutSettingListener _listener;
@override
Future<void> close() async {
await _listener.stop();
return super.close();
}
void _dispatch() {
on<CalendarSettingEvent>((event, emit) {
event.when(
initial: () {
_startListening();
},
didUpdateLayoutSetting: (CalendarLayoutSettingPB setting) {
emit(state.copyWith(layoutSetting: layoutSetting));
},
updateLayoutSetting: (
bool? showWeekends,
bool? showWeekNumbers,
int? firstDayOfWeek,
String? layoutFieldId,
) {
_updateLayoutSettings(
showWeekends,
showWeekNumbers,
firstDayOfWeek,
layoutFieldId,
emit,
);
},
);
});
}
void _updateLayoutSettings(
bool? showWeekends,
bool? showWeekNumbers,
int? firstDayOfWeek,
String? layoutFieldId,
Emitter<CalendarSettingState> emit,
) {
final currentSetting = state.layoutSetting;
if (currentSetting == null) {
return;
}
currentSetting.freeze();
final newSetting = currentSetting.rebuild((setting) {
if (showWeekends != null) {
setting.showWeekends = !showWeekends;
}
if (showWeekNumbers != null) {
setting.showWeekNumbers = !showWeekNumbers;
}
if (firstDayOfWeek != null) {
setting.firstDayOfWeek = firstDayOfWeek;
}
if (layoutFieldId != null) {
setting.fieldId = layoutFieldId;
}
});
_databaseController.updateLayoutSetting(
calendarLayoutSetting: newSetting,
);
emit(state.copyWith(layoutSetting: newSetting));
}
CalendarLayoutSettingPB? get layoutSetting =>
_databaseController.databaseLayoutSetting?.calendar;
void _startListening() {
_listener.start(
onLayoutChanged: (result) {
if (isClosed) {
return;
}
result.fold(
(setting) => add(
CalendarSettingEvent.didUpdateLayoutSetting(setting.calendar),
),
(r) => Log.error(r),
);
},
);
}
}
@freezed
class CalendarSettingState with _$CalendarSettingState {
const factory CalendarSettingState({
required CalendarLayoutSettingPB? layoutSetting,
}) = _CalendarSettingState;
factory CalendarSettingState.initial(
CalendarLayoutSettingPB? layoutSettings,
) {
return CalendarSettingState(layoutSetting: layoutSettings);
}
}
@freezed
class CalendarSettingEvent with _$CalendarSettingEvent {
const factory CalendarSettingEvent.initial() = _Initial;
const factory CalendarSettingEvent.didUpdateLayoutSetting(
CalendarLayoutSettingPB setting,
) = _DidUpdateLayoutSetting;
const factory CalendarSettingEvent.updateLayoutSetting({
bool? showWeekends,
bool? showWeekNumbers,
int? firstDayOfWeek,
String? layoutFieldId,
}) = _UpdateLayoutSetting;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/application/unschedule_event_bloc.dart | import 'package:appflowy/plugins/database/application/cell/cell_cache.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../application/database_controller.dart';
import '../../application/row/row_cache.dart';
part 'unschedule_event_bloc.freezed.dart';
class UnscheduleEventsBloc
extends Bloc<UnscheduleEventsEvent, UnscheduleEventsState> {
UnscheduleEventsBloc({required this.databaseController})
: super(UnscheduleEventsState.initial()) {
_dispatch();
}
final DatabaseController databaseController;
Map<String, FieldInfo> fieldInfoByFieldId = {};
// Getters
String get viewId => databaseController.viewId;
FieldController get fieldController => databaseController.fieldController;
CellMemCache get cellCache => databaseController.rowCache.cellCache;
RowCache get rowCache => databaseController.rowCache;
void _dispatch() {
on<UnscheduleEventsEvent>(
(event, emit) async {
await event.when(
initial: () async {
_startListening();
_loadAllEvents();
},
didLoadAllEvents: (events) {
emit(
state.copyWith(
allEvents: events,
unscheduleEvents:
events.where((element) => !element.isScheduled).toList(),
),
);
},
didDeleteEvents: (List<RowId> deletedRowIds) {
final events = [...state.allEvents];
events.retainWhere(
(element) => !deletedRowIds.contains(element.rowMeta.id),
);
emit(
state.copyWith(
allEvents: events,
unscheduleEvents:
events.where((element) => !element.isScheduled).toList(),
),
);
},
didReceiveEvent: (CalendarEventPB event) {
final events = [...state.allEvents, event];
emit(
state.copyWith(
allEvents: events,
unscheduleEvents:
events.where((element) => !element.isScheduled).toList(),
),
);
},
);
},
);
}
Future<CalendarEventPB?> _loadEvent(
RowId rowId,
) async {
final payload = RowIdPB(viewId: viewId, rowId: rowId);
return DatabaseEventGetCalendarEvent(payload).send().then(
(result) => result.fold(
(eventPB) => eventPB,
(r) {
Log.error(r);
return null;
},
),
);
}
void _loadAllEvents() async {
final payload = CalendarEventRequestPB.create()..viewId = viewId;
final result = await DatabaseEventGetAllCalendarEvents(payload).send();
result.fold(
(events) {
if (!isClosed) {
add(UnscheduleEventsEvent.didLoadAllEvents(events.items));
}
},
(r) => Log.error(r),
);
}
void _startListening() {
final onDatabaseChanged = DatabaseCallbacks(
onRowsCreated: (rowIds) async {
if (isClosed) {
return;
}
for (final id in rowIds) {
final event = await _loadEvent(id);
if (event != null && !isClosed) {
add(UnscheduleEventsEvent.didReceiveEvent(event));
}
}
},
onRowsDeleted: (rowIds) {
if (isClosed) {
return;
}
add(UnscheduleEventsEvent.didDeleteEvents(rowIds));
},
onRowsUpdated: (rowIds, reason) async {
if (isClosed) {
return;
}
for (final id in rowIds) {
final event = await _loadEvent(id);
if (event != null) {
add(UnscheduleEventsEvent.didDeleteEvents([id]));
add(UnscheduleEventsEvent.didReceiveEvent(event));
}
}
},
);
databaseController.addListener(onDatabaseChanged: onDatabaseChanged);
}
}
@freezed
class UnscheduleEventsEvent with _$UnscheduleEventsEvent {
const factory UnscheduleEventsEvent.initial() = _InitialCalendar;
// Called after loading all the current evnets
const factory UnscheduleEventsEvent.didLoadAllEvents(
List<CalendarEventPB> events,
) = _ReceiveUnscheduleEventsEvents;
const factory UnscheduleEventsEvent.didDeleteEvents(List<RowId> rowIds) =
_DidDeleteEvents;
const factory UnscheduleEventsEvent.didReceiveEvent(
CalendarEventPB event,
) = _DidReceiveEvent;
}
@freezed
class UnscheduleEventsState with _$UnscheduleEventsState {
const factory UnscheduleEventsState({
required DatabasePB? database,
required List<CalendarEventPB> allEvents,
required List<CalendarEventPB> unscheduleEvents,
}) = _UnscheduleEventsState;
factory UnscheduleEventsState.initial() => const UnscheduleEventsState(
database: null,
allEvents: [],
unscheduleEvents: [],
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/application/calendar_bloc.dart | import 'package:appflowy/plugins/database/application/cell/cell_cache.dart';
import 'package:appflowy/plugins/database/application/defines.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:calendar_view/calendar_view.dart';
import 'package:fixnum/fixnum.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../application/database_controller.dart';
import '../../application/row/row_cache.dart';
part 'calendar_bloc.freezed.dart';
class CalendarBloc extends Bloc<CalendarEvent, CalendarState> {
CalendarBloc({required this.databaseController})
: super(CalendarState.initial()) {
_dispatch();
}
final DatabaseController databaseController;
Map<String, FieldInfo> fieldInfoByFieldId = {};
// Getters
String get viewId => databaseController.viewId;
FieldController get fieldController => databaseController.fieldController;
CellMemCache get cellCache => databaseController.rowCache.cellCache;
RowCache get rowCache => databaseController.rowCache;
void _dispatch() {
on<CalendarEvent>(
(event, emit) async {
await event.when(
initial: () async {
_startListening();
await _openDatabase(emit);
_loadAllEvents();
},
didReceiveCalendarSettings: (CalendarLayoutSettingPB settings) {
// If the field id changed, reload all events
if (state.settings?.fieldId != settings.fieldId) {
_loadAllEvents();
}
emit(state.copyWith(settings: settings));
},
didReceiveDatabaseUpdate: (DatabasePB database) {
emit(state.copyWith(database: database));
},
didLoadAllEvents: (events) {
final calenderEvents = _calendarEventDataFromEventPBs(events);
emit(
state.copyWith(
initialEvents: calenderEvents,
allEvents: calenderEvents,
),
);
},
createEvent: (DateTime date) async {
await _createEvent(date);
},
duplicateEvent: (String viewId, String rowId) async {
final result = await RowBackendService.duplicateRow(viewId, rowId);
result.fold(
(_) => null,
(e) => Log.error('Failed to duplicate event: $e', e),
);
},
deleteEvent: (String viewId, String rowId) async {
final result = await RowBackendService.deleteRow(viewId, rowId);
result.fold(
(_) => null,
(e) => Log.error('Failed to delete event: $e', e),
);
},
newEventPopupDisplayed: () {
emit(state.copyWith(editingEvent: null));
},
moveEvent: (CalendarDayEvent event, DateTime date) async {
await _moveEvent(event, date);
},
didCreateEvent: (CalendarEventData<CalendarDayEvent> event) {
emit(state.copyWith(editingEvent: event));
},
updateCalendarLayoutSetting:
(CalendarLayoutSettingPB layoutSetting) async {
await _updateCalendarLayoutSetting(layoutSetting);
},
didUpdateEvent: (CalendarEventData<CalendarDayEvent> eventData) {
final allEvents = [...state.allEvents];
final index = allEvents.indexWhere(
(element) => element.event!.eventId == eventData.event!.eventId,
);
if (index != -1) {
allEvents[index] = eventData;
}
emit(state.copyWith(allEvents: allEvents, updateEvent: eventData));
},
didDeleteEvents: (List<RowId> deletedRowIds) {
final events = [...state.allEvents];
events.retainWhere(
(element) => !deletedRowIds.contains(element.event!.eventId),
);
emit(
state.copyWith(
allEvents: events,
deleteEventIds: deletedRowIds,
),
);
},
didReceiveEvent: (CalendarEventData<CalendarDayEvent> event) {
emit(
state.copyWith(
allEvents: [...state.allEvents, event],
newEvent: event,
),
);
},
);
},
);
}
FieldInfo? _getCalendarFieldInfo(String fieldId) {
final fieldInfos = databaseController.fieldController.fieldInfos;
final index = fieldInfos.indexWhere(
(element) => element.field.id == fieldId,
);
if (index != -1) {
return fieldInfos[index];
} else {
return null;
}
}
Future<void> _openDatabase(Emitter<CalendarState> emit) async {
final result = await databaseController.open();
result.fold(
(database) {
databaseController.setIsLoading(false);
emit(
state.copyWith(
loadingState: LoadingState.finish(FlowyResult.success(null)),
),
);
},
(err) => emit(
state.copyWith(
loadingState: LoadingState.finish(FlowyResult.failure(err)),
),
),
);
}
Future<void> _createEvent(DateTime date) async {
final settings = state.settings;
if (settings == null) {
Log.warn('Calendar settings not found');
return;
}
final dateField = _getCalendarFieldInfo(settings.fieldId);
if (dateField != null) {
final newRow = await RowBackendService.createRow(
viewId: viewId,
withCells: (builder) => builder.insertDate(dateField, date),
).then(
(result) => result.fold(
(newRow) => newRow,
(err) {
Log.error(err);
return null;
},
),
);
if (newRow != null) {
final event = await _loadEvent(newRow.id);
if (event != null && !isClosed) {
add(CalendarEvent.didCreateEvent(event));
}
}
}
}
Future<void> _moveEvent(CalendarDayEvent event, DateTime date) async {
final timestamp = _eventTimestamp(event, date);
final payload = MoveCalendarEventPB(
cellPath: CellIdPB(
viewId: viewId,
rowId: event.eventId,
fieldId: event.dateFieldId,
),
timestamp: timestamp,
);
return DatabaseEventMoveCalendarEvent(payload).send().then((result) {
return result.fold(
(_) async {
final modifiedEvent = await _loadEvent(event.eventId);
add(CalendarEvent.didUpdateEvent(modifiedEvent!));
},
(err) {
Log.error(err);
return null;
},
);
});
}
Future<void> _updateCalendarLayoutSetting(
CalendarLayoutSettingPB layoutSetting,
) async {
return databaseController.updateLayoutSetting(
calendarLayoutSetting: layoutSetting,
);
}
Future<CalendarEventData<CalendarDayEvent>?> _loadEvent(RowId rowId) async {
final payload = RowIdPB(viewId: viewId, rowId: rowId);
return DatabaseEventGetCalendarEvent(payload).send().then((result) {
return result.fold(
(eventPB) => _calendarEventDataFromEventPB(eventPB),
(r) {
Log.error(r);
return null;
},
);
});
}
void _loadAllEvents() async {
final payload = CalendarEventRequestPB.create()..viewId = viewId;
final result = await DatabaseEventGetAllCalendarEvents(payload).send();
result.fold(
(events) {
if (!isClosed) {
add(CalendarEvent.didLoadAllEvents(events.items));
}
},
(r) => Log.error(r),
);
}
List<CalendarEventData<CalendarDayEvent>> _calendarEventDataFromEventPBs(
List<CalendarEventPB> eventPBs,
) {
final calendarEvents = <CalendarEventData<CalendarDayEvent>>[];
for (final eventPB in eventPBs) {
final event = _calendarEventDataFromEventPB(eventPB);
if (event != null) {
calendarEvents.add(event);
}
}
return calendarEvents;
}
CalendarEventData<CalendarDayEvent>? _calendarEventDataFromEventPB(
CalendarEventPB eventPB,
) {
final fieldInfo = fieldInfoByFieldId[eventPB.dateFieldId];
if (fieldInfo == null) {
return null;
}
// timestamp is stored as seconds, but constructor requires milliseconds
final date = DateTime.fromMillisecondsSinceEpoch(
eventPB.timestamp.toInt() * 1000,
);
final eventData = CalendarDayEvent(
event: eventPB,
eventId: eventPB.rowMeta.id,
dateFieldId: eventPB.dateFieldId,
date: date,
);
return CalendarEventData(
title: eventPB.title,
date: date,
event: eventData,
);
}
void _startListening() {
final onDatabaseChanged = DatabaseCallbacks(
onDatabaseChanged: (database) {
if (isClosed) return;
},
onFieldsChanged: (fieldInfos) {
if (isClosed) {
return;
}
fieldInfoByFieldId = {
for (final fieldInfo in fieldInfos) fieldInfo.field.id: fieldInfo,
};
},
onRowsCreated: (rowIds) async {
if (isClosed) {
return;
}
for (final id in rowIds) {
final event = await _loadEvent(id);
if (event != null && !isClosed) {
add(CalendarEvent.didReceiveEvent(event));
}
}
},
onRowsDeleted: (rowIds) {
if (isClosed) {
return;
}
add(CalendarEvent.didDeleteEvents(rowIds));
},
onRowsUpdated: (rowIds, reason) async {
if (isClosed) {
return;
}
for (final id in rowIds) {
final event = await _loadEvent(id);
if (event != null) {
if (isEventDayChanged(event)) {
add(CalendarEvent.didDeleteEvents([id]));
add(CalendarEvent.didReceiveEvent(event));
} else {
add(CalendarEvent.didUpdateEvent(event));
}
}
}
},
);
final onLayoutSettingsChanged = DatabaseLayoutSettingCallbacks(
onLayoutSettingsChanged: _didReceiveLayoutSetting,
);
databaseController.addListener(
onDatabaseChanged: onDatabaseChanged,
onLayoutSettingsChanged: onLayoutSettingsChanged,
);
}
void _didReceiveLayoutSetting(DatabaseLayoutSettingPB layoutSetting) {
if (layoutSetting.hasCalendar()) {
if (isClosed) {
return;
}
add(CalendarEvent.didReceiveCalendarSettings(layoutSetting.calendar));
}
}
bool isEventDayChanged(CalendarEventData<CalendarDayEvent> event) {
final index = state.allEvents.indexWhere(
(element) => element.event!.eventId == event.event!.eventId,
);
if (index == -1) {
return false;
}
return state.allEvents[index].date.day != event.date.day;
}
Int64 _eventTimestamp(CalendarDayEvent event, DateTime date) {
final time =
event.date.hour * 3600 + event.date.minute * 60 + event.date.second;
return Int64(date.millisecondsSinceEpoch ~/ 1000 + time);
}
}
typedef Events = List<CalendarEventData<CalendarDayEvent>>;
@freezed
class CalendarEvent with _$CalendarEvent {
const factory CalendarEvent.initial() = _InitialCalendar;
// Called after loading the calendar layout setting from the backend
const factory CalendarEvent.didReceiveCalendarSettings(
CalendarLayoutSettingPB settings,
) = _ReceiveCalendarSettings;
// Called after loading all the current evnets
const factory CalendarEvent.didLoadAllEvents(List<CalendarEventPB> events) =
_ReceiveCalendarEvents;
// Called when specific event was updated
const factory CalendarEvent.didUpdateEvent(
CalendarEventData<CalendarDayEvent> event,
) = _DidUpdateEvent;
// Called after creating a new event
const factory CalendarEvent.didCreateEvent(
CalendarEventData<CalendarDayEvent> event,
) = _DidReceiveNewEvent;
// Called after creating a new event
const factory CalendarEvent.newEventPopupDisplayed() =
_NewEventPopupDisplayed;
// Called when receive a new event
const factory CalendarEvent.didReceiveEvent(
CalendarEventData<CalendarDayEvent> event,
) = _DidReceiveEvent;
// Called when deleting events
const factory CalendarEvent.didDeleteEvents(List<RowId> rowIds) =
_DidDeleteEvents;
// Called when creating a new event
const factory CalendarEvent.createEvent(DateTime date) = _CreateEvent;
// Called when moving an event
const factory CalendarEvent.moveEvent(CalendarDayEvent event, DateTime date) =
_MoveEvent;
// Called when updating the calendar's layout settings
const factory CalendarEvent.updateCalendarLayoutSetting(
CalendarLayoutSettingPB layoutSetting,
) = _UpdateCalendarLayoutSetting;
const factory CalendarEvent.didReceiveDatabaseUpdate(DatabasePB database) =
_ReceiveDatabaseUpdate;
const factory CalendarEvent.duplicateEvent(String viewId, String rowId) =
_DuplicateEvent;
const factory CalendarEvent.deleteEvent(String viewId, String rowId) =
_DeleteEvent;
}
@freezed
class CalendarState with _$CalendarState {
const factory CalendarState({
required DatabasePB? database,
// events by row id
required Events allEvents,
required Events initialEvents,
CalendarEventData<CalendarDayEvent>? editingEvent,
CalendarEventData<CalendarDayEvent>? newEvent,
CalendarEventData<CalendarDayEvent>? updateEvent,
required List<String> deleteEventIds,
required CalendarLayoutSettingPB? settings,
required LoadingState loadingState,
required FlowyError? noneOrError,
}) = _CalendarState;
factory CalendarState.initial() => const CalendarState(
database: null,
allEvents: [],
initialEvents: [],
deleteEventIds: [],
settings: null,
noneOrError: null,
loadingState: LoadingState.loading(),
);
}
class CalendarEditingRow {
CalendarEditingRow({
required this.row,
required this.index,
});
RowPB row;
int? index;
}
@freezed
class CalendarDayEvent with _$CalendarDayEvent {
const factory CalendarDayEvent({
required CalendarEventPB event,
required String dateFieldId,
required String eventId,
required DateTime date,
}) = _CalendarDayEvent;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/presentation/calendar_day.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/database/mobile_calendar_events_screen.dart';
import 'package:appflowy/plugins/database/application/row/row_cache.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:calendar_view/calendar_view.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra/time/duration.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import '../../grid/presentation/layout/sizes.dart';
import '../application/calendar_bloc.dart';
import 'calendar_event_card.dart';
class CalendarDayCard extends StatelessWidget {
const CalendarDayCard({
super.key,
required this.viewId,
required this.isToday,
required this.isInMonth,
required this.date,
required this.rowCache,
required this.events,
required this.onCreateEvent,
required this.position,
});
final String viewId;
final bool isToday;
final bool isInMonth;
final DateTime date;
final RowCache rowCache;
final List<CalendarDayEvent> events;
final void Function(DateTime) onCreateEvent;
final CellPosition position;
@override
Widget build(BuildContext context) {
final hoverBackgroundColor =
Theme.of(context).brightness == Brightness.light
? Theme.of(context).colorScheme.secondaryContainer
: Colors.transparent;
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return ChangeNotifierProvider(
create: (_) => _CardEnterNotifier(),
builder: (context, child) {
final child = Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_Header(
date: date,
isInMonth: isInMonth,
isToday: isToday,
),
// Add a separator between the header and the content.
const VSpace(6.0),
// List of cards or empty space
if (events.isNotEmpty && !PlatformExtension.isMobile) ...[
_EventList(
events: events,
viewId: viewId,
rowCache: rowCache,
constraints: constraints,
),
] else if (events.isNotEmpty && PlatformExtension.isMobile) ...[
const _EventIndicator(),
],
],
);
return Stack(
children: [
GestureDetector(
onDoubleTap: () => onCreateEvent(date),
onTap: PlatformExtension.isMobile
? () => _mobileOnTap(context)
: null,
child: Container(
decoration: BoxDecoration(
color: date.isWeekend
? AFThemeExtension.of(context).calendarWeekendBGColor
: Colors.transparent,
border: _borderFromPosition(context, position),
),
),
),
DragTarget<CalendarDayEvent>(
builder: (context, candidate, __) {
return Stack(
children: [
Container(
width: double.infinity,
height: double.infinity,
color:
candidate.isEmpty ? null : hoverBackgroundColor,
padding: const EdgeInsets.only(top: 5.0),
child: child,
),
if (candidate.isEmpty && !PlatformExtension.isMobile)
NewEventButton(
onCreate: () => onCreateEvent(date),
),
],
);
},
onAcceptWithDetails: (details) {
final event = details.data;
if (event.date != date) {
context
.read<CalendarBloc>()
.add(CalendarEvent.moveEvent(event, date));
}
},
),
MouseRegion(
onEnter: (p) => notifyEnter(context, true),
onExit: (p) => notifyEnter(context, false),
opaque: false,
hitTestBehavior: HitTestBehavior.translucent,
),
],
);
},
);
},
);
}
void _mobileOnTap(BuildContext context) {
context.push(
MobileCalendarEventsScreen.routeName,
extra: {
MobileCalendarEventsScreen.calendarBlocKey:
context.read<CalendarBloc>(),
MobileCalendarEventsScreen.calendarDateKey: date,
MobileCalendarEventsScreen.calendarEventsKey: events,
MobileCalendarEventsScreen.calendarRowCacheKey: rowCache,
MobileCalendarEventsScreen.calendarViewIdKey: viewId,
},
);
}
bool notifyEnter(BuildContext context, bool isEnter) =>
Provider.of<_CardEnterNotifier>(context, listen: false).onEnter = isEnter;
Border _borderFromPosition(BuildContext context, CellPosition position) {
final BorderSide borderSide =
BorderSide(color: Theme.of(context).dividerColor);
return Border(
top: borderSide,
left: borderSide,
bottom: [
CellPosition.bottom,
CellPosition.bottomLeft,
CellPosition.bottomRight,
].contains(position)
? borderSide
: BorderSide.none,
right: [
CellPosition.topRight,
CellPosition.bottomRight,
CellPosition.right,
].contains(position)
? borderSide
: BorderSide.none,
);
}
}
class _EventIndicator extends StatelessWidget {
const _EventIndicator();
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 7,
height: 7,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Theme.of(context).hintColor,
),
),
],
);
}
}
class _Header extends StatelessWidget {
const _Header({
required this.isToday,
required this.isInMonth,
required this.date,
});
final bool isToday;
final bool isInMonth;
final DateTime date;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 6.0),
child: _DayBadge(isToday: isToday, isInMonth: isInMonth, date: date),
);
}
}
@visibleForTesting
class NewEventButton extends StatelessWidget {
const NewEventButton({super.key, required this.onCreate});
final VoidCallback onCreate;
@override
Widget build(BuildContext context) {
return Consumer<_CardEnterNotifier>(
builder: (context, notifier, _) {
if (!notifier.onEnter) {
return const SizedBox.shrink();
}
return Padding(
padding: const EdgeInsets.all(4.0),
child: FlowyIconButton(
onPressed: onCreate,
icon: const FlowySvg(FlowySvgs.add_s),
fillColor: Theme.of(context).colorScheme.background,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
width: 22,
tooltipText: LocaleKeys.calendar_newEventButtonTooltip.tr(),
decoration: BoxDecoration(
border: Border.fromBorderSide(
BorderSide(
color: Theme.of(context).brightness == Brightness.light
? const Color(0xffd0d3d6)
: const Color(0xff59647a),
width: 0.5,
),
),
borderRadius: Corners.s5Border,
boxShadow: [
BoxShadow(
spreadRadius: -2,
color: const Color(0xFF1F2329).withOpacity(0.02),
blurRadius: 2,
),
BoxShadow(
color: const Color(0xFF1F2329).withOpacity(0.02),
blurRadius: 4,
),
BoxShadow(
spreadRadius: 2,
color: const Color(0xFF1F2329).withOpacity(0.02),
blurRadius: 8,
),
],
),
),
);
},
);
}
}
class _DayBadge extends StatelessWidget {
const _DayBadge({
required this.isToday,
required this.isInMonth,
required this.date,
});
final bool isToday;
final bool isInMonth;
final DateTime date;
@override
Widget build(BuildContext context) {
Color dayTextColor = Theme.of(context).colorScheme.onBackground;
Color monthTextColor = Theme.of(context).colorScheme.onBackground;
final String monthString =
DateFormat("MMM ", context.locale.toLanguageTag()).format(date);
final String dayString = date.day.toString();
if (!isInMonth) {
dayTextColor = Theme.of(context).disabledColor;
monthTextColor = Theme.of(context).disabledColor;
}
if (isToday) {
dayTextColor = Theme.of(context).colorScheme.onPrimary;
}
final double size = PlatformExtension.isMobile ? 20 : 18;
return SizedBox(
height: size,
child: Row(
mainAxisAlignment: PlatformExtension.isMobile
? MainAxisAlignment.center
: MainAxisAlignment.end,
children: [
if (date.day == 1 && !PlatformExtension.isMobile)
FlowyText.medium(
monthString,
fontSize: 11,
color: monthTextColor,
),
Container(
decoration: BoxDecoration(
color: isToday ? Theme.of(context).colorScheme.primary : null,
borderRadius: BorderRadius.circular(10),
),
width: isToday ? size : null,
height: isToday ? size : null,
child: Center(
child: FlowyText.medium(
dayString,
fontSize: PlatformExtension.isMobile ? 12 : 11,
color: dayTextColor,
),
),
),
],
),
);
}
}
class _EventList extends StatelessWidget {
const _EventList({
required this.events,
required this.viewId,
required this.rowCache,
required this.constraints,
});
final List<CalendarDayEvent> events;
final String viewId;
final RowCache rowCache;
final BoxConstraints constraints;
@override
Widget build(BuildContext context) {
final editingEvent = context.watch<CalendarBloc>().state.editingEvent;
return Flexible(
child: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: true),
child: ListView.separated(
itemBuilder: (BuildContext context, int index) {
final autoEdit =
editingEvent?.event?.eventId == events[index].eventId;
return EventCard(
databaseController:
context.read<CalendarBloc>().databaseController,
event: events[index],
constraints: constraints,
autoEdit: autoEdit,
);
},
itemCount: events.length,
padding: const EdgeInsets.fromLTRB(4.0, 0, 4.0, 4.0),
separatorBuilder: (_, __) =>
VSpace(GridSize.typeOptionSeparatorHeight),
shrinkWrap: true,
),
),
);
}
}
class _CardEnterNotifier extends ChangeNotifier {
_CardEnterNotifier();
bool _onEnter = false;
set onEnter(bool value) {
if (_onEnter != value) {
_onEnter = value;
notifyListeners();
}
}
bool get onEnter => _onEnter;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/presentation/calendar_event_editor.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/database/application/cell/bloc/text_cell_bloc.dart';
import 'package:appflowy/plugins/database/application/cell/cell_controller.dart';
import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/row/row_controller.dart';
import 'package:appflowy/plugins/database/calendar/application/calendar_bloc.dart';
import 'package:appflowy/plugins/database/calendar/application/calendar_event_editor_bloc.dart';
import 'package:appflowy/plugins/database/widgets/cell/editable_cell_builder.dart';
import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/text.dart';
import 'package:appflowy/plugins/database/widgets/row/accessory/cell_accessory.dart';
import 'package:appflowy/plugins/database/widgets/row/cells/cell_container.dart';
import 'package:appflowy/plugins/database/widgets/row/row_detail.dart';
import 'package:appflowy/util/field_type_extension.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.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:flowy_infra_ui/widget/flowy_tooltip.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class CalendarEventEditor extends StatelessWidget {
CalendarEventEditor({
super.key,
required RowMetaPB rowMeta,
required this.layoutSettings,
required this.databaseController,
}) : rowController = RowController(
rowMeta: rowMeta,
viewId: databaseController.viewId,
rowCache: databaseController.rowCache,
),
cellBuilder =
EditableCellBuilder(databaseController: databaseController);
final CalendarLayoutSettingPB layoutSettings;
final DatabaseController databaseController;
final RowController rowController;
final EditableCellBuilder cellBuilder;
@override
Widget build(BuildContext context) {
return BlocProvider<CalendarEventEditorBloc>(
create: (context) => CalendarEventEditorBloc(
fieldController: databaseController.fieldController,
rowController: rowController,
layoutSettings: layoutSettings,
)..add(const CalendarEventEditorEvent.initial()),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
EventEditorControls(
rowController: rowController,
databaseController: databaseController,
),
Flexible(
child: EventPropertyList(
fieldController: databaseController.fieldController,
dateFieldId: layoutSettings.fieldId,
cellBuilder: cellBuilder,
),
),
],
),
);
}
}
class EventEditorControls extends StatelessWidget {
const EventEditorControls({
super.key,
required this.rowController,
required this.databaseController,
});
final RowController rowController;
final DatabaseController databaseController;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(12.0, 8.0, 12.0, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FlowyTooltip(
message: LocaleKeys.calendar_duplicateEvent.tr(),
child: FlowyIconButton(
width: 20,
icon: const FlowySvg(
FlowySvgs.m_duplicate_s,
size: Size.square(17),
),
iconColorOnHover: Theme.of(context).colorScheme.onSecondary,
onPressed: () => context.read<CalendarBloc>().add(
CalendarEvent.duplicateEvent(
rowController.viewId,
rowController.rowId,
),
),
),
),
const HSpace(8.0),
FlowyIconButton(
width: 20,
icon: const FlowySvg(FlowySvgs.delete_s),
iconColorOnHover: Theme.of(context).colorScheme.onSecondary,
onPressed: () => context.read<CalendarBloc>().add(
CalendarEvent.deleteEvent(
rowController.viewId,
rowController.rowId,
),
),
),
const HSpace(8.0),
FlowyIconButton(
width: 20,
icon: const FlowySvg(FlowySvgs.full_view_s),
iconColorOnHover: Theme.of(context).colorScheme.onSecondary,
onPressed: () {
PopoverContainer.of(context).close();
FlowyOverlay.show(
context: context,
builder: (_) => RowDetailPage(
databaseController: databaseController,
rowController: rowController,
),
);
},
),
],
),
);
}
}
class EventPropertyList extends StatelessWidget {
const EventPropertyList({
super.key,
required this.fieldController,
required this.dateFieldId,
required this.cellBuilder,
});
final FieldController fieldController;
final String dateFieldId;
final EditableCellBuilder cellBuilder;
@override
Widget build(BuildContext context) {
return BlocBuilder<CalendarEventEditorBloc, CalendarEventEditorState>(
builder: (context, state) {
final primaryFieldId = fieldController.fieldInfos
.firstWhereOrNull((fieldInfo) => fieldInfo.isPrimary)!
.id;
final reorderedList = List<CellContext>.from(state.cells)
..retainWhere((cell) => cell.fieldId != primaryFieldId);
final primaryCellContext = state.cells
.firstWhereOrNull((cell) => cell.fieldId == primaryFieldId);
final dateFieldIndex =
reorderedList.indexWhere((cell) => cell.fieldId == dateFieldId);
if (primaryCellContext == null || dateFieldIndex == -1) {
return const SizedBox.shrink();
}
reorderedList.insert(0, reorderedList.removeAt(dateFieldIndex));
final children = [
Padding(
padding: const EdgeInsets.fromLTRB(16.0, 12.0, 16.0, 8.0),
child: cellBuilder.buildCustom(
primaryCellContext,
skinMap: EditableCellSkinMap(textSkin: _TitleTextCellSkin()),
),
),
...reorderedList.map(
(cellContext) => PropertyCell(
fieldController: fieldController,
cellContext: cellContext,
cellBuilder: cellBuilder,
),
),
];
return ListView(
shrinkWrap: true,
padding: const EdgeInsets.only(bottom: 16.0),
children: children,
);
},
);
}
}
class PropertyCell extends StatefulWidget {
const PropertyCell({
super.key,
required this.fieldController,
required this.cellContext,
required this.cellBuilder,
});
final FieldController fieldController;
final CellContext cellContext;
final EditableCellBuilder cellBuilder;
@override
State<StatefulWidget> createState() => _PropertyCellState();
}
class _PropertyCellState extends State<PropertyCell> {
@override
Widget build(BuildContext context) {
final fieldInfo =
widget.fieldController.getField(widget.cellContext.fieldId)!;
final cell = widget.cellBuilder
.buildStyled(widget.cellContext, EditableCellStyle.desktopRowDetail);
final gesture = GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => cell.requestFocus.notify(),
child: AccessoryHover(
fieldType: fieldInfo.fieldType,
child: cell,
),
);
return Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
constraints: const BoxConstraints(minHeight: 28),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 88,
height: 28,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 6),
child: Row(
children: [
FlowySvg(
fieldInfo.fieldType.svgData,
color: Theme.of(context).hintColor,
size: const Size.square(14),
),
const HSpace(4.0),
Expanded(
child: FlowyText.regular(
fieldInfo.name,
color: Theme.of(context).hintColor,
overflow: TextOverflow.ellipsis,
fontSize: 11,
),
),
],
),
),
),
const HSpace(8),
Expanded(child: gesture),
],
),
);
}
}
class _TitleTextCellSkin extends IEditableTextCellSkin {
@override
Widget build(
BuildContext context,
CellContainerNotifier cellContainerNotifier,
TextCellBloc bloc,
FocusNode focusNode,
TextEditingController textEditingController,
) {
return FlowyTextField(
controller: textEditingController,
textStyle: Theme.of(context).textTheme.bodyMedium?.copyWith(fontSize: 14),
focusNode: focusNode,
hintText: LocaleKeys.calendar_defaultNewCalendarTitle.tr(),
onChanged: (text) {
if (textEditingController.value.composing.isCollapsed) {
bloc.add(TextCellEvent.updateText(text));
}
},
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/presentation/calendar_event_card.dart | import 'package:flutter/material.dart';
import 'package:appflowy/mobile/presentation/database/card/card_detail/mobile_card_detail_screen.dart';
import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/application/row/row_cache.dart';
import 'package:appflowy/plugins/database/widgets/card/card.dart';
import 'package:appflowy/plugins/database/widgets/cell/card_cell_builder.dart';
import 'package:appflowy/plugins/database/widgets/cell/card_cell_style_maps/calendar_card_cell_style.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_popover/appflowy_popover.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:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../application/calendar_bloc.dart';
import 'calendar_event_editor.dart';
class EventCard extends StatefulWidget {
const EventCard({
super.key,
required this.databaseController,
required this.event,
required this.constraints,
required this.autoEdit,
this.isDraggable = true,
this.padding = EdgeInsets.zero,
});
final DatabaseController databaseController;
final CalendarDayEvent event;
final BoxConstraints constraints;
final bool autoEdit;
final bool isDraggable;
final EdgeInsets padding;
@override
State<EventCard> createState() => _EventCardState();
}
class _EventCardState extends State<EventCard> {
final PopoverController _popoverController = PopoverController();
String get viewId => widget.databaseController.viewId;
RowCache get rowCache => widget.databaseController.rowCache;
@override
void initState() {
super.initState();
if (widget.autoEdit) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_popoverController.show();
context
.read<CalendarBloc>()
.add(const CalendarEvent.newEventPopupDisplayed());
});
}
}
@override
Widget build(BuildContext context) {
final rowInfo = rowCache.getRow(widget.event.eventId);
if (rowInfo == null) {
return const SizedBox.shrink();
}
final cellBuilder = CardCellBuilder(
databaseController: widget.databaseController,
);
Widget card = RowCard(
// Add the key here to make sure the card is rebuilt when the cells
// in this row are updated.
key: ValueKey(widget.event.eventId),
fieldController: widget.databaseController.fieldController,
rowMeta: rowInfo.rowMeta,
viewId: viewId,
rowCache: rowCache,
isEditing: false,
cellBuilder: cellBuilder,
openCard: (context) {
if (PlatformExtension.isMobile) {
context.push(
MobileRowDetailPage.routeName,
extra: {
MobileRowDetailPage.argRowId: rowInfo.rowId,
MobileRowDetailPage.argDatabaseController:
widget.databaseController,
},
);
} else {
_popoverController.show();
}
},
styleConfiguration: RowCardStyleConfiguration(
cellStyleMap: desktopCalendarCardCellStyleMap(context),
showAccessory: false,
cardPadding: const EdgeInsets.all(6),
hoverStyle: HoverStyle(
hoverColor: Theme.of(context).brightness == Brightness.light
? const Color(0x0F1F2329)
: const Color(0x0FEFF4FB),
foregroundColorOnHover: Theme.of(context).colorScheme.onBackground,
),
),
onStartEditing: () {},
onEndEditing: () {},
);
final decoration = BoxDecoration(
color: Theme.of(context).colorScheme.surface,
border: Border.fromBorderSide(
BorderSide(
color: Theme.of(context).brightness == Brightness.light
? const Color(0xffd0d3d6)
: const Color(0xff59647a),
width: 0.5,
),
),
borderRadius: Corners.s6Border,
boxShadow: [
BoxShadow(
spreadRadius: -2,
color: const Color(0xFF1F2329).withOpacity(0.02),
blurRadius: 2,
),
BoxShadow(
color: const Color(0xFF1F2329).withOpacity(0.02),
blurRadius: 4,
),
BoxShadow(
spreadRadius: 2,
color: const Color(0xFF1F2329).withOpacity(0.02),
blurRadius: 8,
),
],
);
card = AppFlowyPopover(
triggerActions: PopoverTriggerFlags.none,
direction: PopoverDirection.rightWithCenterAligned,
controller: _popoverController,
constraints: const BoxConstraints(maxWidth: 360, maxHeight: 348),
asBarrier: true,
margin: EdgeInsets.zero,
offset: const Offset(10.0, 0),
popupBuilder: (_) {
final settings = context.watch<CalendarBloc>().state.settings;
if (settings == null) {
return const SizedBox.shrink();
}
return BlocProvider.value(
value: context.read<CalendarBloc>(),
child: CalendarEventEditor(
databaseController: widget.databaseController,
rowMeta: widget.event.event.rowMeta,
layoutSettings: settings,
),
);
},
child: Container(
padding: widget.padding,
decoration: decoration,
child: card,
),
);
if (widget.isDraggable) {
return Draggable<CalendarDayEvent>(
data: widget.event,
feedback: Container(
constraints: BoxConstraints(
maxWidth: widget.constraints.maxWidth - 8.0,
),
decoration: decoration,
child: Opacity(
opacity: 0.6,
child: card,
),
),
child: card,
);
}
return card;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/presentation/calendar_page.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/database/card/card.dart';
import 'package:appflowy/mobile/presentation/presentation.dart';
import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/calendar/application/calendar_bloc.dart';
import 'package:appflowy/plugins/database/calendar/application/unschedule_event_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:appflowy/plugins/database/tab_bar/tab_bar_view.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/calendar_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:calendar_view/calendar_view.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra/theme_extension.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';
import 'package:go_router/go_router.dart';
import '../../application/row/row_controller.dart';
import '../../widgets/row/row_detail.dart';
import 'calendar_day.dart';
import 'layout/sizes.dart';
import 'toolbar/calendar_setting_bar.dart';
class CalendarPageTabBarBuilderImpl extends DatabaseTabBarItemBuilder {
@override
Widget content(
BuildContext context,
ViewPB view,
DatabaseController controller,
bool shrinkWrap,
String? initialRowId,
) {
return CalendarPage(
key: _makeValueKey(controller),
view: view,
databaseController: controller,
shrinkWrap: shrinkWrap,
);
}
@override
Widget settingBar(BuildContext context, DatabaseController controller) {
return CalendarSettingBar(
key: _makeValueKey(controller),
databaseController: controller,
);
}
@override
Widget settingBarExtension(
BuildContext context,
DatabaseController controller,
) {
return SizedBox.fromSize();
}
ValueKey _makeValueKey(DatabaseController controller) {
return ValueKey(controller.viewId);
}
}
class CalendarPage extends StatefulWidget {
const CalendarPage({
super.key,
required this.view,
required this.databaseController,
this.shrinkWrap = false,
});
final ViewPB view;
final DatabaseController databaseController;
final bool shrinkWrap;
@override
State<CalendarPage> createState() => _CalendarPageState();
}
class _CalendarPageState extends State<CalendarPage> {
final _eventController = EventController<CalendarDayEvent>();
late final CalendarBloc _calendarBloc;
GlobalKey<MonthViewState>? _calendarState;
@override
void initState() {
_calendarState = GlobalKey<MonthViewState>();
_calendarBloc = CalendarBloc(
databaseController: widget.databaseController,
)..add(const CalendarEvent.initial());
super.initState();
}
@override
void dispose() {
_calendarBloc.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return CalendarControllerProvider(
controller: _eventController,
child: BlocProvider<CalendarBloc>.value(
value: _calendarBloc,
child: MultiBlocListener(
listeners: [
BlocListener<CalendarBloc, CalendarState>(
listenWhen: (p, c) => p.initialEvents != c.initialEvents,
listener: (context, state) {
_eventController.removeWhere((_) => true);
_eventController.addAll(state.initialEvents);
},
),
BlocListener<CalendarBloc, CalendarState>(
listenWhen: (p, c) => p.deleteEventIds != c.deleteEventIds,
listener: (context, state) {
_eventController.removeWhere(
(element) =>
state.deleteEventIds.contains(element.event!.eventId),
);
},
),
BlocListener<CalendarBloc, CalendarState>(
// Event create by click the + button or double click on the
// calendar
listenWhen: (p, c) => p.newEvent != c.newEvent,
listener: (context, state) {
if (state.newEvent != null) {
_eventController.add(state.newEvent!);
}
},
),
BlocListener<CalendarBloc, CalendarState>(
// When an event is rescheduled
listenWhen: (p, c) => p.updateEvent != c.updateEvent,
listener: (context, state) {
if (state.updateEvent != null) {
_eventController.removeWhere(
(element) =>
element.event!.eventId ==
state.updateEvent!.event!.eventId,
);
_eventController.add(state.updateEvent!);
}
},
),
],
child: BlocBuilder<CalendarBloc, CalendarState>(
builder: (context, state) {
return ValueListenableBuilder<bool>(
valueListenable: widget.databaseController.isLoading,
builder: (_, value, ___) {
if (value) {
return const Center(
child: CircularProgressIndicator.adaptive(),
);
}
return _buildCalendar(
context,
_eventController,
state.settings?.firstDayOfWeek ?? 0,
);
},
);
},
),
),
),
);
}
Widget _buildCalendar(
BuildContext context,
EventController eventController,
int firstDayOfWeek,
) {
return LayoutBuilder(
// must specify MonthView width for useAvailableVerticalSpace to work properly
builder: (context, constraints) {
return Padding(
padding: PlatformExtension.isMobile
? CalendarSize.contentInsetsMobile
: CalendarSize.contentInsets,
child: ScrollConfiguration(
behavior:
ScrollConfiguration.of(context).copyWith(scrollbars: false),
child: MonthView(
key: _calendarState,
controller: _eventController,
width: constraints.maxWidth,
cellAspectRatio: PlatformExtension.isMobile ? 0.9 : 0.6,
startDay: _weekdayFromInt(firstDayOfWeek),
showBorder: false,
headerBuilder: _headerNavigatorBuilder,
weekDayBuilder: _headerWeekDayBuilder,
cellBuilder: _calendarDayBuilder,
useAvailableVerticalSpace: widget.shrinkWrap,
),
),
);
},
);
}
Widget _headerNavigatorBuilder(DateTime currentMonth) {
return SizedBox(
height: 24,
child: Row(
children: [
GestureDetector(
onTap: PlatformExtension.isMobile
? () => showMobileBottomSheet(
context,
title: LocaleKeys.calendar_quickJumpYear.tr(),
showHeader: true,
showCloseButton: true,
builder: (_) => SizedBox(
height: 200,
child: YearPicker(
firstDate: CalendarConstants.epochDate.withoutTime,
lastDate: CalendarConstants.maxDate.withoutTime,
selectedDate: currentMonth,
currentDate: DateTime.now(),
onChanged: (newDate) {
_calendarState?.currentState?.jumpToMonth(newDate);
context.pop();
},
),
),
)
: null,
child: Row(
children: [
FlowyText.medium(
DateFormat('MMMM y', context.locale.toLanguageTag())
.format(currentMonth),
),
if (PlatformExtension.isMobile) ...[
const HSpace(6),
const FlowySvg(FlowySvgs.arrow_down_s),
],
],
),
),
const Spacer(),
FlowyIconButton(
width: CalendarSize.navigatorButtonWidth,
height: CalendarSize.navigatorButtonHeight,
icon: const FlowySvg(FlowySvgs.arrow_left_s),
tooltipText: LocaleKeys.calendar_navigation_previousMonth.tr(),
hoverColor: AFThemeExtension.of(context).lightGreyHover,
onPressed: () => _calendarState?.currentState?.previousPage(),
),
FlowyTextButton(
LocaleKeys.calendar_navigation_today.tr(),
fillColor: Colors.transparent,
fontWeight: FontWeight.w400,
fontSize: 10,
tooltip: LocaleKeys.calendar_navigation_jumpToday.tr(),
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
hoverColor: AFThemeExtension.of(context).lightGreyHover,
onPressed: () =>
_calendarState?.currentState?.animateToMonth(DateTime.now()),
),
FlowyIconButton(
width: CalendarSize.navigatorButtonWidth,
height: CalendarSize.navigatorButtonHeight,
icon: const FlowySvg(FlowySvgs.arrow_right_s),
tooltipText: LocaleKeys.calendar_navigation_nextMonth.tr(),
hoverColor: AFThemeExtension.of(context).lightGreyHover,
onPressed: () => _calendarState?.currentState?.nextPage(),
),
const HSpace(6.0),
UnscheduledEventsButton(
databaseController: widget.databaseController,
),
],
),
);
}
Widget _headerWeekDayBuilder(day) {
// incoming day starts from Monday, the symbols start from Sunday
final symbols = DateFormat.EEEE(context.locale.toLanguageTag()).dateSymbols;
String weekDayString = symbols.WEEKDAYS[(day + 1) % 7];
if (PlatformExtension.isMobile) {
weekDayString = weekDayString.substring(0, 3);
}
return Center(
child: Padding(
padding: CalendarSize.daysOfWeekInsets,
child: FlowyText.regular(
weekDayString,
fontSize: 9,
color: Theme.of(context).hintColor,
),
),
);
}
Widget _calendarDayBuilder(
DateTime date,
List<CalendarEventData<CalendarDayEvent>> calenderEvents,
isToday,
isInMonth,
position,
) {
// Sort the events by timestamp. Because the database view is not
// reserving the order of the events. Reserving the order of the rows/events
// is implemnted in the develop branch(WIP). Will be replaced with that.
final events = calenderEvents.map((value) => value.event!).toList()
..sort((a, b) => a.event.timestamp.compareTo(b.event.timestamp));
return CalendarDayCard(
viewId: widget.view.id,
isToday: isToday,
isInMonth: isInMonth,
events: events,
date: date,
rowCache: _calendarBloc.rowCache,
onCreateEvent: (date) =>
_calendarBloc.add(CalendarEvent.createEvent(date)),
position: position,
);
}
WeekDays _weekdayFromInt(int dayOfWeek) {
// dayOfWeek starts from Sunday, WeekDays starts from Monday
return WeekDays.values[(dayOfWeek - 1) % 7];
}
}
void showEventDetails({
required BuildContext context,
required DatabaseController databaseController,
required CalendarEventPB event,
}) {
final rowController = RowController(
rowMeta: event.rowMeta,
viewId: databaseController.viewId,
rowCache: databaseController.rowCache,
);
FlowyOverlay.show(
context: context,
builder: (BuildContext overlayContext) {
return RowDetailPage(
rowController: rowController,
databaseController: databaseController,
);
},
);
}
class UnscheduledEventsButton extends StatefulWidget {
const UnscheduledEventsButton({super.key, required this.databaseController});
final DatabaseController databaseController;
@override
State<UnscheduledEventsButton> createState() =>
_UnscheduledEventsButtonState();
}
class _UnscheduledEventsButtonState extends State<UnscheduledEventsButton> {
late final PopoverController _popoverController;
@override
void initState() {
super.initState();
_popoverController = PopoverController();
}
@override
Widget build(BuildContext context) {
return BlocProvider<UnscheduleEventsBloc>(
create: (_) =>
UnscheduleEventsBloc(databaseController: widget.databaseController)
..add(const UnscheduleEventsEvent.initial()),
child: BlocBuilder<UnscheduleEventsBloc, UnscheduleEventsState>(
builder: (context, state) {
return AppFlowyPopover(
direction: PopoverDirection.bottomWithCenterAligned,
triggerActions: PopoverTriggerFlags.none,
controller: _popoverController,
offset: const Offset(0, 8),
constraints: const BoxConstraints(maxWidth: 282, maxHeight: 600),
child: OutlinedButton(
style: OutlinedButton.styleFrom(
shape: RoundedRectangleBorder(
side: BorderSide(color: Theme.of(context).dividerColor),
borderRadius: Corners.s6Border,
),
side: BorderSide(color: Theme.of(context).dividerColor),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
visualDensity: VisualDensity.compact,
),
onPressed: () {
if (state.unscheduleEvents.isNotEmpty) {
if (PlatformExtension.isMobile) {
_showUnscheduledEventsMobile(state.unscheduleEvents);
} else {
_popoverController.show();
}
}
},
child: FlowyTooltip(
message: LocaleKeys.calendar_settings_noDateHint.plural(
state.unscheduleEvents.length,
namedArgs: {'count': '${state.unscheduleEvents.length}'},
),
child: FlowyText.regular(
"${LocaleKeys.calendar_settings_noDateTitle.tr()} (${state.unscheduleEvents.length})",
fontSize: 10,
),
),
),
popupBuilder: (context) {
return UnscheduleEventsList(
databaseController: widget.databaseController,
unscheduleEvents: state.unscheduleEvents,
);
},
);
},
),
);
}
void _showUnscheduledEventsMobile(List<CalendarEventPB> events) =>
showMobileBottomSheet(
context,
builder: (_) {
return Column(
children: [
FlowyText.medium(
LocaleKeys.calendar_settings_unscheduledEventsTitle.tr(),
),
UnscheduleEventsList(
databaseController: widget.databaseController,
unscheduleEvents: events,
),
],
);
},
);
}
class UnscheduleEventsList extends StatelessWidget {
const UnscheduleEventsList({
super.key,
required this.unscheduleEvents,
required this.databaseController,
});
final List<CalendarEventPB> unscheduleEvents;
final DatabaseController databaseController;
@override
Widget build(BuildContext context) {
final cells = [
if (!PlatformExtension.isMobile)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
child: FlowyText.medium(
LocaleKeys.calendar_settings_clickToAdd.tr(),
fontSize: 10,
color: Theme.of(context).hintColor,
overflow: TextOverflow.ellipsis,
),
),
...unscheduleEvents.map(
(event) => UnscheduledEventCell(
event: event,
onPressed: () {
if (PlatformExtension.isMobile) {
context.push(
MobileRowDetailPage.routeName,
extra: {
MobileRowDetailPage.argRowId: event.rowMeta.id,
MobileRowDetailPage.argDatabaseController: databaseController,
},
);
context.pop();
} else {
showEventDetails(
context: context,
event: event,
databaseController: databaseController,
);
PopoverContainer.of(context).close();
}
},
),
),
];
final child = ListView.separated(
itemBuilder: (context, index) => cells[index],
itemCount: cells.length,
separatorBuilder: (context, index) =>
VSpace(GridSize.typeOptionSeparatorHeight),
shrinkWrap: true,
);
if (PlatformExtension.isMobile) {
return Flexible(child: child);
}
return child;
}
}
class UnscheduledEventCell extends StatelessWidget {
const UnscheduledEventCell({
super.key,
required this.event,
required this.onPressed,
});
final CalendarEventPB event;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return PlatformExtension.isMobile
? MobileUnscheduledEventTile(event: event, onPressed: onPressed)
: DesktopUnscheduledEventTile(event: event, onPressed: onPressed);
}
}
class DesktopUnscheduledEventTile extends StatelessWidget {
const DesktopUnscheduledEventTile({
super.key,
required this.event,
required this.onPressed,
});
final CalendarEventPB event;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 26,
child: FlowyButton(
margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
text: FlowyText.medium(
event.title.isEmpty
? LocaleKeys.calendar_defaultNewCalendarTitle.tr()
: event.title,
fontSize: 11,
),
onTap: onPressed,
),
);
}
}
class MobileUnscheduledEventTile extends StatelessWidget {
const MobileUnscheduledEventTile({
super.key,
required this.event,
required this.onPressed,
});
final CalendarEventPB event;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return MobileSettingItem(
name: event.title.isEmpty
? LocaleKeys.calendar_defaultNewCalendarTitle.tr()
: event.title,
onTap: onPressed,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/presentation | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/presentation/toolbar/calendar_setting_bar.dart | import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/widgets/setting/setting_button.dart';
import 'package:flutter/material.dart';
class CalendarSettingBar extends StatelessWidget {
const CalendarSettingBar({
super.key,
required this.databaseController,
});
final DatabaseController databaseController;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 20,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
SettingButton(
databaseController: databaseController,
),
],
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/presentation | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/presentation/toolbar/calendar_layout_setting.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/application/setting/property_bloc.dart';
import 'package:appflowy/plugins/database/calendar/application/calendar_setting_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:appflowy/workspace/presentation/widgets/toggle/toggle.dart';
import 'package:appflowy/workspace/presentation/widgets/toggle/toggle_style.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/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';
/// Widget that displays a list of settings that alters the appearance of the
/// calendar
class CalendarLayoutSetting extends StatefulWidget {
const CalendarLayoutSetting({
super.key,
required this.databaseController,
});
final DatabaseController databaseController;
@override
State<CalendarLayoutSetting> createState() => _CalendarLayoutSettingState();
}
class _CalendarLayoutSettingState extends State<CalendarLayoutSetting> {
final PopoverMutex popoverMutex = PopoverMutex();
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) {
return CalendarSettingBloc(
databaseController: widget.databaseController,
)..add(const CalendarSettingEvent.initial());
},
child: BlocBuilder<CalendarSettingBloc, CalendarSettingState>(
builder: (context, state) {
final CalendarLayoutSettingPB? settings = state.layoutSetting;
if (settings == null) {
return const CircularProgressIndicator();
}
final availableSettings = _availableCalendarSettings(settings);
final bloc = context.read<CalendarSettingBloc>();
final items = availableSettings.map((setting) {
switch (setting) {
case CalendarLayoutSettingAction.showWeekNumber:
return ShowWeekNumber(
showWeekNumbers: settings.showWeekNumbers,
onUpdated: (showWeekNumbers) => bloc.add(
CalendarSettingEvent.updateLayoutSetting(
showWeekNumbers: showWeekNumbers,
),
),
);
case CalendarLayoutSettingAction.showWeekends:
return ShowWeekends(
showWeekends: settings.showWeekends,
onUpdated: (showWeekends) => bloc.add(
CalendarSettingEvent.updateLayoutSetting(
showWeekends: showWeekends,
),
),
);
case CalendarLayoutSettingAction.firstDayOfWeek:
return FirstDayOfWeek(
firstDayOfWeek: settings.firstDayOfWeek,
popoverMutex: popoverMutex,
onUpdated: (firstDayOfWeek) => bloc.add(
CalendarSettingEvent.updateLayoutSetting(
firstDayOfWeek: firstDayOfWeek,
),
),
);
case CalendarLayoutSettingAction.layoutField:
return LayoutDateField(
databaseController: widget.databaseController,
fieldId: settings.fieldId,
popoverMutex: popoverMutex,
onUpdated: (fieldId) => bloc.add(
CalendarSettingEvent.updateLayoutSetting(
layoutFieldId: fieldId,
),
),
);
default:
return const SizedBox.shrink();
}
}).toList();
return SizedBox(
width: 200,
child: ListView.separated(
shrinkWrap: true,
itemCount: items.length,
separatorBuilder: (_, __) =>
VSpace(GridSize.typeOptionSeparatorHeight),
physics: StyledScrollPhysics(),
itemBuilder: (_, int index) => items[index],
padding: const EdgeInsets.all(6.0),
),
);
},
),
);
}
List<CalendarLayoutSettingAction> _availableCalendarSettings(
CalendarLayoutSettingPB layoutSettings,
) {
final List<CalendarLayoutSettingAction> settings = [
CalendarLayoutSettingAction.layoutField,
];
switch (layoutSettings.layoutTy) {
case CalendarLayoutPB.DayLayout:
break;
case CalendarLayoutPB.MonthLayout:
case CalendarLayoutPB.WeekLayout:
settings.add(CalendarLayoutSettingAction.firstDayOfWeek);
break;
}
return settings;
}
}
class LayoutDateField extends StatelessWidget {
const LayoutDateField({
super.key,
required this.databaseController,
required this.fieldId,
required this.popoverMutex,
required this.onUpdated,
});
final DatabaseController databaseController;
final String fieldId;
final PopoverMutex popoverMutex;
final Function(String fieldId) onUpdated;
@override
Widget build(BuildContext context) {
return AppFlowyPopover(
direction: PopoverDirection.leftWithTopAligned,
triggerActions: PopoverTriggerFlags.hover | PopoverTriggerFlags.click,
constraints: BoxConstraints.loose(const Size(300, 400)),
mutex: popoverMutex,
offset: const Offset(-14, 0),
popupBuilder: (context) {
return BlocProvider(
create: (context) => DatabasePropertyBloc(
viewId: databaseController.viewId,
fieldController: databaseController.fieldController,
)..add(const DatabasePropertyEvent.initial()),
child: BlocBuilder<DatabasePropertyBloc, DatabasePropertyState>(
builder: (context, state) {
final items = state.fieldContexts
.where((field) => field.fieldType == FieldType.DateTime)
.map(
(fieldInfo) {
return SizedBox(
height: GridSize.popoverItemHeight,
child: FlowyButton(
text: FlowyText.medium(fieldInfo.name),
onTap: () {
onUpdated(fieldInfo.id);
popoverMutex.close();
},
leftIcon: const FlowySvg(FlowySvgs.grid_s),
rightIcon: fieldInfo.id == fieldId
? const FlowySvg(FlowySvgs.check_s)
: null,
),
);
},
).toList();
return SizedBox(
width: 200,
child: ListView.separated(
shrinkWrap: true,
itemBuilder: (_, index) => items[index],
separatorBuilder: (_, __) =>
VSpace(GridSize.typeOptionSeparatorHeight),
itemCount: items.length,
),
);
},
),
);
},
child: SizedBox(
height: GridSize.popoverItemHeight,
child: FlowyButton(
margin: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 10.0),
text: FlowyText.medium(
LocaleKeys.calendar_settings_layoutDateField.tr(),
),
),
),
);
}
}
class ShowWeekNumber extends StatelessWidget {
const ShowWeekNumber({
super.key,
required this.showWeekNumbers,
required this.onUpdated,
});
final bool showWeekNumbers;
final Function(bool showWeekNumbers) onUpdated;
@override
Widget build(BuildContext context) {
return _toggleItem(
onToggle: (showWeekNumbers) => onUpdated(!showWeekNumbers),
value: showWeekNumbers,
text: LocaleKeys.calendar_settings_showWeekNumbers.tr(),
);
}
}
class ShowWeekends extends StatelessWidget {
const ShowWeekends({
super.key,
required this.showWeekends,
required this.onUpdated,
});
final bool showWeekends;
final Function(bool showWeekends) onUpdated;
@override
Widget build(BuildContext context) {
return _toggleItem(
onToggle: (showWeekends) => onUpdated(!showWeekends),
value: showWeekends,
text: LocaleKeys.calendar_settings_showWeekends.tr(),
);
}
}
class FirstDayOfWeek extends StatelessWidget {
const FirstDayOfWeek({
super.key,
required this.firstDayOfWeek,
required this.popoverMutex,
required this.onUpdated,
});
final int firstDayOfWeek;
final PopoverMutex popoverMutex;
final Function(int firstDayOfWeek) onUpdated;
@override
Widget build(BuildContext context) {
return AppFlowyPopover(
direction: PopoverDirection.leftWithTopAligned,
constraints: BoxConstraints.loose(const Size(300, 400)),
triggerActions: PopoverTriggerFlags.hover | PopoverTriggerFlags.click,
mutex: popoverMutex,
offset: const Offset(-14, 0),
popupBuilder: (context) {
final symbols =
DateFormat.EEEE(context.locale.toLanguageTag()).dateSymbols;
// starts from sunday
const len = 2;
final items = symbols.WEEKDAYS.take(len).indexed.map((entry) {
return StartFromButton(
title: entry.$2,
dayIndex: entry.$1,
isSelected: firstDayOfWeek == entry.$1,
onTap: (index) {
onUpdated(index);
popoverMutex.close();
},
);
}).toList();
return SizedBox(
width: 100,
child: ListView.separated(
shrinkWrap: true,
itemBuilder: (_, index) => items[index],
separatorBuilder: (_, __) =>
VSpace(GridSize.typeOptionSeparatorHeight),
itemCount: len,
),
);
},
child: SizedBox(
height: GridSize.popoverItemHeight,
child: FlowyButton(
margin: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 10.0),
text: FlowyText.medium(
LocaleKeys.calendar_settings_firstDayOfWeek.tr(),
),
),
),
);
}
}
Widget _toggleItem({
required String text,
required bool value,
required void Function(bool) onToggle,
}) {
return SizedBox(
height: GridSize.popoverItemHeight,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 10.0),
child: Row(
children: [
FlowyText.medium(text),
const Spacer(),
Toggle(
value: value,
onChanged: (value) => onToggle(!value),
style: ToggleStyle.big,
padding: EdgeInsets.zero,
),
],
),
),
);
}
enum CalendarLayoutSettingAction {
layoutField,
layoutType,
showWeekends,
firstDayOfWeek,
showWeekNumber,
showTimeLine,
}
class StartFromButton extends StatelessWidget {
const StartFromButton({
super.key,
required this.title,
required this.dayIndex,
required this.onTap,
required this.isSelected,
});
final String title;
final int dayIndex;
final void Function(int) onTap;
final bool isSelected;
@override
Widget build(BuildContext context) {
return SizedBox(
height: GridSize.popoverItemHeight,
child: FlowyButton(
text: FlowyText.medium(title),
onTap: () => onTap(dayIndex),
rightIcon: isSelected ? const FlowySvg(FlowySvgs.check_s) : null,
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/presentation | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/calendar/presentation/layout/sizes.dart | import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:flutter/widgets.dart';
class CalendarSize {
static double scale = 1;
static double get headerContainerPadding => 12 * scale;
static EdgeInsets get contentInsets => EdgeInsets.fromLTRB(
GridSize.horizontalHeaderPadding,
CalendarSize.headerContainerPadding,
GridSize.horizontalHeaderPadding,
CalendarSize.headerContainerPadding,
);
static EdgeInsets get contentInsetsMobile => EdgeInsets.fromLTRB(
GridSize.horizontalHeaderPadding / 2,
0,
GridSize.horizontalHeaderPadding / 2,
0,
);
static double get scrollBarSize => 8 * scale;
static double get navigatorButtonWidth => 20 * scale;
static double get navigatorButtonHeight => 24 * scale;
static EdgeInsets get daysOfWeekInsets =>
EdgeInsets.only(top: 12.0 * scale, bottom: 5.0 * scale);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/grid.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/tab_bar/tab_bar_view.dart';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
class GridPluginBuilder implements PluginBuilder {
@override
Plugin build(dynamic data) {
if (data is ViewPB) {
return DatabaseTabBarViewPlugin(pluginType: pluginType, view: data);
} else {
throw FlowyPluginException.invalidData;
}
}
@override
String get menuName => LocaleKeys.grid_menuName.tr();
@override
FlowySvgData get icon => FlowySvgs.grid_s;
@override
PluginType get pluginType => PluginType.grid;
@override
ViewLayoutPB? get layoutType => ViewLayoutPB.Grid;
}
class GridPluginConfig implements PluginConfig {
@override
bool get creatable => true;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/grid_accessory_bloc.dart | import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'grid_accessory_bloc.freezed.dart';
class DatabaseViewSettingExtensionBloc extends Bloc<
DatabaseViewSettingExtensionEvent, DatabaseViewSettingExtensionState> {
DatabaseViewSettingExtensionBloc({required this.viewId})
: super(DatabaseViewSettingExtensionState.initial(viewId)) {
on<DatabaseViewSettingExtensionEvent>(
(event, emit) async {
event.when(
initial: () {},
toggleMenu: () {
emit(state.copyWith(isVisible: !state.isVisible));
},
);
},
);
}
final String viewId;
}
@freezed
class DatabaseViewSettingExtensionEvent
with _$DatabaseViewSettingExtensionEvent {
const factory DatabaseViewSettingExtensionEvent.initial() = _Initial;
const factory DatabaseViewSettingExtensionEvent.toggleMenu() =
_MenuVisibleChange;
}
@freezed
class DatabaseViewSettingExtensionState
with _$DatabaseViewSettingExtensionState {
const factory DatabaseViewSettingExtensionState({
required String viewId,
required bool isVisible,
}) = _DatabaseViewSettingExtensionState;
factory DatabaseViewSettingExtensionState.initial(
String viewId,
) =>
DatabaseViewSettingExtensionState(
viewId: viewId,
isVisible: false,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/grid_header_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/field_settings_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../domain/field_service.dart';
part 'grid_header_bloc.freezed.dart';
class GridHeaderBloc extends Bloc<GridHeaderEvent, GridHeaderState> {
GridHeaderBloc({required this.viewId, required this.fieldController})
: super(GridHeaderState.initial()) {
_dispatch();
}
final String viewId;
final FieldController fieldController;
void _dispatch() {
on<GridHeaderEvent>(
(event, emit) async {
await event.when(
initial: () {
_startListening();
add(
GridHeaderEvent.didReceiveFieldUpdate(fieldController.fieldInfos),
);
},
didReceiveFieldUpdate: (List<FieldInfo> fields) {
emit(
state.copyWith(
fields: fields
.where(
(element) =>
element.visibility != null &&
element.visibility != FieldVisibility.AlwaysHidden,
)
.toList(),
),
);
},
startEditingField: (fieldId) {
emit(state.copyWith(editingFieldId: fieldId));
},
startEditingNewField: (fieldId) {
emit(state.copyWith(editingFieldId: fieldId, newFieldId: fieldId));
},
endEditingField: () {
emit(state.copyWith(editingFieldId: null, newFieldId: null));
},
moveField: (fromIndex, toIndex) async {
await _moveField(fromIndex, toIndex, emit);
},
);
},
);
}
Future<void> _moveField(
int fromIndex,
int toIndex,
Emitter<GridHeaderState> emit,
) async {
final fromId = state.fields[fromIndex].id;
final toId = state.fields[toIndex].id;
final fields = List<FieldInfo>.from(state.fields);
fields.insert(toIndex, fields.removeAt(fromIndex));
emit(state.copyWith(fields: fields));
final result = await FieldBackendService.moveField(
viewId: viewId,
fromFieldId: fromId,
toFieldId: toId,
);
result.fold((l) {}, (err) => Log.error(err));
}
void _startListening() {
fieldController.addListener(
onReceiveFields: (fields) =>
add(GridHeaderEvent.didReceiveFieldUpdate(fields)),
listenWhen: () => !isClosed,
);
}
}
@freezed
class GridHeaderEvent with _$GridHeaderEvent {
const factory GridHeaderEvent.initial() = _InitialHeader;
const factory GridHeaderEvent.didReceiveFieldUpdate(List<FieldInfo> fields) =
_DidReceiveFieldUpdate;
const factory GridHeaderEvent.startEditingField(String fieldId) =
_StartEditingField;
const factory GridHeaderEvent.startEditingNewField(String fieldId) =
_StartEditingNewField;
const factory GridHeaderEvent.endEditingField() = _EndEditingField;
const factory GridHeaderEvent.moveField(
int fromIndex,
int toIndex,
) = _MoveField;
}
@freezed
class GridHeaderState with _$GridHeaderState {
const factory GridHeaderState({
required List<FieldInfo> fields,
required String? editingFieldId,
required String? newFieldId,
}) = _GridHeaderState;
factory GridHeaderState.initial() =>
const GridHeaderState(fields: [], editingFieldId: null, newFieldId: null);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/grid_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/defines.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/application/row/row_cache.dart';
import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/filter_info.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/sort_info.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../application/database_controller.dart';
part 'grid_bloc.freezed.dart';
class GridBloc extends Bloc<GridEvent, GridState> {
GridBloc({required ViewPB view, required this.databaseController})
: super(GridState.initial(view.id)) {
_dispatch();
}
final DatabaseController databaseController;
String get viewId => databaseController.viewId;
void _dispatch() {
on<GridEvent>(
(event, emit) async {
await event.when(
initial: () async {
_startListening();
await _openGrid(emit);
},
createRow: (openRowDetail) async {
final result = await RowBackendService.createRow(viewId: viewId);
result.fold(
(createdRow) => emit(
state.copyWith(
createdRow: createdRow,
openRowDetail: openRowDetail ?? false,
),
),
(err) => Log.error(err),
);
},
resetCreatedRow: () {
emit(state.copyWith(createdRow: null, openRowDetail: false));
},
deleteRow: (rowInfo) async {
await RowBackendService.deleteRow(rowInfo.viewId, rowInfo.rowId);
},
moveRow: (int from, int to) {
final List<RowInfo> rows = [...state.rowInfos];
final fromRow = rows[from].rowId;
final toRow = rows[to].rowId;
rows.insert(to, rows.removeAt(from));
emit(state.copyWith(rowInfos: rows));
databaseController.moveRow(fromRowId: fromRow, toRowId: toRow);
},
didReceiveGridUpdate: (grid) {
emit(state.copyWith(grid: grid));
},
didReceiveFieldUpdate: (fields) {
emit(
state.copyWith(
fields: fields,
),
);
},
didLoadRows: (newRowInfos, reason) {
emit(
state.copyWith(
rowInfos: newRowInfos,
rowCount: newRowInfos.length,
reason: reason,
),
);
},
didReceveFilters: (List<FilterInfo> filters) {
emit(
state.copyWith(filters: filters),
);
},
didReceveSorts: (List<SortInfo> sorts) {
emit(
state.copyWith(
reorderable: sorts.isEmpty,
sorts: sorts,
),
);
},
);
},
);
}
RowCache getRowCache(RowId rowId) => databaseController.rowCache;
void _startListening() {
final onDatabaseChanged = DatabaseCallbacks(
onDatabaseChanged: (database) {
if (!isClosed) {
add(GridEvent.didReceiveGridUpdate(database));
}
},
onNumOfRowsChanged: (rowInfos, _, reason) {
if (!isClosed) {
add(GridEvent.didLoadRows(rowInfos, reason));
}
},
onRowsUpdated: (rows, reason) {
if (!isClosed) {
add(
GridEvent.didLoadRows(databaseController.rowCache.rowInfos, reason),
);
}
},
onFieldsChanged: (fields) {
if (!isClosed) {
add(GridEvent.didReceiveFieldUpdate(fields));
}
},
onFiltersChanged: (filters) {
if (!isClosed) {
add(GridEvent.didReceveFilters(filters));
}
},
onSortsChanged: (sorts) {
if (!isClosed) {
add(GridEvent.didReceveSorts(sorts));
}
},
);
databaseController.addListener(onDatabaseChanged: onDatabaseChanged);
}
Future<void> _openGrid(Emitter<GridState> emit) async {
final result = await databaseController.open();
result.fold(
(grid) {
databaseController.setIsLoading(false);
emit(
state.copyWith(
loadingState: LoadingState.finish(FlowyResult.success(null)),
),
);
},
(err) => emit(
state.copyWith(
loadingState: LoadingState.finish(FlowyResult.failure(err)),
),
),
);
}
}
@freezed
class GridEvent with _$GridEvent {
const factory GridEvent.initial() = InitialGrid;
const factory GridEvent.createRow({bool? openRowDetail}) = _CreateRow;
const factory GridEvent.resetCreatedRow() = _ResetCreatedRow;
const factory GridEvent.deleteRow(RowInfo rowInfo) = _DeleteRow;
const factory GridEvent.moveRow(int from, int to) = _MoveRow;
const factory GridEvent.didLoadRows(
List<RowInfo> rows,
ChangedReason reason,
) = _DidReceiveRowUpdate;
const factory GridEvent.didReceiveFieldUpdate(
List<FieldInfo> fields,
) = _DidReceiveFieldUpdate;
const factory GridEvent.didReceiveGridUpdate(
DatabasePB grid,
) = _DidReceiveGridUpdate;
const factory GridEvent.didReceveFilters(List<FilterInfo> filters) =
_DidReceiveFilters;
const factory GridEvent.didReceveSorts(List<SortInfo> sorts) =
_DidReceiveSorts;
}
@freezed
class GridState with _$GridState {
const factory GridState({
required String viewId,
required DatabasePB? grid,
required List<FieldInfo> fields,
required List<RowInfo> rowInfos,
required int rowCount,
required RowMetaPB? createdRow,
required LoadingState loadingState,
required bool reorderable,
required ChangedReason reason,
required List<SortInfo> sorts,
required List<FilterInfo> filters,
required bool openRowDetail,
}) = _GridState;
factory GridState.initial(String viewId) => GridState(
fields: [],
rowInfos: [],
rowCount: 0,
createdRow: null,
grid: null,
viewId: viewId,
reorderable: true,
loadingState: const LoadingState.loading(),
reason: const InitialListState(),
filters: [],
sorts: [],
openRowDetail: false,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/sort/sort_editor_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/domain/sort_service.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/sort_info.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:collection/collection.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'sort_editor_bloc.freezed.dart';
class SortEditorBloc extends Bloc<SortEditorEvent, SortEditorState> {
SortEditorBloc({
required this.viewId,
required this.fieldController,
}) : _sortBackendSvc = SortBackendService(viewId: viewId),
super(
SortEditorState.initial(
fieldController.sortInfos,
fieldController.fieldInfos,
),
) {
_dispatch();
_startListening();
}
final String viewId;
final SortBackendService _sortBackendSvc;
final FieldController fieldController;
void Function(List<FieldInfo>)? _onFieldFn;
void Function(List<SortInfo>)? _onSortsFn;
void _dispatch() {
on<SortEditorEvent>(
(event, emit) async {
await event.when(
didReceiveFields: (List<FieldInfo> fields) {
emit(
state.copyWith(
allFields: fields,
creatableFields: getCreatableSorts(fields),
),
);
},
updateCreateSortFilter: (text) {
emit(state.copyWith(filter: text));
},
createSort: (
String fieldId,
SortConditionPB? condition,
) async {
final result = await _sortBackendSvc.insertSort(
fieldId: fieldId,
condition: condition ?? SortConditionPB.Ascending,
);
result.fold((l) => {}, (err) => Log.error(err));
},
editSort: (
String sortId,
String? fieldId,
SortConditionPB? condition,
) async {
final sortInfo = state.sortInfos
.firstWhereOrNull((element) => element.sortId == sortId);
if (sortInfo == null) {
return;
}
final result = await _sortBackendSvc.updateSort(
sortId: sortId,
fieldId: fieldId ?? sortInfo.fieldId,
condition: condition ?? sortInfo.sortPB.condition,
);
result.fold((l) => {}, (err) => Log.error(err));
},
deleteAllSorts: () async {
final result = await _sortBackendSvc.deleteAllSorts();
result.fold((l) => {}, (err) => Log.error(err));
},
didReceiveSorts: (List<SortInfo> sortInfos) {
emit(state.copyWith(sortInfos: sortInfos));
},
deleteSort: (SortInfo sortInfo) async {
final result = await _sortBackendSvc.deleteSort(
fieldId: sortInfo.fieldInfo.id,
sortId: sortInfo.sortId,
);
result.fold((l) => null, (err) => Log.error(err));
},
reorderSort: (fromIndex, toIndex) async {
if (fromIndex < toIndex) {
toIndex--;
}
final fromId = state.sortInfos[fromIndex].sortId;
final toId = state.sortInfos[toIndex].sortId;
final newSorts = [...state.sortInfos];
newSorts.insert(toIndex, newSorts.removeAt(fromIndex));
emit(state.copyWith(sortInfos: newSorts));
final result = await _sortBackendSvc.reorderSort(
fromSortId: fromId,
toSortId: toId,
);
result.fold((l) => null, (err) => Log.error(err));
},
);
},
);
}
void _startListening() {
_onFieldFn = (fields) {
add(SortEditorEvent.didReceiveFields(List.from(fields)));
};
_onSortsFn = (sorts) {
add(SortEditorEvent.didReceiveSorts(sorts));
};
fieldController.addListener(
listenWhen: () => !isClosed,
onReceiveFields: _onFieldFn,
onSorts: _onSortsFn,
);
}
@override
Future<void> close() async {
fieldController.removeListener(
onFieldsListener: _onFieldFn,
onSortsListener: _onSortsFn,
);
_onFieldFn = null;
_onSortsFn = null;
return super.close();
}
}
@freezed
class SortEditorEvent with _$SortEditorEvent {
const factory SortEditorEvent.didReceiveFields(List<FieldInfo> fieldInfos) =
_DidReceiveFields;
const factory SortEditorEvent.didReceiveSorts(List<SortInfo> sortInfos) =
_DidReceiveSorts;
const factory SortEditorEvent.updateCreateSortFilter(String text) =
_UpdateCreateSortFilter;
const factory SortEditorEvent.createSort({
required String fieldId,
SortConditionPB? condition,
}) = _CreateSort;
const factory SortEditorEvent.editSort({
required String sortId,
String? fieldId,
SortConditionPB? condition,
}) = _EditSort;
const factory SortEditorEvent.reorderSort(int oldIndex, int newIndex) =
_ReorderSort;
const factory SortEditorEvent.deleteSort(SortInfo sortInfo) = _DeleteSort;
const factory SortEditorEvent.deleteAllSorts() = _DeleteAllSorts;
}
@freezed
class SortEditorState with _$SortEditorState {
const factory SortEditorState({
required List<SortInfo> sortInfos,
required List<FieldInfo> creatableFields,
required List<FieldInfo> allFields,
required String filter,
}) = _SortEditorState;
factory SortEditorState.initial(
List<SortInfo> sortInfos,
List<FieldInfo> fields,
) {
return SortEditorState(
creatableFields: getCreatableSorts(fields),
allFields: fields,
sortInfos: sortInfos,
filter: "",
);
}
}
List<FieldInfo> getCreatableSorts(List<FieldInfo> fieldInfos) {
final List<FieldInfo> creatableFields = List.from(fieldInfos);
creatableFields.retainWhere((element) => element.canCreateSort);
return creatableFields;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/row/mobile_row_detail_bloc.dart | import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/application/row/row_cache.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'mobile_row_detail_bloc.freezed.dart';
class MobileRowDetailBloc
extends Bloc<MobileRowDetailEvent, MobileRowDetailState> {
MobileRowDetailBloc({required this.databaseController})
: super(MobileRowDetailState.initial()) {
_dispatch();
}
final DatabaseController databaseController;
void _dispatch() {
on<MobileRowDetailEvent>(
(event, emit) {
event.when(
initial: (rowId) {
_startListening();
emit(
state.copyWith(
isLoading: false,
currentRowId: rowId,
rowInfos: databaseController.rowCache.rowInfos,
),
);
},
didLoadRows: (rows) {
emit(state.copyWith(rowInfos: rows));
},
changeRowId: (rowId) {
emit(state.copyWith(currentRowId: rowId));
},
);
},
);
}
void _startListening() {
final onDatabaseChanged = DatabaseCallbacks(
onNumOfRowsChanged: (rowInfos, _, reason) {
if (!isClosed) {
add(MobileRowDetailEvent.didLoadRows(rowInfos));
}
},
onRowsUpdated: (rows, reason) {
if (!isClosed) {
add(
MobileRowDetailEvent.didLoadRows(
databaseController.rowCache.rowInfos,
),
);
}
},
);
databaseController.addListener(onDatabaseChanged: onDatabaseChanged);
}
}
@freezed
class MobileRowDetailEvent with _$MobileRowDetailEvent {
const factory MobileRowDetailEvent.initial(String rowId) = _Initial;
const factory MobileRowDetailEvent.didLoadRows(List<RowInfo> rows) =
_DidLoadRows;
const factory MobileRowDetailEvent.changeRowId(String rowId) = _ChangeRowId;
}
@freezed
class MobileRowDetailState with _$MobileRowDetailState {
const factory MobileRowDetailState({
required bool isLoading,
required String? currentRowId,
required List<RowInfo> rowInfos,
}) = _MobileRowDetailState;
factory MobileRowDetailState.initial() {
return const MobileRowDetailState(
isLoading: true,
rowInfos: [],
currentRowId: null,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/row/row_document_bloc.dart | import 'package:flutter/foundation.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-error/code.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../../application/row/row_service.dart';
part 'row_document_bloc.freezed.dart';
class RowDocumentBloc extends Bloc<RowDocumentEvent, RowDocumentState> {
RowDocumentBloc({
required this.rowId,
required String viewId,
}) : _rowBackendSvc = RowBackendService(viewId: viewId),
super(RowDocumentState.initial()) {
_dispatch();
}
final String rowId;
final RowBackendService _rowBackendSvc;
void _dispatch() {
on<RowDocumentEvent>(
(event, emit) async {
await event.when(
initial: () {
_getRowDocumentView();
},
didReceiveRowDocument: (view) {
emit(
state.copyWith(
viewPB: view,
loadingState: const LoadingState.finish(),
),
);
},
didReceiveError: (FlowyError error) {
emit(
state.copyWith(
loadingState: LoadingState.error(error),
),
);
},
updateIsEmpty: (isEmpty) async {
final unitOrFailure = await _rowBackendSvc.updateMeta(
rowId: rowId,
isDocumentEmpty: isEmpty,
);
unitOrFailure.fold((l) => null, (err) => Log.error(err));
},
);
},
);
}
Future<void> _getRowDocumentView() async {
final rowDetailOrError = await _rowBackendSvc.getRowMeta(rowId);
rowDetailOrError.fold(
(RowMetaPB rowMeta) async {
final viewsOrError =
await ViewBackendService.getView(rowMeta.documentId);
if (isClosed) {
return;
}
viewsOrError.fold(
(view) => add(RowDocumentEvent.didReceiveRowDocument(view)),
(error) async {
if (error.code == ErrorCode.RecordNotFound) {
// By default, the document of the row is not exist. So creating a
// new document for the given document id of the row.
final documentView =
await _createRowDocumentView(rowMeta.documentId);
if (documentView != null) {
add(RowDocumentEvent.didReceiveRowDocument(documentView));
}
} else {
add(RowDocumentEvent.didReceiveError(error));
}
},
);
},
(err) => Log.error('Failed to get row detail: $err'),
);
}
Future<ViewPB?> _createRowDocumentView(String viewId) async {
final result = await ViewBackendService.createOrphanView(
viewId: viewId,
name: LocaleKeys.menuAppHeader_defaultNewPageName.tr(),
desc: '',
layoutType: ViewLayoutPB.Document,
);
return result.fold(
(view) => view,
(error) {
Log.error(error);
return null;
},
);
}
}
@freezed
class RowDocumentEvent with _$RowDocumentEvent {
const factory RowDocumentEvent.initial() = _InitialRow;
const factory RowDocumentEvent.didReceiveRowDocument(ViewPB view) =
_DidReceiveRowDocument;
const factory RowDocumentEvent.didReceiveError(FlowyError error) =
_DidReceiveError;
const factory RowDocumentEvent.updateIsEmpty(bool isDocumentEmpty) =
_UpdateIsEmpty;
}
@freezed
class RowDocumentState with _$RowDocumentState {
const factory RowDocumentState({
ViewPB? viewPB,
required LoadingState loadingState,
}) = _RowDocumentState;
factory RowDocumentState.initial() => const RowDocumentState(
loadingState: LoadingState.loading(),
);
}
@freezed
class LoadingState with _$LoadingState {
const factory LoadingState.loading() = _Loading;
const factory LoadingState.error(FlowyError error) = _Error;
const factory LoadingState.finish() = _Finish;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/row/row_bloc.dart | import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:appflowy/plugins/database/application/cell/cell_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/widgets/setting/field_visibility_extension.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../../application/row/row_cache.dart';
import '../../../application/row/row_controller.dart';
import '../../../application/row/row_service.dart';
part 'row_bloc.freezed.dart';
class RowBloc extends Bloc<RowEvent, RowState> {
RowBloc({
required this.fieldController,
required this.rowId,
required this.viewId,
required RowController rowController,
}) : _rowBackendSvc = RowBackendService(viewId: viewId),
_rowController = rowController,
super(RowState.initial()) {
_dispatch();
_startListening();
_init();
}
final FieldController fieldController;
final RowBackendService _rowBackendSvc;
final RowController _rowController;
final String viewId;
final String rowId;
@override
Future<void> close() async {
_rowController.dispose();
return super.close();
}
void _dispatch() {
on<RowEvent>(
(event, emit) async {
event.when(
createRow: () {
_rowBackendSvc.createRowAfter(rowId);
},
didReceiveCells: (List<CellContext> cellContexts, reason) {
final visibleCellContexts = cellContexts
.where(
(cellContext) => fieldController
.getField(cellContext.fieldId)!
.fieldSettings!
.visibility
.isVisibleState(),
)
.toList();
emit(
state.copyWith(
cellContexts: visibleCellContexts,
changeReason: reason,
),
);
},
);
},
);
}
void _startListening() {
_rowController.addListener(
onRowChanged: (cells, reason) {
if (!isClosed) {
add(RowEvent.didReceiveCells(cells, reason));
}
},
);
}
void _init() {
add(
RowEvent.didReceiveCells(
_rowController.loadData(),
const ChangedReason.setInitialRows(),
),
);
}
}
@freezed
class RowEvent with _$RowEvent {
const factory RowEvent.createRow() = _CreateRow;
const factory RowEvent.didReceiveCells(
List<CellContext> cellsByFieldId,
ChangedReason reason,
) = _DidReceiveCells;
}
@freezed
class RowState with _$RowState {
const factory RowState({
required List<CellContext> cellContexts,
ChangedReason? changeReason,
}) = _RowState;
factory RowState.initial() => const RowState(cellContexts: []);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/row/row_detail_bloc.dart | import 'package:appflowy/plugins/database/application/cell/cell_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/domain/field_service.dart';
import 'package:appflowy/plugins/database/domain/field_settings_service.dart';
import 'package:appflowy/plugins/database/application/row/row_controller.dart';
import 'package:appflowy/plugins/database/widgets/setting/field_visibility_extension.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/field_settings_entities.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'row_detail_bloc.freezed.dart';
class RowDetailBloc extends Bloc<RowDetailEvent, RowDetailState> {
RowDetailBloc({
required this.fieldController,
required this.rowController,
}) : super(RowDetailState.initial()) {
_dispatch();
_startListening();
_init();
}
final FieldController fieldController;
final RowController rowController;
final List<CellContext> allCells = [];
@override
Future<void> close() async {
rowController.dispose();
return super.close();
}
void _dispatch() {
on<RowDetailEvent>(
(event, emit) async {
await event.when(
didReceiveCellDatas: (visibleCells, numHiddenFields) {
emit(
state.copyWith(
visibleCells: visibleCells,
numHiddenFields: numHiddenFields,
),
);
},
didUpdateFields: (fields) {
emit(state.copyWith(fields: fields));
},
deleteField: (fieldId) async {
final result = await FieldBackendService.deleteField(
viewId: rowController.viewId,
fieldId: fieldId,
);
result.fold((l) {}, (err) => Log.error(err));
},
toggleFieldVisibility: (fieldId) async {
await _toggleFieldVisibility(fieldId, emit);
},
reorderField: (fromIndex, toIndex) async {
await _reorderField(fromIndex, toIndex, emit);
},
toggleHiddenFieldVisibility: () {
final showHiddenFields = !state.showHiddenFields;
final visibleCells = List<CellContext>.from(
allCells.where((cellContext) {
final fieldInfo = fieldController.getField(cellContext.fieldId);
return fieldInfo != null &&
!fieldInfo.isPrimary &&
(fieldInfo.visibility!.isVisibleState() ||
showHiddenFields);
}),
);
emit(
state.copyWith(
showHiddenFields: showHiddenFields,
visibleCells: visibleCells,
),
);
},
);
},
);
}
void _startListening() {
rowController.addListener(
onRowChanged: (cellMap, reason) {
if (isClosed) {
return;
}
allCells.clear();
allCells.addAll(cellMap);
int numHiddenFields = 0;
final visibleCells = <CellContext>[];
for (final cellContext in allCells) {
final fieldInfo = fieldController.getField(cellContext.fieldId);
if (fieldInfo == null || fieldInfo.isPrimary) {
continue;
}
final isHidden = !fieldInfo.visibility!.isVisibleState();
if (!isHidden || state.showHiddenFields) {
visibleCells.add(cellContext);
}
if (isHidden) {
numHiddenFields++;
}
}
add(
RowDetailEvent.didReceiveCellDatas(
visibleCells,
numHiddenFields,
),
);
},
);
fieldController.addListener(
onReceiveFields: (fields) => add(RowDetailEvent.didUpdateFields(fields)),
listenWhen: () => !isClosed,
);
}
void _init() {
allCells.addAll(rowController.loadData());
int numHiddenFields = 0;
final visibleCells = <CellContext>[];
for (final cell in allCells) {
final fieldInfo = fieldController.getField(cell.fieldId);
if (fieldInfo == null || fieldInfo.isPrimary) {
continue;
}
final isHidden = !fieldInfo.visibility!.isVisibleState();
if (!isHidden) {
visibleCells.add(cell);
} else {
numHiddenFields++;
}
}
add(
RowDetailEvent.didReceiveCellDatas(
visibleCells,
numHiddenFields,
),
);
add(RowDetailEvent.didUpdateFields(fieldController.fieldInfos));
}
Future<void> _toggleFieldVisibility(
String fieldId,
Emitter<RowDetailState> emit,
) async {
final fieldInfo = fieldController.getField(fieldId)!;
final fieldVisibility = fieldInfo.visibility == FieldVisibility.AlwaysShown
? FieldVisibility.AlwaysHidden
: FieldVisibility.AlwaysShown;
final result =
await FieldSettingsBackendService(viewId: rowController.viewId)
.updateFieldSettings(
fieldId: fieldId,
fieldVisibility: fieldVisibility,
);
result.fold((l) {}, (err) => Log.error(err));
}
Future<void> _reorderField(
int fromIndex,
int toIndex,
Emitter<RowDetailState> emit,
) async {
if (fromIndex < toIndex) {
toIndex--;
}
final fromId = state.visibleCells[fromIndex].fieldId;
final toId = state.visibleCells[toIndex].fieldId;
final cells = List<CellContext>.from(state.visibleCells);
cells.insert(toIndex, cells.removeAt(fromIndex));
emit(state.copyWith(visibleCells: cells));
final result = await FieldBackendService.moveField(
viewId: rowController.viewId,
fromFieldId: fromId,
toFieldId: toId,
);
result.fold((l) {}, (err) => Log.error(err));
}
}
@freezed
class RowDetailEvent with _$RowDetailEvent {
const factory RowDetailEvent.didUpdateFields(List<FieldInfo> fields) =
_DidUpdateFields;
/// Triggered by listeners to update row data
const factory RowDetailEvent.didReceiveCellDatas(
List<CellContext> visibleCells,
int numHiddenFields,
) = _DidReceiveCellDatas;
/// Used to delete a field
const factory RowDetailEvent.deleteField(String fieldId) = _DeleteField;
/// Used to show/hide a field
const factory RowDetailEvent.toggleFieldVisibility(String fieldId) =
_ToggleFieldVisibility;
/// Used to reorder a field
const factory RowDetailEvent.reorderField(
int fromIndex,
int toIndex,
) = _ReorderField;
/// Used to hide/show the hidden fields in the row detail page
const factory RowDetailEvent.toggleHiddenFieldVisibility() =
_ToggleHiddenFieldVisibility;
}
@freezed
class RowDetailState with _$RowDetailState {
const factory RowDetailState({
required List<FieldInfo> fields,
required List<CellContext> visibleCells,
required bool showHiddenFields,
required int numHiddenFields,
}) = _RowDetailState;
factory RowDetailState.initial() => const RowDetailState(
fields: [],
visibleCells: [],
showHiddenFields: false,
numHiddenFields: 0,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/calculations/field_type_calc_ext.dart | import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
extension AvailableCalculations on FieldType {
List<CalculationType> calculationsForFieldType() {
final calculationTypes = [
CalculationType.Count,
];
// These FieldTypes cannot be empty, or might hold secondary
// data causing them to be seen as not empty when in fact they
// are empty.
if (![
FieldType.URL,
FieldType.Checkbox,
FieldType.LastEditedTime,
FieldType.CreatedTime,
].contains(this)) {
calculationTypes.addAll([
CalculationType.CountEmpty,
CalculationType.CountNonEmpty,
]);
}
switch (this) {
case FieldType.Number:
calculationTypes.addAll([
CalculationType.Sum,
CalculationType.Average,
CalculationType.Min,
CalculationType.Max,
CalculationType.Median,
]);
break;
default:
break;
}
return calculationTypes;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/calculations/calculations_bloc.dart | import 'package:appflowy/plugins/database/application/calculations/calculations_listener.dart';
import 'package:appflowy/plugins/database/application/calculations/calculations_service.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/calculation_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/field_settings_entities.pbenum.dart';
import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'calculations_bloc.freezed.dart';
class CalculationsBloc extends Bloc<CalculationsEvent, CalculationsState> {
CalculationsBloc({
required this.viewId,
required FieldController fieldController,
}) : _fieldController = fieldController,
_calculationsListener = CalculationsListener(viewId: viewId),
_calculationsService = CalculationsBackendService(viewId: viewId),
super(CalculationsState.initial()) {
_dispatch();
}
final String viewId;
final FieldController _fieldController;
final CalculationsListener _calculationsListener;
late final CalculationsBackendService _calculationsService;
@override
Future<void> close() async {
_fieldController.removeListener(onFieldsListener: _onReceiveFields);
await _calculationsListener.stop();
await super.close();
}
void _dispatch() {
on<CalculationsEvent>((event, emit) async {
await event.when(
started: () async {
_startListening();
await _getAllCalculations();
add(
CalculationsEvent.didReceiveFieldUpdate(
_fieldController.fieldInfos,
),
);
},
didReceiveFieldUpdate: (fields) async {
emit(
state.copyWith(
fields: fields
.where(
(e) =>
e.visibility != null &&
e.visibility != FieldVisibility.AlwaysHidden,
)
.toList(),
),
);
},
didReceiveCalculationsUpdate: (calculationsMap) async {
emit(
state.copyWith(
calculationsByFieldId: calculationsMap,
),
);
},
updateCalculationType: (fieldId, type, calculationId) async {
await _calculationsService.updateCalculation(
fieldId,
type,
calculationId: calculationId,
);
},
removeCalculation: (fieldId, calculationId) async {
await _calculationsService.removeCalculation(fieldId, calculationId);
},
);
});
}
void _startListening() {
_fieldController.addListener(
listenWhen: () => !isClosed,
onReceiveFields: _onReceiveFields,
);
_calculationsListener.start(
onCalculationChanged: (changesetOrFailure) {
if (isClosed) {
return;
}
changesetOrFailure.fold(
(changeset) {
final calculationsMap = {...state.calculationsByFieldId};
if (changeset.insertCalculations.isNotEmpty) {
for (final insert in changeset.insertCalculations) {
calculationsMap[insert.fieldId] = insert;
}
}
if (changeset.updateCalculations.isNotEmpty) {
for (final update in changeset.updateCalculations) {
calculationsMap.removeWhere((key, _) => key == update.fieldId);
calculationsMap.addAll({update.fieldId: update});
}
}
if (changeset.deleteCalculations.isNotEmpty) {
for (final delete in changeset.deleteCalculations) {
calculationsMap.removeWhere((key, _) => key == delete.fieldId);
}
}
add(
CalculationsEvent.didReceiveCalculationsUpdate(
calculationsMap,
),
);
},
(_) => null,
);
},
);
}
void _onReceiveFields(List<FieldInfo> fields) =>
add(CalculationsEvent.didReceiveFieldUpdate(fields));
Future<void> _getAllCalculations() async {
final calculationsOrFailure = await _calculationsService.getCalculations();
final RepeatedCalculationsPB? calculations =
calculationsOrFailure.fold((s) => s, (e) => null);
if (calculations != null) {
final calculationMap = <String, CalculationPB>{};
for (final calculation in calculations.items) {
calculationMap[calculation.fieldId] = calculation;
}
add(CalculationsEvent.didReceiveCalculationsUpdate(calculationMap));
}
}
}
@freezed
class CalculationsEvent with _$CalculationsEvent {
const factory CalculationsEvent.started() = _Started;
const factory CalculationsEvent.didReceiveFieldUpdate(
List<FieldInfo> fields,
) = _DidReceiveFieldUpdate;
const factory CalculationsEvent.didReceiveCalculationsUpdate(
Map<String, CalculationPB> calculationsByFieldId,
) = _DidReceiveCalculationsUpdate;
const factory CalculationsEvent.updateCalculationType(
String fieldId,
CalculationType type, {
@Default(null) String? calculationId,
}) = _UpdateCalculationType;
const factory CalculationsEvent.removeCalculation(
String fieldId,
String calculationId,
) = _RemoveCalculation;
}
@freezed
class CalculationsState with _$CalculationsState {
const factory CalculationsState({
required List<FieldInfo> fields,
required Map<String, CalculationPB> calculationsByFieldId,
}) = _CalculationsState;
factory CalculationsState.initial() => const CalculationsState(
fields: [],
calculationsByFieldId: {},
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/filter/select_option_filter_list_bloc.dart | import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/choicechip/select_option/select_option_loader.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'select_option_filter_list_bloc.freezed.dart';
class SelectOptionFilterListBloc<T>
extends Bloc<SelectOptionFilterListEvent, SelectOptionFilterListState> {
SelectOptionFilterListBloc({
required this.delegate,
required List<String> selectedOptionIds,
}) : super(SelectOptionFilterListState.initial(selectedOptionIds)) {
_dispatch();
}
final SelectOptionFilterDelegate delegate;
void _dispatch() {
on<SelectOptionFilterListEvent>(
(event, emit) async {
await event.when(
initial: () async {
_startListening();
_loadOptions();
},
selectOption: (option, condition) {
final selectedOptionIds = delegate.selectOption(
state.selectedOptionIds,
option.id,
condition,
);
_updateSelectOptions(
selectedOptionIds: selectedOptionIds,
emit: emit,
);
},
unSelectOption: (option) {
final selectedOptionIds = Set<String>.from(state.selectedOptionIds);
selectedOptionIds.remove(option.id);
_updateSelectOptions(
selectedOptionIds: selectedOptionIds,
emit: emit,
);
},
didReceiveOptions: (newOptions) {
final List<SelectOptionPB> options = List.from(newOptions);
options.retainWhere(
(element) => element.name.contains(state.predicate),
);
final visibleOptions = options.map((option) {
return VisibleSelectOption(
option,
state.selectedOptionIds.contains(option.id),
);
}).toList();
emit(
state.copyWith(
options: options,
visibleOptions: visibleOptions,
),
);
},
filterOption: (optionName) {
_updateSelectOptions(predicate: optionName, emit: emit);
},
);
},
);
}
void _updateSelectOptions({
String? predicate,
Set<String>? selectedOptionIds,
required Emitter<SelectOptionFilterListState> emit,
}) {
final List<VisibleSelectOption> visibleOptions = _makeVisibleOptions(
predicate ?? state.predicate,
selectedOptionIds ?? state.selectedOptionIds,
);
emit(
state.copyWith(
predicate: predicate ?? state.predicate,
visibleOptions: visibleOptions,
selectedOptionIds: selectedOptionIds ?? state.selectedOptionIds,
),
);
}
List<VisibleSelectOption> _makeVisibleOptions(
String predicate,
Set<String> selectedOptionIds,
) {
final List<SelectOptionPB> options = List.from(state.options);
options.retainWhere((element) => element.name.contains(predicate));
return options.map((option) {
return VisibleSelectOption(option, selectedOptionIds.contains(option.id));
}).toList();
}
void _loadOptions() {
if (!isClosed) {
final options = delegate.loadOptions();
add(SelectOptionFilterListEvent.didReceiveOptions(options));
}
}
void _startListening() {}
}
@freezed
class SelectOptionFilterListEvent with _$SelectOptionFilterListEvent {
const factory SelectOptionFilterListEvent.initial() = _Initial;
const factory SelectOptionFilterListEvent.selectOption(
SelectOptionPB option,
SelectOptionFilterConditionPB condition,
) = _SelectOption;
const factory SelectOptionFilterListEvent.unSelectOption(
SelectOptionPB option,
) = _UnSelectOption;
const factory SelectOptionFilterListEvent.didReceiveOptions(
List<SelectOptionPB> options,
) = _DidReceiveOptions;
const factory SelectOptionFilterListEvent.filterOption(String optionName) =
_SelectOptionFilter;
}
@freezed
class SelectOptionFilterListState with _$SelectOptionFilterListState {
const factory SelectOptionFilterListState({
required List<SelectOptionPB> options,
required List<VisibleSelectOption> visibleOptions,
required Set<String> selectedOptionIds,
required String predicate,
}) = _SelectOptionFilterListState;
factory SelectOptionFilterListState.initial(List<String> selectedOptionIds) {
return SelectOptionFilterListState(
options: [],
predicate: '',
visibleOptions: [],
selectedOptionIds: selectedOptionIds.toSet(),
);
}
}
class VisibleSelectOption {
VisibleSelectOption(this.optionPB, this.isSelected);
final SelectOptionPB optionPB;
final bool isSelected;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/filter/filter_menu_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/filter_info.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'filter_menu_bloc.freezed.dart';
class DatabaseFilterMenuBloc
extends Bloc<DatabaseFilterMenuEvent, DatabaseFilterMenuState> {
DatabaseFilterMenuBloc({required this.viewId, required this.fieldController})
: super(
DatabaseFilterMenuState.initial(
viewId,
fieldController.filterInfos,
fieldController.fieldInfos,
),
) {
_dispatch();
}
final String viewId;
final FieldController fieldController;
void Function(List<FilterInfo>)? _onFilterFn;
void Function(List<FieldInfo>)? _onFieldFn;
void _dispatch() {
on<DatabaseFilterMenuEvent>(
(event, emit) async {
event.when(
initial: () {
_startListening();
},
didReceiveFilters: (filters) {
emit(state.copyWith(filters: filters));
},
toggleMenu: () {
final isVisible = !state.isVisible;
emit(state.copyWith(isVisible: isVisible));
},
didReceiveFields: (List<FieldInfo> fields) {
emit(
state.copyWith(
fields: fields,
creatableFields: getCreatableFilter(fields),
),
);
},
);
},
);
}
void _startListening() {
_onFilterFn = (filters) {
add(DatabaseFilterMenuEvent.didReceiveFilters(filters));
};
_onFieldFn = (fields) {
add(DatabaseFilterMenuEvent.didReceiveFields(fields));
};
fieldController.addListener(
onFilters: (filters) {
_onFilterFn?.call(filters);
},
onReceiveFields: (fields) {
_onFieldFn?.call(fields);
},
);
}
@override
Future<void> close() async {
if (_onFilterFn != null) {
fieldController.removeListener(onFiltersListener: _onFilterFn!);
_onFilterFn = null;
}
if (_onFieldFn != null) {
fieldController.removeListener(onFieldsListener: _onFieldFn!);
_onFieldFn = null;
}
return super.close();
}
}
@freezed
class DatabaseFilterMenuEvent with _$DatabaseFilterMenuEvent {
const factory DatabaseFilterMenuEvent.initial() = _Initial;
const factory DatabaseFilterMenuEvent.didReceiveFilters(
List<FilterInfo> filters,
) = _DidReceiveFilters;
const factory DatabaseFilterMenuEvent.didReceiveFields(
List<FieldInfo> fields,
) = _DidReceiveFields;
const factory DatabaseFilterMenuEvent.toggleMenu() = _SetMenuVisibility;
}
@freezed
class DatabaseFilterMenuState with _$DatabaseFilterMenuState {
const factory DatabaseFilterMenuState({
required String viewId,
required List<FilterInfo> filters,
required List<FieldInfo> fields,
required List<FieldInfo> creatableFields,
required bool isVisible,
}) = _DatabaseFilterMenuState;
factory DatabaseFilterMenuState.initial(
String viewId,
List<FilterInfo> filterInfos,
List<FieldInfo> fields,
) =>
DatabaseFilterMenuState(
viewId: viewId,
filters: filterInfos,
fields: fields,
creatableFields: getCreatableFilter(fields),
isVisible: false,
);
}
List<FieldInfo> getCreatableFilter(List<FieldInfo> fieldInfos) {
final List<FieldInfo> creatableFields = List.from(fieldInfos);
creatableFields.retainWhere((element) => element.canCreateFilter);
return creatableFields;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/filter/number_filter_editor_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/domain/filter_listener.dart';
import 'package:appflowy/plugins/database/domain/filter_service.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/filter_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'number_filter_editor_bloc.freezed.dart';
class NumberFilterEditorBloc
extends Bloc<NumberFilterEditorEvent, NumberFilterEditorState> {
NumberFilterEditorBloc({required this.filterInfo})
: _filterBackendSvc = FilterBackendService(viewId: filterInfo.viewId),
_listener = FilterListener(
viewId: filterInfo.viewId,
filterId: filterInfo.filter.id,
),
super(NumberFilterEditorState.initial(filterInfo)) {
_dispatch();
_startListening();
}
final FilterInfo filterInfo;
final FilterBackendService _filterBackendSvc;
final FilterListener _listener;
void _dispatch() {
on<NumberFilterEditorEvent>(
(event, emit) async {
event.when(
didReceiveFilter: (filter) {
final filterInfo = state.filterInfo.copyWith(filter: filter);
emit(
state.copyWith(
filterInfo: filterInfo,
filter: filterInfo.numberFilter()!,
),
);
},
updateCondition: (NumberFilterConditionPB condition) {
_filterBackendSvc.insertNumberFilter(
filterId: filterInfo.filter.id,
fieldId: filterInfo.fieldInfo.id,
condition: condition,
content: state.filter.content,
);
},
updateContent: (content) {
_filterBackendSvc.insertNumberFilter(
filterId: filterInfo.filter.id,
fieldId: filterInfo.fieldInfo.id,
condition: state.filter.condition,
content: content,
);
},
delete: () {
_filterBackendSvc.deleteFilter(
fieldId: filterInfo.fieldInfo.id,
filterId: filterInfo.filter.id,
);
},
);
},
);
}
void _startListening() {
_listener.start(
onUpdated: (filter) {
if (!isClosed) {
add(NumberFilterEditorEvent.didReceiveFilter(filter));
}
},
);
}
@override
Future<void> close() async {
await _listener.stop();
return super.close();
}
}
@freezed
class NumberFilterEditorEvent with _$NumberFilterEditorEvent {
const factory NumberFilterEditorEvent.didReceiveFilter(FilterPB filter) =
_DidReceiveFilter;
const factory NumberFilterEditorEvent.updateCondition(
NumberFilterConditionPB condition,
) = _UpdateCondition;
const factory NumberFilterEditorEvent.updateContent(String content) =
_UpdateContent;
const factory NumberFilterEditorEvent.delete() = _Delete;
}
@freezed
class NumberFilterEditorState with _$NumberFilterEditorState {
const factory NumberFilterEditorState({
required FilterInfo filterInfo,
required NumberFilterPB filter,
}) = _NumberFilterEditorState;
factory NumberFilterEditorState.initial(FilterInfo filterInfo) {
return NumberFilterEditorState(
filterInfo: filterInfo,
filter: filterInfo.numberFilter()!,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/filter/checklist_filter_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/domain/filter_listener.dart';
import 'package:appflowy/plugins/database/domain/filter_service.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/filter_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/checklist_filter.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/util.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'checklist_filter_bloc.freezed.dart';
class ChecklistFilterEditorBloc
extends Bloc<ChecklistFilterEditorEvent, ChecklistFilterEditorState> {
ChecklistFilterEditorBloc({required this.filterInfo})
: _filterBackendSvc = FilterBackendService(viewId: filterInfo.viewId),
_listener = FilterListener(
viewId: filterInfo.viewId,
filterId: filterInfo.filter.id,
),
super(ChecklistFilterEditorState.initial(filterInfo)) {
_dispatch();
}
final FilterInfo filterInfo;
final FilterBackendService _filterBackendSvc;
final FilterListener _listener;
void _dispatch() {
on<ChecklistFilterEditorEvent>(
(event, emit) async {
await event.when(
initial: () async {
_startListening();
},
updateCondition: (ChecklistFilterConditionPB condition) {
_filterBackendSvc.insertChecklistFilter(
filterId: filterInfo.filter.id,
fieldId: filterInfo.fieldInfo.id,
condition: condition,
);
},
delete: () {
_filterBackendSvc.deleteFilter(
fieldId: filterInfo.fieldInfo.id,
filterId: filterInfo.filter.id,
);
},
didReceiveFilter: (FilterPB filter) {
final filterInfo = state.filterInfo.copyWith(filter: filter);
final checklistFilter = filterInfo.checklistFilter()!;
emit(
state.copyWith(
filterInfo: filterInfo,
filter: checklistFilter,
),
);
},
);
},
);
}
void _startListening() {
_listener.start(
onUpdated: (filter) {
if (!isClosed) {
add(ChecklistFilterEditorEvent.didReceiveFilter(filter));
}
},
);
}
@override
Future<void> close() async {
await _listener.stop();
return super.close();
}
}
@freezed
class ChecklistFilterEditorEvent with _$ChecklistFilterEditorEvent {
const factory ChecklistFilterEditorEvent.initial() = _Initial;
const factory ChecklistFilterEditorEvent.didReceiveFilter(FilterPB filter) =
_DidReceiveFilter;
const factory ChecklistFilterEditorEvent.updateCondition(
ChecklistFilterConditionPB condition,
) = _UpdateCondition;
const factory ChecklistFilterEditorEvent.delete() = _Delete;
}
@freezed
class ChecklistFilterEditorState with _$ChecklistFilterEditorState {
const factory ChecklistFilterEditorState({
required FilterInfo filterInfo,
required ChecklistFilterPB filter,
required String filterDesc,
}) = _GridFilterState;
factory ChecklistFilterEditorState.initial(FilterInfo filterInfo) {
return ChecklistFilterEditorState(
filterInfo: filterInfo,
filter: filterInfo.checklistFilter()!,
filterDesc: '',
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/filter/checkbox_filter_editor_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/domain/filter_listener.dart';
import 'package:appflowy/plugins/database/domain/filter_service.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/filter_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/checkbox_filter.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/util.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'checkbox_filter_editor_bloc.freezed.dart';
class CheckboxFilterEditorBloc
extends Bloc<CheckboxFilterEditorEvent, CheckboxFilterEditorState> {
CheckboxFilterEditorBloc({required this.filterInfo})
: _filterBackendSvc = FilterBackendService(viewId: filterInfo.viewId),
_listener = FilterListener(
viewId: filterInfo.viewId,
filterId: filterInfo.filter.id,
),
super(CheckboxFilterEditorState.initial(filterInfo)) {
_dispatch();
}
final FilterInfo filterInfo;
final FilterBackendService _filterBackendSvc;
final FilterListener _listener;
void _dispatch() {
on<CheckboxFilterEditorEvent>(
(event, emit) async {
await event.when(
initial: () async {
_startListening();
},
updateCondition: (CheckboxFilterConditionPB condition) {
_filterBackendSvc.insertCheckboxFilter(
filterId: filterInfo.filter.id,
fieldId: filterInfo.fieldInfo.id,
condition: condition,
);
},
delete: () {
_filterBackendSvc.deleteFilter(
fieldId: filterInfo.fieldInfo.id,
filterId: filterInfo.filter.id,
);
},
didReceiveFilter: (FilterPB filter) {
final filterInfo = state.filterInfo.copyWith(filter: filter);
final checkboxFilter = filterInfo.checkboxFilter()!;
emit(
state.copyWith(
filterInfo: filterInfo,
filter: checkboxFilter,
),
);
},
);
},
);
}
void _startListening() {
_listener.start(
onUpdated: (filter) {
if (!isClosed) {
add(CheckboxFilterEditorEvent.didReceiveFilter(filter));
}
},
);
}
@override
Future<void> close() async {
await _listener.stop();
return super.close();
}
}
@freezed
class CheckboxFilterEditorEvent with _$CheckboxFilterEditorEvent {
const factory CheckboxFilterEditorEvent.initial() = _Initial;
const factory CheckboxFilterEditorEvent.didReceiveFilter(FilterPB filter) =
_DidReceiveFilter;
const factory CheckboxFilterEditorEvent.updateCondition(
CheckboxFilterConditionPB condition,
) = _UpdateCondition;
const factory CheckboxFilterEditorEvent.delete() = _Delete;
}
@freezed
class CheckboxFilterEditorState with _$CheckboxFilterEditorState {
const factory CheckboxFilterEditorState({
required FilterInfo filterInfo,
required CheckboxFilterPB filter,
}) = _GridFilterState;
factory CheckboxFilterEditorState.initial(FilterInfo filterInfo) {
return CheckboxFilterEditorState(
filterInfo: filterInfo,
filter: filterInfo.checkboxFilter()!,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/filter/filter_create_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/domain/filter_service.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/checkbox_filter.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/checklist_filter.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/date_filter.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/number_filter.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_filter.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/text_filter.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pbserver.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'filter_create_bloc.freezed.dart';
class GridCreateFilterBloc
extends Bloc<GridCreateFilterEvent, GridCreateFilterState> {
GridCreateFilterBloc({required this.viewId, required this.fieldController})
: _filterBackendSvc = FilterBackendService(viewId: viewId),
super(GridCreateFilterState.initial(fieldController.fieldInfos)) {
_dispatch();
}
final String viewId;
final FilterBackendService _filterBackendSvc;
final FieldController fieldController;
void Function(List<FieldInfo>)? _onFieldFn;
void _dispatch() {
on<GridCreateFilterEvent>(
(event, emit) async {
event.when(
initial: () {
_startListening();
},
didReceiveFields: (List<FieldInfo> fields) {
emit(
state.copyWith(
allFields: fields,
creatableFields: _filterFields(fields, state.filterText),
),
);
},
didReceiveFilterText: (String text) {
emit(
state.copyWith(
filterText: text,
creatableFields: _filterFields(state.allFields, text),
),
);
},
createDefaultFilter: (FieldInfo field) {
emit(state.copyWith(didCreateFilter: true));
_createDefaultFilter(field);
},
);
},
);
}
List<FieldInfo> _filterFields(
List<FieldInfo> fields,
String filterText,
) {
final List<FieldInfo> allFields = List.from(fields);
final keyword = filterText.toLowerCase();
allFields.retainWhere((field) {
if (!field.canCreateFilter) {
return false;
}
if (filterText.isNotEmpty) {
return field.name.toLowerCase().contains(keyword);
}
return true;
});
return allFields;
}
void _startListening() {
_onFieldFn = (fields) {
fields.retainWhere((field) => field.canCreateFilter);
add(GridCreateFilterEvent.didReceiveFields(fields));
};
fieldController.addListener(onReceiveFields: _onFieldFn);
}
Future<FlowyResult<void, FlowyError>> _createDefaultFilter(
FieldInfo field,
) async {
final fieldId = field.id;
switch (field.fieldType) {
case FieldType.Checkbox:
return _filterBackendSvc.insertCheckboxFilter(
fieldId: fieldId,
condition: CheckboxFilterConditionPB.IsChecked,
);
case FieldType.DateTime:
case FieldType.LastEditedTime:
case FieldType.CreatedTime:
final timestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
return _filterBackendSvc.insertDateFilter(
fieldId: fieldId,
condition: DateFilterConditionPB.DateIs,
timestamp: timestamp,
fieldType: field.fieldType,
);
case FieldType.MultiSelect:
return _filterBackendSvc.insertSelectOptionFilter(
fieldId: fieldId,
condition: SelectOptionFilterConditionPB.OptionContains,
fieldType: FieldType.MultiSelect,
);
case FieldType.Checklist:
return _filterBackendSvc.insertChecklistFilter(
fieldId: fieldId,
condition: ChecklistFilterConditionPB.IsIncomplete,
);
case FieldType.Number:
return _filterBackendSvc.insertNumberFilter(
fieldId: fieldId,
condition: NumberFilterConditionPB.Equal,
);
case FieldType.RichText:
return _filterBackendSvc.insertTextFilter(
fieldId: fieldId,
condition: TextFilterConditionPB.TextContains,
content: '',
);
case FieldType.SingleSelect:
return _filterBackendSvc.insertSelectOptionFilter(
fieldId: fieldId,
condition: SelectOptionFilterConditionPB.OptionIs,
fieldType: FieldType.SingleSelect,
);
case FieldType.URL:
return _filterBackendSvc.insertURLFilter(
fieldId: fieldId,
condition: TextFilterConditionPB.TextContains,
);
default:
throw UnimplementedError();
}
}
@override
Future<void> close() async {
if (_onFieldFn != null) {
fieldController.removeListener(onFieldsListener: _onFieldFn);
_onFieldFn = null;
}
return super.close();
}
}
@freezed
class GridCreateFilterEvent with _$GridCreateFilterEvent {
const factory GridCreateFilterEvent.initial() = _Initial;
const factory GridCreateFilterEvent.didReceiveFields(List<FieldInfo> fields) =
_DidReceiveFields;
const factory GridCreateFilterEvent.createDefaultFilter(FieldInfo field) =
_CreateDefaultFilter;
const factory GridCreateFilterEvent.didReceiveFilterText(String text) =
_DidReceiveFilterText;
}
@freezed
class GridCreateFilterState with _$GridCreateFilterState {
const factory GridCreateFilterState({
required String filterText,
required List<FieldInfo> creatableFields,
required List<FieldInfo> allFields,
required bool didCreateFilter,
}) = _GridFilterState;
factory GridCreateFilterState.initial(List<FieldInfo> fields) {
return GridCreateFilterState(
filterText: "",
creatableFields: getCreatableFilter(fields),
allFields: fields,
didCreateFilter: false,
);
}
}
List<FieldInfo> getCreatableFilter(List<FieldInfo> fieldInfos) {
final List<FieldInfo> creatableFields = List.from(fieldInfos);
creatableFields.retainWhere((element) => element.canCreateFilter);
return creatableFields;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/filter/text_filter_editor_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/domain/filter_listener.dart';
import 'package:appflowy/plugins/database/domain/filter_service.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/filter_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'text_filter_editor_bloc.freezed.dart';
class TextFilterEditorBloc
extends Bloc<TextFilterEditorEvent, TextFilterEditorState> {
TextFilterEditorBloc({required this.filterInfo, required this.fieldType})
: _filterBackendSvc = FilterBackendService(viewId: filterInfo.viewId),
_listener = FilterListener(
viewId: filterInfo.viewId,
filterId: filterInfo.filter.id,
),
super(TextFilterEditorState.initial(filterInfo)) {
_dispatch();
}
final FilterInfo filterInfo;
final FieldType fieldType;
final FilterBackendService _filterBackendSvc;
final FilterListener _listener;
void _dispatch() {
on<TextFilterEditorEvent>(
(event, emit) async {
event.when(
initial: () {
_startListening();
},
updateCondition: (TextFilterConditionPB condition) {
fieldType == FieldType.RichText
? _filterBackendSvc.insertTextFilter(
filterId: filterInfo.filter.id,
fieldId: filterInfo.fieldInfo.id,
condition: condition,
content: state.filter.content,
)
: _filterBackendSvc.insertURLFilter(
filterId: filterInfo.filter.id,
fieldId: filterInfo.fieldInfo.id,
condition: condition,
content: state.filter.content,
);
},
updateContent: (String content) {
fieldType == FieldType.RichText
? _filterBackendSvc.insertTextFilter(
filterId: filterInfo.filter.id,
fieldId: filterInfo.fieldInfo.id,
condition: state.filter.condition,
content: content,
)
: _filterBackendSvc.insertURLFilter(
filterId: filterInfo.filter.id,
fieldId: filterInfo.fieldInfo.id,
condition: state.filter.condition,
content: content,
);
},
delete: () {
_filterBackendSvc.deleteFilter(
fieldId: filterInfo.fieldInfo.id,
filterId: filterInfo.filter.id,
);
},
didReceiveFilter: (FilterPB filter) {
final filterInfo = state.filterInfo.copyWith(filter: filter);
final textFilter = filterInfo.textFilter()!;
emit(
state.copyWith(
filterInfo: filterInfo,
filter: textFilter,
),
);
},
);
},
);
}
void _startListening() {
_listener.start(
onUpdated: (filter) {
if (!isClosed) {
add(TextFilterEditorEvent.didReceiveFilter(filter));
}
},
);
}
@override
Future<void> close() async {
await _listener.stop();
return super.close();
}
}
@freezed
class TextFilterEditorEvent with _$TextFilterEditorEvent {
const factory TextFilterEditorEvent.initial() = _Initial;
const factory TextFilterEditorEvent.didReceiveFilter(FilterPB filter) =
_DidReceiveFilter;
const factory TextFilterEditorEvent.updateCondition(
TextFilterConditionPB condition,
) = _UpdateCondition;
const factory TextFilterEditorEvent.updateContent(String content) =
_UpdateContent;
const factory TextFilterEditorEvent.delete() = _Delete;
}
@freezed
class TextFilterEditorState with _$TextFilterEditorState {
const factory TextFilterEditorState({
required FilterInfo filterInfo,
required TextFilterPB filter,
}) = _GridFilterState;
factory TextFilterEditorState.initial(FilterInfo filterInfo) {
return TextFilterEditorState(
filterInfo: filterInfo,
filter: filterInfo.textFilter()!,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/application/filter/select_option_filter_bloc.dart | import 'dart:async';
import 'package:appflowy/plugins/database/domain/filter_listener.dart';
import 'package:appflowy/plugins/database/domain/filter_service.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/choicechip/select_option/select_option_loader.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/filter_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/select_option_filter.pbserver.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/util.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'select_option_filter_bloc.freezed.dart';
class SelectOptionFilterEditorBloc
extends Bloc<SelectOptionFilterEditorEvent, SelectOptionFilterEditorState> {
SelectOptionFilterEditorBloc({
required this.filterInfo,
required this.delegate,
}) : _filterBackendSvc = FilterBackendService(viewId: filterInfo.viewId),
_listener = FilterListener(
viewId: filterInfo.viewId,
filterId: filterInfo.filter.id,
),
super(SelectOptionFilterEditorState.initial(filterInfo)) {
_dispatch();
}
final FilterInfo filterInfo;
final FilterBackendService _filterBackendSvc;
final FilterListener _listener;
final SelectOptionFilterDelegate delegate;
void _dispatch() {
on<SelectOptionFilterEditorEvent>(
(event, emit) async {
event.when(
initial: () {
_startListening();
_loadOptions();
},
updateCondition: (SelectOptionFilterConditionPB condition) {
_filterBackendSvc.insertSelectOptionFilter(
filterId: filterInfo.filter.id,
fieldId: filterInfo.fieldInfo.id,
condition: condition,
optionIds: state.filter.optionIds,
fieldType: state.filterInfo.fieldInfo.fieldType,
);
},
updateContent: (List<String> optionIds) {
_filterBackendSvc.insertSelectOptionFilter(
filterId: filterInfo.filter.id,
fieldId: filterInfo.fieldInfo.id,
condition: state.filter.condition,
optionIds: optionIds,
fieldType: state.filterInfo.fieldInfo.fieldType,
);
},
delete: () {
_filterBackendSvc.deleteFilter(
fieldId: filterInfo.fieldInfo.id,
filterId: filterInfo.filter.id,
);
},
didReceiveFilter: (FilterPB filter) {
final filterInfo = state.filterInfo.copyWith(filter: filter);
final selectOptionFilter = filterInfo.selectOptionFilter()!;
emit(
state.copyWith(
filterInfo: filterInfo,
filter: selectOptionFilter,
),
);
},
updateFilterDescription: (String desc) {
emit(state.copyWith(filterDesc: desc));
},
);
},
);
}
void _startListening() {
_listener.start(
onUpdated: (filter) {
if (!isClosed) {
add(SelectOptionFilterEditorEvent.didReceiveFilter(filter));
}
},
);
}
void _loadOptions() {
if (!isClosed) {
final options = delegate.loadOptions();
String filterDesc = '';
for (final option in options) {
if (state.filter.optionIds.contains(option.id)) {
filterDesc += "${option.name} ";
}
}
add(SelectOptionFilterEditorEvent.updateFilterDescription(filterDesc));
}
}
@override
Future<void> close() async {
await _listener.stop();
return super.close();
}
}
@freezed
class SelectOptionFilterEditorEvent with _$SelectOptionFilterEditorEvent {
const factory SelectOptionFilterEditorEvent.initial() = _Initial;
const factory SelectOptionFilterEditorEvent.didReceiveFilter(
FilterPB filter,
) = _DidReceiveFilter;
const factory SelectOptionFilterEditorEvent.updateCondition(
SelectOptionFilterConditionPB condition,
) = _UpdateCondition;
const factory SelectOptionFilterEditorEvent.updateContent(
List<String> optionIds,
) = _UpdateContent;
const factory SelectOptionFilterEditorEvent.updateFilterDescription(
String desc,
) = _UpdateDesc;
const factory SelectOptionFilterEditorEvent.delete() = _Delete;
}
@freezed
class SelectOptionFilterEditorState with _$SelectOptionFilterEditorState {
const factory SelectOptionFilterEditorState({
required FilterInfo filterInfo,
required SelectOptionFilterPB filter,
required String filterDesc,
}) = _GridFilterState;
factory SelectOptionFilterEditorState.initial(FilterInfo filterInfo) {
return SelectOptionFilterEditorState(
filterInfo: filterInfo,
filter: filterInfo.selectOptionFilter()!,
filterDesc: '',
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/mobile_grid_page.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/mobile/presentation/database/card/card_detail/mobile_card_detail_screen.dart';
import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy/plugins/database/grid/application/grid_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/shortcuts.dart';
import 'package:appflowy/plugins/database/tab_bar/tab_bar_view.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/action_navigation/action_navigation_bloc.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.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';
import 'package:go_router/go_router.dart';
import 'package:linked_scroll_controller/linked_scroll_controller.dart';
import 'grid_scroll.dart';
import 'layout/sizes.dart';
import 'widgets/header/mobile_grid_header.dart';
import 'widgets/mobile_fab.dart';
import 'widgets/row/mobile_row.dart';
class MobileGridTabBarBuilderImpl extends DatabaseTabBarItemBuilder {
@override
Widget content(
BuildContext context,
ViewPB view,
DatabaseController controller,
bool shrinkWrap,
String? initialRowId,
) {
return MobileGridPage(
key: _makeValueKey(controller),
view: view,
databaseController: controller,
initialRowId: initialRowId,
);
}
@override
Widget settingBar(BuildContext context, DatabaseController controller) =>
const SizedBox.shrink();
@override
Widget settingBarExtension(
BuildContext context,
DatabaseController controller,
) =>
const SizedBox.shrink();
ValueKey _makeValueKey(DatabaseController controller) {
return ValueKey(controller.viewId);
}
}
class MobileGridPage extends StatefulWidget {
const MobileGridPage({
super.key,
required this.view,
required this.databaseController,
this.onDeleted,
this.initialRowId,
});
final ViewPB view;
final DatabaseController databaseController;
final VoidCallback? onDeleted;
final String? initialRowId;
@override
State<MobileGridPage> createState() => _MobileGridPageState();
}
class _MobileGridPageState extends State<MobileGridPage> {
bool _didOpenInitialRow = false;
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<ActionNavigationBloc>.value(
value: getIt<ActionNavigationBloc>(),
),
BlocProvider<GridBloc>(
create: (context) => GridBloc(
view: widget.view,
databaseController: widget.databaseController,
)..add(const GridEvent.initial()),
),
],
child: BlocBuilder<GridBloc, GridState>(
builder: (context, state) {
return state.loadingState.map(
loading: (_) =>
const Center(child: CircularProgressIndicator.adaptive()),
finish: (result) {
_openRow(context, widget.initialRowId, true);
return result.successOrFail.fold(
(_) => GridShortcuts(child: GridPageContent(view: widget.view)),
(err) => FlowyErrorPage.message(
err.toString(),
howToFix: LocaleKeys.errorDialog_howToFixFallback.tr(),
),
);
},
idle: (_) => const SizedBox.shrink(),
);
},
),
);
}
void _openRow(
BuildContext context,
String? rowId, [
bool initialRow = false,
]) {
if (rowId != null && (!initialRow || (initialRow && !_didOpenInitialRow))) {
_didOpenInitialRow = initialRow;
WidgetsBinding.instance.addPostFrameCallback((_) {
context.push(
MobileRowDetailPage.routeName,
extra: {
MobileRowDetailPage.argRowId: rowId,
MobileRowDetailPage.argDatabaseController:
widget.databaseController,
},
);
});
}
}
}
class GridPageContent extends StatefulWidget {
const GridPageContent({
super.key,
required this.view,
});
final ViewPB view;
@override
State<GridPageContent> createState() => _GridPageContentState();
}
class _GridPageContentState extends State<GridPageContent> {
final _scrollController = GridScrollController(
scrollGroupController: LinkedScrollControllerGroup(),
);
late final ScrollController contentScrollController;
late final ScrollController reorderableController;
@override
void initState() {
super.initState();
contentScrollController = _scrollController.linkHorizontalController();
reorderableController = _scrollController.linkHorizontalController();
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocListener<GridBloc, GridState>(
listenWhen: (previous, current) =>
previous.createdRow != current.createdRow,
listener: (context, state) {
if (state.createdRow == null || !state.openRowDetail) {
return;
}
final bloc = context.read<GridBloc>();
context.push(
MobileRowDetailPage.routeName,
extra: {
MobileRowDetailPage.argRowId: state.createdRow!.id,
MobileRowDetailPage.argDatabaseController: bloc.databaseController,
},
);
bloc.add(const GridEvent.resetCreatedRow());
},
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_GridHeader(
contentScrollController: contentScrollController,
reorderableController: reorderableController,
),
_GridRows(
viewId: widget.view.id,
scrollController: _scrollController,
),
],
),
Positioned(
bottom: 16,
right: 16,
child: getGridFabs(context),
),
],
),
);
}
}
class _GridHeader extends StatelessWidget {
const _GridHeader({
required this.contentScrollController,
required this.reorderableController,
});
final ScrollController contentScrollController;
final ScrollController reorderableController;
@override
Widget build(BuildContext context) {
return BlocBuilder<GridBloc, GridState>(
builder: (context, state) {
return MobileGridHeader(
viewId: state.viewId,
contentScrollController: contentScrollController,
reorderableController: reorderableController,
);
},
);
}
}
class _GridRows extends StatelessWidget {
const _GridRows({
required this.viewId,
required this.scrollController,
});
final String viewId;
final GridScrollController scrollController;
@override
Widget build(BuildContext context) {
return BlocBuilder<GridBloc, GridState>(
buildWhen: (previous, current) => previous.fields != current.fields,
builder: (context, state) {
final double contentWidth = getMobileGridContentWidth(state.fields);
return Expanded(
child: _WrapScrollView(
scrollController: scrollController,
contentWidth: contentWidth,
child: BlocBuilder<GridBloc, GridState>(
buildWhen: (previous, current) => current.reason.maybeWhen(
reorderRows: () => true,
reorderSingleRow: (reorderRow, rowInfo) => true,
delete: (item) => true,
insert: (item) => true,
orElse: () => false,
),
builder: (context, state) {
final behavior = ScrollConfiguration.of(context).copyWith(
scrollbars: false,
physics: const ClampingScrollPhysics(),
);
return ScrollConfiguration(
behavior: behavior,
child: _renderList(context, state),
);
},
),
),
);
},
);
}
Widget _renderList(
BuildContext context,
GridState state,
) {
final children = state.rowInfos.mapIndexed((index, rowInfo) {
return ReorderableDelayedDragStartListener(
key: ValueKey(rowInfo.rowMeta.id),
index: index,
child: _renderRow(
context,
rowInfo.rowId,
isDraggable: state.reorderable,
index: index,
),
);
}).toList();
return ReorderableListView.builder(
scrollController: scrollController.verticalController,
buildDefaultDragHandles: false,
proxyDecorator: (child, index, animation) => Material(
color: Colors.transparent,
child: child,
),
onReorder: (fromIndex, newIndex) {
final toIndex = newIndex > fromIndex ? newIndex - 1 : newIndex;
if (fromIndex == toIndex) {
return;
}
context.read<GridBloc>().add(GridEvent.moveRow(fromIndex, toIndex));
},
itemCount: state.rowInfos.length,
itemBuilder: (context, index) => children[index],
footer: Padding(
padding: GridSize.footerContentInsets,
child: _AddRowButton(),
),
);
}
Widget _renderRow(
BuildContext context,
RowId rowId, {
int? index,
required bool isDraggable,
Animation<double>? animation,
}) {
final rowMeta = context
.read<GridBloc>()
.databaseController
.rowCache
.getRow(rowId)
?.rowMeta;
if (rowMeta == null) {
Log.warn('RowMeta is null for rowId: $rowId');
return const SizedBox.shrink();
}
final databaseController = context.read<GridBloc>().databaseController;
final child = MobileGridRow(
key: ValueKey(rowMeta.id),
rowId: rowId,
isDraggable: isDraggable,
databaseController: databaseController,
openDetailPage: (context) {
context.push(
MobileRowDetailPage.routeName,
extra: {
MobileRowDetailPage.argRowId: rowId,
MobileRowDetailPage.argDatabaseController: databaseController,
},
);
},
);
if (animation != null) {
return SizeTransition(
sizeFactor: animation,
child: child,
);
}
return child;
}
}
class _WrapScrollView extends StatelessWidget {
const _WrapScrollView({
required this.contentWidth,
required this.scrollController,
required this.child,
});
final GridScrollController scrollController;
final double contentWidth;
final Widget child;
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
controller: scrollController.horizontalController,
scrollDirection: Axis.horizontal,
child: SizedBox(
width: contentWidth,
child: child,
),
);
}
}
class _AddRowButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
final borderSide = BorderSide(
color: Theme.of(context).dividerColor,
);
const radius = BorderRadius.only(
bottomLeft: Radius.circular(24),
bottomRight: Radius.circular(24),
);
final decoration = BoxDecoration(
borderRadius: radius,
border: BorderDirectional(
start: borderSide,
end: borderSide,
bottom: borderSide,
),
);
return Container(
height: 54,
decoration: decoration,
child: FlowyButton(
text: FlowyText(
LocaleKeys.grid_row_newRow.tr(),
fontSize: 15,
color: Theme.of(context).hintColor,
),
margin: const EdgeInsets.symmetric(horizontal: 20.0),
radius: radius,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
onTap: () => context.read<GridBloc>().add(const GridEvent.createRow()),
leftIcon: FlowySvg(
FlowySvgs.add_s,
color: Theme.of(context).hintColor,
size: const Size.square(18),
),
leftIconSize: const Size.square(18),
),
);
}
}
double getMobileGridContentWidth(List<FieldInfo> fields) {
final visibleFields = fields.where(
(field) => field.visibility != FieldVisibility.AlwaysHidden,
);
return (visibleFields.length + 1) * 200 +
GridSize.horizontalHeaderPadding * 2;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/grid_scroll.dart | import 'package:flutter/material.dart';
import 'package:linked_scroll_controller/linked_scroll_controller.dart';
class GridScrollController {
GridScrollController({
required LinkedScrollControllerGroup scrollGroupController,
}) : _scrollGroupController = scrollGroupController,
verticalController = ScrollController(),
horizontalController = scrollGroupController.addAndGet();
final LinkedScrollControllerGroup _scrollGroupController;
final ScrollController verticalController;
final ScrollController horizontalController;
final List<ScrollController> _linkHorizontalControllers = [];
ScrollController linkHorizontalController() {
final controller = _scrollGroupController.addAndGet();
_linkHorizontalControllers.add(controller);
return controller;
}
void dispose() {
for (final controller in _linkHorizontalControllers) {
controller.dispose();
}
verticalController.dispose();
horizontalController.dispose();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/grid_page.dart | import 'package:flutter/material.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/application/row/row_service.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/calculations/calculations_row.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/toolbar/grid_setting_bar.dart';
import 'package:appflowy/plugins/database/tab_bar/desktop/setting_menu.dart';
import 'package:appflowy/plugins/database/widgets/cell/editable_cell_builder.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_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flowy_infra_ui/style_widget/scrolling/styled_scrollview.dart';
import 'package:flowy_infra_ui/widget/error_page.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:linked_scroll_controller/linked_scroll_controller.dart';
import '../../application/database_controller.dart';
import '../../application/row/row_controller.dart';
import '../../tab_bar/tab_bar_view.dart';
import '../../widgets/row/row_detail.dart';
import '../application/grid_bloc.dart';
import 'grid_scroll.dart';
import 'layout/layout.dart';
import 'layout/sizes.dart';
import 'widgets/footer/grid_footer.dart';
import 'widgets/header/grid_header.dart';
import 'widgets/row/row.dart';
import 'widgets/shortcuts.dart';
class ToggleExtensionNotifier extends ChangeNotifier {
bool _isToggled = false;
bool get isToggled => _isToggled;
void toggle() {
_isToggled = !_isToggled;
notifyListeners();
}
}
class DesktopGridTabBarBuilderImpl extends DatabaseTabBarItemBuilder {
final _toggleExtension = ToggleExtensionNotifier();
@override
Widget content(
BuildContext context,
ViewPB view,
DatabaseController controller,
bool shrinkWrap,
String? initialRowId,
) {
return GridPage(
key: _makeValueKey(controller),
view: view,
databaseController: controller,
initialRowId: initialRowId,
);
}
@override
Widget settingBar(BuildContext context, DatabaseController controller) {
return GridSettingBar(
key: _makeValueKey(controller),
controller: controller,
toggleExtension: _toggleExtension,
);
}
@override
Widget settingBarExtension(
BuildContext context,
DatabaseController controller,
) {
return DatabaseViewSettingExtension(
key: _makeValueKey(controller),
viewId: controller.viewId,
databaseController: controller,
toggleExtension: _toggleExtension,
);
}
@override
void dispose() {
_toggleExtension.dispose();
super.dispose();
}
ValueKey _makeValueKey(DatabaseController controller) {
return ValueKey(controller.viewId);
}
}
class GridPage extends StatefulWidget {
const GridPage({
super.key,
required this.view,
required this.databaseController,
this.onDeleted,
this.initialRowId,
});
final ViewPB view;
final DatabaseController databaseController;
final VoidCallback? onDeleted;
final String? initialRowId;
@override
State<GridPage> createState() => _GridPageState();
}
class _GridPageState extends State<GridPage> {
bool _didOpenInitialRow = false;
@override
Widget build(BuildContext context) {
return BlocProvider<GridBloc>(
create: (context) => GridBloc(
view: widget.view,
databaseController: widget.databaseController,
)..add(const GridEvent.initial()),
child: BlocListener<ActionNavigationBloc, ActionNavigationState>(
listener: (context, state) {
final action = state.action;
if (action?.type == ActionType.openRow &&
action?.objectId == widget.view.id) {
final rowId = action!.arguments?[ActionArgumentKeys.rowId];
if (rowId != null) {
// If Reminder in existing database is pressed
// then open the row
_openRow(context, rowId);
}
}
},
child: BlocConsumer<GridBloc, GridState>(
listener: (context, state) => state.loadingState.whenOrNull(
// If initial row id is defined, open row details overlay
finish: (_) {
if (widget.initialRowId != null && !_didOpenInitialRow) {
_didOpenInitialRow = true;
_openRow(context, widget.initialRowId!);
}
return;
},
),
builder: (context, state) => state.loadingState.map(
loading: (_) =>
const Center(child: CircularProgressIndicator.adaptive()),
finish: (result) => result.successOrFail.fold(
(_) => GridShortcuts(child: GridPageContent(view: widget.view)),
(err) => FlowyErrorPage.message(
err.toString(),
howToFix: LocaleKeys.errorDialog_howToFixFallback.tr(),
),
),
idle: (_) => const SizedBox.shrink(),
),
),
),
);
}
void _openRow(
BuildContext context,
String rowId,
) {
WidgetsBinding.instance.addPostFrameCallback((_) {
final gridBloc = context.read<GridBloc>();
final rowCache = gridBloc.getRowCache(rowId);
final rowMeta = rowCache.getRow(rowId)?.rowMeta;
if (rowMeta == null) {
return;
}
final rowController = RowController(
viewId: widget.view.id,
rowMeta: rowMeta,
rowCache: rowCache,
);
FlowyOverlay.show(
context: context,
builder: (_) => RowDetailPage(
databaseController: context.read<GridBloc>().databaseController,
rowController: rowController,
),
);
});
}
}
class GridPageContent extends StatefulWidget {
const GridPageContent({
super.key,
required this.view,
});
final ViewPB view;
@override
State<GridPageContent> createState() => _GridPageContentState();
}
class _GridPageContentState extends State<GridPageContent> {
final _scrollController = GridScrollController(
scrollGroupController: LinkedScrollControllerGroup(),
);
late final ScrollController headerScrollController;
@override
void initState() {
super.initState();
headerScrollController = _scrollController.linkHorizontalController();
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_GridHeader(headerScrollController: headerScrollController),
_GridRows(
viewId: widget.view.id,
scrollController: _scrollController,
),
],
);
}
}
class _GridHeader extends StatelessWidget {
const _GridHeader({required this.headerScrollController});
final ScrollController headerScrollController;
@override
Widget build(BuildContext context) {
return BlocBuilder<GridBloc, GridState>(
builder: (context, state) {
return GridHeaderSliverAdaptor(
viewId: state.viewId,
anchorScrollController: headerScrollController,
);
},
);
}
}
class _GridRows extends StatefulWidget {
const _GridRows({
required this.viewId,
required this.scrollController,
});
final String viewId;
final GridScrollController scrollController;
@override
State<_GridRows> createState() => _GridRowsState();
}
class _GridRowsState extends State<_GridRows> {
bool showFloatingCalculations = false;
@override
void initState() {
super.initState();
_evaluateFloatingCalculations();
}
void _evaluateFloatingCalculations() {
WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() {
// maxScrollExtent is 0.0 if scrolling is not possible
showFloatingCalculations = widget
.scrollController.verticalController.position.maxScrollExtent >
0;
});
});
}
@override
Widget build(BuildContext context) {
return BlocBuilder<GridBloc, GridState>(
buildWhen: (previous, current) => previous.fields != current.fields,
builder: (context, state) {
return Flexible(
child: _WrapScrollView(
scrollController: widget.scrollController,
contentWidth: GridLayout.headerWidth(state.fields),
child: BlocConsumer<GridBloc, GridState>(
listenWhen: (previous, current) =>
previous.rowCount != current.rowCount,
listener: (context, state) => _evaluateFloatingCalculations(),
builder: (context, state) {
return ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(
scrollbars: false,
),
child: _renderList(context, state),
);
},
),
),
);
},
);
}
Widget _renderList(
BuildContext context,
GridState state,
) {
final children = state.rowInfos.mapIndexed((index, rowInfo) {
return _renderRow(
context,
rowInfo.rowId,
isDraggable: state.reorderable,
index: index,
);
}).toList()
..add(const GridRowBottomBar(key: Key('grid_footer')));
if (showFloatingCalculations) {
children.add(
const SizedBox(
key: Key('calculations_bottom_padding'),
height: 36,
),
);
} else {
children.add(
GridCalculationsRow(
key: const Key('grid_calculations'),
viewId: widget.viewId,
),
);
}
children.add(const SizedBox(key: Key('footer_padding'), height: 10));
return Stack(
children: [
Positioned.fill(
child: ReorderableListView.builder(
/// This is a workaround related to
/// https://github.com/flutter/flutter/issues/25652
cacheExtent: 5000,
scrollController: widget.scrollController.verticalController,
physics: const ClampingScrollPhysics(),
buildDefaultDragHandles: false,
proxyDecorator: (child, index, animation) => Material(
color: Colors.white.withOpacity(.1),
child: Opacity(opacity: .5, child: child),
),
onReorder: (fromIndex, newIndex) {
final toIndex = newIndex > fromIndex ? newIndex - 1 : newIndex;
if (fromIndex != toIndex) {
context
.read<GridBloc>()
.add(GridEvent.moveRow(fromIndex, toIndex));
}
},
itemCount: children.length,
itemBuilder: (context, index) => children[index],
),
),
if (showFloatingCalculations) ...[
_PositionedCalculationsRow(viewId: widget.viewId),
],
],
);
}
Widget _renderRow(
BuildContext context,
RowId rowId, {
int? index,
required bool isDraggable,
Animation<double>? animation,
}) {
final databaseController = context.read<GridBloc>().databaseController;
final DatabaseController(:viewId, :rowCache) = databaseController;
final rowMeta = rowCache.getRow(rowId)?.rowMeta;
/// Return placeholder widget if the rowMeta is null.
if (rowMeta == null) {
Log.warn('RowMeta is null for rowId: $rowId');
return const SizedBox.shrink();
}
final rowController = RowController(
viewId: viewId,
rowMeta: rowMeta,
rowCache: rowCache,
);
final child = GridRow(
key: ValueKey(rowMeta.id),
fieldController: databaseController.fieldController,
rowId: rowId,
viewId: viewId,
index: index,
isDraggable: isDraggable,
rowController: rowController,
cellBuilder: EditableCellBuilder(databaseController: databaseController),
openDetailPage: (context, cellBuilder) {
FlowyOverlay.show(
context: context,
builder: (_) => RowDetailPage(
rowController: rowController,
databaseController: databaseController,
),
);
},
);
if (animation != null) {
return SizeTransition(sizeFactor: animation, child: child);
}
return child;
}
}
class _WrapScrollView extends StatelessWidget {
const _WrapScrollView({
required this.contentWidth,
required this.scrollController,
required this.child,
});
final GridScrollController scrollController;
final double contentWidth;
final Widget child;
@override
Widget build(BuildContext context) {
return ScrollbarListStack(
includeInsets: false,
axis: Axis.vertical,
controller: scrollController.verticalController,
barSize: GridSize.scrollBarSize,
autoHideScrollbar: false,
child: StyledSingleChildScrollView(
autoHideScrollbar: false,
includeInsets: false,
controller: scrollController.horizontalController,
axis: Axis.horizontal,
child: SizedBox(
width: contentWidth,
child: child,
),
),
);
}
}
/// This Widget is used to show the Calculations Row at the bottom of the Grids ScrollView
/// when the ScrollView is scrollable.
///
class _PositionedCalculationsRow extends StatefulWidget {
const _PositionedCalculationsRow({
required this.viewId,
});
final String viewId;
@override
State<_PositionedCalculationsRow> createState() =>
_PositionedCalculationsRowState();
}
class _PositionedCalculationsRowState
extends State<_PositionedCalculationsRow> {
@override
Widget build(BuildContext context) {
return Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
margin: EdgeInsets.only(left: GridSize.horizontalHeaderPadding),
padding: const EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
color: Theme.of(context).canvasColor,
border: Border(
top: BorderSide(color: Theme.of(context).dividerColor),
),
),
child: SizedBox(
height: 36,
width: double.infinity,
child: GridCalculationsRow(
key: const Key('floating_grid_calculations'),
viewId: widget.viewId,
includeDefaultInsets: false,
),
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/shortcuts.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class GridShortcuts extends StatelessWidget {
const GridShortcuts({required this.child, super.key});
final Widget child;
@override
Widget build(BuildContext context) {
return Shortcuts(
shortcuts: bindKeys([]),
child: Actions(
dispatcher: LoggingActionDispatcher(),
actions: const {},
child: child,
),
);
}
}
Map<ShortcutActivator, Intent> bindKeys(List<LogicalKeyboardKey> keys) {
return {for (final key in keys) LogicalKeySet(key): KeyboardKeyIdent(key)};
}
Map<Type, Action<Intent>> bindActions() {
return {
KeyboardKeyIdent: KeyboardBindingAction(),
};
}
class KeyboardKeyIdent extends Intent {
const KeyboardKeyIdent(this.key);
final KeyboardKey key;
}
class KeyboardBindingAction extends Action<KeyboardKeyIdent> {
KeyboardBindingAction();
@override
void invoke(covariant KeyboardKeyIdent intent) {
// print(intent);
}
}
class LoggingActionDispatcher extends ActionDispatcher {
@override
Object? invokeAction(
covariant Action<Intent> action,
covariant Intent intent, [
BuildContext? context,
]) {
// print('Action invoked: $action($intent) from $context');
super.invokeAction(action, intent, context);
return null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/mobile_fab.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/mobile/presentation/database/card/card_detail/mobile_card_detail_screen.dart';
import 'package:appflowy/plugins/database/grid/application/grid_bloc.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
Widget getGridFabs(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
MobileGridFab(
backgroundColor: Theme.of(context).colorScheme.surface,
foregroundColor: Theme.of(context).primaryColor,
onTap: () {
final bloc = context.read<GridBloc>();
if (bloc.state.rowInfos.isNotEmpty) {
context.push(
MobileRowDetailPage.routeName,
extra: {
MobileRowDetailPage.argRowId: bloc.state.rowInfos.first.rowId,
MobileRowDetailPage.argDatabaseController:
bloc.databaseController,
},
);
}
},
boxShadow: const BoxShadow(
offset: Offset(0, 8),
color: Color(0x145D7D8B),
blurRadius: 20,
),
icon: FlowySvgs.properties_s,
iconSize: const Size.square(24),
),
const HSpace(16),
MobileGridFab(
backgroundColor: Theme.of(context).primaryColor,
foregroundColor: Colors.white,
onTap: () {
context
.read<GridBloc>()
.add(const GridEvent.createRow(openRowDetail: true));
},
overlayColor: const MaterialStatePropertyAll<Color>(Color(0xFF009FD1)),
boxShadow: const BoxShadow(
offset: Offset(0, 8),
color: Color(0x6612BFEF),
blurRadius: 18,
spreadRadius: -5,
),
icon: FlowySvgs.add_s,
iconSize: const Size.square(24),
),
],
);
}
class MobileGridFab extends StatelessWidget {
const MobileGridFab({
super.key,
required this.backgroundColor,
required this.foregroundColor,
required this.boxShadow,
required this.onTap,
required this.icon,
required this.iconSize,
this.overlayColor,
});
final Color backgroundColor;
final Color foregroundColor;
final BoxShadow boxShadow;
final VoidCallback onTap;
final FlowySvgData icon;
final Size iconSize;
final MaterialStateProperty<Color?>? overlayColor;
@override
Widget build(BuildContext context) {
final radius = BorderRadius.circular(20);
return DecoratedBox(
decoration: BoxDecoration(
color: backgroundColor,
border: const Border.fromBorderSide(
BorderSide(width: 0.5, color: Color(0xFFE4EDF0)),
),
borderRadius: radius,
boxShadow: [boxShadow],
),
child: Material(
borderOnForeground: false,
color: Colors.transparent,
borderRadius: radius,
child: InkWell(
borderRadius: radius,
overlayColor: overlayColor,
onTap: onTap,
child: SizedBox.square(
dimension: 56,
child: Center(
child: FlowySvg(
icon,
color: foregroundColor,
size: iconSize,
),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/sort/order_panel.dart | import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/sort/sort_editor.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pbenum.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flutter/material.dart';
class OrderPanel extends StatelessWidget {
const OrderPanel({required this.onCondition, super.key});
final Function(SortConditionPB) onCondition;
@override
Widget build(BuildContext context) {
final List<Widget> children = SortConditionPB.values.map((condition) {
return OrderPannelItem(
condition: condition,
onCondition: onCondition,
);
}).toList();
return ConstrainedBox(
constraints: const BoxConstraints(minWidth: 160),
child: IntrinsicWidth(
child: IntrinsicHeight(
child: Column(
children: children,
),
),
),
);
}
}
class OrderPannelItem extends StatelessWidget {
const OrderPannelItem({
super.key,
required this.condition,
required this.onCondition,
});
final SortConditionPB condition;
final Function(SortConditionPB) onCondition;
@override
Widget build(BuildContext context) {
return SizedBox(
height: GridSize.popoverItemHeight,
child: FlowyButton(
text: FlowyText.medium(condition.title),
onTap: () => onCondition(condition),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/sort/sort_menu.dart | import 'dart:math' as math;
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/grid/application/sort/sort_editor_bloc.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';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:easy_localization/easy_localization.dart';
import 'sort_choice_button.dart';
import 'sort_editor.dart';
import 'sort_info.dart';
class SortMenu extends StatelessWidget {
const SortMenu({
super.key,
required this.fieldController,
});
final FieldController fieldController;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => SortEditorBloc(
viewId: fieldController.viewId,
fieldController: fieldController,
),
child: BlocBuilder<SortEditorBloc, SortEditorState>(
builder: (context, state) {
if (state.sortInfos.isEmpty) {
return const SizedBox.shrink();
}
return AppFlowyPopover(
controller: PopoverController(),
constraints: BoxConstraints.loose(const Size(320, 200)),
direction: PopoverDirection.bottomWithLeftAligned,
offset: const Offset(0, 5),
margin: const EdgeInsets.fromLTRB(6.0, 0.0, 6.0, 6.0),
popupBuilder: (BuildContext popoverContext) {
return BlocProvider.value(
value: context.read<SortEditorBloc>(),
child: const SortEditor(),
);
},
child: SortChoiceChip(sortInfos: state.sortInfos),
);
},
),
);
}
}
class SortChoiceChip extends StatelessWidget {
const SortChoiceChip({
super.key,
required this.sortInfos,
this.onTap,
});
final List<SortInfo> sortInfos;
final VoidCallback? onTap;
@override
Widget build(BuildContext context) {
final arrow = Transform.rotate(
angle: -math.pi / 2,
child: FlowySvg(
FlowySvgs.arrow_left_s,
color: Theme.of(context).iconTheme.color,
),
);
final text = LocaleKeys.grid_settings_sort.tr();
final leftIcon = FlowySvg(
FlowySvgs.sort_ascending_s,
color: Theme.of(context).iconTheme.color,
);
return SizedBox(
height: 28,
child: SortChoiceButton(
text: text,
leftIcon: leftIcon,
rightIcon: arrow,
onTap: onTap,
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/sort/sort_info.dart | import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pb.dart';
class SortInfo {
SortInfo({required this.sortPB, required this.fieldInfo});
final SortPB sortPB;
final FieldInfo fieldInfo;
String get sortId => sortPB.id;
String get fieldId => sortPB.fieldId;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/sort/sort_editor.dart | import 'dart:io';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/grid/application/sort/sort_editor_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/sort_entities.pbenum.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'create_sort_list.dart';
import 'order_panel.dart';
import 'sort_choice_button.dart';
import 'sort_info.dart';
class SortEditor extends StatefulWidget {
const SortEditor({super.key});
@override
State<SortEditor> createState() => _SortEditorState();
}
class _SortEditorState extends State<SortEditor> {
final popoverMutex = PopoverMutex();
@override
Widget build(BuildContext context) {
return BlocBuilder<SortEditorBloc, SortEditorState>(
builder: (context, state) {
final sortInfos = state.sortInfos;
return ReorderableListView.builder(
onReorder: (oldIndex, newIndex) => context
.read<SortEditorBloc>()
.add(SortEditorEvent.reorderSort(oldIndex, newIndex)),
itemCount: state.sortInfos.length,
itemBuilder: (context, index) => DatabaseSortItem(
key: ValueKey(sortInfos[index].sortId),
index: index,
sortInfo: sortInfos[index],
popoverMutex: popoverMutex,
),
proxyDecorator: (child, index, animation) => Material(
color: Colors.transparent,
child: Stack(
children: [
BlocProvider.value(
value: context.read<SortEditorBloc>(),
child: child,
),
MouseRegion(
cursor: Platform.isWindows
? SystemMouseCursors.click
: SystemMouseCursors.grabbing,
child: const SizedBox.expand(),
),
],
),
),
shrinkWrap: true,
buildDefaultDragHandles: false,
footer: Row(
children: [
Flexible(
child: DatabaseAddSortButton(
disable: state.creatableFields.isEmpty,
popoverMutex: popoverMutex,
),
),
const HSpace(6),
Flexible(
child: DeleteAllSortsButton(
popoverMutex: popoverMutex,
),
),
],
),
);
},
);
}
}
class DatabaseSortItem extends StatelessWidget {
const DatabaseSortItem({
super.key,
required this.index,
required this.popoverMutex,
required this.sortInfo,
});
final int index;
final PopoverMutex popoverMutex;
final SortInfo sortInfo;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 6),
color: Theme.of(context).cardColor,
child: Row(
children: [
ReorderableDragStartListener(
index: index,
child: MouseRegion(
cursor: Platform.isWindows
? SystemMouseCursors.click
: SystemMouseCursors.grab,
child: SizedBox(
width: 14 + 12,
height: 14,
child: FlowySvg(
FlowySvgs.drag_element_s,
size: const Size.square(14),
color: Theme.of(context).iconTheme.color,
),
),
),
),
Flexible(
fit: FlexFit.tight,
child: SizedBox(
height: 26,
child: SortChoiceButton(
text: sortInfo.fieldInfo.name,
editable: false,
),
),
),
const HSpace(6),
Flexible(
fit: FlexFit.tight,
child: SizedBox(
height: 26,
child: SortConditionButton(
sortInfo: sortInfo,
popoverMutex: popoverMutex,
),
),
),
const HSpace(6),
FlowyIconButton(
width: 26,
onPressed: () {
context
.read<SortEditorBloc>()
.add(SortEditorEvent.deleteSort(sortInfo));
PopoverContainer.of(context).close();
},
hoverColor: AFThemeExtension.of(context).lightGreyHover,
icon: FlowySvg(
FlowySvgs.trash_m,
color: Theme.of(context).iconTheme.color,
size: const Size.square(16),
),
),
],
),
);
}
}
extension SortConditionExtension on SortConditionPB {
String get title {
return switch (this) {
SortConditionPB.Ascending => LocaleKeys.grid_sort_ascending.tr(),
SortConditionPB.Descending => LocaleKeys.grid_sort_descending.tr(),
_ => throw UnimplementedError(),
};
}
}
class DatabaseAddSortButton extends StatefulWidget {
const DatabaseAddSortButton({
super.key,
required this.disable,
required this.popoverMutex,
});
final bool disable;
final PopoverMutex popoverMutex;
@override
State<DatabaseAddSortButton> createState() => _DatabaseAddSortButtonState();
}
class _DatabaseAddSortButtonState extends State<DatabaseAddSortButton> {
final _popoverController = PopoverController();
@override
Widget build(BuildContext context) {
return AppFlowyPopover(
controller: _popoverController,
mutex: widget.popoverMutex,
direction: PopoverDirection.bottomWithLeftAligned,
constraints: BoxConstraints.loose(const Size(200, 300)),
offset: const Offset(-6, 8),
triggerActions: PopoverTriggerFlags.none,
asBarrier: true,
popupBuilder: (popoverContext) {
return BlocProvider.value(
value: context.read<SortEditorBloc>(),
child: CreateDatabaseViewSortList(
onTap: () => _popoverController.close(),
),
);
},
onClose: () => context
.read<SortEditorBloc>()
.add(const SortEditorEvent.updateCreateSortFilter("")),
child: SizedBox(
height: GridSize.popoverItemHeight,
child: FlowyButton(
hoverColor: AFThemeExtension.of(context).greyHover,
disable: widget.disable,
text: FlowyText.medium(LocaleKeys.grid_sort_addSort.tr()),
onTap: () => _popoverController.show(),
leftIcon: const FlowySvg(FlowySvgs.add_s),
),
),
);
}
}
class DeleteAllSortsButton extends StatelessWidget {
const DeleteAllSortsButton({super.key, required this.popoverMutex});
final PopoverMutex popoverMutex;
@override
Widget build(BuildContext context) {
return BlocBuilder<SortEditorBloc, SortEditorState>(
builder: (context, state) {
return SizedBox(
height: GridSize.popoverItemHeight,
child: FlowyButton(
text: FlowyText.medium(LocaleKeys.grid_sort_deleteAllSorts.tr()),
onTap: () {
context
.read<SortEditorBloc>()
.add(const SortEditorEvent.deleteAllSorts());
PopoverContainer.of(context).close();
},
leftIcon: const FlowySvg(FlowySvgs.delete_s),
),
);
},
);
}
}
class SortConditionButton extends StatefulWidget {
const SortConditionButton({
super.key,
required this.popoverMutex,
required this.sortInfo,
});
final PopoverMutex popoverMutex;
final SortInfo sortInfo;
@override
State<SortConditionButton> createState() => _SortConditionButtonState();
}
class _SortConditionButtonState extends State<SortConditionButton> {
final PopoverController popoverController = PopoverController();
@override
Widget build(BuildContext context) {
return AppFlowyPopover(
controller: popoverController,
mutex: widget.popoverMutex,
constraints: BoxConstraints.loose(const Size(340, 200)),
direction: PopoverDirection.bottomWithLeftAligned,
triggerActions: PopoverTriggerFlags.none,
popupBuilder: (BuildContext popoverContext) {
return OrderPanel(
onCondition: (condition) {
context.read<SortEditorBloc>().add(
SortEditorEvent.editSort(
sortId: widget.sortInfo.sortId,
condition: condition,
),
);
popoverController.close();
},
);
},
child: SortChoiceButton(
text: widget.sortInfo.sortPB.condition.title,
rightIcon: FlowySvg(
FlowySvgs.arrow_down_s,
color: Theme.of(context).iconTheme.color,
),
onTap: () => popoverController.show(),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/sort/create_sort_list.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/grid/application/sort/sort_editor_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:appflowy/util/field_type_extension.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flowy_infra_ui/style_widget/scrolling/styled_list.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flowy_infra_ui/style_widget/text_field.dart';
import 'package:flowy_infra_ui/widget/spacing.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class CreateDatabaseViewSortList extends StatelessWidget {
const CreateDatabaseViewSortList({
super.key,
required this.onTap,
});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return BlocBuilder<SortEditorBloc, SortEditorState>(
builder: (context, state) {
final filter = state.filter.toLowerCase();
final cells = state.creatableFields
.where((field) => field.field.name.toLowerCase().contains(filter))
.map((fieldInfo) {
return GridSortPropertyCell(
fieldInfo: fieldInfo,
onTap: () {
context
.read<SortEditorBloc>()
.add(SortEditorEvent.createSort(fieldId: fieldInfo.id));
onTap.call();
},
);
}).toList();
final List<Widget> slivers = [
SliverPersistentHeader(
pinned: true,
delegate: _SortTextFieldDelegate(),
),
SliverToBoxAdapter(
child: ListView.separated(
shrinkWrap: true,
itemCount: cells.length,
itemBuilder: (_, index) => cells[index],
separatorBuilder: (_, __) =>
VSpace(GridSize.typeOptionSeparatorHeight),
),
),
];
return CustomScrollView(
shrinkWrap: true,
slivers: slivers,
physics: StyledScrollPhysics(),
);
},
);
}
}
class _SortTextFieldDelegate extends SliverPersistentHeaderDelegate {
_SortTextFieldDelegate();
double fixHeight = 36;
@override
Widget build(
BuildContext context,
double shrinkOffset,
bool overlapsContent,
) {
return Container(
padding: const EdgeInsets.only(bottom: 4),
color: Theme.of(context).cardColor,
height: fixHeight,
child: FlowyTextField(
hintText: LocaleKeys.grid_settings_sortBy.tr(),
onChanged: (text) {
context
.read<SortEditorBloc>()
.add(SortEditorEvent.updateCreateSortFilter(text));
},
),
);
}
@override
double get maxExtent => fixHeight;
@override
double get minExtent => fixHeight;
@override
bool shouldRebuild(covariant oldDelegate) => false;
}
class GridSortPropertyCell extends StatelessWidget {
const GridSortPropertyCell({
super.key,
required this.fieldInfo,
required this.onTap,
});
final FieldInfo fieldInfo;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return SizedBox(
height: GridSize.popoverItemHeight,
child: FlowyButton(
hoverColor: AFThemeExtension.of(context).lightGreyHover,
text: FlowyText.medium(
fieldInfo.name,
color: AFThemeExtension.of(context).textColor,
),
onTap: onTap,
leftIcon: FlowySvg(
fieldInfo.fieldType.svgData,
color: Theme.of(context).iconTheme.color,
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/sort/sort_choice_button.dart | import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/style_widget/button.dart';
import 'package:flowy_infra_ui/style_widget/text.dart';
import 'package:flutter/material.dart';
class SortChoiceButton extends StatelessWidget {
const SortChoiceButton({
super.key,
required this.text,
this.onTap,
this.radius = const Radius.circular(14),
this.leftIcon,
this.rightIcon,
this.editable = true,
});
final String text;
final VoidCallback? onTap;
final Radius radius;
final Widget? leftIcon;
final Widget? rightIcon;
final bool editable;
@override
Widget build(BuildContext context) {
return FlowyButton(
decoration: BoxDecoration(
color: Colors.transparent,
border: Border.fromBorderSide(
BorderSide(color: Theme.of(context).dividerColor),
),
borderRadius: BorderRadius.all(radius),
),
useIntrinsicWidth: true,
text: FlowyText(
text,
color: AFThemeExtension.of(context).textColor,
overflow: TextOverflow.ellipsis,
),
margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
radius: BorderRadius.all(radius),
leftIcon: leftIcon,
rightIcon: rightIcon,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
onTap: onTap,
disable: !editable,
disableOpacity: 1.0,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/header/mobile_grid_header.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/database/field/mobile_field_bottom_sheets.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/grid/application/grid_bloc.dart';
import 'package:appflowy/plugins/database/grid/application/grid_header_bloc.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../layout/sizes.dart';
import '../../mobile_grid_page.dart';
import 'mobile_field_button.dart';
const double _kGridHeaderHeight = 50.0;
class MobileGridHeader extends StatefulWidget {
const MobileGridHeader({
super.key,
required this.viewId,
required this.contentScrollController,
required this.reorderableController,
});
final String viewId;
final ScrollController contentScrollController;
final ScrollController reorderableController;
@override
State<MobileGridHeader> createState() => _MobileGridHeaderState();
}
class _MobileGridHeaderState extends State<MobileGridHeader> {
@override
Widget build(BuildContext context) {
final fieldController =
context.read<GridBloc>().databaseController.fieldController;
return BlocProvider(
create: (context) {
return GridHeaderBloc(
viewId: widget.viewId,
fieldController: fieldController,
)..add(const GridHeaderEvent.initial());
},
child: Stack(
children: [
BlocBuilder<GridHeaderBloc, GridHeaderState>(
builder: (context, state) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
controller: widget.contentScrollController,
child: Stack(
children: [
Positioned(
top: 0,
left: GridSize.horizontalHeaderPadding + 24,
right: GridSize.horizontalHeaderPadding + 24,
child: _divider(),
),
Positioned(
bottom: 0,
left: GridSize.horizontalHeaderPadding,
right: GridSize.horizontalHeaderPadding,
child: _divider(),
),
SizedBox(
height: _kGridHeaderHeight,
width: getMobileGridContentWidth(state.fields),
),
],
),
);
},
),
SizedBox(
height: _kGridHeaderHeight,
child: _GridHeader(
viewId: widget.viewId,
fieldController: fieldController,
scrollController: widget.reorderableController,
),
),
],
),
);
}
Widget _divider() {
return Divider(
height: 1,
thickness: 1,
color: Theme.of(context).dividerColor,
);
}
}
class _GridHeader extends StatefulWidget {
const _GridHeader({
required this.viewId,
required this.fieldController,
required this.scrollController,
});
final String viewId;
final FieldController fieldController;
final ScrollController scrollController;
@override
State<_GridHeader> createState() => _GridHeaderState();
}
class _GridHeaderState extends State<_GridHeader> {
@override
Widget build(BuildContext context) {
return BlocBuilder<GridHeaderBloc, GridHeaderState>(
builder: (context, state) {
final fields = [...state.fields];
FieldInfo? firstField;
if (fields.isNotEmpty) {
firstField = fields.removeAt(0);
}
final cells = fields
.mapIndexed(
(index, fieldInfo) => MobileFieldButton(
key: ValueKey(fieldInfo.id),
index: index,
viewId: widget.viewId,
fieldController: widget.fieldController,
fieldInfo: fieldInfo,
),
)
.toList();
return ReorderableListView.builder(
scrollController: widget.scrollController,
shrinkWrap: true,
scrollDirection: Axis.horizontal,
proxyDecorator: (child, index, anim) => Material(
color: Colors.transparent,
child: child,
),
padding: EdgeInsets.symmetric(
horizontal: GridSize.horizontalHeaderPadding,
),
header: firstField != null
? MobileFieldButton.first(
viewId: widget.viewId,
fieldController: widget.fieldController,
fieldInfo: firstField,
)
: null,
footer: CreateFieldButton(
viewId: widget.viewId,
onFieldCreated: (fieldId) => context
.read<GridHeaderBloc>()
.add(GridHeaderEvent.startEditingNewField(fieldId)),
),
onReorder: (int oldIndex, int newIndex) {
if (oldIndex < newIndex) {
newIndex--;
}
oldIndex++;
newIndex++;
context
.read<GridHeaderBloc>()
.add(GridHeaderEvent.moveField(oldIndex, newIndex));
},
itemCount: cells.length,
itemBuilder: (context, index) => cells[index],
);
},
);
}
}
class CreateFieldButton extends StatefulWidget {
const CreateFieldButton({
super.key,
required this.viewId,
required this.onFieldCreated,
});
final String viewId;
final void Function(String fieldId) onFieldCreated;
@override
State<CreateFieldButton> createState() => _CreateFieldButtonState();
}
class _CreateFieldButtonState extends State<CreateFieldButton> {
@override
Widget build(BuildContext context) {
return Container(
width: 200,
decoration: _getDecoration(context),
child: FlowyButton(
margin: const EdgeInsets.symmetric(vertical: 14, horizontal: 12),
radius: const BorderRadius.only(topRight: Radius.circular(24)),
text: FlowyText(
LocaleKeys.grid_field_newProperty.tr(),
fontSize: 15,
overflow: TextOverflow.ellipsis,
color: Theme.of(context).hintColor,
),
hoverColor: AFThemeExtension.of(context).greyHover,
onTap: () => mobileCreateFieldWorkflow(context, widget.viewId),
leftIconSize: const Size.square(18),
leftIcon: FlowySvg(
FlowySvgs.add_s,
size: const Size.square(18),
color: Theme.of(context).hintColor,
),
),
);
}
BoxDecoration? _getDecoration(BuildContext context) {
final borderSide = BorderSide(
color: Theme.of(context).dividerColor,
);
return BoxDecoration(
borderRadius: const BorderRadiusDirectional.only(
topEnd: Radius.circular(24),
),
border: BorderDirectional(
top: borderSide,
end: borderSide,
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/header/grid_header.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/domain/field_service.dart';
import 'package:appflowy/plugins/database/grid/application/grid_bloc.dart';
import 'package:appflowy/plugins/database/grid/application/grid_header_bloc.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_editor/appflowy_editor.dart' hide Log;
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:reorderables/reorderables.dart';
import '../../layout/sizes.dart';
import 'desktop_field_cell.dart';
class GridHeaderSliverAdaptor extends StatefulWidget {
const GridHeaderSliverAdaptor({
super.key,
required this.viewId,
required this.anchorScrollController,
});
final String viewId;
final ScrollController anchorScrollController;
@override
State<GridHeaderSliverAdaptor> createState() =>
_GridHeaderSliverAdaptorState();
}
class _GridHeaderSliverAdaptorState extends State<GridHeaderSliverAdaptor> {
@override
Widget build(BuildContext context) {
final fieldController =
context.read<GridBloc>().databaseController.fieldController;
return BlocProvider(
create: (context) {
return GridHeaderBloc(
viewId: widget.viewId,
fieldController: fieldController,
)..add(const GridHeaderEvent.initial());
},
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
controller: widget.anchorScrollController,
child: _GridHeader(
viewId: widget.viewId,
fieldController: fieldController,
),
),
);
}
}
class _GridHeader extends StatefulWidget {
const _GridHeader({required this.viewId, required this.fieldController});
final String viewId;
final FieldController fieldController;
@override
State<_GridHeader> createState() => _GridHeaderState();
}
class _GridHeaderState extends State<_GridHeader> {
final Map<String, ValueKey<String>> _gridMap = {};
final _scrollController = ScrollController();
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocBuilder<GridHeaderBloc, GridHeaderState>(
builder: (context, state) {
final cells = state.fields
.map(
(fieldInfo) => GridFieldCell(
key: _getKeyById(fieldInfo.id),
viewId: widget.viewId,
fieldInfo: fieldInfo,
fieldController: widget.fieldController,
onTap: () => context
.read<GridHeaderBloc>()
.add(GridHeaderEvent.startEditingField(fieldInfo.id)),
onFieldInsertedOnEitherSide: (fieldId) => context
.read<GridHeaderBloc>()
.add(GridHeaderEvent.startEditingNewField(fieldId)),
onEditorOpened: () => context
.read<GridHeaderBloc>()
.add(const GridHeaderEvent.endEditingField()),
isEditing: state.editingFieldId == fieldInfo.id,
isNew: state.newFieldId == fieldInfo.id,
),
)
.toList();
return RepaintBoundary(
child: ReorderableRow(
scrollController: _scrollController,
buildDraggableFeedback: (context, constraints, child) => Material(
color: Colors.transparent,
child: child,
),
draggingWidgetOpacity: 0,
header: _cellLeading(),
needsLongPressDraggable: PlatformExtension.isMobile,
footer: _CellTrailing(viewId: widget.viewId),
onReorder: (int oldIndex, int newIndex) {
context
.read<GridHeaderBloc>()
.add(GridHeaderEvent.moveField(oldIndex, newIndex));
},
children: cells,
),
);
},
);
}
/// This is a workaround for [ReorderableRow].
/// [ReorderableRow] warps the child's key with a [GlobalKey].
/// It will trigger the child's widget's to recreate.
/// The state will lose.
ValueKey<String>? _getKeyById(String id) {
if (_gridMap.containsKey(id)) {
return _gridMap[id];
}
final newKey = ValueKey(id);
_gridMap[id] = newKey;
return newKey;
}
Widget _cellLeading() {
return SizedBox(width: GridSize.horizontalHeaderPadding);
}
}
class _CellTrailing extends StatelessWidget {
const _CellTrailing({required this.viewId});
final String viewId;
@override
Widget build(BuildContext context) {
return Container(
width: GridSize.trailHeaderPadding,
margin: EdgeInsets.only(right: GridSize.scrollBarSize + Insets.m),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Theme.of(context).dividerColor),
),
),
child: CreateFieldButton(
viewId: viewId,
onFieldCreated: (fieldId) => context
.read<GridHeaderBloc>()
.add(GridHeaderEvent.startEditingNewField(fieldId)),
),
);
}
}
class CreateFieldButton extends StatefulWidget {
const CreateFieldButton({
super.key,
required this.viewId,
required this.onFieldCreated,
});
final String viewId;
final void Function(String fieldId) onFieldCreated;
@override
State<CreateFieldButton> createState() => _CreateFieldButtonState();
}
class _CreateFieldButtonState extends State<CreateFieldButton> {
@override
Widget build(BuildContext context) {
return FlowyButton(
margin: GridSize.cellContentInsets,
radius: BorderRadius.zero,
text: FlowyText(
LocaleKeys.grid_field_newProperty.tr(),
overflow: TextOverflow.ellipsis,
),
hoverColor: AFThemeExtension.of(context).greyHover,
onTap: () async {
final result = await FieldBackendService.createField(
viewId: widget.viewId,
);
result.fold(
(field) => widget.onFieldCreated(field.id),
(err) => Log.error("Failed to create field type option: $err"),
);
},
leftIcon: const FlowySvg(
FlowySvgs.add_s,
size: Size.square(18),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/header/mobile_field_button.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/mobile/presentation/database/field/mobile_field_bottom_sheets.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/util/field_type_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
class MobileFieldButton extends StatelessWidget {
const MobileFieldButton.first({
super.key,
required this.viewId,
required this.fieldController,
required this.fieldInfo,
}) : radius = const BorderRadius.only(topLeft: Radius.circular(24)),
margin = const EdgeInsets.symmetric(vertical: 14, horizontal: 18),
index = null;
const MobileFieldButton({
super.key,
required this.viewId,
required this.fieldController,
required this.fieldInfo,
required this.index,
}) : radius = BorderRadius.zero,
margin = const EdgeInsets.symmetric(vertical: 14, horizontal: 12);
final String viewId;
final int? index;
final FieldController fieldController;
final FieldInfo fieldInfo;
final BorderRadius? radius;
final EdgeInsets? margin;
@override
Widget build(BuildContext context) {
Widget child = Container(
width: 200,
decoration: _getDecoration(context),
child: FlowyButton(
onTap: () =>
showQuickEditField(context, viewId, fieldController, fieldInfo),
radius: radius,
margin: margin,
leftIconSize: const Size.square(18),
leftIcon: FlowySvg(
fieldInfo.fieldType.svgData,
size: const Size.square(18),
),
text: FlowyText(
fieldInfo.name,
fontSize: 15,
overflow: TextOverflow.ellipsis,
),
),
);
if (index != null) {
child = ReorderableDelayedDragStartListener(index: index!, child: child);
}
return child;
}
BoxDecoration? _getDecoration(BuildContext context) {
final borderSide = BorderSide(
color: Theme.of(context).dividerColor,
);
if (index == null) {
return BoxDecoration(
borderRadius: const BorderRadiusDirectional.only(
topStart: Radius.circular(24),
),
border: BorderDirectional(
top: borderSide,
start: borderSide,
),
);
} else {
return null;
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/header/desktop_field_cell.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/plugins/database/application/field/field_cell_bloc.dart';
import 'package:appflowy/plugins/database/application/field/field_controller.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
import 'package:appflowy/plugins/database/widgets/field/field_editor.dart';
import 'package:appflowy/util/field_type_extension.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pb.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:flowy_infra/theme_extension.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 'package:flutter_bloc/flutter_bloc.dart';
import '../../layout/sizes.dart';
class GridFieldCell extends StatefulWidget {
const GridFieldCell({
super.key,
required this.viewId,
required this.fieldController,
required this.fieldInfo,
required this.onTap,
required this.onEditorOpened,
required this.onFieldInsertedOnEitherSide,
required this.isEditing,
required this.isNew,
});
final String viewId;
final FieldController fieldController;
final FieldInfo fieldInfo;
final VoidCallback onTap;
final VoidCallback onEditorOpened;
final void Function(String fieldId) onFieldInsertedOnEitherSide;
final bool isEditing;
final bool isNew;
@override
State<GridFieldCell> createState() => _GridFieldCellState();
}
class _GridFieldCellState extends State<GridFieldCell> {
late final FieldCellBloc _bloc;
late PopoverController popoverController;
@override
void initState() {
super.initState();
popoverController = PopoverController();
_bloc = FieldCellBloc(viewId: widget.viewId, fieldInfo: widget.fieldInfo);
if (widget.isEditing) {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
popoverController.show();
});
}
}
@override
void didUpdateWidget(covariant oldWidget) {
if (widget.fieldInfo != oldWidget.fieldInfo && !_bloc.isClosed) {
_bloc.add(FieldCellEvent.onFieldChanged(widget.fieldInfo));
}
if (widget.isEditing) {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
popoverController.show();
});
}
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
return BlocProvider.value(
value: _bloc,
child: BlocBuilder<FieldCellBloc, FieldCellState>(
builder: (context, state) {
final button = AppFlowyPopover(
triggerActions: PopoverTriggerFlags.none,
constraints: const BoxConstraints(),
margin: EdgeInsets.zero,
direction: PopoverDirection.bottomWithLeftAligned,
controller: popoverController,
popupBuilder: (BuildContext context) {
widget.onEditorOpened();
return FieldEditor(
viewId: widget.viewId,
fieldController: widget.fieldController,
field: widget.fieldInfo.field,
initialPage: widget.isNew
? FieldEditorPage.details
: FieldEditorPage.general,
onFieldInserted: widget.onFieldInsertedOnEitherSide,
);
},
child: FieldCellButton(
field: widget.fieldInfo.field,
onTap: widget.onTap,
),
);
const line = Positioned(
top: 0,
bottom: 0,
right: 0,
child: _DragToExpandLine(),
);
return _GridHeaderCellContainer(
width: state.width,
child: Stack(
alignment: Alignment.centerRight,
children: [button, line],
),
);
},
),
);
}
@override
void dispose() {
_bloc.close();
super.dispose();
}
}
class _GridHeaderCellContainer extends StatelessWidget {
const _GridHeaderCellContainer({
required this.child,
required this.width,
});
final Widget child;
final double width;
@override
Widget build(BuildContext context) {
final borderSide = BorderSide(
color: Theme.of(context).dividerColor,
);
final decoration = BoxDecoration(
border: Border(
right: borderSide,
bottom: borderSide,
),
);
return Container(
width: width,
decoration: decoration,
child: child,
);
}
}
class _DragToExpandLine extends StatelessWidget {
const _DragToExpandLine();
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {},
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onHorizontalDragStart: (details) {
context
.read<FieldCellBloc>()
.add(const FieldCellEvent.onResizeStart());
},
onHorizontalDragUpdate: (value) {
context
.read<FieldCellBloc>()
.add(FieldCellEvent.startUpdateWidth(value.localPosition.dx));
},
onHorizontalDragEnd: (end) {
context
.read<FieldCellBloc>()
.add(const FieldCellEvent.endUpdateWidth());
},
child: FlowyHover(
cursor: SystemMouseCursors.resizeLeftRight,
style: HoverStyle(
hoverColor: Theme.of(context).colorScheme.primary,
borderRadius: BorderRadius.zero,
contentMargin: const EdgeInsets.only(left: 6),
),
child: const SizedBox(width: 4),
),
),
);
}
}
class FieldCellButton extends StatelessWidget {
const FieldCellButton({
super.key,
required this.field,
required this.onTap,
this.maxLines = 1,
this.radius = BorderRadius.zero,
this.margin,
});
final FieldPB field;
final VoidCallback onTap;
final int? maxLines;
final BorderRadius? radius;
final EdgeInsets? margin;
@override
Widget build(BuildContext context) {
return FlowyButton(
hoverColor: AFThemeExtension.of(context).lightGreyHover,
onTap: onTap,
leftIcon: FlowySvg(
field.fieldType.svgData,
color: Theme.of(context).iconTheme.color,
),
radius: radius,
text: FlowyText.medium(
field.name,
maxLines: maxLines,
overflow: TextOverflow.ellipsis,
color: AFThemeExtension.of(context).textColor,
),
margin: margin ?? GridSize.cellContentInsets,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/header/field_type_extension.dart | import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pb.dart';
extension FieldTypeListExtension on FieldType {
bool get canEditHeader => switch (this) {
FieldType.MultiSelect => true,
FieldType.SingleSelect => true,
_ => false,
};
bool get canCreateNewGroup => switch (this) {
FieldType.MultiSelect => true,
FieldType.SingleSelect => true,
_ => false,
};
bool get canDeleteGroup => switch (this) {
FieldType.URL ||
FieldType.SingleSelect ||
FieldType.MultiSelect ||
FieldType.DateTime =>
true,
_ => false,
};
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/toolbar/grid_setting_bar.dart | import 'package:appflowy/plugins/database/application/database_controller.dart';
import 'package:appflowy/plugins/database/grid/application/filter/filter_menu_bloc.dart';
import 'package:appflowy/plugins/database/grid/application/sort/sort_editor_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/grid_page.dart';
import 'package:appflowy/plugins/database/widgets/setting/setting_button.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'filter_button.dart';
import 'sort_button.dart';
class GridSettingBar extends StatelessWidget {
const GridSettingBar({
super.key,
required this.controller,
required this.toggleExtension,
});
final DatabaseController controller;
final ToggleExtensionNotifier toggleExtension;
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<DatabaseFilterMenuBloc>(
create: (context) => DatabaseFilterMenuBloc(
viewId: controller.viewId,
fieldController: controller.fieldController,
)..add(const DatabaseFilterMenuEvent.initial()),
),
BlocProvider<SortEditorBloc>(
create: (context) => SortEditorBloc(
viewId: controller.viewId,
fieldController: controller.fieldController,
),
),
],
child: BlocListener<DatabaseFilterMenuBloc, DatabaseFilterMenuState>(
listenWhen: (p, c) => p.isVisible != c.isVisible,
listener: (context, state) => toggleExtension.toggle(),
child: ValueListenableBuilder<bool>(
valueListenable: controller.isLoading,
builder: (context, value, child) {
if (value) {
return const SizedBox.shrink();
}
return SizedBox(
height: 20,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
const FilterButton(),
const HSpace(2),
SortButton(toggleExtension: toggleExtension),
const HSpace(2),
SettingButton(
databaseController: controller,
),
],
),
);
},
),
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/toolbar/sort_button.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/grid/application/sort/sort_editor_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/grid_page.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import '../sort/create_sort_list.dart';
class SortButton extends StatefulWidget {
const SortButton({super.key, required this.toggleExtension});
final ToggleExtensionNotifier toggleExtension;
@override
State<SortButton> createState() => _SortButtonState();
}
class _SortButtonState extends State<SortButton> {
final _popoverController = PopoverController();
@override
Widget build(BuildContext context) {
return BlocBuilder<SortEditorBloc, SortEditorState>(
builder: (context, state) {
final textColor = state.sortInfos.isEmpty
? AFThemeExtension.of(context).textColor
: Theme.of(context).colorScheme.primary;
return wrapPopover(
context,
FlowyTextButton(
LocaleKeys.grid_settings_sort.tr(),
fontColor: textColor,
fontSize: FontSizes.s11,
fontWeight: FontWeight.w400,
fillColor: Colors.transparent,
hoverColor: AFThemeExtension.of(context).lightGreyHover,
padding: GridSize.toolbarSettingButtonInsets,
radius: Corners.s4Border,
onPressed: () {
if (state.sortInfos.isEmpty) {
_popoverController.show();
} else {
widget.toggleExtension.toggle();
}
},
),
);
},
);
}
Widget wrapPopover(BuildContext context, Widget child) {
return AppFlowyPopover(
controller: _popoverController,
direction: PopoverDirection.bottomWithLeftAligned,
constraints: BoxConstraints.loose(const Size(200, 300)),
offset: const Offset(0, 8),
triggerActions: PopoverTriggerFlags.none,
popupBuilder: (popoverContext) {
return BlocProvider.value(
value: context.read<SortEditorBloc>(),
child: CreateDatabaseViewSortList(
onTap: () {
if (!widget.toggleExtension.isToggled) {
widget.toggleExtension.toggle();
}
_popoverController.close();
},
),
);
},
onClose: () => context
.read<SortEditorBloc>()
.add(const SortEditorEvent.updateCreateSortFilter("")),
child: child,
);
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.