editor_page.dart 15 KB

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