main.dart 8.0 KB

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