main.dart 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:example/plugin/editor_theme.dart';
  4. import 'package:flutter/foundation.dart';
  5. import 'package:flutter/material.dart';
  6. import 'package:flutter/services.dart';
  7. import 'package:example/plugin/code_block_node_widget.dart';
  8. import 'package:example/plugin/horizontal_rule_node_widget.dart';
  9. import 'package:example/plugin/tex_block_node_widget.dart';
  10. import 'package:file_picker/file_picker.dart';
  11. import 'package:flutter_localizations/flutter_localizations.dart';
  12. import 'package:path_provider/path_provider.dart';
  13. import 'package:universal_html/html.dart' as html;
  14. import 'package:appflowy_editor/appflowy_editor.dart';
  15. import 'expandable_floating_action_button.dart';
  16. void main() {
  17. runApp(const MyApp());
  18. }
  19. class MyApp extends StatelessWidget {
  20. const MyApp({Key? key}) : super(key: key);
  21. @override
  22. Widget build(BuildContext context) {
  23. return const MaterialApp(
  24. localizationsDelegates: [
  25. GlobalMaterialLocalizations.delegate,
  26. GlobalCupertinoLocalizations.delegate,
  27. GlobalWidgetsLocalizations.delegate,
  28. AppFlowyEditorLocalizations.delegate,
  29. ],
  30. supportedLocales: [Locale('en', 'US')],
  31. debugShowCheckedModeBanner: false,
  32. home: MyHomePage(title: 'AppFlowyEditor Example'),
  33. );
  34. }
  35. }
  36. class MyHomePage extends StatefulWidget {
  37. const MyHomePage({Key? key, required this.title}) : super(key: key);
  38. final String title;
  39. @override
  40. State<MyHomePage> createState() => _MyHomePageState();
  41. }
  42. class _MyHomePageState extends State<MyHomePage> {
  43. int _pageIndex = 0;
  44. EditorState? _editorState;
  45. bool darkMode = false;
  46. Future<String>? _jsonString;
  47. ThemeData? _editorThemeData;
  48. @override
  49. Widget build(BuildContext context) {
  50. return Scaffold(
  51. extendBodyBehindAppBar: true,
  52. body: _buildEditor(context),
  53. floatingActionButton: _buildExpandableFab(),
  54. );
  55. }
  56. Widget _buildEditor(BuildContext context) {
  57. if (_jsonString != null) {
  58. return _buildEditorWithJsonString(_jsonString!);
  59. }
  60. if (_pageIndex == 0) {
  61. return _buildEditorWithJsonString(
  62. rootBundle.loadString('assets/example.json'),
  63. );
  64. } else if (_pageIndex == 1) {
  65. return _buildEditorWithJsonString(
  66. Future.value(
  67. jsonEncode(EditorState.empty().document.toJson()),
  68. ),
  69. );
  70. }
  71. throw UnimplementedError();
  72. }
  73. Widget _buildEditorWithJsonString(Future<String> jsonString) {
  74. return FutureBuilder<String>(
  75. future: jsonString,
  76. builder: (_, snapshot) {
  77. if (snapshot.hasData &&
  78. snapshot.connectionState == ConnectionState.done) {
  79. _editorState ??= EditorState(
  80. document: Document.fromJson(
  81. Map<String, Object>.from(
  82. json.decode(snapshot.data!),
  83. ),
  84. ),
  85. );
  86. _editorState!.logConfiguration
  87. ..level = LogLevel.all
  88. ..handler = (message) {
  89. debugPrint(message);
  90. };
  91. _editorState!.transactionStream.listen((event) {
  92. debugPrint('Transaction: ${event.toJson()}');
  93. });
  94. _editorThemeData ??= Theme.of(context).copyWith(extensions: [
  95. if (darkMode) ...darkEditorStyleExtension,
  96. if (darkMode) ...darkPlguinStyleExtension,
  97. if (!darkMode) ...lightEditorStyleExtension,
  98. if (!darkMode) ...lightPlguinStyleExtension,
  99. ]);
  100. return Container(
  101. color: darkMode ? Colors.black : Colors.white,
  102. width: MediaQuery.of(context).size.width,
  103. child: AppFlowyEditor(
  104. editorState: _editorState!,
  105. editable: true,
  106. autoFocus: _editorState!.document.isEmpty,
  107. themeData: _editorThemeData,
  108. customBuilders: {
  109. 'text/code_block': CodeBlockNodeWidgetBuilder(),
  110. 'tex': TeXBlockNodeWidgetBuidler(),
  111. 'horizontal_rule': HorizontalRuleWidgetBuilder(),
  112. },
  113. shortcutEvents: [
  114. enterInCodeBlock,
  115. ignoreKeysInCodeBlock,
  116. insertHorizontalRule,
  117. ],
  118. selectionMenuItems: [
  119. codeBlockMenuItem,
  120. teXBlockMenuItem,
  121. horizontalRuleMenuItem,
  122. ],
  123. ),
  124. );
  125. } else {
  126. return const Center(
  127. child: CircularProgressIndicator(),
  128. );
  129. }
  130. },
  131. );
  132. }
  133. Widget _buildExpandableFab() {
  134. return ExpandableFab(
  135. distance: 112.0,
  136. children: [
  137. ActionButton(
  138. icon: const Icon(Icons.abc),
  139. onPressed: () => _switchToPage(0),
  140. ),
  141. ActionButton(
  142. icon: const Icon(Icons.abc),
  143. onPressed: () => _switchToPage(1),
  144. ),
  145. ActionButton(
  146. icon: const Icon(Icons.print),
  147. onPressed: () => _exportDocument(_editorState!),
  148. ),
  149. ActionButton(
  150. icon: const Icon(Icons.import_export),
  151. onPressed: () async => await _importDocument(),
  152. ),
  153. ActionButton(
  154. icon: const Icon(Icons.dark_mode),
  155. onPressed: () {
  156. setState(() {
  157. darkMode = !darkMode;
  158. });
  159. },
  160. ),
  161. ActionButton(
  162. icon: const Icon(Icons.color_lens),
  163. onPressed: () {
  164. setState(() {
  165. _editorThemeData = customizeEditorTheme(context);
  166. darkMode = true;
  167. });
  168. },
  169. ),
  170. ],
  171. );
  172. }
  173. void _exportDocument(EditorState editorState) async {
  174. final document = editorState.document.toJson();
  175. final json = jsonEncode(document);
  176. if (kIsWeb) {
  177. final blob = html.Blob([json], 'text/plain', 'native');
  178. html.AnchorElement(
  179. href: html.Url.createObjectUrlFromBlob(blob).toString(),
  180. )
  181. ..setAttribute('download', 'editor.json')
  182. ..click();
  183. } else {
  184. final directory = await getTemporaryDirectory();
  185. final path = directory.path;
  186. final file = File('$path/editor.json');
  187. await file.writeAsString(json);
  188. if (mounted) {
  189. ScaffoldMessenger.of(context).showSnackBar(
  190. SnackBar(
  191. content: Text('The document is saved to the ${file.path}'),
  192. ),
  193. );
  194. }
  195. }
  196. }
  197. Future<void> _importDocument() async {
  198. if (kIsWeb) {
  199. final result = await FilePicker.platform.pickFiles(
  200. allowMultiple: false,
  201. allowedExtensions: ['json'],
  202. type: FileType.custom,
  203. );
  204. final bytes = result?.files.first.bytes;
  205. if (bytes != null) {
  206. final jsonString = const Utf8Decoder().convert(bytes);
  207. setState(() {
  208. _editorState = null;
  209. _jsonString = Future.value(jsonString);
  210. });
  211. }
  212. } else {
  213. final directory = await getTemporaryDirectory();
  214. final path = '${directory.path}/editor.json';
  215. final file = File(path);
  216. setState(() {
  217. _editorState = null;
  218. _jsonString = file.readAsString();
  219. });
  220. }
  221. }
  222. void _switchToPage(int pageIndex) {
  223. if (pageIndex != _pageIndex) {
  224. setState(() {
  225. _editorThemeData = null;
  226. _editorState = null;
  227. _pageIndex = pageIndex;
  228. });
  229. }
  230. }
  231. }