diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..37f4414 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,51 @@ +name: Bug report +description: Something doesn't work as documented. +labels: [bug] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to report a bug. Security issues must be reported privately; see SECURITY.md. + - type: dropdown + id: package + attributes: + label: Package + multiple: true + options: + - '@spatialkit/core' + - '@spatialkit/svg' + - '@spatialkit/react' + - Not sure + validations: + required: true + - type: input + id: version + attributes: + label: Package version + placeholder: '0.2.0' + validations: + required: true + - type: textarea + id: description + attributes: + label: What happened? + description: What did you expect to happen, and what happened instead? + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Reproduction + description: Minimal code or a link to a repository or sandbox that reproduces the problem. + render: ts + validations: + required: true + - type: textarea + id: environment + attributes: + label: Environment + description: Browser and version, OS, framework version (React, bundler) if relevant. + placeholder: | + Browser: Chrome 140 + OS: macOS 15 + React: 19.1 diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..cd885d7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Report a security vulnerability + url: https://github.com/spatialkit/spatial/security/advisories/new + about: Please report security issues privately, not as public issues. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..e181643 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,40 @@ +name: Feature request +description: Suggest a new feature or an improvement. +labels: [enhancement] +body: + - type: dropdown + id: package + attributes: + label: Package + multiple: true + options: + - '@spatialkit/core' + - '@spatialkit/svg' + - '@spatialkit/react' + - New package + - Not sure + validations: + required: true + - type: textarea + id: problem + attributes: + label: Problem + description: What are you trying to build, and what is missing or hard today? + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposed solution + description: How could the API look? Code sketches are welcome. + - type: textarea + id: alternatives + attributes: + label: Alternatives and workarounds + description: Anything you tried or considered. + - type: checkboxes + id: contribute + attributes: + label: Contribution + options: + - label: I'd like to work on this. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..dd9611c --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,17 @@ +## What does this change? + + + +Closes # + +## How was it tested? + + + +## Checklist + +- [ ] `pnpm typecheck && pnpm test && pnpm lint && pnpm build` pass locally +- [ ] Tests added or updated +- [ ] Docs (READMEs) updated if the public API changed +- [ ] Changeset added (`pnpm changeset`) if a published package changed +- [ ] No new production dependencies diff --git a/CLAUDE.md b/CLAUDE.md index d75828a..f34474e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,7 +5,7 @@ Spatial is a zero-dependency TypeScript toolkit for building interactive 2D editors (floor plans, seat maps, office layouts, warehouse maps). It exposes low-level primitives for pan/zoom/selection/picking and ships pluggable renderers. **Repo:** `github.com/spatialkit/spatial` -**Status:** v0.0.0 — core stable, SVG renderer complete, React adapter in progress +**Status:** v0.x — core, SVG renderer and React adapter are functional; the API may still change between minor versions > Detailed per-package guides: [`packages/core/CLAUDE.md`](packages/core/CLAUDE.md) · [`packages/svg/CLAUDE.md`](packages/svg/CLAUDE.md) @@ -34,7 +34,7 @@ Adapters live under `packages/adapters/` — add new framework adapters (e.g. `v ```bash pnpm test # run all tests once (vitest) pnpm test:watch # vitest in watch mode -pnpm typecheck # tsc -b --verbose (all packages) +pnpm typecheck # tsc --noEmit (all packages) pnpm build # tsup build for all packages pnpm lint # eslint on all .ts/.tsx pnpm dev # dev server (packages/examples) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..d7ad21f --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,84 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement privately through the repository's [private reporting form](https://github.com/spatialkit/spatial/security/advisories/new) (start the title with "Code of Conduct"), or by contacting the maintainer, [@lucasfelixs](https://github.com/lucasfelixs), on GitHub. All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b6f14d1 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,106 @@ +# Contributing to Spatial + +Thanks for your interest in contributing. This guide covers how to set up the project, the conventions the code follows, and how changes get released. + +By participating, you agree to follow the [Code of Conduct](./CODE_OF_CONDUCT.md). + +## Ways to contribute + +- **Report a bug**: open an issue using the bug report template. Include a minimal reproduction. +- **Suggest a feature**: open an issue using the feature request template before writing code, so the design can be discussed first. +- **Improve the docs**: fixes to READMEs and examples are always welcome. +- **Pick an issue**: issues labeled [`good first issue`](https://github.com/spatialkit/spatial/labels/good%20first%20issue) or [`help wanted`](https://github.com/spatialkit/spatial/labels/help%20wanted) are a good place to start. Comment on the issue before starting, so work isn't duplicated. + +Security issues must not be reported in public issues. See [SECURITY.md](./SECURITY.md). + +## Development setup + +**Prerequisites:** Node.js 22 (see [`.nvmrc`](./.nvmrc)) and pnpm 10. + +```bash +git clone https://github.com//spatial.git +cd spatial +pnpm install +pnpm test +``` + +| Command | Description | +|---------|-------------| +| `pnpm test` | Run all tests once (Vitest) | +| `pnpm test:watch` | Run tests in watch mode | +| `pnpm typecheck` | Type-check all packages | +| `pnpm lint` | Run ESLint | +| `pnpm build` | Build the publishable packages (ESM + CJS + types) | +| `pnpm dev` | Start the vanilla JS example (Vite) | +| `pnpm dev:react` | Start the React example (Vite) | + +## Repository layout + +``` +packages/ + core/ @spatialkit/core — scene engine, viewport, selection, events, picking + svg/ @spatialkit/svg — SVG renderer + DOM event handlers + adapters/ + react/ @spatialkit/react — React adapter (hooks + SpatialCanvas) + examples/ + js-vanilla/ vanilla JS example (not published) + react/ React example (not published) +``` + +Each package README documents its public API. + +## Code conventions + +- **No production dependencies** in `@spatialkit/core`, `@spatialkit/svg` or `@spatialkit/react`. Peer dependencies on other `@spatialkit/*` packages and on React are the only exceptions. +- **`@spatialkit/core` stays framework-agnostic**: no DOM, no browser APIs. +- **TypeScript strict**: no `any`, no unused variables (prefix intentionally unused arguments with `_`). +- **Branded ids**: use `EntityId` and `LayerId`, never plain `string`. +- **Immutable selection**: never mutate the `Set` returned by `applySelection`. +- **Factory functions over classes** (`createCore`, `createEmptyScene`). +- **Comments** only when the *why* is not obvious from the code. +- **Formatting**: Prettier (single quotes, semicolons, 100-character lines). Run `npx prettier --write ` on what you changed. + +## Tests + +- Tests live in `src/__tests__/*.test.ts(x)` inside each package. +- `core` tests run in Node; `svg` and `react` tests run in jsdom. +- jsdom returns a zero rect from `getBoundingClientRect` and does not implement `setPointerCapture` or `ResizeObserver`. Mock them in tests that depend on them. +- New features and bug fixes need tests. A bug fix should include a test that fails without the fix. + +## Pull requests + +1. Fork the repository and create a branch from `main` (for example `fix/pinch-zoom-origin` or `feat/rubber-band-selection`). +2. Make the change, with tests and docs. +3. Add a changeset if the change affects a published package (see below). +4. Make sure everything passes locally: + + ```bash + pnpm typecheck && pnpm test && pnpm lint && pnpm build + ``` + +5. Open the pull request against `main` and fill in the template. Keep it focused on one change. + +CI runs the same checks on every pull request. A maintainer will review it; please be patient and responsive to feedback. + +## Changesets and releases + +Versioning and changelogs are managed with [Changesets](https://github.com/changesets/changesets). If your change affects a published package, run: + +```bash +pnpm changeset +``` + +Pick the affected packages and the bump type, and write a short summary for the changelog. Commit the generated file in `.changeset/` with your pull request. + +While the packages are on `0.x`: + +- `patch`: bug fixes and internal changes +- `minor`: new features **and** breaking changes + +Changes to docs, tests, examples or tooling don't need a changeset. + +After merge, a bot opens a "version packages" pull request. When a maintainer merges it, the packages are published to npm automatically. + +## License + +By contributing, you agree that your contributions will be licensed under the [MIT License](./LICENSE). diff --git a/LICENSE b/LICENSE index 0bd224f..f0a9f69 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 spatialkit +Copyright (c) 2025 Lucas Felix Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index fcf0db8..5caeb88 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,15 @@ Spatial
Open-source TypeScript toolkit for interactive 2D editors and floor plans. +
+
+ Live demo +

