├── .github
└── workflows
│ ├── android.yml
│ ├── auto-author-assign.yml
│ ├── dependent-issues.yml
│ └── rebase-default-branch.yml
├── .gitignore
├── .idea
└── copyright
│ ├── Editor_copyright.xml
│ └── profiles_settings.xml
├── LICENSE
├── README.md
├── assets
├── android-sample.png
└── infomaniak-mail.webp
├── build.gradle.kts
├── gradle.properties
├── gradle
├── libs.versions.toml
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
├── rich-html-editor
├── .gitignore
├── build.gradle.kts
├── proguard-rules.pro
└── src
│ └── main
│ ├── assets
│ ├── attach_listeners.js
│ ├── define_listeners.js
│ ├── editor_template.html
│ ├── focus_request.js
│ ├── link_detection.js
│ └── manage_links.js
│ └── java
│ └── com
│ └── infomaniak
│ └── lib
│ └── richhtmleditor
│ ├── DocumentInitializer.kt
│ ├── EditorReloader.kt
│ ├── EditorStatuses.kt
│ ├── Extensions.kt
│ ├── JsBridge.kt
│ ├── JsColor.kt
│ ├── Justification.kt
│ ├── RichHtmlEditorWebView.kt
│ ├── RichHtmlEditorWebViewClient.kt
│ ├── StatusCommand.kt
│ ├── Utils.kt
│ └── executor
│ ├── HtmlSetter.kt
│ ├── JsExecutableMethod.kt
│ ├── JsExecutor.kt
│ ├── JsLifecycleAwareExecutor.kt
│ ├── KeyboardOpener.kt
│ ├── ScriptCssInjector.kt
│ ├── SpellCheckHtmlSetter.kt
│ └── StateSubscriber.kt
├── sample
├── .gitignore
├── build.gradle.kts
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── assets
│ ├── editor_custom_css.css
│ ├── example1.html
│ └── example2.html
│ ├── java
│ └── com
│ │ └── infomaniak
│ │ └── lib
│ │ └── richhtmleditor
│ │ └── sample
│ │ ├── EditorSampleFragment.kt
│ │ ├── EditorSampleViewModel.kt
│ │ └── MainActivity.kt
│ └── res
│ ├── color
│ └── background_editor_button.xml
│ ├── drawable
│ ├── ic_indent.xml
│ ├── ic_justify_center.xml
│ ├── ic_justify_full.xml
│ ├── ic_justify_left.xml
│ ├── ic_justify_right.xml
│ ├── ic_launcher_background.xml
│ ├── ic_launcher_foreground.xml
│ ├── ic_ordered_list.xml
│ ├── ic_outdent.xml
│ ├── ic_redo.xml
│ ├── ic_subscript.xml
│ ├── ic_superscript.xml
│ ├── ic_undo.xml
│ └── ic_unordered_list.xml
│ ├── layout
│ ├── activity_main.xml
│ ├── create_link_text_input.xml
│ └── fragment_editor_sample.xml
│ ├── mipmap-anydpi-v26
│ ├── ic_launcher.xml
│ └── ic_launcher_round.xml
│ ├── mipmap-hdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-mdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.webp
│ └── ic_launcher_round.webp
│ ├── navigation
│ └── nav_graph.xml
│ ├── values-night
│ ├── colors.xml
│ └── themes.xml
│ ├── values-v23
│ └── themes.xml
│ ├── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ ├── style.xml
│ └── themes.xml
│ └── xml
│ ├── data_extraction_rules.xml
│ └── network_security_config.xml
└── settings.gradle.kts
/.github/workflows/android.yml:
--------------------------------------------------------------------------------
1 | name: Android CI
2 |
3 | on:
4 | pull_request:
5 |
6 | concurrency:
7 | group: ${{ github.head_ref }}
8 | cancel-in-progress: true
9 |
10 | jobs:
11 |
12 | instrumentation-tests:
13 | if: github.event.pull_request.draft == false
14 | runs-on: [ self-hosted, Android ]
15 | strategy:
16 | matrix:
17 | api-level: [ 34 ]
18 | target: [ google_apis ]
19 |
20 | steps:
21 | - name: Cancel Previous Runs
22 | uses: styfle/cancel-workflow-action@0.12.1
23 | with:
24 | access_token: ${{ github.token }}
25 |
26 | - name: Checkout the code
27 | uses: actions/checkout@v4.1.1
28 | with:
29 | token: ${{ github.token }}
30 | submodules: recursive
31 |
32 | # Setup Gradle and run Build
33 | - name: Grant execute permission for gradlew
34 | run: chmod +x gradlew
35 | - name: Build with Gradle
36 | run: ./gradlew build
37 |
38 | # Run tests
39 | - name: Run Unit tests
40 | run: ./gradlew testDebugUnitTest --stacktrace
41 |
--------------------------------------------------------------------------------
/.github/workflows/auto-author-assign.yml:
--------------------------------------------------------------------------------
1 | name: Auto Author Assign
2 |
3 | on:
4 | pull_request_target:
5 | types: [ opened, reopened ]
6 |
7 | permissions:
8 | pull-requests: write
9 |
10 | jobs:
11 | assign-author:
12 | runs-on: ubuntu-latest
13 | steps:
14 | - uses: toshimaru/auto-author-assign@v2.1.0
15 |
--------------------------------------------------------------------------------
/.github/workflows/dependent-issues.yml:
--------------------------------------------------------------------------------
1 | name: Dependent Issues
2 |
3 | on:
4 | issues:
5 | types:
6 | - opened
7 | - edited
8 | - closed
9 | - reopened
10 | pull_request_target:
11 | types:
12 | - opened
13 | - edited
14 | - closed
15 | - reopened
16 | # Makes sure we always add status check for PRs. Useful only if
17 | # this action is required to pass before merging. Otherwise, it
18 | # can be removed.
19 | - synchronize
20 |
21 | jobs:
22 | check:
23 | runs-on: ubuntu-latest
24 | steps:
25 | - uses: z0al/dependent-issues@v1.5.2
26 | env:
27 | # (Required) The token to use to make API calls to GitHub.
28 | GITHUB_TOKEN: ${{ github.token }}
29 |
--------------------------------------------------------------------------------
/.github/workflows/rebase-default-branch.yml:
--------------------------------------------------------------------------------
1 | # GitHub Actions Virtual Environments
2 | # https://github.com/actions/virtual-environments/
3 |
4 | # Rebases a pull request on the repo's default branch when the "rebase" label is added
5 | # Note: you'll need to add a personal access token to your repo, `PERSONAL_ACCESS_TOKEN`. (`REBASE_PR_TOKEN`)
6 | # Link: https://github.com/jessesquires/gh-workflows/blob/main/.github/workflows/rebase-default-branch.yml
7 |
8 | name: Rebase Pull Request
9 |
10 | on:
11 | pull_request:
12 | types: [ labeled ]
13 |
14 | env:
15 | DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
16 |
17 | jobs:
18 | main:
19 | if: ${{ contains(github.event.*.labels.*.name, 'rebase') }}
20 | name: Rebase
21 | runs-on: ubuntu-latest
22 | steps:
23 | - name: git checkout
24 | uses: actions/checkout@v3
25 | with:
26 | token: ${{ secrets.REBASE_PR_TOKEN }}
27 | ref: ${{ github.event.pull_request.head.ref }}
28 | fetch-depth: 0
29 |
30 | # Link: https://httgp.com/signing-commits-in-github-actions/
31 | - name: Import bot's GPG key for signing commits
32 | id: import-gpg
33 | uses: crazy-max/ghaction-import-gpg@v4
34 | with:
35 | gpg_private_key: ${{ secrets.BOT_GPG_PRIVATE_KEY }}
36 | passphrase: ${{ secrets.BOT_GPG_PASSPHRASE }}
37 | git_config_global: true
38 | git_user_signingkey: true
39 | git_commit_gpgsign: true
40 |
41 | - name: perform rebase
42 | run: |
43 | git config --global user.email "kevin.boulongne+bot@gmail.com"
44 | git status
45 | git pull
46 | git checkout "$DEFAULT_BRANCH"
47 | git status
48 | git pull
49 | git checkout "$GITHUB_HEAD_REF"
50 | git rebase "$DEFAULT_BRANCH"
51 | git push --force-with-lease
52 | git status
53 |
54 | # Link: https://github.com/marketplace/actions/actions-ecosystem-remove-labels
55 | - name: remove label
56 | if: always()
57 | uses: actions-ecosystem/action-remove-labels@v1
58 | with:
59 | labels: rebase
60 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Gradle files
2 | .gradle/
3 | build/
4 |
5 | # Local configuration file (sdk path, etc)
6 | local.properties
7 |
8 | # Log/OS Files
9 | *.log
10 |
11 | # Android Studio generated files and folders
12 | captures/
13 | .externalNativeBuild/
14 | .cxx/
15 | *.apk
16 | *.aab
17 | output.json
18 |
19 | # IntelliJ
20 | *.iml
21 | .idea/
22 | misc.xml
23 | deploymentTargetDropDown.xml
24 | render.experimental.xml
25 |
26 | # Keystore files
27 | *.jks
28 | *.keystore
29 |
30 | # Google Services (e.g. APIs or Firebase)
31 | google-services.json
32 |
33 | # Android Profiling
34 | *.hprof
35 |
36 | # Missing gitignore compared to mail
37 | .DS_Store
38 |
--------------------------------------------------------------------------------
/.idea/copyright/Editor_copyright.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Infomaniak Rich HTML Editor
2 |
3 | 
4 |
5 | The **Infomaniak Rich HTML Editor** is an Android library designed to display HTML and easily modify it on the fly. It relies on
6 | the power of the `contenteditable` HTML attribute inside a WebView.
7 |
8 |
9 |
10 |
11 | Looking for an iOS or macOS equivalent? Check out the Swift version of this editor here: [Infomaniak/swift-rich-html-editor](https://github.com/Infomaniak/swift-rich-html-editor)
12 |
13 | ## ✍️ About
14 |
15 | ### Features
16 |
17 | - **HTML Content Editing**: Full support for viewing and editing HTML content directly.
18 | - **Wide range of formatting commands**: Many commands are available to format text, from simple commands like bold to more
19 | advanced ones like link creation.
20 | - **Useful API to control the editor**: It lets you:
21 | - Listen to format option's activated status when the cursor moves around the html content
22 | - Add custom css to the editor
23 | - Add custom scripts to the editor
24 |
25 | ### Installation
26 |
27 | Add this dependency to your project:
28 |
29 | Using version catalog:
30 |
31 | ```toml
32 | rich-html-editor = { module = "com.github.infomaniak:android-rich-html-editor", version.ref = "richHtmlEditorVersion" }
33 | ```
34 |
35 | Directly inside gradle dependencies:
36 |
37 | ```gradle
38 | dependencies {
39 | implementation "com.github.Infomaniak:android-rich-html-editor:$richHtmlEditorVersion"
40 | }
41 | ```
42 |
43 | The latest version is: 
44 |
45 | ## ⚙️ Usage
46 |
47 | ### Simplest usage
48 |
49 | In your layout:
50 |
51 | ```xml
52 |
56 | ```
57 |
58 | In your fragment:
59 |
60 | ```kt
61 | val html = """
62 |
63 |
64 |
Hello World
65 |
66 |
67 | """.trimMargin()
68 | editor.setHtml(html)
69 | ```
70 |
71 | ### Change format and reacte to its changes
72 |
73 | Add a button to your xml:
74 |
75 | ```xml
76 |
81 | ```
82 |
83 | Set a click listener on the button to apply the associated format and modify the appearance of the button to report the status
84 | where the cursor is placed:
85 |
86 | ```kt
87 | boldButton.setOnClickListener { editor.toggleBold() }
88 |
89 | viewLifecycleOwner.lifecycleScope.launch {
90 | editor.editorStatusesFlow.collect {
91 | // Update your button's activation status how you prefer. If you have provided
92 | // an activated state color for your button, you can do the following:
93 | boldButton.isActivated = it.isBold
94 | }
95 | }
96 | ```
97 |
98 | > [!TIP]
99 | > If you want to listen to the status changes of a format, do not forget to subscribe to it as described in the following
100 | > [Subscribe to format states](#subscribeToStates) section.
101 |
102 | ### Subscribe to format states
103 |
104 | You can subscribe only to the states that are relevant to you. This way, the flow will update its value only when at least one of
105 | your subscribed states changes.
106 |
107 | ```kt
108 | editor.subscribeToStates(setOf(StatusCommand.BOLD, StatusCommand.ITALIC))
109 | ```
110 |
111 | > [!NOTE]
112 | > By default, when `subscribeToStates()` is never called, all available StatusCommand will be subscribed to.
113 | >
114 | > You can subscribe to all possible states by passing in `null`
115 | > ```kt
116 | > editor.subscribeToStates(null)
117 | > ```
118 |
119 | ### Add custom css or script to the editor
120 |
121 | You can add your own css to stylize your editor to your liking or you can add scripts to develop your own advanced
122 | functionalities. To do so, the editor exposes two easy to use methods.
123 |
124 | ```kt
125 | editor.apply {
126 | addCss("div { padding: 8px }")
127 | addScript("document.body.style['background'] = '#00FFFF'")
128 | }
129 | ```
130 |
131 | ### Use a custom WebViewClient with the editor
132 |
133 | To safely use your own WebViewClient instance with the editor, you have to call the
134 | RichHtmlEditorWebView's `notifyPageHasLoaded()` inside your custom WebViewClient's `onPageFinished()` callback.
135 |
136 | ### Activate/Deactivate spellcheck
137 |
138 | Spellcheck is activated by default but if you don't want to have any spellcheck done on the editor content,
139 | you can do that by doing so.
140 |
141 | ```kt
142 | editor.withSpellCheck(false)
143 | ```
144 |
145 | ### More advanced features
146 |
147 | For more advanced features, take a look at the [sample project](sample) or
148 | the [Infomaniak Mail app](https://github.com/Infomaniak/android-kMail) that uses this rich html editor.
149 |
150 | ## 📖 Documentation
151 |
152 | Useful methods and classes inside the project are documented with KDoc.
153 |
154 | ## 🔍 Sample Projects
155 |
156 | You can find a sample project in the [sample](sample) folder.
157 |
158 | ## 📱 Apps using the rich html editor
159 |
160 |
161 |
162 |
163 |
164 | [Infomaniak Mail](https://github.com/Infomaniak/android-kMail) allows you to manage your Infomaniak addresses in a completely
165 | secure environment.
166 |
--------------------------------------------------------------------------------
/assets/android-sample.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/assets/android-sample.png
--------------------------------------------------------------------------------
/assets/infomaniak-mail.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/assets/infomaniak-mail.webp
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | buildscript {
2 | extra.apply {
3 | set("sharedMinSdk", 24)
4 | set("sharedCompileSdk", 34)
5 | set("javaVersion", JavaVersion.VERSION_17)
6 | }
7 | }
8 |
9 | plugins {
10 | alias(libs.plugins.android.application) apply false
11 | alias(libs.plugins.android.library) apply false
12 | alias(libs.plugins.jetbrains.kotlin.android) apply false
13 | }
14 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. For more details, visit
12 | # https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
24 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | agp = "8.3.2"
3 | kotlin = "2.0.0"
4 | coreKtx = "1.13.1"
5 | appcompat = "1.7.0"
6 | material = "1.12.0"
7 | constraintlayout = "2.1.4"
8 | navigationFragmentKtx = "2.7.7"
9 | navigationUiKtx = "2.7.7"
10 |
11 | [libraries]
12 | androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
13 | androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
14 | material = { group = "com.google.android.material", name = "material", version.ref = "material" }
15 | androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
16 | androidx-navigation-fragment-ktx = { group = "androidx.navigation", name = "navigation-fragment-ktx", version.ref = "navigationFragmentKtx" }
17 | androidx-navigation-ui-ktx = { group = "androidx.navigation", name = "navigation-ui-ktx", version.ref = "navigationUiKtx" }
18 |
19 | [plugins]
20 | android-application = { id = "com.android.application", version.ref = "agp" }
21 | android-library = { id = "com.android.library", version.ref = "agp" }
22 | jetbrains-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
23 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Mar 06 15:28:07 CET 2024
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | - openjdk17
3 |
--------------------------------------------------------------------------------
/rich-html-editor/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/rich-html-editor/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.android.library)
3 | alias(libs.plugins.jetbrains.kotlin.android)
4 | id("maven-publish")
5 | }
6 |
7 | val sharedMinSdk: Int by rootProject.extra
8 | val sharedCompileSdk: Int by rootProject.extra
9 | val javaVersion: JavaVersion by rootProject.extra
10 |
11 | android {
12 | namespace = "com.infomaniak.lib.richhtmleditor"
13 | compileSdk = sharedCompileSdk
14 |
15 | defaultConfig {
16 | minSdk = sharedMinSdk
17 |
18 | consumerProguardFiles("consumer-rules.pro")
19 | }
20 |
21 | compileOptions {
22 | sourceCompatibility = javaVersion
23 | targetCompatibility = javaVersion
24 | }
25 | kotlinOptions {
26 | jvmTarget = javaVersion.toString()
27 | }
28 | }
29 |
30 | dependencies {
31 | implementation(libs.androidx.core.ktx)
32 | }
33 |
34 | afterEvaluate {
35 | publishing {
36 | publications {
37 | create("release") {
38 | from(components.findByName("release"))
39 | groupId = "com.github"
40 | artifactId = "android-rich-html-editor"
41 | version = "0.1.0"
42 | }
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/rich-html-editor/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/rich-html-editor/src/main/assets/attach_listeners.js:
--------------------------------------------------------------------------------
1 | onBodyResize(() => {
2 | updateWebViewHeightWithBodyHeight()
3 | focusCursorOnScreen()
4 | })
5 |
6 | document.addEventListener("selectionchange", () => {
7 | reportSelectionStateChangedIfNecessary()
8 | focusCursorOnScreen()
9 | })
10 |
11 | reportEmptyBodyStatus()
12 | onEditorChildListChange(() => {
13 | reportEmptyBodyStatus()
14 | })
15 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/assets/define_listeners.js:
--------------------------------------------------------------------------------
1 | let currentSelectionState = {}
2 | let previousEmptyStat
3 |
4 | // Helper functions
5 |
6 | function getBody() {
7 | return document.body
8 | }
9 |
10 | function getEditor() {
11 | // The id of this HTML tag is shared across multiple files and needs to remain the same
12 | return document.getElementById("editor")
13 | }
14 |
15 | function onBodyResize(callback) {
16 | let resizeObserver = new ResizeObserver(callback)
17 | resizeObserver.observe(document.documentElement)
18 | }
19 |
20 | function getSelectionRangeOrNull() {
21 | const selection = document.getSelection()
22 | return (selection.rangeCount > 0) ? selection.getRangeAt(0) : null
23 | }
24 |
25 | function onEditorChildListChange(callback) {
26 | const config = { childList: true }
27 | const observer = new MutationObserver(callback)
28 | observer.observe(getEditor(), config)
29 | }
30 |
31 | // Core logic
32 |
33 | function exportHtml() {
34 | window.editor.exportHtml(getEditor().innerHTML)
35 | }
36 |
37 | function focusCursorOnScreen() {
38 | let rect = getCaretRect()
39 | if (rect) window.editor.focusCursorOnScreen(rect.left, rect.top, rect.right, rect.bottom)
40 | }
41 |
42 | function findElementNode(element) {
43 | if (element === null) return null
44 | if (element.nodeType === Node.ELEMENT_NODE) return element
45 | return findElementNode(element.parentNode)
46 | }
47 |
48 | function getCaretRect() {
49 | const selection = window.getSelection()
50 | const lastSelectedNode = selection.focusNode
51 |
52 | if (selection.rangeCount === 0) return
53 |
54 | const range = selection.getRangeAt(0).cloneRange()
55 |
56 | // Create a range around the last selected node so the webview can scroll and follow the cursor even if the whole range is
57 | // bigger than the screen
58 | range.selectNodeContents(lastSelectedNode)
59 |
60 | const rangeRects = range.getClientRects()
61 |
62 | let rect
63 | switch (rangeRects.length) {
64 | case 0:
65 | rect = findElementNode(lastSelectedNode).getBoundingClientRect()
66 | break;
67 | case 1:
68 | rect = rangeRects[0]
69 | break;
70 | default:
71 | rect = range.getBoundingClientRect()
72 | break;
73 | }
74 |
75 | return rect
76 | }
77 |
78 | function reportSelectionStateChangedIfNecessary() {
79 | const newSelectionState = getCurrentSelectionState()
80 | if (!areSelectionStatesTheSame(currentSelectionState, newSelectionState)) {
81 | currentSelectionState = newSelectionState
82 | console.log("New selection changed:", currentSelectionState)
83 | window.editor.reportCommandDataChange(
84 | newSelectionState["bold"],
85 | newSelectionState["italic"],
86 | newSelectionState["strikeThrough"],
87 | newSelectionState["underline"],
88 | newSelectionState["fontName"],
89 | newSelectionState["fontSize"],
90 | newSelectionState["foreColor"],
91 | newSelectionState["backColor"],
92 | newSelectionState["isLinkSelected"],
93 | newSelectionState["insertOrderedList"],
94 | newSelectionState["insertUnorderedList"],
95 | newSelectionState["subscript"],
96 | newSelectionState["superscript"],
97 | newSelectionState["justifyLeft"],
98 | newSelectionState["justifyCenter"],
99 | newSelectionState["justifyRight"],
100 | newSelectionState["justifyFull"]
101 | )
102 | }
103 | }
104 |
105 | function getCurrentSelectionState() {
106 | let currentState = {}
107 |
108 | for (const property of stateCommands) {
109 | currentState[property] = document.queryCommandState(property)
110 | }
111 | for (const property of valueCommands) {
112 | currentState[property] = document.queryCommandValue(property)
113 | }
114 |
115 | if (REPORT_LINK_STATUS) currentState["isLinkSelected"] = computeLinkStatus()
116 |
117 | return currentState
118 | }
119 |
120 | function computeLinkStatus() {
121 | return getAllLinksPartiallyContainedInsideSelection().length > 0
122 | }
123 |
124 | function areSelectionStatesTheSame(state1, state2) {
125 | let isLinkTheSame = (REPORT_LINK_STATUS) ? state1["isLinkSelected"] === state2["isLinkSelected"] : true
126 |
127 | return stateCommands.every(property => state1[property] === state2[property])
128 | && valueCommands.every(property => state1[property] === state2[property])
129 | && isLinkTheSame
130 | }
131 |
132 | function updateWebViewHeightWithBodyHeight() {
133 | let documentElement = document.documentElement
134 | let paddingTop = parseInt(window.getComputedStyle(documentElement)["margin-top"])
135 | let paddingBottom = parseInt(window.getComputedStyle(documentElement)["margin-bottom"])
136 |
137 | window.editor.reportNewDocumentHeight((documentElement.offsetHeight + paddingTop + paddingBottom) * window.devicePixelRatio)
138 | }
139 |
140 | function reportEmptyBodyStatus() {
141 | const isEditorEmpty = getEditor().childNodes.length === 0
142 | if (previousEmptyStat === isEditorEmpty) return
143 | previousEmptyStat = isEditorEmpty
144 | window.editor.onEmptyBodyChanges(isEditorEmpty)
145 | }
146 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/assets/editor_template.html:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/assets/focus_request.js:
--------------------------------------------------------------------------------
1 | function requestFocus() {
2 | getEditor().focus()
3 | }
4 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/assets/link_detection.js:
--------------------------------------------------------------------------------
1 | const DOCUMENT_POSITION_SAME = 0 // TODO: Check usefulness
2 |
3 | function getAllLinksPartiallyContainedInsideSelection() {
4 | let elements = [...getEditor().querySelectorAll("a[href]")]
5 | const range = getSelectionRangeOrNull()
6 | if (range === null) return []
7 |
8 | const { startContainer, endContainer } = range
9 |
10 | // TODO: Investigate RoosterJs issues with startContainer and endContainer https://github.com/microsoft/roosterjs/blob/b1d4bab67dcae342cfdc043a8cbe2b96bb823a44/packages/roosterjs-editor-dom/lib/utils/queryElements.ts#L30
11 |
12 | elements = elements.filter(element =>
13 | doesIntersectWithNodeRange(element, startContainer, endContainer)
14 | )
15 |
16 | return elements
17 | }
18 |
19 | function doesIntersectWithNodeRange(node, startNode, endNode) {
20 | const startPosition = node.compareDocumentPosition(startNode)
21 | const endPosition = node.compareDocumentPosition(endNode)
22 | const targetPositions = [DOCUMENT_POSITION_SAME, Node.DOCUMENT_POSITION_CONTAINS, Node.DOCUMENT_POSITION_CONTAINED_BY]
23 |
24 | return (
25 | doesPositionMatchTargets(startPosition, targetPositions) || // intersectStart
26 | doesPositionMatchTargets(endPosition, targetPositions) || // intersectEnd
27 | (doesPositionMatchTargets(startPosition, [Node.DOCUMENT_POSITION_PRECEDING]) && // Contains
28 | doesPositionMatchTargets(endPosition, [Node.DOCUMENT_POSITION_FOLLOWING]) &&
29 | !doesPositionMatchTargets(endPosition, [Node.DOCUMENT_POSITION_CONTAINED_BY]))
30 | )
31 | }
32 |
33 | function doesPositionMatchTargets(position, targets) {
34 | return targets.some(target =>
35 | target === DOCUMENT_POSITION_SAME ? position === DOCUMENT_POSITION_SAME : (position & target) === target
36 | )
37 | }
38 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/assets/manage_links.js:
--------------------------------------------------------------------------------
1 | // Create link
2 |
3 | function createLink(displayText, url) {
4 | let range = getSelectionRangeOrNull()
5 | if (range === null) return
6 |
7 | if (range.collapsed) {
8 | // There's no selection, only a cursor. We can add the link manually
9 | let anchor = getAnchorNodeAtCursor()
10 |
11 | // If there is already a link, just change its href
12 | if (anchor) {
13 | anchor.href = url;
14 | // Change text content if it is specified
15 | updateAnchorDisplayText(anchor, displayText);
16 | } else {
17 | anchor = document.createElement('A')
18 | anchor.textContent = displayText || url;
19 | anchor.href = url;
20 | range.insertNode(anchor)
21 | }
22 |
23 | setCaretAtEndOfAnchor(anchor)
24 | } else {
25 | // There's already a selection so use execCommand to create a new link
26 | document.execCommand("createLink", false, url)
27 |
28 | // Update the newly created link's display text if we have a custom text
29 | if (displayText) {
30 | let anchor = getAnchorNodeAtCursor()
31 | updateAnchorDisplayText(anchor, displayText)
32 | }
33 | }
34 | }
35 |
36 | function getAnchorNodeAtCursor() {
37 | let anchors = getAllLinksPartiallyContainedInsideSelection()
38 | return anchors.length > 0 ? anchors[0] : null
39 | }
40 |
41 | function updateAnchorDisplayText(anchor, displayText) {
42 | if (displayText && anchor.textContent != displayText) {
43 | anchor.textContent = displayText;
44 | }
45 | }
46 |
47 | function setCaretAtEndOfAnchor(anchor) {
48 | const range = new Range();
49 | range.setStart(anchor, 1);
50 | range.setEnd(anchor, 1);
51 | range.collapsed = true;
52 |
53 | const selection = document.getSelection();
54 | selection.removeAllRanges();
55 | selection.addRange(range);
56 | }
57 |
58 | // Unlink
59 |
60 | function unlink() {
61 | getAllLinksPartiallyContainedInsideSelection().forEach(anchor => unlinkAnchorNode(anchor))
62 | }
63 |
64 | function unlinkAnchorNode(anchor) {
65 | let selection = document.getSelection()
66 | if (selection.rangeCount === 0) return
67 |
68 | let range = selection.getRangeAt(0)
69 | let rangeBackup = range.cloneRange()
70 | range.selectNodeContents(anchor)
71 | document.execCommand("unlink")
72 |
73 | selection.removeAllRanges()
74 | selection.addRange(rangeBackup)
75 | }
76 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/DocumentInitializer.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor
19 |
20 | import android.webkit.WebView
21 |
22 | internal class DocumentInitializer {
23 | fun setupDocument(webView: WebView) = with(webView) {
24 | injectScript(context.readAsset("attach_listeners.js")) // Needs to only be called once the page has finished loading
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/EditorReloader.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor
19 |
20 | import android.os.Looper
21 | import kotlinx.coroutines.CoroutineScope
22 | import kotlinx.coroutines.flow.MutableStateFlow
23 | import kotlinx.coroutines.flow.collectLatest
24 | import kotlinx.coroutines.launch
25 |
26 | /**
27 | * A utility class to help easily reload the html content of a [RichHtmlEditorWebView] on configuration changes.
28 | *
29 | * This class is meant to be instantiated inside a ViewModel to be able to retain the HTML content through configuration changes.
30 | *
31 | * @param coroutineScope A coroutine scope where the exportation of the HTML will be processed. Preferably the viewModelScope of
32 | * the ViewModel where this class has been instantiated.
33 | *
34 | * @see load
35 | * @see save
36 | */
37 | class EditorReloader(private val coroutineScope: CoroutineScope) {
38 |
39 | private var needToReloadHtml: Boolean = false
40 | private var savedHtml = MutableStateFlow(null)
41 |
42 | /**
43 | * An alternative for loading the HTML content of the [RichHtmlEditorWebView].
44 | *
45 | * This method can be called within the `onViewCreated()` method of the Fragment containing your [RichHtmlEditorWebView].
46 | * On the initial call, it loads the default HTML content. For all subsequent calls, it reloads the previously loaded HTML
47 | * content.
48 | *
49 | * @param editor The editor to load content into.
50 | * @param defaultHtml The HTML to load on the initial call. On subsequent calls, this value won't be taken into account.
51 | *
52 | * Usage:
53 | * ```
54 | * override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
55 | * super.onViewCreated(view, savedInstanceState)
56 | * lifecycleScope.launch {
57 | * viewModel.editorReloader.load(editor, "
Hello World
")
58 | * }
59 | * }
60 | * ```
61 | *
62 | * @throws IllegalStateException If the method is not called on the main thread.
63 | */
64 | suspend fun load(editor: RichHtmlEditorWebView, defaultHtml: String) {
65 | if (Looper.myLooper() != Looper.getMainLooper()) error("The load method needs to be called on the main thread")
66 |
67 | if (needToReloadHtml) {
68 | savedHtml.collectLatest {
69 | if (it == null) return@collectLatest
70 |
71 | resetSavedHtml()
72 | editor.setHtml(it)
73 | }
74 | } else {
75 | editor.setHtml(defaultHtml)
76 | }
77 |
78 | enableHtmlReload()
79 | }
80 |
81 | /**
82 | * Exports and saves the editor's HTML content for later reloading.
83 | *
84 | * This method should be called within the `onSaveInstanceState()` method of the Fragment.
85 | *
86 | * @param editor The editor whose content needs to be saved.
87 | *
88 | * Usage:
89 | * ```
90 | * override fun onSaveInstanceState(outState: Bundle) {
91 | * super.onSaveInstanceState(outState)
92 | * viewModel.editorReloader.save(editor)
93 | * }
94 | * ```
95 | */
96 | fun save(editor: RichHtmlEditorWebView) {
97 | editor.exportHtml {
98 | coroutineScope.launch { savedHtml.emit(it) }
99 | }
100 | }
101 |
102 | private suspend fun resetSavedHtml() {
103 | savedHtml.emit(null)
104 | }
105 |
106 | private fun enableHtmlReload() {
107 | needToReloadHtml = true
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/EditorStatuses.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor
19 |
20 | import androidx.annotation.ColorInt
21 | import kotlinx.coroutines.sync.Mutex
22 | import kotlinx.coroutines.sync.withLock
23 |
24 | data class EditorStatuses(
25 | var isBold: Boolean = false,
26 | var isItalic: Boolean = false,
27 | var isStrikeThrough: Boolean = false,
28 | var isUnderlined: Boolean = false,
29 | var fontName: String? = null,
30 | var fontSize: Float? = null,
31 | var textColor: Int? = null,
32 | var backgroundColor: Int? = null,
33 | var isLinkSelected: Boolean = false,
34 | var isOrderedListSelected: Boolean = false,
35 | var isUnorderedListSelected: Boolean = false,
36 | var isSubscript: Boolean = false,
37 | var isSuperscript: Boolean = false,
38 | var justification: Justification? = null,
39 | ) {
40 | private val mutex = Mutex()
41 |
42 | suspend fun updateStatusesAtomically(
43 | isBold: Boolean,
44 | isItalic: Boolean,
45 | isStrikeThrough: Boolean,
46 | isUnderlined: Boolean,
47 | fontName: String,
48 | fontSize: Float?,
49 | @ColorInt textColor: Int?,
50 | @ColorInt backgroundColor: Int?,
51 | isLinkSelected: Boolean,
52 | isOrderedListSelected: Boolean,
53 | isUnorderedListSelected: Boolean,
54 | isSubscript: Boolean,
55 | isSuperscript: Boolean,
56 | justification: Justification?,
57 | ) {
58 | mutex.withLock {
59 | this.isBold = isBold
60 | this.isItalic = isItalic
61 | this.isStrikeThrough = isStrikeThrough
62 | this.isUnderlined = isUnderlined
63 | this.fontName = fontName
64 | this.fontSize = fontSize
65 | this.textColor = textColor
66 | this.backgroundColor = backgroundColor
67 | this.isLinkSelected = isLinkSelected
68 | this.isOrderedListSelected = isOrderedListSelected
69 | this.isUnorderedListSelected = isUnorderedListSelected
70 | this.isSubscript = isSubscript
71 | this.isSuperscript = isSuperscript
72 | this.justification = justification
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/Extensions.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor
19 |
20 | import android.content.Context
21 | import android.os.Build
22 | import android.os.Bundle
23 | import android.view.AbsSavedState
24 | import android.webkit.WebView
25 | import java.io.BufferedReader
26 |
27 | internal fun Context.readAsset(fileName: String): String {
28 | return assets
29 | .open(fileName)
30 | .bufferedReader()
31 | .use(BufferedReader::readText)
32 | }
33 |
34 | internal fun WebView.injectScript(scriptCode: String, id: String? = null) {
35 | val escapedStringLiteralId = id?.let { looselyEscapeAsStringLiteralForJs(it) }
36 |
37 | val removePreviousId = escapedStringLiteralId?.let {
38 | """
39 | var previousScript = document.getElementById($it)
40 | if (previousScript) previousScript.remove()
41 | """.trimIndent()
42 | } ?: ""
43 | val setId = escapedStringLiteralId?.let { "script.id = ${it};" } ?: ""
44 |
45 | val escapedStringLiteralScriptCode = looselyEscapeAsStringLiteralForJs(scriptCode)
46 | val addScriptJs = """
47 | var script = document.createElement('script');
48 | script.type = 'text/javascript';
49 | script.text = $escapedStringLiteralScriptCode;
50 | $setId
51 |
52 | document.head.appendChild(script);
53 | """.trimIndent()
54 |
55 | val code = removePreviousId + "\n" + addScriptJs
56 |
57 | evaluateJavascript(code, null)
58 | }
59 |
60 | internal fun WebView.injectCss(css: String) {
61 | val escapedStringLiteralCss = looselyEscapeAsStringLiteralForJs(css)
62 | val addCssJs = """
63 | var style = document.createElement('style');
64 | style.textContent = $escapedStringLiteralCss;
65 |
66 | document.head.appendChild(style);
67 | """.trimIndent()
68 |
69 | evaluateJavascript(addCssJs, null)
70 | }
71 |
72 | fun Bundle.getParcelableCompat(key: String, clazz: Class): AbsSavedState? {
73 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
74 | getParcelable(key, clazz)
75 | } else {
76 | getParcelable(key)
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/JsBridge.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor
19 |
20 | import android.graphics.Color
21 | import android.webkit.JavascriptInterface
22 | import androidx.annotation.ColorInt
23 | import androidx.annotation.IntRange
24 | import com.infomaniak.lib.richhtmleditor.executor.JsExecutableMethod
25 | import com.infomaniak.lib.richhtmleditor.executor.JsExecutor
26 | import kotlinx.coroutines.CoroutineDispatcher
27 | import kotlinx.coroutines.CoroutineScope
28 | import kotlinx.coroutines.Dispatchers
29 | import kotlinx.coroutines.channels.BufferOverflow
30 | import kotlinx.coroutines.flow.MutableSharedFlow
31 | import kotlinx.coroutines.flow.MutableStateFlow
32 | import kotlinx.coroutines.flow.SharedFlow
33 | import kotlinx.coroutines.flow.StateFlow
34 | import kotlinx.coroutines.flow.asSharedFlow
35 | import kotlinx.coroutines.flow.asStateFlow
36 | import kotlinx.coroutines.launch
37 |
38 | internal class JsBridge(
39 | private val coroutineScope: CoroutineScope,
40 | private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default,
41 | private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main,
42 | private val jsExecutor: JsExecutor,
43 | private val notifyExportedHtml: (String) -> Unit,
44 | private val requestRectangleOnScreen: (left: Int, top: Int, right: Int, bottom: Int) -> Unit,
45 | private val updateWebViewHeight: (Int) -> Unit,
46 | ) {
47 |
48 | private val editorStatuses = EditorStatuses()
49 |
50 | private val _editorStatusesFlow = MutableSharedFlow(
51 | extraBufferCapacity = 1,
52 | onBufferOverflow = BufferOverflow.DROP_OLDEST,
53 | )
54 | val editorStatusesFlow: SharedFlow = _editorStatusesFlow.asSharedFlow()
55 |
56 | private var _isEmptyFlow: MutableStateFlow = MutableStateFlow(null)
57 | var isEmptyFlow: StateFlow = _isEmptyFlow.asStateFlow()
58 |
59 | fun toggleBold() = execCommand(StatusCommand.BOLD)
60 |
61 | fun toggleItalic() = execCommand(StatusCommand.ITALIC)
62 |
63 | fun toggleStrikeThrough() = execCommand(StatusCommand.STRIKE_THROUGH)
64 |
65 | fun toggleUnderline() = execCommand(StatusCommand.UNDERLINE)
66 |
67 | fun toggleOrderedList() = execCommand(StatusCommand.ORDERED_LIST)
68 |
69 | fun toggleUnorderedList() = execCommand(StatusCommand.UNORDERED_LIST)
70 |
71 | fun toggleSubscript() = execCommand(StatusCommand.SUBSCRIPT)
72 |
73 | fun toggleSuperscript() = execCommand(StatusCommand.SUPERSCRIPT)
74 |
75 | fun removeFormat() = execCommand(OtherCommand.REMOVE_FORMAT)
76 |
77 | fun justify(justification: Justification) = execCommand(justification.execCommand)
78 |
79 | fun indent() = execCommand(OtherCommand.INDENT)
80 |
81 | fun outdent() = execCommand(OtherCommand.OUTDENT)
82 |
83 | fun setTextColor(color: JsColor) = execCommand(StatusCommand.TEXT_COLOR, color)
84 |
85 | fun setTextBackgroundColor(color: JsColor) = execCommand(StatusCommand.BACKGROUND_COLOR, color)
86 |
87 | fun setFontSize(@IntRange(from = FONT_MIN_SIZE, to = FONT_MAX_SIZE) fontSize: Int) {
88 | execCommand(StatusCommand.FONT_SIZE, fontSize)
89 | }
90 |
91 | fun undo() = execCommand(OtherCommand.UNDO)
92 |
93 | fun redo() = execCommand(OtherCommand.REDO)
94 |
95 | fun createLink(displayText: String?, url: String) {
96 | jsExecutor.executeImmediatelyAndRefreshToolbar(JsExecutableMethod("createLink", displayText, url))
97 | }
98 |
99 | fun unlink() = jsExecutor.executeImmediatelyAndRefreshToolbar(JsExecutableMethod("unlink"))
100 |
101 | private fun execCommand(command: ExecCommand, argument: Any? = null) {
102 | jsExecutor.executeImmediatelyAndRefreshToolbar(
103 | JsExecutableMethod(
104 | "document.execCommand",
105 | command.argumentName,
106 | false,
107 | argument,
108 | )
109 | )
110 | }
111 |
112 | // Parses the css formatted color string obtained from the js method queryCommandValue() into an easy to use ColorInt
113 | @ColorInt
114 | fun String.toColorIntOrNull(): Int? {
115 | if (!startsWith("rgb")) return null
116 |
117 | val (r, g, b) = filterNot { it in CHARACTERS_TO_REMOVE }.split(",").takeIf { it.size == 3 || it.size == 4 } ?: return null
118 |
119 | return Color.argb(255, r.toInt(), g.toInt(), b.toInt())
120 | }
121 |
122 | @JavascriptInterface
123 | fun reportCommandDataChange(
124 | isBold: Boolean,
125 | isItalic: Boolean,
126 | isStrikeThrough: Boolean,
127 | isUnderlined: Boolean,
128 | fontName: String,
129 | fontSize: String,
130 | textColor: String,
131 | backgroundColor: String,
132 | isLinkSelected: Boolean,
133 | isOrderedListSelected: Boolean,
134 | isUnorderedListSelected: Boolean,
135 | isSubscript: Boolean,
136 | isSuperscript: Boolean,
137 | isJustifyLeft: Boolean,
138 | isJustifyCenter: Boolean,
139 | isJustifyRight: Boolean,
140 | isJustifyFull: Boolean,
141 | ) {
142 | fun computeJustification(): Justification? = when {
143 | isJustifyLeft -> Justification.LEFT
144 | isJustifyCenter -> Justification.CENTER
145 | isJustifyRight -> Justification.RIGHT
146 | isJustifyFull -> Justification.FULL
147 | else -> null
148 | }
149 |
150 | coroutineScope.launch(defaultDispatcher) {
151 | editorStatuses.updateStatusesAtomically(
152 | isBold,
153 | isItalic,
154 | isStrikeThrough,
155 | isUnderlined,
156 | fontName,
157 | fontSize.toFloatOrNull(),
158 | textColor.toColorIntOrNull(),
159 | backgroundColor.toColorIntOrNull(),
160 | isLinkSelected,
161 | isOrderedListSelected,
162 | isUnorderedListSelected,
163 | isSubscript,
164 | isSuperscript,
165 | computeJustification(),
166 | )
167 | _editorStatusesFlow.emit(editorStatuses)
168 | }
169 | }
170 |
171 | @JavascriptInterface
172 | fun reportNewDocumentHeight(newHeight: Int) {
173 | coroutineScope.launch(mainDispatcher) {
174 | updateWebViewHeight(newHeight)
175 | }
176 | }
177 |
178 | @JavascriptInterface
179 | fun focusCursorOnScreen(left: Int, top: Int, right: Int, bottom: Int) {
180 | requestRectangleOnScreen(left, top, right, bottom)
181 | }
182 |
183 | @JavascriptInterface
184 | fun exportHtml(html: String) = notifyExportedHtml(html)
185 |
186 | @JavascriptInterface
187 | fun onEmptyBodyChanges(isBodyEmpty: Boolean) {
188 | coroutineScope.launch(defaultDispatcher) {
189 | _isEmptyFlow.emit(isBodyEmpty)
190 | }
191 | }
192 |
193 | companion object {
194 | private val CHARACTERS_TO_REMOVE = setOf('r', 'g', 'b', 'a', '(', ')', ' ')
195 | const val FONT_MIN_SIZE: Long = 1
196 | const val FONT_MAX_SIZE: Long = 7
197 | }
198 | }
199 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/JsColor.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor
19 |
20 | import androidx.annotation.ColorInt
21 |
22 | data class JsColor(@ColorInt val color: Int)
23 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/Justification.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor
19 |
20 | enum class Justification(val execCommand: StatusCommand) {
21 | LEFT(StatusCommand.JUSTIFY_LEFT),
22 | CENTER(StatusCommand.JUSTIFY_CENTER),
23 | RIGHT(StatusCommand.JUSTIFY_RIGHT),
24 | FULL(StatusCommand.JUSTIFY_FULL),
25 | }
26 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/RichHtmlEditorWebView.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor
19 |
20 | import android.annotation.SuppressLint
21 | import android.content.Context
22 | import android.graphics.Rect
23 | import android.os.Bundle
24 | import android.os.Parcelable
25 | import android.util.AttributeSet
26 | import android.view.AbsSavedState
27 | import android.view.ViewGroup
28 | import android.webkit.WebView
29 | import android.webkit.WebViewClient
30 | import androidx.annotation.ColorInt
31 | import androidx.annotation.IntRange
32 | import androidx.core.os.bundleOf
33 | import androidx.core.view.updateLayoutParams
34 | import com.infomaniak.lib.richhtmleditor.JsBridge.Companion.FONT_MAX_SIZE
35 | import com.infomaniak.lib.richhtmleditor.JsBridge.Companion.FONT_MIN_SIZE
36 | import com.infomaniak.lib.richhtmleditor.executor.HtmlSetter
37 | import com.infomaniak.lib.richhtmleditor.executor.JsExecutableMethod
38 | import com.infomaniak.lib.richhtmleditor.executor.JsExecutor
39 | import com.infomaniak.lib.richhtmleditor.executor.KeyboardOpener
40 | import com.infomaniak.lib.richhtmleditor.executor.ScriptCssInjector
41 | import com.infomaniak.lib.richhtmleditor.executor.ScriptCssInjector.CodeInjection
42 | import com.infomaniak.lib.richhtmleditor.executor.ScriptCssInjector.CodeInjection.InjectionType
43 | import com.infomaniak.lib.richhtmleditor.executor.SpellCheckHtmlSetter
44 | import com.infomaniak.lib.richhtmleditor.executor.StateSubscriber
45 | import kotlinx.coroutines.CoroutineName
46 | import kotlinx.coroutines.CoroutineScope
47 | import kotlinx.coroutines.DelicateCoroutinesApi
48 | import kotlinx.coroutines.Dispatchers
49 | import kotlinx.coroutines.Job
50 | import kotlinx.coroutines.flow.SharedFlow
51 | import kotlinx.coroutines.flow.StateFlow
52 | import kotlinx.coroutines.invoke
53 | import kotlinx.coroutines.launch
54 | import kotlinx.coroutines.newSingleThreadContext
55 | import kotlinx.coroutines.sync.Mutex
56 | import kotlinx.coroutines.sync.withLock
57 | import kotlin.math.roundToInt
58 |
59 | /**
60 | * A custom WebView designed to provide simple formatting and editing capabilities to an existing HTML content.
61 | *
62 | * The [RichHtmlEditorWebView] class utilizes the `contenteditable` attribute in HTML along with a combination of `execCommand`
63 | * and custom logic to enable editing and basic formatting of existing HTML.
64 | *
65 | * When the [RichHtmlEditorWebView] is instantiated it loads its HTML template and activates the necessary JavaScript mechanisms
66 | * for the editor to update different format statuses and function properly.
67 | *
68 | * To interact with the editor, you can either listen to format status notifications or call methods to modify the current format
69 | * such as [toggleBold].
70 | *
71 | * @see setHtml
72 | * @see subscribeToStates
73 | * @see addCss
74 | * @see addScript
75 | */
76 | class RichHtmlEditorWebView @JvmOverloads constructor(
77 | context: Context,
78 | attrs: AttributeSet? = null,
79 | defStyleAttr: Int = 0,
80 | ) : WebView(context, attrs, defStyleAttr) {
81 |
82 | private var keepKeyboardOpenedOnConfigurationChanged: Boolean = false
83 |
84 | private val documentInitializer = DocumentInitializer()
85 | private val stateSubscriber = StateSubscriber(this)
86 | private val htmlSetter = HtmlSetter(this)
87 | private val spellCheckHtmlSetter = SpellCheckHtmlSetter(this)
88 | private val jsExecutor = JsExecutor(this)
89 | private val scriptCssInjector = ScriptCssInjector(this)
90 | private val keyboardOpener = KeyboardOpener(this)
91 |
92 | private val jsBridgeJob = Job()
93 | private val jsBridge = JsBridge(
94 | coroutineScope = CoroutineScope(CoroutineName("JsBridgeCoroutine") + jsBridgeJob),
95 | jsExecutor = jsExecutor,
96 | notifyExportedHtml = ::notifyExportedHtml,
97 | requestRectangleOnScreen = ::requestRectangleOnScreen,
98 | updateWebViewHeight = ::updateWebViewHeight,
99 | )
100 |
101 | @OptIn(DelicateCoroutinesApi::class)
102 | private val htmlExportCoroutineScope = CoroutineScope(newSingleThreadContext("HtmlExportCoroutine"))
103 |
104 | /**
105 | * Flow that is notified everytime a subscribed [EditorStatuses] is updated.
106 | *
107 | * You can use this flow to listen to subscribed [EditorStatuses] and update your toolbar's UI accordingly to show which
108 | * formatting is enabled on the current selection.
109 | *
110 | * @see subscribeToStates
111 | */
112 | val editorStatusesFlow: SharedFlow by jsBridge::editorStatusesFlow
113 |
114 | /**
115 | * Describes if the content of the editor is empty or not.
116 | *
117 | * With some user inputs, the editor could visually look empty but still have a or other tags inside it. In this case
118 | * [isEmptyFlow] will still return false, so this value might not be suited for all usages.
119 | *
120 | * The flow is initialized to the value `null` until it receives its very first value from the javascript observer and won't
121 | * ever become `null` again.
122 | *
123 | * If the flow emits a new value it will always be different than the previous value, i.e. it's already distinctUntilChanged
124 | * by nature.
125 | */
126 | val isEmptyFlow: StateFlow by jsBridge::isEmptyFlow
127 |
128 | private var htmlExportCallback: MutableList<((html: String) -> Unit)> = mutableListOf()
129 |
130 | private val htmlExportMutex = Mutex()
131 |
132 | init {
133 | @SuppressLint("SetJavaScriptEnabled")
134 | settings.javaScriptEnabled = true
135 | isFocusableInTouchMode = true // Else the WebView can't be written in
136 |
137 | webViewClient = RichHtmlEditorWebViewClient(::notifyPageHasLoaded)
138 |
139 | withSpellCheck(true)
140 |
141 | addJavascriptInterface(jsBridge, "editor")
142 |
143 | stateSubscriber.executeWhenDomIsLoaded(null)
144 |
145 | val template = context.readAsset("editor_template.html")
146 | super.loadDataWithBaseURL("", template, "text/html", "UTF-8", null)
147 | }
148 |
149 | /**
150 | * Sets the HTML content that will be displayed inside of the editor.
151 | *
152 | * @param html A string containing the HTML content to be set.
153 | */
154 | fun setHtml(html: String) = htmlSetter.executeWhenDomIsLoaded(html)
155 |
156 | /**
157 | * Subscribes to a subset of states, ensuring that [editorStatusesFlow] triggers only when at least one of the specified
158 | * states changes. By default, when this method is never called, all available [StatusCommand] will be subscribed to.
159 | *
160 | * @param subscribedStates A set of [StatusCommand] to subscribe to. If `null`, all available [StatusCommand] will be
161 | * subscribed to.
162 | */
163 | fun subscribeToStates(subscribedStates: Set?) = stateSubscriber.executeWhenDomIsLoaded(subscribedStates)
164 |
165 |
166 | /**
167 | * Injects a custom CSS tag into the `` of the editor template.
168 | *
169 | * This method can be called repeatedly to add multiple tags. You don't need to wait for the [WebView]'s content to load. If
170 | * the [WebView]'s content hasn't finished loading, the method will wait and inject the tag once the page is ready. If the
171 | * page has already loaded, it injects the tag immediately.
172 | *
173 | * The content string to inject can span multiple lines and include any character, such as backquotes, backslashes,
174 | * dollar signs, and more.
175 | */
176 | fun addCss(css: String) = scriptCssInjector.executeWhenDomIsLoaded(CodeInjection(InjectionType.CSS, css))
177 |
178 | /**
179 | * Injects a custom attribute to the editor div to activate/deactivate spellchecking. By default, spellcheck is activated.
180 | */
181 | fun withSpellCheck(enable: Boolean) = spellCheckHtmlSetter.executeWhenDomIsLoaded(enable)
182 |
183 | /**
184 | * Injects a custom script tag into the `` of the editor template.
185 | *
186 | * This method can be called repeatedly to add multiple tags. You don't need to wait for the [WebView]'s content to load. If
187 | * the [WebView]'s content hasn't finished loading, the method will wait and inject the tag once the page is ready. If the
188 | * page has already loaded, it injects the tag immediately.
189 | *
190 | * The content string to inject can span multiple lines and include any character, such as backquotes, backslashes,
191 | * dollar signs, and more.
192 | *
193 | * The html loaded with [initEditor] is not guaranteed to be loaded inside the editor by the time this injected script is
194 | * loaded.
195 | * */
196 | fun addScript(script: String) = scriptCssInjector.executeWhenDomIsLoaded(CodeInjection(InjectionType.SCRIPT, script))
197 |
198 | fun toggleBold() = jsBridge.toggleBold()
199 | fun toggleItalic() = jsBridge.toggleItalic()
200 | fun toggleStrikeThrough() = jsBridge.toggleStrikeThrough()
201 | fun toggleUnderline() = jsBridge.toggleUnderline()
202 | fun toggleOrderedList() = jsBridge.toggleOrderedList()
203 | fun toggleUnorderedList() = jsBridge.toggleUnorderedList()
204 | fun toggleSubscript() = jsBridge.toggleSubscript()
205 | fun toggleSuperscript() = jsBridge.toggleSuperscript()
206 | fun removeFormat() = jsBridge.removeFormat()
207 | fun justify(justification: Justification) = jsBridge.justify(justification)
208 | fun indent() = jsBridge.indent()
209 | fun outdent() = jsBridge.outdent()
210 | fun setTextColor(@ColorInt color: Int) = jsBridge.setTextColor(JsColor(color))
211 | fun setTextBackgroundColor(@ColorInt color: Int) = jsBridge.setTextBackgroundColor(JsColor(color))
212 |
213 | /**
214 | * Updates the font size of the text.
215 | *
216 | * @param fontSize The new size of the text. This value's range constraint comes from the JavaScript `execCommand` method
217 | * called with the argument `fontSize`.
218 | */
219 | fun setFontSize(@IntRange(from = FONT_MIN_SIZE, to = FONT_MAX_SIZE) fontSize: Int) = jsBridge.setFontSize(fontSize)
220 | fun undo() = jsBridge.undo()
221 | fun redo() = jsBridge.redo()
222 | fun createLink(displayText: String?, url: String) = jsBridge.createLink(displayText?.takeIf { it.isNotBlank() }, url)
223 | fun unlink() = jsBridge.unlink()
224 |
225 | /**
226 | * Notifies the [RichHtmlEditorWebView] to setup the editor.
227 | *
228 | * This method is only required if you want to use your own custom WebViewClient. To use your own custom WebViewClient call
229 | * this method inside [WebViewClient.onPageFinished] of your [WebViewClient] so the editor can setup itself correctly.
230 | */
231 | fun notifyPageHasLoaded() {
232 | documentInitializer.setupDocument(this)
233 |
234 | stateSubscriber.notifyDomLoaded()
235 | htmlSetter.notifyDomLoaded()
236 | spellCheckHtmlSetter.notifyDomLoaded()
237 | jsExecutor.notifyDomLoaded()
238 | scriptCssInjector.notifyDomLoaded()
239 | keyboardOpener.notifyDomLoaded()
240 | }
241 |
242 | fun requestFocusAndOpenKeyboard() {
243 | keepKeyboardOpenedOnConfigurationChanged = true
244 | keyboardOpener.executeWhenDomIsLoaded(Unit)
245 | }
246 |
247 | fun exportHtml(resultCallback: (html: String) -> Unit) {
248 | htmlExportCoroutineScope.launch {
249 | htmlExportMutex.withLock {
250 | val notYetRunning = htmlExportCallback.isEmpty()
251 | htmlExportCallback.add(resultCallback)
252 | Dispatchers.Main {
253 | if (notYetRunning) jsExecutor.executeWhenDomIsLoaded(JsExecutableMethod("exportHtml"))
254 | }
255 | }
256 | }
257 | }
258 |
259 | override fun onSaveInstanceState(): Parcelable {
260 | val superState = super.onSaveInstanceState()
261 | return bundleOf(
262 | KEYBOARD_SHOULD_REOPEN_KEY to keepKeyboardOpenedOnConfigurationChanged,
263 | SUPER_STATE_KEY to superState,
264 | )
265 | }
266 |
267 | override fun onRestoreInstanceState(state: Parcelable?) {
268 | (state as Bundle?)?.getBoolean(KEYBOARD_SHOULD_REOPEN_KEY)?.let { keepKeyboardOpenedOnConfigurationChanged = it }
269 | super.onRestoreInstanceState(state?.getParcelableCompat(SUPER_STATE_KEY, AbsSavedState::class.java))
270 | }
271 |
272 | override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
273 | super.onFocusChanged(focused, direction, previouslyFocusedRect)
274 | if (focused) {
275 | jsExecutor.executeWhenDomIsLoaded(JsExecutableMethod("requestFocus"))
276 | if (keepKeyboardOpenedOnConfigurationChanged) keyboardOpener.executeWhenDomIsLoaded(Unit)
277 | } else {
278 | keepKeyboardOpenedOnConfigurationChanged = false
279 | }
280 | }
281 |
282 | override fun onDetachedFromWindow() {
283 | super.onDetachedFromWindow()
284 | keyboardOpener.removePendingListener()
285 | jsBridgeJob.cancel()
286 | }
287 |
288 | private fun notifyExportedHtml(html: String) {
289 | htmlExportCoroutineScope.launch {
290 | htmlExportMutex.withLock {
291 | Dispatchers.Main {
292 | htmlExportCallback.forEach { it.invoke(html) }
293 | }
294 | htmlExportCallback.clear()
295 | }
296 | }
297 | }
298 |
299 | private fun requestRectangleOnScreen(left: Int, top: Int, right: Int, bottom: Int) {
300 | val density: Float = resources.displayMetrics.density
301 |
302 | requestRectangleOnScreen(
303 | Rect(
304 | (left * density).roundToInt(),
305 | (top * density).roundToInt(),
306 | (right * density).roundToInt(),
307 | (bottom * density).roundToInt(),
308 | ),
309 | )
310 | }
311 |
312 | private fun updateWebViewHeight(newHeight: Int) {
313 | updateLayoutParams {
314 | height = newHeight
315 | }
316 | }
317 |
318 | // Prevent scrolling bug that makes the editor twitch
319 | override fun onOverScrolled(scrollX: Int, scrollY: Int, clampedX: Boolean, clampedY: Boolean) = Unit
320 |
321 | @Deprecated(
322 | "Use setHtml() instead to initialize the editor with the desired HTML content.",
323 | ReplaceWith("setHtml()", "com.infomaniak.lib.richhtmleditor")
324 | )
325 | override fun loadUrl(url: String) = unsupported()
326 |
327 | @Deprecated(
328 | "Use setHtml() instead to initialize the editor with the desired HTML content.",
329 | ReplaceWith("setHtml()", "com.infomaniak.lib.richhtmleditor")
330 | )
331 | override fun loadUrl(url: String, additionalHttpHeaders: MutableMap) = unsupported()
332 |
333 | @Deprecated(
334 | "Use setHtml() instead to initialize the editor with the desired HTML content.",
335 | ReplaceWith("setHtml()", "com.infomaniak.lib.richhtmleditor")
336 | )
337 | override fun loadData(data: String, mimeType: String?, encoding: String?) = unsupported()
338 |
339 | @Deprecated(
340 | "Use setHtml() instead to initialize the editor with the desired HTML content.",
341 | ReplaceWith("setHtml()", "com.infomaniak.lib.richhtmleditor")
342 | )
343 | override fun loadDataWithBaseURL(baseUrl: String?, data: String, mimeType: String?, encoding: String?, historyUrl: String?) {
344 | unsupported()
345 | }
346 |
347 | private fun unsupported() {
348 | throw UnsupportedOperationException("Use setHtml() instead")
349 | }
350 |
351 | companion object {
352 | // The id of this HTML tag is shared across multiple files and needs to remain the same
353 | const val EDITOR_ID = "editor"
354 |
355 | private const val KEYBOARD_SHOULD_REOPEN_KEY = "keyboardShouldReopen"
356 | private const val SUPER_STATE_KEY = "superState"
357 | }
358 | }
359 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/RichHtmlEditorWebViewClient.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor
19 |
20 | import android.webkit.WebView
21 | import android.webkit.WebViewClient
22 |
23 |
24 | /**
25 | * A custom [WebViewClient] used to notify the [RichHtmlEditorWebView] editor of when the template has finished loading.
26 | * [RichHtmlEditorWebView.notifyPageHasLoaded] needs to be called inside [WebViewClient.onPageFinished] so the editor can work
27 | * properly.
28 | */
29 | class RichHtmlEditorWebViewClient(private val onPageLoaded: () -> Unit) : WebViewClient() {
30 | override fun onPageFinished(webView: WebView, url: String?) = onPageLoaded()
31 | }
32 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/StatusCommand.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor
19 |
20 | enum class StatusCommand(override val argumentName: String, val statusType: StatusType) : ExecCommand {
21 | BOLD("bold", StatusType.STATE),
22 | ITALIC("italic", StatusType.STATE),
23 | STRIKE_THROUGH("strikeThrough", StatusType.STATE),
24 | UNDERLINE("underline", StatusType.STATE),
25 | ORDERED_LIST("insertOrderedList", StatusType.STATE),
26 | UNORDERED_LIST("insertUnorderedList", StatusType.STATE),
27 | SUBSCRIPT("subscript", StatusType.STATE),
28 | SUPERSCRIPT("superscript", StatusType.STATE),
29 | JUSTIFY_LEFT("justifyLeft", StatusType.STATE),
30 | JUSTIFY_CENTER("justifyCenter", StatusType.STATE),
31 | JUSTIFY_RIGHT("justifyRight", StatusType.STATE),
32 | JUSTIFY_FULL("justifyFull", StatusType.STATE),
33 | FONT_NAME("fontName", StatusType.VALUE),
34 | FONT_SIZE("fontSize", StatusType.VALUE),
35 | TEXT_COLOR("foreColor", StatusType.VALUE),
36 | BACKGROUND_COLOR("backColor", StatusType.VALUE),
37 | CREATE_LINK("", StatusType.COMPLEX), // This value is not meant to be called by JsBride's execCommand()
38 | }
39 |
40 | enum class OtherCommand(override val argumentName: String) : ExecCommand {
41 | REMOVE_FORMAT("removeFormat"),
42 | INDENT("indent"),
43 | OUTDENT("outdent"),
44 | UNDO("undo"),
45 | REDO("redo"),
46 | }
47 |
48 | interface ExecCommand {
49 | val argumentName: String
50 | }
51 |
52 | enum class StatusType { STATE, VALUE, COMPLEX }
53 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/Utils.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor
19 |
20 | import androidx.annotation.ColorInt
21 |
22 | // TODO: This method might not be enough to escape user inputs and prevent access to JS code execution
23 | fun looselyEscapeAsStringLiteralForJs(string: String): String {
24 | val stringBuilder = StringBuilder("`")
25 |
26 | string.forEach {
27 | val char = when (it) {
28 | '`' -> "\\`"
29 | '\\' -> "\\\\"
30 | '$' -> "\\$"
31 | else -> it
32 | }
33 | stringBuilder.append(char)
34 | }
35 |
36 | return stringBuilder.append("`").toString()
37 | }
38 |
39 | fun encodeArgsForJs(value: Any?): String {
40 | return when (value) {
41 | null -> "null"
42 | is String -> looselyEscapeAsStringLiteralForJs(value)
43 | is Boolean, is Number -> value.toString()
44 | is JsColor -> "'${colorToRgbHex(value.color)}'"
45 | else -> throw NotImplementedError("Encoding ${value::class} for JS is not yet implemented")
46 | }
47 | }
48 |
49 | @OptIn(ExperimentalStdlibApi::class)
50 | private fun colorToRgbHex(@ColorInt color: Int) = color.toHexString(HexFormat.UpperCase).takeLast(6)
51 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/executor/HtmlSetter.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor.executor
19 |
20 | import android.webkit.WebView
21 | import com.infomaniak.lib.richhtmleditor.RichHtmlEditorWebView.Companion.EDITOR_ID
22 | import com.infomaniak.lib.richhtmleditor.looselyEscapeAsStringLiteralForJs
23 |
24 | internal class HtmlSetter(private val webView: WebView) : JsLifecycleAwareExecutor() {
25 |
26 | override fun executeImmediately(value: String) = webView.insertUserHtml(value)
27 |
28 | private fun WebView.insertUserHtml(html: String) {
29 | val escapedHtmlStringLiteral = looselyEscapeAsStringLiteralForJs(html)
30 | evaluateJavascript(
31 | """document.getElementById("$EDITOR_ID").innerHTML = $escapedHtmlStringLiteral""",
32 | null
33 | )
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/executor/JsExecutableMethod.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor.executor
19 |
20 | import android.webkit.WebView
21 | import com.infomaniak.lib.richhtmleditor.encodeArgsForJs
22 |
23 | class JsExecutableMethod(
24 | private val methodName: String,
25 | private vararg val args: Any?,
26 | resultCallback: ((String) -> Unit)? = null,
27 | ) {
28 | private val callbacks: MutableList<(String) -> Unit> = resultCallback?.let { mutableListOf(it) } ?: mutableListOf()
29 |
30 | fun executeOn(webView: WebView) {
31 | val formattedArgs = args.joinToString(transform = ::encodeArgsForJs)
32 | val jsCode = "$methodName($formattedArgs)"
33 |
34 | val evaluationCallback: ((String) -> Unit)? = if (callbacks.isEmpty()) {
35 | null
36 | } else {
37 | { jsExecutionOutput ->
38 | callbacks.forEach { callback -> callback(jsExecutionOutput) }
39 | }
40 | }
41 |
42 | webView.evaluateJavascript(jsCode, evaluationCallback)
43 | }
44 |
45 | fun addCallback(callback: (String) -> Unit) {
46 | callbacks.add(callback)
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/executor/JsExecutor.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor.executor
19 |
20 | import android.webkit.WebView
21 |
22 | internal class JsExecutor(private val webView: WebView) : JsLifecycleAwareExecutor() {
23 |
24 | override fun executeImmediately(value: JsExecutableMethod) {
25 | value.executeOn(webView)
26 | }
27 |
28 | fun executeImmediatelyAndRefreshToolbar(method: JsExecutableMethod) {
29 | method.addCallback { JsExecutableMethod("reportSelectionStateChangedIfNecessary").executeOn(webView) }
30 | executeImmediately(method)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/executor/JsLifecycleAwareExecutor.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor.executor
19 |
20 | internal abstract class JsLifecycleAwareExecutor {
21 |
22 | private var hasDomLoaded = false
23 | private val objectsWaitingForDom = mutableListOf()
24 |
25 | fun executeWhenDomIsLoaded(value: T): Unit = synchronized(lock = this) {
26 | if (hasDomLoaded) executeImmediately(value) else objectsWaitingForDom.add(value)
27 | }
28 |
29 | fun notifyDomLoaded() = synchronized(lock = this) {
30 | hasDomLoaded = true
31 | objectsWaitingForDom.forEach(::executeImmediately)
32 | objectsWaitingForDom.clear()
33 | }
34 |
35 | abstract fun executeImmediately(value: T)
36 | }
37 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/executor/KeyboardOpener.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor.executor
19 |
20 | import android.app.Activity
21 | import android.view.View
22 | import android.view.ViewTreeObserver
23 | import android.view.inputmethod.InputMethodManager
24 |
25 | internal class KeyboardOpener(private val view: View) : JsLifecycleAwareExecutor() {
26 |
27 | private var listener: ViewTreeObserver.OnWindowFocusChangeListener? = null
28 |
29 | override fun executeImmediately(value: Unit) {
30 | if (view.requestFocus()) {
31 | if (view.hasWindowFocus()) {
32 | openKeyboard()
33 | } else {
34 | // The window won't have the focus most of the time when the configuration changes and we want to reopen the
35 | // keyboard right away. When this happen, we need to wait for the window to get the focus before opening the
36 | // keyboard.
37 | listener = object : ViewTreeObserver.OnWindowFocusChangeListener {
38 | override fun onWindowFocusChanged(hasFocus: Boolean) {
39 | if (hasFocus) {
40 | openKeyboard()
41 | view.viewTreeObserver.removeOnWindowFocusChangeListener(this)
42 | }
43 | }
44 | }
45 |
46 | view.viewTreeObserver.addOnWindowFocusChangeListener(listener)
47 | }
48 | }
49 | }
50 |
51 | fun removePendingListener() {
52 | view.viewTreeObserver.removeOnWindowFocusChangeListener(listener)
53 | listener = null
54 | }
55 |
56 | private fun openKeyboard() {
57 | val inputMethodManager = view.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
58 | inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/executor/ScriptCssInjector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor.executor
19 |
20 | import android.webkit.WebView
21 | import com.infomaniak.lib.richhtmleditor.executor.ScriptCssInjector.CodeInjection
22 | import com.infomaniak.lib.richhtmleditor.executor.ScriptCssInjector.CodeInjection.InjectionType
23 | import com.infomaniak.lib.richhtmleditor.injectCss
24 | import com.infomaniak.lib.richhtmleditor.injectScript
25 |
26 | internal class ScriptCssInjector(private val webView: WebView) : JsLifecycleAwareExecutor() {
27 |
28 | override fun executeImmediately(value: CodeInjection): Unit = with(webView) {
29 | when (value.type) {
30 | InjectionType.SCRIPT -> injectScript(value.code)
31 | InjectionType.CSS -> injectCss(value.code)
32 | }
33 | }
34 |
35 | data class CodeInjection(val type: InjectionType, val code: String) {
36 | enum class InjectionType { SCRIPT, CSS }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/executor/SpellCheckHtmlSetter.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor.executor
19 |
20 | import android.webkit.WebView
21 | import com.infomaniak.lib.richhtmleditor.RichHtmlEditorWebView.Companion.EDITOR_ID
22 | import com.infomaniak.lib.richhtmleditor.encodeArgsForJs
23 |
24 | internal class SpellCheckHtmlSetter(private val webView: WebView) : JsLifecycleAwareExecutor() {
25 |
26 | override fun executeImmediately(value: Boolean) = webView.insertSpellCheckValue(value)
27 |
28 | private fun WebView.insertSpellCheckValue(enable: Boolean) {
29 | evaluateJavascript(
30 | """document.getElementById("$EDITOR_ID").setAttribute("spellcheck", ${encodeArgsForJs(enable)})""",
31 | null
32 | )
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/rich-html-editor/src/main/java/com/infomaniak/lib/richhtmleditor/executor/StateSubscriber.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor.executor
19 |
20 | import android.webkit.WebView
21 | import com.infomaniak.lib.richhtmleditor.StatusCommand
22 | import com.infomaniak.lib.richhtmleditor.StatusType
23 | import com.infomaniak.lib.richhtmleditor.injectScript
24 |
25 | internal class StateSubscriber(private val webView: WebView) : JsLifecycleAwareExecutor?>() {
26 |
27 | override fun executeImmediately(value: Set?) {
28 | webView.injectScript(createSubscribedStatesScript(value), "subscribedStates")
29 | }
30 |
31 | private fun createSubscribedStatesScript(inputSubscribedStates: Set?): String {
32 | val subscribedStates = inputSubscribedStates ?: StatusCommand.entries
33 |
34 | val stateCommands = mutableListOf()
35 | val valueCommands = mutableListOf()
36 |
37 | subscribedStates.forEach {
38 | when (it.statusType) {
39 | StatusType.STATE -> stateCommands.add(it)
40 | StatusType.VALUE -> valueCommands.add(it)
41 | StatusType.COMPLEX -> Unit
42 | }
43 | }
44 |
45 | val firstLine = generateConstTable("stateCommands", stateCommands)
46 | val secondLine = generateConstTable("valueCommands", valueCommands)
47 |
48 | val areLinksSubscribedTo = subscribedStates.contains(StatusCommand.CREATE_LINK)
49 | val reportLinkStatusLine = "var REPORT_LINK_STATUS = $areLinksSubscribedTo"
50 |
51 | return "$firstLine\n$secondLine\n$reportLinkStatusLine"
52 | }
53 |
54 | private fun generateConstTable(name: String, commands: Collection): String {
55 | return commands.joinToString(prefix = "var $name = [ ", postfix = " ]") { "'${it.argumentName}'" }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/sample/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.android.application)
3 | alias(libs.plugins.jetbrains.kotlin.android)
4 | }
5 |
6 | val sharedMinSdk: Int by rootProject.extra
7 | val sharedCompileSdk: Int by rootProject.extra
8 | val javaVersion: JavaVersion by rootProject.extra
9 |
10 | android {
11 | namespace = "com.infomaniak.lib.richhtmleditor.sample"
12 | compileSdk = sharedCompileSdk
13 |
14 | defaultConfig {
15 | applicationId = "com.infomaniak.lib.richhtmleditor.sample"
16 | minSdk = sharedMinSdk
17 | targetSdk = sharedCompileSdk
18 | versionCode = 1
19 | versionName = "1.0"
20 | }
21 |
22 | buildTypes {
23 | release {
24 | isMinifyEnabled = true
25 | isShrinkResources = true
26 | proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
27 | }
28 | }
29 | compileOptions {
30 | sourceCompatibility = javaVersion
31 | targetCompatibility = javaVersion
32 | }
33 | kotlinOptions {
34 | jvmTarget = javaVersion.toString()
35 | }
36 | buildFeatures {
37 | viewBinding = true
38 | }
39 | }
40 |
41 | dependencies {
42 | implementation(project(":rich-html-editor"))
43 |
44 | implementation(libs.androidx.core.ktx)
45 | implementation(libs.androidx.appcompat)
46 | implementation(libs.material)
47 | implementation(libs.androidx.constraintlayout)
48 | implementation(libs.androidx.navigation.fragment.ktx)
49 | implementation(libs.androidx.navigation.ui.ktx)
50 | }
51 |
--------------------------------------------------------------------------------
/sample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
18 |
20 |
21 |
22 |
23 |
35 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/sample/src/main/assets/editor_custom_css.css:
--------------------------------------------------------------------------------
1 | html {
2 | background: #888888;
3 | }
4 |
--------------------------------------------------------------------------------
/sample/src/main/assets/example1.html:
--------------------------------------------------------------------------------
1 |
Hello World
2 | Yo
3 |
--------------------------------------------------------------------------------
/sample/src/main/assets/example2.html:
--------------------------------------------------------------------------------
1 |
Hello
2 |
3 |
Goodbye
4 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/infomaniak/lib/richhtmleditor/sample/EditorSampleFragment.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor.sample
19 |
20 | import android.app.Activity
21 | import android.graphics.Color
22 | import android.os.Bundle
23 | import android.util.Log
24 | import android.view.LayoutInflater
25 | import android.view.View
26 | import android.view.ViewGroup
27 | import android.view.inputmethod.InputMethodManager
28 | import androidx.core.view.forEach
29 | import androidx.core.view.isVisible
30 | import androidx.fragment.app.Fragment
31 | import androidx.fragment.app.activityViewModels
32 | import androidx.lifecycle.lifecycleScope
33 | import com.google.android.material.dialog.MaterialAlertDialogBuilder
34 | import com.infomaniak.lib.richhtmleditor.Justification
35 | import com.infomaniak.lib.richhtmleditor.sample.databinding.CreateLinkTextInputBinding
36 | import com.infomaniak.lib.richhtmleditor.sample.databinding.FragmentEditorSampleBinding
37 | import kotlinx.coroutines.flow.filterNotNull
38 | import kotlinx.coroutines.flow.launchIn
39 | import kotlinx.coroutines.flow.onEach
40 | import kotlinx.coroutines.launch
41 | import java.io.BufferedReader
42 |
43 | class EditorSampleFragment : Fragment() {
44 |
45 | private var _binding: FragmentEditorSampleBinding? = null
46 | private val binding get() = _binding!! // This property is only valid between onCreateView and onDestroyView
47 |
48 | private val editorSampleViewModel: EditorSampleViewModel by activityViewModels()
49 |
50 | private val createLinkDialog by lazy { CreateLinkDialog() }
51 |
52 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
53 | return FragmentEditorSampleBinding.inflate(inflater, container, false).also { _binding = it }.root
54 | }
55 |
56 | override fun onViewCreated(view: View, savedInstanceState: Bundle?): Unit = with(binding) {
57 | super.onViewCreated(view, savedInstanceState)
58 |
59 | setToolbarEnabledStatus(false)
60 |
61 | setEditorContent()
62 | editor.apply {
63 | // You can configure the editor like this:
64 | // addCss(readAsset("editor_custom_css.css"))
65 | // addScript("document.body.style['background'] = '#00FFFF'")
66 | // subscribeToStates(setOf(StatusCommand.BOLD, StatusCommand.ITALIC))
67 | // withSpellCheck(false)
68 |
69 | isVisible = true
70 | setOnFocusChangeListener { _, hasFocus -> setToolbarEnabledStatus(hasFocus) }
71 |
72 | isEmptyFlow
73 | .filterNotNull()
74 | .onEach { isEditorEmpty -> placeholder.isVisible = isEditorEmpty }
75 | .launchIn(lifecycleScope)
76 | }
77 |
78 | setEditorButtonClickListeners()
79 | observeEditorStatusUpdates()
80 | }
81 |
82 | private fun setEditorContent() {
83 | lifecycleScope.launch {
84 | editorSampleViewModel.editorReloader.load(binding.editor, readAsset("example1.html"))
85 | }
86 | }
87 |
88 | private fun setEditorButtonClickListeners() = with(binding) {
89 | buttonBold.setOnClickListener { editor.toggleBold() }
90 | buttonItalic.setOnClickListener { editor.toggleItalic() }
91 | buttonStrikeThrough.setOnClickListener { editor.toggleStrikeThrough() }
92 | buttonUnderline.setOnClickListener { editor.toggleUnderline() }
93 | buttonRemoveFormat.setOnClickListener { editor.removeFormat() }
94 | buttonLink.setOnClickListener {
95 | if (buttonLink.isActivated) {
96 | editor.unlink()
97 | } else {
98 | createLinkDialog.show("", "") { url, displayText ->
99 | editor.createLink(displayText, url)
100 | }
101 | }
102 | }
103 | orderedList.setOnClickListener { editor.toggleOrderedList() }
104 | unorderedList.setOnClickListener { editor.toggleUnorderedList() }
105 | buttonSubscript.setOnClickListener { editor.toggleSubscript() }
106 | buttonSuperscript.setOnClickListener { editor.toggleSuperscript() }
107 | buttonOutdent.setOnClickListener { editor.outdent() }
108 | buttonIndent.setOnClickListener { editor.indent() }
109 | justifyLeft.setOnClickListener { editor.justify(Justification.LEFT) }
110 | justifyCenter.setOnClickListener { editor.justify(Justification.CENTER) }
111 | justifyRight.setOnClickListener { editor.justify(Justification.RIGHT) }
112 | justifyFull.setOnClickListener { editor.justify(Justification.FULL) }
113 |
114 | buttonExportHtml.setOnClickListener { editor.exportHtml { html -> Log.d("editor", "Output html: $html") } }
115 |
116 | removeEditorFocusButton.setOnClickListener {
117 | editor.clearFocus()
118 | val inputMethodManager = requireContext().getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
119 | inputMethodManager.hideSoftInputFromWindow(editor.windowToken, 0)
120 | }
121 | focusEditorButton.setOnClickListener { editor.requestFocusAndOpenKeyboard() }
122 |
123 | textColorRed.setOnClickListener { editor.setTextColor(RED) }
124 | textColorBlue.setOnClickListener { editor.setTextColor(BLUE) }
125 | textBackgroundColorRed.setOnClickListener { editor.setTextBackgroundColor(RED) }
126 | textBackgroundColorBlue.setOnClickListener { editor.setTextBackgroundColor(BLUE) }
127 |
128 | fontSmallButton.setOnClickListener { editor.setFontSize(SMALL_FONT_SIZE) }
129 | fontMediumButton.setOnClickListener { editor.setFontSize(MEDIUM_FONT_SIZE) }
130 | fontBigButton.setOnClickListener { editor.setFontSize(BIG_FONT_SIZE) }
131 | undoButton.setOnClickListener { editor.undo() }
132 | redoButton.setOnClickListener { editor.redo() }
133 | }
134 |
135 | private fun observeEditorStatusUpdates() = with(binding) {
136 | viewLifecycleOwner.lifecycleScope.launch {
137 | editor.editorStatusesFlow.collect {
138 | buttonBold.isActivated = it.isBold
139 | buttonItalic.isActivated = it.isItalic
140 | buttonStrikeThrough.isActivated = it.isStrikeThrough
141 | buttonUnderline.isActivated = it.isUnderlined
142 |
143 | buttonLink.isActivated = it.isLinkSelected
144 |
145 | orderedList.isActivated = it.isOrderedListSelected
146 | unorderedList.isActivated = it.isUnorderedListSelected
147 | buttonSubscript.isActivated = it.isSubscript
148 | buttonSuperscript.isActivated = it.isSuperscript
149 |
150 | justifyLeft.isActivated = it.justification == Justification.LEFT
151 | justifyCenter.isActivated = it.justification == Justification.CENTER
152 | justifyRight.isActivated = it.justification == Justification.RIGHT
153 | justifyFull.isActivated = it.justification == Justification.FULL
154 | }
155 | }
156 | }
157 |
158 | override fun onDestroyView() {
159 | editorSampleViewModel.editorReloader.save(binding.editor)
160 | super.onDestroyView()
161 | _binding = null
162 | }
163 |
164 | private fun readAsset(fileName: String): String {
165 | return requireContext().assets
166 | .open(fileName)
167 | .bufferedReader()
168 | .use(BufferedReader::readText)
169 | }
170 |
171 | private fun setToolbarEnabledStatus(isEnabled: Boolean) = with(binding) {
172 | toolbarLayout.forEach { view -> view.isEnabled = isEnabled }
173 | colorLayout.forEach { view -> view.isEnabled = isEnabled }
174 | fontLayout.forEach { view -> view.isEnabled = isEnabled }
175 | }
176 |
177 | inner class CreateLinkDialog {
178 | private var callback: ((String, String) -> Unit)? = null
179 | private var binding: CreateLinkTextInputBinding
180 |
181 | private val dialog = with(CreateLinkTextInputBinding.inflate(layoutInflater)) {
182 | binding = this
183 | MaterialAlertDialogBuilder(requireContext())
184 | .setView(root)
185 | .setTitle(R.string.link_dialog_title)
186 | .setPositiveButton(R.string.link_dialog_title_button_positive) { _, _ ->
187 | callback?.invoke(
188 | textInputEditTextUrl.text.toString(),
189 | textInputEditTextPlaceholder.text.toString()
190 | )
191 | }
192 | .setNegativeButton(R.string.link_dialog_title_button_negative, null)
193 | .create()
194 | }
195 |
196 | fun show(url: String? = null, text: String?, callback: (String, String) -> Unit) {
197 | this.callback = callback
198 | with(binding) {
199 | textInputEditTextUrl.setText(url ?: "")
200 | textInputEditTextPlaceholder.setText(text ?: "")
201 | }
202 | dialog.show()
203 | }
204 | }
205 |
206 | companion object {
207 | private val RED = Color.parseColor("#FF0000")
208 | private val BLUE = Color.parseColor("#0000FF")
209 |
210 | private const val SMALL_FONT_SIZE = 2
211 | private const val MEDIUM_FONT_SIZE = 4
212 | private const val BIG_FONT_SIZE = 6
213 | }
214 | }
215 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/infomaniak/lib/richhtmleditor/sample/EditorSampleViewModel.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor.sample
19 |
20 | import androidx.lifecycle.ViewModel
21 | import androidx.lifecycle.viewModelScope
22 | import com.infomaniak.lib.richhtmleditor.EditorReloader
23 |
24 | class EditorSampleViewModel : ViewModel() {
25 | val editorReloader = EditorReloader(viewModelScope)
26 | }
27 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/infomaniak/lib/richhtmleditor/sample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Infomaniak Rich HTML Editor - Android
3 | * Copyright (C) 2024 Infomaniak Network SA
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU General Public License as published by
7 | * the Free Software Foundation, either version 3 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU General Public License
16 | * along with this program. If not, see .
17 | */
18 | package com.infomaniak.lib.richhtmleditor.sample
19 |
20 | import android.os.Bundle
21 | import android.webkit.WebView
22 | import androidx.appcompat.app.AppCompatActivity
23 | import com.infomaniak.lib.richhtmleditor.sample.databinding.ActivityMainBinding
24 |
25 | class MainActivity : AppCompatActivity() {
26 |
27 | private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
28 |
29 | override fun onCreate(savedInstanceState: Bundle?) {
30 | super.onCreate(savedInstanceState)
31 | setContentView(binding.root)
32 |
33 | WebView.setWebContentsDebuggingEnabled(true)
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/sample/src/main/res/color/background_editor_button.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_indent.xml:
--------------------------------------------------------------------------------
1 |
18 |
25 |
26 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_justify_center.xml:
--------------------------------------------------------------------------------
1 |
18 |
24 |
25 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_justify_full.xml:
--------------------------------------------------------------------------------
1 |
18 |
24 |
25 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_justify_left.xml:
--------------------------------------------------------------------------------
1 |
18 |
25 |
26 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_justify_right.xml:
--------------------------------------------------------------------------------
1 |
18 |
25 |
26 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
18 |
23 |
26 |
31 |
36 |
41 |
46 |
51 |
56 |
61 |
66 |
71 |
76 |
81 |
86 |
91 |
96 |
101 |
106 |
111 |
116 |
121 |
126 |
131 |
136 |
141 |
146 |
151 |
156 |
161 |
166 |
171 |
176 |
181 |
186 |
187 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
18 |
24 |
25 |
26 |
32 |
35 |
38 |
39 |
40 |
41 |
47 |
48 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_ordered_list.xml:
--------------------------------------------------------------------------------
1 |
18 |
23 |
26 |
29 |
32 |
35 |
38 |
41 |
42 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_outdent.xml:
--------------------------------------------------------------------------------
1 |
18 |
25 |
26 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_redo.xml:
--------------------------------------------------------------------------------
1 |
18 |
25 |
26 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_subscript.xml:
--------------------------------------------------------------------------------
1 |
18 |
24 |
25 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_superscript.xml:
--------------------------------------------------------------------------------
1 |
18 |
24 |
25 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_undo.xml:
--------------------------------------------------------------------------------
1 |
18 |
25 |
26 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/ic_unordered_list.xml:
--------------------------------------------------------------------------------
1 |
18 |
23 |
26 |
29 |
32 |
35 |
38 |
41 |
42 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
18 |
25 |
26 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/create_link_text_input.xml:
--------------------------------------------------------------------------------
1 |
18 |
23 |
24 |
30 |
31 |
36 |
37 |
38 |
39 |
44 |
45 |
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/fragment_editor_sample.xml:
--------------------------------------------------------------------------------
1 |
18 |
26 |
27 |
34 |
35 |
41 |
42 |
47 |
48 |
54 |
55 |
61 |
62 |
68 |
69 |
75 |
76 |
82 |
83 |
89 |
90 |
91 |
92 |
98 |
99 |
105 |
106 |
107 |
108 |
114 |
115 |
121 |
122 |
123 |
124 |
130 |
131 |
137 |
138 |
139 |
140 |
146 |
147 |
153 |
154 |
160 |
161 |
167 |
168 |
169 |
170 |
171 |
172 |
176 |
177 |
184 |
185 |
189 |
190 |
197 |
198 |
205 |
206 |
207 |
208 |
211 |
212 |
217 |
218 |
223 |
224 |
230 |
231 |
238 |
239 |
246 |
247 |
253 |
254 |
261 |
262 |
269 |
270 |
271 |
272 |
273 |
274 |
279 |
280 |
286 |
287 |
294 |
295 |
302 |
303 |
310 |
311 |
315 |
316 |
323 |
324 |
331 |
332 |
333 |
334 |
338 |
339 |
343 |
344 |
347 |
348 |
356 |
357 |
362 |
363 |
364 |
365 |
380 |
381 |
382 |
383 |
384 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/sample/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/sample/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/sample/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/sample/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/sample/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/sample/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Infomaniak/android-rich-html-editor/81ab78ddc183c688af6698eaacc150fd17917644/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/sample/src/main/res/navigation/nav_graph.xml:
--------------------------------------------------------------------------------
1 |
18 |
23 |
24 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/sample/src/main/res/values-night/colors.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 | #F1F1F1
20 | #9F9F9F
21 | #666666
22 |
23 |
--------------------------------------------------------------------------------
/sample/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/sample/src/main/res/values-v23/themes.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 |
25 |
26 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 | #FF000000
20 | #FFFFFFFF
21 |
22 | #333333
23 | #666666
24 | #9F9F9F
25 |
26 | #888888
27 |
28 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 | 250dp
20 |
21 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 | Editor sample
20 |
21 | URL
22 | Name
23 | Insert a URL
24 | Add
25 | Cancel
26 | Link text:\u0020
27 | Link url:\u0020
28 |
29 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/style.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 |
24 |
25 |
31 |
32 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/sample/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
18 |
23 |
24 |
25 |
29 |
30 |
36 |
37 |
--------------------------------------------------------------------------------
/sample/src/main/res/xml/network_security_config.xml:
--------------------------------------------------------------------------------
1 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google {
4 | content {
5 | includeGroupByRegex("com\\.android.*")
6 | includeGroupByRegex("com\\.google.*")
7 | includeGroupByRegex("androidx.*")
8 | }
9 | }
10 | mavenCentral()
11 | gradlePluginPortal()
12 | }
13 | }
14 | dependencyResolutionManagement {
15 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
16 | repositories {
17 | google()
18 | mavenCentral()
19 | }
20 | }
21 |
22 | rootProject.name = "editor"
23 | include(":sample")
24 | include(":rich-html-editor")
25 |
--------------------------------------------------------------------------------