diff --git a/src/index.ts b/src/index.ts index e4cab81..e56aa4c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,8 +28,11 @@ export { export {createCanvasState, type CanvasState} from './core/canvas-state'; // Renderer — Skia + Reanimated React Native components. -export {CanvasView, type CanvasCamera, type FindResult} from './renderer/CanvasView'; +export {CanvasView, type CanvasCamera, type FindResult, type NodeLongPress} from './renderer/CanvasView'; +export {CanvasNodePreview, canvasNodePreviewSize, type CanvasNodePreviewProps} from './renderer/CanvasNodePreview'; export {nodesMatching} from './renderer/findNodes'; +export {resolveFileUri} from './renderer/utils/resolveFileUri'; +export {isImageFile} from './renderer/utils/fileNodeLabel'; export {CanvasMinimap, type Insets, type MinimapPosition} from './renderer/CanvasMinimap'; export {getNodeColors, resolveScheme, type ColorScheme} from './renderer/theme'; export {useCanvasContext, CanvasProvider} from './renderer/CanvasContext'; diff --git a/src/renderer/CanvasNodePreview.tsx b/src/renderer/CanvasNodePreview.tsx new file mode 100644 index 0000000..5199640 --- /dev/null +++ b/src/renderer/CanvasNodePreview.tsx @@ -0,0 +1,104 @@ +import React, {useEffect, useMemo, useState} from 'react'; +import {useColorScheme} from 'react-native'; +import {Canvas, Group, Picture, type SkPicture} from 'react-native-skia'; +import type {CanvasEdge, CanvasNode, FileNode, GroupNode} from '../core'; +import {resolveScheme} from './theme'; +import {FONT_SIZE} from './typography'; +import {GROUP_LABEL} from './metrics'; +import {SkiaImageRenderer} from './nodes/SkiaImageRenderer'; +import {loadNodeImages, recordNodesPicture} from './useCanvasPicture'; +import type {ImageNames} from './utils/fileNodeLabel'; + +const SVG_RE = /\.svg$/i; + +/** How far a small card is enlarged in its preview, at most. */ +const MAX_SCALE = 2; + +export interface CanvasNodePreviewProps { + /** What to draw: a node and, for a group, what's inside it (`onNodeLongPress`'s `contents.nodes`). */ + nodes: CanvasNode[]; + /** The edges between them (`contents.edges`). */ + edges?: CanvasEdge[]; + /** Directory containing the .canvas file, for the nodes' images. */ + basePath?: string; + /** The room the preview has, in points: it's drawn as large as fits, up to twice its size on the canvas. */ + maxWidth: number; + maxHeight: number; + /** Whether an image's name is drawn in its card, as on the canvas. */ + imageNames?: ImageNames; + /** The preview's images have loaded and it's drawn: when a host can show it. */ + onReady?: () => void; +} + +/** The world-space box a preview draws: the nodes, and a group's label above it. */ +function previewBounds(nodes: CanvasNode[]) { + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + for (const node of nodes) { + const labelled = node.type === 'group' && !!(node as GroupNode).label; + const top = labelled ? node.y - (FONT_SIZE.groupLabel + GROUP_LABEL.paddingY * 2 + 8) : node.y; + minX = Math.min(minX, node.x); + minY = Math.min(minY, top); + maxX = Math.max(maxX, node.x + node.width); + maxY = Math.max(maxY, node.y + node.height); + } + if (!isFinite(minX)) return {x: 0, y: 0, width: 1, height: 1}; + return {x: minX, y: minY, width: Math.max(1, maxX - minX), height: Math.max(1, maxY - minY)}; +} + +/** + * The size a preview of these nodes is drawn at, in points: as large as fits + * `maxWidth` × `maxHeight`, and no more than twice their size on the canvas. + * A host sizes its menu's preview with it. + */ +export function canvasNodePreviewSize(nodes: CanvasNode[], maxWidth: number, maxHeight: number) { + const b = previewBounds(nodes); + const scale = Math.min(maxWidth / b.width, maxHeight / b.height, MAX_SCALE); + return {width: Math.round(b.width * scale), height: Math.round(b.height * scale), scale}; +} + +/** + * One node drawn on its own, as the canvas draws it: what a host shows + * lifted in its own menu for a long-pressed node (the system's context + * menu on iOS). The library draws the card; where it goes and what the + * menu offers are the host's. + */ +export function CanvasNodePreview({nodes, edges = [], basePath, maxWidth, maxHeight, imageNames = 'onReveal', onReady}: CanvasNodePreviewProps) { + const colorScheme = resolveScheme(useColorScheme()); + const [picture, setPicture] = useState(null); + const bounds = useMemo(() => previewBounds(nodes), [nodes]); + const size = useMemo(() => canvasNodePreviewSize(nodes, maxWidth, maxHeight), [nodes, maxWidth, maxHeight]); + const svgNodes = useMemo( + () => nodes.filter((n): n is FileNode => n.type === 'file' && SVG_RE.test((n as FileNode).file)), + [nodes], + ); + + useEffect(() => { + let cancelled = false; + loadNodeImages(nodes, basePath).then(images => { + if (cancelled) return; + setPicture(recordNodesPicture(nodes, edges, colorScheme, basePath, imageNames, images)); + }); + return () => { + cancelled = true; + }; + }, [nodes, edges, basePath, colorScheme, imageNames]); + + useEffect(() => { + if (!picture) return; + // Drawn on the next frame: tell the host after it. + const frame = requestAnimationFrame(() => onReady?.()); + return () => cancelAnimationFrame(frame); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [picture]); + + return ( + + + {picture && } + {svgNodes.map(node => ( + + ))} + + + ); +} diff --git a/src/renderer/CanvasView.tsx b/src/renderer/CanvasView.tsx index a1a113e..a2eca44 100644 --- a/src/renderer/CanvasView.tsx +++ b/src/renderer/CanvasView.tsx @@ -9,6 +9,7 @@ import { type CanvasNode, type CanvasEdge, } from '../core'; +import {nodeContents} from './nodeContents'; import {cameraActionForResize} from './keepCameraOnResize'; import {SkiaCanvasLayer} from './SkiaCanvasLayer'; import {CanvasMinimap, type Insets, type MinimapPosition} from './CanvasMinimap'; @@ -148,11 +149,13 @@ interface Props { */ imageNames?: ImageNames; /** - * A node was long-pressed (touch screens), at `at` in the view's - * coordinates: where a host shows its own menu for the node. An image's - * name is revealed either way. + * A node was long-pressed (touch screens): where a host shows its own menu + * for the node (the system's context menu on iOS, with + * `CanvasNodePreview` lifted from `frame`), and its own feedback (a + * haptic). With a host's menu, the canvas doesn't reveal an image's name + * itself: the menu says it. Without one, a long-press reveals the name. */ - onNodeLongPress?: (node: CanvasNode, at: {x: number; y: number}) => void; + onNodeLongPress?: (node: CanvasNode, press: NodeLongPress) => void; /** * A strip along the view's left edge, in points, where a drag doesn't pan * the canvas but is left to the system: iOS's swipe back, when the canvas @@ -162,6 +165,16 @@ interface Props { systemEdge?: number; } +/** A long-press on a node, as `onNodeLongPress` tells a host. */ +export interface NodeLongPress { + /** Where the press was, in the view's coordinates. */ + at: {x: number; y: number}; + /** The node's card as it's drawn now, in the view's coordinates: where a menu's preview lifts from. */ + 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[]}; +} + /** What a search of the canvas found: how many, and which of them is shown (-1 when none). */ export interface FindResult { count: number; @@ -882,9 +895,9 @@ export function CanvasView({content, basePath, initialViewState, onViewStateChan return () => sub.remove(); }, [canvasState, translateX, translateY, scale, isPinching, leftOverlayWidth]); - // Long-press, on a touch screen: reveals an image's name, as hovering does - // on the Mac, and tells the host (its own menu). The name stays until the - // canvas is next moved. + // Long-press, on a touch screen: tells the host (its own menu), or, with + // none, reveals an image's name, as hovering does on the Mac. The name + // stays until the canvas is next moved. const nameRevealed = useSharedValue(false); const onNodeLongPressRef = useRef(onNodeLongPress); onNodeLongPressRef.current = onNodeLongPress; @@ -894,11 +907,18 @@ export function CanvasView({content, basePath, initialViewState, onViewStateChan const hits = canvasState?.hitTest(wx, wy) ?? []; // Smallest-area-wins, as double-tap and hover: a file node in a group means the file node. const hit = hits.length > 0 ? hits.reduce((a, b) => (a.width * a.height < b.width * b.height ? a : b)) : null; + const host = onNodeLongPressRef.current; + if (host) { + if (!hit || !canvasState) return; + const s = scale.value; + const frame = {x: hit.x * s + translateX.value, y: hit.y * s + translateY.value, width: hit.width * s, height: hit.height * s}; + host(hit, {at: {x, y}, frame, contents: nodeContents(hit, canvasState)}); + return; + } const fileId = hit?.type === 'file' ? hit.id : null; hoveredFileNodeIdRef.current = fileId; setHoveredFileNodeId(fileId); nameRevealed.value = fileId !== null; - if (hit) onNodeLongPressRef.current?.(hit, {x, y}); }, [canvasState, translateX, translateY, scale, nameRevealed]); const hideRevealed = useCallback(() => { if (Platform.OS === 'macos') return; // the Mac's chip follows the pointer diff --git a/src/renderer/__tests__/nodeContents.test.ts b/src/renderer/__tests__/nodeContents.test.ts new file mode 100644 index 0000000..aad2ceb --- /dev/null +++ b/src/renderer/__tests__/nodeContents.test.ts @@ -0,0 +1,31 @@ +import {createCanvasState} from '../../core'; +import type {CanvasDocument} from '../../core'; +import {nodeContents} from '../nodeContents'; + +const doc: CanvasDocument = { + nodes: [ + {id: 'g', type: 'group', label: 'Team', x: 0, y: 0, width: 400, height: 300}, + {id: 'a', type: 'text', text: 'A', x: 20, y: 20, width: 100, height: 60}, + {id: 'b', type: 'text', text: 'B', x: 200, y: 20, width: 100, height: 60}, + {id: 'half', type: 'text', text: 'Half in', x: 350, y: 20, width: 100, height: 60}, + {id: 'out', type: 'text', text: 'Out', x: 600, y: 20, width: 100, height: 60}, + ], + edges: [ + {id: 'ab', fromNode: 'a', toNode: 'b'}, + {id: 'a-out', fromNode: 'a', toNode: 'out'}, + ], +}; + +describe('nodeContents', () => { + const state = createCanvasState(doc); + + it('is the node alone for a card', () => { + expect(nodeContents(state.getNode('a')!, state)).toEqual({nodes: [state.getNode('a')], edges: []}); + }); + + it("is a group with the nodes wholly inside it and the edges between them", () => { + const {nodes, edges} = nodeContents(state.getNode('g')!, state); + expect(nodes.map(n => n.id).sort()).toEqual(['a', 'b', 'g']); + expect(edges.map(e => e.id)).toEqual(['ab']); + }); +}); diff --git a/src/renderer/index.ts b/src/renderer/index.ts index 7dbd94e..feddcaa 100644 --- a/src/renderer/index.ts +++ b/src/renderer/index.ts @@ -1,4 +1,5 @@ export {CanvasView} from './CanvasView'; +export {CanvasNodePreview, canvasNodePreviewSize} from './CanvasNodePreview'; export {CanvasMinimap, type MinimapPosition} from './CanvasMinimap'; export {getNodeColors, resolveScheme, type ColorScheme} from './theme'; export {useCanvasContext, CanvasProvider} from './CanvasContext'; diff --git a/src/renderer/nodeContents.ts b/src/renderer/nodeContents.ts new file mode 100644 index 0000000..99e8a20 --- /dev/null +++ b/src/renderer/nodeContents.ts @@ -0,0 +1,13 @@ +import type {CanvasEdge, CanvasNode, CanvasState} from '../core'; + +/** A node and, for a group, every node inside it, with the edges between them: what its preview draws. */ +export function nodeContents(node: CanvasNode, state: CanvasState): {nodes: CanvasNode[]; edges: CanvasEdge[]} { + if (node.type !== 'group') return {nodes: [node], edges: []}; + const inside = state + .getNodesInViewport({x: node.x, y: node.y, width: node.width, height: node.height}) + .filter(n => n.id !== node.id && n.x >= node.x && n.y >= node.y && n.x + n.width <= node.x + node.width && n.y + n.height <= node.y + node.height); + const nodes = [node, ...inside]; + const ids = new Set(nodes.map(n => n.id)); + const edges = (state.document.edges ?? []).filter(e => ids.has(e.fromNode) && ids.has(e.toNode)); + return {nodes, edges}; +} diff --git a/src/renderer/useCanvasPicture.ts b/src/renderer/useCanvasPicture.ts index a6230bb..8794cf6 100644 --- a/src/renderer/useCanvasPicture.ts +++ b/src/renderer/useCanvasPicture.ts @@ -196,7 +196,7 @@ const RASTER_RE = /\.(png|jpg|jpeg|gif|webp|bmp|ico)$/i; // SVGs are excluded from Picture recording — they render live during pinch // to preserve vector fidelity at any zoom level. type ImageCacheEntry = {type: 'raster'; image: SkImage}; -type ImageCache = Map; +export type ImageCache = Map; /** Extract raster image URIs from nodes (group backgrounds + file node images). * SVGs are excluded — they render live during pinch for vector fidelity. */ @@ -838,6 +838,31 @@ export function recordShapesPicture(allNodes: CanvasNode[], edges: CanvasEdge[], return recordCanvasPicture({allNodes, edges, nodeMap, colorScheme}, new Map(), 'shapes'); } +/** + * A few nodes and the edges between them, recorded on their own: a node's + * preview (`CanvasNodePreview`). The same drawing as the canvas's, so a + * card looks the same lifted out as it does in place. + */ +export function recordNodesPicture( + nodes: CanvasNode[], + edges: CanvasEdge[], + colorScheme: ColorScheme, + basePath: string | undefined, + imageNames: ImageNames, + images: ImageCache, +): SkPicture { + const groups = nodes.filter(n => n.type === 'group'); + const others = nodes.filter(n => n.type !== 'group'); + const allNodes = [...groups, ...others]; + const nodeMap = new Map(allNodes.map(n => [n.id, n] as const)); + return recordCanvasPicture({allNodes, edges, nodeMap, colorScheme, basePath, imageNames}, images, 'full'); +} + +/** Loads the raster images some nodes draw (file nodes, group backgrounds), for `recordNodesPicture`. */ +export function loadNodeImages(nodes: CanvasNode[], basePath?: string): Promise { + return loadImageCache(collectImageUris(nodes, basePath)); +} + /** The canvas's two recordings: everything, and the same without text for far zoomed out. */ export interface CanvasPictures { full: SkPicture;