ScopeLayer.ts 14.8 KB
import { fitPlate, mercY, roundRectPath, textWidth, type Overlay, type PaintEnv } from '@hm/map-overlay';
import { MAP_LABEL_FONT, PALETTE, paletteHexToRgb, rgbCss } from './palette';
import { defineAppOverlay } from './appOverlay';
import { fmtInt } from '@/utils/format';
import type { Basemap } from './provider/types';

/**
 * 收窄标识层:把「屏上这会儿只画哪一片」写在地图上。
 *
 * 为什么需要它 —— 高频街道 / 高频道路点「在地图上查看」之后,屏上是这一类的热力图与聚合点,
 * 而热力斑不带名字。区还有区界可认,街道与道路没有任何底图要素可以对照
 * (高德的区划接口只到区一级,官方文档写明街道级别不给边界 polyline),
 * 一条道路的案件沿路铺开,看上去就是一片散开的暖色,读的人分不清是深南大道还是滨海大道。
 *
 * 所以这一层只做两件事,都是**地图该说的话**:
 *   1. 一圈虚线框住这一类的实际范围(这批点的外包框),边界可见;
 *   2. 收窄到多个成员时,逐个在自己那块地方标一行小字(`深南大道 812`)——
 *      六条路并成一个框,框只能说明「在这片城市里」,说不出「哪一段是哪条」。
 * 左上角一块名牌念这一刀的名字与起数(`高频道路 · 深南大道、滨海大道 等 6 条 · 3,210 起`)。
 *
 * ⚠️ 「取消收窄」不在这里 —— 右上角那颗「只看 · …」胶囊已经带了清单与 ✕
 * (见 MapStage 的 ToolbarReadouts)。同一句话、同一个动作在一屏上出现两遍,
 * 就是上一轮刚被点过名的「重复冗余」。地图只负责「在哪儿」,不重复「是什么状态」。
 *
 * 颜色只用品牌主色、且半透明:它是一句说明,不该和热力、黑点抢注意力。
 * 名牌与定位标记的信息板同一套长相(白底半透明 + 圆角 + 细描边),
 * 两者同时在场时不会像两种控件。
 *
 * 只在**地理类**收窄(区 / 街道 / 道路 / 反复出险位置)时出现;按营运或车辆属性收窄
 * 不画框 —— 那一刀不是一块地方,画框反而是误导(判据见 MapStage 的 isGeoScope)。
 */

/** 框线的虚线节奏与留白(CSS 像素) */
const FRAME_DASH = [7, 5];
const FRAME_RADIUS = 10;
/** 名牌与框左上角的间距;没有框时退到画布左上角这一档 */
const PLATE_OFFSET = 6;
const PLATE_INSET = 14;
const PLATE_H = 24;
const PLATE_PAD_X = 8;
const PLATE_BAR_W = 3;
const PLATE_GAP = 7;
/** 名牌文字上限(再长就截断加省略号):它只是「这一片叫什么」,完整说法在面板那一行 */
const PLATE_TEXT_MAX = 260;
const PLATE_FONT = `500 11px ${MAP_LABEL_FONT}`;
const PLATE_FONT_NUM = `400 11px ${MAP_LABEL_FONT}`;
const PLATE_FILL = 'rgba(255, 255, 255, 0.88)';
const PLATE_MUTED = 'rgba(34, 43, 95, 0.62)';

/** 成员小签:比名牌更轻一档,只标「这一段是哪个」 */
const CHIP_H = 19;
const CHIP_PAD_X = 6;
const CHIP_GAP = 5;
const CHIP_FONT = `600 10.5px ${MAP_LABEL_FONT}`;
const CHIP_FONT_NUM = `400 10.5px ${MAP_LABEL_FONT}`;
const CHIP_FILL = 'rgba(255, 255, 255, 0.82)';
/** 两个签之间至少留这么多像素,否则宁可不画(叠在一起的字比不标更糟) */
const CHIP_CLEAR = 4;

const PRIMARY = paletteHexToRgb(PALETTE.primary);
const PRIMARY_SOFT = paletteHexToRgb(PALETTE.primarySoft);

/** 一个成员(一条街道 / 一条道路)的框与名字 */
export interface ScopeMemberMark {
  name: string;
  count: number;
  minLng: number;
  minLat: number;
  maxLng: number;
  maxLat: number;
}

