chore: replace all cn comments of fe to en version by volc api (#320)

This commit is contained in:
tecvan
2025-07-31 10:32:15 +08:00
committed by GitHub
parent 716ec0cba8
commit 71f6245a01
2960 changed files with 15545 additions and 15545 deletions

View File

@@ -19,13 +19,13 @@ import { renderHook } from '@testing-library/react';
import { useReportTti } from '../src/index';
// 模拟 custom-perf-metric 模块
// Simulate custom-perf-metric module
vi.mock('../src/utils/custom-perf-metric', () => ({
reportTti: vi.fn(),
REPORT_TTI_DEFAULT_SCENE: 'init',
}));
// 导入被模拟的函数,以便在测试中访问
// Import mocked functions for access in tests
import { reportTti } from '../src/utils/custom-perf-metric';
describe('useReportTti', () => {

View File

@@ -20,7 +20,7 @@ import { reporter } from '@coze-arch/logger';
const mockSlardarInstance = vi.fn();
mockSlardarInstance.config = vi.fn();
// 模拟 logger reporter
// Analog loggers and reporters
vi.mock('@coze-arch/logger', () => ({
logger: {
info: vi.fn(),
@@ -32,18 +32,18 @@ vi.mock('@coze-arch/logger', () => ({
}));
describe('custom-perf-metric', () => {
// 保存原始的全局对象
// Save the original global object
const originalPerformance = global.performance;
const originalDocument = global.document;
const originalPerformanceObserver = global.PerformanceObserver;
// 模拟函数
// simulation function
const mockObserve = vi.fn();
const mockDisconnect = vi.fn();
const mockGetEntriesByName = vi.fn();
const mockPerformanceNow = vi.fn().mockReturnValue(1000);
// 模拟路由变更条目
// simulated route change entry
const mockRouteChangeEntry = {
startTime: 500,
detail: {
@@ -53,12 +53,12 @@ describe('custom-perf-metric', () => {
},
};
// 确保数组有 at 方法
// Make sure the array has at method
if (!Array.prototype.at) {
// 添加 at 方法的 polyfill
// Add at method polyfill
Object.defineProperty(Array.prototype, 'at', {
value(index) {
// 将负索引转换为从数组末尾开始的索引
// Converts a negative index to an index starting at the end of the array
return this[index < 0 ? this.length + index : index];
},
writable: true,
@@ -70,13 +70,13 @@ describe('custom-perf-metric', () => {
vi.clearAllMocks();
vi.resetModules();
// 模拟 performance 对象
// Simulated performance object
vi.stubGlobal('performance', {
now: mockPerformanceNow,
getEntriesByName: mockGetEntriesByName,
});
// 默认模拟 getEntriesByName 返回值
// Default simulated getEntriesByName return value
mockGetEntriesByName.mockImplementation(name => {
if (name === 'route_change') {
return [mockRouteChangeEntry];
@@ -91,18 +91,18 @@ describe('custom-perf-metric', () => {
return [];
});
// 模拟 document 对象
// Mock document object
global.document = {
visibilityState: 'visible',
} as any;
// 模拟 PerformanceObserver
// Analog PerformanceObserver
global.PerformanceObserver = vi.fn().mockImplementation(callback => ({
observe: mockObserve,
disconnect: mockDisconnect,
})) as any;
// 添加 supportedEntryTypes 属性
// Add the supportedEntryTypes property
Object.defineProperty(global.PerformanceObserver, 'supportedEntryTypes', {
value: ['paint'],
configurable: true,
@@ -110,7 +110,7 @@ describe('custom-perf-metric', () => {
});
afterEach(() => {
// 恢复原始对象
// Restore original object
global.performance = originalPerformance;
global.document = originalDocument;
global.PerformanceObserver = originalPerformanceObserver;
@@ -132,10 +132,10 @@ describe('custom-perf-metric', () => {
'../../src/utils/custom-perf-metric',
);
// 执行
// execute
reportTti({ key: 'value' });
// 验证
// verify
expect(mockSlardarInstance).toHaveBeenCalledWith('sendCustomPerfMetric', {
value: 1000,
name: PerfMetricNames.TTI,
@@ -152,16 +152,16 @@ describe('custom-perf-metric', () => {
'../../src/utils/custom-perf-metric',
);
// 修改 document.visibilityState
// Modify document visibilityState
Object.defineProperty(global.document, 'visibilityState', {
value: 'hidden',
configurable: true,
});
// 执行
// execute
reportTti();
// 验证
// verify
expect(mockSlardarInstance).not.toHaveBeenCalled();
});
@@ -170,16 +170,16 @@ describe('custom-perf-metric', () => {
'../../src/utils/custom-perf-metric',
);
// 第一次调用
// first call
reportTti({}, 'test-scene');
// 清除模拟
// Clear simulation
vi.clearAllMocks();
// 第二次调用同一路由和场景
// Second call to the same route and scenario
reportTti({}, 'test-scene');
// 验证
// verify
expect(mockSlardarInstance).not.toHaveBeenCalled();
});
@@ -188,7 +188,7 @@ describe('custom-perf-metric', () => {
'../../src/utils/custom-perf-metric',
);
// 修改 getEntriesByName 返回多个路由变更
// Modify getEntriesByName to return multiple route changes
mockGetEntriesByName.mockImplementation(name => {
if (name === 'route_change') {
const entries = [
@@ -210,7 +210,7 @@ describe('custom-perf-metric', () => {
},
];
// 确保数组有 at 方法
// Make sure the array has at method
if (!entries.at) {
entries.at = function (index) {
return this[index < 0 ? this.length + index : index];
@@ -222,10 +222,10 @@ describe('custom-perf-metric', () => {
return [];
});
// 执行
// execute
reportTti({ key: 'value' });
// 验证
// verify
expect(mockSlardarInstance).toHaveBeenCalledWith('sendCustomPerfMetric', {
value: 500, // 1000 - 500 = 500
name: PerfMetricNames.TTI_HOT,
@@ -241,15 +241,15 @@ describe('custom-perf-metric', () => {
'../../src/utils/custom-perf-metric',
);
// 修改 performance.now 返回值
// Modify performance.now return value
mockPerformanceNow.mockReturnValue(700);
// 执行
// execute
reportTti();
// 验证
// verify
expect(mockSlardarInstance).toHaveBeenCalledWith('sendCustomPerfMetric', {
value: 800, // 使用 FCP 时间
value: 800, // Use FCP time
name: PerfMetricNames.TTI,
type: 'perf',
extra: {
@@ -263,19 +263,19 @@ describe('custom-perf-metric', () => {
'../../src/utils/custom-perf-metric',
);
// 修改 getEntriesByName 不返回 FCP
// Modify getEntriesByName to not return FCP
mockGetEntriesByName.mockImplementation(name => {
if (name === 'route_change') {
return [mockRouteChangeEntry];
}
// 返回空数组表示没有 FCP
// Returning an empty array indicates that there is no FCP.
return [];
});
// 执行
// execute
reportTti();
// 验证
// verify
expect(mockObserve).toHaveBeenCalledWith({ type: 'paint', buffered: true });
expect(mockSlardarInstance).not.toHaveBeenCalled();
});
@@ -285,7 +285,7 @@ describe('custom-perf-metric', () => {
'../../src/utils/custom-perf-metric',
);
// 修改 getEntriesByName 不返回 FCP
// Modify getEntriesByName to not return FCP
mockGetEntriesByName.mockImplementation(name => {
if (name === 'route_change') {
return [mockRouteChangeEntry];
@@ -293,7 +293,7 @@ describe('custom-perf-metric', () => {
return [];
});
// 准备模拟 PerformanceObserver 回调
// Prepare to simulate the PerformanceObserver callback
let observerCallback: Function | undefined;
global.PerformanceObserver = vi.fn().mockImplementation(callback => {
observerCallback = callback;
@@ -303,23 +303,23 @@ describe('custom-perf-metric', () => {
};
}) as any;
// 执行
// execute
reportTti({ key: 'value' });
// 模拟 PerformanceObserver 回调
// Simulate PerformanceObserver callbacks
const mockList = {
getEntriesByName: vi.fn().mockReturnValue([{ startTime: 900 }]),
};
// 确保 observerCallback 已被赋值
// Make sure observerCallback has been assigned a value
expect(observerCallback).toBeDefined();
// 执行回调
// execute callback
if (observerCallback) {
observerCallback(mockList);
}
// 验证
// verify
expect(mockSlardarInstance).toHaveBeenCalledWith('sendCustomPerfMetric', {
value: 900,
name: PerfMetricNames.TTI,
@@ -337,7 +337,7 @@ describe('custom-perf-metric', () => {
'../../src/utils/custom-perf-metric',
);
// 修改 getEntriesByName 不返回 FCP
// Modify getEntriesByName to not return FCP
mockGetEntriesByName.mockImplementation(name => {
if (name === 'route_change') {
return [mockRouteChangeEntry];
@@ -345,15 +345,15 @@ describe('custom-perf-metric', () => {
return [];
});
// 模拟 observe 抛出错误
// Simulate observe throw error
mockObserve.mockImplementationOnce(() => {
throw new Error('Failed to execute observe');
});
// 执行
// execute
reportTti();
// 验证
// verify
expect(mockObserve).toHaveBeenCalledTimes(2);
expect(mockObserve).toHaveBeenNthCalledWith(1, {
type: 'paint',
@@ -371,7 +371,7 @@ describe('custom-perf-metric', () => {
'../../src/utils/custom-perf-metric',
);
// 修改 getEntriesByName 不返回 FCP
// Modify getEntriesByName to not return FCP
mockGetEntriesByName.mockImplementation(name => {
if (name === 'route_change') {
return [mockRouteChangeEntry];
@@ -379,21 +379,21 @@ describe('custom-perf-metric', () => {
return [];
});
// 模拟 observe 抛出错误
// Simulate observe throw error
mockObserve.mockImplementationOnce(() => {
throw new Error('Failed to execute observe');
});
// 移除 supportedEntryTypes
// Remove supportedEntryTypes
Object.defineProperty(global.PerformanceObserver, 'supportedEntryTypes', {
value: [],
configurable: true,
});
// 执行
// execute
reportTti();
// 验证
// verify
expect(mockObserve).toHaveBeenCalledTimes(1);
expect(reporter.info).toHaveBeenCalledWith({
message: 'Failed to execute observe',
@@ -406,7 +406,7 @@ describe('custom-perf-metric', () => {
'../../src/utils/custom-perf-metric',
);
// 修改 getEntriesByName 不返回 FCP
// Modify getEntriesByName to not return FCP
mockGetEntriesByName.mockImplementation(name => {
if (name === 'route_change') {
return [mockRouteChangeEntry];
@@ -414,7 +414,7 @@ describe('custom-perf-metric', () => {
return [];
});
// 模拟 observe 抛出错误
// Simulate observe throw error
mockObserve
.mockImplementationOnce(() => {
throw new Error('First error');
@@ -423,10 +423,10 @@ describe('custom-perf-metric', () => {
throw new Error('Second error');
});
// 执行
// execute
reportTti();
// 验证
// verify
expect(mockObserve).toHaveBeenCalledTimes(2);
expect(reporter.info).toHaveBeenCalledTimes(2);
expect(reporter.info).toHaveBeenNthCalledWith(1, {
@@ -444,7 +444,7 @@ describe('custom-perf-metric', () => {
'../../src/utils/custom-perf-metric',
);
// 修改 getEntriesByName 返回多个路由变更但最后一个没有startTime
// Modify getEntriesByName to return multiple route changes, but the last one does not have a prepTime
mockGetEntriesByName.mockImplementation(name => {
if (name === 'route_change') {
const entries = [
@@ -457,7 +457,7 @@ describe('custom-perf-metric', () => {
},
},
{
// 没有startTime属性
// No StartTime property
detail: {
location: {
pathname: '/test-path2',
@@ -466,7 +466,7 @@ describe('custom-perf-metric', () => {
},
];
// 确保数组有 at 方法
// Make sure the array has at method
if (!entries.at) {
entries.at = function (index) {
return this[index < 0 ? this.length + index : index];
@@ -478,12 +478,12 @@ describe('custom-perf-metric', () => {
return [];
});
// 执行
// execute
reportTti({ key: 'value' });
// 验证
// verify
expect(mockSlardarInstance).toHaveBeenCalledWith('sendCustomPerfMetric', {
value: 700, // 1000 - 300 = 700 (使用了第一个路由的startTime)
value: 700, // 1000 - 300 = 700 (with the first route's prepTime)
name: PerfMetricNames.TTI_HOT,
type: 'perf',
extra: {

View File

@@ -17,7 +17,7 @@
/// <reference types='@coze-arch/bot-typings' />
declare interface Window {
// 运行 e2e 时会注入这个全局方法
// This global method is injected when running e2e
REPORT_TTI_FOR_E2E?: (
timestamp: number,
performanceEntry: PerformanceEntryList,

View File

@@ -24,7 +24,7 @@ import {
export interface ReportTtiParams {
isLive: boolean;
extra?: Record<string, string>;
scene?: string; // 一个页面默认只上报一次tti设置不同的scene可上报多次
scene?: string; // A page only reports tti once by default, and different scenes can be reported multiple times.
}
export const useReportTti = ({
@@ -34,8 +34,8 @@ export const useReportTti = ({
}: ReportTtiParams) => {
useEffect(() => {
if (isLive) {
// TODO useEffect 与真实 DOM 渲染之间会有 gap需要考虑如何抹平差异
// settimeout 在网页后台会挂起,导致 TTI 严重不准
// There will be a gap between TODO useEffect and real DOM rendering, you need to consider how to smooth the difference
// SetTimeout hangs in the background of the page, causing TTI to be severely inaccurate
reportTti(extra, scene);
}
}, [isLive]);

View File

@@ -41,7 +41,7 @@ export const reportTti = (extra?: Record<string, string>, scene?: string) => {
CustomPerfMarkNames.RouteChange,
) as PerformanceMark[];
const lastRoute = routeChangeEntries.at(-1);
// 当前页面已经上报过
// The current page has been reported
if (
lastRoute?.detail?.location?.pathname &&
lastRoute.detail.location.pathname === lastRouteNameRef.name &&
@@ -50,7 +50,7 @@ export const reportTti = (extra?: Record<string, string>, scene?: string) => {
return;
}
if (document.visibilityState === 'hidden') {
// 页签处于后台FCP / TTI 均不准确,放弃上报
// The tab is in the background, the FCP/TTI is inaccurate, and the reporting is abandoned.
reporter.info({
message: 'page_hidden_on_tti_report',
namespace: 'performance',
@@ -60,21 +60,21 @@ export const reportTti = (extra?: Record<string, string>, scene?: string) => {
lastRouteNameRef.name = lastRoute?.detail?.location?.pathname;
lastRouteNameRef.reportScene.push(sceneKey);
// 首个路由视为冷启动,否则视为热启动,因为预期 TTI 时间差异会比较大,这里上报到不同的埋点上
// The first route is regarded as a cold start, otherwise it is regarded as a hot start, because the expected TTI time difference will be relatively large, and it will be reported to different event tracking here.
if (routeChangeEntries.length > 1) {
// startTime 是相对于 performance.timeOrigin 的一个偏移量
// StartTime is an offset from the performance .timeOrigin
executeSendTtiHot(value - (lastRoute?.startTime ?? 0), extra);
return;
}
const fcp = performance.getEntriesByName(fcpEntryName)[0];
if (fcp) {
// 已发生 FCP比较 TTI FCP 时间,取耗时更长的一个
// FCP has occurred, compare TTI and FCP times, and take the longer one.
executeSendTti(value > fcp.startTime ? value : fcp.startTime, {
...extra,
fcpTime: `${fcp.startTime}`,
});
} else if (window.PerformanceObserver) {
// 还未发生 FCP 时,监听 FCP 作为 TTI 上报
// When no FCP has occurred, monitor the FCP and report it as a TTI
const observer = new PerformanceObserver(list => {
const fcpEntry = list.getEntriesByName(fcpEntryName)[0];
if (fcpEntry) {
@@ -88,7 +88,7 @@ export const reportTti = (extra?: Record<string, string>, scene?: string) => {
try {
observer.observe({ type: 'paint', buffered: true });
} catch (error) {
// 处理兼容性问题 Failed to execute 'observe' on 'PerformanceObserver': required member entryTypes is undefined.
// Handling compatibility issues Failed to execute'observe 'on'PerformanceObserver': required member entryTypes is undefined.
if (PerformanceObserver.supportedEntryTypes?.includes('paint')) {
try {
observer.observe({ entryTypes: ['paint'] });
@@ -111,7 +111,7 @@ const executeSendTti = (value: number, extra?: Record<string, string>) => {
getSlardarInstance()?.('sendCustomPerfMetric', {
value,
name: PerfMetricNames.TTI,
/** 性能指标类型, perf => 传统性能, spa => SPA 性能, mf => 微前端性能 */
/** Performance index type, perf = > traditional performance, spa = > SPA performance, mf = > micro frontend performance */
type: 'perf',
extra: {
...extra,
@@ -128,7 +128,7 @@ const executeSendTtiHot = (value: number, extra?: Record<string, string>) => {
getSlardarInstance()?.('sendCustomPerfMetric', {
value,
name: PerfMetricNames.TTI_HOT,
/** 性能指标类型, perf => 传统性能, spa => SPA 性能, mf => 微前端性能 */
/** Performance index type, perf = > traditional performance, spa = > SPA performance, mf = > micro frontend performance */
type: 'perf',
extra: {
...extra,