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 + } }