editor_page.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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/settings/appearance/appearance_cubit.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. supportSlashMenuNodeWhiteList.addAll([
  134. ToggleListBlockKeys.type,
  135. ]);
  136. toolbarItemWhiteList.addAll([
  137. ToggleListBlockKeys.type,
  138. CalloutBlockKeys.type,
  139. TableBlockKeys.type,
  140. ]);
  141. AppFlowyRichTextKeys.supportSliced.add(AppFlowyRichTextKeys.fontFamily);
  142. }
  143. @override
  144. void dispose() {
  145. if (widget.scrollController == null) {
  146. effectiveScrollController.dispose();
  147. }
  148. inlineActionsService.dispose();
  149. widget.editorState.dispose();
  150. super.dispose();
  151. }
  152. @override
  153. Widget build(BuildContext context) {
  154. final (bool autoFocus, Selection? selection) =
  155. _computeAutoFocusParameters();
  156. final isRTL =
  157. context.read<AppearanceSettingsCubit>().state.layoutDirection ==
  158. LayoutDirection.rtlLayout;
  159. final textDirection = isRTL ? TextDirection.rtl : TextDirection.ltr;
  160. _setRTLToolbarItems(isRTL);
  161. final editorScrollController = EditorScrollController(
  162. editorState: widget.editorState,
  163. shrinkWrap: widget.shrinkWrap,
  164. scrollController: effectiveScrollController,
  165. );
  166. final editor = AppFlowyEditor(
  167. editorState: widget.editorState,
  168. editable: true,
  169. editorScrollController: editorScrollController,
  170. // setup the auto focus parameters
  171. autoFocus: widget.autoFocus ?? autoFocus,
  172. focusedSelection: selection,
  173. // setup the theme
  174. editorStyle: styleCustomizer.style(),
  175. // customize the block builders
  176. blockComponentBuilders: blockComponentBuilders,
  177. // customize the shortcuts
  178. characterShortcutEvents: characterShortcutEvents,
  179. commandShortcutEvents: commandShortcutEvents,
  180. // customize the context menu items
  181. contextMenuItems: customContextMenuItems,
  182. // customize the header and footer.
  183. header: widget.header,
  184. footer: const VSpace(200),
  185. );
  186. return Center(
  187. child: FloatingToolbar(
  188. style: styleCustomizer.floatingToolbarStyleBuilder(),
  189. items: toolbarItems,
  190. editorState: widget.editorState,
  191. editorScrollController: editorScrollController,
  192. textDirection: textDirection,
  193. child: Directionality(
  194. textDirection: textDirection,
  195. child: editor,
  196. ),
  197. ),
  198. );
  199. }
  200. Map<String, BlockComponentBuilder> _customAppFlowyBlockComponentBuilders() {
  201. final standardActions = [
  202. OptionAction.delete,
  203. OptionAction.duplicate,
  204. // OptionAction.divider,
  205. // OptionAction.moveUp,
  206. // OptionAction.moveDown,
  207. ];
  208. final calloutBGColor = AFThemeExtension.of(context).calloutBGColor;
  209. final configuration = BlockComponentConfiguration(
  210. padding: (_) => const EdgeInsets.symmetric(vertical: 5.0),
  211. );
  212. final customBlockComponentBuilderMap = {
  213. PageBlockKeys.type: PageBlockComponentBuilder(),
  214. ParagraphBlockKeys.type: ParagraphBlockComponentBuilder(
  215. configuration: configuration,
  216. ),
  217. TodoListBlockKeys.type: TodoListBlockComponentBuilder(
  218. configuration: configuration.copyWith(
  219. placeholderText: (_) => 'To-do',
  220. ),
  221. ),
  222. BulletedListBlockKeys.type: BulletedListBlockComponentBuilder(
  223. configuration: configuration.copyWith(
  224. placeholderText: (_) => 'List',
  225. ),
  226. ),
  227. NumberedListBlockKeys.type: NumberedListBlockComponentBuilder(
  228. configuration: configuration.copyWith(
  229. placeholderText: (_) => 'List',
  230. ),
  231. ),
  232. QuoteBlockKeys.type: QuoteBlockComponentBuilder(
  233. configuration: configuration.copyWith(
  234. placeholderText: (_) => 'Quote',
  235. ),
  236. ),
  237. HeadingBlockKeys.type: HeadingBlockComponentBuilder(
  238. configuration: configuration.copyWith(
  239. padding: (_) => const EdgeInsets.only(top: 12.0, bottom: 4.0),
  240. placeholderText: (node) =>
  241. 'Heading ${node.attributes[HeadingBlockKeys.level]}',
  242. ),
  243. textStyleBuilder: (level) => styleCustomizer.headingStyleBuilder(level),
  244. ),
  245. ImageBlockKeys.type: CustomImageBlockComponentBuilder(
  246. configuration: configuration,
  247. showMenu: true,
  248. menuBuilder: (Node node, CustomImageBlockComponentState state) =>
  249. Positioned(
  250. top: 0,
  251. right: 10,
  252. child: ImageMenu(
  253. node: node,
  254. state: state,
  255. ),
  256. ),
  257. ),
  258. TableBlockKeys.type: TableBlockComponentBuilder(
  259. menuBuilder: (node, editorState, position, dir, onBuild, onClose) =>
  260. TableMenu(
  261. node: node,
  262. editorState: editorState,
  263. position: position,
  264. dir: dir,
  265. onBuild: onBuild,
  266. onClose: onClose,
  267. ),
  268. ),
  269. TableCellBlockKeys.type: TableCellBlockComponentBuilder(
  270. menuBuilder: (node, editorState, position, dir, onBuild, onClose) =>
  271. TableMenu(
  272. node: node,
  273. editorState: editorState,
  274. position: position,
  275. dir: dir,
  276. onBuild: onBuild,
  277. onClose: onClose,
  278. ),
  279. ),
  280. DatabaseBlockKeys.gridType: DatabaseViewBlockComponentBuilder(
  281. configuration: configuration.copyWith(
  282. padding: (_) => const EdgeInsets.symmetric(vertical: 10),
  283. ),
  284. ),
  285. DatabaseBlockKeys.boardType: DatabaseViewBlockComponentBuilder(
  286. configuration: configuration.copyWith(
  287. padding: (_) => const EdgeInsets.symmetric(vertical: 10),
  288. ),
  289. ),
  290. DatabaseBlockKeys.calendarType: DatabaseViewBlockComponentBuilder(
  291. configuration: configuration.copyWith(
  292. padding: (_) => const EdgeInsets.symmetric(vertical: 10),
  293. ),
  294. ),
  295. CalloutBlockKeys.type: CalloutBlockComponentBuilder(
  296. configuration: configuration,
  297. defaultColor: calloutBGColor,
  298. ),
  299. DividerBlockKeys.type: DividerBlockComponentBuilder(
  300. configuration: configuration,
  301. height: 28.0,
  302. ),
  303. MathEquationBlockKeys.type: MathEquationBlockComponentBuilder(
  304. configuration: configuration.copyWith(
  305. padding: (_) => const EdgeInsets.symmetric(vertical: 20),
  306. ),
  307. ),
  308. CodeBlockKeys.type: CodeBlockComponentBuilder(
  309. configuration: configuration.copyWith(
  310. textStyle: (_) => styleCustomizer.codeBlockStyleBuilder(),
  311. placeholderTextStyle: (_) => styleCustomizer.codeBlockStyleBuilder(),
  312. ),
  313. padding: const EdgeInsets.only(
  314. left: 30,
  315. right: 30,
  316. bottom: 36,
  317. ),
  318. ),
  319. AutoCompletionBlockKeys.type: AutoCompletionBlockComponentBuilder(),
  320. SmartEditBlockKeys.type: SmartEditBlockComponentBuilder(),
  321. ToggleListBlockKeys.type: ToggleListBlockComponentBuilder(
  322. configuration: configuration,
  323. ),
  324. OutlineBlockKeys.type: OutlineBlockComponentBuilder(
  325. configuration: configuration.copyWith(
  326. placeholderTextStyle: (_) =>
  327. styleCustomizer.outlineBlockPlaceholderStyleBuilder(),
  328. ),
  329. ),
  330. errorBlockComponentBuilderKey: ErrorBlockComponentBuilder(
  331. configuration: configuration.copyWith(
  332. padding: (_) => const EdgeInsets.symmetric(vertical: 10),
  333. ),
  334. ),
  335. };
  336. final builders = {
  337. ...standardBlockComponentBuilderMap,
  338. ...customBlockComponentBuilderMap,
  339. };
  340. // customize the action builder. actually, we can customize them in their own builder. Put them here just for convenience.
  341. for (final entry in builders.entries) {
  342. if (entry.key == PageBlockKeys.type) {
  343. continue;
  344. }
  345. final builder = entry.value;
  346. // customize the action builder.
  347. final supportColorBuilderTypes = [
  348. ParagraphBlockKeys.type,
  349. HeadingBlockKeys.type,
  350. BulletedListBlockKeys.type,
  351. NumberedListBlockKeys.type,
  352. QuoteBlockKeys.type,
  353. TodoListBlockKeys.type,
  354. CalloutBlockKeys.type,
  355. OutlineBlockKeys.type,
  356. ToggleListBlockKeys.type,
  357. ];
  358. final supportAlignBuilderType = [
  359. ImageBlockKeys.type,
  360. ];
  361. final colorAction = [
  362. OptionAction.divider,
  363. OptionAction.color,
  364. ];
  365. final alignAction = [
  366. OptionAction.divider,
  367. OptionAction.align,
  368. ];
  369. final List<OptionAction> actions = [
  370. ...standardActions,
  371. if (supportColorBuilderTypes.contains(entry.key)) ...colorAction,
  372. if (supportAlignBuilderType.contains(entry.key)) ...alignAction,
  373. ];
  374. builder.showActions =
  375. (node) => node.parent?.type != TableCellBlockKeys.type;
  376. builder.actionBuilder = (context, state) {
  377. final top = builder.configuration.padding(context.node).top;
  378. final padding = context.node.type == HeadingBlockKeys.type
  379. ? EdgeInsets.only(top: top + 8.0)
  380. : EdgeInsets.only(top: top + 2.0);
  381. return Padding(
  382. padding: padding,
  383. child: BlockActionList(
  384. blockComponentContext: context,
  385. blockComponentState: state,
  386. editorState: widget.editorState,
  387. actions: actions,
  388. showSlashMenu: () => showSlashMenu(widget.editorState),
  389. ),
  390. );
  391. };
  392. }
  393. return builders;
  394. }
  395. List<SelectionMenuItem> _customSlashMenuItems() {
  396. final items = [...standardSelectionMenuItems];
  397. final imageItem = items.firstWhereOrNull(
  398. (element) => element.name == AppFlowyEditorLocalizations.current.image,
  399. );
  400. if (imageItem != null) {
  401. final imageItemIndex = items.indexOf(imageItem);
  402. if (imageItemIndex != -1) {
  403. items[imageItemIndex] = customImageMenuItem;
  404. }
  405. }
  406. return [
  407. ...items,
  408. inlineGridMenuItem(documentBloc),
  409. referencedGridMenuItem,
  410. inlineBoardMenuItem(documentBloc),
  411. referencedBoardMenuItem,
  412. inlineCalendarMenuItem(documentBloc),
  413. referencedCalendarMenuItem,
  414. calloutItem,
  415. outlineItem,
  416. mathEquationItem,
  417. codeBlockItem,
  418. toggleListBlockItem,
  419. emojiMenuItem,
  420. autoGeneratorMenuItem,
  421. ];
  422. }
  423. (bool, Selection?) _computeAutoFocusParameters() {
  424. if (widget.editorState.document.isEmpty) {
  425. return (
  426. true,
  427. Selection.collapsed(
  428. Position(path: [0], offset: 0),
  429. ),
  430. );
  431. }
  432. final nodes = widget.editorState.document.root.children
  433. .where((element) => element.delta != null);
  434. final isAllEmpty =
  435. nodes.isNotEmpty && nodes.every((element) => element.delta!.isEmpty);
  436. if (isAllEmpty) {
  437. return (
  438. true,
  439. Selection.collapsed(
  440. Position(path: nodes.first.path, offset: 0),
  441. )
  442. );
  443. }
  444. return const (false, null);
  445. }
  446. Future<void> _initializeShortcuts() async {
  447. // TODO(Xazin): Refactor lazy initialization
  448. defaultCommandShortcutEvents;
  449. final settingsShortcutService = SettingsShortcutService();
  450. final customizeShortcuts =
  451. await settingsShortcutService.getCustomizeShortcuts();
  452. await settingsShortcutService.updateCommandShortcuts(
  453. commandShortcutEvents,
  454. customizeShortcuts,
  455. );
  456. }
  457. void _setRTLToolbarItems(bool isRTL) {
  458. final textDirectionItemIds = textDirectionItems.map((e) => e.id);
  459. // clear all the text direction items
  460. toolbarItems.removeWhere(
  461. (item) => textDirectionItemIds.contains(item.id),
  462. );
  463. // only show the rtl item when the layout direction is ltr.
  464. if (isRTL) {
  465. toolbarItems.addAll(textDirectionItems);
  466. }
  467. }
  468. List<CommandShortcutEvent> _buildFindAndReplaceCommands() {
  469. return findAndReplaceCommands(
  470. context: context,
  471. style: FindReplaceStyle(
  472. findMenuBuilder: (
  473. context,
  474. editorState,
  475. localizations,
  476. style,
  477. showReplaceMenu,
  478. onDismiss,
  479. ) {
  480. return Material(
  481. child: DecoratedBox(
  482. decoration: BoxDecoration(
  483. color: Theme.of(context).colorScheme.surfaceVariant,
  484. borderRadius: BorderRadius.circular(4),
  485. ),
  486. child: FindAndReplaceMenuWidget(
  487. editorState: editorState,
  488. onDismiss: onDismiss,
  489. ),
  490. ),
  491. );
  492. },
  493. ),
  494. );
  495. }
  496. }