@octane-xplat/context-menu 0.0.1 → 0.10.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.
@@ -0,0 +1,158 @@
1
+ // Adapted from @expo/ui (MIT) — Copyright 2025-present 650 Industries.
2
+ // Upstream: expo/packages/expo-ui/android/.../ui/menu/DropdownMenu.kt,
3
+ // DropdownMenuItem.kt, DropdownMenuRecords.kt (sdk-57).
4
+ // The ExpoModules glue (ComposeProps records, slot views, ModifierRegistry)
5
+ // is replaced by the @nativescript/jetpack-compose provider contract:
6
+ // updateData(Map) + onEvent. The trigger child is a registered
7
+ // NativeScript view hosted through AndroidView — XplatViewRegistry is the
8
+ // leaf-side counterpart of iOS's NativeScriptViewFactory-by-id.
9
+
10
+ package com.octanexplat.contextmenu
11
+
12
+ import android.view.View
13
+ import android.view.ViewGroup
14
+ import androidx.compose.foundation.layout.Box
15
+ import androidx.compose.material3.DropdownMenu
16
+ import androidx.compose.material3.DropdownMenuItem
17
+ import androidx.compose.material3.HorizontalDivider
18
+ import androidx.compose.material3.MaterialTheme
19
+ import androidx.compose.material3.Text
20
+ import androidx.compose.runtime.Composable
21
+ import androidx.compose.runtime.getValue
22
+ import androidx.compose.runtime.mutableStateOf
23
+ import androidx.compose.runtime.setValue
24
+ import androidx.compose.ui.platform.ComposeView
25
+ import androidx.compose.ui.viewinterop.AndroidView
26
+ import org.json.JSONObject
27
+ import java.lang.ref.WeakReference
28
+
29
+ /** id → NativeScript view registry, callable directly from JS
30
+ * (`com.octanexplat.contextmenu.XplatViewRegistry.register`). The leaf's
31
+ * TSRX wrapper registers the trigger host's android.view.View before the
32
+ * ComposeView reads it back inside AndroidView. Weak refs — JS owns the
33
+ * view's real lifecycle and unregisters on unmount. */
34
+ object XplatViewRegistry {
35
+ private val views = HashMap<String, WeakReference<View>>()
36
+
37
+ @JvmStatic
38
+ fun register(id: String, view: View) {
39
+ views[id] = WeakReference(view)
40
+ }
41
+
42
+ @JvmStatic
43
+ fun unregister(id: String) {
44
+ views.remove(id)
45
+ }
46
+
47
+ @JvmStatic
48
+ fun get(id: String): View? = views[id]?.get()
49
+ }
50
+
51
+ private data class ContextMenuItemSpec(
52
+ val id: String,
53
+ val title: String,
54
+ val destructive: Boolean,
55
+ val disabled: Boolean,
56
+ val divider: Boolean,
57
+ )
58
+
59
+ private data class ContextMenuUiState(
60
+ val triggerId: String = "",
61
+ val expanded: Boolean = false,
62
+ val items: List<ContextMenuItemSpec> = emptyList(),
63
+ )
64
+
65
+ private fun Any?.asBoolean(): Boolean = when (this) {
66
+ is Boolean -> this
67
+ is Number -> toInt() != 0
68
+ else -> false
69
+ }
70
+
71
+ private fun Any?.asList(): List<Any?> = when (this) {
72
+ is org.json.JSONArray -> (0 until length()).map { get(it) }
73
+ is List<*> -> this
74
+ else -> emptyList()
75
+ }
76
+
77
+ private fun Any?.field(key: String): Any? = when (this) {
78
+ is org.json.JSONObject -> if (has(key)) get(key) else null
79
+ is Map<*, *> -> this[key]
80
+ else -> null
81
+ }
82
+
83
+ private fun parseItems(raw: Any?): List<ContextMenuItemSpec> {
84
+ return raw.asList().mapNotNull { entry ->
85
+ entry ?: return@mapNotNull null
86
+ ContextMenuItemSpec(
87
+ id = entry.field("id") as? String ?: return@mapNotNull null,
88
+ title = entry.field("title") as? String ?: "",
89
+ destructive = entry.field("destructive").asBoolean(),
90
+ disabled = entry.field("disabled").asBoolean(),
91
+ divider = entry.field("divider").asBoolean(),
92
+ )
93
+ }
94
+ }
95
+
96
+ @Composable
97
+ private fun ContextMenuContent(state: ContextMenuUiState, onDismiss: () -> Unit, onSelect: (String) -> Unit) {
98
+ Box {
99
+ val triggerId = state.triggerId
100
+ if (triggerId.isNotEmpty()) {
101
+ AndroidView(
102
+ factory = { ctx ->
103
+ XplatViewRegistry.get(triggerId) ?: View(ctx).apply {
104
+ layoutParams = ViewGroup.LayoutParams(0, 0)
105
+ }
106
+ },
107
+ )
108
+ }
109
+
110
+ // Expanded is controlled: activation lives in the NativeScript touch
111
+ // layer (the embedded subtree consumes pointer input before Compose
112
+ // gesture detection can resolve it), dismissal is reported back so
113
+ // the JS side can close the loop.
114
+ DropdownMenu(
115
+ expanded = state.expanded,
116
+ onDismissRequest = onDismiss,
117
+ ) {
118
+ state.items.forEach { item ->
119
+ if (item.divider) {
120
+ HorizontalDivider()
121
+ }
122
+ DropdownMenuItem(
123
+ text = { Text(item.title) },
124
+ enabled = !item.disabled,
125
+ onClick = {
126
+ onSelect(item.id)
127
+ },
128
+ )
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ class XplatContextMenuProvider {
135
+ private var state by mutableStateOf(ContextMenuUiState())
136
+ var onEvent: ((Any) -> Unit)? = null
137
+
138
+ fun generateComposeView(view: ComposeView) {
139
+ view.setContent {
140
+ MaterialTheme {
141
+ ContextMenuContent(
142
+ state = state,
143
+ onDismiss = { onEvent?.invoke(JSONObject().put("dismissed", true)) },
144
+ onSelect = { id -> onEvent?.invoke(JSONObject().put("item", id)) },
145
+ )
146
+ }
147
+ }
148
+ }
149
+
150
+ fun updateData(input: Map<Any, Any>) {
151
+ val data = input["data"] as? Map<*, *> ?: input
152
+ state = ContextMenuUiState(
153
+ triggerId = data["triggerId"] as? String ?: "",
154
+ expanded = data["expanded"].asBoolean(),
155
+ items = parseItems(data["items"]),
156
+ )
157
+ }
158
+ }
@@ -0,0 +1,123 @@
1
+ // Adapted from @expo/ui (MIT) — Copyright 2025-present 650 Industries.
2
+ // Upstream: expo/packages/expo-ui/ios/ContextMenu/ContextMenu.swift (sdk-57).
3
+ // The ExpoModules glue (children slot views, EventDispatcher) is replaced by
4
+ // the @nativescript/swift-ui provider contract: the activation element is a
5
+ // UIViewRepresentable resolved by id from NativeScriptViewFactory (the same
6
+ // lookup the plugin's own NativeScriptView uses — re-declared here because
7
+ // the plugin's struct is module-internal), and menu content arrives as
8
+ // serialized item data through updateData(NSDictionary) + onEvent.
9
+
10
+ import SwiftUI
11
+
12
+ private struct ContextMenuItemSpec: Identifiable {
13
+ let id: String
14
+ let title: String
15
+ let destructive: Bool
16
+ let disabled: Bool
17
+ let divider: Bool
18
+ }
19
+
20
+ private final class ContextMenuModel: ObservableObject {
21
+ @Published var triggerId: String = ""
22
+ @Published var previewId: String = ""
23
+ @Published var items: [ContextMenuItemSpec] = []
24
+ var onSelect: ((String) -> Void)?
25
+ }
26
+
27
+ // Same shape as the plugin's NativeScriptViewRepresentable: a unique
28
+ // instance id (registered id + uuid) resolved through the core-owned
29
+ // NativeScriptViewFactory, which the JS-side SwiftUIManager hooks up.
30
+ private struct HostedNativeScriptView: UIViewRepresentable {
31
+ let id: String
32
+
33
+ init(id: String) {
34
+ self.id = id + "-" + UUID().uuidString
35
+ }
36
+
37
+ func makeUIView(context: Context) -> UIView {
38
+ return NativeScriptViewFactory.shared?.getViewById(id) ?? UIView()
39
+ }
40
+
41
+ func updateUIView(_ uiView: UIView, context: Context) {}
42
+ }
43
+
44
+ @available(iOS 14.0, *)
45
+ private struct ContextMenuContent: View {
46
+ @ObservedObject var model: ContextMenuModel
47
+
48
+ private var menuItems: some View {
49
+ ForEach(model.items) { item in
50
+ if item.divider {
51
+ Divider()
52
+ }
53
+ Button(role: item.destructive ? .destructive : nil) {
54
+ model.onSelect?(item.id)
55
+ } label: {
56
+ Text(item.title)
57
+ }
58
+ .disabled(item.disabled)
59
+ }
60
+ }
61
+
62
+ var body: some View {
63
+ if model.triggerId.isEmpty {
64
+ EmptyView()
65
+ } else if #available(iOS 16.0, tvOS 16.0, *), !model.previewId.isEmpty {
66
+ HostedNativeScriptView(id: model.triggerId)
67
+ .contextMenu(menuItems: { menuItems }, preview: {
68
+ HostedNativeScriptView(id: model.previewId)
69
+ })
70
+ } else {
71
+ HostedNativeScriptView(id: model.triggerId)
72
+ .contextMenu(menuItems: { menuItems })
73
+ }
74
+ }
75
+ }
76
+
77
+ @objc(XplatContextMenuProvider)
78
+ public final class XplatContextMenuProvider: UIViewController, SwiftUIProvider {
79
+ private let model = ContextMenuModel()
80
+
81
+ public required init() {
82
+ super.init(nibName: nil, bundle: nil)
83
+ model.onSelect = { [weak self] id in
84
+ self?.onEvent?(["item": id])
85
+ }
86
+ }
87
+
88
+ public required init?(coder: NSCoder) {
89
+ super.init(coder: coder)
90
+ model.onSelect = { [weak self] id in
91
+ self?.onEvent?(["item": id])
92
+ }
93
+ }
94
+
95
+ public override func viewDidLoad() {
96
+ super.viewDidLoad()
97
+ if #available(iOS 14.0, *) {
98
+ setupSwiftUIView(content: ContextMenuContent(model: model))
99
+ }
100
+ }
101
+
102
+ public func updateData(data: NSDictionary) {
103
+ if let triggerId = data["triggerId"] as? String {
104
+ model.triggerId = triggerId
105
+ }
106
+ if let previewId = data["previewId"] as? String {
107
+ model.previewId = previewId
108
+ }
109
+ if let items = data["items"] as? [NSDictionary] {
110
+ model.items = items.map { raw in
111
+ ContextMenuItemSpec(
112
+ id: raw["id"] as? String ?? "",
113
+ title: raw["title"] as? String ?? "",
114
+ destructive: (raw["destructive"] as? NSNumber)?.boolValue ?? false,
115
+ disabled: (raw["disabled"] as? NSNumber)?.boolValue ?? false,
116
+ divider: (raw["divider"] as? NSNumber)?.boolValue ?? false,
117
+ )
118
+ }
119
+ }
120
+ }
121
+
122
+ public var onEvent: ((NSDictionary) -> Void)?
123
+ }
@@ -0,0 +1,33 @@
1
+ /** @jsxImportSource @octane-xplat/macos-renderer */
2
+ import { useEffect, useRef } from 'octane'
3
+ import type { AppKitContextMenuProps } from './macos/types'
4
+
5
+ const host = (): any => (globalThis as any).__xplatAppKit ?? {}
6
+
7
+ /** macOS context menu — the trigger renders inline as this element's
8
+ * children and a real NSMenu is attached to the backing NSView's `menu`,
9
+ * so AppKit drives right-click activation and disabled items. Items are
10
+ * serialized data; selection reports through `onItemSelected`. */
11
+ export function AppKitContextMenu(props: AppKitContextMenuProps) @{
12
+ const anchor = useRef<any>(null)
13
+
14
+ useEffect(() => {
15
+ const view = anchor.current
16
+ const attach = host().attachContextMenu
17
+ if (!view || typeof attach !== 'function') return
18
+ return attach(
19
+ view,
20
+ { items: props.items ?? [] },
21
+ (id: string) => props.onItemSelected?.(id),
22
+ )
23
+ }, [props.items])
24
+
25
+ <flexboxlayout
26
+ ref={(v: any) => { anchor.current = v }}
27
+ id={props.id}
28
+ className={props.className}
29
+ style={props.style}
30
+ >
31
+ {props.trigger()}
32
+ </flexboxlayout>;
33
+ }
@@ -0,0 +1,84 @@
1
+ /** @jsxImportSource octane */
2
+ import { useState } from 'octane'
3
+ import type { ContextMenuProps } from './web/types'
4
+
5
+ /** Web context menu: the trigger subtree renders inline; right-click (or
6
+ * long-press via the `activation` prop's 'singlePress' = click) opens an
7
+ * in-page menu at the pointer. */
8
+ export function ContextMenu(props: ContextMenuProps) @{
9
+ const [menu, setMenu] = useState<{ x: number; y: number } | null>(null)
10
+ const items = props.items ?? []
11
+ const openAt = (e: any) => {
12
+ e.preventDefault?.()
13
+ setMenu({ x: e.clientX ?? 0, y: e.clientY ?? 0 })
14
+ }
15
+
16
+ <span
17
+ id={props.id}
18
+ className={props.className}
19
+ style={{ display: 'inline-block', ...(props.style ?? {}) }}
20
+ onContextMenu={props.activation === 'singlePress' ? undefined : openAt}
21
+ onClick={props.activation === 'singlePress' ? openAt : undefined}
22
+ aria-label={props.accessibilityLabel}
23
+ >
24
+ {props.trigger()}
25
+ {menu && (
26
+ <>
27
+ <span
28
+ style={{ position: 'fixed', inset: 0, zIndex: 999 }}
29
+ onClick={() => setMenu(null)}
30
+ onContextMenu={(e: any) => {
31
+ e.preventDefault?.()
32
+ setMenu(null)
33
+ }}
34
+ />
35
+ <ul
36
+ role="menu"
37
+ style={{
38
+ position: 'fixed',
39
+ left: menu.x,
40
+ top: menu.y,
41
+ zIndex: 1000,
42
+ margin: 0,
43
+ padding: '4px 0',
44
+ listStyle: 'none',
45
+ background: 'var(--menu-bg, Canvas)',
46
+ color: 'var(--menu-fg, CanvasText)',
47
+ border: '1px solid color-mix(in srgb, CanvasText 20%, transparent)',
48
+ borderRadius: 8,
49
+ boxShadow: '0 6px 24px rgb(0 0 0 / 0.18)',
50
+ minWidth: 160,
51
+ }}
52
+ >
53
+ {items.map((item) => (
54
+ <>
55
+ {item.divider && (
56
+ <li
57
+ aria-hidden="true"
58
+ style={{ borderTop: '1px solid color-mix(in srgb, CanvasText 15%, transparent)', margin: '4px 0' }}
59
+ />
60
+ )}
61
+ <li
62
+ role="menuitem"
63
+ aria-disabled={item.disabled || undefined}
64
+ style={{
65
+ padding: '6px 12px',
66
+ cursor: item.disabled ? 'default' : 'pointer',
67
+ opacity: item.disabled ? 0.5 : 1,
68
+ color: item.destructive ? 'crimson' : undefined,
69
+ }}
70
+ onClick={() => {
71
+ if (item.disabled) return
72
+ setMenu(null)
73
+ props.onItemSelected?.(item.id)
74
+ }}
75
+ >
76
+ {item.title}
77
+ </li>
78
+ </>
79
+ ))}
80
+ </ul>
81
+ </>
82
+ )}
83
+ </span>;
84
+ }
@@ -0,0 +1,125 @@
1
+ /** @jsxImportSource @nativescript-community/octane */
2
+ import { registerElement } from '@nativescript-community/octane'
3
+ import type { Attributes } from '@nativescript-community/octane/intrinsics'
4
+ import { ComposeDataDriver, JetpackCompose, registerJetpackCompose } from '@nativescript/jetpack-compose'
5
+ import { Application, GridLayout } from '@nativescript/core'
6
+ import { createNativeScriptRoot } from '@nativescript-community/octane'
7
+ import { useEffect, useRef, useState } from 'octane'
8
+ import type { UniversalComponent } from 'octane/universal'
9
+ import type { MaterialContextMenuProps } from './android/types'
10
+
11
+ declare const com: any
12
+
13
+ declare module '@nativescript-community/octane/intrinsics' {
14
+ interface NativeScriptElements {
15
+ xplatandroidcontextmenu: Attributes<typeof JetpackCompose>
16
+ }
17
+ }
18
+
19
+ registerElement('xplatandroidcontextmenu', JetpackCompose)
20
+ registerJetpackCompose('xplat-material-contextmenu', (owner: any) =>
21
+ new ComposeDataDriver(new com.octanexplat.contextmenu.XplatContextMenuProvider(), owner),
22
+ )
23
+
24
+ // Dash-free ids — the host-side representable appends "-<uuid>" and the
25
+ // registry lookup splits on the first dash.
26
+ let seq = 0
27
+
28
+ function TriggerRoot(props: { render: () => any }) @{
29
+ <>{props.render()}</>;
30
+ }
31
+
32
+ /** Renders a Material 3 DropdownMenu anchored to a NativeScript-hosted
33
+ * trigger subtree. The trigger mounts into a detached octane root whose
34
+ * android.view.View the provider embeds through AndroidView. */
35
+ export function MaterialContextMenu(props: MaterialContextMenuProps) @{
36
+ const triggerId = useRef<string>('')
37
+ if (!triggerId.current) {
38
+ triggerId.current = `ctxmenu${++seq}`
39
+ }
40
+
41
+ const mounted = useRef<{ host: any; root: any } | null>(null)
42
+ const [ready, setReady] = useState(false)
43
+ const [expanded, setExpanded] = useState(false)
44
+
45
+ useEffect(() => {
46
+ const host = new GridLayout()
47
+ // Detached subtree — the plugin's generateNativeView shortcut passes
48
+ // `{}` as the native context, which fails to marshal on Android; the
49
+ // view factory needs a real android.content.Context to build its
50
+ // native view.
51
+
52
+ const context = (Application.android as any).foregroundActivity ?? (Application.android as any).startActivity
53
+ const nativeHost = host as any
54
+
55
+ nativeHost._setupAsRootView(context)
56
+ nativeHost.callLoaded()
57
+ const root = createNativeScriptRoot(host)
58
+ root.render(TriggerRoot as unknown as UniversalComponent, { render: props.trigger })
59
+ com.octanexplat.contextmenu.XplatViewRegistry.register(triggerId.current, host.android)
60
+ mounted.current = { host, root }
61
+ // Activation is an NS gesture on the trigger host — the hosted
62
+ // subtree consumes pointer input before Compose's gesture detectors
63
+ // could resolve it, so expanded is pushed through data instead.
64
+ const open = () => setExpanded(true)
65
+
66
+ if ((props.activation ?? 'longPress') === 'singlePress') {
67
+ host.on('tap', open)
68
+ } else {
69
+ host.on('longPress', open)
70
+ }
71
+
72
+ // Gate triggerId on registration — the provider only composes the
73
+ // AndroidView host once triggerId is non-empty, so the factory must
74
+ // find the view in the registry on first read.
75
+ setReady(true)
76
+
77
+ return () => {
78
+ com.octanexplat.contextmenu.XplatViewRegistry.unregister(triggerId.current)
79
+ nativeHost.off()
80
+ root.unmount?.()
81
+ mounted.current = null
82
+ setReady(false)
83
+ }
84
+ }, [])
85
+
86
+ useEffect(() => {
87
+ mounted.current?.root?.render(TriggerRoot as unknown as UniversalComponent, {
88
+ render: props.trigger,
89
+ })
90
+ }, [props.trigger])
91
+
92
+ const items = props.items ?? []
93
+
94
+ <xplatandroidcontextmenu
95
+ id={props.id}
96
+ className={props.className}
97
+ style={props.style}
98
+ accessibilityLabel={props.accessibilityLabel}
99
+ composeId="xplat-material-contextmenu"
100
+ data={{
101
+ triggerId: ready ? triggerId.current : '',
102
+ expanded: expanded ? 1 : 0,
103
+ items: items.map((item) => ({
104
+ id: item.id,
105
+ title: item.title,
106
+ // The bridge's dataSerialize throws on booleans; send numbers.
107
+ destructive: item.destructive ? 1 : 0,
108
+ disabled: item.disabled ? 1 : 0,
109
+ divider: item.divider ? 1 : 0,
110
+ })),
111
+ }}
112
+ onComposeEvent={(event: any) => {
113
+ if (event.data?.dismissed) {
114
+ setExpanded(false)
115
+ return
116
+ }
117
+
118
+ const item = event.data?.item
119
+ if (typeof item === 'string' && item) {
120
+ setExpanded(false)
121
+ props.onItemSelected?.(item)
122
+ }
123
+ }}
124
+ />;
125
+ }
@@ -0,0 +1,127 @@
1
+ /** @jsxImportSource @nativescript-community/octane */
2
+ import { registerElement } from '@nativescript-community/octane'
3
+ import type { Attributes } from '@nativescript-community/octane/intrinsics'
4
+ import { SwiftUI, UIDataDriver, registerSwiftUI, SwiftUIManager } from '@nativescript/swift-ui'
5
+ import { GridLayout } from '@nativescript/core'
6
+ import { createNativeScriptRoot } from '@nativescript-community/octane'
7
+ import { useEffect, useRef, useState } from 'octane'
8
+ import type { UniversalComponent, UniversalRoot } from 'octane/universal'
9
+ import type { SwiftUIContextMenuProps } from './ios/types'
10
+
11
+ declare const XplatContextMenuProvider: any
12
+
13
+ declare module '@nativescript-community/octane/intrinsics' {
14
+ interface NativeScriptElements {
15
+ xplatioscontextmenu: Attributes<typeof SwiftUI>
16
+ }
17
+ }
18
+
19
+ registerElement('xplatioscontextmenu', SwiftUI)
20
+ registerSwiftUI('xplat-swiftui-contextmenu', (owner: any) =>
21
+ new UIDataDriver(new XplatContextMenuProvider(), owner),
22
+ )
23
+
24
+ // Host views keyed by dash-free registry id — the provider's representable
25
+ // appends "-<uuid>" and the factory looks the host up by the first segment.
26
+ const hosts = new Map<string, GridLayout>()
27
+ const roots = new Map<string, UniversalRoot>()
28
+
29
+ function mountSubtree(id: string, render: () => any): void {
30
+ let host = hosts.get(id)
31
+ if (!host) {
32
+ host = new GridLayout()
33
+ hosts.set(id, host)
34
+ // Register the id the first time the host exists — the factory's
35
+ // lifecycle resolves it back out of this map.
36
+ SwiftUIManager.registerNativeScriptViews(
37
+ { [id]: true },
38
+ {
39
+ create: (fullId: string) => hosts.get(fullId.split('-')[0]) as any,
40
+ destroy: (fullId: string) => {
41
+ hosts.delete(fullId.split('-')[0])
42
+ },
43
+ } as any,
44
+ )
45
+ }
46
+
47
+ let root = roots.get(id)
48
+ if (!root) {
49
+ root = createNativeScriptRoot(host)
50
+ roots.set(id, root)
51
+ }
52
+
53
+ root.render(TriggerRoot as unknown as UniversalComponent, { render })
54
+ }
55
+
56
+ function unmountSubtree(id: string): void {
57
+ roots.get(id)?.unmount?.()
58
+ roots.delete(id)
59
+ hosts.delete(id)
60
+ }
61
+
62
+ function TriggerRoot(props: { render: () => any }) @{
63
+ <>{props.render()}</>;
64
+ }
65
+
66
+ let seq = 0
67
+
68
+ /** Renders a SwiftUI .contextMenu whose activation element is a detached
69
+ * octane subtree embedded through the plugin's NativeScriptView-by-id
70
+ * factory. Menu items arrive as serialized data. */
71
+ export function SwiftUIContextMenu(props: SwiftUIContextMenuProps) @{
72
+ const triggerId = useRef<string>('')
73
+ if (!triggerId.current) {
74
+ triggerId.current = `ctxmenu${++seq}`
75
+ }
76
+
77
+ const [ready, setReady] = useState(false)
78
+
79
+ useEffect(() => {
80
+ mountSubtree(triggerId.current, props.trigger)
81
+ // Gate triggerId on registration — the representable resolves the id
82
+ // through NativeScriptViewFactory on first composition.
83
+ setReady(true)
84
+
85
+ return () => {
86
+ unmountSubtree(triggerId.current)
87
+ setReady(false)
88
+ }
89
+ }, [])
90
+
91
+ useEffect(() => {
92
+ mountSubtree(triggerId.current, props.trigger)
93
+ }, [props.trigger])
94
+
95
+ useEffect(() => {
96
+ if (props.preview) {
97
+ mountSubtree(`${triggerId.current}preview`, props.preview)
98
+ }
99
+ }, [props.preview])
100
+
101
+ const items = props.items ?? []
102
+
103
+ <xplatioscontextmenu
104
+ id={props.id}
105
+ className={props.className}
106
+ style={props.style}
107
+ accessibilityLabel={props.accessibilityLabel}
108
+ swiftId="xplat-swiftui-contextmenu"
109
+ data={{
110
+ triggerId: ready ? triggerId.current : '',
111
+ previewId: ready && props.preview ? `${triggerId.current}preview` : '',
112
+ items: items.map((item) => ({
113
+ id: item.id,
114
+ title: item.title,
115
+ destructive: item.destructive ? 1 : 0,
116
+ disabled: item.disabled ? 1 : 0,
117
+ divider: item.divider ? 1 : 0,
118
+ })),
119
+ }}
120
+ onSwiftUIEvent={(event: any) => {
121
+ const item = event.data?.item
122
+ if (typeof item === 'string' && item) {
123
+ props.onItemSelected?.(item)
124
+ }
125
+ }}
126
+ />;
127
+ }
@@ -0,0 +1,6 @@
1
+ export { MaterialContextMenu } from '../MaterialContextMenu.android.tsrx'
2
+ export type {
3
+ MaterialContextMenuActivation,
4
+ MaterialContextMenuItem,
5
+ MaterialContextMenuProps,
6
+ } from './types'
@@ -0,0 +1,26 @@
1
+ export type MaterialContextMenuActivation = 'longPress' | 'singlePress'
2
+
3
+ /** One row of serialized menu content carried over the bridge. */
4
+ export interface MaterialContextMenuItem {
5
+ /** Stable id reported to `onItemSelected`. */
6
+ id: string
7
+ title: string
8
+ destructive?: boolean
9
+ disabled?: boolean
10
+ /** Render a divider before this item. */
11
+ divider?: boolean
12
+ }
13
+
14
+ export interface MaterialContextMenuProps {
15
+ id?: string
16
+ className?: any
17
+ style?: any
18
+ /** Activation gesture. @default 'longPress' */
19
+ activation?: MaterialContextMenuActivation
20
+ items?: readonly MaterialContextMenuItem[]
21
+ /** Render fn producing the trigger subtree — hosted inside the menu's
22
+ * anchor via AndroidView. */
23
+ trigger: () => any
24
+ onItemSelected?: (id: string) => void
25
+ accessibilityLabel?: string
26
+ }
@@ -0,0 +1,2 @@
1
+ export { SwiftUIContextMenu } from '../SwiftUIContextMenu.ios.tsrx'
2
+ export type { SwiftUIContextMenuItem, SwiftUIContextMenuProps } from './types'