main.dart 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. autoFocus: _editorState!.document.isEmpty,
  143. customBuilders: {
  144. 'text/code_block': CodeBlockNodeWidgetBuilder(),
  145. 'tex': TeXBlockNodeWidgetBuidler(),
  146. 'horizontal_rule': HorizontalRuleWidgetBuilder(),
  147. },
  148. shortcutEvents: [
  149. enterInCodeBlock,
  150. ignoreKeysInCodeBlock,
  151. insertHorizontalRule,
  152. ],
  153. selectionMenuItems: [
  154. codeBlockMenuItem,
  155. teXBlockMenuItem,
  156. horizontalRuleMenuItem,
  157. ],
  158. ),
  159. );
  160. } else {
  161. return const Center(
  162. child: CircularProgressIndicator(),
  163. );
  164. }
  165. },
  166. );
  167. }
  168. Widget _buildExpandableFab() {
  169. return ExpandableFab(
  170. distance: 112.0,
  171. children: [
  172. ActionButton(
  173. icon: const Icon(Icons.abc),
  174. onPressed: () => _switchToPage(0),
  175. ),
  176. ActionButton(
  177. icon: const Icon(Icons.abc),
  178. onPressed: () => _switchToPage(1),
  179. ),
  180. ActionButton(
  181. icon: const Icon(Icons.abc),
  182. onPressed: () => _switchToPage(2),
  183. ),
  184. ActionButton(
  185. icon: const Icon(Icons.print),
  186. onPressed: () => _exportDocument(_editorState!),
  187. ),
  188. ActionButton(
  189. icon: const Icon(Icons.import_export),
  190. onPressed: () async => await _importDocument(),
  191. ),
  192. ActionButton(
  193. icon: const Icon(Icons.color_lens),
  194. onPressed: () {
  195. setState(() {
  196. darkMode = !darkMode;
  197. });
  198. },
  199. ),
  200. ],
  201. );
  202. }
  203. void _exportDocument(EditorState editorState) async {
  204. final document = editorState.document.toJson();
  205. final json = jsonEncode(document);
  206. if (kIsWeb) {
  207. final blob = html.Blob([json], 'text/plain', 'native');
  208. html.AnchorElement(
  209. href: html.Url.createObjectUrlFromBlob(blob).toString(),
  210. )
  211. ..setAttribute('download', 'editor.json')
  212. ..click();
  213. } else {
  214. final directory = await getTemporaryDirectory();
  215. final path = directory.path;
  216. final file = File('$path/editor.json');
  217. await file.writeAsString(json);
  218. if (mounted) {
  219. ScaffoldMessenger.of(context).showSnackBar(
  220. SnackBar(
  221. content: Text('The document is saved to the ${file.path}'),
  222. ),
  223. );
  224. }
  225. }
  226. }
  227. Future<void> _importDocument() async {
  228. if (kIsWeb) {
  229. final result = await FilePicker.platform.pickFiles(
  230. allowMultiple: false,
  231. allowedExtensions: ['json'],
  232. type: FileType.custom,
  233. );
  234. final bytes = result?.files.first.bytes;
  235. if (bytes != null) {
  236. final jsonString = const Utf8Decoder().convert(bytes);
  237. setState(() {
  238. _editorState = null;
  239. _jsonString = Future.value(jsonString);
  240. });
  241. }
  242. } else {
  243. final directory = await getTemporaryDirectory();
  244. final path = '${directory.path}/editor.json';
  245. final file = File(path);
  246. setState(() {
  247. _editorState = null;
  248. _jsonString = file.readAsString();
  249. });
  250. }
  251. }
  252. void _switchToPage(int pageIndex) {
  253. if (pageIndex != _pageIndex) {
  254. setState(() {
  255. _editorState = null;
  256. _pageIndex = pageIndex;
  257. });
  258. }
  259. }
  260. }