From 666bd5f58ad77aff8174cbc3d71a7fff84cb5c03 Mon Sep 17 00:00:00 2001 From: jideguru Date: Mon, 31 May 2021 22:19:49 +0100 Subject: [PATCH 01/13] feat: added editor settings --- LICENSE | 208 +++++++++++++++++- example/lib/main.dart | 56 +++-- .../macos/Runner.xcodeproj/project.pbxproj | 62 +++++- .../contents.xcworkspacedata | 3 + lib/rich_editor.dart | 2 +- lib/src/extensions/extensions.dart | 10 +- lib/src/rendering/rich_editor.dart | 45 +++- lib/src/utils/font_list_parser.dart | 6 +- lib/src/utils/javascript_executor_base.dart | 200 ++++++++++------- 9 files changed, 461 insertions(+), 131 deletions(-) diff --git a/LICENSE b/LICENSE index 17ad059..031ce04 100644 --- a/LICENSE +++ b/LICENSE @@ -1,13 +1,201 @@ -Copyright 2021 JideGuru + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - http://www.apache.org/licenses/LICENSE-2.0 + 1. Definitions. -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. \ No newline at end of file + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021 JideGuru + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/example/lib/main.dart b/example/lib/main.dart index 6985a23..147d388 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -65,20 +65,28 @@ class _MyHomePageState extends State { ]; }, onSelected: (val) async { - switch(val) { - case 0: { - String? html = await keyEditor.currentState?.getHtml(); - print(html); - } break; - case 1: { - await keyEditor.currentState?.clear(); - } break; - case 2: { - await keyEditor.currentState?.unFocus(); - } break; - case 3: { - await keyEditor.currentState?.focus(); - } break; + switch (val) { + case 0: + { + String? html = await keyEditor.currentState?.getHtml(); + print(html); + } + break; + case 1: + { + await keyEditor.currentState?.clear(); + } + break; + case 2: + { + await keyEditor.currentState?.unFocus(); + } + break; + case 3: + { + await keyEditor.currentState?.focus(); + } + break; } }, ), @@ -86,14 +94,18 @@ class _MyHomePageState extends State { ), body: RichEditor( key: keyEditor, - value: ''' -

Heading 1

-

Heading 2

-

Heading 3

-

Heading 4

-
Heading 5
-
Heading 6
- ''', +// value: ''' +//

Heading 1

+//

Heading 2

+//

Heading 3

+//

Heading 4

