main.dart 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. themeData: _editorThemeData,
  107. customBuilders: {
  108. 'text/code_block': CodeBlockNodeWidgetBuilder(),
  109. 'tex': TeXBlockNodeWidgetBuidler(),
  110. 'horizontal_rule': HorizontalRuleWidgetBuilder(),
  111. },
  112. shortcutEvents: [
  113. enterInCodeBlock,
  114. ignoreKeysInCodeBlock,
  115. insertHorizontalRule,
  116. ],
  117. selectionMenuItems: [
  118. codeBlockMenuItem,
  119. teXBlockMenuItem,
  120. horizontalRuleMenuItem,
  121. ],
  122. ),
  123. );
  124. } else {
  125. return const Center(
  126. child: CircularProgressIndicator(),
  127. );
  128. }
  129. },
  130. );
  131. }
  132. Widget _buildExpandableFab() {
  133. return ExpandableFab(
  134. distance: 112.0,
  135. children: [
  136. ActionButton(
  137. icon: const Icon(Icons.abc),
  138. onPressed: () => _switchToPage(0),
  139. ),
  140. ActionButton(
  141. icon: const Icon(Icons.abc),
  142. onPressed: () => _switchToPage(1),
  143. ),
  144. ActionButton(
  145. icon: const Icon(Icons.print),
  146. onPressed: () => _exportDocument(_editorState!),
  147. ),
  148. ActionButton(
  149. icon: const Icon(Icons.import_export),
  150. onPressed: () async => await _importDocument(),
  151. ),
  152. ActionButton(
  153. icon: const Icon(Icons.dark_mode),
  154. onPressed: () {
  155. setState(() {
  156. darkMode = !darkMode;
  157. });
  158. },
  159. ),
  160. ActionButton(
  161. icon: const Icon(Icons.color_lens),
  162. onPressed: () {
  163. setState(() {
  164. _editorThemeData = customizeEditorTheme(context);
  165. darkMode = true;
  166. });
  167. },
  168. ),
  169. ],
  170. );
  171. }
  172. void _exportDocument(EditorState editorState) async {
  173. final document = editorState.document.toJson();
  174. final json = jsonEncode(document);
  175. if (kIsWeb) {
  176. final blob = html.Blob([json], 'text/plain', 'native');
  177. html.AnchorElement(
  178. href: html.Url.createObjectUrlFromBlob(blob).toString(),
  179. )
  180. ..setAttribute('download', 'editor.json')
  181. ..click();
  182. } else {
  183. final directory = await getTemporaryDirectory();
  184. final path = directory.path;
  185. final file = File('$path/editor.json');
  186. await file.writeAsString(json);
  187. if (mounted) {
  188. ScaffoldMessenger.of(context).showSnackBar(
  189. SnackBar(
  190. content: Text('The document is saved to the ${file.path}'),
  191. ),
  192. );
  193. }
  194. }
  195. }
  196. Future<void> _importDocument() async {
  197. if (kIsWeb) {
  198. final result = await FilePicker.platform.pickFiles(
  199. allowMultiple: false,
  200. allowedExtensions: ['json'],
  201. type: FileType.custom,
  202. );
  203. final bytes = result?.files.first.bytes;
  204. if (bytes != null) {
  205. final jsonString = const Utf8Decoder().convert(bytes);
  206. setState(() {
  207. _editorState = null;
  208. _jsonString = Future.value(jsonString);
  209. });
  210. }
  211. } else {
  212. final directory = await getTemporaryDirectory();
  213. final path = '${directory.path}/editor.json';
  214. final file = File(path);
  215. setState(() {
  216. _editorState = null;
  217. _jsonString = file.readAsString();
  218. });
  219. }
  220. }
  221. void _switchToPage(int pageIndex) {
  222. if (pageIndex != _pageIndex) {
  223. setState(() {
  224. _editorThemeData = null;
  225. _editorState = null;
  226. _pageIndex = pageIndex;
  227. });
  228. }
  229. }
  230. }