main.dart 8.2 KB

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