main.dart 8.3 KB

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