Skip to content

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.

feat(flutter): date picker improvements (#6582)

Richard Shiue6a5c4c95b713
diff --git a/frontend/appflowy_flutter/integration_test/desktop/board/board_hide_groups_test.dart b/frontend/appflowy_flutter/integration_test/desktop/board/board_hide_groups_test.dart
index a83372fcc6..15da47f0f1 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/board/board_hide_groups_test.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/board/board_hide_groups_test.dart
@@ -4,7 +4,6 @@ import 'package:appflowy/plugins/database/board/presentation/widgets/board_colum
import 'package:appflowy/plugins/database/board/presentation/widgets/board_hidden_groups.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:easy_localization/easy_localization.dart';
-import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
@@ -121,22 +120,3 @@ void main() {
});
});
}
-
-extension FlowySvgFinder on CommonFinders {
- Finder byFlowySvg(FlowySvgData svg) => _FlowySvgFinder(svg);
-}
-
-class _FlowySvgFinder extends MatchFinder {
- _FlowySvgFinder(this.svg);
-
- final FlowySvgData svg;
-
- @override
- String get description => 'flowy_svg "$svg"';
-
- @override
- bool matches(Element candidate) {
- final Widget widget = candidate.widget;
- return widget is FlowySvg && widget.svg == svg;
- }
-}
diff --git a/frontend/appflowy_flutter/integration_test/desktop/database/database_cell_test.dart b/frontend/appflowy_flutter/integration_test/desktop/database/database_cell_test.dart
index 7cc87d86e0..62e95cf6a8 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/database/database_cell_test.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/database/database_cell_test.dart
@@ -212,6 +212,7 @@ void main() {
// Select a date
final now = DateTime.now();
+ final expected = DateTime(now.year, now.month, now.day);
await tester.selectDay(content: now.day);
await tester.dismissCellEditor();
@@ -219,7 +220,7 @@ void main() {
tester.assertCellContent(
rowIndex: 0,
fieldType: FieldType.DateTime,
- content: DateFormat('MMM dd, y').format(now),
+ content: DateFormat('MMM dd, y').format(expected),
);
await tester.tapCellInGrid(rowIndex: 0, fieldType: fieldType);
@@ -233,7 +234,7 @@ void main() {
tester.assertCellContent(
rowIndex: 0,
fieldType: FieldType.DateTime,
- content: DateFormat('MMM dd, y HH:mm').format(now),
+ content: DateFormat('MMM dd, y HH:mm').format(expected),
);
await tester.tapCellInGrid(rowIndex: 0, fieldType: fieldType);
@@ -248,7 +249,7 @@ void main() {
tester.assertCellContent(
rowIndex: 0,
fieldType: FieldType.DateTime,
- content: DateFormat('dd/MM/y HH:mm').format(now),
+ content: DateFormat('dd/MM/y HH:mm').format(expected),
);
await tester.tapCellInGrid(rowIndex: 0, fieldType: fieldType);
@@ -263,7 +264,7 @@ void main() {
tester.assertCellContent(
rowIndex: 0,
fieldType: FieldType.DateTime,
- content: DateFormat('dd/MM/y hh:mm a').format(now),
+ content: DateFormat('dd/MM/y hh:mm a').format(expected),
);
await tester.tapCellInGrid(rowIndex: 0, fieldType: fieldType);
diff --git a/frontend/appflowy_flutter/integration_test/desktop/database/database_field_test.dart b/frontend/appflowy_flutter/integration_test/desktop/database/database_field_test.dart
index b2871ffd31..32acd51369 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/database/database_field_test.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/database/database_field_test.dart
@@ -292,6 +292,7 @@ void main() {
await tester.tapCellInGrid(rowIndex: 0, fieldType: FieldType.DateTime);
await tester.toggleIncludeTime();
final now = DateTime.now();
+ final expected = DateTime(now.year, now.month, now.day);
await tester.selectDay(content: now.day);
await tester.dismissCellEditor();
@@ -299,7 +300,7 @@ void main() {
tester.assertCellContent(
rowIndex: 0,
fieldType: FieldType.DateTime,
- content: DateFormat('MMM dd, y HH:mm').format(now),
+ content: DateFormat('MMM dd, y HH:mm').format(expected),
);
// open editor and change date & time format
@@ -313,7 +314,7 @@ void main() {
tester.assertCellContent(
rowIndex: 0,
fieldType: FieldType.DateTime,
- content: DateFormat('dd/MM/y hh:mm a').format(now),
+ content: DateFormat('dd/MM/y hh:mm a').format(expected),
);
});
@@ -540,6 +541,7 @@ void main() {
await tester.tapCellInGrid(rowIndex: 0, fieldType: FieldType.DateTime);
await tester.toggleIncludeTime();
final now = DateTime.now();
+ final expected = DateTime(now.year, now.month, now.day);
await tester.selectDay(content: now.day);
await tester.dismissCellEditor();
@@ -547,7 +549,7 @@ void main() {
tester.assertCellContent(
rowIndex: 0,
fieldType: FieldType.DateTime,
- content: DateFormat('MMM dd, y HH:mm').format(now),
+ content: DateFormat('MMM dd, y HH:mm').format(expected),
);
await tester.changeFieldTypeOfFieldWithName(
@@ -557,7 +559,7 @@ void main() {
tester.assertCellContent(
rowIndex: 0,
fieldType: FieldType.RichText,
- content: DateFormat('MMM dd, y HH:mm').format(now),
+ content: DateFormat('MMM dd, y HH:mm').format(expected),
cellIndex: 1,
);
@@ -581,8 +583,7 @@ void main() {
tester.assertCellContent(
rowIndex: 0,
fieldType: FieldType.DateTime,
- content: DateFormat('MMM dd, y').format(now),
- // content: DateFormat('MMM dd, y HH:mm').format(now),
+ content: DateFormat('MMM dd, y').format(expected),
);
tester.assertCellContent(
rowIndex: 1,
diff --git a/frontend/appflowy_flutter/integration_test/desktop/database/database_media_test.dart b/frontend/appflowy_flutter/integration_test/desktop/database/database_media_test.dart
index 43f6f1f4a5..2703c3ebc6 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/database/database_media_test.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/database/database_media_test.dart
@@ -21,7 +21,6 @@ import 'package:path_provider/path_provider.dart';
import '../../shared/database_test_op.dart';
import '../../shared/mock/mock_file_picker.dart';
import '../../shared/util.dart';
-import '../board/board_hide_groups_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
diff --git a/frontend/appflowy_flutter/integration_test/desktop/document/document_inline_sub_page_test.dart b/frontend/appflowy_flutter/integration_test/desktop/document/document_inline_sub_page_test.dart
index 51942a96f6..c2083009c2 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/document/document_inline_sub_page_test.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/document/document_inline_sub_page_test.dart
@@ -14,7 +14,6 @@ import 'package:integration_test/integration_test.dart';
import '../../shared/keyboard.dart';
import '../../shared/util.dart';
-import '../board/board_hide_groups_test.dart';
const _firstDocName = "Inline Sub Page Mention";
const _createdPageName = "hi world";
diff --git a/frontend/appflowy_flutter/integration_test/desktop/document/document_with_date_reminder_test.dart b/frontend/appflowy_flutter/integration_test/desktop/document/document_with_date_reminder_test.dart
index 0eda885abb..da59e30a04 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/document/document_with_date_reminder_test.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/document/document_with_date_reminder_test.dart
@@ -10,7 +10,6 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import '../../shared/util.dart';
-import '../board/board_hide_groups_test.dart';
void main() {
setUp(() {
@@ -63,7 +62,7 @@ void main() {
widget is TextField && widget.controller!.text == currentTime,
);
await tester.enterText(textField, "11:12");
- await tester.editor.tapLineOfEditorAt(0);
+ await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pumpAndSettle();
// we will get field with current date and 11:12 as time
diff --git a/frontend/appflowy_flutter/integration_test/desktop/document/document_with_multi_image_block_test.dart b/frontend/appflowy_flutter/integration_test/desktop/document/document_with_multi_image_block_test.dart
index d85e6c631e..0f4057be7a 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/document/document_with_multi_image_block_test.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/document/document_with_multi_image_block_test.dart
@@ -26,7 +26,6 @@ import 'package:path_provider/path_provider.dart';
import '../../shared/mock/mock_file_picker.dart';
import '../../shared/util.dart';
-import '../board/board_hide_groups_test.dart';
void main() {
setUp(() {
diff --git a/frontend/appflowy_flutter/integration_test/desktop/settings/shortcuts_settings_test.dart b/frontend/appflowy_flutter/integration_test/desktop/settings/shortcuts_settings_test.dart
index 5e1227fb6c..7913a88294 100644
--- a/frontend/appflowy_flutter/integration_test/desktop/settings/shortcuts_settings_test.dart
+++ b/frontend/appflowy_flutter/integration_test/desktop/settings/shortcuts_settings_test.dart
@@ -10,7 +10,6 @@ import 'package:integration_test/integration_test.dart';
import '../../shared/keyboard.dart';
import '../../shared/util.dart';
-import '../board/board_hide_groups_test.dart';
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
diff --git a/frontend/appflowy_flutter/integration_test/shared/common_operations.dart b/frontend/appflowy_flutter/integration_test/shared/common_operations.dart
index 3f8fb870f5..cab8faaf35 100644
--- a/frontend/appflowy_flutter/integration_test/shared/common_operations.dart
+++ b/frontend/appflowy_flutter/integration_test/shared/common_operations.dart
@@ -43,7 +43,6 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
-import '../desktop/board/board_hide_groups_test.dart';
import 'emoji.dart';
import 'util.dart';
@@ -790,6 +789,25 @@ extension SettingsFinder on CommonFinders {
.first;
}
+extension FlowySvgFinder on CommonFinders {
+ Finder byFlowySvg(FlowySvgData svg) => _FlowySvgFinder(svg);
+}
+
+class _FlowySvgFinder extends MatchFinder {
+ _FlowySvgFinder(this.svg);
+
+ final FlowySvgData svg;
+
+ @override
+ String get description => 'flowy_svg "$svg"';
+
+ @override
+ bool matches(Element candidate) {
+ final Widget widget = candidate.widget;
+ return widget is FlowySvg && widget.svg == svg;
+ }
+}
+
extension ViewLayoutPBTest on ViewLayoutPB {
String get menuName {
switch (this) {
diff --git a/frontend/appflowy_flutter/integration_test/shared/database_test_op.dart b/frontend/appflowy_flutter/integration_test/shared/database_test_op.dart
index ad279acb13..83f9e4d868 100644
--- a/frontend/appflowy_flutter/integration_test/shared/database_test_op.dart
+++ b/frontend/appflowy_flutter/integration_test/shared/database_test_op.dart
@@ -55,7 +55,7 @@ import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/ti
import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/url.dart';
import 'package:appflowy/plugins/database/widgets/cell_editor/checklist_cell_editor.dart';
import 'package:appflowy/plugins/database/widgets/cell_editor/checklist_progress_bar.dart';
-import 'package:appflowy/plugins/database/widgets/cell_editor/date_editor.dart';
+import 'package:appflowy/plugins/database/widgets/cell_editor/date_cell_editor.dart';
import 'package:appflowy/plugins/database/widgets/cell_editor/extension.dart';
import 'package:appflowy/plugins/database/widgets/cell_editor/media_cell_editor.dart';
import 'package:appflowy/plugins/database/widgets/cell_editor/select_option_cell_editor.dart';
diff --git a/frontend/appflowy_flutter/integration_test/shared/settings.dart b/frontend/appflowy_flutter/integration_test/shared/settings.dart
index e06634efef..a4e56c59e1 100644
--- a/frontend/appflowy_flutter/integration_test/shared/settings.dart
+++ b/frontend/appflowy_flutter/integration_test/shared/settings.dart
@@ -11,7 +11,6 @@ import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/style_widget/text_field.dart';
import 'package:flutter_test/flutter_test.dart';
-import '../desktop/board/board_hide_groups_test.dart';
import 'base.dart';
import 'common_operations.dart';
diff --git a/frontend/appflowy_flutter/lib/mobile/presentation/database/date_picker/mobile_date_picker_screen.dart b/frontend/appflowy_flutter/lib/mobile/presentation/database/date_picker/mobile_date_picker_screen.dart
index 5d5774156b..6c6baa00b9 100644
--- a/frontend/appflowy_flutter/lib/mobile/presentation/database/date_picker/mobile_date_picker_screen.dart
+++ b/frontend/appflowy_flutter/lib/mobile/presentation/database/date_picker/mobile_date_picker_screen.dart
@@ -7,7 +7,6 @@ import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/reminder/reminder_bloc.dart';
import 'package:appflowy/workspace/presentation/widgets/date_picker/mobile_appflowy_date_picker.dart';
import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/mobile_date_header.dart';
-import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pb.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -71,71 +70,44 @@ class _MobileDateCellEditScreenState extends State<MobileDateCellEditScreen> {
);
}
- Widget _buildDatePicker() => MultiBlocProvider(
- providers: [
- BlocProvider<DateCellEditorBloc>(
- create: (_) => DateCellEditorBloc(
- reminderBloc: getIt<ReminderBloc>(),
- cellController: widget.controller,
- ),
- ),
- ],
- child: BlocBuilder<DateCellEditorBloc, DateCellEditorState>(
- builder: (context, state) {
- return MobileAppFlowyDatePicker(
- selectedDay: state.dateTime,
- dateStr: state.dateStr,
- endDateStr: state.endDateStr,
- timeStr: state.timeStr,
- endTimeStr: state.endTimeStr,
- startDay: state.startDay,
- endDay: state.endDay,
- enableRanges: true,
- isRange: state.isRange,
- includeTime: state.includeTime,
- use24hFormat: state.dateTypeOptionPB.timeFormat ==
- TimeFormatPB.TwentyFourHour,
- timeFormat: state.dateTypeOptionPB.timeFormat,
- selectedReminderOption: state.reminderOption,
- onStartTimeChanged: (String? time) {
- if (time != null) {
- context
- .read<DateCellEditorBloc>()
- .add(DateCellEditorEvent.setTime(time));
- }
- },
- onEndTimeChanged: (String? time) {
- if (time != null) {
- context
- .read<DateCellEditorBloc>()
- .add(DateCellEditorEvent.setEndTime(time));
- }
- },
- onDaySelected: (selectedDay, focusedDay) => context
- .read<DateCellEditorBloc>()
- .add(DateCellEditorEvent.selectDay(selectedDay)),
- onRangeSelected: (start, end, focused) => context
- .read<DateCellEditorBloc>()
- .add(DateCellEditorEvent.selectDateRange(start, end)),
- onRangeChanged: (value) => context
- .read<DateCellEditorBloc>()
- .add(DateCellEditorEvent.setIsRange(value)),
- onIncludeTimeChanged: (value) => context
- .read<DateCellEditorBloc>()
- .add(DateCellEditorEvent.setIncludeTime(value)),
- onClearDate: () => context
- .read<DateCellEditorBloc>()
- .add(const DateCellEditorEvent.clearDate()),
- onReminderSelected: (option) =>
- context.read<DateCellEditorBloc>().add(
- DateCellEditorEvent.setReminderOption(
- option: option,
- selectedDay:
- state.dateTime == null ? DateTime.now() : null,
- ),
- ),
- );
- },
- ),
- );
+ Widget _buildDatePicker() {
+ return BlocProvider(
+ create: (_) => DateCellEditorBloc(
+ reminderBloc: getIt<ReminderBloc>(),
+ cellController: widget.controller,
+ ),
+ child: BlocBuilder<DateCellEditorBloc, DateCellEditorState>(
+ builder: (context, state) {
+ final dateCellBloc = context.read<DateCellEditorBloc>();
+ return MobileAppFlowyDatePicker(
+ dateTime: state.dateTime,
+ endDateTime: state.endDateTime,
+ isRange: state.isRange,
+ includeTime: state.includeTime,
+ dateFormat: state.dateTypeOptionPB.dateFormat,
+ timeFormat: state.dateTypeOptionPB.timeFormat,
+ reminderOption: state.reminderOption,
+ onDaySelected: (selectedDay) {
+ dateCellBloc.add(DateCellEditorEvent.updateDateTime(selectedDay));
+ },
+ onRangeSelected: (start, end) {
+ dateCellBloc.add(DateCellEditorEvent.updateDateRange(start, end));
+ },
+ onIsRangeChanged: (value) {
+ dateCellBloc.add(DateCellEditorEvent.setIsRange(value));
+ },
+ onIncludeTimeChanged: (value) {
+ dateCellBloc.add(DateCellEditorEvent.setIncludeTime(value));
+ },
+ onClearDate: () {
+ dateCellBloc.add(const DateCellEditorEvent.clearDate());
+ },
+ onReminderSelected: (option) {
+ dateCellBloc.add(DateCellEditorEvent.setReminderOption(option));
+ },
+ );
+ },
+ ),
+ );
+ }
}
diff --git a/frontend/appflowy_flutter/lib/mobile/presentation/database/view/database_filter_bottom_sheet.dart b/frontend/appflowy_flutter/lib/mobile/presentation/database/view/database_filter_bottom_sheet.dart
index e48d5bf8e1..aea68ac27a 100644
--- a/frontend/appflowy_flutter/lib/mobile/presentation/database/view/database_filter_bottom_sheet.dart
+++ b/frontend/appflowy_flutter/lib/mobile/presentation/database/view/database_filter_bottom_sheet.dart
@@ -1054,34 +1054,55 @@ class _SelectOptionFilterContentEditorState
}
}
-class _DateTimeFilterContentEditor extends StatelessWidget {
+class _DateTimeFilterContentEditor extends StatefulWidget {
const _DateTimeFilterContentEditor({
required this.filter,
});
final DateTimeFilter filter;
+ @override
+ State<_DateTimeFilterContentEditor> createState() =>
+ _DateTimeFilterContentEditorState();
+}
+
+class _DateTimeFilterContentEditorState
+ extends State<_DateTimeFilterContentEditor> {
+ late DateTime focusedDay;
+
+ bool get isRange => widget.filter.condition.isRange;
+
+ @override
+ void initState() {
+ super.initState();
+ focusedDay = (isRange ? widget.filter.start : widget.filter.timestamp) ??
+ DateTime.now();
+ }
+
@override
Widget build(BuildContext context) {
- final isRange = filter.condition.isRange;
return MobileDatePicker(
isRange: isRange,
- selectedDay: isRange ? filter.start : filter.timestamp,
- startDay: isRange ? filter.start : null,
- endDay: isRange ? filter.end : null,
- onDaySelected: (selectedDay, _) {
+ selectedDay: isRange ? widget.filter.start : widget.filter.timestamp,
+ startDay: isRange ? widget.filter.start : null,
+ endDay: isRange ? widget.filter.end : null,
+ focusedDay: focusedDay,
+ onDaySelected: (selectedDay) {
final newFilter = isRange
- ? filter.copyWithRange(start: selectedDay, end: null)
- : filter.copyWithTimestamp(timestamp: selectedDay);
+ ? widget.filter.copyWithRange(start: selectedDay, end: null)
+ : widget.filter.copyWithTimestamp(timestamp: selectedDay);
context.read<MobileFilterEditorCubit>().updateFilter(newFilter);
},
- onRangeSelected: (start, end, _) {
- final newFilter = filter.copyWithRange(
+ onRangeSelected: (start, end) {
+ final newFilter = widget.filter.copyWithRange(
start: start,
end: end,
);
context.read<MobileFilterEditorCubit>().updateFilter(newFilter);
},
+ onPageChanged: (focusedDay) {
+ setState(() => this.focusedDay = focusedDay);
+ },
);
}
}
diff --git a/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/date_cell_bloc.dart b/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/date_cell_bloc.dart
index c5573a9061..6f1d57fb50 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/date_cell_bloc.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/date_cell_bloc.dart
@@ -1,4 +1,5 @@
import 'dart:async';
+import 'dart:ui';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.dart';
import 'package:appflowy/plugins/database/application/field/field_info.dart';
@@ -6,6 +7,8 @@ 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';
+import 'date_cell_editor_bloc.dart';
+
part 'date_cell_bloc.freezed.dart';
class DateCellBloc extends Bloc<DateCellEvent, DateCellState> {
@@ -16,7 +19,7 @@ class DateCellBloc extends Bloc<DateCellEvent, DateCellState> {
}
final DateCellController cellController;
- void Function()? _onCellChangedFn;
+ VoidCallback? _onCellChangedFn;
@override
Future<void> close() async {
@@ -35,15 +38,19 @@ class DateCellBloc extends Bloc<DateCellEvent, DateCellState> {
(event, emit) async {
event.when(
didReceiveCellUpdate: (DateCellDataPB? cellData) {
+ final dateCellData = DateCellData.fromPB(cellData);
emit(
state.copyWith(
- data: cellData,
- dateStr: _dateStrFromCellData(cellData),
+ cellData: dateCellData,
),
);
},
didUpdateField: (fieldInfo) {
- emit(state.copyWith(fieldInfo: fieldInfo));
+ emit(
+ state.copyWith(
+ fieldInfo: fieldInfo,
+ ),
+ );
},
);
},
@@ -79,41 +86,16 @@ class DateCellEvent with _$DateCellEvent {
@freezed
class DateCellState with _$DateCellState {
const factory DateCellState({
- required DateCellDataPB? data,
- required String dateStr,
required FieldInfo fieldInfo,
+ required DateCellData cellData,
}) = _DateCellState;
- factory DateCellState.initial(DateCellController context) {
- final cellData = context.getCellData();
+ factory DateCellState.initial(DateCellController cellController) {
+ final cellData = DateCellData.fromPB(cellController.getCellData());
return DateCellState(
- fieldInfo: context.fieldInfo,
- data: cellData,
- dateStr: _dateStrFromCellData(cellData),
+ fieldInfo: cellController.fieldInfo,
+ cellData: 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();
-}
diff --git a/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/date_cell_editor_bloc.dart b/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/date_cell_editor_bloc.dart
index 879e759f35..2a828bc953 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/date_cell_editor_bloc.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/application/cell/bloc/date_cell_editor_bloc.dart
@@ -2,6 +2,7 @@ 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/application/field/field_info.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';
@@ -11,18 +12,16 @@ 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';
+import 'package:protobuf/protobuf.dart' hide FieldInfo;
part 'date_cell_editor_bloc.freezed.dart';
@@ -45,6 +44,7 @@ class DateCellEditorBloc
final DateCellBackendService _dateCellBackendService;
final DateCellController cellController;
final ReminderBloc _reminderBloc;
+
void Function()? _onCellChangedFn;
void _dispatch() {
@@ -52,17 +52,15 @@ class DateCellEditorBloc
(event, emit) async {
await event.when(
didReceiveCellUpdate: (DateCellDataPB? cellData) {
- final dateCellData = _dateDataFromCellData(cellData);
- final endDay =
- dateCellData.isRange == state.isRange && dateCellData.isRange
- ? dateCellData.endDateTime
- : null;
+ final dateCellData = DateCellData.fromPB(cellData);
+
ReminderOption option = state.reminderOption;
+ final cellReminderId = dateCellData.reminderId;
if (dateCellData.dateTime != null &&
- (state.reminderId?.isEmpty ?? true) &&
- (dateCellData.reminderId?.isNotEmpty ?? false) &&
- state.reminderOption != ReminderOption.none) {
+ state.reminderId.isEmpty &&
+ state.reminderOption != ReminderOption.none &&
+ cellReminderId.isNotEmpty) {
final date = state.reminderOption.withoutTime
? dateCellData.dateTime!.withoutTime
: dateCellData.dateTime!;
@@ -70,7 +68,7 @@ class DateCellEditorBloc
// Add Reminder
_reminderBloc.add(
ReminderEvent.addById(
- reminderId: dateCellData.reminderId!,
+ reminderId: dateCellData.reminderId,
objectId: cellController.viewId,
meta: {
ReminderMetaKeys.includeTime: true.toString(),
@@ -78,7 +76,7 @@ class DateCellEditorBloc
},
scheduledAt: Int64(
state.reminderOption
- .fromDate(date)
+ .getNotificationDateTime(date)
.millisecondsSinceEpoch ~/
1000,
),
@@ -86,8 +84,7 @@ class DateCellEditorBloc
);
}
- if ((dateCellData.reminderId?.isNotEmpty ?? false) &&
- dateCellData.dateTime != null) {
+ if (cellReminderId.isNotEmpty && dateCellData.dateTime != null) {
if (option.requiresNoTime && dateCellData.includeTime) {
option = ReminderOption.atTimeOfEvent;
} else if (!option.withoutTime && !dateCellData.includeTime) {
@@ -98,13 +95,13 @@ class DateCellEditorBloc
? dateCellData.dateTime!.withoutTime
: dateCellData.dateTime!;
- final scheduledAt = option.fromDate(date);
+ final scheduledAt = option.getNotificationDateTime(date);
// Update Reminder
_reminderBloc.add(
ReminderEvent.update(
ReminderUpdate(
- id: dateCellData.reminderId!,
+ id: dateCellData.reminderId,
scheduledAt: scheduledAt,
includeTime: true,
),
@@ -115,129 +112,75 @@ class DateCellEditorBloc
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,
- ),
- );
+ didUpdateField: (field) {
+ final typeOption = DateTypeOptionDataParser()
+ .fromBuffer(field.field.typeOptionData);
+ emit(state.copyWith(dateTypeOptionPB: typeOption));
},
- selectDay: (date) async {
- if (!state.isRange) {
- await _updateDateData(date: date);
+ updateDateTime: (date) async {
+ if (state.isRange) {
+ return;
}
+ 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);
+ updateDateRange: (DateTime start, DateTime end) async {
+ if (!state.isRange) {
+ return;
}
+ await _updateDateData(date: start, endDate: end);
},
- 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,
- );
- }
+ setIncludeTime: (includeTime) async {
+ await _updateIncludeTime(includeTime);
},
- 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);
- }
+ setIsRange: (isRange) async {
+ await _updateIsRange(isRange);
},
- 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);
},
- 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) {
+ if (state.reminderId.isNotEmpty) {
_reminderBloc
- .add(ReminderEvent.remove(reminderId: state.reminderId!));
+ .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) {
+ if (option == ReminderOption.none && state.reminderId.isNotEmpty) {
+ _reminderBloc.add(
+ ReminderEvent.remove(reminderId: state.reminderId),
+ );
+ await _updateDateData(reminderId: "");
+ } else if (state.reminderId.isEmpty) {
// New Reminder
final reminderId = nanoid();
- await _updateDateData(reminderId: reminderId, date: selectedDay);
-
- emit(
- state.copyWith(reminderOption: option, dateTime: selectedDay),
+ await _updateDateData(
+ reminderId: reminderId,
+ date: state.dateTime ?? DateTime.now().withoutTime,
);
- } 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!);
-
+ } else if (state.dateTime != null) {
// Update reminder
+ final scheduledAt =
+ option.getNotificationDateTime(state.dateTime!);
_reminderBloc.add(
ReminderEvent.update(
ReminderUpdate(
- id: state.reminderId!,
+ id: state.reminderId,
scheduledAt: scheduledAt,
includeTime: true,
),
@@ -245,8 +188,9 @@ class DateCellEditorBloc
);
}
},
- // Empty String signifies no reminder
- removeReminder: () async => _updateDateData(reminderId: ""),
+ removeReminder: () async {
+ await _updateDateData(reminderId: "");
+ },
);
},
);
@@ -254,102 +198,43 @@ class DateCellEditorBloc
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),
+ final result = await _dateCellBackendService.update(
+ date: date,
+ endDate: endDate,
+ reminderId: reminderId,
);
+ result.fold((_) {}, (err) => Log.error(err));
+ }
- // 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);
+ Future<void> _updateIsRange(bool isRange) async {
+ final dateTime = state.dateTime == null ? DateTime.now().withoutTime : null;
+ final endDateTime = dateTime;
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,
+ date: dateTime,
+ endDate: endDateTime,
+ isRange: isRange,
);
+ result.fold((_) {}, (err) => Log.error(err));
+ }
- 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> _updateIncludeTime(bool includeTime) async {
+ final dateTime = state.dateTime ?? DateTime.now().withoutTime;
+ final endDateTime = state.isRange ? state.endDateTime ?? dateTime : null;
+ final result = await _dateCellBackendService.update(
+ date: dateTime,
+ endDate: endDateTime,
+ includeTime: includeTime,
);
+ result.fold((_) {}, (err) => 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,
- );
+ result.fold((_) {}, (err) => Log.error(err));
}
String timeFormatPrompt(FlowyError error) {
@@ -367,6 +252,7 @@ class DateCellEditorBloc
if (_onCellChangedFn != null) {
cellController.removeListener(
onCellChanged: _onCellChangedFn!,
+ onFieldChanged: _onFieldChangedListener,
);
}
return super.close();
@@ -379,10 +265,17 @@ class DateCellEditorBloc
add(DateCellEditorEvent.didReceiveCellUpdate(cell));
}
},
+ onFieldChanged: _onFieldChangedListener,
);
}
- Future<void>? _updateTypeOption(
+ void _onFieldChangedListener(FieldInfo fieldInfo) {
+ if (!isClosed) {
+ add(DateCellEditorEvent.didUpdateField(fieldInfo));
+ }
+ }
+
+ Future<void> _updateTypeOption(
Emitter<DateCellEditorState> emit, {
DateFormatPB? dateFormat,
TimeFormatPB? timeFormat,
@@ -404,59 +297,36 @@ class DateCellEditorBloc
typeOptionData: newDateTypeOption.writeToBuffer(),
);
- result.fold(
- (_) => emit(
- state.copyWith(
- dateTypeOptionPB: newDateTypeOption,
- timeHintText: _timeHintText(newDateTypeOption),
- ),
- ),
- (err) => Log.error(err),
- );
+ result.fold((_) => {}, (err) => Log.error(err));
}
}
@freezed
class DateCellEditorEvent with _$DateCellEditorEvent {
+ const factory DateCellEditorEvent.didUpdateField(
+ FieldInfo fieldInfo,
+ ) = _DidUpdateField;
+
// 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.updateDateTime(DateTime day) =
+ _UpdateDateTime;
- 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.updateDateRange(
+ DateTime start,
+ DateTime end,
+ ) = _UpdateDateRange;
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.setReminderOption(ReminderOption option) =
+ _SetReminderOption;
const factory DateCellEditorEvent.removeReminder() = _RemoveReminder;
@@ -476,25 +346,12 @@ class DateCellEditorState with _$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,
+ required String reminderId,
@Default(ReminderOption.none) ReminderOption reminderOption,
}) = _DateCellEditorState;
@@ -504,11 +361,11 @@ class DateCellEditorState with _$DateCellEditorState {
) {
final typeOption = controller.getTypeOption(DateTypeOptionDataParser());
final cellData = controller.getCellData();
- final dateCellData = _dateDataFromCellData(cellData);
+ final dateCellData = DateCellData.fromPB(cellData);
ReminderOption reminderOption = ReminderOption.none;
- if ((dateCellData.reminderId?.isNotEmpty ?? false) &&
- dateCellData.dateTime != null) {
+
+ if (dateCellData.reminderId.isNotEmpty && dateCellData.dateTime != null) {
final reminder = reminderBloc.state.reminders
.firstWhereOrNull((r) => r.id == dateCellData.reminderId);
if (reminder != null) {
@@ -524,114 +381,60 @@ class DateCellEditorState with _$DateCellEditorState {
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({
+/// Helper class to parse ProtoBuf payloads into DateCellEditorState
+class DateCellData {
+ const 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,
});
+ const DateCellData.empty()
+ : dateTime = null,
+ endDateTime = null,
+ includeTime = false,
+ isRange = false,
+ reminderId = "";
+
+ factory DateCellData.fromPB(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 const DateCellData.empty();
+ }
+
+ final dateTime =
+ cellData.hasTimestamp() ? cellData.timestamp.toDateTime() : null;
+ final endDateTime = dateTime == null || !cellData.isRange
+ ? null
+ : cellData.hasEndTimestamp()
+ ? cellData.endTimestamp.toDateTime()
+ : null;
+
+ return DateCellData(
+ dateTime: dateTime,
+ endDateTime: endDateTime,
+ includeTime: cellData.includeTime,
+ isRange: cellData.isRange,
+ reminderId: cellData.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;
+ final String reminderId;
}
diff --git a/frontend/appflowy_flutter/lib/plugins/database/application/cell/cell_controller.dart b/frontend/appflowy_flutter/lib/plugins/database/application/cell/cell_controller.dart
index 2fd71d744f..d9009b2ba0 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/application/cell/cell_controller.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/application/cell/cell_controller.dart
@@ -241,15 +241,11 @@ class CellDataNotifier<T> extends ChangeNotifier {
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();
- }
+ if (listenWhen != null && !listenWhen!.call(_value, newValue)) {
+ return;
}
+ _value = newValue;
+ notifyListeners();
}
T get value => _value;
diff --git a/frontend/appflowy_flutter/lib/plugins/database/domain/date_cell_service.dart b/frontend/appflowy_flutter/lib/plugins/database/domain/date_cell_service.dart
index 9a9f75e75f..4afd41ad9c 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/domain/date_cell_service.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/domain/date_cell_service.dart
@@ -10,7 +10,7 @@ final class DateCellBackendService {
required String viewId,
required String fieldId,
required String rowId,
- }) : cellId = CellIdPB.create()
+ }) : cellId = CellIdPB()
..viewId = viewId
..fieldId = fieldId
..rowId = rowId;
@@ -18,32 +18,27 @@ final class DateCellBackendService {
final CellIdPB cellId;
Future<FlowyResult<void, FlowyError>> update({
- required bool includeTime,
- required bool isRange,
+ bool? includeTime,
+ bool? isRange,
DateTime? date,
- String? time,
DateTime? endDate,
- String? endTime,
String? reminderId,
}) {
- final payload = DateCellChangesetPB.create()
- ..cellId = cellId
- ..includeTime = includeTime
- ..isRange = isRange;
+ final payload = DateCellChangesetPB()..cellId = cellId;
+ if (includeTime != null) {
+ payload.includeTime = includeTime;
+ }
+ if (isRange != null) {
+ payload.isRange = isRange;
+ }
if (date != null) {
final dateTimestamp = date.millisecondsSinceEpoch ~/ 1000;
- payload.date = Int64(dateTimestamp);
- }
- if (time != null) {
- payload.time = time;
+ payload.timestamp = Int64(dateTimestamp);
}
if (endDate != null) {
final dateTimestamp = endDate.millisecondsSinceEpoch ~/ 1000;
- payload.endDate = Int64(dateTimestamp);
- }
- if (endTime != null) {
- payload.endTime = endTime;
+ payload.endTimestamp = Int64(dateTimestamp);
}
if (reminderId != null) {
payload.reminderId = reminderId;
@@ -53,7 +48,7 @@ final class DateCellBackendService {
}
Future<FlowyResult<void, FlowyError>> clear() {
- final payload = DateCellChangesetPB.create()
+ final payload = DateCellChangesetPB()
..cellId = cellId
..clearFlag = true;
diff --git a/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/filter/choicechip/date.dart b/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/filter/choicechip/date.dart
index 7a2c9ed967..752c484c40 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/filter/choicechip/date.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/grid/presentation/widgets/filter/choicechip/date.dart
@@ -201,15 +201,12 @@ class _DateFilterEditorState extends State<DateFilterEditor> {
builder: (context, filter, field) {
return AppFlowyDatePicker(
isRange: isRange,
- timeHintText: LocaleKeys.grid_field_selectTime.tr(),
includeTime: false,
dateFormat: DateFormatPB.Friendly,
timeFormat: TimeFormatPB.TwentyFourHour,
- selectedDay: isRange ? filter.start : filter.timestamp,
- startDay: isRange ? filter.start : null,
- endDay: isRange ? filter.end : null,
- enableReminder: false,
- onDaySelected: (selectedDay, _) {
+ dateTime: isRange ? filter.start : filter.timestamp,
+ endDateTime: isRange ? filter.end : null,
+ onDaySelected: (selectedDay) {
final newFilter = isRange
? filter.copyWithRange(start: selectedDay, end: null)
: filter.copyWithTimestamp(timestamp: selectedDay);
@@ -220,7 +217,7 @@ class _DateFilterEditorState extends State<DateFilterEditor> {
popooverController.close();
}
},
- onRangeSelected: (start, end, _) {
+ onRangeSelected: (start, end) {
final newFilter = filter.copyWithRange(
start: start,
end: end,
diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/card_cell_skeleton/date_card_cell.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/card_cell_skeleton/date_card_cell.dart
index 746a0c677d..c459d8cc60 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/card_cell_skeleton/date_card_cell.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/card_cell_skeleton/date_card_cell.dart
@@ -7,6 +7,7 @@ import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
+import '../editable_cell_skeleton/date.dart';
import 'card_cell.dart';
class DateCardCellStyle extends CardCellStyle {
@@ -46,11 +47,13 @@ class _DateCellState extends State<DateCardCell> {
);
},
child: BlocBuilder<DateCellBloc, DateCellState>(
- buildWhen: (previous, current) =>
- previous.dateStr != current.dateStr ||
- previous.data != current.data,
builder: (context, state) {
- if (state.dateStr.isEmpty) {
+ final dateStr = getDateCellStrFromCellData(
+ state.fieldInfo,
+ state.cellData,
+ );
+
+ if (dateStr.isEmpty) {
return const SizedBox.shrink();
}
@@ -61,12 +64,12 @@ class _DateCellState extends State<DateCardCell> {
children: [
Flexible(
child: Text(
- state.dateStr,
+ dateStr,
style: widget.style.textStyle,
overflow: TextOverflow.ellipsis,
),
),
- if (state.data?.reminderId.isNotEmpty ?? false) ...[
+ if (state.cellData.reminderId.isNotEmpty) ...[
const HSpace(4),
const FlowySvg(FlowySvgs.clock_alarm_s),
],
diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_grid/desktop_grid_date_cell.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_grid/desktop_grid_date_cell.dart
index 2da589f0e0..ee6e2e2ead 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_grid/desktop_grid_date_cell.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_grid/desktop_grid_date_cell.dart
@@ -3,7 +3,7 @@ import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/grid/presentation/layout/sizes.dart';
import 'package:appflowy/plugins/database/widgets/row/cells/cell_container.dart';
import 'package:appflowy/plugins/database/application/cell/bloc/date_cell_bloc.dart';
-import 'package:appflowy/plugins/database/widgets/cell_editor/date_editor.dart';
+import 'package:appflowy/plugins/database/widgets/cell_editor/date_cell_editor.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
@@ -50,6 +50,10 @@ class DesktopGridDateCellSkin extends IEditableDateCellSkin {
Widget _buildCellContent(DateCellState state) {
final wrap = state.fieldInfo.wrapCellContent ?? false;
+ final dateStr = getDateCellStrFromCellData(
+ state.fieldInfo,
+ state.cellData,
+ );
return Padding(
padding: GridSize.cellContentInsets,
child: Row(
@@ -57,12 +61,12 @@ class DesktopGridDateCellSkin extends IEditableDateCellSkin {
children: [
Flexible(
child: FlowyText(
- state.dateStr,
+ dateStr,
overflow: wrap ? null : TextOverflow.ellipsis,
maxLines: wrap ? null : 1,
),
),
- if (state.data?.reminderId.isNotEmpty ?? false) ...[
+ if (state.cellData.reminderId.isNotEmpty) ...[
const HSpace(4),
FlowyTooltip(
message: LocaleKeys.grid_field_reminderOnDateTooltip.tr(),
diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_row_detail/desktop_row_detail_date_cell.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_row_detail/desktop_row_detail_date_cell.dart
index 014621465c..c3f20f9183 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_row_detail/desktop_row_detail_date_cell.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/desktop_row_detail/desktop_row_detail_date_cell.dart
@@ -3,7 +3,7 @@ import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/date.dart';
import 'package:appflowy/plugins/database/widgets/row/cells/cell_container.dart';
import 'package:appflowy/plugins/database/application/cell/bloc/date_cell_bloc.dart';
-import 'package:appflowy/plugins/database/widgets/cell_editor/date_editor.dart';
+import 'package:appflowy/plugins/database/widgets/cell_editor/date_cell_editor.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
@@ -18,10 +18,13 @@ class DesktopRowDetailDateCellSkin extends IEditableDateCellSkin {
DateCellState state,
PopoverController popoverController,
) {
- final text = state.dateStr.isEmpty
- ? LocaleKeys.grid_row_textPlaceholder.tr()
- : state.dateStr;
- final color = state.dateStr.isEmpty ? Theme.of(context).hintColor : null;
+ final dateStr = getDateCellStrFromCellData(
+ state.fieldInfo,
+ state.cellData,
+ );
+ final text =
+ dateStr.isEmpty ? LocaleKeys.grid_row_textPlaceholder.tr() : dateStr;
+ final color = dateStr.isEmpty ? Theme.of(context).hintColor : null;
return AppFlowyPopover(
controller: popoverController,
@@ -42,7 +45,7 @@ class DesktopRowDetailDateCellSkin extends IEditableDateCellSkin {
overflow: TextOverflow.ellipsis,
),
),
- if (state.data?.reminderId.isNotEmpty ?? false) ...[
+ if (state.cellData.reminderId.isNotEmpty) ...[
const HSpace(4),
FlowyTooltip(
message: LocaleKeys.grid_field_reminderOnDateTooltip.tr(),
diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/editable_cell_skeleton/date.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/editable_cell_skeleton/date.dart
index 4b12c780d1..877b4c6dfb 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/editable_cell_skeleton/date.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/editable_cell_skeleton/date.dart
@@ -1,12 +1,17 @@
+import 'package:appflowy/plugins/database/application/cell/bloc/date_cell_editor_bloc.dart';
import 'package:appflowy/plugins/database/application/cell/cell_controller.dart';
import 'package:appflowy/plugins/database/application/cell/cell_controller_builder.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/field/type_option/type_option_data_parser.dart';
import 'package:appflowy/plugins/database/widgets/row/cells/cell_container.dart';
import 'package:appflowy/plugins/database/application/cell/bloc/date_cell_bloc.dart';
import 'package:appflowy/plugins/database/widgets/cell/editable_cell_builder.dart';
+import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
+import 'package:intl/intl.dart';
import '../desktop_grid/desktop_grid_date_cell.dart';
import '../desktop_row_detail/desktop_row_detail_date_cell.dart';
@@ -90,5 +95,45 @@ class _DateCellState extends GridCellState<EditableDateCell> {
}
@override
- String? onCopy() => cellBloc.state.dateStr;
+ String? onCopy() => getDateCellStrFromCellData(
+ cellBloc.state.fieldInfo,
+ cellBloc.state.cellData,
+ );
+}
+
+String getDateCellStrFromCellData(FieldInfo field, DateCellData cellData) {
+ if (cellData.dateTime == null) {
+ return "";
+ }
+
+ final DateTypeOptionPB(:dateFormat, :timeFormat) =
+ DateTypeOptionDataParser().fromBuffer(field.field.typeOptionData);
+
+ final format = cellData.includeTime
+ ? DateFormat("${dateFormat.pattern} ${timeFormat.pattern}")
+ : DateFormat(dateFormat.pattern);
+
+ if (cellData.isRange) {
+ return "${format.format(cellData.dateTime!)} → ${format.format(cellData.endDateTime!)}";
+ } else {
+ return format.format(cellData.dateTime!);
+ }
+}
+
+extension GetDateFormatExtension on DateFormatPB {
+ String get pattern => switch (this) {
+ DateFormatPB.Local => 'MM/dd/y',
+ DateFormatPB.US => 'y/MM/dd',
+ DateFormatPB.ISO => 'y-MM-dd',
+ DateFormatPB.Friendly => 'MMM dd, y',
+ DateFormatPB.DayMonthYear => 'dd/MM/y',
+ _ => 'MMM dd, y',
+ };
+}
+
+extension GetTimeFormatExtension on TimeFormatPB {
+ String get pattern => switch (this) {
+ TimeFormatPB.TwelveHour => 'hh:mm a',
+ _ => 'HH:mm',
+ };
}
diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_grid/mobile_grid_date_cell.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_grid/mobile_grid_date_cell.dart
index 7984322328..5e45afd551 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_grid/mobile_grid_date_cell.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_grid/mobile_grid_date_cell.dart
@@ -18,6 +18,10 @@ class MobileGridDateCellSkin extends IEditableDateCellSkin {
DateCellState state,
PopoverController popoverController,
) {
+ final dateStr = getDateCellStrFromCellData(
+ state.fieldInfo,
+ state.cellData,
+ );
return FlowyButton(
radius: BorderRadius.zero,
hoverColor: Colors.transparent,
@@ -29,12 +33,12 @@ class MobileGridDateCellSkin extends IEditableDateCellSkin {
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row(
children: [
- if (state.data?.reminderId.isNotEmpty ?? false) ...[
+ if (state.cellData.reminderId.isNotEmpty) ...[
const FlowySvg(FlowySvgs.clock_alarm_s),
const HSpace(6),
],
FlowyText(
- state.dateStr,
+ dateStr,
fontSize: 15,
),
],
diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_row_detail/mobile_row_detail_date_cell.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_row_detail/mobile_row_detail_date_cell.dart
index a5c500cdbc..0ac1263e46 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_row_detail/mobile_row_detail_date_cell.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell/mobile_row_detail/mobile_row_detail_date_cell.dart
@@ -1,3 +1,4 @@
+import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/mobile/presentation/bottom_sheet/show_mobile_bottom_sheet.dart';
import 'package:appflowy/mobile/presentation/database/date_picker/mobile_date_picker_screen.dart';
@@ -18,10 +19,13 @@ class MobileRowDetailDateCellSkin extends IEditableDateCellSkin {
DateCellState state,
PopoverController popoverController,
) {
- final text = state.dateStr.isEmpty
- ? LocaleKeys.grid_row_textPlaceholder.tr()
- : state.dateStr;
- final color = state.dateStr.isEmpty ? Theme.of(context).hintColor : null;
+ final dateStr = getDateCellStrFromCellData(
+ state.fieldInfo,
+ state.cellData,
+ );
+ final text =
+ dateStr.isEmpty ? LocaleKeys.grid_row_textPlaceholder.tr() : dateStr;
+ final color = dateStr.isEmpty ? Theme.of(context).hintColor : null;
return InkWell(
borderRadius: const BorderRadius.all(Radius.circular(14)),
@@ -46,11 +50,19 @@ class MobileRowDetailDateCellSkin extends IEditableDateCellSkin {
borderRadius: const BorderRadius.all(Radius.circular(14)),
),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 13),
- child: FlowyText.regular(
- text,
- fontSize: 16,
- color: color,
- maxLines: null,
+ child: Row(
+ children: [
+ if (state.cellData.reminderId.isNotEmpty) ...[
+ const FlowySvg(FlowySvgs.clock_alarm_s),
+ const HSpace(6),
+ ],
+ FlowyText.regular(
+ text,
+ fontSize: 16,
+ color: color,
+ maxLines: null,
+ ),
+ ],
),
),
);
diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/date_editor.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/date_cell_editor.dart
similarity index 50%
rename from frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/date_editor.dart
rename to frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/date_cell_editor.dart
index 54ef8ec177..d85a5dfbbf 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/date_editor.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/cell_editor/date_cell_editor.dart
@@ -36,44 +36,23 @@ class _DateCellEditor extends State<DateCellEditor> {
@override
Widget build(BuildContext context) {
- return MultiBlocProvider(
- providers: [
- BlocProvider<DateCellEditorBloc>(
- create: (context) => DateCellEditorBloc(
- reminderBloc: getIt<ReminderBloc>(),
- cellController: widget.cellController,
- ),
- ),
- ],
+ return BlocProvider<DateCellEditorBloc>(
+ create: (context) => DateCellEditorBloc(
+ reminderBloc: getIt<ReminderBloc>(),
+ cellController: widget.cellController,
+ ),
child: BlocBuilder<DateCellEditorBloc, DateCellEditorState>(
builder: (context, state) {
final dateCellBloc = context.read<DateCellEditorBloc>();
return AppFlowyDatePicker(
- includeTime: state.includeTime,
- rebuildOnDaySelected: false,
- onIncludeTimeChanged: (value) =>
- dateCellBloc.add(DateCellEditorEvent.setIncludeTime(value)),
- isRange: state.isRange,
- startDay: state.isRange ? state.startDay : null,
- endDay: state.isRange ? state.endDay : null,
- onIsRangeChanged: (value) =>
- dateCellBloc.add(DateCellEditorEvent.setIsRange(value)),
+ dateTime: state.dateTime,
+ endDateTime: state.endDateTime,
dateFormat: state.dateTypeOptionPB.dateFormat,
timeFormat: state.dateTypeOptionPB.timeFormat,
- selectedDay: state.dateTime,
- timeStr: state.timeStr,
- endTimeStr: state.endTimeStr,
- timeHintText: state.timeHintText,
- parseEndTimeError: state.parseEndTimeError,
- parseTimeError: state.parseTimeError,
+ includeTime: state.includeTime,
+ isRange: state.isRange,
+ reminderOption: state.reminderOption,
popoverMutex: popoverMutex,
- onReminderSelected: (option) => dateCellBloc.add(
- DateCellEditorEvent.setReminderOption(
- option: option,
- selectedDay: state.dateTime == null ? DateTime.now() : null,
- ),
- ),
- selectedReminderOption: state.reminderOption,
options: [
OptionGroup(
options: [
@@ -81,26 +60,38 @@ class _DateCellEditor extends State<DateCellEditor> {
popoverMutex: popoverMutex,
dateFormat: state.dateTypeOptionPB.dateFormat,
timeFormat: state.dateTypeOptionPB.timeFormat,
- onDateFormatChanged: (format) => dateCellBloc
- .add(DateCellEditorEvent.setDateFormat(format)),
- onTimeFormatChanged: (format) => dateCellBloc
- .add(DateCellEditorEvent.setTimeFormat(format)),
+ onDateFormatChanged: (format) {
+ dateCellBloc
+ .add(DateCellEditorEvent.setDateFormat(format));
+ },
+ onTimeFormatChanged: (format) {
+ dateCellBloc
+ .add(DateCellEditorEvent.setTimeFormat(format));
+ },
),
ClearDateButton(
- onClearDate: () =>
- dateCellBloc.add(const DateCellEditorEvent.clearDate()),
+ onClearDate: () {
+ dateCellBloc.add(const DateCellEditorEvent.clearDate());
+ },
),
],
),
],
- onStartTimeSubmitted: (timeStr) =>
- dateCellBloc.add(DateCellEditorEvent.setTime(timeStr)),
- onEndTimeSubmitted: (timeStr) =>
- dateCellBloc.add(DateCellEditorEvent.setEndTime(timeStr)),
- onDaySelected: (selectedDay, _) =>
- dateCellBloc.add(DateCellEditorEvent.selectDay(selectedDay)),
- onRangeSelected: (start, end, _) => dateCellBloc
- .add(DateCellEditorEvent.selectDateRange(start, end)),
+ onIncludeTimeChanged: (value) {
+ dateCellBloc.add(DateCellEditorEvent.setIncludeTime(value));
+ },
+ onIsRangeChanged: (value) {
+ dateCellBloc.add(DateCellEditorEvent.setIsRange(value));
+ },
+ onDaySelected: (selectedDay) {
+ dateCellBloc.add(DateCellEditorEvent.updateDateTime(selectedDay));
+ },
+ onRangeSelected: (start, end) {
+ dateCellBloc.add(DateCellEditorEvent.updateDateRange(start, end));
+ },
+ onReminderSelected: (option) {
+ dateCellBloc.add(DateCellEditorEvent.setReminderOption(option));
+ },
);
},
),
diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/field/type_option_editor/date/date_time_format.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/field/type_option_editor/date/date_time_format.dart
index 3fa869405d..862e46fc3b 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/field/type_option_editor/date/date_time_format.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/field/type_option_editor/date/date_time_format.dart
@@ -240,11 +240,11 @@ class IncludeTimeButton extends StatelessWidget {
const IncludeTimeButton({
super.key,
required this.onChanged,
- required this.value,
+ required this.includeTime,
});
final Function(bool value) onChanged;
- final bool value;
+ final bool includeTime;
@override
Widget build(BuildContext context) {
@@ -262,7 +262,7 @@ class IncludeTimeButton extends StatelessWidget {
FlowyText(LocaleKeys.grid_field_includeTime.tr()),
const Spacer(),
Toggle(
- value: value,
+ value: includeTime,
onChanged: onChanged,
padding: EdgeInsets.zero,
),
diff --git a/frontend/appflowy_flutter/lib/plugins/database/widgets/field/type_option_editor/timestamp.dart b/frontend/appflowy_flutter/lib/plugins/database/widgets/field/type_option_editor/timestamp.dart
index 7eed322bc8..be094c70a8 100644
--- a/frontend/appflowy_flutter/lib/plugins/database/widgets/field/type_option_editor/timestamp.dart
+++ b/frontend/appflowy_flutter/lib/plugins/database/widgets/field/type_option_editor/timestamp.dart
@@ -38,7 +38,7 @@ class TimestampTypeOptionEditorFactory implements TypeOptionEditorFactory {
);
onTypeOptionUpdated(newTypeOption.writeToBuffer());
},
- value: typeOption.includeTime,
+ includeTime: typeOption.includeTime,
),
),
],
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_block.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_block.dart
index d8c6354273..cf2f0b8e11 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_block.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_block.dart
@@ -122,7 +122,7 @@ class MentionBlock extends StatelessWidget {
textStyle: textStyle,
index: index,
reminderId: mention[MentionBlockKeys.reminderId],
- reminderOption: reminderOption,
+ reminderOption: reminderOption ?? ReminderOption.none,
includeTime: mention[MentionBlockKeys.includeTime] ?? false,
);
default:
diff --git a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_date_block.dart b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_date_block.dart
index 18cf6303cb..eb27134c7f 100644
--- a/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_date_block.dart
+++ b/frontend/appflowy_flutter/lib/plugins/document/presentation/editor_plugins/mention/mention_date_block.dart
@@ -10,17 +10,14 @@ import 'package:appflowy/util/theme_extension.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy/workspace/application/settings/date_time/date_format_ext.dart';
import 'package:appflowy/workspace/presentation/widgets/date_picker/mobile_appflowy_date_picker.dart';
+import 'package:appflowy/workspace/presentation/widgets/date_picker/utils/date_time_format_ext.dart';
import 'package:appflowy/workspace/presentation/widgets/date_picker/utils/user_time_format_ext.dart';
import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/date_picker_dialog.dart';
import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/mobile_date_header.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.pbenum.dart';
-import 'package:appflowy_backend/protobuf/flowy-user/date_time.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-user/reminder.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:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:fixnum/fixnum.dart';
@@ -40,7 +37,7 @@ class MentionDateBlock extends StatefulWidget {
required this.node,
this.textStyle,
this.reminderId,
- this.reminderOption,
+ this.reminderOption = ReminderOption.none,
this.includeTime = false,
});
@@ -53,7 +50,7 @@ class MentionDateBlock extends StatefulWidget {
/// null or empty
final String? reminderId;
- final ReminderOption? reminderOption;
+ final ReminderOption reminderOption;
final bool includeTime;
@@ -81,177 +78,118 @@ class _MentionDateBlockState extends State<MentionDateBlock> {
return const SizedBox.shrink();
}
- return MultiBlocProvider(
- providers: [
- BlocProvider<ReminderBloc>.value(value: context.read<ReminderBloc>()),
- BlocProvider<AppearanceSettingsCubit>.value(
- value: context.read<AppearanceSettingsCubit>(),
- ),
- ],
- child: BlocBuilder<AppearanceSettingsCubit, AppearanceSettingsState>(
- buildWhen: (previous, current) =>
- previous.dateFormat != current.dateFormat ||
- previous.timeFormat != current.timeFormat,
- builder: (context, appearance) =>
- BlocBuilder<ReminderBloc, ReminderState>(
- builder: (context, state) {
- final reminder = state.reminders
- .firstWhereOrNull((r) => r.id == widget.reminderId);
-
- final formattedDate = appearance.dateFormat
- .formatDate(parsedDate!, _includeTime, appearance.timeFormat);
-
- final timeStr = parsedDate != null
- ? _timeFromDate(parsedDate!, appearance.timeFormat)
- : null;
-
- final options = DatePickerOptions(
- focusedDay: parsedDate,
- popoverMutex: mutex,
- selectedDay: parsedDate,
- timeStr: timeStr,
- includeTime: _includeTime,
- dateFormat: appearance.dateFormat,
- timeFormat: appearance.timeFormat,
- selectedReminderOption: widget.reminderOption,
- onIncludeTimeChanged: (includeTime) {
- _includeTime = includeTime;
-
- if (![null, ReminderOption.none]
- .contains(widget.reminderOption)) {
- _updateReminder(
- widget.reminderOption!,
- reminder,
- includeTime,
- );
- } else {
- _updateBlock(
- parsedDate!,
- includeTime: includeTime,
- );
- }
- },
- onStartTimeChanged: (time) {
- final parsed = _parseTime(time, appearance.timeFormat);
- parsedDate = parsedDate!.withoutTime
- .add(Duration(hours: parsed.hour, minutes: parsed.minute));
-
- if (![null, ReminderOption.none]
- .contains(widget.reminderOption)) {
- _updateReminder(
- widget.reminderOption!,
- reminder,
- _includeTime,
- );
- } else {
- _updateBlock(parsedDate!, includeTime: _includeTime);
- }
- },
- onDaySelected: (selectedDay, focusedDay) {
- parsedDate = selectedDay;
-
- if (![null, ReminderOption.none]
- .contains(widget.reminderOption)) {
- _updateReminder(
- widget.reminderOption!,
- reminder,
- _includeTime,
- );
- } else {
- _updateBlock(selectedDay, includeTime: _includeTime);
- }
- },
- onReminderSelected: (reminderOption) =>
- _updateReminder(reminderOption, reminder),
- );
-
- Color? color;
- if (reminder != null) {
- if (reminder.type == ReminderType.today) {
- color = Theme.of(context).isLightMode
- ? const Color(0xFFFE0299)
- : Theme.of(context).colorScheme.error;
+ return BlocBuilder<AppearanceSettingsCubit, AppearanceSettingsState>(
+ buildWhen: (previous, current) =>
+ previous.dateFormat != current.dateFormat ||
+ previous.timeFormat != current.timeFormat,
+ builder: (context, appearance) =>
+ BlocBuilder<ReminderBloc, ReminderState>(
+ builder: (context, state) {
+ final reminder = state.reminders
+ .firstWhereOrNull((r) => r.id == widget.reminderId);
+
+ final formattedDate = appearance.dateFormat
+ .formatDate(parsedDate!, _includeTime, appearance.timeFormat);
+
+ final options = DatePickerOptions(
+ focusedDay: parsedDate,
+ popoverMutex: mutex,
+ selectedDay: parsedDate,
+ includeTime: _includeTime,
+ dateFormat: appearance.dateFormat,
+ timeFormat: appearance.timeFormat,
+ selectedReminderOption: widget.reminderOption,
+ onIncludeTimeChanged: (includeTime) {
+ _includeTime = includeTime;
+
+ if (widget.reminderOption != ReminderOption.none) {
+ _updateReminder(
+ widget.reminderOption,
+ reminder,
+ includeTime,
+ );
+ } else {
+ _updateBlock(
+ parsedDate!,
+ includeTime: includeTime,
+ );
}
- }
- final textStyle = widget.textStyle?.copyWith(
- color: color,
- leadingDistribution: TextLeadingDistribution.even,
- );
-
- // when font size equals 14, the icon size is 16.0.
- // scale the icon size based on the font size.
- final iconSize = (widget.textStyle?.fontSize ?? 14.0) / 14.0 * 16.0;
-
- return GestureDetector(
- onTapDown: (details) {
- _showDatePicker(
- context: context,
- offset: details.globalPosition,
- reminder: reminder,
- timeStr: timeStr,
- options: options,
+ },
+ onDaySelected: (selectedDay) {
+ parsedDate = selectedDay;
+
+ if (widget.reminderOption != ReminderOption.none) {
+ _updateReminder(
+ widget.reminderOption,
+ reminder,
+ _includeTime,
);
- },
- child: MouseRegion(
- cursor: SystemMouseCursors.click,
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- '@$formattedDate',
- style: textStyle,
- strutStyle: textStyle != null
- ? StrutStyle.fromTextStyle(textStyle)
- : null,
- ),
- const HSpace(4),
- FlowySvg(
- widget.reminderId != null
- ? FlowySvgs.reminder_clock_s
- : FlowySvgs.date_s,
- size: Size.square(iconSize),
- color: textStyle?.color,
- ),
- ],
- ),
+ } else {
+ _updateBlock(selectedDay, includeTime: _includeTime);
+ }
+ },
+ onReminderSelected: (reminderOption) =>
+ _updateReminder(reminderOption, reminder),
+ );
+
+ Color? color;
+ if (reminder != null) {
+ if (reminder.type == ReminderType.today) {
+ color = Theme.of(context).isLightMode
+ ? const Color(0xFFFE0299)
+ : Theme.of(context).colorScheme.error;
+ }
+ }
+ final textStyle = widget.textStyle?.copyWith(
+ color: color,
+ leadingDistribution: TextLeadingDistribution.even,
+ );
+
+ // when font size equals 14, the icon size is 16.0.
+ // scale the icon size based on the font size.
+ final iconSize = (widget.textStyle?.fontSize ?? 14.0) / 14.0 * 16.0;
+
+ return GestureDetector(
+ onTapDown: (details) {
+ _showDatePicker(
+ context: context,
+ offset: details.globalPosition,
+ reminder: reminder,
+ options: options,
+ );
+ },
+ child: MouseRegion(
+ cursor: SystemMouseCursors.click,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ '@$formattedDate',
+ style: textStyle,
+ strutStyle: textStyle != null
+ ? StrutStyle.fromTextStyle(textStyle)
+ : null,
+ ),
+ const HSpace(4),
+ FlowySvg(
+ widget.reminderId != null
+ ? FlowySvgs.reminder_clock_s
+ : FlowySvgs.date_s,
+ size: Size.square(iconSize),
+ color: textStyle?.color,
+ ),
+ ],
),
- );
- },
- ),
+ ),
+ );
+ },
),
);
}
- DateTime _parseTime(String timeStr, UserTimeFormatPB timeFormat) {
- final twelveHourFormat = DateFormat('hh:mm a');
- final twentyFourHourFormat = DateFormat('HH:mm');
-
- try {
- if (timeFormat == UserTimeFormatPB.TwelveHour) {
- return twelveHourFormat.parseStrict(timeStr);
- }
-
- return twentyFourHourFormat.parseStrict(timeStr);
- } on FormatException {
- Log.error("failed to parse time string ($timeStr)");
- return DateTime.now();
- }
- }
-
- String _timeFromDate(DateTime date, UserTimeFormatPB timeFormat) {
- final twelveHourFormat = DateFormat('HH:mm a');
- final twentyFourHourFormat = DateFormat('HH:mm');
-
- if (timeFormat == TimeFormatPB.TwelveHour) {
- return twelveHourFormat.format(date);
- }
-
- return twentyFourHourFormat.format(date);
- }
-
void _updateBlock(
DateTime date, {
- bool includeTime = false,
+ required bool includeTime,
String? reminderId,
ReminderOption? reminderOption,
}) {
@@ -266,14 +204,14 @@ class _MentionDateBlockState extends State<MentionDateBlock> {
MentionBlockKeys.reminderId: rId,
MentionBlockKeys.includeTime: includeTime,
MentionBlockKeys.reminderOption:
- reminderOption?.name ?? widget.reminderOption?.name,
+ reminderOption?.name ?? widget.reminderOption.name,
},
});
widget.editorState.apply(transaction, withUpdateSelection: false);
// Length of rendered block changes, this synchronizes
- // the cursor with the new block render
+ // the cursor with the new block render
widget.editorState.updateSelectionWithReason(
widget.editorState.selection,
);
@@ -308,7 +246,8 @@ class _MentionDateBlockState extends State<MentionDateBlock> {
ReminderEvent.update(
ReminderUpdate(
id: widget.reminderId!,
- scheduledAt: reminderOption.fromDate(parsedDate!),
+ scheduledAt:
+ reminderOption.getNotificationDateTime(parsedDate!),
date: parsedDate!,
),
),
@@ -349,7 +288,6 @@ class _MentionDateBlockState extends State<MentionDateBlock> {
required BuildContext context,
required DatePickerOptions options,
required Offset offset,
- String? timeStr,
ReminderPB? reminder,
}) {
if (!widget.editorState.editable) {
@@ -369,7 +307,6 @@ class _MentionDateBlockState extends State<MentionDateBlock> {
builder: (_, controller) => _DatePickerBottomSheet(
controller: controller,
parsedDate: parsedDate,
- timeStr: timeStr,
options: options,
includeTime: _includeTime,
reminderOption: widget.reminderOption,
@@ -393,25 +330,21 @@ class _DatePickerBottomSheet extends StatelessWidget {
const _DatePickerBottomSheet({
required this.controller,
required this.parsedDate,
- required this.timeStr,
required this.options,
required this.includeTime,
- this.reminderOption,
+ required this.reminderOption,
required this.onReminderSelected,
});
final ScrollController controller;
final DateTime? parsedDate;
- final String? timeStr;
final DatePickerOptions options;
final bool includeTime;
- final ReminderOption? reminderOption;
+ final ReminderOption reminderOption;
final void Function(ReminderOption) onReminderSelected;
@override
Widget build(BuildContext context) {
- final appearance = context.read<AppearanceSettingsCubit>().state;
-
return Material(
color: Theme.of(context).colorScheme.secondaryContainer,
child: ListView(
@@ -423,26 +356,13 @@ class _DatePickerBottomSheet extends StatelessWidget {
),
const MobileDateHeader(),
MobileAppFlowyDatePicker(
- selectedDay: parsedDate,
- timeStr: timeStr,
- dateStr: parsedDate != null
- ? options.dateFormat.formatDate(parsedDate!, includeTime)
- : null,
- includeTime: options.includeTime,
- use24hFormat: options.timeFormat == UserTimeFormatPB.TwentyFourHour,
- rebuildOnDaySelected: true,
- rebuildOnTimeChanged: true,
+ dateTime: parsedDate,
+ includeTime: includeTime,
+ dateFormat: options.dateFormat.simplified,
timeFormat: options.timeFormat.simplified,
- selectedReminderOption: reminderOption,
+ reminderOption: reminderOption,
onDaySelected: options.onDaySelected,
- onStartTimeChanged: (time) =>
- options.onStartTimeChanged?.call(time ?? ""),
onIncludeTimeChanged: options.onIncludeTimeChanged,
- liveDateFormatter: (selected) => appearance.dateFormat.formatDate(
- selected,
- false,
- appearance.timeFormat,
- ),
onReminderSelected: onReminderSelected,
),
],
diff --git a/frontend/appflowy_flutter/lib/shared/time_format.dart b/frontend/appflowy_flutter/lib/shared/time_format.dart
index 450f9954af..ba9ce0fabd 100644
--- a/frontend/appflowy_flutter/lib/shared/time_format.dart
+++ b/frontend/appflowy_flutter/lib/shared/time_format.dart
@@ -18,8 +18,8 @@ String formatTimestampWithContext(
final difference = now.difference(dateTime);
final String date;
- final dateFormate = context.read<AppearanceSettingsCubit>().state.dateFormat;
- final timeFormate = context.read<AppearanceSettingsCubit>().state.timeFormat;
+ final dateFormat = context.read<AppearanceSettingsCubit>().state.dateFormat;
+ final timeFormat = context.read<AppearanceSettingsCubit>().state.timeFormat;
if (difference.inMinutes < 1) {
date = LocaleKeys.sideBar_justNow.tr();
@@ -29,9 +29,9 @@ String formatTimestampWithContext(
.tr(namedArgs: {'count': difference.inMinutes.toString()});
} else if (difference.inHours >= 1 && dateTime.isToday) {
// in same day
- date = timeFormate.formatTime(dateTime);
+ date = timeFormat.formatTime(dateTime);
} else {
- date = dateFormate.formatDate(dateTime, false);
+ date = dateFormat.formatDate(dateTime, false);
}
if (difference.inHours >= 1 && prefix != null) {
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/appflowy_date_picker.dart b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/appflowy_date_picker.dart
index 64220fab28..5ad194a55f 100644
--- a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/appflowy_date_picker.dart
+++ b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/appflowy_date_picker.dart
@@ -1,15 +1,16 @@
+import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/plugins/database/grid/presentation/widgets/common/type_option_separator.dart';
import 'package:appflowy/plugins/database/widgets/field/type_option_editor/date/date_time_format.dart';
-import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/date_picker.dart';
-import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/end_text_field.dart';
-import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/end_time_button.dart';
-import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart';
-import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/start_text_field.dart';
import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pbenum.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
import 'package:flutter/material.dart';
-import 'package:universal_platform/universal_platform.dart';
+import 'package:intl/intl.dart';
+
+import 'widgets/date_picker.dart';
+import 'widgets/date_time_text_field.dart';
+import 'widgets/end_time_button.dart';
+import 'widgets/reminder_selector.dart';
class OptionGroup {
OptionGroup({required this.options});
@@ -17,87 +18,47 @@ class OptionGroup {
final List<Widget> options;
}
-typedef DaySelectedCallback = Function(DateTime, DateTime);
-typedef RangeSelectedCallback = Function(DateTime?, DateTime?, DateTime);
-typedef IncludeTimeChangedCallback = Function(bool);
-typedef TimeChangedCallback = Function(String);
+typedef DaySelectedCallback = void Function(DateTime);
+typedef RangeSelectedCallback = void Function(DateTime, DateTime);
+typedef IncludeTimeChangedCallback = void Function(bool);
class AppFlowyDatePicker extends StatefulWidget {
const AppFlowyDatePicker({
super.key,
+ required this.dateTime,
+ this.endDateTime,
required this.includeTime,
- this.onIncludeTimeChanged,
- this.rebuildOnDaySelected = true,
- this.enableRanges = true,
- this.isRange = false,
- this.onIsRangeChanged,
+ required this.isRange,
+ this.reminderOption = ReminderOption.none,
required this.dateFormat,
required this.timeFormat,
- this.selectedDay,
- this.focusedDay,
- this.firstDay,
- this.lastDay,
- this.startDay,
- this.endDay,
- this.timeStr,
- this.endTimeStr,
- this.timeHintText,
- this.parseEndTimeError,
- this.parseTimeError,
this.popoverMutex,
- this.selectedReminderOption = ReminderOption.none,
- this.onStartTimeSubmitted,
- this.onEndTimeSubmitted,
+ this.options = const [],
this.onDaySelected,
this.onRangeSelected,
- this.enableReminder = true,
+ this.onIncludeTimeChanged,
+ this.onIsRangeChanged,
this.onReminderSelected,
- this.options,
- this.allowFormatChanges = false,
- this.onDateFormatChanged,
- this.onTimeFormatChanged,
- this.onClearDate,
- this.onCalendarCreated,
- this.onPageChanged,
});
- final bool includeTime;
- final Function(bool)? onIncludeTimeChanged;
-
- final bool enableRanges;
- final bool isRange;
- final Function(bool)? onIsRangeChanged;
-
- final bool rebuildOnDaySelected;
+ final DateTime? dateTime;
+ final DateTime? endDateTime;
final DateFormatPB dateFormat;
final TimeFormatPB timeFormat;
- final DateTime? selectedDay;
- final DateTime? focusedDay;
- final DateTime? firstDay;
- final DateTime? lastDay;
-
- /// Start date in selected range
- final DateTime? startDay;
-
- /// End date in selected range
- final DateTime? endDay;
-
- final String? timeStr;
- final String? endTimeStr;
- final String? timeHintText;
- final String? parseEndTimeError;
- final String? parseTimeError;
final PopoverMutex? popoverMutex;
- final ReminderOption selectedReminderOption;
- final TimeChangedCallback? onStartTimeSubmitted;
- final TimeChangedCallback? onEndTimeSubmitted;
final DaySelectedCallback? onDaySelected;
final RangeSelectedCallback? onRangeSelected;
- final bool enableReminder;
+ final bool includeTime;
+ final Function(bool)? onIncludeTimeChanged;
+
+ final bool isRange;
+ final Function(bool)? onIsRangeChanged;
+
+ final ReminderOption reminderOption;
final OnReminderSelected? onReminderSelected;
/// A list of [OptionGroup] that will be rendered with proper
@@ -105,77 +66,74 @@ class AppFlowyDatePicker extends StatefulWidget {
///
/// __Supported on Desktop & Web__
///
- final List<OptionGroup>? options;
+ final List<OptionGroup> options;
- /// If this value is true, then [onTimeFormatChanged] and [onDateFormatChanged]
- /// cannot be null
- ///
- final bool allowFormatChanges;
-
- /// If [allowFormatChanges] is true, this must be provided
- ///
- final Function(DateFormatPB)? onDateFormatChanged;
+ @override
+ State<AppFlowyDatePicker> createState() => AppFlowyDatePickerState();
+}
- /// If [allowFormatChanges] is true, this must be provided
- ///
- final Function(TimeFormatPB)? onTimeFormatChanged;
+@visibleForTesting
+class AppFlowyDatePickerState extends State<AppFlowyDatePicker> {
+ // store date values in the state and refresh the ui upon any changes made, instead of only updating them after receiving update from backend.
+ late DateTime? dateTime;
+ late DateTime? startDateTime;
+ late DateTime? endDateTime;
+ late bool includeTime;
+ late bool isRange;
+ late ReminderOption reminderOption;
- /// If provided, the ClearDate button will be shown
- /// Otherwise it will be hidden
- ///
- final VoidCallback? onClearDate;
+ late DateTime focusedDateTime;
+ PageController? pageController;
- final void Function(PageController pageController)? onCalendarCreated;
+ bool justChangedIsRange = false;
- final void Function(DateTime focusedDay)? onPageChanged;
+ final isTabPressedNotifier = ValueNotifier<bool>(false);
+ final refreshStartTextFieldNotifier = RefreshDateTimeTextFieldController();
+ final refreshEndTextFieldNotifier = RefreshDateTimeTextFieldController();
@override
- State<AppFlowyDatePicker> createState() => _AppFlowyDatePickerState();
-}
+ void initState() {
+ super.initState();
+
+ dateTime = widget.dateTime;
+ startDateTime = widget.isRange ? widget.dateTime : null;
+ endDateTime = widget.isRange ? widget.endDateTime : null;
+ includeTime = widget.includeTime;
+ isRange = widget.isRange;
+ reminderOption = widget.reminderOption;
-class _AppFlowyDatePickerState extends State<AppFlowyDatePicker> {
- late DateTime? _selectedDay = widget.selectedDay;
- late ReminderOption _selectedReminderOption = widget.selectedReminderOption;
+ focusedDateTime = widget.dateTime ?? DateTime.now();
+ }
@override
- void didUpdateWidget(covariant AppFlowyDatePicker oldWidget) {
- _selectedDay = oldWidget.selectedDay != widget.selectedDay
- ? widget.selectedDay
- : _selectedDay;
- _selectedReminderOption =
- oldWidget.selectedReminderOption != widget.selectedReminderOption
- ? widget.selectedReminderOption
- : _selectedReminderOption;
+ void didUpdateWidget(covariant oldWidget) {
+ setState(() {
+ dateTime = widget.dateTime;
+ if (widget.isRange) {
+ startDateTime = widget.dateTime;
+ endDateTime = widget.endDateTime;
+ } else {
+ startDateTime = endDateTime = null;
+ }
+ includeTime = widget.includeTime;
+ isRange = widget.isRange;
+ if (oldWidget.reminderOption != widget.reminderOption) {
+ reminderOption = widget.reminderOption;
+ }
+ });
super.didUpdateWidget(oldWidget);
}
@override
- Widget build(BuildContext context) =>
- UniversalPlatform.isMobile ? buildMobilePicker() : buildDesktopPicker();
-
- Widget buildMobilePicker() {
- return DatePicker(
- isRange: widget.isRange,
- onDaySelected: (selectedDay, focusedDay) {
- widget.onDaySelected?.call(selectedDay, focusedDay);
-
- if (widget.rebuildOnDaySelected) {
- setState(() => _selectedDay = selectedDay);
- }
- },
- onRangeSelected: widget.onRangeSelected,
- selectedDay:
- widget.rebuildOnDaySelected ? _selectedDay : widget.selectedDay,
- firstDay: widget.firstDay,
- lastDay: widget.lastDay,
- startDay: widget.startDay,
- endDay: widget.endDay,
- onCalendarCreated: widget.onCalendarCreated,
- onPageChanged: widget.onPageChanged,
- );
+ void dispose() {
+ isTabPressedNotifier.dispose();
+ refreshStartTextFieldNotifier.dispose();
+ refreshEndTextFieldNotifier.dispose();
+ super.dispose();
}
- Widget buildDesktopPicker() {
+ @override
+ Widget build(BuildContext context) {
// GestureDetector is a workaround to stop popover from closing
// when clicking on the date picker.
return GestureDetector(
@@ -186,51 +144,78 @@ class _AppFlowyDatePickerState extends State<AppFlowyDatePicker> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
- StartTextField(
- includeTime: widget.includeTime,
+ DateTimeTextField(
+ key: const ValueKey('date_time_text_field'),
+ includeTime: includeTime,
+ dateTime: isRange ? startDateTime : dateTime,
+ dateFormat: widget.dateFormat,
timeFormat: widget.timeFormat,
- timeHintText: widget.timeHintText,
- parseEndTimeError: widget.parseEndTimeError,
- parseTimeError: widget.parseTimeError,
- timeStr: widget.timeStr,
popoverMutex: widget.popoverMutex,
- onSubmitted: widget.onStartTimeSubmitted,
+ isTabPressed: isTabPressedNotifier,
+ refreshTextController: refreshStartTextFieldNotifier,
+ onSubmitted: onDateTimeInputSubmitted,
),
- EndTextField(
- includeTime: widget.includeTime,
- timeFormat: widget.timeFormat,
- isRange: widget.isRange,
- endTimeStr: widget.endTimeStr,
- popoverMutex: widget.popoverMutex,
- onSubmitted: widget.onEndTimeSubmitted,
+ if (isRange) ...[
+ const VSpace(8),
+ DateTimeTextField(
+ key: const ValueKey('end_date_time_text_field'),
+ includeTime: includeTime,
+ dateTime: endDateTime,
+ dateFormat: widget.dateFormat,
+ timeFormat: widget.timeFormat,
+ popoverMutex: widget.popoverMutex,
+ isTabPressed: isTabPressedNotifier,
+ refreshTextController: refreshEndTextFieldNotifier,
+ onSubmitted: onEndDateTimeInputSubmitted,
+ ),
+ ],
+ const VSpace(14),
+ Focus(
+ descendantsAreTraversable: false,
+ child: _buildDatePickerHeader(),
),
+ const VSpace(14),
DatePicker(
- isRange: widget.isRange,
+ isRange: isRange,
onDaySelected: (selectedDay, focusedDay) {
- widget.onDaySelected?.call(selectedDay, focusedDay);
-
- if (widget.rebuildOnDaySelected) {
- setState(() => _selectedDay = selectedDay);
- }
+ onDateSelectedFromDatePicker(selectedDay, null);
+ },
+ onRangeSelected: (start, end, focusedDay) {
+ onDateSelectedFromDatePicker(start, end);
+ },
+ selectedDay: dateTime,
+ startDay: isRange ? startDateTime : null,
+ endDay: isRange ? endDateTime : null,
+ focusedDay: focusedDateTime,
+ onCalendarCreated: (controller) {
+ pageController = controller;
+ },
+ onPageChanged: (focusedDay) {
+ setState(
+ () => focusedDateTime = DateTime(
+ focusedDay.year,
+ focusedDay.month,
+ focusedDay.day,
+ ),
+ );
},
- onRangeSelected: widget.onRangeSelected,
- selectedDay: widget.rebuildOnDaySelected
- ? _selectedDay
- : widget.selectedDay,
- firstDay: widget.firstDay,
- lastDay: widget.lastDay,
- startDay: widget.startDay,
- endDay: widget.endDay,
- onCalendarCreated: widget.onCalendarCreated,
- onPageChanged: widget.onPageChanged,
),
- if (widget.enableRanges && widget.onIsRangeChanged != null ||
+ if (widget.onIsRangeChanged != null ||
widget.onIncludeTimeChanged != null)
const TypeOptionSeparator(spacing: 12.0),
- if (widget.enableRanges && widget.onIsRangeChanged != null) ...[
+ if (widget.onIsRangeChanged != null) ...[
EndTimeButton(
- isRange: widget.isRange,
- onChanged: widget.onIsRangeChanged!,
+ isRange: isRange,
+ onChanged: (value) {
+ if (value) {
+ justChangedIsRange = true;
+ }
+ widget.onIsRangeChanged!.call(value);
+ if (dateTime != null && value) {
+ widget.onRangeSelected?.call(dateTime!, dateTime!);
+ }
+ setState(() => isRange = value);
+ },
),
const VSpace(4.0),
],
@@ -238,31 +223,35 @@ class _AppFlowyDatePickerState extends State<AppFlowyDatePicker> {
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: IncludeTimeButton(
- value: widget.includeTime,
- onChanged: widget.onIncludeTimeChanged!,
+ includeTime: includeTime,
+ onChanged: (value) {
+ widget.onIncludeTimeChanged?.call(value);
+ setState(() => includeTime = value);
+ },
),
),
- if (widget.enableReminder) ...[
+ if (widget.onReminderSelected != null) ...[
const _GroupSeparator(),
ReminderSelector(
mutex: widget.popoverMutex,
hasTime: widget.includeTime,
timeFormat: widget.timeFormat,
- selectedOption: _selectedReminderOption,
+ selectedOption: reminderOption,
onOptionSelected: (option) {
- setState(() => _selectedReminderOption = option);
widget.onReminderSelected?.call(option);
+ setState(() => reminderOption = option);
},
),
],
- if (widget.options?.isNotEmpty ?? false) ...[
+ if (widget.options.isNotEmpty) ...[
const _GroupSeparator(),
ListView.separated(
shrinkWrap: true,
- itemCount: widget.options!.length,
+ itemCount: widget.options.length,
+ physics: const NeverScrollableScrollPhysics(),
separatorBuilder: (_, __) => const _GroupSeparator(),
itemBuilder: (_, index) =>
- _renderGroupOptions(widget.options![index].options),
+ _renderGroupOptions(widget.options[index].options),
),
],
],
@@ -271,12 +260,199 @@ class _AppFlowyDatePickerState extends State<AppFlowyDatePicker> {
);
}
+ Widget _buildDatePickerHeader() {
+ return Padding(
+ padding: const EdgeInsetsDirectional.only(start: 22.0, end: 18.0),
+ child: Row(
+ children: [
+ Expanded(
+ child: FlowyText(
+ DateFormat.yMMMM().format(focusedDateTime),
+ ),
+ ),
+ FlowyIconButton(
+ width: 20,
+ icon: FlowySvg(
+ FlowySvgs.arrow_left_s,
+ color: Theme.of(context).iconTheme.color,
+ size: const Size.square(20.0),
+ ),
+ onPressed: () => pageController?.previousPage(
+ duration: const Duration(milliseconds: 300),
+ curve: Curves.easeOut,
+ ),
+ ),
+ const HSpace(4.0),
+ FlowyIconButton(
+ width: 20,
+ icon: FlowySvg(
+ FlowySvgs.arrow_right_s,
+ color: Theme.of(context).iconTheme.color,
+ size: const Size.square(20.0),
+ ),
+ onPressed: () {
+ pageController?.nextPage(
+ duration: const Duration(milliseconds: 300),
+ curve: Curves.easeOut,
+ );
+ },
+ ),
+ ],
+ ),
+ );
+ }
+
Widget _renderGroupOptions(List<Widget> options) => ListView.separated(
shrinkWrap: true,
itemCount: options.length,
separatorBuilder: (_, __) => const VSpace(4),
itemBuilder: (_, index) => options[index],
);
+
+ void onDateSelectedFromDatePicker(
+ DateTime? newStartDateTime,
+ DateTime? newEndDateTime,
+ ) {
+ if (newStartDateTime == null) {
+ return;
+ }
+ if (isRange) {
+ if (newEndDateTime == null) {
+ if (justChangedIsRange && dateTime != null) {
+ justChangedIsRange = false;
+ DateTime start = dateTime!;
+ DateTime end = DateTime(
+ newStartDateTime.year,
+ newStartDateTime.month,
+ newStartDateTime.day,
+ );
+ if (end.isBefore(start)) {
+ (start, end) = (end, start);
+ }
+ widget.onRangeSelected?.call(start, end);
+ setState(() {
+ // hAcK: Resetting these state variables to null to reset the click counter of the table calendar widget, which doesn't expose a controller for us to do so otherwise. The parent widget needs to provide the data again so that it can be shown.
+ dateTime = startDateTime = endDateTime = null;
+ focusedDateTime = getNewFocusedDay(newStartDateTime);
+ });
+ } else {
+ final combined = combineDateTimes(newStartDateTime, dateTime);
+ setState(() {
+ dateTime = combined;
+ startDateTime = combined;
+ endDateTime = null;
+ focusedDateTime = getNewFocusedDay(combined);
+ });
+ }
+ } else {
+ bool switched = false;
+ DateTime combinedDateTime =
+ combineDateTimes(newStartDateTime, dateTime);
+ DateTime combinedEndDateTime =
+ combineDateTimes(newEndDateTime, widget.endDateTime);
+
+ if (combinedEndDateTime.isBefore(combinedDateTime)) {
+ (combinedDateTime, combinedEndDateTime) =
+ (combinedEndDateTime, combinedDateTime);
+ switched = true;
+ }
+
+ widget.onRangeSelected?.call(combinedDateTime, combinedEndDateTime);
+
+ setState(() {
+ dateTime = switched ? combinedDateTime : combinedEndDateTime;
+ startDateTime = combinedDateTime;
+ endDateTime = combinedEndDateTime;
+ focusedDateTime = getNewFocusedDay(newEndDateTime);
+ });
+ }
+ } else {
+ final combinedDateTime = combineDateTimes(newStartDateTime, dateTime);
+ widget.onDaySelected?.call(combinedDateTime);
+
+ setState(() {
+ dateTime = combinedDateTime;
+ focusedDateTime = getNewFocusedDay(combinedDateTime);
+ });
+ }
+ }
+
+ DateTime combineDateTimes(DateTime date, DateTime? time) {
+ final timeComponent = time == null
+ ? Duration.zero
+ : Duration(hours: time.hour, minutes: time.minute);
+
+ return DateTime(date.year, date.month, date.day).add(timeComponent);
+ }
+
+ void onDateTimeInputSubmitted(DateTime value) {
+ if (isRange) {
+ DateTime end = endDateTime ?? value;
+ if (end.isBefore(value)) {
+ (value, end) = (end, value);
+ refreshStartTextFieldNotifier.refresh();
+ }
+
+ widget.onRangeSelected?.call(value, end);
+
+ setState(() {
+ dateTime = value;
+ startDateTime = value;
+ endDateTime = end;
+ focusedDateTime = getNewFocusedDay(value);
+ });
+ } else {
+ widget.onDaySelected?.call(value);
+
+ setState(() {
+ dateTime = value;
+ focusedDateTime = getNewFocusedDay(value);
+ });
+ }
+ }
+
+ void onEndDateTimeInputSubmitted(DateTime value) {
+ if (isRange) {
+ DateTime start = startDateTime ?? value;
+ if (value.isBefore(start)) {
+ (start, value) = (value, start);
+ refreshEndTextFieldNotifier.refresh();
+ }
+
+ widget.onRangeSelected?.call(start, value);
+
+ if (endDateTime == null) {
+ // hAcK: Resetting these state variables to null to reset the click counter of the table calendar widget, which doesn't expose a controller for us to do so otherwise. The parent widget needs to provide the data again so that it can be shown.
+ setState(() {
+ dateTime = startDateTime = endDateTime = null;
+ focusedDateTime = getNewFocusedDay(value);
+ });
+ } else {
+ setState(() {
+ dateTime = start;
+ startDateTime = start;
+ endDateTime = value;
+ focusedDateTime = getNewFocusedDay(value);
+ });
+ }
+ } else {
+ widget.onDaySelected?.call(value);
+
+ setState(() {
+ dateTime = value;
+ focusedDateTime = getNewFocusedDay(value);
+ });
+ }
+ }
+
+ DateTime getNewFocusedDay(DateTime dateTime) {
+ if (focusedDateTime.year != dateTime.year ||
+ focusedDateTime.month != dateTime.month) {
+ return DateTime(dateTime.year, dateTime.month);
+ } else {
+ return focusedDateTime;
+ }
+ }
}
class _GroupSeparator extends StatelessWidget {
@@ -288,3 +464,7 @@ class _GroupSeparator extends StatelessWidget {
child: Container(color: Theme.of(context).dividerColor, height: 1.0),
);
}
+
+class RefreshDateTimeTextFieldController extends ChangeNotifier {
+ void refresh() => notifyListeners();
+}
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/mobile_appflowy_date_picker.dart b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/mobile_appflowy_date_picker.dart
index 5047b73e63..c3e029a138 100644
--- a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/mobile_appflowy_date_picker.dart
+++ b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/mobile_appflowy_date_picker.dart
@@ -18,74 +18,91 @@ import 'package:go_router/go_router.dart';
class MobileAppFlowyDatePicker extends StatefulWidget {
const MobileAppFlowyDatePicker({
super.key,
- this.selectedDay,
- this.startDay,
- this.endDay,
- this.dateStr,
- this.endDateStr,
- this.timeStr,
- this.endTimeStr,
- this.enableRanges = false,
- this.isRange = false,
- this.rebuildOnDaySelected = false,
- this.rebuildOnTimeChanged = false,
- required this.includeTime,
- required this.use24hFormat,
+ this.dateTime,
+ this.endDateTime,
+ required this.dateFormat,
required this.timeFormat,
- this.selectedReminderOption,
- required this.onStartTimeChanged,
- this.onEndTimeChanged,
+ this.reminderOption = ReminderOption.none,
+ required this.includeTime,
required this.onIncludeTimeChanged,
- this.onRangeChanged,
+ this.isRange = false,
+ this.onIsRangeChanged,
this.onDaySelected,
this.onRangeSelected,
this.onClearDate,
- this.liveDateFormatter,
this.onReminderSelected,
});
- final DateTime? selectedDay;
- final DateTime? startDay;
- final DateTime? endDay;
+ final DateTime? dateTime;
+ final DateTime? endDateTime;
- final String? dateStr;
- final String? endDateStr;
- final String? timeStr;
- final String? endTimeStr;
-
- final bool enableRanges;
final bool isRange;
final bool includeTime;
- final bool rebuildOnDaySelected;
- final bool rebuildOnTimeChanged;
- final bool use24hFormat;
final TimeFormatPB timeFormat;
+ final DateFormatPB dateFormat;
- final ReminderOption? selectedReminderOption;
+ final ReminderOption reminderOption;
- final Function(String? time) onStartTimeChanged;
- final Function(String? time)? onEndTimeChanged;
- final Function(bool) onIncludeTimeChanged;
- final Function(bool)? onRangeChanged;
+ final Function(bool)? onIncludeTimeChanged;
+ final Function(bool)? onIsRangeChanged;
final DaySelectedCallback? onDaySelected;
final RangeSelectedCallback? onRangeSelected;
final VoidCallback? onClearDate;
final OnReminderSelected? onReminderSelected;
- final String Function(DateTime)? liveDateFormatter;
-
@override
State<MobileAppFlowyDatePicker> createState() =>
_MobileAppFlowyDatePickerState();
}
class _MobileAppFlowyDatePickerState extends State<MobileAppFlowyDatePicker> {
- late bool _includeTime = widget.includeTime;
- late String? _dateStr = widget.dateStr;
- late ReminderOption _reminderOption =
- widget.selectedReminderOption ?? ReminderOption.none;
+ // store date values in the state and refresh the ui upon any changes made, instead of only updating them after receiving update from backend.
+ late DateTime? dateTime;
+ late DateTime? startDateTime;
+ late DateTime? endDateTime;
+ late bool includeTime;
+ late bool isRange;
+ late ReminderOption reminderOption;
+
+ late DateTime focusedDateTime;
+ PageController? pageController;
+
+ bool justChangedIsRange = false;
+
+ @override
+ void initState() {
+ super.initState();
+
+ dateTime = widget.dateTime;
+ startDateTime = widget.isRange ? widget.dateTime : null;
+ endDateTime = widget.isRange ? widget.endDateTime : null;
+ includeTime = widget.includeTime;
+ isRange = widget.isRange;
+ reminderOption = widget.reminderOption;
+
+ focusedDateTime = widget.dateTime ?? DateTime.now();
+ }
+
+ @override
+ void didUpdateWidget(covariant oldWidget) {
+ setState(() {
+ dateTime = widget.dateTime;
+ if (widget.isRange) {
+ startDateTime = widget.dateTime;
+ endDateTime = widget.endDateTime;
+ } else {
+ startDateTime = endDateTime = null;
+ }
+ includeTime = widget.includeTime;
+ isRange = widget.isRange;
+ if (oldWidget.reminderOption != widget.reminderOption) {
+ reminderOption = widget.reminderOption;
+ }
+ });
+ super.didUpdateWidget(oldWidget);
+ }
@override
Widget build(BuildContext context) {
@@ -93,58 +110,64 @@ class _MobileAppFlowyDatePickerState extends State<MobileAppFlowyDatePicker> {
children: [
FlowyOptionDecorateBox(
showTopBorder: false,
- child: _IncludeTimePicker(
- dateStr:
- widget.liveDateFormatter != null ? _dateStr : widget.dateStr,
- endDateStr: widget.endDateStr,
- timeStr: widget.timeStr,
- endTimeStr: widget.endTimeStr,
- includeTime: _includeTime,
- use24hFormat: widget.use24hFormat,
- onStartTimeChanged: widget.onStartTimeChanged,
- onEndTimeChanged: widget.onEndTimeChanged,
- rebuildOnTimeChanged: widget.rebuildOnTimeChanged,
+ child: _TimePicker(
+ dateTime: isRange ? startDateTime : dateTime,
+ endDateTime: endDateTime,
+ includeTime: includeTime,
+ isRange: isRange,
+ dateFormat: widget.dateFormat,
+ timeFormat: widget.timeFormat,
+ onStartTimeChanged: onStartTimeChanged,
+ onEndTimeChanged: onEndTimeChanged,
),
),
const _Divider(),
FlowyOptionDecorateBox(
child: MobileDatePicker(
- isRange: widget.isRange,
- selectedDay: widget.selectedDay,
- startDay: widget.startDay,
- endDay: widget.endDay,
- onDaySelected: (selected, focused) {
- widget.onDaySelected?.call(selected, focused);
-
- if (widget.liveDateFormatter != null) {
- setState(() => _dateStr = widget.liveDateFormatter!(selected));
- }
+ isRange: isRange,
+ selectedDay: dateTime,
+ startDay: isRange ? startDateTime : null,
+ endDay: isRange ? endDateTime : null,
+ focusedDay: focusedDateTime,
+ onDaySelected: (selectedDay) {
+ onDateSelectedFromDatePicker(selectedDay, null);
+ },
+ onRangeSelected: (start, end) {
+ onDateSelectedFromDatePicker(start, end);
+ },
+ onPageChanged: (focusedDay) {
+ setState(() => focusedDateTime = focusedDay);
},
- onRangeSelected: widget.onRangeSelected,
- rebuildOnDaySelected: widget.rebuildOnDaySelected,
),
),
const _Divider(),
- if (widget.enableRanges && widget.onRangeChanged != null)
- _EndDateSwitch(
+ if (widget.onIsRangeChanged != null)
+ _IsRangeSwitch(
isRange: widget.isRange,
- onRangeChanged: widget.onRangeChanged!,
+ onRangeChanged: (value) {
+ if (!isRange) {
+ justChangedIsRange = true;
+ }
+ widget.onIsRangeChanged!.call(value);
+ setState(() => isRange = value);
+ },
+ ),
+ if (widget.onIncludeTimeChanged != null)
+ _IncludeTimeSwitch(
+ showTopBorder: widget.onIsRangeChanged == null,
+ includeTime: includeTime,
+ onIncludeTimeChanged: (includeTime) {
+ widget.onIncludeTimeChanged?.call(includeTime);
+ setState(() => this.includeTime = includeTime);
+ },
),
- _IncludeTimeSwitch(
- showTopBorder: !widget.enableRanges || widget.onRangeChanged == null,
- includeTime: _includeTime,
- onIncludeTimeChanged: (includeTime) {
- widget.onIncludeTimeChanged(includeTime);
- setState(() => _includeTime = includeTime);
- },
- ),
if (widget.onReminderSelected != null) ...[
const _Divider(),
_ReminderSelector(
- selectedReminderOption: _reminderOption,
+ selectedReminderOption: reminderOption,
onReminderSelected: (option) {
widget.onReminderSelected!.call(option);
- setState(() => _reminderOption = option);
+ setState(() => reminderOption = option);
},
timeFormat: widget.timeFormat,
hasTime: widget.includeTime,
@@ -152,12 +175,160 @@ class _MobileAppFlowyDatePickerState extends State<MobileAppFlowyDatePicker> {
],
if (widget.onClearDate != null) ...[
const _Divider(),
- _ClearDateButton(onClearDate: widget.onClearDate!),
+ _ClearDateButton(
+ onClearDate: () {
+ widget.onClearDate!.call();
+ Navigator.of(context).pop();
+ },
+ ),
],
const _Divider(),
],
);
}
+
+ void onDateSelectedFromDatePicker(
+ DateTime? newStartDateTime,
+ DateTime? newEndDateTime,
+ ) {
+ if (newStartDateTime == null) {
+ return;
+ }
+ if (isRange) {
+ if (newEndDateTime == null) {
+ if (justChangedIsRange && dateTime != null) {
+ justChangedIsRange = false;
+ DateTime start = dateTime!;
+ DateTime end = DateTime(
+ newStartDateTime.year,
+ newStartDateTime.month,
+ newStartDateTime.day,
+ );
+ if (end.isBefore(start)) {
+ (start, end) = (end, start);
+ }
+ widget.onRangeSelected?.call(start, end);
+ setState(() {
+ // hAcK: Resetting these state variables to null to reset the click counter of the table calendar widget, which doesn't expose a controller for us to do so otherwise. The parent widget needs to provide the data again so that it can be shown.
+ dateTime = startDateTime = endDateTime = null;
+ focusedDateTime = getNewFocusedDay(newStartDateTime);
+ });
+ } else {
+ final combined = combineDateTimes(newStartDateTime, dateTime);
+ setState(() {
+ dateTime = combined;
+ startDateTime = combined;
+ endDateTime = null;
+ focusedDateTime = getNewFocusedDay(combined);
+ });
+ }
+ } else {
+ bool switched = false;
+ DateTime combinedDateTime =
+ combineDateTimes(newStartDateTime, dateTime);
+ DateTime combinedEndDateTime =
+ combineDateTimes(newEndDateTime, widget.endDateTime);
+
+ if (combinedEndDateTime.isBefore(combinedDateTime)) {
+ (combinedDateTime, combinedEndDateTime) =
+ (combinedEndDateTime, combinedDateTime);
+ switched = true;
+ }
+
+ widget.onRangeSelected?.call(combinedDateTime, combinedEndDateTime);
+
+ setState(() {
+ dateTime = switched ? combinedDateTime : combinedEndDateTime;
+ startDateTime = combinedDateTime;
+ endDateTime = combinedEndDateTime;
+ focusedDateTime = getNewFocusedDay(newEndDateTime);
+ });
+ }
+ } else {
+ final combinedDateTime = combineDateTimes(newStartDateTime, dateTime);
+ widget.onDaySelected?.call(combinedDateTime);
+
+ setState(() {
+ dateTime = combinedDateTime;
+ focusedDateTime = getNewFocusedDay(combinedDateTime);
+ });
+ }
+ }
+
+ DateTime combineDateTimes(DateTime date, DateTime? time) {
+ final timeComponent = time == null
+ ? Duration.zero
+ : Duration(hours: time.hour, minutes: time.minute);
+
+ return DateTime(date.year, date.month, date.day).add(timeComponent);
+ }
+
+ void onStartTimeChanged(DateTime value) {
+ if (isRange) {
+ DateTime end = endDateTime ?? value;
+ if (end.isBefore(value)) {
+ (value, end) = (end, value);
+ }
+
+ widget.onRangeSelected?.call(value, end);
+
+ setState(() {
+ dateTime = value;
+ startDateTime = value;
+ endDateTime = end;
+ focusedDateTime = getNewFocusedDay(value);
+ });
+ } else {
+ widget.onDaySelected?.call(value);
+
+ setState(() {
+ dateTime = value;
+ focusedDateTime = getNewFocusedDay(value);
+ });
+ }
+ }
+
+ void onEndTimeChanged(DateTime value) {
+ if (isRange) {
+ DateTime start = startDateTime ?? value;
+ if (value.isBefore(start)) {
+ (start, value) = (value, start);
+ }
+
+ widget.onRangeSelected?.call(start, value);
+
+ if (endDateTime == null) {
+ // hAcK: Resetting these state variables to null to reset the click counter of the table calendar widget, which doesn't expose a controller for us to do so otherwise. The parent widget needs to provide the data again so that it can be shown.
+ setState(() {
+ dateTime = startDateTime = endDateTime = null;
+ focusedDateTime = getNewFocusedDay(value);
+ });
+ } else {
+ setState(() {
+ dateTime = start;
+ startDateTime = start;
+ endDateTime = value;
+ focusedDateTime = getNewFocusedDay(value);
+ });
+ }
+ } else {
+ widget.onDaySelected?.call(value);
+
+ setState(() {
+ dateTime = value;
+ focusedDateTime = getNewFocusedDay(value);
+ });
+ }
+ }
+
+ DateTime getNewFocusedDay(DateTime dateTime) {
+ if (focusedDateTime.year != dateTime.year ||
+ focusedDateTime.month != dateTime.month) {
+ return DateTime(dateTime.year, dateTime.month);
+ } else {
+ return focusedDateTime;
+ }
+ }
}
class _Divider extends StatelessWidget {
@@ -295,48 +466,54 @@ class _ReminderSelectHeader extends StatelessWidget {
}
}
-class _IncludeTimePicker extends StatefulWidget {
- const _IncludeTimePicker({
+class _TimePicker extends StatelessWidget {
+ const _TimePicker({
+ required this.dateTime,
+ required this.endDateTime,
+ required this.dateFormat,
+ required this.timeFormat,
required this.includeTime,
- this.dateStr,
- this.endDateStr,
- this.timeStr,
- this.endTimeStr,
- this.rebuildOnTimeChanged = false,
- required this.use24hFormat,
+ required this.isRange,
required this.onStartTimeChanged,
- required this.onEndTimeChanged,
+ this.onEndTimeChanged,
});
- final bool includeTime;
-
- final String? dateStr;
- final String? endDateStr;
-
- final String? timeStr;
- final String? endTimeStr;
+ final DateTime? dateTime;
+ final DateTime? endDateTime;
- final bool rebuildOnTimeChanged;
-
- final bool use24hFormat;
-
- final Function(String? time) onStartTimeChanged;
- final Function(String? time)? onEndTimeChanged;
+ final bool includeTime;
+ final bool isRange;
- @override
- State<_IncludeTimePicker> createState() => _IncludeTimePickerState();
-}
+ final DateFormatPB dateFormat;
+ final TimeFormatPB timeFormat;
-class _IncludeTimePickerState extends State<_IncludeTimePicker> {
- late String? _timeStr = widget.timeStr;
- late String? _endTimeStr = widget.endTimeStr;
+ final void Function(DateTime time) onStartTimeChanged;
+ final void Function(DateTime time)? onEndTimeChanged;
@override
Widget build(BuildContext context) {
- if (widget.dateStr == null || widget.dateStr!.isEmpty) {
+ final dateStr = getDateStr(dateTime);
+ final timeStr = getTimeStr(dateTime);
+ final endDateStr = getDateStr(endDateTime);
+ final endTimeStr = getTimeStr(endDateTime);
+
+ if (dateStr.isEmpty) {
return const Divider(height: 1);
}
+ if (endDateStr.isEmpty) {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ child: _buildTime(
+ context,
+ dateStr,
+ timeStr,
+ includeTime,
+ false,
+ ),
+ );
+ }
+
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Column(
@@ -344,20 +521,18 @@ class _IncludeTimePickerState extends State<_IncludeTimePicker> {
children: [
_buildTime(
context,
- widget.includeTime,
- widget.use24hFormat,
+ dateStr,
+ timeStr,
+ includeTime,
true,
- widget.dateStr,
- widget.rebuildOnTimeChanged ? _timeStr : widget.timeStr,
),
VSpace(8.0, color: Theme.of(context).colorScheme.surface),
_buildTime(
context,
- widget.includeTime,
- widget.use24hFormat,
+ endDateStr,
+ endTimeStr,
+ includeTime,
false,
- widget.endDateStr,
- widget.rebuildOnTimeChanged ? _endTimeStr : widget.endTimeStr,
),
],
),
@@ -366,11 +541,10 @@ class _IncludeTimePickerState extends State<_IncludeTimePicker> {
Widget _buildTime(
BuildContext context,
- bool isIncludeTime,
- bool use24hFormat,
- bool isStartDay,
String? dateStr,
String? timeStr,
+ bool includeTime,
+ bool isStartDay,
) {
if (dateStr == null) {
return const SizedBox.shrink();
@@ -378,23 +552,65 @@ class _IncludeTimePickerState extends State<_IncludeTimePicker> {
final List<Widget> children = [];
- if (!isIncludeTime) {
- children.addAll([
- const HSpace(12.0),
- FlowyText(dateStr),
- ]);
+ if (!includeTime) {
+ children.add(
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12.0),
+ child: GestureDetector(
+ onTap: () async {
+ final result = await _showDateTimePicker(
+ context,
+ isStartDay ? dateTime : endDateTime,
+ use24hFormat: timeFormat == TimeFormatPB.TwentyFourHour,
+ mode: CupertinoDatePickerMode.date,
+ );
+ handleDateTimePickerResult(result, isStartDay);
+ },
+ child: FlowyText(dateStr),
+ ),
+ ),
+ ),
+ );
} else {
children.addAll([
- Expanded(child: FlowyText(dateStr, textAlign: TextAlign.center)),
- Container(width: 1, height: 16, color: Colors.grey),
Expanded(
child: GestureDetector(
- onTap: () => _showTimePicker(
- context,
- use24hFormat: use24hFormat,
- isStartDay: isStartDay,
+ onTap: () async {
+ final result = await _showDateTimePicker(
+ context,
+ isStartDay ? dateTime : endDateTime,
+ use24hFormat: timeFormat == TimeFormatPB.TwentyFourHour,
+ mode: CupertinoDatePickerMode.date,
+ );
+ handleDateTimePickerResult(result, isStartDay);
+ },
+ child: FlowyText(
+ dateStr,
+ textAlign: TextAlign.center,
+ ),
+ ),
+ ),
+ Container(
+ width: 1,
+ height: 16,
+ color: Theme.of(context).colorScheme.outline,
+ ),
+ Expanded(
+ child: GestureDetector(
+ onTap: () async {
+ final result = await _showDateTimePicker(
+ context,
+ isStartDay ? dateTime : endDateTime,
+ use24hFormat: timeFormat == TimeFormatPB.TwentyFourHour,
+ mode: CupertinoDatePickerMode.time,
+ );
+ handleDateTimePickerResult(result, isStartDay);
+ },
+ child: FlowyText(
+ timeStr!,
+ textAlign: TextAlign.center,
),
- child: FlowyText(timeStr ?? '', textAlign: TextAlign.center),
),
),
]);
@@ -413,15 +629,13 @@ class _IncludeTimePickerState extends State<_IncludeTimePicker> {
);
}
- Future<void> _showTimePicker(
- BuildContext context, {
+ Future<DateTime?> _showDateTimePicker(
+ BuildContext context,
+ DateTime? dateTime, {
+ required CupertinoDatePickerMode mode,
required bool use24hFormat,
- required bool isStartDay,
}) async {
- String? selectedTime = isStartDay ? _timeStr : _endTimeStr;
- final initialDateTime = selectedTime != null
- ? _convertTimeStringToDateTime(selectedTime)
- : null;
+ DateTime? result;
return showMobileBottomSheet(
context,
@@ -431,13 +645,11 @@ class _IncludeTimePickerState extends State<_IncludeTimePicker> {
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 300),
child: CupertinoDatePicker(
- mode: CupertinoDatePickerMode.time,
- initialDateTime: initialDateTime,
+ mode: mode,
+ initialDateTime: dateTime,
use24hFormat: use24hFormat,
onDateTimeChanged: (dateTime) {
- selectedTime = use24hFormat
- ? DateFormat('HH:mm').format(dateTime)
- : DateFormat('hh:mm a').format(dateTime);
+ result = dateTime;
},
),
),
@@ -450,21 +662,7 @@ class _IncludeTimePickerState extends State<_IncludeTimePicker> {
fontColor: Theme.of(context).colorScheme.onPrimary,
fillColor: Theme.of(context).primaryColor,
onPressed: () {
- if (isStartDay) {
- widget.onStartTimeChanged(selectedTime);
-
- if (widget.rebuildOnTimeChanged && mounted) {
- setState(() => _timeStr = selectedTime);
- }
- } else {
- widget.onEndTimeChanged?.call(selectedTime);
-
- if (widget.rebuildOnTimeChanged && mounted) {
- setState(() => _endTimeStr = selectedTime);
- }
- }
-
- Navigator.of(context).pop();
+ Navigator.of(context).pop(result);
},
),
),
@@ -474,24 +672,48 @@ class _IncludeTimePickerState extends State<_IncludeTimePicker> {
);
}
- DateTime _convertTimeStringToDateTime(String timeString) {
- final DateTime now = DateTime.now();
-
- final List<String> timeParts = timeString.split(':');
+ void handleDateTimePickerResult(DateTime? result, bool isStartDay) {
+ if (result == null) {
+ return;
+ } else if (isStartDay) {
+ onStartTimeChanged(result);
+ } else {
+ onEndTimeChanged?.call(result);
+ }
+ }
- if (timeParts.length != 2) {
- return now;
+ String getDateStr(DateTime? dateTime) {
+ if (dateTime == null) {
+ return "";
}
+ final format = DateFormat(
+ switch (dateFormat) {
+ DateFormatPB.Local => 'MM/dd/y',
+ DateFormatPB.US => 'y/MM/dd',
+ DateFormatPB.ISO => 'y-MM-dd',
+ DateFormatPB.Friendly => 'MMM dd, y',
+ DateFormatPB.DayMonthYear => 'dd/MM/y',
+ _ => 'MMM dd, y',
+ },
+ );
- final int hour = int.parse(timeParts[0]);
- final int minute = int.parse(timeParts[1]);
+ return format.format(dateTime);
+ }
+
+ String getTimeStr(DateTime? dateTime) {
+ if (dateTime == null || !includeTime) {
+ return "";
+ }
+ final format = timeFormat == TimeFormatPB.TwelveHour
+ ? DateFormat.jm()
+ : DateFormat.Hm();
- return DateTime(now.year, now.month, now.day, hour, minute);
+ return format.format(dateTime);
}
}
-class _EndDateSwitch extends StatelessWidget {
- const _EndDateSwitch({
+class _IsRangeSwitch extends StatelessWidget {
+ const _IsRangeSwitch({
required this.isRange,
required this.onRangeChanged,
});
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/date_picker.dart b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/date_picker.dart
index 876e1cfa46..5cbdc2bc43 100644
--- a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/date_picker.dart
+++ b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/date_picker.dart
@@ -1,4 +1,3 @@
-import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra/theme_extension.dart';
import 'package:flutter/material.dart';
@@ -16,8 +15,7 @@ class DatePicker extends StatefulWidget {
this.startDay,
this.endDay,
this.selectedDay,
- this.firstDay,
- this.lastDay,
+ required this.focusedDay,
this.onDaySelected,
this.onRangeSelected,
this.onCalendarCreated,
@@ -31,20 +29,14 @@ class DatePicker extends StatefulWidget {
final DateTime? endDay;
final DateTime? selectedDay;
- /// If not provided, defaults to 1st January 1970
- ///
- final DateTime? firstDay;
+ final DateTime focusedDay;
- /// If not provided, defaults to 1st January 2100
- ///
- final DateTime? lastDay;
-
- final Function(
+ final void Function(
DateTime selectedDay,
DateTime focusedDay,
)? onDaySelected;
- final Function(
+ final void Function(
DateTime? start,
DateTime? end,
DateTime focusedDay,
@@ -59,7 +51,6 @@ class DatePicker extends StatefulWidget {
}
class _DatePickerState extends State<DatePicker> {
- late DateTime _focusedDay = widget.selectedDay ?? DateTime.now();
late CalendarFormat _calendarFormat = widget.calendarFormat;
@override
@@ -78,8 +69,6 @@ class _DatePickerState extends State<DatePicker> {
),
)
: _CalendarStyle.desktop(
- textStyle: textStyle,
- iconColor: Theme.of(context).iconTheme.color,
dowTextStyle: AFThemeExtension.of(context).caption,
selectedColor: Theme.of(context).colorScheme.primary,
);
@@ -87,9 +76,9 @@ class _DatePickerState extends State<DatePicker> {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: TableCalendar(
- firstDay: widget.firstDay ?? kFirstDay,
- lastDay: widget.lastDay ?? kLastDay,
- focusedDay: _focusedDay,
+ firstDay: kFirstDay,
+ lastDay: kLastDay,
+ focusedDay: widget.focusedDay,
rowHeight: calendarStyle.rowHeight,
calendarFormat: _calendarFormat,
daysOfWeekHeight: calendarStyle.dowHeight,
@@ -156,7 +145,6 @@ class _DatePickerState extends State<DatePicker> {
setState(() => _calendarFormat = calendarFormat),
onPageChanged: (focusedDay) {
widget.onPageChanged?.call(focusedDay);
- setState(() => _focusedDay = focusedDay);
},
onDaySelected: widget.onDaySelected,
onRangeSelected: widget.onRangeSelected,
@@ -167,26 +155,13 @@ class _DatePickerState extends State<DatePicker> {
class _CalendarStyle {
_CalendarStyle.desktop({
- required TextStyle textStyle,
required this.selectedColor,
required this.dowTextStyle,
- Color? iconColor,
}) : rowHeight = 33,
dowHeight = 35,
- headerVisible = true,
- headerStyle = HeaderStyle(
- formatButtonVisible: false,
- titleCentered: true,
- titleTextStyle: textStyle,
- leftChevronMargin: EdgeInsets.zero,
- leftChevronPadding: EdgeInsets.zero,
- leftChevronIcon: FlowySvg(FlowySvgs.arrow_left_s, color: iconColor),
- rightChevronPadding: EdgeInsets.zero,
- rightChevronMargin: EdgeInsets.zero,
- rightChevronIcon: FlowySvg(FlowySvgs.arrow_right_s, color: iconColor),
- headerPadding: const EdgeInsets.only(bottom: 8.0),
- ),
- availableGestures = AvailableGestures.all;
+ headerVisible = false,
+ headerStyle = const HeaderStyle(),
+ availableGestures = AvailableGestures.horizontalSwipe;
_CalendarStyle.mobile({required this.dowTextStyle})
: rowHeight = 48,
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/date_picker_dialog.dart b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/date_picker_dialog.dart
index ceeb0d2832..ae8e58c468 100644
--- a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/date_picker_dialog.dart
+++ b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/date_picker_dialog.dart
@@ -17,20 +17,13 @@ class DatePickerOptions {
DateTime? focusedDay,
this.popoverMutex,
this.selectedDay,
- this.firstDay,
- this.lastDay,
- this.timeStr,
- this.endTimeStr,
this.includeTime = false,
this.isRange = false,
- this.enableRanges = true,
this.dateFormat = UserDateFormatPB.Friendly,
this.timeFormat = UserTimeFormatPB.TwentyFourHour,
this.selectedReminderOption,
this.onDaySelected,
required this.onIncludeTimeChanged,
- this.onStartTimeChanged,
- this.onEndTimeChanged,
this.onRangeSelected,
this.onIsRangeChanged,
this.onReminderSelected,
@@ -39,23 +32,16 @@ class DatePickerOptions {
final DateTime focusedDay;
final PopoverMutex? popoverMutex;
final DateTime? selectedDay;
- final DateTime? firstDay;
- final DateTime? lastDay;
- final String? timeStr;
- final String? endTimeStr;
final bool includeTime;
final bool isRange;
- final bool enableRanges;
final UserDateFormatPB dateFormat;
final UserTimeFormatPB timeFormat;
final ReminderOption? selectedReminderOption;
final DaySelectedCallback? onDaySelected;
- final IncludeTimeChangedCallback onIncludeTimeChanged;
- final TimeChangedCallback? onStartTimeChanged;
- final TimeChangedCallback? onEndTimeChanged;
final RangeSelectedCallback? onRangeSelected;
- final Function(bool)? onIsRangeChanged;
+ final IncludeTimeChangedCallback onIncludeTimeChanged;
+ final void Function(bool)? onIsRangeChanged;
final OnReminderSelected? onReminderSelected;
}
@@ -65,8 +51,7 @@ abstract class DatePickerService {
}
const double _datePickerWidth = 260;
-const double _datePickerHeight = 370;
-const double _includeTimeHeight = 32;
+const double _datePickerHeight = 404;
const double _ySpacing = 15;
class DatePickerMenu extends DatePickerService {
@@ -146,7 +131,7 @@ class DatePickerMenu extends DatePickerService {
}
}
-class _AnimatedDatePicker extends StatefulWidget {
+class _AnimatedDatePicker extends StatelessWidget {
const _AnimatedDatePicker({
required this.offset,
required this.showBelow,
@@ -157,26 +142,14 @@ class _AnimatedDatePicker extends StatefulWidget {
final bool showBelow;
final DatePickerOptions options;
- @override
- State<_AnimatedDatePicker> createState() => _AnimatedDatePickerState();
-}
-
-class _AnimatedDatePickerState extends State<_AnimatedDatePicker> {
- late bool _includeTime = widget.options.includeTime;
-
@override
Widget build(BuildContext context) {
- double dy = widget.offset.dy;
- if (!widget.showBelow && _includeTime) {
- dy -= _includeTimeHeight;
- }
-
- dy += (widget.showBelow ? _ySpacing : -_ySpacing);
+ final dy = offset.dy + (showBelow ? _ySpacing : -_ySpacing);
return AnimatedPositioned(
duration: const Duration(milliseconds: 200),
top: dy,
- left: widget.offset.dx,
+ left: offset.dx,
child: Container(
decoration: FlowyDecoration.decoration(
Theme.of(context).cardColor,
@@ -184,29 +157,20 @@ class _AnimatedDatePickerState extends State<_AnimatedDatePicker> {
),
constraints: BoxConstraints.loose(const Size(_datePickerWidth, 465)),
child: AppFlowyDatePicker(
- includeTime: _includeTime,
+ includeTime: options.includeTime,
onIncludeTimeChanged: (includeTime) {
- widget.options.onIncludeTimeChanged.call(includeTime);
- setState(() => _includeTime = includeTime);
+ options.onIncludeTimeChanged.call(includeTime);
},
- enableRanges: widget.options.enableRanges,
- isRange: widget.options.isRange,
- onIsRangeChanged: widget.options.onIsRangeChanged,
- dateFormat: widget.options.dateFormat.simplified,
- timeFormat: widget.options.timeFormat.simplified,
- selectedDay: widget.options.selectedDay,
- focusedDay: widget.options.focusedDay,
- firstDay: widget.options.firstDay,
- lastDay: widget.options.lastDay,
- timeStr: widget.options.timeStr,
- endTimeStr: widget.options.endTimeStr,
- popoverMutex: widget.options.popoverMutex,
- selectedReminderOption:
- widget.options.selectedReminderOption ?? ReminderOption.none,
- onStartTimeSubmitted: widget.options.onStartTimeChanged,
- onDaySelected: widget.options.onDaySelected,
- onRangeSelected: widget.options.onRangeSelected,
- onReminderSelected: widget.options.onReminderSelected,
+ isRange: options.isRange,
+ onIsRangeChanged: options.onIsRangeChanged,
+ dateFormat: options.dateFormat.simplified,
+ timeFormat: options.timeFormat.simplified,
+ dateTime: options.selectedDay,
+ popoverMutex: options.popoverMutex,
+ reminderOption: options.selectedReminderOption ?? ReminderOption.none,
+ onDaySelected: options.onDaySelected,
+ onRangeSelected: options.onRangeSelected,
+ onReminderSelected: options.onReminderSelected,
),
),
);
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/date_time_text_field.dart b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/date_time_text_field.dart
new file mode 100644
index 0000000000..ad663420aa
--- /dev/null
+++ b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/date_time_text_field.dart
@@ -0,0 +1,359 @@
+import 'package:any_date/any_date.dart';
+import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/date.dart';
+import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pbenum.dart';
+import 'package:appflowy_popover/appflowy_popover.dart';
+import 'package:easy_localization/easy_localization.dart';
+import 'package:flowy_infra/size.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../appflowy_date_picker.dart';
+import 'date_picker.dart';
+
+class DateTimeTextField extends StatefulWidget {
+ const DateTimeTextField({
+ super.key,
+ required this.dateTime,
+ required this.includeTime,
+ required this.dateFormat,
+ this.timeFormat,
+ this.onSubmitted,
+ this.popoverMutex,
+ this.isTabPressed,
+ this.refreshTextController,
+ }) : assert(includeTime && timeFormat != null || !includeTime);
+
+ final DateTime? dateTime;
+ final bool includeTime;
+ final void Function(DateTime dateTime)? onSubmitted;
+ final DateFormatPB dateFormat;
+ final TimeFormatPB? timeFormat;
+ final PopoverMutex? popoverMutex;
+ final ValueNotifier<bool>? isTabPressed;
+ final RefreshDateTimeTextFieldController? refreshTextController;
+
+ @override
+ State<DateTimeTextField> createState() => _DateTimeTextFieldState();
+}
+
+class _DateTimeTextFieldState extends State<DateTimeTextField> {
+ late final FocusNode focusNode;
+ late final FocusNode dateFocusNode;
+ late final FocusNode timeFocusNode;
+
+ final dateTextController = TextEditingController();
+ final timeTextController = TextEditingController();
+
+ final statesController = WidgetStatesController();
+
+ bool justSubmitted = false;
+
+ @override
+ void initState() {
+ super.initState();
+ updateTextControllers();
+
+ focusNode = FocusNode()..addListener(focusNodeListener);
+ dateFocusNode = FocusNode(onKeyEvent: textFieldOnKeyEvent)
+ ..addListener(dateFocusNodeListener);
+ timeFocusNode = FocusNode(onKeyEvent: textFieldOnKeyEvent)
+ ..addListener(timeFocusNodeListener);
+ widget.isTabPressed?.addListener(isTabPressedListener);
+ widget.refreshTextController?.addListener(updateTextControllers);
+ widget.popoverMutex?.addPopoverListener(popoverListener);
+ }
+
+ @override
+ void didUpdateWidget(covariant oldWidget) {
+ if (oldWidget.dateTime != widget.dateTime ||
+ oldWidget.dateFormat != widget.dateFormat ||
+ oldWidget.timeFormat != widget.timeFormat) {
+ statesController.update(WidgetState.error, false);
+ updateTextControllers();
+ }
+ super.didUpdateWidget(oldWidget);
+ }
+
+ @override
+ void dispose() {
+ dateTextController.dispose();
+ timeTextController.dispose();
+ widget.popoverMutex?.removePopoverListener(popoverListener);
+ widget.isTabPressed?.removeListener(isTabPressedListener);
+ widget.refreshTextController?.removeListener(updateTextControllers);
+ dateFocusNode
+ ..removeListener(dateFocusNodeListener)
+ ..dispose();
+ timeFocusNode
+ ..removeListener(timeFocusNodeListener)
+ ..dispose();
+ focusNode
+ ..removeListener(focusNodeListener)
+ ..dispose();
+ statesController.dispose();
+ super.dispose();
+ }
+
+ void focusNodeListener() {
+ if (focusNode.hasFocus) {
+ statesController.update(WidgetState.focused, true);
+ widget.popoverMutex?.close();
+ } else {
+ statesController.update(WidgetState.focused, false);
+ }
+ }
+
+ void isTabPressedListener() {
+ if (!dateFocusNode.hasFocus && !timeFocusNode.hasFocus) {
+ return;
+ }
+ final controller =
+ dateFocusNode.hasFocus ? dateTextController : timeTextController;
+ if (widget.isTabPressed != null && widget.isTabPressed!.value) {
+ controller.selection = TextSelection(
+ baseOffset: 0,
+ extentOffset: controller.text.characters.length,
+ );
+ widget.isTabPressed?.value = false;
+ }
+ }
+
+ KeyEventResult textFieldOnKeyEvent(FocusNode node, KeyEvent event) {
+ if (event is KeyUpEvent && event.logicalKey == LogicalKeyboardKey.tab) {
+ widget.isTabPressed?.value = true;
+ }
+ return KeyEventResult.ignored;
+ }
+
+ void dateFocusNodeListener() {
+ if (dateFocusNode.hasFocus || justSubmitted) {
+ justSubmitted = true;
+ return;
+ }
+
+ final expected = widget.dateTime == null
+ ? ""
+ : DateFormat(widget.dateFormat.pattern).format(widget.dateTime!);
+ if (expected != dateTextController.text.trim()) {
+ onDateTextFieldSubmitted();
+ }
+ }
+
+ void timeFocusNodeListener() {
+ if (timeFocusNode.hasFocus || widget.timeFormat == null || justSubmitted) {
+ justSubmitted = true;
+ return;
+ }
+
+ final expected = widget.dateTime == null
+ ? ""
+ : DateFormat(widget.timeFormat!.pattern).format(widget.dateTime!);
+ if (expected != timeTextController.text.trim()) {
+ onTimeTextFieldSubmitted();
+ }
+ }
+
+ void popoverListener() {
+ if (focusNode.hasFocus) {
+ focusNode.unfocus();
+ }
+ }
+
+ void updateTextControllers() {
+ if (widget.dateTime == null) {
+ dateTextController.clear();
+ timeTextController.clear();
+ return;
+ }
+
+ final dateFormat = DateFormat(widget.dateFormat.pattern);
+ final timeFormat = DateFormat(widget.timeFormat?.pattern);
+
+ dateTextController.text = dateFormat.format(widget.dateTime!);
+ timeTextController.text = timeFormat.format(widget.dateTime!);
+ }
+
+ void onDateTextFieldSubmitted() {
+ DateTime? dateTime = parseDateTimeStr(dateTextController.text.trim());
+ if (dateTime == null) {
+ statesController.update(WidgetState.error, true);
+ return;
+ }
+ statesController.update(WidgetState.error, false);
+ if (widget.dateTime != null) {
+ final timeComponent = Duration(
+ hours: widget.dateTime!.hour,
+ minutes: widget.dateTime!.minute,
+ seconds: widget.dateTime!.second,
+ );
+ dateTime = DateTime(
+ dateTime.year,
+ dateTime.month,
+ dateTime.day,
+ ).add(timeComponent);
+ }
+ widget.onSubmitted?.call(dateTime);
+ }
+
+ void onTimeTextFieldSubmitted() {
+ final adjustedTimeStr = "Jan 01, 2000 ${timeTextController.text.trim()}";
+ DateTime? dateTime = parseDateTimeStr(adjustedTimeStr);
+
+ if (dateTime == null) {
+ statesController.update(WidgetState.error, true);
+ return;
+ }
+ statesController.update(WidgetState.error, false);
+ final dateComponent = widget.dateTime ?? DateTime.now();
+ final timeComponent = Duration(
+ hours: dateTime.hour,
+ minutes: dateTime.minute,
+ seconds: dateTime.second,
+ );
+ dateTime = DateTime(
+ dateComponent.year,
+ dateComponent.month,
+ dateComponent.day,
+ ).add(timeComponent);
+ widget.onSubmitted?.call(dateTime);
+ }
+
+ DateTime? parseDateTimeStr(String string) {
+ final locale = context.locale.toLanguageTag();
+ final parser = AnyDate.fromLocale(locale);
+ late DateTime? result;
+ try {
+ result = parser.parse(string);
+ if (result.isBefore(kFirstDay) || result.isAfter(kLastDay)) {
+ result = null;
+ }
+ } catch (err) {
+ result = null;
+ }
+ return result;
+ }
+
+ late final WidgetStateProperty<Color?> borderColor =
+ WidgetStateProperty.resolveWith(
+ (states) {
+ if (states.contains(WidgetState.error)) {
+ return Theme.of(context).colorScheme.errorContainer;
+ }
+ if (states.contains(WidgetState.focused)) {
+ return Theme.of(context).colorScheme.primary;
+ }
+ return Theme.of(context).colorScheme.outline;
+ },
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ return Focus(
+ focusNode: focusNode,
+ skipTraversal: true,
+ child: wrapWithGestures(
+ child: ListenableBuilder(
+ listenable: statesController,
+ builder: (context, child) {
+ final resolved = borderColor.resolve(statesController.value);
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 18.0),
+ child: Container(
+ constraints: const BoxConstraints.tightFor(height: 32),
+ decoration: BoxDecoration(
+ border: Border.fromBorderSide(
+ BorderSide(
+ color: resolved ?? Colors.transparent,
+ ),
+ ),
+ borderRadius: Corners.s8Border,
+ ),
+ child: child,
+ ),
+ );
+ },
+ child: widget.includeTime
+ ? Row(
+ children: [
+ Expanded(
+ child: TextField(
+ key: const ValueKey('date_time_text_field_date'),
+ focusNode: dateFocusNode,
+ controller: dateTextController,
+ style: Theme.of(context).textTheme.bodyMedium,
+ decoration: getInputDecoration(
+ const EdgeInsetsDirectional.fromSTEB(12, 6, 6, 6),
+ ),
+ onSubmitted: (value) {
+ justSubmitted = true;
+ onDateTextFieldSubmitted();
+ },
+ ),
+ ),
+ VerticalDivider(
+ indent: 4,
+ endIndent: 4,
+ width: 1,
+ color: Theme.of(context).colorScheme.outline,
+ ),
+ Expanded(
+ child: TextField(
+ key: const ValueKey('date_time_text_field_time'),
+ focusNode: timeFocusNode,
+ controller: timeTextController,
+ style: Theme.of(context).textTheme.bodyMedium,
+ decoration: getInputDecoration(
+ const EdgeInsetsDirectional.fromSTEB(6, 6, 12, 6),
+ ),
+ onSubmitted: (value) {
+ justSubmitted = true;
+ onTimeTextFieldSubmitted();
+ },
+ ),
+ ),
+ ],
+ )
+ : Center(
+ child: TextField(
+ key: const ValueKey('date_time_text_field_date'),
+ focusNode: dateFocusNode,
+ controller: dateTextController,
+ style: Theme.of(context).textTheme.bodyMedium,
+ decoration: getInputDecoration(
+ const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
+ ),
+ onSubmitted: (value) {
+ justSubmitted = true;
+ onDateTextFieldSubmitted();
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget wrapWithGestures({required Widget child}) {
+ return GestureDetector(
+ onTapDown: (_) {
+ statesController.update(WidgetState.pressed, true);
+ },
+ onTapCancel: () {
+ statesController.update(WidgetState.pressed, false);
+ },
+ onTap: () {
+ statesController.update(WidgetState.pressed, false);
+ },
+ child: child,
+ );
+ }
+
+ InputDecoration getInputDecoration(EdgeInsetsGeometry padding) {
+ return InputDecoration(
+ border: InputBorder.none,
+ contentPadding: padding,
+ isCollapsed: true,
+ isDense: true,
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/end_text_field.dart b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/end_text_field.dart
deleted file mode 100644
index fae8782af5..0000000000
--- a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/end_text_field.dart
+++ /dev/null
@@ -1,43 +0,0 @@
-import 'package:flutter/material.dart';
-
-import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/time_text_field.dart';
-import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pbenum.dart';
-import 'package:appflowy_popover/appflowy_popover.dart';
-
-class EndTextField extends StatelessWidget {
- const EndTextField({
- super.key,
- required this.includeTime,
- required this.isRange,
- required this.timeFormat,
- this.endTimeStr,
- this.popoverMutex,
- this.onSubmitted,
- });
-
- final bool includeTime;
- final bool isRange;
- final TimeFormatPB timeFormat;
- final String? endTimeStr;
- final PopoverMutex? popoverMutex;
- final Function(String timeStr)? onSubmitted;
-
- @override
- Widget build(BuildContext context) {
- return AnimatedSwitcher(
- duration: const Duration(milliseconds: 300),
- child: includeTime && isRange
- ? Padding(
- padding: const EdgeInsets.only(top: 8.0),
- child: TimeTextField(
- isEndTime: true,
- timeFormat: timeFormat,
- endTimeStr: endTimeStr,
- popoverMutex: popoverMutex,
- onSubmitted: onSubmitted,
- ),
- )
- : const SizedBox.shrink(),
- );
- }
-}
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/mobile_date_editor.dart b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/mobile_date_editor.dart
index 60476712e6..4d8176ba5c 100644
--- a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/mobile_date_editor.dart
+++ b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/mobile_date_editor.dart
@@ -1,7 +1,6 @@
import 'package:flutter/material.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
-import 'package:appflowy/workspace/presentation/widgets/date_picker/appflowy_date_picker.dart';
import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/date_picker.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flowy_infra_ui/flowy_infra_ui.dart';
@@ -10,39 +9,32 @@ class MobileDatePicker extends StatefulWidget {
const MobileDatePicker({
super.key,
this.selectedDay,
+ this.startDay,
+ this.endDay,
+ required this.focusedDay,
required this.isRange,
this.onDaySelected,
- this.rebuildOnDaySelected = false,
this.onRangeSelected,
- this.firstDay,
- this.lastDay,
- this.startDay,
- this.endDay,
+ this.onPageChanged,
});
final DateTime? selectedDay;
+ final DateTime? startDay;
+ final DateTime? endDay;
+ final DateTime focusedDay;
final bool isRange;
- final DaySelectedCallback? onDaySelected;
-
- final bool rebuildOnDaySelected;
- final RangeSelectedCallback? onRangeSelected;
-
- final DateTime? firstDay;
- final DateTime? lastDay;
- final DateTime? startDay;
- final DateTime? endDay;
+ final void Function(DateTime)? onDaySelected;
+ final void Function(DateTime?, DateTime?)? onRangeSelected;
+ final void Function(DateTime)? onPageChanged;
@override
State<MobileDatePicker> createState() => _MobileDatePickerState();
}
class _MobileDatePickerState extends State<MobileDatePicker> {
- PageController? _pageController;
-
- late DateTime _focusedDay = widget.selectedDay ?? DateTime.now();
- late DateTime? _selectedDay = widget.selectedDay;
+ PageController? pageController;
@override
Widget build(BuildContext context) {
@@ -60,60 +52,64 @@ class _MobileDatePickerState extends State<MobileDatePicker> {
Widget _buildCalendar(BuildContext context) {
return DatePicker(
isRange: widget.isRange,
- onDaySelected: (selectedDay, focusedDay) {
- widget.onDaySelected?.call(selectedDay, focusedDay);
-
- if (widget.rebuildOnDaySelected) {
- setState(() => _selectedDay = selectedDay);
- }
+ onDaySelected: (selectedDay, _) {
+ widget.onDaySelected?.call(selectedDay);
+ },
+ focusedDay: widget.focusedDay,
+ onRangeSelected: (start, end, focusedDay) {
+ widget.onRangeSelected?.call(start, end);
},
- onRangeSelected: widget.onRangeSelected,
- selectedDay:
- widget.rebuildOnDaySelected ? _selectedDay : widget.selectedDay,
- firstDay: widget.firstDay,
- lastDay: widget.lastDay,
+ selectedDay: widget.selectedDay,
startDay: widget.startDay,
endDay: widget.endDay,
- onCalendarCreated: (pageController) => _pageController = pageController,
- onPageChanged: (focusedDay) => setState(() => _focusedDay = focusedDay),
+ onCalendarCreated: (pageController) {
+ this.pageController = pageController;
+ },
+ onPageChanged: widget.onPageChanged,
);
}
Widget _buildHeader(BuildContext context) {
- return Row(
- children: [
- const HSpace(16.0),
- FlowyText(
- DateFormat.yMMMM().format(_focusedDay),
- ),
- const Spacer(),
- FlowyButton(
- useIntrinsicWidth: true,
- text: FlowySvg(
- FlowySvgs.arrow_left_s,
- color: Theme.of(context).iconTheme.color,
- size: const Size.square(24.0),
+ return Padding(
+ padding: const EdgeInsetsDirectional.only(start: 16, end: 8),
+ child: Row(
+ children: [
+ Expanded(
+ child: FlowyText(
+ DateFormat.yMMMM().format(widget.focusedDay),
+ ),
),
- onTap: () => _pageController?.previousPage(
- duration: const Duration(milliseconds: 300),
- curve: Curves.easeOut,
+ FlowyButton(
+ useIntrinsicWidth: true,
+ text: FlowySvg(
+ FlowySvgs.arrow_left_s,
+ color: Theme.of(context).iconTheme.color,
+ size: const Size.square(24.0),
+ ),
+ onTap: () {
+ pageController?.previousPage(
+ duration: const Duration(milliseconds: 300),
+ curve: Curves.easeOut,
+ );
+ },
),
- ),
- const HSpace(24.0),
- FlowyButton(
- useIntrinsicWidth: true,
- text: FlowySvg(
- FlowySvgs.arrow_right_s,
- color: Theme.of(context).iconTheme.color,
- size: const Size.square(24.0),
+ const HSpace(24.0),
+ FlowyButton(
+ useIntrinsicWidth: true,
+ text: FlowySvg(
+ FlowySvgs.arrow_right_s,
+ color: Theme.of(context).iconTheme.color,
+ size: const Size.square(24.0),
+ ),
+ onTap: () {
+ pageController?.nextPage(
+ duration: const Duration(milliseconds: 300),
+ curve: Curves.easeOut,
+ );
+ },
),
- onTap: () => _pageController?.nextPage(
- duration: const Duration(milliseconds: 300),
- curve: Curves.easeOut,
- ),
- ),
- const HSpace(8.0),
- ],
+ ],
+ ),
);
}
}
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart
index d7f88e8d12..528100dc9f 100644
--- a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart
+++ b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/reminder_selector.dart
@@ -51,7 +51,7 @@ class ReminderSelector extends StatelessWidget {
return SizedBox(
height: DatePickerSize.itemHeight,
child: FlowyButton(
- text: FlowyText.medium(label),
+ text: FlowyText(label),
rightIcon:
o == selectedOption ? const FlowySvg(FlowySvgs.check_s) : null,
onTap: () {
@@ -87,7 +87,7 @@ class ReminderSelector extends StatelessWidget {
child: SizedBox(
height: DatePickerSize.itemHeight,
child: FlowyButton(
- text: FlowyText.medium(LocaleKeys.datePicker_reminderLabel.tr()),
+ text: FlowyText(LocaleKeys.datePicker_reminderLabel.tr()),
rightIcon: Row(
children: [
FlowyText.regular(selectedOption.label),
@@ -191,7 +191,7 @@ enum ReminderOption {
_ => ReminderOption.custom,
};
- DateTime fromDate(DateTime date) => switch (withoutTime) {
+ DateTime getNotificationDateTime(DateTime date) => switch (withoutTime) {
true => requiresNoTime
? date.withoutTime.add(time)
: date.withoutTime.subtract(time),
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/start_text_field.dart b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/start_text_field.dart
deleted file mode 100644
index 77afa8f7e1..0000000000
--- a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/start_text_field.dart
+++ /dev/null
@@ -1,50 +0,0 @@
-import 'package:flutter/material.dart';
-
-import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/time_text_field.dart';
-import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pbenum.dart';
-import 'package:appflowy_popover/appflowy_popover.dart';
-
-class StartTextField extends StatelessWidget {
- const StartTextField({
- super.key,
- required this.includeTime,
- required this.timeFormat,
- this.timeHintText,
- this.parseEndTimeError,
- this.parseTimeError,
- this.timeStr,
- this.endTimeStr,
- this.popoverMutex,
- this.onSubmitted,
- });
-
- final bool includeTime;
- final TimeFormatPB timeFormat;
- final String? timeHintText;
- final String? parseEndTimeError;
- final String? parseTimeError;
- final String? timeStr;
- final String? endTimeStr;
- final PopoverMutex? popoverMutex;
- final Function(String timeStr)? onSubmitted;
-
- @override
- Widget build(BuildContext context) {
- return AnimatedSwitcher(
- duration: const Duration(milliseconds: 300),
- child: includeTime
- ? TimeTextField(
- isEndTime: false,
- timeFormat: timeFormat,
- timeHintText: timeHintText,
- parseEndTimeError: parseEndTimeError,
- parseTimeError: parseTimeError,
- timeStr: timeStr,
- endTimeStr: endTimeStr,
- popoverMutex: popoverMutex,
- onSubmitted: onSubmitted,
- )
- : const SizedBox.shrink(),
- );
- }
-}
diff --git a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/time_text_field.dart b/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/time_text_field.dart
deleted file mode 100644
index 99a516b4d3..0000000000
--- a/frontend/appflowy_flutter/lib/workspace/presentation/widgets/date_picker/widgets/time_text_field.dart
+++ /dev/null
@@ -1,176 +0,0 @@
-import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pbenum.dart';
-import 'package:appflowy_popover/appflowy_popover.dart';
-import 'package:flowy_infra_ui/style_widget/text_field.dart';
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import 'package:intl/intl.dart';
-
-const _maxLengthTwelveHour = 8;
-const _maxLengthTwentyFourHour = 5;
-
-class TimeTextField extends StatefulWidget {
- const TimeTextField({
- super.key,
- required this.isEndTime,
- required this.timeFormat,
- this.timeHintText,
- this.parseEndTimeError,
- this.parseTimeError,
- this.timeStr,
- this.endTimeStr,
- this.popoverMutex,
- this.onSubmitted,
- });
-
- final bool isEndTime;
- final TimeFormatPB timeFormat;
- final String? timeHintText;
- final String? parseEndTimeError;
- final String? parseTimeError;
- final String? timeStr;
- final String? endTimeStr;
- final PopoverMutex? popoverMutex;
- final Function(String timeStr)? onSubmitted;
-
- @override
- State<TimeTextField> createState() => _TimeTextFieldState();
-}
-
-class _TimeTextFieldState extends State<TimeTextField> {
- final FocusNode _focusNode = FocusNode();
- late final TextEditingController _textController = TextEditingController()
- ..text = widget.timeStr ?? "";
- String text = "";
-
- @override
- void initState() {
- super.initState();
-
- _textController.text =
- (widget.isEndTime ? widget.endTimeStr : widget.timeStr) ?? "";
-
- if (!widget.isEndTime && widget.timeStr != null) {
- text = widget.timeStr!;
- } else if (widget.endTimeStr != null) {
- text = widget.endTimeStr!;
- }
-
- if (widget.timeFormat == TimeFormatPB.TwelveHour) {
- final twentyFourHourFormat = DateFormat('HH:mm');
- final twelveHourFormat = DateFormat('hh:mm a');
- final date = twentyFourHourFormat.parse(text);
- text = twelveHourFormat.format(date);
- }
-
- _focusNode.addListener(_focusNodeListener);
- widget.popoverMutex?.addPopoverListener(_popoverListener);
- }
-
- @override
- void dispose() {
- widget.popoverMutex?.removePopoverListener(_popoverListener);
- _textController.dispose();
- _focusNode.removeListener(_focusNodeListener);
- _focusNode.dispose();
- super.dispose();
- }
-
- void _focusNodeListener() {
- if (_focusNode.hasFocus) {
- widget.popoverMutex?.close();
- }
- }
-
- void _popoverListener() {
- if (_focusNode.hasFocus) {
- _focusNode.unfocus();
- }
- }
-
- @override
- Widget build(BuildContext context) {
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 18.0),
- child: FlowyTextField(
- text: text,
- keyboardType: TextInputType.datetime,
- focusNode: _focusNode,
- autoFocus: false,
- controller: _textController,
- submitOnLeave: true,
- hintText: widget.timeHintText,
- errorText:
- widget.isEndTime ? widget.parseEndTimeError : widget.parseTimeError,
- maxLength: widget.timeFormat == TimeFormatPB.TwelveHour
- ? _maxLengthTwelveHour
- : _maxLengthTwentyFourHour,
- showCounter: false,
- inputFormatters: [
- if (widget.timeFormat == TimeFormatPB.TwelveHour) ...[
- // Allow for AM/PM if time format is 12-hour
- FilteringTextInputFormatter.allow(RegExp('[0-9:aApPmM ]')),
- ] else ...[
- // Default allow for hh:mm format
- FilteringTextInputFormatter.allow(RegExp('[0-9:]')),
- ],
- TimeInputFormatter(widget.timeFormat),
- ],
- onSubmitted: widget.onSubmitted,
- ),
- );
- }
-}
-
-class TimeInputFormatter extends TextInputFormatter {
- TimeInputFormatter(this.timeFormat);
-
- final TimeFormatPB timeFormat;
- static const int colonPosition = 2;
- static const int spacePosition = 5;
-
- @override
- TextEditingValue formatEditUpdate(
- TextEditingValue oldValue,
- TextEditingValue newValue,
- ) {
- final oldText = oldValue.text;
- final newText = newValue.text;
-
- // If the user has typed enough for a time separator(:) and hasn't already typed
- if (newText.length == colonPosition + 1 &&
- oldText.length == colonPosition &&
- !newText.contains(":")) {
- return _formatText(newText, colonPosition, ':');
- }
-
- // If the user has typed enough for an AM/PM separator and hasn't already typed
- if (timeFormat == TimeFormatPB.TwelveHour &&
- newText.length == spacePosition + 1 &&
- oldText.length == spacePosition &&
- newText[newText.length - 1] != ' ') {
- return _formatText(newText, spacePosition, ' ');
- }
-
- if (timeFormat == TimeFormatPB.TwentyFourHour &&
- newValue.text.length == 5) {
- final prefix = newValue.text.substring(0, 3);
- final suffix = newValue.text.length > 5 ? newValue.text.substring(6) : '';
-
- final minutes = int.tryParse(newValue.text.substring(3, 5));
- if (minutes == null || minutes <= 0) {
- return newValue.copyWith(text: '${prefix}00$suffix'.toUpperCase());
- } else if (minutes > 59) {
- return newValue.copyWith(text: '${prefix}59$suffix'.toUpperCase());
- }
- }
-
- return newValue.copyWith(text: newText.toUpperCase());
- }
-
- TextEditingValue _formatText(String text, int index, String separator) {
- return TextEditingValue(
- text: '${text.substring(0, index)}$separator${text.substring(index)}',
- selection: TextSelection.collapsed(offset: text.length + 1),
- );
- }
-}
diff --git a/frontend/appflowy_flutter/pubspec.lock b/frontend/appflowy_flutter/pubspec.lock
index ec03c15748..f8cda142c5 100644
--- a/frontend/appflowy_flutter/pubspec.lock
+++ b/frontend/appflowy_flutter/pubspec.lock
@@ -25,6 +25,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.11"
+ any_date:
+ dependency: "direct main"
+ description:
+ name: any_date
+ sha256: "3981efcc15edd1673bcfc1aec298cc6079029fbffb3734c7eae8ceeb878f911e"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.4"
app_links:
dependency: "direct main"
description:
diff --git a/frontend/appflowy_flutter/pubspec.yaml b/frontend/appflowy_flutter/pubspec.yaml
index 58163151ec..dc1cf8a80b 100644
--- a/frontend/appflowy_flutter/pubspec.yaml
+++ b/frontend/appflowy_flutter/pubspec.yaml
@@ -11,6 +11,7 @@ environment:
sdk: ">=3.3.0 <4.0.0"
dependencies:
+ any_date: ^1.0.4
app_links: ^3.5.0
appflowy_backend:
path: packages/appflowy_backend
diff --git a/frontend/appflowy_flutter/test/bloc_test/board_test/group_by_date_test.dart b/frontend/appflowy_flutter/test/bloc_test/board_test/group_by_date_test.dart
index 8208501f06..92998f9cc0 100644
--- a/frontend/appflowy_flutter/test/bloc_test/board_test/group_by_date_test.dart
+++ b/frontend/appflowy_flutter/test/bloc_test/board_test/group_by_date_test.dart
@@ -43,7 +43,7 @@ void main() {
);
await boardResponseFuture();
- bloc.add(DateCellEditorEvent.selectDay(DateTime.now()));
+ bloc.add(DateCellEditorEvent.updateDateTime(DateTime.now()));
await boardResponseFuture();
final gridGroupBloc = DatabaseGroupBloc(
@@ -89,7 +89,7 @@ void main() {
);
await boardResponseFuture();
- bloc.add(DateCellEditorEvent.selectDay(DateTime.now()));
+ bloc.add(DateCellEditorEvent.updateDateTime(DateTime.now()));
await boardResponseFuture();
final gridGroupBloc = DatabaseGroupBloc(
diff --git a/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/date_cell_bloc_test.dart b/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/date_cell_bloc_test.dart
new file mode 100644
index 0000000000..5277c74759
--- /dev/null
+++ b/frontend/appflowy_flutter/test/bloc_test/grid_test/cell/date_cell_bloc_test.dart
@@ -0,0 +1,174 @@
+import 'package:appflowy/plugins/database/application/cell/bloc/date_cell_editor_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/user/application/reminder/reminder_bloc.dart';
+import 'package:appflowy_backend/protobuf/flowy-database2/date_entities.pb.dart';
+import 'package:appflowy_backend/protobuf/flowy-database2/field_entities.pbenum.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:time/time.dart';
+
+import '../util.dart';
+
+void main() {
+ late AppFlowyGridTest cellTest;
+
+ setUpAll(() async {
+ cellTest = await AppFlowyGridTest.ensureInitialized();
+ });
+
+ group('date time cell bloc:', () {
+ late GridTestContext context;
+ late DateCellController cellController;
+
+ setUp(() async {
+ context = await cellTest.makeDefaultTestGrid();
+ await FieldBackendService.createField(
+ viewId: context.viewId,
+ fieldType: FieldType.DateTime,
+ );
+ await gridResponseFuture();
+ final fieldIndex = context.fieldController.fieldInfos
+ .indexWhere((field) => field.fieldType == FieldType.DateTime);
+ cellController = context.makeGridCellController(fieldIndex, 0).as();
+ });
+
+ test('select date', () async {
+ final reminderBloc = ReminderBloc();
+ final bloc = DateCellEditorBloc(
+ cellController: cellController,
+ reminderBloc: reminderBloc,
+ );
+ await gridResponseFuture();
+
+ expect(bloc.state.dateTime, null);
+ expect(bloc.state.endDateTime, null);
+ expect(bloc.state.includeTime, false);
+ expect(bloc.state.isRange, false);
+
+ final now = DateTime.now();
+ bloc.add(DateCellEditorEvent.updateDateTime(now));
+ await gridResponseFuture();
+
+ expect(bloc.state.dateTime!.isAtSameMinuteAs(now), true);
+ });
+
+ test('include time', () async {
+ final reminderBloc = ReminderBloc();
+ final bloc = DateCellEditorBloc(
+ cellController: cellController,
+ reminderBloc: reminderBloc,
+ );
+ await gridResponseFuture();
+
+ final now = DateTime.now();
+ final expected = DateTime(now.year, now.month, now.day);
+ bloc.add(const DateCellEditorEvent.setIncludeTime(true));
+ await gridResponseFuture();
+
+ expect(bloc.state.includeTime, true);
+ expect(bloc.state.dateTime!.isAtSameMinuteAs(expected), true);
+ expect(bloc.state.endDateTime, null);
+
+ bloc.add(const DateCellEditorEvent.setIncludeTime(false));
+ await gridResponseFuture();
+
+ expect(bloc.state.includeTime, false);
+ expect(bloc.state.dateTime!.isAtSameMinuteAs(expected), true);
+ expect(bloc.state.endDateTime, null);
+ });
+
+ test('end time', () async {
+ final reminderBloc = ReminderBloc();
+ final bloc = DateCellEditorBloc(
+ cellController: cellController,
+ reminderBloc: reminderBloc,
+ );
+ await gridResponseFuture();
+
+ expect(bloc.state.isRange, false);
+ expect(bloc.state.dateTime, null);
+ expect(bloc.state.endDateTime, null);
+
+ final now = DateTime.now();
+ final expected = DateTime(now.year, now.month, now.day);
+ bloc.add(const DateCellEditorEvent.setIsRange(true));
+ await gridResponseFuture();
+
+ expect(bloc.state.isRange, true);
+ expect(bloc.state.dateTime!.isAtSameMinuteAs(expected), true);
+ expect(bloc.state.endDateTime!.isAtSameMinuteAs(expected), true);
+
+ bloc.add(const DateCellEditorEvent.setIsRange(false));
+ await gridResponseFuture();
+
+ expect(bloc.state.isRange, false);
+ expect(bloc.state.dateTime!.isAtSameMinuteAs(expected), true);
+ expect(bloc.state.endDateTime, null);
+ });
+
+ test('clear date', () async {
+ final reminderBloc = ReminderBloc();
+ final bloc = DateCellEditorBloc(
+ cellController: cellController,
+ reminderBloc: reminderBloc,
+ );
+ await gridResponseFuture();
+
+ final now = DateTime.now();
+ final expected = DateTime(now.year, now.month, now.day);
+ bloc.add(const DateCellEditorEvent.setIsRange(true));
+ await gridResponseFuture();
+ bloc.add(const DateCellEditorEvent.setIncludeTime(true));
+ await gridResponseFuture();
+
+ expect(bloc.state.isRange, true);
+ expect(bloc.state.includeTime, true);
+ expect(bloc.state.dateTime!.isAtSameMinuteAs(expected), true);
+ expect(bloc.state.endDateTime!.isAtSameMinuteAs(expected), true);
+
+ bloc.add(const DateCellEditorEvent.clearDate());
+ await gridResponseFuture();
+
+ expect(bloc.state.dateTime, null);
+ expect(bloc.state.endDateTime, null);
+ expect(bloc.state.includeTime, false);
+ expect(bloc.state.isRange, false);
+ });
+
+ test('set date format', () async {
+ final reminderBloc = ReminderBloc();
+ final bloc = DateCellEditorBloc(
+ cellController: cellController,
+ reminderBloc: reminderBloc,
+ );
+ await gridResponseFuture();
+
+ expect(
+ bloc.state.dateTypeOptionPB.dateFormat,
+ DateFormatPB.Friendly,
+ );
+ expect(
+ bloc.state.dateTypeOptionPB.timeFormat,
+ TimeFormatPB.TwentyFourHour,
+ );
+
+ bloc.add(
+ const DateCellEditorEvent.setDateFormat(DateFormatPB.ISO),
+ );
+ await gridResponseFuture();
+ expect(
+ bloc.state.dateTypeOptionPB.dateFormat,
+ DateFormatPB.ISO,
+ );
+
+ bloc.add(
+ const DateCellEditorEvent.setTimeFormat(TimeFormatPB.TwelveHour),
+ );
+ await gridResponseFuture();
+ expect(
+ bloc.state.dateTypeOptionPB.timeFormat,
+ TimeFormatPB.TwelveHour,
+ );
+ });
+ });
+}
diff --git a/frontend/appflowy_flutter/test/widget_test/date_picker_test.dart b/frontend/appflowy_flutter/test/widget_test/date_picker_test.dart
new file mode 100644
index 0000000000..c834b3595f
--- /dev/null
+++ b/frontend/appflowy_flutter/test/widget_test/date_picker_test.dart
@@ -0,0 +1,808 @@
+import 'package:appflowy/generated/flowy_svgs.g.dart';
+import 'package:appflowy/plugins/database/widgets/cell/editable_cell_skeleton/date.dart';
+import 'package:appflowy/plugins/database/widgets/field/type_option_editor/date/date_time_format.dart';
+import 'package:appflowy/workspace/presentation/widgets/date_picker/appflowy_date_picker.dart';
+import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/date_picker.dart';
+import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/date_time_text_field.dart';
+import 'package:appflowy/workspace/presentation/widgets/date_picker/widgets/end_time_button.dart';
+import 'package:appflowy/workspace/presentation/widgets/toggle/toggle.dart';
+import 'package:appflowy_backend/protobuf/flowy-database2/protobuf.dart';
+import 'package:easy_localization/easy_localization.dart';
+import 'package:flowy_infra/theme_extension.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'package:table_calendar/table_calendar.dart';
+import 'package:time/time.dart';
+
+import '../../integration_test/shared/util.dart';
+import 'test_asset_bundle.dart';
+
+const _mockDatePickerDelay = Duration(milliseconds: 200);
+
+class _DatePickerDataStub {
+ _DatePickerDataStub({
+ required this.dateTime,
+ required this.endDateTime,
+ required this.includeTime,
+ required this.isRange,
+ });
+
+ _DatePickerDataStub.empty()
+ : dateTime = null,
+ endDateTime = null,
+ includeTime = false,
+ isRange = false;
+
+ DateTime? dateTime;
+ DateTime? endDateTime;
+ bool includeTime;
+ bool isRange;
+}
+
+class _MockDatePicker extends StatefulWidget {
+ const _MockDatePicker({
+ this.data,
+ this.dateFormat,
+ this.timeFormat,
+ });
+
+ final _DatePickerDataStub? data;
+ final DateFormatPB? dateFormat;
+ final TimeFormatPB? timeFormat;
+
+ @override
+ State<_MockDatePicker> createState() => _MockDatePickerState();
+}
+
+class _MockDatePickerState extends State<_MockDatePicker> {
+ late final _DatePickerDataStub data;
+ late DateFormatPB dateFormat;
+ late TimeFormatPB timeFormat;
+
+ @override
+ void initState() {
+ super.initState();
+ data = widget.data ?? _DatePickerDataStub.empty();
+ dateFormat = widget.dateFormat ?? DateFormatPB.Friendly;
+ timeFormat = widget.timeFormat ?? TimeFormatPB.TwelveHour;
+ }
+
+ void updateDateFormat(DateFormatPB dateFormat) async {
+ setState(() {
+ this.dateFormat = dateFormat;
+ });
+ }
+
+ void updateTimeFormat(TimeFormatPB timeFormat) async {
+ setState(() {
+ this.timeFormat = timeFormat;
+ });
+ }
+
+ void updateDateCellData({
+ required DateTime? dateTime,
+ required DateTime? endDateTime,
+ required bool isRange,
+ required bool includeTime,
+ }) {
+ setState(() {
+ data.dateTime = dateTime;
+ data.endDateTime = endDateTime;
+ data.includeTime = includeTime;
+ data.isRange = isRange;
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return AppFlowyDatePicker(
+ dateTime: data.dateTime,
+ endDateTime: data.endDateTime,
+ includeTime: data.includeTime,
+ isRange: data.isRange,
+ dateFormat: dateFormat,
+ timeFormat: timeFormat,
+ onDaySelected: (date) async {
+ await Future.delayed(_mockDatePickerDelay);
+ setState(() {
+ data.dateTime = date;
+ });
+ },
+ onRangeSelected: (start, end) async {
+ await Future.delayed(_mockDatePickerDelay);
+ setState(() {
+ data.dateTime = start;
+ data.endDateTime = end;
+ });
+ },
+ onIncludeTimeChanged: (value) async {
+ await Future.delayed(_mockDatePickerDelay);
+ setState(() {
+ data.includeTime = value;
+ });
+ },
+ onIsRangeChanged: (value) async {
+ await Future.delayed(_mockDatePickerDelay);
+ setState(() {
+ data.isRange = value;
+ });
+ },
+ );
+ }
+}
+
+void main() {
+ setUpAll(() async {
+ SharedPreferences.setMockInitialValues({});
+ EasyLocalization.logger.enableLevels = [];
+ await EasyLocalization.ensureInitialized();
+ });
+
+ Finder dayInDatePicker(int day) {
+ final findCalendar = find.byType(TableCalendar);
+ final findDay = find.text(day.toString());
+
+ return find.descendant(
+ of: findCalendar,
+ matching: findDay,
+ );
+ }
+
+ _MockDatePickerState getMockState(WidgetTester tester) =>
+ tester.state<_MockDatePickerState>(find.byType(_MockDatePicker));
+
+ AppFlowyDatePickerState getAfState(WidgetTester tester) =>
+ tester.state<AppFlowyDatePickerState>(find.byType(AppFlowyDatePicker));
+
+ group('AppFlowy date picker:', () {
+ testWidgets('default state', (tester) async {
+ await tester.pumpWidget(
+ const WidgetTestApp(
+ child: _MockDatePicker(),
+ ),
+ );
+
+ await tester.pumpAndSettle();
+
+ expect(find.byType(AppFlowyDatePicker), findsOneWidget);
+ expect(
+ find.byWidgetPredicate(
+ (w) => w is DateTimeTextField && w.dateTime == null,
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.byWidgetPredicate((w) => w is DatePicker && w.selectedDay == null),
+ findsOneWidget,
+ );
+ expect(
+ find.byWidgetPredicate((w) => w is IncludeTimeButton && !w.includeTime),
+ findsOneWidget,
+ );
+ expect(
+ find.byWidgetPredicate((w) => w is EndTimeButton && !w.isRange),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('passed in state', (tester) async {
+ await tester.pumpWidget(
+ WidgetTestApp(
+ child: _MockDatePicker(
+ data: _DatePickerDataStub(
+ dateTime: DateTime(2024, 10, 12, 13),
+ endDateTime: DateTime(2024, 10, 14, 5),
+ includeTime: true,
+ isRange: true,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(find.byType(AppFlowyDatePicker), findsOneWidget);
+ expect(find.byType(DateTimeTextField), findsNWidgets(2));
+ expect(find.byType(DatePicker), findsOneWidget);
+ expect(
+ find.byWidgetPredicate((w) => w is IncludeTimeButton && w.includeTime),
+ findsOneWidget,
+ );
+ expect(
+ find.byWidgetPredicate((w) => w is EndTimeButton && w.isRange),
+ findsOneWidget,
+ );
+ final afState = getAfState(tester);
+ expect(afState.focusedDateTime, DateTime(2024, 10, 12, 13));
+ });
+
+ testWidgets('date and time formats', (tester) async {
+ final date = DateTime(2024, 10, 12, 13);
+ await tester.pumpWidget(
+ WidgetTestApp(
+ child: _MockDatePicker(
+ dateFormat: DateFormatPB.Friendly,
+ timeFormat: TimeFormatPB.TwelveHour,
+ data: _DatePickerDataStub(
+ dateTime: date,
+ endDateTime: null,
+ includeTime: true,
+ isRange: false,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ final dateText = find.descendant(
+ of: find.byKey(const ValueKey('date_time_text_field_date')),
+ matching:
+ find.text(DateFormat(DateFormatPB.Friendly.pattern).format(date)),
+ );
+ expect(dateText, findsOneWidget);
+
+ final timeText = find.descendant(
+ of: find.byKey(const ValueKey('date_time_text_field_time')),
+ matching:
+ find.text(DateFormat(TimeFormatPB.TwelveHour.pattern).format(date)),
+ );
+ expect(timeText, findsOneWidget);
+
+ _MockDatePickerState mockState = getMockState(tester);
+ mockState.updateDateFormat(DateFormatPB.US);
+ await tester.pumpAndSettle();
+ final dateText2 = find.descendant(
+ of: find.byKey(const ValueKey('date_time_text_field_date')),
+ matching: find.text(DateFormat(DateFormatPB.US.pattern).format(date)),
+ );
+ expect(dateText2, findsOneWidget);
+
+ mockState = getMockState(tester);
+ mockState.updateTimeFormat(TimeFormatPB.TwentyFourHour);
+ await tester.pumpAndSettle();
+ final timeText2 = find.descendant(
+ of: find.byKey(const ValueKey('date_time_text_field_time')),
+ matching: find
+ .text(DateFormat(TimeFormatPB.TwentyFourHour.pattern).format(date)),
+ );
+ expect(timeText2, findsOneWidget);
+ });
+
+ testWidgets('page turn buttons', (tester) async {
+ await tester.pumpWidget(
+ const WidgetTestApp(
+ child: _MockDatePicker(),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ final now = DateTime.now();
+ expect(
+ find.text(DateFormat.yMMMM().format(now)),
+ findsOneWidget,
+ );
+
+ final lastMonth = now.subtract(const Duration(days: 32));
+ await tester.tap(find.byFlowySvg(FlowySvgs.arrow_left_s));
+ await tester.pumpAndSettle();
+ expect(
+ find.text(DateFormat.yMMMM().format(lastMonth)),
+ findsOneWidget,
+ );
+
+ await tester.tap(find.byFlowySvg(FlowySvgs.arrow_right_s));
+ await tester.pumpAndSettle();
+ expect(
+ find.text(DateFormat.yMMMM().format(now)),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('select date', (tester) async {
+ await tester.pumpWidget(
+ const WidgetTestApp(
+ child: _MockDatePicker(),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ final now = DateTime.now();
+ final third = dayInDatePicker(3).first;
+ await tester.tap(third);
+ await tester.pump();
+
+ DateTime expected = DateTime(now.year, now.month, 3);
+
+ AppFlowyDatePickerState afState = getAfState(tester);
+ _MockDatePickerState mockState = getMockState(tester);
+ expect(afState.dateTime, expected);
+ expect(mockState.data.dateTime, null);
+
+ await tester.pumpAndSettle();
+ mockState = getMockState(tester);
+ expect(mockState.data.dateTime, expected);
+
+ final firstOfNextMonth = dayInDatePicker(1).last;
+ await tester.tap(firstOfNextMonth);
+ await tester.pumpAndSettle();
+
+ expected = DateTime(now.year, now.month + 1);
+ afState = getAfState(tester);
+ expect(afState.dateTime, expected);
+ expect(afState.focusedDateTime, expected);
+ });
+
+ testWidgets('select date range', (tester) async {
+ await tester.pumpWidget(
+ WidgetTestApp(
+ child: _MockDatePicker(
+ data: _DatePickerDataStub(
+ dateTime: null,
+ endDateTime: null,
+ includeTime: false,
+ isRange: true,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ AppFlowyDatePickerState afState = getAfState(tester);
+ _MockDatePickerState mockState = getMockState(tester);
+ expect(afState.startDateTime, null);
+ expect(afState.endDateTime, null);
+ expect(mockState.data.dateTime, null);
+ expect(mockState.data.endDateTime, null);
+
+ // 3-10
+ final now = DateTime.now();
+ final third = dayInDatePicker(3).first;
+ await tester.tap(third);
+ await tester.pumpAndSettle();
+
+ final expectedStart = DateTime(now.year, now.month, 3);
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.startDateTime, expectedStart);
+ expect(afState.endDateTime, null);
+ expect(mockState.data.dateTime, null);
+ expect(mockState.data.endDateTime, null);
+
+ final tenth = dayInDatePicker(10).first;
+ await tester.tap(tenth);
+ await tester.pump();
+
+ final expectedEnd = DateTime(now.year, now.month, 10);
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.startDateTime, expectedStart);
+ expect(afState.endDateTime, expectedEnd);
+ expect(mockState.data.dateTime, null);
+ expect(mockState.data.endDateTime, null);
+
+ await tester.pumpAndSettle();
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.startDateTime, expectedStart);
+ expect(afState.endDateTime, expectedEnd);
+ expect(mockState.data.dateTime, expectedStart);
+ expect(mockState.data.endDateTime, expectedEnd);
+
+ // 7-18, backwards
+ final eighteenth = dayInDatePicker(18).first;
+ await tester.tap(eighteenth);
+ await tester.pumpAndSettle();
+
+ final expectedEnd2 = DateTime(now.year, now.month, 18);
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.startDateTime, expectedEnd2);
+ expect(afState.endDateTime, null);
+ expect(mockState.data.dateTime, expectedStart);
+ expect(mockState.data.endDateTime, expectedEnd);
+
+ final seventh = dayInDatePicker(7).first;
+ await tester.tap(seventh);
+ await tester.pump();
+
+ final expectedStart2 = DateTime(now.year, now.month, 7);
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.startDateTime, expectedStart2);
+ expect(afState.endDateTime, expectedEnd2);
+ expect(mockState.data.dateTime, expectedStart);
+ expect(mockState.data.endDateTime, expectedEnd);
+
+ await tester.pumpAndSettle();
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.startDateTime, expectedStart2);
+ expect(afState.endDateTime, expectedEnd2);
+ expect(mockState.data.dateTime, expectedStart2);
+ expect(mockState.data.endDateTime, expectedEnd2);
+ });
+
+ testWidgets('select date range after toggling is range', (tester) async {
+ final now = DateTime.now();
+ final fourteenthDateTime = DateTime(now.year, now.month, 14);
+
+ await tester.pumpWidget(
+ WidgetTestApp(
+ child: _MockDatePicker(
+ data: _DatePickerDataStub(
+ dateTime: fourteenthDateTime,
+ endDateTime: null,
+ includeTime: false,
+ isRange: false,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ AppFlowyDatePickerState afState = getAfState(tester);
+ _MockDatePickerState mockState = getMockState(tester);
+ expect(afState.dateTime, fourteenthDateTime);
+ expect(afState.startDateTime, null);
+ expect(afState.endDateTime, null);
+ expect(afState.justChangedIsRange, false);
+
+ await tester.tap(
+ find.descendant(
+ of: find.byType(EndTimeButton),
+ matching: find.byType(Toggle),
+ ),
+ );
+ await tester.pump();
+
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.dateTime, fourteenthDateTime);
+ expect(afState.startDateTime, null);
+ expect(afState.endDateTime, null);
+ expect(afState.justChangedIsRange, true);
+ expect(afState.isRange, true);
+ expect(mockState.data.dateTime, fourteenthDateTime);
+ expect(mockState.data.endDateTime, null);
+ expect(mockState.data.isRange, false);
+
+ await tester.pumpAndSettle();
+
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.dateTime, fourteenthDateTime);
+ expect(afState.startDateTime, fourteenthDateTime);
+ expect(afState.endDateTime, fourteenthDateTime);
+ expect(afState.justChangedIsRange, true);
+ expect(mockState.data.dateTime, fourteenthDateTime);
+ expect(mockState.data.endDateTime, fourteenthDateTime);
+ expect(mockState.data.isRange, true);
+
+ final twentyFirst = dayInDatePicker(21).first;
+ await tester.tap(twentyFirst);
+ await tester.pumpAndSettle();
+
+ final expected = DateTime(now.year, now.month, 21);
+
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.dateTime, fourteenthDateTime);
+ expect(afState.startDateTime, fourteenthDateTime);
+ expect(afState.endDateTime, expected);
+ expect(afState.justChangedIsRange, false);
+ expect(mockState.data.dateTime, fourteenthDateTime);
+ expect(mockState.data.endDateTime, expected);
+ expect(mockState.data.isRange, true);
+ });
+
+ testWidgets('include time and modify', (tester) async {
+ final now = DateTime.now();
+ final fourteenthDateTime = DateTime(now.year, now.month, 14);
+
+ await tester.pumpWidget(
+ WidgetTestApp(
+ child: _MockDatePicker(
+ data: _DatePickerDataStub(
+ dateTime: fourteenthDateTime,
+ endDateTime: null,
+ includeTime: false,
+ isRange: false,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ AppFlowyDatePickerState afState = getAfState(tester);
+ _MockDatePickerState mockState = getMockState(tester);
+ expect(afState.dateTime, fourteenthDateTime);
+ expect(afState.startDateTime, null);
+ expect(afState.endDateTime, null);
+ expect(afState.includeTime, false);
+
+ await tester.tap(
+ find.descendant(
+ of: find.byType(IncludeTimeButton),
+ matching: find.byType(Toggle),
+ ),
+ );
+ await tester.pump();
+
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.dateTime, fourteenthDateTime);
+ expect(afState.includeTime, true);
+ expect(mockState.data.dateTime, fourteenthDateTime);
+ expect(mockState.data.includeTime, false);
+
+ await tester.pumpAndSettle(300.milliseconds);
+ mockState = getMockState(tester);
+ expect(mockState.data.dateTime, fourteenthDateTime);
+ expect(mockState.data.includeTime, true);
+
+ final timeField = find.byKey(const ValueKey('date_time_text_field_time'));
+ await tester.enterText(timeField, "1");
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle(300.milliseconds);
+
+ DateTime expected = DateTime(
+ fourteenthDateTime.year,
+ fourteenthDateTime.month,
+ fourteenthDateTime.day,
+ 1,
+ );
+
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.dateTime, expected);
+ expect(mockState.data.dateTime, expected);
+
+ final dateText = find.descendant(
+ of: find.byKey(const ValueKey('date_time_text_field_date')),
+ matching: find
+ .text(DateFormat(DateFormatPB.Friendly.pattern).format(expected)),
+ );
+ expect(dateText, findsOneWidget);
+ final timeText = find.descendant(
+ of: find.byKey(const ValueKey('date_time_text_field_time')),
+ matching: find
+ .text(DateFormat(TimeFormatPB.TwelveHour.pattern).format(expected)),
+ );
+ expect(timeText, findsOneWidget);
+
+ final third = dayInDatePicker(3).first;
+ await tester.tap(third);
+ await tester.pumpAndSettle();
+
+ expected = DateTime(
+ fourteenthDateTime.year,
+ fourteenthDateTime.month,
+ 3,
+ 1,
+ );
+
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.dateTime, expected);
+ expect(mockState.data.dateTime, expected);
+ });
+
+ testWidgets('edit text field causes start and end to get swapped',
+ (tester) async {
+ final fourteenth = DateTime(2024, 10, 14);
+
+ await tester.pumpWidget(
+ WidgetTestApp(
+ child: _MockDatePicker(
+ data: _DatePickerDataStub(
+ dateTime: fourteenth,
+ endDateTime: fourteenth,
+ includeTime: false,
+ isRange: true,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(
+ find.text(
+ DateFormat(DateFormatPB.Friendly.pattern).format(fourteenth),
+ ),
+ findsNWidgets(2),
+ );
+
+ final dateTextField = find.descendant(
+ of: find.byKey(const ValueKey('date_time_text_field')),
+ matching: find.byKey(const ValueKey('date_time_text_field_date')),
+ );
+ expect(dateTextField, findsOneWidget);
+ await tester.enterText(dateTextField, "Nov 30, 2024");
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ await tester.pumpAndSettle();
+
+ final bday = DateTime(2024, 11, 30);
+
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('date_time_text_field')),
+ matching: find.text(
+ DateFormat(DateFormatPB.Friendly.pattern).format(fourteenth),
+ ),
+ ),
+ findsOneWidget,
+ );
+
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('end_date_time_text_field')),
+ matching: find.text(
+ DateFormat(DateFormatPB.Friendly.pattern).format(bday),
+ ),
+ ),
+ findsOneWidget,
+ );
+
+ final mockState = getMockState(tester);
+ expect(mockState.data.dateTime, fourteenth);
+ expect(mockState.data.endDateTime, bday);
+ });
+
+ testWidgets('select start with calendar and then enter end with keyboard',
+ (tester) async {
+ final fourteenth = DateTime(2024, 10, 14);
+
+ await tester.pumpWidget(
+ WidgetTestApp(
+ child: _MockDatePicker(
+ data: _DatePickerDataStub(
+ dateTime: fourteenth,
+ endDateTime: fourteenth,
+ includeTime: false,
+ isRange: true,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ final third = dayInDatePicker(3).first;
+ await tester.tap(third);
+ await tester.pumpAndSettle();
+
+ final start = DateTime(2024, 10, 3);
+
+ AppFlowyDatePickerState afState = getAfState(tester);
+ _MockDatePickerState mockState = getMockState(tester);
+ expect(afState.dateTime, start);
+ expect(afState.startDateTime, start);
+ expect(afState.endDateTime, null);
+ expect(mockState.data.dateTime, fourteenth);
+ expect(mockState.data.endDateTime, fourteenth);
+ expect(mockState.data.isRange, true);
+
+ final dateTextField = find.descendant(
+ of: find.byKey(const ValueKey('end_date_time_text_field')),
+ matching: find.byKey(const ValueKey('date_time_text_field_date')),
+ );
+ expect(dateTextField, findsOneWidget);
+ await tester.enterText(dateTextField, "Oct 18, 2024");
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ await tester.pumpAndSettle();
+
+ final end = DateTime(2024, 10, 18);
+
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('date_time_text_field')),
+ matching: find.text(
+ DateFormat(DateFormatPB.Friendly.pattern).format(start),
+ ),
+ ),
+ findsOneWidget,
+ );
+
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('end_date_time_text_field')),
+ matching: find.text(
+ DateFormat(DateFormatPB.Friendly.pattern).format(end),
+ ),
+ ),
+ findsOneWidget,
+ );
+
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.dateTime, start);
+ expect(afState.startDateTime, start);
+ expect(afState.endDateTime, end);
+ expect(mockState.data.dateTime, start);
+ expect(mockState.data.endDateTime, end);
+
+ // make sure click counter was reset
+ final twentyFifth = dayInDatePicker(25).first;
+ final expected = DateTime(2024, 10, 25);
+ await tester.tap(twentyFifth);
+ await tester.pumpAndSettle();
+ afState = getAfState(tester);
+ mockState = getMockState(tester);
+ expect(afState.dateTime, expected);
+ expect(afState.startDateTime, expected);
+ expect(afState.endDateTime, null);
+ expect(mockState.data.dateTime, start);
+ expect(mockState.data.endDateTime, end);
+ });
+ });
+}
+
+class WidgetTestApp extends StatelessWidget {
+ const WidgetTestApp({
+ super.key,
+ required this.child,
+ });
+
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) {
+ return EasyLocalization(
+ supportedLocales: const [Locale('en')],
+ path: 'assets/translations',
+ fallbackLocale: const Locale('en'),
+ useFallbackTranslations: true,
+ saveLocale: false,
+ assetLoader: const TestBundleAssetLoader(),
+ child: Builder(
+ builder: (context) => MaterialApp(
+ supportedLocales: const [Locale('en')],
+ locale: const Locale('en'),
+ localizationsDelegates: context.localizationDelegates,
+ theme: ThemeData.light().copyWith(
+ extensions: const [
+ AFThemeExtension(
+ warning: Colors.transparent,
+ success: Colors.transparent,
+ tint1: Colors.transparent,
+ tint2: Colors.transparent,
+ tint3: Colors.transparent,
+ tint4: Colors.transparent,
+ tint5: Colors.transparent,
+ tint6: Colors.transparent,
+ tint7: Colors.transparent,
+ tint8: Colors.transparent,
+ tint9: Colors.transparent,
+ textColor: Colors.transparent,
+ secondaryTextColor: Colors.transparent,
+ strongText: Colors.transparent,
+ greyHover: Colors.transparent,
+ greySelect: Colors.transparent,
+ lightGreyHover: Colors.transparent,
+ toggleOffFill: Colors.transparent,
+ progressBarBGColor: Colors.transparent,
+ toggleButtonBGColor: Colors.transparent,
+ calendarWeekendBGColor: Colors.transparent,
+ gridRowCountColor: Colors.transparent,
+ code: TextStyle(),
+ callout: TextStyle(),
+ calloutBGColor: Colors.transparent,
+ tableCellBGColor: Colors.transparent,
+ caption: TextStyle(),
+ onBackground: Colors.transparent,
+ background: Colors.transparent,
+ borderColor: Colors.transparent,
+ scrollbarColor: Colors.transparent,
+ scrollbarHoverColor: Colors.transparent,
+ ),
+ ],
+ ),
+ home: Scaffold(
+ body: child,
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/frontend/appflowy_flutter/test/widget_test/test_asset_bundle.dart b/frontend/appflowy_flutter/test/widget_test/test_asset_bundle.dart
new file mode 100644
index 0000000000..ddcabff61f
--- /dev/null
+++ b/frontend/appflowy_flutter/test/widget_test/test_asset_bundle.dart
@@ -0,0 +1,48 @@
+import 'dart:convert';
+import 'dart:ui';
+
+import 'package:easy_localization/easy_localization.dart';
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+
+/// TestAssetBundle is required in order to avoid issues with large assets
+///
+/// ref: https://medium.com/@sardox/flutter-test-and-randomly-missing-assets-in-goldens-ea959cdd336a
+///
+/// "If your AssetManifest.json file exceeds 10kb, it will be
+/// loaded with isolate that (most likely) will cause your
+/// test to finish before assets are loaded so goldens will
+/// get empty assets."
+///
+class TestAssetBundle extends CachingAssetBundle {
+ @override
+ Future<String> loadString(String key, {bool cache = true}) async {
+ // overriding this method to avoid limit of 10KB per asset
+ try {
+ final data = await load(key);
+ return utf8.decode(data.buffer.asUint8List());
+ } catch (err) {
+ throw FlutterError('Unable to load asset: $key');
+ }
+ }
+
+ @override
+ Future<ByteData> load(String key) async => rootBundle.load(key);
+}
+
+final testAssetBundle = TestAssetBundle();
+
+/// Loads from our custom asset bundle
+class TestBundleAssetLoader extends AssetLoader {
+ const TestBundleAssetLoader();
+
+ String getLocalePath(String basePath, Locale locale) {
+ return '$basePath/${locale.toStringWithSeparator(separator: "-")}.json';
+ }
+
+ @override
+ Future<Map<String, dynamic>> load(String path, Locale locale) async {
+ final localePath = getLocalePath(path, locale);
+ return json.decode(await testAssetBundle.loadString(localePath));
+ }
+}
diff --git a/frontend/rust-lib/event-integration-test/src/database_event.rs b/frontend/rust-lib/event-integration-test/src/database_event.rs
index fd7bd9c4d5..096c692b4f 100644
--- a/frontend/rust-lib/event-integration-test/src/database_event.rs
+++ b/frontend/rust-lib/event-integration-test/src/database_event.rs
@@ -590,15 +590,14 @@ impl<'a> TestRowBuilder<'a> {
pub fn insert_date_cell(
&mut self,
- date: i64,
- time: Option<String>,
+ timestamp: i64,
include_time: Option<bool>,
field_type: &FieldType,
) -> String {
let date_field = self.field_with_type(field_type);
self
.cell_build
- .insert_date_cell(&date_field.id, date, time, include_time);
+ .insert_date_cell(&date_field.id, timestamp, include_time);
date_field.id.clone()
}
diff --git a/frontend/rust-lib/event-integration-test/tests/database/local_test/event_test.rs b/frontend/rust-lib/event-integration-test/tests/database/local_test/event_test.rs
index 36f3d8ea32..885d1b6817 100644
--- a/frontend/rust-lib/event-integration-test/tests/database/local_test/event_test.rs
+++ b/frontend/rust-lib/event-integration-test/tests/database/local_test/event_test.rs
@@ -536,7 +536,7 @@ async fn update_date_cell_event_test() {
let error = test
.update_date_cell(DateCellChangesetPB {
cell_id: cell_path,
- date: Some(timestamp),
+ timestamp: Some(timestamp),
..Default::default()
})
.await;
@@ -546,8 +546,7 @@ async fn update_date_cell_event_test() {
let cell = test
.get_date_cell(&grid_view.id, &database.rows[0].id, &date_field.id)
.await;
- assert_eq!(cell.date, "Jun 09, 2023");
- assert_eq!(cell.timestamp, timestamp);
+ assert_eq!(cell.timestamp, Some(timestamp));
}
#[tokio::test]
@@ -572,7 +571,7 @@ async fn update_date_cell_event_with_empty_time_str_test() {
let error = test
.update_date_cell(DateCellChangesetPB {
cell_id: cell_path,
- date: None,
+ timestamp: None,
..Default::default()
})
.await;
@@ -582,8 +581,7 @@ async fn update_date_cell_event_with_empty_time_str_test() {
let cell = test
.get_date_cell(&grid_view.id, &row_id, &date_field.id)
.await;
- assert_eq!(cell.date, "");
- assert_eq!(cell.timestamp, 0);
+ assert_eq!(cell.timestamp, None);
}
#[tokio::test]
@@ -788,7 +786,7 @@ async fn create_calendar_event_test() {
field_id: date_field.id.clone(),
row_id: row.id,
},
- date: Some(timestamp()),
+ timestamp: Some(timestamp()),
..Default::default()
})
.await;
diff --git a/frontend/rust-lib/flowy-database2/src/entities/type_option_entities/date_entities.rs b/frontend/rust-lib/flowy-database2/src/entities/type_option_entities/date_entities.rs
index 3085e74aff..4e9730f5ed 100644
--- a/frontend/rust-lib/flowy-database2/src/entities/type_option_entities/date_entities.rs
+++ b/frontend/rust-lib/flowy-database2/src/entities/type_option_entities/date_entities.rs
@@ -11,38 +11,27 @@ use crate::entities::CellIdPB;
#[derive(Clone, Debug, Default, ProtoBuf)]
pub struct DateCellDataPB {
- #[pb(index = 1)]
- pub date: String,
+ #[pb(index = 1, one_of)]
+ pub timestamp: Option<i64>,
- #[pb(index = 2)]
- pub time: String,
+ #[pb(index = 2, one_of)]
+ pub end_timestamp: Option<i64>,
#[pb(index = 3)]
- pub timestamp: i64,
-
- #[pb(index = 4)]
- pub end_date: String,
-
- #[pb(index = 5)]
- pub end_time: String,
-
- #[pb(index = 6)]
- pub end_timestamp: i64,
-
- #[pb(index = 7)]
pub include_time: bool,
- #[pb(index = 8)]
+ #[pb(index = 4)]
pub is_range: bool,
- #[pb(index = 9)]
+ #[pb(index = 5)]
pub reminder_id: String,
}
+
impl From<&DateCellDataPB> for DateCellData {
fn from(data: &DateCellDataPB) -> Self {
Self {
- timestamp: Some(data.timestamp),
- end_timestamp: Some(data.end_timestamp),
+ timestamp: data.timestamp,
+ end_timestamp: data.end_timestamp,
include_time: data.include_time,
is_range: data.is_range,
reminder_id: data.reminder_id.to_owned(),
@@ -56,27 +45,21 @@ pub struct DateCellChangesetPB {
pub cell_id: CellIdPB,
#[pb(index = 2, one_of)]
- pub date: Option<i64>,
+ pub timestamp: Option<i64>,
#[pb(index = 3, one_of)]
- pub time: Option<String>,
+ pub end_timestamp: Option<i64>,
#[pb(index = 4, one_of)]
- pub end_date: Option<i64>,
-
- #[pb(index = 5, one_of)]
- pub end_time: Option<String>,
-
- #[pb(index = 6, one_of)]
pub include_time: Option<bool>,
- #[pb(index = 7, one_of)]
+ #[pb(index = 5, one_of)]
pub is_range: Option<bool>,
- #[pb(index = 8, one_of)]
+ #[pb(index = 6, one_of)]
pub clear_flag: Option<bool>,
- #[pb(index = 9, one_of)]
+ #[pb(index = 7, one_of)]
pub reminder_id: Option<String>,
}
diff --git a/frontend/rust-lib/flowy-database2/src/event_handler.rs b/frontend/rust-lib/flowy-database2/src/event_handler.rs
index 5f53088788..d641cb234a 100644
--- a/frontend/rust-lib/flowy-database2/src/event_handler.rs
+++ b/frontend/rust-lib/flowy-database2/src/event_handler.rs
@@ -711,10 +711,8 @@ pub(crate) async fn update_date_cell_handler(
let data = data.into_inner();
let cell_id: CellIdParams = data.cell_id.try_into()?;
let cell_changeset = DateCellChangeset {
- date: data.date,
- time: data.time,
- end_date: data.end_date,
- end_time: data.end_time,
+ timestamp: data.timestamp,
+ end_timestamp: data.end_timestamp,
include_time: data.include_time,
is_range: data.is_range,
clear_flag: data.clear_flag,
@@ -992,7 +990,7 @@ pub(crate) async fn move_calendar_event_handler(
let data = data.into_inner();
let cell_id: CellIdParams = data.cell_path.try_into()?;
let cell_changeset = DateCellChangeset {
- date: Some(data.timestamp),
+ timestamp: Some(data.timestamp),
..Default::default()
};
let database_editor = manager
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.rs
index 15aecc0072..8c3b757e02 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
@@ -172,15 +172,13 @@ pub fn insert_checkbox_cell(is_checked: bool, field: &Field) -> Cell {
pub fn insert_date_cell(
timestamp: i64,
- start_time: Option<String>,
end_timestamp: Option<i64>,
include_time: Option<bool>,
field: &Field,
) -> Cell {
let cell_data = DateCellChangeset {
- date: Some(timestamp),
- time: start_time,
- end_date: end_timestamp,
+ timestamp: Some(timestamp),
+ end_timestamp,
include_time,
..Default::default()
};
@@ -238,7 +236,7 @@ impl<'a> CellBuilder<'a> {
if let Ok(timestamp) = cell_str.parse::<i64>() {
cells.insert(
field_id,
- insert_date_cell(timestamp, None, None, Some(false), field),
+ insert_date_cell(timestamp, None, Some(false), field),
);
}
},
@@ -324,19 +322,13 @@ impl<'a> CellBuilder<'a> {
}
}
- pub fn insert_date_cell(
- &mut self,
- field_id: &str,
- timestamp: i64,
- time: Option<String>,
- include_time: Option<bool>,
- ) {
+ pub fn insert_date_cell(&mut self, field_id: &str, timestamp: i64, include_time: Option<bool>) {
match self.field_maps.get(&field_id.to_owned()) {
None => tracing::warn!("Can't find the date field with id: {}", field_id),
Some(field) => {
self.cells.insert(
field_id.to_owned(),
- insert_date_cell(timestamp, time, None, include_time, field),
+ insert_date_cell(timestamp, None, include_time, field),
);
},
}
diff --git a/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_filter.rs b/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_filter.rs
index 6aea621326..2396b09f41 100644
--- a/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_filter.rs
+++ b/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_filter.rs
@@ -175,7 +175,7 @@ impl PreFillCellsWithFilter for DateFilterPB {
_ => None,
};
- start_timestamp.map(|timestamp| insert_date_cell(timestamp, None, None, None, field))
+ start_timestamp.map(|timestamp| insert_date_cell(timestamp, None, None, field))
}
}
diff --git a/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_tests.rs b/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_tests.rs
index 8342e3d776..8210018f49 100644
--- a/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_tests.rs
+++ b/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_tests.rs
@@ -1,569 +1,238 @@
#[cfg(test)]
mod tests {
- use chrono::format::strftime::StrftimeItems;
- use chrono::FixedOffset;
- use collab_database::fields::Field;
use collab_database::rows::Cell;
- use strum::IntoEnumIterator;
- use crate::entities::FieldType;
use crate::services::cell::{CellDataChangeset, CellDataDecoder};
- use crate::services::field::{DateCellChangeset, FieldBuilder};
- use collab_database::fields::date_type_option::{DateFormat, DateTypeOption, TimeFormat};
+ use crate::services::field::DateCellChangeset;
+ use collab_database::fields::date_type_option::{DateCellData, DateTypeOption};
#[test]
- fn date_type_option_date_format_test() {
- let mut type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(FieldType::DateTime).build();
- for date_format in DateFormat::iter() {
- type_option.date_format = date_format;
- match date_format {
- DateFormat::Friendly => {
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1647251762),
- time: None,
- include_time: None,
- ..Default::default()
- },
- None,
- "Mar 14, 2022",
- );
- },
- DateFormat::US => {
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1647251762),
- time: None,
- include_time: None,
- ..Default::default()
- },
- None,
- "2022/03/14",
- );
- },
- DateFormat::ISO => {
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1647251762),
- time: None,
- include_time: None,
- ..Default::default()
- },
- None,
- "2022-03-14",
- );
- },
- DateFormat::Local => {
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1647251762),
- time: None,
- include_time: None,
- ..Default::default()
- },
- None,
- "03/14/2022",
- );
- },
- DateFormat::DayMonthYear => {
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1647251762),
- time: None,
- include_time: None,
- ..Default::default()
- },
- None,
- "14/03/2022",
- );
- },
- DateFormat::FriendlyFull => {
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1647251762),
- time: None,
- include_time: None,
- ..Default::default()
- },
- None,
- "March 14, 2022",
- );
- },
- }
- }
- }
-
- #[test]
- fn date_type_option_different_time_format_test() {
- let mut type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(FieldType::DateTime).build();
-
- for time_format in TimeFormat::iter() {
- type_option.time_format = time_format;
- match time_format {
- TimeFormat::TwentyFourHour => {
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1653609600),
- time: None,
- include_time: Some(true),
- ..Default::default()
- },
- None,
- "May 27, 2022 00:00",
- );
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1653609600),
- time: Some("9:00".to_owned()),
- include_time: Some(true),
- ..Default::default()
- },
- None,
- "May 27, 2022 09:00",
- );
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1653609600),
- time: Some("23:00".to_owned()),
- include_time: Some(true),
- ..Default::default()
- },
- None,
- "May 27, 2022 23:00",
- );
- },
- TimeFormat::TwelveHour => {
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1653609600),
- time: None,
- include_time: Some(true),
- ..Default::default()
- },
- None,
- "May 27, 2022 12:00 AM",
- );
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1653609600),
- time: Some("9:00 AM".to_owned()),
- include_time: Some(true),
- ..Default::default()
- },
- None,
- "May 27, 2022 09:00 AM",
- );
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1653609600),
- time: Some("11:23 pm".to_owned()),
- include_time: Some(true),
- ..Default::default()
- },
- None,
- "May 27, 2022 11:23 PM",
- );
- },
- }
- }
- }
-
- #[test]
- #[should_panic]
- fn date_type_option_invalid_include_time_str_test() {
- let field_type = FieldType::DateTime;
+ fn apply_changeset_to_empty_cell() {
let type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(field_type).build();
assert_date(
&type_option,
- &field,
DateCellChangeset {
- date: Some(1653609600),
- time: Some("1:".to_owned()),
+ timestamp: Some(1653782400),
include_time: Some(true),
..Default::default()
},
None,
- "May 27, 2022 01:00",
- );
- }
-
- #[test]
- #[should_panic]
- fn date_type_option_empty_include_time_str_test() {
- let field_type = FieldType::DateTime;
- let type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(field_type).build();
-
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1653609600),
- time: Some("".to_owned()),
- include_time: Some(true),
+ &DateCellData {
+ timestamp: Some(1653782400),
+ include_time: true,
..Default::default()
},
- None,
- "May 27, 2022 01:00",
);
- }
- #[test]
- fn date_type_midnight_include_time_str_test() {
- let field_type = FieldType::DateTime;
- let type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(field_type).build();
assert_date(
&type_option,
- &field,
DateCellChangeset {
- date: Some(1653609600),
- time: Some("00:00".to_owned()),
- include_time: Some(true),
+ timestamp: Some(1625130000),
+ end_timestamp: Some(1653782400),
+ is_range: Some(true),
..Default::default()
},
None,
- "May 27, 2022 00:00",
+ &DateCellData {
+ timestamp: Some(1625130000),
+ end_timestamp: Some(1653782400),
+ is_range: true,
+ ..Default::default()
+ },
);
}
- /// The default time format is TwentyFourHour, so the include_time_str in
- /// twelve_hours_format will cause parser error.
#[test]
- #[should_panic]
- fn date_type_option_twelve_hours_include_time_str_in_twenty_four_hours_format() {
+ fn apply_changeset_to_exsiting_cell() {
let type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(FieldType::DateTime).build();
- assert_date(
+
+ let date_cell = initialize_date_cell(
&type_option,
- &field,
DateCellChangeset {
- date: Some(1653609600),
- time: Some("1:00 am".to_owned()),
- include_time: Some(true),
+ timestamp: Some(1653782400),
..Default::default()
},
- None,
- "May 27, 2022 01:00 AM",
);
- }
-
- /// Attempting to parse include_time_str as TwelveHour when TwentyFourHour
- /// format is given should cause parser error.
- #[test]
- #[should_panic]
- fn date_type_option_twenty_four_hours_include_time_str_in_twelve_hours_format() {
- let field_type = FieldType::DateTime;
- let mut type_option = DateTypeOption::default_utc();
- type_option.time_format = TimeFormat::TwelveHour;
- let field = FieldBuilder::from_field_type(field_type).build();
-
assert_date(
&type_option,
- &field,
DateCellChangeset {
- date: Some(1653609600),
- time: Some("20:00".to_owned()),
- include_time: Some(true),
+ timestamp: Some(1625130000),
+ ..Default::default()
+ },
+ Some(date_cell.clone()),
+ &DateCellData {
+ timestamp: Some(1625130000),
..Default::default()
},
- None,
- "May 27, 2022 08:00 PM",
- );
- }
-
- #[test]
- fn utc_to_native_test() {
- let native_timestamp = 1647251762;
- let native = chrono::DateTime::from_timestamp(native_timestamp, 0)
- .unwrap()
- .naive_utc();
-
- let utc = chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(native, chrono::Utc);
- // utc_timestamp doesn't carry timezone
- let utc_timestamp = utc.timestamp();
- assert_eq!(native_timestamp, utc_timestamp);
-
- let format = "%m/%d/%Y %I:%M %p".to_string();
- let native_time_str = format!("{}", native.format_with_items(StrftimeItems::new(&format)));
- let utc_time_str = format!("{}", utc.format_with_items(StrftimeItems::new(&format)));
- assert_eq!(native_time_str, utc_time_str);
-
- // Mon Mar 14 2022 17:56:02 GMT+0800 (China Standard Time)
- let gmt_8_offset = FixedOffset::east_opt(8 * 3600).unwrap();
- let china_local =
- chrono::DateTime::<chrono::Local>::from_naive_utc_and_offset(native, gmt_8_offset);
- let china_local_time = format!(
- "{}",
- china_local.format_with_items(StrftimeItems::new(&format))
);
- assert_eq!(china_local_time, "03/14/2022 05:56 PM");
- }
-
- /// The time component shouldn't remain the same since the timestamp is
- /// completely overwritten. To achieve the desired result, also pass in the
- /// time string along with the new timestamp.
- #[test]
- #[should_panic]
- fn update_date_keep_time() {
- let type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(FieldType::DateTime).build();
-
- let old_cell_data = initialize_date_cell(
+ let date_cell = initialize_date_cell(
&type_option,
DateCellChangeset {
- date: Some(1700006400),
- time: Some("08:00".to_owned()),
- include_time: Some(true),
+ timestamp: Some(1653782400),
..Default::default()
},
);
assert_date(
&type_option,
- &field,
DateCellChangeset {
- date: Some(1701302400),
- time: None,
- include_time: None,
+ timestamp: Some(1653782400),
+ include_time: Some(true),
+ ..Default::default()
+ },
+ Some(date_cell.clone()),
+ &DateCellData {
+ timestamp: Some(1653782400),
+ include_time: true,
..Default::default()
},
- Some(old_cell_data),
- "Nov 30, 2023 08:00",
);
- }
-
- #[test]
- fn update_time_keep_date() {
- let type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(FieldType::DateTime).build();
- let old_cell_data = initialize_date_cell(
+ let date_cell = initialize_date_cell(
&type_option,
DateCellChangeset {
- date: Some(1700006400),
- time: Some("08:00".to_owned()),
- include_time: Some(true),
+ timestamp: Some(1653782400),
+ end_timestamp: Some(1653782400),
+ is_range: Some(true),
..Default::default()
},
);
assert_date(
&type_option,
- &field,
DateCellChangeset {
- date: None,
- time: Some("14:00".to_owned()),
- include_time: None,
+ timestamp: Some(1625130000),
+ end_timestamp: Some(1625130000),
+ ..Default::default()
+ },
+ Some(date_cell.clone()),
+ &DateCellData {
+ timestamp: Some(1625130000),
+ end_timestamp: Some(1625130000),
+ is_range: true,
..Default::default()
},
- Some(old_cell_data),
- "Nov 15, 2023 14:00",
);
- }
-
- #[test]
- fn clear_date() {
- let type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(FieldType::DateTime).build();
- let old_cell_data = initialize_date_cell(
+ let date_cell = initialize_date_cell(
&type_option,
DateCellChangeset {
- date: Some(1700006400),
- time: Some("08:00".to_owned()),
- include_time: Some(true),
+ timestamp: Some(1653782400),
+ end_timestamp: Some(1653782400),
+ is_range: Some(true),
..Default::default()
},
);
assert_date(
&type_option,
- &field,
DateCellChangeset {
- date: None,
- time: None,
- include_time: Some(true),
- clear_flag: Some(true),
+ is_range: Some(false),
+ ..Default::default()
+ },
+ Some(date_cell.clone()),
+ &DateCellData {
+ timestamp: Some(1653782400),
+ is_range: false,
..Default::default()
},
- Some(old_cell_data),
- "",
);
}
#[test]
- fn end_date_time_test() {
+ fn apply_invalid_changeset_to_empty_cell() {
let type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(FieldType::DateTime).build();
-
- assert_date(
- &type_option,
- &field,
- DateCellChangeset {
- date: Some(1653609600),
- end_date: Some(1653782400),
- include_time: Some(false),
- is_range: Some(true),
- ..Default::default()
- },
- None,
- "May 27, 2022 → May 29, 2022",
- );
assert_date(
&type_option,
- &field,
DateCellChangeset {
- date: Some(1653609600),
- time: Some("20:00".to_owned()),
- end_date: Some(1653782400),
- end_time: Some("08:00".to_owned()),
- include_time: Some(true),
- is_range: Some(true),
+ timestamp: Some(1653782400),
+ end_timestamp: Some(1653782400),
+ is_range: Some(false),
..Default::default()
},
None,
- "May 27, 2022 20:00 → May 29, 2022 08:00",
+ &DateCellData::default(),
);
assert_date(
&type_option,
- &field,
DateCellChangeset {
- date: Some(1653609600),
- time: Some("20:00".to_owned()),
- end_date: Some(1653782400),
- include_time: Some(true),
+ timestamp: None,
+ end_timestamp: Some(1653782400),
is_range: Some(true),
..Default::default()
},
None,
- "May 27, 2022 20:00 → May 29, 2022 00:00",
+ &DateCellData::default(),
);
}
#[test]
- fn turn_on_date_range() {
+ fn apply_invalid_changeset_to_existing_cell() {
let type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(FieldType::DateTime).build();
- let old_cell_data = initialize_date_cell(
+ // is_range is false but a date range is passed in
+ let date_cell = initialize_date_cell(
&type_option,
DateCellChangeset {
- date: Some(1653609600),
- time: Some("08:00".to_owned()),
- include_time: Some(true),
+ timestamp: Some(1653782400),
+ is_range: Some(false),
..Default::default()
},
);
assert_date(
&type_option,
- &field,
DateCellChangeset {
- is_range: Some(true),
+ timestamp: Some(1653782400),
+ end_timestamp: Some(1653782400),
..Default::default()
},
- Some(old_cell_data),
- "May 27, 2022 08:00 → May 27, 2022 08:00",
+ Some(date_cell.clone()),
+ &decode_cell_data(&date_cell, &type_option),
);
- }
- #[test]
- fn add_an_end_time() {
- let type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(FieldType::DateTime).build();
-
- let old_cell_data = initialize_date_cell(
- &type_option,
- DateCellChangeset {
- date: Some(1653609600),
- time: Some("08:00".to_owned()),
- include_time: Some(true),
- ..Default::default()
- },
- );
- assert_date(
+ // is_range is true but either the start or end is missing
+ let date_cell = initialize_date_cell(
&type_option,
- &field,
DateCellChangeset {
- date: None,
- time: None,
- end_date: Some(1700006400),
- end_time: Some("16:00".to_owned()),
- include_time: Some(true),
- is_range: Some(true),
+ timestamp: Some(1653782400),
+ end_timestamp: Some(1653782400),
+ is_range: Some(false),
..Default::default()
},
- Some(old_cell_data),
- "May 27, 2022 08:00 → Nov 15, 2023 16:00",
);
- }
-
- #[test]
- #[should_panic]
- fn end_date_with_no_start_date() {
- let type_option = DateTypeOption::default_utc();
- let field = FieldBuilder::from_field_type(FieldType::DateTime).build();
-
assert_date(
&type_option,
- &field,
DateCellChangeset {
- date: None,
- end_date: Some(1653782400),
- include_time: Some(false),
- is_range: Some(true),
+ timestamp: None,
+ end_timestamp: Some(1653782400),
..Default::default()
},
- None,
- "→ May 29, 2022",
+ Some(date_cell.clone()),
+ &decode_cell_data(&date_cell, &type_option),
);
}
fn assert_date(
type_option: &DateTypeOption,
- field: &Field,
changeset: DateCellChangeset,
old_cell_data: Option<Cell>,
- expected_str: &str,
+ expected: &DateCellData,
) {
let (cell, _) = type_option
.apply_changeset(changeset, old_cell_data)
.unwrap();
- assert_eq!(decode_cell_data(&cell, type_option, field), expected_str,);
+ let actual = decode_cell_data(&cell, type_option);
+
+ assert_eq!(expected.timestamp, actual.timestamp);
+ assert_eq!(expected.end_timestamp, actual.end_timestamp);
+ assert_eq!(expected.include_time, actual.include_time);
+ assert_eq!(expected.is_range, actual.is_range);
}
- fn decode_cell_data(cell: &Cell, type_option: &DateTypeOption, _field: &Field) -> String {
- let decoded_data = type_option.decode_cell(cell).unwrap();
- type_option.stringify_cell_data(decoded_data)
+ fn decode_cell_data(cell: &Cell, type_option: &DateTypeOption) -> DateCellData {
+ type_option.decode_cell(cell).unwrap()
}
fn initialize_date_cell(type_option: &DateTypeOption, changeset: DateCellChangeset) -> Cell {
diff --git a/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_type_option.rs b/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_type_option.rs
index 1c2b481f28..a7bc56d019 100644
--- a/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_type_option.rs
+++ b/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_type_option.rs
@@ -1,3 +1,5 @@
+use std::cmp::Ordering;
+
use async_trait::async_trait;
use collab::util::AnyMapExt;
use collab_database::database::Database;
@@ -6,9 +8,6 @@ use collab_database::fields::{Field, TypeOptionData};
use collab_database::rows::Cell;
use collab_database::template::date_parse::cast_string_to_timestamp;
use flowy_error::FlowyResult;
-
-use std::cmp::Ordering;
-
use tracing::info;
use crate::entities::{DateCellDataPB, DateFilterPB, FieldType};
@@ -18,6 +17,7 @@ use crate::services::field::{
TypeOptionCellDataFilter, TypeOptionCellDataSerde, TypeOptionTransform, CELL_DATA,
};
use crate::services::sort::SortCondition;
+
impl TypeOption for DateTypeOption {
type CellData = DateCellData;
type CellChangeset = DateCellChangeset;
@@ -34,20 +34,13 @@ impl TypeOptionCellDataSerde for DateTypeOption {
let is_range = cell_data.is_range;
let timestamp = cell_data.timestamp;
- let (date, time) = self.formatted_date_time_from_timestamp(&timestamp);
-
let end_timestamp = cell_data.end_timestamp;
- let (end_date, end_time) = self.formatted_date_time_from_timestamp(&end_timestamp);
let reminder_id = cell_data.reminder_id;
DateCellDataPB {
- date,
- time,
- timestamp: timestamp.unwrap_or_default(),
- end_date,
- end_time,
- end_timestamp: end_timestamp.unwrap_or_default(),
+ timestamp,
+ end_timestamp,
include_time,
is_range,
reminder_id,
@@ -161,71 +154,46 @@ impl CellDataChangeset for DateTypeOption {
changeset: <Self as TypeOption>::CellChangeset,
cell: Option<Cell>,
) -> FlowyResult<(Cell, <Self as TypeOption>::CellData)> {
+ if let Some(true) = changeset.clear_flag {
+ let cell_data = DateCellData::default();
+ return Ok((Cell::from(&cell_data), cell_data));
+ }
+
// old date cell data
- let (previous_timestamp, previous_end_timestamp, include_time, is_range, reminder_id) =
- match cell {
- Some(cell) => {
- let cell_data = DateCellData::from(&cell);
- (
- cell_data.timestamp,
- cell_data.end_timestamp,
- cell_data.include_time,
- cell_data.is_range,
- cell_data.reminder_id,
- )
- },
- None => (None, None, false, false, String::new()),
- };
+ let cell_data = match cell {
+ Some(cell) => DateCellData::from(&cell),
+ None => DateCellData::default(),
+ };
- if changeset.clear_flag == Some(true) {
- let cell_data = DateCellData {
- timestamp: None,
- end_timestamp: None,
- include_time,
- is_range,
- reminder_id: String::new(),
- };
+ let is_range = changeset.is_range.unwrap_or(cell_data.is_range);
+
+ let has_timestamp = changeset.timestamp.is_some();
+ let has_end_timestamp = changeset.end_timestamp.is_some();
+ let unexpected_end_changeset = !is_range && has_end_timestamp;
+ let missing_timestamp = is_range && has_timestamp != has_end_timestamp;
+ if unexpected_end_changeset || missing_timestamp {
return Ok((Cell::from(&cell_data), cell_data));
}
- // update include_time and is_range if necessary
+ let DateCellData {
+ timestamp,
+ end_timestamp,
+ include_time,
+ is_range: _,
+ reminder_id,
+ } = cell_data;
+
+ // update include_time and reminder_id if necessary
let include_time = changeset.include_time.unwrap_or(include_time);
- let is_range = changeset.is_range.unwrap_or(is_range);
let reminder_id = changeset.reminder_id.unwrap_or(reminder_id);
- // Calculate the timestamp in the time zone specified in type option. If
- // a new timestamp is included in the changeset without an accompanying
- // time string, the old timestamp will simply be overwritten. Meaning, in
- // order to change the day without changing the time, the old time string
- // should be passed in as well.
-
- // parse the time string, which is in the local timezone
- let parsed_start_time = self.naive_time_from_time_string(include_time, changeset.time)?;
-
- let timestamp = self.timestamp_from_parsed_time_previous_and_new_timestamp(
- parsed_start_time,
- previous_timestamp,
- changeset.date,
- );
-
- let end_timestamp =
- if is_range && changeset.end_date.is_none() && previous_end_timestamp.is_none() {
- // just toggled is_range so no passed in or existing end time data
- timestamp
- } else if is_range {
- // parse the changeset's end time data or fallback to previous version
- let parsed_end_time = self.naive_time_from_time_string(include_time, changeset.end_time)?;
-
- self.timestamp_from_parsed_time_previous_and_new_timestamp(
- parsed_end_time,
- previous_end_timestamp,
- changeset.end_date,
- )
- } else {
- // clear the end time data
- None
- };
+ let timestamp = changeset.timestamp.or(timestamp);
+ let end_timestamp = if is_range && timestamp.is_some() {
+ changeset.end_timestamp.or(end_timestamp)
+ } else {
+ None
+ };
let cell_data = DateCellData {
timestamp,
diff --git a/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_type_option_entities.rs b/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_type_option_entities.rs
index 3cf6e7474b..86fcb3b9c1 100644
--- a/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_type_option_entities.rs
+++ b/frontend/rust-lib/flowy-database2/src/services/field/type_options/date_type_option/date_type_option_entities.rs
@@ -10,10 +10,8 @@ use crate::services::field::TypeOptionCellData;
#[derive(Clone, Debug, Default)]
pub struct DateCellChangeset {
- pub date: Option<i64>,
- pub time: Option<String>,
- pub end_date: Option<i64>,
- pub end_time: Option<String>,
+ pub timestamp: Option<i64>,
+ pub end_timestamp: Option<i64>,
pub include_time: Option<bool>,
pub is_range: Option<bool>,
pub clear_flag: Option<bool>,
diff --git a/frontend/rust-lib/flowy-database2/src/services/group/controller_impls/date_controller.rs b/frontend/rust-lib/flowy-database2/src/services/group/controller_impls/date_controller.rs
index ad2fd069eb..ba70618388 100644
--- a/frontend/rust-lib/flowy-database2/src/services/group/controller_impls/date_controller.rs
+++ b/frontend/rust-lib/flowy-database2/src/services/group/controller_impls/date_controller.rs
@@ -221,7 +221,7 @@ impl GroupCustomize for DateGroupController {
None => tracing::warn!("Can not find the group: {}", group_id),
Some((_, _)) => {
let date = DateTime::parse_from_str(group_id, GROUP_ID_DATE_FORMAT).unwrap();
- let cell = insert_date_cell(date.timestamp(), None, None, Some(false), field);
+ let cell = insert_date_cell(date.timestamp(), None, Some(false), field);
cells.insert(field.id.clone(), cell);
},
}
diff --git a/frontend/rust-lib/flowy-database2/src/services/group/controller_impls/select_option_controller/util.rs b/frontend/rust-lib/flowy-database2/src/services/group/controller_impls/select_option_controller/util.rs
index 55c3d54236..827e4f0e53 100644
--- a/frontend/rust-lib/flowy-database2/src/services/group/controller_impls/select_option_controller/util.rs
+++ b/frontend/rust-lib/flowy-database2/src/services/group/controller_impls/select_option_controller/util.rs
@@ -157,7 +157,7 @@ pub fn make_inserted_cell(group_id: &str, field: &Field) -> Option<Cell> {
let date =
NaiveDateTime::parse_from_str(&format!("{} 00:00:00", group_id), "%Y/%m/%d %H:%M:%S")
.unwrap();
- let cell = insert_date_cell(date.and_utc().timestamp(), None, None, Some(false), field);
+ let cell = insert_date_cell(date.and_utc().timestamp(), None, Some(false), field);
Some(cell)
},
_ => {
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.rs
index e02b8c9d2c..6a467520f4 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
@@ -27,7 +27,7 @@ async fn grid_cell_update() {
FieldType::RichText => BoxAny::new("".to_string()),
FieldType::Number => BoxAny::new("123".to_string()),
FieldType::DateTime => BoxAny::new(DateCellChangeset {
- date: Some(123),
+ timestamp: Some(123),
..Default::default()
}),
FieldType::SingleSelect => {
diff --git a/frontend/rust-lib/flowy-database2/tests/database/group_test/script.rs b/frontend/rust-lib/flowy-database2/tests/database/group_test/script.rs
index ca34b550f8..1b700b96f3 100644
--- a/frontend/rust-lib/flowy-database2/tests/database/group_test/script.rs
+++ b/frontend/rust-lib/flowy-database2/tests/database/group_test/script.rs
@@ -132,13 +132,9 @@ impl DatabaseGroupTest {
let field_type = FieldType::from(field.field_type);
let cell = match field_type {
FieldType::URL => insert_url_cell(cell_data, &field),
- FieldType::DateTime => insert_date_cell(
- cell_data.parse::<i64>().unwrap(),
- None,
- None,
- Some(true),
- &field,
- ),
+ FieldType::DateTime => {
+ insert_date_cell(cell_data.parse::<i64>().unwrap(), None, Some(true), &field)
+ },
_ => panic!("Unsupported group field type"),
};
diff --git a/frontend/rust-lib/flowy-database2/tests/database/mock_data/board_mock_data.rs b/frontend/rust-lib/flowy-database2/tests/database/mock_data/board_mock_data.rs
index 1cf07529e8..605e0b8ce2 100644
--- a/frontend/rust-lib/flowy-database2/tests/database/mock_data/board_mock_data.rs
+++ b/frontend/rust-lib/flowy-database2/tests/database/mock_data/board_mock_data.rs
@@ -161,9 +161,7 @@ pub fn make_test_board() -> DatabaseData {
FieldType::RichText => row_builder.insert_text_cell("A"),
FieldType::Number => row_builder.insert_number_cell("1"),
// 1647251762 => Mar 14,2022
- FieldType::DateTime => {
- row_builder.insert_date_cell(1647251762, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1647251762, None, &field_type),
FieldType::SingleSelect => {
row_builder.insert_single_select_cell(|mut options| options.remove(0))
},
@@ -181,9 +179,7 @@ pub fn make_test_board() -> DatabaseData {
FieldType::RichText => row_builder.insert_text_cell("B"),
FieldType::Number => row_builder.insert_number_cell("2"),
// 1647251762 => Mar 14,2022
- FieldType::DateTime => {
- row_builder.insert_date_cell(1647251762, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1647251762, None, &field_type),
FieldType::SingleSelect => {
row_builder.insert_single_select_cell(|mut options| options.remove(0))
},
@@ -200,9 +196,7 @@ pub fn make_test_board() -> DatabaseData {
FieldType::RichText => row_builder.insert_text_cell("C"),
FieldType::Number => row_builder.insert_number_cell("3"),
// 1647251762 => Mar 14,2022
- FieldType::DateTime => {
- row_builder.insert_date_cell(1647251762, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1647251762, None, &field_type),
FieldType::SingleSelect => {
row_builder.insert_single_select_cell(|mut options| options.remove(1))
},
@@ -222,9 +216,7 @@ pub fn make_test_board() -> DatabaseData {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("DA"),
FieldType::Number => row_builder.insert_number_cell("4"),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1668704685, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1668704685, None, &field_type),
FieldType::SingleSelect => {
row_builder.insert_single_select_cell(|mut options| options.remove(1))
},
@@ -239,9 +231,7 @@ pub fn make_test_board() -> DatabaseData {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("AE"),
FieldType::Number => row_builder.insert_number_cell(""),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1668359085, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1668359085, None, &field_type),
FieldType::SingleSelect => {
row_builder.insert_single_select_cell(|mut options| options.remove(2))
},
diff --git a/frontend/rust-lib/flowy-database2/tests/database/mock_data/calendar_mock_data.rs b/frontend/rust-lib/flowy-database2/tests/database/mock_data/calendar_mock_data.rs
index a14de66ed4..bc374ae32e 100644
--- a/frontend/rust-lib/flowy-database2/tests/database/mock_data/calendar_mock_data.rs
+++ b/frontend/rust-lib/flowy-database2/tests/database/mock_data/calendar_mock_data.rs
@@ -48,9 +48,7 @@ pub fn make_test_calendar() -> DatabaseData {
for field_type in FieldType::iter() {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("A"),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1678090778, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1678090778, None, &field_type),
_ => "".to_owned(),
};
}
@@ -59,9 +57,7 @@ pub fn make_test_calendar() -> DatabaseData {
for field_type in FieldType::iter() {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("B"),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1677917978, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1677917978, None, &field_type),
_ => "".to_owned(),
};
}
@@ -70,9 +66,7 @@ pub fn make_test_calendar() -> DatabaseData {
for field_type in FieldType::iter() {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("C"),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1679213978, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1679213978, None, &field_type),
_ => "".to_owned(),
};
}
@@ -81,9 +75,7 @@ pub fn make_test_calendar() -> DatabaseData {
for field_type in FieldType::iter() {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("D"),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1678695578, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1678695578, None, &field_type),
_ => "".to_owned(),
};
}
@@ -92,9 +84,7 @@ pub fn make_test_calendar() -> DatabaseData {
for field_type in FieldType::iter() {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("E"),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1678695578, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1678695578, None, &field_type),
_ => "".to_owned(),
};
}
diff --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.rs
index 208f82cc42..fac99c431b 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
@@ -181,9 +181,7 @@ pub fn make_test_grid() -> DatabaseData {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("A"),
FieldType::Number => row_builder.insert_number_cell("1"),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1647251762, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1647251762, None, &field_type),
FieldType::MultiSelect => row_builder
.insert_multi_select_cell(|mut options| vec![options.remove(0), options.remove(0)]),
FieldType::Checkbox => row_builder.insert_checkbox_cell("true"),
@@ -206,9 +204,7 @@ pub fn make_test_grid() -> DatabaseData {
match field_type {
FieldType::RichText => row_builder.insert_text_cell(""),
FieldType::Number => row_builder.insert_number_cell("2"),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1647251762, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1647251762, None, &field_type),
FieldType::MultiSelect => row_builder
.insert_multi_select_cell(|mut options| vec![options.remove(0), options.remove(1)]),
FieldType::Checkbox => row_builder.insert_checkbox_cell("true"),
@@ -228,9 +224,7 @@ pub fn make_test_grid() -> DatabaseData {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("C"),
FieldType::Number => row_builder.insert_number_cell("3"),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1647251762, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1647251762, None, &field_type),
FieldType::SingleSelect => {
row_builder.insert_single_select_cell(|mut options| options.remove(0))
},
@@ -247,9 +241,7 @@ pub fn make_test_grid() -> DatabaseData {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("DA"),
FieldType::Number => row_builder.insert_number_cell("14"),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1668704685, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1668704685, None, &field_type),
FieldType::SingleSelect => {
row_builder.insert_single_select_cell(|mut options| options.remove(0))
},
@@ -269,9 +261,7 @@ pub fn make_test_grid() -> DatabaseData {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("AE"),
FieldType::Number => row_builder.insert_number_cell(""),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1668359085, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1668359085, None, &field_type),
FieldType::SingleSelect => {
row_builder.insert_single_select_cell(|mut options| options.remove(1))
},
@@ -287,9 +277,7 @@ pub fn make_test_grid() -> DatabaseData {
match field_type {
FieldType::RichText => row_builder.insert_text_cell("AE"),
FieldType::Number => row_builder.insert_number_cell("5"),
- FieldType::DateTime => {
- row_builder.insert_date_cell(1671938394, None, None, &field_type)
- },
+ FieldType::DateTime => row_builder.insert_date_cell(1671938394, None, &field_type),
FieldType::SingleSelect => {
row_builder.insert_single_select_cell(|mut options| options.remove(1))
},