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
8 changes: 8 additions & 0 deletions .changeset/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Changesets

Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets).

We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md).
11 changes: 11 additions & 0 deletions .changeset/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.1.4/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "restricted",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}
24 changes: 15 additions & 9 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
name: Publish

on:
release:
types: [published]
push:
branches:
- main

jobs:
publish:
release:
runs-on: ubuntu-latest
permissions:
contents: read
contents: write
pull-requests: write
packages: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0

- uses: pnpm/action-setup@v4

Expand All @@ -24,12 +28,14 @@ jobs:

- run: pnpm install --frozen-lockfile

- run: pnpm typecheck

- run: pnpm test

- run: pnpm build

- run: pnpm changeset publish
- uses: changesets/action@v1
with:
publish: pnpm changeset publish
version: pnpm changeset version
commit: "chore: version packages"
title: "chore: version packages"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@floormap:registry=https://npm.pkg.github.com
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ Floormap provides the low-level engine for pan/zoom, selection, hit testing, and

| Package | Version | Description |
|---------|---------|-------------|
| [`@floormap/core`](packages/core) | 0.0.0 | Scene engine, viewport, event bus, picking, selection |
| [`@floormap/svg`](packages/svg) | 0.0.0 | SVG renderer + DOM event handlers |
| [`@floormap/react`](packages/adapters/react) | 0.0.0 | React adapter — hooks and `FloormapCanvas` component |
| [`@floormap/core`](packages/core) | 0.1.0 | Scene engine, viewport, event bus, picking, selection |
| [`@floormap/svg`](packages/svg) | 0.1.0 | SVG renderer + DOM event handlers |
| [`@floormap/react`](packages/adapters/react) | 0.1.0 | React adapter — hooks and `FloormapCanvas` component |

