frameBudget.test.ts 14.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
/**
 * 出帧预算的守卫。
 *
 * 这一组盯的不是画法,是「什么时候该落笔」。那几条规则散在四个自绘层和 CanvasSurface 里:
 * 视图与本层都没变就整帧跳过、不能落笔的层不发重画请求、量字只在第一次、快拖那一拍只算不画。
 * 它们的失效方式全都长在同一个方向上 —— 视图没变也重画、收起的层也被点名、每帧重新量一遍字。
 * 每一种都只让地图变沉,不让任何东西画错,所以观感看不出来、typecheck 看不出来,
 * 只有把「画了几笔」钉进测试才守得住。
 *
 * 怎么观察:jsdom 没有 canvas 实现,这里把 getContext 换成一份记账的假上下文,
 * 于是 clearRect / fillText / measureText 的次数就是这一层的实际落笔量与量字量。
 * CustomLayer 也换成假的:只把 render 回调留着,出帧由测试按帧点名(高德就是这么驱动的)。
 */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CasePinLayer } from './CasePinLayer';
import { ClusterLayer } from './ClusterLayer';
import { setMapGesture } from './gesture';
import { HotspotLayer } from './HotspotLayer';
import type { HotspotRow } from '../aggregate/types';
import { SpotlightLayer, type SpotlightData } from './SpotlightLayer';

/* ------------------------------ 假的浏览器现场 ------------------------------ */

/** 假 2d 上下文:方法只管记账,属性随便写(各层只读自己不关心的那几项) */
interface FakeCtx {
  calls: Map<string, number>;
  /** 清空这一帧的账。计数器跟着上下文走,而不是换成另一份假对象 */
  reset(): void;
  [key: string]: unknown;
}

function fakeCtx(): FakeCtx {
  const calls = new Map<string, number>();
  const hit = (name: string) => {
    calls.set(name, (calls.get(name) ?? 0) + 1);
  };
  const ctx: FakeCtx = {
    calls,
    reset: () => {
      calls.clear();
    },
  };
  for (const name of [
    'setTransform',
    'clearRect',
    'beginPath',
    'closePath',
    'moveTo',
    'lineTo',
    'arc',
    'arcTo',
    'fill',
    'stroke',
    'fillRect',
    'strokeRect',
    'fillText',
    'strokeText',
    'save',
    'restore',
    'translate',
    'setLineDash',
  ]) {
    ctx[name] = () => hit(name);
  }
  ctx.measureText = (text: string) => {
    hit('measureText');
    return { width: String(text).length * 6 };
  };
  const gradient = () => {
    return { addColorStop: () => undefined };
  };
  ctx.createRadialGradient = () => {
    hit('createRadialGradient');
    return gradient();
  };
  ctx.createLinearGradient = () => {
    hit('createLinearGradient');
    return gradient();
  };
  return ctx;
}

/** 假 CustomLayer:把 render 留着,出帧由测试点名;顺数建了几层 */
class FakeCustomLayer {
  static created: FakeCustomLayer[] = [];
  render: (() => void) | null = null;

  constructor(
    readonly canvas: HTMLCanvasElement,
    readonly opts: { zIndex: number; alwaysRender?: boolean },
  ) {
    FakeCustomLayer.created.push(this);
  }

  setMap() {}
  show() {}
  hide() {}
}

interface FakeView {
  zoom: number;
  lng: number;
  lat: number;
  w: number;
  h: number;
}

