hotspotLayer.test.ts 12.9 KB
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { HotspotLayer, type HotspotGrid } from './HotspotLayer';
import type { HotspotRow } from '../aggregate/types';

/**
 * 黑点图形的绘制守卫。
 *
 * 这一组只盯一件事:一片黑点的范围是**一条闭合轮廓**画出来的,不是一堆格子边。
 *
 * 为什么值得钉死:逐条格边 stroke 时,每段都是独立子路径、butt 端点,90° 台阶拐角
 * 外侧缺一个三角。格子越密缺口越多,屏幕上就是一堆没连起来的短线(实测截图如此,
 * 用户的原话是「线条杂乱 都没有连接起来」)。闭合环一次 stroke 后,拐角由 lineJoin
 * 连起来,这个失效模式就回不来了 —— 而它只在真实地图上肉眼可见,typecheck 与
 * 数字类断言都发现不了,所以只能把「画了几条子路径」记下来守。
 */

interface FakeCtx {
  calls: Map<string, number>;
  /** 关键落笔的先后顺序:erase(destination-out 的 fill)与 text(盘心数字 / 排名牌文字) */
  seq: string[];
  [key: string]: unknown;
}

function fakeCtx(): FakeCtx {
  const calls = new Map<string, number>();
  const seq: string[] = [];
  const hit = (name: string) => calls.set(name, (calls.get(name) ?? 0) + 1);
  const ctx: FakeCtx = { calls, seq };
  for (const name of [
    'setTransform',
    'clearRect',
    'beginPath',
    'closePath',
    'moveTo',
    'lineTo',
    'rect',
    'arc',
    'arcTo',
    'quadraticCurveTo',
    'fill',
    'stroke',
    'fillRect',
    'fillText',
    'strokeText',
    'save',
    'restore',
    'translate',
    'setLineDash',
    'clip',
    // jsdom 里 Path2D 是否存在随版本而变:两条命中路径都给个默认「不命中」,
    // 免得探针测试在不同 jsdom 版本上走的分支不一样。
    'isPointInPath',
    'isPointInStroke',
  ]) {
    ctx[name] = () => hit(name);
  }
  ctx.measureText = (text: string) => ({ width: String(text).length * 6 });
  /**
   * fill 单独记一笔:光雾朝内的那一半靠 destination-out 擦掉,是**用 fill 擦的**。
   * 只看 fill 的总数分不出「擦」和「填」,所以按调用那一刻的合成模式再记一个计数。
   */
  ctx.fill = () => {
    hit('fill');
    if (ctx.globalCompositeOperation === 'destination-out') {
      hit('erase');
      seq.push('erase');
    } else {
      seq.push('fill');
    }
  };
  ctx.fillText = () => {
    hit('fillText');
    seq.push('text');
  };
  return ctx;
}

class FakeCustomLayer {
  static created: FakeCustomLayer[] = [];
  render: (() => void) | null = null;
  constructor(readonly canvas: HTMLCanvasElement) {
    FakeCustomLayer.created.push(this);
  }
  setMap() {}
  show() {}
  hide() {}
}

const VIEW = { zoom: 13, lng: 114.0015, lat: 22.5015, w: 800, h: 600 };

function fakeMap() {
  return {
    getSize: () => ({ width: VIEW.w, height: VIEW.h }),
    getCenter: () => ({ getLng: () => VIEW.lng, getLat: () => VIEW.lat }),
    getZoom: () => VIEW.zoom,
    lngLatToContainer: () => ({ x: VIEW.w / 2, y: VIEW.h / 2 }),
    containerToLngLat: () => ({ getLng: () => VIEW.lng, getLat: () => VIEW.lat }),
  } as unknown as AMap.Map;
}

const ctx = fakeCtx();
let restoreCanvas: (() => void) | null = null;
let restoreAmap: (() => void) | null = null;