+//
Heading 5
+//
Heading 6
+// ''', + placeholder: 'Start typing', + // backgroundColor: Colors.blueGrey, + // baseTextColor: Colors.white, + padding: EdgeInsets.symmetric(horizontal: 50.0), // You can return a Link (maybe you need to upload the image to your // storage before displaying in the editor or you can also use base64 getImageUrl: (image) { diff --git a/example/macos/Runner.xcodeproj/project.pbxproj b/example/macos/Runner.xcodeproj/project.pbxproj index cc89c87..e52dad5 100644 --- a/example/macos/Runner.xcodeproj/project.pbxproj +++ b/example/macos/Runner.xcodeproj/project.pbxproj @@ -26,6 +26,7 @@ 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + C9461C47681F0FF10BFACAC7 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A1D0103636D5BC6143471898 /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -54,7 +55,7 @@ /* Begin PBXFileReference section */ 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; - 33CC10ED2044A3C60003C045 /* example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "example.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10ED2044A3C60003C045 /* example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = example.app; sourceTree = BUILT_PRODUCTS_DIR; }; 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; @@ -66,8 +67,12 @@ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 67E13F4865ADF40CF5FAA8FC /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; + A1D0103636D5BC6143471898 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A7593B64764F2BD906AA475F /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + C4DAD072CA42D22C645EC022 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -75,6 +80,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + C9461C47681F0FF10BFACAC7 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -99,6 +105,7 @@ 33CEB47122A05771004F2AC0 /* Flutter */, 33CC10EE2044A3C60003C045 /* Products */, D73912EC22F37F3D000D13A0 /* Frameworks */, + 42B7EB610A1F9C85B7C623A2 /* Pods */, ); sourceTree = ""; }; @@ -145,9 +152,21 @@ path = Runner; sourceTree = ""; }; + 42B7EB610A1F9C85B7C623A2 /* Pods */ = { + isa = PBXGroup; + children = ( + A7593B64764F2BD906AA475F /* Pods-Runner.debug.xcconfig */, + 67E13F4865ADF40CF5FAA8FC /* Pods-Runner.release.xcconfig */, + C4DAD072CA42D22C645EC022 /* Pods-Runner.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; D73912EC22F37F3D000D13A0 /* Frameworks */ = { isa = PBXGroup; children = ( + A1D0103636D5BC6143471898 /* Pods_Runner.framework */, ); name = Frameworks; sourceTree = ""; @@ -159,11 +178,13 @@ isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( + B7620E0CE768F128AE1679D1 /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, 33CC110E2044A8840003C045 /* Bundle Framework */, 3399D490228B24CF009A79C7 /* ShellScript */, + 06400C234E158CC19ED60959 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -233,6 +254,23 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ + 06400C234E158CC19ED60959 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; 3399D490228B24CF009A79C7 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -270,6 +308,28 @@ shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; + B7620E0CE768F128AE1679D1 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ diff --git a/example/macos/Runner.xcworkspace/contents.xcworkspacedata b/example/macos/Runner.xcworkspace/contents.xcworkspacedata index 1d526a1..21a3cc1 100644 --- a/example/macos/Runner.xcworkspace/contents.xcworkspacedata +++ b/example/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -4,4 +4,7 @@ + + diff --git a/lib/rich_editor.dart b/lib/rich_editor.dart index b5ca9cb..48e80cd 100644 --- a/lib/rich_editor.dart +++ b/lib/rich_editor.dart @@ -2,4 +2,4 @@ library rich_editor; export 'src/rendering/rich_editor.dart'; export 'src/widgets/editor_tool_bar.dart'; -export 'src/widgets/tab_button.dart'; \ No newline at end of file +export 'src/widgets/tab_button.dart'; diff --git a/lib/src/extensions/extensions.dart b/lib/src/extensions/extensions.dart index 4849404..9d6ceda 100644 --- a/lib/src/extensions/extensions.dart +++ b/lib/src/extensions/extensions.dart @@ -1,5 +1,11 @@ import 'package:flutter/material.dart'; +/// An extension that makes it easy to get Hex code +/// from [Color] and [MaterialColor] extension ColorX on Color { - String toHexColorString() => '#${value.toRadixString(16).replaceAll('ff', '')}'; -} \ No newline at end of file + String toHexColorString() { + String hex = value.toRadixString(16).replaceAll('ff', ''); + if(hex.isEmpty) hex = '000000'; + return '#$hex'; + } +} diff --git a/lib/src/rendering/rich_editor.dart b/lib/src/rendering/rich_editor.dart index 2c61fef..bded914 100644 --- a/lib/src/rendering/rich_editor.dart +++ b/lib/src/rendering/rich_editor.dart @@ -11,10 +11,22 @@ import 'package:webview_flutter/webview_flutter.dart'; class RichEditor extends StatefulWidget { final String? value; + final Color? backgroundColor; + final Color? baseTextColor; + final EdgeInsets? padding; + final String? placeholder; final Function(File image)? getImageUrl; final Function(File video)? getVideoUrl; - RichEditor({Key? key, this.value, this.getImageUrl, this.getVideoUrl}) + RichEditor( + {Key? key, + this.value, + this.backgroundColor, + this.baseTextColor, + this.padding, + this.placeholder, + this.getImageUrl, + this.getVideoUrl}) : super(key: key); @override @@ -86,22 +98,17 @@ class RichEditorState extends State { key: _mapKey, onWebViewCreated: (WebViewController controller) async { _controller = controller; - print('WebView created'); setState(() {}); if (!Platform.isAndroid) { - print('Loading'); await _loadHtmlFromAssets(); } else { await _controller! .loadUrl('file:///android_asset/flutter_assets/$assetPath'); } javascriptExecutorBase.init(_controller!); - if (widget.value != null) { - // wait 1 second before setting the html - Timer(Duration(seconds: 1), () async { - await javascriptExecutorBase.setHtml(widget.value!); - }); - } + }, + onPageFinished: (link) async { + await _setInitialValues(); }, javascriptMode: JavascriptMode.unrestricted, gestureNavigationEnabled: true, @@ -117,6 +124,19 @@ class RichEditorState extends State { ); } + _setInitialValues() async { + if (widget.value != null) + await javascriptExecutorBase.setHtml(widget.value!); + if (widget.padding != null) + await javascriptExecutorBase.setPadding(widget.padding!); + if (widget.backgroundColor != null) + await javascriptExecutorBase.setBackgroundColor(widget.backgroundColor!); + if (widget.baseTextColor != null) + await javascriptExecutorBase.setBaseTextColor(widget.baseTextColor!); + if (widget.placeholder != null) + await javascriptExecutorBase.setPlaceholder(widget.placeholder!); + } + Future getHtml() async { try { html = await javascriptExecutorBase.getCurrentHtml(); @@ -131,17 +151,18 @@ class RichEditorState extends State { // Hide the keyboard using JavaScript since it's being opened in a WebView // https://stackoverflow.com/a/8263376/10835183 unFocus() { - _controller!.evaluateJavascript('document.activeElement.blur();'); + javascriptExecutorBase.unFocus(); } // Clear editor content using Javascript clear() { - _controller!.evaluateJavascript('document.getElementById(\'editor\').innerHTML = "";'); + _controller!.evaluateJavascript( + 'document.getElementById(\'editor\').innerHTML = "";'); } // Focus and Show the keyboard using JavaScript // https://stackoverflow.com/a/6809236/10835183 focus() { - _controller!.evaluateJavascript('document.getElementById(\'editor\').focus();'); + javascriptExecutorBase.focus(); } } diff --git a/lib/src/utils/font_list_parser.dart b/lib/src/utils/font_list_parser.dart index df61e74..8f84afd 100644 --- a/lib/src/utils/font_list_parser.dart +++ b/lib/src/utils/font_list_parser.dart @@ -8,12 +8,13 @@ import 'package:rich_editor/src/models/font.dart'; import 'package:rich_editor/src/models/system_font.dart'; import 'package:xml2json/xml2json.dart'; -// A simple port of FontListParser from Java to Kotlin -// See https://stackoverflow.com/a/29533686/10835183 +/// A simple port of FontListParser from Java to Kotlin +/// See https://stackoverflow.com/a/29533686/10835183 class FontListParser { File androidFontsFile = File("/system/etc/fonts.xml"); File androidSystemFontsFile = File("/system/etc/system_fonts.xml"); + /// Gets fonts from the fonts xml files in the android system List getSystemFonts() { String fontsXml; if (androidFontsFile.existsSync()) { @@ -75,6 +76,7 @@ class FontListParser { return fonts; } + /// Gets font from the list defined incase the above function doesn't work List safelyGetSystemFonts() { try { return getSystemFonts(); diff --git a/lib/src/utils/javascript_executor_base.dart b/lib/src/utils/javascript_executor_base.dart index b67044d..a564049 100644 --- a/lib/src/utils/javascript_executor_base.dart +++ b/lib/src/utils/javascript_executor_base.dart @@ -8,6 +8,7 @@ import 'package:webview_flutter/webview_flutter.dart'; import '../models/command_state.dart'; +/// A class that handles all editor-related javascript functions class JavascriptExecutorBase { WebViewController? _controller; @@ -193,6 +194,41 @@ class JavascriptExecutorBase { await executeJavascript("disableImageResizing()"); } + // Editor settings commands + focus() async { + await executeJavascript("focus()"); + } + + unFocus() async { + await executeJavascript("blurFocus()"); + } + + setBackgroundColor(Color? color) async { + String? hex = color!.toHexColorString(); + await executeJavascript("setBackgroundColor('$hex')"); + } + + setBackgroundImage(String image) async { + await executeJavascript("setBackgroundImage('$image')"); + } + + setBaseTextColor(Color? color) async { + String? hex = color!.toHexColorString(); + await executeJavascript("setBaseTextColor('$hex')"); + } + + setPadding(EdgeInsets? padding) async { + String left = padding!.left.toString(); + String top = padding.top.toString(); + String right = padding.right.toString(); + String bottom = padding.bottom.toString(); + await executeJavascript("setPadding('$left', '$top', '$right', '$bottom')"); + } + + setPlaceholder(String placeholder) async { + await executeJavascript("setPlaceholder('$placeholder')"); + } + static decodeHtml(String html) { return Uri.decodeFull(html); } @@ -201,87 +237,89 @@ class JavascriptExecutorBase { return Uri.encodeFull(html); } - // bool shouldOverrideUrlLoading(String url) { - // String decodedUrl; - // try { - // decodedUrl = decodeHtml(url); - // } catch (e) { - // // No handling - // return false; - // } - // - // if (url.indexOf(editorStateChangedCallbackScheme) == 0) { - // editorStateChanged( - // decodedUrl.substring(editorStateChangedCallbackScheme.length)); - // return true; - // } - // - // return false; - // } - // - // editorStateChanged(String statesString) { - // try { - // var editorState = EditorState.fromJson(jsonDecode(statesString)); - // - // bool currentHtmlChanged = this.htmlField != editorState.html; - // this.htmlField = editorState.html; - // - // retrievedEditorState(editorState.didHtmlChange, editorState.commandStates) - // - // if (currentHtmlChanged) { - // fireHtmlChangedListenersAsync(editorState.html); - // } - // } - // catch (e) { - // throw("Could not parse command states: $statesString $e"); - // } - // } - // - // retrievedEditorState(bool didHtmlChange, - // Map commandStates) { - // if (this.didHtmlChange != didHtmlChange) { - // this.didHtmlChange = didHtmlChange; - // didHtmlChangeListeners.forEach { - // it.didHtmlChange(didHtmlChange); - // } - // } - // - // handleRetrievedCommandStates(commandStates) - // } - // - // handleRetrievedCommandStates(Map commandStates) { - // determineDerivedCommandStates(commandStates) - // - // this.commandStates = commandStates; - // - // commandStatesChangedListeners.forEach { - // it.invoke(this.commandStates) - // } - // } + bool shouldOverrideUrlLoading(String url) { + String decodedUrl; + try { + decodedUrl = decodeHtml(url); + } catch (e) { + // No handling + return false; + } - // determineDerivedCommandStates(Map commandStates) { - // commandStates[CommandName.FORMATBLOCK]?.let { formatCommandState -> - // commandStates.put(CommandName.H1, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h1"))) - // commandStates.put(CommandName.H2, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h2"))) - // commandStates.put(CommandName.H3, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h3"))) - // commandStates.put(CommandName.H4, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h4"))) - // commandStates.put(CommandName.H5, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h5"))) - // commandStates.put(CommandName.H6, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h6"))) - // commandStates.put(CommandName.P, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "p"))) - // commandStates.put(CommandName.PRE, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "pre"))) - // commandStates.put(CommandName.BR, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, ""))) - // commandStates.put(CommandName.BLOCKQUOTE, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "blockquote"))) - // } - // - // commandStates[CommandName.INSERTHTML]?.let { insertHtmlState -> - // commandStates.put(CommandName.INSERTLINK, insertHtmlState) - // commandStates.put(CommandName.INSERTIMAGE, insertHtmlState) - // commandStates.put(CommandName.INSERTCHECKBOX, insertHtmlState) - // } - // } + if (url.indexOf(editorStateChangedCallbackScheme) == 0) { + editorStateChanged( + decodedUrl.substring(editorStateChangedCallbackScheme.length)); + return true; + } - // String isFormatActivated(CommandState formatCommandState, String format) { - // return (formatCommandState.value == format) - // .toString(); // rich_text_editor.js reports boolean values as string, so we also have to convert it to string - // } + return false; + } + + editorStateChanged(String statesString) { + try { + var editorState = EditorState.fromJson(jsonDecode(statesString)); + + bool currentHtmlChanged = this.htmlField != editorState.html; + this.htmlField = editorState.html; + + retrievedEditorState( + editorState.didHtmlChange!, editorState.commandStates!); + + if (currentHtmlChanged) { + // fireHtmlChangedListenersAsync(editorState.html); + } + } catch (e) { + throw ("Could not parse command states: $statesString $e"); + } + } + + retrievedEditorState( + bool didHtmlChange, Map commandStates) { + if (this.didHtmlChange != didHtmlChange) { + this.didHtmlChange = didHtmlChange; + // didHtmlChangeListeners.forEach { + // it.didHtmlChange(didHtmlChange); + // } + } + + handleRetrievedCommandStates(commandStates); + } + + handleRetrievedCommandStates(Map commandStates) { + determineDerivedCommandStates(commandStates); + + this.commandStates = commandStates; + + // commandStatesChangedListeners.forEach { + // it.invoke(this.commandStates) + // } + } + + determineDerivedCommandStates(Map commandStates) { + // commandStates[CommandName.FORMATBLOCK]?.let { + // formatCommandState + // -> + // commandStates.put(CommandName.H1, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h1"))) + // commandStates.put(CommandName.H2, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h2"))) + // commandStates.put(CommandName.H3, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h3"))) + // commandStates.put(CommandName.H4, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h4"))) + // commandStates.put(CommandName.H5, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h5"))) + // commandStates.put(CommandName.H6, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "h6"))) + // commandStates.put(CommandName.P, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "p"))) + // commandStates.put(CommandName.PRE, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "pre"))) + // commandStates.put(CommandName.BR, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, ""))) + // commandStates.put(CommandName.BLOCKQUOTE, CommandState(formatCommandState.executable, isFormatActivated(formatCommandState, "blockquote"))) + // } + // + // commandStates[CommandName.INSERTHTML]?.let { insertHtmlState -> + // commandStates.put(CommandName.INSERTLINK, insertHtmlState) + // commandStates.put(CommandName.INSERTIMAGE, insertHtmlState) + // commandStates.put(CommandName.INSERTCHECKBOX, insertHtmlState) + // } + } + + String isFormatActivated(CommandState formatCommandState, String format) { + return (formatCommandState.value == format) + .toString(); // rich_text_editor.js reports boolean values as string, so we also have to convert it to string + } } From 509808d2201c5e62ee3d88d3eec31fe6b75d98ee Mon Sep 17 00:00:00 2001 From: jideguru Date: Thu, 3 Jun 2021 00:13:12 +0100 Subject: [PATCH 02/13] feat: added more editor settings --- example/lib/main.dart | 3 +- example/pubspec.lock | 2 +- lib/src/rendering/rich_editor.dart | 93 +++++++++++++-------- lib/src/utils/font_list_parser.dart | 18 ++-- lib/src/utils/javascript_executor_base.dart | 38 ++++++--- lib/src/widgets/editor_tool_bar.dart | 87 ++++++++----------- lib/src/widgets/fonts_dialog.dart | 12 +-- 7 files changed, 134 insertions(+), 119 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index 147d388..4a31452 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -105,7 +105,8 @@ class _MyHomePageState extends State { placeholder: 'Start typing', // backgroundColor: Colors.blueGrey, // baseTextColor: Colors.white, - padding: EdgeInsets.symmetric(horizontal: 50.0), + padding: EdgeInsets.symmetric(horizontal: 5.0), + baseFontFamily: 'sans-serif', // You can return a Link (maybe you need to upload the image to your // storage before displaying in the editor or you can also use base64 getImageUrl: (image) { diff --git a/example/pubspec.lock b/example/pubspec.lock index da1c2d2..15051c1 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -281,7 +281,7 @@ packages: path: ".." relative: true source: path - version: "0.0.1" + version: "0.0.2" sky_engine: dependency: transitive description: flutter diff --git a/lib/src/rendering/rich_editor.dart b/lib/src/rendering/rich_editor.dart index bded914..54494d8 100644 --- a/lib/src/rendering/rich_editor.dart +++ b/lib/src/rendering/rich_editor.dart @@ -15,19 +15,21 @@ class RichEditor extends StatefulWidget { final Color? baseTextColor; final EdgeInsets? padding; final String? placeholder; + final String? baseFontFamily; final Function(File image)? getImageUrl; final Function(File video)? getVideoUrl; - RichEditor( - {Key? key, - this.value, - this.backgroundColor, - this.baseTextColor, - this.padding, - this.placeholder, - this.getImageUrl, - this.getVideoUrl}) - : super(key: key); + RichEditor({ + Key? key, + this.value, + this.backgroundColor, + this.baseTextColor, + this.padding, + this.placeholder, + this.baseFontFamily, + this.getImageUrl, + this.getVideoUrl, + }) : super(key: key); @override RichEditorState createState() => RichEditorState(); @@ -35,30 +37,29 @@ class RichEditor extends StatefulWidget { class RichEditorState extends State { WebViewController? _controller; - String text = ""; final Key _mapKey = UniqueKey(); String assetPath = 'packages/rich_editor/assets/editor/editor.html'; int port = 5321; String html = ''; LocalServer? localServer; - JavascriptExecutorBase javascriptExecutorBase = JavascriptExecutorBase(); + JavascriptExecutorBase javascriptExecutor = JavascriptExecutorBase(); @override void initState() { super.initState(); if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView(); if (!Platform.isAndroid) { - initServer(); + _initServer(); } } - initServer() async { + _initServer() async { localServer = LocalServer(port); - await localServer!.start(handleRequest); + await localServer!.start(_handleRequest); } - void handleRequest(HttpRequest request) { + void _handleRequest(HttpRequest request) { try { if (request.method == 'GET' && request.uri.queryParameters['query'] == "getRawTeXHTML") { @@ -91,7 +92,7 @@ class RichEditorState extends State { EditorToolBar( controller: _controller, getImageUrl: widget.getImageUrl, - javascriptExecutorBase: javascriptExecutorBase, + javascriptExecutor: javascriptExecutor, ), Expanded( child: WebView( @@ -105,7 +106,7 @@ class RichEditorState extends State { await _controller! .loadUrl('file:///android_asset/flutter_assets/$assetPath'); } - javascriptExecutorBase.init(_controller!); + javascriptExecutor.init(_controller!); }, onPageFinished: (link) async { await _setInitialValues(); @@ -125,44 +126,70 @@ class RichEditorState extends State { } _setInitialValues() async { - if (widget.value != null) - await javascriptExecutorBase.setHtml(widget.value!); + if (widget.value != null) await javascriptExecutor.setHtml(widget.value!); if (widget.padding != null) - await javascriptExecutorBase.setPadding(widget.padding!); + await javascriptExecutor.setPadding(widget.padding!); if (widget.backgroundColor != null) - await javascriptExecutorBase.setBackgroundColor(widget.backgroundColor!); + await javascriptExecutor.setBackgroundColor(widget.backgroundColor!); if (widget.baseTextColor != null) - await javascriptExecutorBase.setBaseTextColor(widget.baseTextColor!); + await javascriptExecutor.setBaseTextColor(widget.baseTextColor!); if (widget.placeholder != null) - await javascriptExecutorBase.setPlaceholder(widget.placeholder!); + await javascriptExecutor.setPlaceholder(widget.placeholder!); + if (widget.baseFontFamily != null) + await javascriptExecutor.setBaseFontFamily(widget.baseFontFamily!); } + /// Get current HTML from editor Future getHtml() async { try { - html = await javascriptExecutorBase.getCurrentHtml(); + html = await javascriptExecutor.getCurrentHtml(); } catch (e) {} return html; } + /// Set your HTML to the editor setHtml(String html) async { - return await javascriptExecutorBase.setHtml(html); + return await javascriptExecutor.setHtml(html); } - // Hide the keyboard using JavaScript since it's being opened in a WebView - // https://stackoverflow.com/a/8263376/10835183 + /// Hide the keyboard using JavaScript since it's being opened in a WebView + /// https://stackoverflow.com/a/8263376/10835183 unFocus() { - javascriptExecutorBase.unFocus(); + javascriptExecutor.unFocus(); } - // Clear editor content using Javascript + /// Clear editor content using Javascript clear() { _controller!.evaluateJavascript( 'document.getElementById(\'editor\').innerHTML = "";'); } - // Focus and Show the keyboard using JavaScript - // https://stackoverflow.com/a/6809236/10835183 + /// Focus and Show the keyboard using JavaScript + /// https://stackoverflow.com/a/6809236/10835183 focus() { - javascriptExecutorBase.focus(); + javascriptExecutor.focus(); + } + + /// Add custom CSS code to Editor + loadCSS(String cssFile) { + var jsCSSImport = "(function() {" + + " var head = document.getElementsByTagName(\"head\")[0];" + + " var link = document.createElement(\"link\");" + + " link.rel = \"stylesheet\";" + + " link.type = \"text/css\";" + + " link.href = \"" + + cssFile + + "\";" + + " link.media = \"all\";" + + " head.appendChild(link);" + + "}) ();"; + _controller!.evaluateJavascript(jsCSSImport); + } + + /// if html is equal to html RichTextEditor sets by default at start + /// (

) so that RichTextEditor can be considered as 'empty'. + Future isEmpty() async { + html = await javascriptExecutor.getCurrentHtml(); + return html == '

'; } } diff --git a/lib/src/utils/font_list_parser.dart b/lib/src/utils/font_list_parser.dart index 8f84afd..0b98637 100644 --- a/lib/src/utils/font_list_parser.dart +++ b/lib/src/utils/font_list_parser.dart @@ -8,7 +8,7 @@ import 'package:rich_editor/src/models/font.dart'; import 'package:rich_editor/src/models/system_font.dart'; import 'package:xml2json/xml2json.dart'; -/// A simple port of FontListParser from Java to Kotlin +/// A simple port of FontListParser from Java to Dart /// See https://stackoverflow.com/a/29533686/10835183 class FontListParser { File androidFontsFile = File("/system/etc/fonts.xml"); @@ -39,7 +39,7 @@ class FontListParser { break; } } - if( font.t != null) { + if (font.t != null) { SystemFont systemFont = new SystemFont(family.name!, font.t!); if (fonts.contains(systemFont)) { continue; @@ -76,7 +76,7 @@ class FontListParser { return fonts; } - /// Gets font from the list defined incase the above function doesn't work + /// Gets font from the list defined in case the above function doesn't work List safelyGetSystemFonts() { try { return getSystemFonts(); @@ -85,16 +85,16 @@ class FontListParser { ["cursive", "DancingScript-Regular.ttf"], ["monospace", "DroidSansMono.ttf"], ["sans-serif", "Roboto-Regular.ttf"], - ["sans-serif-light" "Roboto-Light.ttf"], - ["sans-serif-medium", "Roboto-Medium.ttf"], - ["sans-serif-black", "Roboto-Black.ttf"], - ["sans-serif-condensed", "RobotoCondensed-Regular.ttf"], - ["sans-serif-thin", "Roboto-Thin.ttf"], + ["sans-serif-light" "Roboto-Light.ttf"], + ["sans-serif-medium", "Roboto-Medium.ttf"], + ["sans-serif-black", "Roboto-Black.ttf"], + ["sans-serif-condensed", "RobotoCondensed-Regular.ttf"], + ["sans-serif-thin", "Roboto-Thin.ttf"], ["serif", "NotoSerif-Regular.ttf"] ]; List fonts = []; for (List names in defaultSystemFonts) { - File file = new File("/system/fonts/"+ names[1]); + File file = new File("/system/fonts/" + names[1]); if (file.existsSync()) { fonts.add(new SystemFont(names[0], file.path)); } diff --git a/lib/src/utils/javascript_executor_base.dart b/lib/src/utils/javascript_executor_base.dart index a564049..e5ac1ad 100644 --- a/lib/src/utils/javascript_executor_base.dart +++ b/lib/src/utils/javascript_executor_base.dart @@ -173,48 +173,52 @@ class JavascriptExecutorBase { if (height == null) height = 300; if (alt == null) alt = ''; await executeJavascript( - "insertImage('$url', '$alt', '$width', '$height', $rotation)", + "insertImage('$url', '$alt', '$width', '$height', $rotation);", ); } insertCheckbox(String text) async { - await executeJavascript("insertCheckbox('$text')"); + await executeJavascript("insertCheckbox('$text');"); } insertHtml(String html) async { String? encodedHtml = encodeHtml(html); - await executeJavascript("insertHtml('$encodedHtml')"); + await executeJavascript("insertHtml('$encodedHtml');"); } makeImagesResizeable() async { - await executeJavascript("makeImagesResizeable()"); + await executeJavascript("makeImagesResizeable();"); } disableImageResizing() async { - await executeJavascript("disableImageResizing()"); + await executeJavascript("disableImageResizing();"); } // Editor settings commands focus() async { - await executeJavascript("focus()"); + await executeJavascript("focus();"); } unFocus() async { - await executeJavascript("blurFocus()"); + await executeJavascript("blurFocus();"); } setBackgroundColor(Color? color) async { String? hex = color!.toHexColorString(); - await executeJavascript("setBackgroundColor('$hex')"); + await executeJavascript("setBackgroundColor('$hex');"); } setBackgroundImage(String image) async { - await executeJavascript("setBackgroundImage('$image')"); + await executeJavascript("setBackgroundImage('$image');"); } setBaseTextColor(Color? color) async { String? hex = color!.toHexColorString(); - await executeJavascript("setBaseTextColor('$hex')"); + await executeJavascript("setBaseTextColor('$hex');"); + } + + setBaseFontFamily(String fontFamily) async { + await executeJavascript("setBaseFontFamily('$fontFamily');"); } setPadding(EdgeInsets? padding) async { @@ -222,11 +226,21 @@ class JavascriptExecutorBase { String top = padding.top.toString(); String right = padding.right.toString(); String bottom = padding.bottom.toString(); - await executeJavascript("setPadding('$left', '$top', '$right', '$bottom')"); + await executeJavascript( + "setPadding('${left}px', '${top}px', '${right}px', '${bottom}px');"); } + // Doesnt actually work for' now setPlaceholder(String placeholder) async { - await executeJavascript("setPlaceholder('$placeholder')"); + await executeJavascript("setPlaceholder('$placeholder');"); + } + + setEditorWidth(int px) async { + await executeJavascript("setWidth('" + px.toString() + "px');"); + } + + setEditorHeight(int px) async { + await executeJavascript("setHeight('" + px.toString() + "px');"); } static decodeHtml(String html) { diff --git a/lib/src/widgets/editor_tool_bar.dart b/lib/src/widgets/editor_tool_bar.dart index 18302fb..4dd059b 100644 --- a/lib/src/widgets/editor_tool_bar.dart +++ b/lib/src/widgets/editor_tool_bar.dart @@ -17,23 +17,18 @@ class EditorToolBar extends StatelessWidget { final WebViewController? controller; final Function(File image)? getImageUrl; final Function(File video)? getVideoUrl; - final JavascriptExecutorBase javascriptExecutorBase; + final JavascriptExecutorBase javascriptExecutor; EditorToolBar({ this.controller, this.getImageUrl, this.getVideoUrl, - required this.javascriptExecutorBase, + required this.javascriptExecutor, }); @override Widget build(BuildContext context) { - // if (controller != null) { - // javascriptExecutorBase.init(controller!); - // } - return Container( - // color: Color(0xff424242), height: 54.0, child: Column( children: [ @@ -46,21 +41,20 @@ class EditorToolBar extends StatelessWidget { tooltip: 'Bold', icon: Icons.format_bold, onTap: () async { - await javascriptExecutorBase.setBold(); + await javascriptExecutor.setBold(); }, ), TabButton( tooltip: 'Italic', icon: Icons.format_italic, onTap: () async { - await javascriptExecutorBase.setItalic(); + await javascriptExecutor.setItalic(); }, ), TabButton( tooltip: 'Insert Link', icon: Icons.link, onTap: () async { - _closeKeyboard(); var link = await showDialog( context: context, barrierDismissible: false, @@ -69,14 +63,13 @@ class EditorToolBar extends StatelessWidget { }, ); if (link != null) - await javascriptExecutorBase.insertLink(link[0], link[1]); + await javascriptExecutor.insertLink(link[0], link[1]); }, ), TabButton( tooltip: 'Insert Image', icon: Icons.image, onTap: () async { - _closeKeyboard(); var link = await showDialog( context: context, barrierDismissible: false, @@ -88,7 +81,7 @@ class EditorToolBar extends StatelessWidget { if (getImageUrl != null && link[2]) { link[0] = await getImageUrl!(File(link[0])); } - await javascriptExecutorBase.insertImage( + await javascriptExecutor.insertImage( link[0], alt: link[1], ); @@ -99,63 +92,62 @@ class EditorToolBar extends StatelessWidget { tooltip: 'Underline', icon: Icons.format_underline, onTap: () async { - await javascriptExecutorBase.setUnderline(); + await javascriptExecutor.setUnderline(); }, ), TabButton( tooltip: 'Strike through', icon: Icons.format_strikethrough, onTap: () async { - await javascriptExecutorBase.setStrikeThrough(); + await javascriptExecutor.setStrikeThrough(); }, ), TabButton( tooltip: 'Superscript', icon: Icons.superscript, onTap: () async { - await javascriptExecutorBase.setSuperscript(); + await javascriptExecutor.setSuperscript(); }, ), TabButton( tooltip: 'Subscript', icon: Icons.subscript, onTap: () async { - await javascriptExecutorBase.setSubscript(); + await javascriptExecutor.setSubscript(); }, ), TabButton( tooltip: 'Clear format', icon: Icons.format_clear, onTap: () async { - await javascriptExecutorBase.removeFormat(); + await javascriptExecutor.removeFormat(); }, ), TabButton( tooltip: 'Undo', icon: Icons.undo, onTap: () async { - await javascriptExecutorBase.undo(); + await javascriptExecutor.undo(); }, ), TabButton( tooltip: 'Redo', icon: Icons.redo, onTap: () async { - await javascriptExecutorBase.redo(); + await javascriptExecutor.redo(); }, ), TabButton( tooltip: 'Blockquote', icon: Icons.format_quote, onTap: () async { - await javascriptExecutorBase.setBlockQuote(); + await javascriptExecutor.setBlockQuote(); }, ), TabButton( tooltip: 'Font format', icon: Icons.text_format, onTap: () async { - _closeKeyboard(); var command = await showDialog( // isScrollControlled: true, context: context, @@ -165,13 +157,13 @@ class EditorToolBar extends StatelessWidget { ); if (command != null) { if (command == 'p') { - await javascriptExecutorBase.setFormattingToParagraph(); + await javascriptExecutor.setFormattingToParagraph(); } else if (command == 'pre') { - await javascriptExecutorBase.setPreformat(); + await javascriptExecutor.setPreformat(); } else if (command == 'blockquote') { - await javascriptExecutorBase.setBlockQuote(); + await javascriptExecutor.setBlockQuote(); } else { - await javascriptExecutorBase + await javascriptExecutor .setHeading(int.tryParse(command)!); } } @@ -184,9 +176,6 @@ class EditorToolBar extends StatelessWidget { tooltip: 'Font face', icon: Icons.font_download, onTap: () async { - Directory fontsDir = Directory("/system/fonts/"); - File file = File('/system/etc/fonts.xml'); - // debugPrint(await file.readAsString()); var command = await showDialog( // isScrollControlled: true, context: context, @@ -194,8 +183,9 @@ class EditorToolBar extends StatelessWidget { return FontsDialog(); }, ); + print(command); if (command != null) - await javascriptExecutorBase.setFontName(command); + await javascriptExecutor.setFontName(command); }, ), ), @@ -203,7 +193,6 @@ class EditorToolBar extends StatelessWidget { icon: Icons.format_size, tooltip: 'Font Size', onTap: () async { - _closeKeyboard(); String? command = await showDialog( // isScrollControlled: true, context: context, @@ -212,7 +201,7 @@ class EditorToolBar extends StatelessWidget { }, ); if (command != null) - await javascriptExecutorBase + await javascriptExecutor .setFontSize(int.tryParse(command)!); }, ), @@ -220,7 +209,6 @@ class EditorToolBar extends StatelessWidget { tooltip: 'Text Color', icon: Icons.format_color_text, onTap: () async { - _closeKeyboard(); var color = await showDialog( context: context, builder: (BuildContext context) { @@ -228,14 +216,13 @@ class EditorToolBar extends StatelessWidget { }, ); if (color != null) - await javascriptExecutorBase.setTextColor(color); + await javascriptExecutor.setTextColor(color); }, ), TabButton( tooltip: 'Background Color', icon: Icons.format_color_fill, onTap: () async { - _closeKeyboard(); var color = await showDialog( context: context, builder: (BuildContext context) { @@ -243,71 +230,69 @@ class EditorToolBar extends StatelessWidget { }, ); if (color != null) - await javascriptExecutorBase - .setTextBackgroundColor(color); + await javascriptExecutor.setTextBackgroundColor(color); }, ), TabButton( tooltip: 'Increase Indent', icon: Icons.format_indent_increase, onTap: () async { - await javascriptExecutorBase.setIndent(); + await javascriptExecutor.setIndent(); }, ), TabButton( tooltip: 'Decrease Indent', icon: Icons.format_indent_decrease, onTap: () async { - await javascriptExecutorBase.setOutdent(); + await javascriptExecutor.setOutdent(); }, ), TabButton( tooltip: 'Align Left', icon: Icons.format_align_left_outlined, onTap: () async { - await javascriptExecutorBase.setJustifyLeft(); + await javascriptExecutor.setJustifyLeft(); }, ), TabButton( tooltip: 'Align Center', icon: Icons.format_align_center, onTap: () async { - await javascriptExecutorBase.setJustifyCenter(); + await javascriptExecutor.setJustifyCenter(); }, ), TabButton( tooltip: 'Align Right', icon: Icons.format_align_right, onTap: () async { - await javascriptExecutorBase.setJustifyRight(); + await javascriptExecutor.setJustifyRight(); }, ), TabButton( tooltip: 'Justify', icon: Icons.format_align_justify, onTap: () async { - await javascriptExecutorBase.setJustifyFull(); + await javascriptExecutor.setJustifyFull(); }, ), TabButton( tooltip: 'Bullet List', icon: Icons.format_list_bulleted, onTap: () async { - await javascriptExecutorBase.insertBulletList(); + await javascriptExecutor.insertBulletList(); }, ), TabButton( tooltip: 'Numbered List', icon: Icons.format_list_numbered, onTap: () async { - await javascriptExecutorBase.insertNumberedList(); + await javascriptExecutor.insertNumberedList(); }, ), TabButton( tooltip: 'Checkbox', icon: Icons.check_box_outlined, onTap: () async { - _closeKeyboard(); var text = await showDialog( context: context, builder: (BuildContext context) { @@ -316,7 +301,7 @@ class EditorToolBar extends StatelessWidget { ); print(text); if (text != null) - await javascriptExecutorBase.insertCheckbox(text); + await javascriptExecutor.insertCheckbox(text); }, ), @@ -325,7 +310,7 @@ class EditorToolBar extends StatelessWidget { // tooltip: 'Search', // icon: Icons.search, // onTap: () async { - // // await javascriptExecutorBase.insertNumberedList(); + // // await javascriptExecutor.insertNumberedList(); // }, // ), ], @@ -335,10 +320,4 @@ class EditorToolBar extends StatelessWidget { ), ); } - - // Hide the keyboard using JavaScript since it's being opened in a WebView - // https://stackoverflow.com/a/8263376/10835183 - _closeKeyboard() async { - // controller!.evaluateJavascript('document.activeElement.blur();'); - } } diff --git a/lib/src/widgets/fonts_dialog.dart b/lib/src/widgets/fonts_dialog.dart index 8846127..fe6c372 100644 --- a/lib/src/widgets/fonts_dialog.dart +++ b/lib/src/widgets/fonts_dialog.dart @@ -23,19 +23,13 @@ class FontsDialog extends StatelessWidget { InkWell( child: Html(data: '

' '${basename(font.path!)}

'), - onTap: () => Navigator.pop(context, font.path), + onTap: () { + Navigator.pop(context, font.name); + }, ) ], ), ), ); } - - fontSlug(FileSystemEntity font) { - String name = basename(font.path); - String slug = name.toLowerCase(); - slug = slug.replaceAll(extension(font.path), ''); - // print(slug); - return slug; - } } From 9ce8ad23652f388dca8fc7368132da815789499e Mon Sep 17 00:00:00 2001 From: jideguru Date: Thu, 3 Jun 2021 00:32:29 +0100 Subject: [PATCH 03/13] feat: added more editor settings --- README.md | 9 ++++ example/lib/main.dart | 8 ++- lib/rich_editor.dart | 1 + lib/src/models/enum.dart | 2 + lib/src/rendering/rich_editor.dart | 34 +++++++++++-- lib/src/utils/javascript_executor_base.dart | 56 +++++++++++---------- lib/src/widgets/editor_tool_bar.dart | 2 - 7 files changed, 77 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 9852535..0d5210d 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,15 @@ Based on https://github.com/dankito/RichTextEditor, but for Flutter. RichEditor( key: keyEditor, value: 'initial html here', + placeholder: 'Start typing', + // backgroundColor: Colors.blueGrey, // Editor's bg color + // baseTextColor: Colors.white, + // editor padding + padding: EdgeInsets.symmetric(horizontal: 5.0), + // font name + baseFontFamily: 'sans-serif', + // Position of the editing bar (BarPosition.TOP or BarPosition.BOTTOM) + barPosition: BarPosition.TOP, // You can return a Link (maybe you need to upload the image to your // storage before displaying in the editor or you can also use base64 getImageUrl: (image) { diff --git a/example/lib/main.dart b/example/lib/main.dart index 4a31452..dc7f102 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -101,12 +101,16 @@ class _MyHomePageState extends State { //

Heading 4

//
Heading 5
//
Heading 6
-// ''', +// ''', // initial HTML data placeholder: 'Start typing', - // backgroundColor: Colors.blueGrey, + // backgroundColor: Colors.blueGrey, // Editor's bg color // baseTextColor: Colors.white, + // editor padding padding: EdgeInsets.symmetric(horizontal: 5.0), + // font name baseFontFamily: 'sans-serif', + // Position of the editing bar (BarPosition.TOP or BarPosition.BOTTOM) + barPosition: BarPosition.TOP, // You can return a Link (maybe you need to upload the image to your // storage before displaying in the editor or you can also use base64 getImageUrl: (image) { diff --git a/lib/rich_editor.dart b/lib/rich_editor.dart index 48e80cd..746c738 100644 --- a/lib/rich_editor.dart +++ b/lib/rich_editor.dart @@ -3,3 +3,4 @@ library rich_editor; export 'src/rendering/rich_editor.dart'; export 'src/widgets/editor_tool_bar.dart'; export 'src/widgets/tab_button.dart'; +export 'src/models/enum.dart'; diff --git a/lib/src/models/enum.dart b/lib/src/models/enum.dart index 5ba1a95..e4e9e47 100644 --- a/lib/src/models/enum.dart +++ b/lib/src/models/enum.dart @@ -42,3 +42,5 @@ enum CommandName { TOGGLE_GROUPED_TEXT_STYLES_COMMANDS_VIEW, TOGGLE_GROUPED_INSERT_COMMANDS_COMMANDS_VIEW } + +enum BarPosition {TOP, BOTTOM} \ No newline at end of file diff --git a/lib/src/rendering/rich_editor.dart b/lib/src/rendering/rich_editor.dart index 54494d8..8749da9 100644 --- a/lib/src/rendering/rich_editor.dart +++ b/lib/src/rendering/rich_editor.dart @@ -4,6 +4,7 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:rich_editor/src/models/enum.dart'; import 'package:rich_editor/src/services/local_server.dart'; import 'package:rich_editor/src/utils/javascript_executor_base.dart'; import 'package:rich_editor/src/widgets/editor_tool_bar.dart'; @@ -16,6 +17,7 @@ class RichEditor extends StatefulWidget { final EdgeInsets? padding; final String? placeholder; final String? baseFontFamily; + final BarPosition barPosition; final Function(File image)? getImageUrl; final Function(File video)? getVideoUrl; @@ -27,6 +29,7 @@ class RichEditor extends StatefulWidget { this.padding, this.placeholder, this.baseFontFamily, + this.barPosition = BarPosition.TOP, this.getImageUrl, this.getVideoUrl, }) : super(key: key); @@ -89,10 +92,13 @@ class RichEditorState extends State { Widget build(BuildContext context) { return Column( children: [ - EditorToolBar( - controller: _controller, - getImageUrl: widget.getImageUrl, - javascriptExecutor: javascriptExecutor, + Visibility( + visible: widget.barPosition == BarPosition.TOP, + child: EditorToolBar( + controller: _controller, + getImageUrl: widget.getImageUrl, + javascriptExecutor: javascriptExecutor, + ), ), Expanded( child: WebView( @@ -120,7 +126,15 @@ class RichEditorState extends State { print("error ${e.description}"); }, ), - ) + ), + Visibility( + visible: widget.barPosition == BarPosition.BOTTOM, + child: EditorToolBar( + controller: _controller, + getImageUrl: widget.getImageUrl, + javascriptExecutor: javascriptExecutor, + ), + ), ], ); } @@ -192,4 +206,14 @@ class RichEditorState extends State { html = await javascriptExecutor.getCurrentHtml(); return html == '

'; } + + /// Enable Editing (If editing is disabled) + enableEditing() async { + await javascriptExecutor.setInputEnabled(true); + } + + /// Disable Editing (Could be used for a 'view mode') + disableEditing() async { + await javascriptExecutor.setInputEnabled(false); + } } diff --git a/lib/src/utils/javascript_executor_base.dart b/lib/src/utils/javascript_executor_base.dart index e5ac1ad..0ffc88d 100644 --- a/lib/src/utils/javascript_executor_base.dart +++ b/lib/src/utils/javascript_executor_base.dart @@ -55,113 +55,113 @@ class JavascriptExecutorBase { // Text commands undo() async { - await executeJavascript("undo()"); + await executeJavascript("undo();"); } redo() async { - await executeJavascript("redo()"); + await executeJavascript("redo();"); } setBold() async { - await executeJavascript("setBold()"); + await executeJavascript("setBold();"); } setItalic() async { - await executeJavascript("setItalic()"); + await executeJavascript("setItalic();"); } setUnderline() async { - await executeJavascript("setUnderline()"); + await executeJavascript("setUnderline();"); } setSubscript() async { - await executeJavascript("setSubscript()"); + await executeJavascript("setSubscript();"); } setSuperscript() async { - await executeJavascript("setSuperscript()"); + await executeJavascript("setSuperscript();"); } setStrikeThrough() async { - await executeJavascript("setStrikeThrough()"); + await executeJavascript("setStrikeThrough();"); } setTextColor(Color? color) async { String? hex = color!.toHexColorString(); - await executeJavascript("setTextColor('$hex')"); + await executeJavascript("setTextColor('$hex');"); } setTextBackgroundColor(Color? color) async { String? hex = color!.toHexColorString(); - await executeJavascript("setTextBackgroundColor('$hex')"); + await executeJavascript("setTextBackgroundColor('$hex');"); } setFontName(String fontName) async { - await executeJavascript("setFontName('$fontName')"); + await executeJavascript("setFontName('$fontName');"); } setFontSize(int fontSize) async { if (fontSize < 1 || fontSize > 7) { throw ("Font size should have a value between 1-7"); } - await executeJavascript("setFontSize('$fontSize')"); + await executeJavascript("setFontSize('$fontSize');"); } setHeading(int heading) async { - await executeJavascript("setHeading('$heading')"); + await executeJavascript("setHeading('$heading');"); } setFormattingToParagraph() async { - await executeJavascript("setFormattingToParagraph()"); + await executeJavascript("setFormattingToParagraph();"); } setPreformat() async { - await executeJavascript("setPreformat()"); + await executeJavascript("setPreformat();"); } setBlockQuote() async { - await executeJavascript("setBlockQuote()"); + await executeJavascript("setBlockQuote();"); } removeFormat() async { - await executeJavascript("removeFormat()"); + await executeJavascript("removeFormat();"); } setJustifyLeft() async { - await executeJavascript("setJustifyLeft()"); + await executeJavascript("setJustifyLeft();"); } setJustifyCenter() async { - await executeJavascript("setJustifyCenter()"); + await executeJavascript("setJustifyCenter();"); } setJustifyRight() async { - await executeJavascript("setJustifyRight()"); + await executeJavascript("setJustifyRight();"); } setJustifyFull() async { - await executeJavascript("setJustifyFull()"); + await executeJavascript("setJustifyFull();"); } setIndent() async { - await executeJavascript("setIndent()"); + await executeJavascript("setIndent();"); } setOutdent() async { - await executeJavascript("setOutdent()"); + await executeJavascript("setOutdent();"); } insertBulletList() async { - await executeJavascript("insertBulletList()"); + await executeJavascript("insertBulletList();"); } insertNumberedList() async { - await executeJavascript("insertNumberedList()"); + await executeJavascript("insertNumberedList();"); } // Insert element insertLink(String url, String title) async { - await executeJavascript("insertLink('$url', '$title')"); + await executeJavascript("insertLink('$url', '$title');"); } /// The rotation parameter is used to signal that the image is rotated and should be rotated by CSS by given value. @@ -243,6 +243,10 @@ class JavascriptExecutorBase { await executeJavascript("setHeight('" + px.toString() + "px');"); } + setInputEnabled(bool inputEnabled) async { + await executeJavascript("setInputEnabled($inputEnabled);"); + } + static decodeHtml(String html) { return Uri.decodeFull(html); } diff --git a/lib/src/widgets/editor_tool_bar.dart b/lib/src/widgets/editor_tool_bar.dart index 4dd059b..df427dd 100644 --- a/lib/src/widgets/editor_tool_bar.dart +++ b/lib/src/widgets/editor_tool_bar.dart @@ -183,7 +183,6 @@ class EditorToolBar extends StatelessWidget { return FontsDialog(); }, ); - print(command); if (command != null) await javascriptExecutor.setFontName(command); }, @@ -299,7 +298,6 @@ class EditorToolBar extends StatelessWidget { return CheckDialog(); }, ); - print(text); if (text != null) await javascriptExecutor.insertCheckbox(text); }, From 75ae842f4bac2e568ab21b3eaddd2a2f4e5bdd9c Mon Sep 17 00:00:00 2001 From: jideguru Date: Thu, 3 Jun 2021 00:37:45 +0100 Subject: [PATCH 04/13] feat: added more editor settings --- example/lib/main.dart | 18 +++++------------- lib/src/widgets/fonts_dialog.dart | 7 +++---- test/rich_editor_test.dart | 13 +------------ 3 files changed, 9 insertions(+), 29 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index dc7f102..532275e 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -67,25 +67,17 @@ class _MyHomePageState extends State { onSelected: (val) async { switch (val) { case 0: - { - String? html = await keyEditor.currentState?.getHtml(); - print(html); - } + String? html = await keyEditor.currentState?.getHtml(); + print(html); break; case 1: - { - await keyEditor.currentState?.clear(); - } + await keyEditor.currentState?.clear(); break; case 2: - { - await keyEditor.currentState?.unFocus(); - } + await keyEditor.currentState?.unFocus(); break; case 3: - { - await keyEditor.currentState?.focus(); - } + await keyEditor.currentState?.focus(); break; } }, diff --git a/lib/src/widgets/fonts_dialog.dart b/lib/src/widgets/fonts_dialog.dart index fe6c372..f276ecc 100644 --- a/lib/src/widgets/fonts_dialog.dart +++ b/lib/src/widgets/fonts_dialog.dart @@ -1,5 +1,3 @@ -import 'dart:io'; - import 'package:flutter/material.dart'; import 'package:flutter_html/flutter_html.dart'; import 'package:path/path.dart'; @@ -21,8 +19,9 @@ class FontsDialog extends StatelessWidget { children: [ for (SystemFont font in getSystemFonts()) InkWell( - child: Html(data: '

' - '${basename(font.path!)}

'), + child: Html( + data: '

' + '${basename(font.path!)}

'), onTap: () { Navigator.pop(context, font.name); }, diff --git a/test/rich_editor_test.dart b/test/rich_editor_test.dart index 2f4b195..ab73b3a 100644 --- a/test/rich_editor_test.dart +++ b/test/rich_editor_test.dart @@ -1,12 +1 @@ -import 'package:flutter_test/flutter_test.dart'; - -import 'package:rich_editor/rich_editor.dart'; - -void main() { - // test('adds one to input values', () { - // final calculator = Calculator(); - // expect(calculator.addOne(2), 3); - // expect(calculator.addOne(-7), -6); - // expect(calculator.addOne(0), 1); - // }); -} +void main() {} From 4097c7c7469d00de6f88e1b252ed2a8e2f7ca688 Mon Sep 17 00:00:00 2001 From: jideguru Date: Thu, 3 Jun 2021 00:42:53 +0100 Subject: [PATCH 05/13] refactor: format files with dartFmt --- lib/src/extensions/extensions.dart | 2 +- lib/src/models/alias.dart | 2 +- lib/src/models/editor_state.dart | 1 - lib/src/models/enum.dart | 5 +- lib/src/models/family.dart | 3 +- lib/src/utils/constants.dart | 147 -------------------- lib/src/widgets/custom_dialog_template.dart | 1 - 7 files changed, 4 insertions(+), 157 deletions(-) diff --git a/lib/src/extensions/extensions.dart b/lib/src/extensions/extensions.dart index 9d6ceda..d5a28db 100644 --- a/lib/src/extensions/extensions.dart +++ b/lib/src/extensions/extensions.dart @@ -5,7 +5,7 @@ import 'package:flutter/material.dart'; extension ColorX on Color { String toHexColorString() { String hex = value.toRadixString(16).replaceAll('ff', ''); - if(hex.isEmpty) hex = '000000'; + if (hex.isEmpty) hex = '000000'; return '#$hex'; } } diff --git a/lib/src/models/alias.dart b/lib/src/models/alias.dart index d628c1a..7d66a32 100644 --- a/lib/src/models/alias.dart +++ b/lib/src/models/alias.dart @@ -18,4 +18,4 @@ class Alias { data['weight'] = this.weight; return data; } -} \ No newline at end of file +} diff --git a/lib/src/models/editor_state.dart b/lib/src/models/editor_state.dart index b43f354..70dde80 100644 --- a/lib/src/models/editor_state.dart +++ b/lib/src/models/editor_state.dart @@ -27,4 +27,3 @@ class EditorState { return data; } } - diff --git a/lib/src/models/enum.dart b/lib/src/models/enum.dart index e4e9e47..3c3a70a 100644 --- a/lib/src/models/enum.dart +++ b/lib/src/models/enum.dart @@ -37,10 +37,7 @@ enum CommandName { INSERTIMAGE, INSERTCHECKBOX, // pseudo commands for toggling grouped command views - ENTER_VIEWING_MODE, EXPANDING_SEARCH_VIEWING, - TOGGLE_GROUPED_TEXT_STYLES_COMMANDS_VIEW, - TOGGLE_GROUPED_INSERT_COMMANDS_COMMANDS_VIEW } -enum BarPosition {TOP, BOTTOM} \ No newline at end of file +enum BarPosition { TOP, BOTTOM } diff --git a/lib/src/models/family.dart b/lib/src/models/family.dart index a56b684..6eb3218 100644 --- a/lib/src/models/family.dart +++ b/lib/src/models/family.dart @@ -12,12 +12,11 @@ class Family { name = json['name']; if (json['font'] != null) { fonts = []; - if(json['font'] is List) { + if (json['font'] is List) { json['font'].forEach((v) { fonts!.add(new Font.fromJson(v)); }); } - } lang = json['lang']; variant = json['variant']; diff --git a/lib/src/utils/constants.dart b/lib/src/utils/constants.dart index 6c78fb6..8b13789 100644 --- a/lib/src/utils/constants.dart +++ b/lib/src/utils/constants.dart @@ -1,148 +1 @@ -import 'package:flutter/material.dart'; -import 'package:rich_editor/src/models/button.dart'; -import 'javascript_executor_base.dart'; - -List