function fakeMap(view: FakeView) {
  return {
    view,
    map: {
      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,
  };
}

/**
 * 全程一份假上下文。
 *
 * 不能每个用例新建:内核的量字画布只建一次(模块级缓存),新用例若换掉假对象,
 * 那把尺子还握着上一个用例的上下文 —— 于是 measureText 的账记到别处,
 * 「量字只在第一次」这一组断言会集体空过(看着全绿,其实一笔都没量到)。
 */
const ctx = fakeCtx();

function count(name: string): number {
  return ctx.calls.get(name) ?? 0;
}

function resetCount(name: string) {
  ctx.calls.set(name, 0);
}

/** 每一层各测各的,取帧入口统一从这里走 */
function frameOf(index = 0): () => void {
  const render = FakeCustomLayer.created[index]!.render;
  if (!render) throw new Error('假 CustomLayer 没拿到 render 回调');
  return () => render();
}

const VIEW = (): FakeView => ({ zoom: 12, lng: 114.05, lat: 22.54, w: 800, h: 600 });

/**
 * 用例建了哪些层。断言中途抛错时,各层自建的 rAF 不能带着已还原的 getContext
 * 爬进下一个用例 —— 那会造成「arcTo is not a function」这类与断言无关的报错。
 */
const alive: { destroy: () => void }[] = [];
function keep<T extends { destroy: () => void }>(layer: T): T {
  alive.push(layer);
  return layer;
}

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

beforeEach(() => {
  ctx.reset();
  FakeCustomLayer.created = [];
  const proto = window.HTMLCanvasElement.prototype as unknown as {
    getContext: (id: string) => unknown;
  };
  const original = proto.getContext;
  proto.getContext = () => ctx;
  restoreCanvas = () => {
    proto.getContext = original;
  };
  const g = globalThis as Record<string, unknown>;
  const previous = g.AMap;
  g.AMap = { CustomLayer: FakeCustomLayer };
  restoreAmap = () => {
    g.AMap = previous;
  };
});

afterEach(() => {
  while (alive.length) alive.pop()?.destroy();
  restoreCanvas?.();
  restoreAmap?.();
  setMapGesture(false);
  vi.restoreAllMocks();
});

/* ------------------------------ 各层的最小数据 ------------------------------ */

/** 三个方格:够把「逐格落笔」跑起来,又不至于让断言读不出所以 */
function buckets() {
  return {
    lng: Int32Array.from([114_050_000, 114_060_000, 114_070_000]),
    lat: Int32Array.from([22_540_000, 22_545_000, 22_550_000]),
    count: Int32Array.from([1, 12, 240]),
    gx: Int32Array.from([0, 1, 2]),
    gy: Int32Array.from([0, 0, 0]),
  };
}

/** 三个黑点,彼此只隔千分之一度:任何一档缩放下都在屏幕里(分档色、盘心数、排名牌都走到) */
function hotspots(): HotspotRow[] {
  return [0, 1, 2].map((i) => ({
    domainId: `d${i}`,
    lng: 114.05 + i * 0.001,
    lat: 22.54 + i * 0.0005,
    district: i,
    street: i,
    count: 30 + i * 10,
    cells: 4 + i,
    radiusM: 180 + i * 40,
    cellMeters: 60,
    peak: 3,
    days: 5,
  })) as unknown as HotspotRow[];
}

/** 聚焦层的一档,格子多一些:分格线那一条断言要有量才分得出「逐格」还是「整档一次」 */
function spotlightData(cellCount: number): SpotlightData {
  const cells = Array.from({ length: cellCount }, (_, k) => ({
    lng: 114.05 + k * 0.0001,
    lat: 22.54 + k * 0.0001,
    n: cellCount - k,
  }));
  return {
    variant: 'streets',
    cellM: 100,
    units: [{ label: '滨海大道', count: 120, cells }],
  };
}

/* -------------------------------- 守卫内容 -------------------------------- */

describe('出帧预算 · 视图没变就不落笔', () => {
  it('同一视图连开三帧,只有一帧真的清屏重画', () => {
    const { map } = fakeMap(VIEW());
    const cluster = keep(new ClusterLayer(map as unknown as import("./provider/types").Basemap));
    const b = buckets();
    cluster.setData(b.lng, b.lat, b.count, b.gx, b.gy, 0.001, 0.001);
    const frame = frameOf();

    resetCount('clearRect');
    frame();
    frame();
    frame();
    // 视图与本层都没变 → 后两帧整帧跳过(begin 给 null,各层直接 return)
    expect(count('clearRect')).toBe(1);
    cluster.destroy();
  });

  it('视图每动一帧才清一帧屏', () => {
    const view = VIEW();
    const { map } = fakeMap(view);
    const cluster = keep(new ClusterLayer(map as unknown as import("./provider/types").Basemap));
    const b = buckets();
    cluster.setData(b.lng, b.lat, b.count, b.gx, b.gy, 0.001, 0.001);
    const frame = frameOf();

    resetCount('clearRect');
    view.lng += 0.002;
    frame();
    view.lng += 0.002;
    frame();
    expect(count('clearRect')).toBe(2);
    cluster.destroy();
  });
});

describe('出帧预算 · 不能落笔的层不接活', () => {
  it('方格数字层收起期间,改分母、让位表、点名都不画一笔', () => {
    const view = VIEW();
    const { map } = fakeMap(view);
    const cluster = keep(new ClusterLayer(map as unknown as import("./provider/types").Basemap));
    const b = buckets();
    cluster.setData(b.lng, b.lat, b.count, b.gx, b.gy, 0.001, 0.001);
    cluster.setVisible(false);
    const frame = frameOf();

    resetCount('clearRect');
    resetCount('fillText');
    view.lng += 0.01;
    cluster.setReference(300);
    cluster.invalidate();
    cluster.setHotspotDiscs(null);
    frame();
    frame();
    expect(count('clearRect')).toBe(0);
    expect(count('fillText')).toBe(0);

    // 重新展开:收起期间欠下的那些变化正在这一屏等着兑现,一帧都不能少
    // 三桶案量 1/12/240 横向相邻:局部峰值抽稀只是把前两格写淡,三格数字都还在
    cluster.setVisible(true);
    frame();
    expect(count('fillText')).toBe(3);
    cluster.destroy();
  });

  it('聚焦层收到空数据时不建画布;展开后清空那一屏只清一次', () => {
    const view = VIEW();
    const { map } = fakeMap(view);
    const spot = keep(new SpotlightLayer(map as unknown as import("./provider/types").Basemap));
    spot.setData(null);
    // 一屏不画的东西不该换来一张全屏 backing store(多数会话里这一层从来没出现过)
    expect(FakeCustomLayer.created.length).toBe(0);

    spot.setData(spotlightData(4));
    spot.setVisible(true);
    expect(FakeCustomLayer.created.length).toBe(1);
    const frame = frameOf();
    resetCount('clearRect');
    frame();
    frame();
    expect(count('clearRect')).toBe(1);

    spot.setData(null);
    spot.setVisible(false);
    resetCount('clearRect');
    frame();
    expect(count('clearRect')).toBe(0);
    spot.destroy();
  });

  it('定位层:没有标记时连开帧都不必;标记挂着时视图没变的那些帧按 33 毫秒下限走', () => {
    const view = VIEW();
    const { map } = fakeMap(view);
    const pin = keep(new CasePinLayer(map as unknown as import("./provider/types").Basemap));
    pin.invalidate();
    expect(FakeCustomLayer.created.length).toBe(0);

    const clock = vi.spyOn(performance, 'now').mockReturnValue(1000);
    pin.setPin({ lng: view.lng, lat: view.lat, address: '滨河大道 1028 号' });
    expect(FakeCustomLayer.created.length).toBe(1);
    const frame = frameOf();

    resetCount('arc');
    frame();
    const onePaint = count('arc');
    expect(onePaint).toBeGreaterThan(0);
    // 同一拍里再点名一次(高德那条回调和自己那条 rAF 都汇到这里):不该再画
    frame();
    expect(count('arc')).toBe(onePaint);
    // 过了一拍:光圈接着转
    clock.mockReturnValue(1100);
    view.lng += 0.001;
    frame();
    expect(count('arc')).toBeGreaterThan(onePaint);
    pin.setPin(null);
    pin.destroy();
  });
});

describe('出帧预算 · 量字只在第一次', () => {
  it('同一视图里补画的帧一次字都不重量', () => {
    const { map } = fakeMap(VIEW());
    const hot = keep(new HotspotLayer(map as unknown as import("./provider/types").Basemap));
    hot.setData(hotspots());
    const frame = frameOf();
    frame();

    resetCount('measureText');
    hot.invalidate();
    frame();
    hot.setOptions({ active: 1 });
    frame();
    expect(count('measureText')).toBe(0);
    hot.destroy();
  });

  it('缩放来回穿过同一档字号也不再重量(原先那张按缩放清空的宽度表就漏在这条上)', () => {
    const view = VIEW();
    const { map } = fakeMap(view);
    const hot = keep(new HotspotLayer(map as unknown as import("./provider/types").Basemap));
    hot.setData(hotspots());
    const frame = frameOf();

    // z12 / z16 / z18 三档字号不同(盘径随缩放长大,盘心的数也跟着放大一档),先各量一遍
    for (const zoom of [12, 16, 18, 16]) {
      view.zoom = zoom;
      frame();
    }
    expect(count('measureText')).toBeGreaterThan(0);
    resetCount('measureText');
    // 退回用过的档位:底衬半径按「那一串数字 + 第几档字号」存着,一个都不该重新量
    for (const zoom of [18, 16, 12]) {
      view.zoom = zoom;
      frame();
    }
    expect(count('measureText')).toBe(0);
    hot.destroy();
  });

  it('快拖那一拍整层不落笔也不量字;松手补的那一帧数字回来、仍然不重量', () => {
    const view = VIEW();
    const { map } = fakeMap(view);
    const hot = keep(new HotspotLayer(map as unknown as import("./provider/types").Basemap));
    hot.setData(hotspots());
    const frame = frameOf();
    frame();

    setMapGesture(true, true);
    resetCount('measureText');
    resetCount('fillText');
    // 位移取小:快慢由 setMapGesture 直接定档,不必靠像素量。挪太远的话松手补的那一帧
    // 黑点已经出了视野,被裁掉的是盘而不是「数字回来了」,断言就白测。
    view.lng += 0.0005;
    frame();
    expect(count('fillText')).toBe(0);
    expect(count('measureText')).toBe(0);

    setMapGesture(false);
    resetCount('fillText');
    view.zoom = 16;
    frame();
    expect(count('fillText')).toBeGreaterThan(0);
    // 这一帧换了字号,量新那一档是应当的;换过之后再补一帧就不该再量
    resetCount('measureText');
    view.lng += 0.001;
    frame();
    expect(count('measureText')).toBe(0);
    hot.destroy();
  });

  it('方格的分格白线整档设一次参数,不逐格重复赋值', () => {
    const view = VIEW();
    const { map } = fakeMap(view);
    const spot = keep(new SpotlightLayer(map as unknown as import("./provider/types").Basemap));
    spot.setData(spotlightData(30));
    spot.setVisible(true);
    const frame = frameOf();
    frame();
    expect(count('strokeRect')).toBe(30);

    // 假上下文的属性写入次数就是赋值次数:逐格设参数的写法在 30 格上是三十次以上
    let lineWidthWrites = 0;
    let current = 1;
    Object.defineProperty(ctx, 'lineWidth', {
      configurable: true,
      get: () => current,
      set: (v: number) => {
        lineWidthWrites += 1;
        current = v;
      },
    });
    view.lng += 0.001;
    spot.invalidate();
    frame();
    expect(lineWidthWrites).toBeLessThan(6);
    spot.destroy();
  });
});