@momo-kits/calculator-keyboard 0.125.4-rc.7 → 0.150.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Dũng (Wem)
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # react-native-calculator-keyboard
2
+
3
+ react native calculator keyboard
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ npm install react-native-calculator-keyboard
9
+ ```
10
+
11
+ ## Usage
12
+
13
+
14
+ ```js
15
+ import { CalculatorKeyboardView } from "react-native-calculator-keyboard";
16
+
17
+ // ...
18
+
19
+ <CalculatorKeyboardView color="tomato" />
20
+ ```
21
+
22
+
23
+ ## Contributing
24
+
25
+ See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
26
+
27
+ ## License
28
+
29
+ MIT
30
+
31
+ ---
32
+
33
+ Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
@@ -0,0 +1,101 @@
1
+ buildscript {
2
+ // Buildscript is evaluated before everything else so we can't use getExtOrDefault
3
+ def kotlin_version = rootProject.ext.has("kotlinVersion") ? rootProject.ext.get("kotlinVersion") : project.properties["CalculatorKeyboard_kotlinVersion"]
4
+
5
+ repositories {
6
+ google()
7
+ mavenCentral()
8
+ }
9
+
10
+ dependencies {
11
+ classpath "com.android.tools.build:gradle:7.2.1"
12
+ // noinspection DifferentKotlinGradleVersion
13
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
14
+ }
15
+ }
16
+
17
+ def reactNativeArchitectures() {
18
+ def value = rootProject.getProperties().get("reactNativeArchitectures")
19
+ return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
20
+ }
21
+
22
+ def isNewArchitectureEnabled() {
23
+ return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true"
24
+ }
25
+
26
+ apply plugin: "com.android.library"
27
+ apply plugin: "kotlin-android"
28
+
29
+ if (isNewArchitectureEnabled()) {
30
+ apply plugin: "com.facebook.react"
31
+ }
32
+
33
+ def getExtOrDefault(name) {
34
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["CalculatorKeyboard_" + name]
35
+ }
36
+
37
+ def getExtOrIntegerDefault(name) {
38
+ return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["CalculatorKeyboard_" + name]).toInteger()
39
+ }
40
+
41
+ def supportsNamespace() {
42
+ def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
43
+ def major = parsed[0].toInteger()
44
+ def minor = parsed[1].toInteger()
45
+
46
+ // Namespace support was added in 7.3.0
47
+ return (major == 7 && minor >= 3) || major >= 8
48
+ }
49
+
50
+ android {
51
+ if (supportsNamespace()) {
52
+ namespace "com.calculatorkeyboard"
53
+
54
+ sourceSets {
55
+ main {
56
+ manifest.srcFile "src/main/AndroidManifestNew.xml"
57
+ }
58
+ }
59
+ }
60
+
61
+ compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
62
+
63
+ defaultConfig {
64
+ minSdkVersion getExtOrIntegerDefault("minSdkVersion")
65
+ targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
66
+
67
+ }
68
+
69
+ buildTypes {
70
+ release {
71
+ minifyEnabled false
72
+ }
73
+ }
74
+
75
+ lintOptions {
76
+ disable "GradleCompatible"
77
+ }
78
+
79
+ compileOptions {
80
+ sourceCompatibility JavaVersion.VERSION_1_8
81
+ targetCompatibility JavaVersion.VERSION_1_8
82
+ }
83
+ }
84
+
85
+ repositories {
86
+ mavenCentral()
87
+ google()
88
+ }
89
+
90
+ def kotlin_version = getExtOrDefault("kotlinVersion")
91
+
92
+ dependencies {
93
+ // For < 0.71, this will be from the local maven repo
94
+ // For > 0.71, this will be replaced by `com.facebook.react:react-android:$version` by react gradle plugin
95
+ //noinspection GradleDynamicVersion
96
+ implementation "com.facebook.react:react-native:+"
97
+ implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
98
+ implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
99
+ implementation("org.mariuszgromada.math:MathParser.org-mXparser:5.2.1")
100
+ }
101
+
@@ -0,0 +1,5 @@
1
+ CalculatorKeyboard_kotlinVersion=1.7.0
2
+ CalculatorKeyboard_minSdkVersion=21
3
+ CalculatorKeyboard_targetSdkVersion=31
4
+ CalculatorKeyboard_compileSdkVersion=31
5
+ CalculatorKeyboard_ndkversion=21.4.7075529
@@ -0,0 +1,3 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
+ package="com.calculatorkeyboard">
3
+ </manifest>
@@ -0,0 +1,2 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ </manifest>
@@ -0,0 +1,17 @@
1
+ package com.calculatorkeyboard
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+
8
+
9
+ class CalculatorKeyboardPackage : ReactPackage {
10
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
11
+ return emptyList()
12
+ }
13
+
14
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
15
+ return listOf(RCTInputCalculator())
16
+ }
17
+ }
@@ -0,0 +1,28 @@
1
+ package com.calculatorkeyboard
2
+
3
+ import android.content.Context
4
+ import android.graphics.Rect
5
+ import com.facebook.react.views.textinput.ReactEditText
6
+
7
+ class CalculatorEditText(context: Context) : ReactEditText(context) {
8
+ var onFocusListener: OnFocusChangeListener? = null
9
+
10
+ override fun requestFocus(direction: Int, previouslyFocusedRect: Rect?): Boolean {
11
+ if (isFocused) {
12
+ return true
13
+ }
14
+ isFocusable = true
15
+ isFocusableInTouchMode = true
16
+ return super.requestFocus(direction, previouslyFocusedRect)
17
+ }
18
+
19
+ override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
20
+ super.onFocusChanged(focused, direction, previouslyFocusedRect)
21
+ onFocusListener?.onFocusChange(this, isFocused)
22
+ }
23
+
24
+
25
+ interface OnFocusChangeListener {
26
+ fun onFocusChange(view: CalculatorEditText, hasFocus: Boolean)
27
+ }
28
+ }
@@ -0,0 +1,242 @@
1
+ package com.calculatorkeyboard
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.content.res.ColorStateList
5
+ import android.graphics.Color
6
+ import android.graphics.drawable.GradientDrawable
7
+ import android.view.Gravity
8
+ import android.widget.Button
9
+ import android.widget.ImageButton
10
+ import androidx.appcompat.app.AppCompatActivity
11
+ import androidx.constraintlayout.widget.ConstraintLayout
12
+ import androidx.core.graphics.ColorUtils
13
+ import com.facebook.react.uimanager.ThemedReactContext
14
+ import org.mariuszgromada.math.mxparser.Expression
15
+ import androidx.core.graphics.toColorInt
16
+ import com.facebook.react.uimanager.PixelUtil.dpToPx
17
+
18
+
19
+ @SuppressLint("SetTextI18n", "ViewConstructor")
20
+ class CustomKeyboardView(
21
+ context: ThemedReactContext,
22
+ private val editText: CalculatorEditText
23
+ ) : ConstraintLayout(context) {
24
+ private val keys = listOf(
25
+ listOf("AC", "÷", "×", "back"),
26
+ listOf("7", "8", "9", "-"),
27
+ listOf("4", "5", "6", "+"),
28
+ listOf("1", "2", "3", "="),
29
+ listOf("000", "0")
30
+ )
31
+ private val specialKeys = listOf("=", "-", "×", "÷", "AC", "back", "+")
32
+ private val separatorWidth = 8f
33
+ private var specialButtonColor: Int = "#D8D8D8".toColorInt()
34
+
35
+ init {
36
+ val activity = context.currentActivity as? AppCompatActivity
37
+ if (activity != null) {
38
+ val displayMetrics = resources.displayMetrics
39
+ val widthButton = (displayMetrics.widthPixels - separatorWidth * 2 - 3 * separatorWidth) / 4f
40
+ val heightButton = (290.dpToPx() - separatorWidth * 2 - 4 * separatorWidth) / 5
41
+
42
+ renderUI(widthButton, heightButton)
43
+ }
44
+
45
+ }
46
+
47
+ private fun renderUI(buttonWidth: Float, buttonHeight: Float) {
48
+ var yOffset = separatorWidth
49
+ for ((_, row) in keys.withIndex()) {
50
+ var xOffset = separatorWidth
51
+ for ((_, key) in row.withIndex()) {
52
+ val width = if (key == "000") buttonWidth * 2 + separatorWidth else buttonWidth
53
+ val height = if (key == "=") buttonWidth + separatorWidth else buttonHeight
54
+
55
+ val button = if (key == "back") {
56
+ createImageButton(key, xOffset, yOffset, buttonWidth.toInt(), buttonHeight.toInt())
57
+ } else {
58
+ createButton(key, xOffset, yOffset, width.toInt(), height.toInt())
59
+ }
60
+
61
+ addView(button)
62
+
63
+ xOffset += width + separatorWidth
64
+ }
65
+ yOffset += buttonHeight + separatorWidth
66
+ }
67
+ }
68
+
69
+ private fun createButton(
70
+ key: String,
71
+ xOffset: Float,
72
+ yOffset: Float,
73
+ buttonWidth: Int,
74
+ buttonHeight: Int,
75
+ ): Button {
76
+ val specialKeys = listOf("=", "-", "×", "÷", "AC", "back", "+")
77
+ return Button(context).apply {
78
+ val shapeInit = GradientDrawable().apply {
79
+ shape = GradientDrawable.RECTANGLE
80
+ cornerRadius = 24f
81
+ setColor(Color.WHITE)
82
+ setBackgroundColor(Color.WHITE)
83
+ }
84
+ gravity = Gravity.CENTER
85
+ background = shapeInit
86
+ text = key
87
+ setTypeface(typeface)
88
+ textSize = 24.toFloat()
89
+ setTextColor(Color.BLACK)
90
+ stateListAnimator = null
91
+ layoutParams = LayoutParams(
92
+ buttonWidth,
93
+ buttonHeight
94
+ ).apply {
95
+ constrainedWidth = false
96
+ }
97
+
98
+ if (specialKeys.contains(key)) {
99
+ background = GradientDrawable().apply {
100
+ shape = GradientDrawable.RECTANGLE
101
+ cornerRadius = 24f
102
+ setColor(specialButtonColor)
103
+ }
104
+ setTextColor(Color.BLACK)
105
+ }
106
+
107
+
108
+ translationX = xOffset.toInt().toFloat()
109
+ translationY = yOffset.toInt().toFloat()
110
+ setOnClickListener { onKeyPress(key) }
111
+ }
112
+ }
113
+
114
+ private fun createImageButton(
115
+ key: String,
116
+ xOffset: Float,
117
+ yOffset: Float,
118
+ buttonWidth: Int,
119
+ buttonHeight: Int,
120
+ ): ImageButton {
121
+ return ImageButton(context).apply {
122
+ val shapeInit = GradientDrawable().apply {
123
+ shape = GradientDrawable.RECTANGLE
124
+ cornerRadius = 24f
125
+ setColor(specialButtonColor)
126
+ }
127
+ background = shapeInit
128
+ stateListAnimator = null
129
+ layoutParams = LayoutParams(
130
+ buttonWidth,
131
+ buttonHeight
132
+ ).apply {
133
+ constrainedWidth = false
134
+ }
135
+ translationX = xOffset
136
+ translationY = yOffset
137
+ setImageResource(android.R.drawable.ic_input_delete)
138
+ setImageTintList(ColorStateList.valueOf(Color.BLACK))
139
+ setOnClickListener { onKeyPress(key) }
140
+ }
141
+ }
142
+
143
+ fun updateButtonColors(color: Int) {
144
+ specialButtonColor = color
145
+ for (i in 0 until childCount) {
146
+ val child = getChildAt(i)
147
+ if (child is Button) {
148
+ val key = child.text.toString()
149
+ if (specialKeys.contains(key)) {
150
+ if (key == "=") {
151
+ child.background = GradientDrawable().apply {
152
+ shape = GradientDrawable.RECTANGLE
153
+ cornerRadius = 24f
154
+ setColor(specialButtonColor)
155
+ }
156
+ } else {
157
+ child.background = GradientDrawable().apply {
158
+ shape = GradientDrawable.RECTANGLE
159
+ cornerRadius = 24f
160
+ setColor(specialButtonColor)
161
+ }
162
+ }
163
+ child.setTextColor(Color.BLACK)
164
+ }
165
+ } else if (child is ImageButton) {
166
+ child.background = GradientDrawable().apply {
167
+ shape = GradientDrawable.RECTANGLE
168
+ cornerRadius = 24f
169
+ setColor(specialButtonColor)
170
+ }
171
+ }
172
+ }
173
+ }
174
+
175
+ private fun onKeyPress(key: String) {
176
+ when (key) {
177
+ "AC" -> {
178
+ clearText()
179
+ }
180
+
181
+ "back" -> {
182
+ onBackSpace()
183
+ }
184
+
185
+ "=" -> {
186
+ calculateResult()
187
+ }
188
+
189
+ "×", "+", "-", "÷" -> keyDidPress(" $key ")
190
+
191
+ else -> {
192
+ editText.text?.insert(editText.selectionStart, key)
193
+ }
194
+ }
195
+ }
196
+
197
+ private fun keyDidPress(key: String) {
198
+ println("Key pressed: $key")
199
+ editText.text?.replace(editText.selectionStart, editText.selectionEnd, key)
200
+ }
201
+
202
+ private fun clearText() {
203
+ editText.text?.clear()
204
+ }
205
+
206
+ private fun onBackSpace() {
207
+ val start = editText.selectionStart
208
+ val end = editText.selectionEnd
209
+ if (start > 0) {
210
+ val newText = end.let { editText.text?.replaceRange(start - 1, it, "") }
211
+ editText.setText(newText)
212
+ editText.setSelection(start - 1)
213
+ }
214
+ }
215
+
216
+ private fun calculateResult() {
217
+ val text = editText?.text.toString().replace("×", "*").replace("÷", "/")
218
+ val pattern = "^\\s*(-?\\d+(\\.\\d+)?\\s*[-+*/]\\s*)*-?\\d+(\\.\\d+)?\\s*$"
219
+ val regex = Regex(pattern)
220
+ if (regex.matches(text)) {
221
+ try {
222
+ val result = eval(text).toString()
223
+ editText.setTextKeepState(result)
224
+ } catch (e: Exception) {
225
+ e.printStackTrace()
226
+ }
227
+ } else {
228
+ println("Invalid expression")
229
+ }
230
+ }
231
+
232
+ private fun eval(str: String): Long? {
233
+ val e = Expression(str)
234
+ println("Expression: $e")
235
+ return if (e.checkSyntax()) {
236
+ e.calculate().toLong()
237
+ } else {
238
+ null
239
+ }
240
+ }
241
+
242
+ }
@@ -0,0 +1,166 @@
1
+ package com.calculatorkeyboard
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.app.Activity
5
+ import android.graphics.PixelFormat
6
+ import android.graphics.drawable.ColorDrawable
7
+ import android.view.Gravity
8
+ import android.view.KeyEvent
9
+ import android.view.View
10
+ import android.view.WindowInsets
11
+ import android.view.WindowManager
12
+ import android.widget.PopupWindow
13
+ import androidx.constraintlayout.widget.ConstraintLayout
14
+ import androidx.core.graphics.toColorInt
15
+ import com.facebook.react.bridge.ReadableArray
16
+ import com.facebook.react.bridge.UiThreadUtil
17
+ import com.facebook.react.uimanager.ThemedReactContext
18
+ import com.facebook.react.uimanager.annotations.ReactProp
19
+ import com.facebook.react.views.textinput.ReactEditText
20
+ import com.facebook.react.views.textinput.ReactTextInputManager
21
+ import androidx.core.graphics.drawable.toDrawable
22
+ import androidx.core.view.ViewCompat
23
+ import androidx.core.view.WindowInsetsCompat
24
+ import com.facebook.react.uimanager.PixelUtil.dpToPx
25
+
26
+ class RCTInputCalculator : ReactTextInputManager() {
27
+
28
+ private var keyboardView: CustomKeyboardView? = null
29
+ private var calculatorHeight: Int = 290.dpToPx().toInt()
30
+ private var popup: PopupWindow? = null
31
+ private val animationDuration = 250L
32
+
33
+ private lateinit var editText: CalculatorEditText
34
+
35
+ override fun getName() = REACT_CLASS
36
+
37
+ companion object {
38
+ const val REACT_CLASS = "RCTInputCalculator"
39
+ }
40
+
41
+ @ReactProp(name = "value")
42
+ fun setValue(view: ReactEditText, value: String?) {
43
+ // view.setText(value)
44
+ }
45
+
46
+ @ReactProp(name = "keyboardColor")
47
+ fun setKeyboardColor(view: ReactEditText, color: String) {
48
+ keyboardView?.updateButtonColors(color.toColorInt())
49
+ }
50
+
51
+ @SuppressLint("ClickableViewAccessibility")
52
+ override fun createViewInstance(context: ThemedReactContext): ReactEditText {
53
+ editText = CalculatorEditText(context).apply {
54
+ showSoftInputOnFocus = false
55
+ }
56
+
57
+ keyboardView = CustomKeyboardView(context, editText).apply {
58
+ setBackgroundColor("#f2f2f6".toColorInt())
59
+ elevation = 24f
60
+ }
61
+
62
+ editText.onFocusListener = object : CalculatorEditText.OnFocusChangeListener {
63
+ override fun onFocusChange(view: CalculatorEditText, hasFocus: Boolean) {
64
+ UiThreadUtil.runOnUiThread {
65
+ if (hasFocus) {
66
+ showKeyboardPopup(view)
67
+ } else {
68
+ hideKeyboardPopup()
69
+ }
70
+ view.setOnKeyListener { v, keyCode, _ ->
71
+ if (keyCode == KeyEvent.KEYCODE_BACK && hasFocus) {
72
+ v.clearFocus()
73
+ true
74
+ } else false
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ return editText
81
+ }
82
+
83
+ override fun getCommandsMap(): Map<String, Int> {
84
+ return mapOf(
85
+ "blur" to 1,
86
+ "focus" to 2
87
+ )
88
+ }
89
+
90
+ override fun receiveCommand(reactEditText: ReactEditText, commandId: Int, args: ReadableArray?) {
91
+ when (commandId) {
92
+ 1 -> blur()
93
+ 2 -> focus()
94
+ }
95
+ }
96
+
97
+ private fun ensurePopup() {
98
+ if (popup != null) return
99
+ val content = keyboardView ?: return
100
+
101
+ popup = PopupWindow(
102
+ content,
103
+ WindowManager.LayoutParams.MATCH_PARENT,
104
+ calculatorHeight + bottomInsetFrom(editText.rootView),
105
+ false
106
+ ).apply {
107
+ setBackgroundDrawable(android.graphics.Color.TRANSPARENT.toDrawable())
108
+ isOutsideTouchable = false
109
+ isClippingEnabled = false
110
+ softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING
111
+ inputMethodMode = PopupWindow.INPUT_METHOD_NOT_NEEDED
112
+ }
113
+ }
114
+
115
+ private fun bottomInsetFrom(view: View): Int {
116
+ val insets = ViewCompat.getRootWindowInsets(view) ?: return 0
117
+ val mask = WindowInsetsCompat.Type.navigationBars() or WindowInsetsCompat.Type.displayCutout()
118
+ return insets.getInsets(mask).bottom
119
+ }
120
+
121
+ private fun showKeyboardPopup(anchor: View) {
122
+ ensurePopup()
123
+ val p = popup ?: return
124
+ if (p.isShowing) return
125
+
126
+ val root = keyboardView ?: return
127
+
128
+ root.translationY = calculatorHeight.toFloat()
129
+ p.showAtLocation(anchor.rootView, Gravity.BOTTOM or Gravity.START, 0, 0)
130
+
131
+ root.animate()
132
+ ?.translationY(0f)
133
+ ?.setDuration(animationDuration)
134
+ ?.start()
135
+ }
136
+
137
+ private fun hideKeyboardPopup() {
138
+ val p = popup ?: return
139
+ if (!p.isShowing) return
140
+ val root = keyboardView ?: return
141
+
142
+ root.animate()
143
+ .translationY(calculatorHeight.toFloat())
144
+ .setDuration(animationDuration)
145
+ .withEndAction {
146
+ try {
147
+ if (p.isShowing) p.dismiss()
148
+ } catch (_: Throwable) { }
149
+ }
150
+ .start()
151
+
152
+ popup = null
153
+ }
154
+
155
+ private fun focus() {
156
+ UiThreadUtil.runOnUiThread {
157
+ if (!editText.isFocused) editText.requestFocus()
158
+ }
159
+ }
160
+
161
+ private fun blur() {
162
+ UiThreadUtil.runOnUiThread {
163
+ if (editText.isFocused) editText.clearFocus()
164
+ }
165
+ }
166
+ }