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

[DON'T MERGE] Add _decorator.ccclass.forward() helper decorator to allow transfer cc-class information #14961

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
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
116 changes: 113 additions & 3 deletions cocos/core/data/decorators/ccclass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,82 @@
*/

import { DEV } from 'internal:constants';
import { getSuper, mixin, getClassName } from '../../utils/js-typed';
import { getSuper, mixin, getClassName, transferCCClassIdAndName } from '../../utils/js-typed';
import { CCClass } from '../class';
import { doValidateMethodWithProps_DEV } from '../utils/preprocess-class';
import { CACHE_KEY, makeSmartClassDecorator } from './utils';

// eslint-disable-next-line @typescript-eslint/no-namespace
namespace ccclassNamespace {
/**
* @zh
* 返回一个装饰器,它运作时会直接调用指定的另一个装饰器。
* 当指定的装饰器返回新的类时,将原本构造函数上关联的所有 cc-class 相关的信息转移到新的构造函数上。
*
* 当你的类装饰器会返回新的类时,你需要将你的类装饰器包裹在此方法中来转移所有 cc-class 相关的信息。
*
* @en
* Returns a decorator, when this decorator works,
* it will immediately invoke another specified decorator.
* In case of the specified decorator returning new class,
* all cc-class information that was associated to original constructor
* are transferred to new constructor.
*
* If your class decorator is going to return a new class.
* You have to wrap your decorator by this method to transfer all cc-class information to the new class.
*
* @param originalConstructor @zh 原始构造函数。 @en The original constructor.
*
* @param newConstructor @zh 新的接收 cc 属性构造函数。 @en The new constructor which accepts the properties.
*
* @example
*
* @zh
* ```ts
* const someClassDecorator: ClassDecorator = (constructor) => {
* class NewClass {}
* return NewClass;
* };
*
* \@ccclass('SomeClass')
* // 如果你不包裹,得到的类不能再作为正常的 cc 类来用,
* // 比如,它不能再被序列化或展示在编辑器中。
* \@ccclass.forward(someClassDecorator)
* class SomeClass {
* \@property someProperty = '';
* }
* ```
*
* @en
*
* ```ts
* const someClassDecorator: ClassDecorator = (constructor) => {
* class NewClass {}
* return NewClass;
* };
*
* \@ccclass('SomeClass')
* // If you do not wrap,
* // the result class will not be able to used as a normal cc-class,
* // for example, will not be able to be serialized or be shown in editor.
* \@ccclass.forward(someClassDecorator)
* class SomeClass {
* \@property someProperty = '';
* }
* ```
*/
export function forward (classDecorator: ClassDecorator): ClassDecorator {
return (originalConstructor) => {
const maybeNewConstructor = classDecorator(originalConstructor);
if (!maybeNewConstructor) {
return undefined;
}
transferCCClass(originalConstructor, maybeNewConstructor);
return maybeNewConstructor;
};
}
}

/**
* @en Declare a standard class as a CCClass, please refer to the [document](https://docs.cocos.com/creator3d/manual/en/scripting/ccclass.html)
* @zh 将标准写法的类声明为 CC 类,具体用法请参阅[类型定义](https://docs.cocos.com/creator3d/manual/zh/scripting/ccclass.html)。
Expand All @@ -50,7 +121,7 @@ import { CACHE_KEY, makeSmartClassDecorator } from './utils';
* }
* ```
*/
export const ccclass: ((name?: string) => ClassDecorator) & ClassDecorator = makeSmartClassDecorator<string>((constructor, name) => {
export const ccclass = Object.assign(makeSmartClassDecorator<string>((constructor, name) => {
let base = getSuper(constructor);
if (base === Object) {
base = null;
Expand Down Expand Up @@ -89,4 +160,43 @@ export const ccclass: ((name?: string) => ClassDecorator) & ClassDecorator = mak
}

return res;
});
}), ccclassNamespace);

function transferCCClass (
// eslint-disable-next-line @typescript-eslint/ban-types
originalConstructor: Function,

// eslint-disable-next-line @typescript-eslint/ban-types
newConstructor: Function,
) {
// Transfer id and name in case of `@ccclass()` has already been applied on `originalConstructor`.
transferCCClassIdAndName(originalConstructor, newConstructor);

// These properties are injected before `@ccclass` is called.
tryTransferConstructorProperty(originalConstructor, newConstructor, CACHE_KEY);

// These properties are injected after `@ccclass` is called.
tryTransferConstructorProperty(originalConstructor, newConstructor, '__props__');
tryTransferConstructorProperty(originalConstructor, newConstructor, '__attrs__');
tryTransferConstructorProperty(originalConstructor, newConstructor, '__values__');
tryTransferConstructorProperty(originalConstructor, newConstructor, '__ctors__');
tryTransferConstructorProperty(originalConstructor, newConstructor, '_sealed');
}

const hasOwnProperty = Object.prototype.hasOwnProperty;

function tryTransferConstructorProperty (
// eslint-disable-next-line @typescript-eslint/ban-types
originalConstructor: Function,

// eslint-disable-next-line @typescript-eslint/ban-types
newConstructor: Function,

propertyKey: typeof CACHE_KEY | '__props__' | '__attrs__' | '__values__' | '__ctors__' | '_sealed',
) {
// eslint-disable-next-line no-prototype-builtins
if (hasOwnProperty.call(originalConstructor, propertyKey)) {
newConstructor[propertyKey] = originalConstructor[propertyKey];
delete originalConstructor[propertyKey];
}
}
27 changes: 27 additions & 0 deletions cocos/core/utils/js-typed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,30 @@ export function createMap (forceDictMode?: boolean): any {
return map;
}

/**
* @internal
Copy link
Contributor

Choose a reason for hiding this comment

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

for now, use engineInternal instead

* @engineInternal
*/
export function transferCCClassIdAndName (
// eslint-disable-next-line @typescript-eslint/ban-types
originalConstructor: Function,

// eslint-disable-next-line @typescript-eslint/ban-types
newConstructor: Function,
) {
const className = (originalConstructor.prototype as unknown as { [classNameTag]: string | undefined })[classNameTag];
const classId = getClassId(originalConstructor, false);

unregisterClass(originalConstructor);

if (className) {
doSetClassName(className, newConstructor as Constructor<any>);
}
if (classId) {
_setClassId(classId, newConstructor as Constructor<any>);
}
}

/**
* @en
* Gets class name of the object, if object is just a {} (and which class named 'Object'), it will return "".
Expand Down Expand Up @@ -719,10 +743,12 @@ export function unregisterClass (...constructors: Function[]) {
const p = constructor.prototype;
const classId = p[classIdTag];
if (classId) {
delete p[classIdTag];
Copy link
Contributor

Choose a reason for hiding this comment

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

If we have a registerClass method, then it should satisfy the following:
unregister(A);
register(A);
// At this point, there should be no changes.

So I don't think it's very necessary to reset a class's own properties. Literally speaking, unregistering a class doesn't necessarily have to include resetting or clearing the target class. When a class needs to be unregistered, it's often no longer needed, so its own data can be safely garbage collected without the need for a reset.

delete _idToClass[classId];
}
const classname = p[classNameTag];
if (classname) {
delete p[classNameTag];
delete _nameToClass[classname];
}
const aliases = p[aliasesTag];
Expand All @@ -732,6 +758,7 @@ export function unregisterClass (...constructors: Function[]) {
delete _nameToClass[alias];
delete _idToClass[alias];
}
delete p[aliasesTag];
}
}
}
Expand Down
80 changes: 79 additions & 1 deletion tests/core/decorator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { CCClass } from '../../cocos/core/data/class';
import { property } from '../../cocos/core/data/decorators/property';
import { getClassByName, unregisterClass } from '../../cocos/core/utils/js-typed';
import { LegacyPropertyDecorator } from '../../cocos/core/data/decorators/utils';
import { CCBoolean, CCFloat, CCInteger, CCString } from '../../exports/base';
import { CCBoolean, CCFloat, CCInteger, CCString, js } from '../../exports/base';
import { PrimitiveType } from '../../cocos/core/data/utils/attribute';

test('Decorators signature', () => {
Expand Down Expand Up @@ -333,6 +333,84 @@ describe(`Decorators`, () => {

});
});

describe('@ccclass.forward', () => {
/**
* This decorator is taken from issue:
* cocos/cocos-engine#14959
* with some modifications.
*/
const deco = (): ClassDecorator => {
return <TFunction extends Function>(constructorFunction: TFunction) => {
const newConstructorFunction = function (...args: unknown[]) {
let func: any = function () {
return new (constructorFunction as unknown as { new(...constructorArgs: any[]) })(...args);
};
func.prototype = constructorFunction.prototype;
return new func();
};
newConstructorFunction.prototype = constructorFunction.prototype;
return newConstructorFunction as unknown as TFunction;
};
};

@ccclass('SomeBaseClass')
class SomeBaseClass {
@property public someBaseProp = 456;
}

afterAll(() => {
unregisterClass(SomeBaseClass);
});

test('Applied after @ccclass', () => {
@ccclass.forward(deco())
@ccclass('SomeClass')
class SomeClass extends SomeBaseClass {
@property
public someProp = '123';
}

// Checks if the class is correctly registered.
expect(CCClass._isCCClass(SomeClass)).toBe(true);
expect(js.getClassByName('SomeClass')).toBe(SomeClass);

// Checks if the properties are transferred.
expect(CCClass.Attr.attr(SomeClass, 'someProp')).toStrictEqual(expect.objectContaining({
default: '123',
}));
// Checks if base properties are transferred.
expect(CCClass.Attr.attr(SomeClass, 'someBaseProp')).toStrictEqual(expect.objectContaining({
default: 456,
}));

js.unregisterClass(SomeClass);
});

test('Applied before @ccclass', () => {
@ccclass('SomeClass')
@ccclass.forward(deco())
class SomeClass extends SomeBaseClass {
@property
public someProp = '123';
}

// Checks if the class is correctly registered.
expect(CCClass._isCCClass(SomeClass)).toBe(true);
expect(js.getClassByName('SomeClass')).toBe(SomeClass);

// Checks if the properties are transferred.
expect(CCClass.Attr.attr(SomeClass, 'someProp')).toStrictEqual(expect.objectContaining({
default: '123',
}));
// Checks if base properties are transferred.
expect(CCClass.Attr.attr(SomeClass, 'someBaseProp')).toStrictEqual(expect.objectContaining({
default: 456,
}));

js.unregisterClass(SomeClass);
});
});
});

describe('Decorated property test', () => {
Expand Down