Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): tilemap ellipse tool + saved-stamp library

yhhca92157e2086
diff --git a/desktop/src/i18n/messages/tile.ts b/desktop/src/i18n/messages/tile.ts
index ddac13933..0333a852d 100644
--- a/desktop/src/i18n/messages/tile.ts
+++ b/desktop/src/i18n/messages/tile.ts
@@ -10,6 +10,7 @@ export const tileMessages = defineMessages({
'tile.tool.brush': { en: 'Brush', zh: '笔刷' },
'tile.tool.eraser': { en: 'Eraser', zh: '橡皮擦' },
'tile.tool.rect': { en: 'Rect', zh: '矩形' },
+ 'tile.tool.ellipse': { en: 'Ellipse', zh: '椭圆' },
'tile.tool.line': { en: 'Line', zh: '直线' },
'tile.tool.bucket': { en: 'Bucket', zh: '填充' },
'tile.tool.select': { en: 'Select ({mod}C/X/V copy/cut/paste)', zh: '选择({mod}C/X/V 复制/剪切/粘贴)' },
@@ -25,6 +26,12 @@ export const tileMessages = defineMessages({
},
'tile.terrainBrush': { en: 'Terrain brush', zh: '地形笔刷' },
+ // — Saved-stamp library —
+ 'tile.saveStamp': { en: 'Save the current brush as a stamp', zh: '将当前笔刷保存为图章' },
+ 'tile.recallStamp': { en: '{name} ({w}×{h}) — click to use as brush', zh: '{name}({w}×{h})— 点击用作笔刷' },
+ 'tile.deleteStamp': { en: 'Delete stamp', zh: '删除图章' },
+ 'tile.stampsEmpty': { en: 'No saved stamps — pick a pattern, then save it here', zh: '暂无图章 — 选好图案后在此保存' },
+
// — Painter layer strip —
'tile.newLayerTip': { en: 'New layer on this tileset', zh: '在此瓦片集上新建层' },
'tile.show': { en: 'Show', zh: '显示' },
diff --git a/desktop/src/i18n/messages/viewport.ts b/desktop/src/i18n/messages/viewport.ts
index 1a9013a0f..b84309767 100644
--- a/desktop/src/i18n/messages/viewport.ts
+++ b/desktop/src/i18n/messages/viewport.ts
@@ -34,6 +34,7 @@ export const viewportMessages = defineMessages({
},
'vp.tileHint.erase': { en: 'Drag to erase (brush-sized) · Q/Esc exits', zh: '拖动擦除(笔刷大小)· Q/Esc 退出' },
'vp.tileHint.rect': { en: 'Drag a rectangle to fill · Q/Esc exits', zh: '拖出矩形以填充 · Q/Esc 退出' },
+ 'vp.tileHint.ellipse': { en: 'Drag a box to fill its ellipse · Q/Esc exits', zh: '拖出包围盒以填充椭圆 · Q/Esc 退出' },
'vp.tileHint.line': { en: 'Drag a straight line · Q/Esc exits', zh: '拖出直线 · Q/Esc 退出' },
'vp.tileHint.bucket': { en: 'Click to fill the connected region · Q/Esc exits', zh: '点击填充连通区域 · Q/Esc 退出' },
'vp.tileHint.select': {
@@ -50,6 +51,7 @@ export const viewportMessages = defineMessages({
'vp.tileTool.brush': { en: 'Brush', zh: '笔刷' },
'vp.tileTool.erase': { en: 'Erase', zh: '擦除' },
'vp.tileTool.rect': { en: 'Rect', zh: '矩形' },
+ 'vp.tileTool.ellipse': { en: 'Ellipse', zh: '椭圆' },
'vp.tileTool.line': { en: 'Line', zh: '直线' },
'vp.tileTool.bucket': { en: 'Bucket', zh: '油漆桶' },
'vp.tileTool.select': { en: 'Select', zh: '选择' },
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
index 17b5746cf..e91bc5a3a 100644
--- a/desktop/src/panels/TilemapPainter.tsx
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -11,9 +11,9 @@
import { useEffect, useRef, useState } from 'react';
import {
- Brush, Eraser, Square, Slash, PaintBucket, BoxSelect, Pipette,
+ Brush, Eraser, Square, Circle, Slash, PaintBucket, BoxSelect, Pipette,
FlipHorizontal, FlipVertical, RotateCw, Mountain, Plus, X, MousePointer2, Dices,
- ZoomIn, ZoomOut, Maximize2, Eye, EyeOff, Lock, Unlock,
+ ZoomIn, ZoomOut, Maximize2, Eye, EyeOff, Lock, Unlock, Bookmark,
} from 'lucide-react';
import { encodeTile, type TilesetAsset, type TileStamp } from 'esengine';
import { useTilemapPaint, type PaintTool, type PaletteTileset, type AtlasInfo } from '@/store/tilemapPaintStore';
@@ -28,6 +28,7 @@ import { colsFor, rowsFor, TERRAIN_COLORS } from '@/tools/tileMath';
import { loadTilesetAsset } from '@/tileset/loadTileset';
import { createTilemapFromTileset } from '@/tilemap/createTilemap';
import { AnimPreview, tileThumbStyle, type TileAtlas } from '@/tools/tileThumb';
+import { parseStampLibrary, serializeStampLibrary, stampLibraryKey, addStamp, removeStampAt, type SavedStamp } from '@/tools/stampLibrary';
import { IconButton } from '@/components/IconButton';
import { t } from '@/i18n';
@@ -35,6 +36,7 @@ const TOOLS: { id: PaintTool; icon: typeof Brush; label: string }[] = [
{ id: 'brush', icon: Brush, label: t('tile.tool.brush') },
{ id: 'erase', icon: Eraser, label: t('tile.tool.eraser') },
{ id: 'rect', icon: Square, label: t('tile.tool.rect') },
+ { id: 'ellipse', icon: Circle, label: t('tile.tool.ellipse') },
{ id: 'line', icon: Slash, label: t('tile.tool.line') },
{ id: 'bucket', icon: PaintBucket, label: t('tile.tool.bucket') },
{ id: 'select', icon: BoxSelect, label: t('tile.tool.select', { mod: MOD_LABEL }) },
@@ -109,6 +111,16 @@ export function TilemapPainter() {
const [reloadKey, setReloadKey] = useState(0);
const [addOpen, setAddOpen] = useState(false);
+ // Saved-stamp library — per project (stamps carry gids only this project's tilesets
+ // mint), persisted in localStorage, pure logic in tools/stampLibrary.
+ const projectRoot = ProjectStore.getSnapshot()?.root ?? '';
+ const [savedStamps, setSavedStamps] = useState<SavedStamp[]>(() =>
+ parseStampLibrary(typeof localStorage !== 'undefined' ? localStorage.getItem(stampLibraryKey(projectRoot)) : null));
+ const updateStamps = (next: SavedStamp[]) => {
+ setSavedStamps(next);
+ if (typeof localStorage !== 'undefined') localStorage.setItem(stampLibraryKey(projectRoot), serializeStampLibrary(next));
+ };
+
// Selecting a TilemapLayer loads ALL its referenced .estileset(s) into the palette,
// each assigned its firstId (matching resolveTilesetModel's running sum), so the tab
// bar can switch between them and painted cells encode to the right global gid.
@@ -464,6 +476,33 @@ export function TilemapPainter() {
)}
</span>
</div>
+ {tool !== 'terrain' && (
+ <div className="tp-stamps">
+ <IconButton size="sm" title={t('tile.saveStamp')} onClick={() => updateStamps(addStamp(savedStamps, stamp))}>
+ <Bookmark size={13} />
+ </IconButton>
+ {savedStamps.length === 0 ? (
+ <span className="tp-stamps-empty">{t('tile.stampsEmpty')}</span>
+ ) : (
+ savedStamps.map((s, i) => (
+ <span key={s.name} className="tp-tschip tp-stampchip">
+ <button
+ type="button"
+ className="tp-tsbtn"
+ title={t('tile.recallStamp', { name: s.name, w: s.stamp.w, h: s.stamp.h })}
+ onClick={() => setStamp(s.stamp)}
+ >
+ <BrushThumbnail stamp={s.stamp} atlas={localAtlas} />
+ {s.name}
+ </button>
+ <button type="button" className="tp-tsx" title={t('tile.deleteStamp')} onClick={() => updateStamps(removeStampAt(savedStamps, i))}>
+ <X size={11} />
+ </button>
+ </span>
+ ))
+ )}
+ </div>
+ )}
{tool !== 'terrain' && (
<div className="tp-tilesets">
{tilesets.map((ts, i) => (
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 1af35cd0e..da60e448f 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -398,6 +398,7 @@ const TILE_HINT: Record<PaintTool, string> = {
brush: t('vp.tileHint.brush'),
erase: t('vp.tileHint.erase'),
rect: t('vp.tileHint.rect'),
+ ellipse: t('vp.tileHint.ellipse'),
line: t('vp.tileHint.line'),
bucket: t('vp.tileHint.bucket'),
select: t('vp.tileHint.select', { mod: MOD_LABEL }),
@@ -407,7 +408,7 @@ const TILE_HINT: Record<PaintTool, string> = {
// Label for the mode badge — the paint tool's short name.
const TILE_TOOL_LABEL: Record<PaintTool, string> = {
- brush: t('vp.tileTool.brush'), erase: t('vp.tileTool.erase'), rect: t('vp.tileTool.rect'), line: t('vp.tileTool.line'),
+ brush: t('vp.tileTool.brush'), erase: t('vp.tileTool.erase'), rect: t('vp.tileTool.rect'), ellipse: t('vp.tileTool.ellipse'), line: t('vp.tileTool.line'),
bucket: t('vp.tileTool.bucket'), select: t('vp.tileTool.select'), eyedropper: t('vp.tileTool.eyedropper'), terrain: t('vp.tileTool.terrain'),
};
diff --git a/desktop/src/store/tilemapPaintStore.ts b/desktop/src/store/tilemapPaintStore.ts
index 8cbeff5c2..bede238b6 100644
--- a/desktop/src/store/tilemapPaintStore.ts
+++ b/desktop/src/store/tilemapPaintStore.ts
@@ -14,7 +14,7 @@ import {
singleStamp, flipStampH, flipStampV, rotateStampCW, encodeTile,
} from 'esengine';
-export type PaintTool = 'brush' | 'erase' | 'rect' | 'line' | 'bucket' | 'select' | 'eyedropper' | 'terrain';
+export type PaintTool = 'brush' | 'erase' | 'rect' | 'ellipse' | 'line' | 'bucket' | 'select' | 'eyedropper' | 'terrain';
/** One tileset in the active layer's palette: its `.estileset` path, parsed asset, and
* the GLOBAL tile-id base (firstId) it occupies — matching the runtime tileset model, so
diff --git a/desktop/src/theme/tilemap.css b/desktop/src/theme/tilemap.css
index ed3a0ab8d..ef9591cf8 100644
--- a/desktop/src/theme/tilemap.css
+++ b/desktop/src/theme/tilemap.css
@@ -220,6 +220,19 @@
cursor: pointer;
}
.tp-tsx:hover { color: var(--error); background: var(--srf-4); }
+/* Saved-stamp library strip: save button + recall chips (tileset-chip vocabulary,
+ each chip previews its pattern via the brush thumbnail). */
+.tp-stamps {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 8px;
+ overflow-x: auto;
+ background: var(--srf-0);
+ border-bottom: 1px solid var(--line);
+}
+.tp-stamps-empty { color: var(--text-faint); font-size: var(--fs-xs); white-space: nowrap; }
+.tp-stampchip .tp-tsbtn { display: inline-flex; align-items: center; gap: 5px; padding: 2px 7px; }
/* Add-tileset opener + dropdown of the project's other .estileset assets. */
.tp-tsadd-wrap { position: relative; flex: 0 0 auto; }
.tp-tsadd {
diff --git a/desktop/src/tools/stampLibrary.ts b/desktop/src/tools/stampLibrary.ts
new file mode 100644
index 000000000..5d131727b
--- /dev/null
+++ b/desktop/src/tools/stampLibrary.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file stampLibrary.ts
+ * @brief The tilemap painter's saved-stamp library (pure half): parse/serialize
+ * the per-project localStorage blob (fail-quiet — a corrupt blob yields
+ * an empty library, never a crash), add with auto-naming + dedupe, and
+ * remove. Stamps carry raw cells (gids + flip flags), so they are only
+ * meaningful within the project whose tilesets minted those gids —
+ * hence per-project persistence, keyed by project root.
+ */
+import type { TileStamp } from 'esengine';
+
+export interface SavedStamp {
+ name: string;
+ stamp: TileStamp;
+}
+
+/** The localStorage key for a project's stamp library. */
+export function stampLibraryKey(projectRoot: string): string {
+ return `estella.tileStamps:${projectRoot}`;
+}
+
+function isValidStamp(s: unknown): s is TileStamp {
+ if (!s || typeof s !== 'object') return false;
+ const t = s as TileStamp;
+ return (
+ Number.isInteger(t.w) && t.w > 0 &&
+ Number.isInteger(t.h) && t.h > 0 &&
+ Array.isArray(t.cells) && t.cells.length === t.w * t.h &&
+ t.cells.every((c) => typeof c === 'number')
+ );
+}
+
+/** Parse a stored library blob; invalid entries (or garbage input) drop silently. */
+export function parseStampLibrary(json: string | null): SavedStamp[] {
+ if (!json) return [];
+ try {
+ const raw = JSON.parse(json) as unknown;
+ if (!Array.isArray(raw)) return [];
+ return raw.filter(
+ (e): e is SavedStamp =>
+ !!e && typeof e === 'object' &&
+ typeof (e as SavedStamp).name === 'string' &&
+ isValidStamp((e as SavedStamp).stamp),
+ );
+ } catch {
+ return [];
+ }
+}
+
+export function serializeStampLibrary(list: SavedStamp[]): string {
+ return JSON.stringify(list);
+}
+
+const sameStamp = (a: TileStamp, b: TileStamp): boolean =>
+ a.w === b.w && a.h === b.h && a.cells.every((c, i) => c === b.cells[i]);
+
+/**
+ * Add `stamp` under the lowest free auto-name (S1, S2, …). Adding a stamp that
+ * is already in the library (same size + cells) returns the list unchanged.
+ */
+export function addStamp(list: SavedStamp[], stamp: TileStamp): SavedStamp[] {
+ if (list.some((e) => sameStamp(e.stamp, stamp))) return list;
+ const used = new Set(list.map((e) => e.name));
+ let n = 1;
+ while (used.has(`S${n}`)) n++;
+ return [...list, { name: `S${n}`, stamp: { w: stamp.w, h: stamp.h, cells: [...stamp.cells] } }];
+}
+
+export function removeStampAt(list: SavedStamp[], index: number): SavedStamp[] {
+ return list.filter((_, i) => i !== index);
+}
diff --git a/desktop/src/tools/tileMode.ts b/desktop/src/tools/tileMode.ts
index 1207db7b6..3b8c519f2 100644
--- a/desktop/src/tools/tileMode.ts
+++ b/desktop/src/tools/tileMode.ts
@@ -54,14 +54,14 @@ export function exitTilePaint(transform: ToolMode = 'select'): void {
/** Single-key hint shown on each paint tool button — one key per tool, no collisions
* among themselves (Q/W/E/R stay the transform tools until you're actually painting). */
export const TILE_TOOL_KEY: Record<PaintTool, string> = {
- brush: 'B', erase: 'E', rect: 'U', line: 'L', bucket: 'G', select: 'M', eyedropper: 'I', terrain: 'T',
+ brush: 'B', erase: 'E', rect: 'U', ellipse: 'O', line: 'L', bucket: 'G', select: 'M', eyedropper: 'I', terrain: 'T',
};
// Keys that select a paint tool from the tile context whether or not one is active yet.
// Deliberately excludes the transform letters except E (erasing is worth the override —
// tilemaps are rarely keyboard-rotated; rotate/scale stay reachable via the toolbar).
const ENTRY_KEY: Record<string, PaintTool> = {
- b: 'brush', e: 'erase', u: 'rect', l: 'line', g: 'bucket', m: 'select', i: 'eyedropper', t: 'terrain',
+ b: 'brush', e: 'erase', u: 'rect', o: 'ellipse', l: 'line', g: 'bucket', m: 'select', i: 'eyedropper', t: 'terrain',
};
/**
diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.ts
index 87761d51e..b011c0086 100644
--- a/desktop/src/tools/tileTools.ts
+++ b/desktop/src/tools/tileTools.ts
@@ -82,6 +82,33 @@ export function cellPicker(stamp: TileStamp): (x: number, y: number) => number {
return (x, y) => tiledCell(stamp, x, y);
}
+/**
+ * The tile coords inside the ellipse inscribed in the (x0,y0)-(x1,y1) box (inclusive,
+ * unordered corners). Cell centers test against the ellipse equation with the radii
+ * pulled in a quarter-cell (w/2 − 0.25) — the classic pixel-circle tweak, so a 3×3
+ * reads as a plus (corners out) instead of a filled square while 2×2 stays full.
+ * Exported for tests (like lineCells).
+ */
+export function ellipseCells(x0: number, y0: number, x1: number, y1: number): { x: number; y: number }[] {
+ const minX = Math.min(x0, x1);
+ const maxX = Math.max(x0, x1);
+ const minY = Math.min(y0, y1);
+ const maxY = Math.max(y0, y1);
+ const cx = (minX + maxX) / 2;
+ const cy = (minY + maxY) / 2;
+ const rx = Math.max(0.25, (maxX - minX + 1) / 2 - 0.25);
+ const ry = Math.max(0.25, (maxY - minY + 1) / 2 - 0.25);
+ const cells: { x: number; y: number }[] = [];
+ for (let y = minY; y <= maxY; y++) {
+ for (let x = minX; x <= maxX; x++) {
+ const nx = (x - cx) / rx;
+ const ny = (y - cy) / ry;
+ if (nx * nx + ny * ny <= 1) cells.push({ x, y });
+ }
+ }
+ return cells;
+}
+
/** The tile coords a Bresenham line from (x0,y0) to (x1,y1) passes through (inclusive). */
export function lineCells(x0: number, y0: number, x1: number, y1: number): { x: number; y: number }[] {
const cells: { x: number; y: number }[] = [];
@@ -319,6 +346,50 @@ function makeLineTool(): EditorTool {
};
}
+/** Ellipse fill: drag the bounding box, fill its inscribed ellipse on release (one step). */
+function makeEllipseTool(): EditorTool {
+ let stroke: { sourceId: number; startX: number; startY: number } | null = null;
+ return {
+ id: 'tilemap.ellipse',
+ onPointerDown(p, ctx) {
+ const selId = selectedTilemap();
+ if (selId == null) return false;
+ const tile = cursorTile(p.clientX, p.clientY, selId);
+ if (!tile) return false;
+ stroke = { sourceId: selId, startX: tile.x, startY: tile.y };
+ TilePaintPreview.set({ kind: 'line', cells: [{ x: tile.x, y: tile.y }] });
+ ctx.capture(p.pointerId);
+ return true;
+ },
+ onPointerMove(p) {
+ if (!stroke) return;
+ const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ if (!tile) return;
+ TilePaintPreview.set({ kind: 'line', cells: ellipseCells(stroke.startX, stroke.startY, tile.x, tile.y) });
+ },
+ onPointerUp(p, ctx) {
+ if (!stroke) return;
+ ctx.release(p.pointerId);
+ TilePaintPreview.clear();
+ const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);
+ if (tile) {
+ const minX = Math.min(stroke.startX, tile.x);
+ const minY = Math.min(stroke.startY, tile.y);
+ const pick = cellPicker(activeStamp());
+ const edits: TilePaint[] = [];
+ for (const c of ellipseCells(stroke.startX, stroke.startY, tile.x, tile.y)) {
+ const raw = pick(c.x - minX, c.y - minY);
+ if (tileIdOf(raw) === 0) continue;
+ edits.push({ x: c.x, y: c.y, tileId: raw });
+ }
+ if (edits.length > 0) SceneCommands.paintTiles(stroke.sourceId, edits);
+ }
+ stroke = null;
+ },
+ cancel() { stroke = null; TilePaintPreview.clear(); },
+ };
+}
+
// Bound the flood fill so an empty-target fill on an infinite layer can't run away.
const BUCKET_CAP = 16384;
@@ -422,6 +493,7 @@ export const TILE_TOOLS: Record<PaintTool, EditorTool> = {
brush: brushTool,
erase: eraseTool,
rect: makeRectTool(),
+ ellipse: makeEllipseTool(),
line: makeLineTool(),
bucket: bucketTool,
select: makeSelectTool(),
diff --git a/desktop/tests/tile-ellipse.test.ts b/desktop/tests/tile-ellipse.test.ts
new file mode 100644
index 000000000..5a0e7a2cf
--- /dev/null
+++ b/desktop/tests/tile-ellipse.test.ts
@@ -0,0 +1,81 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Ellipse tile enumeration — the ellipse tool's committed tiles AND its live
+ * drag preview both walk this (like lineCells for the line tool). Pins the
+ * small-size shapes (the quarter-cell radius pull-in that keeps a 3×3 a plus,
+ * not a filled square), degenerate boxes, symmetry, and corner ordering; plus
+ * the saved-stamp library's parse/add/remove contract.
+ */
+import { describe, it, expect } from 'vitest';
+import { ellipseCells } from '@/tools/tileTools';
+import { parseStampLibrary, serializeStampLibrary, addStamp, removeStampAt } from '@/tools/stampLibrary';
+
+const key = (c: { x: number; y: number }) => `${c.x},${c.y}`;
+const keys = (cells: { x: number; y: number }[]) => new Set(cells.map(key));
+
+describe('ellipseCells', () => {
+ it('a 1×1 box is the single cell', () => {
+ expect(ellipseCells(2, 3, 2, 3)).toEqual([{ x: 2, y: 3 }]);
+ });
+
+ it('a 2×2 box stays fully filled (too small to round)', () => {
+ expect(ellipseCells(0, 0, 1, 1)).toHaveLength(4);
+ });
+
+ it('a 3×3 box rounds to a plus — corners out', () => {
+ const got = keys(ellipseCells(0, 0, 2, 2));
+ expect(got).toEqual(new Set(['1,0', '0,1', '1,1', '2,1', '1,2']));
+ });
+
+ it('a 1×n box degenerates to a full line', () => {
+ expect(ellipseCells(4, 0, 4, 4)).toHaveLength(5);
+ });
+
+ it('is corner-order independent and axis-symmetric', () => {
+ const a = keys(ellipseCells(0, 0, 6, 4));
+ expect(keys(ellipseCells(6, 4, 0, 0))).toEqual(a);
+ // symmetric about the box centre (3, 2)
+ for (const c of ellipseCells(0, 0, 6, 4)) {
+ expect(a.has(`${6 - c.x},${4 - c.y}`)).toBe(true);
+ }
+ });
+
+ it('a larger circle excludes corners but keeps the axis extremes', () => {
+ const got = keys(ellipseCells(0, 0, 6, 6));
+ expect(got.has('3,0')).toBe(true);
+ expect(got.has('0,3')).toBe(true);
+ expect(got.has('0,0')).toBe(false);
+ expect(got.has('6,6')).toBe(false);
+ });
+});
+
+describe('stamp library', () => {
+ const stamp = { w: 2, h: 1, cells: [5, 9] };
+
+ it('adds with auto-names and round-trips through serialization', () => {
+ const lib = addStamp(addStamp([], stamp), { w: 1, h: 1, cells: [3] });
+ expect(lib.map((e) => e.name)).toEqual(['S1', 'S2']);
+ expect(parseStampLibrary(serializeStampLibrary(lib))).toEqual(lib);
+ });
+
+ it('deduplicates an identical stamp and reuses freed names', () => {
+ let lib = addStamp([], stamp);
+ expect(addStamp(lib, { w: 2, h: 1, cells: [5, 9] })).toBe(lib); // same cells → unchanged
+ lib = addStamp(lib, { w: 1, h: 1, cells: [3] });
+ lib = removeStampAt(lib, 0); // frees S1
+ expect(addStamp(lib, stamp).map((e) => e.name)).toEqual(['S2', 'S1']);
+ });
+
+ it('drops garbage blobs and malformed entries', () => {
+ expect(parseStampLibrary(null)).toEqual([]);
+ expect(parseStampLibrary('not json')).toEqual([]);
+ expect(parseStampLibrary('{"a":1}')).toEqual([]);
+ const mixed = JSON.stringify([
+ { name: 'ok', stamp },
+ { name: 'bad', stamp: { w: 2, h: 2, cells: [1] } }, // cells ≠ w*h
+ { stamp }, // no name
+ ]);
+ expect(parseStampLibrary(mixed).map((e) => e.name)).toEqual(['ok']);
+ });
+});