editor_page.dart 17 KB

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