editor_page.dart 15 KB

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