main.dart 8.3 KB

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