editor_page.dart 15 KB

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