/** 屏上这一刻的收窄标识 */
export interface ScopeMark {
  /** 念什么:直接取 mapScope.label(入口那边已经把地名写进去了) */
  label: string;
  /** 这一刀收窄的起数;还在路上时给 null,名牌只念名字 */
  count: number | null;
  /** 这一类的实际外包框;null 表示还没算出来(此时整层不出现,免得只有一块牌子悬在半空) */
  extent: { minLng: number; minLat: number; maxLng: number; maxLat: number } | null;
  /**
   * 这一刀的范围已经大到「框住整座城」了 —— 那就别画框。
   *
   * 前 6 条道路并起来往往就是全市:给整座城套一圈虚线,画的不是信息,是一句废话,
   * 还把底图围了一圈杂音。这种时候只留名牌与逐条的小签(它们才说出了「哪条在哪儿」)。
   */
  frameless?: boolean;
  /** 逐成员(街道 / 道路)的框;只有一个成员时不必给,名牌已经念了名字 */
  members?: ScopeMemberMark[];
}

/** 名牌算好的布局:一次量字,帧里只落笔 */
interface PlateLayout {
  w: number;
  text: string;
  count: string;
}

/** 成员小签算好的布局:墨卡托纬度在喂数据时算好,帧里只剩乘加 */
interface ChipLayout {
  text: string;
  count: string;
  nameW: number;
  countW: number;
  w: number;
  minLng: number;
  maxLng: number;
  myTop: number;
  myBottom: number;
}

export class ScopeLayer {
  private overlay: Overlay | null = null;
  private mark: ScopeMark | null = null;
  /** 已经换算好的墨卡托纬度:每帧两次乘加就够,不必再碰底图 */
  private myTop = 0;
  private myBottom = 0;
  private layout: PlateLayout | null = null;
  private chips: ChipLayout[] = [];

  constructor(private readonly map: Basemap) {}

  private ensure() {
    if (this.overlay) return;
    this.overlay = defineAppOverlay(this.map, {
      runtime: this.map.overlayRuntime,
      id: 'scope',
      name: 'ScopeLayer · 收窄标识层',
      // 高于黑点(140)、低于定位标记(150):它说的是「屏上这一片是哪一片」,
      // 该压住底下的热力与轮廓,但不该盖住用户正在找的那一个点
      zIndex: 145,
      zooms: [3, 20],
      extras: () => ({
        built: this.overlay !== null,
        visible: this.mark !== null,
        note: this.mark
          ? `收窄标识:${this.mark.label}${this.chips.length ? ` · 逐个标注 ${this.chips.length} 处` : ''}`
          : '无收窄:不占画布',
      }),
      canPaint: () => this.mark !== null && this.mark.extent !== null,
      paint: (env) => this.paint(env),
    });
  }

  /**
   * 传 null 即撤掉标识(取消收窄、离开页签、或换成一个非地理的收窄)。
   *
   * 这里没有「点牌子取消收窄」的命中判定:取消那颗按钮在右上角的「只看 · …」胶囊上
   * (ToolbarReadouts),同一屏不做第二份。
   */
  setScope(mark: ScopeMark | null) {
    if (!mark || !mark.extent) {
      if (!this.mark) return;
      this.mark = null;
      this.layout = null;
      this.chips = [];
      // 没建过就不必做什么:一屏没有标识的画布不该换来一次全屏清空
      this.overlay?.setTotal(0);
      this.overlay?.release();
      return;
    }
    this.ensure();
    this.mark = mark;
    this.myTop = mercY(mark.extent.maxLat);
    this.myBottom = mercY(mark.extent.minLat);
    this.layout = this.buildPlate(mark);
    this.chips = this.buildChips(mark);
    this.overlay?.setTotal(1);
    this.overlay?.invalidate();
  }

  /** 视图或数据变了:交给内核合并到下一帧(这一层自己不跑 rAF) */
  invalidate() {
    this.overlay?.invalidate();
  }

  destroy() {
    this.mark = null;
    this.layout = null;
    this.chips = [];
    this.overlay?.destroy();
    this.overlay = null;
  }

