fix: fix lint issues for renderer-core/renderer/base

This commit is contained in:
JackLian 2022-06-29 20:16:05 +08:00 committed by 刘菊萍(絮黎)
parent 5dd462544f
commit 4b59190c7f
3 changed files with 66 additions and 37 deletions

View File

@ -1,3 +1,4 @@
/* eslint-disable no-console */
/* eslint-disable max-len */ /* eslint-disable max-len */
/* eslint-disable react/prop-types */ /* eslint-disable react/prop-types */
import classnames from 'classnames'; import classnames from 'classnames';
@ -47,7 +48,7 @@ export default function baseRendererFactory(): IBaseRenderComponent {
Record<string, any>, Record<string, any>,
any any
>; >;
const createElement = runtime.createElement; const { createElement } = runtime;
const Div = divFactory(); const Div = divFactory();
const VisualDom = visualDomFactory(); const VisualDom = visualDomFactory();
const AppContext = contextFactory(); const AppContext = contextFactory();
@ -97,6 +98,7 @@ export default function baseRendererFactory(): IBaseRenderComponent {
this.__debug(`constructor - ${props?.__schema?.fileName}`); this.__debug(`constructor - ${props?.__schema?.fileName}`);
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
__beforeInit(_props: IBaseRendererProps) { } __beforeInit(_props: IBaseRendererProps) { }
__init(props: IBaseRendererProps) { __init(props: IBaseRendererProps) {
@ -107,6 +109,7 @@ export default function baseRendererFactory(): IBaseRenderComponent {
this.__initI18nAPIs(); this.__initI18nAPIs();
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
__afterInit(_props: IBaseRendererProps) { } __afterInit(_props: IBaseRendererProps) { }
static getDerivedStateFromProps(props: IBaseRendererProps, state: any) { static getDerivedStateFromProps(props: IBaseRendererProps, state: any) {
@ -120,35 +123,36 @@ export default function baseRendererFactory(): IBaseRenderComponent {
} }
if (typeof func === 'function') { if (typeof func === 'function') {
// eslint-disable-next-line @typescript-eslint/ban-types
return (func as Function)(props, state); return (func as Function)(props, state);
} }
} }
return null; return null;
} }
async getSnapshotBeforeUpdate() { async getSnapshotBeforeUpdate(...args: any[]) {
this.__setLifeCycleMethods('getSnapshotBeforeUpdate', arguments); this.__setLifeCycleMethods('getSnapshotBeforeUpdate', args);
this.__debug(`getSnapshotBeforeUpdate - ${this.props?.__schema?.fileName}`); this.__debug(`getSnapshotBeforeUpdate - ${this.props?.__schema?.fileName}`);
} }
async componentDidMount() { async componentDidMount(...args: any[]) {
this.reloadDataSource(); this.reloadDataSource();
this.__setLifeCycleMethods('componentDidMount', arguments); this.__setLifeCycleMethods('componentDidMount', args);
this.__debug(`componentDidMount - ${this.props?.__schema?.fileName}`); this.__debug(`componentDidMount - ${this.props?.__schema?.fileName}`);
} }
async componentDidUpdate(...args: any) { async componentDidUpdate(...args: any[]) {
this.__setLifeCycleMethods('componentDidUpdate', args); this.__setLifeCycleMethods('componentDidUpdate', args);
this.__debug(`componentDidUpdate - ${this.props.__schema.fileName}`); this.__debug(`componentDidUpdate - ${this.props.__schema.fileName}`);
} }
async componentWillUnmount(...args: any) { async componentWillUnmount(...args: any[]) {
this.__setLifeCycleMethods('componentWillUnmount', args); this.__setLifeCycleMethods('componentWillUnmount', args);
this.__debug(`componentWillUnmount - ${this.props?.__schema?.fileName}`); this.__debug(`componentWillUnmount - ${this.props?.__schema?.fileName}`);
} }
async componentDidCatch(e: any) { async componentDidCatch(e: any, ...args: any[]) {
this.__setLifeCycleMethods('componentDidCatch', arguments); this.__setLifeCycleMethods('componentDidCatch', { e, ...args });
console.warn(e); console.warn(e);
} }
@ -165,7 +169,7 @@ export default function baseRendererFactory(): IBaseRenderComponent {
this.forceUpdate(); this.forceUpdate();
return resolve({}); return resolve({});
} }
this.setState(res, resolve); this.setState(res, resolve as () => void);
}) })
.catch((err: Error) => { .catch((err: Error) => {
if (this.__showPlaceholder) { if (this.__showPlaceholder) {
@ -229,14 +233,15 @@ export default function baseRendererFactory(): IBaseRenderComponent {
}); });
this.__customMethodsList = customMethodsList; this.__customMethodsList = customMethodsList;
forEach(__schema.methods, (val: any, key: string) => { forEach(__schema.methods, (val: any, key: string) => {
if (isJSExpression(val) || isJSFunction(val)) { let value = val;
val = this.parseExpression(val, this); if (isJSExpression(value) || isJSFunction(value)) {
value = this.parseExpression(value, this);
} }
if (typeof val !== 'function') { if (typeof value !== 'function') {
console.error(`自定义函数${key}类型不符`, val); console.error(`自定义函数${key}类型不符`, value);
return; return;
} }
this[key] = val.bind(this); this[key] = value.bind(this);
}); });
}; };
@ -304,7 +309,7 @@ export default function baseRendererFactory(): IBaseRenderComponent {
this.forceUpdate(); this.forceUpdate();
return resolve({}); return resolve({});
} }
this.setState(res, resolve); this.setState(res, resolve as () => void);
}) })
.catch((err: Error) => { .catch((err: Error) => {
if (this.__showPlaceholder) { if (this.__showPlaceholder) {
@ -417,7 +422,9 @@ export default function baseRendererFactory(): IBaseRenderComponent {
// self 为每个渲染组件构造的上下文self是自上而下继承的 // self 为每个渲染组件构造的上下文self是自上而下继承的
// parentInfo 父组件的信息包含schema和Comp // parentInfo 父组件的信息包含schema和Comp
// idx 若为循环渲染的循环Index // idx 若为循环渲染的循环Index
__createVirtualDom = (schema: NodeData | NodeData[] | undefined, scope: any, parentInfo: IInfo, idx: string | number = ''): any => { __createVirtualDom = (originalSchema: NodeData | NodeData[] | undefined, originalScope: any, parentInfo: IInfo, idx: string | number = ''): any => {
let scope = originalScope;
let schema = originalSchema;
const { engine } = this.context || {}; const { engine } = this.context || {};
try { try {
if (!schema) return null; if (!schema) return null;
@ -588,7 +595,7 @@ export default function baseRendererFactory(): IBaseRenderComponent {
} }
let child = this.__getSchemaChildrenVirtualDom(schema, scope, Comp); let child = this.__getSchemaChildrenVirtualDom(schema, scope, Comp);
const renderComp = (props: any) => engine.createElement(Comp, props, child); const renderComp = (innerProps: any) => engine.createElement(Comp, innerProps, child);
// 设计模式下的特殊处理 // 设计模式下的特殊处理
if (engine && [DESIGN_MODE.EXTEND, DESIGN_MODE.BORDER].includes(engine.props.designMode)) { if (engine && [DESIGN_MODE.EXTEND, DESIGN_MODE.BORDER].includes(engine.props.designMode)) {
// 对于overlay,dialog等组件为了使其在设计模式下显示外层需要增加一个div容器 // 对于overlay,dialog等组件为了使其在设计模式下显示外层需要增加一个div容器
@ -698,7 +705,7 @@ export default function baseRendererFactory(): IBaseRenderComponent {
if (!Array.isArray(schema.loop)) return null; if (!Array.isArray(schema.loop)) return null;
const itemArg = (schema.loopArgs && schema.loopArgs[0]) || 'item'; const itemArg = (schema.loopArgs && schema.loopArgs[0]) || 'item';
const indexArg = (schema.loopArgs && schema.loopArgs[1]) || 'index'; const indexArg = (schema.loopArgs && schema.loopArgs[1]) || 'index';
const loop: (JSONValue| CompositeValue)[] = schema.loop; const { loop } = schema;
return loop.map((item: JSONValue | CompositeValue, i: number) => { return loop.map((item: JSONValue | CompositeValue, i: number) => {
const loopSelf: any = { const loopSelf: any = {
[itemArg]: item, [itemArg]: item,
@ -722,7 +729,8 @@ export default function baseRendererFactory(): IBaseRenderComponent {
return engine?.props?.designMode === 'design'; return engine?.props?.designMode === 'design';
} }
__parseProps = (props: any, scope: any, path: string, info: IInfo): any => { __parseProps = (originalProps: any, scope: any, path: string, info: IInfo): any => {
let props = originalProps;
const { schema, Comp, componentInfo = {} } = info; const { schema, Comp, componentInfo = {} } = info;
const propInfo = getValue(componentInfo.props, path); const propInfo = getValue(componentInfo.props, path);
// FIXME! 将这行逻辑外置,解耦,线上环境不要验证参数,调试环境可以有,通过传参自定义 // FIXME! 将这行逻辑外置,解耦,线上环境不要验证参数,调试环境可以有,通过传参自定义
@ -737,14 +745,14 @@ export default function baseRendererFactory(): IBaseRenderComponent {
if (isEmpty(params)) { if (isEmpty(params)) {
return checkProps(this.__createVirtualDom(data, scope, ({ schema, Comp } as IInfo))); return checkProps(this.__createVirtualDom(data, scope, ({ schema, Comp } as IInfo)));
} }
return checkProps(function () { return checkProps((...argValues: any[]) => {
const args: any = {}; const args: any = {};
if (Array.isArray(params) && params.length) { if (Array.isArray(params) && params.length) {
params.forEach((item, idx) => { params.forEach((item, idx) => {
if (typeof item === 'string') { if (typeof item === 'string') {
args[item] = arguments[idx]; args[item] = argValues[idx];
} else if (item && typeof item === 'object') { } else if (item && typeof item === 'object') {
args[item.name] = arguments[idx]; args[item.name] = argValues[idx];
} }
}); });
} }
@ -770,7 +778,7 @@ export default function baseRendererFactory(): IBaseRenderComponent {
if (!isSchema(props) && !isJSSlot(props)) return checkProps(props); if (!isSchema(props) && !isJSSlot(props)) return checkProps(props);
} }
const handleLegaoI18n = (props: any) => props[props.use || 'zh_CN']; const handleLegaoI18n = (innerProps: any) => innerProps[innerProps.use || 'zh_CN'];
// 兼容乐高设计态 i18n 数据 // 兼容乐高设计态 i18n 数据
if (isI18nData(props)) { if (isI18nData(props)) {
@ -810,13 +818,16 @@ export default function baseRendererFactory(): IBaseRenderComponent {
&& propInfo?.props?.types?.indexOf('ReactNode') > -1 && propInfo?.props?.types?.indexOf('ReactNode') > -1
&& propInfo?.props?.reactNodeProps?.type === 'function' && propInfo?.props?.reactNodeProps?.type === 'function'
); );
let params = null;
if (isReactNodeFunction) {
params = propInfo?.props?.params;
} else if (isMixinReactNodeFunction) {
params = propInfo?.props?.reactNodeProps?.params;
}
return parseReactNode( return parseReactNode(
props, props,
isReactNodeFunction params,
? propInfo.props.params
: isMixinReactNodeFunction
? propInfo.props.reactNodeProps.params
: null,
); );
} }
if (Array.isArray(props)) { if (Array.isArray(props)) {
@ -857,15 +868,13 @@ export default function baseRendererFactory(): IBaseRenderComponent {
__debug = logger.log; __debug = logger.log;
__renderContextProvider = (customProps?: object, children?: any) => { __renderContextProvider = (customProps?: object, children?: any) => {
customProps = customProps || {};
children = children || this.__createDom();
return createElement(AppContext.Provider, { return createElement(AppContext.Provider, {
value: { value: {
...this.context, ...this.context,
blockContext: this, blockContext: this,
...customProps, ...(customProps || {}),
}, },
children, children: children || this.__createDom(),
}); });
}; };
@ -873,7 +882,8 @@ export default function baseRendererFactory(): IBaseRenderComponent {
return createElement(AppContext.Consumer, {}, children); return createElement(AppContext.Consumer, {}, children);
}; };
__getHocComp(Comp: any, schema: any, scope: any) { __getHocComp(OriginalComp: any, schema: any, scope: any) {
let Comp = OriginalComp;
this.componentHoc.forEach((ComponentConstruct: IComponentConstruct) => { this.componentHoc.forEach((ComponentConstruct: IComponentConstruct) => {
Comp = ComponentConstruct(Comp || Div, { Comp = ComponentConstruct(Comp || Div, {
schema, schema,
@ -886,7 +896,8 @@ export default function baseRendererFactory(): IBaseRenderComponent {
return Comp; return Comp;
} }
__renderComp(Comp: any, ctxProps: object) { __renderComp(OriginalComp: any, ctxProps: object) {
let Comp = OriginalComp;
const { __schema } = this.props; const { __schema } = this.props;
const { __ctx } = this.props; const { __ctx } = this.props;
const scope: any = {}; const scope: any = {};
@ -935,7 +946,8 @@ export default function baseRendererFactory(): IBaseRenderComponent {
}, children); }, children);
} }
__checkSchema = (schema: NodeSchema | undefined, extraComponents: string | string[] = []) => { __checkSchema = (schema: NodeSchema | undefined, originalExtraComponents: string | string[] = []) => {
let extraComponents = originalExtraComponents;
if (typeof extraComponents === 'string') { if (typeof extraComponents === 'string') {
extraComponents = [extraComponents]; extraComponents = [extraComponents];
} }

View File

@ -1,6 +1,5 @@
// @ts-nocheck // @ts-nocheck
import adapter, { Env } from '../../src/adapter'; import adapter, { Env } from '../../src/adapter';
import { IRuntime, IRendererModules, IGeneralConstructor } from '../../src/types';

View File

@ -0,0 +1,18 @@
const mockGetRenderers = jest.fn();
jest.mock('../../src/adapter', () => {
return {
getRenderers: () => { return mockGetRenderers();}
};
});
import baseRendererFactory from '../../src/renderer/base';
describe('Base Render', () => {
it('customBaseRenderer logic works', () => {
mockGetRenderers.mockReturnValue({BaseRenderer: {}});
const baseRenderer = baseRendererFactory();
expect(mockGetRenderers).toBeCalledTimes(1);
expect(baseRenderer).toStrictEqual({});
mockGetRenderers.mockClear();
});
});