editor_page.dart 16 KB

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