editor_page.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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 = onlyShowInSingleTextTypeSelectionAndExcludeTable,
  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 editor = AppFlowyEditor(
  129. editorState: widget.editorState,
  130. editable: true,
  131. shrinkWrap: widget.shrinkWrap,
  132. scrollController: effectiveScrollController,
  133. // setup the auto focus parameters
  134. autoFocus: widget.autoFocus ?? autoFocus,
  135. focusedSelection: selection,
  136. // setup the theme
  137. editorStyle: styleCustomizer.style(),
  138. // customize the block builder
  139. blockComponentBuilders: blockComponentBuilders,
  140. // customize the shortcuts
  141. characterShortcutEvents: characterShortcutEvents,
  142. commandShortcutEvents: commandShortcutEvents,
  143. contextMenuItems: customContextMenuItems,
  144. header: widget.header,
  145. footer: const VSpace(200),
  146. );
  147. return Center(
  148. child: ConstrainedBox(
  149. constraints: const BoxConstraints(
  150. maxWidth: double.infinity,
  151. maxHeight: double.infinity,
  152. ),
  153. child: FloatingToolbar(
  154. style: styleCustomizer.floatingToolbarStyleBuilder(),
  155. items: toolbarItems,
  156. editorState: widget.editorState,
  157. scrollController: effectiveScrollController,
  158. child: editor,
  159. ),
  160. ),
  161. );
  162. }
  163. Map<String, BlockComponentBuilder> _customAppFlowyBlockComponentBuilders() {
  164. final standardActions = [
  165. OptionAction.delete,
  166. OptionAction.duplicate,
  167. // OptionAction.divider,
  168. // OptionAction.moveUp,
  169. // OptionAction.moveDown,
  170. ];
  171. final calloutBGColor = AFThemeExtension.of(context).calloutBGColor;
  172. final configuration = BlockComponentConfiguration(
  173. padding: (_) => const EdgeInsets.symmetric(vertical: 5.0),
  174. );
  175. final customBlockComponentBuilderMap = {
  176. PageBlockKeys.type: PageBlockComponentBuilder(),
  177. ParagraphBlockKeys.type: TextBlockComponentBuilder(
  178. configuration: configuration,
  179. ),
  180. TodoListBlockKeys.type: TodoListBlockComponentBuilder(
  181. configuration: configuration.copyWith(
  182. placeholderText: (_) => 'To-do',
  183. ),
  184. ),
  185. BulletedListBlockKeys.type: BulletedListBlockComponentBuilder(
  186. configuration: configuration.copyWith(
  187. placeholderText: (_) => 'List',
  188. ),
  189. ),
  190. NumberedListBlockKeys.type: NumberedListBlockComponentBuilder(
  191. configuration: configuration.copyWith(
  192. placeholderText: (_) => 'List',
  193. ),
  194. ),
  195. QuoteBlockKeys.type: QuoteBlockComponentBuilder(
  196. configuration: configuration.copyWith(
  197. placeholderText: (_) => 'Quote',
  198. ),
  199. ),
  200. HeadingBlockKeys.type: HeadingBlockComponentBuilder(
  201. configuration: configuration.copyWith(
  202. padding: (_) => const EdgeInsets.only(top: 12.0, bottom: 4.0),
  203. placeholderText: (node) =>
  204. 'Heading ${node.attributes[HeadingBlockKeys.level]}',
  205. ),
  206. textStyleBuilder: (level) => styleCustomizer.headingStyleBuilder(level),
  207. ),
  208. ImageBlockKeys.type: ImageBlockComponentBuilder(
  209. configuration: configuration,
  210. showMenu: true,
  211. menuBuilder: (node, state) => Positioned(
  212. top: 0,
  213. right: 10,
  214. child: ImageMenu(
  215. node: node,
  216. state: state,
  217. ),
  218. ),
  219. ),
  220. TableBlockKeys.type: TableBlockComponentBuilder(
  221. menuBuilder: (node, editorState, position, dir, onBuild, onClose) =>
  222. TableMenu(
  223. node: node,
  224. editorState: editorState,
  225. position: position,
  226. dir: dir,
  227. onBuild: onBuild,
  228. onClose: onClose,
  229. ),
  230. ),
  231. TableCellBlockKeys.type: TableCellBlockComponentBuilder(
  232. menuBuilder: (node, editorState, position, dir, onBuild, onClose) =>
  233. TableMenu(
  234. node: node,
  235. editorState: editorState,
  236. position: position,
  237. dir: dir,
  238. onBuild: onBuild,
  239. onClose: onClose,
  240. ),
  241. ),
  242. DatabaseBlockKeys.gridType: DatabaseViewBlockComponentBuilder(
  243. configuration: configuration.copyWith(
  244. padding: (_) => const EdgeInsets.symmetric(vertical: 10),
  245. ),
  246. ),
  247. DatabaseBlockKeys.boardType: DatabaseViewBlockComponentBuilder(
  248. configuration: configuration.copyWith(
  249. padding: (_) => const EdgeInsets.symmetric(vertical: 10),
  250. ),
  251. ),
  252. DatabaseBlockKeys.calendarType: DatabaseViewBlockComponentBuilder(
  253. configuration: configuration.copyWith(
  254. padding: (_) => const EdgeInsets.symmetric(vertical: 10),
  255. ),
  256. ),
  257. CalloutBlockKeys.type: CalloutBlockComponentBuilder(
  258. configuration: configuration,
  259. defaultColor: calloutBGColor,
  260. ),
  261. DividerBlockKeys.type: DividerBlockComponentBuilder(
  262. configuration: configuration,
  263. height: 28.0,
  264. ),
  265. MathEquationBlockKeys.type: MathEquationBlockComponentBuilder(
  266. configuration: configuration.copyWith(
  267. padding: (_) => const EdgeInsets.symmetric(vertical: 20),
  268. ),
  269. ),
  270. CodeBlockKeys.type: CodeBlockComponentBuilder(
  271. configuration: configuration.copyWith(
  272. textStyle: (_) => styleCustomizer.codeBlockStyleBuilder(),
  273. placeholderTextStyle: (_) => styleCustomizer.codeBlockStyleBuilder(),
  274. ),
  275. padding: const EdgeInsets.only(
  276. left: 30,
  277. right: 30,
  278. bottom: 36,
  279. ),
  280. ),
  281. AutoCompletionBlockKeys.type: AutoCompletionBlockComponentBuilder(),
  282. SmartEditBlockKeys.type: SmartEditBlockComponentBuilder(),
  283. ToggleListBlockKeys.type: ToggleListBlockComponentBuilder(
  284. configuration: configuration,
  285. ),
  286. OutlineBlockKeys.type: OutlineBlockComponentBuilder(
  287. configuration: configuration.copyWith(
  288. placeholderTextStyle: (_) =>
  289. styleCustomizer.outlineBlockPlaceholderStyleBuilder(),
  290. ),
  291. ),
  292. };
  293. final builders = {
  294. ...standardBlockComponentBuilderMap,
  295. ...customBlockComponentBuilderMap,
  296. };
  297. // customize the action builder. actually, we can customize them in their own builder. Put them here just for convenience.
  298. for (final entry in builders.entries) {
  299. if (entry.key == PageBlockKeys.type) {
  300. continue;
  301. }
  302. final builder = entry.value;
  303. // customize the action builder.
  304. final supportColorBuilderTypes = [
  305. ParagraphBlockKeys.type,
  306. HeadingBlockKeys.type,
  307. BulletedListBlockKeys.type,
  308. NumberedListBlockKeys.type,
  309. QuoteBlockKeys.type,
  310. TodoListBlockKeys.type,
  311. CalloutBlockKeys.type,
  312. OutlineBlockKeys.type,
  313. ToggleListBlockKeys.type,
  314. ];
  315. final supportAlignBuilderType = [
  316. ImageBlockKeys.type,
  317. ];
  318. final colorAction = [
  319. OptionAction.divider,
  320. OptionAction.color,
  321. ];
  322. final alignAction = [
  323. OptionAction.divider,
  324. OptionAction.align,
  325. ];
  326. final List<OptionAction> actions = [
  327. ...standardActions,
  328. if (supportColorBuilderTypes.contains(entry.key)) ...colorAction,
  329. if (supportAlignBuilderType.contains(entry.key)) ...alignAction,
  330. ];
  331. builder.showActions =
  332. (node) => node.parent?.type != TableCellBlockKeys.type;
  333. builder.actionBuilder = (context, state) {
  334. final top = builder.configuration.padding(context.node).top;
  335. final padding = context.node.type == HeadingBlockKeys.type
  336. ? EdgeInsets.only(top: top + 8.0)
  337. : EdgeInsets.only(top: top + 2.0);
  338. return Padding(
  339. padding: padding,
  340. child: BlockActionList(
  341. blockComponentContext: context,
  342. blockComponentState: state,
  343. editorState: widget.editorState,
  344. actions: actions,
  345. showSlashMenu: () => showSlashMenu(widget.editorState),
  346. ),
  347. );
  348. };
  349. }
  350. return builders;
  351. }
  352. List<SelectionMenuItem> _customSlashMenuItems() {
  353. final items = [...standardSelectionMenuItems];
  354. final imageItem = items.firstWhereOrNull(
  355. (element) => element.name == AppFlowyEditorLocalizations.current.image,
  356. );
  357. if (imageItem != null) {
  358. final imageItemIndex = items.indexOf(imageItem);
  359. if (imageItemIndex != -1) {
  360. items[imageItemIndex] = customImageMenuItem;
  361. }
  362. }
  363. return [
  364. ...items,
  365. inlineGridMenuItem(documentBloc),
  366. referencedGridMenuItem,
  367. inlineBoardMenuItem(documentBloc),
  368. referencedBoardMenuItem,
  369. inlineCalendarMenuItem(documentBloc),
  370. referencedCalendarMenuItem,
  371. calloutItem,
  372. outlineItem,
  373. mathEquationItem,
  374. codeBlockItem,
  375. toggleListBlockItem,
  376. emojiMenuItem,
  377. autoGeneratorMenuItem,
  378. ];
  379. }
  380. (bool, Selection?) _computeAutoFocusParameters() {
  381. if (widget.editorState.document.isEmpty) {
  382. return (
  383. true,
  384. Selection.collapsed(
  385. Position(path: [0], offset: 0),
  386. ),
  387. );
  388. }
  389. final nodes = widget.editorState.document.root.children
  390. .where((element) => element.delta != null);
  391. final isAllEmpty =
  392. nodes.isNotEmpty && nodes.every((element) => element.delta!.isEmpty);
  393. if (isAllEmpty) {
  394. return (
  395. true,
  396. Selection.collapsed(
  397. Position(path: nodes.first.path, offset: 0),
  398. )
  399. );
  400. }
  401. return const (false, null);
  402. }
  403. Future<void> _initializeShortcuts() async {
  404. //TODO(Xazin): Refactor lazy initialization
  405. defaultCommandShortcutEvents;
  406. final settingsShortcutService = SettingsShortcutService();
  407. final customizeShortcuts =
  408. await settingsShortcutService.getCustomizeShortcuts();
  409. await settingsShortcutService.updateCommandShortcuts(
  410. standardCommandShortcutEvents,
  411. customizeShortcuts,
  412. );
  413. }
  414. }