main.dart 8.8 KB

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