editor_page.dart 15 KB

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