editor_page.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. import 'package:appflowy/plugins/document/application/doc_bloc.dart';
  2. import 'package:appflowy/plugins/document/presentation/editor_plugins/image/custom_image_block_component.dart';
  3. import 'package:appflowy/plugins/document/presentation/editor_plugins/plugins.dart';
  4. import 'package:appflowy/plugins/document/presentation/editor_style.dart';
  5. import 'package:appflowy/plugins/inline_actions/handlers/date_reference.dart';
  6. import 'package:appflowy/plugins/inline_actions/handlers/inline_page_reference.dart';
  7. import 'package:appflowy/plugins/inline_actions/handlers/reminder_reference.dart';
  8. import 'package:appflowy/plugins/inline_actions/inline_actions_command.dart';
  9. import 'package:appflowy/plugins/inline_actions/inline_actions_service.dart';
  10. import 'package:appflowy/workspace/application/appearance.dart';
  11. import 'package:appflowy/workspace/application/settings/shortcuts/settings_shortcuts_service.dart';
  12. import 'package:appflowy/workspace/presentation/settings/widgets/emoji_picker/emoji_picker.dart';
  13. import 'package:appflowy_editor/appflowy_editor.dart';
  14. import 'package:collection/collection.dart';
  15. import 'package:flowy_infra/theme_extension.dart';
  16. import 'package:flowy_infra_ui/flowy_infra_ui.dart';
  17. import 'package:flutter/material.dart';
  18. import 'package:flutter_bloc/flutter_bloc.dart';
  19. final List<CommandShortcutEvent> commandShortcutEvents = [
  20. toggleToggleListCommand,
  21. ...codeBlockCommands,
  22. customCopyCommand,
  23. customPasteCommand,
  24. customCutCommand,
  25. ...standardCommandShortcutEvents,
  26. ];
  27. final List<CommandShortcutEvent> defaultCommandShortcutEvents = [
  28. ...commandShortcutEvents.map((e) => e.copyWith()).toList(),
  29. ];
  30. /// Wrapper for the appflowy editor.
  31. class AppFlowyEditorPage extends StatefulWidget {
  32. const AppFlowyEditorPage({
  33. super.key,
  34. required this.editorState,
  35. this.header,
  36. this.shrinkWrap = false,
  37. this.scrollController,
  38. this.autoFocus,
  39. required this.styleCustomizer,
  40. });
  41. final Widget? header;
  42. final EditorState editorState;
  43. final ScrollController? scrollController;
  44. final bool shrinkWrap;
  45. final bool? autoFocus;
  46. final EditorStyleCustomizer styleCustomizer;
  47. @override
  48. State<AppFlowyEditorPage> createState() => _AppFlowyEditorPageState();
  49. }
  50. class _AppFlowyEditorPageState extends State<AppFlowyEditorPage> {
  51. late final ScrollController effectiveScrollController;
  52. late final InlineActionsService inlineActionsService = InlineActionsService(
  53. context: context,
  54. handlers: [
  55. InlinePageReferenceService(
  56. currentViewId: documentBloc.view.id,
  57. ).inlinePageReferenceDelegate,
  58. DateReferenceService(context).dateReferenceDelegate,
  59. ReminderReferenceService(context).reminderReferenceDelegate,
  60. ],
  61. );
  62. late final List<CommandShortcutEvent> commandShortcutEvents = [
  63. toggleToggleListCommand,
  64. ...codeBlockCommands,
  65. customCopyCommand,
  66. customPasteCommand,
  67. customCutCommand,
  68. ...standardCommandShortcutEvents,
  69. ..._buildFindAndReplaceCommands(),
  70. ];
  71. final List<ToolbarItem> toolbarItems = [
  72. smartEditItem..isActive = onlyShowInSingleTextTypeSelectionAndExcludeTable,
  73. paragraphItem..isActive = onlyShowInSingleTextTypeSelectionAndExcludeTable,
  74. ...(headingItems
  75. ..forEach(
  76. (e) => e.isActive = onlyShowInSingleSelectionAndTextType,
  77. )),
  78. ...markdownFormatItems,
  79. quoteItem..isActive = onlyShowInSingleTextTypeSelectionAndExcludeTable,
  80. bulletedListItem
  81. ..isActive = onlyShowInSingleTextTypeSelectionAndExcludeTable,
  82. numberedListItem
  83. ..isActive = onlyShowInSingleTextTypeSelectionAndExcludeTable,
  84. inlineMathEquationItem,
  85. linkItem,
  86. alignToolbarItem,
  87. buildTextColorItem(),
  88. buildHighlightColorItem(),
  89. customizeFontToolbarItem,
  90. ];
  91. late final List<SelectionMenuItem> slashMenuItems;
  92. late final Map<String, BlockComponentBuilder> blockComponentBuilders =
  93. _customAppFlowyBlockComponentBuilders();
  94. List<CharacterShortcutEvent> get characterShortcutEvents => [
  95. // code block
  96. ...codeBlockCharacterEvents,
  97. // toggle list
  98. formatGreaterToToggleList,
  99. insertChildNodeInsideToggleList,
  100. // customize the slash menu command
  101. customSlashCommand(
  102. slashMenuItems,
  103. style: styleCustomizer.selectionMenuStyleBuilder(),
  104. ),
  105. ...standardCharacterShortcutEvents
  106. ..removeWhere(
  107. (element) => element == slashCommand,
  108. ), // remove the default slash command.
  109. /// Inline Actions
  110. /// - Reminder
  111. /// - Inline-page reference
  112. inlineActionsCommand(
  113. inlineActionsService,
  114. style: styleCustomizer.inlineActionsMenuStyleBuilder(),
  115. ),
  116. ];
  117. late final showSlashMenu = customSlashCommand(
  118. slashMenuItems,
  119. shouldInsertSlash: false,
  120. style: styleCustomizer.selectionMenuStyleBuilder(),
  121. ).handler;
  122. EditorStyleCustomizer get styleCustomizer => widget.styleCustomizer;
  123. DocumentBloc get documentBloc => context.read<DocumentBloc>();
  124. @override
  125. void initState() {
  126. super.initState();
  127. _initializeShortcuts();
  128. indentableBlockTypes.add(ToggleListBlockKeys.type);
  129. convertibleBlockTypes.add(ToggleListBlockKeys.type);
  130. slashMenuItems = _customSlashMenuItems();
  131. effectiveScrollController = widget.scrollController ?? ScrollController();
  132. // keep the previous font style when typing new text.
  133. AppFlowyRichTextKeys.supportSliced.add(AppFlowyRichTextKeys.fontFamily);
  134. }
  135. @override
  136. void dispose() {
  137. if (widget.scrollController == null) {
  138. effectiveScrollController.dispose();
  139. }
  140. inlineActionsService.dispose();
  141. widget.editorState.dispose();
  142. super.dispose();
  143. }
  144. @override
  145. Widget build(BuildContext context) {
  146. final (bool autoFocus, Selection? selection) =
  147. _computeAutoFocusParameters();
  148. final isRTL =
  149. context.read<AppearanceSettingsCubit>().state.layoutDirection ==
  150. LayoutDirection.rtlLayout;
  151. final textDirection = isRTL ? TextDirection.rtl : TextDirection.ltr;
  152. _setRTLToolbarItems(isRTL);
  153. final editorScrollController = EditorScrollController(
  154. editorState: widget.editorState,
  155. shrinkWrap: widget.shrinkWrap,
  156. scrollController: effectiveScrollController,
  157. );
  158. final editor = AppFlowyEditor(
  159. editorState: widget.editorState,
  160. editable: true,
  161. editorScrollController: editorScrollController,
  162. // setup the auto focus parameters
  163. autoFocus: widget.autoFocus ?? autoFocus,
  164. focusedSelection: selection,
  165. // setup the theme
  166. editorStyle: styleCustomizer.style(),
  167. // customize the block builders
  168. blockComponentBuilders: blockComponentBuilders,
  169. // customize the shortcuts
  170. characterShortcutEvents: characterShortcutEvents,
  171. commandShortcutEvents: commandShortcutEvents,
  172. // customize the context menu items
  173. contextMenuItems: customContextMenuItems,
  174. // customize the header and footer.
  175. header: widget.header,
  176. footer: const VSpace(200),
  177. );
  178. return Center(
  179. child: FloatingToolbar(
  180. style: styleCustomizer.floatingToolbarStyleBuilder(),
  181. items: toolbarItems,
  182. editorState: widget.editorState,
  183. editorScrollController: editorScrollController,
  184. textDirection: textDirection,
  185. child: Directionality(
  186. textDirection: textDirection,
  187. child: editor,
  188. ),
  189. ),
  190. );
  191. }
  192. Map<String, BlockComponentBuilder> _customAppFlowyBlockComponentBuilders() {
  193. final standardActions = [
  194. OptionAction.delete,
  195. OptionAction.duplicate,
  196. // OptionAction.divider,
  197. // OptionAction.moveUp,
  198. // OptionAction.moveDown,
  199. ];
  200. final calloutBGColor = AFThemeExtension.of(context).calloutBGColor;
  201. final configuration = BlockComponentConfiguration(
  202. padding: (_) => const EdgeInsets.symmetric(vertical: 5.0),
  203. );
  204. final customBlockComponentBuilderMap = {
  205. PageBlockKeys.type: PageBlockComponentBuilder(),
  206. ParagraphBlockKeys.type: TextBlockComponentBuilder(
  207. configuration: configuration,
  208. ),
  209. TodoListBlockKeys.type: TodoListBlockComponentBuilder(
  210. configuration: configuration.copyWith(
  211. placeholderText: (_) => 'To-do',
  212. ),
  213. ),
  214. BulletedListBlockKeys.type: BulletedListBlockComponentBuilder(
  215. configuration: configuration.copyWith(
  216. placeholderText: (_) => 'List',
  217. ),
  218. ),
  219. NumberedListBlockKeys.type: NumberedListBlockComponentBuilder(
  220. configuration: configuration.copyWith(
  221. placeholderText: (_) => 'List',
  222. ),
  223. ),
  224. QuoteBlockKeys.type: QuoteBlockComponentBuilder(
  225. configuration: configuration.copyWith(
  226. placeholderText: (_) => 'Quote',
  227. ),
  228. ),
  229. HeadingBlockKeys.type: HeadingBlockComponentBuilder(
  230. configuration: configuration.copyWith(
  231. padding: (_) => const EdgeInsets.only(top: 12.0, bottom: 4.0),
  232. placeholderText: (node) =>
  233. 'Heading ${node.attributes[HeadingBlockKeys.level]}',
  234. ),
  235. textStyleBuilder: (level) => styleCustomizer.headingStyleBuilder(level),
  236. ),
  237. ImageBlockKeys.type: CustomImageBlockComponentBuilder(
  238. configuration: configuration,
  239. showMenu: true,
  240. menuBuilder: (Node node, CustomImageBlockComponentState state) =>
  241. Positioned(
  242. top: 0,
  243. right: 10,
  244. child: ImageMenu(
  245. node: node,
  246. state: state,
  247. ),
  248. ),
  249. ),
  250. TableBlockKeys.type: TableBlockComponentBuilder(
  251. menuBuilder: (node, editorState, position, dir, onBuild, onClose) =>
  252. TableMenu(
  253. node: node,
  254. editorState: editorState,
  255. position: position,
  256. dir: dir,
  257. onBuild: onBuild,
  258. onClose: onClose,
  259. ),
  260. ),
  261. TableCellBlockKeys.type: TableCellBlockComponentBuilder(
  262. menuBuilder: (node, editorState, position, dir, onBuild, onClose) =>
  263. TableMenu(
  264. node: node,
  265. editorState: editorState,
  266. position: position,
  267. dir: dir,
  268. onBuild: onBuild,
  269. onClose: onClose,
  270. ),
  271. ),
  272. DatabaseBlockKeys.gridType: DatabaseViewBlockComponentBuilder(
  273. configuration: configuration.copyWith(
  274. padding: (_) => const EdgeInsets.symmetric(vertical: 10),
  275. ),
  276. ),
  277. DatabaseBlockKeys.boardType: DatabaseViewBlockComponentBuilder(
  278. configuration: configuration.copyWith(
  279. padding: (_) => const EdgeInsets.symmetric(vertical: 10),
  280. ),
  281. ),
  282. DatabaseBlockKeys.calendarType: DatabaseViewBlockComponentBuilder(
  283. configuration: configuration.copyWith(
  284. padding: (_) => const EdgeInsets.symmetric(vertical: 10),
  285. ),
  286. ),
  287. CalloutBlockKeys.type: CalloutBlockComponentBuilder(
  288. configuration: configuration,
  289. defaultColor: calloutBGColor,
  290. ),
  291. DividerBlockKeys.type: DividerBlockComponentBuilder(
  292. configuration: configuration,
  293. height: 28.0,
  294. ),
  295. MathEquationBlockKeys.type: MathEquationBlockComponentBuilder(
  296. configuration: configuration.copyWith(
  297. padding: (_) => const EdgeInsets.symmetric(vertical: 20),
  298. ),
  299. ),
  300. CodeBlockKeys.type: CodeBlockComponentBuilder(
  301. configuration: configuration.copyWith(
  302. textStyle: (_) => styleCustomizer.codeBlockStyleBuilder(),
  303. placeholderTextStyle: (_) => styleCustomizer.codeBlockStyleBuilder(),
  304. ),
  305. padding: const EdgeInsets.only(
  306. left: 30,
  307. right: 30,
  308. bottom: 36,
  309. ),
  310. ),
  311. AutoCompletionBlockKeys.type: AutoCompletionBlockComponentBuilder(),
  312. SmartEditBlockKeys.type: SmartEditBlockComponentBuilder(),
  313. ToggleListBlockKeys.type: ToggleListBlockComponentBuilder(
  314. configuration: configuration,
  315. ),
  316. OutlineBlockKeys.type: OutlineBlockComponentBuilder(
  317. configuration: configuration.copyWith(
  318. placeholderTextStyle: (_) =>
  319. styleCustomizer.outlineBlockPlaceholderStyleBuilder(),
  320. ),
  321. ),
  322. };
  323. final builders = {
  324. ...standardBlockComponentBuilderMap,
  325. ...customBlockComponentBuilderMap,
  326. };
  327. // customize the action builder. actually, we can customize them in their own builder. Put them here just for convenience.
  328. for (final entry in builders.entries) {
  329. if (entry.key == PageBlockKeys.type) {
  330. continue;
  331. }
  332. final builder = entry.value;
  333. // customize the action builder.
  334. final supportColorBuilderTypes = [
  335. ParagraphBlockKeys.type,
  336. HeadingBlockKeys.type,
  337. BulletedListBlockKeys.type,
  338. NumberedListBlockKeys.type,
  339. QuoteBlockKeys.type,
  340. TodoListBlockKeys.type,
  341. CalloutBlockKeys.type,
  342. OutlineBlockKeys.type,
  343. ToggleListBlockKeys.type,
  344. ];
  345. final supportAlignBuilderType = [
  346. ImageBlockKeys.type,
  347. ];
  348. final colorAction = [
  349. OptionAction.divider,
  350. OptionAction.color,
  351. ];
  352. final alignAction = [
  353. OptionAction.divider,
  354. OptionAction.align,
  355. ];
  356. final List<OptionAction> actions = [
  357. ...standardActions,
  358. if (supportColorBuilderTypes.contains(entry.key)) ...colorAction,
  359. if (supportAlignBuilderType.contains(entry.key)) ...alignAction,
  360. ];
  361. builder.showActions =
  362. (node) => node.parent?.type != TableCellBlockKeys.type;
  363. builder.actionBuilder = (context, state) {
  364. final top = builder.configuration.padding(context.node).top;
  365. final padding = context.node.type == HeadingBlockKeys.type
  366. ? EdgeInsets.only(top: top + 8.0)
  367. : EdgeInsets.only(top: top + 2.0);
  368. return Padding(
  369. padding: padding,
  370. child: BlockActionList(
  371. blockComponentContext: context,
  372. blockComponentState: state,
  373. editorState: widget.editorState,
  374. actions: actions,
  375. showSlashMenu: () => showSlashMenu(widget.editorState),
  376. ),
  377. );
  378. };
  379. }
  380. return builders;
  381. }
  382. List<SelectionMenuItem> _customSlashMenuItems() {
  383. final items = [...standardSelectionMenuItems];
  384. final imageItem = items.firstWhereOrNull(
  385. (element) => element.name == AppFlowyEditorLocalizations.current.image,
  386. );
  387. if (imageItem != null) {
  388. final imageItemIndex = items.indexOf(imageItem);
  389. if (imageItemIndex != -1) {
  390. items[imageItemIndex] = customImageMenuItem;
  391. }
  392. }
  393. return [
  394. ...items,
  395. inlineGridMenuItem(documentBloc),
  396. referencedGridMenuItem,
  397. inlineBoardMenuItem(documentBloc),
  398. referencedBoardMenuItem,
  399. inlineCalendarMenuItem(documentBloc),
  400. referencedCalendarMenuItem,
  401. calloutItem,
  402. outlineItem,
  403. mathEquationItem,
  404. codeBlockItem,
  405. toggleListBlockItem,
  406. emojiMenuItem,
  407. autoGeneratorMenuItem,
  408. ];
  409. }
  410. (bool, Selection?) _computeAutoFocusParameters() {
  411. if (widget.editorState.document.isEmpty) {
  412. return (
  413. true,
  414. Selection.collapsed(
  415. Position(path: [0], offset: 0),
  416. ),
  417. );
  418. }
  419. final nodes = widget.editorState.document.root.children
  420. .where((element) => element.delta != null);
  421. final isAllEmpty =
  422. nodes.isNotEmpty && nodes.every((element) => element.delta!.isEmpty);
  423. if (isAllEmpty) {
  424. return (
  425. true,
  426. Selection.collapsed(
  427. Position(path: nodes.first.path, offset: 0),
  428. )
  429. );
  430. }
  431. return const (false, null);
  432. }
  433. Future<void> _initializeShortcuts() async {
  434. // TODO(Xazin): Refactor lazy initialization
  435. defaultCommandShortcutEvents;
  436. final settingsShortcutService = SettingsShortcutService();
  437. final customizeShortcuts =
  438. await settingsShortcutService.getCustomizeShortcuts();
  439. await settingsShortcutService.updateCommandShortcuts(
  440. commandShortcutEvents,
  441. customizeShortcuts,
  442. );
  443. }
  444. void _setRTLToolbarItems(bool isRTL) {
  445. final textDirectionItemIds = textDirectionItems.map((e) => e.id);
  446. // clear all the text direction items
  447. toolbarItems.removeWhere(
  448. (item) => textDirectionItemIds.contains(item.id),
  449. );
  450. // only show the rtl item when the layout direction is ltr.
  451. if (isRTL) {
  452. toolbarItems.addAll(textDirectionItems);
  453. }
  454. }
  455. List<CommandShortcutEvent> _buildFindAndReplaceCommands() {
  456. return findAndReplaceCommands(
  457. context: context,
  458. style: FindReplaceStyle(
  459. findMenuBuilder: (
  460. context,
  461. editorState,
  462. localizations,
  463. style,
  464. showReplaceMenu,
  465. onDismiss,
  466. ) {
  467. return Material(
  468. child: DecoratedBox(
  469. decoration: BoxDecoration(
  470. color: Theme.of(context).colorScheme.surfaceVariant,
  471. borderRadius: BorderRadius.circular(4),
  472. ),
  473. child: FindAndReplaceMenuWidget(
  474. editorState: editorState,
  475. onDismiss: onDismiss,
  476. ),
  477. ),
  478. );
  479. },
  480. ),
  481. );
  482. }
  483. }