main.dart 6.8 KB

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