@ng-native/components 0.22.2 → 0.23.0

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.
Files changed (138) hide show
  1. package/android/build.gradle +22 -0
  2. package/android/src/main/java/dev/ngnative/components/ContextMenuAccessibility.kt +71 -0
  3. package/android/src/main/java/dev/ngnative/components/ContextMenuGesture.kt +161 -0
  4. package/android/src/main/java/dev/ngnative/components/ContextMenuPopup.kt +197 -0
  5. package/android/src/main/java/dev/ngnative/components/MenuHost.kt +45 -0
  6. package/android/src/main/java/dev/ngnative/components/MenuWindowCallback.kt +76 -0
  7. package/android/src/main/java/dev/ngnative/components/MenusModule.kt +85 -0
  8. package/android/src/main/java/dev/ngnative/components/Shortcut.kt +144 -0
  9. package/android/src/main/java/dev/ngnative/components/WindowWrapper.kt +22 -0
  10. package/dist/activity-indicator.d.ts +4 -1
  11. package/dist/activity-indicator.js +6 -2
  12. package/dist/activity-indicator.js.map +1 -1
  13. package/dist/context-menu.d.ts +52 -0
  14. package/dist/context-menu.js +101 -0
  15. package/dist/context-menu.js.map +1 -0
  16. package/dist/drag-and-drop.d.ts +52 -0
  17. package/dist/drag-and-drop.js +112 -0
  18. package/dist/drag-and-drop.js.map +1 -0
  19. package/dist/gesture-backend.d.ts +32 -2
  20. package/dist/gesture-backend.js.map +1 -1
  21. package/dist/gesture-dispatch.d.ts +8 -1
  22. package/dist/gesture-dispatch.js +60 -16
  23. package/dist/gesture-dispatch.js.map +1 -1
  24. package/dist/gesture-interaction.d.ts +13 -0
  25. package/dist/gesture-interaction.js +97 -0
  26. package/dist/gesture-interaction.js.map +1 -0
  27. package/dist/gesture-tracking.d.ts +18 -0
  28. package/dist/gesture-tracking.js +28 -0
  29. package/dist/gesture-tracking.js.map +1 -0
  30. package/dist/gestures-web.d.ts +3 -1
  31. package/dist/gestures-web.js +5 -2
  32. package/dist/gestures-web.js.map +1 -1
  33. package/dist/gestures.d.ts +1 -0
  34. package/dist/gestures.js +45 -3
  35. package/dist/gestures.js.map +1 -1
  36. package/dist/image.d.ts +1 -1
  37. package/dist/index.d.ts +12 -1
  38. package/dist/index.js +12 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/interaction-observer.d.ts +11 -0
  41. package/dist/interaction-observer.js +12 -0
  42. package/dist/interaction-observer.js.map +1 -0
  43. package/dist/keyboard-avoiding-view.js +3 -3
  44. package/dist/keyboard-avoiding-view.js.map +1 -1
  45. package/dist/markdown-stream.d.ts +3 -1
  46. package/dist/markdown-stream.js +14 -2
  47. package/dist/markdown-stream.js.map +1 -1
  48. package/dist/markdown.d.ts +2 -0
  49. package/dist/markdown.js +5 -3
  50. package/dist/markdown.js.map +1 -1
  51. package/dist/menu.d.ts +71 -0
  52. package/dist/menu.js +193 -0
  53. package/dist/menu.js.map +1 -0
  54. package/dist/modal.d.ts +30 -1
  55. package/dist/modal.js +67 -6
  56. package/dist/modal.js.map +1 -1
  57. package/dist/native-button.d.ts +54 -0
  58. package/dist/native-button.js +100 -0
  59. package/dist/native-button.js.map +1 -0
  60. package/dist/native-gesture.d.ts +9 -1
  61. package/dist/native-gesture.js +32 -3
  62. package/dist/native-gesture.js.map +1 -1
  63. package/dist/native-id.d.ts +10 -0
  64. package/dist/native-id.js +70 -0
  65. package/dist/native-id.js.map +1 -0
  66. package/dist/pressable.d.ts +31 -0
  67. package/dist/pressable.js +102 -9
  68. package/dist/pressable.js.map +1 -1
  69. package/dist/safe-area-provider.js +15 -8
  70. package/dist/safe-area-provider.js.map +1 -1
  71. package/dist/scroll-view-props.d.ts +7 -1
  72. package/dist/scroll-view-props.js +54 -3
  73. package/dist/scroll-view-props.js.map +1 -1
  74. package/dist/section-list.js +2 -2
  75. package/dist/section-list.js.map +1 -1
  76. package/dist/shortcut.d.ts +21 -0
  77. package/dist/shortcut.js +34 -0
  78. package/dist/shortcut.js.map +1 -0
  79. package/dist/sidebar-item.d.ts +53 -0
  80. package/dist/sidebar-item.js +152 -0
  81. package/dist/sidebar-item.js.map +1 -0
  82. package/dist/sidebar-section.d.ts +21 -0
  83. package/dist/sidebar-section.js +74 -0
  84. package/dist/sidebar-section.js.map +1 -0
  85. package/dist/sidebar.d.ts +47 -0
  86. package/dist/sidebar.js +110 -0
  87. package/dist/sidebar.js.map +1 -0
  88. package/dist/split-view.d.ts +63 -0
  89. package/dist/split-view.js +121 -0
  90. package/dist/split-view.js.map +1 -0
  91. package/dist/switch.d.ts +9 -1
  92. package/dist/switch.js +23 -2
  93. package/dist/switch.js.map +1 -1
  94. package/dist/text-input.d.ts +8 -3
  95. package/dist/text-input.js +10 -4
  96. package/dist/text-input.js.map +1 -1
  97. package/dist/transforms.d.ts +5 -0
  98. package/dist/transforms.js +7 -0
  99. package/dist/transforms.js.map +1 -1
  100. package/dist/tray-icon.d.ts +18 -0
  101. package/dist/tray-icon.js +46 -0
  102. package/dist/tray-icon.js.map +1 -0
  103. package/dist/view-base.d.ts +42 -1
  104. package/dist/view-base.js +67 -39
  105. package/dist/view-base.js.map +1 -1
  106. package/dist/virtual-list.js +12 -1
  107. package/dist/virtual-list.js.map +1 -1
  108. package/dist/written-props.js +25 -0
  109. package/dist/written-props.js.map +1 -1
  110. package/expo-module.config.json +6 -0
  111. package/ios/NgNativeButtonComponentView.mm +132 -0
  112. package/ios/NgNativeButtonMetrics.h +28 -0
  113. package/ios/NgNativeButtonMetrics.mm +68 -0
  114. package/ios/NgNativeButtonShadowNode.h +65 -0
  115. package/ios/NgNativeButtonShadowNode.mm +40 -0
  116. package/ios/NgNativeComponents.podspec +28 -0
  117. package/ios/NgNativeDragAndDrop.mm +342 -0
  118. package/ios/NgNativeDropItems.h +29 -0
  119. package/ios/NgNativeDropItems.mm +55 -0
  120. package/ios/NgNativeMenuBuilding.h +40 -0
  121. package/ios/NgNativeMenuBuilding.mm +217 -0
  122. package/ios/NgNativeMenus.mm +320 -0
  123. package/ios/NgNativeResponderHooks.h +53 -0
  124. package/ios/NgNativeResponderHooks.mm +215 -0
  125. package/ios/NgNativeSceneKeys.h +36 -0
  126. package/ios/NgNativeSceneKeys.mm +56 -0
  127. package/ios/NgNativeSplitView.mm +433 -0
  128. package/ios/NgNativeSplitViewDelegate.h +29 -0
  129. package/ios/NgNativeSplitViewDelegate.mm +122 -0
  130. package/ios/NgNativeSplitViewShadowNodes.h +115 -0
  131. package/ios/NgNativeSplitViewShadowNodes.mm +31 -0
  132. package/ios/NgNativeUndo.mm +107 -0
  133. package/ios/NgNativeUndoSteps.h +17 -0
  134. package/ios/NgNativeUndoSteps.mm +22 -0
  135. package/ios/NgNativeViewBinder.h +54 -0
  136. package/ios/NgNativeViewBinder.mm +225 -0
  137. package/ios/NgNativeWindows.mm +1126 -0
  138. package/package.json +13 -5
