diff --git a/AGENTS.md b/AGENTS.md index 4214330..8349424 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,6 +5,7 @@ A JSON Canvas (`.canvas`) renderer with three layers on one document model: - `src/core/`: spec-pure JSON Canvas (parser, serialiser, spatial index, state, colour presets). No React, no rendering, and no community conventions such as cssclasses or callouts. - `src/renderer/`: the React Native renderer (Skia + Reanimated) for iOS, Android and macOS, consumed from the package root. - `src/gtk/`: the GTK4 / libadwaita renderer (Cairo, through GTKX) for Linux, consumed as `./gtk`. +- `src/menu/`: a card's long-press menu on Android (Material 3's dropdown, from `@expo/ui`'s Compose components), consumed as `./menu`. It's its own entry point so the package root never imports `@expo/ui`, an optional peer: nothing under `src/renderer/` or `src/index.ts` may import from `src/menu/`. Workspace consumes all three. Issue numbers written `workspace#N` are in workspace-sh/workspace. diff --git a/README.md b/README.md index 5ecc2ad..89df029 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,7 @@ the library ships every gesture it supports as a default. | Ctrl + scroll to zoom | — | — | — | ✓ (about the pointer) | | Double-tap to zoom-to-node | ✓ | ✓ | ✓ (trackpad two-finger double-tap, a.k.a. Smart Zoom) | — | | Inertial fling | ✓ | ✓ | — (macOS pan is direct, no inertia) | — | +| Long-press a card | ✓ (`onNodeLongPress`) | ✓ (`onNodeLongPress`) | — (right-click: `onNodeContextMenu`) | — | ### iOS / Android (Expo or bare RN) @@ -83,6 +84,46 @@ Expo: works in any SDK that supports the peer-dep range. Use `expo install` if you prefer Expo's version-pinning. No native config needed in `app.json`. +### A card's menu + +A long-press on a card calls `onNodeLongPress(node, press)`, with where the +card is drawn (`press.frame`). The actions are the host's; what shows them +is the platform's: + +- **iOS:** the system's context menu, with `CanvasNodePreview` lifted from + `press.frame` (Workspace uses `react-native-ios-context-menu`). +- **Android:** `CanvasNodeMenu`, from its own entry point, is Material 3's + dropdown menu (Jetpack Compose, through + [Expo UI](https://docs.expo.dev/versions/latest/sdk/ui/)) anchored to the + card: below it, or above it with no room below, lined up with its leading + edge, and the card outlined while the menu is open. It needs `@expo/ui` + (an optional peer, so the package root doesn't); icons are Material + Symbols' vector drawables, from `@expo/material-symbols`. Elsewhere it + draws nothing. + +```tsx +import {CanvasNodeMenu} from '@workspace.sh/react-native-jsoncanvas/menu'; + +const [pressed, setPressed] = useState<{node: CanvasNode; press: NodeLongPress} | null>(null); + + setPressed({node, press})} /> +{/* Mounted per press here; one kept-mounted instance works too: each new + `press` opens it afresh and is dismissed once. */} +{pressed && ( + run(key, pressed.node)} + onDismiss={() => setPressed(null)} + /> +)} +``` + +Render it beside the `CanvasView`, in the same coordinates. The example app +(`example/expo-app/nodeMenu.tsx`) offers what Workspace does: copy, share +and open. + ### macOS (`react-native-macos`) RNGH on macOS can't see trackpad multi-finger gestures @@ -211,7 +252,7 @@ consumer (Workspace's Linux client). See `AGENTS.md`. Example harnesses live under `example/` and follow the org's standard layout (mirrors `react-native-source-editor/example/*`): -- **`example/expo-app/`** — Expo SDK 55 host serving iOS + Android. Uses Expo +- **`example/expo-app/`** — Expo SDK 58 host serving iOS + Android. Uses Expo CNG, owned by `expo prebuild` — never run `pod install` (iOS) or hand-edit `android/` here manually. - **`example/macos-app/`** — `react-native-macos` 0.81 host. Tracked in #21. diff --git a/example/expo-app/.gitignore b/example/expo-app/.gitignore index d914c32..8301010 100644 --- a/example/expo-app/.gitignore +++ b/example/expo-app/.gitignore @@ -39,3 +39,7 @@ yarn-error.* # generated native folders /ios /android + +# Native (Expo CNG: generated by prebuild) +/ios +/android diff --git a/example/expo-app/App.tsx b/example/expo-app/App.tsx index ae23d11..5fbd648 100644 --- a/example/expo-app/App.tsx +++ b/example/expo-app/App.tsx @@ -1,11 +1,13 @@ import {useCallback, useRef, useState} from 'react'; import {Pressable, StyleSheet, Text, useColorScheme, View} from 'react-native'; import {GestureHandlerRootView} from 'react-native-gesture-handler'; +import {SafeAreaProvider, useSafeAreaInsets} from 'react-native-safe-area-context'; import {StatusBar} from 'expo-status-bar'; import * as DocumentPicker from 'expo-document-picker'; import * as FileSystem from 'expo-file-system'; import {CanvasView} from '@workspace.sh/react-native-jsoncanvas'; import {SAMPLE_CANVAS} from '../shared/fixtures'; +import {useNodeMenu} from './nodeMenu'; type Controls = { fitToViewport: (leftInset?: number) => void; @@ -18,7 +20,22 @@ function dirname(uri: string): string { return i >= 0 ? uri.slice(0, i + 1) : uri; } +/** The buttons' row: its height, and the gap kept below it and above the minimap. */ +const CONTROLS_HEIGHT = 40; +const GAP = 16; + export default function App() { + return ( + + + + ); +} + +function Playground() { + // The canvas draws edge to edge (Android draws behind its system bars); + // the buttons and the minimap keep inside the safe area. + const insets = useSafeAreaInsets(); const controlsRef = useRef(null); const [lastAction, setLastAction] = useState('—'); // Active canvas content + basePath for the renderer. Defaults to the @@ -30,6 +47,7 @@ export default function App() { // wrapper has to match so canvas-empty background doesn't fight node // colours (e.g. dark nodes on a white background in dark mode). const isDark = useColorScheme() === 'dark'; + const nodeMenu = useNodeMenu(basePath); const openFile = useCallback(async () => { try { @@ -73,8 +91,12 @@ export default function App() { onReady={c => { controlsRef.current = c; }} + onNodeLongPress={nodeMenu.onNodeLongPress} + safeAreaInsets={insets} + minimapBottomInset={CONTROLS_HEIGHT + GAP} /> - + {nodeMenu.menu} + [styles.button, pressed && styles.pressed]} onPress={openFile} @@ -117,9 +139,7 @@ const styles = StyleSheet.create({ root: {flex: 1}, controls: { position: 'absolute', - bottom: 32, - left: 16, - right: 16, + height: CONTROLS_HEIGHT, flexDirection: 'row', gap: 8, alignItems: 'center', diff --git a/example/expo-app/app.json b/example/expo-app/app.json index 1073df4..f709f4c 100644 --- a/example/expo-app/app.json +++ b/example/expo-app/app.json @@ -11,6 +11,7 @@ "bundleIdentifier": "com.leslieoa.playground" }, "android": { + "package": "com.leslieoa.playground", "adaptiveIcon": { "backgroundColor": "#E6F4FE", "foregroundImage": "./assets/android-icon-foreground.png", diff --git a/example/expo-app/nodeMenu.tsx b/example/expo-app/nodeMenu.tsx new file mode 100644 index 0000000..02b8e42 --- /dev/null +++ b/example/expo-app/nodeMenu.tsx @@ -0,0 +1,96 @@ +// A card's long-press menu, as Workspace offers it: copy, share, open. On +// Android it's the library's CanvasNodeMenu (Material's dropdown, anchored +// to the card); elsewhere the playground keeps the canvas's own long-press, +// which reveals an image's name. +import {useCallback, useState, type ReactElement} from 'react'; +import {Linking, Platform, Share} from 'react-native'; +import * as Clipboard from 'expo-clipboard'; +import {AndroidHaptics, performAndroidHapticsAsync} from 'expo-haptics'; +import {resolveFileUri, type CanvasNode, type NodeLongPress} from '@workspace.sh/react-native-jsoncanvas'; +import {CanvasNodeMenu, type CanvasNodeMenuItem} from '@workspace.sh/react-native-jsoncanvas/menu'; + +interface Action { + item: CanvasNodeMenuItem; + run: () => void; +} + +const ICONS = { + copy: require('@expo/material-symbols/content_copy.xml'), + share: require('@expo/material-symbols/share.xml'), + open: require('@expo/material-symbols/open_in_browser.xml'), + link: require('@expo/material-symbols/link.xml'), +}; + +/** The menu's title: what the card is, where the card doesn't say it in a line. */ +function titleOf(node: CanvasNode): string | undefined { + switch (node.type) { + case 'file': + return node.file.split('/').pop() ?? node.file; + case 'link': + try { + return new URL(node.url).host; + } catch { + return node.url; + } + default: + return undefined; + } +} + +function actionsOf(node: CanvasNode, basePath: string | undefined): Action[] { + const share = (content: {url: string} | {message: string}): Action => ({ + item: {key: 'share', title: 'Share…', icon: ICONS.share}, + // Android's share sheet takes text, so a link goes as its message. + run: () => void Share.share('url' in content ? {message: content.url} : content), + }); + switch (node.type) { + case 'text': + return [ + {item: {key: 'copy', title: 'Copy text', icon: ICONS.copy}, run: () => void Clipboard.setStringAsync(node.text)}, + share({message: node.text}), + ]; + case 'link': + return [ + {item: {key: 'open', title: 'Open link', icon: ICONS.open}, run: () => void Linking.openURL(node.url)}, + {item: {key: 'copy', title: 'Copy link', icon: ICONS.link}, run: () => void Clipboard.setStringAsync(node.url)}, + share({url: node.url}), + ]; + case 'file': { + const uri = resolveFileUri(node.file, basePath); + return uri ? [share({url: uri})] : []; + } + default: + return []; + } +} + +export function useNodeMenu(basePath: string | undefined): { + onNodeLongPress: ((node: CanvasNode, press: NodeLongPress) => void) | undefined; + menu: ReactElement | null; +} { + const [pressed, setPressed] = useState<{node: CanvasNode; press: NodeLongPress} | null>(null); + const onNodeLongPress = useCallback( + (node: CanvasNode, press: NodeLongPress) => { + // Nothing to offer (a group), no menu. + if (actionsOf(node, basePath).length === 0) return; + void performAndroidHapticsAsync(AndroidHaptics.Long_Press).catch(() => {}); + setPressed({node, press}); + }, + [basePath], + ); + if (Platform.OS !== 'android') return {onNodeLongPress: undefined, menu: null}; + if (!pressed) return {onNodeLongPress, menu: null}; + const actions = actionsOf(pressed.node, basePath); + const menu = ( + a.item)} + onSelect={key => actions.find(a => a.item.key === key)?.run()} + onDismiss={() => setPressed(null)} + /> + ); + return {onNodeLongPress, menu}; +} diff --git a/example/expo-app/package.json b/example/expo-app/package.json index 6a41e52..19014cb 100644 --- a/example/expo-app/package.json +++ b/example/expo-app/package.json @@ -4,12 +4,17 @@ "main": "index.ts", "private": true, "dependencies": { + "@expo/material-symbols": "^0.1.1", + "@expo/ui": "~58.0.27", "@workspace.sh/react-native-jsoncanvas": "file:../..", "expo": "^58.0.22", + "expo-clipboard": "~58.0.4", "expo-dev-client": "~58.0.18", "expo-document-picker": "~58.0.4", "expo-file-system": "~58.0.13", + "expo-haptics": "~58.0.7", "expo-status-bar": "~58.0.4", + "expo-system-ui": "~58.0.7", "react": "19.3.0", "react-native": "0.88.1", "react-native-gesture-handler": "~3.3.0", diff --git a/package-lock.json b/package-lock.json index 1b03e80..307a046 100644 --- a/package-lock.json +++ b/package-lock.json @@ -41,6 +41,7 @@ "node": ">=20" }, "peerDependencies": { + "@expo/ui": ">=58.0.0", "@gtkx/cairo": ">=1.4.0", "@gtkx/react": ">=1.4.0", "react": ">=19.0.0", @@ -51,6 +52,9 @@ "react-native-worklets": ">=0.7.0" }, "peerDependenciesMeta": { + "@expo/ui": { + "optional": true + }, "@gtkx/cairo": { "optional": true }, @@ -62,12 +66,17 @@ "example/expo-app": { "version": "1.0.0", "dependencies": { + "@expo/material-symbols": "^0.1.1", + "@expo/ui": "~58.0.27", "@workspace.sh/react-native-jsoncanvas": "file:../..", "expo": "^58.0.22", + "expo-clipboard": "~58.0.4", "expo-dev-client": "~58.0.18", "expo-document-picker": "~58.0.4", "expo-file-system": "~58.0.13", + "expo-haptics": "~58.0.7", "expo-status-bar": "~58.0.4", + "expo-system-ui": "~58.0.7", "react": "19.3.0", "react-native": "0.88.1", "react-native-gesture-handler": "~3.3.0", @@ -3531,6 +3540,15 @@ "integrity": "sha512-My8Lwe9FU/yDwwzqwi5LN2rzzDcJqIAZKrD9f0XHZEKz/FQnWJYdt1rsV7+RwqMGeGq2XsxTCVT1ggTCOvumxw==", "license": "MIT" }, + "node_modules/@expo/material-symbols": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@expo/material-symbols/-/material-symbols-0.1.1.tgz", + "integrity": "sha512-ruA6hZATOPKxo1qSd1NE3HI9FrmEDwcMDhsvzTAdMkP9AapdHfJ/0tKmBMWFJir85voxs1twYxLVrGW9OLGaOg==", + "license": "MIT", + "bin": { + "add-material-symbols": "bin/add-material-symbols.mjs" + } + }, "node_modules/@expo/metro": { "version": "58.0.0", "resolved": "https://registry.npmjs.org/@expo/metro/-/metro-58.0.0.tgz", @@ -4184,6 +4202,34 @@ "integrity": "sha512-HHQigo3rQWKMDzYDLkubN5WQOYXJJE2eNqIQC2axC2iO3mHdwnIR7FgZVvHWtBwAdzBgAP0ECp8KqS8TiMKvgw==", "license": "MIT" }, + "node_modules/@expo/ui": { + "version": "58.0.27", + "resolved": "https://registry.npmjs.org/@expo/ui/-/ui-58.0.27.tgz", + "integrity": "sha512-g2BDAofZBgmDVxQ9PtbrWk6z9aPf5OUH+06Jdw7XPPTIFCNZ7qZQ94umEisAm8Vt4xViiECyWNTkHMKo7Pi2+w==", + "license": "MIT", + "dependencies": { + "sf-symbols-typescript": "^2.1.0" + }, + "peerDependencies": { + "@babel/core": "*", + "expo": "*", + "react": "*", + "react-dom": "*", + "react-native": "*", + "react-native-worklets": "*" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "react-dom": { + "optional": true + }, + "react-native-worklets": { + "optional": true + } + } + }, "node_modules/@expo/xcpretty": { "version": "4.4.7", "resolved": "https://registry.npmjs.org/@expo/xcpretty/-/xcpretty-4.4.7.tgz", @@ -9116,6 +9162,17 @@ "react-native": "*" } }, + "node_modules/expo-clipboard": { + "version": "58.0.4", + "resolved": "https://registry.npmjs.org/expo-clipboard/-/expo-clipboard-58.0.4.tgz", + "integrity": "sha512-b2eEJMwdWXLTrmrkg/otsmL2OV6s9D90tytSNBsY87UswrWf6JwxcB2OaWegyUWD9XnvtBVNeVK7lej0zZh+5A==", + "license": "MIT", + "peerDependencies": { + "expo": "*", + "react": "*", + "react-native": "*" + } + }, "node_modules/expo-constants": { "version": "58.0.14", "resolved": "https://registry.npmjs.org/expo-constants/-/expo-constants-58.0.14.tgz", @@ -9213,6 +9270,15 @@ "react-native": "*" } }, + "node_modules/expo-haptics": { + "version": "58.0.7", + "resolved": "https://registry.npmjs.org/expo-haptics/-/expo-haptics-58.0.7.tgz", + "integrity": "sha512-mAY3rbng6EuYysq9wnJKhKwYYlDjqnPYcS5OXe3zj4TlAaOFMl/EfiSOuAMawc2nsXCAnwJ5U0E11nq5zQO0mg==", + "license": "MIT", + "peerDependencies": { + "expo": "*" + } + }, "node_modules/expo-json-utils": { "version": "58.0.1", "resolved": "https://registry.npmjs.org/expo-json-utils/-/expo-json-utils-58.0.1.tgz", @@ -9323,6 +9389,26 @@ "react-native": "*" } }, + "node_modules/expo-system-ui": { + "version": "58.0.7", + "resolved": "https://registry.npmjs.org/expo-system-ui/-/expo-system-ui-58.0.7.tgz", + "integrity": "sha512-XxrMY93bT8MpZUlc6uRKzkeUoXhBi/Eq8j3qx2pjk0ARCV+0Ed1eqzmgxuAoKZ+10cyOZVSke5Hhi78NVFReuQ==", + "license": "MIT", + "dependencies": { + "@react-native/normalize-colors": "0.88.1", + "debug": "^4.3.2" + }, + "peerDependencies": { + "expo": "*", + "react-native": "*", + "react-native-web": "*" + }, + "peerDependenciesMeta": { + "react-native-web": { + "optional": true + } + } + }, "node_modules/expo-updates-interface": { "version": "58.0.1", "resolved": "https://registry.npmjs.org/expo-updates-interface/-/expo-updates-interface-58.0.1.tgz", @@ -15977,6 +16063,15 @@ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", "license": "ISC" }, + "node_modules/sf-symbols-typescript": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/sf-symbols-typescript/-/sf-symbols-typescript-2.2.0.tgz", + "integrity": "sha512-TPbeg0b7ylrswdGCji8FRGFAKuqbpQlLbL8SOle3j1iHSs5Ob5mhvMAxWN2UItOjgALAB5Zp3fmMfj8mbWvXKw==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", diff --git a/package.json b/package.json index 6c7cc21..68306a7 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,11 @@ "types": "./src/index.ts", "default": "./src/index.ts" }, + "./menu": { + "source": "./src/menu/index.ts", + "types": "./src/menu/index.ts", + "default": "./src/menu/index.ts" + }, "./gtk": { "source": "./src/gtk/index.ts", "types": "./src/gtk/index.ts", @@ -84,6 +89,7 @@ "node": ">=20" }, "peerDependencies": { + "@expo/ui": ">=58.0.0", "@gtkx/cairo": ">=1.4.0", "@gtkx/react": ">=1.4.0", "react": ">=19.0.0", @@ -119,6 +125,9 @@ "typescript": "^5.8.3" }, "peerDependenciesMeta": { + "@expo/ui": { + "optional": true + }, "@gtkx/cairo": { "optional": true }, diff --git a/patches/@expo+plist+0.5.4.patch b/patches/@expo+plist+0.10.1.patch similarity index 73% rename from patches/@expo+plist+0.5.4.patch rename to patches/@expo+plist+0.10.1.patch index 28a0759..975aabf 100644 --- a/patches/@expo+plist+0.5.4.patch +++ b/patches/@expo+plist+0.10.1.patch @@ -1,11 +1,11 @@ diff --git a/node_modules/@expo/plist/build/parse.js b/node_modules/@expo/plist/build/parse.js -index 572d7f8..33ca3b7 100644 +index e00107a..983dc28 100644 --- a/node_modules/@expo/plist/build/parse.js +++ b/node_modules/@expo/plist/build/parse.js -@@ -99,7 +99,7 @@ function parsePlistXML(node) { +@@ -108,7 +108,7 @@ function parse(xml) { + } return new_arr; - } - else if (node.nodeName === 'dict') { + } else if (node.nodeName === 'dict') { - new_obj = Object.create(null); + new_obj = {}; key = null; diff --git a/patches/react-native-skia+3.8.1.patch b/patches/react-native-skia+3.8.1.patch new file mode 100644 index 0000000..02f8b7c --- /dev/null +++ b/patches/react-native-skia+3.8.1.patch @@ -0,0 +1,21 @@ +diff --git a/node_modules/react-native-skia/android/build.gradle b/node_modules/react-native-skia/android/build.gradle +index 06517c4..88dafdd 100644 +--- a/node_modules/react-native-skia/android/build.gradle ++++ b/node_modules/react-native-skia/android/build.gradle +@@ -42,7 +42,15 @@ static def findNodeModules(baseDir) { + throw new GradleException("React-Native-Skia: Failed to find node_modules/ path!") + } + +-def nodeModules = findNodeModules(projectDir) ++// The app's node_modules first: in an npm workspace another React Native can ++// be hoisted nearer this library than the app's own, and its headers then ++// don't match the libraries the app links. ++def nodeModules ++try { ++ nodeModules = findNodeModules(rootProject.projectDir) ++} catch (GradleException ignored) { ++ nodeModules = findNodeModules(projectDir) ++} + + // Resolve a node package directory using Node's own module resolution, so we + // pick up the prebuilt Skia binaries straight from node_modules (no postinstall diff --git a/src/menu/CanvasNodeMenu.android.tsx b/src/menu/CanvasNodeMenu.android.tsx new file mode 100644 index 0000000..067c67c --- /dev/null +++ b/src/menu/CanvasNodeMenu.android.tsx @@ -0,0 +1,106 @@ +import {useCallback, useEffect, useRef, type ReactElement} from 'react'; +import {StyleSheet, View} from 'react-native'; +import { + Box, + DropdownMenu, + DropdownMenuItem, + Host, + HorizontalDivider, + Icon, + Text, + useMaterialColors, +} from '@expo/ui/jetpack-compose'; +import {fillMaxSize} from '@expo/ui/jetpack-compose/modifiers'; +import {menuAnchor} from './menuAnchor'; +import type {CanvasNodeMenuProps} from './types'; + +/** A card's corners on the canvas, in its own points (SkiaCardRenderer's). */ +const CARD_RADIUS = 8; +const GROUP_RADIUS = 12; +const ICON_SIZE = 24; + +/** + * A card's menu on Android: Material 3's dropdown menu (Compose's, through + * Expo UI) anchored to the long-pressed card, opening below it, or above + * with no room below, and lined up with its leading edge. The card is + * outlined in the theme's primary colour while its menu is open, so it's + * clear which card the menu is for (Android has no lifted preview, as iOS's + * context menu has). A tap outside the menu, or Back, closes it. + * + * Render it beside the `CanvasView`, over the canvas and in the same + * coordinates, while a long-press is being answered. + */ +export function CanvasNodeMenu({node, press, items, title, onSelect, onDismiss}: CanvasNodeMenuProps): ReactElement | null { + const colors = useMaterialColors(); + // Choosing an action closes the menu too: dismiss once, whichever came + // first, once for each press (a host may keep one instance mounted). + const closed = useRef(false); + useEffect(() => { + closed.current = false; + }, [press]); + const dismiss = useCallback(() => { + if (closed.current) return; + closed.current = true; + onDismiss(); + }, [onDismiss]); + if (items.length === 0) return null; + + const anchor = menuAnchor(press); + const {frame} = press; + const zoom = node.width > 0 ? frame.width / node.width : 1; + const radius = (node.type === 'group' ? GROUP_RADIUS : CARD_RADIUS) * zoom; + + return ( + <> + + + + + + + + {title ? ( + + + + {title} + + + + ) : null} + {title ? : null} + {items.map(item => ( + { + dismiss(); + onSelect(item.key); + }} + > + {item.icon ? ( + + + + ) : null} + + {item.title} + + + ))} + + + + + ); +} + +const styles = StyleSheet.create({ + outline: {position: 'absolute', borderWidth: 2}, +}); diff --git a/src/menu/CanvasNodeMenu.tsx b/src/menu/CanvasNodeMenu.tsx new file mode 100644 index 0000000..15a6e40 --- /dev/null +++ b/src/menu/CanvasNodeMenu.tsx @@ -0,0 +1,11 @@ +import type {ReactElement} from 'react'; +import type {CanvasNodeMenuProps} from './types'; + +/** + * A card's menu, on Android (`CanvasNodeMenu.android.tsx`). Elsewhere it + * draws nothing: on iOS a host shows the system's context menu, with + * `CanvasNodePreview` lifted from `press.frame`; on the Mac, its own. + */ +export function CanvasNodeMenu(_props: CanvasNodeMenuProps): ReactElement | null { + return null; +} diff --git a/src/menu/__tests__/menuAnchor.test.ts b/src/menu/__tests__/menuAnchor.test.ts new file mode 100644 index 0000000..043ef1e --- /dev/null +++ b/src/menu/__tests__/menuAnchor.test.ts @@ -0,0 +1,20 @@ +import {menuAnchor} from '../menuAnchor'; + +const viewport = {width: 400, height: 800}; + +describe('menuAnchor', () => { + it('hangs the menu from a card that is wholly on screen', () => { + const frame = {x: 40, y: 100, width: 200, height: 120}; + expect(menuAnchor({frame, at: {x: 50, y: 150}, viewport})).toEqual(frame); + }); + + it('keeps to the part of a card that is on screen', () => { + const frame = {x: -100, y: 700, width: 300, height: 300}; + expect(menuAnchor({frame, at: {x: 50, y: 750}, viewport})).toEqual({x: 0, y: 700, width: 200, height: 100}); + }); + + it('opens at the finger when the card fills most of the view', () => { + const frame = {x: 20, y: -200, width: 360, height: 1400}; + expect(menuAnchor({frame, at: {x: 100, y: 420}, viewport})).toEqual({x: 20, y: 420, width: 360, height: 1}); + }); +}); diff --git a/src/menu/index.ts b/src/menu/index.ts new file mode 100644 index 0000000..3cc2303 --- /dev/null +++ b/src/menu/index.ts @@ -0,0 +1,5 @@ +// A card's menu on Android: Material 3's dropdown, from Expo UI's Compose +// components. Its own entry point, so the package root needs no @expo/ui. +export {CanvasNodeMenu} from './CanvasNodeMenu'; +export {menuAnchor} from './menuAnchor'; +export type {CanvasNodeMenuItem, CanvasNodeMenuProps} from './types'; diff --git a/src/menu/menuAnchor.ts b/src/menu/menuAnchor.ts new file mode 100644 index 0000000..9d89ca9 --- /dev/null +++ b/src/menu/menuAnchor.ts @@ -0,0 +1,29 @@ +import type {NodeLongPress} from '../renderer/CanvasView'; + +export interface Rect { + x: number; + y: number; + width: number; + height: number; +} + +/** A card taller than this share of the view anchors its menu at the finger: there's no room above or below it. */ +const TALL = 0.6; + +/** + * What a card's menu hangs from, in the view's coordinates: the part of the + * card that's on screen, so the menu opens below it (or above, with no room + * below) and lines up with its leading edge, as Material's menus do. A card + * that fills most of the view has no room either side, so its menu opens at + * the finger instead, still lined up with the card. + */ +export function menuAnchor({frame, at, viewport}: Pick): Rect { + const left = Math.max(0, frame.x); + const top = Math.max(0, frame.y); + const right = Math.min(viewport.width, frame.x + frame.width); + const bottom = Math.min(viewport.height, frame.y + frame.height); + const width = Math.max(1, right - left); + const height = bottom - top; + if (height > viewport.height * TALL) return {x: left, y: at.y, width, height: 1}; + return {x: left, y: top, width, height: Math.max(1, height)}; +} diff --git a/src/menu/types.ts b/src/menu/types.ts new file mode 100644 index 0000000..155ad89 --- /dev/null +++ b/src/menu/types.ts @@ -0,0 +1,33 @@ +import type {ImageSourcePropType} from 'react-native'; +import type {CanvasNode} from '../core'; +import type {NodeLongPress} from '../renderer/CanvasView'; + +/** One action in a card's menu. */ +export interface CanvasNodeMenuItem { + /** What `onSelect` is told when the action is chosen. */ + key: string; + /** The action's name, as the menu shows it ("Copy Text"). */ + title: string; + /** + * Its leading icon: a Material Symbol's vector drawable, e.g. + * `require('@expo/material-symbols/content_copy.xml')`. + */ + icon?: ImageSourcePropType; + /** An action that removes something: drawn in the theme's error colour. */ + destructive?: boolean; +} + +export interface CanvasNodeMenuProps { + /** The long-pressed node, as `CanvasView`'s `onNodeLongPress` gave it. */ + node: CanvasNode; + /** Where it was pressed, from the same call: the menu is anchored to `press.frame`. */ + press: NodeLongPress; + /** What the card offers, in order. */ + items: CanvasNodeMenuItem[]; + /** A label above the actions, where the card doesn't say what it is in a line (a file's name, a link's host). */ + title?: string; + /** An action was chosen. The menu has closed (`onDismiss` was called first). */ + onSelect: (key: string) => void; + /** The menu closed: an action was chosen, or the reader tapped outside it or pressed Back. */ + onDismiss: () => void; +} diff --git a/src/renderer/CanvasView.tsx b/src/renderer/CanvasView.tsx index 668aba6..f93579b 100644 --- a/src/renderer/CanvasView.tsx +++ b/src/renderer/CanvasView.tsx @@ -192,6 +192,8 @@ export interface NodeLongPress { frame: {x: number; y: number; width: number; height: number}; /** What a preview of the node draws: the node and, for a group, everything inside it, with the edges between them. */ contents: {nodes: CanvasNode[]; edges: CanvasEdge[]}; + /** The view's size: what of `frame` is on screen, for a menu anchored to the card. */ + viewport: {width: number; height: number}; } /** What a search of the canvas found: how many, and which of them is shown (-1 when none). */ @@ -932,8 +934,8 @@ export function CanvasView({content, basePath, initialViewState, onViewStateChan if (!canvasState) return null; const s = scale.value; const frame = {x: node.x * s + translateX.value, y: node.y * s + translateY.value, width: node.width * s, height: node.height * s}; - return {at: {x, y}, frame, contents: nodeContents(node, canvasState)}; - }, [canvasState, translateX, translateY, scale]); + return {at: {x, y}, frame, contents: nodeContents(node, canvasState), viewport: {width: viewportWidth, height: viewportHeight}}; + }, [canvasState, translateX, translateY, scale, viewportWidth, viewportHeight]); const revealAt = useCallback((x: number, y: number) => { const hit = nodeAt(x, y); const host = onNodeLongPressRef.current; diff --git a/src/renderer/edges/EdgeRenderer.tsx b/src/renderer/edges/EdgeRenderer.tsx index 5ba95d6..0aece4a 100644 --- a/src/renderer/edges/EdgeRenderer.tsx +++ b/src/renderer/edges/EdgeRenderer.tsx @@ -7,11 +7,12 @@ import { Group, matchFont, } from 'react-native-skia'; +import {canvasFont} from '../fonts'; import type {CanvasEdge, CanvasNode, EdgeSide} from '../../core'; import {devFlags} from '../devFlags'; import {EDGE_LABEL_TEXT_COLOR, resolveEdgeColor} from '../theme'; import {EDGE_LABEL} from '../metrics'; -import {FONT_SIZE} from '../typography'; +import {FONT_SIZE, SYSTEM_FONT} from '../typography'; interface Props { edge: CanvasEdge; @@ -23,7 +24,7 @@ interface Props { let _labelFont: ReturnType | null = null; function getLabelFont() { - if (!_labelFont) _labelFont = matchFont({fontFamily: 'System', fontSize: FONT_SIZE.edgeLabel}); + if (!_labelFont) _labelFont = canvasFont({fontFamily: SYSTEM_FONT, fontSize: FONT_SIZE.edgeLabel}); return _labelFont; } diff --git a/src/renderer/fonts.ts b/src/renderer/fonts.ts new file mode 100644 index 0000000..32bf4f9 --- /dev/null +++ b/src/renderer/fonts.ts @@ -0,0 +1,21 @@ +import {Platform} from 'react-native'; +import {FontEdging, FontHinting, matchFont, type SkFont} from 'react-native-skia'; + +/** + * A font for single-line text on the canvas (labels, link and file names), + * as `matchFont` makes one. It's drawn at one size and scaled by the camera. + * On Android its glyphs are unhinted and placed to subpixels with unrounded + * advances: hinted, Android rounds each advance to a whole pixel at the + * small size, and zoomed in the letters drift apart ("Render er"). iOS and + * macOS keep `matchFont`'s font as it is. + */ +export function canvasFont(spec: Parameters[0]): SkFont { + const font = matchFont(spec); + if (Platform.OS === 'android') { + font.setHinting(FontHinting.None); + font.setSubpixel(true); + font.setLinearMetrics(true); + font.setEdging(FontEdging.AntiAlias); + } + return font; +} diff --git a/src/renderer/nodes/SkiaCardLabelRenderer.tsx b/src/renderer/nodes/SkiaCardLabelRenderer.tsx index 00c6cb2..6c5604e 100644 --- a/src/renderer/nodes/SkiaCardLabelRenderer.tsx +++ b/src/renderer/nodes/SkiaCardLabelRenderer.tsx @@ -1,12 +1,13 @@ import React, {memo} from 'react'; import {Group, Line, Text, vec, rect, matchFont} from 'react-native-skia'; +import {canvasFont} from '../fonts'; import type {TextNode} from '../../core'; import type {EnrichedTextNode} from '../extensions/cssclasses'; import {hasCallouts, parseCallouts, getLabels} from '../extensions/callouts'; import {toPlainText} from '../markdown'; import {getMutedTextColor, getTextColor, type ColorScheme} from '../theme'; import {ZONE} from '../metrics'; -import {H4} from '../typography'; +import {H4, SYSTEM_FONT} from '../typography'; import {shapeClipPath} from './shapes'; const DEG_TO_RAD = Math.PI / 180; @@ -14,7 +15,7 @@ const DEG_TO_RAD = Math.PI / 180; let _labelFont: ReturnType | null = null; function getLabelFont() { if (!_labelFont) { - _labelFont = matchFont({fontFamily: 'System', fontSize: H4.fontSize, fontWeight: 'bold'}); + _labelFont = canvasFont({fontFamily: SYSTEM_FONT, fontSize: H4.fontSize, fontWeight: 'bold'}); } return _labelFont; } diff --git a/src/renderer/nodes/SkiaFileRenderer.tsx b/src/renderer/nodes/SkiaFileRenderer.tsx index 8a4312e..bf7fab0 100644 --- a/src/renderer/nodes/SkiaFileRenderer.tsx +++ b/src/renderer/nodes/SkiaFileRenderer.tsx @@ -1,5 +1,7 @@ import React, {memo} from 'react'; import {Text, RoundedRect, matchFont} from 'react-native-skia'; +import {canvasFont} from '../fonts'; +import {SYSTEM_FONT} from '../typography'; import type {FileNode} from '../../core'; import {getChipBackground, getMutedTextColor, getTextColor, type ColorScheme} from '../theme'; import {CHIP, LABEL} from '../metrics'; @@ -23,12 +25,12 @@ let _nameFont: ReturnType | null = null; let _subpathFont: ReturnType | null = null; function getNameFont() { - if (!_nameFont) _nameFont = matchFont({fontFamily: 'System', fontSize: 12, fontWeight: 'bold'}); + if (!_nameFont) _nameFont = canvasFont({fontFamily: SYSTEM_FONT, fontSize: 12, fontWeight: 'bold'}); return _nameFont; } function getSubpathFont() { - if (!_subpathFont) _subpathFont = matchFont({fontFamily: 'System', fontSize: 10}); + if (!_subpathFont) _subpathFont = canvasFont({fontFamily: SYSTEM_FONT, fontSize: 10}); return _subpathFont; } diff --git a/src/renderer/nodes/SkiaGroupLabelRenderer.tsx b/src/renderer/nodes/SkiaGroupLabelRenderer.tsx index 9bbceb6..eae3645 100644 --- a/src/renderer/nodes/SkiaGroupLabelRenderer.tsx +++ b/src/renderer/nodes/SkiaGroupLabelRenderer.tsx @@ -1,9 +1,10 @@ import React, {memo} from 'react'; import {Text, RoundedRect, matchFont} from 'react-native-skia'; +import {canvasFont} from '../fonts'; import type {GroupNode} from '../../core'; import {getNodeColors, type ColorScheme} from '../theme'; import {GROUP_LABEL} from '../metrics'; -import {FONT_SIZE} from '../typography'; +import {FONT_SIZE, SYSTEM_FONT} from '../typography'; interface Props { node: GroupNode; @@ -15,7 +16,7 @@ interface Props { let _font: ReturnType | null = null; function getFont() { - if (!_font) _font = matchFont({fontFamily: 'System', fontSize: FONT_SIZE.groupLabel, fontWeight: 'bold'}); + if (!_font) _font = canvasFont({fontFamily: SYSTEM_FONT, fontSize: FONT_SIZE.groupLabel, fontWeight: 'bold'}); return _font; } diff --git a/src/renderer/nodes/SkiaLinkRenderer.tsx b/src/renderer/nodes/SkiaLinkRenderer.tsx index b5f8064..ea8cc7c 100644 --- a/src/renderer/nodes/SkiaLinkRenderer.tsx +++ b/src/renderer/nodes/SkiaLinkRenderer.tsx @@ -1,9 +1,10 @@ import React, {memo} from 'react'; import {Text, matchFont} from 'react-native-skia'; +import {canvasFont} from '../fonts'; import type {LinkNode} from '../../core'; import {getLinkColor, getMutedTextColor, type ColorScheme} from '../theme'; import {LINK, NODE} from '../metrics'; -import {FONT_SIZE} from '../typography'; +import {FONT_SIZE, SYSTEM_FONT} from '../typography'; interface Props { node: LinkNode; @@ -17,12 +18,12 @@ let _hostnameFont: ReturnType | null = null; let _urlFont: ReturnType | null = null; function getHostnameFont() { - if (!_hostnameFont) _hostnameFont = matchFont({fontFamily: 'System', fontSize: FONT_SIZE.linkHostname, fontWeight: 'bold'}); + if (!_hostnameFont) _hostnameFont = canvasFont({fontFamily: SYSTEM_FONT, fontSize: FONT_SIZE.linkHostname, fontWeight: 'bold'}); return _hostnameFont; } function getUrlFont() { - if (!_urlFont) _urlFont = matchFont({fontFamily: 'System', fontSize: FONT_SIZE.linkUrl}); + if (!_urlFont) _urlFont = canvasFont({fontFamily: SYSTEM_FONT, fontSize: FONT_SIZE.linkUrl}); return _urlFont; } diff --git a/src/renderer/nodes/SkiaTextRenderer.tsx b/src/renderer/nodes/SkiaTextRenderer.tsx index 16c2f52..6acad99 100644 --- a/src/renderer/nodes/SkiaTextRenderer.tsx +++ b/src/renderer/nodes/SkiaTextRenderer.tsx @@ -3,12 +3,13 @@ import { Group, Line, vec, matchFont, Text, rect, Paragraph as SkiaParagraph, } from 'react-native-skia'; +import {canvasFont} from '../fonts'; import type {TextNode} from '../../core'; import type {EnrichedTextNode} from '../extensions/cssclasses'; import {hasCallouts, parseCallouts, getHeader, getFooter, getCenteredCallout} from '../extensions/callouts'; import {getMutedTextColor, getTextColor, type ColorScheme} from '../theme'; import {NODE, ZONE} from '../metrics'; -import {H4, type FontConfig} from '../typography'; +import {H4, SYSTEM_FONT, type FontConfig} from '../typography'; import {parseToSegments, toPlainText} from '../markdown'; import {buildParagraph, getParagraphColours} from '../paragraphBuilder'; import {shapeClipPath} from './shapes'; @@ -27,15 +28,15 @@ interface Props { const fontCache = new Map>(); function getFont(config: FontConfig) { - const key = `${config.fontSize}-${config.fontWeight ?? 'normal'}-${config.fontFamily ?? 'System'}`; + const key = `${config.fontSize}-${config.fontWeight ?? 'normal'}-${config.fontFamily ?? SYSTEM_FONT}`; let f = fontCache.get(key); if (!f) { const spec: Parameters[0] = { - fontFamily: config.fontFamily ?? 'System', + fontFamily: config.fontFamily ?? SYSTEM_FONT, fontSize: config.fontSize, }; if (config.fontWeight) spec.fontWeight = config.fontWeight; - f = matchFont(spec); + f = canvasFont(spec); fontCache.set(key, f); } return f; diff --git a/src/renderer/paragraphBuilder.ts b/src/renderer/paragraphBuilder.ts index 3b28423..2062c71 100644 --- a/src/renderer/paragraphBuilder.ts +++ b/src/renderer/paragraphBuilder.ts @@ -12,6 +12,7 @@ import {Skia, TextDecoration} from 'react-native-skia'; import type {SkParagraph, SkTextStyle, SkColor} from 'react-native-skia'; import {paragraphRuns, type TextSegment, type SegmentStyle} from './markdown'; +import {SYSTEM_FONT} from './typography'; import {getLinkColor, getMutedTextColor, getTextColor, type ColorScheme} from './theme'; export interface ParagraphColours { @@ -41,6 +42,16 @@ export function getParagraphColours(colorScheme: ColorScheme): ParagraphColours return colorScheme === 'dark' ? PARAGRAPH_COLOURS.dark : PARAGRAPH_COLOURS.light; } +/** + * The families a style's font is looked for in, first found wins. Code asks + * for Menlo, which Android doesn't have: there it falls back to the system's + * monospace font rather than to the default sans. + */ +function fontFamiliesFor(family: string | undefined): string[] { + if (family === 'Menlo') return ['Menlo', 'monospace']; + return [family ?? SYSTEM_FONT]; +} + function toSkTextStyle(style: SegmentStyle, c: ParagraphColours): SkTextStyle { const color = style.color === 'muted' ? c.muted : style.color === 'link' ? c.link @@ -48,7 +59,7 @@ function toSkTextStyle(style: SegmentStyle, c: ParagraphColours): SkTextStyle { const result: SkTextStyle = { fontSize: style.fontSize, - fontFamilies: [style.fontFamily ?? 'System'], + fontFamilies: fontFamiliesFor(style.fontFamily), color, heightMultiplier: style.lineHeight / style.fontSize, }; @@ -79,7 +90,7 @@ export function buildParagraph( if (segments.length === 0) return null; const builder = Skia.ParagraphBuilder.Make({ - textStyle: {fontSize: 13, color: colours.text, fontFamilies: ['System']}, + textStyle: {fontSize: 13, color: colours.text, fontFamilies: [SYSTEM_FONT]}, }); for (const run of paragraphRuns(segments)) { diff --git a/src/renderer/typography.ts b/src/renderer/typography.ts index de3b4f3..b686749 100644 --- a/src/renderer/typography.ts +++ b/src/renderer/typography.ts @@ -1,3 +1,12 @@ +import {Platform} from 'react-native'; + +/** + * The system's sans-serif family, by the name each platform's font manager + * knows it by. Android's has no "System": a font matched by that name there + * has no typeface, and its text draws nothing. + */ +export const SYSTEM_FONT = Platform.OS === 'android' ? 'sans-serif' : 'System'; + /** * Type scale, shared by both rendering paths. * diff --git a/src/renderer/useCanvasPicture.ts b/src/renderer/useCanvasPicture.ts index 8794cf6..6b00d7c 100644 --- a/src/renderer/useCanvasPicture.ts +++ b/src/renderer/useCanvasPicture.ts @@ -1,5 +1,6 @@ import {useState, useEffect, useRef} from 'react'; import {Skia, createPicture, matchFont, PaintStyle, TileMode} from 'react-native-skia'; +import {canvasFont} from './fonts'; import type {SkPicture, SkCanvas, SkFont, SkPaint, SkImage} from 'react-native-skia'; import type {CanvasNode, CanvasEdge, TextNode, LinkNode, FileNode, GroupNode, EdgeSide} from '../core'; import type {EnrichedTextNode} from './extensions/cssclasses'; @@ -9,7 +10,7 @@ import { resolveEdgeColor, EDGE_LABEL_TEXT_COLOR, type ColorScheme, } from './theme'; import {CHIP, EDGE_LABEL, FILE_IMAGE, GROUP_LABEL, LABEL, LINK, NODE, ZONE} from './metrics'; -import {FONT_SIZE, H4, type FontConfig} from './typography'; +import {FONT_SIZE, H4, SYSTEM_FONT, type FontConfig} from './typography'; import {hasInlineLabel, isImageFile, type ImageNames} from './utils/fileNodeLabel'; import {parseToSegments, toPlainText} from './markdown'; import {buildParagraph, getParagraphColours} from './paragraphBuilder'; @@ -27,11 +28,11 @@ function getFont(config: FontConfig): SkFont { let f = fontCache.get(config); if (!f) { const spec: Parameters[0] = { - fontFamily: config.fontFamily ?? 'System', + fontFamily: config.fontFamily ?? SYSTEM_FONT, fontSize: config.fontSize, }; if (config.fontWeight) spec.fontWeight = config.fontWeight; - f = matchFont(spec); + f = canvasFont(spec); fontCache.set(config, f); } return f; @@ -45,23 +46,23 @@ let _fileSubpathFont: SkFont | null = null; let _labelFont: SkFont | null = null; function getHostnameFont(): SkFont { - if (!_hostnameFont) _hostnameFont = matchFont({fontFamily: 'System', fontSize: FONT_SIZE.linkHostname, fontWeight: 'bold'}); + if (!_hostnameFont) _hostnameFont = canvasFont({fontFamily: SYSTEM_FONT, fontSize: FONT_SIZE.linkHostname, fontWeight: 'bold'}); return _hostnameFont; } function getUrlFont(): SkFont { - if (!_urlFont) _urlFont = matchFont({fontFamily: 'System', fontSize: FONT_SIZE.linkUrl}); + if (!_urlFont) _urlFont = canvasFont({fontFamily: SYSTEM_FONT, fontSize: FONT_SIZE.linkUrl}); return _urlFont; } function getFileNameFont(): SkFont { - if (!_fileNameFont) _fileNameFont = matchFont({fontFamily: 'System', fontSize: FONT_SIZE.fileName, fontWeight: 'bold'}); + if (!_fileNameFont) _fileNameFont = canvasFont({fontFamily: SYSTEM_FONT, fontSize: FONT_SIZE.fileName, fontWeight: 'bold'}); return _fileNameFont; } function getFileSubpathFont(): SkFont { - if (!_fileSubpathFont) _fileSubpathFont = matchFont({fontFamily: 'System', fontSize: FONT_SIZE.fileSubpath}); + if (!_fileSubpathFont) _fileSubpathFont = canvasFont({fontFamily: SYSTEM_FONT, fontSize: FONT_SIZE.fileSubpath}); return _fileSubpathFont; } function getEdgeLabelFont(): SkFont { - if (!_labelFont) _labelFont = matchFont({fontFamily: 'System', fontSize: FONT_SIZE.edgeLabel}); + if (!_labelFont) _labelFont = canvasFont({fontFamily: SYSTEM_FONT, fontSize: FONT_SIZE.edgeLabel}); return _labelFont; } @@ -686,7 +687,7 @@ function drawFileLabel(canvas: SkCanvas, node: FileNode, colorScheme: ColorSchem function drawGroupLabel(canvas: SkCanvas, node: GroupNode, colorScheme: ColorScheme) { if (!node.label) return; const colors = getNodeColors(node.color, colorScheme); - const font = matchFont({fontFamily: 'System', fontSize: FONT_SIZE.groupLabel, fontWeight: 'bold'}); + const font = canvasFont({fontFamily: SYSTEM_FONT, fontSize: FONT_SIZE.groupLabel, fontWeight: 'bold'}); const textWidth = font.measureText(node.label).width; const pillWidth = textWidth + GROUP_LABEL.paddingX * 2;