Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optimize: fix eslint in @base/object module #16380

Merged
merged 6 commits into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 43 additions & 44 deletions cocos/core/data/class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@

import { DEV, EDITOR, SUPPORT_JIT, TEST } from 'internal:constants';
import { cclegacy } from '@base/global';
import { errorID, warnID, error } from '@base/debug';
import { errorID, warnID, error, _throw, StringSubstitution, getError } from '@base/debug';
import { js } from '@base/utils';
import { BitMask } from '../value-types';
import { Enum } from '../value-types/enum';
import { Enum, EnumType } from '../value-types/enum';
import * as attributeUtils from './utils/attribute';
import { IAcceptableAttributes } from './utils/attribute-defines';
import { preprocessAttrs } from './utils/preprocess-class';
Expand Down Expand Up @@ -73,7 +73,7 @@
pushUnique(cls.__props__, name);
}

function defineProp (cls, className, propName, val): void {
function defineProp (cls: Constructor, className: string, propName: string, val: PropertyStash): void {
if (DEV) {
// check base prototype to avoid name collision
if (CCClass.getInheritanceChain(cls)
Expand All @@ -96,12 +96,12 @@
}
}

function defineGetSet (cls, name, propName, val): void {
function defineGetSet (cls: Constructor, className: string, propName: string, val: PropertyStash): void {
const getter = val.get;
const setter = val.set;

if (getter) {
parseAttributes(cls, val, name, propName, true);
parseAttributes(cls, val, className, propName, true);
if ((EDITOR && !window.Build) || TEST) {
onAfterProps_ET.length = 0;
}
Expand Down Expand Up @@ -131,7 +131,7 @@
try {
return defaultVal();
} catch (e) {
cclegacy._throw(e);
_throw(e);
return undefined;
}
} else {
Expand All @@ -141,36 +141,36 @@
return defaultVal;
}

function doDefine (className, baseClass, options): any {
const ctor = options.ctor;
function doDefine (className: string | undefined, baseClass: Constructor | null, options: Parameters<typeof CCClass>[0]): Constructor {
const ctor = options.ctor as Constructor;

if (DEV) {
// check ctor
if (CCClass._isCCClass(ctor)) {
errorID(3618, className);
errorID(3618, className!);
}
}

js.value(ctor, CCCLASS_TAG, true, true);

const prototype = ctor.prototype;
if (baseClass) {
ctor.$super = baseClass;
// TODO: this is a dynamic inject method, should be define in class
// issue: https://github.com/cocos/cocos-engine/issues/14643
(ctor as any).$super = baseClass;
}

js.setClassName(className, ctor);
js.setClassName(className!, ctor);
return ctor;
}

function define (className, baseClass, options): any {
function define (className: string | undefined, baseClass: Constructor | null, options: Parameters<typeof CCClass>[0]): Constructor {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why class name can be undefined?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not a good interface design, but as it is used in CCClass method, it should be typeof string | undefined

export function CCClass<TFunction> (options: {
name?: string;
extends: null | (Function & { __props__?: any; _sealed?: boolean });
ctor: TFunction;
properties?: any;
editor?: any;
}): any {
let name = options.name;
const base = options.extends/* || CCObject */;
// create constructor
const cls = define(name, base, options);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can it work if passing undefined?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, actually in the past, undefined was often passed in

Copy link
Contributor Author

@PPpro PPpro Oct 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this line fix the undefined issue

className = className || frame.script;

There is much HACK code in this module :(
I try to add more type detail for it

const Component = cclegacy.Component;
const frame = RF.peek();

if (frame && js.isChildClassOf(baseClass, Component)) {
// project component
if (js.isChildClassOf(frame.cls, Component)) {
errorID(3615);
return null;
_throw(getError(3615));
}
if (DEV && frame.uuid && className) {
// warnID(3616, className);
Expand All @@ -197,14 +197,14 @@
}
// 增加了 hidden: 开头标识,使它最终不会显示在 Editor inspector 的添加组件列表里

window.EditorExtends && window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1);

Check warning on line 200 in cocos/core/data/class.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Expected an assignment or function call and instead saw an expression
}

// Note: `options.ctor` should be the same as `cls` except if
// cc-class is defined by `cc.Class({/* ... */})`.
// In such case, `options.ctor` may be `undefined`.
// So we can not use `options.ctor`. Instead, we should use `cls` which is the "real" registered cc-class.
EditorExtends.emit('class-registered', cls, frame, className);
EditorExtends.emit('class-registered', cls, frame, className!);
}

if (frame) {
Expand Down Expand Up @@ -258,15 +258,16 @@
// simple test variable name
const IDENTIFIER_RE = /^[A-Za-z_$][0-9A-Za-z_$]*$/;

function declareProperties (cls, className, properties, baseClass): void {
cls.__props__ = [];
function declareProperties (cls: Constructor, className: string, properties: Record<string, PropertyStash> | undefined, baseClass: Constructor | null): void {
// TODO: this is a dynamic inject method, should be define in class
// issue: https://github.com/cocos/cocos-engine/issues/14643
(cls as any).__props__ = [];

if (baseClass && baseClass.__props__) {
cls.__props__ = baseClass.__props__.slice();
if (baseClass && (baseClass as any).__props__) {
(cls as any).__props__ = (baseClass as any).__props__.slice();
}

if (properties) {
// 预处理属性
preprocessAttrs(properties, className, cls);

for (const propName in properties) {
Expand All @@ -280,14 +281,14 @@
}

const attrs = attributeUtils.getClassAttrs(cls);
cls.__values__ = cls.__props__.filter((prop) => attrs[`${prop}${DELIMETER}serializable`] !== false);
(cls as any).__values__ = (cls as any).__props__.filter((prop) => attrs[`${prop}${DELIMETER}serializable`] !== false);
}

export function CCClass<TFunction> (options: {
name?: string;
extends: null | (Function & { __props__?: any; _sealed?: boolean });
extends: null | (Constructor & { __props__?: any; _sealed?: boolean });
ctor: TFunction;
properties?: any;
properties?: Record<string, PropertyStash>;
editor?: any;
}): any {
let name = options.name;
Expand All @@ -296,10 +297,10 @@
// create constructor
const cls = define(name, base, options);
if (!name) {
name = cclegacy.js.getClassName(cls);
name = js.getClassName(cls);
}

cls._sealed = true;
(cls as any)._sealed = true;
if (base) {
base._sealed = false;
}
Expand All @@ -313,7 +314,7 @@
if (js.isChildClassOf(base, cclegacy.Component)) {
cclegacy.Component._registerEditorProps(cls, editor);
} else if (DEV) {
warnID(3623, name!);
warnID(3623, name);
}
}

Expand Down Expand Up @@ -346,9 +347,11 @@
// @param {Object} serializableFields
// @private
//
CCClass.fastDefine = function (className, constructor, serializableFields): void {
CCClass.fastDefine = function (className: string, constructor: Constructor, serializableFields: Record<string, unknown>): void {

Check warning on line 350 in cocos/core/data/class.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Unexpected unnamed function
js.setClassName(className, constructor);
const props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields);
// TODO: this is a dynamic inject method, should be define in class
// issue: https://github.com/cocos/cocos-engine/issues/14643
const props = (constructor as any).__props__ = (constructor as any).__values__ = Object.keys(serializableFields);
const attrs = attributeUtils.getClassAttrs(constructor);
for (let i = 0; i < props.length; i++) {
const key = props[i];
Expand Down Expand Up @@ -378,7 +381,7 @@
* Return all super classes.
* @param constructor The Constructor.
*/
function getInheritanceChain (constructor): any[] {
function getInheritanceChain (constructor: Constructor): any[] {
const chain: any[] = [];
for (; ;) {
constructor = getSuper(constructor);
Expand All @@ -405,11 +408,11 @@
};

interface IParsedAttribute extends IAcceptableAttributes {
ctor?: Function;
ctor?: Constructor;
enumList?: readonly any[];
bitmaskList?: any[];
}
type OnAfterProp = (constructor: Function, mainPropertyName: string) => void;
type OnAfterProp = (constructor: Constructor, mainPropertyName: string) => void;
const onAfterProps_ET: OnAfterProp[] = [];

interface AttributesRecord {
Expand All @@ -418,7 +421,7 @@
default?: unknown;
}

function parseAttributes (constructor: Function, attributes: PropertyStash, className: string, propertyName: string, usedInGetter): void {
function parseAttributes (constructor: Constructor, attributes: PropertyStash, className: string, propertyName: string, usedInGetter): void {
const ERR_Type = DEV ? 'The %s of %s must be type %s' : '';

let attrs: IParsedAttribute | null = null;
Expand All @@ -440,7 +443,7 @@

const type = attributes.type;
if (type) {
const primitiveType = PrimitiveTypes[type];
const primitiveType = PrimitiveTypes[type] as string;
if (primitiveType) {
(attrs || initAttrs())[`${propertyNamePrefix}type`] = type;
if (((EDITOR && !window.Build) || TEST) && !attributes._short) {
Expand All @@ -450,23 +453,18 @@
if (DEV) {
errorID(3644, className, propertyName);
}
}
// else if (type === Attr.ScriptUuid) {
// (attrs || initAttrs())[propertyNamePrefix + 'type'] = 'Script';
// attrs[propertyNamePrefix + 'ctor'] = cc.ScriptAsset;
// }
else if (typeof type === 'object') {
} else if (typeof type === 'object') {
if (Enum.isEnum(type)) {
setPropertyEnumTypeOnAttrs(
attrs || initAttrs(),
(attrs || initAttrs()) as Record<string, unknown>,
propertyName,
type,
type as EnumType,
);
} else if (BitMask.isBitMask(type)) {
(attrs || initAttrs())[`${propertyNamePrefix}type`] = BITMASK_TAG;
attrs![`${propertyNamePrefix}bitmaskList`] = BitMask.getList(type);
} else if (DEV) {
errorID(3645, className, propertyName, type);
errorID(3645, className, propertyName, type as StringSubstitution);
}
} else if (typeof type === 'function') {
// Do not warn missing-default if the type is object
Expand All @@ -477,7 +475,7 @@
onAfterProps_ET.push(attributeUtils.getObjTypeChecker_ET(type));
}
} else if (DEV) {
errorID(3646, className, propertyName, type);
errorID(3646, className, propertyName, type as StringSubstitution);
}
}

Expand All @@ -492,6 +490,7 @@
const parseSimpleAttribute = (attributeName: keyof IAcceptableAttributes, expectType: string): void => {
if (attributeName in attributes) {
const val = attributes[attributeName];
// eslint-disable-next-line valid-typeof
if (typeof val === expectType) {
(attrs || initAttrs())[propertyNamePrefix + attributeName] = val;
} else if (DEV) {
Expand Down Expand Up @@ -597,7 +596,7 @@
parseSimpleAttribute('step', 'number');
}

CCClass.isArray = function (defaultVal): boolean {

Check warning on line 599 in cocos/core/data/class.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Unexpected unnamed function
defaultVal = getDefault(defaultVal);
return Array.isArray(defaultVal);
};
Expand Down
12 changes: 6 additions & 6 deletions cocos/core/data/decorators/property.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,8 @@ function mergePropertyOptions (
descriptorOrInitializer: Parameters<LegacyPropertyDecorator>[2] | undefined,
): void {
let fullOptions;
const isGetset = descriptorOrInitializer && typeof descriptorOrInitializer !== 'function'
&& (descriptorOrInitializer.get || descriptorOrInitializer.set);
const isGetset = !!(descriptorOrInitializer && typeof descriptorOrInitializer !== 'function'
&& (descriptorOrInitializer.get || descriptorOrInitializer.set));
if (options) {
fullOptions = getFullFormOfProperty(options, isGetset);
}
Expand All @@ -208,11 +208,11 @@ function mergePropertyOptions (
warnID(3655, propertyKey as string, getClassName(ctor), propertyKey as string, propertyKey as string);
}
}
if ((descriptorOrInitializer as BabelPropertyDecoratorDescriptor).get) {
propertyRecord.get = (descriptorOrInitializer as BabelPropertyDecoratorDescriptor).get;
if (descriptorOrInitializer.get) {
propertyRecord.get = descriptorOrInitializer.get;
}
if ((descriptorOrInitializer as BabelPropertyDecoratorDescriptor).set) {
propertyRecord.set = (descriptorOrInitializer as BabelPropertyDecoratorDescriptor).set;
if (descriptorOrInitializer.set) {
propertyRecord.set = descriptorOrInitializer.set;
}
} else { // Target property is non-accessor
if (DEV && (propertyRecord.get || propertyRecord.set)) {
Expand Down
24 changes: 16 additions & 8 deletions cocos/core/data/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
const objectsToDestroy: CCObject[] = [];
let deferredDestroyTimer: number | null = null;

function compileDestruct (obj, ctor): Function {
function compileDestruct (obj, ctor): AnyFunction {
const shouldSkipId = obj instanceof cclegacy.Node || obj instanceof cclegacy.Component;
const idToSkip = shouldSkipId ? '_id' : null;

Expand Down Expand Up @@ -134,7 +134,7 @@

for (key in propsToReset) {
let statement;
if (CCClass.IDENTIFIER_RE.test(key)) {
if (CCClass.IDENTIFIER_RE.test(key as string)) {
statement = `o.${key}=`;
} else {
statement = `o[${CCClass.escapeForJS(key)}]=`;
Expand Down Expand Up @@ -347,8 +347,10 @@
* ```
*/
public _destruct (): void {
const ctor: any = this.constructor;
let destruct = ctor.__destruct__;
const ctor = this.constructor as Constructor;
// TODO: this is a dynamic inject method, should be define in class
// issue: https://github.com/cocos/cocos-engine/issues/14643
let destruct = (ctor as any).__destruct__;
if (!destruct) {
destruct = compileDestruct(this, ctor);
js.value(ctor, '__destruct__', destruct, true);
Expand Down Expand Up @@ -386,7 +388,7 @@

const prototype = CCObject.prototype;
if (EDITOR || TEST) {
js.get(prototype, 'isRealValid', function (this: CCObject) {

Check warning on line 391 in cocos/core/data/object.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Unexpected unnamed function
return !(this._objFlags & RealDestroyed);
});

Expand All @@ -395,13 +397,16 @@
* This method is only available for editors and is not recommended for developers
* @zh 在继承 CCObject 对象后,控制是否需要隐藏,锁定,序列化等功能(该方法仅提供给编辑器使用,不建议开发者使用)。
*/
js.getset(prototype, 'objFlags',
js.getset(
prototype,
'objFlags',
function (this: CCObject) {

Check warning on line 403 in cocos/core/data/object.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Unexpected unnamed function
return this._objFlags;
},
function (this: CCObject, objFlags: CCObject.Flags) {

Check warning on line 406 in cocos/core/data/object.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Unexpected unnamed function
this._objFlags = objFlags;
});
},
);

/*
* @en
Expand All @@ -415,7 +420,7 @@
* TODO: this is a dynamic inject method, should be define in class
* issue: https://github.com/cocos/cocos-engine/issues/14643
*/
(prototype as any).realDestroyInEditor = function (): void {

Check warning on line 423 in cocos/core/data/object.ts

View workflow job for this annotation

GitHub Actions / Run ESLint

Unexpected unnamed function
if (!(this._objFlags & Destroyed)) {
warnID(5001);
return;
Expand Down Expand Up @@ -675,8 +680,11 @@

if (JSB) {
copyAllProperties(CCObject, jsb.CCObject, ['prototype', 'length', 'name']);
copyAllProperties(CCObject.prototype, jsb.CCObject.prototype,
['constructor', 'name', 'hideFlags', 'isValid']);
copyAllProperties(
CCObject.prototype,
jsb.CCObject.prototype,
['constructor', 'name', 'hideFlags', 'isValid'],
);

(CCObject as unknown as any) = jsb.CCObject;
}
Expand Down
4 changes: 2 additions & 2 deletions cocos/core/data/utils/attribute-internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ import { getClassAttrs, DELIMETER } from './attribute';

// eslint-disable-next-line @typescript-eslint/ban-types
export function setPropertyEnumType (objectOrConstructor: object, propertyName: string, enumType: EnumType): void {
setPropertyEnumTypeOnAttrs(getClassAttrs(objectOrConstructor), propertyName, enumType);
setPropertyEnumTypeOnAttrs(getClassAttrs(objectOrConstructor) as Record<string, unknown>, propertyName, enumType);
}

export function setPropertyEnumTypeOnAttrs (attrs: Record<string, any>, propertyName: string, enumType: EnumType): void {
export function setPropertyEnumTypeOnAttrs (attrs: Record<string, unknown>, propertyName: string, enumType: EnumType): void {
attrs[`${propertyName}${DELIMETER}type`] = 'Enum';
attrs[`${propertyName}${DELIMETER}enumList`] = Enum.getList(enumType);
}
Loading
Loading