before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
this.owner.setHeight(bottom - top); } if (this._leftEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( left + this.owner.getX() - this.owner.getDrawableX() ); } if (this._topEdgeAnchor !== VerticalAnchor.None) { this.owner.setY( top + this.owner.getY() - this.owner.getDrawableY() ); } } // End of compatibility code else { // Resize if right and left anchors are set if ( this._rightEdgeAnchor !== HorizontalAnchor.None && this._leftEdgeAnchor !== HorizontalAnchor.None ) { const width = right - left; this.owner.setX( left + ((this.owner.getX() - this.owner.getDrawableX()) * width) / this.owner.getWidth() ); this.owner.setWidth(width); } else { if (this._leftEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( left + this.owner.getX() - this.owner.getDrawableX() ); } if (this._rightEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( right + this.owner.getX() - this.owner.getDrawableX() - this.owner.getWidth() ); } } // Resize if top and bottom anchors are set if ( this._bottomEdgeAnchor !== VerticalAnchor.None && this._topEdgeAnchor !== VerticalAnchor.None ) { const height = bottom - top; this.owner.setY( top + ((this.owner.getY() - this.owner.getDrawableY()) * height) /
Should we had `if (this.owner.getX() === this.owner.getDrawableX())` to avoid extra computations 90% of the time at the cost of the `if`?
this.owner.setHeight(bottom - top); } if (this._leftEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( left + this.owner.getX() - this.owner.getDrawableX() ); } if (this._topEdgeAnchor !== VerticalAnchor.None) { this.owner.setY( top + this.owner.getY() - this.owner.getDrawableY() ); } } // End of compatibility code else { // Resize if right and left anchors are set if ( this._rightEdgeAnchor !== HorizontalAnchor.None && this._leftEdgeAnchor !== HorizontalAnchor.None ) { const width = right - left; this.owner.setX( this.owner.getX() === this.owner.getDrawableX() ? left : left + ((this.owner.getX() - this.owner.getDrawableX()) * width) / this.owner.getWidth() ); this.owner.setWidth(width); } else { if (this._leftEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( left + this.owner.getX() - this.owner.getDrawableX() ); } if (this._rightEdgeAnchor !== HorizontalAnchor.None) { this.owner.setX( right + this.owner.getX() - this.owner.getDrawableX() - this.owner.getWidth() ); } } // Resize if top and bottom anchors are set if ( this._bottomEdgeAnchor !== VerticalAnchor.None && this._topEdgeAnchor !== VerticalAnchor.None ) { const height = bottom - top; this.owner.setY(
@@ -270,8 +270,13 @@ namespace gdjs { this._rightEdgeAnchor !== HorizontalAnchor.None && this._leftEdgeAnchor !== HorizontalAnchor.None ) { - this.owner.setWidth(right - left); - this.owner.setX(left); + const width = right - left; + this.owner.setX( + left + + ((this.owner.getX() - this.owner.getDrawableX()) * width) / + this.owner.getWidth() + );
Extensions/AnchorBehavior/anchorruntimebehavior.ts
26
TypeScript
0.571
question
137
51
51
false
Fix anchor behavior when objects has custom origin
6,970
4ian/GDevelop
10,154
JavaScript
D8H
D8H
} setCustomCenter(customCenterX, customCenterY) { this._customCenterX = customCenterX; this._customCenterY = customCenterY; this.invalidateHitboxes(); } getRendererObject() { return null; } getWidth() { return this._customWidth; } getHeight() { return this._customHeight; } setWidth(width) { this._customWidth = width; } setHeight(height) { return this._customHeight = height; } getCenterX() { if (this._customCenterX === null) return super.getCenterX(); return this._customCenterX; } getCenterY() { if (this._customCenterY === null) return super.getCenterY(); return this._customCenterY; } }; gdjs.registerObject('TestSpriteObject::TestSpriteObject', gdjs.TestSpriteRuntimeObject);
```suggestion this._customHeight = height; ```
} setCustomCenter(customCenterX, customCenterY) { this._customCenterX = customCenterX; this._customCenterY = customCenterY; this.invalidateHitboxes(); } getRendererObject() { return null; } getWidth() { return this._customWidth; } getHeight() { return this._customHeight; } setWidth(width) { this._customWidth = width; } setHeight(height) { this._customHeight = height; } getCenterX() { if (this._customCenterX === null) return super.getCenterX(); return this._customCenterX; } getCenterY() { if (this._customCenterY === null) return super.getCenterY(); return this._customCenterY; } }; gdjs.registerObject('TestSpriteObject::TestSpriteObject', gdjs.TestSpriteRuntimeObject);
@@ -62,6 +62,14 @@ return this._customHeight; } + setWidth(width) { + this._customWidth = width; + } + + setHeight(height) { + return this._customHeight = height;
GDJS/tests/tests/Extensions/testspriteruntimeobject.js
26
JavaScript
0.571
suggestion
51
41
41
false
Fix anchor behavior when objects has custom origin
6,970
4ian/GDevelop
10,154
JavaScript
4ian
D8H
* sub-expression that a given node represents. */ static const gd::String GetType(const gd::Platform &platform, const gd::ProjectScopedContainers &projectScopedContainers, const gd::String &rootType, gd::ExpressionNode& node) { gd::ExpressionTypeFinder typeFinder( platform, projectScopedContainers, rootType); node.Visit(typeFinder); return typeFinder.GetType(); } virtual ~ExpressionTypeFinder(){}; protected: ExpressionTypeFinder(const gd::Platform &platform_, const gd::ProjectScopedContainers &projectScopedContainers_, const gd::String &rootType_) : platform(platform_), projectScopedContainers(projectScopedContainers_), rootType(rootType_), type(ExpressionTypeFinder::unknownType), child(nullptr) {}; const gd::String &GetType() { return gd::ParameterMetadata::GetExpressionValueType(type); }; void OnVisitSubExpressionNode(SubExpressionNode& node) override { VisitParent(node); } void OnVisitOperatorNode(OperatorNode& node) override { VisitParent(node); } void OnVisitUnaryOperatorNode(UnaryOperatorNode& node) override { VisitParent(node); } void OnVisitNumberNode(NumberNode& node) override { type = ExpressionTypeFinder::numberType; } void OnVisitTextNode(TextNode& node) override { type = ExpressionTypeFinder::stringType; } void OnVisitVariableNode(VariableNode& node) override { VisitParent(node); } void OnVisitVariableAccessorNode(VariableAccessorNode& node) override { VisitParent(node); } void OnVisitIdentifierNode(IdentifierNode& node) override { VisitParent(node);
This doesn't change anything. It's just to navigate more easily without going through deprecated functions.
* sub-expression that a given node represents. */ static const gd::String GetType(const gd::Platform &platform, const gd::ProjectScopedContainers &projectScopedContainers, const gd::String &rootType, gd::ExpressionNode& node) { gd::ExpressionTypeFinder typeFinder( platform, projectScopedContainers, rootType); node.Visit(typeFinder); return typeFinder.GetType(); } virtual ~ExpressionTypeFinder(){}; protected: ExpressionTypeFinder(const gd::Platform &platform_, const gd::ProjectScopedContainers &projectScopedContainers_, const gd::String &rootType_) : platform(platform_), projectScopedContainers(projectScopedContainers_), rootType(rootType_), type(ExpressionTypeFinder::unknownType), child(nullptr) {}; const gd::String &GetType() { return gd::ValueTypeMetadata::GetExpressionPrimitiveValueType(type); }; void OnVisitSubExpressionNode(SubExpressionNode& node) override { VisitParent(node); } void OnVisitOperatorNode(OperatorNode& node) override { VisitParent(node); } void OnVisitUnaryOperatorNode(UnaryOperatorNode& node) override { VisitParent(node); } void OnVisitNumberNode(NumberNode& node) override { type = ExpressionTypeFinder::numberType; } void OnVisitTextNode(TextNode& node) override { type = ExpressionTypeFinder::stringType; } void OnVisitVariableNode(VariableNode& node) override { VisitParent(node); } void OnVisitVariableAccessorNode(VariableAccessorNode& node) override { VisitParent(node); } void OnVisitIdentifierNode(IdentifierNode& node) override { VisitParent(node);
@@ -72,7 +72,7 @@ class GD_CORE_API ExpressionTypeFinder : public ExpressionParser2NodeWorker { child(nullptr) {}; const gd::String &GetType() { - return gd::ParameterMetadata::GetExpressionValueType(type); + return gd::ValueTypeMetadata::GetExpressionPrimitiveValueType(type);
Core/GDCore/IDE/Events/ExpressionTypeFinder.h
26
C/C++
0.429
suggestion
107
51
51
false
Fix mouse and key parameters for event-functions
7,052
4ian/GDevelop
10,154
JavaScript
D8H
D8H
case 'RotateCamera': case 'ZoomCamera': case 'FixCamera': case 'CentreCamera': return ['smooth-camera-movement']; case 'ChangeTimeScale': return ['pause-menu']; case 'EcrireFichierExp': case 'EcrireFichierTxt': case 'LireFichierExp': case 'LireFichierTxt': case 'ReadNumberFromStorage': case 'ReadStringFromStorage': return ['intermediate-storage']; case 'PlatformBehavior::SimulateJumpKey': return ['simple-trampoline-platformer']; case 'AjoutObjConcern': case 'PickNearest': case 'AjoutHasard': return ['intermediate-object-picking']; case 'ToggleObjectVariableAsBoolean': case 'ToggleGlobalVariableAsBoolean': case 'ToggleSceneVariableAsBoolean': case 'SetBooleanObjectVariable': case 'SetBooleanVariable': return ['iIntermediate-toggle-states-with-variable']; case 'Scene': case 'PushScene': case 'PopScene': return ['intermediate-level-select-menu']; case 'Animation': case 'AnimationName': case 'ChangeAnimation': case 'ChangeAnimationName': case 'AnimatableCapability::AnimatableBehavior::Index': case 'AnimatableCapability::AnimatableBehavior::Name': case 'AnimatableCapability::AnimatableBehavior::SetIndex': case 'AnimatableCapability::AnimatableBehavior::SetName': return ['intermediate-changing-animations']; case 'PopStartedTouch': case 'MouseButtonPressed': case 'HasAnyTouchOrMouseStarted': case 'HasTouchEnded': return ['intermediate-touchscreen-controls']; default: return []; } };
```suggestion return ['intermediate-toggle-states-with-variable']; ```
case 'RotateCamera': case 'ZoomCamera': case 'FixCamera': case 'CentreCamera': return ['smooth-camera-movement']; case 'ChangeTimeScale': return ['pause-menu']; case 'EcrireFichierExp': case 'EcrireFichierTxt': case 'LireFichierExp': case 'LireFichierTxt': case 'ReadNumberFromStorage': case 'ReadStringFromStorage': return ['intermediate-storage']; case 'PlatformBehavior::SimulateJumpKey': return ['simple-trampoline-platformer']; case 'AjoutObjConcern': case 'PickNearest': case 'AjoutHasard': return ['intermediate-object-picking']; case 'ToggleObjectVariableAsBoolean': case 'ToggleGlobalVariableAsBoolean': case 'ToggleSceneVariableAsBoolean': case 'SetBooleanObjectVariable': case 'SetBooleanVariable': return ['intermediate-toggle-states-with-variable']; case 'Scene': case 'PushScene': case 'PopScene': return ['intermediate-level-select-menu']; case 'Animation': case 'AnimationName': case 'ChangeAnimation': case 'ChangeAnimationName': case 'AnimatableCapability::AnimatableBehavior::Index': case 'AnimatableCapability::AnimatableBehavior::Name': case 'AnimatableCapability::AnimatableBehavior::SetIndex': case 'AnimatableCapability::AnimatableBehavior::SetName': return ['intermediate-changing-animations']; case 'PopStartedTouch': case 'MouseButtonPressed': case 'HasAnyTouchOrMouseStarted': case 'HasTouchEnded': return ['intermediate-touchscreen-controls']; default: return []; } };
@@ -124,6 +126,8 @@ export const getInstructionTutorialIds = (type: string): Array<string> => { case 'ToggleObjectVariableAsBoolean': case 'ToggleGlobalVariableAsBoolean': case 'ToggleSceneVariableAsBoolean': + case 'SetBooleanObjectVariable': + case 'SetBooleanVariable': return ['iIntermediate-toggle-states-with-variable'];
newIDE/app/src/Utils/GDevelopServices/Tutorial.js
26
JavaScript
0.571
suggestion
78
49
49
false
Add tutorial bubbles on actions replacing deprecated ones
7,077
4ian/GDevelop
10,154
JavaScript
AlexandreSi
D8H
// @flow export default function getObjectByName( globalObjectsContainer: gdObjectsContainer | null, objectsContainer?: ?gdObjectsContainer, objectName: string ): ?gdObject { if (objectsContainer && objectsContainer.hasObjectNamed(objectName)) return objectsContainer.getObject(objectName); else if ( globalObjectsContainer && globalObjectsContainer.hasObjectNamed(objectName) ) return globalObjectsContainer.getObject(objectName); return null; } export const hasObjectWithName = ( globalObjectsContainer: gdObjectsContainer | null, objectsContainer?: ?gdObjectsContainer, objectName: string ): boolean => { if (objectsContainer && objectsContainer.hasObjectNamed(objectName)) return true; else if ( globalObjectsContainer && globalObjectsContainer.hasObjectNamed(objectName) ) return true; return false; };
`ObjectsContainersList` should be used instead. You can pass a `ProjectScopedContainersAccessor` to your component.
// @flow export default function getObjectByName( globalObjectsContainer: gdObjectsContainer | null, objectsContainer?: ?gdObjectsContainer, objectName: string ): ?gdObject { if (objectsContainer && objectsContainer.hasObjectNamed(objectName)) return objectsContainer.getObject(objectName); else if ( globalObjectsContainer && globalObjectsContainer.hasObjectNamed(objectName) ) return globalObjectsContainer.getObject(objectName); return null; }
@@ -15,3 +15,18 @@ export default function getObjectByName( return null; } + +export const hasObjectWithName = ( + globalObjectsContainer: gdObjectsContainer | null, + objectsContainer?: ?gdObjectsContainer, + objectName: string +): boolean => {
newIDE/app/src/Utils/GetObjectByName.js
23
JavaScript
0.571
suggestion
115
33
18
false
Fix instances paste from a scene to another
7,105
4ian/GDevelop
10,154
JavaScript
D8H
AlexandreSi
> <QuickPublish project={testProject.project} gameAndBuildsManager={fakeEmptyGameAndBuildsManager} isSavingProject={false} isRequiredToSaveAsNewCloudProject={() => // Indicates that the project is already saved, there will be // no need to save it as a new cloud project. false } onSaveProject={async () => {}} onlineWebExporter={onlineWebExporter} setIsNavigationDisabled={() => {}} onClose={action('onClose')} onContinueQuickCustomization={action('onContinueQuickCustomization')} onTryAnotherGame={action('onTryAnotherGame')} /> </AuthenticatedUserContext.Provider> </Template> ); }; export const AuthenticatedAndLoadingUserCloudProjects = () => { return ( <Template> <AuthenticatedUserContext.Provider value={{ ...fakeAuthenticatedUserWithNoSubscriptionAndCredits, cloudProjects: null, }} > <QuickPublish project={testProject.project} gameAndBuildsManager={fakeEmptyGameAndBuildsManager} isSavingProject={false} isRequiredToSaveAsNewCloudProject={() => true} onSaveProject={async () => {}} onlineWebExporter={onlineWebExporter} setIsNavigationDisabled={() => {}} onClose={action('onClose')} onContinueQuickCustomization={action('onContinueQuickCustomization')} onTryAnotherGame={action('onTryAnotherGame')} /> </AuthenticatedUserContext.Provider> </Template> ); }; export const AuthenticatedAndFails = () => { return ( <Template>
I feel like this comment should be next to the props type in QuickPublish. I was not sure what it meant before reading this comment
onClose={action('onClose')} onContinueQuickCustomization={action('onContinueQuickCustomization')} onTryAnotherGame={action('onTryAnotherGame')} /> </AuthenticatedUserContext.Provider> </Template> ); }; export const AuthenticatedWithCloudProjectsMaximumReachedButSavedAlready = () => { return ( <Template> <AuthenticatedUserContext.Provider value={{ ...fakeAuthenticatedUserWithNoSubscriptionAndCredits, // We have more projects than the maximum allowed, but the project is already saved // so there are no problems. cloudProjects: tenCloudProjects, }} > <QuickPublish project={testProject.project} gameAndBuildsManager={fakeGameAndBuildsManager} isSavingProject={false} isRequiredToSaveAsNewCloudProject={() => // Indicates that the project is already saved, there will be // no need to save it as a new cloud project. false } onSaveProject={async () => {}} onlineWebExporter={onlineWebExporter} setIsNavigationDisabled={() => {}} onClose={action('onClose')} onContinueQuickCustomization={action('onContinueQuickCustomization')} onTryAnotherGame={action('onTryAnotherGame')} /> </AuthenticatedUserContext.Provider> </Template> ); }; export const AuthenticatedAndLoadingUserCloudProjects = () => { return ( <Template> <AuthenticatedUserContext.Provider value={{ ...fakeAuthenticatedUserWithNoSubscriptionAndCredits, cloudProjects: null, }} > <QuickPublish
@@ -119,6 +124,39 @@ export const AuthenticatedWithTooManyCloudProjects = () => { </Template> ); }; + +export const AuthenticatedWithCloudProjectsMaximumReachedButSavedAlready = () => { + return ( + <Template> + <AuthenticatedUserContext.Provider + value={{ + ...fakeAuthenticatedUserWithNoSubscriptionAndCredits, + // We have more projects than the maximum allowed, but the project is already saved + // so there are no problems. + cloudProjects: tenCloudProjects, + }} + > + <QuickPublish + project={testProject.project} + gameAndBuildsManager={fakeEmptyGameAndBuildsManager} + isSavingProject={false} + isRequiredToSaveAsNewCloudProject={() => + // Indicates that the project is already saved, there will be
newIDE/app/src/stories/componentStories/QuickCustomization/QuickPublish.stories.js
26
JavaScript
0.571
suggestion
131
51
51
false
Fix issues when reworking a quick customization project
7,109
4ian/GDevelop
10,154
JavaScript
AlexandreSi
4ian
if (!selectedItem) return; if (selectedItem.content.isDescendantOf(item.content)) { selectObjectFolderOrObjectWithContext(null); } }, [selectObjectFolderOrObjectWithContext, selectedItems] ); // Force List component to be mounted again if project or objectsContainer // has been changed. Avoid accessing to invalid objects that could // crash the app. const listKey = project.ptr + ';' + objectsContainer.ptr; const initiallyOpenedNodeIds = [ globalObjectsRootFolder && globalObjectsRootFolder.getChildrenCount() > 0 ? globalObjectsRootFolderId : null, sceneObjectsRootFolderId, ].filter(Boolean); const arrowKeyNavigationProps = React.useMemo( () => ({ onGetItemInside: (item: TreeViewItem): ?TreeViewItem => { if (item.isPlaceholder || item.isRoot) return null; const objectFolderOrObject = item.content.getObjectFolderOrObject(); if (!objectFolderOrObject) return null; if (!objectFolderOrObject.isFolder()) return null; else { if (objectFolderOrObject.getChildrenCount() === 0) return null; return createTreeViewItem({ objectFolderOrObject: objectFolderOrObject.getChildAt(0), isGlobal: item.content.isGlobal(), objectFolderTreeViewItemProps, objectTreeViewItemProps, }); } }, onGetItemOutside: (item: TreeViewItem): ?TreeViewItem => { if (item.isPlaceholder || item.isRoot) return null; const objectFolderOrObject = item.content.getObjectFolderOrObject(); if (!objectFolderOrObject) return null; const parent = objectFolderOrObject.getParent(); if (parent.isRootFolder()) return null; return createTreeViewItem({ objectFolderOrObject: parent, isGlobal: item.content.isGlobal(), objectFolderTreeViewItemProps, objectTreeViewItemProps, }); }, }), [objectFolderTreeViewItemProps, objectTreeViewItemProps]
Removing the column, you removed the margin, you should maybe remove the `noMargin` in the child Column
* does not stay selected and not visible to the user. */ const onCollapseItem = React.useCallback( (item: TreeViewItem) => { if (!selectedItems || selectedItems.length !== 1) return; const selectedItem = selectedItems[0]; if (!selectedItem) return; if (selectedItem.content.isDescendantOf(item.content)) { selectObjectFolderOrObjectWithContext(null); } }, [selectObjectFolderOrObjectWithContext, selectedItems] ); // Force List component to be mounted again if project or objectsContainer // has been changed. Avoid accessing to invalid objects that could // crash the app. const listKey = project.ptr + ';' + objectsContainer.ptr; const initiallyOpenedNodeIds = [ globalObjectsRootFolder && globalObjectsRootFolder.getChildrenCount() > 0 ? globalObjectsRootFolderId : null, sceneObjectsRootFolderId, ].filter(Boolean); const arrowKeyNavigationProps = React.useMemo( () => ({ onGetItemInside: (item: TreeViewItem): ?TreeViewItem => { if (item.isPlaceholder || item.isRoot) return null; const objectFolderOrObject = item.content.getObjectFolderOrObject(); if (!objectFolderOrObject) return null; if (!objectFolderOrObject.isFolder()) return null; else { if (objectFolderOrObject.getChildrenCount() === 0) return null; return createTreeViewItem({ objectFolderOrObject: objectFolderOrObject.getChildAt(0), isGlobal: item.content.isGlobal(), objectFolderTreeViewItemProps, objectTreeViewItemProps, }); } }, onGetItemOutside: (item: TreeViewItem): ?TreeViewItem => { if (item.isPlaceholder || item.isRoot) return null; const objectFolderOrObject = item.content.getObjectFolderOrObject(); if (!objectFolderOrObject) return null; const parent = objectFolderOrObject.getParent(); if (parent.isRootFolder()) return null; return createTreeViewItem({ objectFolderOrObject: parent, isGlobal: item.content.isGlobal(),
@@ -1363,28 +1393,16 @@ const ObjectsList = React.forwardRef<Props, ObjectsListInterface>( return ( <Background maxWidth> - <Column>
newIDE/app/src/ObjectsList/index.js
26
JavaScript
0.571
suggestion
103
51
51
false
Replace the "add folder" button by a drop-down menu action
7,117
4ian/GDevelop
10,154
JavaScript
AlexandreSi
D8H
this._injectExternalLayout ); this._watermark.displayAtStartup(); //Uncomment to profile the first x frames of the game. // var x = 500; // var startTime = Date.now(); // console.profile("Stepping for " + x + " frames") // for(var i = 0; i < x; ++i) { // this._sceneStack.step(16); // } // console.profileEnd(); // var time = Date.now() - startTime; // logger.log("Took", time, "ms"); // return; this._setupGameVisibilityEvents(); // The standard game loop let accumulatedElapsedTime = 0; this._hasJustResumed = false; this._renderer.startGameLoop((lastCallElapsedTime) => { try { if (this._isDisposed) { return false; } if (this._paused) { return true; } // Skip the frame if we rendering frames too fast accumulatedElapsedTime += lastCallElapsedTime; if ( this._maxFPS > 0 && 1000.0 / accumulatedElapsedTime > this._maxFPS + 7 ) { // Only skip frame if the framerate is 7 frames above the maximum framerate. // Most browser/engines will try to run at slightly more than 60 frames per second. // If game is set to have a maximum FPS to 60, then one out of two frames will be dropped. // Hence, we use a 7 frames margin to ensure that we're not skipping frames too much. return true; } const elapsedTime = accumulatedElapsedTime; accumulatedElapsedTime = 0; // Manage resize events. if (this._notifyScenesForGameResolutionResize) { this._sceneStack.onGameResolutionResized(); this._notifyScenesForGameResolutionResize = false; }
This check should not exist, you should stop gameLoop before disposing of the renderer.
? firstSceneName : // There is always at least a scene this.getSceneAndExtensionsData()!.sceneData.name; } /** * Start the game loop, to be called once assets are loaded. */ startGameLoop() { this._throwIfDisposed(); try { if (!this.hasScene()) { logger.error('The game has no scene.'); return; } this._forceGameResolutionUpdate(); // Load the first scene this._sceneStack.push( this._getFirstSceneName(), this._injectExternalLayout ); this._watermark.displayAtStartup(); //Uncomment to profile the first x frames of the game. // var x = 500; // var startTime = Date.now(); // console.profile("Stepping for " + x + " frames") // for(var i = 0; i < x; ++i) { // this._sceneStack.step(16); // } // console.profileEnd(); // var time = Date.now() - startTime; // logger.log("Took", time, "ms"); // return; this._setupGameVisibilityEvents(); // The standard game loop let accumulatedElapsedTime = 0; this._hasJustResumed = false; this._renderer.startGameLoop((lastCallElapsedTime) => { try { if (this._paused) { return true; } // Skip the frame if we rendering frames too fast accumulatedElapsedTime += lastCallElapsedTime; if ( this._maxFPS > 0 &&
@@ -888,6 +889,10 @@ namespace gdjs { this._hasJustResumed = false; this._renderer.startGameLoop((lastCallElapsedTime) => { try { + if (this._isDisposed) { + return false; + }
GDJS/Runtime/runtimegame.ts
26
TypeScript
0.286
suggestion
87
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
? !!navigator.maxTouchPoints && navigator.maxTouchPoints > 2 : false, supportedCompressionMethods: getSupportedCompressionMethods(), }; }; _setupGameVisibilityEvents() { if (typeof navigator !== 'undefined' && typeof document !== 'undefined') { document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { this._hasJustResumed = true; } }); window.addEventListener( 'resume', () => { this._hasJustResumed = true; }, false ); } } /** * Register a new session for the game, and set up listeners to follow the session * time. */ _setupSessionMetrics() { if (this._isDisposed) { return; } if (this._sessionMetricsInitialized) { return; } if (this._disableMetrics) { return; } if (this.isPreview()) { return; } if (typeof fetch === 'undefined') { return; } if (!this._data.properties.projectUuid) { return; } const baseUrl = 'https://api.gdevelop-app.com/analytics'; this._playerId = this._makePlayerUuid(); /** * The duration that is already sent to the service
Remove this check, and clear the interval instead.
enableMetrics(enable: boolean): void { this._disableMetrics = !enable; if (enable) { this._setupSessionMetrics(); } } /** * Helper function to get information about the platform running the game. */ getPlatformInfo = () => { return { // @ts-ignore isCordova: !!window.cordova, devicePlatform: // @ts-ignore typeof device !== 'undefined' ? device.platform || '' : '', navigatorPlatform: typeof navigator !== 'undefined' ? navigator.platform : '', hasTouch: typeof navigator !== 'undefined' ? !!navigator.maxTouchPoints && navigator.maxTouchPoints > 2 : false, supportedCompressionMethods: getSupportedCompressionMethods(), }; }; _setupGameVisibilityEvents() { if (typeof navigator !== 'undefined' && typeof document !== 'undefined') { document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { this._hasJustResumed = true; } }); window.addEventListener( 'resume', () => { this._hasJustResumed = true; }, false ); } } /** * Register a new session for the game, and set up listeners to follow the session * time. */ _setupSessionMetrics() { if (this._sessionMetricsInitialized) { return;
@@ -989,6 +1005,10 @@ namespace gdjs { * time. */ _setupSessionMetrics() { + if (this._isDisposed) { + return; + }
GDJS/Runtime/runtimegame.ts
26
TypeScript
0.286
refactor
50
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
} catch (e) { if (this._debuggerClient) this._debuggerClient.onUncaughtException(e); throw e; } }); setTimeout(() => { this._setupSessionMetrics(); }, 4000); } catch (e) { if (this._debuggerClient) this._debuggerClient.onUncaughtException(e); throw e; } } dispose(): void { if (this._isDisposed) { return; } this._isDisposed = true; this._sceneStack.dispose(); this._renderer.dispose(); this._resourcesLoader.dispose(); } /** * Set if the session should be registered. */ enableMetrics(enable: boolean): void { this._disableMetrics = !enable; if (enable) { this._setupSessionMetrics(); } } /** * Helper function to get information about the platform running the game. */ getPlatformInfo = () => { return { // @ts-ignore isCordova: !!window.cordova, devicePlatform: // @ts-ignore typeof device !== 'undefined' ? device.platform || '' : '', navigatorPlatform: typeof navigator !== 'undefined' ? navigator.platform : '', hasTouch:
What is the aim of this check? Calling the dispose method once is the responsibility of whoever created the game.
const elapsedTime = accumulatedElapsedTime; accumulatedElapsedTime = 0; // Manage resize events. if (this._notifyScenesForGameResolutionResize) { this._sceneStack.onGameResolutionResized(); this._notifyScenesForGameResolutionResize = false; } // Render and step the scene. if (this._sceneStack.step(elapsedTime)) { this.getInputManager().onFrameEnded(); this._hasJustResumed = false; return true; } return false; } catch (e) { if (this._debuggerClient) this._debuggerClient.onUncaughtException(e); throw e; } }); setTimeout(() => { this._setupSessionMetrics(); }, 4000); if (this._captureManager) { this._captureManager.setupCaptureOptions(this._isPreview); } } catch (e) { if (this._debuggerClient) this._debuggerClient.onUncaughtException(e); throw e; } } /** * Stop game loop, unload all scenes, dispose renderer and resources. * After calling this method, the RuntimeGame should not be used anymore. */ dispose(): void { this._renderer.stopGameLoop(); this._sceneStack.dispose(); this._renderer.dispose(); this._resourcesLoader.dispose(); this._wasDisposed = true; } /** * Set if the session should be registered.
@@ -937,6 +942,17 @@ namespace gdjs { } } + dispose(): void { + if (this._isDisposed) { + return; + } + + this._isDisposed = true;
GDJS/Runtime/runtimegame.ts
26
TypeScript
0.357
question
113
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
newScene.networkId = sceneSyncData.networkId; } hasMadeChangeToStack = true; // Continue to the next scene in the stack received from the host. continue; } // The scene is in the stack and has the right networkId. // Nothing to do, just continue to the next scene in the stack received from the host. } // Pop any scene not on the host. // In the future, we could avoid to pop scenes if they are not set to be synchronized. if (this._stack.length > sceneStackSyncData.length) { const popCount = this._stack.length - sceneStackSyncData.length; this.pop(popCount); hasMadeChangeToStack = true; } return hasMadeChangeToStack; } dispose(): void { for (let i = 0; i < this._stack.length; ++i) { this._stack[i].unloadScene(); } this._stack.length = 0; } } }
Use `for...of` or `forEach` because there is no logic with `i` involved.
debugLogger.info( `Scene at position ${i} and name ${sceneAtThisPositionInOurStack.getName()} has a different networkId ${ sceneAtThisPositionInOurStack.networkId } than the expected ${sceneSyncData.networkId}, replacing.` ); // The scene is in the stack but has a different networkId // This can happen if the host has restarted the scene // We can't just update the networkId of the scene in the stack // We need to replace it with a new scene const newScene = this.replace( sceneSyncData.name, false // Don't clear the stack ); if (newScene) { newScene.networkId = sceneSyncData.networkId; } hasMadeChangeToStack = true; // Continue to the next scene in the stack received from the host. continue; } // The scene is in the stack and has the right networkId. // Nothing to do, just continue to the next scene in the stack received from the host. } // Pop any scene not on the host. // In the future, we could avoid to pop scenes if they are not set to be synchronized. if (this._stack.length > sceneStackSyncData.length) { const popCount = this._stack.length - sceneStackSyncData.length; this.pop(popCount); hasMadeChangeToStack = true; } return hasMadeChangeToStack; } /** * Unload all the scenes and clear the stack. */ dispose(): void { for (const item of this._stack) { item.unloadScene(); } this._stack.length = 0; this._wasDisposed = true; } private _throwIfDisposed(): void { if (this._wasDisposed) { throw 'The scene stack has been disposed and should not be used anymore.';
@@ -354,5 +354,12 @@ namespace gdjs { return hasMadeChangeToStack; } + + dispose(): void { + for (let i = 0; i < this._stack.length; ++i) { + this._stack[i].unloadScene(); + }
GDJS/Runtime/scenestack.ts
26
TypeScript
0.429
suggestion
72
31
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
logger.error('Window closing failed. See error:', error); } } } else { if ( typeof navigator !== 'undefined' && // @ts-ignore navigator.app && // @ts-ignore navigator.app.exitApp ) { // @ts-ignore navigator.app.exitApp(); } } // HTML5 games on mobile/browsers don't have a way to close their window/page. } dispose() { this._pixiRenderer?.destroy(true); this._pixiRenderer = null; this._threeRenderer = null; this._gameCanvas = null; this._domElementsContainer = null; } /** * Get the canvas DOM element. */ getCanvas(): HTMLCanvasElement | null { return this._gameCanvas; } /** * Check if the device supports WebGL. * @returns true if WebGL is supported */ isWebGLSupported(): boolean { return ( !!this._pixiRenderer && this._pixiRenderer.type === PIXI.RENDERER_TYPE.WEBGL ); } /** * Get the electron module, if running as a electron renderer process. */ getElectron() { if (typeof require === 'function') { return require('electron'); }
Call `this._threeRenderer?.dispose();`.
} /** * Close the game, if applicable. */ stopGame() { // Try to detect the environment to use the most adapted // way of closing the app const remote = this.getElectronRemote(); if (remote) { const browserWindow = remote.getCurrentWindow(); if (browserWindow) { try { browserWindow.close(); } catch (error) { logger.error('Window closing failed. See error:', error); } } } else { if ( typeof navigator !== 'undefined' && // @ts-ignore navigator.app && // @ts-ignore navigator.app.exitApp ) { // @ts-ignore navigator.app.exitApp(); } } // HTML5 games on mobile/browsers don't have a way to close their window/page. } /** * Dispose PixiRenderer, ThreeRenderer and remove canvas from DOM. */ dispose() { this._pixiRenderer?.destroy(true); this._threeRenderer?.dispose(); this._pixiRenderer = null; this._threeRenderer = null; this._gameCanvas = null; this._domElementsContainer = null; this._wasDisposed = true; } /** * Get the canvas DOM element. */ getCanvas(): HTMLCanvasElement | null { return this._gameCanvas;
@@ -924,6 +924,14 @@ namespace gdjs { // HTML5 games on mobile/browsers don't have a way to close their window/page. } + dispose() { + this._pixiRenderer?.destroy(true); + this._pixiRenderer = null; + this._threeRenderer = null;
GDJS/Runtime/pixi-renderers/runtimegame-pixi-renderer.ts
26
TypeScript
0.214
suggestion
39
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
} } } else { if ( typeof navigator !== 'undefined' && // @ts-ignore navigator.app && // @ts-ignore navigator.app.exitApp ) { // @ts-ignore navigator.app.exitApp(); } } // HTML5 games on mobile/browsers don't have a way to close their window/page. } dispose() { this._pixiRenderer?.destroy(true); this._pixiRenderer = null; this._threeRenderer = null; this._gameCanvas = null; this._domElementsContainer = null; } /** * Get the canvas DOM element. */ getCanvas(): HTMLCanvasElement | null { return this._gameCanvas; } /** * Check if the device supports WebGL. * @returns true if WebGL is supported */ isWebGLSupported(): boolean { return ( !!this._pixiRenderer && this._pixiRenderer.type === PIXI.RENDERER_TYPE.WEBGL ); } /** * Get the electron module, if running as a electron renderer process. */ getElectron() { if (typeof require === 'function') { return require('electron'); } return null;
Remove gameCanvas and domElementsContainer from the parent element.
/** * Close the game, if applicable. */ stopGame() { // Try to detect the environment to use the most adapted // way of closing the app const remote = this.getElectronRemote(); if (remote) { const browserWindow = remote.getCurrentWindow(); if (browserWindow) { try { browserWindow.close(); } catch (error) { logger.error('Window closing failed. See error:', error); } } } else { if ( typeof navigator !== 'undefined' && // @ts-ignore navigator.app && // @ts-ignore navigator.app.exitApp ) { // @ts-ignore navigator.app.exitApp(); } } // HTML5 games on mobile/browsers don't have a way to close their window/page. } /** * Dispose PixiRenderer, ThreeRenderer and remove canvas from DOM. */ dispose() { this._pixiRenderer?.destroy(true); this._threeRenderer?.dispose(); this._pixiRenderer = null; this._threeRenderer = null; this._gameCanvas = null; this._domElementsContainer = null; this._wasDisposed = true; } /** * Get the canvas DOM element. */ getCanvas(): HTMLCanvasElement | null { return this._gameCanvas; }
@@ -924,6 +924,14 @@ namespace gdjs { // HTML5 games on mobile/browsers don't have a way to close their window/page. } + dispose() { + this._pixiRenderer?.destroy(true); + this._pixiRenderer = null; + this._threeRenderer = null; + this._gameCanvas = null;
GDJS/Runtime/pixi-renderers/runtimegame-pixi-renderer.ts
26
TypeScript
0.286
suggestion
67
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
/* * GDevelop JS Platform * Copyright 2013-2023 Florian Rival (Florian.Rival@gmail.com). All rights reserved. * This project is released under the MIT License. */ namespace gdjs { /** * A resource managers that download and remember downloaded content for one * kind of resource. */ export interface ResourceManager { /** * Load the specified resource. * * This method will be run during the game. It should only do light tasks * like file downloading. */ loadResource(resourceName: string): Promise<void>; /** * Process the specified resource. * * This method will only be run while loading screen is shown. It can do * heavy tasks like parsing data. */ processResource(resourceName: string): Promise<void>; /** * Return the kind of resources handled by this manager. */ getResourceKinds(): Array<ResourceKind>; dispose(): void; } }
Please, add jsdoc description.
/** * Load the specified resource. * * This method will be run during the game. It should only do light tasks * like file downloading. */ loadResource(resourceName: string): Promise<void>; /** * Process the specified resource. * * This method will only be run while loading screen is shown. It can do * heavy tasks like parsing data. */ processResource(resourceName: string): Promise<void>; /** * Return the kind of resources handled by this manager. */ getResourceKinds(): Array<ResourceKind>; /** * Should clear all resources, data, loaders stored by this manager. * Using the manager after calling this method is undefined behavior. */ dispose(): void; } }
@@ -29,5 +29,7 @@ namespace gdjs { * Return the kind of resources handled by this manager. */ getResourceKinds(): Array<ResourceKind>; + + dispose(): void;
GDJS/Runtime/ResourceManager.ts
26
TypeScript
0.071
suggestion
30
36
29
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
xhr.send(); } /** * Check if the given json resource was loaded (preloaded or loaded with `loadJson`). * @param resourceName The name of the json resource. * @returns true if the content of the json resource is loaded. false otherwise. */ isJsonLoaded(resourceName: string): boolean { return !!this._loadedJsons.getFromName(resourceName); } /** * Get the object for the given resource that is already loaded (preloaded or loaded with `loadJson`). * If the resource is not loaded, `null` will be returned. * * @param resourceName The name of the json resource. * @returns the content of the json resource, if loaded. `null` otherwise. */ getLoadedJson(resourceName: string): Object | null { return this._loadedJsons.getFromName(resourceName) || null; } dispose(): void { this._loadedJsons.clear(); this._callbacks.clear } } }
Do not forget to call the function.
xhr.send(); } /** * Check if the given json resource was loaded (preloaded or loaded with `loadJson`). * @param resourceName The name of the json resource. * @returns true if the content of the json resource is loaded. false otherwise. */ isJsonLoaded(resourceName: string): boolean { return !!this._loadedJsons.getFromName(resourceName); } /** * Get the object for the given resource that is already loaded (preloaded or loaded with `loadJson`). * If the resource is not loaded, `null` will be returned. * * @param resourceName The name of the json resource. * @returns the content of the json resource, if loaded. `null` otherwise. */ getLoadedJson(resourceName: string): Object | null { return this._loadedJsons.getFromName(resourceName) || null; } /** * To be called when the game is disposed. * Clear the JSONs loaded in this manager. */ dispose(): void { this._loadedJsons.clear(); this._callbacks.clear(); } } }
@@ -200,5 +200,10 @@ namespace gdjs { getLoadedJson(resourceName: string): Object | null { return this._loadedJsons.getFromName(resourceName) || null; } + + dispose(): void { + this._loadedJsons.clear(); + this._callbacks.clear
GDJS/Runtime/jsonmanager.ts
26
TypeScript
0.071
suggestion
35
30
34
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
'include' : // For other resources, use "same-origin" as done by default by fetch. 'same-origin', } ); const fontData = await response.text(); this._loadedFontsData.set(resource, fontData); } catch (error) { logger.error( "Can't fetch the bitmap font file " + resource.file + ', error: ' + error ); } } dispose(): void { for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) { PIXI.BitmapFont.uninstall(bitmapFontInstallKey); } for (const bitmapFontInstallKey of this._pixiBitmapFontsToUninstall) { PIXI.BitmapFont.uninstall(bitmapFontInstallKey); } this._pixiBitmapFontsInUse = {}; this._pixiBitmapFontsToUninstall = []; this._loadedFontsData.clear(); } } // Register the class to let the engine use it. export const BitmapFontManager = gdjs.PixiBitmapFontManager; export type BitmapFontManager = gdjs.PixiBitmapFontManager; }
Might be: `this._pixiBitmapFontsToUninstall.length = 0;`
'include' : // For other resources, use "same-origin" as done by default by fetch. 'same-origin', } ); const fontData = await response.text(); this._loadedFontsData.set(resource, fontData); } catch (error) { logger.error( "Can't fetch the bitmap font file " + resource.file + ', error: ' + error ); } } /** * To be called when the game is disposed. * Uninstall all the fonts from memory and clear cache of loaded fonts. */ dispose(): void { for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) { PIXI.BitmapFont.uninstall(bitmapFontInstallKey); } for (const bitmapFontInstallKey of this._pixiBitmapFontsToUninstall) { PIXI.BitmapFont.uninstall(bitmapFontInstallKey); } this._pixiBitmapFontsInUse = {}; this._pixiBitmapFontsToUninstall.length = 0; this._loadedFontsData.clear(); } } // Register the class to let the engine use it. export const BitmapFontManager = gdjs.PixiBitmapFontManager; export type BitmapFontManager = gdjs.PixiBitmapFontManager; }
@@ -289,6 +289,18 @@ namespace gdjs { ); } } + + dispose(): void { + for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) { + PIXI.BitmapFont.uninstall(bitmapFontInstallKey); + } + for (const bitmapFontInstallKey of this._pixiBitmapFontsToUninstall) { + PIXI.BitmapFont.uninstall(bitmapFontInstallKey); + } + this._pixiBitmapFontsInUse = {}; + this._pixiBitmapFontsToUninstall = [];
GDJS/Runtime/pixi-renderers/pixi-bitmapfont-manager.ts
26
TypeScript
0.357
suggestion
56
35
41
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
this._loadedTextures.clear(); const threeTextures: THREE.Texture[] = []; this._loadedThreeTextures.values(threeTextures); this._loadedThreeTextures.clear(); for (const threeTexture of threeTextures) { threeTexture.dispose(); } const threeMaterials: THREE.Material[] = []; this._loadedThreeMaterials.values(threeMaterials); this._loadedThreeMaterials.clear(); for (const threeMaterial of threeMaterials) { threeMaterial.dispose(); } const diskPixiTextures = [...this._diskTextures.values()]; this._diskTextures.clear(); for (const pixiTexture of diskPixiTextures) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } const rectanglePixiTextures = [...this._rectangleTextures.values()]; this._rectangleTextures.clear(); for (const pixiTexture of rectanglePixiTextures) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } const scaledPixiTextures = [...this._scaledTextures.values()]; this._scaledTextures.clear(); for (const pixiTexture of scaledPixiTextures) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } } } //Register the class to let the engine use it. export const ImageManager = gdjs.PixiImageManager; export type ImageManager = gdjs.PixiImageManager;
Will this work? ``` for (const pixiTexture of this._diskTextures.values()) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } this._diskTextures.clear(); ``` Minus new array creation.
* To be called when the game is disposed. * Clear caches of loaded textures and materials. */ dispose(): void { this._loadedTextures.clear(); const threeTextures: THREE.Texture[] = []; this._loadedThreeTextures.values(threeTextures); this._loadedThreeTextures.clear(); for (const threeTexture of threeTextures) { threeTexture.dispose(); } const threeMaterials: THREE.Material[] = []; this._loadedThreeMaterials.values(threeMaterials); this._loadedThreeMaterials.clear(); for (const threeMaterial of threeMaterials) { threeMaterial.dispose(); } for (const pixiTexture of this._diskTextures.values()) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } this._diskTextures.clear(); for (const pixiTexture of this._rectangleTextures.values()) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } this._rectangleTextures.clear(); for (const pixiTexture of this._scaledTextures.values()) { if (pixiTexture.destroyed) { continue; } pixiTexture.destroy(); } this._scaledTextures.clear(); } } //Register the class to let the engine use it. export const ImageManager = gdjs.PixiImageManager;
@@ -463,6 +463,54 @@ namespace gdjs { } return particleTexture; } + + dispose(): void { + this._loadedTextures.clear(); + + const threeTextures: THREE.Texture[] = []; + this._loadedThreeTextures.values(threeTextures); + this._loadedThreeTextures.clear(); + for (const threeTexture of threeTextures) { + threeTexture.dispose(); + } + + const threeMaterials: THREE.Material[] = []; + this._loadedThreeMaterials.values(threeMaterials); + this._loadedThreeMaterials.clear(); + for (const threeMaterial of threeMaterials) { + threeMaterial.dispose(); + } + + const diskPixiTextures = [...this._diskTextures.values()]; + this._diskTextures.clear(); + for (const pixiTexture of diskPixiTextures) { + if (pixiTexture.destroyed) { + continue; + } + + pixiTexture.destroy(); + }
GDJS/Runtime/pixi-renderers/pixi-image-manager.ts
26
TypeScript
0.786
suggestion
262
51
51
false
Add dispose method to Runtimegame
7,118
4ian/GDevelop
10,154
JavaScript
malec-palec
danvervlad
/** * @brief Return the scene variables of the current scene or the current * extension. It allows legacy "scenevar" parameters to accept extension * variables. */ const gd::VariablesContainer &GetLegacySceneVariables() const { return legacySceneVariables; }; const gd::PropertiesContainersList &GetPropertiesContainersList() const { return propertiesContainersList; }; const std::vector<const ParameterMetadataContainer *> &GetParametersVectorsList() const { return parametersVectorsList; }; /** Do not use - should be private but accessible to let Emscripten create a * temporary. */ ProjectScopedContainers(){}; private: gd::ObjectsContainersList objectsContainersList; gd::VariablesContainersList variablesContainersList; gd::VariablesContainer legacyGlobalVariables; gd::VariablesContainer legacySceneVariables; gd::PropertiesContainersList propertiesContainersList; std::vector<const ParameterMetadataContainer *> parametersVectorsList; }; } // namespace gd
These are not references/pointers but values, meaning that ProjectScopedContainers moved from "I'm just a set of lists pointing to things in your project" to "I actually hold stuff, and you will have a bad time if you destroyed me and kept references to things".
/** * @brief Return the scene variables of the current scene or the current * extension. It allows legacy "scenevar" parameters to accept extension * variables. */ const gd::VariablesContainer *GetLegacySceneVariables() const { return legacySceneVariables; }; const gd::PropertiesContainersList &GetPropertiesContainersList() const { return propertiesContainersList; }; const std::vector<const ParameterMetadataContainer *> &GetParametersVectorsList() const { return parametersVectorsList; }; /** Do not use - should be private but accessible to let Emscripten create a * temporary. */ ProjectScopedContainers(){}; private: gd::ObjectsContainersList objectsContainersList; gd::VariablesContainersList variablesContainersList; const gd::VariablesContainer *legacyGlobalVariables; const gd::VariablesContainer *legacySceneVariables; gd::PropertiesContainersList propertiesContainersList; std::vector<const ParameterMetadataContainer *> parametersVectorsList; }; } // namespace gd
@@ -236,6 +230,8 @@ class ProjectScopedContainers { private: gd::ObjectsContainersList objectsContainersList; gd::VariablesContainersList variablesContainersList; + gd::VariablesContainer legacyGlobalVariables; + gd::VariablesContainer legacySceneVariables;
Core/GDCore/Project/ProjectScopedContainers.h
26
C/C++
0.5
suggestion
262
31
31
false
Allow legacy scene variable parameters to use extension variables
7,121
4ian/GDevelop
10,154
JavaScript
4ian
D8H
auto &initialInstances = eventsBasedObject.GetInitialInstances(); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer(""); initialInstances.InsertNewInitialInstance().SetLayer(""); initialInstances.InsertNewInitialInstance().SetLayer("My other layer"); REQUIRE(initialInstances.GetInstancesCount() == 6); REQUIRE(initialInstances.GetLayerInstancesCount("My layer") == 3); gd::WholeProjectRefactorer::MergeLayersInEventsBasedObject( eventsBasedObject, "My layer", ""); // No instance was removed. REQUIRE(initialInstances.GetInstancesCount() == 6); // No instance remain in "My layer". REQUIRE(initialInstances.GetLayerInstancesCount("My layer") == 0); // Other layers from the same layout are untouched. REQUIRE(initialInstances.GetLayerInstancesCount("My other layer") == 1); } SECTION("Can find and rename leaderboards in a project") { gd::Project project; gd::Platform platform; SetupProjectWithDummyPlatform(project, platform); auto &layout = project.InsertNewLayout("My layout", 0); gd::StandardEvent &event = dynamic_cast<gd::StandardEvent &>( layout.GetEvents().InsertNewEvent(project, "BuiltinCommonInstructions::Standard")); gd::Instruction action; action.SetType("MyExtension::DisplayLeaderboard"); action.SetParametersCount(1); action.SetParameter(0, gd::Expression("\"12345678-9abc-def0-1234-56789abcdef0\"")); event.GetActions().Insert(action); std::set<gd::String> allLeaderboardIds = gd::WholeProjectRefactorer::FindAllLeaderboardIds(project); REQUIRE(allLeaderboardIds.size() == 1); REQUIRE(allLeaderboardIds.count("12345678-9abc-def0-1234-56789abcdef0") == 1); std::map<gd::String, gd::String> leaderboardIdMap; leaderboardIdMap["12345678-9abc-def0-1234-56789abcdef0"] = "87654321-9abc-def0-1234-56789abcdef0"; gd::WholeProjectRefactorer::RenameLeaderboards(project, leaderboardIdMap); REQUIRE(GetEventFirstActionFirstParameterString(layout.GetEvents().GetEvent(0)) == "\"87654321-9abc-def0-1234-56789abcdef0\"");
The previous description better fit what the test actually covers.
auto &initialInstances = eventsBasedObject.GetInitialInstances(); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer("My layer"); initialInstances.InsertNewInitialInstance().SetLayer(""); initialInstances.InsertNewInitialInstance().SetLayer(""); initialInstances.InsertNewInitialInstance().SetLayer("My other layer"); REQUIRE(initialInstances.GetInstancesCount() == 6); REQUIRE(initialInstances.GetLayerInstancesCount("My layer") == 3); gd::WholeProjectRefactorer::MergeLayersInEventsBasedObject( eventsBasedObject, "My layer", ""); // No instance was removed. REQUIRE(initialInstances.GetInstancesCount() == 6); // No instance remain in "My layer". REQUIRE(initialInstances.GetLayerInstancesCount("My layer") == 0); // Other layers from the same layout are untouched. REQUIRE(initialInstances.GetLayerInstancesCount("My other layer") == 1); } // TODO: ideally, a test should also cover objects having `leaderboardId` as property. SECTION("Can rename a leaderboard in scene events") { gd::Project project; gd::Platform platform; SetupProjectWithDummyPlatform(project, platform); auto &layout = project.InsertNewLayout("My layout", 0); gd::StandardEvent &event = dynamic_cast<gd::StandardEvent &>( layout.GetEvents().InsertNewEvent(project, "BuiltinCommonInstructions::Standard")); gd::Instruction action; action.SetType("MyExtension::DisplayLeaderboard"); action.SetParametersCount(1); action.SetParameter(0, gd::Expression("\"12345678-9abc-def0-1234-56789abcdef0\"")); event.GetActions().Insert(action); std::set<gd::String> allLeaderboardIds = gd::WholeProjectRefactorer::FindAllLeaderboardIds(project); REQUIRE(allLeaderboardIds.size() == 1); REQUIRE(allLeaderboardIds.count("12345678-9abc-def0-1234-56789abcdef0") == 1); std::map<gd::String, gd::String> leaderboardIdMap; leaderboardIdMap["12345678-9abc-def0-1234-56789abcdef0"] = "87654321-9abc-def0-1234-56789abcdef0"; gd::WholeProjectRefactorer::RenameLeaderboards(project, leaderboardIdMap); REQUIRE(GetEventFirstActionFirstParameterString(layout.GetEvents().GetEvent(0)) ==
@@ -4452,13 +4452,13 @@ TEST_CASE("MergeLayers", "[common]") { REQUIRE(initialInstances.GetLayerInstancesCount("My other layer") == 1); } - SECTION("Can rename a leaderboard in scene events") { + SECTION("Can find and rename leaderboards in a project") {
Core/tests/WholeProjectRefactorer.cpp
26
C++
0.286
suggestion
66
51
51
false
Fix leaderboards not properly replaced in projects using them in custom objects
7,131
4ian/GDevelop
10,154
JavaScript
D8H
4ian
} onInstructionTypeChanged={onInstructionTypeChanged} /> {editorOpen && project && !objectGroup && ( <ObjectVariablesDialog project={project} projectScopedContainersAccessor={projectScopedContainersAccessor} objectName={objectName} variablesContainer={variablesContainers[0]} open onCancel={() => setEditorOpen(null)} onApply={onVariableEditorApply} preventRefactoringToDeleteInstructions initiallySelectedVariableName={editorOpen.variableName} shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} onComputeAllVariableNames={onComputeAllVariableNames} hotReloadPreviewButtonProps={null} /> )} {editorOpen && project && objectGroup && ( <ObjectGroupVariablesDialog project={project} projectScopedContainersAccessor={projectScopedContainersAccessor} globalObjectsContainer={globalObjectsContainer} objectsContainer={objectsContainer} objectGroup={objectGroup} onCancel={() => setEditorOpen(null)} onApply={onVariableEditorApply} open initiallySelectedVariableName={editorOpen.variableName} shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} onComputeAllVariableNames={onComputeAllVariableNames} /> )} </React.Fragment> ); } ); export const renderInlineObjectVariable = ( props: ParameterInlineRendererProps ) => renderVariableWithIcon(props, 'object variable', ObjectVariableIcon);
Sounds suspicious as not used then?
} onInstructionTypeChanged={onInstructionTypeChanged} /> {editorOpen && project && !!variablesContainers.length && !objectGroup && ( <ObjectVariablesDialog project={project} projectScopedContainersAccessor={projectScopedContainersAccessor} objectName={objectName} variablesContainer={variablesContainers[0]} open onCancel={() => setEditorOpen(null)} onApply={onVariableEditorApply} preventRefactoringToDeleteInstructions initiallySelectedVariableName={editorOpen.variableName} shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} onComputeAllVariableNames={onComputeAllVariableNames} hotReloadPreviewButtonProps={null} /> )} {editorOpen && project && objectGroup && !!variablesContainers.length && ( <ObjectGroupVariablesDialog project={project} projectScopedContainersAccessor={projectScopedContainersAccessor} globalObjectsContainer={globalObjectsContainer} objectsContainer={objectsContainer} objectGroup={objectGroup} onCancel={() => setEditorOpen(null)} onApply={onVariableEditorApply} open initiallySelectedVariableName={editorOpen.variableName} shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} onComputeAllVariableNames={onComputeAllVariableNames} /> )} </React.Fragment> ); } ); export const renderInlineObjectVariable = ( props: ParameterInlineRendererProps ) => renderVariableWithIcon(props, 'object variable', ObjectVariableIcon);
@@ -188,37 +188,43 @@ export default React.forwardRef<ParameterFieldProps, ParameterFieldInterface>( } onInstructionTypeChanged={onInstructionTypeChanged} /> - {editorOpen && project && !objectGroup && ( - <ObjectVariablesDialog - project={project} - projectScopedContainersAccessor={projectScopedContainersAccessor} - objectName={objectName} - variablesContainer={variablesContainers[0]} - open - onCancel={() => setEditorOpen(null)} - onApply={onVariableEditorApply} - preventRefactoringToDeleteInstructions - initiallySelectedVariableName={editorOpen.variableName} - shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} - onComputeAllVariableNames={onComputeAllVariableNames} - hotReloadPreviewButtonProps={null} - /> - )} - {editorOpen && project && objectGroup && ( - <ObjectGroupVariablesDialog - project={project} - projectScopedContainersAccessor={projectScopedContainersAccessor} - globalObjectsContainer={globalObjectsContainer} - objectsContainer={objectsContainer} - objectGroup={objectGroup} - onCancel={() => setEditorOpen(null)} - onApply={onVariableEditorApply} - open - initiallySelectedVariableName={editorOpen.variableName} - shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} - onComputeAllVariableNames={onComputeAllVariableNames} - /> - )} + {editorOpen && + project && + !!variablesContainers.length && + !objectGroup && ( + <ObjectVariablesDialog + project={project} + projectScopedContainersAccessor={projectScopedContainersAccessor} + objectName={objectName} + variablesContainer={variablesContainers[0]} + open + onCancel={() => setEditorOpen(null)} + onApply={onVariableEditorApply} + preventRefactoringToDeleteInstructions + initiallySelectedVariableName={editorOpen.variableName} + shouldCreateInitiallySelectedVariable={editorOpen.shouldCreate} + onComputeAllVariableNames={onComputeAllVariableNames} + hotReloadPreviewButtonProps={null} + /> + )} + {editorOpen && + project && + objectGroup && + !!variablesContainers.length && (
newIDE/app/src/EventsSheet/ParameterFields/ObjectVariableField.js
26
JavaScript
0.143
question
35
43
49
false
Prevent opening variables dialog for objects & groups if there is no object
7,132
4ian/GDevelop
10,154
JavaScript
4ian
ClementPasteau
// We could pass it a string, but lets do it right this.removeJoint(parseInt(jId, 10)); } } } } // Remove the joint this.world.DestroyJoint(joint); delete this.joints[jointId]; } } } gdjs.registerRuntimeSceneUnloadedCallback(function (runtimeScene) { if ( // @ts-ignore runtimeScene.physics2SharedData && // @ts-ignore runtimeScene.physics2SharedData.world ) { // @ts-ignore Box2D.destroy(runtimeScene.physics2SharedData.world); } }); export class Physics2RuntimeBehavior extends gdjs.RuntimeBehavior { bodyType: string; bullet: boolean; fixedRotation: boolean; canSleep: boolean; shape: string; shapeDimensionA: any; shapeDimensionB: any; shapeOffsetX: float; shapeOffsetY: float; polygonOrigin: string; polygon: gdjs.Polygon | null; density: float; friction: float; restitution: float; linearDamping: float; angularDamping: float; gravityScale: float; layers: integer; masks: integer; shapeScale: number = 1; /** * Array containing the beginning of contacts reported by onContactBegin. Each contact * should be unique to avoid recording glitches where the object loses and regain * contact between two frames. The array is updated each time the method
In the future, a `destroy()` method on the shared data would be I think safer (in the sense: it's part of the class, so there is less chance you forget to update it when needed) and we we should probably made the "shared data" something first class that is handled by the runtime scene (rather than something that is manually handled by the behavior like now).
if ( this.joints[jId].GetType() === Box2D.e_gearJoint && (Box2D.getPointer( (this.joints[jId] as Box2D.b2GearJoint).GetJoint1() ) === Box2D.getPointer(joint) || Box2D.getPointer( (this.joints[jId] as Box2D.b2GearJoint).GetJoint2() ) === Box2D.getPointer(joint)) ) { // We could pass it a string, but lets do it right this.removeJoint(parseInt(jId, 10)); } } } } // Remove the joint this.world.DestroyJoint(joint); delete this.joints[jointId]; } } } gdjs.registerRuntimeSceneUnloadedCallback(function (runtimeScene) { const physics2SharedData = runtimeScene.physics2SharedData; if (physics2SharedData && physics2SharedData.world) { Box2D.destroy(physics2SharedData.world); Box2D.destroy(physics2SharedData._tempb2Vec2); Box2D.destroy(physics2SharedData._tempb2Vec2Sec); } }); export class Physics2RuntimeBehavior extends gdjs.RuntimeBehavior { bodyType: string; bullet: boolean; fixedRotation: boolean; canSleep: boolean; shape: string; shapeDimensionA: any; shapeDimensionB: any; shapeOffsetX: float; shapeOffsetY: float; polygonOrigin: string; polygon: gdjs.Polygon | null; density: float; friction: float; restitution: float; linearDamping: float; angularDamping: float; gravityScale: float; layers: integer; masks: integer;
@@ -300,14 +309,11 @@ namespace gdjs { } } gdjs.registerRuntimeSceneUnloadedCallback(function (runtimeScene) { - if ( - // @ts-ignore - runtimeScene.physics2SharedData && - // @ts-ignore - runtimeScene.physics2SharedData.world - ) { - // @ts-ignore - Box2D.destroy(runtimeScene.physics2SharedData.world); + const physics2SharedData = runtimeScene.physics2SharedData; + if (physics2SharedData && physics2SharedData.world) { + Box2D.destroy(physics2SharedData.world);
Extensions/Physics2Behavior/physics2runtimebehavior.ts
26
TypeScript
0.786
suggestion
360
51
51
false
[Physics2] Fix a memory leak on object instances
7,136
4ian/GDevelop
10,154
JavaScript
4ian
D8H
// we need to relay the ownership change to others, // and expect an acknowledgment from them. if (gdjs.multiplayer.isCurrentPlayerHost()) { const connectedPeerIds = gdjs.multiplayerPeerJsHelper.getAllPeers(); // We don't need to send the message to the player who sent the ownership change message. const otherPeerIds = connectedPeerIds.filter( (peerId) => peerId !== messageSender ); if (!otherPeerIds.length) { // No one else to relay the message to. return; } addExpectedMessageAcknowledgement({ originalMessageName: messageName, originalData: messageData, expectedMessageName: variableOwnerChangedMessageName, otherPeerIds, // As we are the host, we do not cancel the message if it times out. shouldCancelMessageIfTimesOut: false, }); for (const peerId of otherPeerIds) { debugLogger.info( `Relaying ownership change of variable with Id ${variableNetworkId} to ${peerId}.` ); sendDataTo(otherPeerIds, messageName, messageData); } } }); }); }; const getRegexFromAckMessageName = (messageName: string) => { if (messageName.startsWith(instanceDestroyedMessageNamePrefix)) { return instanceDestroyedMessageNameRegex; } else if ( messageName.startsWith(instanceOwnerChangedMessageNamePrefix) ) { return instanceOwnerChangedMessageNameRegex; } else if ( messageName.startsWith(variableOwnerChangedMessageNamePrefix) ) { return variableOwnerChangedMessageNameRegex; } else if (messageName.startsWith(customMessageAcknowledgePrefix)) { return customMessageAcknowledgeRegex; } return null; }; const isMessageAcknowledgement = (messageName: string) => { return (
So this was sending too many messages!
// we need to relay the ownership change to others, // and expect an acknowledgment from them. if (gdjs.multiplayer.isCurrentPlayerHost()) { const connectedPeerIds = gdjs.multiplayerPeerJsHelper.getAllPeers(); // We don't need to send the message to the player who sent the ownership change message. const otherPeerIds = connectedPeerIds.filter( (peerId) => peerId !== messageSender ); if (!otherPeerIds.length) { // No one else to relay the message to. return; } addExpectedMessageAcknowledgement({ originalMessageName: messageName, originalData: messageData, expectedMessageName: variableOwnerChangedMessageName, otherPeerIds, // As we are the host, we do not cancel the message if it times out. shouldCancelMessageIfTimesOut: false, }); debugLogger.info( `Relaying ownership change of variable with Id ${variableNetworkId} to ${otherPeerIds.join( ', ' )}.` ); sendDataTo(otherPeerIds, messageName, messageData); } }); }); }; const getRegexFromAckMessageName = (messageName: string) => { if (messageName.startsWith(instanceDestroyedMessageNamePrefix)) { return instanceDestroyedMessageNameRegex; } else if ( messageName.startsWith(instanceOwnerChangedMessageNamePrefix) ) { return instanceOwnerChangedMessageNameRegex; } else if ( messageName.startsWith(variableOwnerChangedMessageNamePrefix) ) { return variableOwnerChangedMessageNameRegex; } else if (messageName.startsWith(customMessageAcknowledgePrefix)) { return customMessageAcknowledgeRegex; } return null; }; const isMessageAcknowledgement = (messageName: string) => { return (
@@ -917,12 +917,12 @@ namespace gdjs { // As we are the host, we do not cancel the message if it times out. shouldCancelMessageIfTimesOut: false, }); - for (const peerId of otherPeerIds) { - debugLogger.info( - `Relaying ownership change of variable with Id ${variableNetworkId} to ${peerId}.` - ); - sendDataTo(otherPeerIds, messageName, messageData);
Extensions/Multiplayer/messageManager.ts
26
TypeScript
0.071
suggestion
38
51
51
false
Fix destroying an object even if flagged as "DoNothing" in the multiplayer behavior
7,137
4ian/GDevelop
10,154
JavaScript
4ian
ClementPasteau
} catch (error) { console.error('Error while login:', error); throw error; } } async loginOrSignupWithProvider({ provider, signal, }: {| provider: IdentityProvider, signal?: AbortSignal, |}) { if (signal && signal.aborted) { return Promise.reject( new UserCancellationError( 'Login or Signup with provider already aborted.' ) ); } const promise = new Promise((resolve, reject) => { // Listen for abort event on signal if (signal) { signal.addEventListener('abort', () => { terminateWebSocket(); }); } setupAuthenticationWebSocket({ onConnectionEstablished: connectionId => { if (signal && signal.aborted) return; const url = new URL(authenticationPortalUrl); url.searchParams.set('connection-id', connectionId); url.searchParams.set('provider', provider); url.searchParams.set('env', isDev ? 'dev' : 'live'); Window.openExternalURL(url.toString()); }, onTokenReceived: async ({ provider, data, }: {| provider: 'apple' | 'google' | 'github', data: any, |}) => { if (signal && signal.aborted) return; try { const credential = provider === 'google' ? GoogleAuthProvider.credential(data.credential) : provider === 'github' ? GithubAuthProvider.credential(data.accessToken) : new OAuthProvider('apple.com').credential({
this seemed duplicated in this file and the browser one. This was always causing an error in the console because the signal always aborts (we trigger it when we close the dialog) I don't think this deserves to raise an error as it's the expected path?
} catch (error) { console.error('Error while login:', error); throw error; } } async loginOrSignupWithProvider({ provider, signal, }: {| provider: IdentityProvider, signal?: AbortSignal, |}) { if (signal && signal.aborted) { return Promise.reject( new UserCancellationError( 'Login or Signup with provider already aborted.' ) ); } const promise = new Promise((resolve, reject) => { // Listen for abort event on signal if (signal) { signal.addEventListener('abort', () => { terminateWebSocket(); reject( new UserCancellationError( 'Login or Signup with provider already aborted.' ) ); }); } setupAuthenticationWebSocket({ onConnectionEstablished: connectionId => { if (signal && signal.aborted) return; const url = new URL(authenticationPortalUrl); url.searchParams.set('connection-id', connectionId); url.searchParams.set('provider', provider); url.searchParams.set('env', isDev ? 'dev' : 'live'); Window.openExternalURL(url.toString()); }, onTokenReceived: async ({ provider, data, }: {| provider: 'apple' | 'google' | 'github', data: any, |}) => { if (signal && signal.aborted) return; try { const credential =
@@ -61,11 +61,6 @@ class LocalLoginProvider implements LoginProvider, FirebaseBasedLoginProvider { if (signal) { signal.addEventListener('abort', () => { terminateWebSocket(); - reject(
newIDE/app/src/LoginProvider/LocalLoginProvider.js
26
JavaScript
0.643
refactor
253
51
51
false
Fix infinite loading when canceling login with provider
7,138
4ian/GDevelop
10,154
JavaScript
ClementPasteau
ClementPasteau
}, }); } } this.setState({ createAccountInProgress: false, loginInProgress: false, authenticatedUser: { ...this.state.authenticatedUser, creatingOrLoggingInAccount: false, }, }); this._automaticallyUpdateUserProfile = true; }; _cancelLoginOrSignUp = () => { if (this._abortController) { this._abortController.abort(); this._abortController = null; } this.setState({ loginInProgress: false, createAccountInProgress: false, authenticatedUser: { ...this.state.authenticatedUser, creatingOrLoggingInAccount: false, }, }); }; _doLogin = async (form: LoginForm) => { const { authentication } = this.props; if (!authentication) return; this.setState({ loginInProgress: true, apiCallError: null, authenticatedUser: { ...this.state.authenticatedUser, creatingOrLoggingInAccount: true, authenticationError: null, }, }); this._automaticallyUpdateUserProfile = false; try { await authentication.login(form); await this._fetchUserProfileWithoutThrowingErrors({ resetState: true }); this.openLoginDialog(false); this._showLoginSnackbar(this.state.authenticatedUser); } catch (apiCallError) { this.setState({
I don't like doing this here. It looks like we're trying to "finish a process". But the process is already there: <img width="776" alt="image" src="https://github.com/user-attachments/assets/6fe5b8b4-8d4c-4124-b83a-34f6d90bbd83"> There is already a catch (ensuring that an exception will never stop the end to run) and at the end we set the boolean back to false.
}, }); } } this.setState({ createAccountInProgress: false, loginInProgress: false, authenticatedUser: { ...this.state.authenticatedUser, creatingOrLoggingInAccount: false, }, }); this._automaticallyUpdateUserProfile = true; }; _cancelLoginOrSignUp = () => { if (this._abortController) { this._abortController.abort(); this._abortController = null; } }; _doLogin = async (form: LoginForm) => { const { authentication } = this.props; if (!authentication) return; this.setState({ loginInProgress: true, apiCallError: null, authenticatedUser: { ...this.state.authenticatedUser, creatingOrLoggingInAccount: true, authenticationError: null, }, }); this._automaticallyUpdateUserProfile = false; try { await authentication.login(form); await this._fetchUserProfileWithoutThrowingErrors({ resetState: true }); this.openLoginDialog(false); this._showLoginSnackbar(this.state.authenticatedUser); } catch (apiCallError) { this.setState({ apiCallError, authenticatedUser: { ...this.state.authenticatedUser, authenticationError: apiCallError, }, }); } this.setState({
@@ -996,11 +996,19 @@ export default class AuthenticatedUserProvider extends React.Component< this._automaticallyUpdateUserProfile = true; }; - _cancelLogin = () => { + _cancelLoginOrSignUp = () => { if (this._abortController) { this._abortController.abort(); this._abortController = null; } + this.setState({ + loginInProgress: false, + createAccountInProgress: false, + authenticatedUser: { + ...this.state.authenticatedUser, + creatingOrLoggingInAccount: false,
newIDE/app/src/Profile/AuthenticatedUserProvider.js
26
JavaScript
0.643
suggestion
369
51
51
false
Fix infinite loading when canceling login with provider
7,138
4ian/GDevelop
10,154
JavaScript
4ian
ClementPasteau
Props, State > { state = { eventsFunction: null, extensionName: '', createNewExtension: false, }; _projectScopedContainersAccessor: ProjectScopedContainersAccessor | null = null; componentDidMount() { const { project, scope, globalObjectsContainer, objectsContainer, serializedEvents, } = this.props; // This is only used to check parameter for name conflict. // TODO Update it according to the chosen extension. this._projectScopedContainersAccessor = new ProjectScopedContainersAccessor( { project } ); // Set up the function const eventsFunction = new gd.EventsFunction(); setupFunctionFromEvents({ project, scope, globalObjectsContainer, objectsContainer, serializedEvents, eventsFunction, }); this.setState({ eventsFunction, }); // Prepopulate the form const eventsFunctionsExtensions = enumerateEventsFunctionsExtensions( project ); if (eventsFunctionsExtensions.length === 0) { this.setState({ createNewExtension: true, }); } } componentWillUnmount() {
This is kind of regression as it will forbid to use the same name as global variables and global objects for a parameter. We should probably use a new blank project instead.
Props, State > { state = { eventsFunction: null, extensionName: '', createNewExtension: false, }; _projectScopedContainersAccessor: ProjectScopedContainersAccessor | null = null; componentDidMount() { const { project, scope, globalObjectsContainer, objectsContainer, serializedEvents, } = this.props; // This is only used to check parameter for name conflict,but the parameter // editor is locked so users can't actually change parameter names. // Thus, it's fine to use the wrong scope. this._projectScopedContainersAccessor = new ProjectScopedContainersAccessor( { project } ); // Set up the function const eventsFunction = new gd.EventsFunction(); setupFunctionFromEvents({ project, scope, globalObjectsContainer, objectsContainer, serializedEvents, eventsFunction, }); this.setState({ eventsFunction, }); // Prepopulate the form const eventsFunctionsExtensions = enumerateEventsFunctionsExtensions( project ); if (eventsFunctionsExtensions.length === 0) { this.setState({ createNewExtension: true, }); } }
@@ -65,6 +67,12 @@ export default class EventsFunctionExtractorDialog extends React.Component< serializedEvents, } = this.props; + // This is only used to check parameter for name conflict. + // TODO Update it according to the chosen extension. + this._projectScopedContainersAccessor = new ProjectScopedContainersAccessor( + { project } + );
newIDE/app/src/EventsSheet/EventsFunctionExtractor/EventsFunctionExtractorDialog.js
26
JavaScript
0.429
suggestion
174
51
51
false
Reduce the risk of name collisions between objects, variables, parameters and properties
7,148
4ian/GDevelop
10,154
JavaScript
D8H
D8H
preferences.values.openDiagnosticReportAutomatically, onLaunchPreviewWithDiagnosticReport, previewState.overridenPreviewLayoutName, previewState.overridenPreviewExternalLayoutName, previewState.isPreviewOverriden, previewState.previewExternalLayoutName, previewState.previewLayoutName, setPreviewOverride, ] ); // Create a separate function to avoid the button passing its event as // the first argument. const onShareClick = React.useCallback( () => { openShareDialog(); }, [openShareDialog] ); return ( <LineStackLayout noMargin> <FlatButtonWithSplitMenu primary onClick={ !hasPreviewsRunning && preferences.values.takeScreenshotOnPreview // Take a screenshot on first preview. ? onLaunchPreviewWithScreenshot : onHotReloadPreview } disabled={!isPreviewEnabled} icon={hasPreviewsRunning ? <UpdateIcon /> : <PreviewIcon />} label={ !isMobile ? ( hasPreviewsRunning ? ( <Trans>Update</Trans> ) : ( <Trans>Preview</Trans> ) ) : null } id="toolbar-preview-button" splitMenuButtonId="toolbar-preview-split-menu-button" buildMenuTemplate={previewBuildMenuTemplate} /> <ResponsiveRaisedButton primary onClick={onShareClick} disabled={!isSharingEnabled} icon={<PublishIcon />} label={<Trans>Share</Trans>} // This ID is used for guided lessons, let's keep it stable.
wondering if we should also take a screenshot only if: - you don't have a thumbnailUrl already set (but the screenshots might be useful) - you haven't taken a screenshot recently (to avoid taking one on every preview) - like every x minutes ?
previewState.overridenPreviewLayoutName, previewState.overridenPreviewExternalLayoutName, previewState.isPreviewOverriden, previewState.previewExternalLayoutName, previewState.previewLayoutName, setPreviewOverride, ] ); // Create a separate function to avoid the button passing its event as // the first argument. const onShareClick = React.useCallback( () => { openShareDialog(); }, [openShareDialog] ); return ( <LineStackLayout noMargin> <FlatButtonWithSplitMenu primary onClick={onHotReloadPreview} disabled={!isPreviewEnabled} icon={hasPreviewsRunning ? <UpdateIcon /> : <PreviewIcon />} label={ !isMobile ? ( hasPreviewsRunning ? ( <Trans>Update</Trans> ) : ( <Trans>Preview</Trans> ) ) : null } id="toolbar-preview-button" splitMenuButtonId="toolbar-preview-split-menu-button" buildMenuTemplate={previewBuildMenuTemplate} /> <ResponsiveRaisedButton primary onClick={onShareClick} disabled={!isSharingEnabled} icon={<PublishIcon />} label={<Trans>Share</Trans>} // This ID is used for guided lessons, let's keep it stable. id="toolbar-publish-button" /> </LineStackLayout> ); } );
@@ -185,7 +187,11 @@ const PreviewAndShareButtons = React.memo<PreviewAndShareButtonsProps>( <LineStackLayout noMargin> <FlatButtonWithSplitMenu primary - onClick={onHotReloadPreview} + onClick={ + !hasPreviewsRunning && preferences.values.takeScreenshotOnPreview // Take a screenshot on first preview.
newIDE/app/src/MainFrame/Toolbar/PreviewAndShareButtons.js
26
JavaScript
0.5
question
244
51
51
false
Take a screenshot on preview
7,156
4ian/GDevelop
10,154
JavaScript
ClementPasteau
ClementPasteau
preferences.getIsMenuBarHiddenInPreview, preferences.getIsAlwaysOnTopInPreview, preferences.values.openDiagnosticReportAutomatically, currentlyRunningInAppTutorial, getAuthenticatedPlayerForPreview, quickCustomizationDialogOpenedFromGameId, onCaptureFinished, createCaptureOptionsForPreview, ] ); const launchPreview = addCreateBadgePreHookIfNotClaimed( authenticatedUser, TRIVIAL_FIRST_PREVIEW, _launchPreview ); const launchNewPreview = React.useCallback( async options => { const numberOfWindows = options ? options.numberOfWindows : 1; await launchPreview({ networkPreview: false, numberOfWindows }); }, [launchPreview] ); const launchPreviewWithScreenshot = React.useCallback( () => launchPreview({ networkPreview: false, hotReload: false, launchCaptureOptions: { screenshots: [ { delayTimeInSeconds: 3000 }, // Take only 1 screenshot per preview. ], }, }), [launchPreview] ); const launchHotReloadPreview = React.useCallback( () => launchPreview({ networkPreview: false, hotReload: true, }), [launchPreview] ); const launchNetworkPreview = React.useCallback( () => launchPreview({ networkPreview: true, hotReload: false }), [launchPreview]
Consider not adding yet-another-way-to-launch-preview and instead: - Make the logic related to the timing inside the existing function. - delayTimeInSeconds can also be in the function - forcing a screenshot, bypassing the check for timing, is "just" a "forceScreenshot: true". But this is only used for quick customization. For normal previews, the buttons are unchanged.
preferences.getIsMenuBarHiddenInPreview, preferences.getIsAlwaysOnTopInPreview, preferences.values.openDiagnosticReportAutomatically, currentlyRunningInAppTutorial, getAuthenticatedPlayerForPreview, quickCustomizationDialogOpenedFromGameId, onCaptureFinished, createCaptureOptionsForPreview, ] ); const launchPreview = addCreateBadgePreHookIfNotClaimed( authenticatedUser, TRIVIAL_FIRST_PREVIEW, _launchPreview ); const launchNewPreview = React.useCallback( async options => { const numberOfWindows = options ? options.numberOfWindows : 1; await launchPreview({ networkPreview: false, numberOfWindows }); }, [launchPreview] ); const launchHotReloadPreview = React.useCallback( async () => { const launchCaptureOptions = currentProject ? getHotReloadPreviewLaunchCaptureOptions( currentProject.getProjectUuid() ) : undefined; await launchPreview({ networkPreview: false, hotReload: true, launchCaptureOptions, }); }, [currentProject, launchPreview, getHotReloadPreviewLaunchCaptureOptions] ); const launchNetworkPreview = React.useCallback( () => launchPreview({ networkPreview: true, hotReload: false }), [launchPreview] ); const launchPreviewWithDiagnosticReport = React.useCallback( () => launchPreview({ forceDiagnosticReport: true }), [launchPreview] );
@@ -1723,13 +1724,31 @@ const MainFrame = (props: Props) => { const launchNewPreview = React.useCallback( async options => { const numberOfWindows = options ? options.numberOfWindows : 1; - launchPreview({ networkPreview: false, numberOfWindows }); + await launchPreview({ networkPreview: false, numberOfWindows }); }, [launchPreview] ); + const launchPreviewWithScreenshot = React.useCallback(
newIDE/app/src/MainFrame/index.js
26
JavaScript
0.5
suggestion
375
51
51
false
Take a screenshot on preview
7,156
4ian/GDevelop
10,154
JavaScript
4ian
ClementPasteau
// (because the target is in the scope), replace or remove it: RenameOrRemovePropertyOfTargetPropertyContainer(node.name); } if (node.child) node.child->Visit(*this); }); } void OnVisitVariableAccessorNode(VariableAccessorNode& node) override { if (node.child) node.child->Visit(*this); } void OnVisitVariableBracketAccessorNode( VariableBracketAccessorNode& node) override { node.expression->Visit(*this); if (node.child) node.child->Visit(*this); } void OnVisitIdentifierNode(IdentifierNode& node) override { auto& propertiesContainersList = projectScopedContainers.GetPropertiesContainersList(); // Match the potential *new* name of the property, because refactorings are // done after changes in the variables container. projectScopedContainers.MatchIdentifierWithName<void>( GetPotentialNewName(node.identifierName), [&]() { // Do nothing, it's an object variable. }, [&]() { // Do nothing, it's a variable. }, [&]() { // This is a property, check if it's coming from the target container with // properties to replace. if (propertiesContainersList.HasPropertiesContainer( targetPropertiesContainer)) { // The node represents a property, that can come from the target // (because the target is in the scope), replace or remove it: RenameOrRemovePropertyOfTargetPropertyContainer(node.identifierName); } }, [&]() { // Do nothing, it's a parameter. }, [&]() { // This is something else - potentially a deleted property. // Check if it's coming from the target container with // properties to replace. if (propertiesContainersList.HasPropertiesContainer( targetPropertiesContainer)) { // The node represents a property, that can come from the target // (because the target is in the scope), replace or remove it: RenameOrRemovePropertyOfTargetPropertyContainer(node.identifierName); } }); } void OnVisitObjectFunctionNameNode(ObjectFunctionNameNode& node) override {}
I don't understand why this "MatchIdentifierWithName" is not doing its job? If it's a variable, it should match it (and so do nothing), no?
}, [&]() { // Do nothing, it's something else. if (node.child) node.child->Visit(*this); }); } void OnVisitVariableAccessorNode(VariableAccessorNode& node) override { if (node.child) node.child->Visit(*this); } void OnVisitVariableBracketAccessorNode( VariableBracketAccessorNode& node) override { bool isGrandParentTypeAVariable = isParentTypeAVariable; isParentTypeAVariable = false; node.expression->Visit(*this); isParentTypeAVariable = isGrandParentTypeAVariable; if (node.child) node.child->Visit(*this); } void OnVisitIdentifierNode(IdentifierNode& node) override { if (isParentTypeAVariable) { // Do nothing, it's a variable. return; } auto& propertiesContainersList = projectScopedContainers.GetPropertiesContainersList(); projectScopedContainers.MatchIdentifierWithName<void>( // The property name is changed after the refactor operation node.identifierName, [&]() { // Do nothing, it's an object variable. }, [&]() { // Do nothing, it's a variable. }, [&]() { // This is a property, check if it's coming from the target container with // properties to replace. if (propertiesContainersList.HasPropertiesContainer( targetPropertiesContainer)) { // The node represents a property, that can come from the target // (because the target is in the scope), replace or remove it: RenameOrRemovePropertyOfTargetPropertyContainer(node.identifierName); } }, [&]() { // Do nothing, it's a parameter. }, [&]() { // Do nothing, it's something else. }); } void OnVisitObjectFunctionNameNode(ObjectFunctionNameNode& node) override {} void OnVisitFunctionCallNode(FunctionCallNode &node) override { bool isGrandParentTypeAVariable = isParentTypeAVariable; for (auto &parameter : node.parameters) {
@@ -118,17 +116,24 @@ class GD_CORE_API ExpressionPropertyReplacer } void OnVisitVariableBracketAccessorNode( VariableBracketAccessorNode& node) override { + bool isGrandParentTypeAVariable = isParentTypeAVariable; + isParentTypeAVariable = false; node.expression->Visit(*this); + isParentTypeAVariable = isGrandParentTypeAVariable; if (node.child) node.child->Visit(*this); } void OnVisitIdentifierNode(IdentifierNode& node) override { + if (isParentTypeAVariable) { + // Do nothing, it's a variable. + return; + } + auto& propertiesContainersList = projectScopedContainers.GetPropertiesContainersList(); - // Match the potential *new* name of the property, because refactorings are - // done after changes in the variables container. projectScopedContainers.MatchIdentifierWithName<void>(
Core/GDCore/IDE/Events/EventsPropertyReplacer.cpp
26
C++
0.429
question
139
51
51
false
Fix variables from being renamed with a property
7,186
4ian/GDevelop
10,154
JavaScript
4ian
D8H
for (std::size_t c = 0; c < GetCameraCount(); ++c) { SerializerElement& cameraElement = camerasElement.AddChild("camera"); cameraElement.SetAttribute("defaultSize", GetCamera(c).UseDefaultSize()); cameraElement.SetAttribute("width", GetCamera(c).GetWidth()); cameraElement.SetAttribute("height", GetCamera(c).GetHeight()); cameraElement.SetAttribute("defaultViewport", GetCamera(c).UseDefaultViewport()); cameraElement.SetAttribute("viewportLeft", GetCamera(c).GetViewportX1()); cameraElement.SetAttribute("viewportTop", GetCamera(c).GetViewportY1()); cameraElement.SetAttribute("viewportRight", GetCamera(c).GetViewportX2()); cameraElement.SetAttribute("viewportBottom", GetCamera(c).GetViewportY2()); } SerializerElement& effectsElement = element.AddChild("effects"); effectsContainer.SerializeTo(effectsElement); } /** * \brief Unserialize the layer. */ void Layer::UnserializeFrom(const SerializerElement& element) { SetName(element.GetStringAttribute("name", "", "Name")); SetRenderingType(element.GetStringAttribute("renderingType", "")); SetCameraType(element.GetStringAttribute("cameraType", "perspective")); SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "keep-top-left-fixed-if-never-moved")); SetVisibility(element.GetBoolAttribute("visibility", true, "Visibility")); SetLocked(element.GetBoolAttribute("isLocked", false)); SetLightingLayer(element.GetBoolAttribute("isLightingLayer", false)); SetFollowBaseLayerCamera( element.GetBoolAttribute("followBaseLayerCamera", false)); SetAmbientLightColor(element.GetIntAttribute("ambientLightColorR", 200), element.GetIntAttribute("ambientLightColorG", 200), element.GetIntAttribute("ambientLightColorB", 200)); SetCamera3DNearPlaneDistance(element.GetDoubleAttribute( "camera3DNearPlaneDistance", 0.1, "threeDNearPlaneDistance")); SetCamera3DFarPlaneDistance(element.GetDoubleAttribute( "camera3DFarPlaneDistance", 10000, "threeDFarPlaneDistance")); SetCamera3DFieldOfView(element.GetDoubleAttribute( "camera3DFieldOfView", 45, "threeDFieldOfView")); cameras.clear(); SerializerElement& camerasElement = element.GetChild("cameras"); camerasElement.ConsiderAsArrayOf("camera"); for (std::size_t i = 0; i < camerasElement.GetChildrenCount(); ++i) { const SerializerElement& cameraElement = camerasElement.GetChild(i); Camera camera; camera.SetUseDefaultSize( cameraElement.GetBoolAttribute("defaultSize", true)); camera.SetSize(cameraElement.GetDoubleAttribute("width"),
to make it a bit shorter ```suggestion SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "top-left-anchored-if-never-moved")); ```
for (std::size_t c = 0; c < GetCameraCount(); ++c) { SerializerElement& cameraElement = camerasElement.AddChild("camera"); cameraElement.SetAttribute("defaultSize", GetCamera(c).UseDefaultSize()); cameraElement.SetAttribute("width", GetCamera(c).GetWidth()); cameraElement.SetAttribute("height", GetCamera(c).GetHeight()); cameraElement.SetAttribute("defaultViewport", GetCamera(c).UseDefaultViewport()); cameraElement.SetAttribute("viewportLeft", GetCamera(c).GetViewportX1()); cameraElement.SetAttribute("viewportTop", GetCamera(c).GetViewportY1()); cameraElement.SetAttribute("viewportRight", GetCamera(c).GetViewportX2()); cameraElement.SetAttribute("viewportBottom", GetCamera(c).GetViewportY2()); } SerializerElement& effectsElement = element.AddChild("effects"); effectsContainer.SerializeTo(effectsElement); } /** * \brief Unserialize the layer. */ void Layer::UnserializeFrom(const SerializerElement& element) { SetName(element.GetStringAttribute("name", "", "Name")); SetRenderingType(element.GetStringAttribute("renderingType", "")); SetCameraType(element.GetStringAttribute("cameraType", "perspective")); SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "top-left-anchored-if-never-moved")); SetVisibility(element.GetBoolAttribute("visibility", true, "Visibility")); SetLocked(element.GetBoolAttribute("isLocked", false)); SetLightingLayer(element.GetBoolAttribute("isLightingLayer", false)); SetFollowBaseLayerCamera( element.GetBoolAttribute("followBaseLayerCamera", false)); SetAmbientLightColor(element.GetIntAttribute("ambientLightColorR", 200), element.GetIntAttribute("ambientLightColorG", 200), element.GetIntAttribute("ambientLightColorB", 200)); SetCamera3DNearPlaneDistance(element.GetDoubleAttribute( "camera3DNearPlaneDistance", 0.1, "threeDNearPlaneDistance")); SetCamera3DFarPlaneDistance(element.GetDoubleAttribute( "camera3DFarPlaneDistance", 10000, "threeDFarPlaneDistance")); SetCamera3DFieldOfView(element.GetDoubleAttribute( "camera3DFieldOfView", 45, "threeDFieldOfView")); cameras.clear(); SerializerElement& camerasElement = element.GetChild("cameras"); camerasElement.ConsiderAsArrayOf("camera"); for (std::size_t i = 0; i < camerasElement.GetChildrenCount(); ++i) { const SerializerElement& cameraElement = camerasElement.GetChild(i); Camera camera; camera.SetUseDefaultSize( cameraElement.GetBoolAttribute("defaultSize", true)); camera.SetSize(cameraElement.GetDoubleAttribute("width"),
@@ -80,6 +84,7 @@ void Layer::UnserializeFrom(const SerializerElement& element) { SetName(element.GetStringAttribute("name", "", "Name")); SetRenderingType(element.GetStringAttribute("renderingType", "")); SetCameraType(element.GetStringAttribute("cameraType", "perspective")); + SetDefaultCameraBehavior(element.GetStringAttribute("defaultCameraBehavior", "keep-top-left-fixed-if-never-moved"));
Core/GDCore/Project/Layer.cpp
26
C++
0.786
suggestion
164
51
51
false
Fix anchor behavior and add option to center layer or keep top-left fixed when resized
7,188
4ian/GDevelop
10,154
JavaScript
D8H
4ian
_cameraX: float; _cameraY: float; _cameraZ: float = 0; /** * `_cameraZ` is dirty when the zoom factor is set last. */ _isCameraZDirty: boolean = true; /** * @param layerData The data used to initialize the layer * @param instanceContainer The container in which the layer is used */ constructor( layerData: LayerData, instanceContainer: gdjs.RuntimeInstanceContainer ) { super(layerData, instanceContainer); if ( this._defaultCameraBehavior === gdjs.RuntimeLayerDefaultCameraBehavior .KEEP_TOP_LEFT_FIXED_IF_NEVER_MOVED ) { // If top-left must stay in the top-left corner, this means we center the camera on the current size. this._cameraX = this._runtimeScene.getViewportWidth() / 2; this._cameraY = this._runtimeScene.getViewportHeight() / 2; } else { // Otherwise, the default camera position is the center of the initial viewport. this._cameraX = (this._runtimeScene.getInitialUnrotatedViewportMinX() + this._runtimeScene.getInitialUnrotatedViewportMaxX()) / 2; this._cameraY = (this._runtimeScene.getInitialUnrotatedViewportMinY() + this._runtimeScene.getInitialUnrotatedViewportMaxY()) / 2; } if (this.getCameraType() === gdjs.RuntimeLayerCameraType.ORTHOGRAPHIC) { this._cameraZ = (this._initialCamera3DFarPlaneDistance + this._initialCamera3DNearPlaneDistance) / 2; } // Let the renderer do its final set up: this._renderer.onCreated(); } /** * Called by the RuntimeScene whenever the game resolution size is changed. * Updates the layer width/height and position.
Should this use `getViewportOriginX/Y` to handle the fact that custom objects don't necessarily have the top-left corner at (0 ; 0) (even if it probably doesn't matter here as it's a scene layer)?
_cameraX: float; _cameraY: float; _cameraZ: float = 0; /** * `_cameraZ` is dirty when the zoom factor is set last. */ _isCameraZDirty: boolean = true; /** * @param layerData The data used to initialize the layer * @param instanceContainer The container in which the layer is used */ constructor( layerData: LayerData, instanceContainer: gdjs.RuntimeInstanceContainer ) { super(layerData, instanceContainer); if ( this._defaultCameraBehavior === gdjs.RuntimeLayerDefaultCameraBehavior.TOP_LEFT_ANCHORED_IF_NEVER_MOVED ) { // If top-left must stay in the top-left corner, this means we center the camera on the current size. this._cameraX = this._runtimeScene.getViewportOriginX(); this._cameraY = this._runtimeScene.getViewportOriginY(); } else { // Otherwise, the default camera position is the center of the initial viewport. this._cameraX = (this._runtimeScene.getInitialUnrotatedViewportMinX() + this._runtimeScene.getInitialUnrotatedViewportMaxX()) / 2; this._cameraY = (this._runtimeScene.getInitialUnrotatedViewportMinY() + this._runtimeScene.getInitialUnrotatedViewportMaxY()) / 2; } if (this.getCameraType() === gdjs.RuntimeLayerCameraType.ORTHOGRAPHIC) { this._cameraZ = (this._initialCamera3DFarPlaneDistance + this._initialCamera3DNearPlaneDistance) / 2; } // Let the renderer do its final set up: this._renderer.onCreated(); } /** * Called by the RuntimeScene whenever the game resolution size is changed. * Updates the layer width/height and position. */
@@ -28,8 +28,25 @@ namespace gdjs { ) { super(layerData, instanceContainer); - this._cameraX = this.getWidth() / 2; - this._cameraY = this.getHeight() / 2; + if ( + this._defaultCameraBehavior === + gdjs.RuntimeLayerDefaultCameraBehavior + .KEEP_TOP_LEFT_FIXED_IF_NEVER_MOVED + ) { + // If top-left must stay in the top-left corner, this means we center the camera on the current size. + this._cameraX = this._runtimeScene.getViewportWidth() / 2; + this._cameraY = this._runtimeScene.getViewportHeight() / 2;
GDJS/Runtime/layer.ts
26
TypeScript
0.714
question
196
51
51
false
Fix anchor behavior and add option to center layer or keep top-left fixed when resized
7,188
4ian/GDevelop
10,154
JavaScript
D8H
4ian
// Handle scale mode. if (this._game.getScaleMode() === 'nearest') { gameCanvas.style['image-rendering'] = '-moz-crisp-edges'; gameCanvas.style['image-rendering'] = '-webkit-optimize-contrast'; gameCanvas.style['image-rendering'] = '-webkit-crisp-edges'; gameCanvas.style['image-rendering'] = 'pixelated'; } // Handle pixels rounding. if (this._game.getPixelsRounding()) { PIXI.settings.ROUND_PIXELS = true; } // Handle resize: immediately adjust the game canvas (and dom element container) // and notify the game (that may want to adjust to the new size of the window). window.addEventListener('resize', () => { this._game.onWindowInnerSizeChanged(); this._resizeCanvas(); }); // Focus the canvas when created. gameCanvas.focus(); } useCanvas(gameCanvas: HTMLCanvasElement): void { if (typeof THREE !== "undefined") { this._threeRenderer = new THREE.WebGLRenderer({ canvas: gameCanvas, antialias: this._game.getAntialiasingMode() !== "none" && (this._game.isAntialisingEnabledOnMobile() || !gdjs.evtTools.common.isMobile()), preserveDrawingBuffer: true, // Keep to true to allow screenshots. }); this._threeRenderer.useLegacyLights = true; this._threeRenderer.autoClear = false; this._threeRenderer.setSize(this._game.getGameResolutionWidth(), this._game.getGameResolutionHeight()); // Create a PixiJS renderer that use the same GL context as Three.js // so that both can render to the canvas and even have PixiJS rendering // reused in Three.js (by using a RenderTexture and the same internal WebGL texture). this._pixiRenderer = new PIXI.Renderer({ width: this._game.getGameResolutionWidth(), height: this._game.getGameResolutionHeight(), view: gameCanvas, // @ts-ignore - reuse the context from Three.js. context: this._threeRenderer.getContext(), clearBeforeRender: false, preserveDrawingBuffer: true, // Keep to true to allow screenshots. antialias: false, backgroundAlpha: 0,
There is a lot of copy from the `createStandardCanvas` function. Could you rework `createStandardCanvas` so that it's using `useCanvas` under the hood? Also, the name is probably not showing this is an important operation enough, that just can't be redone a second time. So I think it should be called `initializeForCanvas`
// Prevent magnifying glass on iOS with a long press. // Note that there are related bugs on iOS 15 (see https://bugs.webkit.org/show_bug.cgi?id=231161) // but it seems not to affect us as the `domElementsContainer` has `pointerEvents` set to `none`. domElementsContainer.style['-webkit-user-select'] = 'none'; gameCanvas.parentNode?.appendChild(domElementsContainer); this._domElementsContainer = domElementsContainer; this._resizeCanvas(); // Handle scale mode. if (this._game.getScaleMode() === 'nearest') { gameCanvas.style['image-rendering'] = '-moz-crisp-edges'; gameCanvas.style['image-rendering'] = '-webkit-optimize-contrast'; gameCanvas.style['image-rendering'] = '-webkit-crisp-edges'; gameCanvas.style['image-rendering'] = 'pixelated'; } // Handle pixels rounding. if (this._game.getPixelsRounding()) { PIXI.settings.ROUND_PIXELS = true; } // Handle resize: immediately adjust the game canvas (and dom element container) // and notify the game (that may want to adjust to the new size of the window). window.addEventListener('resize', () => { this._game.onWindowInnerSizeChanged(); this._resizeCanvas(); }); // Focus the canvas when created. gameCanvas.focus(); } static getWindowInnerWidth() { return typeof window !== 'undefined' ? window.innerWidth : 800; } static getWindowInnerHeight() { return typeof window !== 'undefined' ? window.innerHeight : 800; } /** * Update the game renderer size according to the "game resolution". * Called when game resolution changes. * * Note that if the canvas is fullscreen, it won't be resized, but when going back to * non fullscreen mode, the requested size will be used. */ updateRendererSize(): void {
@@ -189,6 +189,120 @@ namespace gdjs { gameCanvas.focus(); } + useCanvas(gameCanvas: HTMLCanvasElement): void {
GDJS/Runtime/pixi-renderers/runtimegame-pixi-renderer.ts
26
TypeScript
0.643
suggestion
326
51
51
false
Add external canvas usage to RuntimeGamePixiRenderer
7,199
4ian/GDevelop
10,154
JavaScript
4ian
danvervlad
} else { outputObjectsContainer.InsertNewObject( project, parameter.GetExtraInfo(), objectName, outputObjectsContainer.GetObjectsCount()); } // Memorize the last object name. By convention, parameters that require // an object (mainly, "objectvar" and "behavior") should be placed after // the object in the list of parameters (if possible, just after). // Search "lastObjectName" in the codebase for other place where this // convention is enforced. lastObjectName = objectName; } else if (gd::ParameterMetadata::IsBehavior(parameter.GetType())) { if (!lastObjectName.empty()) { if (outputObjectsContainer.HasObjectNamed(lastObjectName)) { const gd::String& behaviorName = parameter.GetName(); const gd::String& behaviorType = parameter.GetExtraInfo(); gd::Object& object = outputObjectsContainer.GetObject(lastObjectName); allObjectBehaviorNames[lastObjectName].insert(behaviorName); // Check if we can keep the existing behavior. if (object.HasBehaviorNamed(behaviorName)) { if (object.GetBehavior(behaviorName).GetTypeName() != behaviorType) { // Behavior type has changed, remove it so it is re-created. object.RemoveBehavior(behaviorName); } } if (!object.HasBehaviorNamed(behaviorName)) { object.AddNewBehavior( project, parameter.GetExtraInfo(), behaviorName); } } } } } // Remove objects that are not in the parameters anymore. std::set<gd::String> objectNamesInContainer = outputObjectsContainer.GetAllObjectNames(); for (const auto& objectName : objectNamesInContainer) { if (allObjectNames.find(objectName) == allObjectNames.end()) { outputObjectsContainer.RemoveObject(objectName); } } // Remove behaviors of objects that are not in the parameters anymore.
I wonder if the name can be confusing because a free function could have an object parameter without object type and the following behavior parameters be some capabilities (default behavior). It also won't be "all" the behaviors of the actual objects. I guess it's kind of the required behavior for objects passed in parameter, but "required" may be confusing as it's already used for behavior properties. ```suggestion objectAdditionnalBehaviorNames[lastObjectName].insert(behaviorName); ```
// are all present (and no more than required by the object type). // Non default behaviors coming from parameters will be added or removed later. project.EnsureObjectDefaultBehaviors(outputObjectsContainer.GetObject(objectName)); } else { // Create a new object (and its default behaviors) if needed. outputObjectsContainer.InsertNewObject( project, objectType, objectName, outputObjectsContainer.GetObjectsCount()); } // Memorize the last object name. By convention, parameters that require // an object (mainly, "objectvar" and "behavior") should be placed after // the object in the list of parameters (if possible, just after). // Search "lastObjectName" in the codebase for other place where this // convention is enforced. lastObjectName = objectName; } else if (gd::ParameterMetadata::IsBehavior(parameter.GetType())) { if (!lastObjectName.empty()) { if (outputObjectsContainer.HasObjectNamed(lastObjectName)) { const gd::String& behaviorName = parameter.GetName(); const gd::String& behaviorType = parameter.GetExtraInfo(); gd::Object& object = outputObjectsContainer.GetObject(lastObjectName); allObjectNonDefaultBehaviorNames[lastObjectName].insert(behaviorName); // Check if we can keep the existing behavior. if (object.HasBehaviorNamed(behaviorName)) { if (object.GetBehavior(behaviorName).GetTypeName() != behaviorType) { // Behavior type has changed, remove it so it is re-created. object.RemoveBehavior(behaviorName); } } if (!object.HasBehaviorNamed(behaviorName)) { object.AddNewBehavior( project, parameter.GetExtraInfo(), behaviorName); } } } } } // Remove objects that are not in the parameters anymore. std::set<gd::String> objectNamesInContainer = outputObjectsContainer.GetAllObjectNames(); for (const auto& objectName : objectNamesInContainer) { if (allObjectNames.find(objectName) == allObjectNames.end()) { outputObjectsContainer.RemoveObject(objectName);
@@ -71,7 +75,7 @@ void ParameterMetadataTools::ParametersToObjectsContainer( const gd::String& behaviorType = parameter.GetExtraInfo(); gd::Object& object = outputObjectsContainer.GetObject(lastObjectName); - allObjectBehaviorNames[lastObjectName].insert(behaviorName); + allObjectNonDefaultBehaviorNames[lastObjectName].insert(behaviorName);
Core/GDCore/Extensions/Metadata/ParameterMetadataTools.cpp
26
C++
1
suggestion
510
51
51
false
Fix default behaviors not added properly to objects in functions
7,206
4ian/GDevelop
10,154
JavaScript
D8H
4ian
parameters.removeParameter('MySpriteObject2'); expect(parameters.getParametersCount()).toBe(7); objectsContainer = new gd.ObjectsContainer(gd.ObjectsContainer.Function); gd.ParameterMetadataTools.parametersToObjectsContainer( project, parameters, objectsContainer ); // Check that object parameters are considered as objects in the objects container. expect(objectsContainer.getObjectsCount()).toBe(2); expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true); expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true); const objectWithoutType = objectsContainer.getObject('MyObjectWithoutType'); expect(objectWithoutType.getType()).toBe( '' ); const mySpriteObject = objectsContainer.getObject('MySpriteObject'); expect(objectsContainer.getObject('MySpriteObject').getType()).toBe( 'Sprite' ); // Check that behaviors were also added. expect(objectsContainer.getObject('MySpriteObject').getAllBehaviorNames().toJSArray()).toEqual( ['MyFirstBehavior', 'MySecondBehavior'] ); // Call a second time and verify no changes. gd.ParameterMetadataTools.parametersToObjectsContainer( project, parameters, objectsContainer ); expect(objectsContainer.getObjectsCount()).toBe(2); expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true); expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true); expect(objectsContainer.getObject('MySpriteObject').getAllBehaviorNames().toJSArray()).toEqual( ['MyFirstBehavior', 'MySecondBehavior'] ); // Verify that objects are even stable in memory. expect(objectWithoutType).toBe(objectsContainer.getObject('MyObjectWithoutType')); expect(gd.getPointer(objectWithoutType)).toBe(gd.getPointer(objectsContainer.getObject('MyObjectWithoutType'))); expect(mySpriteObject).toBe(objectsContainer.getObject('MySpriteObject')); expect(gd.getPointer(mySpriteObject)).toBe(gd.getPointer(objectsContainer.getObject('MySpriteObject'))); // Change an object type, rename a behavior and add a new object. parameters.getParameter("MyObjectWithoutType").setExtraInfo('Sprite');
Maybe `ObjectMetadata::AddDefaultBehavior` can be used to simulate a change of capability in a custom object.
parameters.removeParameter('MySpriteObject2'); expect(parameters.getParametersCount()).toBe(7); objectsContainer = new gd.ObjectsContainer(); gd.ParameterMetadataTools.parametersToObjectsContainer( project, parameters, objectsContainer ); // Check that object parameters are considered as objects in the objects container. expect(objectsContainer.getObjectsCount()).toBe(2); expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true); expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true); const objectWithoutType = objectsContainer.getObject( 'MyObjectWithoutType' ); expect(objectWithoutType.getType()).toBe(''); const mySpriteObject = objectsContainer.getObject('MySpriteObject'); expect(objectsContainer.getObject('MySpriteObject').getType()).toBe( 'Sprite' ); // Check that behaviors were also added AND that default behaviors are also present. expect( objectsContainer .getObject('MySpriteObject') .getAllBehaviorNames() .toJSArray() ).toEqual([ 'Animation', 'Effect', 'Flippable', 'MyFirstBehavior', 'MySecondBehavior', 'Opacity', 'Resizable', 'Scale', ]); expect( objectsContainer .getObject('MyObjectWithoutType') .getAllBehaviorNames() .toJSArray() ).toEqual([]); // Call a second time and verify no changes. gd.ParameterMetadataTools.parametersToObjectsContainer( project,
@@ -4295,19 +4295,37 @@ describe('libGD.js', function () { expect(objectsContainer.hasObjectNamed('MyObjectWithoutType')).toBe(true); expect(objectsContainer.hasObjectNamed('MySpriteObject')).toBe(true); - const objectWithoutType = objectsContainer.getObject('MyObjectWithoutType'); - expect(objectWithoutType.getType()).toBe( - '' + const objectWithoutType = objectsContainer.getObject( + 'MyObjectWithoutType' ); + expect(objectWithoutType.getType()).toBe(''); const mySpriteObject = objectsContainer.getObject('MySpriteObject'); expect(objectsContainer.getObject('MySpriteObject').getType()).toBe( 'Sprite' ); - // Check that behaviors were also added. - expect(objectsContainer.getObject('MySpriteObject').getAllBehaviorNames().toJSArray()).toEqual( - ['MyFirstBehavior', 'MySecondBehavior'] - ); + // Check that behaviors were also added AND that default behaviors are also present.
GDevelop.js/__tests__/Core.js
26
JavaScript
0.571
suggestion
109
51
51
false
Fix default behaviors not added properly to objects in functions
7,206
4ian/GDevelop
10,154
JavaScript
D8H
4ian
std::set<gd::String> objectNamesInContainer = outputObjectsContainer.GetAllObjectNames(); for (const auto& objectName : objectNamesInContainer) { if (allObjectNames.find(objectName) == allObjectNames.end()) { outputObjectsContainer.RemoveObject(objectName); } } // Remove behaviors of objects that are not in the parameters anymore. for (const auto& objectName : allObjectNames) { if (!outputObjectsContainer.HasObjectNamed(objectName)) { // Should not happen. continue; } auto& object = outputObjectsContainer.GetObject(objectName); for (const auto& behaviorName : object.GetAllBehaviorNames()) { const auto& allBehaviorNames = allObjectBehaviorNames[objectName]; if (allBehaviorNames.find(behaviorName) == allBehaviorNames.end()) { object.RemoveBehavior(behaviorName); } } } } void ParameterMetadataTools::ForEachParameterMatchingSearch( const std::vector<const ParameterMetadataContainer*>& parametersVectorsList, const gd::String& search, std::function<void(const gd::ParameterMetadata&)> cb) { for (auto it = parametersVectorsList.rbegin(); it != parametersVectorsList.rend(); ++it) { const ParameterMetadataContainer* parametersVector = *it; for (const auto &parameterMetadata : parametersVector->GetInternalVector()) { if (parameterMetadata->GetName().FindCaseInsensitive(search) != gd::String::npos) cb(*parameterMetadata); } } } bool ParameterMetadataTools::Has( const std::vector<const ParameterMetadataContainer*>& parametersVectorsList, const gd::String& parameterName) { for (auto it = parametersVectorsList.rbegin(); it != parametersVectorsList.rend(); ++it) { const ParameterMetadataContainer* parametersVector = *it;
Actually, I think it's legit to add behavior parameters to require capabilities on an object without any specified type.
} } // Remove objects that are not in the parameters anymore. std::set<gd::String> objectNamesInContainer = outputObjectsContainer.GetAllObjectNames(); for (const auto& objectName : objectNamesInContainer) { if (allObjectNames.find(objectName) == allObjectNames.end()) { outputObjectsContainer.RemoveObject(objectName); } } // Remove behaviors of objects that are not in the parameters anymore. for (const auto& objectName : allObjectNames) { if (!outputObjectsContainer.HasObjectNamed(objectName)) { // Should not happen. continue; } auto& object = outputObjectsContainer.GetObject(objectName); const auto& allBehaviorNames = allObjectNonDefaultBehaviorNames[objectName]; for (const auto& behaviorName : object.GetAllBehaviorNames()) { if (object.GetBehavior(behaviorName).IsDefaultBehavior()) { // Default behaviors are already ensured to be all present // (and no more than required by the object type). continue; } if (allBehaviorNames.find(behaviorName) == allBehaviorNames.end()) { object.RemoveBehavior(behaviorName); } } } } void ParameterMetadataTools::ForEachParameterMatchingSearch( const std::vector<const ParameterMetadataContainer*>& parametersVectorsList, const gd::String& search, std::function<void(const gd::ParameterMetadata&)> cb) { for (auto it = parametersVectorsList.rbegin(); it != parametersVectorsList.rend(); ++it) { const ParameterMetadataContainer* parametersVector = *it; for (const auto &parameterMetadata : parametersVector->GetInternalVector()) { if (parameterMetadata->GetName().FindCaseInsensitive(search) != gd::String::npos) cb(*parameterMetadata); }
@@ -108,8 +112,14 @@ void ParameterMetadataTools::ParametersToObjectsContainer( } auto& object = outputObjectsContainer.GetObject(objectName); + const auto& allBehaviorNames = allObjectNonDefaultBehaviorNames[objectName]; for (const auto& behaviorName : object.GetAllBehaviorNames()) { - const auto& allBehaviorNames = allObjectBehaviorNames[objectName]; + if (object.GetBehavior(behaviorName).IsDefaultBehavior()) { + // Default behaviors are already ensured to be all present + // (and no more than required by the object type). + continue;
Core/GDCore/Extensions/Metadata/ParameterMetadataTools.cpp
26
C++
0.5
suggestion
120
51
51
false
Fix default behaviors not added properly to objects in functions
7,206
4ian/GDevelop
10,154
JavaScript
D8H
4ian
behavior->SetDefaultBehavior(true); }; auto &objectMetadata = gd::MetadataProvider::GetObjectMetadata(platform, objectType); if (!MetadataProvider::IsBadObjectMetadata(objectMetadata)) { for (auto &behaviorType : objectMetadata.GetDefaultBehaviors()) { addDefaultBehavior(behaviorType); } } // During project deserialization, event-based object metadata are not yet // generated. Default behaviors will be added by // MetadataDeclarationHelper::UpdateCustomObjectDefaultBehaviors else if (!project.HasEventsBasedObject(objectType)) { gd::LogWarning("Object: " + name + " has an unknown type: " + objectType); } return std::move(object); } std::unique_ptr<gd::ObjectConfiguration> Project::CreateObjectConfiguration( const gd::String& type) const { if (Project::HasEventsBasedObject(type)) { return gd::make_unique<CustomObjectConfiguration>(*this, type); } else { // Create a base object if the type can't be found in the platform. return currentPlatform->CreateObjectConfiguration(type); } } bool Project::HasEventsBasedObject(const gd::String& type) const { const auto separatorIndex = type.find(PlatformExtension::GetNamespaceSeparator()); if (separatorIndex == std::string::npos) { return false; } gd::String extensionName = type.substr(0, separatorIndex); if (!Project::HasEventsFunctionsExtensionNamed(extensionName)) { return false; } auto& extension = Project::GetEventsFunctionsExtension(extensionName); gd::String objectTypeName = type.substr(separatorIndex + 2); return extension.GetEventsBasedObjects().Has(objectTypeName); } gd::EventsBasedObject& Project::GetEventsBasedObject(const gd::String& type) { const auto separatorIndex = type.find(PlatformExtension::GetNamespaceSeparator()); gd::String extensionName = type.substr(0, separatorIndex); gd::String objectTypeName = type.substr(separatorIndex + 2);
It's probably not a big issue, but instance stability won't be ensured for capabilities required for an object without any type. Unless capabilities from parameters are not marked as default behavior?
const auto& behavior = object.GetBehavior(behaviorName); if (!behavior.IsDefaultBehavior() || behavior.GetTypeName() != behaviorType) { // Behavior type has changed, remove it so it is re-created. object.RemoveBehavior(behaviorName); } } if (!object.HasBehaviorNamed(behaviorName)) { auto* behavior = object.AddNewBehavior( project, behaviorType, behaviorName); behavior->SetDefaultBehavior(true); } }; auto &objectMetadata = gd::MetadataProvider::GetObjectMetadata(platform, objectType); if (!MetadataProvider::IsBadObjectMetadata(objectMetadata)) { // Add all default behaviors. const auto& defaultBehaviorTypes = objectMetadata.GetDefaultBehaviors(); for (auto &behaviorType : defaultBehaviorTypes) { addDefaultBehavior(behaviorType); } // Ensure there are no default behaviors that would not be required left on the object. for (const auto& behaviorName : object.GetAllBehaviorNames()) { auto& behavior = object.GetBehavior(behaviorName); if (!behavior.IsDefaultBehavior()) { // Non default behaviors are not handled by this function. continue; } if (defaultBehaviorTypes.find(behavior.GetTypeName()) == defaultBehaviorTypes.end()) { object.RemoveBehavior(behaviorName); } } } // During project deserialization, event-based object metadata are not yet // generated. Default behaviors will be added by // MetadataDeclarationHelper::UpdateCustomObjectDefaultBehaviors else if (!project.HasEventsBasedObject(objectType)) { gd::LogWarning("Object: " + name + " has an unknown type: " + objectType); } } std::unique_ptr<gd::Object> Project::CreateObject( const gd::String& objectType, const gd::String& name) const { std::unique_ptr<gd::Object> object = gd::make_unique<Object>( name, objectType, CreateObjectConfiguration(objectType)); EnsureObjectDefaultBehaviors(*object);
@@ -97,24 +95,62 @@ std::unique_ptr<gd::Object> Project::CreateObject( " has an unknown default behavior: " + behaviorType); return; } - auto* behavior = object->AddNewBehavior( - project, behaviorType, behaviorMetadata.GetDefaultName()); - behavior->SetDefaultBehavior(true); + + const gd::String& behaviorName = behaviorMetadata.GetDefaultName(); + + // Check if we can keep a behavior that would have been already set up on the object. + if (object.HasBehaviorNamed(behaviorName)) { + const auto& behavior = object.GetBehavior(behaviorName); + + if (!behavior.IsDefaultBehavior() || behavior.GetTypeName() != behaviorType) { + // Behavior type has changed, remove it so it is re-created. + object.RemoveBehavior(behaviorName); + } + } + + if (!object.HasBehaviorNamed(behaviorName)) { + auto* behavior = object.AddNewBehavior( + project, behaviorType, behaviorName); + behavior->SetDefaultBehavior(true); + } }; auto &objectMetadata = gd::MetadataProvider::GetObjectMetadata(platform, objectType); if (!MetadataProvider::IsBadObjectMetadata(objectMetadata)) { - for (auto &behaviorType : objectMetadata.GetDefaultBehaviors()) { + // Add all default behaviors. + const auto& defaultBehaviorTypes = objectMetadata.GetDefaultBehaviors(); + for (auto &behaviorType : defaultBehaviorTypes) { addDefaultBehavior(behaviorType); } + + // Ensure there are no default behaviors that would not be required left on the object. + for (const auto& behaviorName : object.GetAllBehaviorNames()) {
Core/GDCore/Project/Project.cpp
26
C++
0.571
question
201
51
51
false
Fix default behaviors not added properly to objects in functions
7,206
4ian/GDevelop
10,154
JavaScript
D8H
4ian
import { getRelativeOrAbsoluteDisplayDate } from '../Utils/DateDisplay'; const electron = optionalRequire('electron'); const path = optionalRequire('path'); export const getThumbnailWidth = ({ isMobile }: {| isMobile: boolean |}) => isMobile ? undefined : Math.min(245, Math.max(130, window.innerWidth / 4)); export const getProjectDisplayDate = (i18n: I18nType, date: number) => getRelativeOrAbsoluteDisplayDate({ i18n, dateAsNumber: date, sameDayFormat: 'todayAndHour', dayBeforeFormat: 'yesterdayAndHour', relativeLimit: 'currentWeek', sameWeekFormat: 'thisWeek', }); export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) => i18n.date(date, { dateStyle: 'short', timeStyle: 'short', }); const getNoProjectAlertMessage = () => { if (!electron) { // Trying to open a local project from the web app of the mobile app. return t`Looks like your project isn't there!${'\n\n'}Your project is surely stored on your computer.`; } else { return t`We couldn't find your project.${'\n\n'}If your project is stored on a different computer, launch GDevelop on that computer.${'\n'}Otherwise, use the "Open project" button and find it in your filesystem.`; } }; const styles = { tooltipButtonContainer: { display: 'flex', flexDirection: 'column', alignItems: 'stretch', }, buttonsContainer: { display: 'flex', flexShrink: 0, flexDirection: 'column', justifyContent: 'center', }, iconAndText: { display: 'flex', gap: 2, alignItems: 'flex-start' }, title: { ...textEllipsisStyle, overflowWrap: 'break-word', }, projectFilesButton: { minWidth: 32 }, fileIcon: { width: 16,
I'd rather say `Your project must be stored on your computer` rather than surely, it feels more english
import { getRelativeOrAbsoluteDisplayDate } from '../Utils/DateDisplay'; const electron = optionalRequire('electron'); const path = optionalRequire('path'); export const getThumbnailWidth = ({ isMobile }: {| isMobile: boolean |}) => isMobile ? undefined : Math.min(245, Math.max(130, window.innerWidth / 4)); export const getProjectDisplayDate = (i18n: I18nType, date: number) => getRelativeOrAbsoluteDisplayDate({ i18n, dateAsNumber: date, sameDayFormat: 'todayAndHour', dayBeforeFormat: 'yesterdayAndHour', relativeLimit: 'currentWeek', sameWeekFormat: 'thisWeek', }); export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) => i18n.date(date, { dateStyle: 'short', timeStyle: 'short', }); const getNoProjectAlertMessage = () => { if (!electron) { // Trying to open a local project from the web app of the mobile app. return t`Looks like your project isn't there!${'\n\n'}Your project must be stored on your computer.`; } else { return t`We couldn't find your project.${'\n\n'}If your project is stored on a different computer, launch GDevelop on that computer.${'\n'}Otherwise, use the "Open project" button and find it in your filesystem.`; } }; const styles = { tooltipButtonContainer: { display: 'flex', flexDirection: 'column', alignItems: 'stretch', }, buttonsContainer: { display: 'flex', flexShrink: 0, flexDirection: 'column', justifyContent: 'center', }, iconAndText: { display: 'flex', gap: 2, alignItems: 'flex-start' }, title: { ...textEllipsisStyle, overflowWrap: 'break-word', }, projectFilesButton: { minWidth: 32 }, fileIcon: { width: 16,
@@ -50,13 +51,37 @@ import PreferencesContext from '../MainFrame/Preferences/PreferencesContext'; import { textEllipsisStyle } from '../UI/TextEllipsis'; import FileWithLines from '../UI/CustomSvgIcons/FileWithLines'; import TextButton from '../UI/TextButton'; -import { Tooltip } from '@material-ui/core'; +import { getRelativeOrAbsoluteDisplayDate } from '../Utils/DateDisplay'; const electron = optionalRequire('electron'); const path = optionalRequire('path'); export const getThumbnailWidth = ({ isMobile }: {| isMobile: boolean |}) => isMobile ? undefined : Math.min(245, Math.max(130, window.innerWidth / 4)); +export const getProjectDisplayDate = (i18n: I18nType, date: number) => + getRelativeOrAbsoluteDisplayDate({ + i18n, + dateAsNumber: date, + sameDayFormat: 'todayAndHour', + dayBeforeFormat: 'yesterdayAndHour', + relativeLimit: 'currentWeek', + sameWeekFormat: 'thisWeek', + }); +export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) => + i18n.date(date, { + dateStyle: 'short', + timeStyle: 'short', + }); + +const getNoProjectAlertMessage = () => { + if (!electron) { + // Trying to open a local project from the web app of the mobile app. + return t`Looks like your project isn't there!${'\n\n'}Your project is surely stored on your computer.`;
newIDE/app/src/GameDashboard/GameDashboardCard.js
26
JavaScript
0.5
suggestion
103
51
51
false
Polishing the new Create tab
7,236
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) => i18n.date(date, { dateStyle: 'short', timeStyle: 'short', }); const getNoProjectAlertMessage = () => { if (!electron) { // Trying to open a local project from the web app of the mobile app. return t`Looks like your project isn't there!${'\n\n'}Your project is surely stored on your computer.`; } else { return t`We couldn't find your project.${'\n\n'}If your project is stored on a different computer, launch GDevelop on that computer.${'\n'}Otherwise, use the "Open project" button and find it in your filesystem.`; } }; const styles = { tooltipButtonContainer: { display: 'flex', flexDirection: 'column', alignItems: 'stretch', }, buttonsContainer: { display: 'flex', flexShrink: 0, flexDirection: 'column', justifyContent: 'center', }, iconAndText: { display: 'flex', gap: 2, alignItems: 'flex-start' }, title: { ...textEllipsisStyle, overflowWrap: 'break-word', }, projectFilesButton: { minWidth: 32 }, fileIcon: { width: 16, height: 16, }, }; const locateProjectFile = (file: FileMetadataAndStorageProviderName) => { if (!electron) return; electron.shell.showItemInFolder( path.resolve(file.fileMetadata.fileIdentifier) ); }; const getFileNameWithoutExtensionFromPath = (path: string) => { // Normalize path separators for cross-platform compatibility const normalizedPath = path.replace(/\\/g, '/'); // Extract file name
maybe double check landscape/mobile/etc...
export const getDetailedProjectDisplayDate = (i18n: I18nType, date: number) => i18n.date(date, { dateStyle: 'short', timeStyle: 'short', }); const getNoProjectAlertMessage = () => { if (!electron) { // Trying to open a local project from the web app of the mobile app. return t`Looks like your project isn't there!${'\n\n'}Your project must be stored on your computer.`; } else { return t`We couldn't find your project.${'\n\n'}If your project is stored on a different computer, launch GDevelop on that computer.${'\n'}Otherwise, use the "Open project" button and find it in your filesystem.`; } }; const styles = { tooltipButtonContainer: { display: 'flex', flexDirection: 'column', alignItems: 'stretch', }, buttonsContainer: { display: 'flex', flexShrink: 0, flexDirection: 'column', justifyContent: 'center', }, iconAndText: { display: 'flex', gap: 2, alignItems: 'flex-start' }, title: { ...textEllipsisStyle, overflowWrap: 'break-word', }, projectFilesButton: { minWidth: 32 }, fileIcon: { width: 16, height: 16, }, }; const locateProjectFile = (file: FileMetadataAndStorageProviderName) => { if (!electron) return; electron.shell.showItemInFolder( path.resolve(file.fileMetadata.fileIdentifier) ); }; const getFileNameWithoutExtensionFromPath = (path: string) => { // Normalize path separators for cross-platform compatibility const normalizedPath = path.replace(/\\/g, '/'); // Extract file name
@@ -67,7 +92,7 @@ const styles = { display: 'flex', flexShrink: 0, flexDirection: 'column', - justifyContent: 'flex-end', + justifyContent: 'center',
newIDE/app/src/GameDashboard/GameDashboardCard.js
26
JavaScript
0.071
suggestion
43
51
51
false
Polishing the new Create tab
7,236
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
newSaveAsOptions = saveAsOptions; } if (canFileMetadataBeSafelySavedAs && currentFileMetadata) { const canProjectBeSafelySavedAs = await canFileMetadataBeSafelySavedAs( currentFileMetadata, { showAlert, showConfirmation, } ); if (!canProjectBeSafelySavedAs) return; } let originalProjectUuid = null; if (newSaveAsOptions && newSaveAsOptions.generateNewProjectUuid) { originalProjectUuid = currentProject.getProjectUuid(); currentProject.resetProjectUuid(); } let originalProjectName = null; const newProjectName = newSaveAsLocation && newSaveAsLocation.name ? newSaveAsLocation.name : null; if (newProjectName) { originalProjectName = currentProject.getName(); currentProject.setName(newProjectName); } const { wasSaved, fileMetadata } = await onSaveProjectAs( currentProject, newSaveAsLocation, { onStartSaving: () => _replaceSnackMessage(i18n._(t`Saving...`), null), onMoveResources: async ({ newFileMetadata }) => { if (currentFileMetadata) await ensureResourcesAreMoved({ project: currentProject, newFileMetadata, newStorageProvider, newStorageProviderOperations, oldFileMetadata: currentFileMetadata, oldStorageProvider, oldStorageProviderOperations, authenticatedUser, }); }, } );
just double checking this will not affect the initial project? I assume not as we're not saving that project
// ... or if the project is opened from a URL. oldStorageProvider.internalName !== 'UrlStorageProvider', }); if (!saveAsLocation) { return; // Save as was cancelled. } newSaveAsLocation = saveAsLocation; newSaveAsOptions = saveAsOptions; } if (canFileMetadataBeSafelySavedAs && currentFileMetadata) { const canProjectBeSafelySavedAs = await canFileMetadataBeSafelySavedAs( currentFileMetadata, { showAlert, showConfirmation, } ); if (!canProjectBeSafelySavedAs) return; } let originalProjectUuid = null; if (newSaveAsOptions && newSaveAsOptions.generateNewProjectUuid) { originalProjectUuid = currentProject.getProjectUuid(); currentProject.resetProjectUuid(); } let originalProjectName = null; const newProjectName = newSaveAsLocation && newSaveAsLocation.name ? newSaveAsLocation.name : null; if (newProjectName) { originalProjectName = currentProject.getName(); currentProject.setName(newProjectName); } const { wasSaved, fileMetadata } = await onSaveProjectAs( currentProject, newSaveAsLocation, { onStartSaving: () => _replaceSnackMessage(i18n._(t`Saving...`), null), onMoveResources: async ({ newFileMetadata }) => { if (currentFileMetadata) await ensureResourcesAreMoved({ project: currentProject, newFileMetadata, newStorageProvider, newStorageProviderOperations, oldFileMetadata: currentFileMetadata,
@@ -2627,6 +2633,21 @@ const MainFrame = (props: Props) => { if (!canProjectBeSafelySavedAs) return; } + let originalProjectUuid = null; + if (newSaveAsOptions && newSaveAsOptions.generateNewProjectUuid) { + originalProjectUuid = currentProject.getProjectUuid(); + currentProject.resetProjectUuid();
newIDE/app/src/MainFrame/index.js
26
JavaScript
0.357
suggestion
109
51
51
false
When duplicating a project, ask for the new name and if link with game should be kept
7,253
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
|}) => async ({ project, fileMetadata, }: {| project: gdProject, fileMetadata: ?FileMetadata, |}): Promise<{| saveAsLocation: ?SaveAsLocation, saveAsOptions: ?SaveAsOptions, |}> => { if (!authenticatedUser.authenticated) { return { saveAsLocation: null, saveAsOptions: null }; } const options = await new Promise(resolve => { setDialog(() => ( <SaveAsOptionsDialog onCancel={() => { closeDialog(); resolve(null); }} nameMaxLength={CLOUD_PROJECT_NAME_MAX_LENGTH} nameSuggestion={ fileMetadata ? `${project.getName()} - Copy` : project.getName() } shouldAskForGameLinkRemoval={!!fileMetadata && !!fileMetadata.gameId} onSave={options => { closeDialog(); resolve(options); }} /> )); }); if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. return { saveAsLocation: { name: options.name, }, saveAsOptions: { generateNewProjectUuid: options.generateNewProjectUuid, }, }; }; export const generateOnSaveProjectAs = ( authenticatedUser: AuthenticatedUser, setDialog: (() => React.Node) => void, closeDialog: () => void ) => async (
maybe name this prop `shouldAskForNewProjectUuid` to be consistent with the props you use in the component?
|}) => async ({ project, fileMetadata, displayOptionToGenerateNewProjectUuid, }: {| project: gdProject, fileMetadata: ?FileMetadata, displayOptionToGenerateNewProjectUuid: boolean, |}): Promise<{| saveAsLocation: ?SaveAsLocation, saveAsOptions: ?SaveAsOptions, |}> => { if (!authenticatedUser.authenticated) { return { saveAsLocation: null, saveAsOptions: null }; } const options = await new Promise(resolve => { setDialog(() => ( <SaveAsOptionsDialog onCancel={() => { closeDialog(); resolve(null); }} nameMaxLength={CLOUD_PROJECT_NAME_MAX_LENGTH} nameSuggestion={ fileMetadata ? `${project.getName()} - Copy` : project.getName() } displayOptionToGenerateNewProjectUuid={ displayOptionToGenerateNewProjectUuid } onSave={options => { closeDialog(); resolve(options); }} /> )); }); if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. return { saveAsLocation: { name: options.name, }, saveAsOptions: { generateNewProjectUuid: options.generateNewProjectUuid, }, }; }; export const generateOnSaveProjectAs = (
@@ -189,33 +190,40 @@ export const generateOnChooseSaveProjectAsLocation = ({ fileMetadata: ?FileMetadata, |}): Promise<{| saveAsLocation: ?SaveAsLocation, + saveAsOptions: ?SaveAsOptions, |}> => { if (!authenticatedUser.authenticated) { - return { saveAsLocation: null }; + return { saveAsLocation: null, saveAsOptions: null }; } - const name = await new Promise(resolve => { + const options = await new Promise(resolve => { setDialog(() => ( - <CloudSaveAsDialog + <SaveAsOptionsDialog onCancel={() => { closeDialog(); resolve(null); }} - nameSuggestion={project.getName()} - onSave={(newName: string) => { + nameMaxLength={CLOUD_PROJECT_NAME_MAX_LENGTH} + nameSuggestion={ + fileMetadata ? `${project.getName()} - Copy` : project.getName() + } + shouldAskForGameLinkRemoval={!!fileMetadata && !!fileMetadata.gameId}
newIDE/app/src/ProjectsStorage/CloudStorageProvider/CloudProjectWriter.js
26
JavaScript
0.571
question
107
51
51
false
When duplicating a project, ask for the new name and if link with game should be kept
7,253
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
return { saveAsLocation: { name: options.name, }, saveAsOptions: { generateNewProjectUuid: options.generateNewProjectUuid, }, }; }; export const generateOnSaveProjectAs = ( authenticatedUser: AuthenticatedUser, setDialog: (() => React.Node) => void, closeDialog: () => void ) => async ( project: gdProject, saveAsLocation: ?SaveAsLocation, options: {| onStartSaving: () => void, onMoveResources: ({| newFileMetadata: FileMetadata, |}) => Promise<void>, |} ) => { if (!saveAsLocation) throw new Error('A location was not chosen before saving as.'); const { name } = saveAsLocation; if (!name) throw new Error('A name was not chosen before saving as.'); if (!authenticatedUser.authenticated) { return { wasSaved: false, fileMetadata: null }; } options.onStartSaving(); const gameId = project.getProjectUuid(); try { // Create a new cloud project. const cloudProject = await createCloudProject(authenticatedUser, { name, gameId, }); if (!cloudProject) throw new Error('No cloud project was returned from creation api call.'); const cloudProjectId = cloudProject.id; const fileMetadata: FileMetadata = { fileIdentifier: cloudProjectId, gameId, }; // Move the resources to the new project.
why this change? was this not used?
}); if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. return { saveAsLocation: { name: options.name, }, saveAsOptions: { generateNewProjectUuid: options.generateNewProjectUuid, }, }; }; export const generateOnSaveProjectAs = ( authenticatedUser: AuthenticatedUser, setDialog: (() => React.Node) => void, closeDialog: () => void ) => async ( project: gdProject, saveAsLocation: ?SaveAsLocation, options: {| onStartSaving: () => void, onMoveResources: ({| newFileMetadata: FileMetadata, |}) => Promise<void>, |} ) => { if (!saveAsLocation) throw new Error('A location was not chosen before saving as.'); const { name } = saveAsLocation; if (!name) throw new Error('A name was not chosen before saving as.'); if (!authenticatedUser.authenticated) { return { wasSaved: false, fileMetadata: null }; } options.onStartSaving(); const gameId = project.getProjectUuid(); try { // Create a new cloud project. const cloudProject = await createCloudProject(authenticatedUser, { name, gameId, }); if (!cloudProject) throw new Error('No cloud project was returned from creation api call.'); const cloudProjectId = cloudProject.id; const fileMetadata: FileMetadata = { fileIdentifier: cloudProjectId,
@@ -243,7 +251,7 @@ export const generateOnSaveProjectAs = ( } options.onStartSaving(); - const gameId = saveAsLocation.gameId || project.getProjectUuid();
newIDE/app/src/ProjectsStorage/CloudStorageProvider/CloudProjectWriter.js
26
JavaScript
0.143
question
35
51
51
false
When duplicating a project, ask for the new name and if link with game should be kept
7,253
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
|}> => { const options = await new Promise(resolve => { setDialog(() => ( <SaveAsOptionsDialog onCancel={() => { closeDialog(); resolve(null); }} nameSuggestion={ fileMetadata ? `${project.getName()} - Copy` : project.getName() } mainActionLabel={<Trans>Continue</Trans>} shouldAskForGameLinkRemoval={!!fileMetadata && !!fileMetadata.gameId} onSave={options => { closeDialog(); resolve(options); }} /> )); }); if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. let defaultPath = fileMetadata ? fileMetadata.fileIdentifier : ''; if (path && defaultPath) { defaultPath = path.join(path.dirname(defaultPath), `${options.name}.json`); } const browserWindow = remote.getCurrentWindow(); const saveDialogOptions = { defaultPath, filters: [{ name: 'GDevelop 5 project', extensions: ['json'] }], }; if (!dialog) { throw new Error('Unsupported'); } const filePath = dialog.showSaveDialogSync(browserWindow, saveDialogOptions); if (!filePath) { return { saveAsLocation: null, saveAsOptions: null }; } return { saveAsLocation: { name: options.name, fileIdentifier: filePath, }, saveAsOptions: { generateNewProjectUuid: options.generateNewProjectUuid, }, };
any risk the `options.name` results in a filename that is not compatible with path? like with '/' in it?
saveAsLocation: ?SaveAsLocation, // This is the newly chosen location (or null if cancelled). saveAsOptions: ?SaveAsOptions, |}> => { const options = await new Promise(resolve => { setDialog(() => ( <SaveAsOptionsDialog onCancel={() => { closeDialog(); resolve(null); }} nameSuggestion={ fileMetadata ? `${project.getName()} - Copy` : project.getName() } mainActionLabel={<Trans>Continue</Trans>} displayOptionToGenerateNewProjectUuid={ displayOptionToGenerateNewProjectUuid } onSave={options => { closeDialog(); resolve(options); }} /> )); }); if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. let defaultPath = fileMetadata ? fileMetadata.fileIdentifier : ''; const { name } = options; if (path && defaultPath && name) { const safeFilename = name.replace(/[<>:"/\\|?*]/g, '_'); defaultPath = path.join(path.dirname(defaultPath), `${safeFilename}.json`); } const browserWindow = remote.getCurrentWindow(); const saveDialogOptions = { defaultPath, filters: [{ name: 'GDevelop 5 project', extensions: ['json'] }], }; if (!dialog) { throw new Error('Unsupported'); } const filePath = dialog.showSaveDialogSync(browserWindow, saveDialogOptions); if (!filePath) { return { saveAsLocation: null, saveAsOptions: null }; } return { saveAsLocation: { name: options.name,
@@ -180,16 +185,49 @@ export const onSaveProject = async ( }; }; -export const onChooseSaveProjectAsLocation = async ({ +export const generateOnChooseSaveProjectAsLocation = ({ + setDialog, + closeDialog, +}: { + setDialog: (() => React.Node) => void, + closeDialog: () => void, +}) => async ({ project, fileMetadata, }: {| project: gdProject, fileMetadata: ?FileMetadata, // This is the current location. |}): Promise<{| saveAsLocation: ?SaveAsLocation, // This is the newly chosen location (or null if cancelled). + saveAsOptions: ?SaveAsOptions, |}> => { - const defaultPath = fileMetadata ? fileMetadata.fileIdentifier : ''; + const options = await new Promise(resolve => { + setDialog(() => ( + <SaveAsOptionsDialog + onCancel={() => { + closeDialog(); + resolve(null); + }} + nameSuggestion={ + fileMetadata ? `${project.getName()} - Copy` : project.getName() + } + mainActionLabel={<Trans>Continue</Trans>} + shouldAskForGameLinkRemoval={!!fileMetadata && !!fileMetadata.gameId} + onSave={options => { + closeDialog(); + resolve(options); + }} + /> + )); + }); + + if (!options) return { saveAsLocation: null, saveAsOptions: null }; // Save was cancelled. + + let defaultPath = fileMetadata ? fileMetadata.fileIdentifier : ''; + if (path && defaultPath) { + defaultPath = path.join(path.dirname(defaultPath), `${options.name}.json`);
newIDE/app/src/ProjectsStorage/LocalFileStorageProvider/LocalProjectWriter.js
26
JavaScript
0.5
question
104
51
51
false
When duplicating a project, ask for the new name and if link with game should be kept
7,253
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
) : ( <Text> <Trans>You don't have any feedback for this game.</Trans> </Text> )} </> )} {displayedFeedbacksArray.length !== 0 && ( <ColumnStackLayout expand noMargin> {Object.keys(displayedFeedbacks).map((key, index) => { const title = sortByDate ? key : getBuildNameTitle(key); return ( <ColumnStackLayout key={key} noMargin> <Line justifyContent="space-between" alignItems="center" > <Column> <Text size="block-title"> {title} {title ? ' - ' : ' '} {displayedFeedbacks[key].length === 1 ? ( <Trans>1 review</Trans> ) : ( <Trans> {displayedFeedbacks[key].length} reviews </Trans> )} </Text> </Column> {index === 0 && ( <Column justifyContent="center"> <IconButton disabled={isMarkingAllAsProcessed} onClick={event => openOptionsContextMenu(event)} > {!isMarkingAllAsProcessed ? ( <Options fontSize="small" /> ) : ( <CircularProgress size={20} /> )} </IconButton> </Column> )} </Line> {displayedFeedbacks[key].map( (comment: Comment, index: number) => ( <FeedbackCard key={comment.id} comment={comment} buildProperties={getBuildPropertiesForComment(
I don't think that's useful, let's not do it
value={''} label={t`All exports`} /> <SelectOption key={'game-only'} value={'game-only'} label={t`On game page only`} /> {Object.keys(buildsByIds).map(buildId => { return ( <SelectOption key={buildId} value={buildId} label={getBuildNameOption(buildId)} /> ); })} </SelectField> </div> </Line> </Column> )} </ResponsiveLineStackLayout> <ColumnStackLayout expand noMargin> {!!feedbacks && feedbacks.length > 0 && ( // TODO: Should it display the data for the filtered pieces of feedback only? <FeedbackAverageCard feedbacks={feedbacks} /> )} </ColumnStackLayout> {displayedFeedbacks.length === 0 && ( <> {showProcessed ? ( <LineStackLayout alignItems="center" justifyContent="center" > <EmptyMessage> {isShowingCommentsForASpecificBuild ? ( <Trans> You don't have any unread feedback for this export. </Trans> ) : ( <Trans> You don't have any unread feedback for this game. </Trans> )} </EmptyMessage> <FlatButton onClick={() => setShowProcessed(false)} label={<Trans>Show all feedbacks</Trans>} />
@@ -374,89 +419,154 @@ const GameFeedback = ({ i18n, authenticatedUser, game }: Props) => { </ResponsiveLineStackLayout> <ColumnStackLayout expand noMargin> {!!feedbacks && feedbacks.length > 0 && ( + // TODO: Should it display the data for the filtered pieces of feedback only?
newIDE/app/src/GameDashboard/Feedbacks/GameFeedback.js
26
JavaScript
0.143
suggestion
44
51
51
false
Paginate feedbacks
7,259
4ian/GDevelop
10,154
JavaScript
4ian
AlexandreSi
// - The normal keeps the same length (as the normal is included in the 2D space) this._slopeClimbingMinNormalZ = Math.min( Math.cos(gdjs.toRad(slopeMaxAngle)), 1 - 1 / 1024 ); } getStairHeightMax(): float { return this._stairHeightMax; } setStairHeightMax(stairHeightMax: float): void { const { extendedUpdateSettings } = this.getPhysics3D(); this._stairHeightMax = stairHeightMax; console.log(stairHeightMax); const walkStairsStepUp = stairHeightMax * this._sharedData.worldInvScale; extendedUpdateSettings.mWalkStairsStepUp = this.getVec3( 0, 0, walkStairsStepUp ); // Use default values proportionally; extendedUpdateSettings.mWalkStairsMinStepForward = (0.02 / 0.4) * walkStairsStepUp; extendedUpdateSettings.mWalkStairsStepForwardTest = (0.15 / 0.4) * walkStairsStepUp; } /** * Get the gravity of the Character. * @returns The current gravity. */ getGravity(): float { return this._gravity; } /** * Set the gravity of the Character. * @param gravity The new gravity. */ setGravity(gravity: float): void { this._gravity = gravity; } /** * Get the maximum falling speed of the Character. * @returns The maximum falling speed. */ getMaxFallingSpeed(): float { return this._maxFallingSpeed; }
Is there an explanation for those factors?
// - The normal keeps the same length (as the normal is included in the 2D space) this._slopeClimbingMinNormalZ = Math.min( Math.cos(gdjs.toRad(slopeMaxAngle)), 1 - 1 / 1024 ); } getStairHeightMax(): float { return this._stairHeightMax; } setStairHeightMax(stairHeightMax: float): void { const { extendedUpdateSettings } = this.getPhysics3D(); this._stairHeightMax = stairHeightMax; const walkStairsStepUp = stairHeightMax * this._sharedData.worldInvScale; extendedUpdateSettings.mWalkStairsStepUp = this.getVec3( 0, 0, walkStairsStepUp ); // Use default values proportionally; // "The factors are arbitrary but works well when tested in a game." extendedUpdateSettings.mWalkStairsMinStepForward = (0.02 / 0.4) * walkStairsStepUp; extendedUpdateSettings.mWalkStairsStepForwardTest = (0.15 / 0.4) * walkStairsStepUp; } /** * Get the gravity of the Character. * @returns The current gravity. */ getGravity(): float { return this._gravity; } /** * Set the gravity of the Character. * @param gravity The new gravity. */ setGravity(gravity: float): void { this._gravity = gravity; } /** * Get the maximum falling speed of the Character. * @returns The maximum falling speed. */ getMaxFallingSpeed(): float { return this._maxFallingSpeed; }
@@ -783,6 +791,27 @@ namespace gdjs { ); } + getStairHeightMax(): float { + return this._stairHeightMax; + } + + setStairHeightMax(stairHeightMax: float): void { + const { extendedUpdateSettings } = this.getPhysics3D(); + this._stairHeightMax = stairHeightMax; + console.log(stairHeightMax); + const walkStairsStepUp = stairHeightMax * this._sharedData.worldInvScale; + extendedUpdateSettings.mWalkStairsStepUp = this.getVec3( + 0, + 0, + walkStairsStepUp + ); + // Use default values proportionally; + extendedUpdateSettings.mWalkStairsMinStepForward = + (0.02 / 0.4) * walkStairsStepUp; + extendedUpdateSettings.mWalkStairsStepForwardTest = + (0.15 / 0.4) * walkStairsStepUp;
Extensions/Physics3DBehavior/PhysicsCharacter3DRuntimeBehavior.ts
26
TypeScript
0.071
question
42
51
51
false
Add a property to choose the maximum stair height a 3D character can walk
7,265
4ian/GDevelop
10,154
JavaScript
AlexandreSi
D8H
}); if (output.code !== 0) { shell.exit(0); } }); // Copy the GDJS runtime and extension sources (used for autocompletions // in the IDE). This is optional as this takes a lot of time that would add // up whenever any change is made. if (!args['skip-sources']) { shell.echo( `ℹ️ Copying GDJS and extensions runtime sources to ${destinationPaths.join( ', ' )}...` ); destinationPaths.forEach(destinationPath => { const copyOptions = { overwrite: true, expand: true, dot: true, junk: true, }; const startTime = Date.now(); const pixiDestinationPath = path.join(destinationPath, 'Runtime-sources', 'pixi'); // TODO: Investigate the use of a smart & faster sync // that only copy files with changed content. return Promise.all([ copy( path.join(gdevelopRootPath, 'GDJS', 'Runtime'), path.join(destinationPath, 'Runtime-sources'), copyOptions ), copy( path.join(gdevelopRootPath, 'Extensions'), path.join(destinationPath, 'Runtime-sources', 'Extensions'), { ...copyOptions, filter: ['**/*.js', '**/*.ts'] } ), copy( path.join(gdevelopRootPath, 'GDJS', 'node_modules', '@types', 'three'), path.join(destinationPath, 'Runtime-sources', 'three'), { ...copyOptions, filter: ['*.d.ts'] } ), copy( path.join(gdevelopRootPath, 'GDJS', 'node_modules', '@types', 'three', 'src'), path.join(destinationPath, 'Runtime-sources', 'three', 'src'), { ...copyOptions, filter: ['**/*.d.ts'] } ), copy( path.join(gdevelopRootPath, 'GDJS', 'node_modules', '@pixi'),
Should `pixi` and `three` be a sub-folders of `libs`?
cwd: path.join(gdevelopRootPath, 'GDJS'), }); if (output.code !== 0) { shell.exit(0); } }); // Copy the GDJS runtime and extension sources (used for autocompletions // in the IDE). This is optional as this takes a lot of time that would add // up whenever any change is made. if (!args['skip-sources']) { shell.echo( `ℹ️ Copying GDJS and extensions runtime sources to ${destinationPaths.join( ', ' )}...` ); destinationPaths.forEach(destinationPath => { const copyOptions = { overwrite: true, expand: true, dot: true, junk: true, }; const startTime = Date.now(); const typesDestinationPath = path.join(destinationPath, 'Runtime-sources', 'types'); const pixiDestinationPath = path.join(typesDestinationPath, 'pixi'); // TODO: Investigate the use of a smart & faster sync // that only copy files with changed content. return Promise.all([ copy( path.join(gdevelopRootPath, 'GDJS', 'Runtime'), path.join(destinationPath, 'Runtime-sources'), copyOptions ), copy( path.join(gdevelopRootPath, 'Extensions'), path.join(destinationPath, 'Runtime-sources', 'Extensions'), { ...copyOptions, filter: ['**/*.js', '**/*.ts'] } ), copy( path.join(gdevelopRootPath, 'GDJS', 'node_modules', '@types', 'three'), path.join(typesDestinationPath, 'three'), { ...copyOptions, filter: ['*.d.ts'] } ), copy( path.join(gdevelopRootPath, 'GDJS', 'node_modules', '@types', 'three', 'src'), path.join(typesDestinationPath, 'three', 'src'), { ...copyOptions, filter: ['**/*.d.ts'] } ),
@@ -53,6 +53,7 @@ if (!args['skip-sources']) { const startTime = Date.now(); + const pixiDestinationPath = path.join(destinationPath, 'Runtime-sources', 'pixi');
newIDE/app/scripts/import-GDJS-Runtime.js
26
JavaScript
0.429
question
53
51
51
false
Add Pixi and Three type definitions for JS events
7,266
4ian/GDevelop
10,154
JavaScript
D8H
D8H
onChange(); }} /> <Checkbox label={<Trans>Expand inner area with parent</Trans>} checked={eventsBasedObject.isInnerAreaFollowingParentSize()} onCheck={(e, checked) => { eventsBasedObject.markAsInnerAreaFollowingParentSize(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} /> {isDev && ( <Checkbox label={<Trans>Use legacy renderer</Trans>} checked={eventsBasedObject.isUsingLegacyInstancesRenderer()} onCheck={(e, checked) => { eventsBasedObject.makAsUsingLegacyInstancesRenderer(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} /> )} <Checkbox label={<Trans>Private</Trans>} checked={eventsBasedObject.isPrivate()} onCheck={(e, checked) => { eventsBasedObject.setPrivate(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} /> <Line noMargin justifyContent="center"> <RaisedButton label={<Trans>Open visual editor for the object</Trans>} primary onClick={onOpenCustomObjectEditor} /> </Line> <Line noMargin> <HelpButton key="help" helpPagePath="/objects/custom-objects-prefab-template" /> </Line> </ColumnStackLayout> ); }
```suggestion label={<Trans>Private (can only be used inside the extension)</Trans>} ```
eventsBasedObject.markAsTextContainer(checked); onChange(); }} /> <Checkbox label={<Trans>Expand inner area with parent</Trans>} checked={eventsBasedObject.isInnerAreaFollowingParentSize()} onCheck={(e, checked) => { eventsBasedObject.markAsInnerAreaFollowingParentSize(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} /> {isDev && ( <Checkbox label={<Trans>Use legacy renderer</Trans>} checked={eventsBasedObject.isUsingLegacyInstancesRenderer()} onCheck={(e, checked) => { eventsBasedObject.makAsUsingLegacyInstancesRenderer(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} /> )} <Checkbox label={<Trans>Private</Trans>} checked={eventsBasedObject.isPrivate()} onCheck={(e, checked) => { eventsBasedObject.setPrivate(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} tooltipOrHelperText={ eventsBasedObject.isPrivate() ? ( <Trans> This object won't be visible in the scene and events editors. </Trans> ) : ( <Trans> This object will be visible in the scene and events editors. </Trans> ) } /> <Line noMargin justifyContent="center"> <RaisedButton label={<Trans>Open visual editor for the object</Trans>} primary onClick={onOpenCustomObjectEditor} /> </Line>
@@ -141,6 +141,15 @@ export default function EventsBasedObjectEditor({ }} /> )} + <Checkbox + label={<Trans>Private</Trans>}
newIDE/app/src/EventsBasedObjectEditor/index.js
26
JavaScript
0.643
suggestion
98
49
51
false
Allow to make custom objects private to an extension
7,275
4ian/GDevelop
10,154
JavaScript
4ian
D8H
eventsBasedObject.markAsTextContainer(checked); onChange(); }} /> <Checkbox label={<Trans>Expand inner area with parent</Trans>} checked={eventsBasedObject.isInnerAreaFollowingParentSize()} onCheck={(e, checked) => { eventsBasedObject.markAsInnerAreaFollowingParentSize(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} /> {isDev && ( <Checkbox label={<Trans>Use legacy renderer</Trans>} checked={eventsBasedObject.isUsingLegacyInstancesRenderer()} onCheck={(e, checked) => { eventsBasedObject.makAsUsingLegacyInstancesRenderer(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} /> )} <Checkbox label={<Trans>Private (can only be used inside the extension)</Trans>} checked={eventsBasedObject.isPrivate()} onCheck={(e, checked) => { eventsBasedObject.setPrivate(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} /> <Line noMargin justifyContent="center"> <RaisedButton label={<Trans>Open visual editor for the object</Trans>} primary onClick={onOpenCustomObjectEditor} /> </Line> <Line noMargin> <HelpButton key="help" helpPagePath="/objects/custom-objects-prefab-template" /> </Line> </ColumnStackLayout> ); }
Won't it be a bit heavy? Should it be a tool tip?
onCheck={(e, checked) => { eventsBasedObject.markAsTextContainer(checked); onChange(); }} /> <Checkbox label={<Trans>Expand inner area with parent</Trans>} checked={eventsBasedObject.isInnerAreaFollowingParentSize()} onCheck={(e, checked) => { eventsBasedObject.markAsInnerAreaFollowingParentSize(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} /> {isDev && ( <Checkbox label={<Trans>Use legacy renderer</Trans>} checked={eventsBasedObject.isUsingLegacyInstancesRenderer()} onCheck={(e, checked) => { eventsBasedObject.makAsUsingLegacyInstancesRenderer(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} /> )} <Checkbox label={<Trans>Private</Trans>} checked={eventsBasedObject.isPrivate()} onCheck={(e, checked) => { eventsBasedObject.setPrivate(checked); onChange(); onEventsBasedObjectChildrenEdited(); }} tooltipOrHelperText={ eventsBasedObject.isPrivate() ? ( <Trans> This object won't be visible in the scene and events editors. </Trans> ) : ( <Trans> This object will be visible in the scene and events editors. </Trans> ) } /> <Line noMargin justifyContent="center"> <RaisedButton label={<Trans>Open visual editor for the object</Trans>} primary onClick={onOpenCustomObjectEditor} />
@@ -141,6 +141,15 @@ export default function EventsBasedObjectEditor({ }} /> )} + <Checkbox + label={<Trans>Private (can only be used inside the extension)</Trans>}
newIDE/app/src/EventsBasedObjectEditor/index.js
26
JavaScript
0.143
question
49
50
51
false
Allow to make custom objects private to an extension
7,275
4ian/GDevelop
10,154
JavaScript
D8H
D8H
type: 'separator', }, { label: i18n._(t`Copy`), click: () => this.copy(), accelerator: 'CmdOrCtrl+C', }, { label: i18n._(t`Cut`), click: () => this.cut(), accelerator: 'CmdOrCtrl+X', }, { label: i18n._(t`Paste`), enabled: Clipboard.has(EVENTS_BASED_OBJECT_CLIPBOARD_KIND), click: () => this.paste(), accelerator: 'CmdOrCtrl+V', }, ].filter(Boolean); } renderRightComponent(i18n: I18nType): ?React.Node { return this.eventsBasedObject.isPrivate() ? ( <Tooltip title={ <Trans>This object won't be visible in the events editor.</Trans> } > <VisibilityOff fontSize="small" style={{ ...styles.tooltip, color: this.props.gdevelopTheme.text.color.disabled, }} /> </Tooltip> ) : null; } delete(): void { this._deleteEventsBasedObject({ askForConfirmation: true, }); } async _deleteEventsBasedObject({ askForConfirmation, }: {| askForConfirmation: boolean, |}): Promise<void> { const { eventsBasedObjectsList } = this.props;
```suggestion <Trans>This object won't be visible in the scene editor.</Trans> ```
type: 'separator', }, { label: i18n._(t`Copy`), click: () => this.copy(), accelerator: 'CmdOrCtrl+C', }, { label: i18n._(t`Cut`), click: () => this.cut(), accelerator: 'CmdOrCtrl+X', }, { label: i18n._(t`Paste`), enabled: Clipboard.has(EVENTS_BASED_OBJECT_CLIPBOARD_KIND), click: () => this.paste(), accelerator: 'CmdOrCtrl+V', }, ].filter(Boolean); } renderRightComponent(i18n: I18nType): ?React.Node { return this.eventsBasedObject.isPrivate() ? ( <Tooltip title={ <Trans> This object won't be visible in the scene and events editors. </Trans> } > <VisibilityOff fontSize="small" style={{ ...styles.tooltip, color: this.props.gdevelopTheme.text.color.disabled, }} /> </Tooltip> ) : null; } delete(): void { this._deleteEventsBasedObject({ askForConfirmation: true, }); } async _deleteEventsBasedObject({ askForConfirmation, }: {| askForConfirmation: boolean,
@@ -193,7 +206,21 @@ export class EventsBasedObjectTreeViewItemContent } renderRightComponent(i18n: I18nType): ?React.Node { - return null; + return this.eventsBasedObject.isPrivate() ? ( + <Tooltip + title={ + <Trans>This object won't be visible in the events editor.</Trans>
newIDE/app/src/EventsFunctionsList/EventsBasedObjectTreeViewItemContent.js
26
JavaScript
0.571
suggestion
94
51
51
false
Allow to make custom objects private to an extension
7,275
4ian/GDevelop
10,154
JavaScript
4ian
D8H
const lastObject = objects[objects.length - 1]; let objectToScrollTo; if ( newObjectDialogOpen && newObjectDialogOpen.from && // If a scene objectFolderOrObject is selected, move added assets next to or inside it. !newObjectDialogOpen.from.global ) { const selectedItem = newObjectDialogOpen.from.objectFolderOrObject; if (treeViewRef.current) { treeViewRef.current.openItems( getFoldersAscendanceWithoutRootFolder(selectedItem).map(folder => getObjectFolderTreeViewItemId(folder) ) ); } const { folder: parentFolder, position, } = getInsertionParentAndPositionFromSelection(selectedItem); const rootFolder = objectsContainer.getRootFolder(); objects.forEach((object, index) => { const objectFolderOrObject = rootFolder.getObjectChild( object.getName() ); rootFolder.moveObjectFolderOrObjectToAnotherFolder( objectFolderOrObject, parentFolder, position + index ); }); objectToScrollTo = parentFolder.getObjectChild(lastObject.getName()); } else { if (treeViewRef.current) { treeViewRef.current.openItems([sceneObjectsRootFolderId]); } // A new object is always added to the scene (layout) by default. objectToScrollTo = objectsContainer .getRootFolder() .getObjectChild(lastObject.getName()); } // Scroll to the new object. // Ideally, we'd wait for the list to be updated to scroll, but // to simplify the code, we just wait a few ms for a new render // to be done. setTimeout(() => { scrollToItem(getObjectTreeViewItemId(objectToScrollTo.getObject())); }, 100); // A few ms is enough for a new render to be done. }, [objectsContainer, onObjectCreated, scrollToItem, newObjectDialogOpen] );
instead of moving them after they're created, should we instead modify the `targetObjectsContainer` to be the selected folder in the `AssetPackInstallDialog` instead of the root of the scene?
// Here, the last object in the array might not be the last object // in the tree view, given the fact that assets are added in parallel // See (AssetPackInstallDialog.onInstallAssets). const lastObject = objects[objects.length - 1]; if (newObjectDialogOpen && newObjectDialogOpen.from) { const { objectFolderOrObject: selectedObjectFolderOrObject, } = newObjectDialogOpen.from; if (treeViewRef.current) { treeViewRef.current.openItems( getFoldersAscendanceWithoutRootFolder( selectedObjectFolderOrObject ).map(folder => getObjectFolderTreeViewItemId(folder)) ); } } else { if (treeViewRef.current) { treeViewRef.current.openItems([sceneObjectsRootFolderId]); } } // Scroll to the new object. // Ideally, we'd wait for the list to be updated to scroll, but // to simplify the code, we just wait a few ms for a new render // to be done. setTimeout(() => { scrollToItem(getObjectTreeViewItemId(lastObject)); }, 100); // A few ms is enough for a new render to be done. }, [onObjectCreated, scrollToItem, newObjectDialogOpen] ); const swapObjectAsset = React.useCallback( (objectWithContext: ObjectWithContext) => { setObjectAssetSwappingDialogOpen({ objectWithContext }); }, [] ); const onAddNewObject = React.useCallback( (item: ObjectFolderOrObjectWithContext | null) => { setNewObjectDialogOpen({ from: item }); }, [] ); const onObjectModified = React.useCallback( (shouldForceUpdateList: boolean) => { if (unsavedChanges) unsavedChanges.triggerUnsavedChanges(); if (shouldForceUpdateList) forceUpdateList();
@@ -638,27 +638,62 @@ const ObjectsList = React.forwardRef<Props, ObjectsListInterface>( const onObjectsAddedFromAssets = React.useCallback( (objects: Array<gdObject>) => { + if (objects.length === 0) return; + objects.forEach(object => { onObjectCreated(object); }); - if (treeViewRef.current) - treeViewRef.current.openItems([sceneObjectsRootFolderId]); const lastObject = objects[objects.length - 1]; - // A new object is always added to the scene (layout) by default. - const object = objectsContainer - .getRootFolder() - .getObjectChild(lastObject.getName()); - + let objectToScrollTo; + if ( + newObjectDialogOpen && + newObjectDialogOpen.from && + // If a scene objectFolderOrObject is selected, move added assets next to or inside it. + !newObjectDialogOpen.from.global + ) { + const selectedItem = newObjectDialogOpen.from.objectFolderOrObject; + if (treeViewRef.current) { + treeViewRef.current.openItems( + getFoldersAscendanceWithoutRootFolder(selectedItem).map(folder => + getObjectFolderTreeViewItemId(folder) + ) + ); + } + const { + folder: parentFolder, + position, + } = getInsertionParentAndPositionFromSelection(selectedItem); + const rootFolder = objectsContainer.getRootFolder(); + objects.forEach((object, index) => { + const objectFolderOrObject = rootFolder.getObjectChild( + object.getName() + ); + rootFolder.moveObjectFolderOrObjectToAnotherFolder(
newIDE/app/src/ObjectsList/index.js
26
JavaScript
0.571
question
192
51
51
false
Add objects installed from the asset store in selected folder
7,287
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
/* * GDevelop Core * Copyright 2015-2016 Victor Levasseur (victorlevasseur52@gmail.com). * This project is released under the MIT License. */ // NOLINTBEGIN #include "GDCore/String.h" #include <algorithm> #include <string.h> #include <iostream> #include "GDCore/CommonTools.h" #include "GDCore/Utf8/utf8proc.h" namespace gd { constexpr String::size_type String::npos; String::String() : m_string() { } String::String(const char *characters) : m_string() { *this = characters; } String::String(const std::u32string &string) : m_string() { *this = string; } String& String::operator=(const char *characters) { m_string = std::string(characters);
Was this needed to be able to compile?
/* * GDevelop Core * Copyright 2015-2016 Victor Levasseur (victorlevasseur52@gmail.com). * This project is released under the MIT License. */ // NOLINTBEGIN #include "GDCore/String.h" #include <algorithm> #include <string.h> #include "GDCore/CommonTools.h" #include "GDCore/Utf8/utf8proc.h" namespace gd { constexpr String::size_type String::npos; String::String() : m_string() { } String::String(const char *characters) : m_string() { *this = characters; } String::String(const std::u32string &string) : m_string() { *this = string; } String& String::operator=(const char *characters) {
@@ -10,7 +10,7 @@ #include <algorithm> #include <string.h> - +#include <iostream>
Core/GDCore/String.cpp
13
C++
0.071
question
38
38
38
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
#include "ObjectJsImplementation.h" #include <GDCore/IDE/Project/ArbitraryResourceWorker.h> #include <GDCore/Project/Object.h> #include <GDCore/Project/Project.h> #include <GDCore/Project/PropertyDescriptor.h> #include <GDCore/Serialization/Serializer.h> #include <GDCore/Serialization/SerializerElement.h> #include <emscripten.h> #include <map> //using namespace gd; std::unique_ptr<gd::ObjectConfiguration> ObjectJsImplementation::Clone() const { ObjectJsImplementation* clone = new ObjectJsImplementation(*this); // Copy the references to the JS implementations of the functions (because we // want an object cloned from C++ to retain the functions implemented in JS). EM_ASM_INT( { var clone = Module['wrapPointer']($0, Module['ObjectJsImplementation']); var self = Module['wrapPointer']($1, Module['ObjectJsImplementation']); clone['getProperties'] = self['getProperties']; clone['updateProperty'] = self['updateProperty']; clone['getInitialInstanceProperties'] = self['getInitialInstanceProperties']; clone['updateInitialInstanceProperty'] = self['updateInitialInstanceProperty']; // Make a clone of the JavaScript object containing the data. If we don't do that, the // content of the object would be shared between the original and the clone. clone['content'] = Module['_deepCloneForObjectJsImplementationContent'](self['content']); }, (int)clone, (int)this); return std::unique_ptr<gd::ObjectConfiguration>(clone);
It was probably comitted by mistake.
#include "ObjectJsImplementation.h" #include <GDCore/IDE/Project/ArbitraryResourceWorker.h> #include <GDCore/Project/Object.h> #include <GDCore/Project/Project.h> #include <GDCore/Project/PropertyDescriptor.h> #include <GDCore/Serialization/Serializer.h> #include <GDCore/Serialization/SerializerElement.h> #include <emscripten.h> #include <map> using namespace gd; std::unique_ptr<gd::ObjectConfiguration> ObjectJsImplementation::Clone() const { ObjectJsImplementation* clone = new ObjectJsImplementation(*this); // Copy the references to the JS implementations of the functions (because we // want an object cloned from C++ to retain the functions implemented in JS). EM_ASM_INT( { var clone = Module['wrapPointer']($0, Module['ObjectJsImplementation']); var self = Module['wrapPointer']($1, Module['ObjectJsImplementation']); clone['getProperties'] = self['getProperties']; clone['updateProperty'] = self['updateProperty']; clone['getInitialInstanceProperties'] = self['getInitialInstanceProperties']; clone['updateInitialInstanceProperty'] = self['updateInitialInstanceProperty']; // Make a clone of the JavaScript object containing the data. If we don't do that, the // content of the object would be shared between the original and the clone. clone['content'] = Module['_deepCloneForObjectJsImplementationContent'](self['content']); }, (int)clone, (int)this); return std::unique_ptr<gd::ObjectConfiguration>(clone);
@@ -10,7 +10,7 @@ #include <map> -using namespace gd; +//using namespace gd;
GDevelop.js/Bindings/ObjectJsImplementation.cpp
13
C++
0.071
suggestion
36
38
38
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
'Bindings/glue.js', buildOutputPath + 'libGD.js', buildOutputPath + 'libGD.wasm', ], }, }, }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-string-replace'); grunt.loadNpmTasks('grunt-shell'); grunt.loadNpmTasks('grunt-newer'); grunt.loadNpmTasks('grunt-mkdir'); grunt.registerTask('build:raw', [ 'mkdir:embuild', 'shell:cmake', 'newer:shell:updateGDBindings', 'shell:make', ]); grunt.registerTask('build', [ 'shell:syncVersions', 'build:raw', 'shell:copyToNewIDE', 'shell:generateFlowTypes', //'shell:generateTSTypes', ]); };
It was probably comitted by mistake too.
'Bindings/glue.js', buildOutputPath + 'libGD.js', buildOutputPath + 'libGD.wasm', ], }, }, }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-string-replace'); grunt.loadNpmTasks('grunt-shell'); grunt.loadNpmTasks('grunt-newer'); grunt.loadNpmTasks('grunt-mkdir'); grunt.registerTask('build:raw', [ 'mkdir:embuild', 'shell:cmake', 'newer:shell:updateGDBindings', 'shell:make', ]); grunt.registerTask('build', [ 'shell:syncVersions', 'build:raw', 'shell:copyToNewIDE', 'shell:generateFlowTypes', 'shell:generateTSTypes', ]); };
@@ -183,6 +183,6 @@ module.exports = function (grunt) { 'build:raw', 'shell:copyToNewIDE', 'shell:generateFlowTypes', - 'shell:generateTSTypes', + //'shell:generateTSTypes',
GDevelop.js/Gruntfile.js
26
JavaScript
0.071
suggestion
40
29
29
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
// @flow import { ProjectScopedContainersAccessor } from '../../InstructionOrExpression/EventsScope'; import { type ResourceManagementProps } from '../../ResourcesList/ResourceSource'; /** * The props given to any behavior editor */ export type BehaviorEditorProps = {| behavior: gdBehavior, project: gdProject, object: gdObject, resourceManagementProps: ResourceManagementProps, onBehaviorUpdated: () => void, |};
Did you forget to revert this line?
// @flow import { type ResourceManagementProps } from '../../ResourcesList/ResourceSource'; /** * The props given to any behavior editor */ export type BehaviorEditorProps = {| behavior: gdBehavior, project: gdProject, object: gdObject, resourceManagementProps: ResourceManagementProps, onBehaviorUpdated: () => void, |};
@@ -1,4 +1,5 @@ // @flow +import { ProjectScopedContainersAccessor } from '../../InstructionOrExpression/EventsScope';
newIDE/app/src/BehaviorsEditor/Editors/BehaviorEditorProps.flow.js
2
JavaScript
0.071
question
35
15
14
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, }; } else if (valueType === 'textarea') { return { name, valueType: 'textarea', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, }; } else if(valueType ==='animationname') { function getChoices() { if(!object) { return [{value:"Object is not valid !", label:"Object is not valid !"}] } let animationArray = []; for(let i = 0; i < object.getConfiguration().getAnimationsCount(); i++ ) { animationArray.push(object.getConfiguration().getAnimationName(i)); } return animationArray.map(value => ({ value, label: value })); } return { name, valueType: 'string', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { console.log(instance, name, newValue); onUpdateProperty(instance, name, newValue);
You can run `npm run format` in `newIDE/app/`.
return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, }; } else if (valueType === 'textarea') { return { name, valueType: 'textarea', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, }; } else if (valueType === 'animationname') { return { getChoices: () => { if (!object) { return []; } const animationArray = mapFor( 0, object.getConfiguration().getAnimationsCount(), i => { const animationName = object.getConfiguration().getAnimationName(i); if (animationName === '') { return null; } return { value: animationName, label: animationName, }; } ).filter(Boolean); animationArray.push({ value: '', label: '(no animation)' }); return animationArray; }, name, valueType: 'string', getValue: (instance: Instance): string => {
@@ -220,7 +220,40 @@ const createField = ( getLabel, getDescription, }; - } else { + } else if(valueType ==='animationname')
newIDE/app/src/PropertiesEditor/PropertiesMapToSchema.js
26
JavaScript
0.214
suggestion
46
51
51
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, }; } else if (valueType === 'textarea') { return { name, valueType: 'textarea', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, }; } else if(valueType ==='animationname') { function getChoices() { if(!object) { return [{value:"Object is not valid !", label:"Object is not valid !"}] } let animationArray = []; for(let i = 0; i < object.getConfiguration().getAnimationsCount(); i++ ) { animationArray.push(object.getConfiguration().getAnimationName(i)); } return animationArray.map(value => ({ value, label: value })); } return { name, valueType: 'string', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { console.log(instance, name, newValue); onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, getChoices, }
The editor should ensure it never happens. If we only allow to define "AnimationName" properties in the "Behavior properties" tab here (and not in "Scene properties"): ![image](https://github.com/user-attachments/assets/099c544f-9d8d-4b86-b78e-0494f1d43319) There should always be an object when a behavior propeties values are edited. So, it should be fine to return an empty Array.
onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, }; } else if (valueType === 'textarea') { return { name, valueType: 'textarea', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, }; } else if (valueType === 'animationname') { return { getChoices: () => { if (!object) { return []; } const animationArray = mapFor( 0, object.getConfiguration().getAnimationsCount(), i => { const animationName = object.getConfiguration().getAnimationName(i); if (animationName === '') { return null; } return { value: animationName, label: animationName, }; } ).filter(Boolean); animationArray.push({ value: '', label: '(no animation)' }); return animationArray; }, name, valueType: 'string', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => {
@@ -220,7 +220,40 @@ const createField = ( getLabel, getDescription, }; - } else { + } else if(valueType ==='animationname') + { + function getChoices() + { + if(!object) + { return [{value:"Object is not valid !", label:"Object is not valid !"}] }
newIDE/app/src/PropertiesEditor/PropertiesMapToSchema.js
26
JavaScript
0.5
suggestion
389
51
51
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
name, valueType: 'textarea', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, }; } else if(valueType ==='animationname') { function getChoices() { if(!object) { return [{value:"Object is not valid !", label:"Object is not valid !"}] } let animationArray = []; for(let i = 0; i < object.getConfiguration().getAnimationsCount(); i++ ) { animationArray.push(object.getConfiguration().getAnimationName(i)); } return animationArray.map(value => ({ value, label: value })); } return { name, valueType: 'string', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { console.log(instance, name, newValue); onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, getChoices, } } else { console.error( `A property with type=${valueType} could not be mapped to a field. Ensure that this type is correct and understood by the IDE.` ); return null;
You can use the `mapFor` fonction to shorten the code a bit. The empty string should be added to the list.
name, valueType: 'textarea', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, }; } else if (valueType === 'animationname') { return { getChoices: () => { if (!object) { return []; } const animationArray = mapFor( 0, object.getConfiguration().getAnimationsCount(), i => { const animationName = object.getConfiguration().getAnimationName(i); if (animationName === '') { return null; } return { value: animationName, label: animationName, }; } ).filter(Boolean); animationArray.push({ value: '', label: '(no animation)' }); return animationArray; }, name, valueType: 'string', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, }; } else { console.error( `A property with type=${valueType} could not be mapped to a field. Ensure that this type is correct and understood by the IDE.`
@@ -220,7 +220,40 @@ const createField = ( getLabel, getDescription, }; - } else { + } else if(valueType ==='animationname') + { + function getChoices() + { + if(!object) + { return [{value:"Object is not valid !", label:"Object is not valid !"}] } + + let animationArray = []; + for(let i = 0; i < object.getConfiguration().getAnimationsCount(); i++ ) + { + animationArray.push(object.getConfiguration().getAnimationName(i)); + } + return animationArray.map(value => ({ value, label: value }));
newIDE/app/src/PropertiesEditor/PropertiesMapToSchema.js
26
JavaScript
0.571
suggestion
107
51
51
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
if(!object) { return [{value:"Object is not valid !", label:"Object is not valid !"}] } let animationArray = []; for(let i = 0; i < object.getConfiguration().getAnimationsCount(); i++ ) { animationArray.push(object.getConfiguration().getAnimationName(i)); } return animationArray.map(value => ({ value, label: value })); } return { name, valueType: 'string', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { console.log(instance, name, newValue); onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, getChoices, } } else { console.error( `A property with type=${valueType} could not be mapped to a field. Ensure that this type is correct and understood by the IDE.` ); return null; } }; const propertyKeywordCouples: Array<Array<string>> = [ ['X', 'Y', 'Z'], ['Width', 'Height', 'Depth'], ['Top', 'Bottom'], ['Left', 'Right'], ['Front', 'Back'], ['Up', 'Down'], ['Min', 'Max'], ['Low', 'High'], ['Color', 'Opacity'], ['Horizontal', 'Vertical'], ['Acceleration', 'Deceleration'], ['Duration', 'Easing'], ['EffectName', 'EffectProperty'],
I guess a new attribute `isAllowingFreeText` could be added and `PropertiesEditor` will only allow the current property value until we make a new component that does autocompletion one day. A easier solution would be to add the default property value to the list but the extension creator may decide to change it and it may have side effects if some behaviors still have the old default value and it's not an existing animation either. But, I guess it will be rare enough. What do you think about only adding the property default value to the list for now?
return []; } const animationArray = mapFor( 0, object.getConfiguration().getAnimationsCount(), i => { const animationName = object.getConfiguration().getAnimationName(i); if (animationName === '') { return null; } return { value: animationName, label: animationName, }; } ).filter(Boolean); animationArray.push({ value: '', label: '(no animation)' }); return animationArray; }, name, valueType: 'string', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, }; } else { console.error( `A property with type=${valueType} could not be mapped to a field. Ensure that this type is correct and understood by the IDE.` ); return null; } }; const propertyKeywordCouples: Array<Array<string>> = [ ['X', 'Y', 'Z'], ['Width', 'Height', 'Depth'], ['Top', 'Bottom'], ['Left', 'Right'], ['Front', 'Back'], ['Up', 'Down'], ['Min', 'Max'], ['Low', 'High'], ['Color', 'Opacity'], ['Horizontal', 'Vertical'], ['Acceleration', 'Deceleration'],
@@ -220,7 +220,40 @@ const createField = ( getLabel, getDescription, }; - } else { + } else if(valueType ==='animationname') + { + function getChoices() + { + if(!object) + { return [{value:"Object is not valid !", label:"Object is not valid !"}] } + + let animationArray = []; + for(let i = 0; i < object.getConfiguration().getAnimationsCount(); i++ ) + { + animationArray.push(object.getConfiguration().getAnimationName(i)); + } + return animationArray.map(value => ({ value, label: value })); + + } + return { + name, + valueType: 'string', + getValue: (instance: Instance): string => { + return getProperties(instance) + .get(name) + .getValue(); + }, + setValue: (instance: Instance, newValue: string) => { + console.log(instance, name, newValue); + onUpdateProperty(instance, name, newValue); + }, + getLabel, + getDescription, + getChoices,
newIDE/app/src/PropertiesEditor/PropertiesMapToSchema.js
26
JavaScript
0.643
question
562
51
51
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
/* * GDevelop Core * Copyright 2015-2016 Victor Levasseur (victorlevasseur52@gmail.com). * This project is released under the MIT License. */ // NOLINTBEGIN #include "GDCore/String.h" #include <algorithm> #include <string.h> #include "GDCore/CommonTools.h" #include "GDCore/Utf8/utf8proc.h" namespace gd { constexpr String::size_type String::npos; String::String() : m_string() { } String::String(const char *characters) : m_string() { *this = characters; } String::String(const std::u32string &string) : m_string() { *this = string; } String& String::operator=(const char *characters) { m_string = std::string(characters); return *this;
This file only have empty line changes. It should be reverted to have a clearer history.
/* * GDevelop Core * Copyright 2015-2016 Victor Levasseur (victorlevasseur52@gmail.com). * This project is released under the MIT License. */ // NOLINTBEGIN #include "GDCore/String.h" #include <algorithm> #include <string.h> #include "GDCore/CommonTools.h" #include "GDCore/Utf8/utf8proc.h" namespace gd { constexpr String::size_type String::npos; String::String() : m_string() { } String::String(const char *characters) : m_string() { *this = characters; } String::String(const std::u32string &string) : m_string() { *this = string; } String& String::operator=(const char *characters) {
@@ -10,7 +10,6 @@ #include <algorithm> #include <string.h> - #include "GDCore/CommonTools.h"
Core/GDCore/String.cpp
13
C++
0.286
suggestion
88
38
38
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
}, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, hasImpactOnAllOtherFields: property.hasImpactOnOtherProperties(), }; } else if (valueType === 'textarea') { return { name, valueType: 'textarea', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, hasImpactOnAllOtherFields: property.hasImpactOnOtherProperties(), }; } else if (valueType === 'animationname') { function getChoices() { const animationArray = mapFor( 0, object.getConfiguration().getAnimationsCount(), i => { const animationName = object.getConfiguration().getAnimationName(i); return { value: animationName, label: animationName, }; } ); animationArray.push({ value: '', label: '(no animation' }); return animationArray; } return { name, valueType: 'string', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); },
The rest of the code uses this notation: `getChoices: () => {` I think it's a bit easier to read.
}, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, hasImpactOnAllOtherFields: property.hasImpactOnOtherProperties(), }; } else if (valueType === 'textarea') { return { name, valueType: 'textarea', getValue: (instance: Instance): string => { return getProperties(instance) .get(name) .getValue(); }, setValue: (instance: Instance, newValue: string) => { onUpdateProperty(instance, name, newValue); }, getLabel, getDescription, hasImpactOnAllOtherFields: property.hasImpactOnOtherProperties(), }; } else if (valueType === 'animationname') { return { getChoices: () => { if (!object) { return []; } const animationArray = mapFor( 0, object.getConfiguration().getAnimationsCount(), i => { const animationName = object.getConfiguration().getAnimationName(i); if (animationName === '') { return null; } return { value: animationName, label: animationName, }; } ).filter(Boolean); animationArray.push({ value: '', label: '(no animation)' }); return animationArray; }, name, valueType: 'string', getValue: (instance: Instance): string => { return getProperties(instance)
@@ -234,6 +234,37 @@ const createField = ( getDescription, hasImpactOnAllOtherFields: property.hasImpactOnOtherProperties(), }; + } else if (valueType === 'animationname') { + function getChoices() {
newIDE/app/src/CompactPropertiesEditor/PropertiesMapToCompactSchema.js
26
JavaScript
0.429
suggestion
98
51
51
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
onPropertiesUpdated && onPropertiesUpdated(); }} fullWidth > {getExtraInfoArray(property).map( (choice, index) => ( <SelectOption key={index} value={choice} label={choice} /> ) )} </SelectField> )} </ResponsiveLineStackLayout> {property.getType() === 'Choice' && ( <StringArrayEditor extraInfo={getExtraInfoArray(property)} setExtraInfo={setChoiceExtraInfo( property )} /> )} <ResponsiveLineStackLayout noMargin> <SemiControlledTextField commitOnBlur floatingLabelText={ <Trans>Short label</Trans> } translatableHintText={t`Make the purpose of the property easy to understand`} floatingLabelFixed value={property.getLabel()} onChange={text => { property.setLabel(text); forceUpdate(); }} fullWidth /> <SemiControlledAutoComplete floatingLabelText={ <Trans>Group name</Trans> } hintText={t`Leave it empty to use the default group`} fullWidth value={property.getGroup()} onChange={text => { property.setGroup(text); forceUpdate();
Nitpick: This empty line is alone.
onPropertiesUpdated && onPropertiesUpdated(); }} fullWidth > {getExtraInfoArray(property).map( (choice, index) => ( <SelectOption key={index} value={choice} label={choice} /> ) )} </SelectField> )} </ResponsiveLineStackLayout> {property.getType() === 'Choice' && ( <StringArrayEditor extraInfo={getExtraInfoArray(property)} setExtraInfo={setChoiceExtraInfo( property )} /> )} <ResponsiveLineStackLayout noMargin> <SemiControlledTextField commitOnBlur floatingLabelText={ <Trans>Short label</Trans> } translatableHintText={t`Make the purpose of the property easy to understand`} floatingLabelFixed value={property.getLabel()} onChange={text => { property.setLabel(text); forceUpdate(); }} fullWidth /> <SemiControlledAutoComplete floatingLabelText={ <Trans>Group name</Trans> } hintText={t`Leave it empty to use the default group`} fullWidth value={property.getGroup()} onChange={text => { property.setGroup(text); forceUpdate(); onPropertiesUpdated &&
@@ -944,6 +951,7 @@ export default function EventsBasedBehaviorPropertiesEditor({ )} /> )} +
newIDE/app/src/EventsBasedBehaviorEditor/EventsBasedBehaviorPropertiesEditor.js
26
JavaScript
0.071
nitpick
34
51
51
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
forceUpdate(); onPropertiesUpdated && onPropertiesUpdated(); }} fullWidth > <SelectOption key="property-type-number" value="Number" label={t`Number`} /> <SelectOption key="property-type-string" value="String" label={t`String`} /> <SelectOption key="property-type-boolean" value="Boolean" label={t`Boolean (checkbox)`} /> <SelectOption key="property-type-animationname" value="AnimationName" label={t`Animation Name (text)`} /> <SelectOption key="property-type-choice" value="Choice" label={t`String from a list of options (text)`} /> <SelectOption key="property-type-color" value="Color" label={t`Color (text)`} /> <SelectOption key="property-type-resource" value="Resource" label={t`Resource (JavaScript only)`} /> {!isSceneProperties && ( <SelectOption key="property-type-behavior" value="Behavior" label={t`Required behavior`} /> )} </SelectField> {property.getType() === 'Number' && ( <SelectField
I wonder if it should be below the "Choice" type as it's a bit more specific. ```suggestion <SelectOption key="property-type-animationname" value="AnimationName" label={t`Animation name (text)`} /> ```
forceUpdate(); onPropertiesUpdated && onPropertiesUpdated(); }} fullWidth > <SelectOption key="property-type-number" value="Number" label={t`Number`} /> <SelectOption key="property-type-string" value="String" label={t`String`} /> <SelectOption key="property-type-boolean" value="Boolean" label={t`Boolean (checkbox)`} /> <SelectOption key="property-type-animationname" value="AnimationName" label={t`Animation name (text)`} /> <SelectOption key="property-type-choice" value="Choice" label={t`String from a list of options (text)`} /> <SelectOption key="property-type-color" value="Color" label={t`Color (text)`} /> <SelectOption key="property-type-resource" value="Resource" label={t`Resource (JavaScript only)`} /> {!isSceneProperties && ( <SelectOption key="property-type-behavior" value="Behavior" label={t`Required behavior`} /> )} </SelectField> {property.getType() === 'Number' && ( <SelectField
@@ -729,6 +729,11 @@ export default function EventsBasedBehaviorPropertiesEditor({ value="Boolean" label={t`Boolean (checkbox)`} /> + <SelectOption + key="property-type-animationname" + value="AnimationName" + label={t`Animation Name (text)`} + />
newIDE/app/src/EventsBasedBehaviorEditor/EventsBasedBehaviorPropertiesEditor.js
26
JavaScript
1
suggestion
414
51
51
false
AnimationName selector
7,288
4ian/GDevelop
10,154
JavaScript
D8H
NeylMahfouf2608
const refocusValueField = useRefocusField(topLevelVariableValueInputRefs); const gdevelopTheme = React.useContext(GDevelopThemeContext); const draggedNodeId = React.useRef<?string>(null); const forceUpdate = useForceUpdate(); const [searchText, setSearchText] = React.useState<string>(''); const { onComputeAllVariableNames, onSelectedVariableChange } = props; const allVariablesNames = React.useMemo<?Array<string>>( () => (onComputeAllVariableNames ? onComputeAllVariableNames() : null), [onComputeAllVariableNames] ); const [selectedNodes, doSetSelectedNodes] = React.useState<Array<string>>( () => { if (!props.initiallySelectedVariableName) { return []; } let variableContext = getVariableContextFromNodeId( getNodeIdFromVariableName(props.initiallySelectedVariableName), props.variablesContainer ); // When a child-variable is not declared, its direct parent is used. if (!variableContext.variable) { variableContext = getParentVariableContext(variableContext); } if (variableContext.variable) { refocusNameField({ identifier: variableContext.variable.ptr }); } const initialSelectedNodeId = variableContext.variable ? getNodeIdFromVariableContext(variableContext) : null; return initialSelectedNodeId ? [initialSelectedNodeId] : []; } ); const setSelectedNodes = React.useCallback( (nodes: Array<string> | ((nodes: Array<string>) => Array<string>)) => { doSetSelectedNodes(selectedNodes => { const newNodes = Array.isArray(nodes) ? nodes : nodes(selectedNodes); if (onSelectedVariableChange) { onSelectedVariableChange(newNodes); } return newNodes; }); }, [onSelectedVariableChange] ); const triggerSearch = React.useCallback( () => { let matchingInheritedNodes = []; const matchingNodes = generateListOfNodesMatchingSearchInVariablesContainer( props.variablesContainer,
Why wasn't it done before? Any technical limitation?
// in the case the user wants to modify the value at the instance level // of an object's variable: in that case, a new variable is created and // the new variable value field needs to be focused. [number]: SimpleTextFieldInterface, |}>({}); // $FlowFixMe - Hard to fix issue regarding strict checking with interface. const refocusNameField = useRefocusField(variableNameInputRefs); // $FlowFixMe - Hard to fix issue regarding strict checking with interface. const refocusValueField = useRefocusField(topLevelVariableValueInputRefs); const gdevelopTheme = React.useContext(GDevelopThemeContext); const draggedNodeId = React.useRef<?string>(null); const forceUpdate = useForceUpdate(); const [searchText, setSearchText] = React.useState<string>(''); const { onComputeAllVariableNames, onSelectedVariableChange } = props; const allVariablesNames = React.useMemo<?Array<string>>( () => (onComputeAllVariableNames ? onComputeAllVariableNames() : null), [onComputeAllVariableNames] ); const [selectedNodes, doSetSelectedNodes] = React.useState<Array<string>>( () => { if (!props.initiallySelectedVariableName) { return []; } let variableContext = getVariableContextFromNodeId( getNodeIdFromVariableName(props.initiallySelectedVariableName), props.variablesContainer ); // When a child-variable is not declared, its direct parent is used. if (!variableContext.variable) { variableContext = getParentVariableContext(variableContext); } if (variableContext.variable) { refocusNameField({ identifier: variableContext.variable.ptr }); } const initialSelectedNodeId = variableContext.variable ? getNodeIdFromVariableContext(variableContext) : null; return initialSelectedNodeId ? [initialSelectedNodeId] : []; } ); const setSelectedNodes = React.useCallback( (nodes: Array<string> | ((nodes: Array<string>) => Array<string>)) => { doSetSelectedNodes(selectedNodes => { const newNodes = Array.isArray(nodes) ? nodes : nodes(selectedNodes); if (onSelectedVariableChange) { onSelectedVariableChange(newNodes); } return newNodes; }); },
@@ -636,7 +636,6 @@ const VariablesList = React.forwardRef<Props, VariablesListInterface>( variableContext = getParentVariableContext(variableContext); } if (variableContext.variable) { - // TODO Add ref to child-variables to allow to focus them.
newIDE/app/src/VariablesList/VariablesList.js
26
JavaScript
0.214
question
52
51
51
false
Fix variable list usability
7,290
4ian/GDevelop
10,154
JavaScript
ClementPasteau
AlexandreSi
} } } } else if (requestedTab === 'learn') { const courseId = routeArguments['course-id']; if (courseId && selectedCourse && selectedCourse.id === courseId) { setLearnCategory('course'); removeRouteArguments(['course-id']); } } removeRouteArguments(['initial-dialog']); }, [ routeArguments, selectedCourse, removeRouteArguments, setInitialPackUserFriendlySlug, setInitialGameTemplateUserFriendlySlug, games, ] ); React.useEffect( () => { if (initialTab === 'get-started') { incrementGetStartedSectionViewCount(); } }, [initialTab] ); // Load everything when the user opens the home page, to avoid future loading times. React.useEffect( () => { fetchExamplesAndFilters(); fetchGameTemplates(); fetchTutorials(); }, [fetchExamplesAndFilters, fetchTutorials, fetchGameTemplates] ); // Only fetch games if the user decides to open the games dashboard tab // or the build tab to enable the context menu on project list items that // redirects to the games dashboard. React.useEffect( () => { if (activeTab === 'create' && !games) { fetchGames(); }
Can you check there is no side effects on other things like game dashboard? (small risk that the chapters are loaded and so ready, and the effect runs again even if the URL you're loading is totally not chapters related). If it's a problem, a potential solution is to divide the effects into multiple effects with just the dependencies actually needed.
} } } } else if (requestedTab === 'learn') { const courseId = routeArguments['course-id']; if (!areChaptersReady) { // Do not process requested tab before courses are ready. return; } if (courseId && selectedCourse && selectedCourse.id === courseId) { setLearnCategory('course'); removeRouteArguments(['course-id']); } } removeRouteArguments(['initial-dialog']); }, [ routeArguments, selectedCourse, removeRouteArguments, setInitialPackUserFriendlySlug, setInitialGameTemplateUserFriendlySlug, games, areChaptersReady, ] ); React.useEffect( () => { if (initialTab === 'get-started') { incrementGetStartedSectionViewCount(); } }, [initialTab] ); // Load everything when the user opens the home page, to avoid future loading times. React.useEffect( () => { fetchExamplesAndFilters(); fetchGameTemplates(); fetchTutorials(); }, [fetchExamplesAndFilters, fetchTutorials, fetchGameTemplates] ); // Only fetch games if the user decides to open the games dashboard tab // or the build tab to enable the context menu on project list items that // redirects to the games dashboard.
@@ -332,6 +336,7 @@ export const HomePage = React.memo<Props>( setInitialPackUserFriendlySlug, setInitialGameTemplateUserFriendlySlug, games, + areChaptersReady,
newIDE/app/src/MainFrame/EditorContainers/HomePage/index.js
26
JavaScript
0.429
suggestion
356
51
51
false
Wait for courses to load before opening them
7,304
4ian/GDevelop
10,154
JavaScript
4ian
AlexandreSi
0, Math.min(255, parseFloat(newValue)) ); return true; } else if (propertyName === 'borderWidth') { objectContent.borderWidth = Math.max(0, parseFloat(newValue)); return true; } else if (propertyName === 'readOnly') { objectContent.readOnly = newValue === '1'; return true; } else if (propertyName === 'disabled') { objectContent.disabled = newValue === '1'; return true; } else if(propertyName === 'maxLength') { objectContent.maxLength = newValue; } else if (propertyName === 'padding') { objectContent.padding = newValue; } else if(propertyName === 'textAlignement') { objectContent.textAlignement = newValue; } return false; }; textInputObject.getProperties = function () { const objectProperties = new gd.MapStringPropertyDescriptor(); const objectContent = this.content; objectProperties .getOrCreate('initialValue') .setValue(objectContent.initialValue) .setType('string') .setLabel(_('Initial value')) .setGroup(_('Content')); objectProperties .getOrCreate('placeholder') .setValue(objectContent.placeholder) .setType('string') .setLabel(_('Placeholder')) .setGroup(_('Content')); objectProperties .getOrCreate('fontResourceName') .setValue(objectContent.fontResourceName || '') .setType('resource')
Don't miss the return true to end the condition check and the function.
0, Math.min(255, parseFloat(newValue)) ); return true; } else if (propertyName === 'borderWidth') { objectContent.borderWidth = Math.max(0, parseFloat(newValue)); return true; } else if (propertyName === 'readOnly') { objectContent.readOnly = newValue === '1'; return true; } else if (propertyName === 'disabled') { objectContent.disabled = newValue === '1'; return true; } else if (propertyName === 'maxLength') { objectContent.maxLength = newValue; return true; } else if (propertyName === 'padding') { objectContent.padding = newValue; return true; } else if (propertyName === 'textAlign') { objectContent.textAlign = newValue; return true; } return false; }; textInputObject.getProperties = function () { const objectProperties = new gd.MapStringPropertyDescriptor(); const objectContent = this.content; objectProperties .getOrCreate('initialValue') .setValue(objectContent.initialValue) .setType('string') .setLabel(_('Initial value')) .setGroup(_('Content')); objectProperties .getOrCreate('placeholder') .setValue(objectContent.placeholder) .setType('string') .setLabel(_('Placeholder')) .setGroup(_('Content')); objectProperties .getOrCreate('fontResourceName') .setValue(objectContent.fontResourceName || '') .setType('resource') .addExtraInfo('font') .setLabel(_('Font')) .setGroup(_('Font'));
@@ -79,6 +79,18 @@ module.exports = { objectContent.disabled = newValue === '1'; return true; } + else if(propertyName === 'maxLength') + { + objectContent.maxLength = newValue; + } + else if (propertyName === 'padding') + { + objectContent.padding = newValue; + } + else if(propertyName === 'textAlignement') + { + objectContent.textAlignement = newValue; + }
Extensions/TextInput/JsExtension.js
26
JavaScript
0.214
suggestion
71
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
Bouh
NeylMahfouf2608
.addExtraInfo('number') .addExtraInfo('telephone number') .addExtraInfo('url') .addExtraInfo('search') .setLabel(_('Input type')) .setDescription( _( 'By default, a "text" is single line. Choose "text area" to allow multiple lines to be entered.' ) ); objectProperties .getOrCreate('readOnly') .setValue(objectContent.readOnly ? 'true' : 'false') .setType('boolean') .setLabel(_('Read only')) .setGroup(_('Field')); objectProperties .getOrCreate('disabled') .setValue(objectContent.disabled ? 'true' : 'false') .setType('boolean') .setLabel(_('Disabled')) .setGroup(_('Field')); objectProperties .getOrCreate('textColor') .setValue(objectContent.textColor || '0;0;0') .setType('color') .setLabel(_('Text color')) .setGroup(_('Font')); objectProperties .getOrCreate('fillColor') .setValue(objectContent.fillColor || '0;0;0') .setType('color') .setLabel(_('Fill color')) .setGroup(_('Field appearance')); objectProperties .getOrCreate('fillOpacity') .setValue( (objectContent.fillOpacity != undefined ? objectContent.fillOpacity : 255 ).toString() ) .setType('number') .setLabel(_('Fill opacity')) .setGroup(_('Field appearance'));
It's a good idea not to change those default values unless it's actually useful to your feature. I'm not sure that's the case, or is it?
.addExtraInfo('number') .addExtraInfo('telephone number') .addExtraInfo('url') .addExtraInfo('search') .setLabel(_('Input type')) .setDescription( _( 'By default, a "text" is single line. Choose "text area" to allow multiple lines to be entered.' ) ); objectProperties .getOrCreate('readOnly') .setValue(objectContent.readOnly ? 'true' : 'false') .setType('boolean') .setLabel(_('Read only')) .setGroup(_('Field')); objectProperties .getOrCreate('disabled') .setValue(objectContent.disabled ? 'true' : 'false') .setType('boolean') .setLabel(_('Disabled')) .setGroup(_('Field')); objectProperties .getOrCreate('textColor') .setValue(objectContent.textColor || '0;0;0') .setType('color') .setLabel(_('Text color')) .setGroup(_('Font')); objectProperties .getOrCreate('fillColor') .setValue(objectContent.fillColor || '255;255;255') .setType('color') .setLabel(_('Fill color')) .setGroup(_('Field appearance')); objectProperties .getOrCreate('fillOpacity') .setValue( (objectContent.fillOpacity != undefined ? objectContent.fillOpacity : 255 ).toString() ) .setType('number') .setLabel(_('Fill opacity')) .setGroup(_('Field appearance'));
@@ -157,7 +166,7 @@ module.exports = { objectProperties .getOrCreate('fillColor') - .setValue(objectContent.fillColor || '255;255;255')
Extensions/TextInput/JsExtension.js
26
JavaScript
0.429
question
136
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
.setType('color') .setLabel(_('Color')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderOpacity') .setValue( (objectContent.borderOpacity != undefined ? objectContent.borderOpacity : 255 ).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('maxLength') .setValue(objectContent.maxLength || 20) .setType('number') .setLabel(_('Max length')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('right') .addExtraInfo('center') .setLabel(_('text Alignement')) .setGroup(_('Border appearance')); return objectProperties; }; textInputObject.content = { initialValue: '',
Why do you convert the number to a string?
.setType('color') .setLabel(_('Color')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderOpacity') .setValue( (objectContent.borderOpacity != undefined ? objectContent.borderOpacity : 255 ).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue((objectContent.maxLength || 0).toString()) .setType('number') .setLabel(_('Max length')) .setDescription( _( 'The maximum length of the input value (this property will be ignored if the input type is a number).' ) ) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font'));
@@ -200,6 +209,30 @@ module.exports = { .setLabel(_('Width')) .setGroup(_('Border appearance')); + objectProperties + .getOrCreate('padding') + .setValue((objectContent.padding || 0).toString())
Extensions/TextInput/JsExtension.js
26
JavaScript
0.071
question
42
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('maxLength') .setValue(objectContent.maxLength || 20) .setType('number') .setLabel(_('Max length')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('right') .addExtraInfo('center') .setLabel(_('text Alignement')) .setGroup(_('Border appearance')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255, borderColor: '0;0;0', borderOpacity: 255, borderWidth: 1,
Definitely not the right group
).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue((objectContent.maxLength || 0).toString()) .setType('number') .setLabel(_('Max length')) .setDescription( _( 'The maximum length of the input value (this property will be ignored if the input type is a number).' ) ) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255',
@@ -200,6 +209,30 @@ module.exports = { .setLabel(_('Width')) .setGroup(_('Border appearance')); + objectProperties + .getOrCreate('padding') + .setValue((objectContent.padding || 0).toString()) + .setType('number') + .setLabel(_('Padding')) + .setGroup(_('Border appearance')); + + objectProperties + .getOrCreate('maxLength') + .setValue(objectContent.maxLength || 20) + .setType('number') + .setLabel(_('Max length')) + .setGroup(_('Border appearance'));
Extensions/TextInput/JsExtension.js
26
JavaScript
0.071
suggestion
30
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
(objectContent.borderOpacity != undefined ? objectContent.borderOpacity : 255 ).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('maxLength') .setValue(objectContent.maxLength || 20) .setType('number') .setLabel(_('Max length')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('right') .addExtraInfo('center') .setLabel(_('text Alignement')) .setGroup(_('Border appearance')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255,
20 seems a bit low, you can use 40 instead I think.
(objectContent.borderOpacity != undefined ? objectContent.borderOpacity : 255 ).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue((objectContent.maxLength || 0).toString()) .setType('number') .setLabel(_('Max length')) .setDescription( _( 'The maximum length of the input value (this property will be ignored if the input type is a number).' ) ) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20,
@@ -200,6 +209,30 @@ module.exports = { .setLabel(_('Width')) .setGroup(_('Border appearance')); + objectProperties + .getOrCreate('padding') + .setValue((objectContent.padding || 0).toString()) + .setType('number') + .setLabel(_('Padding')) + .setGroup(_('Border appearance')); + + objectProperties + .getOrCreate('maxLength') + .setValue(objectContent.maxLength || 20)
Extensions/TextInput/JsExtension.js
26
JavaScript
0.286
suggestion
51
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
? objectContent.borderOpacity : 255 ).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('maxLength') .setValue(objectContent.maxLength || 20) .setType('number') .setLabel(_('Max length')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('right') .addExtraInfo('center') .setLabel(_('text Alignement')) .setGroup(_('Border appearance')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255, borderColor: '0;0;0',
You can precise that's the Input value max length (and not the size of the input rectangle for instance)
? objectContent.borderOpacity : 255 ).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue((objectContent.maxLength || 0).toString()) .setType('number') .setLabel(_('Max length')) .setDescription( _( 'The maximum length of the input value (this property will be ignored if the input type is a number).' ) ) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text',
@@ -200,6 +209,30 @@ module.exports = { .setLabel(_('Width')) .setGroup(_('Border appearance')); + objectProperties + .getOrCreate('padding') + .setValue((objectContent.padding || 0).toString()) + .setType('number') + .setLabel(_('Padding')) + .setGroup(_('Border appearance')); + + objectProperties + .getOrCreate('maxLength') + .setValue(objectContent.maxLength || 20) + .setType('number') + .setLabel(_('Max length'))
Extensions/TextInput/JsExtension.js
26
JavaScript
0.357
suggestion
104
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
.setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('maxLength') .setValue(objectContent.maxLength || 20) .setType('number') .setLabel(_('Max length')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('right') .addExtraInfo('center') .setLabel(_('text Alignement')) .setGroup(_('Border appearance')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255, borderColor: '0;0;0', borderOpacity: 255, borderWidth: 1, readOnly: false, disabled: false, padding: 0, textAlign: 'left', maxLength: '20', }; textInputObject.updateInitialInstanceProperty = function ( instance,
This is not correctly formatted
.setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue((objectContent.maxLength || 0).toString()) .setType('number') .setLabel(_('Max length')) .setDescription( _( 'The maximum length of the input value (this property will be ignored if the input type is a number).' ) ) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255, borderColor: '0;0;0', borderOpacity: 255, borderWidth: 1, readOnly: false, disabled: false, padding: 0, textAlign: 'left', maxLength: 0,
@@ -200,6 +209,30 @@ module.exports = { .setLabel(_('Width')) .setGroup(_('Border appearance')); + objectProperties + .getOrCreate('padding') + .setValue((objectContent.padding || 0).toString()) + .setType('number') + .setLabel(_('Padding')) + .setGroup(_('Border appearance')); + + objectProperties + .getOrCreate('maxLength') + .setValue(objectContent.maxLength || 20) + .setType('number') + .setLabel(_('Max length')) + .setGroup(_('Border appearance')); + + objectProperties + .getOrCreate('textAlign') + .setValue(objectContent.textAlign || 'left') + .setType('choice') + .addExtraInfo('left') + .addExtraInfo('right') + .addExtraInfo('center') + .setLabel(_('text Alignement'))
Extensions/TextInput/JsExtension.js
26
JavaScript
0.071
style
31
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
.setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('maxLength') .setValue(objectContent.maxLength || 20) .setType('number') .setLabel(_('Max length')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('right') .addExtraInfo('center') .setLabel(_('text Alignement')) .setGroup(_('Border appearance')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255, borderColor: '0;0;0', borderOpacity: 255, borderWidth: 1, readOnly: false, disabled: false, padding: 0, textAlign: 'left', maxLength: '20', }; textInputObject.updateInitialInstanceProperty = function ( instance, propertyName, newValue
I think that the order is important here. I see that the text uses the order `left, center right`, so we might as well use the same here
.setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue((objectContent.maxLength || 0).toString()) .setType('number') .setLabel(_('Max length')) .setDescription( _( 'The maximum length of the input value (this property will be ignored if the input type is a number).' ) ) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255, borderColor: '0;0;0', borderOpacity: 255, borderWidth: 1, readOnly: false, disabled: false, padding: 0, textAlign: 'left', maxLength: 0, };
@@ -200,6 +209,30 @@ module.exports = { .setLabel(_('Width')) .setGroup(_('Border appearance')); + objectProperties + .getOrCreate('padding') + .setValue((objectContent.padding || 0).toString()) + .setType('number') + .setLabel(_('Padding')) + .setGroup(_('Border appearance')); + + objectProperties + .getOrCreate('maxLength') + .setValue(objectContent.maxLength || 20) + .setType('number') + .setLabel(_('Max length')) + .setGroup(_('Border appearance')); + + objectProperties + .getOrCreate('textAlign') + .setValue(objectContent.textAlign || 'left') + .setType('choice') + .addExtraInfo('left') + .addExtraInfo('right') + .addExtraInfo('center')
Extensions/TextInput/JsExtension.js
26
JavaScript
0.571
suggestion
136
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
) ) .setFunctionName('setOpacity') .setGetter('getOpacity') .setHidden(); object .addScopedCondition( 'Focused', _('Focused'), _( 'Check if the text input is focused (the cursor is in the field and player can type text in).' ), _('_PARAM0_ is focused'), '', 'res/conditions/surObjet24.png', 'res/conditions/surObjet.png' ) .addParameter('object', _('Text input'), 'TextInputObject', false) .getCodeExtraInformation() .setFunctionName('isFocused'); object .addScopedCondition( 'IsInputSubmitted', _('Input is Submitted (Enter pressed'), _( 'Check if the input is submitted, which usually happens when the Enter key is pressed on a keyboard, or a specific button on mobile virtual keyboards.' ), _('_PARAM0_ got input submitted'), '', 'res/conditions/surObject24.png', 'res/conditions/surObject.png' ) .addParameter('object', _('Text input'), 'TextInputObject', false) .getCodeExtraInformation() .setFunctionName('isSubmitted'); object .addScopedAction( 'Focus', _('Focus'), _( 'Focus the input so that text can be entered (like if it was touched/clicked).' ), _('Focus _PARAM0_'), _(''), 'res/conditions/surObjet24.png', 'res/conditions/surObjet.png' ) .addParameter('object', _('Text input'), 'TextInputObject', false)
```suggestion _('Input is submitted'), ``` I think it's better not mentioning any platform specific detail in the name
'number', gd.ParameterOptions.makeNewOptions().setDescription( _('Opacity (0-255)') ) ) .setFunctionName('setOpacity') .setGetter('getOpacity') .setHidden(); object .addScopedCondition( 'Focused', _('Focused'), _( 'Check if the text input is focused (the cursor is in the field and player can type text in).' ), _('_PARAM0_ is focused'), '', 'res/conditions/surObjet24.png', 'res/conditions/surObjet.png' ) .addParameter('object', _('Text input'), 'TextInputObject', false) .getCodeExtraInformation() .setFunctionName('isFocused'); object .addScopedCondition( 'IsInputSubmitted', _('Input is submitted'), _( 'Check if the input is submitted, which usually happens when the Enter key is pressed on a keyboard, or a specific button on mobile virtual keyboards.' ), _('_PARAM0_ value was submitted'), '', 'res/conditions/surObject24.png', 'res/conditions/surObject.png' ) .addParameter('object', _('Text input'), 'TextInputObject', false) .getCodeExtraInformation() .setFunctionName('isSubmitted'); object .addScopedAction( 'Focus', _('Focus'), _( 'Focus the input so that text can be entered (like if it was touched/clicked).' ), _('Focus _PARAM0_'), _(''), 'res/conditions/surObjet24.png',
@@ -572,6 +609,22 @@ module.exports = { .getCodeExtraInformation() .setFunctionName('isFocused'); + object + .addScopedCondition( + 'IsInputSubmitted', + _('Input is Submitted (Enter pressed'),
Extensions/TextInput/JsExtension.js
26
JavaScript
0.786
suggestion
129
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
.setHidden(); object .addScopedCondition( 'Focused', _('Focused'), _( 'Check if the text input is focused (the cursor is in the field and player can type text in).' ), _('_PARAM0_ is focused'), '', 'res/conditions/surObjet24.png', 'res/conditions/surObjet.png' ) .addParameter('object', _('Text input'), 'TextInputObject', false) .getCodeExtraInformation() .setFunctionName('isFocused'); object .addScopedCondition( 'IsInputSubmitted', _('Input is Submitted (Enter pressed'), _( 'Check if the input is submitted, which usually happens when the Enter key is pressed on a keyboard, or a specific button on mobile virtual keyboards.' ), _('_PARAM0_ got input submitted'), '', 'res/conditions/surObject24.png', 'res/conditions/surObject.png' ) .addParameter('object', _('Text input'), 'TextInputObject', false) .getCodeExtraInformation() .setFunctionName('isSubmitted'); object .addScopedAction( 'Focus', _('Focus'), _( 'Focus the input so that text can be entered (like if it was touched/clicked).' ), _('Focus _PARAM0_'), _(''), 'res/conditions/surObjet24.png', 'res/conditions/surObjet.png' ) .addParameter('object', _('Text input'), 'TextInputObject', false) .getCodeExtraInformation() .setFunctionName('focus'); return extension;
```suggestion _('_PARAM0_ value was submitted'), ```
) .setFunctionName('setOpacity') .setGetter('getOpacity') .setHidden(); object .addScopedCondition( 'Focused', _('Focused'), _( 'Check if the text input is focused (the cursor is in the field and player can type text in).' ), _('_PARAM0_ is focused'), '', 'res/conditions/surObjet24.png', 'res/conditions/surObjet.png' ) .addParameter('object', _('Text input'), 'TextInputObject', false) .getCodeExtraInformation() .setFunctionName('isFocused'); object .addScopedCondition( 'IsInputSubmitted', _('Input is submitted'), _( 'Check if the input is submitted, which usually happens when the Enter key is pressed on a keyboard, or a specific button on mobile virtual keyboards.' ), _('_PARAM0_ value was submitted'), '', 'res/conditions/surObject24.png', 'res/conditions/surObject.png' ) .addParameter('object', _('Text input'), 'TextInputObject', false) .getCodeExtraInformation() .setFunctionName('isSubmitted'); object .addScopedAction( 'Focus', _('Focus'), _( 'Focus the input so that text can be entered (like if it was touched/clicked).' ), _('Focus _PARAM0_'), _(''), 'res/conditions/surObjet24.png', 'res/conditions/surObjet.png' ) .addParameter('object', _('Text input'), 'TextInputObject', false) .getCodeExtraInformation()
@@ -572,6 +609,22 @@ module.exports = { .getCodeExtraInformation() .setFunctionName('isFocused'); + object + .addScopedCondition( + 'IsInputSubmitted', + _('Input is Submitted (Enter pressed'), + _( + 'Check if the input is submitted, which usually happens when the Enter key is pressed on a keyboard, or a specific button on mobile virtual keyboards.' + ), + _('_PARAM0_ got input submitted'),
Extensions/TextInput/JsExtension.js
26
JavaScript
0.571
suggestion
62
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
this._pixiObject.pivot.x = width / 2; this._pixiObject.pivot.y = height / 2; this._pixiObject.position.x = instance.getX() + width / 2; this._pixiObject.position.y = instance.getY() + height / 2; this._pixiObject.rotation = RenderedInstance.toRad( this._instance.getAngle() ); const borderWidth = object.content.borderWidth || 0; // Draw the mask for the text. const textOffset = borderWidth + TEXT_MASK_PADDING; // + object.content.padding; this._pixiTextMask.clear(); this._pixiTextMask.beginFill(0xdddddd, 1); this._pixiTextMask.drawRect( textOffset, textOffset, width - 2 * textOffset, height - 2 * textOffset ); this._pixiTextMask.endFill(); const isTextArea = object.content.inputType === 'text area'; const textAlign = object.content.textAlign; if (textAlign === 'left') this._pixiText.position.x = 0; else if (textAlign === 'right') this._pixiText.position.x = 0 + width - this._pixiText.width - textOffset; else if (textAlign === 'center') { this._pixiText.align = 'center'; this._pixiText.position.x = 0 + width / 2 - this._pixiText.width / 2; } this._pixiText.position.y = isTextArea ? textOffset : height / 2 - this._pixiText.height / 2; // Draw the background and border. const fillColor = object.content.fillColor; const fillOpacity = object.content.fillOpacity; const borderColor = object.content.borderColor; const borderOpacity = object.content.borderOpacity; this._pixiGraphics.clear(); this._pixiGraphics.lineStyle( borderWidth, objectsRenderingService.rgbOrHexToHexNumber(borderColor), borderOpacity / 255 ); this._pixiGraphics.beginFill(
textOffset is not used anymore?
width = this.getCustomWidth(); height = this.getCustomHeight(); } this._pixiObject.pivot.x = width / 2; this._pixiObject.pivot.y = height / 2; this._pixiObject.position.x = instance.getX() + width / 2; this._pixiObject.position.y = instance.getY() + height / 2; this._pixiObject.rotation = RenderedInstance.toRad( this._instance.getAngle() ); const borderWidth = object.content.borderWidth || 0; // Draw the mask for the text. const textOffset = borderWidth + TEXT_MASK_PADDING; this._pixiTextMask.clear(); this._pixiTextMask.beginFill(0xdddddd, 1); this._pixiTextMask.drawRect( textOffset, textOffset, width - 2 * textOffset, height - 2 * textOffset ); this._pixiTextMask.endFill(); const isTextArea = object.content.inputType === 'text area'; const textAlign = object.content.textAlign ? object.content.textAlign : 'left'; const padding = object.content.padding ? parseFloat(object.content.padding) : 0; if (textAlign === 'left') this._pixiText.position.x = textOffset + padding; else if (textAlign === 'right') this._pixiText.position.x = 0 + width - this._pixiText.width - textOffset - padding; else if (textAlign === 'center') { this._pixiText.align = 'center'; this._pixiText.position.x = 0 + width / 2 - this._pixiText.width / 2; } this._pixiText.position.y = isTextArea ? textOffset : height / 2 - this._pixiText.height / 2; // Draw the background and border. const fillColor = object.content.fillColor; const fillOpacity = object.content.fillOpacity;
@@ -755,8 +808,16 @@ module.exports = { this._pixiTextMask.endFill(); const isTextArea = object.content.inputType === 'text area'; + const textAlign = object.content.textAlign; + if (textAlign === 'left') this._pixiText.position.x = 0;
Extensions/TextInput/JsExtension.js
26
JavaScript
0.143
question
31
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
namespace gdjs { const userFriendlyToHtmlInputTypes = { text: 'text', email: 'email', password: 'password', number: 'number', 'telephone number': 'tel', url: 'url', search: 'search', }; const userFriendlyToHtmlAlignement = { left: 'left', center: 'center', right: 'right', }; const formatRgbAndOpacityToCssRgba = ( rgbColor: [float, float, float], opacity: float ) => { return ( 'rgba(' + rgbColor[0] + ',' + rgbColor[1] + ',' + rgbColor[2] + ',' + opacity / 255 + ')' ); }; class TextInputRuntimeObjectPixiRenderer { private _object: gdjs.TextInputRuntimeObject; private _input: HTMLInputElement | HTMLTextAreaElement | null = null;
Does not seem useful in that case 😅
namespace gdjs { const userFriendlyToHtmlInputTypes = { text: 'text', email: 'email', password: 'password', number: 'number', 'telephone number': 'tel', url: 'url', search: 'search', }; const formatRgbAndOpacityToCssRgba = ( rgbColor: [float, float, float], opacity: float ) => { return ( 'rgba(' + rgbColor[0] + ',' + rgbColor[1] + ',' + rgbColor[2] + ',' + opacity / 255 + ')' ); }; class TextInputRuntimeObjectPixiRenderer { private _object: gdjs.TextInputRuntimeObject; private _input: HTMLInputElement | HTMLTextAreaElement | null = null; private _instanceContainer: gdjs.RuntimeInstanceContainer; private _runtimeGame: gdjs.RuntimeGame; private _form: HTMLFormElement | null = null; constructor( runtimeObject: gdjs.TextInputRuntimeObject,
@@ -9,6 +9,12 @@ namespace gdjs { search: 'search', }; + const userFriendlyToHtmlAlignement = {
Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts
12
TypeScript
0.143
suggestion
36
37
37
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
}; const formatRgbAndOpacityToCssRgba = ( rgbColor: [float, float, float], opacity: float ) => { return ( 'rgba(' + rgbColor[0] + ',' + rgbColor[1] + ',' + rgbColor[2] + ',' + opacity / 255 + ')' ); }; class TextInputRuntimeObjectPixiRenderer { private _object: gdjs.TextInputRuntimeObject; private _input: HTMLInputElement | HTMLTextAreaElement | null = null; private _instanceContainer: gdjs.RuntimeInstanceContainer; private _runtimeGame: gdjs.RuntimeGame; private _form: HTMLFormElement | null = null; private _isSubmited: boolean; constructor( runtimeObject: gdjs.TextInputRuntimeObject, instanceContainer: gdjs.RuntimeInstanceContainer ) { this._object = runtimeObject; this._instanceContainer = instanceContainer; this._runtimeGame = this._instanceContainer.getGame(); this._createElement(); this._isSubmited = false; } _createElement() { if (!!this._input) throw new Error('Tried to recreate an input while it already exists.'); this._form = document.createElement('form'); this._form.setAttribute('id', 'dynamicForm'); const isTextArea = this._object.getInputType() === 'text area'; this._input = document.createElement(isTextArea ? 'textarea' : 'input'); this._form.style.border = '0px'; this._input.autocomplete = 'off'; this._form.style.borderRadius = '0px'; this._form.style.backgroundColor = 'transparent';
```suggestion private _isSubmitted: boolean; ```
return ( 'rgba(' + rgbColor[0] + ',' + rgbColor[1] + ',' + rgbColor[2] + ',' + opacity / 255 + ')' ); }; class TextInputRuntimeObjectPixiRenderer { private _object: gdjs.TextInputRuntimeObject; private _input: HTMLInputElement | HTMLTextAreaElement | null = null; private _instanceContainer: gdjs.RuntimeInstanceContainer; private _runtimeGame: gdjs.RuntimeGame; private _form: HTMLFormElement | null = null; constructor( runtimeObject: gdjs.TextInputRuntimeObject, instanceContainer: gdjs.RuntimeInstanceContainer ) { this._object = runtimeObject; this._instanceContainer = instanceContainer; this._runtimeGame = this._instanceContainer.getGame(); this._createElement(); } _createElement() { if (!!this._input) throw new Error('Tried to recreate an input while it already exists.'); this._form = document.createElement('form'); const isTextArea = this._object.getInputType() === 'text area'; this._input = document.createElement(isTextArea ? 'textarea' : 'input'); this._form.style.border = '0px'; this._form.style.borderRadius = '0px'; this._form.style.backgroundColor = 'transparent'; this._form.style.position = 'absolute'; this._form.style.outline = 'none'; this._form.style.resize = 'none'; this._form.style.pointerEvents = 'auto'; // Element can be clicked/touched. this._form.style.display = 'none'; // Hide while object is being set up. this._form.style.boxSizing = 'border-box'; this._form.style.textAlign = this._object.getTextAlign();
@@ -31,6 +37,8 @@ namespace gdjs { private _input: HTMLInputElement | HTMLTextAreaElement | null = null; private _instanceContainer: gdjs.RuntimeInstanceContainer; private _runtimeGame: gdjs.RuntimeGame; + private _form: HTMLFormElement | null = null; + private _isSubmited: boolean;
Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts
26
TypeScript
0.571
suggestion
54
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
this._isSubmited = false; } _createElement() { if (!!this._input) throw new Error('Tried to recreate an input while it already exists.'); this._form = document.createElement('form'); this._form.setAttribute('id', 'dynamicForm'); const isTextArea = this._object.getInputType() === 'text area'; this._input = document.createElement(isTextArea ? 'textarea' : 'input'); this._form.style.border = '0px'; this._input.autocomplete = 'off'; this._form.style.borderRadius = '0px'; this._form.style.backgroundColor = 'transparent'; this._input.style.backgroundColor = 'red'; this._input.style.border = '1px solid black'; this._form.style.position = 'absolute'; this._form.style.resize = 'none'; this._form.style.outline = 'none'; this._form.style.pointerEvents = 'auto'; // Element can be clicked/touched. this._form.style.display = 'none'; // Hide while object is being set up. this._form.style.boxSizing = 'border-box'; // Important for iOS, because border is added to width/height. this._input.maxLength = this._object.getMaxLength(); this._input.style.padding = this._object.getPadding() + 'px'; this._form.style.textAlign = this._object.getTextAlign(); this._form.appendChild(this._input); this._isSubmited = false; this._input.addEventListener('input', () => { if (!this._input) return; this._object.onRendererInputValueChanged(this._input.value); }); this._input.addEventListener('touchstart', () => { if (!this._input) return; // Focus directly when touching the input on touchscreens. if (document.activeElement !== this._input) this._input.focus(); }); this._form.addEventListener('submit', (event) => { event.preventDefault(); this._isSubmited = true; }); this.updateString(); this.updateFont(); this.updatePlaceholder(); this.updateOpacity(); this.updateInputType();
If you decide to keep `userFriendlyToHtmlAlignement`, it should be used here
const isTextArea = this._object.getInputType() === 'text area'; this._input = document.createElement(isTextArea ? 'textarea' : 'input'); this._form.style.border = '0px'; this._form.style.borderRadius = '0px'; this._form.style.backgroundColor = 'transparent'; this._form.style.position = 'absolute'; this._form.style.outline = 'none'; this._form.style.resize = 'none'; this._form.style.pointerEvents = 'auto'; // Element can be clicked/touched. this._form.style.display = 'none'; // Hide while object is being set up. this._form.style.boxSizing = 'border-box'; this._form.style.textAlign = this._object.getTextAlign(); this._input.autocomplete = 'off'; this._input.style.backgroundColor = 'white'; this._input.style.border = '1px solid black'; this._input.style.boxSizing = 'border-box'; this._input.style.width = '100%'; this._input.style.height = '100%'; this._input.maxLength = this._object.getMaxLength(); this._input.style.padding = this._object.getPadding() + 'px'; this._form.appendChild(this._input); this._input.addEventListener('input', () => { if (!this._input) return; this._object.onRendererInputValueChanged(this._input.value); }); this._input.addEventListener('touchstart', () => { if (!this._input) return; // Focus directly when touching the input on touchscreens. if (document.activeElement !== this._input) this._input.focus(); }); this._form.addEventListener('submit', (event) => { event.preventDefault(); this._object.onRendererFormSubmitted(); }); this.updateString(); this.updateFont(); this.updatePlaceholder(); this.updateOpacity(); this.updateInputType(); this.updateTextColor(); this.updateFillColorAndOpacity(); this.updateBorderColorAndOpacity();
@@ -41,24 +49,34 @@ namespace gdjs { this._runtimeGame = this._instanceContainer.getGame(); this._createElement(); + this._isSubmited = false; } _createElement() { if (!!this._input) throw new Error('Tried to recreate an input while it already exists.'); + this._form = document.createElement('form'); + this._form.setAttribute('id', 'dynamicForm'); const isTextArea = this._object.getInputType() === 'text area'; this._input = document.createElement(isTextArea ? 'textarea' : 'input'); - this._input.style.border = '1px solid black'; + this._form.style.border = '0px'; this._input.autocomplete = 'off'; - this._input.style.borderRadius = '0px'; - this._input.style.backgroundColor = 'white'; - this._input.style.position = 'absolute'; - this._input.style.resize = 'none'; - this._input.style.outline = 'none'; - this._input.style.pointerEvents = 'auto'; // Element can be clicked/touched. - this._input.style.display = 'none'; // Hide while object is being set up. - this._input.style.boxSizing = 'border-box'; // Important for iOS, because border is added to width/height. + this._form.style.borderRadius = '0px'; + this._form.style.backgroundColor = 'transparent'; + this._input.style.backgroundColor = 'red'; + this._input.style.border = '1px solid black'; + this._form.style.position = 'absolute'; + this._form.style.resize = 'none'; + this._form.style.outline = 'none'; + this._form.style.pointerEvents = 'auto'; // Element can be clicked/touched. + this._form.style.display = 'none'; // Hide while object is being set up. + this._form.style.boxSizing = 'border-box'; // Important for iOS, because border is added to width/height. + this._input.maxLength = this._object.getMaxLength(); + this._input.style.padding = this._object.getPadding() + 'px'; + this._form.style.textAlign = this._object.getTextAlign();
Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts
26
TypeScript
0.429
suggestion
76
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
isDisabled(): boolean { return this._disabled; } setReadOnly(value: boolean) { this._readOnly = value; this._renderer.updateReadOnly(); } isReadOnly(): boolean { return this._readOnly; } isFocused(): boolean { return this._renderer.isFocused(); } isSubmitted(): boolean { console.log(this._renderer.getSubmitted()); return this._renderer.getSubmitted(); } getMaxLength(): integer { return this._maxLength; } SetMaxLength(value: integer) { this._maxLength = value; this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } SetPadding(value: integer) { this._padding = value; } getTextAlign(): SupportedtextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const lowercasedNewTextAlign = newTextAlign.toLowerCase(); if (lowercasedNewTextAlign === this._textAlign) return; this._textAlign = parseTextAlign(lowercasedNewTextAlign); this._renderer.updateTextAlign(); } focus(): void { if (!this.isFocused()) { // If the input was not previously focused, reset input manager because there is
In JS/TS, methods are usually written using camelCase
} setBorderWidth(width: float) { this._borderWidth = Math.max(0, width); this._renderer.updateBorderWidth(); } getBorderWidth(): float { return this._borderWidth; } setDisabled(value: boolean) { this._disabled = value; this._renderer.updateDisabled(); } isDisabled(): boolean { return this._disabled; } setReadOnly(value: boolean) { this._readOnly = value; this._renderer.updateReadOnly(); } isReadOnly(): boolean { return this._readOnly; } isFocused(): boolean { return this._renderer.isFocused(); } isSubmitted(): boolean { return this._isSubmitted; } getMaxLength(): integer { return this._maxLength; } setMaxLength(value: integer) { if (this._maxLength === value) return; this._maxLength = value; this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } setPadding(value: integer) { if (this._padding === value) return; if (value < 0) {
@@ -500,6 +531,37 @@ namespace gdjs { isFocused(): boolean { return this._renderer.isFocused(); } + isSubmitted(): boolean { + console.log(this._renderer.getSubmitted()); + + return this._renderer.getSubmitted(); + } + + getMaxLength(): integer { + return this._maxLength; + } + SetMaxLength(value: integer) {
Extensions/TextInput/textinputruntimeobject.ts
26
TypeScript
0.214
style
54
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
setDisabled(value: boolean) { this._disabled = value; this._renderer.updateDisabled(); } isDisabled(): boolean { return this._disabled; } setReadOnly(value: boolean) { this._readOnly = value; this._renderer.updateReadOnly(); } isReadOnly(): boolean { return this._readOnly; } isFocused(): boolean { return this._renderer.isFocused(); } isSubmitted(): boolean { console.log(this._renderer.getSubmitted()); return this._renderer.getSubmitted(); } getMaxLength(): integer { return this._maxLength; } SetMaxLength(value: integer) { this._maxLength = value; this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } SetPadding(value: integer) { this._padding = value; } getTextAlign(): SupportedtextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const lowercasedNewTextAlign = newTextAlign.toLowerCase(); if (lowercasedNewTextAlign === this._textAlign) return; this._textAlign = parseTextAlign(lowercasedNewTextAlign);
See other comment: I think this `isSubmitted` state should be stored at the object level.
this._borderOpacity = Math.max(0, Math.min(255, newOpacity)); this._renderer.updateBorderColorAndOpacity(); } getBorderOpacity(): float { return this._borderOpacity; } setBorderWidth(width: float) { this._borderWidth = Math.max(0, width); this._renderer.updateBorderWidth(); } getBorderWidth(): float { return this._borderWidth; } setDisabled(value: boolean) { this._disabled = value; this._renderer.updateDisabled(); } isDisabled(): boolean { return this._disabled; } setReadOnly(value: boolean) { this._readOnly = value; this._renderer.updateReadOnly(); } isReadOnly(): boolean { return this._readOnly; } isFocused(): boolean { return this._renderer.isFocused(); } isSubmitted(): boolean { return this._isSubmitted; } getMaxLength(): integer { return this._maxLength; } setMaxLength(value: integer) { if (this._maxLength === value) return; this._maxLength = value; this._renderer.updateMaxLength(); }
@@ -500,6 +531,37 @@ namespace gdjs { isFocused(): boolean { return this._renderer.isFocused(); } + isSubmitted(): boolean { + console.log(this._renderer.getSubmitted()); + + return this._renderer.getSubmitted();
Extensions/TextInput/textinputruntimeobject.ts
26
TypeScript
0.429
suggestion
89
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
.setType('color') .setLabel(_('Color')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderOpacity') .setValue( (objectContent.borderOpacity != undefined ? objectContent.borderOpacity : 255 ).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0)) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue(objectContent.maxLength || 0) .setType('number') .setLabel(_('Max length')) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('right') .addExtraInfo('center') .setLabel(_('text Alignement')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '',
Here and below: add .toString()
.setType('color') .setLabel(_('Color')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderOpacity') .setValue( (objectContent.borderOpacity != undefined ? objectContent.borderOpacity : 255 ).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue((objectContent.maxLength || 0).toString()) .setType('number') .setLabel(_('Max length')) .setDescription( _( 'The maximum length of the input value (this property will be ignored if the input type is a number).' ) ) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font'));
@@ -200,6 +209,30 @@ module.exports = { .setLabel(_('Width')) .setGroup(_('Border appearance')); + objectProperties + .getOrCreate('padding') + .setValue((objectContent.padding || 0))
Extensions/TextInput/JsExtension.js
26
JavaScript
0.071
suggestion
31
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
4ian
NeylMahfouf2608
namespace gdjs { const supportedInputTypes = [ 'text', 'email', 'password', 'number', 'telephone number', 'url', 'search', 'text area', ] as const; const supportedtextAlign = ['left', 'center', 'right'] as const; type SupportedInputType = typeof supportedInputTypes[number]; type SupportedtextAlign = typeof supportedtextAlign[number]; const parseInputType = (potentialInputType: string): SupportedInputType => { const lowercasedNewInputType = potentialInputType.toLowerCase(); // @ts-ignore - we're actually checking that this value is correct. if (supportedInputTypes.includes(lowercasedNewInputType)) return potentialInputType as SupportedInputType; return 'text'; }; const parseTextAlign = (potentialTextAlign: string): SupportedtextAlign => { const lowercasedNewTextAlign = potentialTextAlign.toLowerCase(); // @ts-ignore - we're actually checking that this value is correct. if (supportedtextAlign.includes(lowercasedNewTextAlign)) return potentialTextAlign as SupportedtextAlign; return 'left'; }; /** Base parameters for {@link gdjs.TextInputRuntimeObject} */ export interface TextInputObjectData extends ObjectData {
Capital T and below for the type too.
namespace gdjs { const supportedInputTypes = [ 'text', 'email', 'password', 'number', 'telephone number', 'url', 'search', 'text area', ] as const; const supportedTextAlign = ['left', 'center', 'right'] as const; type SupportedInputType = typeof supportedInputTypes[number]; type SupportedTextAlign = typeof supportedTextAlign[number]; const parseInputType = (potentialInputType: string): SupportedInputType => { const lowercasedNewInputType = potentialInputType.toLowerCase(); // @ts-ignore - we're actually checking that this value is correct. if (supportedInputTypes.includes(lowercasedNewInputType)) return potentialInputType as SupportedInputType; return 'text'; }; const parseTextAlign = ( potentialTextAlign: string | undefined ): SupportedTextAlign => { if (!potentialTextAlign) return 'left'; const lowercasedNewTextAlign = potentialTextAlign.toLowerCase(); // @ts-ignore - we're actually checking that this value is correct. if (supportedTextAlign.includes(lowercasedNewTextAlign)) return potentialTextAlign as SupportedTextAlign; return 'left'; };
@@ -9,9 +9,10 @@ namespace gdjs { 'search', 'text area', ] as const; + const supportedtextAlign = ['left', 'center', 'right'] as const;
Extensions/TextInput/textinputruntimeobject.ts
12
TypeScript
0.214
suggestion
37
37
37
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
4ian
NeylMahfouf2608
private _readOnly: boolean; private _isSubmitted: boolean; _renderer: TextInputRuntimeObjectRenderer; constructor( instanceContainer: gdjs.RuntimeInstanceContainer, objectData: TextInputObjectData ) { super(instanceContainer, objectData); this._string = objectData.content.initialValue; this._placeholder = objectData.content.placeholder; this._fontResourceName = objectData.content.fontResourceName; this._fontSize = objectData.content.fontSize || 20; this._inputType = parseInputType(objectData.content.inputType); this._textColor = gdjs.rgbOrHexToRGBColor(objectData.content.textColor); this._fillColor = gdjs.rgbOrHexToRGBColor(objectData.content.fillColor); this._fillOpacity = objectData.content.fillOpacity; this._borderColor = gdjs.rgbOrHexToRGBColor( objectData.content.borderColor ); this._borderOpacity = objectData.content.borderOpacity; this._borderWidth = objectData.content.borderWidth; this._disabled = objectData.content.disabled; this._readOnly = objectData.content.readOnly; this._padding = objectData.content.padding; this._textAlign = objectData.content.textAlign; this._maxLength = objectData.content.maxLength; this._isSubmitted = false; this._renderer = new gdjs.TextInputRuntimeObjectRenderer( this, instanceContainer ); // *ALWAYS* call `this.onCreated()` at the very end of your object constructor. this.onCreated(); } getRendererObject() { return null; } updateFromObjectData( oldObjectData: TextInputObjectData, newObjectData: TextInputObjectData ): boolean { if ( oldObjectData.content.initialValue !== newObjectData.content.initialValue ) { if (this._string === oldObjectData.content.initialValue) {
These can, sadly, be undefined. Add a default value in this case.
private _borderOpacity: float; private _borderWidth: float; private _disabled: boolean; private _readOnly: boolean; private _isSubmitted: boolean; _renderer: TextInputRuntimeObjectRenderer; constructor( instanceContainer: gdjs.RuntimeInstanceContainer, objectData: TextInputObjectData ) { super(instanceContainer, objectData); this._string = objectData.content.initialValue; this._placeholder = objectData.content.placeholder; this._fontResourceName = objectData.content.fontResourceName; this._fontSize = objectData.content.fontSize || 20; this._inputType = parseInputType(objectData.content.inputType); this._textColor = gdjs.rgbOrHexToRGBColor(objectData.content.textColor); this._fillColor = gdjs.rgbOrHexToRGBColor(objectData.content.fillColor); this._fillOpacity = objectData.content.fillOpacity; this._borderColor = gdjs.rgbOrHexToRGBColor( objectData.content.borderColor ); this._borderOpacity = objectData.content.borderOpacity; this._borderWidth = objectData.content.borderWidth; this._disabled = objectData.content.disabled; this._readOnly = objectData.content.readOnly; this._textAlign = parseTextAlign(objectData.content.textAlign); //textAlign is defaulted to 'left' by the parser if undefined. this._maxLength = objectData.content.maxLength || 0; //maxlength and padding require a default value as they can be undefined in older projects. this._padding = objectData.content.padding || 0; this._isSubmitted = false; this._renderer = new gdjs.TextInputRuntimeObjectRenderer( this, instanceContainer ); // *ALWAYS* call `this.onCreated()` at the very end of your object constructor. this.onCreated(); } getRendererObject() { return null; } updateFromObjectData( oldObjectData: TextInputObjectData, newObjectData: TextInputObjectData ): boolean { if ( oldObjectData.content.initialValue !==
@@ -113,7 +130,10 @@ namespace gdjs { this._borderWidth = objectData.content.borderWidth; this._disabled = objectData.content.disabled; this._readOnly = objectData.content.readOnly; - + this._padding = objectData.content.padding;
Extensions/TextInput/textinputruntimeobject.ts
26
TypeScript
0.357
suggestion
65
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
4ian
NeylMahfouf2608
} getText() { return this._string; } setText(newString: string) { if (newString === this._string) return; this._string = newString; this._renderer.updateString(); } /** * Called by the renderer when the value of the input shown on the screen * was changed (because the user typed something). * This does not propagate back the value to the renderer, which would * result in the cursor being sent back to the end of the text. * * Do not use this if you are not inside the renderer - use `setString` instead. */ onRendererInputValueChanged(inputValue: string) { this._string = inputValue; } onRendererFormSubmitted(inputValue: boolean) { this._isSubmitted = inputValue; } getFontResourceName() { return this._fontResourceName; } setFontResourceName(resourceName: string) { if (this._fontResourceName === resourceName) return; this._fontResourceName = resourceName; this._renderer.updateFont(); } getFontSize() { return this._fontSize; } setFontSize(newSize: number) { this._fontSize = newSize; } /** * Get the placeholder shown when no text is entered */
```suggestion onRendererFormSubmitted() { ```
* @deprecated use `getText` instead */ getString() { return this.getText(); } /** * Replace the text inside the text input. * @deprecated use `setText` instead */ setString(text: string) { this.setText(text); } getText() { return this._string; } setText(newString: string) { if (newString === this._string) return; this._string = newString; this._renderer.updateString(); } /** * Called by the renderer when the value of the input shown on the screen * was changed (because the user typed something). * This does not propagate back the value to the renderer, which would * result in the cursor being sent back to the end of the text. * * Do not use this if you are not inside the renderer - use `setString` instead. */ onRendererInputValueChanged(inputValue: string) { this._string = inputValue; } onRendererFormSubmitted() { this._isSubmitted = true; } getFontResourceName() { return this._fontResourceName; } setFontResourceName(resourceName: string) { if (this._fontResourceName === resourceName) return; this._fontResourceName = resourceName; this._renderer.updateFont(); }
@@ -348,6 +379,10 @@ namespace gdjs { onRendererInputValueChanged(inputValue: string) { this._string = inputValue; } + + onRendererFormSubmitted(inputValue: boolean) {
Extensions/TextInput/textinputruntimeobject.ts
26
TypeScript
0.571
suggestion
51
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
4ian
NeylMahfouf2608
return this._padding; } SetPadding(value: integer) { this._padding = value; } getTextAlign(): SupportedtextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const lowercasedNewTextAlign = newTextAlign.toLowerCase(); if (lowercasedNewTextAlign === this._textAlign) return; this._textAlign = parseTextAlign(lowercasedNewTextAlign); this._renderer.updateTextAlign(); } focus(): void { if (!this.isFocused()) { // If the input was not previously focused, reset input manager because there is // no reason to maintain its state. It avoids bugs where a key is pressed, the text // input is focused and then the input manager does not have access to the keyup event // and considers the key still pressed. this.getInstanceContainer() .getGame() .getInputManager() .clearAllPressedKeys(); } this._renderer.focus(); } } gdjs.registerObject( 'TextInput::TextInputObject', gdjs.TextInputRuntimeObject ); }
this._renderer.updatePadding();
isSubmitted(): boolean { return this._isSubmitted; } getMaxLength(): integer { return this._maxLength; } setMaxLength(value: integer) { if (this._maxLength === value) return; this._maxLength = value; this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } setPadding(value: integer) { if (this._padding === value) return; if (value < 0) { this._padding = 0; return; } this._padding = value; this._renderer.updatePadding(); } getTextAlign(): SupportedTextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const parsedTextAlign = parseTextAlign(newTextAlign); if (parsedTextAlign === this._textAlign) return; this._textAlign = parsedTextAlign; this._renderer.updateTextAlign(); } focus(): void { if (!this.isFocused()) { // If the input was not previously focused, reset input manager because there is // no reason to maintain its state. It avoids bugs where a key is pressed, the text // input is focused and then the input manager does not have access to the keyup event // and considers the key still pressed. this.getInstanceContainer() .getGame() .getInputManager() .clearAllPressedKeys(); } this._renderer.focus();
@@ -500,6 +535,35 @@ namespace gdjs { isFocused(): boolean { return this._renderer.isFocused(); } + isSubmitted(): boolean { + return this._isSubmitted; + } + + getMaxLength(): integer { + return this._maxLength; + } + setMaxLength(value: integer) { + this._maxLength = value; + this._renderer.updateMaxLength(); + } + getPadding(): integer { + return this._padding; + } + SetPadding(value: integer) { + this._padding = value; + }
Extensions/TextInput/textinputruntimeobject.ts
26
TypeScript
0.071
suggestion
31
38
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
4ian
NeylMahfouf2608
constructor( runtimeObject: gdjs.TextInputRuntimeObject, instanceContainer: gdjs.RuntimeInstanceContainer ) { this._object = runtimeObject; this._instanceContainer = instanceContainer; this._runtimeGame = this._instanceContainer.getGame(); this._createElement(); } _createElement() { if (!!this._input) throw new Error('Tried to recreate an input while it already exists.'); this._form = document.createElement('form'); const isTextArea = this._object.getInputType() === 'text area'; this._input = document.createElement(isTextArea ? 'textarea' : 'input'); this._form.style.border = '0px'; this._input.autocomplete = 'off'; this._form.style.borderRadius = '0px'; this._form.style.backgroundColor = 'transparent'; this._input.style.backgroundColor = 'white'; this._input.style.border = '1px solid black'; this._form.style.position = 'absolute'; this._form.style.resize = 'none'; this._form.style.outline = 'none'; this._form.style.pointerEvents = 'auto'; // Element can be clicked/touched. this._form.style.display = 'none'; // Hide while object is being set up. this._form.style.boxSizing = 'border-box'; // Important for iOS, because border is added to width/height. this._input.style.boxSizing = 'border-box'; this._input.style.width = '100%'; this._input.style.height = '100%'; this._input.style.padding = this._object.getPadding() + 'px'; this._form.style.textAlign = this._object.getTextAlign(); this._form.appendChild(this._input); this._input.maxLength = this._object.getMaxLength(); this._input.addEventListener('input', () => { if (!this._input) return; this._object.onRendererInputValueChanged(this._input.value); }); this._input.addEventListener('touchstart', () => { if (!this._input) return; // Focus directly when touching the input on touchscreens. if (document.activeElement !== this._input) this._input.focus(); });
Could you split the lines where you change `this._form` and those where you change `this._input` ? it's a bit hard to read at the moment
constructor( runtimeObject: gdjs.TextInputRuntimeObject, instanceContainer: gdjs.RuntimeInstanceContainer ) { this._object = runtimeObject; this._instanceContainer = instanceContainer; this._runtimeGame = this._instanceContainer.getGame(); this._createElement(); } _createElement() { if (!!this._input) throw new Error('Tried to recreate an input while it already exists.'); this._form = document.createElement('form'); const isTextArea = this._object.getInputType() === 'text area'; this._input = document.createElement(isTextArea ? 'textarea' : 'input'); this._form.style.border = '0px'; this._form.style.borderRadius = '0px'; this._form.style.backgroundColor = 'transparent'; this._form.style.position = 'absolute'; this._form.style.outline = 'none'; this._form.style.resize = 'none'; this._form.style.pointerEvents = 'auto'; // Element can be clicked/touched. this._form.style.display = 'none'; // Hide while object is being set up. this._form.style.boxSizing = 'border-box'; this._form.style.textAlign = this._object.getTextAlign(); this._input.autocomplete = 'off'; this._input.style.backgroundColor = 'white'; this._input.style.border = '1px solid black'; this._input.style.boxSizing = 'border-box'; this._input.style.width = '100%'; this._input.style.height = '100%'; this._input.maxLength = this._object.getMaxLength(); this._input.style.padding = this._object.getPadding() + 'px'; this._form.appendChild(this._input); this._input.addEventListener('input', () => { if (!this._input) return; this._object.onRendererInputValueChanged(this._input.value); }); this._input.addEventListener('touchstart', () => { if (!this._input) return;
@@ -47,18 +48,28 @@ namespace gdjs { if (!!this._input) throw new Error('Tried to recreate an input while it already exists.'); + this._form = document.createElement('form'); const isTextArea = this._object.getInputType() === 'text area'; this._input = document.createElement(isTextArea ? 'textarea' : 'input'); - this._input.style.border = '1px solid black'; + this._form.style.border = '0px'; this._input.autocomplete = 'off'; - this._input.style.borderRadius = '0px'; + this._form.style.borderRadius = '0px'; + this._form.style.backgroundColor = 'transparent'; this._input.style.backgroundColor = 'white'; - this._input.style.position = 'absolute'; - this._input.style.resize = 'none'; - this._input.style.outline = 'none'; - this._input.style.pointerEvents = 'auto'; // Element can be clicked/touched. - this._input.style.display = 'none'; // Hide while object is being set up. - this._input.style.boxSizing = 'border-box'; // Important for iOS, because border is added to width/height. + this._input.style.border = '1px solid black'; + this._form.style.position = 'absolute'; + this._form.style.resize = 'none'; + this._form.style.outline = 'none';
Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts
26
TypeScript
0.571
question
136
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
this._object = runtimeObject; this._instanceContainer = instanceContainer; this._runtimeGame = this._instanceContainer.getGame(); this._createElement(); } _createElement() { if (!!this._input) throw new Error('Tried to recreate an input while it already exists.'); this._form = document.createElement('form'); const isTextArea = this._object.getInputType() === 'text area'; this._input = document.createElement(isTextArea ? 'textarea' : 'input'); this._form.style.border = '0px'; this._input.autocomplete = 'off'; this._form.style.borderRadius = '0px'; this._form.style.backgroundColor = 'transparent'; this._input.style.backgroundColor = 'white'; this._input.style.border = '1px solid black'; this._form.style.position = 'absolute'; this._form.style.resize = 'none'; this._form.style.outline = 'none'; this._form.style.pointerEvents = 'auto'; // Element can be clicked/touched. this._form.style.display = 'none'; // Hide while object is being set up. this._form.style.boxSizing = 'border-box'; // Important for iOS, because border is added to width/height. this._input.style.boxSizing = 'border-box'; this._input.style.width = '100%'; this._input.style.height = '100%'; this._input.style.padding = this._object.getPadding() + 'px'; this._form.style.textAlign = this._object.getTextAlign(); this._form.appendChild(this._input); this._input.maxLength = this._object.getMaxLength(); this._input.addEventListener('input', () => { if (!this._input) return; this._object.onRendererInputValueChanged(this._input.value); }); this._input.addEventListener('touchstart', () => { if (!this._input) return; // Focus directly when touching the input on touchscreens. if (document.activeElement !== this._input) this._input.focus(); }); this._form.addEventListener('submit', (event) => { event.preventDefault(); this._object.onRendererFormSubmitted(); });
I'm not sure you mean `iOS` here. Did you mean a specific browser?
this._object = runtimeObject; this._instanceContainer = instanceContainer; this._runtimeGame = this._instanceContainer.getGame(); this._createElement(); } _createElement() { if (!!this._input) throw new Error('Tried to recreate an input while it already exists.'); this._form = document.createElement('form'); const isTextArea = this._object.getInputType() === 'text area'; this._input = document.createElement(isTextArea ? 'textarea' : 'input'); this._form.style.border = '0px'; this._form.style.borderRadius = '0px'; this._form.style.backgroundColor = 'transparent'; this._form.style.position = 'absolute'; this._form.style.outline = 'none'; this._form.style.resize = 'none'; this._form.style.pointerEvents = 'auto'; // Element can be clicked/touched. this._form.style.display = 'none'; // Hide while object is being set up. this._form.style.boxSizing = 'border-box'; this._form.style.textAlign = this._object.getTextAlign(); this._input.autocomplete = 'off'; this._input.style.backgroundColor = 'white'; this._input.style.border = '1px solid black'; this._input.style.boxSizing = 'border-box'; this._input.style.width = '100%'; this._input.style.height = '100%'; this._input.maxLength = this._object.getMaxLength(); this._input.style.padding = this._object.getPadding() + 'px'; this._form.appendChild(this._input); this._input.addEventListener('input', () => { if (!this._input) return; this._object.onRendererInputValueChanged(this._input.value); }); this._input.addEventListener('touchstart', () => { if (!this._input) return; // Focus directly when touching the input on touchscreens. if (document.activeElement !== this._input) this._input.focus(); }); this._form.addEventListener('submit', (event) => {
@@ -47,18 +48,28 @@ namespace gdjs { if (!!this._input) throw new Error('Tried to recreate an input while it already exists.'); + this._form = document.createElement('form'); const isTextArea = this._object.getInputType() === 'text area'; this._input = document.createElement(isTextArea ? 'textarea' : 'input'); - this._input.style.border = '1px solid black'; + this._form.style.border = '0px'; this._input.autocomplete = 'off'; - this._input.style.borderRadius = '0px'; + this._form.style.borderRadius = '0px'; + this._form.style.backgroundColor = 'transparent'; this._input.style.backgroundColor = 'white'; - this._input.style.position = 'absolute'; - this._input.style.resize = 'none'; - this._input.style.outline = 'none'; - this._input.style.pointerEvents = 'auto'; // Element can be clicked/touched. - this._input.style.display = 'none'; // Hide while object is being set up. - this._input.style.boxSizing = 'border-box'; // Important for iOS, because border is added to width/height. + this._input.style.border = '1px solid black'; + this._form.style.position = 'absolute'; + this._form.style.resize = 'none'; + this._form.style.outline = 'none'; + this._form.style.pointerEvents = 'auto'; // Element can be clicked/touched. + this._form.style.display = 'none'; // Hide while object is being set up. + this._form.style.boxSizing = 'border-box'; // Important for iOS, because border is added to width/height.
Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts
26
TypeScript
0.357
question
66
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
runtimeGameRenderer.convertCanvasToDomElementContainerCoords( workingPoint, workingPoint ); const pageLeft = workingPoint[0]; const pageTop = workingPoint[1]; workingPoint[0] = canvasRight; workingPoint[1] = canvasBottom; runtimeGameRenderer.convertCanvasToDomElementContainerCoords( workingPoint, workingPoint ); const pageRight = workingPoint[0]; const pageBottom = workingPoint[1]; const widthInContainer = pageRight - pageLeft; const heightInContainer = pageBottom - pageTop; this._form.style.left = pageLeft + 'px'; this._form.style.top = pageTop + 'px'; this._form.style.width = widthInContainer + 'px'; this._form.style.height = heightInContainer + 'px'; this._form.style.transform = 'rotate3d(0,0,1,' + (this._object.getAngle() % 360) + 'deg)'; this._input.style.padding = this._object.getPadding() + 'px'; this._form.style.textAlign = this._object.getTextAlign(); // Automatically adjust the font size to follow the game scale. this._input.style.fontSize = this._object.getFontSize() * runtimeGameRenderer.getCanvasToDomElementContainerHeightScale() + 'px'; // Display after the object is positioned. this._form.style.display = 'initial'; } updateString() { if (!this._input) return; this._input.value = this._object.getString(); } updatePlaceholder() { if (!this._input) return; this._input.placeholder = this._object.getPlaceholder(); } updateFont() { if (!this._input) return; this._input.style.fontFamily = this._instanceContainer
I think the padding should have a minimum of 0, otherwise you might have some weird results
// Position the input on the container on top of the canvas. workingPoint[0] = canvasLeft; workingPoint[1] = canvasTop; runtimeGameRenderer.convertCanvasToDomElementContainerCoords( workingPoint, workingPoint ); const pageLeft = workingPoint[0]; const pageTop = workingPoint[1]; workingPoint[0] = canvasRight; workingPoint[1] = canvasBottom; runtimeGameRenderer.convertCanvasToDomElementContainerCoords( workingPoint, workingPoint ); const pageRight = workingPoint[0]; const pageBottom = workingPoint[1]; const widthInContainer = pageRight - pageLeft; const heightInContainer = pageBottom - pageTop; this._form.style.left = pageLeft + 'px'; this._form.style.top = pageTop + 'px'; this._form.style.width = widthInContainer + 'px'; this._form.style.height = heightInContainer + 'px'; this._form.style.transform = 'rotate3d(0,0,1,' + (this._object.getAngle() % 360) + 'deg)'; this._form.style.textAlign = this._object.getTextAlign(); this._input.style.padding = this._object.getPadding() + 'px'; // Automatically adjust the font size to follow the game scale. this._input.style.fontSize = this._object.getFontSize() * runtimeGameRenderer.getCanvasToDomElementContainerHeightScale() + 'px'; // Display after the object is positioned. this._form.style.display = 'initial'; } updateString() { if (!this._input) return; this._input.value = this._object.getString(); } updatePlaceholder() { if (!this._input) return; this._input.placeholder = this._object.getPlaceholder();
@@ -210,12 +228,14 @@ namespace gdjs { const widthInContainer = pageRight - pageLeft; const heightInContainer = pageBottom - pageTop; - this._input.style.left = pageLeft + 'px'; - this._input.style.top = pageTop + 'px'; - this._input.style.width = widthInContainer + 'px'; - this._input.style.height = heightInContainer + 'px'; - this._input.style.transform = + this._form.style.left = pageLeft + 'px'; + this._form.style.top = pageTop + 'px'; + this._form.style.width = widthInContainer + 'px'; + this._form.style.height = heightInContainer + 'px'; + this._form.style.transform = 'rotate3d(0,0,1,' + (this._object.getAngle() % 360) + 'deg)'; + this._input.style.padding = this._object.getPadding() + 'px';
Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts
26
TypeScript
0.286
suggestion
91
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
this._input.style.borderColor = formatRgbAndOpacityToCssRgba( this._object._getRawBorderColor(), this._object.getBorderOpacity() ); } updateBorderWidth() { if (!this._input) return; this._input.style.borderWidth = this._object.getBorderWidth() + 'px'; } updateDisabled() { if (!this._form) return; this._form.disabled = this._object.isDisabled(); } updateReadOnly() { if (!this._form) return; this._form.readOnly = this._object.isReadOnly(); } updateMaxLength() { if (!this._input) return; if (this._object.getMaxLength() <= 0) { this._input?.removeAttribute('maxLength'); return; } this._input.maxLength = this._object.getMaxLength(); } updatePadding() { if (!this._input) return; this._input.style.padding = this._object.getPadding() + 'px'; } updateTextAlign() { if (!this._input) return; const newTextAlign = this._object.getTextAlign() || 'left'; this._input.style.textAlign = newTextAlign; } isFocused() { return this._input === document.activeElement; } focus() { if (!this._input) return;
to avoid having the `?`, you could do this: ```js const input = this._input; if (!input) return; // From then on, you can use `input` without TS complaining ```
); } updateBorderColorAndOpacity() { if (!this._input) return; this._input.style.borderColor = formatRgbAndOpacityToCssRgba( this._object._getRawBorderColor(), this._object.getBorderOpacity() ); } updateBorderWidth() { if (!this._input) return; this._input.style.borderWidth = this._object.getBorderWidth() + 'px'; } updateDisabled() { if (!this._form) return; this._form.disabled = this._object.isDisabled(); } updateReadOnly() { if (!this._form) return; this._form.readOnly = this._object.isReadOnly(); } updateMaxLength() { const input = this._input; if (!input) return; if (this._object.getMaxLength() <= 0) { input.removeAttribute('maxLength'); return; } input.maxLength = this._object.getMaxLength(); } updatePadding() { if (!this._input) return; this._input.style.padding = this._object.getPadding() + 'px'; } updateTextAlign() { if (!this._input) return; const newTextAlign = this._object.getTextAlign(); this._input.style.textAlign = newTextAlign; } isFocused() {
@@ -297,14 +317,36 @@ namespace gdjs { this._input.style.borderWidth = this._object.getBorderWidth() + 'px'; } updateDisabled() { - if (!this._input) return; + if (!this._form) return; - this._input.disabled = this._object.isDisabled(); + this._form.disabled = this._object.isDisabled(); } updateReadOnly() { + if (!this._form) return; + + this._form.readOnly = this._object.isReadOnly(); + } + + updateMaxLength() { + if (!this._input) return; + if (this._object.getMaxLength() <= 0) { + this._input?.removeAttribute('maxLength');
Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts
26
TypeScript
0.786
suggestion
165
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } setPadding(value: integer) { this._padding = value; this._renderer.updatePadding(); } getTextAlign(): SupportedTextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const lowercasedNewTextAlign = newTextAlign.toLowerCase(); if (lowercasedNewTextAlign === this._textAlign) return; this._textAlign = parseTextAlign(lowercasedNewTextAlign); this._renderer.updateTextAlign(); } focus(): void { if (!this.isFocused()) { // If the input was not previously focused, reset input manager because there is // no reason to maintain its state. It avoids bugs where a key is pressed, the text // input is focused and then the input manager does not have access to the keyup event // and considers the key still pressed. this.getInstanceContainer() .getGame() .getInputManager() .clearAllPressedKeys(); } this._renderer.focus(); } } gdjs.registerObject( 'TextInput::TextInputObject', gdjs.TextInputRuntimeObject ); }
Early return if values are equal?
return this._renderer.isFocused(); } isSubmitted(): boolean { return this._isSubmitted; } getMaxLength(): integer { return this._maxLength; } setMaxLength(value: integer) { if (this._maxLength === value) return; this._maxLength = value; this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } setPadding(value: integer) { if (this._padding === value) return; if (value < 0) { this._padding = 0; return; } this._padding = value; this._renderer.updatePadding(); } getTextAlign(): SupportedTextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const parsedTextAlign = parseTextAlign(newTextAlign); if (parsedTextAlign === this._textAlign) return; this._textAlign = parsedTextAlign; this._renderer.updateTextAlign(); } focus(): void { if (!this.isFocused()) { // If the input was not previously focused, reset input manager because there is // no reason to maintain its state. It avoids bugs where a key is pressed, the text // input is focused and then the input manager does not have access to the keyup event // and considers the key still pressed. this.getInstanceContainer() .getGame() .getInputManager() .clearAllPressedKeys();
@@ -500,6 +536,36 @@ namespace gdjs { isFocused(): boolean { return this._renderer.isFocused(); } + isSubmitted(): boolean { + return this._isSubmitted; + } + + getMaxLength(): integer { + return this._maxLength; + } + setMaxLength(value: integer) { + this._maxLength = value; + this._renderer.updateMaxLength(); + } + getPadding(): integer { + return this._padding; + } + setPadding(value: integer) { + this._padding = value;
Extensions/TextInput/textinputruntimeobject.ts
26
TypeScript
0.071
question
33
42
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
isFocused(): boolean { return this._renderer.isFocused(); } isSubmitted(): boolean { return this._isSubmitted; } getMaxLength(): integer { return this._maxLength; } setMaxLength(value: integer) { this._maxLength = value; this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } setPadding(value: integer) { this._padding = value; this._renderer.updatePadding(); } getTextAlign(): SupportedTextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const lowercasedNewTextAlign = newTextAlign.toLowerCase(); if (lowercasedNewTextAlign === this._textAlign) return; this._textAlign = parseTextAlign(lowercasedNewTextAlign); this._renderer.updateTextAlign(); } focus(): void { if (!this.isFocused()) { // If the input was not previously focused, reset input manager because there is // no reason to maintain its state. It avoids bugs where a key is pressed, the text // input is focused and then the input manager does not have access to the keyup event // and considers the key still pressed. this.getInstanceContainer() .getGame() .getInputManager() .clearAllPressedKeys(); } this._renderer.focus(); } } gdjs.registerObject( 'TextInput::TextInputObject',
Early return if values are equal?
return this._disabled; } setReadOnly(value: boolean) { this._readOnly = value; this._renderer.updateReadOnly(); } isReadOnly(): boolean { return this._readOnly; } isFocused(): boolean { return this._renderer.isFocused(); } isSubmitted(): boolean { return this._isSubmitted; } getMaxLength(): integer { return this._maxLength; } setMaxLength(value: integer) { if (this._maxLength === value) return; this._maxLength = value; this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } setPadding(value: integer) { if (this._padding === value) return; if (value < 0) { this._padding = 0; return; } this._padding = value; this._renderer.updatePadding(); } getTextAlign(): SupportedTextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const parsedTextAlign = parseTextAlign(newTextAlign); if (parsedTextAlign === this._textAlign) return; this._textAlign = parsedTextAlign;
@@ -500,6 +536,36 @@ namespace gdjs { isFocused(): boolean { return this._renderer.isFocused(); } + isSubmitted(): boolean { + return this._isSubmitted; + } + + getMaxLength(): integer { + return this._maxLength; + } + setMaxLength(value: integer) { + this._maxLength = value;
Extensions/TextInput/textinputruntimeobject.ts
26
TypeScript
0.071
question
33
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
} getMaxLength(): integer { return this._maxLength; } setMaxLength(value: integer) { this._maxLength = value; this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } setPadding(value: integer) { this._padding = value; this._renderer.updatePadding(); } getTextAlign(): SupportedTextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const lowercasedNewTextAlign = newTextAlign.toLowerCase(); if (lowercasedNewTextAlign === this._textAlign) return; this._textAlign = parseTextAlign(lowercasedNewTextAlign); this._renderer.updateTextAlign(); } focus(): void { if (!this.isFocused()) { // If the input was not previously focused, reset input manager because there is // no reason to maintain its state. It avoids bugs where a key is pressed, the text // input is focused and then the input manager does not have access to the keyup event // and considers the key still pressed. this.getInstanceContainer() .getGame() .getInputManager() .clearAllPressedKeys(); } this._renderer.focus(); } } gdjs.registerObject( 'TextInput::TextInputObject', gdjs.TextInputRuntimeObject ); }
You can do the parsing as the first step and then you the returned value for the early return. Otherwise, you equality check above is wrong
} isReadOnly(): boolean { return this._readOnly; } isFocused(): boolean { return this._renderer.isFocused(); } isSubmitted(): boolean { return this._isSubmitted; } getMaxLength(): integer { return this._maxLength; } setMaxLength(value: integer) { if (this._maxLength === value) return; this._maxLength = value; this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } setPadding(value: integer) { if (this._padding === value) return; if (value < 0) { this._padding = 0; return; } this._padding = value; this._renderer.updatePadding(); } getTextAlign(): SupportedTextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const parsedTextAlign = parseTextAlign(newTextAlign); if (parsedTextAlign === this._textAlign) return; this._textAlign = parsedTextAlign; this._renderer.updateTextAlign(); } focus(): void { if (!this.isFocused()) { // If the input was not previously focused, reset input manager because there is
@@ -500,6 +536,36 @@ namespace gdjs { isFocused(): boolean { return this._renderer.isFocused(); } + isSubmitted(): boolean { + return this._isSubmitted; + } + + getMaxLength(): integer { + return this._maxLength; + } + setMaxLength(value: integer) { + this._maxLength = value; + this._renderer.updateMaxLength(); + } + getPadding(): integer { + return this._padding; + } + setPadding(value: integer) { + this._padding = value; + this._renderer.updatePadding(); + } + + getTextAlign(): SupportedTextAlign { + return this._textAlign; + } + + setTextAlign(newTextAlign: string) { + const lowercasedNewTextAlign = newTextAlign.toLowerCase(); + if (lowercasedNewTextAlign === this._textAlign) return; + + this._textAlign = parseTextAlign(lowercasedNewTextAlign);
Extensions/TextInput/textinputruntimeobject.ts
26
TypeScript
0.357
bug
139
49
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
: 255 ).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue((objectContent.maxLength || 0).toString()) .setType('number') .setLabel(_('Max length')) .setDescription(_('The maximum length of the input value.')) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255, borderColor: '0;0;0', borderOpacity: 255,
I added a comment on the PR, I think you should add in the description that this property will not be used if the input type is a number.
: 255 ).toString() ) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue((objectContent.maxLength || 0).toString()) .setType('number') .setLabel(_('Max length')) .setDescription( _( 'The maximum length of the input value (this property will be ignored if the input type is a number).' ) ) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0',
@@ -200,6 +209,30 @@ module.exports = { .setLabel(_('Width')) .setGroup(_('Border appearance')); + objectProperties + .getOrCreate('padding') + .setValue((objectContent.padding || 0).toString()) + .setType('number') + .setLabel(_('Padding')) + .setGroup(_('Font')); + objectProperties + .getOrCreate('maxLength') + .setValue((objectContent.maxLength || 0).toString()) + .setType('number') + .setLabel(_('Max length')) + .setDescription(_('The maximum length of the input value.'))
Extensions/TextInput/JsExtension.js
26
JavaScript
0.571
suggestion
137
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
.setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255, borderColor: '0;0;0', borderOpacity: 255, borderWidth: 1, readOnly: false, disabled: false, padding: 0, textAlign: 'left', maxLength: '20', }; textInputObject.updateInitialInstanceProperty = function ( instance, propertyName, newValue ) { if (propertyName === 'initialValue') { instance.setRawStringProperty('initialValue', newValue); return true; } else if (propertyName === 'placeholder') { instance.setRawStringProperty('placeholder', newValue); return true; } return false; }; textInputObject.getInitialInstanceProperties = function (instance) { const instanceProperties = new gd.MapStringPropertyDescriptor(); instanceProperties .getOrCreate('initialValue') .setValue(instance.getRawStringProperty('initialValue')) .setType('string') .setLabel(_('Initial value'));
Should it be a string here? Also, should you use -1/0 instead as an initial value?
objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255, borderColor: '0;0;0', borderOpacity: 255, borderWidth: 1, readOnly: false, disabled: false, padding: 0, textAlign: 'left', maxLength: 0, }; textInputObject.updateInitialInstanceProperty = function ( instance, propertyName, newValue ) { if (propertyName === 'initialValue') { instance.setRawStringProperty('initialValue', newValue); return true; } else if (propertyName === 'placeholder') { instance.setRawStringProperty('placeholder', newValue); return true; } return false; }; textInputObject.getInitialInstanceProperties = function (instance) { const instanceProperties = new gd.MapStringPropertyDescriptor(); instanceProperties
@@ -216,6 +249,9 @@ module.exports = { borderWidth: 1, readOnly: false, disabled: false, + padding: 0, + textAlign: 'left', + maxLength: '20',
Extensions/TextInput/JsExtension.js
26
JavaScript
0.286
question
82
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
// Display after the object is positioned. this._form.style.display = 'initial'; } updateString() { if (!this._input) return; this._input.value = this._object.getString(); } updatePlaceholder() { if (!this._input) return; this._input.placeholder = this._object.getPlaceholder(); } updateFont() { if (!this._input) return; this._input.style.fontFamily = this._instanceContainer .getGame() .getFontManager() .getFontFamily(this._object.getFontResourceName()); } updateOpacity() { if (!this._form) return; this._form.style.opacity = '' + this._object.getOpacity() / 255; } updateInputType() { if (!this._input) return; const isTextArea = this._input instanceof HTMLTextAreaElement; const shouldBeTextArea = this._object.getInputType() === 'text area'; if (isTextArea !== shouldBeTextArea) { this._destroyElement(); this._createElement(); } const newType = userFriendlyToHtmlInputTypes[this._object.getInputType()] || 'text'; this._input.setAttribute('type', newType); } updateTextColor() { if (!this._input) return; this._input.style.color = formatRgbAndOpacityToCssRgba( this._object._getRawTextColor(), 255 ); }
I think you could use `(this._object.getOpacity() / 255).toFixed(3)` instead. The result of the division could be `0.59200000000005`, and I'm not sure if CSS has some limitations about that.
// Display after the object is positioned. this._form.style.display = 'initial'; } updateString() { if (!this._input) return; this._input.value = this._object.getString(); } updatePlaceholder() { if (!this._input) return; this._input.placeholder = this._object.getPlaceholder(); } updateFont() { if (!this._input) return; this._input.style.fontFamily = this._instanceContainer .getGame() .getFontManager() .getFontFamily(this._object.getFontResourceName()); } updateOpacity() { if (!this._form) return; this._form.style.opacity = (this._object.getOpacity() / 255).toFixed(3); } updateInputType() { if (!this._input) return; const isTextArea = this._input instanceof HTMLTextAreaElement; const shouldBeTextArea = this._object.getInputType() === 'text area'; if (isTextArea !== shouldBeTextArea) { this._destroyElement(); this._createElement(); } const newType = userFriendlyToHtmlInputTypes[this._object.getInputType()] || 'text'; this._input.setAttribute('type', newType); } updateTextColor() { if (!this._input) return; this._input.style.color = formatRgbAndOpacityToCssRgba( this._object._getRawTextColor(), 255 ); }
@@ -246,8 +271,8 @@ namespace gdjs { } updateOpacity() { - if (!this._input) return; - this._input.style.opacity = '' + this._object.getOpacity() / 255; + if (!this._form) return; + this._form.style.opacity = '' + this._object.getOpacity() / 255;
Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts
26
TypeScript
0.571
suggestion
190
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
updateReadOnly() { if (!this._form) return; this._form.readOnly = this._object.isReadOnly(); } updateMaxLength() { const input = this._input; if (!input) return; if (this._object.getMaxLength() <= 0) { input.removeAttribute('maxLength'); return; } input.maxLength = this._object.getMaxLength(); } updatePadding() { if (!this._input) return; this._input.style.padding = this._object.getPadding() + 'px'; } updateTextAlign() { if (!this._input) return; const newTextAlign = this._object.getTextAlign() || 'left'; this._input.style.textAlign = newTextAlign; } isFocused() { return this._input === document.activeElement; } focus() { if (!this._input) return; this._input.focus(); } } export const TextInputRuntimeObjectRenderer = TextInputRuntimeObjectPixiRenderer; export type TextInputRuntimeObjectRenderer = TextInputRuntimeObjectPixiRenderer; }
Is the `|| 'left'` necessary? I think we can be confident that the object only stores correct values
updateReadOnly() { if (!this._form) return; this._form.readOnly = this._object.isReadOnly(); } updateMaxLength() { const input = this._input; if (!input) return; if (this._object.getMaxLength() <= 0) { input.removeAttribute('maxLength'); return; } input.maxLength = this._object.getMaxLength(); } updatePadding() { if (!this._input) return; this._input.style.padding = this._object.getPadding() + 'px'; } updateTextAlign() { if (!this._input) return; const newTextAlign = this._object.getTextAlign(); this._input.style.textAlign = newTextAlign; } isFocused() { return this._input === document.activeElement; } focus() { if (!this._input) return; this._input.focus(); } } export const TextInputRuntimeObjectRenderer = TextInputRuntimeObjectPixiRenderer; export type TextInputRuntimeObjectRenderer = TextInputRuntimeObjectPixiRenderer; }
@@ -297,14 +322,37 @@ namespace gdjs { this._input.style.borderWidth = this._object.getBorderWidth() + 'px'; } updateDisabled() { - if (!this._input) return; + if (!this._form) return; - this._input.disabled = this._object.isDisabled(); + this._form.disabled = this._object.isDisabled(); } updateReadOnly() { + if (!this._form) return; + + this._form.readOnly = this._object.isReadOnly(); + } + + updateMaxLength() { + const input = this._input; + if (!input) return; + if (this._object.getMaxLength() <= 0) { + input.removeAttribute('maxLength'); + return; + } + input.maxLength = this._object.getMaxLength(); + } + + updatePadding() { + if (!this._input) return; + + this._input.style.padding = this._object.getPadding() + 'px'; + } + + updateTextAlign() { if (!this._input) return; - this._input.readOnly = this._object.isReadOnly(); + const newTextAlign = this._object.getTextAlign() || 'left';
Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts
26
TypeScript
0.5
suggestion
100
43
43
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
private _isSubmitted: boolean; _renderer: TextInputRuntimeObjectRenderer; constructor( instanceContainer: gdjs.RuntimeInstanceContainer, objectData: TextInputObjectData ) { super(instanceContainer, objectData); this._string = objectData.content.initialValue; this._placeholder = objectData.content.placeholder; this._fontResourceName = objectData.content.fontResourceName; this._fontSize = objectData.content.fontSize || 20; this._inputType = parseInputType(objectData.content.inputType); this._textColor = gdjs.rgbOrHexToRGBColor(objectData.content.textColor); this._fillColor = gdjs.rgbOrHexToRGBColor(objectData.content.fillColor); this._fillOpacity = objectData.content.fillOpacity; this._borderColor = gdjs.rgbOrHexToRGBColor( objectData.content.borderColor ); this._borderOpacity = objectData.content.borderOpacity; this._borderWidth = objectData.content.borderWidth; this._disabled = objectData.content.disabled; this._readOnly = objectData.content.readOnly; this._padding = objectData.content.padding || 0; this._textAlign = objectData.content.textAlign || 'left'; this._maxLength = objectData.content.maxLength || 0; this._isSubmitted = false; this._renderer = new gdjs.TextInputRuntimeObjectRenderer( this, instanceContainer ); // *ALWAYS* call `this.onCreated()` at the very end of your object constructor. this.onCreated(); } getRendererObject() { return null; } updateFromObjectData( oldObjectData: TextInputObjectData, newObjectData: TextInputObjectData ): boolean { if ( oldObjectData.content.initialValue !== newObjectData.content.initialValue ) { if (this._string === oldObjectData.content.initialValue) { this.setString(newObjectData.content.initialValue);
You could use `parseTextAlign` here.
private _borderWidth: float; private _disabled: boolean; private _readOnly: boolean; private _isSubmitted: boolean; _renderer: TextInputRuntimeObjectRenderer; constructor( instanceContainer: gdjs.RuntimeInstanceContainer, objectData: TextInputObjectData ) { super(instanceContainer, objectData); this._string = objectData.content.initialValue; this._placeholder = objectData.content.placeholder; this._fontResourceName = objectData.content.fontResourceName; this._fontSize = objectData.content.fontSize || 20; this._inputType = parseInputType(objectData.content.inputType); this._textColor = gdjs.rgbOrHexToRGBColor(objectData.content.textColor); this._fillColor = gdjs.rgbOrHexToRGBColor(objectData.content.fillColor); this._fillOpacity = objectData.content.fillOpacity; this._borderColor = gdjs.rgbOrHexToRGBColor( objectData.content.borderColor ); this._borderOpacity = objectData.content.borderOpacity; this._borderWidth = objectData.content.borderWidth; this._disabled = objectData.content.disabled; this._readOnly = objectData.content.readOnly; this._textAlign = parseTextAlign(objectData.content.textAlign); //textAlign is defaulted to 'left' by the parser if undefined. this._maxLength = objectData.content.maxLength || 0; //maxlength and padding require a default value as they can be undefined in older projects. this._padding = objectData.content.padding || 0; this._isSubmitted = false; this._renderer = new gdjs.TextInputRuntimeObjectRenderer( this, instanceContainer ); // *ALWAYS* call `this.onCreated()` at the very end of your object constructor. this.onCreated(); } getRendererObject() { return null; } updateFromObjectData( oldObjectData: TextInputObjectData, newObjectData: TextInputObjectData ): boolean { if ( oldObjectData.content.initialValue !== newObjectData.content.initialValue
@@ -113,7 +130,10 @@ namespace gdjs { this._borderWidth = objectData.content.borderWidth; this._disabled = objectData.content.disabled; this._readOnly = objectData.content.readOnly; - + this._padding = objectData.content.padding || 0; + this._textAlign = objectData.content.textAlign || 'left';
Extensions/TextInput/textinputruntimeobject.ts
26
TypeScript
0.286
suggestion
36
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
getMaxLength(): integer { return this._maxLength; } setMaxLength(value: integer) { if (this._maxLength === value) return; this._maxLength = value; this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } setPadding(value: integer) { if (this._padding === value) return; this._padding = value; this._renderer.updatePadding(); } getTextAlign(): SupportedTextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const parsedTextAlign = parseTextAlign(newTextAlign); if (parsedTextAlign === this._textAlign) return; this._textAlign = parsedTextAlign; this._renderer.updateTextAlign(); } focus(): void { if (!this.isFocused()) { // If the input was not previously focused, reset input manager because there is // no reason to maintain its state. It avoids bugs where a key is pressed, the text // input is focused and then the input manager does not have access to the keyup event // and considers the key still pressed. this.getInstanceContainer() .getGame() .getInputManager() .clearAllPressedKeys(); } this._renderer.focus(); } } gdjs.registerObject( 'TextInput::TextInputObject', gdjs.TextInputRuntimeObject ); }
I think you should also prevent the function from setting negative values for the padding, there should be a minimum of 0
isReadOnly(): boolean { return this._readOnly; } isFocused(): boolean { return this._renderer.isFocused(); } isSubmitted(): boolean { return this._isSubmitted; } getMaxLength(): integer { return this._maxLength; } setMaxLength(value: integer) { if (this._maxLength === value) return; this._maxLength = value; this._renderer.updateMaxLength(); } getPadding(): integer { return this._padding; } setPadding(value: integer) { if (this._padding === value) return; if (value < 0) { this._padding = 0; return; } this._padding = value; this._renderer.updatePadding(); } getTextAlign(): SupportedTextAlign { return this._textAlign; } setTextAlign(newTextAlign: string) { const parsedTextAlign = parseTextAlign(newTextAlign); if (parsedTextAlign === this._textAlign) return; this._textAlign = parsedTextAlign; this._renderer.updateTextAlign(); } focus(): void { if (!this.isFocused()) { // If the input was not previously focused, reset input manager because there is // no reason to maintain its state. It avoids bugs where a key is pressed, the text
@@ -500,6 +535,40 @@ namespace gdjs { isFocused(): boolean { return this._renderer.isFocused(); } + isSubmitted(): boolean { + return this._isSubmitted; + } + + getMaxLength(): integer { + return this._maxLength; + } + setMaxLength(value: integer) { + if (this._maxLength === value) return; + + this._maxLength = value; + this._renderer.updateMaxLength(); + } + getPadding(): integer { + return this._padding; + } + setPadding(value: integer) { + if (this._padding === value) return;
Extensions/TextInput/textinputruntimeobject.ts
26
TypeScript
0.429
suggestion
121
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue((objectContent.maxLength || 0).toString()) .setType('number') .setLabel(_('Max length')) .setDescription( _( 'The maximum length of the input value. (this property will be ignored if the input type is a number' ) ) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255,
```suggestion 'The maximum length of the input value (this property will be ignored if the input type is a number).' ```
) .setType('number') .setLabel(_('Opacity')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('borderWidth') .setValue((objectContent.borderWidth || 0).toString()) .setType('number') .setLabel(_('Width')) .setGroup(_('Border appearance')); objectProperties .getOrCreate('padding') .setValue((objectContent.padding || 0).toString()) .setType('number') .setLabel(_('Padding')) .setGroup(_('Font')); objectProperties .getOrCreate('maxLength') .setValue((objectContent.maxLength || 0).toString()) .setType('number') .setLabel(_('Max length')) .setDescription( _( 'The maximum length of the input value (this property will be ignored if the input type is a number).' ) ) .setAdvanced(true); objectProperties .getOrCreate('textAlign') .setValue(objectContent.textAlign || 'left') .setType('choice') .addExtraInfo('left') .addExtraInfo('center') .addExtraInfo('right') .setLabel(_('Text alignment')) .setGroup(_('Font')); return objectProperties; }; textInputObject.content = { initialValue: '', placeholder: 'Touch to start typing', fontResourceName: '', fontSize: 20, inputType: 'text', textColor: '0;0;0', fillColor: '255;255;255', fillOpacity: 255,
@@ -200,6 +209,34 @@ module.exports = { .setLabel(_('Width')) .setGroup(_('Border appearance')); + objectProperties + .getOrCreate('padding') + .setValue((objectContent.padding || 0).toString()) + .setType('number') + .setLabel(_('Padding')) + .setGroup(_('Font')); + objectProperties + .getOrCreate('maxLength') + .setValue((objectContent.maxLength || 0).toString()) + .setType('number') + .setLabel(_('Max length')) + .setDescription( + _( + 'The maximum length of the input value. (this property will be ignored if the input type is a number'
Extensions/TextInput/JsExtension.js
26
JavaScript
0.857
suggestion
134
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
// Display after the object is positioned. this._form.style.display = 'initial'; } updateString() { if (!this._input) return; this._input.value = this._object.getString(); } updatePlaceholder() { if (!this._input) return; this._input.placeholder = this._object.getPlaceholder(); } updateFont() { if (!this._input) return; this._input.style.fontFamily = this._instanceContainer .getGame() .getFontManager() .getFontFamily(this._object.getFontResourceName()); } updateOpacity() { if (!this._form) return; this._form.style.opacity = '' + (this._object.getOpacity() / 255).toFixed(3); } updateInputType() { if (!this._input) return; const isTextArea = this._input instanceof HTMLTextAreaElement; const shouldBeTextArea = this._object.getInputType() === 'text area'; if (isTextArea !== shouldBeTextArea) { this._destroyElement(); this._createElement(); } const newType = userFriendlyToHtmlInputTypes[this._object.getInputType()] || 'text'; this._input.setAttribute('type', newType); } updateTextColor() { if (!this._input) return; this._input.style.color = formatRgbAndOpacityToCssRgba( this._object._getRawTextColor(), 255 ); }
```suggestion (this._object.getOpacity() / 255).toFixed(3); ``` toFixed returns as string already
// Display after the object is positioned. this._form.style.display = 'initial'; } updateString() { if (!this._input) return; this._input.value = this._object.getString(); } updatePlaceholder() { if (!this._input) return; this._input.placeholder = this._object.getPlaceholder(); } updateFont() { if (!this._input) return; this._input.style.fontFamily = this._instanceContainer .getGame() .getFontManager() .getFontFamily(this._object.getFontResourceName()); } updateOpacity() { if (!this._form) return; this._form.style.opacity = (this._object.getOpacity() / 255).toFixed(3); } updateInputType() { if (!this._input) return; const isTextArea = this._input instanceof HTMLTextAreaElement; const shouldBeTextArea = this._object.getInputType() === 'text area'; if (isTextArea !== shouldBeTextArea) { this._destroyElement(); this._createElement(); } const newType = userFriendlyToHtmlInputTypes[this._object.getInputType()] || 'text'; this._input.setAttribute('type', newType); } updateTextColor() { if (!this._input) return; this._input.style.color = formatRgbAndOpacityToCssRgba( this._object._getRawTextColor(), 255 ); }
@@ -246,8 +271,9 @@ namespace gdjs { } updateOpacity() { - if (!this._input) return; - this._input.style.opacity = '' + this._object.getOpacity() / 255; + if (!this._form) return; + this._form.style.opacity = + '' + (this._object.getOpacity() / 255).toFixed(3);
Extensions/TextInput/textinputruntimeobject-pixi-renderer.ts
26
TypeScript
0.714
suggestion
108
51
51
false
Improvement features for Input text box
7,308
4ian/GDevelop
10,154
JavaScript
AlexandreSi
NeylMahfouf2608
isOver, canDrop, }) => { setIsStayingOver(isOver, canDrop); let itemRow = ( <div className={classNames(classes.rowContentSide, { [classes.rowContentSideLeft]: !node.item.isRoot, [classes.rowContentExtraPadding]: !displayAsFolder, })} > {displayAsFolder ? ( <> <IconButton size="small" onClick={e => { e.stopPropagation(); onOpen(node); }} disabled={node.disableCollapse} > {node.collapsed ? ( <ChevronArrowRight/> ) : ( <ChevronArrowBottom/> )} </IconButton> {node.thumbnailSrc && node.thumbnailSrc !== 'FOLDER' ? ( <div className={classes.thumbnail}> <ListIcon iconSize={20} src={node.thumbnailSrc} /> </div> ) : ( !node.item.isRoot && ( <Folder className={classes.folderIcon} /> ) )} </> ) : node.thumbnailSrc ? ( <div className={classes.thumbnail}> <ListIcon iconSize={20} src={node.thumbnailSrc} /> </div> ) : null} {renamedItemId === node.id && typeof node.name === 'string' ? ( <SemiControlledRowInput initialValue={node.name} onEndRenaming={endRenaming} onBlur={onBlurField} /> ) : ( <span
Use SVG directly and remove use of Material UI (See comment at PR level)
isOver, canDrop, }) => { setIsStayingOver(isOver, canDrop); let itemRow = ( <div className={classNames(classes.rowContentSide, { [classes.rowContentSideLeft]: !node.item.isRoot, [classes.rowContentExtraPadding]: !displayAsFolder, })} > {displayAsFolder ? ( <> <IconButton size="small" onClick={e => { e.stopPropagation(); onOpen(node); }} disabled={node.disableCollapse} > {node.collapsed ? ( <ChevronArrowRight viewBox="2 2 12 12" fontSize="small" /> ) : ( <ChevronArrowBottom viewBox="2 2 12 12" fontSize="small" /> )} </IconButton> {node.thumbnailSrc && node.thumbnailSrc !== 'FOLDER' ? ( <div className={classes.thumbnail}> <ListIcon iconSize={20} src={node.thumbnailSrc} /> </div> ) : ( !node.item.isRoot && ( <Folder className={classes.folderIcon} /> ) )} </> ) : node.thumbnailSrc ? ( <div className={classes.thumbnail}> <ListIcon iconSize={20} src={node.thumbnailSrc} /> </div> ) : null} {renamedItemId === node.id && typeof node.name === 'string' ? ( <SemiControlledRowInput initialValue={node.name} onEndRenaming={endRenaming} onBlur={onBlurField}
@@ -358,9 +358,9 @@ const TreeViewRow = <Item: ItemBaseAttributes>(props: Props<Item>) => { disabled={node.disableCollapse} > {node.collapsed ? ( - <ArrowHeadRight fontSize="small" /> + <ChevronArrowRight/> ) : ( - <ArrowHeadBottom fontSize="small" />
newIDE/app/src/UI/TreeView/TreeViewRow.js
26
JavaScript
0.286
suggestion
72
51
51
false
Consistency on arrows
7,322
4ian/GDevelop
10,154
JavaScript
AlexandreSi
Bouh
title, isFolded, toggleFolded, renderContent, renderContentAsHiddenWhenFolded, noContentMargin, onOpenFullEditor, onAdd, }: {| title: React.Node, isFolded: boolean, toggleFolded: () => void, renderContent: () => React.Node, renderContentAsHiddenWhenFolded?: boolean, noContentMargin?: boolean, onOpenFullEditor: () => void, onAdd?: () => void, |}) => ( <> <Separator /> <Column noOverflowParent> <LineStackLayout alignItems="center" justifyContent="space-between"> <LineStackLayout noMargin alignItems="center"> <IconButton size="small" onClick={toggleFolded}> {isFolded ? ( <SquaredChevronArrowUp style={styles.icon} /> ) : ( <SquaredChevronArrowDown style={styles.icon} /> )} </IconButton> <Text size="sub-title" noMargin style={textEllipsisStyle}> {title} </Text> </LineStackLayout> <Line alignItems="center" noMargin> <IconButton size="small" onClick={onOpenFullEditor}> <ShareExternal style={styles.icon} /> </IconButton> {onAdd && ( <IconButton size="small" onClick={onAdd}> <Add style={styles.icon} /> </IconButton> )} </Line> </LineStackLayout> </Column> <Column noMargin={noContentMargin}> {isFolded ? ( renderContentAsHiddenWhenFolded ? ( <div style={styles.hiddenContent}>{renderContent()}</div> ) : null
Asked on the mock up on Figma: why is it not ...ArrowRight here?
title, isFolded, toggleFolded, renderContent, renderContentAsHiddenWhenFolded, noContentMargin, onOpenFullEditor, onAdd, }: {| title: React.Node, isFolded: boolean, toggleFolded: () => void, renderContent: () => React.Node, renderContentAsHiddenWhenFolded?: boolean, noContentMargin?: boolean, onOpenFullEditor: () => void, onAdd?: () => void, |}) => ( <> <Separator /> <Column noOverflowParent> <LineStackLayout alignItems="center" justifyContent="space-between"> <LineStackLayout noMargin alignItems="center"> s <IconButton size="small" onClick={toggleFolded}> {isFolded ? ( <ChevronArrowRightWithRoundedBorder style={styles.icon} /> ) : ( <ChevronArrowDownWithRoundedBorder style={styles.icon} /> )} </IconButton> <Text size="sub-title" noMargin style={textEllipsisStyle}> {title} </Text> </LineStackLayout> <Line alignItems="center" noMargin> <IconButton size="small" onClick={onOpenFullEditor}> <ShareExternal style={styles.icon} /> </IconButton> {onAdd && ( <IconButton size="small" onClick={onAdd}> <Add style={styles.icon} /> </IconButton> )} </Line> </LineStackLayout> </Column> <Column noMargin={noContentMargin}> {isFolded ? ( renderContentAsHiddenWhenFolded ? ( <div style={styles.hiddenContent}>{renderContent()}</div>
@@ -166,9 +166,9 @@ const TopLevelCollapsibleSection = ({ <LineStackLayout noMargin alignItems="center"> <IconButton size="small" onClick={toggleFolded}> {isFolded ? ( - <SquaredDoubleChevronArrowUp style={styles.icon} /> + <SquaredChevronArrowUp style={styles.icon} />
newIDE/app/src/ObjectEditor/CompactObjectPropertiesEditor/index.js
26
JavaScript
0.214
question
64
51
51
false
Consistency on arrows
7,322
4ian/GDevelop
10,154
JavaScript
AlexandreSi
Bouh