editor_page.dart 15 KB

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