main.dart 8.3 KB

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