beforeEach(() => {
  ctx.calls.clear();
  ctx.seq.length = 0;
  FakeCustomLayer.created = [];
  const proto = window.HTMLCanvasElement.prototype as unknown as { getContext: () => unknown };
  const original = proto.getContext;
  proto.getContext = () => ctx;
  restoreCanvas = () => {
    proto.getContext = original;
  };
  const g = globalThis as Record<string, unknown>;
  const prev = g.AMap;
  g.AMap = { CustomLayer: FakeCustomLayer };
  restoreAmap = () => {
    g.AMap = prev;
  };
});

afterEach(() => {
  restoreCanvas?.();
  restoreAmap?.();
});

/** 100m 见方的栅格,域是一块 4×4(16 格) */
const GRID: HotspotGrid = {
  originLng: 114.0,
  originLat: 22.5,
  dLng: 0.001,
  dLat: 0.001,
  w: 40,
  h: 40,
};

function squareDomain(): { mask: Uint8Array; row: HotspotRow } {
  const mask = new Uint8Array(GRID.w * GRID.h);
  for (let y = 0; y < 4; y += 1) {
    for (let x = 0; x < 4; x += 1) mask[y * GRID.w + x] = 1;
  }
  const row = {
    id: 0,
    domainId: 1,
    lng: 114.0015,
    lat: 22.5015,
    count: 42,
    cells: 16,
    radiusM: 113,
    cellMeters: 100,
  } as unknown as HotspotRow;
  return { mask, row };
}

describe('黑点图形 · 一片一条闭合轮廓', () => {
  it('4×4 的域只产生 1 条闭合子路径,而不是 16 个格子的边', () => {
    const layer = new HotspotLayer(fakeMap() as unknown as import("./provider/types").Basemap);
    const { mask, row } = squareDomain();
    layer.setData([row], GRID, mask);

    const render = FakeCustomLayer.created[0]?.render;
    expect(render).toBeTypeOf('function');
    render!();

    // 一条闭合环 = 一次 closePath;旧的逐格描边根本不 closePath。
    // 注意排名牌也走 roundRectPath(内部会 closePath),所以不能断言「恰好 1 次」,
    // 改用 moveTo 的次数来区分:整片轮廓只有 1 个起点,旧画法每条格边都是一个起点。
    expect(ctx.calls.get('closePath') ?? 0).toBeGreaterThanOrEqual(1);
    expect(ctx.calls.get('moveTo') ?? 0).toBeLessThanOrEqual(5);
    // 旧画法每格一个 ctx.rect;闭合环用 lineTo 连边,一次 rect 都不该有
    expect(ctx.calls.get('rect') ?? 0).toBe(0);
    expect(ctx.calls.get('stroke') ?? 0).toBeGreaterThanOrEqual(1);
    expect(ctx.calls.get('fill') ?? 0).toBeGreaterThanOrEqual(1);

    // 圆润:轮廓的每个顶点一次二次贝塞尔(4×4 方块去共线后 4 个角)。
    // 现在整圈走 quadraticCurveTo(见 roundedPath),不再是 arcTo 的小倒角;排名牌另走 roundRectPath。
    expect(ctx.calls.get('quadraticCurveTo') ?? 0).toBeGreaterThanOrEqual(4);
    // 外发光 = 同一路径两层宽描边 + 一层主边,至少 3 次 stroke
    expect(ctx.calls.get('stroke') ?? 0).toBeGreaterThanOrEqual(3);
    layer.destroy();
  });

  it('轮廓内的点能命中这一片,轮廓外的点不命中', () => {
    const layer = new HotspotLayer(fakeMap() as unknown as import("./provider/types").Basemap);
    const { mask, row } = squareDomain();
    layer.setData([row], GRID, mask);
    FakeCustomLayer.created[0]?.render?.();

    // 视图中心就是这一片的中心 → 屏幕中心必落在格子内
    expect(layer.hitAt(VIEW.w / 2, VIEW.h / 2)).toBe(0);
    // 域只占中心一小块,左上角远在域外
    expect(layer.hitAt(30, 30)).toBe(-1);
    layer.destroy();
  });

  it('没拿到 grid+mask 时退回圆:走 arc,不画格子路径', () => {
    const layer = new HotspotLayer(fakeMap() as unknown as import("./provider/types").Basemap);
    const { row } = squareDomain();
    layer.setData([row]);
    FakeCustomLayer.created[0]?.render?.();

    expect(ctx.calls.get('arc') ?? 0).toBeGreaterThanOrEqual(1);
    expect(ctx.calls.get('rect') ?? 0).toBe(0);
    layer.destroy();
  });
});