+ +

+ CI + npm @spatialkit/core + MIT license

--- @@ -19,9 +28,9 @@ Spatial provides the low-level engine for pan/zoom, selection, hit testing, and | Package | Version | Description | |---------|---------|-------------| -| [`@spatialkit/core`](packages/core) | 0.1.0 | Scene engine, viewport, event bus, picking, selection | -| [`@spatialkit/svg`](packages/svg) | 0.1.0 | SVG renderer + DOM event handlers | -| [`@spatialkit/react`](packages/adapters/react) | 0.1.0 | React adapter — hooks and `SpatialCanvas` component | +| [`@spatialkit/core`](packages/core) | [![npm](https://img.shields.io/npm/v/@spatialkit/core)](https://www.npmjs.com/package/@spatialkit/core) | Scene engine, viewport, event bus, picking, selection | +| [`@spatialkit/svg`](packages/svg) | [![npm](https://img.shields.io/npm/v/@spatialkit/svg)](https://www.npmjs.com/package/@spatialkit/svg) | SVG renderer + DOM event handlers | +| [`@spatialkit/react`](packages/adapters/react) | [![npm](https://img.shields.io/npm/v/@spatialkit/react)](https://www.npmjs.com/package/@spatialkit/react) | React adapter — hooks and `SpatialCanvas` component | --- @@ -139,6 +148,7 @@ The main component. Renders an `` element and wires all interactions. clickThresholdPx={3} wheelZoomFactor={0.0015} pinchZoomFactor={0.005} + snapToGrid={20} // snap drag and resize to a 20-unit grid (off by default) // SVG element className="my-canvas" @@ -152,6 +162,10 @@ The main component. Renders an `` element and wires all interactions. **`selectionOverlay`** draws an outline rect around each selected entity. Pass `false` to disable. +**Resize handles** are drawn on every selected entity. Drag one of the 8 handles to resize; the size in pixels stays the same at any zoom level. + +**`snapToGrid`** rounds entity positions (on drag) and edges (on resize) to the nearest multiple of the given world-space size. + --- ### Hooks @@ -297,6 +311,8 @@ renderer.destroy(); - Click-to-select with AABB hit testing - Multi-select: Shift (add), Ctrl/Meta (toggle) - Drag-to-move selected entities +- Drag handles to resize the selected entity +- Optional snap-to-grid for drag and resize **Rendering** (via `@spatialkit/svg` or `@spatialkit/react`) - Bring-your-own-drawEntity callback — full SVG freedom @@ -364,6 +380,7 @@ All entity `bounds` are in world coordinates. Mouse positions from DOM events ar - **[`packages/core/README.md`](packages/core/README.md)** — full API reference: `createCore`, `createEmptyScene`, viewport methods, events, picking, selection - **[`packages/svg/README.md`](packages/svg/README.md)** — `mountSvgRenderer` options, `drawEntity` callback, grid, selection overlay, pointer handler configuration +- **[`packages/adapters/react/README.md`](packages/adapters/react/README.md)** — `SpatialCanvas` props, hooks (`useSpatialCore`, `useSelection`, `useViewport`, `useCoreEvent`), patterns --- @@ -381,7 +398,7 @@ pnpm install |---------|-------------| | `pnpm test` | Run all tests once (vitest) | | `pnpm test:watch` | Vitest in watch mode | -| `pnpm typecheck` | `tsc -b` across all packages | +| `pnpm typecheck` | `tsc --noEmit` across all packages | | `pnpm build` | tsup build (ESM + CJS + .d.ts) | | `pnpm lint` | ESLint on all `.ts` files | | `pnpm dev` | Start examples dev server (Vite, `localhost:5173`) | @@ -392,12 +409,9 @@ All commands run from the repo root. Per-package commands also work inside each ## Contributing -If you find a bug or want to suggest an improvement, please open an **issue**. +Contributions are welcome. Read [CONTRIBUTING.md](./CONTRIBUTING.md) for the development setup and pull request process, and the [Code of Conduct](./CODE_OF_CONDUCT.md) before participating. -For pull requests: -- Keep the PR focused on a single change or feature -- Run `pnpm typecheck && pnpm test && pnpm lint` before submitting -- Do not add production dependencies to `@spatialkit/core`, `@spatialkit/svg`, or `@spatialkit/react` +To report a security issue, follow [SECURITY.md](./SECURITY.md). Do not open a public issue. --- diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..53f81dc --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,38 @@ +# Security Policy + +## Supported versions + +Spatial is in `0.x`. Security fixes are released for the latest published minor version of each package only. + +| Package | Supported | +|---------|-----------| +| `@spatialkit/core` | latest `0.x` minor | +| `@spatialkit/svg` | latest `0.x` minor | +| `@spatialkit/react` | latest `0.x` minor | + +## Reporting a vulnerability + +**Do not open a public issue for security problems.** + +Report vulnerabilities privately through GitHub: + +1. Go to the [Security tab](https://github.com/spatialkit/spatial/security) of this repository. +2. Click **Report a vulnerability**. +3. Describe the issue, the affected package and version, and how to reproduce it. + +You can expect: + +- an acknowledgement within **7 days**; +- an assessment and, when confirmed, a plan for a fix; +- credit in the advisory once a fix is released, unless you prefer to stay anonymous. + +Please give us reasonable time to release a fix before disclosing the issue publicly. + +## Scope + +The published packages have no production dependencies and do not perform network requests. Relevant reports include, for example: + +- code paths that let untrusted entity data inject markup or scripts into the rendered SVG; +- issues in the published package contents or in the release pipeline (for example, a compromised build or publish workflow). + +Vulnerabilities in development-only tooling (test runners, bundlers) that do not affect the published packages are best reported upstream to those projects. diff --git a/packages/adapters/react/LICENSE b/packages/adapters/react/LICENSE index 0bd224f..f0a9f69 100644 --- a/packages/adapters/react/LICENSE +++ b/packages/adapters/react/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 spatialkit +Copyright (c) 2025 Lucas Felix Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/packages/adapters/react/README.md b/packages/adapters/react/README.md index e47f5b7..4f0d436 100644 --- a/packages/adapters/react/README.md +++ b/packages/adapters/react/README.md @@ -1,6 +1,6 @@ # @spatialkit/react -React adapter for [`@spatialkit/core`](../../core). Provides a drop-in `` component and hooks for building interactive 2D editors — floor plans, seat maps, office layouts — with zero boilerplate. +React adapter for [`@spatialkit/core`](https://github.com/spatialkit/spatial/tree/main/packages/core). Provides a drop-in `` component and hooks for building interactive 2D editors — floor plans, seat maps, office layouts — with zero boilerplate. ## Installation @@ -10,7 +10,7 @@ npm install @spatialkit/core @spatialkit/react pnpm add @spatialkit/core @spatialkit/react ``` -React 18 is required as a peer dependency. +React 18 or 19 is required as a peer dependency. ## Quick start @@ -121,6 +121,9 @@ The main component. Renders an `` element, manages the viewport transform, | `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 | +| `snapToGrid` | `number` | — | Grid size in world units. When set, entity positions (drag) and edges (resize) snap to multiples of it | + +Resize handles are drawn around each selected entity: 8 handles (corners and edge midpoints) with a fixed pixel size at any zoom. Dragging a handle resizes the entity. #### `drawEntity` callback @@ -278,4 +281,4 @@ off(); ## License -[MIT](../../../LICENSE) +[MIT](./LICENSE) diff --git a/packages/core/LICENSE b/packages/core/LICENSE index 0bd224f..f0a9f69 100644 --- a/packages/core/LICENSE +++ b/packages/core/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 spatialkit +Copyright (c) 2025 Lucas Felix Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/packages/core/README.md b/packages/core/README.md index 06bb9e4..b450bbe 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -283,12 +283,55 @@ type SelectionMode = 'replace' | 'add' | 'toggle'; These are exported for use in renderers and application code: ```ts -import { createEmptyScene, clamp, containsPointAABB, expandBounds, unionBounds } from '@spatialkit/core'; +import { + clamp, + containsPointAABB, + expandBounds, + unionBounds, + snapToGrid, + hitTestResizeHandles, + applyResizeDelta, +} from '@spatialkit/core'; clamp(value, min, max) // numeric clamp containsPointAABB(bounds, point) // true if point is inside bounds (inclusive) expandBounds(bounds, padding) // grows bounds by padding in all directions unionBounds(a, b) // smallest AABB containing both bounds +snapToGrid(value, gridSize) // rounds value to the nearest multiple of gridSize +``` + +#### Resizing + +Renderers use these to implement resize handles. They are exported so custom renderers can reuse the same behavior. + +```ts +import type { ResizeDirection } from '@spatialkit/core'; +// 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'nw' + +hitTestResizeHandles(selectedEntities, worldToScreen, screenPoint, handleSizePx = 8) +// → { entityId, direction } | null +// Checks the 8 handles (corners and edge midpoints) of each entity, in screen space. + +applyResizeDelta(originalBounds, direction, worldDelta, snapSize?) +// → Bounds +// Moves the edges named by `direction` by `worldDelta`. When `snapSize` is set, the moved edges +// snap to the grid. Width and height never go below 1. +``` + +Example: resize the bottom-right corner of an entity by a pointer delta. + +```ts +const handle = hitTestResizeHandles( + [...core.selection].map((id) => core.scene.entities.get(id)!), + (p) => core.worldToScreen(p), + pointerScreen, +); + +if (handle) { + const start = core.scene.entities.get(handle.entityId)!.bounds; + const bounds = applyResizeDelta(start, handle.direction, { x: 30, y: 10 }, 10); + core.update(handle.entityId, { bounds }); +} ``` --- @@ -345,4 +388,4 @@ const data = entity?.data as TableData | undefined; ## License -[MIT](../../LICENSE) +[MIT](./LICENSE) diff --git a/packages/svg/LICENSE b/packages/svg/LICENSE index 0bd224f..f0a9f69 100644 --- a/packages/svg/LICENSE +++ b/packages/svg/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 spatialkit +Copyright (c) 2025 Lucas Felix Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/packages/svg/README.md b/packages/svg/README.md index e938f0f..6b99118 100644 --- a/packages/svg/README.md +++ b/packages/svg/README.md @@ -1,6 +1,6 @@ # @spatialkit/svg -SVG renderer and DOM event handlers for [`@spatialkit/core`](../core). Mounts into any `` element, subscribes to core events, and paints the scene automatically. Includes wheel zoom, drag-to-pan, pinch-to-zoom, click-to-select, a background grid, and a selection highlight overlay. +SVG renderer and DOM event handlers for [`@spatialkit/core`](https://github.com/spatialkit/spatial/tree/main/packages/core). Mounts into any `` element, subscribes to core events, and paints the scene automatically. Includes wheel zoom, drag-to-pan, pinch-to-zoom, click-to-select, a background grid, a selection highlight overlay, drag-to-move, resize handles, and optional snap-to-grid. ## Installation @@ -84,6 +84,7 @@ interface SvgRenderer { | `clickThresholdPx` | `number` | `3` | Max pointer travel in pixels before a pointerdown/up is classified as a drag instead of a click | | `modifierSelect` | `boolean` | `true` | Shift = add to selection, Ctrl/Meta = toggle. When `false`, clicks always replace selection | | `onClickEntity` | `(id: EntityId) => void` | — | Called after `core.setSelection` when clicking a selectable entity | +| `snapToGrid` | `number` | — | Grid size in world units. When set, entity positions (drag) and edges (resize) snap to multiples of it | #### Rendering @@ -94,6 +95,18 @@ interface SvgRenderer { | `defs` | `(defs: SVGDefsElement) => void` | — | Populate `` with gradients, clip paths, patterns, etc. | | `clearOnDestroy` | `boolean` | `true` | Remove the viewport group and `` from the DOM on `destroy()` | +Resize handles are always drawn in the `overlays` group around each selected entity: 8 handles (corners and edge midpoints) with a fixed pixel size at any zoom. Dragging a handle resizes the entity, and takes priority over moving it. + +To draw handles yourself, for example in a custom renderer, use `paintResizeHandles`: + +```ts +import { paintResizeHandles } from '@spatialkit/svg'; +import type { ResizeHandleStyle } from '@spatialkit/svg'; + +const style: ResizeHandleStyle = { size: 8, fill: '#fff', stroke: '#2563eb', strokeWidth: 1.5 }; +paintResizeHandles(core, overlaysGroup, style); // values shown are the defaults +``` + --- ### `drawEntity` callback @@ -340,4 +353,4 @@ mountSvgRenderer(core, { ## License -[MIT](../../LICENSE) +[MIT](./LICENSE)