Bring projects, wikis, and teams together with AI. AppFlowy is the AI collaborative workspace where you achieve more without losing control of your data. The leading open source Notion alternative.
Dart blogconfluence-alternativecontent-managementcontent-servicesdocumentationflutternote-takingnotion-alternativeproject-managementtask-managementteam-collaborationwiki
feat: checklist cell improvements (#6515)
Richard Shiueb54e3dd24395
diff --git a/frontend/appflowy_flutter/integration_test/desktop/database/database_row_page_test.dart b/frontend/appflowy_flutter/integration_test/desktop/database/database_row_page_test.dartindex 25a816ad9d..26688ac0cf 100644--- a/frontend/appflowy_flutter/integration_test/desktop/database/database_row_page_test.dart+++ b/frontend/appflowy_flutter/integration_test/desktop/database/database_row_page_test.dart@@ -1,3 +1,6 @@+import 'package:appflowy/plugins/database/widgets/cell/desktop_row_detail/desktop_row_detail_checklist_cell.dart';+import 'package:appflowy/plugins/database/widgets/cell_editor/checklist_cell_editor.dart';+import 'package:flowy_infra_ui/flowy_infra_ui.dart';import 'package:flutter/material.dart';import 'package:appflowy/generated/locale_keys.g.dart';@@ -9,7 +12,7 @@ import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pbenum.import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';import 'package:appflowy_editor/appflowy_editor.dart';import 'package:easy_localization/easy_localization.dart';-import 'package:flowy_infra_ui/style_widget/text.dart';+import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:integration_test/integration_test.dart';@@ -335,5 +338,139 @@ void main() {tester.assertNumberOfRowsInGridPage(4);});++ testWidgets('edit checklist cell', (tester) async {+ await tester.initializeAppFlowy();+ await tester.tapAnonymousSignInButton();++ await tester.createNewPageWithNameUnderParent(layout: ViewLayoutPB.Grid);++ const fieldType = FieldType.Checklist;+ await tester.createField(fieldType);++ await tester.openFirstRowDetailPage();+ await tester.hoverOnWidget(+ find.byType(ChecklistRowDetailCell),+ onHover: () async {+ await tester.tapButton(find.byType(ChecklistItemControl));+ },+ );++ tester.assertPhantomChecklistItemAtIndex(index: 0);+ await tester.enterText(find.byType(PhantomChecklistItem), 'task 1');+ await tester.pumpAndSettle();+ await tester.simulateKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle(const Duration(milliseconds: 500));++ tester.assertChecklistTaskInEditor(+ index: 0,+ name: "task 1",+ isChecked: false,+ );+ tester.assertPhantomChecklistItemAtIndex(index: 1);++ await tester.enterText(find.byType(PhantomChecklistItem), 'task 2');+ await tester.pumpAndSettle();+ await tester.simulateKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle(const Duration(milliseconds: 500));++ tester.assertChecklistTaskInEditor(+ index: 1,+ name: "task 2",+ isChecked: false,+ );+ tester.assertPhantomChecklistItemAtIndex(index: 2);++ await tester.simulateKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(find.byType(PhantomChecklistItem), findsNothing);++ await tester.renameChecklistTask(index: 0, name: "task -1", enter: false);+ await tester.simulateKeyEvent(LogicalKeyboardKey.enter);++ tester.assertChecklistTaskInEditor(+ index: 0,+ name: "task -1",+ isChecked: false,+ );+ tester.assertPhantomChecklistItemAtIndex(index: 1);++ await tester.enterText(find.byType(PhantomChecklistItem), 'task 0');+ await tester.pumpAndSettle();+ await tester.simulateKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle(const Duration(milliseconds: 500));++ tester.assertPhantomChecklistItemAtIndex(index: 2);++ await tester.checkChecklistTask(index: 1);+ expect(find.byType(PhantomChecklistItem), findsNothing);+ expect(find.byType(ChecklistItem), findsNWidgets(3));++ tester.assertChecklistTaskInEditor(+ index: 0,+ name: "task -1",+ isChecked: false,+ );+ tester.assertChecklistTaskInEditor(+ index: 1,+ name: "task 0",+ isChecked: true,+ );+ tester.assertChecklistTaskInEditor(+ index: 2,+ name: "task 2",+ isChecked: false,+ );++ await tester.tapButton(+ find.descendant(+ of: find.byType(ProgressAndHideCompleteButton),+ matching: find.byType(FlowyIconButton),+ ),+ );+ expect(find.byType(ChecklistItem), findsNWidgets(2));++ tester.assertChecklistTaskInEditor(+ index: 0,+ name: "task -1",+ isChecked: false,+ );+ tester.assertChecklistTaskInEditor(+ index: 1,+ name: "task 2",+ isChecked: false,+ );++ await tester.renameChecklistTask(index: 1, name: "task 3", enter: false);+ await tester.simulateKeyEvent(LogicalKeyboardKey.enter);++ await tester.renameChecklistTask(index: 0, name: "task 1", enter: false);+ await tester.simulateKeyEvent(LogicalKeyboardKey.enter);++ await tester.enterText(find.byType(PhantomChecklistItem), 'task 2');+ await tester.pumpAndSettle();+ await tester.simulateKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle(const Duration(milliseconds: 500));++ tester.assertChecklistTaskInEditor(+ index: 0,+ name: "task 1",+ isChecked: false,+ );+ tester.assertChecklistTaskInEditor(+ index: 1,+ name: "task 2",+ isChecked: false,+ );+ tester.assertChecklistTaskInEditor(+ index: 2,+ name: "task 3",+ isChecked: false,+ );+ tester.assertPhantomChecklistItemAtIndex(index: 2);++ await tester.checkChecklistTask(index: 1);+ expect(find.byType(ChecklistItem), findsNWidgets(2));+ });});}diff --git a/frontend/appflowy_flutter/integration_test/shared/database_test_op.dart b/frontend/appflowy_flutter/integration_test/shared/database_test_op.dartindex d3c032c399..6546280a71 100644--- a/frontend/appflowy_flutter/integration_test/shared/database_test_op.dart+++ b/frontend/appflowy_flutter/integration_test/shared/database_test_op.dart@@ -2,6 +2,7 @@ import 'dart:io';import 'package:appflowy/plugins/database/application/field/filter_entities.dart';import 'package:appflowy/plugins/database/grid/presentation/widgets/filter/choicechip/select_option/condition_list.dart';+import 'package:appflowy/plugins/database/widgets/cell/desktop_row_detail/desktop_row_detail_checklist_cell.dart';import 'package:appflowy/shared/icon_emoji_picker/flowy_icon_emoji_picker.dart';import 'package:appflowy/shared/icon_emoji_picker/icon_picker.dart';import 'package:flutter/gestures.dart';@@ -508,6 +509,7 @@ extension AppFlowyDatabaseTest on WidgetTester {Future<void> renameChecklistTask({required int index,required String name,+ bool enter = true,}) async {final textField = find.descendant(@@ -517,7 +519,9 @@ extension AppFlowyDatabaseTest on WidgetTester {.at(index);await enterText(textField, name);- await testTextInput.receiveAction(TextInputAction.done);+ if (enter) {+ await testTextInput.receiveAction(TextInputAction.done);+ }await pumpAndSettle();}@@ -545,6 +549,23 @@ extension AppFlowyDatabaseTest on WidgetTester {await tapButton(button);}+ void assertPhantomChecklistItemAtIndex({required int index}) {+ final paddings = find.descendant(+ of: find.descendant(+ of: find.byType(ChecklistRowDetailCell),+ matching: find.byType(ReorderableListView),+ ),+ matching: find.byWidgetPredicate(+ (widget) =>+ widget is Padding &&+ (widget.child is ChecklistItem ||+ widget.child is PhantomChecklistItem),+ ),+ );+ final phantom = widget<Padding>(paddings.at(index)).child!;+ expect(phantom is PhantomChecklistItem, true);+ }+Future<void> openFirstRowDetailPage() async {await hoverOnFirstRowOfGrid();diff --git a/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/checklist_cell_bloc.dart b/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/checklist_cell_bloc.dartindex 7aad1108b1..34c922aaf9 100644--- a/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/checklist_cell_bloc.dart+++ b/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/checklist_cell_bloc.dart@@ -33,6 +33,8 @@ class ChecklistCellBloc extends Bloc<ChecklistCellEvent, ChecklistCellState> {final ChecklistCellBackendService _checklistCellService;void Function()? _onCellChangedFn;+ int? nextPhantomIndex;+@overrideFuture<void> close() async {if (_onCellChangedFn != null) {@@ -52,17 +54,23 @@ class ChecklistCellBloc extends Bloc<ChecklistCellEvent, ChecklistCellState> {const ChecklistCellState(tasks: [],percent: 0,- newTask: false,+ showIncompleteOnly: false,+ phantomIndex: null,),);return;}+ final phantomIndex = state.phantomIndex != null+ ? nextPhantomIndex ?? state.phantomIndex+ : null;emit(state.copyWith(tasks: _makeChecklistSelectOptions(data),percent: data.percentage,+ phantomIndex: phantomIndex,),);+ nextPhantomIndex = null;},updateTaskName: (option, name) {_updateOption(option, name);@@ -70,16 +78,28 @@ class ChecklistCellBloc extends Bloc<ChecklistCellEvent, ChecklistCellState> {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),- );+ createNewTask: (name, index) async {+ await _createTask(name, index);},deleteTask: (id) async {await _deleteOption([id]);},+ reorderTask: (fromIndex, toIndex) async {+ await _reorderTask(fromIndex, toIndex, emit);+ },+ toggleShowIncompleteOnly: () {+ emit(state.copyWith(showIncompleteOnly: !state.showIncompleteOnly));+ },+ updatePhantomIndex: (index) {+ emit(+ ChecklistCellState(+ tasks: state.tasks,+ percent: state.percent,+ showIncompleteOnly: state.showIncompleteOnly,+ phantomIndex: index,+ ),+ );+ },);},);@@ -95,6 +115,31 @@ class ChecklistCellBloc extends Bloc<ChecklistCellEvent, ChecklistCellState> {);}+ Future<void> _createTask(String name, int? index) async {+ nextPhantomIndex = index == null ? state.tasks.length + 1 : index + 1;++ int? actualIndex = index;+ if (index != null && state.showIncompleteOnly) {+ int notSelectedTaskCount = 0;+ for (int i = 0; i < state.tasks.length; i++) {+ if (!state.tasks[i].isSelected) {+ notSelectedTaskCount++;+ }++ if (notSelectedTaskCount == index) {+ actualIndex = i + 1;+ break;+ }+ }+ }++ final result = await _checklistCellService.create(+ name: name,+ index: actualIndex,+ );+ result.fold((l) {}, (err) => Log.error(err));+ }+void _updateOption(SelectOptionPB option, String name) async {final result =await _checklistCellService.updateName(option: option, name: name);@@ -105,6 +150,32 @@ class ChecklistCellBloc extends Bloc<ChecklistCellEvent, ChecklistCellState> {final result = await _checklistCellService.delete(optionIds: options);result.fold((l) => null, (err) => Log.error(err));}++ Future<void> _reorderTask(+ int fromIndex,+ int toIndex,+ Emitter<ChecklistCellState> emit,+ ) async {+ if (fromIndex < toIndex) {+ toIndex--;+ }++ final tasks = state.showIncompleteOnly+ ? state.tasks.where((task) => !task.isSelected).toList()+ : state.tasks;++ final fromId = tasks[fromIndex].data.id;+ final toId = tasks[toIndex].data.id;++ final newTasks = [...state.tasks];+ newTasks.insert(toIndex, newTasks.removeAt(fromIndex));+ emit(state.copyWith(tasks: newTasks));+ final result = await _checklistCellService.reorder(+ fromTaskId: fromId,+ toTaskId: toId,+ );+ result.fold((l) => null, (err) => Log.error(err));+ }}@freezed@@ -117,9 +188,17 @@ class ChecklistCellEvent with _$ChecklistCellEvent {String name,) = _UpdateTaskName;const factory ChecklistCellEvent.selectTask(String taskId) = _SelectTask;- const factory ChecklistCellEvent.createNewTask(String description) =- _CreateNewTask;+ const factory ChecklistCellEvent.createNewTask(+ String description, {+ int? index,+ }) = _CreateNewTask;const factory ChecklistCellEvent.deleteTask(String taskId) = _DeleteTask;+ const factory ChecklistCellEvent.reorderTask(int fromIndex, int toIndex) =+ _ReorderTask;++ const factory ChecklistCellEvent.toggleShowIncompleteOnly() = _IncompleteOnly;+ const factory ChecklistCellEvent.updatePhantomIndex(int? index) =+ _UpdatePhantomIndex;}@freezed@@ -127,7 +206,8 @@ class ChecklistCellState with _$ChecklistCellState {const factory ChecklistCellState({required List<ChecklistSelectOption> tasks,required double percent,- required bool newTask,+ required bool showIncompleteOnly,+ required int? phantomIndex,}) = _ChecklistCellState;factory ChecklistCellState.initial(ChecklistCellController cellController) {@@ -136,7 +216,8 @@ class ChecklistCellState with _$ChecklistCellState {return ChecklistCellState(tasks: _makeChecklistSelectOptions(cellData),percent: cellData?.percentage ?? 0,- newTask: false,+ showIncompleteOnly: false,+ phantomIndex: null,);}}diff --git a/frontend/appflowy_flutter/lib/plugins/database/domain/checklist_cell_service.dart b/frontend/appflowy_flutter/lib/plugins/database/domain/checklist_cell_service.dartindex 5b89d05643..3dcba2ca37 100644--- a/frontend/appflowy_flutter/lib/plugins/database/domain/checklist_cell_service.dart+++ b/frontend/appflowy_flutter/lib/plugins/database/domain/checklist_cell_service.dart@@ -1,6 +1,5 @@import 'package:appflowy_backend/dispatch/dispatch.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: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:protobuf/protobuf.dart';@@ -18,12 +17,16 @@ class ChecklistCellBackendService {Future<FlowyResult<void, FlowyError>> create({required String name,+ int? index,}) {- final payload = ChecklistCellDataChangesetPB.create()- ..viewId = viewId- ..fieldId = fieldId- ..rowId = rowId- ..insertOptions.add(name);+ final insert = ChecklistCellInsertPB()..name = name;+ if (index != null) {+ insert.index = index;+ }++ final payload = ChecklistCellDataChangesetPB()+ ..cellId = _makdeCellId()+ ..insertTask.add(insert);return DatabaseEventUpdateChecklistCell(payload).send();}@@ -31,11 +34,9 @@ class ChecklistCellBackendService {Future<FlowyResult<void, FlowyError>> delete({required List<String> optionIds,}) {- final payload = ChecklistCellDataChangesetPB.create()- ..viewId = viewId- ..fieldId = fieldId- ..rowId = rowId- ..deleteOptionIds.addAll(optionIds);+ final payload = ChecklistCellDataChangesetPB()+ ..cellId = _makdeCellId()+ ..deleteTasks.addAll(optionIds);return DatabaseEventUpdateChecklistCell(payload).send();}@@ -43,11 +44,9 @@ class ChecklistCellBackendService {Future<FlowyResult<void, FlowyError>> select({required String optionId,}) {- final payload = ChecklistCellDataChangesetPB.create()- ..viewId = viewId- ..fieldId = fieldId- ..rowId = rowId- ..selectedOptionIds.add(optionId);+ final payload = ChecklistCellDataChangesetPB()+ ..cellId = _makdeCellId()+ ..completedTasks.add(optionId);return DatabaseEventUpdateChecklistCell(payload).send();}@@ -60,12 +59,28 @@ class ChecklistCellBackendService {final newOption = option.rebuild((option) {option.name = name;});- final payload = ChecklistCellDataChangesetPB.create()- ..viewId = viewId- ..fieldId = fieldId- ..rowId = rowId- ..updateOptions.add(newOption);+ final payload = ChecklistCellDataChangesetPB()+ ..cellId = _makdeCellId()+ ..updateTasks.add(newOption);return DatabaseEventUpdateChecklistCell(payload).send();}++ Future<FlowyResult<void, FlowyError>> reorder({+ required fromTaskId,+ required toTaskId,+ }) {+ final payload = ChecklistCellDataChangesetPB()+ ..cellId = _makdeCellId()+ ..reorder = "$fromTaskId $toTaskId";++ return DatabaseEventUpdateChecklistCell(payload).send();+ }++ CellIdPB _makdeCellId() {+ return CellIdPB()+ ..viewId = viewId+ ..fieldId = fieldId+ ..rowId = rowId;+ }}diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_grid/desktop_grid_checklist_cell.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_grid/desktop_grid_checklist_cell.dartindex 285b0217eb..95ba57c21d 100644--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_grid/desktop_grid_checklist_cell.dart+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_grid/desktop_grid_checklist_cell.dart@@ -17,7 +17,6 @@ class DesktopGridChecklistCellSkin extends IEditableChecklistCellSkin {BuildContext context,CellContainerNotifier cellContainerNotifier,ChecklistCellBloc bloc,- ChecklistCellState state,PopoverController popoverController,) {return AppFlowyPopover(@@ -27,7 +26,7 @@ class DesktopGridChecklistCellSkin extends IEditableChecklistCellSkin {direction: PopoverDirection.bottomWithLeftAligned,triggerActions: PopoverTriggerFlags.none,skipTraversal: true,- popupBuilder: (BuildContext popoverContext) {+ popupBuilder: (popoverContext) {WidgetsBinding.instance.addPostFrameCallback((_) {cellContainerNotifier.isFocus = true;});@@ -39,15 +38,19 @@ class DesktopGridChecklistCellSkin extends IEditableChecklistCellSkin {);},onClose: () => cellContainerNotifier.isFocus = false,- child: Container(- alignment: AlignmentDirectional.centerStart,- padding: GridSize.cellContentInsets,- child: state.tasks.isEmpty- ? const SizedBox.shrink()- : ChecklistProgressBar(- tasks: state.tasks,- percent: state.percent,- ),+ child: BlocBuilder<ChecklistCellBloc, ChecklistCellState>(+ builder: (context, state) {+ return Container(+ alignment: AlignmentDirectional.centerStart,+ padding: GridSize.cellContentInsets,+ child: state.tasks.isEmpty+ ? const SizedBox.shrink()+ : ChecklistProgressBar(+ tasks: state.tasks,+ percent: state.percent,+ ),+ );+ },),);}diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_row_detail/desktop_row_detail_checklist_cell.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_row_detail/desktop_row_detail_checklist_cell.dartindex b870040660..4890e75771 100644--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_row_detail/desktop_row_detail_checklist_cell.dart+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_row_detail/desktop_row_detail_checklist_cell.dart@@ -1,14 +1,21 @@+import 'dart:io';+import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/plugins/database/application/cell/bloc/checklist_cell_bloc.dart';import 'package:appflowy/plugins/database/widgets/cell_editor/checklist_cell_editor.dart';+import 'package:appflowy/plugins/database/widgets/cell_editor/checklist_cell_textfield.dart';import 'package:appflowy/plugins/database/widgets/cell_editor/checklist_progress_bar.dart';import 'package:appflowy/plugins/database/widgets/row/cells/cell_container.dart';import 'package:appflowy_popover/appflowy_popover.dart';import 'package:collection/collection.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/services.dart';+import 'package:flutter_bloc/flutter_bloc.dart';import 'package:provider/provider.dart';import '../editable_cell_skeleton/checklist.dart';@@ -19,150 +26,358 @@ class DesktopRowDetailChecklistCellSkin extends IEditableChecklistCellSkin {BuildContext context,CellContainerNotifier cellContainerNotifier,ChecklistCellBloc bloc,- ChecklistCellState state,PopoverController popoverController,) {- return ChecklistItems(+ return ChecklistRowDetailCell(context: context,cellContainerNotifier: cellContainerNotifier,bloc: bloc,- state: state,popoverController: popoverController,);}}-class ChecklistItems extends StatefulWidget {- const ChecklistItems({+class ChecklistRowDetailCell extends StatefulWidget {+ const ChecklistRowDetailCell({super.key,required this.context,required this.cellContainerNotifier,required this.bloc,- required this.state,required this.popoverController,});final BuildContext context;final CellContainerNotifier cellContainerNotifier;final ChecklistCellBloc bloc;- final ChecklistCellState state;final PopoverController popoverController;@override- State<ChecklistItems> createState() => _ChecklistItemsState();+ State<ChecklistRowDetailCell> createState() => _ChecklistRowDetailCellState();}-class _ChecklistItemsState extends State<ChecklistItems> {- bool showIncompleteOnly = false;-+class _ChecklistRowDetailCellState extends State<ChecklistRowDetailCell> {@overrideWidget build(BuildContext context) {- final tasks = [...widget.state.tasks];- if (showIncompleteOnly) {- tasks.removeWhere((task) => task.isSelected);- }- // final children = tasks- // .mapIndexed(- // (index, task) => Padding(- // padding: const EdgeInsets.symmetric(vertical: 2.0),- // child: ChecklistItem(- // key: ValueKey('${task.data.id}$index'),- // task: task,- // autofocus: widget.state.newTask && index == tasks.length - 1,- // onSubmitted: () {- // if (index == tasks.length - 1) {- // // create a new task under the last task if the users press enter- // widget.bloc.add(const ChecklistCellEvent.createNewTask(''));- // }- // },- // ),- // ),- // )- // .toList();return Align(alignment: AlignmentDirectional.centerStart,child: Column(mainAxisSize: MainAxisSize.min,children: [- Padding(- padding: const EdgeInsets.only(left: 8.0),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Flexible(- child: ChecklistProgressBar(- tasks: widget.state.tasks,- percent: widget.state.percent,- ),- ),- const HSpace(6.0),- FlowyIconButton(- tooltipText: showIncompleteOnly- ? LocaleKeys.grid_checklist_showComplete.tr()- : LocaleKeys.grid_checklist_hideComplete.tr(),- width: 32,- iconColorOnHover: Theme.of(context).colorScheme.onSurface,- icon: FlowySvg(- showIncompleteOnly ? FlowySvgs.show_m : FlowySvgs.hide_m,- size: const Size.square(16),+ ProgressAndHideCompleteButton(+ onToggleHideComplete: () => context+ .read<ChecklistCellBloc>()+ .add(const ChecklistCellEvent.toggleShowIncompleteOnly()),+ ),+ const VSpace(2.0),+ _ChecklistItems(+ onStartCreatingTaskAfter: (index) {+ context+ .read<ChecklistCellBloc>()+ .add(ChecklistCellEvent.updatePhantomIndex(index + 1));+ },+ ),+ ChecklistItemControl(+ cellNotifer: widget.cellContainerNotifier,+ onTap: () {+ final bloc = context.read<ChecklistCellBloc>();+ if (bloc.state.phantomIndex == null) {+ bloc.add(+ ChecklistCellEvent.updatePhantomIndex(+ bloc.state.showIncompleteOnly+ ? bloc.state.tasks+ .where((task) => !task.isSelected)+ .length+ : bloc.state.tasks.length,),- onPressed: () {- setState(- () => showIncompleteOnly = !showIncompleteOnly,+ );+ }+ },+ ),+ ],+ ),+ );+ }+}++@visibleForTesting+class ProgressAndHideCompleteButton extends StatelessWidget {+ const ProgressAndHideCompleteButton({+ super.key,+ required this.onToggleHideComplete,+ });++ final VoidCallback onToggleHideComplete;++ @override+ Widget build(BuildContext context) {+ return BlocBuilder<ChecklistCellBloc, ChecklistCellState>(+ buildWhen: (previous, current) =>+ previous.showIncompleteOnly != current.showIncompleteOnly,+ builder: (context, state) {+ return Padding(+ padding: const EdgeInsets.only(left: 8.0),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Flexible(+ child: BlocBuilder<ChecklistCellBloc, ChecklistCellState>(+ builder: (context, state) {+ return ChecklistProgressBar(+ tasks: state.tasks,+ percent: state.percent,);},),- ],+ ),+ const HSpace(6.0),+ FlowyIconButton(+ tooltipText: state.showIncompleteOnly+ ? LocaleKeys.grid_checklist_showComplete.tr()+ : LocaleKeys.grid_checklist_hideComplete.tr(),+ width: 32,+ iconColorOnHover: Theme.of(context).colorScheme.onSurface,+ icon: FlowySvg(+ state.showIncompleteOnly+ ? FlowySvgs.show_m+ : FlowySvgs.hide_m,+ size: const Size.square(16),+ ),+ onPressed: onToggleHideComplete,+ ),+ ],+ ),+ );+ },+ );+ }+}++class _ChecklistItems extends StatelessWidget {+ const _ChecklistItems({+ required this.onStartCreatingTaskAfter,+ });++ final void Function(int index) onStartCreatingTaskAfter;++ @override+ Widget build(BuildContext context) {+ return Actions(+ actions: {+ _CancelCreatingFromPhantomIntent:+ CallbackAction<_CancelCreatingFromPhantomIntent>(+ onInvoke: (_CancelCreatingFromPhantomIntent intent) {+ context+ .read<ChecklistCellBloc>()+ .add(const ChecklistCellEvent.updatePhantomIndex(null));+ return;+ },+ ),+ },+ child: BlocBuilder<ChecklistCellBloc, ChecklistCellState>(+ builder: (context, state) {+ final children = _makeChildren(context, state);+ return ReorderableListView.builder(+ shrinkWrap: true,+ proxyDecorator: (child, index, _) => Material(+ color: Colors.transparent,+ child: Stack(+ children: [+ BlocProvider.value(+ value: context.read<ChecklistCellBloc>(),+ child: child,+ ),+ MouseRegion(+ cursor: Platform.isWindows+ ? SystemMouseCursors.click+ : SystemMouseCursors.grabbing,+ child: const SizedBox.expand(),+ ),+ ],+ ),),+ buildDefaultDragHandles: false,+ itemCount: children.length,+ itemBuilder: (_, index) => children[index],+ onReorder: (from, to) {+ context+ .read<ChecklistCellBloc>()+ .add(ChecklistCellEvent.reorderTask(from, to));+ },+ );+ },+ ),+ );+ }++ List<Widget> _makeChildren(BuildContext context, ChecklistCellState state) {+ final children = <Widget>[];++ final tasks = [...state.tasks];++ if (state.showIncompleteOnly) {+ tasks.removeWhere((task) => task.isSelected);+ }++ children.addAll(+ tasks.mapIndexed(+ (index, task) => Padding(+ key: ValueKey('checklist_row_detail_cell_task_${task.data.id}'),+ padding: const EdgeInsets.symmetric(vertical: 2.0),+ child: ChecklistItem(+ task: task,+ index: index,+ onSubmitted: () {+ onStartCreatingTaskAfter(index);+ },),- const VSpace(2.0),- _ChecklistCellEditors(tasks: tasks),- ChecklistItemControl(cellNotifer: widget.cellContainerNotifier),- ],+ ),),);++ if (state.phantomIndex != null) {+ children.insert(+ state.phantomIndex!,+ Padding(+ key: const ValueKey('new_checklist_cell_task'),+ padding: const EdgeInsets.symmetric(vertical: 2.0),+ child: PhantomChecklistItem(index: state.phantomIndex!),+ ),+ );+ }++ return children;}}-class _ChecklistCellEditors extends StatelessWidget {- const _ChecklistCellEditors({- required this.tasks,+class _CancelCreatingFromPhantomIntent extends Intent {+ const _CancelCreatingFromPhantomIntent();+}++class _SubmitPhantomTaskIntent extends Intent {+ const _SubmitPhantomTaskIntent({+ required this.taskDescription,+ required this.index,+ });++ final String taskDescription;+ final int index;+}++@visibleForTesting+class PhantomChecklistItem extends StatefulWidget {+ const PhantomChecklistItem({+ super.key,+ required this.index,});- final List<ChecklistSelectOption> tasks;+ final int index;++ @override+ State<PhantomChecklistItem> createState() => _PhantomChecklistItemState();+}++class _PhantomChecklistItemState extends State<PhantomChecklistItem> {+ TextEditingController textController = TextEditingController();+ final focusNode = FocusNode();++ bool isComposing = false;++ @override+ void initState() {+ super.initState();+ textController.addListener(() {+ setState(() {+ isComposing = !textController.value.composing.isCollapsed;+ });+ });+ focusNode.addListener(() {+ if (!focusNode.hasFocus) {+ textController.clear();+ Actions.maybeInvoke(+ context,+ const _CancelCreatingFromPhantomIntent(),+ );+ }+ });+ WidgetsBinding.instance.addPostFrameCallback((_) {+ focusNode.requestFocus();+ });+ }++ @override+ void dispose() {+ textController.dispose();+ focusNode.dispose();+ super.dispose();+ }@overrideWidget build(BuildContext context) {- final bloc = context.read<ChecklistCellBloc>();- final state = bloc.state;- return Column(- mainAxisSize: MainAxisSize.min,- children: [- ...tasks.mapIndexed(- (index, task) => Padding(- padding: const EdgeInsets.symmetric(vertical: 2.0),- child: ChecklistItem(- key: ValueKey('${task.data.id}$index'),- task: task,- autofocus: state.newTask && index == tasks.length - 1,- onSubmitted: () {- if (index == tasks.length - 1) {- // create a new task under the last task if the users press enter- bloc.add(const ChecklistCellEvent.createNewTask(''));- }- },+ return Actions(+ actions: {+ _SubmitPhantomTaskIntent: CallbackAction<_SubmitPhantomTaskIntent>(+ onInvoke: (_SubmitPhantomTaskIntent intent) {+ if (intent.taskDescription.isNotEmpty) {+ context.read<ChecklistCellBloc>().add(+ ChecklistCellEvent.createNewTask(+ intent.taskDescription,+ index: intent.index,+ ),+ );+ }+ textController.clear();+ return;+ },+ ),+ },+ child: Shortcuts(+ shortcuts: _buildShortcuts(),+ child: Container(+ constraints: const BoxConstraints(minHeight: 32),+ decoration: BoxDecoration(+ color: AFThemeExtension.of(context).lightGreyHover,+ borderRadius: Corners.s6Border,+ ),+ child: Center(+ child: ChecklistCellTextfield(+ textController: textController,+ focusNode: focusNode,+ contentPadding: const EdgeInsets.symmetric(+ horizontal: 10,+ vertical: 10,+ ),),),),- ],+ ),);}++ Map<ShortcutActivator, Intent> _buildShortcuts() {+ return isComposing+ ? const {}+ : {+ const SingleActivator(LogicalKeyboardKey.enter):+ _SubmitPhantomTaskIntent(+ taskDescription: textController.text,+ index: widget.index,+ ),+ const SingleActivator(LogicalKeyboardKey.escape):+ const _CancelCreatingFromPhantomIntent(),+ };+ }}+@visibleForTestingclass ChecklistItemControl extends StatelessWidget {- const ChecklistItemControl({super.key, required this.cellNotifer});+ const ChecklistItemControl({+ super.key,+ required this.cellNotifer,+ required this.onTap,+ });final CellContainerNotifier cellNotifer;+ final VoidCallback onTap;@overrideWidget build(BuildContext context) {@@ -171,9 +386,7 @@ class ChecklistItemControl extends StatelessWidget {child: Consumer<CellContainerNotifier>(builder: (buildContext, notifier, _) => GestureDetector(behavior: HitTestBehavior.opaque,- onTap: () => context- .read<ChecklistCellBloc>()- .add(const ChecklistCellEvent.createNewTask("")),+ onTap: onTap,child: Container(margin: const EdgeInsets.fromLTRB(8.0, 2.0, 8.0, 0),height: 12,@@ -192,11 +405,7 @@ class ChecklistItemControl extends StatelessWidget {maximumSize: const Size.square(12),padding: EdgeInsets.zero,),- onPressed: () => context- .read<ChecklistCellBloc>()- .add(- const ChecklistCellEvent.createNewTask(""),- ),+ onPressed: onTap,child: FlowySvg(FlowySvgs.add_s,color: Theme.of(context).colorScheme.onPrimary,diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/editable_cell_skeleton/checklist.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/editable_cell_skeleton/checklist.dartindex dd7bc6c2c1..4cdebee36d 100644--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/editable_cell_skeleton/checklist.dart+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/editable_cell_skeleton/checklist.dart@@ -29,7 +29,6 @@ abstract class IEditableChecklistCellSkin {BuildContext context,CellContainerNotifier cellContainerNotifier,ChecklistCellBloc bloc,- ChecklistCellState state,PopoverController popoverController,);}@@ -70,16 +69,11 @@ class GridChecklistCellState extends GridCellState<EditableChecklistCell> {Widget build(BuildContext context) {return BlocProvider.value(value: cellBloc,- child: BlocBuilder<ChecklistCellBloc, ChecklistCellState>(- builder: (context, state) {- return widget.skin.build(- context,- widget.cellContainerNotifier,- cellBloc,- state,- _popover,- );- },+ child: widget.skin.build(+ context,+ widget.cellContainerNotifier,+ cellBloc,+ _popover,),);}diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_grid/mobile_grid_checklist_cell.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_grid/mobile_grid_checklist_cell.dartindex aa55dd9e36..78bde58c9a 100644--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_grid/mobile_grid_checklist_cell.dart+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_grid/mobile_grid_checklist_cell.dart@@ -17,35 +17,38 @@ class MobileGridChecklistCellSkin extends IEditableChecklistCellSkin {BuildContext context,CellContainerNotifier cellContainerNotifier,ChecklistCellBloc bloc,- ChecklistCellState state,PopoverController popoverController,) {- return FlowyButton(- radius: BorderRadius.zero,- hoverColor: Colors.transparent,- text: Container(- alignment: Alignment.centerLeft,- padding: GridSize.cellContentInsets,- child: state.tasks.isEmpty- ? const SizedBox.shrink()- : ChecklistProgressBar(- tasks: state.tasks,- percent: state.percent,- textStyle: Theme.of(context)- .textTheme- .bodyMedium- ?.copyWith(fontSize: 15),- ),- ),- onTap: () => showMobileBottomSheet(- context,- builder: (context) {- return BlocProvider.value(- value: bloc,- child: const MobileChecklistCellEditScreen(),- );- },- ),+ return BlocBuilder<ChecklistCellBloc, ChecklistCellState>(+ builder: (context, state) {+ return FlowyButton(+ radius: BorderRadius.zero,+ hoverColor: Colors.transparent,+ text: Container(+ alignment: Alignment.centerLeft,+ padding: GridSize.cellContentInsets,+ child: state.tasks.isEmpty+ ? const SizedBox.shrink()+ : ChecklistProgressBar(+ tasks: state.tasks,+ percent: state.percent,+ textStyle: Theme.of(context)+ .textTheme+ .bodyMedium+ ?.copyWith(fontSize: 15),+ ),+ ),+ onTap: () => showMobileBottomSheet(+ context,+ builder: (context) {+ return BlocProvider.value(+ value: bloc,+ child: const MobileChecklistCellEditScreen(),+ );+ },+ ),+ );+ },);}}diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_row_detail/mobile_row_detail_checklist_cell.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_row_detail/mobile_row_detail_checklist_cell.dartindex 67f9f1c53f..11fa98a323 100644--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_row_detail/mobile_row_detail_checklist_cell.dart+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_row_detail/mobile_row_detail_checklist_cell.dart@@ -19,49 +19,52 @@ class MobileRowDetailChecklistCellSkin extends IEditableChecklistCellSkin {BuildContext context,CellContainerNotifier cellContainerNotifier,ChecklistCellBloc bloc,- ChecklistCellState state,PopoverController popoverController,) {- return InkWell(- borderRadius: const BorderRadius.all(Radius.circular(14)),- onTap: () => showMobileBottomSheet(- context,- backgroundColor: AFThemeExtension.of(context).background,- builder: (context) {- return BlocProvider.value(- value: bloc,- child: const MobileChecklistCellEditScreen(),- );- },- ),- child: Container(- constraints: const BoxConstraints(- minHeight: 48,- minWidth: double.infinity,- ),- decoration: BoxDecoration(- border: Border.fromBorderSide(- BorderSide(color: Theme.of(context).colorScheme.outline),- ),+ return BlocBuilder<ChecklistCellBloc, ChecklistCellState>(+ builder: (context, state) {+ return InkWell(borderRadius: const BorderRadius.all(Radius.circular(14)),- ),- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 13),- alignment: AlignmentDirectional.centerStart,- child: state.tasks.isEmpty- ? FlowyText(- LocaleKeys.grid_row_textPlaceholder.tr(),- fontSize: 15,- color: Theme.of(context).hintColor,- )- : ChecklistProgressBar(- tasks: state.tasks,- percent: state.percent,- textStyle: Theme.of(context).textTheme.bodyMedium?.copyWith(- fontSize: 15,- color: Theme.of(context).hintColor,- ),+ onTap: () => showMobileBottomSheet(+ context,+ backgroundColor: AFThemeExtension.of(context).background,+ builder: (context) {+ return BlocProvider.value(+ value: bloc,+ child: const MobileChecklistCellEditScreen(),+ );+ },+ ),+ child: Container(+ constraints: const BoxConstraints(+ minHeight: 48,+ minWidth: double.infinity,+ ),+ decoration: BoxDecoration(+ border: Border.fromBorderSide(+ BorderSide(color: Theme.of(context).colorScheme.outline),),- ),+ borderRadius: const BorderRadius.all(Radius.circular(14)),+ ),+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 13),+ alignment: AlignmentDirectional.centerStart,+ child: state.tasks.isEmpty+ ? FlowyText(+ LocaleKeys.grid_row_textPlaceholder.tr(),+ fontSize: 15,+ color: Theme.of(context).hintColor,+ )+ : ChecklistProgressBar(+ tasks: state.tasks,+ percent: state.percent,+ textStyle: Theme.of(context).textTheme.bodyMedium?.copyWith(+ fontSize: 15,+ color: Theme.of(context).hintColor,+ ),+ ),+ ),+ );+ },);}}diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/checklist_cell_editor.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/checklist_cell_editor.dartindex 4d18862223..3eb7453f73 100644--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/checklist_cell_editor.dart+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/checklist_cell_editor.dart@@ -1,5 +1,6 @@import 'dart:io';+import 'package:appflowy/generated/flowy_svgs.g.dart';import 'package:appflowy/generated/locale_keys.g.dart';import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';@@ -108,23 +109,46 @@ class ChecklistItemList extends StatelessWidget {final itemList = options.mapIndexed((index, option) => Padding(- padding: const EdgeInsets.symmetric(horizontal: 8.0),+ padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),+ key: ValueKey(option.data.id),child: ChecklistItem(task: option,+ index: index,onSubmitted: index == options.length - 1 ? onUpdateTask : null,- key: ValueKey(option.data.id),),),).toList();return Flexible(- child: ListView.separated(+ child: ReorderableListView.builder(+ shrinkWrap: true,+ proxyDecorator: (child, index, _) => Material(+ color: Colors.transparent,+ child: Stack(+ children: [+ BlocProvider.value(+ value: context.read<ChecklistCellBloc>(),+ child: child,+ ),+ MouseRegion(+ cursor: Platform.isWindows+ ? SystemMouseCursors.click+ : SystemMouseCursors.grabbing,+ child: const SizedBox.expand(),+ ),+ ],+ ),+ ),+ buildDefaultDragHandles: false,itemBuilder: (context, index) => itemList[index],- separatorBuilder: (context, index) => const VSpace(4),itemCount: itemList.length,- shrinkWrap: true,- padding: const EdgeInsets.symmetric(vertical: 8.0),+ padding: const EdgeInsets.symmetric(vertical: 6.0),+ onReorder: (from, to) {+ context+ .read<ChecklistCellBloc>()+ .add(ChecklistCellEvent.reorderTask(from, to));+ },),);}@@ -142,17 +166,17 @@ class _UpdateTaskDescriptionIntent extends Intent {const _UpdateTaskDescriptionIntent();}-/// Represents an existing task-@visibleForTestingclass ChecklistItem extends StatefulWidget {const ChecklistItem({super.key,required this.task,+ required this.index,this.onSubmitted,this.autofocus = false,});final ChecklistSelectOption task;+ final int index;final VoidCallback? onSubmitted;final bool autofocus;@@ -167,27 +191,21 @@ class _ChecklistItemState extends State<ChecklistItem> {bool isHovered = false;bool isFocused = false;+ bool isComposing = false;final _debounceOnChanged = Debounce(duration: const Duration(milliseconds: 300),);- final selectTaskShortcut = {- SingleActivator(- LogicalKeyboardKey.enter,- meta: Platform.isMacOS,- control: !Platform.isMacOS,- ): const _SelectTaskIntent(),- const SingleActivator(LogicalKeyboardKey.enter):- const _UpdateTaskDescriptionIntent(),- const SingleActivator(LogicalKeyboardKey.escape):- const _EndEditingTaskIntent(),- };-@overridevoid initState() {super.initState();textController.text = widget.task.data.name;+ textController.addListener(() {+ setState(() {+ isComposing = !textController.value.composing.isCollapsed;+ });+ });if (widget.autofocus) {WidgetsBinding.instance.addPostFrameCallback((_) {focusNode.requestFocus();@@ -196,6 +214,15 @@ class _ChecklistItemState extends State<ChecklistItem> {}}+ @override+ void didUpdateWidget(covariant oldWidget) {+ if (!focusNode.hasFocus &&+ oldWidget.task.data.name != widget.task.data.name) {+ textController.text = widget.task.data.name;+ }+ super.didUpdateWidget(oldWidget);+ }+@overridevoid dispose() {_debounceOnChanged.dispose();@@ -222,7 +249,7 @@ class _ChecklistItemState extends State<ChecklistItem> {isFocused = value;}),actions: _buildActions(),- shortcuts: selectTaskShortcut,+ shortcuts: _buildShortcuts(),child: Container(constraints: BoxConstraints(minHeight: GridSize.popoverItemHeight,@@ -232,25 +259,45 @@ class _ChecklistItemState extends State<ChecklistItem> {borderRadius: Corners.s6Border,),child: _buildChild(- context,isFocusedOrHovered,),),);}- Widget _buildChild(BuildContext context, bool isFocusedOrHovered) {+ Widget _buildChild(bool isFocusedOrHovered) {return Row(children: [- ChecklistCellCheckIcon(task: widget.task),+ ReorderableDragStartListener(+ index: widget.index,+ child: MouseRegion(+ cursor: Platform.isWindows+ ? SystemMouseCursors.click+ : SystemMouseCursors.grab,+ child: SizedBox(+ width: 20,+ height: 32,+ child: Align(+ alignment: AlignmentDirectional.centerEnd,+ child: FlowySvg(+ FlowySvgs.drag_element_s,+ size: const Size.square(14),+ color: AFThemeExtension.of(context).onBackground,+ ),+ ),+ ),+ ),+ ),+ ChecklistCellCheckIcon(+ task: widget.task,+ ),Expanded(child: ChecklistCellTextfield(textController: textController,focusNode: textFieldFocusNode,- autofocus: widget.autofocus,onChanged: () {_debounceOnChanged.call(() {- if (textController.selection.isCollapsed) {+ if (!isComposing) {_submitUpdateTaskDescription(textController.text);}});@@ -276,6 +323,22 @@ class _ChecklistItemState extends State<ChecklistItem> {);}+ Map<ShortcutActivator, Intent> _buildShortcuts() {+ return {+ SingleActivator(+ LogicalKeyboardKey.enter,+ meta: Platform.isMacOS,+ control: !Platform.isMacOS,+ ): const _SelectTaskIntent(),+ if (!isComposing)+ const SingleActivator(LogicalKeyboardKey.enter):+ const _UpdateTaskDescriptionIntent(),+ if (!isComposing)+ const SingleActivator(LogicalKeyboardKey.escape):+ const _EndEditingTaskIntent(),+ };+ }+Map<Type, Action<Intent>> _buildActions() {return {_SelectTaskIntent: CallbackAction<_SelectTaskIntent>(@@ -326,12 +389,19 @@ class NewTaskItem extends StatefulWidget {}class _NewTaskItemState extends State<NewTaskItem> {- final _textEditingController = TextEditingController();- bool _isCreateButtonEnabled = false;+ final textController = TextEditingController();++ bool isCreateButtonEnabled = false;+ bool isComposing = false;@overridevoid initState() {super.initState();+ textController.addListener(() {+ setState(() {+ isComposing = !textController.value.composing.isCollapsed;+ });+ });if (widget.focusNode.canRequestFocus) {widget.focusNode.requestFocus();}@@ -339,7 +409,7 @@ class _NewTaskItemState extends State<NewTaskItem> {@overridevoid dispose() {- _textEditingController.dispose();+ textController.dispose();super.dispose();}@@ -353,13 +423,15 @@ class _NewTaskItemState extends State<NewTaskItem> {const HSpace(8),Expanded(child: CallbackShortcuts(- bindings: {- const SingleActivator(LogicalKeyboardKey.enter): () =>- _createNewTask(context),- },+ bindings: isComposing+ ? const {}+ : {+ const SingleActivator(LogicalKeyboardKey.enter): () =>+ _createNewTask(context),+ },child: TextField(focusNode: widget.focusNode,- controller: _textEditingController,+ controller: textController,style: Theme.of(context).textTheme.bodyMedium,maxLines: null,decoration: InputDecoration(@@ -373,8 +445,7 @@ class _NewTaskItemState extends State<NewTaskItem> {),onSubmitted: (_) => _createNewTask(context),onChanged: (value) => setState(- () => _isCreateButtonEnabled =- _textEditingController.text.isNotEmpty,+ () => isCreateButtonEnabled = textController.text.isNotEmpty,),),),@@ -382,23 +453,23 @@ class _NewTaskItemState extends State<NewTaskItem> {FlowyTextButton(LocaleKeys.grid_checklist_submitNewTask.tr(),fontSize: 11,- fillColor: _isCreateButtonEnabled+ fillColor: isCreateButtonEnabled? Theme.of(context).colorScheme.primary: Theme.of(context).disabledColor,- hoverColor: _isCreateButtonEnabled+ hoverColor: isCreateButtonEnabled? Theme.of(context).colorScheme.primaryContainer: Theme.of(context).disabledColor,fontColor: Theme.of(context).colorScheme.onPrimary,padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),- onPressed: _isCreateButtonEnabled+ onPressed: isCreateButtonEnabled? () {context.read<ChecklistCellBloc>().add(ChecklistCellEvent.createNewTask(- _textEditingController.text,+ textController.text,),);widget.focusNode.requestFocus();- _textEditingController.clear();+ textController.clear();}: null,),@@ -408,12 +479,12 @@ class _NewTaskItemState extends State<NewTaskItem> {}void _createNewTask(BuildContext context) {- final taskDescription = _textEditingController.text;+ final taskDescription = textController.text;if (taskDescription.isNotEmpty) {context.read<ChecklistCellBloc>().add(ChecklistCellEvent.createNewTask(taskDescription));- _textEditingController.clear();+ textController.clear();}widget.focusNode.requestFocus();}diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/checklist_cell_textfield.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/checklist_cell_textfield.dartindex 9d01340226..d6435e8d34 100644--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/checklist_cell_textfield.dart+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/checklist_cell_textfield.dart@@ -40,23 +40,22 @@ class ChecklistCellTextfield extends StatelessWidget {super.key,required this.textController,required this.focusNode,- required this.autofocus,- required this.onChanged,+ this.onChanged,+ this.contentPadding = const EdgeInsets.symmetric(+ vertical: 10,+ horizontal: 2,+ ),this.onSubmitted,});final TextEditingController textController;final FocusNode focusNode;- final bool autofocus;+ final EdgeInsetsGeometry contentPadding;final VoidCallback? onSubmitted;- final VoidCallback onChanged;+ final VoidCallback? onChanged;@overrideWidget build(BuildContext context) {- const contentPadding = EdgeInsets.symmetric(- vertical: 6.0,- horizontal: 2.0,- );return TextField(controller: textController,focusNode: focusNode,@@ -65,11 +64,12 @@ class ChecklistCellTextfield extends StatelessWidget {decoration: InputDecoration(border: InputBorder.none,isCollapsed: true,+ isDense: true,contentPadding: contentPadding,hintText: LocaleKeys.grid_checklist_taskHint.tr(),),textInputAction: onSubmitted == null ? TextInputAction.next : null,- onChanged: (_) => onChanged(),+ onChanged: (_) => onChanged?.call(),onSubmitted: (_) => onSubmitted?.call(),);}diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/mobile_checklist_cell_editor.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/mobile_checklist_cell_editor.dartindex b8054bb7a7..6e86d88e5b 100644--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/mobile_checklist_cell_editor.dart+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/mobile_checklist_cell_editor.dart@@ -27,21 +27,17 @@ class _MobileChecklistCellEditScreenStateWidget build(BuildContext context) {return ConstrainedBox(constraints: const BoxConstraints.tightFor(height: 420),- child: BlocBuilder<ChecklistCellBloc, ChecklistCellState>(- builder: (context, state) {- return Column(- mainAxisSize: MainAxisSize.min,- children: [- const DragHandle(),- Padding(- padding: const EdgeInsets.symmetric(horizontal: 8.0),- child: _buildHeader(context),- ),- const Divider(),- const Expanded(child: _TaskList()),- ],- );- },+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ const DragHandle(),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 8.0),+ child: _buildHeader(context),+ ),+ const Divider(),+ const Expanded(child: _TaskList()),+ ],),);}@@ -75,19 +71,42 @@ class _TaskList extends StatelessWidget {state.tasks.mapIndexed((index, task) => _ChecklistItem(+ key: ValueKey('mobile_checklist_task_${task.data.id}'),task: task,- autofocus: state.newTask && index == state.tasks.length - 1,+ index: index,+ autofocus: state.phantomIndex != null &&+ index == state.tasks.length - 1,+ onAutofocus: () {+ context+ .read<ChecklistCellBloc>()+ .add(const ChecklistCellEvent.updatePhantomIndex(null));+ },),).toList(),);- cells.add(const _NewTaskButton());+ cells.add(+ const _NewTaskButton(key: ValueKey('mobile_checklist_new_task')),+ );- return ListView.separated(+ return ReorderableListView.builder(+ shrinkWrap: true,+ proxyDecorator: (child, index, _) => Material(+ color: Colors.transparent,+ child: BlocProvider.value(+ value: context.read<ChecklistCellBloc>(),+ child: child,+ ),+ ),+ buildDefaultDragHandles: false,itemCount: cells.length,- separatorBuilder: (_, __) => const VSpace(8),- itemBuilder: (_, int index) => cells[index],+ itemBuilder: (_, index) => cells[index],padding: const EdgeInsets.only(bottom: 12.0),+ onReorder: (from, to) {+ context+ .read<ChecklistCellBloc>()+ .add(ChecklistCellEvent.reorderTask(from, to));+ },);},);@@ -95,26 +114,37 @@ class _TaskList extends StatelessWidget {}class _ChecklistItem extends StatefulWidget {- const _ChecklistItem({required this.task, required this.autofocus});+ const _ChecklistItem({+ super.key,+ required this.task,+ required this.index,+ required this.autofocus,+ this.onAutofocus,+ });final ChecklistSelectOption task;+ final int index;final bool autofocus;+ final VoidCallback? onAutofocus;@overrideState<_ChecklistItem> createState() => _ChecklistItemState();}class _ChecklistItemState extends State<_ChecklistItem> {- late final TextEditingController _textController;- final FocusNode _focusNode = FocusNode();+ late final TextEditingController textController;+ final FocusNode focusNode = FocusNode();Timer? _debounceOnChanged;@overridevoid initState() {super.initState();- _textController = TextEditingController(text: widget.task.data.name);+ textController = TextEditingController(text: widget.task.data.name);if (widget.autofocus) {- _focusNode.requestFocus();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ focusNode.requestFocus();+ widget.onAutofocus?.call();+ });}}@@ -122,47 +152,50 @@ class _ChecklistItemState extends State<_ChecklistItem> {void didUpdateWidget(covariant oldWidget) {super.didUpdateWidget(oldWidget);if (widget.task.data.name != oldWidget.task.data.name &&- !_focusNode.hasFocus) {- _textController.text = widget.task.data.name;+ !focusNode.hasFocus) {+ textController.text = widget.task.data.name;}}@overridevoid dispose() {- _textController.dispose();- _focusNode.dispose();+ textController.dispose();+ focusNode.dispose();super.dispose();}@overrideWidget build(BuildContext context) {return Container(- padding: const EdgeInsets.symmetric(horizontal: 5),+ padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 4),constraints: const BoxConstraints(minHeight: 44),child: Row(children: [- InkWell(- borderRadius: BorderRadius.circular(22),- onTap: () => context- .read<ChecklistCellBloc>()- .add(ChecklistCellEvent.selectTask(widget.task.data.id)),- child: SizedBox.square(- dimension: 44,- child: Center(- child: FlowySvg(- widget.task.isSelected- ? FlowySvgs.check_filled_s- : FlowySvgs.uncheck_s,- size: const Size.square(20.0),- blendMode: BlendMode.dst,+ ReorderableDelayedDragStartListener(+ index: widget.index,+ child: InkWell(+ borderRadius: BorderRadius.circular(22),+ onTap: () => context+ .read<ChecklistCellBloc>()+ .add(ChecklistCellEvent.selectTask(widget.task.data.id)),+ child: SizedBox.square(+ dimension: 44,+ child: Center(+ child: FlowySvg(+ widget.task.isSelected+ ? FlowySvgs.check_filled_s+ : FlowySvgs.uncheck_s,+ size: const Size.square(20.0),+ blendMode: BlendMode.dst,+ ),),),),),Expanded(child: TextField(- controller: _textController,- focusNode: _focusNode,+ controller: textController,+ focusNode: focusNode,style: Theme.of(context).textTheme.bodyMedium,keyboardType: TextInputType.multiline,maxLines: null,@@ -261,7 +294,7 @@ class _ChecklistItemState extends State<_ChecklistItem> {}class _NewTaskButton extends StatelessWidget {- const _NewTaskButton();+ const _NewTaskButton({super.key});@overrideWidget build(BuildContext context) {@@ -270,6 +303,9 @@ class _NewTaskButton extends StatelessWidget {child: InkWell(borderRadius: BorderRadius.circular(12),onTap: () {+ context+ .read<ChecklistCellBloc>()+ .add(const ChecklistCellEvent.updatePhantomIndex(-1));context.read<ChecklistCellBloc>().add(const ChecklistCellEvent.createNewTask(""));diff --git a/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/checklist_cell_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/checklist_cell_bloc_test.dartnew file mode 100644index 0000000000..441ffea556--- /dev/null+++ b/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/checklist_cell_bloc_test.dart@@ -0,0 +1,154 @@+import 'package:appflowy/plugins/database/application/cell/bloc/checklist_cell_bloc.dart';+import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';+import 'package:appflowy/plugins/database/domain/field_service.dart';+import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pbenum.dart';+import 'package:flutter_test/flutter_test.dart';++import '../util.dart';++void main() {+ late AppFlowyGridTest cellTest;++ setUpAll(() async {+ cellTest = await AppFlowyGridTest.ensureInitialized();+ });++ group('checklist cell bloc:', () {+ late GridTestContext context;+ late ChecklistCellController cellController;++ setUp(() async {+ context = await cellTest.makeDefaultTestGrid();+ await FieldBackendService.createField(+ viewId: context.viewId,+ fieldType: FieldType.Checklist,+ );+ await gridResponseFuture();+ final fieldIndex = context.fieldController.fieldInfos+ .indexWhere((field) => field.fieldType == FieldType.Checklist);+ cellController = context.makeGridCellController(fieldIndex, 0).as();+ });++ test('create tasks', () async {+ final bloc = ChecklistCellBloc(cellController: cellController);+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 0);++ bloc.add(const ChecklistCellEvent.createNewTask("B"));+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 1);++ bloc.add(const ChecklistCellEvent.createNewTask("A", index: 0));+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 2);+ expect(bloc.state.tasks.first.data.name, "A");+ expect(bloc.state.tasks.last.data.name, "B");+ });++ test('rename task', () async {+ final bloc = ChecklistCellBloc(cellController: cellController);+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 0);++ bloc.add(const ChecklistCellEvent.createNewTask("B"));+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 1);+ expect(bloc.state.tasks.first.data.name, "B");++ bloc.add(+ ChecklistCellEvent.updateTaskName(bloc.state.tasks.first.data, "A"),+ );+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 1);+ expect(bloc.state.tasks.first.data.name, "A");+ });++ test('select task', () async {+ final bloc = ChecklistCellBloc(cellController: cellController);+ await gridResponseFuture();++ bloc.add(const ChecklistCellEvent.createNewTask("A"));+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 1);+ expect(bloc.state.tasks.first.isSelected, false);++ bloc.add(const ChecklistCellEvent.selectTask('A'));+ await gridResponseFuture();++ expect(bloc.state.tasks.first.isSelected, false);++ bloc.add(+ ChecklistCellEvent.selectTask(bloc.state.tasks.first.data.id),+ );+ await gridResponseFuture();++ expect(bloc.state.tasks.first.isSelected, true);+ });++ test('delete task', () async {+ final bloc = ChecklistCellBloc(cellController: cellController);+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 0);++ bloc.add(const ChecklistCellEvent.createNewTask("A"));+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 1);+ expect(bloc.state.tasks.first.isSelected, false);++ bloc.add(const ChecklistCellEvent.deleteTask('A'));+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 1);++ bloc.add(+ ChecklistCellEvent.deleteTask(bloc.state.tasks.first.data.id),+ );+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 0);+ });++ test('reorder task', () async {+ final bloc = ChecklistCellBloc(cellController: cellController);+ await gridResponseFuture();++ bloc.add(const ChecklistCellEvent.createNewTask("A"));+ await gridResponseFuture();+ bloc.add(const ChecklistCellEvent.createNewTask("B"));+ await gridResponseFuture();+ bloc.add(const ChecklistCellEvent.createNewTask("C"));+ await gridResponseFuture();+ bloc.add(const ChecklistCellEvent.createNewTask("D"));+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 4);++ bloc.add(const ChecklistCellEvent.reorderTask(0, 2));+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 4);+ expect(bloc.state.tasks[0].data.name, "B");+ expect(bloc.state.tasks[1].data.name, "A");+ expect(bloc.state.tasks[2].data.name, "C");+ expect(bloc.state.tasks[3].data.name, "D");++ bloc.add(const ChecklistCellEvent.reorderTask(3, 1));+ await gridResponseFuture();++ expect(bloc.state.tasks.length, 4);+ expect(bloc.state.tasks[0].data.name, "B");+ expect(bloc.state.tasks[1].data.name, "D");+ expect(bloc.state.tasks[2].data.name, "A");+ expect(bloc.state.tasks[3].data.name, "C");+ });+ });+}diff --git a/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/select_option_cell_test.dart b/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/select_option_cell_test.dartindex ae7c2d6bec..4e15d3aaa7 100644--- a/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/select_option_cell_test.dart+++ b/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/select_option_cell_test.dart@@ -20,7 +20,7 @@ void main() {setUp(() async {context = await cellTest.makeDefaultTestGrid();- await RowBackendService.createRow(viewId: context.view.id);+ await RowBackendService.createRow(viewId: context.viewId);final fieldIndex = context.fieldController.fieldInfos.indexWhere((field) => field.fieldType == FieldType.SingleSelect);cellController = context.makeGridCellController(fieldIndex, 0).as();diff --git a/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/text_cell_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/text_cell_bloc_test.dartindex 699c129e5f..bcd39265d0 100644--- a/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/text_cell_bloc_test.dart+++ b/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/text_cell_bloc_test.dart@@ -21,7 +21,7 @@ void main() {setUp(() async {context = await cellTest.makeDefaultTestGrid();- await RowBackendService.createRow(viewId: context.view.id);+ await RowBackendService.createRow(viewId: context.viewId);final fieldIndex = context.fieldController.fieldInfos.indexWhere((field) => field.fieldType == FieldType.RichText);cellController = context.makeGridCellController(fieldIndex, 0).as();@@ -47,7 +47,7 @@ void main() {await primaryBloc.close();await FieldBackendService.createField(- viewId: context.view.id,+ viewId: context.viewId,fieldName: "Second",);await gridResponseFuture();@@ -69,7 +69,7 @@ void main() {expect(bloc.state.wrap, true);await FieldSettingsBackendService(- viewId: context.view.id,+ viewId: context.viewId,).updateFieldSettings(fieldId: cellController.fieldId,wrapCellContent: false,@@ -85,7 +85,7 @@ void main() {expect(bloc.state.emoji!.value, "");- await RowBackendService(viewId: context.view.id)+ await RowBackendService(viewId: context.viewId).updateMeta(rowId: cellController.rowId, iconURL: "dummy");await gridResponseFuture();@@ -99,7 +99,7 @@ void main() {expect(bloc.state.hasDocument!.value, false);- await RowBackendService(viewId: context.view.id)+ await RowBackendService(viewId: context.viewId).updateMeta(rowId: cellController.rowId, isDocumentEmpty: false);await gridResponseFuture();diff --git a/frontend/appflowy_flutter/test/bloc_test/grid_test/field/field_cell_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/grid_test/field/field_cell_bloc_test.dartindex 334f60ee4c..a1fd6d35cc 100644--- a/frontend/appflowy_flutter/test/bloc_test/grid_test/field/field_cell_bloc_test.dart+++ b/frontend/appflowy_flutter/test/bloc_test/grid_test/field/field_cell_bloc_test.dart@@ -23,7 +23,7 @@ void main() {'update field width',build: () => FieldCellBloc(fieldInfo: context.fieldController.fieldInfos[0],- viewId: context.view.id,+ viewId: context.viewId,),act: (bloc) {width = bloc.state.width;@@ -39,7 +39,7 @@ void main() {blocTest('field width should not be less than 50px',build: () => FieldCellBloc(- viewId: context.view.id,+ viewId: context.viewId,fieldInfo: context.fieldController.fieldInfos[0],),act: (bloc) {diff --git a/frontend/appflowy_flutter/test/bloc_test/grid_test/field/field_editor_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/grid_test/field/field_editor_bloc_test.dartindex 8b4fa1ed89..c46ea5532b 100644--- a/frontend/appflowy_flutter/test/bloc_test/grid_test/field/field_editor_bloc_test.dart+++ b/frontend/appflowy_flutter/test/bloc_test/grid_test/field/field_editor_bloc_test.dart@@ -22,7 +22,7 @@ void main() {final fieldInfo = context.fieldController.fieldInfos.firstWhere((field) => field.fieldType == FieldType.SingleSelect);editorBloc = FieldEditorBloc(- viewId: context.view.id,+ viewId: context.viewId,fieldController: context.fieldController,fieldInfo: fieldInfo,isNew: false,diff --git a/frontend/appflowy_flutter/test/bloc_test/grid_test/filter/filter_editor_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/grid_test/filter/filter_editor_bloc_test.dartindex 6f139484c4..f5068282a9 100644--- a/frontend/appflowy_flutter/test/bloc_test/grid_test/filter/filter_editor_bloc_test.dart+++ b/frontend/appflowy_flutter/test/bloc_test/grid_test/filter/filter_editor_bloc_test.dart@@ -22,7 +22,7 @@ void main() {setUp(() async {context = await gridTest.makeDefaultTestGrid();filterBloc = FilterEditorBloc(- viewId: context.view.id,+ viewId: context.viewId,fieldController: context.fieldController,);});@@ -38,7 +38,7 @@ void main() {// through domain directlyfinal textField = getFirstFieldByType(FieldType.RichText);- final service = FilterBackendService(viewId: context.view.id);+ final service = FilterBackendService(viewId: context.viewId);await service.insertTextFilter(fieldId: textField.id,condition: TextFilterConditionPB.TextIsEmpty,@@ -105,7 +105,7 @@ void main() {});test('update filter', () async {- final service = FilterBackendService(viewId: context.view.id);+ final service = FilterBackendService(viewId: context.viewId);final textField = getFirstFieldByType(FieldType.RichText);// Create filter@@ -144,7 +144,7 @@ void main() {// edit fieldawait FieldBackendService(- viewId: context.view.id,+ viewId: context.viewId,fieldId: textField.id,).updateField(name: "New Name");await gridResponseFuture();@@ -160,7 +160,7 @@ void main() {// edit fieldawait FieldBackendService(- viewId: context.view.id,+ viewId: context.viewId,fieldId: checkboxField.id,).updateType(fieldType: FieldType.DateTime);await gridResponseFuture();@@ -179,7 +179,7 @@ void main() {// edit fieldawait FieldBackendService(- viewId: context.view.id,+ viewId: context.viewId,fieldId: checkboxField.id,).updateField(name: "HERRO");await gridResponseFuture();diff --git a/frontend/appflowy_flutter/test/bloc_test/grid_test/sort/sort_editor_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/grid_test/sort/sort_editor_bloc_test.dartindex 91cb81b0c2..a0abebd214 100644--- a/frontend/appflowy_flutter/test/bloc_test/grid_test/sort/sort_editor_bloc_test.dart+++ b/frontend/appflowy_flutter/test/bloc_test/grid_test/sort/sort_editor_bloc_test.dart@@ -20,7 +20,7 @@ void main() {setUp(() async {context = await gridTest.makeDefaultTestGrid();sortBloc = SortEditorBloc(- viewId: context.view.id,+ viewId: context.viewId,fieldController: context.fieldController,);});@@ -170,7 +170,7 @@ void main() {// edit fieldawait FieldBackendService(- viewId: context.view.id,+ viewId: context.viewId,fieldId: selectOptionField.id,).updateField(name: "HERRO");await gridResponseFuture();@@ -191,7 +191,7 @@ void main() {// edit fieldawait FieldBackendService(- viewId: context.view.id,+ viewId: context.viewId,fieldId: selectOptionField.id,).delete();await gridResponseFuture();diff --git a/frontend/appflowy_flutter/test/bloc_test/grid_test/util.dart b/frontend/appflowy_flutter/test/bloc_test/grid_test/util.dartindex 8629461172..518b9dba54 100644--- a/frontend/appflowy_flutter/test/bloc_test/grid_test/util.dart+++ b/frontend/appflowy_flutter/test/bloc_test/grid_test/util.dart@@ -25,6 +25,8 @@ class GridTestContext {final ViewPB view;final DatabaseController databaseController;+ String get viewId => view.id;+List<RowInfo> get rowInfos {return databaseController.rowCache.rowInfos;}diff --git a/frontend/rust-lib/event-integration-test/src/database_event.rs b/frontend/rust-lib/event-integration-test/src/database_event.rsindex 3aecfba5d7..fd7bd9c4d5 100644--- a/frontend/rust-lib/event-integration-test/src/database_event.rs+++ b/frontend/rust-lib/event-integration-test/src/database_event.rs@@ -11,6 +11,7 @@ use collab_database::rows::{Row, RowId};use flowy_database2::entities::*;use flowy_database2::event_map::DatabaseEvent;use flowy_database2::services::cell::CellBuilder;+use flowy_database2::services::field::ChecklistCellInsertChangeset;use flowy_database2::services::share::csv::CSVFormat;use flowy_folder::entities::*;use flowy_folder::event_map::FolderEvent;@@ -656,11 +657,11 @@ impl<'a> TestRowBuilder<'a> {multi_select_field.id.clone()}- pub fn insert_checklist_cell(&mut self, options: Vec<(String, bool)>) -> String {+ pub fn insert_checklist_cell(&mut self, new_tasks: Vec<ChecklistCellInsertChangeset>) -> String {let checklist_field = self.field_with_type(&FieldType::Checklist);self.cell_build- .insert_checklist_cell(&checklist_field.id, options);+ .insert_checklist_cell(&checklist_field.id, new_tasks);checklist_field.id.clone()}diff --git a/frontend/rust-lib/event-integration-test/tests/database/local_test/test.rs b/frontend/rust-lib/event-integration-test/tests/database/local_test/test.rsindex a1f5b1f8e8..36f3d8ea32 100644--- a/frontend/rust-lib/event-integration-test/tests/database/local_test/test.rs+++ b/frontend/rust-lib/event-integration-test/tests/database/local_test/test.rs@@ -5,9 +5,10 @@ use bytes::Bytes;use event_integration_test::event_builder::EventBuilder;use event_integration_test::EventIntegrationTest;use flowy_database2::entities::{- CellChangesetPB, CellIdPB, CheckboxCellDataPB, ChecklistCellDataChangesetPB, DatabaseLayoutPB,- DatabaseSettingChangesetPB, DatabaseViewIdPB, DateCellChangesetPB, FieldType,- OrderObjectPositionPB, RelationCellChangesetPB, SelectOptionCellDataPB, UpdateRowMetaChangesetPB,+ CellChangesetPB, CellIdPB, CheckboxCellDataPB, ChecklistCellDataChangesetPB,+ ChecklistCellInsertPB, DatabaseLayoutPB, DatabaseSettingChangesetPB, DatabaseViewIdPB,+ DateCellChangesetPB, FieldType, OrderObjectPositionPB, RelationCellChangesetPB,+ SelectOptionCellDataPB, UpdateRowMetaChangesetPB,};use lib_infra::util::timestamp;@@ -620,17 +621,29 @@ async fn update_checklist_cell_test() {// update the checklist celllet changeset = ChecklistCellDataChangesetPB {- view_id: grid_view.id.clone(),- row_id: database.rows[0].id.clone(),- field_id: checklist_field.id.clone(),- insert_options: vec![- "task 1".to_string(),- "task 2".to_string(),- "task 3".to_string(),+ cell_id: CellIdPB {+ view_id: grid_view.id.clone(),+ row_id: database.rows[0].id.clone(),+ field_id: checklist_field.id.clone(),+ },+ insert_task: vec![+ ChecklistCellInsertPB {+ name: "task 1".to_string(),+ index: None,+ },+ ChecklistCellInsertPB {+ name: "task 2".to_string(),+ index: None,+ },+ ChecklistCellInsertPB {+ name: "task 3".to_string(),+ index: None,+ },],- selected_option_ids: vec![],- delete_option_ids: vec![],- update_options: vec![],+ completed_tasks: vec![],+ delete_tasks: vec![],+ update_tasks: vec![],+ reorder: "".to_string(),};test.update_checklist_cell(changeset).await;@@ -644,10 +657,12 @@ async fn update_checklist_cell_test() {// select some optionslet changeset = ChecklistCellDataChangesetPB {- view_id: grid_view.id.clone(),- row_id: database.rows[0].id.clone(),- field_id: checklist_field.id.clone(),- selected_option_ids: vec![cell.options[0].id.clone(), cell.options[1].id.clone()],+ cell_id: CellIdPB {+ view_id: grid_view.id.clone(),+ row_id: database.rows[0].id.clone(),+ field_id: checklist_field.id.clone(),+ },+ completed_tasks: vec![cell.options[0].id.clone(), cell.options[1].id.clone()],..Default::default()};test.update_checklist_cell(changeset).await;diff --git a/frontend/rust-lib/flowy-database2/src/entities/cell_entities.rs b/frontend/rust-lib/flowy-database2/src/entities/cell_entities.rsindex 94ecc9866b..9af549c698 100644--- a/frontend/rust-lib/flowy-database2/src/entities/cell_entities.rs+++ b/frontend/rust-lib/flowy-database2/src/entities/cell_entities.rs@@ -2,6 +2,8 @@ use collab_database::rows::RowId;use flowy_derive::ProtoBuf;use flowy_error::ErrorCode;+use lib_infra::validator_fn::required_not_empty_str;+use validator::Validate;use crate::entities::parser::NotEmptyStr;use crate::entities::FieldType;@@ -40,15 +42,18 @@ impl TryInto<CreateSelectOptionParams> for CreateSelectOptionPayloadPB {}}-#[derive(Debug, Clone, Default, ProtoBuf)]+#[derive(Debug, Clone, Default, ProtoBuf, Validate)]pub struct CellIdPB {#[pb(index = 1)]+ #[validate(custom(function = "required_not_empty_str"))]pub view_id: String,#[pb(index = 2)]+ #[validate(custom(function = "required_not_empty_str"))]pub field_id: String,#[pb(index = 3)]+ #[validate(custom(function = "required_not_empty_str"))]pub row_id: String,}diff --git a/frontend/rust-lib/flowy-database2/src/entities/type_option_entities/checklist_entities.rs b/frontend/rust-lib/flowy-database2/src/entities/type_option_entities/checklist_entities.rsindex fe9c665223..b62a0182df 100644--- a/frontend/rust-lib/flowy-database2/src/entities/type_option_entities/checklist_entities.rs+++ b/frontend/rust-lib/flowy-database2/src/entities/type_option_entities/checklist_entities.rs@@ -1,11 +1,7 @@-use collab_database::fields::select_type_option::SelectOption;-use collab_database::rows::RowId;-use flowy_derive::ProtoBuf;-use flowy_error::{ErrorCode, FlowyError};+use validator::Validate;-use crate::entities::parser::NotEmptyStr;-use crate::entities::SelectOptionPB;+use crate::entities::{CellIdPB, SelectOptionPB};#[derive(Debug, Clone, Default, ProtoBuf)]pub struct ChecklistCellDataPB {@@ -19,61 +15,33 @@ pub struct ChecklistCellDataPB {pub percentage: f64,}-#[derive(Debug, Clone, Default, ProtoBuf)]+#[derive(Debug, Clone, Default, ProtoBuf, Validate)]pub struct ChecklistCellDataChangesetPB {#[pb(index = 1)]- pub view_id: String,+ #[validate(nested)]+ pub cell_id: CellIdPB,#[pb(index = 2)]- pub field_id: String,+ pub insert_task: Vec<ChecklistCellInsertPB>,#[pb(index = 3)]- pub row_id: String,+ pub delete_tasks: Vec<String>,#[pb(index = 4)]- pub insert_options: Vec<String>,+ pub update_tasks: Vec<SelectOptionPB>,#[pb(index = 5)]- pub selected_option_ids: Vec<String>,+ pub completed_tasks: Vec<String>,#[pb(index = 6)]- pub delete_option_ids: Vec<String>,-- #[pb(index = 7)]- pub update_options: Vec<SelectOptionPB>,+ pub reorder: String,}-#[derive(Debug)]-pub struct ChecklistCellDataChangesetParams {- pub view_id: String,- pub field_id: String,- pub row_id: RowId,- pub insert_options: Vec<String>,- pub selected_option_ids: Vec<String>,- pub delete_option_ids: Vec<String>,- pub update_options: Vec<SelectOption>,-}--impl TryInto<ChecklistCellDataChangesetParams> for ChecklistCellDataChangesetPB {- type Error = FlowyError;-- fn try_into(self) -> Result<ChecklistCellDataChangesetParams, Self::Error> {- let view_id = NotEmptyStr::parse(self.view_id).map_err(|_| ErrorCode::ViewIdIsInvalid)?;- let field_id = NotEmptyStr::parse(self.field_id).map_err(|_| ErrorCode::FieldIdIsEmpty)?;- let row_id = NotEmptyStr::parse(self.row_id).map_err(|_| ErrorCode::RowIdIsEmpty)?;+#[derive(Debug, Clone, Default, ProtoBuf, Validate)]+pub struct ChecklistCellInsertPB {+ #[pb(index = 1)]+ pub name: String,- Ok(ChecklistCellDataChangesetParams {- view_id: view_id.0,- field_id: field_id.0,- row_id: RowId::from(row_id.0),- insert_options: self.insert_options,- selected_option_ids: self.selected_option_ids,- delete_option_ids: self.delete_option_ids,- update_options: self- .update_options- .into_iter()- .map(SelectOption::from)- .collect(),- })- }+ #[pb(index = 2, one_of)]+ pub index: Option<i32>,}diff --git a/frontend/rust-lib/flowy-database2/src/event_handler.rs b/frontend/rust-lib/flowy-database2/src/event_handler.rsindex 47633ee675..5f53088788 100644--- a/frontend/rust-lib/flowy-database2/src/event_handler.rs+++ b/frontend/rust-lib/flowy-database2/src/event_handler.rs@@ -684,26 +684,19 @@ pub(crate) async fn update_checklist_cell_handler(manager: AFPluginState<Weak<DatabaseManager>>,) -> Result<(), FlowyError> {let manager = upgrade_manager(manager)?;- let params: ChecklistCellDataChangesetParams = data.into_inner().try_into()?;+ let params = data.try_into_inner()?;let database_editor = manager- .get_database_editor_with_view_id(¶ms.view_id)+ .get_database_editor_with_view_id(¶ms.cell_id.view_id).await?;- let changeset = ChecklistCellChangeset {- insert_options: params- .insert_options- .into_iter()- .map(|name| (name, false))- .collect(),- selected_option_ids: params.selected_option_ids,- delete_option_ids: params.delete_option_ids,- update_options: params.update_options,- };++ let cell_id = params.cell_id.clone();+database_editor.update_cell_with_changeset(- ¶ms.view_id,- ¶ms.row_id,- ¶ms.field_id,- BoxAny::new(changeset),+ &cell_id.view_id,+ &(RowId::from(cell_id.row_id)),+ &cell_id.field_id,+ BoxAny::new(ChecklistCellChangeset::from(params)),).await?;Ok(())diff --git a/frontend/rust-lib/flowy-database2/src/services/cell/cell_operation.rs b/frontend/rust-lib/flowy-database2/src/services/cell/cell_operation.rsindex d4bb5dd742..15aecc0072 100644--- a/frontend/rust-lib/flowy-database2/src/services/cell/cell_operation.rs+++ b/frontend/rust-lib/flowy-database2/src/services/cell/cell_operation.rs@@ -192,9 +192,12 @@ pub fn insert_select_option_cell(option_ids: Vec<String>, field: &Field) -> Cellapply_cell_changeset(BoxAny::new(changeset), None, field, None).unwrap()}-pub fn insert_checklist_cell(insert_options: Vec<(String, bool)>, field: &Field) -> Cell {+pub fn insert_checklist_cell(+ insert_options: Vec<ChecklistCellInsertChangeset>,+ field: &Field,+) -> Cell {let changeset = ChecklistCellChangeset {- insert_options,+ insert_tasks: insert_options,..Default::default()};apply_cell_changeset(BoxAny::new(changeset), None, field, None).unwrap()@@ -350,13 +353,17 @@ impl<'a> CellBuilder<'a> {},}}- pub fn insert_checklist_cell(&mut self, field_id: &str, options: Vec<(String, bool)>) {+ pub fn insert_checklist_cell(+ &mut self,+ field_id: &str,+ new_tasks: Vec<ChecklistCellInsertChangeset>,+ ) {match self.field_maps.get(&field_id.to_owned()) {None => tracing::warn!("Can't find the field with id: {}", field_id),Some(field) => {self.cells- .insert(field_id.to_owned(), insert_checklist_cell(options, field));+ .insert(field_id.to_owned(), insert_checklist_cell(new_tasks, field));},}}diff --git a/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/checklist_entities.rs b/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/checklist_entities.rsindex 938e16e25d..41c5ca4468 100644--- a/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/checklist_entities.rs+++ b/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/checklist_entities.rs@@ -1,4 +1,4 @@-use crate::entities::FieldType;+use crate::entities::{ChecklistCellDataChangesetPB, FieldType};use crate::services::field::{TypeOptionCellData, CELL_DATA};use collab::util::AnyMapExt;use collab_database::fields::select_type_option::SelectOption;@@ -44,12 +44,12 @@ impl ChecklistCellData {((selected_options as f64) / (total_options as f64) * 100.0).round() / 100.0}- pub fn from_options(options: Vec<(String, bool)>) -> Self {- let (options, selected_ids): (Vec<_>, Vec<_>) = options+ pub fn from_options(new_tasks: Vec<ChecklistCellInsertChangeset>) -> Self {+ let (options, selected_ids): (Vec<_>, Vec<_>) = new_tasks.into_iter()- .map(|(name, is_selected)| {- let option = SelectOption::new(&name);- let selected_id = is_selected.then(|| option.id.clone());+ .map(|new_task| {+ let option = SelectOption::new(&new_task.name);+ let selected_id = new_task.is_complete.then(|| option.id.clone());(option, selected_id)}).unzip();@@ -82,11 +82,52 @@ impl From<ChecklistCellData> for Cell {#[derive(Debug, Clone, Default)]pub struct ChecklistCellChangeset {- /// List of option names that will be inserted- pub insert_options: Vec<(String, bool)>,- pub selected_option_ids: Vec<String>,- pub delete_option_ids: Vec<String>,- pub update_options: Vec<SelectOption>,+ pub insert_tasks: Vec<ChecklistCellInsertChangeset>,+ pub delete_tasks: Vec<String>,+ pub update_tasks: Vec<SelectOption>,+ pub completed_task_ids: Vec<String>,+ pub reorder: String,+}++impl From<ChecklistCellDataChangesetPB> for ChecklistCellChangeset {+ fn from(value: ChecklistCellDataChangesetPB) -> Self {+ ChecklistCellChangeset {+ insert_tasks: value+ .insert_task+ .into_iter()+ .map(|pb| ChecklistCellInsertChangeset {+ name: pb.name,+ is_complete: false,+ index: pb.index,+ })+ .collect(),+ delete_tasks: value.delete_tasks,+ update_tasks: value+ .update_tasks+ .into_iter()+ .map(SelectOption::from)+ .collect(),+ completed_task_ids: value.completed_tasks,+ reorder: value.reorder,+ }+ }+}++#[derive(Debug, Clone, Default)]+pub struct ChecklistCellInsertChangeset {+ pub name: String,+ pub is_complete: bool,+ pub index: Option<i32>,+}++impl ChecklistCellInsertChangeset {+ pub fn new(name: String, is_complete: bool) -> Self {+ Self {+ name,+ is_complete,+ index: None,+ }+ }}#[cfg(test)]diff --git a/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/checklist.rs b/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/checklist_type_option.rssimilarity index 83%rename from frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/checklist.rsrename to frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/checklist_type_option.rsindex 70106ab453..16ca43c60a 100644--- a/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/checklist.rs+++ b/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/checklist_type_option.rs@@ -78,7 +78,7 @@ impl CellDataChangeset for ChecklistTypeOption {Ok((Cell::from(cell_data.clone()), cell_data))},None => {- let cell_data = ChecklistCellData::from_options(changeset.insert_options);+ let cell_data = ChecklistCellData::from_options(changeset.insert_tasks);Ok((Cell::from(cell_data.clone()), cell_data))},}@@ -93,26 +93,26 @@ fn update_cell_data_with_changeset(// Delete the optionscell_data.options- .retain(|option| !changeset.delete_option_ids.contains(&option.id));+ .retain(|option| !changeset.delete_tasks.contains(&option.id));cell_data.selected_option_ids- .retain(|option_id| !changeset.delete_option_ids.contains(option_id));+ .retain(|option_id| !changeset.delete_tasks.contains(option_id));// Insert new options- changeset- .insert_options- .into_iter()- .for_each(|(option_name, is_selected)| {- let option = SelectOption::new(&option_name);- if is_selected {- cell_data.selected_option_ids.push(option.id.clone())- }- cell_data.options.push(option);- });+ changeset.insert_tasks.into_iter().for_each(|new_task| {+ let option = SelectOption::new(&new_task.name);+ if new_task.is_complete {+ cell_data.selected_option_ids.push(option.id.clone())+ }+ match new_task.index {+ Some(index) => cell_data.options.insert(index as usize, option),+ None => cell_data.options.push(option),+ };+ });// Update optionschangeset- .update_options+ .update_tasks.into_iter().for_each(|updated_option| {if let Some(option) = cell_data@@ -126,7 +126,7 @@ fn update_cell_data_with_changeset(// Select the optionschangeset- .selected_option_ids+ .completed_task_ids.into_iter().for_each(|option_id| {if let Some(index) = cell_data@@ -139,6 +139,21 @@ fn update_cell_data_with_changeset(cell_data.selected_option_ids.push(option_id);}});++ // Reorder+ let mut split = changeset.reorder.split(' ').take(2);+ if let (Some(from), Some(to)) = (split.next(), split.next()) {+ if let (Some(from_index), Some(to_index)) = (+ cell_data+ .options+ .iter()+ .position(|option| option.id == from),+ cell_data.options.iter().position(|option| option.id == to),+ ) {+ let option = cell_data.options.remove(from_index);+ cell_data.options.insert(to_index, option);+ }+ }}impl CellDataDecoder for ChecklistTypeOption {diff --git a/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/mod.rs b/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/mod.rsindex be51a38db8..b17047ef06 100644--- a/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/mod.rs+++ b/frontend/rust-lib/flowy-database2/src/services/field/type_options/checklist_type_option/mod.rs@@ -1,6 +1,7 @@-mod checklist;+#![allow(clippy::module_inception)]mod checklist_entities;mod checklist_filter;+mod checklist_type_option;-pub use checklist::*;pub use checklist_entities::*;+pub use checklist_type_option::*;diff --git a/frontend/rust-lib/flowy-database2/tests/database/cell_test/test.rs b/frontend/rust-lib/flowy-database2/tests/database/cell_test/test.rsindex 64453e8eb0..7cd6053f3a 100644--- a/frontend/rust-lib/flowy-database2/tests/database/cell_test/test.rs+++ b/frontend/rust-lib/flowy-database2/tests/database/cell_test/test.rs@@ -6,8 +6,8 @@ use collab_database::fields::select_type_option::{MultiSelectTypeOption, SingleSuse collab_database::fields::url_type_option::URLCellData;use flowy_database2::entities::{FieldType, MediaCellChangeset};use flowy_database2::services::field::{- ChecklistCellChangeset, DateCellChangeset, RelationCellChangeset, SelectOptionCellChangeset,- StringCellData, TimeCellData,+ ChecklistCellChangeset, ChecklistCellInsertChangeset, DateCellChangeset, RelationCellChangeset,+ SelectOptionCellChangeset, StringCellData, TimeCellData,};use lib_infra::box_any::BoxAny;use std::time::Duration;@@ -49,7 +49,10 @@ async fn grid_cell_update() {))},FieldType::Checklist => BoxAny::new(ChecklistCellChangeset {- insert_options: vec![("new option".to_string(), false)],+ insert_tasks: vec![ChecklistCellInsertChangeset::new(+ "new option".to_string(),+ false,+ )],..Default::default()}),FieldType::Checkbox => BoxAny::new("1".to_string()),diff --git a/frontend/rust-lib/flowy-database2/tests/database/database_editor.rs b/frontend/rust-lib/flowy-database2/tests/database/database_editor.rsindex 91d4a46cb5..22c9c7a536 100644--- a/frontend/rust-lib/flowy-database2/tests/database/database_editor.rs+++ b/frontend/rust-lib/flowy-database2/tests/database/database_editor.rs@@ -248,7 +248,7 @@ impl DatabaseEditorTest {.unwrap().clone();let cell_changeset = ChecklistCellChangeset {- selected_option_ids: selected_options,+ completed_task_ids: selected_options,..Default::default()};selfdiff --git a/frontend/rust-lib/flowy-database2/tests/database/mock_data/grid_mock_data.rs b/frontend/rust-lib/flowy-database2/tests/database/mock_data/grid_mock_data.rsindex 7e18dc9d91..208f82cc42 100644--- a/frontend/rust-lib/flowy-database2/tests/database/mock_data/grid_mock_data.rs+++ b/frontend/rust-lib/flowy-database2/tests/database/mock_data/grid_mock_data.rs@@ -17,7 +17,9 @@ use event_integration_test::database_event::TestRowBuilder;use flowy_database2::entities::FieldType;use flowy_database2::services::field::summary_type_option::summary::SummarizationTypeOption;use flowy_database2::services::field::translate_type_option::translate::TranslateTypeOption;-use flowy_database2::services::field::{ChecklistTypeOption, FieldBuilder, RelationTypeOption};+use flowy_database2::services::field::{+ ChecklistCellInsertChangeset, ChecklistTypeOption, FieldBuilder, RelationTypeOption,+};use flowy_database2::services::field_settings::default_field_settings_for_fields;pub fn make_test_grid() -> DatabaseData {@@ -189,7 +191,10 @@ pub fn make_test_grid() -> DatabaseData {row_builder.insert_url_cell("AppFlowy website - https://www.appflowy.io")},FieldType::Checklist => {- row_builder.insert_checklist_cell(vec![("First thing".to_string(), false)])+ row_builder.insert_checklist_cell(vec![ChecklistCellInsertChangeset::new(+ "First thing".to_string(),+ false,+ )])},FieldType::Time => row_builder.insert_time_cell(75),_ => "".to_owned(),@@ -208,11 +213,11 @@ pub fn make_test_grid() -> DatabaseData {.insert_multi_select_cell(|mut options| vec![options.remove(0), options.remove(1)]),FieldType::Checkbox => row_builder.insert_checkbox_cell("true"),FieldType::Checklist => row_builder.insert_checklist_cell(vec![- ("Have breakfast".to_string(), true),- ("Have lunch".to_string(), true),- ("Take a nap".to_string(), false),- ("Have dinner".to_string(), true),- ("Shower and head to bed".to_string(), false),+ ChecklistCellInsertChangeset::new("Have breakfast".to_string(), true),+ ChecklistCellInsertChangeset::new("Have lunch".to_string(), true),+ ChecklistCellInsertChangeset::new("Take a nap".to_string(), false),+ ChecklistCellInsertChangeset::new("Have dinner".to_string(), true),+ ChecklistCellInsertChangeset::new("Shower and head to bed".to_string(), false),]),_ => "".to_owned(),};@@ -250,7 +255,10 @@ pub fn make_test_grid() -> DatabaseData {},FieldType::Checkbox => row_builder.insert_checkbox_cell("false"),FieldType::Checklist => {- row_builder.insert_checklist_cell(vec![("Task 1".to_string(), true)])+ row_builder.insert_checklist_cell(vec![ChecklistCellInsertChangeset::new(+ "Task 1".to_string(),+ true,+ )])},_ => "".to_owned(),};@@ -290,9 +298,9 @@ pub fn make_test_grid() -> DatabaseData {},FieldType::Checkbox => row_builder.insert_checkbox_cell("true"),FieldType::Checklist => row_builder.insert_checklist_cell(vec![- ("Sprint".to_string(), true),- ("Sprint some more".to_string(), false),- ("Rest".to_string(), true),+ ChecklistCellInsertChangeset::new("Sprint".to_string(), true),+ ChecklistCellInsertChangeset::new("Sprint some more".to_string(), false),+ ChecklistCellInsertChangeset::new("Rest".to_string(), true),]),_ => "".to_owned(),};