/** U2 Task 5: the polygon arithmetic of the vertex handles (R-7, R-9). */ import { describe, expect, it } from 'vitest' import type { Point } from '@faunosteo/core-wasm/types' import { HANDLE_CAP, MIN_VERTICES, insertMidpoint, isNoOpMove, moveVertex, removeVertex, showsInsert, } from '@/editor/annotations/polygonEdit' const square: Point[] = [ [0, 0], [10, 0], [10, 10], [0, 10], ] describe('the limits', () => { it('caps the handles at 40 vertices and keeps 3 at least', () => { expect(HANDLE_CAP).toBe(40) expect(MIN_VERTICES).toBe(3) }) }) describe('insertMidpoint', () => { it.each([ [0, [5, 0], 1], [2, [5, 10], 3], // The last segment wraps to the first vertex. [3, [0, 5], 4], ] as const)('after %i adds %j at %i', (after, middle, at) => { const next = insertMidpoint(square, after)! expect(next).toHaveLength(5) expect(next[at]).toEqual(middle) }) it('rounds the midpoint to the 0.01 grid', () => { const odd: Point[] = [ [0, 0], [0.015, 0.025], [5, 5], ] expect(insertMidpoint(odd, 0)![1]).toEqual([0.01, 0.01]) }) it.each([-1, 4, 1.5, Number.NaN])('gives null for index %s', (index) => { expect(insertMidpoint(square, index)).toBeNull() }) }) describe('removeVertex', () => { it('removes the vertex at the index', () => { expect(removeVertex(square, 1)).toEqual([ [0, 0], [10, 10], [0, 10], ]) }) it('gives null at 3 vertices and out of range', () => { expect(removeVertex(square.slice(0, 3), 0)).toBeNull() expect(removeVertex(square, 4)).toBeNull() expect(removeVertex(square, -1)).toBeNull() }) }) describe('moveVertex', () => { it('moves one vertex, rounded to 0.01', () => { const next = moveVertex(square, 2, { x: 12.345, y: 9.999 })! expect(next[2]).toEqual([12.35, 10]) expect(next[0]).toBe(square[0]) }) it.each([ { x: Number.NaN, y: 1 }, { x: 1, y: Number.POSITIVE_INFINITY }, ])('gives null for a non-finite place %j', (to) => { expect(moveVertex(square, 0, to)).toBeNull() }) it('gives null out of range', () => { expect(moveVertex(square, 9, { x: 1, y: 1 })).toBeNull() }) }) describe('isNoOpMove', () => { const movedTo = (index: number, x: number, y: number) => moveVertex(square, index, { x, y })! it.each([ ['itself', 1, 10, 0], ['the next vertex', 1, 10, 10], ['the previous vertex', 1, 0, 0], // Wrapping both ways. ['the previous one across the start', 0, 0, 10], ['the next one across the end', 3, 0, 0], ] as const)('a release on %s is no change', (_, index, x, y) => { expect(isNoOpMove(square, index, movedTo(index, x, y))).toBe(true) }) it('a release elsewhere is a change, even on a vertex that is not a neighbour', () => { expect(isNoOpMove(square, 0, movedTo(0, 3, 3))).toBe(false) expect(isNoOpMove(square, 0, movedTo(0, 10, 10))).toBe(false) }) }) describe('showsInsert (R-9)', () => { it.each([ [20, 10, true], [19.99, 10, false], [44, 22, true], [43.9, 22, false], [0, 10, false], ])('a %s px segment with a %s px hit radius: %s', (segment, hit, shown) => { expect(showsInsert(segment, hit)).toBe(shown) }) })