  /**
   * 名牌的内容与宽度。
   *
   * 牌子上的字只由「收窄说法 + 起数」决定,与地图无关 —— 与定位标记的信息板同一条预算纪律:
   * 一次量字,之后每帧只落笔。测不出字宽(无 canvas 的环境)时按每字 11px 估,
   * 估出来的宽度只会偏大一点,不会让牌子截断出错。
   */
  private buildPlate(mark: ScopeMark): PlateLayout {
    const measure = (font: string, text: string) => textWidth(font, text) ?? text.length * 11;
    const fitted = fitPlate(measure, mark.label, PLATE_TEXT_MAX, PLATE_FONT, 0);
    const count = mark.count === null ? '' : `${fmtInt(mark.count)} 起`;
    const countW = count ? measure(PLATE_FONT_NUM, count) : 0;
    const w =
      PLATE_PAD_X * 2 + PLATE_BAR_W + PLATE_GAP + fitted.w + (count ? PLATE_GAP + countW : 0);
    return { w: Math.ceil(w), text: fitted.text, count };
  }

  /**
   * 成员小签的布局。
   *
   * 只在「两个以上成员」时做:一个成员时外包框就是它自己,名牌已经念了名字,
   * 再叠一个小签只是把同一句话说两遍。
   */
  private buildChips(mark: ScopeMark): ChipLayout[] {
    const members = mark.members ?? [];
    if (members.length < 2) return [];
    const measure = (font: string, text: string) => textWidth(font, text) ?? text.length * 10;
    const out: ChipLayout[] = [];
    for (const m of members) {
      const text = m.name;
      const count = `${fmtInt(m.count)}`;
      const nameW = measure(CHIP_FONT, text);
      const countW = measure(CHIP_FONT_NUM, count);
      out.push({
        text,
        count,
        nameW,
        countW,
        w: Math.ceil(CHIP_PAD_X * 2 + nameW + CHIP_GAP + countW),
        minLng: m.minLng,
        maxLng: m.maxLng,
        myTop: mercY(m.maxLat),
        myBottom: mercY(m.minLat),
      });
    }
    return out;
  }

  private paint(env: PaintEnv): number {
    const { ctx, frame, width: w, height: h } = env;
    const mark = this.mark;
    const layout = this.layout;
    if (!mark || !mark.extent || !layout) return 0;

    const x0 = frame.x(mark.extent.minLng);
    const x1 = frame.x(mark.extent.maxLng);
    const y0 = frame.y(this.myTop);
    const y1 = frame.y(this.myBottom);

    // 范围已经大到「框住整座城」时不画框(见 ScopeMark.frameless):
    // 名牌这时落在画布左上角,与工具条(右上)分处两端,不打架。
    if (!mark.frameless) {
      // 整片跑到屏幕外就一笔不落(用户把地图拖走了,右上角那颗「只看 · …」胶囊仍在说这一刀是什么)
      const off = 4;
      if (x1 < -off || x0 > w + off || y1 < -off || y0 > h + off) return 0;
      // 品牌主色细虚线,圆角比直角柔和 —— 它标的是「大致这一片」,不是行政边界,
      // 直角会读成一条确切的界线。填充只给一点点,让框内的热力仍然是主角。
      ctx.save();
      ctx.setLineDash(FRAME_DASH);
      ctx.lineWidth = 1.2;
      ctx.strokeStyle = rgbCss(PRIMARY, 0.55);
      ctx.fillStyle = rgbCss(PRIMARY, 0.035);
      roundRectPath(ctx, x0, y0, Math.max(2, x1 - x0), Math.max(2, y1 - y0), FRAME_RADIUS);
      ctx.fill();
      ctx.stroke();
      ctx.restore();
    }

    // 名牌贴在框的左上角;框跑到屏外那一侧时把牌子收进屏内 —— 位置怎么变都还认得出
    // 「说的是这一片」(它始终贴着框的这一角,不会飘到屏幕另一头)。
    const anchorX = mark.frameless ? PLATE_INSET : x0 + PLATE_OFFSET;
    const anchorY = mark.frameless ? PLATE_INSET : y0 + PLATE_OFFSET;
    const plateLeft = clamp(anchorX, 6, Math.max(6, w - layout.w - 6));
    const plateTop = clamp(anchorY, 6, Math.max(6, h - PLATE_H - 6));

    // 2) 成员小签:各自落在自己那块地方的上沿。与新牌子、与已放下的小签重叠的一律不画 ——
    //    六个签挤在市中心时有三个读不出来,那三个不如不画(框还在,仍看得出范围)。
    const taken: Rect[] = [
      { x: plateLeft - CHIP_CLEAR, y: plateTop - CHIP_CLEAR, w: layout.w + CHIP_CLEAR * 2, h: PLATE_H + CHIP_CLEAR * 2 },
    ];
    for (const chip of this.chips) {
      const cx = frame.x((chip.minLng + chip.maxLng) / 2);
      const yTop = frame.y(chip.myTop);
      const yBottom = frame.y(chip.myBottom);
      // 锚在成员框的中线稍上,而不是框的正上方:一条路是斜着走的、框往往又高又窄,
      // 挂在上沿时那行字离这条路本身常常隔着一大截,读起来像在标别的地方。
      // 框太矮(一个街道就那么一小块)时才压到上沿内侧,避免盖住整块。
      const top = Math.max((yTop + yBottom) / 2 - CHIP_H - 4, yTop + 2);
      const left = cx - chip.w / 2;
      const rect: Rect = { x: left, y: top, w: chip.w, h: CHIP_H };
      if (rect.x < 2 || rect.x + rect.w > w - 2 || rect.y < 2 || rect.y + rect.h > h - 2) continue;
      if (taken.some((t) => overlaps(t, rect, CHIP_CLEAR))) continue;
      taken.push(rect);
      this.drawChip(ctx, chip, rect);
    }

    // 3) 名牌画在最后:它是这一层的「主句」,任何小签都不该压住它
    this.drawPlate(ctx, layout, plateLeft, plateTop);
    return 1;
  }

