editor_page.dart 17 KB

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