main.dart 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import 'dart:convert';
  2. import 'dart:io';
  3. import 'package:example/plugin/code_block_node_widget.dart';
  4. import 'package:example/plugin/tex_block_node_widget.dart';
  5. import 'package:flutter/foundation.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:flutter/services.dart';
  8. import 'package:example/plugin/underscore_to_italic.dart';
  9. import 'package:file_picker/file_picker.dart';
  10. import 'package:flutter_localizations/flutter_localizations.dart';
  11. import 'package:google_fonts/google_fonts.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 MaterialApp(
  24. localizationsDelegates: const [
  25. GlobalMaterialLocalizations.delegate,
  26. GlobalCupertinoLocalizations.delegate,
  27. GlobalWidgetsLocalizations.delegate,
  28. AppFlowyEditorLocalizations.delegate,
  29. ],
  30. supportedLocales: const [Locale('en', 'US')],
  31. debugShowCheckedModeBanner: false,
  32. theme: ThemeData(
  33. primarySwatch: Colors.blue,
  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. EditorStyle _editorStyle = EditorStyle.defaultStyle();
  50. Future<String>? _jsonString;
  51. @override
  52. Widget build(BuildContext context) {
  53. return Scaffold(
  54. extendBodyBehindAppBar: true,
  55. body: _buildEditor(context),
  56. floatingActionButton: _buildExpandableFab(),
  57. );
  58. }
  59. Widget _buildEditor(BuildContext context) {
  60. if (_jsonString != null) {
  61. return _buildEditorWithJsonString(_jsonString!);
  62. }
  63. if (_pageIndex == 0) {
  64. return _buildEditorWithJsonString(
  65. rootBundle.loadString('assets/example.json'),
  66. );
  67. } else if (_pageIndex == 1) {
  68. return _buildEditorWithJsonString(
  69. rootBundle.loadString('assets/big_document.json'),
  70. );
  71. } else if (_pageIndex == 2) {
  72. return _buildEditorWithJsonString(
  73. Future.value(
  74. jsonEncode(EditorState.empty().document.toJson()),
  75. ),
  76. );
  77. }
  78. throw UnimplementedError();
  79. }
  80. Widget _buildEditorWithJsonString(Future<String> jsonString) {
  81. return FutureBuilder<String>(
  82. future: jsonString,
  83. builder: (_, snapshot) {
  84. if (snapshot.hasData &&
  85. snapshot.connectionState == ConnectionState.done) {
  86. _editorState ??= EditorState(
  87. document: StateTree.fromJson(
  88. Map<String, Object>.from(
  89. json.decode(snapshot.data!),
  90. ),
  91. ),
  92. );
  93. _editorState!.logConfiguration
  94. ..level = LogLevel.all
  95. ..handler = (message) {
  96. debugPrint(message);
  97. };
  98. _editorState!.operationStream.listen((event) {
  99. debugPrint('Operation: ${event.toJson()}');
  100. });
  101. return Container(
  102. color: darkMode ? Colors.black : Colors.white,
  103. width: MediaQuery.of(context).size.width,
  104. child: AppFlowyEditor(
  105. editorState: _editorState!,
  106. editorStyle: _editorStyle,
  107. editable: true,
  108. customBuilders: {
  109. 'text/code_block': CodeBlockNodeWidgetBuilder(),
  110. 'tex': TeXBlockNodeWidgetBuidler(),
  111. },
  112. shortcutEvents: [
  113. enterInCodeBlock,
  114. ignoreKeysInCodeBlock,
  115. underscoreToItalic,
  116. ],
  117. selectionMenuItems: [
  118. codeBlockMenuItem,
  119. teXBlockMenuItem,
  120. ],
  121. ),
  122. );
  123. } else {
  124. return const Center(
  125. child: CircularProgressIndicator(),
  126. );
  127. }
  128. },
  129. );
  130. }
  131. Widget _buildExpandableFab() {
  132. return ExpandableFab(
  133. distance: 112.0,
  134. children: [
  135. ActionButton(
  136. icon: const Icon(Icons.abc),
  137. onPressed: () => _switchToPage(0),
  138. ),
  139. ActionButton(
  140. icon: const Icon(Icons.abc),
  141. onPressed: () => _switchToPage(1),
  142. ),
  143. ActionButton(
  144. icon: const Icon(Icons.abc),
  145. onPressed: () => _switchToPage(2),
  146. ),
  147. ActionButton(
  148. icon: const Icon(Icons.print),
  149. onPressed: () => _exportDocument(_editorState!),
  150. ),
  151. ActionButton(
  152. icon: const Icon(Icons.import_export),
  153. onPressed: () async => await _importDocument(),
  154. ),
  155. ActionButton(
  156. icon: const Icon(Icons.color_lens),
  157. onPressed: () {
  158. setState(() {
  159. _editorStyle =
  160. darkMode ? EditorStyle.defaultStyle() : _customizedStyle();
  161. darkMode = !darkMode;
  162. });
  163. },
  164. ),
  165. ],
  166. );
  167. }
  168. void _exportDocument(EditorState editorState) async {
  169. final document = editorState.document.toJson();
  170. final json = jsonEncode(document);
  171. if (kIsWeb) {
  172. final blob = html.Blob([json], 'text/plain', 'native');
  173. html.AnchorElement(
  174. href: html.Url.createObjectUrlFromBlob(blob).toString(),
  175. )
  176. ..setAttribute('download', 'editor.json')
  177. ..click();
  178. } else {
  179. final directory = await getTemporaryDirectory();
  180. final path = directory.path;
  181. final file = File('$path/editor.json');
  182. await file.writeAsString(json);
  183. if (mounted) {
  184. ScaffoldMessenger.of(context).showSnackBar(
  185. SnackBar(
  186. content: Text('The document is saved to the ${file.path}'),
  187. ),
  188. );
  189. }
  190. }
  191. }
  192. Future<void> _importDocument() async {
  193. if (kIsWeb) {
  194. final result = await FilePicker.platform.pickFiles(
  195. allowMultiple: false,
  196. allowedExtensions: ['json'],
  197. type: FileType.custom,
  198. );
  199. final bytes = result?.files.first.bytes;
  200. if (bytes != null) {
  201. final jsonString = const Utf8Decoder().convert(bytes);
  202. setState(() {
  203. _editorState = null;
  204. _jsonString = Future.value(jsonString);
  205. });
  206. }
  207. } else {
  208. final directory = await getTemporaryDirectory();
  209. final path = '${directory.path}/editor.json';
  210. final file = File(path);
  211. setState(() {
  212. _editorState = null;
  213. _jsonString = file.readAsString();
  214. });
  215. }
  216. }
  217. void _switchToPage(int pageIndex) {
  218. if (pageIndex != _pageIndex) {
  219. setState(() {
  220. _editorState = null;
  221. _pageIndex = pageIndex;
  222. });
  223. }
  224. }
  225. EditorStyle _customizedStyle() {
  226. final editorStyle = EditorStyle.defaultStyle();
  227. return editorStyle.copyWith(
  228. cursorColor: Colors.white,
  229. selectionColor: Colors.blue.withOpacity(0.3),
  230. textStyle: editorStyle.textStyle.copyWith(
  231. defaultTextStyle: GoogleFonts.poppins().copyWith(
  232. color: Colors.white,
  233. fontSize: 14.0,
  234. ),
  235. defaultPlaceholderTextStyle: GoogleFonts.poppins().copyWith(
  236. color: Colors.white.withOpacity(0.5),
  237. fontSize: 14.0,
  238. ),
  239. bold: const TextStyle(fontWeight: FontWeight.w900),
  240. code: TextStyle(
  241. fontStyle: FontStyle.italic,
  242. color: Colors.red[300],
  243. backgroundColor: Colors.grey.withOpacity(0.3),
  244. ),
  245. highlightColorHex: '0x6FFFEB3B',
  246. ),
  247. pluginStyles: {
  248. 'text/quote': builtInPluginStyle
  249. ..update(
  250. 'textStyle',
  251. (_) {
  252. return (EditorState editorState, Node node) {
  253. return TextStyle(
  254. color: Colors.blue[200],
  255. fontStyle: FontStyle.italic,
  256. fontSize: 12.0,
  257. );
  258. };
  259. },
  260. ),
  261. },
  262. );
  263. }
  264. }