  private drawChip(ctx: CanvasRenderingContext2D, chip: ChipLayout, rect: Rect) {
    ctx.fillStyle = CHIP_FILL;
    ctx.strokeStyle = rgbCss(PRIMARY_SOFT, 0.75);
    ctx.lineWidth = 1;
    roundRectPath(ctx, rect.x, rect.y, rect.w, rect.h, 3);
    ctx.fill();
    ctx.stroke();

    ctx.textBaseline = 'middle';
    ctx.textAlign = 'left';
    const cy = rect.y + rect.h / 2;
    let tx = rect.x + CHIP_PAD_X;
    ctx.font = CHIP_FONT;
    ctx.fillStyle = PALETTE.primaryDeep;
    ctx.fillText(chip.text, tx, cy);
    tx += chip.nameW + CHIP_GAP;
    ctx.font = CHIP_FONT_NUM;
    ctx.fillStyle = PLATE_MUTED;
    ctx.fillText(chip.count, tx, cy);
  }

  private drawPlate(ctx: CanvasRenderingContext2D, layout: PlateLayout, left: number, top: number) {
    ctx.save();
    // 板底:与定位标记的信息板同一套(半透明白 + 细描边 + 一层很轻的投影)
    ctx.shadowColor = 'rgba(34, 43, 95, 0.16)';
    ctx.shadowBlur = 8;
    ctx.shadowOffsetY = 2;
    ctx.fillStyle = PLATE_FILL;
    roundRectPath(ctx, left, top, layout.w, PLATE_H, 5);
    ctx.fill();
    ctx.restore();

    ctx.strokeStyle = rgbCss(PRIMARY_SOFT, 0.9);
    ctx.lineWidth = 1;
    roundRectPath(ctx, left, top, layout.w, PLATE_H, 5);
    ctx.stroke();

    // 左缘一道主色竖条:说明「这是一条关于当前视角的注记」,同时也把牌子与热力的暖色分开
    ctx.fillStyle = rgbCss(PRIMARY, 0.9);
    ctx.fillRect(left + PLATE_PAD_X, top + 6, PLATE_BAR_W, PLATE_H - 12);

    ctx.textBaseline = 'middle';
    ctx.textAlign = 'left';
    const cy = top + PLATE_H / 2;
    let tx = left + PLATE_PAD_X + PLATE_BAR_W + PLATE_GAP;
    ctx.font = PLATE_FONT;
    ctx.fillStyle = PALETTE.primaryDeep;
    ctx.fillText(layout.text, tx, cy);
    tx += ctx.measureText(layout.text).width;

    if (layout.count) {
      ctx.font = PLATE_FONT_NUM;
      ctx.fillStyle = PLATE_MUTED;
      tx += PLATE_GAP;
      ctx.fillText(layout.count, tx, cy);
    }
  }
}

interface Rect {
  x: number;
  y: number;
  w: number;
  h: number;
}

function overlaps(a: Rect, b: Rect, gap: number): boolean {
  return !(
    b.x > a.x + a.w + gap ||
    b.x + b.w + gap < a.x ||
    b.y > a.y + a.h + gap ||
    b.y + b.h + gap < a.y
  );
}

function clamp(v: number, lo: number, hi: number): number {
  return v < lo ? lo : v > hi ? hi : v;
}