size.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { computed, type ComputedRef } from "vue";
  2. import { config } from "../config";
  3. /**
  4. * 字号管理类
  5. * 用于处理文本大小的缩放和样式
  6. */
  7. class Size {
  8. // 预设的字号类名
  9. public names = [
  10. "text-xs",
  11. "text-sm",
  12. "text-md",
  13. "text-lg",
  14. "text-xl",
  15. "text-2xl",
  16. "text-3xl",
  17. "text-4xl",
  18. "text-5xl",
  19. "text-6xl",
  20. "text-7xl",
  21. "text-8xl",
  22. "text-9xl"
  23. ];
  24. // 对应的字号大小
  25. public sizes = [12, 14, 16, 18, 20, 24, 30, 36, 48, 60, 72, 96, 128];
  26. // 对应的行高
  27. public lineHeights = [16, 20, 24, 28, 32, 36, 40, 1, 1, 1, 1, 1, 1];
  28. // 原始类名
  29. public className: ComputedRef<string> = computed(() => "");
  30. // 计算后的类名
  31. public ptClassName: ComputedRef<string>;
  32. constructor(cb: (() => string) | null) {
  33. this.className = computed(cb ?? (() => ""));
  34. // 根据全局字号配置动态计算类名
  35. this.ptClassName = computed(() => {
  36. if (config.fontSize == null) {
  37. return this.className.value;
  38. }
  39. const name = this.names[this.getIndex()];
  40. return this.className.value.replace(`-important-${name}`, "").replace(name, "");
  41. });
  42. }
  43. /**
  44. * 获取全局字号缩放比例
  45. */
  46. getScale = () => {
  47. return config.fontSize ?? 1;
  48. };
  49. /**
  50. * 根据缩放比例计算值
  51. * @param val - 需要转换的值
  52. * @returns 转换后的值
  53. */
  54. toScale = (val: number) => {
  55. return this.getScale() * val;
  56. };
  57. /**
  58. * 获取当前字号在预设中的索引
  59. */
  60. getIndex = () => {
  61. let index = this.names.findIndex((name) => {
  62. if (this.className.value.includes(name)) {
  63. return true;
  64. }
  65. return false;
  66. });
  67. if (index < 0) {
  68. index = 1;
  69. }
  70. return index;
  71. };
  72. }
  73. /**
  74. * 字号管理Hook
  75. * @param className - 类名
  76. */
  77. export function useSize(cb: (() => string) | null = null): Size {
  78. return new Size(cb);
  79. }