上文(#12.1 VChart 插件机制 )介绍了VChart中插件的基本使用,这一节我将深入源码重点探索各类插件的实现逻辑;
相关源码位置
-
packages/vchart/src/plugin/chart/formatter/:格式化插件的核心实现 -
packages/vchart/src/plugin/chart/media-query/:媒体查询插件的核心实现
格式化插件
数值文本格式化
protected _formatSingleText(text: string | number, formatter: string): string | number { const isNumeric = numberSpecifierReg.test(formatter); if (isNumeric && this._numericFormatter) { // 内置的 formatter 逻辑,可以进行缓存性能优化 let numericFormat; if (this._numericFormatterCache && this._numericSpecifier) { if (this._numericFormatterCache.get(formatter)) { numericFormat = this._numericFormatterCache.get(formatter); } else { numericFormat = this._numericSpecifier(formatter) as any; this._numericFormatterCache.set(formatter, numericFormat); } return numericFormat(Number(text)); } return this._numericFormatter(formatter, Number(text)); } else if (formatter.includes('%') && this._timeFormatter) { return this._timeFormatter(formatter, text); } return text; }
时间文本格式化
VChart对于时间格式的转换在
private readonly _timeModeFormat = { utc: TimeUtil.getInstance().timeUTCFormat, local: TimeUtil.getInstance().timeFormat }; // 在 onInit 中设置时间格式化器 onInit(service: IChartPluginService, chartSpec: any) { const { timeMode, timeFormatter } = this._spec; if (isFunction(timeFormatter)) { // 使用自定义时间格式化函数 this._timeFormatter = timeFormatter; } else if (timeMode && this._timeModeFormat[timeMode]) { // 使用内置的 UTC 或本地时间格式化 this._timeFormatter = this._timeModeFormat[timeMode]; } } // 在 _formatSingleText 中处理时间格式化 protected _formatSingleText(text: string | number, formatter: string): string | number { // 数值格式化逻辑... // 时间格式化逻辑 else if (formatter.includes('%') && this._timeFormatter) { return this._timeFormatter(formatter, text); } return text; }
数据变量替换
- 模板解析:
-
使用正则表达式
/\{([^}]+)\}/g匹配大括号模板 -
支持嵌套格式定义(如
{field:format})
- 字段提取:
- 通过冒号分割字段名和格式说明(
field:format)
- 动态替换: