main.dart 8.9 KB

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