main.dart 7.6 KB

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