# @nice2dev/ui-graphics

> Professional-grade Pixel, Vector, Photo, Animation and Game Asset editors for React — fully tree-shakeable, zero external UI dependencies.

[![npm](https://img.shields.io/npm/v/@nice2dev/ui-graphics)](https://www.npmjs.com/package/@nice2dev/ui-graphics)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.x-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)

---

## Features

### Editors

- **PixelEditor** — Aseprite-inspired pixel art with layers, frames, dithering, GIF / sprite-sheet export, .aseprite import, tile map mode
- **VectorEditor** — SVG shapes, pen tool, boolean operations, gradients, pattern fills, text-on-path, PDF export
- **PhotoEditor** — 50+ filters, RAW support, smart selection (magic wand, lasso, magnetic), healing brush, content-aware fill, face detection, batch processing, AI style-transfer
- **AnimationEditor** — 2D character builder with skeleton rigging, IK/FK, ragdoll/cloth physics, motion paths, Lottie & Spine export
- **GameAsset2dEditor** — tile maps, sprite sheets, animation state machines, collision shapes, isometric 2.5D, multi-engine export (Tiled, Godot, Unity, Phaser, Construct)
- **NiceIconEditor** — SVG icon creation with variant system
- **NiceUIDesigner** — drag & drop UI builder generating React code
- **Nice3DTexturePainter** — paint textures on 3D models in-browser
- **NiceFontEditor** — glyph editor with SVG font export

### Core Systems

- **Plugin system** — register custom tools, filters, exporters, panels
- **Visual undo/redo** — thumbnail timeline history
- **Keyboard shortcuts** — customizable, remappable, exportable
- **Drag & drop** — external file/image drops into editors
- **RTL support** — right-to-left UI with logical style swapping
- **Minimap** — zoom navigator for large canvases
- **Grid/Guides/Rulers** — snap-to-grid, snap-to-guide, snap-to-pixel
- **Color blindness simulation** — 8 modes (protanopia, deuteranopia, etc.)
- **Dark/light theme** — CSS custom properties, auto system detection
- **i18n** — `NiceI18nProvider` — zero-dependency translation context

### Integrations

- Unsplash / Pexels stock image picker
- Adobe Creative Cloud connector
- Figma import/export
- Template library
- AI image generation (OpenAI, Stability)

### Collaboration

- Real-time collaborative editing (WebSocket transport)
- Comments/annotations
- Version history with preview

---

## Installation

```bash
npm install @nice2dev/ui-graphics framer-motion
# peer deps: react >=17, react-dom >=17, framer-motion >=10
```

## Quick Start

```tsx
import { PixelEditor } from '@nice2dev/ui-graphics';
import '@nice2dev/ui-graphics/style.css';

function App() {
  return <PixelEditor initialWidth={64} initialHeight={64} />;
}
```

---

## Editors

### PixelEditor

```tsx
import { PixelEditor } from '@nice2dev/ui-graphics';

<PixelEditor
  initialWidth={64}
  initialHeight={64}
  onSaveToLibrary={(dataUrl, name, mimeType) => upload(dataUrl)}
/>
```

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `initialWidth` | `number` | `64` | Canvas width in pixels |
| `initialHeight` | `number` | `64` | Canvas height in pixels |
| `className` | `string` | — | CSS class on root |
| `onSaveToLibrary` | `(dataUrl, name, mimeType) => void` | — | Callback on save |

### VectorEditor

```tsx
import { VectorEditor } from '@nice2dev/ui-graphics';

<VectorEditor />
```

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `className` | `string` | — | CSS class on root |

### PhotoEditor

```tsx
import { PhotoEditor } from '@nice2dev/ui-graphics';

<PhotoEditor />
```

### AnimationEditor

```tsx
import { AnimationEditor } from '@nice2dev/ui-graphics';

<AnimationEditor
  onChange={(cfg) => saveCharacter(cfg)}
  onNotify={(msg, type) => toast(msg, { type })}
/>
```

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `initialConfig` | `CharacterConfig` | `DEFAULT_CHARACTER` | Starting character config |
| `onChange` | `(cfg: CharacterConfig) => void` | — | Called on every change |
| `storageKey` | `string \| false` | `"nice2dev.animation-editor.character"` | localStorage key; `false` to disable |
| `onNotify` | `(msg, type?) => void` | — | Notification callback |
| `showJsonPanel` | `boolean` | `true` | Show JSON editor panel |
| `showPreview` | `boolean` | `true` | Show animated preview |
| `className` | `string` | — | CSS class on root |

### GameAsset2dEditor

```tsx
import { GameAsset2dEditor } from '@nice2dev/ui-graphics';

<GameAsset2dEditor />
```

---

## Core APIs

### i18n — Translation Provider

```tsx
import { NiceI18nProvider, AnimationEditor } from '@nice2dev/ui-graphics';

<NiceI18nProvider t={(key, fallback) => myI18n(key) ?? fallback}>
  <AnimationEditor />
</NiceI18nProvider>
```

### Plugin System

```tsx
import { PluginRegistry, NicePluginProvider, type EditorPlugin } from '@nice2dev/ui-graphics';

const myPlugin: EditorPlugin = {
  id: 'my-plugin',
  name: 'My Plugin',
  version: '1.0.0',
  editors: ['pixel'],
  tools: [{ id: 'custom-brush', label: 'Custom Brush' }],
  filters: [{ id: 'sepia', label: 'Sepia', apply: (img) => /* ... */ img }],
};

// Programmatic registration
PluginRegistry.register(myPlugin);

// Or via React context
<NicePluginProvider plugins={[myPlugin]}>
  <PixelEditor />
</NicePluginProvider>
```

### Theme (Dark / Light)

```tsx
import { NiceEditorThemeProvider, useEditorTheme } from '@nice2dev/ui-graphics';

<NiceEditorThemeProvider initialMode="auto">
  <YourApp />
</NiceEditorThemeProvider>

// Inside components:
const { theme, mode, setMode, toggleMode } = useEditorTheme();
```

### Keyboard Shortcuts

```tsx
import { ShortcutRegistry, useShortcuts, DEFAULT_SHORTCUTS } from '@nice2dev/ui-graphics';

// Register a custom shortcut
ShortcutRegistry.register({
  id: 'custom.action',
  label: 'My Action',
  category: 'Custom',
  defaultKey: 'Ctrl+Shift+M',
  action: () => console.log('fired!'),
});

// Remap an existing shortcut
ShortcutRegistry.remap('general.undo', 'Ctrl+Shift+Z');

// In components — activates key listener
const shortcuts = useShortcuts();
```

### Color Blindness Simulation

```tsx
import { simulateColor, simulateColorBlindness, COLOR_BLINDNESS_TYPES } from '@nice2dev/ui-graphics';

// Simulate a single color
const [r, g, b] = simulateColor(255, 0, 0, 'deuteranopia');

// Simulate on ImageData (in-place)
simulateColorBlindness(imageData, 'protanopia');
```

### Grid, Guides & Snapping

```tsx
import { snapToGrid, snapToGuides, snapPoint, createGuide } from '@nice2dev/ui-graphics';

const snapped = snapToGrid(17, 23, 16); // { x: 16, y: 16, snappedX: true, snappedY: true }
const guide = createGuide('vertical', 100);
```

### RTL Support

```tsx
import { NiceRTLProvider, useIsRTL } from '@nice2dev/ui-graphics';

<NiceRTLProvider direction="rtl">
  <PixelEditor />
</NiceRTLProvider>
```

### Animation Utilities

```tsx
import {
  solveTwoBoneIK,
  blendPose, tweenPose, ease,
  createLinearPath, evaluatePath,
  exportToLottie, exportToSpine,
} from '@nice2dev/ui-graphics';

// IK solving
const { upper, fore } = solveTwoBoneIK(0, 0, 100, 80, targetX, targetY);

// Pose blending
const midPose = blendPose(poseA, poseB, 0.5);

// Lottie export
const lottieJson = exportToLottie(characterConfig, choreography);
```

### Performance Fixes

```tsx
import { setupRetinaCanvas, SpatialHashGrid, AnimationCleanup } from '@nice2dev/ui-graphics';

// Retina-ready canvas
const ctx = setupRetinaCanvas(canvas, { width: 800, height: 600 });

// Spatial indexing for large shape sets
const grid = new SpatialHashGrid<Shape>(200);
grid.insert(shape, bounds);
const visible = grid.query(viewport);

// Memory-safe animation lifecycle
const cleanup = new AnimationCleanup();
cleanup.requestAnimationFrame(render);
cleanup.setTimeout(onComplete, 1000);
// On unmount:
cleanup.dispose();
```

---

## Development

```bash
# Build
npm run build

# Dev (watch mode)
npm run dev

# Demo app
npm run demo

# Storybook
npm run storybook

# Tests
npm run test
npm run test:watch
npm run test:coverage

# Performance benchmarks
npm run bench

# Bundle analysis
npm run analyze
```

## Architecture

```
src/
  index.ts          # public API barrel export
  pixel/            # PixelEditor + utils
  vector/           # VectorEditor + boolean ops, gradients
  photo/            # PhotoEditor + filters, selection
  animation/        # AnimationEditor + rig, physics, motion paths
    rig/            # Skeleton rigging, IK, FK, pose blending
    shapes/         # SVG body part renderers
  game/             # GameAsset2dEditor
  icon/             # NiceIconEditor
  ui/               # NiceUIDesigner
  texture/          # Nice3DTexturePainter
  font/             # NiceFontEditor
  core/             # Shared systems (plugins, shortcuts, theme, i18n, etc.)
```

Every editor and utility is independently tree-shakeable — import only what you need.

## License

MIT © NiceToDev
