index.ts 1.72 KB
import path from 'path-browserify'

export function resolveRoutePath(basePath: string, routePath?: string) {
  return basePath ? path.resolve(basePath, routePath ?? '') : routePath ?? ''
}

/** 计算表格列宽 */
export const calcColumnWidth = (data, title, dataFont, titleFont, otherWidth = 0) => {
  let titleW = measureTextWidth(title, titleFont || dataFont);
  if (!data.length) {
    if (titleW + otherWidth > 260) {
      return 260;
    }
    if (titleW + otherWidth + 32 < 96) {
      return 96;
    }
    return titleW + 32 + otherWidth;//20边距,+2px边框 + 10px间隙
  }
  let maxWidth = 0;
  for (const d of data) {
    let w = measureTextWidth(d, dataFont);
    if (maxWidth < w) {
      maxWidth = w;
    }
    if (maxWidth > 330) {
      break;
    }
  }
  if (maxWidth > 330) {
    return 360;
  }
  if (titleW + otherWidth > maxWidth) {
    maxWidth = titleW + otherWidth;
  }
  if (maxWidth + 32 < 96) {
    return 96;
  }
  return maxWidth + 32;
}

const getOffscreenCanvas = function (): HTMLCanvasElement {
  let canvas = document.getElementById('canvas');
  if (canvas) {
    return <HTMLCanvasElement>canvas;
  }
  canvas = document.createElement('canvas');
  canvas.id = "canvas";
  canvas.style.display = 'none';
  document.body.appendChild(canvas);
  return <HTMLCanvasElement>canvas;
};

export const measureTextWidth = (text, font): number => {
  if (!text) { text = ''; }
  if (!font) {
    return 0;
  }
  let ctx = getOffscreenCanvas().getContext('2d');
  if (!ctx) {
    return 0;
  }
  let fontSize = font.fontSize, fontFamily = font.fontFamily, fontWeight = font.fontWeight;
  ctx.font = [fontWeight, "".concat(fontSize, "px"), fontFamily]
    .join(' ')
    .trim();
  return ctx.measureText("".concat(text)).width;
}