editor_page.dart 17 KB

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