@octane-xplat/context-menu 0.0.0-stage → 0.9.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Alec Larson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # `@octane-xplat/context-menu`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An install boundary for platform-specific context menus: a SwiftUI
4
+ `.contextMenu` on iOS, a Material 3 `DropdownMenu` anchored to a hosted
5
+ trigger on Android, an in-page right-click menu on web, and a real
6
+ `NSMenu` on the backing view on macOS.
7
+
8
+ Install the package in the app that renders a control. Import
9
+ `SwiftUIContextMenu` from `@octane-xplat/context-menu/ios`,
10
+ `MaterialContextMenu` from `@octane-xplat/context-menu/android`,
11
+ `ContextMenu` from `@octane-xplat/context-menu/web`, or
12
+ `AppKitContextMenu` from `@octane-xplat/context-menu/macos` in the matching
13
+ platform-suffixed file. There is no shared context-menu API at the package
14
+ root.
15
+
16
+ Unlike props-only leaves (picker, date-picker), this leaf exercises subtree
17
+ embedding: `trigger` is a render fn whose octane output mounts into a
18
+ detached root, and the native menu wraps that subtree — SwiftUI resolves it
19
+ through `NativeScriptViewFactory` (the same factory the swift-ui plugin's
20
+ `NativeScriptView` uses), and Android through the leaf's
21
+ `XplatViewRegistry` + `AndroidView`. Menu items cross the bridge as
22
+ serialized data (`{id, title, destructive, disabled, divider}`), reported
23
+ back through `onItemSelected(id)`.
24
+
25
+ - iOS: long-press activation (platform native); optional `preview` render fn
26
+ (iOS 16+).
27
+ - Android: `activation` prop — `'longPress'` (default) or `'singlePress'`,
28
+ detected at parent level so interactive children in the trigger keep
29
+ their own taps.
30
+ - Web: right-click (`longPress`) or click (`singlePress`) opens the menu at
31
+ the pointer.
32
+ - macOS: right-click — the NSMenu is the view's `menu`, so AppKit owns
33
+ activation and disabled-item dimming; the trigger renders inline.
34
+
35
+ The native implementations are adapted from `@expo/ui` (MIT,
36
+ `packages/expo-ui` sdk-57): `ios/ContextMenu/ContextMenu.swift` and
37
+ `android/.../ui/menu/DropdownMenu*.kt`. Attribution headers sit on the
38
+ ported files.
@@ -0,0 +1,103 @@
1
+ import { createNativeScriptRoot, defineUniversalComponent, hookSlots, registerElement, universalPlan, universalValue, useEffect, useRef, useState } from "@nativescript-community/octane";
2
+ import { Application, GridLayout } from "@nativescript/core";
3
+ import { ComposeDataDriver, JetpackCompose, registerJetpackCompose } from "@nativescript/jetpack-compose";
4
+ //#region src/MaterialContextMenu.android.tsrx
5
+ var _hs$ = /* @__PURE__ */ hookSlots(6);
6
+ var _h$0 = /* @__PURE__ */ Symbol(_hs$);
7
+ var _h$1 = /* @__PURE__ */ Symbol(_hs$ + 1);
8
+ var _h$2 = /* @__PURE__ */ Symbol(_hs$ + 2);
9
+ var _h$3 = /* @__PURE__ */ Symbol(_hs$ + 3);
10
+ var _h$4 = /* @__PURE__ */ Symbol(_hs$ + 4);
11
+ var _h$5 = /* @__PURE__ */ Symbol(_hs$ + 5);
12
+ var __octaneUniversalPlan0 = universalPlan("nativescript", {
13
+ "kind": "range",
14
+ "children": [{
15
+ "kind": "slot",
16
+ "slot": 0
17
+ }]
18
+ });
19
+ var __octaneUniversalPlan1 = universalPlan("nativescript", {
20
+ "kind": "host",
21
+ "type": "xplatandroidcontextmenu",
22
+ "props": { "composeId": "xplat-material-contextmenu" },
23
+ "bindings": [
24
+ ["id", 0],
25
+ ["className", 1],
26
+ ["style", 2],
27
+ ["accessibilityLabel", 3],
28
+ ["data", 4],
29
+ ["onComposeEvent", 5]
30
+ ]
31
+ });
32
+ registerElement("xplatandroidcontextmenu", JetpackCompose);
33
+ registerJetpackCompose("xplat-material-contextmenu", (owner) => new ComposeDataDriver(new com.octanexplat.contextmenu.XplatContextMenuProvider(), owner));
34
+ var seq = 0;
35
+ var TriggerRoot = defineUniversalComponent("nativescript", function TriggerRoot(props) {
36
+ return universalValue(__octaneUniversalPlan0, [props.render()]);
37
+ }, { "module": "@nativescript-community/octane" });
38
+ var MaterialContextMenu = defineUniversalComponent("nativescript", function MaterialContextMenu(props) {
39
+ const triggerId = useRef("", _h$0);
40
+ if (!triggerId.current) triggerId.current = `ctxmenu${++seq}`;
41
+ const mounted = useRef(null, _h$1);
42
+ const [ready, setReady] = useState(false, _h$2);
43
+ const [expanded, setExpanded] = useState(false, _h$3);
44
+ useEffect(() => {
45
+ const host = new GridLayout();
46
+ const context = Application.android.foregroundActivity ?? Application.android.startActivity;
47
+ const nativeHost = host;
48
+ nativeHost._setupAsRootView(context);
49
+ nativeHost.callLoaded();
50
+ const root = createNativeScriptRoot(host);
51
+ root.render(TriggerRoot, { render: props.trigger });
52
+ com.octanexplat.contextmenu.XplatViewRegistry.register(triggerId.current, host.android);
53
+ mounted.current = {
54
+ host,
55
+ root
56
+ };
57
+ const open = () => setExpanded(true);
58
+ if ((props.activation ?? "longPress") === "singlePress") host.on("tap", open);
59
+ else host.on("longPress", open);
60
+ setReady(true);
61
+ return () => {
62
+ com.octanexplat.contextmenu.XplatViewRegistry.unregister(triggerId.current);
63
+ nativeHost.off();
64
+ root.unmount?.();
65
+ mounted.current = null;
66
+ setReady(false);
67
+ };
68
+ }, [], _h$4);
69
+ useEffect(() => {
70
+ mounted.current?.root?.render(TriggerRoot, { render: props.trigger });
71
+ }, [props.trigger], _h$5);
72
+ const items = props.items ?? [];
73
+ return universalValue(__octaneUniversalPlan1, [
74
+ props.id,
75
+ props.className,
76
+ props.style,
77
+ props.accessibilityLabel,
78
+ {
79
+ triggerId: ready ? triggerId.current : "",
80
+ expanded: expanded ? 1 : 0,
81
+ items: items.map((item) => ({
82
+ id: item.id,
83
+ title: item.title,
84
+ destructive: item.destructive ? 1 : 0,
85
+ disabled: item.disabled ? 1 : 0,
86
+ divider: item.divider ? 1 : 0
87
+ }))
88
+ },
89
+ (event) => {
90
+ if (event.data?.dismissed) {
91
+ setExpanded(false);
92
+ return;
93
+ }
94
+ const item = event.data?.item;
95
+ if (typeof item === "string" && item) {
96
+ setExpanded(false);
97
+ props.onItemSelected?.(item);
98
+ }
99
+ }
100
+ ]);
101
+ }, { "module": "@nativescript-community/octane" });
102
+ //#endregion
103
+ export { MaterialContextMenu };
@@ -0,0 +1,105 @@
1
+ import { createNativeScriptRoot, defineUniversalComponent, hookSlots, registerElement, universalPlan, universalValue, useEffect, useRef, useState } from "@nativescript-community/octane";
2
+ import { SwiftUI, SwiftUIManager, UIDataDriver, registerSwiftUI } from "@nativescript/swift-ui";
3
+ import { GridLayout } from "@nativescript/core";
4
+ //#region src/SwiftUIContextMenu.ios.tsrx
5
+ var _hs$ = /* @__PURE__ */ hookSlots(5);
6
+ var _h$0 = /* @__PURE__ */ Symbol(_hs$);
7
+ var _h$1 = /* @__PURE__ */ Symbol(_hs$ + 1);
8
+ var _h$2 = /* @__PURE__ */ Symbol(_hs$ + 2);
9
+ var _h$3 = /* @__PURE__ */ Symbol(_hs$ + 3);
10
+ var _h$4 = /* @__PURE__ */ Symbol(_hs$ + 4);
11
+ var __octaneUniversalPlan0 = universalPlan("nativescript", {
12
+ "kind": "range",
13
+ "children": [{
14
+ "kind": "slot",
15
+ "slot": 0
16
+ }]
17
+ });
18
+ var __octaneUniversalPlan1 = universalPlan("nativescript", {
19
+ "kind": "host",
20
+ "type": "xplatioscontextmenu",
21
+ "props": { "swiftId": "xplat-swiftui-contextmenu" },
22
+ "bindings": [
23
+ ["id", 0],
24
+ ["className", 1],
25
+ ["style", 2],
26
+ ["accessibilityLabel", 3],
27
+ ["data", 4],
28
+ ["onSwiftUIEvent", 5]
29
+ ]
30
+ });
31
+ registerElement("xplatioscontextmenu", SwiftUI);
32
+ registerSwiftUI("xplat-swiftui-contextmenu", (owner) => new UIDataDriver(new XplatContextMenuProvider(), owner));
33
+ var hosts = /* @__PURE__ */ new Map();
34
+ var roots = /* @__PURE__ */ new Map();
35
+ function mountSubtree(id, render) {
36
+ let host = hosts.get(id);
37
+ if (!host) {
38
+ host = new GridLayout();
39
+ hosts.set(id, host);
40
+ SwiftUIManager.registerNativeScriptViews({ [id]: true }, {
41
+ create: (fullId) => hosts.get(fullId.split("-")[0]),
42
+ destroy: (fullId) => {
43
+ hosts.delete(fullId.split("-")[0]);
44
+ }
45
+ });
46
+ }
47
+ let root = roots.get(id);
48
+ if (!root) {
49
+ root = createNativeScriptRoot(host);
50
+ roots.set(id, root);
51
+ }
52
+ root.render(TriggerRoot, { render });
53
+ }
54
+ function unmountSubtree(id) {
55
+ roots.get(id)?.unmount?.();
56
+ roots.delete(id);
57
+ hosts.delete(id);
58
+ }
59
+ var TriggerRoot = defineUniversalComponent("nativescript", function TriggerRoot(props) {
60
+ return universalValue(__octaneUniversalPlan0, [props.render()]);
61
+ }, { "module": "@nativescript-community/octane" });
62
+ var seq = 0;
63
+ var SwiftUIContextMenu = defineUniversalComponent("nativescript", function SwiftUIContextMenu(props) {
64
+ const triggerId = useRef("", _h$0);
65
+ if (!triggerId.current) triggerId.current = `ctxmenu${++seq}`;
66
+ const [ready, setReady] = useState(false, _h$1);
67
+ useEffect(() => {
68
+ mountSubtree(triggerId.current, props.trigger);
69
+ setReady(true);
70
+ return () => {
71
+ unmountSubtree(triggerId.current);
72
+ setReady(false);
73
+ };
74
+ }, [], _h$2);
75
+ useEffect(() => {
76
+ mountSubtree(triggerId.current, props.trigger);
77
+ }, [props.trigger], _h$3);
78
+ useEffect(() => {
79
+ if (props.preview) mountSubtree(`${triggerId.current}preview`, props.preview);
80
+ }, [props.preview], _h$4);
81
+ const items = props.items ?? [];
82
+ return universalValue(__octaneUniversalPlan1, [
83
+ props.id,
84
+ props.className,
85
+ props.style,
86
+ props.accessibilityLabel,
87
+ {
88
+ triggerId: ready ? triggerId.current : "",
89
+ previewId: ready && props.preview ? `${triggerId.current}preview` : "",
90
+ items: items.map((item) => ({
91
+ id: item.id,
92
+ title: item.title,
93
+ destructive: item.destructive ? 1 : 0,
94
+ disabled: item.disabled ? 1 : 0,
95
+ divider: item.divider ? 1 : 0
96
+ }))
97
+ },
98
+ (event) => {
99
+ const item = event.data?.item;
100
+ if (typeof item === "string" && item) props.onItemSelected?.(item);
101
+ }
102
+ ]);
103
+ }, { "module": "@nativescript-community/octane" });
104
+ //#endregion
105
+ export { SwiftUIContextMenu };
@@ -0,0 +1,2 @@
1
+ import { MaterialContextMenu } from "../MaterialContextMenu.android.tsrx.js";
2
+ export { MaterialContextMenu };
@@ -0,0 +1,2 @@
1
+ import { SwiftUIContextMenu } from "../SwiftUIContextMenu.ios.tsrx.js";
2
+ export { SwiftUIContextMenu };
@@ -0,0 +1,8 @@
1
+ {
2
+ "version": 1,
3
+ "buildId": "3af73beb-7850-41a6-9561-349004721415",
4
+ "mode": "production",
5
+ "capabilities": {
6
+ "independentHydration": false
7
+ }
8
+ }
@@ -0,0 +1,101 @@
1
+ import { Fragment, __s, bag11, child, clone, createElement, createScopedElement, createScopedValue, delegateEvents, hookSlots, positionalChildren, setAriaAttribute, setEventHandler, setStyle, sibling, template, useState } from "octane";
2
+ import { bindSignalAttribute, bindSignalChild, compilerMemoRegion, enableSignalBindings, hookMemoCreate, hookMemoPublishInvariant, setPlainAttribute } from "octane/internal/client";
3
+ //#region src/ContextMenu.web.tsrx
4
+ enableSignalBindings(1, true);
5
+ delegateEvents(["click", "contextmenu"]);
6
+ var _t$0 = /* @__PURE__ */ template("<span><!><!></span>");
7
+ var _hs$ = /* @__PURE__ */ hookSlots(1);
8
+ var ContextMenu = /* @__PURE__ */ __s(function ContextMenu(props, __s, __extra) {
9
+ const __memoRegion = compilerMemoRegion(__s, _hs$ + 0);
10
+ let __hk = __memoRegion.hooks;
11
+ if (__hk === void 0) __memoRegion.hooks = __hk = hookMemoCreate(1);
12
+ const [menu, setMenu] = useState(null, _hs$ + 0);
13
+ const items = props.items ?? [];
14
+ const openAt = __hk[0] ?? hookMemoPublishInvariant(__hk, 0, (e) => {
15
+ e.preventDefault?.();
16
+ setMenu({
17
+ x: e.clientX ?? 0,
18
+ y: e.clientY ?? 0
19
+ });
20
+ });
21
+ let _b = __s.slots[0];
22
+ if (_b === void 0) {
23
+ let _m1, _m5, _m8;
24
+ const _root = clone(_t$0);
25
+ _m1 = _root;
26
+ setEventHandler(_root, "$$contextmenu", props.activation === "singlePress" ? void 0 : openAt);
27
+ setEventHandler(_root, "$$click", props.activation === "singlePress" ? openAt : void 0);
28
+ const _el0 = child(_root);
29
+ _m5 = _el0;
30
+ _m8 = sibling(_el0, 1);
31
+ _b = bag11(__s, _root, void 0, _m1, void 0, void 0, void 0, _m5, null, void 0, _m8, null, void 0);
32
+ } else {
33
+ setEventHandler(_b.b, "$$contextmenu", props.activation === "singlePress" ? void 0 : openAt);
34
+ setEventHandler(_b.b, "$$click", props.activation === "singlePress" ? openAt : void 0);
35
+ }
36
+ _b.a = bindSignalAttribute(__s, _b.a, _b.b, "id", props.id, "b:d5b82f97", setPlainAttribute);
37
+ _b.c = bindSignalAttribute(__s, _b.c, _b.b, "class", props.className, "b:722f753c", "class");
38
+ {
39
+ const _v = {
40
+ display: "inline-block",
41
+ ...props.style ?? {}
42
+ };
43
+ if (_b.d !== _v) {
44
+ setStyle(_b.b, _v, _b.d);
45
+ _b.d = _v;
46
+ }
47
+ }
48
+ _b.e = bindSignalAttribute(__s, _b.e, _b.b, "aria-label", props.accessibilityLabel, "b:a27ad92a", setAriaAttribute);
49
+ _b.l = bindSignalChild(__s, _b.l, 1, _b.b, props.trigger(), "b:6a5a30ce", _b.f, true, void 0, void 0, void 0);
50
+ _b.m = bindSignalChild(__s, _b.m, 2, _b.b, menu && createScopedElement(Fragment, {}, () => positionalChildren([createScopedValue(() => createElement("span", {
51
+ style: {
52
+ position: "fixed",
53
+ inset: 0,
54
+ zIndex: 999
55
+ },
56
+ onClick: () => setMenu(null),
57
+ onContextMenu: (e) => {
58
+ e.preventDefault?.();
59
+ setMenu(null);
60
+ }
61
+ })), createScopedValue(() => createScopedElement("ul", {
62
+ role: "menu",
63
+ style: {
64
+ position: "fixed",
65
+ left: menu.x,
66
+ top: menu.y,
67
+ zIndex: 1e3,
68
+ margin: 0,
69
+ padding: "4px 0",
70
+ listStyle: "none",
71
+ background: "var(--menu-bg, Canvas)",
72
+ color: "var(--menu-fg, CanvasText)",
73
+ border: "1px solid color-mix(in srgb, CanvasText 20%, transparent)",
74
+ borderRadius: 8,
75
+ boxShadow: "0 6px 24px rgb(0 0 0 / 0.18)",
76
+ minWidth: 160
77
+ }
78
+ }, () => items.map((item) => createScopedElement(Fragment, {}, () => positionalChildren([item.divider && createScopedValue(() => createElement("li", {
79
+ "aria-hidden": "true",
80
+ style: {
81
+ borderTop: "1px solid color-mix(in srgb, CanvasText 15%, transparent)",
82
+ margin: "4px 0"
83
+ }
84
+ })), createScopedValue(() => createScopedElement("li", {
85
+ role: "menuitem",
86
+ "aria-disabled": item.disabled || void 0,
87
+ style: {
88
+ padding: "6px 12px",
89
+ cursor: item.disabled ? "default" : "pointer",
90
+ opacity: item.disabled ? .5 : 1,
91
+ color: item.destructive ? "crimson" : void 0
92
+ },
93
+ onClick: () => {
94
+ if (item.disabled) return;
95
+ setMenu(null);
96
+ props.onItemSelected?.(item.id);
97
+ }
98
+ }, () => item.title))])))))])), "b:fff1b948", _b.i, true, void 0, void 0, void 0);
99
+ });
100
+ //#endregion
101
+ export { ContextMenu };
@@ -0,0 +1,8 @@
1
+ {
2
+ "version": 1,
3
+ "buildId": "451d8433-02fa-4009-8abd-11d95e2f143a",
4
+ "mode": "production",
5
+ "capabilities": {
6
+ "independentHydration": false
7
+ }
8
+ }
@@ -0,0 +1,2 @@
1
+ import { ContextMenu } from "../ContextMenu.web.tsrx.js";
2
+ export { ContextMenu };
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@octane-xplat/context-menu",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.9.0",
4
+ "description": "Platform-specific context menu controls for Octane xplat",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/octane-xplat/octane-xplat",
8
+ "directory": "packages/context-menu"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "types",
13
+ "src",
14
+ "platforms"
15
+ ],
16
+ "type": "module",
17
+ "exports": {
18
+ "./ios": {
19
+ "types": "./types/ios/index.d.ts",
20
+ "native": "./dist/native/ios/index.js"
21
+ },
22
+ "./android": {
23
+ "types": "./types/android/index.d.ts",
24
+ "native": "./dist/native/android/index.js"
25
+ },
26
+ "./web": {
27
+ "types": "./types/web/index.d.ts",
28
+ "web": "./dist/web/web/index.js"
29
+ }
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "@nativescript/jetpack-compose": "1.0.0-beta.0",
36
+ "@nativescript/swift-ui": "4.0.2"
37
+ },
38
+ "devDependencies": {
39
+ "@nativescript-community/octane": "0.2.4",
40
+ "@nativescript/core": "9.1.2",
41
+ "@octanejs/vite-plugin": "0.1.60",
42
+ "octane": "0.5.0",
43
+ "tsrx-typegen": "0.2.1",
44
+ "typescript": "5.9.3",
45
+ "vite": "8.3.0"
46
+ },
47
+ "peerDependencies": {
48
+ "@nativescript-community/octane": ">=0.2.1 <1",
49
+ "@nativescript/core": ">=9.1.0 <10",
50
+ "octane": ">=0.1.51 <1"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "@nativescript-community/octane": {
54
+ "optional": true
55
+ },
56
+ "@nativescript/core": {
57
+ "optional": true
58
+ },
59
+ "octane": {
60
+ "optional": true
61
+ }
62
+ },
63
+ "nativescript": {
64
+ "platforms": {
65
+ "android": "9.1.0",
66
+ "ios": "9.1.0"
67
+ }
68
+ },
69
+ "scripts": {
70
+ "build": "vite build && vite build --mode native && tsc -p tsconfig.types.json",
71
+ "test:packed": "node tests/packed-consumer.mjs",
72
+ "pack:check": "tsrx-typegen --pack-check"
73
+ }
6
74
  }
@@ -0,0 +1,15 @@
1
+ apply plugin: 'org.jetbrains.kotlin.plugin.compose'
2
+
3
+ android {
4
+ buildFeatures {
5
+ compose true
6
+ }
7
+ kotlinOptions {
8
+ jvmTarget = '17'
9
+ }
10
+ }
11
+
12
+ dependencies {
13
+ implementation platform('androidx.compose:compose-bom:2024.12.01')
14
+ implementation 'androidx.compose.material3:material3'
15
+ }
@@ -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
+ }