/**
 * 2026-11-27 黑点降噪排查的两处命中漏洞。
 *
 * 第一处:画出来的排名牌与「画得见就点得着」对不上。牌心在轮廓外 effR+11 处,
 * 而脚印模式的命中只认轮廓路径 + 4px 描边;等效圆退回模式却专门给了 22px 余量和
 * 盘心 20px。同一个层、同一个视觉元素,两种模式的可点范围差一截。
 * 第二处:setData 之后、下一帧 paint 之前,逐格矩形缓存还是全 0 —— 点屏幕左上角
 * 会被误判成「命中了第 0 片黑点」,而真正的黑点此时一个都点不中。
 */
describe('黑点命中 · 画得见就点得着', () => {
  it('排名牌的中心落在这一片的可点范围内', () => {
    const layer = new HotspotLayer(fakeMap() as unknown as import('./provider/types').Basemap);
    const { mask, row } = squareDomain();
    layer.setData([row], GRID, mask);
    FakeCustomLayer.created[0]?.render?.();

    // 牌心公式:cx + cw/2 = x + off、cy + ch/2 = y - off,off = (effR+11)*0.7071。
    // 从上一帧投影好的轮廓顶点反推 effR(不依赖命中实现新增的字段,免得测试自证)。
    const internals = layer as unknown as { prepared: Array<{ screen: Float32Array[] }> };
    const screen = internals.prepared[0].screen!;
    let effR = 0;
    for (const ring of screen) {
      for (let k = 0; k < ring.length; k += 2) {
        effR = Math.max(effR, Math.hypot(ring[k] - VIEW.w / 2, ring[k + 1] - VIEW.h / 2));
      }
    }
    const off = (effR + 11) * 0.7071;
    expect(layer.hitAt(VIEW.w / 2 + off, VIEW.h / 2 - off)).toBe(0);
    layer.destroy();
  });

  it('喂完数据还没出帧时,屏幕左上角不能被误判成黑点', () => {
    const layer = new HotspotLayer(fakeMap() as unknown as import('./provider/types').Basemap);
    const { mask, row } = squareDomain();
    layer.setData([row], GRID, mask);
    // 刻意不 render:这一拍内 rects / sx / sy 还是刚分配的全 0
    expect(layer.hitAt(0, 0)).toBe(-1);
    layer.destroy();
  });
});

/**
 * 光雾的 destination-out 是按整条轮廓擦的,而同层所有黑点共用一张画布。
 * 逐片「画完一整片再画下一片」时,后一片的擦会把先一片的主边、填充、盘心数字
 * 与排名牌一起擦掉(两片脚印在屏幕上重叠时必现)。
 * 修法是两遍画:所有擦先做完,再做所有最终落笔。
 */
