Skip to content

Commit

Permalink
chore: 修改 replaceText 的实现,减少没必要的 deepClone (baidu#9399)
Browse files Browse the repository at this point in the history
  • Loading branch information
2betop committed Jan 10, 2024
1 parent 1d7efdc commit d48c516
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 15 deletions.
1 change: 1 addition & 0 deletions packages/amis-core/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ function AMISRenderer({

// 根据环境覆盖 schema,这个要在最前面做,不然就无法覆盖 validations
schema = envOverwrite(schema, locale);
// todo 和 envOverwrite 一起处理,减少循环次数
schema = replaceText(schema, options.replaceText, env.replaceTextIgnoreKeys);

return (
Expand Down
23 changes: 8 additions & 15 deletions packages/amis-core/src/utils/replaceText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* 对文本进行替换
*/
import cloneDeep from 'lodash/cloneDeep';
import {isObject, JSONTraverse} from './helper';
import {isObject, JSONValueMap} from './helper';

export function replaceText(
schema: any,
Expand All @@ -13,8 +13,10 @@ export function replaceText(
) {
// 进行文本替换
if (replaceText && isObject(replaceText)) {
let replicaSchema = cloneDeep(schema);
const replaceKeys = Object.keys(replaceText);
if (!replaceKeys.length) {
return schema;
}
replaceKeys.sort((a, b) => b.length - a.length); // 避免用户将短的放前面
const IgnoreKeys = new Set(
Array.isArray(replaceTextIgnoreKeys) ? replaceTextIgnoreKeys : []
Expand All @@ -26,25 +28,16 @@ export function replaceText(
return IgnoreKeys.has(key);
};

JSONTraverse(replicaSchema, (value: any, key: string, object: any) => {
const descriptor = Object.getOwnPropertyDescriptor(object, key);
if (
typeof value === 'string' &&
descriptor?.writable &&
!ignore(key, value, object)
) {
return JSONValueMap(schema, (value: any, key: string, object: any) => {
if (typeof value === 'string' && !ignore(key, value, object)) {
for (const replaceKey of replaceKeys) {
if (~value.indexOf(replaceKey)) {
value = object[key] = value.replaceAll(
replaceKey,
replaceText[replaceKey]
);
return value.replaceAll(replaceKey, replaceText[replaceKey]);
}
}
}
return value;
});

return replicaSchema;
}
return schema;
}

0 comments on commit d48c516

Please sign in to comment.