plate.ts 3.91 KB
import { ellipsizeBy } from './text';

/**
 * 圆角牌子:底衬 + 一行居中的字。
 *
 * 为什么内核要带这一块:聚合数字、黑点排名牌、定位标记的地址牌、聚焦展示的档位牌共用同一种长相,
 * 原先这几处在三个文件里各写了一份圆角路径、两份截断,而「同一个位置只有一种长相」正是这类界面
 * 一直在守的东西 —— 少一处各写一遍,就多一处「同屏出现两种牌子」的口子。
 *
 * 尺寸与文字(`fitPlate`)和落笔(`drawPlate`)分两步:一次截断要逐字量一遍,
 * 而字宽只由「字体 + 文字本身」决定,跟缩放、屏幕都无关,所以能在喂数据时算完就不该在帧里算。
 */

/** 量字。用专门的量字画布(见 frame.ts 的 textWidth),别用正在画的这块 */
export type TextMeasurer = (font: string, text: string) => number;

/** 一块牌子的文字与外框:算一次,沿用到底 */
export interface PlateLayout {
  text: string;
  w: number;
}

/** 牌子的长相。颜色都是画布上真实存在的 CSS 色串,不在这里解析 hex */
export interface PlateStyle {
  font: string;
  /** 底衬色 */
  fill: string;
  /** 描边色。不给就不描 */
  stroke?: string;
  lineWidth?: number;
  /** 字色 */
  ink: string;
  /** 牌子高(CSS 像素) */
  height: number;
  /** 圆角半径 */
  radius?: number;
}

/**
 * 圆角矩形路径。调用方自己 fill / stroke,所以这里只建路径、不落笔。
 *
 * 用 arcTo 而不是 ctx.roundRect:后者在部分浏览器/WebView 上还没有,
 * 自绘层拿不到报错、只会看到牌子变成直角,那种差异没人会去查。
 */
export function roundRectPath(
  ctx: CanvasRenderingContext2D,
  x: number,
  y: number,
  w: number,
  h: number,
  r: number,
): void {
  const rr = Math.min(r, w / 2, h / 2);
  ctx.beginPath();
  ctx.moveTo(x + rr, y);
  ctx.arcTo(x + w, y, x + w, y + h, rr);
  ctx.arcTo(x + w, y + h, x, y + h, rr);
  ctx.arcTo(x, y + h, x, y, rr);
  ctx.arcTo(x, y, x + w, y, rr);
  ctx.closePath();
}

/**
 * 算出这块牌子上那一行字与它的宽度。
 *
 * `maxTextW` 是文字宽度上限:超出就截断加省略号。上限同时也按画布宽度收过再传进来 ——
 * 小窗口里牌子不该横穿整屏。
 */
export function fitPlate(
  measure: TextMeasurer,
  text: string,
  maxTextW: number,
  font: string,
  padX: number,
): PlateLayout {
  const shown = ellipsizeBy((t) => measure(font, t), text, maxTextW);
  return { text: shown, w: Math.min(maxTextW + padX * 2, measure(font, shown) + padX * 2) };
}

/**
 * 落一块牌子:按中心点摆,贴屏幕边时整块收进来。
 *
 * 不收的话用户会看到「有个标记但牌子跑出去了」;收完要把真正占住的那块报回去,
 * 局部擦除的范围才按得上(照理论位置取会擦不干净,留下一条边)。
 *
 * @param bounds 画布的 CSS 尺寸。给了才做贴边收拢
 * @param inset 离画布边缘的最小间距,默认 4
 */
export function drawPlate(
  ctx: CanvasRenderingContext2D,
  plate: PlateLayout,
  cx: number,
  cy: number,
  style: PlateStyle,
  bounds?: { width: number; height: number },
  inset = 4,
): { left: number; top: number; w: number; h: number } {
  const w = plate.w;
  const h = style.height;
  let left = cx - w / 2;
  let top = cy - h / 2;
  if (bounds) {
    left = Math.max(inset, Math.min(left, bounds.width - w - inset));
    top = Math.max(inset, Math.min(top, bounds.height - h - inset));
  }

  roundRectPath(ctx, left, top, w, h, style.radius ?? 5);
  ctx.fillStyle = style.fill;
  ctx.fill();
  if (style.stroke) {
    ctx.lineWidth = style.lineWidth ?? 1;
    ctx.strokeStyle = style.stroke;
    ctx.stroke();
  }

  ctx.font = style.font;
  ctx.fillStyle = style.ink;
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText(plate.text, left + w / 2, top + h / 2 + 0.5);
  return { left, top, w, h };
}