---

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"release": "changeset version && pnpm install --no-frozen-lockfile && changeset publish"
},
"devDependencies": {
"@changesets/cli": "^2.31.0",
"@types/node": "^22.18.8",
"@typescript-eslint/eslint-plugin": "^8.0.0",
"@typescript-eslint/parser": "^8.0.0",
Expand Down
12 changes: 12 additions & 0 deletions packages/adapters/react/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# @floormap/react

## 0.1.0

### Minor Changes

- Initial release of @floormap/core, @floormap/svg, and @floormap/react.

### Patch Changes

- Updated dependencies
- @floormap/core@0.1.0
281 changes: 281 additions & 0 deletions packages/adapters/react/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,281 @@
# @floormap/react

React adapter for [`@floormap/core`](../../core). Provides a drop-in `<FloormapCanvas>` component and hooks for building interactive 2D editors — floor plans, seat maps, office layouts — with zero boilerplate.

## Installation

```bash
npm install @floormap/core @floormap/react
# or
pnpm add @floormap/core @floormap/react
```

React 18 is required as a peer dependency.

## Quick start

```tsx
import { useCallback, useEffect } from 'react';
import { createEmptyScene } from '@floormap/core';
import type { Entity, EntityId, LayerId } from '@floormap/core';
import { FloormapCanvas, useFloormapCore, useSelection, useViewport } from '@floormap/react';

const LAYER = 'main' as LayerId;

const initialScene = (() => {
const scene = createEmptyScene({ width: 1200, height: 800 }, [LAYER]);
// addEntity is a store helper — import from @floormap/core if needed,
// or use core.add() after the core is created.
return scene;
})();

export function FloorPlan() {
const core = useFloormapCore(() => ({
scene: initialScene,
viewport: { zoom: 1, pan: { x: 0, y: 0 }, screenSize: { width: 800, height: 600 } },
}));

const selection = useSelection(core);
const viewport = useViewport(core);

useEffect(() => {
core.add({
id: 'table-1' as EntityId,
layer: LAYER,
bounds: { x: 100, y: 100, width: 120, height: 80 },
selectable: true,
data: { label: 'Table 1' },
});
core.fitToScene(40);
}, [core]);

const drawEntity = useCallback((entity: Entity, { selected }: { selected: boolean }) => (
<rect
x={entity.bounds.x} y={entity.bounds.y}
width={entity.bounds.width} height={entity.bounds.height}
fill={selected ? '#3b82f6' : '#e5e7eb'} rx={4}
/>
), []);

return (
<div>
<p>Zoom: {Math.round(viewport.zoom * 100)}%</p>
<p>Selected: {[...selection].join(', ') || 'none'}</p>
<FloormapCanvas
core={core}
drawEntity={drawEntity}
grid={{ size: 40 }}
selectionOverlay={{}}
style={{ width: '100%', height: 500 }}
/>
</div>
);
}
```

---

## API reference

### `<FloormapCanvas>`

The main component. Renders an `<svg>` element, manages the viewport transform, wires all pointer/wheel interactions, and calls `drawEntity` for every entity in the scene.

```tsx
<FloormapCanvas
core={core}
drawEntity={(entity, { selected }) => <rect ... />}
grid={{ size: 40 }}
selectionOverlay={{}}
style={{ width: '100%', height: 600 }}
/>
```

#### Required props

| Prop | Type | Description |
|------|------|-------------|
| `core` | `FloormapCore` | The engine instance created with `useFloormapCore` |
| `drawEntity` | `(entity, ctx) => ReactNode` | Called for every entity — return React SVG elements |

#### Rendering

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `grid` | `GridOptions \| false` | `false` | Background grid. Pass `{}` to enable with defaults |
| `selectionOverlay` | `SelectionOverlayStyle \| false` | `{}` | Outline rects around selected entities. Pass `false` to disable |
| `className` | `string` | — | CSS class on the `<svg>` element |
| `style` | `CSSProperties` | — | Inline styles on the `<svg>` element |

#### Interaction

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `enableWheel` | `boolean` | `true` | Wheel-to-zoom |
| `wheelZoomFactor` | `number` | `0.0015` | Wheel sensitivity |
| `enablePanDrag` | `boolean` | `true` | Pointer drag-to-pan |
| `enableEntityDrag` | `boolean` | `true` | Click-drag on an entity to move it. Dragging a selected entity moves all selected entities together |
| `dragButton` | `0 \| 1 \| 2` | `0` | Mouse button for drag pan (0 = left, 1 = middle, 2 = right) |
| `pinchZoomFactor` | `number` | `0.005` | Pinch-to-zoom sensitivity |
| `clickSelect` | `boolean` | `true` | Click on an entity to select it |
| `modifierSelect` | `boolean` | `true` | Shift = add to selection, Ctrl/Meta = toggle |
| `onClickEntity` | `(id: EntityId) => void` | — | Called after `core.setSelection` when clicking a selectable entity |
| `clickThresholdPx` | `number` | `3` | Max pointer travel in pixels before a pointerdown/up is treated as a drag instead of a click |

#### `drawEntity` callback

```ts
drawEntity(entity: Entity, ctx: { selected: boolean }): ReactNode
```

Called for every entity during every repaint. Return React SVG elements — coordinates in `entity.bounds` are in world space, no transform needed.

```tsx
const drawEntity = useCallback((entity: Entity, { selected }: { selected: boolean }) => {
const { x, y, width, height } = entity.bounds;
const data = entity.data as { label: string };
return (
<g>
<rect x={x} y={y} width={width} height={height}
fill={selected ? '#3b82f6' : '#e2e8f0'} rx={4} />
<text x={x + width / 2} y={y + height / 2}
textAnchor="middle" dominantBaseline="middle" fontSize={12}>
{data?.label}
</text>
</g>
);
}, []);
```

Wrap in `useCallback` to avoid unnecessary re-renders.

#### Grid options

```ts
interface GridOptions {
size?: number; // cell size in world units — default 50
stroke?: string; // line color — default '#e5e7eb'
strokeWidth?: number; // line width in screen pixels — default 1
}
```

#### Selection overlay options

```ts
interface SelectionOverlayStyle {
stroke?: string; // outline color — default '#2563eb'
strokeWidth?: number; // outline width in world units — default 2
padding?: number; // outset from entity bounds in world units — default 4
fill?: string; // fill inside outline — default 'none'
}
```

---

### `useFloormapCore(init)`

Creates a `FloormapCore` instance that persists for the lifetime of the component. The initializer is called exactly once.

```ts
const core = useFloormapCore(() => ({
scene: myScene,
viewport: { zoom: 1, pan: { x: 0, y: 0 }, screenSize: { width: 800, height: 600 } },
}));
```

Accepts either a factory function (lazy, called once) or a plain options object. The core is never recreated on re-renders regardless of which form you use.

---

### `useSelection(core)`

Returns the current selection as a `ReadonlySet<EntityId>`. The component re-renders only when the selection changes.

```ts
const selection = useSelection(core);
const isSelected = selection.has('table-1' as EntityId);
```

---

### `useViewport(core)`

Returns the current `Viewport` snapshot. Re-renders on every pan, zoom, or resize.

```ts
const viewport = useViewport(core);
console.log(`${Math.round(viewport.zoom * 100)}%`);
```

---

### `useCoreEvent(core, event, handler)`

Subscribes to any event emitted by the core. The subscription is stable — `handler` can be an inline function without triggering re-subscriptions on every render.

```ts
useCoreEvent(core, 'entities:changed', ({ type, ids }) => {
if (type === 'remove') syncWithServer(ids);
});

useCoreEvent(core, 'selection:change', ({ selection }) => {
console.log('selected:', selection);
});
```

---

## Patterns

### Updating `screenSize` on resize

`FloormapCanvas` automatically keeps `core.viewport.screenSize` in sync with the `<svg>` element via a `ResizeObserver` — no manual wiring needed.

### Fitting the scene on mount

```tsx
useEffect(() => {
core.fitToScene(40); // 40px world-unit padding
}, [core]);
```

### Reading entity data

```ts
interface RoomData { label: string; capacity: number; }

const drawEntity = useCallback((entity: Entity, { selected }: { selected: boolean }) => {
const data = entity.data as RoomData;
return <rect ... />;
}, []);
```

### Programmatic selection

```ts
// Select a single entity
core.setSelection(['room-101' as EntityId], 'replace');

// Add to existing selection
core.setSelection(['room-102' as EntityId], 'add');

// Clear selection
core.setSelection([], 'replace');
```

### Subscribing to selection changes outside a component

```ts
const off = core.on('selection:change', ({ selection }) => {
console.log('selected ids:', selection);
});

// Later — unsubscribe
off();
```

---

## License

[MIT](../../../LICENSE)
Loading
Loading