describe('黑点光雾 · 擦除与落笔分两遍', () => {
  it('所有片的擦都在任何盘心数字 / 排名牌之前', () => {
    const layer = new HotspotLayer(fakeMap() as unknown as import('./provider/types').Basemap);
    const mask = new Uint8Array(GRID.w * GRID.h);
    for (let y = 0; y < 4; y += 1) {
      for (let x = 0; x < 4; x += 1) mask[y * GRID.w + x] = 1;
    }
    for (let y = 20; y < 24; y += 1) {
      for (let x = 20; x < 24; x += 1) mask[y * GRID.w + x] = 1;
    }
    const { row } = squareDomain();
    const second = { ...row, id: 1, domainId: 2, lng: 114.0215, lat: 22.5215 } as HotspotRow;
    layer.setData([row, second], GRID, mask);
    FakeCustomLayer.created[0]?.render?.();

    const lastErase = ctx.seq.lastIndexOf('erase');
    const firstText = ctx.seq.indexOf('text');
    expect(lastErase).toBeGreaterThan(-1);
    expect(firstText).toBeGreaterThan(-1);
    expect(lastErase).toBeLessThan(firstText);
    layer.destroy();
  });
});

/**
 * 这两条守的是「炫」的那部分:外光雾 + 三明治描边,以及选中那一下不加戏。
 *
 * 它们都属于「画得好看」而不是「算得对」,没有数值可以断言,只能钉住笔数:
 * 少画一笔就退回一个平淡的描边圈,多画一笔则会在几十片同屏时拖慢拖动。
 */
describe('黑点图形 · 光效分档', () => {
  /** 20×20 的域:z13 下等效半径远超满配门槛,走完整特效 */
  function bigDomain(): { mask: Uint8Array; row: HotspotRow } {
    const mask = new Uint8Array(GRID.w * GRID.h);
    for (let y = 0; y < 20; y += 1) {
      for (let x = 0; x < 20; x += 1) mask[y * GRID.w + x] = 1;
    }
    const row = {
      id: 0,
      domainId: 1,
      lng: 114.0015,
      lat: 22.5015,
      count: 420,
      cells: 400,
      radiusM: 565,
      cellMeters: 100,
    } as unknown as HotspotRow;
    return { mask, row };
  }

  it('大片走满配:三档光雾 + 暗底 + 主边 + 高光,且光雾只留在轮廓外', () => {
    const layer = new HotspotLayer(fakeMap() as unknown as import("./provider/types").Basemap);
    const { mask, row } = bigDomain();
    layer.setData([row], GRID, mask);
    FakeCustomLayer.created[0]?.render?.();

    // 内侧发光已去掉:不再需要把轮廓 clip 一次再描宽线
    expect(ctx.calls.get('clip') ?? 0).toBe(0);
    // 光雾是描宽线,线宽一半在内 —— 必须用 destination-out 把里面那半擦掉。
    // 这一笔是「内圈光晕」这个问题的根治处:只靠 0.14 的填充压不住 0.34 的光。
    expect(ctx.calls.get('erase') ?? 0).toBeGreaterThanOrEqual(1);
    // 三档光雾 + 暗底 + 主边 + 高光 = 6 笔
    expect(ctx.calls.get('stroke') ?? 0).toBeGreaterThanOrEqual(6);
    // 一次擦 + 一次填充
    expect(ctx.calls.get('fill') ?? 0).toBeGreaterThanOrEqual(2);
    layer.destroy();
  });

  it('选中只在本层加粗描边,不额外建画布、不起动画', () => {
    const layer = new HotspotLayer(fakeMap() as unknown as import("./provider/types").Basemap);
    const { mask, row } = bigDomain();
    layer.setData([row], GRID, mask);
    FakeCustomLayer.created[0]?.render?.();
    const idle = ctx.calls.get('stroke') ?? 0;

    ctx.calls.clear();
    layer.setOptions({ active: 0 });
    FakeCustomLayer.created[0]?.render?.();
    // 同一批笔画,选中只是把线宽与浓度提一档 —— 不再有扩散光圈那几笔
    expect(ctx.calls.get('stroke') ?? 0).toBe(idle);
    // 全程只有一张画布:每片都配一张全屏 backing store 在 DPR 2 下是几十兆
    expect(FakeCustomLayer.created).toHaveLength(1);
    layer.destroy();
  });
});