@@ -0,0 +1,22 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'expo-module-gradle-plugin'
4
+ }
5
+
6
+ group = 'dev.ngnative.components'
7
+ version = '1.0.0'
8
+
9
+ android {
10
+ namespace "dev.ngnative.components"
11
+ defaultConfig {
12
+ versionCode 1
13
+ versionName '1.0.0'
14
+ }
15
+ }
16
+
17
+ dependencies {
18
+ // TouchTargetHelper, which finds the view a press lands on as React Native's touches do, and the
19
+ // event dispatcher that sends a menu's choice to the view.
20
+ implementation 'com.facebook.react:react-android'
21
+ testImplementation 'junit:junit:4.13.2'
22
+ }
@@ -0,0 +1,71 @@
1
+ package dev.ngnative.components
2
+
3
+ import android.app.Activity
4
+ import android.view.View
5
+ import androidx.core.view.ViewCompat
6
+ import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat
7
+ import com.facebook.react.R
8
+ import com.facebook.react.uimanager.ReactAccessibilityDelegate
9
+ import com.facebook.react.uimanager.UIManagerHelper
10
+ import com.facebook.react.uimanager.util.ReactFindViewUtil
11
+
12
+ /**
13
+ * Offers each `[contextMenu]` to TalkBack and other accessibility services as its view's long-press
14
+ * action, which opens the menu at the view's centre. The menu otherwise opens only from touches,
15
+ * and TalkBack's double-tap and hold performs the action instead of sending one.
16
+ *
17
+ * React Native tells `ReactFindViewUtil` each time it gives a view a `nativeID`, so a view that
18
+ * mounts after its menu was set gets the action too. On the main thread only.
19
+ */
20
+ internal object ContextMenuAccessibility {
21
+ private val found = ReactFindViewUtil.OnMultipleViewsFoundListener { view, nativeId ->
22
+ if (nativeId in MenuHost.contextMenus) bind(view)
23
+ }
24
+
25
+ /** Follow a change to `nativeId`'s menu in `MenuHost`, on its view in `activity`'s window. */
26
+ fun update(activity: Activity?, nativeId: String) {
27
+ if (MenuHost.contextMenus.isEmpty()) {
28
+ ReactFindViewUtil.removeViewsListener(found)
29
+ } else {
30
+ ReactFindViewUtil.addViewsListener(found, HashSet(MenuHost.contextMenus.keys))
31
+ }
32
+ val root = activity?.window?.decorView ?: return
33
+ val view = ReactFindViewUtil.findView(root, nativeId) ?: return
34
+ if (nativeId in MenuHost.contextMenus) bind(view) else unbind(view)
35
+ }
36
+
37
+ /** Stop following views, once no module is there to send the choice. */
38
+ fun stop() {
39
+ ReactFindViewUtil.removeViewsListener(found)
40
+ }
41
+
42
+ private fun bind(view: View) {
43
+ // React Native gives a view its own delegate only when it has none. The action needs one, so
44
+ // the view gets React Native's, as it would for a role, rather than a bare one in its place.
45
+ if (!ViewCompat.hasAccessibilityDelegate(view)) {
46
+ ReactAccessibilityDelegate.resetDelegate(view, view.isFocusable, view.importantForAccessibility)
47
+ }
48
+ ViewCompat.replaceAccessibilityAction(view, AccessibilityActionCompat.ACTION_LONG_CLICK, null) { v, _ ->
49
+ open(v)
50
+ }
51
+ }
52
+
53
+ private fun unbind(view: View) {
54
+ ViewCompat.removeAccessibilityAction(view, AccessibilityActionCompat.ACTION_LONG_CLICK.id)
55
+ }
56
+
57
+ /** Open `view`'s menu at its centre. A recycled view that has another id now lets go of it. */
58
+ private fun open(view: View): Boolean {
59
+ val nativeId = view.getTag(R.id.view_tag_native_id) as? String
60
+ if (nativeId == null || nativeId !in MenuHost.contextMenus) {
61
+ unbind(view)
62
+ return false
63
+ }
64
+ val entries = MenuHost.contextMenus[nativeId] ?: return false
65
+ val activity = UIManagerHelper.getReactContext(view).currentActivity ?: return false
66
+ // A view in a <modal> is in the dialog's window, where the menu does not open yet.
67
+ if (!view.isAttachedToWindow || view.rootView !== activity.window?.decorView) return false
68
+ val at = IntArray(2).also(view::getLocationInWindow)
69
+ return ContextMenuPopup.show(activity, view, entries, at[0] + view.width / 2f, at[1] + view.height / 2f)
70
+ }
71
+ }
@@ -0,0 +1,161 @@
1
+ package dev.ngnative.components
2
+
3
+ import android.app.Activity
4
+ import android.os.Handler
5
+ import android.os.Looper
6
+ import android.view.HapticFeedbackConstants
7
+ import android.view.InputDevice
8
+ import android.view.MotionEvent
9
+ import android.view.View
10
+ import android.view.ViewConfiguration
11
+ import android.view.ViewGroup
12
+ import com.facebook.react.R
13
+ import com.facebook.react.uimanager.TouchTargetHelper
14
+ import kotlin.math.hypot
15
+
16
+ /**
17
+ * Opens a `[contextMenu]` on a long press or a right-click, at the press point.
18
+ *
19
+ * It watches the window's touches before React Native does. A press is matched to a menu by the
20
+ * view React Native would send it to, or the nearest view above that with a menu, by `nativeID`.
21
+ * A long press lets React Native have the touch until the menu opens, then cancels it there, so a
22
+ * `<pressable>` neither presses nor long-presses; a right-click is never React Native's at all.
23
+ * Either way the rest of the gesture is the menu's.
24
+ *
25
+ * The innermost handler wins a long press: a view on the way up that takes one itself (a
26
+ * `(longPress)`, in `MenuHost.longPressTakers`) keeps it, and no menu above it opens. A right-click
27
+ * still opens the menu. A `<pressable>` around the menu finds its owner as `menuOwner` does, from
28
+ * what `Menus` sent, and leaves the long press to it.
29
+ */
30
+ internal class ContextMenuGesture(
31
+ private val activity: Activity,
32
+ /** Hands an event on to the window as it would have gone without menus. */
33
+ private val forward: (MotionEvent) -> Boolean,
34
+ ) {
35
+ private val main = Handler(Looper.getMainLooper())
36
+ private val slop = ViewConfiguration.get(activity).scaledTouchSlop
37
+ private var down: MotionEvent? = null
38
+ private var pending: Runnable? = null
39
+
40
+ /** Whether the menu took this gesture, so its remaining events go nowhere. */
41
+ private var taken = false
42
+
43
+ /** Whether `event` is the menu's. */
44
+ fun handle(event: MotionEvent): Boolean {
45
+ when (event.actionMasked) {
46
+ MotionEvent.ACTION_DOWN -> return pressed(event)
47
+ MotionEvent.ACTION_MOVE -> {
48
+ val start = down
49
+ if (pending != null && start != null &&
50
+ hypot(event.x - start.x, event.y - start.y) > slop
51
+ ) {
52
+ stopWaiting()
53
+ }
54
+ }
55
+ MotionEvent.ACTION_POINTER_DOWN -> stopWaiting()
56
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
57
+ stopWaiting()
58
+ val wasTaken = taken
59
+ taken = false
60
+ return wasTaken
61
+ }
62
+ }
63
+ return taken
64
+ }
65
+
66
+ private fun pressed(event: MotionEvent): Boolean {
67
+ stopWaiting()
68
+ taken = false
69
+ if (MenuHost.contextMenus.isEmpty()) return false
70
+ val secondary = isSecondaryClick(event)
71
+ val (view, nativeId) = menuViewAt(event.x, event.y, longPress = !secondary) ?: return false
72
+ if (secondary) {
73
+ taken = open(view, nativeId, event)
74
+ return taken
75
+ }
76
+ val start = MotionEvent.obtain(event)
77
+ down = start
78
+ val longPress = Runnable {
79
+ pending = null
80
+ if (!open(view, nativeId, start)) return@Runnable
81
+ view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
82
+ taken = true
83
+ // React Native had the touch until now: it hears it cancelled, so nothing presses.
84
+ val cancel = MotionEvent.obtain(start).apply { action = MotionEvent.ACTION_CANCEL }
85
+ forward(cancel)
86
+ cancel.recycle()
87
+ }
88
+ pending = longPress
89
+ // The system's timeout, with the Touch & hold delay setting. A `<pressable>` around the menu
90
+ // leaves the hold to it whatever its `delayLongPress`, as it finds the menu the way this does.
91
+ main.postDelayed(longPress, ViewConfiguration.getLongPressTimeout().toLong())
92
+ return false
93
+ }
94
+
95
+ private fun stopWaiting() {
96
+ pending?.let(main::removeCallbacks)
97
+ pending = null
98
+ down?.recycle()
99
+ down = null
100
+ }
101
+
102
+ /**
103
+ * Open the menu for `nativeId` on `view` at `event`'s point, in the window, while `view` is still
104
+ * that menu's: a long press waits, and React Native can recycle the view for another meanwhile.
105
+ */
106
+ private fun open(view: View, nativeId: String, event: MotionEvent): Boolean {
107
+ val entries = MenuHost.contextMenus[nativeId] ?: return false
108
+ if (!stillOwns(view.isAttachedToWindow, view.getTag(R.id.view_tag_native_id), nativeId)) return false
109
+ return ContextMenuPopup.show(activity, view, entries, event.x, event.y)
110
+ }
111
+
112
+ /**
113
+ * The view a press at (`x`, `y`) in the window lands on, as React Native finds its touch target,
114
+ * or the nearest view above it with a menu, and that menu's `nativeID`. For a `longPress`, none
115
+ * where a view on the way takes the long press itself.
116
+ */
117
+ private fun menuViewAt(x: Float, y: Float, longPress: Boolean): Pair<View, String>? {
118
+ val root = activity.window?.decorView as? ViewGroup ?: return null
119
+ val path = TouchTargetHelper.findTargetPathAndCoordinatesForTouch(x, y, root, FloatArray(2))
120
+ val views = generateSequence(path.firstNotNullOfOrNull { it.getView() }) { it.parent as? View }.toList()
121
+ val ids = views.map { it.getTag(R.id.view_tag_native_id) as? String }
122
+ val owner = menuOwner(
123
+ ids,
124
+ longPress,
125
+ MenuHost.contextMenus::containsKey,
126
+ MenuHost.longPressTakers::contains,
127
+ ) ?: return null
128
+ return views[owner] to (ids[owner] ?: return null)
129
+ }
130
+
131
+ private fun isSecondaryClick(event: MotionEvent): Boolean =
132
+ isSecondaryClick(event.isFromSource(InputDevice.SOURCE_MOUSE), event.buttonState)
133
+
134
+ companion object {
135
+ /** Whether a view, `attached` with the `nativeID` `tag`, is still the one with `nativeId`'s menu. */
136
+ fun stillOwns(attached: Boolean, tag: Any?, nativeId: String): Boolean = attached && tag == nativeId
137
+
138
+ /**
139
+ * Which of `chain`, the `nativeID`s from the pressed view outwards, has the menu a press
140
+ * opens: the nearest with one. For a `longPress`, none where a view on the way takes the long
141
+ * press itself.
142
+ */
143
+ fun menuOwner(
144
+ chain: List<String?>,
145
+ longPress: Boolean,
146
+ hasMenu: (String) -> Boolean,
147
+ takesLongPress: (String) -> Boolean,
148
+ ): Int? {
149
+ for ((index, nativeId) in chain.withIndex()) {
150
+ if (nativeId == null) continue
151
+ if (hasMenu(nativeId)) return index
152
+ if (longPress && takesLongPress(nativeId)) return null
153
+ }
154
+ return null
155
+ }
156
+
157
+ /** Whether a press is a right-click: a mouse's, with its secondary button down. */
158
+ fun isSecondaryClick(fromMouse: Boolean, buttonState: Int): Boolean =
159
+ fromMouse && buttonState and MotionEvent.BUTTON_SECONDARY != 0
160
+ }
161
+ }
@@ -0,0 +1,197 @@
1
+ package dev.ngnative.components
2
+
3
+ import android.app.Activity
4
+ import android.content.res.Configuration
5
+ import android.os.Build
6
+ import android.os.Handler
7
+ import android.os.Looper
8
+ import android.text.SpannableString
9
+ import android.text.Spanned
10
+ import android.text.style.ForegroundColorSpan
11
+ import android.util.TypedValue
12
+ import android.view.Gravity
13
+ import android.view.Menu
14
+ import android.view.View
15
+ import android.view.ViewGroup
16
+ import android.widget.FrameLayout
17
+ import android.widget.PopupMenu
18
+ import com.facebook.react.bridge.Arguments
19
+ import com.facebook.react.bridge.WritableMap
20
+ import com.facebook.react.uimanager.UIManagerHelper
21
+ import com.facebook.react.uimanager.events.Event
22
+
23
+ /**
24
+ * A `[contextMenu]` drawn as a PopupMenu at a point in the window, from the entries
25
+ * `serializeMenu` makes: labels, separators (dividers between groups, Android 9 and later),
26
+ * submenus, inline sections, checked, disabled and destructive items, and `icon` as a drawable
27
+ * resource's name. A PopupMenu row has no second line or tooltip, so `subtitle` is not shown.
28
+ * The item chosen goes to the view as `topContextMenuSelect` with its `id`.
29
+ */
30
+ internal object ContextMenuPopup {
31
+ /**
32
+ * A destructive item's label colour on a light menu, or on a dark one: Material's error colour
33
+ * for each.
34
+ */
35
+ fun destructiveColour(light: Boolean): Int = if (light) 0xFFB3261E.toInt() else 0xFFF2B8B5.toInt()
36
+
37
+ private val main by lazy { Handler(Looper.getMainLooper()) }
38
+
39
+ /** The last Android item id given out. On the main thread only. */
40
+ private var lastItemId = 0
41
+
42
+ /**
43
+ * Close each submenu of `menu`, at any depth. On a compact screen a submenu opens in a popup of
44
+ * its own in place of the menu's, which dismissing the menu's popup does not reach.
45
+ */
46
+ fun closeSubmenus(menu: Menu) {
47
+ for (index in 0 until menu.size()) {
48
+ val submenu = menu.getItem(index).subMenu ?: continue
49
+ closeSubmenus(submenu)
50
+ submenu.close()
51
+ }
52
+ }
53
+
54
+ /** What closes `menu` when its view detaches: each submenu, then the popup through `dismiss`. */
55
+ fun closingOnDetach(menu: Menu, dismiss: () -> Unit) =
56
+ object : View.OnAttachStateChangeListener {
57
+ override fun onViewAttachedToWindow(v: View) = Unit
58
+
59
+ override fun onViewDetachedFromWindow(v: View) {
60
+ closeSubmenus(menu)
61
+ dismiss()
62
+ }
63
+ }
64
+
65
+ /** Show `entries` for `view` at (`x`, `y`) in `activity`'s window. Whether there was a menu. */
66
+ fun show(activity: Activity, view: View, entries: List<Map<String, Any?>>, x: Float, y: Float): Boolean {
67
+ val content = activity.findViewById<ViewGroup>(android.R.id.content) ?: return false
68
+ // PopupMenu opens at a view: a one-pixel one at the press point, gone with the menu. The point
69
+ // is physical, so the anchor sits from the left in a right-to-left layout too.
70
+ val at = IntArray(2).also(content::getLocationInWindow)
71
+ val anchor = View(activity)
72
+ content.addView(
73
+ anchor,
74
+ FrameLayout.LayoutParams(1, 1).apply {
75
+ gravity = Gravity.TOP or Gravity.LEFT
76
+ leftMargin = (x - at[0]).toInt()
77
+ topMargin = (y - at[1]).toInt()
78
+ },
79
+ )
80
+ val popup = PopupMenu(activity, anchor, Gravity.NO_GRAVITY)
81
+ val ids = HashMap<Int, String>()
82
+ fill(activity, popup.menu, entries, ids, destructiveColour(isLight(activity)))
83
+ if (popup.menu.size() == 0) {
84
+ content.removeView(anchor)
85
+ return false
86
+ }
87
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) popup.setForceShowIcon(true)
88
+ popup.setOnMenuItemClickListener { item ->
89
+ val id = ids[item.itemId] ?: return@setOnMenuItemClickListener false
90
+ select(view, id)
91
+ true
92
+ }
93
+ // The menu goes with its view: when it unmounts, or its activity is recreated or destroyed.
94
+ // A submenu open in its own popup goes too.
95
+ val gone = closingOnDetach(popup.menu, popup::dismiss)
96
+ view.addOnAttachStateChangeListener(gone)
97
+ // Later, not while the view tree may be detaching its children.
98
+ val done = {
99
+ view.removeOnAttachStateChangeListener(gone)
100
+ main.post { content.removeView(anchor) }
101
+ }
102
+ popup.setOnDismissListener { done() }
103
+ // The anchor has no place until it is laid out, so the menu waits for that.
104
+ anchor.addOnLayoutChangeListener(
105
+ object : View.OnLayoutChangeListener {
106
+ override fun onLayoutChange(
107
+ v: View, l: Int, t: Int, r: Int, b: Int, ol: Int, ot: Int, or: Int, ob: Int,
108
+ ) {
109
+ anchor.removeOnLayoutChangeListener(this)
110
+ if (anchor.isAttachedToWindow && view.isAttachedToWindow) popup.show() else done()
111
+ }
112
+ },
113
+ )
114
+ return true
115
+ }
116
+
117
+ /**
118
+ * Add `entries` to `menu`. Each item's Android id is one more than the last, and `ids` maps it
119
+ * back to the entry's `id`. A separator or an inline section starts a new group.
120
+ */
121
+ private fun fill(
122
+ activity: Activity,
123
+ menu: Menu,
124
+ entries: List<*>,
125
+ ids: HashMap<Int, String>,
126
+ destructive: Int,
127
+ startGroup: Int = 0,
128
+ ): Int {
129
+ var group = startGroup
130
+ for (raw in entries) {
131
+ val entry = raw as? Map<*, *> ?: continue
132
+ if (entry["separator"] == true) {
133
+ group++
134
+ continue
135
+ }
136
+ val label = entry["label"] as? String ?: continue
137
+ val children = entry["items"] as? List<*>
138
+ if (children != null && entry["inline"] == true) {
139
+ group = fill(activity, menu, children, ids, destructive, group + 1) + 1
140
+ continue
141
+ }
142
+ val title = if (entry["destructive"] == true) coloured(label, destructive) else label
143
+ val itemId = ++lastItemId
144
+ (entry["id"] as? String)?.let { ids[itemId] = it }
145
+ val item = if (children != null) {
146
+ menu.addSubMenu(group, itemId, Menu.NONE, title).also { fill(activity, it, children, ids, destructive) }.item
147
+ } else {
148
+ menu.add(group, itemId, Menu.NONE, title)
149
+ }
150
+ item.isEnabled = entry["disabled"] != true
151
+ if (entry["checked"] != null) {
152
+ item.isCheckable = true
153
+ item.isChecked = entry["checked"] == true
154
+ }
155
+ (entry["icon"] as? String)?.let { name ->
156
+ val res = activity.resources.getIdentifier(name, "drawable", activity.packageName)
157
+ if (res != 0) item.setIcon(res)
158
+ }
159
+ }
160
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) menu.setGroupDividerEnabled(true)
161
+ return group
162
+ }
163
+
164
+ private fun coloured(label: String, colour: Int): CharSequence =
165
+ SpannableString(label).apply {
166
+ setSpan(ForegroundColorSpan(colour), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
167
+ }
168
+
169
+ /**
170
+ * Whether `activity`'s menus are light: its theme's `isLightTheme` on Android 10 and later, and
171
+ * the night mode before that.
172
+ */
173
+ private fun isLight(activity: Activity): Boolean {
174
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
175
+ val value = TypedValue()
176
+ if (activity.theme.resolveAttribute(android.R.attr.isLightTheme, value, true)) {
177
+ return value.data != 0
178
+ }
179
+ }
180
+ val night = activity.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
181
+ return night != Configuration.UI_MODE_NIGHT_YES
182
+ }
183
+
184
+ /** Send the chosen item's `id` to `view` as `topContextMenuSelect`. */
185
+ private fun select(view: View, id: String) {
186
+ val context = UIManagerHelper.getReactContext(view)
187
+ val dispatcher = UIManagerHelper.getEventDispatcherForReactTag(context, view.id) ?: return
188
+ dispatcher.dispatchEvent(ContextMenuSelectEvent(UIManagerHelper.getSurfaceId(view), view.id, id))
189
+ }
190
+
191
+ private class ContextMenuSelectEvent(surfaceId: Int, viewTag: Int, private val id: String) :
192
+ Event<ContextMenuSelectEvent>(surfaceId, viewTag) {
193
+ override fun getEventName() = "topContextMenuSelect"
194
+
195
+ override fun getEventData(): WritableMap = Arguments.createMap().apply { putString("id", id) }
196
+ }
197
+ }
@@ -0,0 +1,45 @@
1
+ package dev.ngnative.components
2
+
3
+ /**
4
+ * What the app has sent `NgNativeMenus`, shared by the module and the window it watches. Read and
5
+ * written on the main thread only.
6
+ */
7
+ internal object MenuHost {
8
+ /** Every shortcut the app listens for, `[shortcut]`s and the menu bar's, in the order sent. */
9
+ var shortcuts: List<Shortcut> = emptyList()
10
+
11
+ /** Each `[contextMenu]`'s entries, as `serializeMenu` makes them, by its view's `nativeID`. */
12
+ val contextMenus: MutableMap<String, List<Map<String, Any?>>> = HashMap()
13
+
14
+ /**
15
+ * The `nativeID`s of views that take a long press themselves (a `(longPress)`): one there opens
16
+ * no context menu around them, as the innermost handler wins.
17
+ */
18
+ val longPressTakers: MutableSet<String> = HashSet()
19
+
20
+ /** Sends an `ngNativeMenus` event to JavaScript, while a module is there to send it. */
21
+ var send: ((Map<String, Any?>) -> Unit)? = null
22
+ private set
23
+
24
+ /** A new module's sender: it starts with nothing an earlier module was sent. */
25
+ fun attach(sender: (Map<String, Any?>) -> Unit) {
26
+ send = sender
27
+ forget()
28
+ }
29
+
30
+ /**
31
+ * Let go of the module that set `sender`. A reload's new module can attach before the old one's
32
+ * `OnDestroy` runs, and then keeps what it has.
33
+ */
34
+ fun detach(sender: (Map<String, Any?>) -> Unit) {
35
+ if (send !== sender) return
36
+ send = null
37
+ forget()
38
+ }
39
+
40
+ private fun forget() {
41
+ shortcuts = emptyList()
42
+ contextMenus.clear()
43
+ longPressTakers.clear()
44
+ }
45
+ }
@@ -0,0 +1,76 @@
1
+ package dev.ngnative.components
2
+
3
+ import android.app.Activity
4
+ import android.os.Build
5
+ import android.view.KeyEvent
6
+ import android.view.KeyboardShortcutGroup
7
+ import android.view.Menu
8
+ import android.view.MotionEvent
9
+ import android.view.Window
10
+ import android.widget.EditText
11
+
12
+ /**
13
+ * The activity's window callback with the app's shortcuts and context menus in it. It sees every
14
+ * key and touch the window gets, before React Native or any view, without the app's activity
15
+ * having to subclass anything.
16
+ *
17
+ * - A chord with a modifier reaches `dispatchKeyShortcutEvent` after the focused view has had it:
18
+ * a text input's own Ctrl-Z, X, C, V and A take it first. An app shortcut then fires.
19
+ * - The Keyboard Shortcuts helper asks `onProvideKeyboardShortcuts`, which adds the app's.
20
+ * - A press on a view with a `[contextMenu]` goes to `ContextMenuGesture` first.
21
+ *
22
+ * Only the activity's window has it: a `<modal>` is a Dialog with a window of its own, where the
23
+ * app's shortcuts and context menus do not reach yet.
24
+ */
25
+ internal class MenuWindowCallback private constructor(
26
+ activity: Activity,
27
+ private val base: Window.Callback,
28
+ ) : Window.Callback by base {
29
+ private val contextMenus = ContextMenuGesture(activity) { event -> base.dispatchTouchEvent(event) }
30
+ private val activity = activity
31
+
32
+ override fun dispatchKeyShortcutEvent(event: KeyEvent): Boolean {
33
+ if (base.dispatchKeyShortcutEvent(event)) return true
34
+ val send = MenuHost.send ?: return false
35
+ val shortcut = MenuHost.shortcuts.firstOrNull { it.matches(event) } ?: return false
36
+ send(
37
+ mapOf(
38
+ "type" to "shortcut",
39
+ "id" to shortcut.id,
40
+ "textInputFocused" to (activity.currentFocus is EditText),
41
+ ),
42
+ )
43
+ return true
44
+ }
45
+
46
+ override fun onProvideKeyboardShortcuts(
47
+ data: MutableList<KeyboardShortcutGroup>,
48
+ menu: Menu?,
49
+ deviceId: Int,
50
+ ) {
51
+ base.onProvideKeyboardShortcuts(data, menu, deviceId)
52
+ data.addAll(Shortcut.groups(MenuHost.shortcuts))
53
+ }
54
+
55
+ override fun onPointerCaptureChanged(hasCapture: Boolean) {
56
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) base.onPointerCaptureChanged(hasCapture)
57
+ }
58
+
59
+ override fun dispatchTouchEvent(event: MotionEvent): Boolean =
60
+ contextMenus.handle(event) || base.dispatchTouchEvent(event)
61
+
62
+ companion object {
63
+ private val windows = WindowWrapper<Window>()
64
+
65
+ /**
66
+ * Put the callback on `activity`'s window, once for each window, however other code has
67
+ * wrapped the window's callback since. On the main thread.
68
+ */
69
+ fun install(activity: Activity) {
70
+ val window = activity.window ?: return
71
+ windows.wrapOnce(window, window.callback, { MenuWindowCallback(activity, it) }) {
72
+ window.callback = it
73
+ }
74
+ }
75
+ }
76
+ }
@@ -0,0 +1,85 @@
1
+ package dev.ngnative.components
2
+
3
+ import android.os.Handler
4
+ import android.os.Looper
5
+ import expo.modules.kotlin.modules.Module
6
+ import expo.modules.kotlin.modules.ModuleDefinition
7
+
8
+ /**
9
+ * `NgNativeMenus` on Android, the host side of `Menus` in `@ng-native/device`.
10
+ *
11
+ * Android draws no menu bar, so `setMenuBar` is not here and `menuBar` is false: `Menus` sends the
12
+ * bar's shortcuts with every `[shortcut]` through `setShortcuts`. A hardware keyboard's chord reaches
13
+ * them through the window's key-shortcut dispatch, after a focused view has had it, so a text input
14
+ * keeps Ctrl-Z, X, C, V and A; the Keyboard Shortcuts helper (Meta-/) lists them by group.
15
+ *
16
+ * `setContextMenu` keeps each `[contextMenu]` by its view's `nativeID`, since React Native's view
17
+ * drops a `contextMenu` prop it does not know. A long press or a right-click on the view opens it
18
+ * as a PopupMenu at the press point, and so does the view's long-press accessibility action.
19
+ * `setTakesLongPress` names views inside one that take a long press themselves, where a long press
20
+ * opens no menu.
21
+ */
22
+ class MenusModule : Module() {
23
+ private val main = Handler(Looper.getMainLooper())
24
+
25
+ /** This module's own sender, which `MenuHost` holds while this module is the app's. */
26
+ private val sender: (Map<String, Any?>) -> Unit = { body -> sendEvent("ngNativeMenus", body) }
27
+
28
+ override fun definition() = ModuleDefinition {
29
+ Name("NgNativeMenus")
30
+
31
+ Constant("menuBar") { false }
32
+ Constant("appName") {
33
+ val context = appContext.reactContext ?: return@Constant ""
34
+ context.applicationInfo.loadLabel(context.packageManager).toString()
35
+ }
36
+
37
+ Events("ngNativeMenus")
38
+
39
+ Function("setShortcuts") { shortcuts: List<Map<String, Any?>> ->
40
+ val parsed = shortcuts.mapNotNull(Shortcut::from)
41
+ main.post { MenuHost.shortcuts = parsed }
42
+ }
43
+
44
+ Function("setContextMenu") { nativeId: String, entries: List<Map<String, Any?>>? ->
45
+ main.post {
46
+ if (entries.isNullOrEmpty()) MenuHost.contextMenus.remove(nativeId)
47
+ else MenuHost.contextMenus[nativeId] = entries
48
+ ContextMenuAccessibility.update(appContext.currentActivity, nativeId)
49
+ }
50
+ }
51
+
52
+ Function("setTakesLongPress") { nativeId: String, takes: Boolean ->
53
+ main.post {
54
+ if (takes) {
55
+ MenuHost.longPressTakers.add(nativeId)
56
+ } else {
57
+ MenuHost.longPressTakers.remove(nativeId)
58
+ }
59
+ }
60
+ }
61
+
62
+ // On the main thread, in order with the old module's `OnDestroy` and every call after.
63
+ OnCreate {
64
+ main.post { MenuHost.attach(sender) }
65
+ watchActivity()
66
+ }
67
+
68
+ // A recreated activity is a new window, which the menus move to.
69
+ OnActivityEntersForeground { watchActivity() }
70
+
71
+ // A reload makes a new module, which starts with no shortcuts or menus. The old one lets go
72
+ // only of what it set: the new one may have attached first.
73
+ OnDestroy {
74
+ main.post {
75
+ MenuHost.detach(sender)
76
+ if (MenuHost.send == null) ContextMenuAccessibility.stop()
77
+ }
78
+ }
79
+ }
80
+
81
+ private fun watchActivity() {
82
+ val activity = appContext.currentActivity ?: return
83
+ main.post { MenuWindowCallback.install(activity) }
84
+ }
85
+ }