main.dart 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. // extensions: [HeadingPluginStyle.light],
  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. final themeData = darkMode
  117. ? ThemeData.dark().copyWith(extensions: [
  118. HeadingPluginStyle.dark,
  119. CheckboxPluginStyle.dark,
  120. NumberListPluginStyle.dark,
  121. QuotedTextPluginStyle.dark,
  122. BulletedListPluginStyle.dark
  123. ])
  124. : ThemeData.light().copyWith(
  125. extensions: [
  126. HeadingPluginStyle.light,
  127. CheckboxPluginStyle.light,
  128. NumberListPluginStyle.light,
  129. QuotedTextPluginStyle.light,
  130. BulletedListPluginStyle.light
  131. ],
  132. );
  133. return Theme(
  134. data: themeData,
  135. child: Container(
  136. color: darkMode ? Colors.black : Colors.white,
  137. width: MediaQuery.of(context).size.width,
  138. child: AppFlowyEditor(
  139. editorState: _editorState!,
  140. editorStyle: _editorStyle,
  141. editable: true,
  142. customBuilders: {
  143. 'text/code_block': CodeBlockNodeWidgetBuilder(),
  144. 'tex': TeXBlockNodeWidgetBuidler(),
  145. 'horizontal_rule': HorizontalRuleWidgetBuilder(),
  146. },
  147. shortcutEvents: [
  148. enterInCodeBlock,
  149. ignoreKeysInCodeBlock,
  150. insertHorizontalRule,
  151. ],
  152. selectionMenuItems: [
  153. codeBlockMenuItem,
  154. teXBlockMenuItem,
  155. horizontalRuleMenuItem,
  156. ],
  157. ),
  158. ),
  159. );
  160. } else {
  161. return const Center(
  162. child: CircularProgressIndicator(),
  163. );
  164. }
  165. },
  166. );
  167. }
  168. Widget _buildExpandableFab() {
  169. return ExpandableFab(
  170. distance: 112.0,
  171. children: [
  172. ActionButton(
  173. icon: const Icon(Icons.abc),
  174. onPressed: () => _switchToPage(0),
  175. ),
  176. ActionButton(
  177. icon: const Icon(Icons.abc),
  178. onPressed: () => _switchToPage(1),
  179. ),
  180. ActionButton(
  181. icon: const Icon(Icons.abc),
  182. onPressed: () => _switchToPage(2),
  183. ),
  184. ActionButton(
  185. icon: const Icon(Icons.print),
  186. onPressed: () => _exportDocument(_editorState!),
  187. ),
  188. ActionButton(
  189. icon: const Icon(Icons.import_export),
  190. onPressed: () async => await _importDocument(),
  191. ),
  192. ActionButton(
  193. icon: const Icon(Icons.color_lens),
  194. onPressed: () {
  195. setState(() {
  196. _editorStyle =
  197. darkMode ? EditorStyle.defaultStyle() : _customizedStyle();
  198. darkMode = !darkMode;
  199. });
  200. },
  201. ),
  202. ],
  203. );
  204. }
  205. void _exportDocument(EditorState editorState) async {
  206. final document = editorState.document.toJson();
  207. final json = jsonEncode(document);
  208. if (kIsWeb) {
  209. final blob = html.Blob([json], 'text/plain', 'native');
  210. html.AnchorElement(
  211. href: html.Url.createObjectUrlFromBlob(blob).toString(),
  212. )
  213. ..setAttribute('download', 'editor.json')
  214. ..click();
  215. } else {
  216. final directory = await getTemporaryDirectory();
  217. final path = directory.path;
  218. final file = File('$path/editor.json');
  219. await file.writeAsString(json);
  220. if (mounted) {
  221. ScaffoldMessenger.of(context).showSnackBar(
  222. SnackBar(
  223. content: Text('The document is saved to the ${file.path}'),
  224. ),
  225. );
  226. }
  227. }
  228. }
  229. Future<void> _importDocument() async {
  230. if (kIsWeb) {
  231. final result = await FilePicker.platform.pickFiles(
  232. allowMultiple: false,
  233. allowedExtensions: ['json'],
  234. type: FileType.custom,
  235. );
  236. final bytes = result?.files.first.bytes;
  237. if (bytes != null) {
  238. final jsonString = const Utf8Decoder().convert(bytes);
  239. setState(() {
  240. _editorState = null;
  241. _jsonString = Future.value(jsonString);
  242. });
  243. }
  244. } else {
  245. final directory = await getTemporaryDirectory();
  246. final path = '${directory.path}/editor.json';
  247. final file = File(path);
  248. setState(() {
  249. _editorState = null;
  250. _jsonString = file.readAsString();
  251. });
  252. }
  253. }
  254. void _switchToPage(int pageIndex) {
  255. if (pageIndex != _pageIndex) {
  256. setState(() {
  257. _editorState = null;
  258. _pageIndex = pageIndex;
  259. });
  260. }
  261. }
  262. EditorStyle _customizedStyle() {
  263. final editorStyle = EditorStyle.defaultStyle();
  264. return editorStyle.copyWith(
  265. cursorColor: Colors.white,
  266. selectionColor: Colors.blue.withOpacity(0.3),
  267. textStyle: editorStyle.textStyle.copyWith(
  268. defaultTextStyle: GoogleFonts.poppins().copyWith(
  269. color: Colors.white,
  270. fontSize: 14.0,
  271. ),
  272. defaultPlaceholderTextStyle: GoogleFonts.poppins().copyWith(
  273. color: Colors.white.withOpacity(0.5),
  274. fontSize: 14.0,
  275. ),
  276. bold: const TextStyle(fontWeight: FontWeight.w900),
  277. code: TextStyle(
  278. fontStyle: FontStyle.italic,
  279. color: Colors.red[300],
  280. backgroundColor: Colors.grey.withOpacity(0.3),
  281. ),
  282. highlightColorHex: '0x6FFFEB3B',
  283. ),
  284. pluginStyles: {
  285. 'text/quote': builtInPluginStyle
  286. ..update(
  287. 'textStyle',
  288. (_) {
  289. return (EditorState editorState, Node node) {
  290. return TextStyle(
  291. color: Colors.blue[200],
  292. fontStyle: FontStyle.italic,
  293. fontSize: 12.0,
  294. );
  295. };
  296. },
  297. ),
  298. },
  299. );
  300. }
  301. }