Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
104 changes: 104 additions & 0 deletions src/renderer/CanvasNodePreview.tsx
Original file line number Diff line number Diff line change
@@ -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<SkPicture | null>(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 (
<Canvas style={{width: size.width, height: size.height}}>
<Group transform={[{scale: size.scale}, {translateX: -bounds.x}, {translateY: -bounds.y}]}>
{picture && <Picture picture={picture} />}
{svgNodes.map(node => (
<SkiaImageRenderer key={node.id} node={node} offsetX={0} offsetY={0} basePath={basePath} imageNames={imageNames} />
))}
</Group>
</Canvas>
);
}
36 changes: 28 additions & 8 deletions src/renderer/CanvasView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
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';
Expand Down Expand Up @@ -148,11 +149,13 @@
*/
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
Expand All @@ -162,6 +165,16 @@
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;
Expand Down Expand Up @@ -523,7 +536,7 @@
// (handleDoubleTap, tapGesture) does NOT recompose when the sidebar
// changes. That's load-bearing for #154 — earlier attempts that put
// sidebar state in deps regressed double-tap.
const fitToViewport = useCallback((leftOverlayWidth: number = 0) => {

Check warning on line 539 in src/renderer/CanvasView.tsx

View workflow job for this annotation

GitHub Actions / typecheck · lint · test

'leftOverlayWidth' is already declared in the upper scope on line 227 column 181
lastActionRef.current = 'fit';
const sw = viewportWidth;
const sh = viewportHeight;
Expand Down Expand Up @@ -557,7 +570,7 @@
// from `leftOverlayWidth` and passes it here per call. Kept as a parameter, not
// a closure dep, to preserve callback identity — see the matching
// discussion above `fitToViewport`.
const zoomToNode = useCallback((node: CanvasNode, leftOverlayWidth: number = 0) => {

Check warning on line 573 in src/renderer/CanvasView.tsx

View workflow job for this annotation

GitHub Actions / typecheck · lint · test

'leftOverlayWidth' is already declared in the upper scope on line 227 column 181
const sw = viewportWidth;
const sh = viewportHeight;
const visibleW = Math.max(1, sw - leftOverlayWidth);
Expand Down Expand Up @@ -630,7 +643,7 @@

// Recenter content at current zoom level, against the visible canvas pane.
// See `fitToViewport` for the leftOverlayWidth rationale.
const recenter = useCallback((leftOverlayWidth: number = 0) => {

Check warning on line 646 in src/renderer/CanvasView.tsx

View workflow job for this annotation

GitHub Actions / typecheck · lint · test

'leftOverlayWidth' is already declared in the upper scope on line 227 column 181
lastActionRef.current = 'recenter';
const sw = viewportWidth;
const sh = viewportHeight;
Expand Down Expand Up @@ -700,8 +713,8 @@

useEffect(() => {
onReady?.({
fitToViewport: (leftOverlayWidth?: number) => fitRef.current(leftOverlayWidth),

Check warning on line 716 in src/renderer/CanvasView.tsx

View workflow job for this annotation

GitHub Actions / typecheck · lint · test

'leftOverlayWidth' is already declared in the upper scope on line 227 column 181
recenter: (leftOverlayWidth?: number) => recenterRef.current(leftOverlayWidth),

Check warning on line 717 in src/renderer/CanvasView.tsx

View workflow job for this annotation

GitHub Actions / typecheck · lint · test

'leftOverlayWidth' is already declared in the upper scope on line 227 column 181
getLastAction: () => lastActionRef.current,
camera: {translateX, translateY, scale, isPinching},
find,
Expand Down Expand Up @@ -882,9 +895,9 @@
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;
Expand All @@ -894,11 +907,18 @@
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
Expand Down
31 changes: 31 additions & 0 deletions src/renderer/__tests__/nodeContents.test.ts
Original file line number Diff line number Diff line change
@@ -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']);
});
});
1 change: 1 addition & 0 deletions src/renderer/index.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
13 changes: 13 additions & 0 deletions src/renderer/nodeContents.ts
Original file line number Diff line number Diff line change
@@ -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};
}
27 changes: 26 additions & 1 deletion src/renderer/useCanvasPicture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, ImageCacheEntry>;
export type ImageCache = Map<string, ImageCacheEntry>;

/** Extract raster image URIs from nodes (group backgrounds + file node images).
* SVGs are excluded — they render live during pinch for vector fidelity. */
Expand Down Expand Up @@ -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<ImageCache> {
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;
Expand Down
Loading