main.dart 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:example/home_page.dart';
  4. import 'package:example/plugin/editor_theme.dart';
  5. import 'package:flutter/foundation.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:flutter/services.dart';
  8. import 'package:example/plugin/code_block_node_widget.dart';
  9. import 'package:example/plugin/horizontal_rule_node_widget.dart';
  10. import 'package:example/plugin/tex_block_node_widget.dart';
  11. import 'package:file_picker/file_picker.dart';
  12. import 'package:flutter_localizations/flutter_localizations.dart';
  13. import 'package:path_provider/path_provider.dart';
  14. import 'package:universal_html/html.dart' as html;
  15. import 'package:appflowy_editor/appflowy_editor.dart';
  16. import 'expandable_floating_action_button.dart';
  17. void main() {
  18. runApp(const MyApp());
  19. }
  20. class MyApp extends StatelessWidget {
  21. const MyApp({Key? key}) : super(key: key);
  22. @override
  23. Widget build(BuildContext context) {
  24. return const MaterialApp(
  25. localizationsDelegates: [
  26. GlobalMaterialLocalizations.delegate,
  27. GlobalCupertinoLocalizations.delegate,
  28. GlobalWidgetsLocalizations.delegate,
  29. AppFlowyEditorLocalizations.delegate,
  30. ],
  31. supportedLocales: [Locale('en', 'US')],
  32. debugShowCheckedModeBanner: false,
  33. home: MyHomePage(title: 'AppFlowyEditor Example'),
  34. );
  35. }
  36. }
  37. class MyHomePage extends StatefulWidget {
  38. const MyHomePage({Key? key, required this.title}) : super(key: key);
  39. final String title;
  40. @override
  41. State<MyHomePage> createState() => _MyHomePageState();
  42. }
  43. class _MyHomePageState extends State<MyHomePage> {
  44. int _pageIndex = 0;
  45. EditorState? _editorState;
  46. bool darkMode = false;
  47. Future<String>? _jsonString;
  48. ThemeData? _editorThemeData;
  49. @override
  50. Widget build(BuildContext context) {
  51. return const HomePage();
  52. }
  53. Widget _buildEditor(BuildContext context) {
  54. if (_jsonString != null) {
  55. return _buildEditorWithJsonString(_jsonString!);
  56. }
  57. if (_pageIndex == 0) {
  58. return _buildEditorWithJsonString(
  59. rootBundle.loadString('assets/example.json'),
  60. );
  61. } else if (_pageIndex == 1) {
  62. return _buildEditorWithJsonString(
  63. Future.value(
  64. jsonEncode(EditorState.empty().document.toJson()),
  65. ),
  66. );
  67. }
  68. throw UnimplementedError();
  69. }
  70. Widget _buildEditorWithJsonString(Future<String> jsonString) {
  71. return FutureBuilder<String>(
  72. future: jsonString,
  73. builder: (_, snapshot) {
  74. if (snapshot.hasData &&
  75. snapshot.connectionState == ConnectionState.done) {
  76. _editorState ??= EditorState(
  77. document: Document.fromJson(
  78. Map<String, Object>.from(
  79. json.decode(snapshot.data!),
  80. ),
  81. ),
  82. );
  83. _editorState!.logConfiguration
  84. ..level = LogLevel.all
  85. ..handler = (message) {
  86. debugPrint(message);
  87. };
  88. _editorState!.transactionStream.listen((event) {
  89. debugPrint('Transaction: ${event.toJson()}');
  90. });
  91. _editorThemeData ??= Theme.of(context).copyWith(extensions: [
  92. if (darkMode) ...darkEditorStyleExtension,
  93. if (darkMode) ...darkPlguinStyleExtension,
  94. if (!darkMode) ...lightEditorStyleExtension,
  95. if (!darkMode) ...lightPlguinStyleExtension,
  96. ]);
  97. return Container(
  98. color: darkMode ? Colors.black : Colors.white,
  99. width: MediaQuery.of(context).size.width,
  100. child: AppFlowyEditor(
  101. editorState: _editorState!,
  102. editable: true,
  103. autoFocus: _editorState!.document.isEmpty,
  104. themeData: _editorThemeData,
  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(BuildContext context) {
  131. return FloatingActionButton(onPressed: () {
  132. Scaffold.of(context).openDrawer();
  133. });
  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. }