editor_page.dart 14 KB

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