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