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 3 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 @@ function appendProp (cls, name): void {
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 defineProp (cls, className, propName, val): void {
}
}

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 @@ function getDefault (defaultVal): any {
try {
return defaultVal();
} catch (e) {
cclegacy._throw(e);
_throw(e);
return undefined;
}
} else {
Expand All @@ -141,36 +141,36 @@ function getDefault (defaultVal): any {
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 Down Expand Up @@ -204,7 +204,7 @@ function define (className, baseClass, options): any {
// 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 @@ function escapeForJS (s): string {
// 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 @@ function declareProperties (cls, className, properties, baseClass): void {
}

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 @@ export function CCClass<TFunction> (options: {
// 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 @@ export function CCClass<TFunction> (options: {
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 @@ CCClass._isCCClass = function isCCClass (constructor): boolean {
// @param {Object} serializableFields
// @private
//
CCClass.fastDefine = function (className, constructor, serializableFields): void {
CCClass.fastDefine = function (className: string, constructor: Constructor, serializableFields: Record<string, unknown>): void {
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 @@ CCClass.isCCClassOrFastDefined = isCCClassOrFastDefined;
* 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 @@ const PrimitiveTypes = {
};

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 @@ interface AttributesRecord {
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 @@ function parseAttributes (constructor: Function, attributes: PropertyStash, clas

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 @@ function parseAttributes (constructor: Function, attributes: PropertyStash, clas
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 @@ function parseAttributes (constructor: Function, attributes: PropertyStash, clas
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 @@ function parseAttributes (constructor: Function, attributes: PropertyStash, clas
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
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 AllHideMasks = DontSave | EditorOnly | LockedInEditor | HideInHierarchy;
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 @@ function compileDestruct (obj, ctor): Function {

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 @@ class CCObject implements EditorExtendableObject {
* ```
*/
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 @@ -395,13 +397,16 @@ if (EDITOR || TEST) {
* 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) {
return this._objFlags;
},
function (this: CCObject, objFlags: CCObject.Flags) {
this._objFlags = objFlags;
});
},
);

/*
* @en
Expand Down Expand Up @@ -675,8 +680,11 @@ declare const jsb: any;

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