Compare commits

..

1 Commits

Author SHA1 Message Date
Florian Rival
cb2fad173c Lazily load subscription plans to reduce requests at startup 2025-06-03 13:57:32 +02:00
290 changed files with 5948 additions and 16935 deletions

View File

@@ -13,7 +13,6 @@ orbs:
aws-cli: circleci/aws-cli@2.0.6
macos: circleci/macos@2.5.1 # For Rosetta (see below)
node: circleci/node@5.2.0 # For a recent npm version (see below)
win: circleci/windows@5.1.0
jobs:
# Build the **entire** app for macOS (including the GDevelop.js library).
build-macos:
@@ -24,7 +23,7 @@ jobs:
- checkout
# Install Rosetta for AWS CLI and disable TSO to speed up S3 uploads (https://support.circleci.com/hc/en-us/articles/19334402064027-Troubleshooting-slow-uploads-to-S3-for-jobs-using-an-m1-macOS-resource-class)
- macos/install-rosetta
# - run: sudo sysctl net.inet.tcp.tso=0
- run: sudo sysctl net.inet.tcp.tso=0
# Install a recent version of npm to workaround a notarization issue because of a symlink made by npm: https://github.com/electron-userland/electron-builder/issues/7755
# Node.js v20.14.0 comes with npm v10.7.0.
@@ -47,9 +46,9 @@ jobs:
# GDevelop.js dependencies
- restore_cache:
keys:
- gd-macos-nodejs-dependencies-{{ checksum "newIDE/app/package.json" }}-{{ checksum "newIDE/electron-app/package.json" }}-{{ checksum "GDevelop.js/package.json" }}-{{ checksum "GDJS/package-lock.json" }}
- gd-macos-nodejs-dependencies-{{ checksum "newIDE/app/package.json" }}-{{ checksum "newIDE/electron-app/package.json" }}-{{ checksum "GDevelop.js/package.json" }}
# fallback to using the latest cache if no exact match is found
- gd-macos-nodejs-dependencies-
- gd-macos-nodejs-dependencies---
- run:
name: Install GDevelop.js dependencies
@@ -70,8 +69,7 @@ jobs:
- newIDE/electron-app/node_modules
- newIDE/app/node_modules
- GDevelop.js/node_modules
- GDJS/node_modules
key: gd-macos-nodejs-dependencies-{{ checksum "newIDE/app/package.json" }}-{{ checksum "newIDE/electron-app/package.json" }}-{{ checksum "GDevelop.js/package.json" }}-{{ checksum "GDJS/package-lock.json" }}
key: gd-macos-nodejs-dependencies-{{ checksum "newIDE/app/package.json" }}-{{ checksum "newIDE/electron-app/package.json" }}-{{ checksum "GDevelop.js/package.json" }}
# Build GDevelop IDE (seems like we need to allow Node.js to use more space than usual)
# Note: Code signing is done using CSC_LINK (see https://www.electron.build/code-signing).
@@ -88,35 +86,13 @@ jobs:
- store_artifacts:
path: newIDE/electron-app/dist
# Upload artifacts (AWS)
- run:
name: Deploy to S3 (specific commit)
command: |
export PATH=~/.local/bin:$PATH
for i in 1 2 3 4 5 6 7; do
aws s3 sync newIDE/electron-app/dist s3://gdevelop-releases/$(git rev-parse --abbrev-ref HEAD)/commit/$(git rev-parse HEAD)/ && break
echo "Retry $i failed... retrying in 10 seconds"
sleep 10
done
if [ $i -eq 7 ]; then
echo "All retries for deployment failed!" >&2
exit 1
fi
command: export PATH=~/.local/bin:$PATH && aws s3 sync newIDE/electron-app/dist s3://gdevelop-releases/$(git rev-parse --abbrev-ref HEAD)/commit/$(git rev-parse HEAD)/
- run:
name: Deploy to S3 (latest)
command: |
export PATH=~/.local/bin:$PATH
for i in 1 2 3 4 5 6 7; do
aws s3 sync newIDE/electron-app/dist s3://gdevelop-releases/$(git rev-parse --abbrev-ref HEAD)/latest/ && break
echo "Retry $i failed... retrying in 10 seconds"
sleep 10
done
if [ $i -eq 7 ]; then
echo "All retries for deployment failed!" >&2
exit 1
fi
command: export PATH=~/.local/bin:$PATH && aws s3 sync newIDE/electron-app/dist s3://gdevelop-releases/$(git rev-parse --abbrev-ref HEAD)/latest/
# Build the app for Linux (using a pre-built GDevelop.js library).
build-linux:
@@ -142,9 +118,9 @@ jobs:
- restore_cache:
keys:
- gd-linux-nodejs-dependencies-{{ checksum "newIDE/app/package.json" }}-{{ checksum "newIDE/electron-app/package.json" }}-{{ checksum "GDevelop.js/package.json" }}-{{ checksum "GDJS/package-lock.json" }}
- gd-linux-nodejs-dependencies-{{ checksum "newIDE/app/package.json" }}-{{ checksum "newIDE/electron-app/package.json" }}-{{ checksum "GDevelop.js/package.json" }}
# fallback to using the latest cache if no exact match is found
- gd-linux-nodejs-dependencies-
- gd-linux-nodejs-dependencies---
# GDevelop IDE dependencies (using an exact version of GDevelop.js, built previously)
- run:
@@ -156,8 +132,7 @@ jobs:
- newIDE/electron-app/node_modules
- newIDE/app/node_modules
- GDevelop.js/node_modules
- GDJS/node_modules
key: gd-linux-nodejs-dependencies-{{ checksum "newIDE/app/package.json" }}-{{ checksum "newIDE/electron-app/package.json" }}-{{ checksum "GDevelop.js/package.json" }}-{{ checksum "GDJS/package-lock.json" }}
key: gd-linux-nodejs-dependencies-{{ checksum "newIDE/app/package.json" }}-{{ checksum "newIDE/electron-app/package.json" }}-{{ checksum "GDevelop.js/package.json" }}
# Build GDevelop IDE (seems like we need to allow Node.js to use more space than usual)
- run:
@@ -301,7 +276,8 @@ jobs:
name: Deploy to S3 (specific commit)
command: aws s3 sync Binaries/embuild/GDevelop.js s3://gdevelop-gdevelop.js/$(git rev-parse --abbrev-ref HEAD)/variant/debug-sanitizers/commit/$(git rev-parse HEAD)/
# Trigger AppVeyor build, which also does a Windows build (keep it for redundancy).
# Trigger AppVeyor build, which finishes building the Windows app
# (using GDevelop.js built in a previous step).
trigger-appveyor-windows-build:
docker:
- image: cimg/node:16.13
@@ -318,186 +294,12 @@ jobs:
}" \
-X POST https://ci.appveyor.com/api/builds
build-windows:
executor:
name: win/default
size: medium
working_directory: /home/circleci/project
steps:
- checkout
- run:
# See https://www.ssl.com/how-to/how-to-integrate-esigner-cka-with-ci-cd-tools-for-automated-code-signing/
#
# This is necessary because of "signing to be FIPS-140 compliant". See
# https://github.com/electron-userland/electron-builder/issues/6158
#
# Make sure to DISABLE "malware blocker" in SSL.com to avoid errors like:
# Error information: "Error: SignerSign() failed." (-2146893821/0x80090003)
name: Download and Unzip eSignerCKA Setup
command: |
Invoke-WebRequest -OutFile eSigner_CKA_1.0.3.zip "https://www.ssl.com/download/ssl-com-esigner-cka-1-0-3"
Expand-Archive -Force eSigner_CKA_1.0.3.zip
Remove-Item eSigner_CKA_1.0.3.zip
Move-Item -Destination "eSigner_CKA_1.0.3.exe" -Path "eSigner_CKA_*\*.exe"
- run:
name: Setup eSignerCKA in Silent Mode
command: |
mkdir -p "/home/circleci/project/eSignerCKA"
./eSigner_CKA_1.0.3.exe /CURRENTUSER /VERYSILENT /SUPPRESSMSGBOXES /DIR="/home/circleci/project/eSignerCKA" | Out-Null
- run:
name: Config Account Information on eSignerCKA
command: |
/home/circleci/project/eSignerCKA/eSignerCKATool.exe config -mode product -user "$env:ESIGNER_USER_NAME" -pass "$env:ESIGNER_USER_PASSWORD" -totp "$env:ESIGNER_USER_TOTP" -key "/home/circleci/project/eSignerCKA/master.key" -r
- run:
name: Load Certificate into Windows Store
command: |
/home/circleci/project/eSignerCKA/eSignerCKATool.exe unload
/home/circleci/project/eSignerCKA/eSignerCKATool.exe load
- run:
name: Select Certificate From Windows Store and Sign Sample File with SignTool
command: |
$CodeSigningCert = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert | Select-Object -First 1
echo Certificate: $CodeSigningCert
- restore_cache:
name: Restore node_modules cache
keys:
- v1-win-node-{{ checksum "newIDE/app/package-lock.json" }}-{{ checksum "newIDE/electron-app/package-lock.json" }}-{{ checksum "GDJS/package-lock.json" }}
- v1-win-node-
- run:
name: Install dependencies
no_output_timeout: 25m
# Remove package-lock.json because they seems to cause the npm install to be stuck. We should try again after re-generating them.
# Also install setuptools as something requires distutils in electron-app, and it was removed in Python 3.12.
# setuptools will make distutils available again (but we should migrate our packages probably).
command: |
pip install setuptools
cd newIDE\app
npm -v
Remove-Item package-lock.json
$Env:REQUIRES_EXACT_LIBGD_JS_VERSION = "true"
npm install
cd ..\electron-app
Remove-Item package-lock.json
npm install
cd ..\..
- save_cache:
name: Save node_modules cache
key: v1-win-node-{{ checksum "newIDE/app/package-lock.json" }}-{{ checksum "newIDE/electron-app/package-lock.json" }}-{{ checksum "GDJS/package-lock.json" }}
paths:
- newIDE/app/node_modules
- newIDE/electron-app/node_modules
- GDJS/node_modules
- run:
name: Build NSIS executable (with code signing)
command: |
cd newIDE\electron-app
$CodeSigningCert = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert | Select-Object -First 1
echo Certificate: $CodeSigningCert
# Use a custom signtool path because of the signtool.exe bundled withy electron-builder not working for some reason.
# Can also be found in versioned folders like "C:/Program Files (x86)/Windows Kits/10/bin/10.0.22000.0/x86/signtool.exe".
# or "C:\Program Files (x86)\Windows Kits\10\bin\10.0.22621.0\x86\signtool.exe".
$Env:SIGNTOOL_PATH = "C:\Program Files (x86)\Windows Kits\10\App Certification Kit\signtool.exe"
# Extract thumbprint and subject name of the certificate (will be passed to electron-builder).
$Env:GD_SIGNTOOL_THUMBPRINT = $CodeSigningCert.Thumbprint
$Env:GD_SIGNTOOL_SUBJECT_NAME = ($CodeSigningCert.Subject -replace ", ?", "`n" | ConvertFrom-StringData).CN
# Build the nsis installer (signed: electron-builder will use SignTool.exe with the certificate)
node scripts/build.js --win nsis --publish=never
cd ..\..
- run:
name: Build AppX (without code signing)
# Don't sign the appx (it will be signed by the Microsoft Store).
command: |
cd newIDE\electron-app
# Build the appx (not signed). Ensure all variables used for code signing are empty.
$Env:GD_SIGNTOOL_THUMBPRINT = ''
$Env:GD_SIGNTOOL_SUBJECT_NAME = ''
$Env:CSC_LINK = ''
$Env:CSC_KEY_PASSWORD = ''
node scripts/build.js --skip-app-build --win appx --publish=never
cd ..\..
- run:
name: Clean binaries
shell: cmd.exe
command: |
rmdir /s /q newIDE\electron-app\dist\win-unpacked
- run:
name: Install AWS CLI
command: |
# Install the CLI for the current user
pip install --quiet --upgrade --user awscli
# Add the user-Scripts dir to PATH for this step and the next.
$binDir = (python -m site --user-base) + "\Scripts"
$Env:Path += ";$binDir"
# Sanity check:
aws --version
# Upload artifacts (S3)
- run:
name: Deploy to S3 (specific commit)
command: |
aws s3 sync newIDE\electron-app\dist "s3://gdevelop-releases/$Env:CIRCLE_BRANCH/commit/$Env:CIRCLE_SHA1/"
- run:
name: Deploy to S3 (latest)
command: |
aws s3 sync newIDE\electron-app\dist "s3://gdevelop-releases/$Env:CIRCLE_BRANCH/latest/"
# Upload artifacts (CircleCI)
- store_artifacts:
path: newIDE/electron-app/dist
workflows:
gdevelop_js-wasm-extra-checks:
jobs:
- build-gdevelop_js-debug-sanitizers-and-extra-checks:
# Extra checks are resource intensive so don't always run them.
# Extra checks are resource intensive so don't all run them.
filters:
branches:
only:
@@ -524,14 +326,6 @@ workflows:
only:
- master
- /experimental-build.*/
- build-windows:
requires:
- build-gdevelop_js-wasm-only
filters:
branches:
only:
- master
- /experimental-build.*/
- trigger-appveyor-windows-build:
requires:
- build-gdevelop_js-wasm-only

View File

@@ -61,12 +61,10 @@ void GroupEvent::UnserializeFrom(gd::Project& project,
project, events, element.GetChild("events"));
parameters.clear();
if (element.HasChild("parameters")) {
gd::SerializerElement& parametersElement = element.GetChild("parameters");
parametersElement.ConsiderAsArrayOf("parameters");
for (std::size_t i = 0; i < parametersElement.GetChildrenCount(); ++i)
parameters.push_back(parametersElement.GetChild(i).GetValue().GetString());
}
gd::SerializerElement& parametersElement = element.GetChild("parameters");
parametersElement.ConsiderAsArrayOf("parameters");
for (std::size_t i = 0; i < parametersElement.GetChildrenCount(); ++i)
parameters.push_back(parametersElement.GetChild(i).GetValue().GetString());
}
void GroupEvent::SetBackgroundColor(unsigned int colorR_,

View File

@@ -163,21 +163,6 @@ void LinkEvent::UnserializeFrom(gd::Project& project,
// end of compatibility code
}
vector<gd::String> LinkEvent::GetAllSearchableStrings() const {
vector<gd::String> allSearchableStrings;
allSearchableStrings.push_back(target);
return allSearchableStrings;
}
bool LinkEvent::ReplaceAllSearchableStrings(
std::vector<gd::String> newSearchableString) {
if (newSearchableString[0] == target) return false;
SetTarget(newSearchableString[0]);
return true;
}
bool LinkEvent::AcceptVisitor(gd::EventVisitor &eventVisitor) {
return BaseEvent::AcceptVisitor(eventVisitor) ||
eventVisitor.VisitLinkEvent(*this);

View File

@@ -109,10 +109,6 @@ class GD_CORE_API LinkEvent : public gd::BaseEvent {
virtual bool IsExecutable() const override { return true; };
virtual std::vector<gd::String> GetAllSearchableStrings() const override;
virtual bool ReplaceAllSearchableStrings(
std::vector<gd::String> newSearchableString) override;
virtual void SerializeTo(SerializerElement& element) const override;
virtual void UnserializeFrom(gd::Project& project,
const SerializerElement& element) override;

View File

@@ -286,20 +286,6 @@ class GD_CORE_API BaseEvent {
* \brief True if the event should be folded in the events editor.
*/
bool IsFolded() const { return folded; }
/**
* \brief Set the AI generated event ID.
*/
void SetAiGeneratedEventId(const gd::String& aiGeneratedEventId_) {
aiGeneratedEventId = aiGeneratedEventId_;
}
/**
* \brief Get the AI generated event ID.
*/
const gd::String& GetAiGeneratedEventId() const {
return aiGeneratedEventId;
}
///@}
std::weak_ptr<gd::BaseEvent>
@@ -318,7 +304,6 @@ class GD_CORE_API BaseEvent {
bool disabled; ///< True if the event is disabled and must not be executed
gd::String type; ///< Type of the event. Must be assigned at the creation.
///< Used for saving the event for instance.
gd::String aiGeneratedEventId; ///< When generated by an AI/external tool.
static gd::EventsList badSubEvents;
static gd::VariablesContainer badLocalVariables;

View File

@@ -221,8 +221,6 @@ void EventsListSerialization::UnserializeEventsFrom(
event->SetDisabled(eventElem.GetBoolAttribute("disabled", false));
event->SetFolded(eventElem.GetBoolAttribute("folded", false));
event->SetAiGeneratedEventId(
eventElem.GetStringAttribute("aiGeneratedEventId", ""));
list.InsertEvent(event, list.GetEventsCount());
}
@@ -238,8 +236,6 @@ void EventsListSerialization::SerializeEventsTo(const EventsList& list,
if (event.IsDisabled())
eventElem.SetAttribute("disabled", event.IsDisabled());
if (event.IsFolded()) eventElem.SetAttribute("folded", event.IsFolded());
if (!event.GetAiGeneratedEventId().empty())
eventElem.SetAttribute("aiGeneratedEventId", event.GetAiGeneratedEventId());
eventElem.AddChild("type").SetValue(event.GetType());
event.SerializeTo(eventElem);

View File

@@ -235,8 +235,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
obj.AddAction("SetAngle",
_("Angle"),
_("Change the angle of rotation of an object (in degrees). For "
"3D objects, this is the rotation around the Z axis."),
_("Change the angle of rotation of an object (in degrees)."),
_("the angle"),
_("Angle"),
"res/actions/direction24_black.png",
@@ -251,8 +250,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
obj.AddAction("Rotate",
_("Rotate"),
_("Rotate an object, clockwise if the speed is positive, "
"counterclockwise otherwise. For 3D objects, this is the "
"rotation around the Z axis."),
"counterclockwise otherwise."),
_("Rotate _PARAM0_ at speed _PARAM1_ deg/second"),
_("Angle"),
"res/actions/rotate24_black.png",
@@ -636,8 +634,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
obj.AddCondition("Angle",
_("Angle"),
_("Compare the angle, in degrees, of the specified object. "
"For 3D objects, this is the angle around the Z axis."),
_("Compare the angle of the specified object."),
_("the angle (in degrees)"),
_("Angle"),
"res/conditions/direction24_black.png",
@@ -1271,8 +1268,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
obj.AddExpression("Angle",
_("Angle"),
_("Current angle, in degrees, of the object. For 3D "
"objects, this is the angle around the Z axis."),
_("Current angle, in degrees, of the object"),
_("Angle"),
"res/actions/direction_black.png")
.AddParameter("object", _("Object"));

View File

@@ -779,26 +779,6 @@ gd::String PlatformExtension::GetBehaviorFullType(
return extensionName + separator + behaviorName;
}
gd::String PlatformExtension::GetExtensionFromFullBehaviorType(
const gd::String& type) {
const auto separatorIndex =
type.find(PlatformExtension::GetNamespaceSeparator());
if (separatorIndex == std::string::npos) {
return "";
}
return type.substr(0, separatorIndex);
}
gd::String PlatformExtension::GetBehaviorNameFromFullBehaviorType(
const gd::String& type) {
const auto separatorIndex =
type.find(PlatformExtension::GetNamespaceSeparator());
if (separatorIndex == std::string::npos) {
return "";
}
return type.substr(separatorIndex + 2);
}
gd::String PlatformExtension::GetObjectEventsFunctionFullType(
const gd::String& extensionName,
const gd::String& objectName,

View File

@@ -651,10 +651,6 @@ class GD_CORE_API PlatformExtension {
static gd::String GetBehaviorFullType(const gd::String& extensionName,
const gd::String& behaviorName);
static gd::String GetExtensionFromFullBehaviorType(const gd::String& type);
static gd::String GetBehaviorNameFromFullBehaviorType(const gd::String& type);
static gd::String GetObjectEventsFunctionFullType(
const gd::String& extensionName,
const gd::String& objectName,

View File

@@ -1781,14 +1781,6 @@ void WholeProjectRefactorer::DoRenameBehavior(
projectBrowser.ExposeFunctions(project, behaviorParameterRenamer);
}
void WholeProjectRefactorer::UpdateBehaviorsSharedData(gd::Project &project) {
for (std::size_t i = 0; i < project.GetLayoutsCount(); ++i) {
gd::Layout &layout = project.GetLayout(i);
layout.UpdateBehaviorsSharedData(project);
}
}
void WholeProjectRefactorer::DoRenameObject(
gd::Project &project, const gd::String &oldObjectType,
const gd::String &newObjectType, const gd::ProjectBrowser &projectBrowser) {

View File

@@ -704,16 +704,6 @@ class GD_CORE_API WholeProjectRefactorer {
static size_t GetLayoutAndExternalLayoutLayerInstancesCount(
gd::Project &project, gd::Layout &layout, const gd::String &layerName);
/**
* This ensures that the scenes had an instance of shared data for
* every behavior of every object that can be used on the scene
* (i.e. the objects of the scene and the global objects)
*
* Must be called when a behavior have been added/deleted
* from a global object or an object has been made global.
*/
static void UpdateBehaviorsSharedData(gd::Project &project);
virtual ~WholeProjectRefactorer(){};
private:

View File

@@ -83,9 +83,6 @@ void EventsFunctionsExtension::SerializeTo(SerializerElement& element, bool isEx
element.SetAttribute("iconUrl", iconUrl);
element.SetAttribute("helpPath", helpPath);
element.SetAttribute("gdevelopVersion", gdevelopVersion);
if (changelog.GetChangesCount() > 0) {
changelog.SerializeTo(element.AddChild("changelog"));
}
auto& dependenciesElement = element.AddChild("dependencies");
dependenciesElement.ConsiderAsArray();
for (auto& dependency : dependencies)
@@ -142,9 +139,6 @@ void EventsFunctionsExtension::UnserializeExtensionDeclarationFrom(
iconUrl = element.GetStringAttribute("iconUrl");
helpPath = element.GetStringAttribute("helpPath");
gdevelopVersion = element.GetStringAttribute("gdevelopVersion");
if (element.HasChild("changelog")) {
changelog.UnserializeFrom(element.GetChild("changelog"));
}
if (element.HasChild("origin")) {
gd::String originName =

View File

@@ -12,11 +12,9 @@
#include "GDCore/Project/EventsBasedBehavior.h"
#include "GDCore/Project/EventsBasedObject.h"
#include "GDCore/Project/EventsFunctionsContainer.h"
#include "GDCore/Project/EventsFunctionsExtensionChangelog.h"
#include "GDCore/Project/VariablesContainer.h"
#include "GDCore/String.h"
#include "GDCore/Tools/SerializableWithNameList.h"
namespace gd {
class SerializerElement;
class Project;
@@ -408,7 +406,6 @@ class GD_CORE_API EventsFunctionsExtension {
gd::String helpPath; ///< The relative path to the help for this extension in
///< the documentation (or an absolute URL).
gd::String gdevelopVersion;
gd::EventsFunctionsExtensionChangelog changelog;
gd::SerializableWithNameList<EventsBasedBehavior> eventsBasedBehaviors;
gd::SerializableWithNameList<EventsBasedObject> eventsBasedObjects;
std::vector<gd::DependencyMetadata> dependencies;

View File

@@ -1,105 +0,0 @@
/*
* GDevelop Core
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
* reserved. This project is released under the MIT License.
*/
#pragma once
#include <vector>
#include "GDCore/Serialization/SerializerElement.h"
#include "GDCore/String.h"
namespace gd {
/**
* @brief The change of a specific extension version (only the breaking
* changes).
*/
class GD_CORE_API EventsFunctionsExtensionVersionChange {
public:
EventsFunctionsExtensionVersionChange(){};
virtual ~EventsFunctionsExtensionVersionChange(){};
const gd::String &GetVersion() const { return version; };
gd::EventsFunctionsExtensionVersionChange &
SetVersion(const gd::String &version_) {
version = version_;
return *this;
}
const gd::String &GetBreakingChangesDescription() const { return version; };
gd::EventsFunctionsExtensionVersionChange &
GetBreakingChangesDescription(const gd::String &breakingChangesDescription_) {
breakingChangesDescription = breakingChangesDescription_;
return *this;
}
/**
* \brief Serialize the EventsFunctionsExtensionVersionChange to the specified
* element
*/
void SerializeTo(gd::SerializerElement &element) const {
element.SetAttribute("version", version);
element.AddChild("breaking")
.SetMultilineStringValue(breakingChangesDescription);
}
/**
* \brief Load the EventsFunctionsExtensionVersionChange from the specified
* element.
*/
void UnserializeFrom(const gd::SerializerElement &element) {
version = element.GetStringAttribute("version");
breakingChangesDescription =
element.GetChild("breaking").GetMultilineStringValue();
}
private:
gd::String version;
gd::String breakingChangesDescription;
};
/**
* @brief The changelog of an extension (only the breaking changes).
*/
class GD_CORE_API EventsFunctionsExtensionChangelog {
public:
EventsFunctionsExtensionChangelog(){};
virtual ~EventsFunctionsExtensionChangelog(){};
/**
* \brief Return the number of variants.
*/
std::size_t GetChangesCount() const { return versionChanges.size(); }
/**
* \brief Serialize the EventsFunctionsExtensionChangelog to the specified
* element
*/
void SerializeTo(gd::SerializerElement &element) const {
element.ConsiderAsArray();
for (const auto &versionChange : versionChanges) {
versionChange.SerializeTo(element.AddChild(""));
}
}
/**
* \brief Load the EventsFunctionsExtensionChangelog from the specified
* element.
*/
void UnserializeFrom(const gd::SerializerElement &element) {
versionChanges.clear();
element.ConsiderAsArray();
for (std::size_t i = 0; i < element.GetChildrenCount(); ++i) {
gd::EventsFunctionsExtensionVersionChange versionChange;
versionChange.UnserializeFrom(element.GetChild(i));
versionChanges.push_back(versionChange);
}
}
private:
std::vector<gd::EventsFunctionsExtensionVersionChange> versionChanges;
};
} // namespace gd

View File

@@ -365,8 +365,6 @@ class GD_CORE_API InitialInstance {
* the same initial instance between serialization.
*/
InitialInstance& ResetPersistentUuid();
const gd::String& GetPersistentUuid() const { return persistentUuid; }
///@}
private:

View File

@@ -81,11 +81,6 @@ class GD_CORE_API ObjectsContainersList {
/**
* \brief Return the container of the variables for the specified object or
* group of objects.
*
* \warning In most cases, prefer to use other methods to access variables or use
* ObjectVariableHelper::MergeVariableContainers if you know you're dealing with a group.
* This is because the variables container of an object group does not exist and the one from
* first object of the group will be returned.
*/
const gd::VariablesContainer* GetObjectOrGroupVariablesContainer(
const gd::String& objectOrGroupName) const;

View File

@@ -21,19 +21,14 @@ void PropertyDescriptor::SerializeTo(SerializerElement& element) const {
element.AddChild("unit").SetStringValue(measurementUnit.GetName());
}
element.AddChild("label").SetStringValue(label);
if (!description.empty())
element.AddChild("description").SetStringValue(description);
if (!group.empty()) element.AddChild("group").SetStringValue(group);
if (!extraInformation.empty()) {
SerializerElement& extraInformationElement =
element.AddChild("extraInformation");
extraInformationElement.ConsiderAsArray();
for (const gd::String& information : extraInformation) {
extraInformationElement.AddChild("").SetStringValue(information);
}
element.AddChild("description").SetStringValue(description);
element.AddChild("group").SetStringValue(group);
SerializerElement& extraInformationElement =
element.AddChild("extraInformation");
extraInformationElement.ConsiderAsArray();
for (const gd::String& information : extraInformation) {
extraInformationElement.AddChild("").SetStringValue(information);
}
if (hidden) {
element.AddChild("hidden").SetBoolValue(hidden);
}
@@ -64,21 +59,16 @@ void PropertyDescriptor::UnserializeFrom(const SerializerElement& element) {
: gd::MeasurementUnit::GetUndefined();
}
label = element.GetChild("label").GetStringValue();
description = element.HasChild("description")
? element.GetChild("description").GetStringValue()
: "";
group = element.HasChild("group") ? element.GetChild("group").GetStringValue()
: "";
description = element.GetChild("description").GetStringValue();
group = element.GetChild("group").GetStringValue();
extraInformation.clear();
if (element.HasChild("extraInformation")) {
const SerializerElement& extraInformationElement =
element.GetChild("extraInformation");
extraInformationElement.ConsiderAsArray();
for (std::size_t i = 0; i < extraInformationElement.GetChildrenCount(); ++i)
extraInformation.push_back(
extraInformationElement.GetChild(i).GetStringValue());
}
const SerializerElement& extraInformationElement =
element.GetChild("extraInformation");
extraInformationElement.ConsiderAsArray();
for (std::size_t i = 0; i < extraInformationElement.GetChildrenCount(); ++i)
extraInformation.push_back(
extraInformationElement.GetChild(i).GetStringValue());
hidden = element.HasChild("hidden")
? element.GetChild("hidden").GetBoolValue()

View File

@@ -12,7 +12,7 @@ This project is released under the MIT License.
#include "GDCore/Tools/Localization.h"
void DestroyOutsideBehavior::InitializeContent(gd::SerializerElement& content) {
content.SetAttribute("extraBorder", 300);
content.SetAttribute("extraBorder", 0);
}
#if defined(GD_IDE_ONLY)

View File

@@ -35,32 +35,25 @@ void DeclareDraggableBehaviorExtension(gd::PlatformExtension& extension) {
std::make_shared<DraggableBehavior>(),
std::shared_ptr<gd::BehaviorsSharedData>());
aut.AddCondition(
"Dragged",
_("Being dragged"),
_("Check if the object is being dragged. This means the mouse button "
"or touch is pressed on it. When the mouse button or touch is "
"released, the object is no longer being considered dragged (use "
"the condition \"Was just dropped\" to check when the dragging is "
"ending)."),
_("_PARAM0_ is being dragged"),
_("Draggable"),
"CppPlatform/Extensions/draggableicon24.png",
"CppPlatform/Extensions/draggableicon16.png")
aut.AddCondition("Dragged",
_("Being dragged"),
_("Check if the object is being dragged."),
_("_PARAM0_ is being dragged"),
_("Draggable"),
"CppPlatform/Extensions/draggableicon24.png",
"CppPlatform/Extensions/draggableicon16.png")
.AddParameter("object", _("Object"))
.AddParameter("behavior", _("Behavior"), "Draggable")
.SetFunctionName("IsDragged");
aut.AddCondition(
"Dropped",
_("Was just dropped"),
_("Check if the object was just dropped after being dragged (the "
"mouse button or touch was just released this frame)."),
_("_PARAM0_ was just dropped"),
_("Draggable"),
"CppPlatform/Extensions/draggableicon24.png",
"CppPlatform/Extensions/draggableicon16.png")
aut.AddCondition("Dropped",
_("Was just dropped"),
_("Check if the object was just dropped after being dragged."),
_("_PARAM0_ was just dropped"),
_("Draggable"),
"CppPlatform/Extensions/draggableicon24.png",
"CppPlatform/Extensions/draggableicon16.png")
.AddParameter("object", _("Object"))
.AddParameter("behavior", _("Behavior"), "Draggable")

View File

@@ -116,7 +116,48 @@ namespace gdjs {
_updateLocalPositions() {
const obj = this._object;
this._centerSprite.position.x = obj._lBorder;
this._centerSprite.position.y = obj._tBorder;
//Right
this._borderSprites[0].position.x = obj._width - obj._rBorder;
this._borderSprites[0].position.y = obj._tBorder;
//Top-right
this._borderSprites[1].position.x =
obj._width - this._borderSprites[1].width;
this._borderSprites[1].position.y = 0;
//Top
this._borderSprites[2].position.x = obj._lBorder;
this._borderSprites[2].position.y = 0;
//Top-Left
this._borderSprites[3].position.x = 0;
this._borderSprites[3].position.y = 0;
//Left
this._borderSprites[4].position.x = 0;
this._borderSprites[4].position.y = obj._tBorder;
//Bottom-Left
this._borderSprites[5].position.x = 0;
this._borderSprites[5].position.y =
obj._height - this._borderSprites[5].height;
//Bottom
this._borderSprites[6].position.x = obj._lBorder;
this._borderSprites[6].position.y = obj._height - obj._bBorder;
//Bottom-Right
this._borderSprites[7].position.x =
obj._width - this._borderSprites[7].width;
this._borderSprites[7].position.y =
obj._height - this._borderSprites[7].height;
}
_updateSpritesAndTexturesSize() {
const obj = this._object;
this._centerSprite.width = Math.max(
obj._width - obj._rBorder - obj._lBorder,
0
@@ -126,107 +167,35 @@ namespace gdjs {
0
);
let leftMargin = obj._lBorder;
let rightMargin = obj._rBorder;
if (this._centerSprite.width === 0 && obj._lBorder + obj._rBorder > 0) {
leftMargin =
(obj._width * obj._lBorder) / (obj._lBorder + obj._rBorder);
rightMargin = obj._width - leftMargin;
}
let topMargin = obj._tBorder;
let bottomMargin = obj._bBorder;
if (this._centerSprite.height === 0 && obj._tBorder + obj._bBorder > 0) {
topMargin =
(obj._height * obj._tBorder) / (obj._tBorder + obj._bBorder);
bottomMargin = obj._height - topMargin;
}
//Right
this._borderSprites[0].width = rightMargin;
this._borderSprites[0].width = obj._rBorder;
this._borderSprites[0].height = Math.max(
obj._height - topMargin - bottomMargin,
obj._height - obj._tBorder - obj._bBorder,
0
);
//Top
this._borderSprites[2].height = topMargin;
this._borderSprites[2].height = obj._tBorder;
this._borderSprites[2].width = Math.max(
obj._width - rightMargin - leftMargin,
obj._width - obj._rBorder - obj._lBorder,
0
);
//Left
this._borderSprites[4].width = leftMargin;
this._borderSprites[4].width = obj._lBorder;
this._borderSprites[4].height = Math.max(
obj._height - topMargin - bottomMargin,
obj._height - obj._tBorder - obj._bBorder,
0
);
//Bottom
this._borderSprites[6].height = bottomMargin;
this._borderSprites[6].height = obj._bBorder;
this._borderSprites[6].width = Math.max(
obj._width - rightMargin - leftMargin,
obj._width - obj._rBorder - obj._lBorder,
0
);
//Top-right
this._borderSprites[1].width = rightMargin;
this._borderSprites[1].height = topMargin;
//Top-Left
this._borderSprites[3].width = leftMargin;
this._borderSprites[3].height = topMargin;
//Bottom-Left
this._borderSprites[5].width = leftMargin;
this._borderSprites[5].height = bottomMargin;
//Bottom-Right
this._borderSprites[7].width = rightMargin;
this._borderSprites[7].height = bottomMargin;
this._wasRendered = true;
this._spritesContainer.cacheAsBitmap = false;
const leftBorder = leftMargin;
const topBorder = topMargin;
const rightBorder = obj._width - rightMargin;
const bottomBorder = obj._height - bottomMargin;
this._centerSprite.position.x = leftBorder;
this._centerSprite.position.y = topBorder;
//Right
this._borderSprites[0].position.x = rightBorder;
this._borderSprites[0].position.y = topBorder;
//Top-right
this._borderSprites[1].position.x = rightBorder;
this._borderSprites[1].position.y = 0;
//Top
this._borderSprites[2].position.x = leftBorder;
this._borderSprites[2].position.y = 0;
//Top-Left
this._borderSprites[3].position.x = 0;
this._borderSprites[3].position.y = 0;
//Left
this._borderSprites[4].position.x = 0;
this._borderSprites[4].position.y = topBorder;
//Bottom-Left
this._borderSprites[5].position.x = 0;
this._borderSprites[5].position.y = bottomBorder;
//Bottom
this._borderSprites[6].position.x = leftBorder;
this._borderSprites[6].position.y = bottomBorder;
//Bottom-Right
this._borderSprites[7].position.x = rightBorder;
this._borderSprites[7].position.y = bottomBorder;
}
setTexture(
@@ -371,6 +340,7 @@ namespace gdjs {
)
)
);
this._updateSpritesAndTexturesSize();
this._updateLocalPositions();
this.updatePosition();
this._wrapperContainer.pivot.x = this._object._width / 2;
@@ -379,12 +349,14 @@ namespace gdjs {
updateWidth(): void {
this._wrapperContainer.pivot.x = this._object._width / 2;
this._updateSpritesAndTexturesSize();
this._updateLocalPositions();
this.updatePosition();
}
updateHeight(): void {
this._wrapperContainer.pivot.y = this._object._height / 2;
this._updateSpritesAndTexturesSize();
this._updateLocalPositions();
this.updatePosition();
}

View File

@@ -36,7 +36,6 @@ void PlatformerObjectBehavior::InitializeContent(
behaviorContent.SetAttribute("yGrabOffset", 0);
behaviorContent.SetAttribute("xGrabTolerance", 10);
behaviorContent.SetAttribute("useLegacyTrajectory", false);
behaviorContent.SetAttribute("useRepeatedJump", false);
behaviorContent.SetAttribute("canGoDownFromJumpthru", true);
}
@@ -109,11 +108,11 @@ PlatformerObjectBehavior::GetProperties(
.SetValue(
gd::String::From(behaviorContent.GetDoubleAttribute("maxSpeed")));
properties["IgnoreDefaultControls"]
.SetLabel(_("Disable default keyboard controls"))
.SetLabel(_("Default controls"))
.SetQuickCustomizationVisibility(gd::QuickCustomization::Hidden)
.SetValue(behaviorContent.GetBoolAttribute("ignoreDefaultControls")
? "true"
: "false")
? "false"
: "true")
.SetType("Boolean");
properties["SlopeMaxAngle"]
.SetLabel(_("Slope max. angle"))
@@ -157,23 +156,14 @@ PlatformerObjectBehavior::GetProperties(
.SetValue(gd::String::From(
behaviorContent.GetDoubleAttribute("xGrabTolerance", 10)));
properties["UseLegacyTrajectory"]
.SetLabel(_("Use frame rate dependent trajectories "
"(deprecated — best left unchecked)"))
.SetLabel(_("Use frame rate dependent trajectories (deprecated, it's "
"recommended to leave this unchecked)"))
.SetGroup(_("Deprecated options"))
.SetDeprecated()
.SetValue(behaviorContent.GetBoolAttribute("useLegacyTrajectory", true)
? "true"
: "false")
.SetType("Boolean");
properties["UseRepeatedJump"]
.SetLabel(_("Allows repeated jumps while holding the jump key "
"(deprecated — best left unchecked)"))
.SetGroup(_("Deprecated options"))
.SetDeprecated()
.SetValue(behaviorContent.GetBoolAttribute("useRepeatedJump", true)
? "true"
: "false")
.SetType("Boolean");
properties["CanGoDownFromJumpthru"]
.SetLabel(_("Can go down from jumpthru platforms"))
.SetQuickCustomizationVisibility(gd::QuickCustomization::Hidden)
@@ -190,15 +180,13 @@ bool PlatformerObjectBehavior::UpdateProperty(
const gd::String& name,
const gd::String& value) {
if (name == "IgnoreDefaultControls")
behaviorContent.SetAttribute("ignoreDefaultControls", (value == "1"));
behaviorContent.SetAttribute("ignoreDefaultControls", (value == "0"));
else if (name == "CanGrabPlatforms")
behaviorContent.SetAttribute("canGrabPlatforms", (value == "1"));
else if (name == "CanGrabWithoutMoving")
behaviorContent.SetAttribute("canGrabWithoutMoving", (value == "1"));
else if (name == "UseLegacyTrajectory")
behaviorContent.SetAttribute("useLegacyTrajectory", (value == "1"));
else if (name == "UseRepeatedJump")
behaviorContent.SetAttribute("useRepeatedJump", (value == "1"));
else if (name == "CanGoDownFromJumpthru")
behaviorContent.SetAttribute("canGoDownFromJumpthru", (value == "1"));
else if (name == "YGrabOffset")

View File

@@ -23,6 +23,7 @@ namespace gdjs {
interface JumpingStateNetworkSyncData {
cjs: number;
tscjs: number;
jkhsjs: boolean;
jfd: boolean;
}
@@ -56,7 +57,6 @@ namespace gdjs {
juk: boolean;
rpk: boolean;
rlk: boolean;
jkhsjs: boolean;
sn: string;
ssd: StateNetworkSyncData;
}
@@ -119,7 +119,6 @@ namespace gdjs {
private _xGrabTolerance: any;
_useLegacyTrajectory: boolean;
_useRepeatedJump: boolean;
_canGoDownFromJumpthru: boolean = false;
@@ -140,7 +139,6 @@ namespace gdjs {
_upKey: boolean = false;
_downKey: boolean = false;
_jumpKey: boolean = false;
_jumpKeyHeldSinceJumpStart: boolean = false;
_releasePlatformKey: boolean = false;
_releaseLadderKey: boolean = false;
@@ -206,10 +204,6 @@ namespace gdjs {
behaviorData.useLegacyTrajectory === undefined
? true
: behaviorData.useLegacyTrajectory;
this._useRepeatedJump =
behaviorData.useRepeatedJump === undefined
? true
: behaviorData.useRepeatedJump;
this._canGoDownFromJumpthru = behaviorData.canGoDownFromJumpthru;
this._slopeMaxAngle = 0;
this.setSlopeMaxAngle(behaviorData.slopeMaxAngle);
@@ -255,7 +249,6 @@ namespace gdjs {
juk: this._wasJumpKeyPressed,
rpk: this._wasReleasePlatformKeyPressed,
rlk: this._wasReleaseLadderKeyPressed,
jkhsjs: this._jumpKeyHeldSinceJumpStart,
sn: this._state.toString(),
ssd: this._state.getNetworkSyncData(),
},
@@ -313,9 +306,6 @@ namespace gdjs {
if (behaviorSpecificProps.rlk !== this._releaseLadderKey) {
this._releaseLadderKey = behaviorSpecificProps.rlk;
}
if (behaviorSpecificProps.jkhsjs !== this._jumpKeyHeldSinceJumpStart) {
this._jumpKeyHeldSinceJumpStart = behaviorSpecificProps.jkhsjs;
}
if (behaviorSpecificProps.sn !== this._state.toString()) {
switch (behaviorSpecificProps.sn) {
@@ -437,11 +427,6 @@ namespace gdjs {
(inputManager.isKeyPressed(LSHIFTKEY) ||
inputManager.isKeyPressed(RSHIFTKEY) ||
inputManager.isKeyPressed(SPACEKEY)));
// Check if the jump key is continuously held since
// the beginning of the jump.
if (!this._jumpKey) {
this._jumpKeyHeldSinceJumpStart = false;
}
this._ladderKey ||
(this._ladderKey =
@@ -765,11 +750,7 @@ namespace gdjs {
}
_checkTransitionJumping() {
if (
this._canJump &&
this._jumpKey &&
(!this._jumpKeyHeldSinceJumpStart || this._useRepeatedJump)
) {
if (this._canJump && this._jumpKey) {
this._setJumping();
}
}
@@ -2289,6 +2270,7 @@ namespace gdjs {
private _behavior: PlatformerObjectRuntimeBehavior;
private _currentJumpSpeed: number = 0;
private _timeSinceCurrentJumpStart: number = 0;
private _jumpKeyHeldSinceJumpStart: boolean = false;
private _jumpingFirstDelta: boolean = false;
constructor(behavior: PlatformerObjectRuntimeBehavior) {
@@ -2306,7 +2288,7 @@ namespace gdjs {
enter(from: State) {
const behavior = this._behavior;
this._timeSinceCurrentJumpStart = 0;
behavior._jumpKeyHeldSinceJumpStart = true;
this._jumpKeyHeldSinceJumpStart = true;
if (from !== behavior._jumping && from !== behavior._falling) {
this._jumpingFirstDelta = true;
@@ -2347,12 +2329,17 @@ namespace gdjs {
beforeMovingY(timeDelta: float, oldX: float) {
const behavior = this._behavior;
// Check if the jump key is continuously held since
// the beginning of the jump.
if (!behavior._jumpKey) {
this._jumpKeyHeldSinceJumpStart = false;
}
this._timeSinceCurrentJumpStart += timeDelta;
const previousJumpSpeed = this._currentJumpSpeed;
// Decrease jump speed after the (optional) jump sustain time is over.
const sustainJumpSpeed =
behavior._jumpKeyHeldSinceJumpStart &&
this._jumpKeyHeldSinceJumpStart &&
this._timeSinceCurrentJumpStart < behavior._jumpSustainTime;
if (!sustainJumpSpeed) {
this._currentJumpSpeed -= behavior._gravity * timeDelta;
@@ -2387,6 +2374,7 @@ namespace gdjs {
return {
cjs: this._currentJumpSpeed,
tscjs: this._timeSinceCurrentJumpStart,
jkhsjs: this._jumpKeyHeldSinceJumpStart,
jfd: this._jumpingFirstDelta,
};
}
@@ -2394,6 +2382,7 @@ namespace gdjs {
updateFromNetworkSyncData(data: JumpingStateNetworkSyncData) {
this._currentJumpSpeed = data.cjs;
this._timeSinceCurrentJumpStart = data.tscjs;
this._jumpKeyHeldSinceJumpStart = data.jkhsjs;
this._jumpingFirstDelta = data.jfd;
}

View File

@@ -27,7 +27,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: slopeMaxAngle,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -332,7 +331,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
ignoreDefaultControls: true,
slopeMaxAngle: 60,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -493,7 +491,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -627,7 +624,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 0,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -732,7 +728,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],

View File

@@ -26,7 +26,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
ignoreDefaultControls: true,
slopeMaxAngle: 60,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -173,7 +172,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -289,7 +287,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: true,
useRepeatedJump: true,
},
],
effects: [],
@@ -386,7 +383,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: true,
useRepeatedJump: true,
},
],
effects: [],
@@ -485,7 +481,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: true,
useRepeatedJump: true,
},
],
effects: [],
@@ -560,8 +555,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
let runtimeScene;
let object;
let platform;
/** @type {gdjs.PlatformerObjectRuntimeBehavior} */
let characterBehavior;
beforeEach(function () {
runtimeScene = makePlatformerTestRuntimeScene();
@@ -585,7 +578,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -593,7 +585,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
object.setCustomWidthAndHeight(10, 20);
runtimeScene.addObject(object);
object.setPosition(0, -32);
characterBehavior = object.getBehavior('auto1');
// Put a platform.
platform = addPlatformObject(runtimeScene);
@@ -653,48 +644,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
expect(object.getY()).to.be(-30);
});
it('can only jump once while the jump key is held', function () {
// Ensure the object falls on the platform
for (let i = 0; i < 10; ++i) {
runtimeScene.renderAndStep(1000 / 60);
}
//Check the object is on the platform
expect(object.getY()).to.be(-30); // -30 = -10 (platform y) + -20 (object height)
expect(characterBehavior.isFalling()).to.be(false);
expect(characterBehavior.isFallingWithoutJumping()).to.be(false);
expect(characterBehavior.isMoving()).to.be(false);
// The character jumps a first time.
for (let i = 0; i < 80; ++i) {
characterBehavior.simulateJumpKey();
runtimeScene.renderAndStep(1000 / 60);
characterBehavior.isJumping(true);
}
// The character lands back on the floor
// while the player holds the jump key.
for (let i = 0; i < 4; ++i) {
characterBehavior.simulateJumpKey();
runtimeScene.renderAndStep(1000 / 60);
}
characterBehavior.isOnFloor(true);
expect(object.getY()).to.be(-30);
// The character doesn't jump a 2nd time.
characterBehavior.simulateJumpKey();
runtimeScene.renderAndStep(1000 / 60);
characterBehavior.isOnFloor(true);
// The player release the jump key.
runtimeScene.renderAndStep(1000 / 60);
characterBehavior.isOnFloor(true);
// The character can now jump again.
characterBehavior.simulateJumpKey();
runtimeScene.renderAndStep(1000 / 60);
characterBehavior.isJumping(true);
});
it('can jump, and only sustain the jump while key held', function () {
// Ensure the object falls on the platform
for (let i = 0; i < 10; ++i) {
@@ -1177,7 +1126,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
canGoDownFromJumpthru: true,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -1519,7 +1467,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
ignoreDefaultControls: true,
slopeMaxAngle: 60,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -1550,7 +1497,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
ignoreDefaultControls: true,
slopeMaxAngle: 60,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
{
type: 'PlatformBehavior::PlatformBehavior',
@@ -1691,7 +1637,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -1813,7 +1758,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -1899,7 +1843,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -1978,7 +1921,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],

View File

@@ -26,7 +26,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
canGrabWithoutMoving: canGrabWithoutMoving,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -234,7 +233,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
canGrabWithoutMoving: true,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -400,7 +398,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],

View File

@@ -32,7 +32,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
ignoreDefaultControls: true,
slopeMaxAngle: 60,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -309,7 +308,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
ignoreDefaultControls: true,
slopeMaxAngle: 60,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],

View File

@@ -27,7 +27,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -439,7 +438,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: 60,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],
@@ -548,7 +546,6 @@ describe('gdjs.PlatformerObjectRuntimeBehavior', function () {
slopeMaxAngle: slopeMaxAngle,
jumpSustainTime: 0.2,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],

View File

@@ -36,7 +36,6 @@ describe(`gdjs.PlatformerObjectRuntimeBehavior.findHighestFloorAndMoveOnTop`, fu
ignoreDefaultControls: true,
slopeMaxAngle: 60,
useLegacyTrajectory: false,
useRepeatedJump: false,
},
],
effects: [],

View File

@@ -311,7 +311,7 @@ void DeclarePrimitiveDrawingExtension(gd::PlatformExtension& extension) {
"such as \"Path line\" (in the Advanced category) can be "
"used to draw. Be sure to use \"End fill path\" action when "
"you're done drawing the shape."),
_("Begin drawing filling of an advanced path "
_("Begins drawing filling of an advanced path "
"with _PARAM0_ (start: _PARAM1_;_PARAM2_)"),
_("Advanced"),
"res/actions/beginFillPath24.png",

View File

@@ -34,7 +34,6 @@ void TopDownMovementBehavior::InitializeContent(
behaviorContent.SetAttribute("viewpoint", "TopDown");
behaviorContent.SetAttribute("customIsometryAngle", 30);
behaviorContent.SetAttribute("movementAngleOffset", 0);
behaviorContent.SetAttribute("useLegacyTurnBack", false);
}
std::map<gd::String, gd::PropertyDescriptor>
@@ -90,20 +89,10 @@ TopDownMovementBehavior::GetProperties(
.SetValue(
gd::String::From(behaviorContent.GetDoubleAttribute("angleOffset")));
properties["IgnoreDefaultControls"]
.SetLabel(_("Disable default keyboard controls"))
.SetQuickCustomizationVisibility(gd::QuickCustomization::Hidden)
.SetLabel(_("Default controls"))
.SetValue(behaviorContent.GetBoolAttribute("ignoreDefaultControls")
? "true"
: "false")
.SetType("Boolean");
properties["UseLegacyTurnBack"]
.SetLabel(_("Only use acceleration to turn back "
"(deprecated — best left unchecked)"))
.SetGroup(_("Deprecated options"))
.SetDeprecated()
.SetValue(behaviorContent.GetBoolAttribute("useLegacyTurnBack", true)
? "true"
: "false")
? "false"
: "true")
.SetType("Boolean");
gd::String viewpoint = behaviorContent.GetStringAttribute("viewpoint");
@@ -156,7 +145,7 @@ bool TopDownMovementBehavior::UpdateProperty(
const gd::String& name,
const gd::String& value) {
if (name == "IgnoreDefaultControls") {
behaviorContent.SetAttribute("ignoreDefaultControls", (value == "1"));
behaviorContent.SetAttribute("ignoreDefaultControls", (value == "0"));
return true;
}
if (name == "AllowDiagonals") {
@@ -167,9 +156,6 @@ bool TopDownMovementBehavior::UpdateProperty(
behaviorContent.SetAttribute("rotateObject", (value != "0"));
return true;
}
if (name == "UseLegacyTurnBack") {
behaviorContent.SetAttribute("useLegacyTurnBack", (value == "1"));
}
if (name == "Viewpoint") {
// Fix the offset angle when switching between top-down and isometry
const gd::String& oldValue =

View File

@@ -37,7 +37,6 @@ namespace gdjs {
private _angleOffset: float;
private _ignoreDefaultControls: boolean;
private _movementAngleOffset: float;
private _useLegacyTurnBack: boolean;
/** The latest angle of movement, in degrees. */
private _angle: float = 0;
@@ -103,10 +102,6 @@ namespace gdjs {
behaviorData.customIsometryAngle
);
this._movementAngleOffset = behaviorData.movementAngleOffset || 0;
this._useLegacyTurnBack =
behaviorData.useLegacyTurnBack === undefined
? true
: behaviorData.useLegacyTurnBack;
}
getNetworkSyncData(): TopDownMovementNetworkSyncData {
@@ -308,7 +303,9 @@ namespace gdjs {
}
getSpeed(): float {
return Math.hypot(this._xVelocity, this._yVelocity);
return Math.sqrt(
this._xVelocity * this._xVelocity + this._yVelocity * this._yVelocity
);
}
getXVelocity(): float {
@@ -471,71 +468,74 @@ namespace gdjs {
// variables without assigning them a value.
let directionInRad = 0;
let directionInDeg = 0;
let cos = 1;
let sin = 0;
let isMoving = false;
let targetedSpeed = 0;
// Update the speed of the object:
if (direction !== -1) {
isMoving = true;
directionInRad =
((direction + this._movementAngleOffset / 45) * Math.PI) / 4.0;
directionInDeg = direction * 45 + this._movementAngleOffset;
targetedSpeed = this._maxSpeed;
} else if (this._stickForce !== 0) {
isMoving = true;
if (!this._allowDiagonals) {
this._stickAngle = 90 * Math.floor((this._stickAngle + 45) / 90);
}
directionInDeg = this._stickAngle + this._movementAngleOffset;
directionInRad = (directionInDeg * Math.PI) / 180;
targetedSpeed = this._maxSpeed * this._stickForce;
this._wasStickUsed = true;
} else if (this._yVelocity !== 0 || this._xVelocity !== 0) {
isMoving = true;
directionInRad = Math.atan2(this._yVelocity, this._xVelocity);
directionInDeg = (directionInRad * 180.0) / Math.PI;
}
if (isMoving) {
// This makes the trigo resilient to rounding errors on directionInRad.
let cos = Math.cos(directionInRad);
let sin = Math.sin(directionInRad);
cos = Math.cos(directionInRad);
sin = Math.sin(directionInRad);
if (cos === -1 || cos === 1) {
sin = 0;
}
if (sin === -1 || sin === 1) {
cos = 0;
}
const getAcceleratedSpeed = this._useLegacyTurnBack
? TopDownMovementRuntimeBehavior.getLegacyAcceleratedSpeed
: TopDownMovementRuntimeBehavior.getAcceleratedSpeed;
let currentSpeed = Math.hypot(this._xVelocity, this._yVelocity);
const dotProduct = this._xVelocity * cos + this._yVelocity * sin;
if (dotProduct < 0) {
// The object is turning back.
// Keep the negative velocity projected on the new direction.
currentSpeed = dotProduct;
this._xVelocity += this._acceleration * timeDelta * cos;
this._yVelocity += this._acceleration * timeDelta * sin;
} else if (this._stickForce !== 0) {
if (!this._allowDiagonals) {
this._stickAngle = 90 * Math.floor((this._stickAngle + 45) / 90);
}
const speed = getAcceleratedSpeed(
currentSpeed,
targetedSpeed,
this._maxSpeed,
this._acceleration,
this._deceleration,
timeDelta
);
this._xVelocity = speed * cos;
this._yVelocity = speed * sin;
}
directionInDeg = this._stickAngle + this._movementAngleOffset;
directionInRad = (directionInDeg * Math.PI) / 180;
const norm = this._acceleration * timeDelta * this._stickForce;
// This makes the trigo resilient to rounding errors on directionInRad.
cos = Math.cos(directionInRad);
sin = Math.sin(directionInRad);
if (cos === -1 || cos === 1) {
sin = 0;
}
if (sin === -1 || sin === 1) {
cos = 0;
}
this._xVelocity += norm * cos;
this._yVelocity += norm * sin;
this._wasStickUsed = true;
this._stickForce = 0;
} else if (this._yVelocity !== 0 || this._xVelocity !== 0) {
directionInRad = Math.atan2(this._yVelocity, this._xVelocity);
directionInDeg = (directionInRad * 180.0) / Math.PI;
const xVelocityWasPositive = this._xVelocity >= 0;
const yVelocityWasPositive = this._yVelocity >= 0;
// This makes the trigo resilient to rounding errors on directionInRad.
cos = Math.cos(directionInRad);
sin = Math.sin(directionInRad);
if (cos === -1 || cos === 1) {
sin = 0;
}
if (sin === -1 || sin === 1) {
cos = 0;
}
this._xVelocity -= this._deceleration * timeDelta * cos;
this._yVelocity -= this._deceleration * timeDelta * sin;
if (this._xVelocity > 0 !== xVelocityWasPositive) {
this._xVelocity = 0;
}
if (this._yVelocity > 0 !== yVelocityWasPositive) {
this._yVelocity = 0;
}
}
const squaredSpeed =
this._xVelocity * this._xVelocity + this._yVelocity * this._yVelocity;
if (squaredSpeed > this._maxSpeed * this._maxSpeed) {
const ratio = this._maxSpeed / Math.sqrt(squaredSpeed);
this._xVelocity *= ratio;
this._yVelocity *= ratio;
this._xVelocity = this._maxSpeed * cos;
this._yVelocity = this._maxSpeed * sin;
}
// No acceleration for angular speed for now.
@@ -589,125 +589,9 @@ namespace gdjs {
this._rightKey = false;
this._upKey = false;
this._downKey = false;
this._stickForce = 0;
}
}
private static getAcceleratedSpeed(
currentSpeed: float,
targetedSpeed: float,
speedMax: float,
acceleration: float,
deceleration: float,
timeDelta: float
): float {
let newSpeed = currentSpeed;
const turningBackAcceleration = Math.max(acceleration, deceleration);
if (targetedSpeed < 0) {
if (currentSpeed <= targetedSpeed) {
// Reduce the speed to match the stick force.
newSpeed = Math.min(
targetedSpeed,
currentSpeed + turningBackAcceleration * timeDelta
);
} else if (currentSpeed <= 0) {
// Accelerate
newSpeed -= Math.max(-speedMax, acceleration * timeDelta);
} else {
// Turn back at least as fast as it would stop.
newSpeed = Math.max(
targetedSpeed,
currentSpeed - turningBackAcceleration * timeDelta
);
}
} else if (targetedSpeed > 0) {
if (currentSpeed >= targetedSpeed) {
// Reduce the speed to match the stick force.
newSpeed = Math.max(
targetedSpeed,
currentSpeed - turningBackAcceleration * timeDelta
);
} else if (currentSpeed >= 0) {
// Accelerate
newSpeed = Math.min(
speedMax,
currentSpeed + acceleration * timeDelta
);
} else {
// Turn back at least as fast as it would stop.
newSpeed = Math.min(
targetedSpeed,
currentSpeed + turningBackAcceleration * timeDelta
);
}
} else {
// Decelerate and stop.
if (currentSpeed < 0) {
newSpeed = Math.min(currentSpeed + deceleration * timeDelta, 0);
}
if (currentSpeed > 0) {
newSpeed = Math.max(currentSpeed - deceleration * timeDelta, 0);
}
}
return newSpeed;
}
private static getLegacyAcceleratedSpeed(
currentSpeed: float,
targetedSpeed: float,
speedMax: float,
acceleration: float,
deceleration: float,
timeDelta: float
): float {
let newSpeed = currentSpeed;
if (targetedSpeed < 0) {
if (currentSpeed <= targetedSpeed) {
// Reduce the speed to match the stick force.
newSpeed = Math.min(
targetedSpeed,
currentSpeed + deceleration * timeDelta
);
} else if (currentSpeed <= 0) {
// Accelerate
newSpeed -= Math.max(-speedMax, acceleration * timeDelta);
} else {
newSpeed = Math.max(
targetedSpeed,
currentSpeed - deceleration * timeDelta
);
}
} else if (targetedSpeed > 0) {
if (currentSpeed >= targetedSpeed) {
// Reduce the speed to match the stick force.
newSpeed = Math.max(
targetedSpeed,
currentSpeed - deceleration * timeDelta
);
} else if (currentSpeed >= 0) {
// Accelerate
newSpeed = Math.min(
speedMax,
currentSpeed + acceleration * timeDelta
);
} else {
newSpeed = Math.min(
targetedSpeed,
currentSpeed + deceleration * timeDelta
);
}
} else {
// Decelerate and stop.
if (currentSpeed < 0) {
newSpeed = Math.min(currentSpeed + deceleration * timeDelta, 0);
}
if (currentSpeed > 0) {
newSpeed = Math.max(currentSpeed - deceleration * timeDelta, 0);
}
}
return newSpeed;
}
simulateControl(input: string) {
if (input === 'Left') {
this._leftKey = true;

View File

@@ -60,7 +60,7 @@ module.exports = {
'Tween',
_('Tweening'),
_(
'Smoothly animate object properties over time — such as position, rotation scale, opacity, and more — as well as variables. Ideal for creating fluid transitions and UI animations. While you can use tweens to move objects, other behaviors (like platform, physics, ellipse movement...) or forces are often better suited for dynamic movement. Tween is best used for animating UI elements, static objects that need to move from one point to another, or other values like variables.'
'Animate object properties over time. This allows smooth transitions, animations or movement of objects to specified positions.'
),
'Matthias Meike, Florian Rival',
'Open source (MIT License)'

View File

@@ -222,9 +222,7 @@ namespace gdjs {
kind: 'fatal',
message:
'Unexpected error happened while hot-reloading: ' +
error.message +
'\n' +
error.stack,
error.message,
});
}
})
@@ -474,24 +472,13 @@ namespace gdjs {
newExternalLayoutData.associatedLayout
);
const oldObjectDataList =
HotReloader.resolveCustomObjectConfigurations(
oldProjectData,
oldLayoutData ? oldLayoutData.objects : []
);
const newObjectDataList =
HotReloader.resolveCustomObjectConfigurations(
newProjectData,
newLayoutData ? newLayoutData.objects : []
);
sceneStack._stack.forEach((runtimeScene) => {
this._hotReloadRuntimeSceneInstances(
oldProjectData,
newProjectData,
changedRuntimeBehaviors,
oldObjectDataList,
newObjectDataList,
oldLayoutData ? oldLayoutData.objects : [],
newLayoutData ? newLayoutData.objects : [],
oldExternalLayoutData.instances,
newExternalLayoutData.instances,
runtimeScene

View File

@@ -397,68 +397,60 @@ namespace gdjs {
document.addEventListener(
'pause',
function () {
that.pauseAllActiveSounds();
const soundList = that._freeSounds.concat(that._freeMusics);
for (let key in that._sounds) {
if (that._sounds.hasOwnProperty(key)) {
soundList.push(that._sounds[key]);
}
}
for (let key in that._musics) {
if (that._musics.hasOwnProperty(key)) {
soundList.push(that._musics[key]);
}
}
for (let i = 0; i < soundList.length; i++) {
const sound = soundList[i];
if (!sound.paused() && !sound.stopped()) {
sound.pause();
that._pausedSounds.push(sound);
}
}
that._paused = true;
},
false
);
document.addEventListener(
'resume',
function () {
that.resumeAllActiveSounds();
try {
for (let i = 0; i < that._pausedSounds.length; i++) {
const sound = that._pausedSounds[i];
if (!sound.stopped()) {
sound.play();
}
}
} catch (error) {
if (
error.message &&
typeof error.message === 'string' &&
error.message.startsWith('Maximum call stack size exceeded')
) {
console.warn(
'An error occurred when resuming paused sounds while the game was in background:',
error
);
} else {
throw error;
}
}
that._pausedSounds.length = 0;
that._paused = false;
},
false
);
});
}
pauseAllActiveSounds(): void {
const soundList = this._freeSounds.concat(this._freeMusics);
for (let key in this._sounds) {
if (this._sounds.hasOwnProperty(key)) {
soundList.push(this._sounds[key]);
}
}
for (let key in this._musics) {
if (this._musics.hasOwnProperty(key)) {
soundList.push(this._musics[key]);
}
}
for (let i = 0; i < soundList.length; i++) {
const sound = soundList[i];
if (!sound.paused() && !sound.stopped()) {
sound.pause();
this._pausedSounds.push(sound);
}
}
this._paused = true;
}
resumeAllActiveSounds(): void {
try {
for (let i = 0; i < this._pausedSounds.length; i++) {
const sound = this._pausedSounds[i];
if (!sound.stopped()) {
sound.play();
}
}
} catch (error) {
if (
error.message &&
typeof error.message === 'string' &&
error.message.startsWith('Maximum call stack size exceeded')
) {
console.warn(
'An error occurred when resuming paused sounds while the game was in background:',
error
);
} else {
throw error;
}
}
this._pausedSounds.length = 0;
this._paused = false;
}
getResourceKinds(): ResourceKind[] {
return resourceKinds;
}

View File

@@ -1405,7 +1405,6 @@ interface InitialInstance {
double GetCustomDepth();
[Ref] InitialInstance ResetPersistentUuid();
[Const, Ref] DOMString GetPersistentUuid();
void UpdateCustomProperty(
[Const] DOMString name,
@@ -2294,8 +2293,6 @@ interface PlatformExtension {
[Const, Value] DOMString STATIC_GetNamespaceSeparator();
[Const, Value] DOMString STATIC_GetBehaviorFullType(
[Const] DOMString extensionName, [Const] DOMString behaviorName);
[Const, Value] DOMString STATIC_GetExtensionFromFullBehaviorType([Const] DOMString type);
[Const, Value] DOMString STATIC_GetBehaviorNameFromFullBehaviorType([Const] DOMString type);
[Const, Value] DOMString STATIC_GetObjectFullType(
[Const] DOMString extensionName, [Const] DOMString objectName);
[Const, Value] DOMString STATIC_GetExtensionFromFullObjectType([Const] DOMString type);
@@ -2345,9 +2342,6 @@ interface BaseEvent {
void SerializeTo([Ref] SerializerElement element);
void UnserializeFrom([Ref] Project project, [Const, Ref] SerializerElement element);
[Const, Ref] DOMString GetAiGeneratedEventId();
void SetAiGeneratedEventId([Const] DOMString aiGeneratedEventId);
};
interface StandardEvent {
@@ -2811,7 +2805,6 @@ interface WholeProjectRefactorer {
unsigned long STATIC_GetLayoutAndExternalLayoutLayerInstancesCount([Ref] Project project, [Ref] Layout layout, [Const] DOMString layerName);
void STATIC_RenameLeaderboards([Ref] Project project, [Const, Ref] MapStringString leaderboardIdMap);
[Value] SetString STATIC_FindAllLeaderboardIds([Ref] Project project);
void STATIC_UpdateBehaviorsSharedData([Ref] Project project);
};
interface ObjectTools {

View File

@@ -674,7 +674,6 @@ typedef ExtensionAndMetadata<ExpressionMetadata> ExtensionAndExpressionMetadata;
GetLayoutAndExternalLayoutLayerInstancesCount
#define STATIC_RenameLeaderboards RenameLeaderboards
#define STATIC_FindAllLeaderboardIds FindAllLeaderboardIds
#define STATIC_UpdateBehaviorsSharedData UpdateBehaviorsSharedData
#define STATIC_GenerateBehaviorGetterAndSetter GenerateBehaviorGetterAndSetter
#define STATIC_GenerateObjectGetterAndSetter GenerateObjectGetterAndSetter
@@ -716,8 +715,6 @@ typedef ExtensionAndMetadata<ExpressionMetadata> ExtensionAndExpressionMetadata;
#define STATIC_GetNamespaceSeparator GetNamespaceSeparator
#define STATIC_GetBehaviorFullType GetBehaviorFullType
#define STATIC_GetExtensionFromFullBehaviorType GetExtensionFromFullBehaviorType
#define STATIC_GetBehaviorNameFromFullBehaviorType GetBehaviorNameFromFullBehaviorType
#define STATIC_GetObjectFullType GetObjectFullType
#define STATIC_GetExtensionFromFullObjectType GetExtensionFromFullObjectType
#define STATIC_GetObjectNameFromFullObjectType GetObjectNameFromFullObjectType

View File

@@ -140,9 +140,6 @@ describe('libGD.js', function () {
expect(gd.Project.getSafeName('官话 name')).toBe('官话_name');
expect(gd.Project.getSafeName('')).toBe('Unnamed');
expect(gd.Project.getSafeName('9')).toBe('_9');
expect(gd.Project.getSafeName('ExplosionParticles3D')).toBe(
'ExplosionParticles3D'
);
});
it('should have a list of extensions', function () {

View File

@@ -1167,7 +1167,6 @@ export class InitialInstance extends EmscriptenObject {
setCustomDepth(depth: number): void;
getCustomDepth(): number;
resetPersistentUuid(): InitialInstance;
getPersistentUuid(): string;
updateCustomProperty(name: string, value: string, globalObjectsContainer: ObjectsContainer, objectsContainer: ObjectsContainer): void;
getCustomProperties(globalObjectsContainer: ObjectsContainer, objectsContainer: ObjectsContainer): MapStringPropertyDescriptor;
getRawDoubleProperty(name: string): number;
@@ -1741,8 +1740,6 @@ export class PlatformExtension extends EmscriptenObject {
getAllSourceFiles(): VectorSourceFileMetadata;
static getNamespaceSeparator(): string;
static getBehaviorFullType(extensionName: string, behaviorName: string): string;
static getExtensionFromFullBehaviorType(type: string): string;
static getBehaviorNameFromFullBehaviorType(type: string): string;
static getObjectFullType(extensionName: string, objectName: string): string;
static getExtensionFromFullObjectType(type: string): string;
static getObjectNameFromFullObjectType(type: string): string;
@@ -1783,8 +1780,6 @@ export class BaseEvent extends EmscriptenObject {
setFolded(folded: boolean): void;
serializeTo(element: SerializerElement): void;
unserializeFrom(project: Project, element: SerializerElement): void;
getAiGeneratedEventId(): string;
setAiGeneratedEventId(aiGeneratedEventId: string): void;
}
export class StandardEvent extends BaseEvent {
@@ -1999,7 +1994,6 @@ export class WholeProjectRefactorer extends EmscriptenObject {
static getLayoutAndExternalLayoutLayerInstancesCount(project: Project, layout: Layout, layerName: string): number;
static renameLeaderboards(project: Project, leaderboardIdMap: MapStringString): void;
static findAllLeaderboardIds(project: Project): SetString;
static updateBehaviorsSharedData(project: Project): void;
}
export class ObjectTools extends EmscriptenObject {

View File

@@ -17,8 +17,6 @@ declare class gdBaseEvent extends gdBaseEvent {
setFolded(folded: boolean): void;
serializeTo(element: gdSerializerElement): void;
unserializeFrom(project: gdProject, element: gdSerializerElement): void;
getAiGeneratedEventId(): string;
setAiGeneratedEventId(aiGeneratedEventId: string): void;
delete(): void;
ptr: number;
};

View File

@@ -44,7 +44,6 @@ declare class gdInitialInstance {
setCustomDepth(depth: number): void;
getCustomDepth(): number;
resetPersistentUuid(): gdInitialInstance;
getPersistentUuid(): string;
updateCustomProperty(name: string, value: string, globalObjectsContainer: gdObjectsContainer, objectsContainer: gdObjectsContainer): void;
getCustomProperties(globalObjectsContainer: gdObjectsContainer, objectsContainer: gdObjectsContainer): gdMapStringPropertyDescriptor;
getRawDoubleProperty(name: string): number;

View File

@@ -57,8 +57,6 @@ declare class gdPlatformExtension {
getAllSourceFiles(): gdVectorSourceFileMetadata;
static getNamespaceSeparator(): string;
static getBehaviorFullType(extensionName: string, behaviorName: string): string;
static getExtensionFromFullBehaviorType(type: string): string;
static getBehaviorNameFromFullBehaviorType(type: string): string;
static getObjectFullType(extensionName: string, objectName: string): string;
static getExtensionFromFullObjectType(type: string): string;
static getObjectNameFromFullObjectType(type: string): string;

View File

@@ -63,7 +63,6 @@ declare class gdWholeProjectRefactorer {
static getLayoutAndExternalLayoutLayerInstancesCount(project: gdProject, layout: gdLayout, layerName: string): number;
static renameLeaderboards(project: gdProject, leaderboardIdMap: gdMapStringString): void;
static findAllLeaderboardIds(project: gdProject): gdSetString;
static updateBehaviorsSharedData(project: gdProject): void;
delete(): void;
ptr: number;
};

View File

@@ -1,8 +1,6 @@
# Deprecated AppVeyor configuration to build GDevelop app running
# AppVeyor configuration to build GDevelop app running
# on the Electron runtime (newIDE/electron-app) for Windows.
#
# This was replaced by build on CircleCI - but kept for redundancy/tests.
# For Windows, macOS and Linux builds, see the config.yml file.
# For macOS and Linux, see the config.yml file.
version: 1.0.{build}
pull_requests:
@@ -19,7 +17,6 @@ cache:
- newIDE\app\node_modules -> newIDE\app\package-lock.json
- newIDE\electron-app\node_modules -> newIDE\electron-app\package-lock.json
- GDevelop.js\node_modules -> GDevelop.js\package-lock.json
- GDJS\node_modules -> GDJS\package-lock.json
install:
# Download and install SSL.com eSigner CKA.
# See https://www.ssl.com/how-to/how-to-integrate-esigner-cka-with-ci-cd-tools-for-automated-code-signing/.
@@ -93,8 +90,9 @@ build_script:
echo Certificate: $CodeSigningCert
# Use a custom signtool path because of the signtool.exe bundled withy electron-builder not working for some reason.
# Can also be found in versioned folders like "C:/Program Files (x86)/Windows Kits/10/bin/10.0.22000.0/x86/signtool.exe".
$Env:SIGNTOOL_PATH = "C:\Program Files (x86)\Windows Kits\10\bin\10.0.22000.0\x86\signtool.exe"
$Env:SIGNTOOL_PATH = "C:\Program Files (x86)\Windows Kits\10\App Certification Kit\signtool.exe"
# Extract thumbprint and subject name of the certificate (will be passed to electron-builder).
@@ -134,9 +132,8 @@ artifacts:
name: GDevelopWindows
# Upload artifacts (AWS) - configuration is stored on AppVeyor itself.
# Disabled because done by CircleCI "build-windows" job.
# deploy:
# - provider: Environment
# name: Amazon S3 releases
# - provider: Environment
# name: Amazon S3 latest releases
deploy:
- provider: Environment
name: Amazon S3 releases
- provider: Environment
name: Amazon S3 latest releases

View File

@@ -18,6 +18,5 @@ module.exports = {
},
},
'@storybook/preset-create-react-app',
'storybook-addon-mock',
],
};

File diff suppressed because it is too large Load Diff

View File

@@ -10,13 +10,13 @@
"@babel/preset-react": "^7.22.5",
"@lingui/cli": "^2.7.3",
"@lingui/macro": "^2.7.3",
"@storybook/addon-essentials": "7.4.6",
"@storybook/addons": "7.4.6",
"@storybook/components": "7.4.6",
"@storybook/preset-create-react-app": "7.4.6",
"@storybook/react": "7.4.6",
"@storybook/react-webpack5": "7.4.6",
"@storybook/theming": "7.4.6",
"@storybook/addon-essentials": "^7.4.0",
"@storybook/addons": "^7.4.0",
"@storybook/components": "^7.4.0",
"@storybook/preset-create-react-app": "^7.4.0",
"@storybook/react": "^7.4.0",
"@storybook/react-webpack5": "^7.4.0",
"@storybook/theming": "^7.4.0",
"adm-zip": "^0.5.10",
"axios-mock-adapter": "^1.22.0",
"babel-core": "^7.0.0-bridge.0",
@@ -33,8 +33,7 @@
"recursive-copy": "^2.0.14",
"recursive-readdir": "^2.2.2",
"shelljs": "0.8.4",
"storybook": "7.4.6",
"storybook-addon-mock": "4.3.0",
"storybook": "^7.4.0",
"style-dictionary": "^2.10.2",
"typescript": "^4.1.3",
"webpack": "5.88.2",

View File

@@ -158,18 +158,13 @@ ${extension.getDescription()} ${generateReadMoreLink(extension.getHelpPath())}
};
};
/** @returns {String} */
const generateBuiltInExtensionNote = ({ extension }) => {
return `The ${extension.getFullName()} extension is always installed in all GDevelop projects: there is no need to add it from the Project Manager.\n\n`;
};
/** @returns {RawText} */
const generateExtensionFooterText = ({ extension }) => {
return {
text:
`\n\n---\n\n` +
generateBuiltInExtensionNote({ extension }) +
`*This page is an auto-generated reference page about the **${extension.getFullName()}** feature of [GDevelop, the open-source, cross-platform game engine designed for everyone](https://gdevelop.io/).*` +
`
---
*This page is an auto-generated reference page about the **${extension.getFullName()}** feature of [GDevelop, the open-source, cross-platform game engine designed for everyone](https://gdevelop.io/).*` +
' ' +
'Learn more about [all GDevelop features here](/gdevelop5/all-features).',
};

View File

@@ -1,158 +0,0 @@
// @flow
import {
type AiRequest,
type AiRequestMessageAssistantFunctionCall,
type AiRequestFunctionCallOutput,
} from '../../Utils/GDevelopServices/Generation';
import { type EditorFunctionCallResult } from '../../EditorFunctions/EditorFunctionCallRunner';
export const getFunctionCallToFunctionCallOutputMap = ({
aiRequest,
}: {|
aiRequest: AiRequest,
|}): Map<
AiRequestMessageAssistantFunctionCall,
AiRequestFunctionCallOutput | null
> => {
// Maps each function call to its corresponding output (or null if no output)
const functionCallsToOutputs = new Map<
AiRequestMessageAssistantFunctionCall,
AiRequestFunctionCallOutput | null
>();
// Track function calls by their call_id to match with outputs
const functionCallsByCallId = new Map<
string,
AiRequestMessageAssistantFunctionCall
>();
// Process messages in a single loop
for (let i = 0; i < aiRequest.output.length; i++) {
const message = aiRequest.output[i];
if (message.type === 'message' && message.role === 'assistant') {
// Process function calls in this message
message.content.forEach(content => {
if (content.type === 'function_call') {
// Initialize with null output - will be updated if we find a matching output
functionCallsToOutputs.set(content, null);
// Store function call by call_id for later matching
functionCallsByCallId.set(content.call_id, content);
}
});
} else if (message.type === 'function_call_output') {
// Find the corresponding function calls with this call_id
const functionCall = functionCallsByCallId.get(message.call_id);
functionCallsByCallId.delete(message.call_id);
// Match with the most recent function call with this call_id
if (functionCall) {
functionCallsToOutputs.set(functionCall, message);
}
}
}
return functionCallsToOutputs;
};
export const getFunctionCallsToProcess = ({
aiRequest,
editorFunctionCallResults,
}: {|
aiRequest: AiRequest,
editorFunctionCallResults: Array<EditorFunctionCallResult> | null,
|}): Array<AiRequestMessageAssistantFunctionCall> => {
const functionCallsToProcess: AiRequestMessageAssistantFunctionCall[] = [];
const appliedFunctionCallIds = new Set<string>();
const alreadyProcessedFunctionCallIds = new Set<string>();
// Track already applied function calls
(editorFunctionCallResults || []).forEach(functionCallOutput => {
appliedFunctionCallIds.add(functionCallOutput.call_id);
});
// Process from the end and collect function calls until we hit a message with no function calls
let foundFunctionCall = false;
for (let i = aiRequest.output.length - 1; i >= 0; i--) {
const message = aiRequest.output[i];
// Track already processed function call outputs
if (message.type === 'function_call_output') {
alreadyProcessedFunctionCallIds.add(message.call_id);
}
// Collect function calls that need processing
if (message.type === 'message' && message.role === 'assistant') {
const functionCalls = message.content.filter(
content => content.type === 'function_call'
);
if (functionCalls.length > 0) {
foundFunctionCall = true;
// Add new unique function calls that haven't been processed or applied
for (let j = functionCalls.length - 1; j >= 0; j--) {
const functionCall = functionCalls[j];
if (functionCall.type !== 'function_call') continue;
if (
!alreadyProcessedFunctionCallIds.has(functionCall.call_id) &&
!appliedFunctionCallIds.has(functionCall.call_id)
) {
functionCallsToProcess.unshift(functionCall); // Add to beginning to preserve original order
}
}
} else if (foundFunctionCall) {
// If we've found function calls and now hit a message with no function calls, stop
break;
}
}
}
return functionCallsToProcess;
};
export const getFunctionCallOutputsFromEditorFunctionCallResults = (
editorFunctionCallResults: Array<EditorFunctionCallResult> | null
): {|
hasUnfinishedResult: boolean,
functionCallOutputs: Array<AiRequestFunctionCallOutput>,
|} => {
if (!editorFunctionCallResults)
return { hasUnfinishedResult: false, functionCallOutputs: [] };
let hasUnfinishedResult = false;
const functionCallOutputs = editorFunctionCallResults
.map(functionCallOutput => {
if (functionCallOutput.status === 'finished') {
return {
type: 'function_call_output',
call_id: functionCallOutput.call_id,
output: JSON.stringify({
success: functionCallOutput.success,
...functionCallOutput.output,
}),
};
} else if (functionCallOutput.status === 'ignored') {
return {
type: 'function_call_output',
call_id: functionCallOutput.call_id,
output: JSON.stringify({
ignored: true,
message: 'This was marked as ignored by the user.',
}),
};
}
hasUnfinishedResult = true;
return null;
})
.filter(Boolean);
return {
functionCallOutputs,
hasUnfinishedResult,
};
};

View File

@@ -1,37 +0,0 @@
// @flow
import * as React from 'react';
import classes from './ChatBubble.module.css';
import Paper from '../../UI/Paper';
const styles = {
chatBubble: {
paddingTop: 5,
paddingLeft: 16,
paddingRight: 16,
paddingBottom: 5,
},
};
type ChatBubbleProps = {|
children: React.Node,
feedbackButtons?: React.Node,
role: 'assistant' | 'user',
|};
export const ChatBubble = ({
children,
feedbackButtons,
role,
}: ChatBubbleProps) => {
return (
<div className={classes.chatBubbleContainer}>
<Paper
background={role === 'user' ? 'light' : 'medium'}
style={styles.chatBubble}
>
<div className={classes.chatBubbleContent}>{children}</div>
{feedbackButtons}
</Paper>
</div>
);
};

View File

@@ -1,35 +0,0 @@
@keyframes chat-bubble-appear {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0px);
}
}
@keyframes content-appear {
0% {
opacity: 0;
}
/* Start after the bubble container. */
37% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.chatBubbleContainer {
display: flex;
animation: chat-bubble-appear 0.3s;
min-width: 0; /** Prevents horizontal overflow */
}
.chatBubbleContent {
display: flex;
animation: content-appear 0.8s;
min-width: 0; /** Prevents horizontal overflow */
}

View File

@@ -1,258 +0,0 @@
// @flow
import * as React from 'react';
import { ChatBubble } from './ChatBubble';
import { Line } from '../../UI/Grid';
import { ChatMarkdownText } from './ChatMarkdownText';
import GDevelopThemeContext from '../../UI/Theme/GDevelopThemeContext';
import { getFunctionCallToFunctionCallOutputMap } from './AiRequestUtils';
import { FunctionCallRow } from './FunctionCallRow';
import IconButton from '../../UI/IconButton';
import Like from '../../UI/CustomSvgIcons/Like';
import Dislike from '../../UI/CustomSvgIcons/Dislike';
import Copy from '../../UI/CustomSvgIcons/Copy';
import { Trans, t } from '@lingui/macro';
import {
type AiRequest,
type AiRequestMessageAssistantFunctionCall,
} from '../../Utils/GDevelopServices/Generation';
import {
type EditorFunctionCallResult,
type EditorCallbacks,
} from '../../EditorFunctions';
import classes from './ChatMessages.module.css';
import { DislikeFeedbackDialog } from './DislikeFeedbackDialog';
import LeftLoader from '../../UI/LeftLoader';
import Text from '../../UI/Text';
import AlertMessage from '../../UI/AlertMessage';
type Props = {|
aiRequest: AiRequest,
onSendFeedback: (
aiRequestId: string,
messageIndex: number,
feedback: 'like' | 'dislike',
reason?: string,
freeFormDetails?: string
) => Promise<void>,
editorFunctionCallResults: Array<EditorFunctionCallResult> | null,
onProcessFunctionCalls: (
functionCalls: Array<AiRequestMessageAssistantFunctionCall>,
options: ?{|
ignore?: boolean,
|}
) => Promise<void>,
editorCallbacks: EditorCallbacks,
project: gdProject | null,
|};
export const ChatMessages = React.memo<Props>(function ChatMessages({
aiRequest,
onSendFeedback,
editorFunctionCallResults,
onProcessFunctionCalls,
editorCallbacks,
project,
}: Props) {
const theme = React.useContext(GDevelopThemeContext);
const [messageFeedbacks, setMessageFeedbacks] = React.useState({});
const [
dislikeFeedbackDialogOpenedFor,
setDislikeFeedbackDialogOpenedFor,
] = React.useState(null);
const functionCallToFunctionCallOutput = aiRequest
? getFunctionCallToFunctionCallOutputMap({
aiRequest,
})
: new Map();
return (
<>
{aiRequest.output.flatMap((message, messageIndex) => {
if (message.type === 'message' && message.role === 'user') {
return [
<Line key={messageIndex} justifyContent="flex-end">
<ChatBubble role="user">
<ChatMarkdownText
source={message.content
.map(messageContent => messageContent.text)
.join('\n')}
/>
</ChatBubble>
</Line>,
];
}
if (message.type === 'message' && message.role === 'assistant') {
return [
...message.content
.map((messageContent, messageContentIndex) => {
const key = `messageIndex${messageIndex}-${messageContentIndex}`;
if (messageContent.type === 'output_text') {
const feedbackKey = `${messageIndex}-${messageContentIndex}`;
const currentFeedback = messageFeedbacks[feedbackKey];
return (
<Line key={key} justifyContent="flex-start">
<ChatBubble
role="assistant"
feedbackButtons={
<div className={classes.feedbackButtonsContainer}>
<IconButton
size="small"
tooltip={t`Copy`}
onClick={() => {
navigator.clipboard.writeText(
messageContent.text
);
}}
>
<Copy fontSize="small" />
</IconButton>
<IconButton
size="small"
tooltip={t`This was helpful`}
onClick={() => {
setMessageFeedbacks({
...messageFeedbacks,
[feedbackKey]: 'like',
});
onSendFeedback(
aiRequest.id,
messageIndex,
'like'
);
}}
>
<Like
fontSize="small"
htmlColor={
currentFeedback === 'like'
? theme.message.valid
: undefined
}
/>
</IconButton>
<IconButton
size="small"
tooltip={t`This needs improvement`}
onClick={() => {
setMessageFeedbacks({
...messageFeedbacks,
[feedbackKey]: 'dislike',
});
setDislikeFeedbackDialogOpenedFor({
aiRequestId: aiRequest.id,
messageIndex,
});
}}
>
<Dislike
fontSize="small"
htmlColor={
currentFeedback === 'dislike'
? theme.message.warning
: undefined
}
/>
</IconButton>
</div>
}
>
<ChatMarkdownText source={messageContent.text} />
</ChatBubble>
</Line>
);
}
if (messageContent.type === 'reasoning') {
return (
<Line key={key} justifyContent="flex-start">
<ChatBubble role="assistant">
<ChatMarkdownText
source={messageContent.summary.text}
/>
</ChatBubble>
</Line>
);
}
if (messageContent.type === 'function_call') {
const existingFunctionCallOutput = functionCallToFunctionCallOutput.get(
messageContent
);
// If there is already an existing function call output,
// there can't be an editor function call result.
// Indeed, sometimes, two functions will
// have the same call_id (because of the way some LLM APIs are implemented).
// The editorFunctionCallResult always applies to the last function call,
// which has no function call output associated to it yet.
const editorFunctionCallResult =
(!existingFunctionCallOutput &&
editorFunctionCallResults &&
editorFunctionCallResults.find(
functionCallOutput =>
functionCallOutput.call_id === messageContent.call_id
)) ||
null;
return (
<FunctionCallRow
project={project}
key={key}
onProcessFunctionCalls={onProcessFunctionCalls}
functionCall={messageContent}
editorFunctionCallResult={editorFunctionCallResult}
existingFunctionCallOutput={existingFunctionCallOutput}
editorCallbacks={editorCallbacks}
/>
);
}
return null;
})
.filter(Boolean),
];
}
if (message.type === 'function_call_output') {
return [];
}
return [];
})}
{aiRequest.status === 'error' ? (
<Line justifyContent="flex-start">
<AlertMessage kind="error">
<Trans>
The AI encountered an error while handling your request - this was
request was not counted in your AI usage. Try again later.
</Trans>
</AlertMessage>
</Line>
) : aiRequest.status === 'working' ? (
<Line justifyContent="flex-start">
<div className={classes.thinkingText}>
<LeftLoader isLoading>
<Text noMargin displayInlineAsSpan>
<Trans>Thinking about your request...</Trans>
</Text>
</LeftLoader>
</div>
</Line>
) : null}
{dislikeFeedbackDialogOpenedFor && (
<DislikeFeedbackDialog
mode={aiRequest.mode || 'chat'}
open
onClose={() => setDislikeFeedbackDialogOpenedFor(null)}
onSendFeedback={(reason: string, freeFormDetails: string) => {
onSendFeedback(
dislikeFeedbackDialogOpenedFor.aiRequestId,
dislikeFeedbackDialogOpenedFor.messageIndex,
'dislike',
reason,
freeFormDetails
);
}}
/>
)}
</>
);
});

View File

@@ -1,26 +0,0 @@
@keyframes thinking-appear {
0% {
opacity: 0;
transform: translateX(-10px);
}
/* Start after the bubble container and when the bubble content is almost finished animating. */
60% {
opacity: 0;
transform: translateX(-10px);
}
100% {
opacity: 1;
transform: translateX(0px);
}
}
.thinkingText {
animation: thinking-appear 1s;
}
.feedbackButtonsContainer {
display: flex;
justify-content: flex-end;
gap: 4px;
margin-top: 4px;
}

View File

@@ -1,178 +0,0 @@
// @flow
import * as React from 'react';
import { ColumnStackLayout } from '../../UI/Layout';
import Text from '../../UI/Text';
import { I18n } from '@lingui/react';
import { Trans, t } from '@lingui/macro';
import Dialog, { DialogPrimaryButton } from '../../UI/Dialog';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FlatButton from '../../UI/FlatButton';
import { CompactTextAreaField } from '../../UI/CompactTextAreaField';
type DislikeFeedbackDialogProps = {|
open: boolean,
onClose: () => void,
onSendFeedback: (reason: string, freeFormDetails: string) => void,
mode: 'chat' | 'agent',
|};
export const DislikeFeedbackDialog = ({
mode,
open,
onClose,
onSendFeedback,
}: DislikeFeedbackDialogProps) => {
const [selectedReason, setSelectedReason] = React.useState<?string>(null);
const [freeFormDetails, setFreeFormDetails] = React.useState<string>('');
const handleChange = (event: { target: { value: string } }) => {
setSelectedReason(event.target.value);
};
const handleSendFeedback = () => {
if (selectedReason) {
onSendFeedback(selectedReason, freeFormDetails);
onClose();
}
};
return (
<I18n>
{({ i18n }) => (
<Dialog
title={
mode === 'agent' ? (
<Trans>What went wrong?</Trans>
) : (
<Trans>What could be improved?</Trans>
)
}
actions={[
<FlatButton
key="cancel"
label={<Trans>Cancel</Trans>}
onClick={onClose}
/>,
<DialogPrimaryButton
key="send"
primary
label={<Trans>Send feedback</Trans>}
onClick={handleSendFeedback}
disabled={!selectedReason}
/>,
]}
open={open}
onRequestClose={onClose}
maxWidth="sm"
>
<ColumnStackLayout noMargin>
<Text>
{mode === 'agent' ? (
<Trans>
The AI agent is in beta. Help us make it better by telling us
what went wrong:
</Trans>
) : (
<Trans>
Help us improve by telling us what could be improved:
</Trans>
)}
</Text>
<RadioGroup value={selectedReason || ''} onChange={handleChange}>
{mode === 'agent' ? (
<>
<FormControlLabel
value="not-as-good-as-it-could-be"
control={<Radio color="secondary" />}
label={
<Trans>
The result wasn't as good as it could have been
</Trans>
}
/>
<FormControlLabel
value="too-little-work"
control={<Radio color="secondary" />}
label={<Trans>It didn't do enough</Trans>}
/>
<FormControlLabel
value="does-not-work"
control={<Radio color="secondary" />}
label={<Trans>It didn't work at all</Trans>}
/>
<FormControlLabel
value="too-much-modified-or-broken"
control={<Radio color="secondary" />}
label={
<Trans>Too many things were changed or broken</Trans>
}
/>
</>
) : (
<>
<FormControlLabel
value="not-in-my-language"
control={<Radio color="secondary" />}
label={<Trans>The answer is not in my language</Trans>}
/>
<FormControlLabel
value="non-existing-things"
control={<Radio color="secondary" />}
label={
<Trans>
Some things in the answer don't exist in GDevelop
</Trans>
}
/>
<FormControlLabel
value="not-as-good-as-it-could-be"
control={<Radio color="secondary" />}
label={
<Trans>The answer is not as good as it could be</Trans>
}
/>
<FormControlLabel
value="very-wrong-answer"
control={<Radio color="secondary" />}
label={<Trans>The answer is entirely wrong</Trans>}
/>
<FormControlLabel
value="out-of-scope"
control={<Radio color="secondary" />}
label={
<Trans>The answer is out of scope for GDevelop</Trans>
}
/>
<FormControlLabel
value="too-short"
control={<Radio color="secondary" />}
label={<Trans>The answer is too short</Trans>}
/>
<FormControlLabel
value="too-long"
control={<Radio color="secondary" />}
label={<Trans>The answer is too long</Trans>}
/>
</>
)}
<FormControlLabel
value="other"
control={<Radio color="secondary" />}
label={<Trans>Other reason</Trans>}
/>
</RadioGroup>
<CompactTextAreaField
label={i18n._(t`More details (optional)`)}
value={freeFormDetails}
onChange={value => setFreeFormDetails(value)}
rows={5}
maxLength={10000}
/>
</ColumnStackLayout>
</Dialog>
)}
</I18n>
);
};

View File

@@ -1,89 +0,0 @@
// @flow
import React from 'react';
import { Trans, t } from '@lingui/macro';
import { Column, Line } from '../../UI/Grid';
import Paper from '../../UI/Paper';
import IconButton from '../../UI/IconButton';
import Like from '../../UI/CustomSvgIcons/Like';
import Dislike from '../../UI/CustomSvgIcons/Dislike';
import Text from '../../UI/Text';
import classes from './FeedbackBanner.module.css';
import { DislikeFeedbackDialog } from './DislikeFeedbackDialog';
import GDevelopThemeContext from '../../UI/Theme/GDevelopThemeContext';
type Props = {
onSendFeedback: (
feedback: 'like' | 'dislike',
reason?: string,
freeFormDetails?: string
) => void,
};
export const FeedbackBanner = ({ onSendFeedback }: Props) => {
const [currentFeedback, setCurrentFeedback] = React.useState<
'like' | 'dislike' | null
>(null);
const theme = React.useContext(GDevelopThemeContext);
const [
dislikeFeedbackDialogOpened,
setDislikeFeedbackDialogOpened,
] = React.useState<boolean>(false);
return (
<Line noMargin justifyContent="center">
<Paper background="dark" variant="outlined">
<Column expand>
<div className={classes.textAndButtonsContainer}>
<Text size="block-title" color="inherit">
<Trans>Did it work?</Trans>
</Text>
<Line alignItems="center" noMargin neverShrink>
<IconButton
tooltip={t`This was helpful`}
onClick={() => {
setCurrentFeedback('like');
onSendFeedback('like');
}}
color="inherit"
>
<Like
htmlColor={
currentFeedback === 'like' ? theme.message.valid : undefined
}
/>
</IconButton>
<IconButton
tooltip={t`There was a problem`}
onClick={() => {
setDislikeFeedbackDialogOpened(true);
}}
color="inherit"
>
<Dislike
htmlColor={
currentFeedback === 'dislike'
? theme.message.warning
: undefined
}
/>
</IconButton>
</Line>
</div>
</Column>
</Paper>
{dislikeFeedbackDialogOpened && (
<DislikeFeedbackDialog
mode="agent"
open={dislikeFeedbackDialogOpened}
onClose={() => setDislikeFeedbackDialogOpened(false)}
onSendFeedback={(reason: string, freeFormDetails: string) => {
setDislikeFeedbackDialogOpened(false);
onSendFeedback('dislike', reason, freeFormDetails);
setCurrentFeedback('dislike');
}}
/>
)}
</Line>
);
};

View File

@@ -1,12 +0,0 @@
.textAndButtonsContainer {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
gap: 8px;
padding-left: 8px;
padding-right: 2px;
color: var(--theme-text-secondary-color);
opacity: 0.9;
min-width: 0;
}

View File

@@ -1,228 +0,0 @@
// @flow
import * as React from 'react';
import { t } from '@lingui/macro';
import {
type AiRequestMessageAssistantFunctionCall,
type AiRequestFunctionCallOutput,
} from '../../Utils/GDevelopServices/Generation';
import { type EditorFunctionCallResult } from '../../EditorFunctions/EditorFunctionCallRunner';
import CircularProgress from '../../UI/CircularProgress';
import { Tooltip } from '@material-ui/core';
import Text from '../../UI/Text';
import RaisedButton from '../../UI/RaisedButton';
import { Trans } from '@lingui/macro';
import FlatButtonWithSplitMenu from '../../UI/FlatButtonWithSplitMenu';
import Check from '../../UI/CustomSvgIcons/Check';
import Error from '../../UI/CustomSvgIcons/Error';
import GDevelopThemeContext from '../../UI/Theme/GDevelopThemeContext';
import classes from './FunctionCallRow.module.css';
import {
editorFunctions,
type EditorFunction,
type EditorCallbacks,
} from '../../EditorFunctions';
import Link from '../../UI/Link';
import { LineStackLayout, ResponsiveLineStackLayout } from '../../UI/Layout';
import ChevronArrowRight from '../../UI/CustomSvgIcons/ChevronArrowRight';
import ChevronArrowBottom from '../../UI/CustomSvgIcons/ChevronArrowBottom';
import Paper from '../../UI/Paper';
import { Line, Column } from '../../UI/Grid';
type Props = {|
project: gdProject | null,
functionCall: AiRequestMessageAssistantFunctionCall,
editorFunctionCallResult: ?EditorFunctionCallResult,
existingFunctionCallOutput: ?AiRequestFunctionCallOutput,
onProcessFunctionCalls: (
functionCalls: Array<AiRequestMessageAssistantFunctionCall>,
options: ?{|
ignore?: boolean,
|}
) => Promise<void>,
editorCallbacks: EditorCallbacks,
|};
export const FunctionCallRow = React.memo<Props>(function FunctionCallRow({
project,
functionCall,
editorFunctionCallResult,
existingFunctionCallOutput,
onProcessFunctionCalls,
editorCallbacks,
}: Props) {
const [showDetails, setShowDetails] = React.useState(false);
const gdevelopTheme = React.useContext(GDevelopThemeContext);
let existingParsedOutput;
try {
if (existingFunctionCallOutput) {
// While this could be slightly expensive in a component to render, the component
// is memoized, so this won't impact rendering of large chats.
existingParsedOutput = JSON.parse(existingFunctionCallOutput.output);
}
} catch (error) {
existingParsedOutput = null;
}
const isIgnored =
(!!editorFunctionCallResult &&
editorFunctionCallResult.status === 'ignored') ||
(existingParsedOutput && !!existingParsedOutput.ignored);
const isFinished =
!!existingFunctionCallOutput ||
(!!editorFunctionCallResult &&
editorFunctionCallResult.status === 'finished');
const functionCallResultIsErrored =
editorFunctionCallResult &&
editorFunctionCallResult.status === 'finished' &&
editorFunctionCallResult.success === false;
const hasErrored =
functionCallResultIsErrored ||
(existingParsedOutput && existingParsedOutput.success === false);
const isWorking =
!isFinished &&
!!editorFunctionCallResult &&
editorFunctionCallResult.status === 'working';
const editorFunction: EditorFunction | null =
editorFunctions[functionCall.name] || null;
let text;
let details;
let hasDetailsToShow = false;
if (!editorFunction) {
text = (
<Trans>
The AI tried to use a function of the editor that is unknown.
</Trans>
);
} else {
try {
const result = editorFunction.renderForEditor({
project,
args: JSON.parse(functionCall.arguments),
editorCallbacks,
shouldShowDetails: showDetails,
});
text = result.text;
details = result.details;
hasDetailsToShow = result.hasDetailsToShow;
} catch (error) {
console.error('Error rendering function call:', error);
text = (
<Trans>
The editor was unable to display the operation ({functionCall.name})
used by the AI.
</Trans>
);
}
}
return (
<div className={classes.functionCallContainer}>
<LineStackLayout noMargin alignItems="center">
<Tooltip
title={JSON.stringify(
existingFunctionCallOutput || editorFunctionCallResult
)}
>
<div>
{hasErrored ? (
<Error htmlColor={gdevelopTheme.message.error} />
) : isIgnored ? (
<Check htmlColor={gdevelopTheme.text.color.disabled} />
) : isFinished ? (
<Check htmlColor={gdevelopTheme.message.valid} />
) : (
<CircularProgress
size={24}
value={100}
variant={isWorking ? 'indeterminate' : 'determinate'}
/>
)}
</div>
</Tooltip>
<ResponsiveLineStackLayout
justifyContent="space-between"
expand
noOverflowParent
>
<LineStackLayout noMargin alignItems="baseline">
<Text>{text || 'Working...'}</Text>
{hasDetailsToShow && (
<Text size="body-small" color="secondary">
<Link
color="inherit"
href={'#'}
onClick={() => setShowDetails(!showDetails)}
>
<Trans>Details</Trans>
{details ? (
<ChevronArrowBottom
fontSize="small"
style={{
verticalAlign: 'middle',
}}
/>
) : (
<ChevronArrowRight
fontSize="small"
style={{
verticalAlign: 'middle',
}}
/>
)}
</Link>
</Text>
)}
</LineStackLayout>
<LineStackLayout
noMargin
alignItems="baseline"
justifyContent="flex-end"
neverShrink
>
{!isFinished && !isWorking && (
<FlatButtonWithSplitMenu
primary
style={{ flexShrink: 0 }}
onClick={() => onProcessFunctionCalls([functionCall])}
label={<Trans>Execute this action</Trans>}
buildMenuTemplate={i18n => [
{
label: i18n._(t`Ignore this`),
click: () => {
onProcessFunctionCalls([functionCall], {
ignore: true,
});
},
},
]}
/>
)}
{functionCallResultIsErrored && (
<RaisedButton
color="primary"
onClick={() => onProcessFunctionCalls([functionCall])}
label={<Trans>Retry</Trans>}
/>
)}
</LineStackLayout>
</ResponsiveLineStackLayout>
</LineStackLayout>
{details && (
<div className={classes.detailsPaperContainer}>
<Paper background="medium" elevation={0} square variant="outlined">
<Line expand>
<Column expand>
<Text noMargin color="secondary">
{details}
</Text>
</Column>
</Line>
</Paper>
</div>
)}
</div>
);
});

View File

@@ -1,38 +0,0 @@
@keyframes function-call-appear {
0% {
opacity: 0;
transform: translateX(-10px);
}
/* Start after the bubble container and when the bubble content is almost finished animating. */
60% {
opacity: 0;
transform: translateX(-10px);
}
100% {
opacity: 1;
transform: translateX(0px);
}
}
.functionCallContainer {
animation: function-call-appear 0.5s;
display: flex;
flex-direction: column;
gap: 4px;
}
@keyframes details-paper-appear {
0% {
transform: scaleY(0.9);
opacity: 0.8;
}
100% {
opacity: 1;
transform: scaleY(1);
}
}
.detailsPaperContainer {
transform-origin: top left;
animation: details-paper-appear 0.1s;
}

View File

@@ -1,815 +0,0 @@
// @flow
import * as React from 'react';
import { I18n as I18nType } from '@lingui/core';
import { ColumnStackLayout, LineStackLayout } from '../../UI/Layout';
import Text from '../../UI/Text';
import { Trans, t } from '@lingui/macro';
import {
type AiRequest,
type AiRequestMessageAssistantFunctionCall,
} from '../../Utils/GDevelopServices/Generation';
import RaisedButton from '../../UI/RaisedButton';
import { CompactTextAreaFieldWithControls } from '../../UI/CompactTextAreaFieldWithControls';
import { Column, Line, Spacer } from '../../UI/Grid';
import Tooltip from '@material-ui/core/Tooltip';
import Paper from '../../UI/Paper';
import ScrollView, { type ScrollViewInterface } from '../../UI/ScrollView';
import AlertMessage from '../../UI/AlertMessage';
import classes from './AiRequestChat.module.css';
import RobotIcon from '../../ProjectCreation/RobotIcon';
import { useResponsiveWindowSize } from '../../UI/Responsive/ResponsiveWindowMeasurer';
import GetSubscriptionCard from '../../Profile/Subscription/GetSubscriptionCard';
import {
type Quota,
type UsagePrice,
} from '../../Utils/GDevelopServices/Usage';
import { type MessageDescriptor } from '../../Utils/i18n/MessageDescriptor.flow';
import Link from '../../UI/Link';
import { getHelpLink } from '../../Utils/HelpLink';
import Window from '../../Utils/Window';
import { type EditorFunctionCallResult } from '../../EditorFunctions/EditorFunctionCallRunner';
import { type EditorCallbacks } from '../../EditorFunctions';
import { getFunctionCallsToProcess } from './AiRequestUtils';
import CircularProgress from '../../UI/CircularProgress';
import TwoStatesButton from '../../UI/TwoStatesButton';
import Help from '../../UI/CustomSvgIcons/Help';
import Hammer from '../../UI/CustomSvgIcons/Hammer';
import { ChatMessages } from './ChatMessages';
import Send from '../../UI/CustomSvgIcons/Send';
import { FeedbackBanner } from './FeedbackBanner';
import classNames from 'classnames';
const TOO_MANY_USER_MESSAGES_WARNING_COUNT = 5;
const TOO_MANY_USER_MESSAGES_ERROR_COUNT = 10;
const styles = {
chatScrollView: {
display: 'flex',
flexDirection: 'column',
paddingLeft: 8,
paddingRight: 8,
paddingBottom: 8,
paddingTop: 14,
maskImage: 'linear-gradient(to bottom, transparent, black 14px)',
maskSize: '100% 100%',
maskRepeat: 'no-repeat',
},
};
type Props = {
project: gdProject | null,
i18n: I18nType,
aiRequest: AiRequest | null,
isSending: boolean,
onStartNewAiRequest: (options: {|
userRequest: string,
mode: 'chat' | 'agent',
|}) => void,
onSendMessage: (options: {|
userMessage: string,
|}) => Promise<void>,
onSendFeedback: (
aiRequestId: string,
messageIndex: number,
feedback: 'like' | 'dislike',
reason?: string,
freeFormDetails?: string
) => Promise<void>,
hasOpenedProject: boolean,
isAutoProcessingFunctionCalls: boolean,
setAutoProcessFunctionCalls: boolean => void,
onStartNewChat: () => void,
onProcessFunctionCalls: (
functionCalls: Array<AiRequestMessageAssistantFunctionCall>,
options: ?{| ignore?: boolean |}
) => Promise<void>,
editorFunctionCallResults: Array<EditorFunctionCallResult> | null,
editorCallbacks: EditorCallbacks,
// Error that occurred while sending the last request.
lastSendError: ?Error,
// Quota available for using the feature.
quota: Quota | null,
increaseQuotaOffering: 'subscribe' | 'upgrade' | 'none',
price: UsagePrice | null,
availableCredits: number,
};
export type AiRequestChatInterface = {|
resetUserInput: (aiRequestId: string | null) => void,
|};
const getQuotaOrCreditsText = ({
quota,
increaseQuotaOffering,
price,
availableCredits,
isMobile,
}: {|
quota: Quota | null,
increaseQuotaOffering: 'subscribe' | 'upgrade' | 'none',
price: UsagePrice | null,
availableCredits: number,
isMobile: boolean,
|}) => {
if (!quota) return null;
const quotaOrCreditsText = !quota.limitReached ? (
<Tooltip
title={
<>
{increaseQuotaOffering === 'subscribe' ? (
<Trans>
Get GDevelop premium to get more free requests every month.
</Trans>
) : (
<Trans>
These are parts of your GDevelop premium membership ({quota.max}{' '}
free requests per month).
</Trans>
)}{' '}
<Trans>Free requests do not consume credits on your account.</Trans>
</>
}
>
<div>
{isMobile ? (
<Trans>{quota.max - quota.current} free requests left</Trans>
) : (
<Trans>
{quota.max - quota.current} of {quota.max} free requests left this
month
</Trans>
)}
</div>
</Tooltip>
) : (
<Trans>{Math.max(0, availableCredits)} credits available</Trans>
);
return quotaOrCreditsText;
};
const getPriceText = ({
aiRequestMode,
price,
lastUserMessagePriceInCredits,
}: {|
aiRequestMode: 'chat' | 'agent',
price: UsagePrice | null,
lastUserMessagePriceInCredits: number | null,
|}) => {
if (!price) return null;
const priceInCredits = price.priceInCredits;
const maximumPriceInCredits =
(price.variablePrice &&
price.variablePrice[aiRequestMode] &&
price.variablePrice[aiRequestMode]['default'] &&
price.variablePrice[aiRequestMode]['default'].maximumPriceInCredits) ||
null;
const minimumPriceInCredits =
(price.variablePrice &&
price.variablePrice[aiRequestMode] &&
price.variablePrice[aiRequestMode]['default'] &&
price.variablePrice[aiRequestMode]['default'].minimumPriceInCredits) ||
null;
const priceText = maximumPriceInCredits ? (
<Trans>
{minimumPriceInCredits || priceInCredits} to {maximumPriceInCredits}
</Trans>
) : (
<Trans>{minimumPriceInCredits || priceInCredits}</Trans>
);
return (
<Tooltip
title={
aiRequestMode === 'agent' ? (
<>
<Trans>
Each request to the AI agent costs {priceText} credits. It depends
on the amount of work the agent will do and the number of times it
generates events.
</Trans>{' '}
{lastUserMessagePriceInCredits ? (
<Trans>
The last request used {lastUserMessagePriceInCredits} credits.
</Trans>
) : null}
</>
) : (
<Trans>Each answer from the AI costs {priceText} credits.</Trans>
)
}
>
<div>
<LineStackLayout alignItems="center" noMargin>
{aiRequestMode === 'agent' ? (
<Hammer fontSize="small" />
) : (
<Help fontSize="small" />
)}
{aiRequestMode === 'agent' ? (
<Trans>{priceText} credits/request</Trans>
) : (
<Trans>{priceText} credits/answer</Trans>
)}
</LineStackLayout>
</div>
</Tooltip>
);
};
export const AiRequestChat = React.forwardRef<Props, AiRequestChatInterface>(
(
{
project,
aiRequest,
isSending,
onStartNewAiRequest,
onSendMessage,
onSendFeedback,
onStartNewChat,
quota,
increaseQuotaOffering,
lastSendError,
price,
availableCredits,
hasOpenedProject,
editorFunctionCallResults,
onProcessFunctionCalls,
isAutoProcessingFunctionCalls,
setAutoProcessFunctionCalls,
i18n,
editorCallbacks,
}: Props,
ref
) => {
// TODO: store the default mode in the user preferences?
const [newAiRequestMode, setNewAiRequestMode] = React.useState<
'chat' | 'agent'
>('agent');
const aiRequestId: string = aiRequest ? aiRequest.id : '';
const [
userRequestTextPerAiRequestId,
setUserRequestTextPerRequestId,
] = React.useState<{ [string]: string }>({});
const scrollViewRef = React.useRef<ScrollViewInterface | null>(null);
const requiredGameId = (aiRequest && aiRequest.gameId) || null;
const newChatPlaceholder = React.useMemo(
() => {
const newChatPlaceholders: Array<MessageDescriptor> =
newAiRequestMode === 'agent'
? hasOpenedProject
? [
t`Add solid rocks that falls from the sky at a random position around the player every 0.5 seconds`,
t`Add a score and display it on the screen`,
t`Create a 3D explosion when the player is hit`,
]
: [
t`Build a platformer game with a score and coins to collect`,
t`Make a quizz game with a question and 4 answers`,
t`Make a game where the player must avoid obstacles`,
]
: [
t`How to add a leaderboard?`,
t`How to display the health of my player?`,
t`How to add an explosion when an enemy is destroyed?`,
t`How to create a main menu for my game?`,
...(hasOpenedProject
? [
t`What would you add to my game?`,
t`How to make my game more fun?`,
t`What is a good GDevelop feature I could use in my game?`,
]
: []),
];
return newChatPlaceholders[
Math.floor(Math.random() * newChatPlaceholders.length)
];
},
[newAiRequestMode, hasOpenedProject]
);
React.useImperativeHandle(ref, () => ({
resetUserInput: (aiRequestId: string | null) => {
const aiRequestIdToReset: string = aiRequestId || '';
setUserRequestTextPerRequestId(userRequestTextPerAiRequestId => ({
...userRequestTextPerAiRequestId,
[aiRequestIdToReset]: '',
}));
if (scrollViewRef.current) {
scrollViewRef.current.scrollToBottom({
behavior: 'smooth',
});
}
},
}));
const { isMobile } = useResponsiveWindowSize();
const priceText = (
<Text size="body-small" color="secondary" noMargin>
{getPriceText({
aiRequestMode: aiRequest
? aiRequest.mode || 'chat'
: newAiRequestMode,
price,
lastUserMessagePriceInCredits:
(aiRequest && aiRequest.lastUserMessagePriceInCredits) || null,
}) || '\u00A0'}
</Text>
);
const subscriptionBanner =
quota && quota.limitReached && increaseQuotaOffering !== 'none' ? (
<GetSubscriptionCard
placementId="ai-requests"
subscriptionDialogOpeningReason={
increaseQuotaOffering === 'subscribe'
? 'AI requests (subscribe)'
: 'AI requests (upgrade)'
}
label={
increaseQuotaOffering === 'subscribe' ? (
<Trans>Get GDevelop premium</Trans>
) : (
<Trans>Upgrade</Trans>
)
}
recommendedPlanIdIfNoSubscription="gdevelop_gold"
canHide
>
<Line>
<Column noMargin>
<Text noMargin>
{increaseQuotaOffering === 'subscribe' ? (
<Trans>
Unlock AI requests included with a GDevelop premium plan.
</Trans>
) : (
<Trans>
Get even more AI requests included with a higher premium
plan.
</Trans>
)}
</Text>
</Column>
</Line>
</GetSubscriptionCard>
) : null;
const errorText = lastSendError ? (
<Text size="body-small" color="error" noMargin>
<Trans>
An error happened when sending your request, please try again.
</Trans>
</Text>
) : null;
const quotaOrCreditsText = (
<Text size="body-small" color="secondary" noMargin>
{getQuotaOrCreditsText({
quota,
increaseQuotaOffering,
price,
availableCredits,
isMobile,
})}
</Text>
);
if (!aiRequest) {
return (
<div
className={classNames({
[classes.newChatContainer]: true,
// Move the entire screen up when the soft keyboard is open:
'avoid-soft-keyboard': true,
})}
>
<ColumnStackLayout justifyContent="center" expand>
<Line noMargin justifyContent="center">
<RobotIcon rotating size={40} />
</Line>
<Column noMargin alignItems="center">
<Text size="bold-title">
{newAiRequestMode === 'agent' ? (
<Trans>What do you want to make?</Trans>
) : (
<Trans>Ask any gamedev question</Trans>
)}
</Text>
</Column>
<Line noMargin justifyContent="center">
<TwoStatesButton
value={newAiRequestMode}
leftButton={{
icon: <Hammer fontSize="small" />,
label: <Trans>Build for me (beta)</Trans>,
value: 'agent',
}}
rightButton={{
icon: <Help fontSize="small" />,
label: <Trans>Ask a question</Trans>,
value: 'chat',
}}
onChange={value => {
if (value !== 'chat' && value !== 'agent') {
return;
}
setNewAiRequestMode(value);
}}
/>
</Line>
<form
onSubmit={() => {
onStartNewAiRequest({
mode: newAiRequestMode,
userRequest: userRequestTextPerAiRequestId[''],
});
}}
>
<ColumnStackLayout justifyContent="center" noMargin>
<Column noMargin alignItems="stretch" justifyContent="stretch">
<Spacer />
<CompactTextAreaFieldWithControls
maxLength={6000}
value={userRequestTextPerAiRequestId[''] || ''}
disabled={isSending}
hasNeonCorner
hasAnimatedNeonCorner={isSending}
errored={!!lastSendError}
onChange={userRequestText =>
setUserRequestTextPerRequestId(
userRequestTextPerAiRequestId => ({
...userRequestTextPerAiRequestId,
'': userRequestText,
})
)
}
onSubmit={() => {
onStartNewAiRequest({
mode: newAiRequestMode,
userRequest: userRequestTextPerAiRequestId[''],
});
}}
placeholder={newChatPlaceholder}
rows={5}
controls={
<Column>
<LineStackLayout
alignItems="center"
justifyContent="flex-end"
>
<RaisedButton
color="primary"
icon={<Send />}
label={
newAiRequestMode === 'agent' ? (
hasOpenedProject ? (
<Trans>Build this on my game</Trans>
) : (
<Trans>Start building the game</Trans>
)
) : (
<Trans>Send question</Trans>
)
}
style={{ flexShrink: 0 }}
disabled={
isSending ||
!userRequestTextPerAiRequestId[aiRequestId]
}
onClick={() => {
onStartNewAiRequest({
mode: newAiRequestMode,
userRequest: userRequestTextPerAiRequestId[''],
});
}}
/>
</LineStackLayout>
</Column>
}
/>
</Column>
<Line noMargin>
<LineStackLayout
noMargin
alignItems="center"
justifyContent="space-between"
expand
>
{errorText || priceText}
{errorText ? null : quotaOrCreditsText}
</LineStackLayout>
</Line>
</ColumnStackLayout>
</form>
{subscriptionBanner ? (
<>
<Spacer />
{subscriptionBanner}
</>
) : null}
</ColumnStackLayout>
<Column justifyContent="center">
{newAiRequestMode === 'agent' ? (
<Text size="body-small" color="secondary" align="center" noMargin>
<Trans>
The AI agent will build simple games or features for you.{' '}
<Link
href={getHelpLink('/interface/ai')}
color="secondary"
onClick={() =>
Window.openExternalURL(getHelpLink('/interface/ai'))
}
>
It can inspect your game objects and events.
</Link>
</Trans>
</Text>
) : (
<Text size="body-small" color="secondary" align="center" noMargin>
<Trans>
The AI chat is experimental and still being improved.{' '}
<Link
href={getHelpLink('/interface/ai')}
color="secondary"
onClick={() =>
Window.openExternalURL(getHelpLink('/interface/ai'))
}
>
It has access to your game objects but not events.
</Link>
</Trans>
</Text>
)}
{newAiRequestMode === 'agent' ? (
<Text size="body-small" color="secondary" align="center" noMargin>
<Trans>
Results may vary: experiment and use it for learning.
</Trans>
</Text>
) : (
<Text size="body-small" color="secondary" align="center" noMargin>
<Trans>Answers may have mistakes: always verify them.</Trans>
</Text>
)}
</Column>
</div>
);
}
const userMessagesCount = aiRequest.output.filter(
message => message.type === 'message' && message.role === 'user'
).length;
const hasWorkingFunctionCalls =
editorFunctionCallResults &&
editorFunctionCallResults.some(
functionCallOutput => functionCallOutput.status === 'working'
);
const allFunctionCallsToProcess = getFunctionCallsToProcess({
aiRequest,
editorFunctionCallResults,
});
const isPausedAndHasFunctionCallsToProcess =
!isAutoProcessingFunctionCalls && allFunctionCallsToProcess.length > 0;
const lastMessageIndex = aiRequest.output.length - 1;
const lastMessage = aiRequest.output[lastMessageIndex];
const shouldDisplayFeedbackBanner =
!hasWorkingFunctionCalls &&
!isPausedAndHasFunctionCallsToProcess &&
!isSending &&
aiRequest.status === 'ready' &&
aiRequest.mode === 'agent' &&
lastMessage.type === 'message' &&
lastMessage.role === 'assistant';
const lastMessageFeedbackBanner = shouldDisplayFeedbackBanner && (
<FeedbackBanner
onSendFeedback={(
feedback: 'like' | 'dislike',
reason?: string,
freeFormDetails?: string
) => {
onSendFeedback(
aiRequestId,
lastMessageIndex,
feedback,
reason,
freeFormDetails
);
}}
/>
);
const isForAnotherProject =
!!requiredGameId &&
(!project || requiredGameId !== project.getProjectUuid());
const isForAnotherProjectText = isForAnotherProject ? (
<Text size="body-small" color="secondary" align="center" noMargin>
<Trans>
This request is for another project.{' '}
<Link href="#" onClick={onStartNewChat}>
Start a new chat
</Link>{' '}
to build on a new project.
</Trans>
</Text>
) : null;
return (
<div
className={classNames({
[classes.aiRequestChatContainer]: true,
})}
>
<ScrollView ref={scrollViewRef} style={styles.chatScrollView}>
<ChatMessages
aiRequest={aiRequest}
onSendFeedback={onSendFeedback}
editorFunctionCallResults={editorFunctionCallResults}
editorCallbacks={editorCallbacks}
project={project}
onProcessFunctionCalls={onProcessFunctionCalls}
/>
<Spacer />
<ColumnStackLayout noMargin>
{lastMessageFeedbackBanner}
{userMessagesCount >= TOO_MANY_USER_MESSAGES_WARNING_COUNT ? (
<AlertMessage
kind={
userMessagesCount >= TOO_MANY_USER_MESSAGES_ERROR_COUNT
? 'error'
: 'warning'
}
>
<Trans>
The chat is becoming long - consider creating a new chat to
ask other questions. The AI will better analyze your game and
request in a new chat.
</Trans>
</AlertMessage>
) : (
subscriptionBanner
)}
</ColumnStackLayout>
</ScrollView>
<form
onSubmit={() => {
onSendMessage({
userMessage: userRequestTextPerAiRequestId[aiRequestId] || '',
});
}}
className={classNames({
// Move the form up when the soft keyboard is open:
'avoid-soft-keyboard': true,
})}
>
<ColumnStackLayout
justifyContent="stretch"
alignItems="stretch"
noMargin
>
{aiRequest.mode === 'agent' &&
isAutoProcessingFunctionCalls &&
(hasWorkingFunctionCalls ||
isSending ||
aiRequest.status === 'working') ? (
<Paper background="dark" variant="outlined">
<Column>
<LineStackLayout
justifyContent="space-between"
alignItems="center"
>
<LineStackLayout alignItems="center" noMargin>
<CircularProgress variant="indeterminate" size={12} />
<Text size="body" color="secondary" noMargin>
<Trans>The AI is building your request.</Trans>
</Text>
</LineStackLayout>
<Text size="body" noMargin>
<Link
href={'#'}
color="secondary"
onClick={() => {
setAutoProcessFunctionCalls(false);
}}
>
<Trans>Pause</Trans>
</Link>
</Text>
</LineStackLayout>
</Column>
</Paper>
) : aiRequest.mode === 'agent' &&
isPausedAndHasFunctionCallsToProcess ? (
<Paper background="dark" variant="outlined">
<Column>
<LineStackLayout
justifyContent="space-between"
alignItems="center"
>
<LineStackLayout alignItems="center" noMargin>
<Text size="body" color="secondary" noMargin>
<Trans>The AI agent is paused.</Trans>
</Text>
</LineStackLayout>
<Text size="body" noMargin>
<Link
href={'#'}
color="secondary"
onClick={() => {
setAutoProcessFunctionCalls(true);
onProcessFunctionCalls(allFunctionCallsToProcess);
}}
>
<Trans>Resume all</Trans>
</Link>
</Text>
</LineStackLayout>
</Column>
</Paper>
) : null}
<CompactTextAreaFieldWithControls
maxLength={6000}
value={userRequestTextPerAiRequestId[aiRequestId] || ''}
disabled={isSending || isForAnotherProject}
errored={!!lastSendError}
hasNeonCorner
hasAnimatedNeonCorner={isSending}
onChange={userRequestText =>
setUserRequestTextPerRequestId(
userRequestTextPerAiRequestId => ({
...userRequestTextPerAiRequestId,
[aiRequestId]: userRequestText,
})
)
}
placeholder={
aiRequest.mode === 'agent'
? isForAnotherProject
? t`You must re-open the project to continue this chat.`
: t`Specify something more to the AI to build`
: t`Ask a follow up question`
}
rows={2}
onSubmit={() => {
onSendMessage({
userMessage: userRequestTextPerAiRequestId[aiRequestId] || '',
});
}}
controls={
<Column>
<LineStackLayout
alignItems="center"
justifyContent="flex-end"
>
<RaisedButton
color="primary"
disabled={
aiRequest.status === 'working' ||
isSending ||
isForAnotherProject ||
!userRequestTextPerAiRequestId[aiRequestId]
}
icon={<Send />}
onClick={() => {
onSendMessage({
userMessage:
userRequestTextPerAiRequestId[aiRequestId] || '',
});
}}
/>
</LineStackLayout>
</Column>
}
/>
<Column noMargin alignItems="stretch">
<LineStackLayout
expand
noMargin
alignItems="center"
justifyContent="space-between"
>
{isForAnotherProjectText || errorText || priceText}
{errorText || isForAnotherProjectText
? null
: quotaOrCreditsText}
</LineStackLayout>
</Column>
</ColumnStackLayout>
</form>
</div>
);
}
);

File diff suppressed because it is too large Load Diff

View File

@@ -1,146 +0,0 @@
// @flow
import React from 'react';
import { I18n } from '@lingui/react';
import { type I18n as I18nType } from '@lingui/core';
import { Trans } from '@lingui/macro';
import EmptyAndStartingPointProjects from '../ProjectCreation/EmptyAndStartingPointProjects';
import { ColumnStackLayout } from '../UI/Layout';
import FlatButton from '../UI/FlatButton';
import Dialog from '../UI/Dialog';
import { type ExampleShortHeader } from '../Utils/GDevelopServices/Example';
import UrlStorageProvider from '../ProjectsStorage/UrlStorageProvider';
import { generateProjectName } from '../ProjectCreation/NewProjectSetupDialog';
import { type NewProjectSetup } from '../ProjectCreation/NewProjectSetupDialog';
import { Spacer } from '../UI/Grid';
type RenderCreateAiProjectDialogProps = {
onCreateEmptyProject: (newProjectSetup: NewProjectSetup) => Promise<void>,
onCreateProjectFromExample: (
exampleShortHeader: ExampleShortHeader,
newProjectSetup: NewProjectSetup,
i18n: I18nType,
isQuickCustomization?: boolean
) => Promise<void>,
};
type CreateAiProjectDialogProps = {
onClose: () => void,
onSelectExampleShortHeader: (
exampleShortHeader: ExampleShortHeader
) => Promise<void>,
onSelectEmptyProject: () => Promise<void>,
};
const CreateAiProjectDialog = ({
onClose,
onSelectExampleShortHeader,
onSelectEmptyProject,
}: CreateAiProjectDialogProps) => {
return (
<Dialog
open
title={<Trans>Ok! Choose a game style to start with</Trans>}
id="ai-project-dialog"
maxWidth="md"
actions={[
<FlatButton
key="cancel"
label={<Trans>Cancel</Trans>}
onClick={onClose}
/>,
]}
onRequestClose={onClose}
flexColumnBody
>
<ColumnStackLayout noMargin>
<Spacer />
<EmptyAndStartingPointProjects
onSelectExampleShortHeader={exampleShortHeader => {
onSelectExampleShortHeader(exampleShortHeader);
}}
onSelectEmptyProject={() => {
onSelectEmptyProject();
}}
/>
{/* Use a spacer to avoid extra scrollbars when template tiles are hovered. */}
<Spacer />
</ColumnStackLayout>
</Dialog>
);
};
type CreateAiProjectResult = 'canceled' | 'created';
export const useCreateAiProjectDialog = () => {
const [createPromise, setCreatePromise] = React.useState<null | {|
onFinished: (result: CreateAiProjectResult) => void,
promise: Promise<CreateAiProjectResult>,
|}>(null);
const createAiProject: () => Promise<CreateAiProjectResult> = React.useCallback(
() => {
if (createPromise) {
return createPromise.promise;
}
// Make a promise that we can resolve later from the creation dialog.
let resolve: (result: CreateAiProjectResult) => void = () => {};
const promise = new Promise(resolveFn => {
resolve = resolveFn;
});
setCreatePromise({
onFinished: (result: CreateAiProjectResult) => {
setCreatePromise(null);
resolve(result);
},
promise,
});
return promise;
},
[createPromise]
);
return {
createAiProject,
renderCreateAiProjectDialog: (props: RenderCreateAiProjectDialogProps) => {
if (!createPromise) return null;
return (
<I18n>
{({ i18n }) => (
<CreateAiProjectDialog
onClose={() => {
createPromise.onFinished('canceled');
}}
onSelectExampleShortHeader={async exampleShortHeader => {
const newProjectSetup: NewProjectSetup = {
storageProvider: UrlStorageProvider,
saveAsLocation: null,
dontOpenAnySceneOrProjectManager: true,
};
await props.onCreateProjectFromExample(
exampleShortHeader,
newProjectSetup,
i18n,
false // isQuickCustomization
);
createPromise.onFinished('created');
}}
onSelectEmptyProject={async () => {
await props.onCreateEmptyProject({
projectName: generateProjectName('AI starter'),
storageProvider: UrlStorageProvider,
saveAsLocation: null,
dontOpenAnySceneOrProjectManager: true,
});
createPromise.onFinished('created');
}}
/>
)}
</I18n>
);
},
};
};

View File

@@ -1,54 +0,0 @@
// @flow
import * as React from 'react';
import { type I18n as I18nType } from '@lingui/core';
import { ExtensionStoreContext } from '../AssetStore/ExtensionStore/ExtensionStoreContext';
import EventsFunctionsExtensionsContext from '../EventsFunctionsExtensionsLoader/EventsFunctionsExtensionsContext';
import { installExtension } from '../AssetStore/ExtensionStore/InstallExtension';
type EnsureExtensionInstalledOptions = {|
extensionName: string,
|};
export const useEnsureExtensionInstalled = ({
project,
i18n,
}: {|
project: ?gdProject,
i18n: I18nType,
|}) => {
const { translatedExtensionShortHeadersByName } = React.useContext(
ExtensionStoreContext
);
const eventsFunctionsExtensionsState = React.useContext(
EventsFunctionsExtensionsContext
);
return {
ensureExtensionInstalled: React.useCallback(
async ({ extensionName }: EnsureExtensionInstalledOptions) => {
if (!project) return;
if (project.getCurrentPlatform().isExtensionLoaded(extensionName))
return;
const extensionShortHeader =
translatedExtensionShortHeadersByName[extensionName];
if (!extensionShortHeader) {
throw new Error(`Can't find extension named ${extensionName}.`);
}
await installExtension(
i18n,
project,
eventsFunctionsExtensionsState,
extensionShortHeader
);
},
[
eventsFunctionsExtensionsState,
i18n,
project,
translatedExtensionShortHeadersByName,
]
),
};
};

View File

@@ -1,107 +0,0 @@
// @flow
import * as React from 'react';
import AuthenticatedUserContext from '../Profile/AuthenticatedUserContext';
import { retryIfFailed } from '../Utils/RetryIfFailed';
import { delay } from '../Utils/Delay';
import {
getAiGeneratedEvent,
createAiGeneratedEvent,
} from '../Utils/GDevelopServices/Generation';
import { type EventsGenerationResult } from '../EditorFunctions';
import { makeSimplifiedProjectBuilder } from '../EditorFunctions/SimplifiedProject/SimplifiedProject';
const gd: libGDevelop = global.gd;
export const useGenerateEvents = ({ project }: {| project: ?gdProject |}) => {
const { profile, getAuthorizationHeader } = React.useContext(
AuthenticatedUserContext
);
const generateEvents = React.useCallback(
async ({
sceneName,
eventsDescription,
extensionNamesList,
objectsList,
existingEventsAsText,
placementHint,
relatedAiRequestId,
}: {|
sceneName: string,
eventsDescription: string,
extensionNamesList: string,
objectsList: string,
existingEventsAsText: string,
placementHint: string,
relatedAiRequestId: string,
|}): Promise<EventsGenerationResult> => {
if (!project) throw new Error('No project is opened.');
if (!profile) throw new Error('User should be authenticated.');
const simplifiedProjectBuilder = makeSimplifiedProjectBuilder(gd);
const projectSpecificExtensionsSummaryJson = JSON.stringify(
simplifiedProjectBuilder.getProjectSpecificExtensionsSummary(project)
);
const createResult = await retryIfFailed({ times: 2 }, () =>
createAiGeneratedEvent(getAuthorizationHeader, {
userId: profile.id,
partialGameProjectJson: JSON.stringify(
simplifiedProjectBuilder.getSimplifiedProject(project, {
scopeToScene: sceneName,
}),
null,
2
),
projectSpecificExtensionsSummaryJson,
sceneName,
eventsDescription,
extensionNamesList,
objectsList,
existingEventsAsText,
placementHint,
relatedAiRequestId,
})
);
if (!createResult.creationSucceeded) {
return {
generationCompleted: false,
errorMessage: createResult.errorMessage,
};
}
let remainingAttempts = 50;
let aiGeneratedEvent = createResult.aiGeneratedEvent;
while (aiGeneratedEvent.status === 'working') {
remainingAttempts--;
await delay(1000);
try {
aiGeneratedEvent = await getAiGeneratedEvent(getAuthorizationHeader, {
userId: profile.id,
aiGeneratedEventId: aiGeneratedEvent.id,
});
} catch (error) {
console.warn(
'Error while checking status of AI generated event - continuing...',
error
);
}
if (remainingAttempts <= 0) {
return {
generationCompleted: false,
errorMessage:
'Event generation started but failed to complete in time.',
};
}
}
return { generationCompleted: true, aiGeneratedEvent };
},
[getAuthorizationHeader, project, profile]
);
return { generateEvents };
};

View File

@@ -1,85 +0,0 @@
// @flow
import * as React from 'react';
import {
type AssetSearchAndInstallOptions,
type AssetSearchAndInstallResult,
} from '../EditorFunctions';
import AuthenticatedUserContext from '../Profile/AuthenticatedUserContext';
import {
createAssetSearch,
type AssetSearch,
} from '../Utils/GDevelopServices/Generation';
import { retryIfFailed } from '../Utils/RetryIfFailed';
import { useInstallAsset } from '../AssetStore/NewObjectDialog';
import { type ResourceManagementProps } from '../ResourcesList/ResourceSource';
export const useSearchAndInstallAsset = ({
project,
resourceManagementProps,
onExtensionInstalled,
}: {|
project: gdProject | null,
resourceManagementProps: ResourceManagementProps,
onExtensionInstalled: (extensionNames: Array<string>) => void,
|}) => {
const { profile, getAuthorizationHeader } = React.useContext(
AuthenticatedUserContext
);
const installAsset = useInstallAsset({
project,
resourceManagementProps,
onExtensionInstalled,
});
return {
searchAndInstallAsset: React.useCallback(
async ({
scene,
objectName,
...assetSearchOptions
}: AssetSearchAndInstallOptions): Promise<AssetSearchAndInstallResult> => {
if (!profile) throw new Error('User should be authenticated.');
const assetSearch: AssetSearch = await retryIfFailed({ times: 2 }, () =>
createAssetSearch(getAuthorizationHeader, {
userId: profile.id,
...assetSearchOptions,
})
);
if (!assetSearch.results || assetSearch.results.length === 0) {
return {
status: 'nothing-found',
message: 'No assets found.',
createdObjects: [],
};
}
// In the future, we could ask the user to select the asset they want to use.
// For now, we just return the first asset.
const chosenResult = assetSearch.results[0];
if (!chosenResult) throw new Error('No asset found.');
const installOutput = await installAsset({
assetShortHeader: chosenResult.asset,
objectsContainer: scene.getObjects(),
requestedObjectName: objectName,
});
if (!installOutput) {
return {
status: 'error',
message: 'Asset found but failed to install asset.',
createdObjects: [],
};
}
return {
status: 'asset-installed',
message: 'Asset installed successfully.',
createdObjects: installOutput.createdObjects,
};
},
[installAsset, profile, getAuthorizationHeader]
),
};
};

View File

@@ -49,7 +49,6 @@ type Props = {|
addedAssetIds: Set<string>,
onClose: () => void,
onAssetsAdded: (createdObjects: gdObject[]) => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
project: gdProject,
objectsContainer: ?gdObjectsContainer,
resourceManagementProps: ResourceManagementProps,
@@ -62,7 +61,6 @@ const AssetPackInstallDialog = ({
addedAssetIds,
onClose,
onAssetsAdded,
onExtensionInstalled,
project,
objectsContainer,
resourceManagementProps,
@@ -161,24 +159,17 @@ const AssetPackInstallDialog = ({
project,
}
);
const extensionUpdateAction =
requiredExtensionInstallation.outOfDateExtensionShortHeaders
.length === 0
? 'skip'
: await showExtensionUpdateConfirmation({
project,
outOfDateExtensionShortHeaders:
requiredExtensionInstallation.outOfDateExtensionShortHeaders,
});
if (extensionUpdateAction === 'abort') {
return;
}
const shouldUpdateExtension =
requiredExtensionInstallation.outOfDateExtensionShortHeaders.length >
0 &&
(await showExtensionUpdateConfirmation(
requiredExtensionInstallation.outOfDateExtensionShortHeaders
));
await installRequiredExtensions({
requiredExtensionInstallation,
shouldUpdateExtension: extensionUpdateAction === 'update',
shouldUpdateExtension,
eventsFunctionsExtensionsState,
project,
onExtensionInstalled,
});
// Use a pool to avoid installing an unbounded amount of assets at the same time.
@@ -256,7 +247,6 @@ const AssetPackInstallDialog = ({
eventsFunctionsExtensionsState,
resourceManagementProps,
onAssetsAdded,
onExtensionInstalled,
installPrivateAsset,
targetObjectsContainer,
targetObjectFolderOrObjectWithContext,

View File

@@ -29,7 +29,6 @@ type Props = {|
onClose: ({ swappingDone: boolean }) => void,
// Use minimal UI to hide filters & the details page (useful for Quick Customization)
minimalUI?: boolean,
onExtensionInstalled: (extensionNames: Array<string>) => void,
|};
function AssetSwappingDialog({
@@ -41,7 +40,6 @@ function AssetSwappingDialog({
resourceManagementProps,
onClose,
minimalUI,
onExtensionInstalled,
}: Props) {
const shopNavigationState = React.useContext(AssetStoreNavigatorContext);
const { openedAssetShortHeader } = shopNavigationState.getCurrentPage();
@@ -52,8 +50,8 @@ function AssetSwappingDialog({
] = React.useState<boolean>(false);
const installAsset = useInstallAsset({
project,
objectsContainer,
resourceManagementProps,
onExtensionInstalled,
});
const { showAlert } = useAlertDialog();
@@ -75,10 +73,7 @@ function AssetSwappingDialog({
setIsAssetBeingInstalled(true);
try {
const installAssetOutput = await installAsset({
assetShortHeader: openedAssetShortHeader,
objectsContainer,
});
const installAssetOutput = await installAsset(openedAssetShortHeader);
if (!installAssetOutput) {
throw new Error('Failed to install asset');
}

View File

@@ -1,7 +1,6 @@
// @flow
import * as React from 'react';
import { type BehaviorShortHeader } from '../../Utils/GDevelopServices/Extension';
import { isCompatibleWithGDevelopVersion } from '../../Utils/Extension/ExtensionCompatibilityChecker.js';
import ButtonBase from '@material-ui/core/ButtonBase';
import Text from '../../UI/Text';
import { Trans } from '@lingui/macro';
@@ -11,10 +10,12 @@ import HighlightedText from '../../UI/Search/HighlightedText';
import { type SearchMatch } from '../../UI/Search/UseSearchStructuredItem';
import Chip from '../../UI/Chip';
import { LineStackLayout } from '../../UI/Layout';
import { type SearchableBehaviorMetadata } from './BehaviorStoreContext';
import { UserPublicProfileChip } from '../../UI/User/UserPublicProfileChip';
import Tooltip from '@material-ui/core/Tooltip';
import CircledInfo from '../../UI/CustomSvgIcons/SmallCircledInfo';
import IconButton from '../../UI/IconButton';
import semverSatisfies from 'semver/functions/satisfies';
import { getIDEVersion } from '../../Version';
const gd: libGDevelop = global.gd;
@@ -33,7 +34,7 @@ type Props = {|
id?: string,
objectType: string,
objectBehaviorsTypes: Array<string>,
behaviorShortHeader: BehaviorShortHeader,
behaviorShortHeader: BehaviorShortHeader | SearchableBehaviorMetadata,
matches: ?Array<SearchMatch>,
onChoose: () => void,
onShowDetails: () => void,
@@ -67,10 +68,11 @@ export const BehaviorListItem = ({
objectBehaviorsTypes.includes(requiredBehaviorType)
);
});
const isEngineCompatible = isCompatibleWithGDevelopVersion(
getIDEVersion(),
behaviorShortHeader.gdevelopVersion
);
const isEngineCompatible =
!behaviorShortHeader.gdevelopVersion ||
semverSatisfies(getIDEVersion(), behaviorShortHeader.gdevelopVersion, {
includePrerelease: true,
});
// Report the height of the item once it's known.
const containerRef = React.useRef<?HTMLDivElement>(null);

View File

@@ -22,15 +22,26 @@ const emptySearchText = '';
const noExcludedTiers = new Set();
const excludedCommunityTiers = new Set(['community']);
type TranslatedBehaviorShortHeader = {|
...BehaviorShortHeader,
englishFullName: string,
englishDescription: string,
export type SearchableBehaviorMetadata = {|
type: string,
fullName: string,
description: string,
objectType: string,
/**
* All required behaviors including transitive ones.
*/
allRequiredBehaviorTypes: Array<string>,
previewIconUrl: string,
category: string,
tags: string[],
isDeprecated?: boolean,
|};
type BehaviorStoreState = {|
filters: ?Filters,
searchResults: ?Array<SearchResult<BehaviorShortHeader>>,
searchResults: ?Array<
SearchResult<BehaviorShortHeader | SearchableBehaviorMetadata>
>,
fetchBehaviors: () => void,
error: ?Error,
searchText: string,
@@ -39,11 +50,9 @@ type BehaviorStoreState = {|
chosenCategory: string,
setChosenCategory: string => void,
setInstalledBehaviorMetadataList: (
installedBehaviorMetadataList: Array<BehaviorShortHeader>
installedBehaviorMetadataList: Array<SearchableBehaviorMetadata>
) => void,
translatedBehaviorShortHeadersByType: {
[name: string]: TranslatedBehaviorShortHeader,
},
translatedBehaviorShortHeadersByType: { [name: string]: BehaviorShortHeader },
filtersState: FiltersState,
|};
@@ -83,12 +92,12 @@ export const BehaviorStoreStateProvider = ({
const [
installedBehaviorMetadataList,
setInstalledBehaviorMetadataList,
] = React.useState<Array<BehaviorShortHeader>>([]);
] = React.useState<Array<SearchableBehaviorMetadata>>([]);
const [
translatedBehaviorShortHeadersByType,
setTranslatedBehaviorShortHeadersByType,
] = React.useState<{
[string]: TranslatedBehaviorShortHeader,
[string]: BehaviorShortHeader,
}>({});
const preferences = React.useContext(PreferencesContext);
@@ -130,12 +139,10 @@ export const BehaviorStoreStateProvider = ({
const translatedBehaviorShortHeadersByType = {};
behaviorShortHeaders.forEach(behaviorShortHeader => {
const translatedBehaviorShortHeader: TranslatedBehaviorShortHeader = {
const translatedBehaviorShortHeader: BehaviorShortHeader = {
...behaviorShortHeader,
fullName: i18n._(behaviorShortHeader.fullName),
description: i18n._(behaviorShortHeader.description),
englishFullName: behaviorShortHeader.fullName,
englishDescription: behaviorShortHeader.description,
};
translatedBehaviorShortHeadersByType[
behaviorShortHeader.type
@@ -209,76 +216,16 @@ export const BehaviorStoreStateProvider = ({
const allTranslatedBehaviors = React.useMemo(
() => {
const allTranslatedBehaviors: {
[name: string]: BehaviorShortHeader,
[name: string]: BehaviorShortHeader | SearchableBehaviorMetadata,
} = {};
for (const type in translatedBehaviorShortHeadersByType) {
const behaviorShortHeader: any = {
...translatedBehaviorShortHeadersByType[type],
};
delete behaviorShortHeader.englishFullName;
delete behaviorShortHeader.englishDescription;
allTranslatedBehaviors[type] = behaviorShortHeader;
allTranslatedBehaviors[type] =
translatedBehaviorShortHeadersByType[type];
}
for (const installedBehaviorMetadata of installedBehaviorMetadataList) {
const repositoryBehaviorMetadata =
translatedBehaviorShortHeadersByType[installedBehaviorMetadata.type];
const behaviorMetadata = repositoryBehaviorMetadata
? {
// Attributes from the extension repository
// These attributes are important for the installation and update workflow.
isInstalled: true,
tier: repositoryBehaviorMetadata.tier,
version: repositoryBehaviorMetadata.version,
changelog: repositoryBehaviorMetadata.changelog,
url: repositoryBehaviorMetadata.url,
// It gives info about the extension that can be displayed to users.
headerUrl: repositoryBehaviorMetadata.headerUrl,
authorIds: repositoryBehaviorMetadata.authorIds,
authors: repositoryBehaviorMetadata.authors,
// It's empty and not used.
extensionNamespace: repositoryBehaviorMetadata.extensionNamespace,
// Attributes from the installed extension
// New extension versions might require a different object.
// It must not forbid users to attach the behavior since their
// version allows it.
objectType: installedBehaviorMetadata.objectType,
allRequiredBehaviorTypes:
installedBehaviorMetadata.allRequiredBehaviorTypes,
// These ones are less important but its better to use the icon of
// the installed extension since it's used everywhere in the editor.
previewIconUrl: installedBehaviorMetadata.previewIconUrl,
category: installedBehaviorMetadata.category,
tags: installedBehaviorMetadata.tags,
// Both metadata are supposed to have the same type, but the
// installed ones are safer to use.
// It reduces the risk of accessing an extension that doesn't
// actually exist in the project.
type: installedBehaviorMetadata.type,
name: installedBehaviorMetadata.name,
extensionName: installedBehaviorMetadata.extensionName,
// Attributes switching between both
// Translations may not be relevant for the installed version.
// We use the translation only if the not translated texts match.
fullName:
installedBehaviorMetadata.fullName ===
repositoryBehaviorMetadata.englishFullName
? repositoryBehaviorMetadata.fullName
: installedBehaviorMetadata.fullName,
description:
installedBehaviorMetadata.description ===
repositoryBehaviorMetadata.englishDescription
? repositoryBehaviorMetadata.description
: installedBehaviorMetadata.description,
}
: installedBehaviorMetadata;
allTranslatedBehaviors[
installedBehaviorMetadata.type
] = behaviorMetadata;
] = installedBehaviorMetadata;
}
return allTranslatedBehaviors;
},
@@ -335,7 +282,7 @@ export const BehaviorStoreStateProvider = ({
);
const searchResults: ?Array<
SearchResult<BehaviorShortHeader>
SearchResult<BehaviorShortHeader | SearchableBehaviorMetadata>
> = useSearchStructuredItem(allTranslatedBehaviors, {
searchText,
chosenItemCategory: chosenCategory,

View File

@@ -1,12 +1,7 @@
// @flow
import { type I18n as I18nType } from '@lingui/core';
import * as React from 'react';
import semverGreaterThan from 'semver/functions/gt';
import SearchBar from '../../UI/SearchBar';
import {
getBreakingChanges,
isCompatibleWithGDevelopVersion,
} from '../../Utils/Extension/ExtensionCompatibilityChecker.js';
import { type BehaviorShortHeader } from '../../Utils/GDevelopServices/Extension';
import { BehaviorStoreContext } from './BehaviorStoreContext';
import { ListSearchResults } from '../../UI/Search/ListSearchResults';
@@ -21,31 +16,21 @@ import PreferencesContext from '../../MainFrame/Preferences/PreferencesContext';
import { ResponsiveLineStackLayout } from '../../UI/Layout';
import SearchBarSelectField from '../../UI/SearchBarSelectField';
import SelectOption from '../../UI/SelectOption';
import { type SearchableBehaviorMetadata } from './BehaviorStoreContext';
import ElementWithMenu from '../../UI/Menu/ElementWithMenu';
import IconButton from '../../UI/IconButton';
import ThreeDotsMenu from '../../UI/CustomSvgIcons/ThreeDotsMenu';
import useAlertDialog from '../../UI/Alert/useAlertDialog';
import ExtensionInstallDialog from '../ExtensionStore/ExtensionInstallDialog';
import { getIDEVersion } from '../../Version';
export const useExtensionUpdateAlertDialog = () => {
const { showConfirmation } = useAlertDialog();
return async (
project: gdProject,
behaviorShortHeader: BehaviorShortHeader
): Promise<boolean> => {
return async (): Promise<boolean> => {
return await showConfirmation({
title: t`Extension update`,
message:
behaviorShortHeader.tier === 'reviewed'
? // Reviewed extensions are closely watched
// and any breaking change will be added to the extension metadata.
t`This behavior can be updated with new features and fixes.${'\n\n'}Do you want to update it now ?`
: // Community extensions are checked as much as possible
// but we can't ensure every breaking changes will be added to the extension metadata.
t`This behavior can be updated. You may have to do some adaptations to make sure your game still works.${'\n\n'}Do you want to update it now ?`,
message: t`This behavior needs an extension update. You may have to do some adaptations to make sure your game still works.${'\n\n'}Do you want to update it now ?`,
confirmButtonLabel: t`Update the extension`,
dismissButtonLabel: t`Skip the update`,
dismissButtonLabel: t`Cancel`,
});
};
};
@@ -55,14 +40,15 @@ type Props = {|
project: gdProject,
objectType: string,
objectBehaviorsTypes: Array<string>,
installedBehaviorMetadataList: Array<BehaviorShortHeader>,
deprecatedBehaviorMetadataList: Array<BehaviorShortHeader>,
installedBehaviorMetadataList: Array<SearchableBehaviorMetadata>,
deprecatedBehaviorMetadataList: Array<SearchableBehaviorMetadata>,
onInstall: (behaviorShortHeader: BehaviorShortHeader) => Promise<boolean>,
onChoose: (behaviorType: string) => void,
|};
const getBehaviorType = (behaviorShortHeader: BehaviorShortHeader) =>
behaviorShortHeader.type;
const getBehaviorType = (
behaviorShortHeader: BehaviorShortHeader | SearchableBehaviorMetadata
) => behaviorShortHeader.type;
export const BehaviorStore = ({
isInstalling,
@@ -133,7 +119,9 @@ export const BehaviorStore = ({
);
const getExtensionsMatches = React.useCallback(
(extensionShortHeader: BehaviorShortHeader): SearchMatch[] => {
(
extensionShortHeader: BehaviorShortHeader | SearchableBehaviorMetadata
): SearchMatch[] => {
if (!searchResults) return [];
const extensionMatches = searchResults.find(
result => result.item.type === extensionShortHeader.type
@@ -150,60 +138,20 @@ export const BehaviorStore = ({
const showExtensionUpdateConfirmation = useExtensionUpdateAlertDialog();
const installAndChoose = React.useCallback(
async (behaviorShortHeader: BehaviorShortHeader) => {
if (behaviorShortHeader.tier === 'installed') {
// The extension is not in the repository.
// It's either built-in or user made.
// It can't be updated.
onChoose(behaviorShortHeader.type);
return;
}
async (
behaviorShortHeader: BehaviorShortHeader | SearchableBehaviorMetadata
) => {
const isExtensionAlreadyInstalled =
behaviorShortHeader.extensionName &&
project.hasEventsFunctionsExtensionNamed(
behaviorShortHeader.extensionName
);
if (isExtensionAlreadyInstalled) {
const installedVersion = project
.getEventsFunctionsExtension(behaviorShortHeader.extensionName)
.getVersion();
// repository version <= installed version
if (!semverGreaterThan(behaviorShortHeader.version, installedVersion)) {
// The extension is already up to date.
onChoose(behaviorShortHeader.type);
return;
}
if (
!isCompatibleWithGDevelopVersion(
getIDEVersion(),
behaviorShortHeader.gdevelopVersion
)
) {
// Don't suggest to update the extension if the editor can't understand it.
onChoose(behaviorShortHeader.type);
return;
}
const breakingChanges = getBreakingChanges(
installedVersion,
behaviorShortHeader
);
if (breakingChanges && breakingChanges.length > 0) {
// Don't suggest to update the extension if it would break the project.
onChoose(behaviorShortHeader.type);
return;
}
const shouldUpdateExtension = await showExtensionUpdateConfirmation(
project,
behaviorShortHeader
);
const shouldUpdateExtension = await showExtensionUpdateConfirmation();
if (!shouldUpdateExtension) {
onChoose(behaviorShortHeader.type);
return;
}
}
// Behaviors from the store that are not compatible with the editor are
// greyed out in the list and can't be chosen by users.
// No need to check `isCompatibleWithGDevelopVersion`.
if (behaviorShortHeader.url) {
sendExtensionAddedToProject(behaviorShortHeader.name);

View File

@@ -2,7 +2,7 @@
import { Trans } from '@lingui/macro';
import * as React from 'react';
import { type ExampleShortHeader } from '../../Utils/GDevelopServices/Example';
import { isCompatibleWithGDevelopVersion } from '../../Utils/Extension/ExtensionCompatibilityChecker.js';
import { isCompatibleWithGDevelopVersion } from '../../Utils/GDevelopServices/Asset';
import { MarkdownText } from '../../UI/MarkdownText';
import Text from '../../UI/Text';
import AlertMessage from '../../UI/AlertMessage';

View File

@@ -8,13 +8,8 @@ import {
type ExtensionHeader,
type BehaviorShortHeader,
getExtensionHeader,
isCompatibleWithExtension,
} from '../../Utils/GDevelopServices/Extension';
import {
getBreakingChanges,
formatOldBreakingChanges,
formatBreakingChanges,
isCompatibleWithGDevelopVersion,
} from '../../Utils/Extension/ExtensionCompatibilityChecker.js';
import LeftLoader from '../../UI/LeftLoader';
import PlaceholderLoader from '../../UI/PlaceholderLoader';
import PlaceholderError from '../../UI/PlaceholderError';
@@ -31,7 +26,6 @@ import Window from '../../Utils/Window';
import { useExtensionUpdate } from './UseExtensionUpdates';
import HelpButton from '../../UI/HelpButton';
import useAlertDialog from '../../UI/Alert/useAlertDialog';
import { Accordion, AccordionHeader, AccordionBody } from '../../UI/Accordion';
export const useOutOfDateAlertDialog = () => {
const { showConfirmation } = useAlertDialog();
@@ -90,21 +84,6 @@ const ExtensionInstallDialog = ({
? installedExtension.getOriginName() === 'gdevelop-extension-store'
: false;
const newBreakingChangesText = installedExtension
? formatBreakingChanges(
getBreakingChanges(
installedExtension.getVersion(),
extensionShortHeader
)
)
: null;
const oldBreakingChangesText = installedExtension
? formatOldBreakingChanges(
installedExtension.getVersion(),
extensionShortHeader
)
: null;
const extensionUpdate = useExtensionUpdate(project, extensionShortHeader);
const [error, setError] = React.useState<?Error>(null);
@@ -130,9 +109,9 @@ const ExtensionInstallDialog = ({
React.useEffect(() => loadExtensionheader(), [loadExtensionheader]);
const isCompatible = isCompatibleWithGDevelopVersion(
const isCompatible = isCompatibleWithExtension(
getIDEVersion(),
extensionShortHeader.gdevelopVersion
extensionShortHeader
);
const canInstallExtension = !isInstalling && isCompatible;
@@ -332,26 +311,6 @@ const ExtensionInstallDialog = ({
</Trans>
</PlaceholderError>
)}
{newBreakingChangesText && (
<>
<Text size="sub-title">
<Trans>Breaking changes</Trans>
</Text>
<MarkdownText source={newBreakingChangesText} isStandaloneText />
</>
)}
{oldBreakingChangesText && (
<Accordion noMargin>
<AccordionHeader noMargin>
<Text size="sub-title">
<Trans>Previous breaking changes (no longer relevant)</Trans>
</Text>
</AccordionHeader>
<AccordionBody disableGutters>
<MarkdownText source={oldBreakingChangesText} isStandaloneText />
</AccordionBody>
</Accordion>
)}
</ColumnStackLayout>
</Dialog>
);

View File

@@ -25,7 +25,7 @@ type Props = {|
project: gdProject,
onClose: () => void,
onInstallExtension: (extensionName: string) => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
onExtensionInstalled: (extensionName: string) => void,
onCreateNew?: () => void,
|};
@@ -84,7 +84,7 @@ const ExtensionsSearchDialog = ({
if (installedOrImportedExtensionName) {
setExtensionWasInstalled(true);
onExtensionInstalled([installedOrImportedExtensionName]);
onExtensionInstalled(installedOrImportedExtensionName);
return true;
}

View File

@@ -10,7 +10,6 @@ import { addSerializedExtensionsToProject } from '../InstallAsset';
import { type EventsFunctionsExtensionsState } from '../../EventsFunctionsExtensionsLoader/EventsFunctionsExtensionsContext';
import { t } from '@lingui/macro';
import Window from '../../Utils/Window';
import { retryIfFailed } from '../../Utils/RetryIfFailed';
/**
* Download and add the extension in the project.
@@ -22,9 +21,7 @@ export const installExtension = async (
extensionShortHeader: ExtensionShortHeader | BehaviorShortHeader
): Promise<boolean> => {
try {
const serializedExtension = await retryIfFailed({ times: 2 }, () =>
getExtension(extensionShortHeader)
);
const serializedExtension = await getExtension(extensionShortHeader);
await addSerializedExtensionsToProject(
eventsFunctionsExtensionsState,
project,

View File

@@ -4,6 +4,7 @@ import {
isPixelArt,
isPublicAssetResourceUrl,
extractDecodedFilenameWithExtensionFromPublicAssetResourceUrl,
isCompatibleWithGDevelopVersion,
} from '../Utils/GDevelopServices/Asset';
import { getIDEVersion } from '../Version';
import newNameGenerator from '../Utils/NewNameGenerator';
@@ -22,13 +23,37 @@ import { mapVector } from '../Utils/MapFor';
import { toNewGdMapStringString } from '../Utils/MapStringString';
import { getInsertionParentAndPositionFromSelection } from '../Utils/ObjectFolders';
import { allResourceKindsAndMetadata } from '../ResourcesList/ResourceSource';
import {
getBreakingChanges,
isCompatibleWithGDevelopVersion,
} from '../Utils/Extension/ExtensionCompatibilityChecker.js';
const gd: libGDevelop = global.gd;
const toPascalCase = (str: string) => {
if (!str) return '';
return str
.replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g, '$')
.replace(/[^A-Za-z0-9]+/g, '$')
.replace(/([a-z])([A-Z])/g, function(m, a, b) {
return a + '$' + b;
})
.toLowerCase()
.replace(/(\$)(\w?)/g, function(m, a, b) {
return b.toUpperCase();
});
};
export const sanitizeObjectName = (objectName: string) => {
const trimmedObjectName = objectName.trim();
if (!trimmedObjectName) return 'UnnamedObject';
const pascalCaseName = toPascalCase(trimmedObjectName);
let prefixedObjectName = pascalCaseName;
if (prefixedObjectName[0] >= '0' && prefixedObjectName[0] <= '9') {
prefixedObjectName = '_' + prefixedObjectName;
}
return prefixedObjectName;
};
/**
* Adds the specified resource to the resources manager, avoiding to duplicate
* if it was already added.
@@ -128,7 +153,6 @@ export type InstallAssetArgs = {|
project: gdProject,
objectsContainer: gdObjectsContainer,
targetObjectFolderOrObject?: ?gdObjectFolderOrObject,
requestedObjectName?: string,
|};
const findVariant = (
@@ -153,7 +177,6 @@ export const addAssetToProject = async ({
project,
objectsContainer,
targetObjectFolderOrObject,
requestedObjectName,
}: InstallAssetArgs): Promise<InstallAssetOutput> => {
const objectNewNames = {};
const resourceNewNames = {};
@@ -246,10 +269,8 @@ export const addAssetToProject = async ({
}
}
// Insert the object.
const originalName = gd.Project.getSafeName(
requestedObjectName || objectAsset.object.name
);
// Insert the object
const originalName = sanitizeObjectName(objectAsset.object.name);
const newName = newNameGenerator(originalName, name =>
objectsContainer.hasObjectNamed(name)
);
@@ -370,10 +391,7 @@ export type RequiredExtensionInstallation = {|
requiredExtensionShortHeaders: Array<ExtensionShortHeader>,
missingExtensionShortHeaders: Array<ExtensionShortHeader>,
outOfDateExtensionShortHeaders: Array<ExtensionShortHeader>,
breakingChangesExtensionShortHeaders: Array<ExtensionShortHeader>,
incompatibleWithIdeExtensionShortHeaders: Array<ExtensionShortHeader>,
safeToUpdateExtensions: Array<ExtensionShortHeader>,
isGDevelopUpdateNeeded: boolean,
|};
export type InstallRequiredExtensionsArgs = {|
@@ -381,7 +399,6 @@ export type InstallRequiredExtensionsArgs = {|
shouldUpdateExtension: boolean,
eventsFunctionsExtensionsState: EventsFunctionsExtensionsState,
project: gdProject,
onExtensionInstalled: (extensionNames: Array<string>) => void,
|};
export const installRequiredExtensions = async ({
@@ -389,7 +406,6 @@ export const installRequiredExtensions = async ({
shouldUpdateExtension,
eventsFunctionsExtensionsState,
project,
onExtensionInstalled,
}: InstallRequiredExtensionsArgs): Promise<void> => {
const {
requiredExtensionShortHeaders,
@@ -419,9 +435,6 @@ export const installRequiredExtensions = async ({
project,
serializedExtensions
);
onExtensionInstalled(
neededExtensions.map(extensionShortHeader => extensionShortHeader.name)
);
const stillMissingExtensions = filterMissingExtensions(
gd,
@@ -496,10 +509,7 @@ export const checkRequiredExtensionsUpdate = async ({
requiredExtensionShortHeaders: [],
missingExtensionShortHeaders: [],
outOfDateExtensionShortHeaders: [],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: false,
};
}
@@ -524,15 +534,24 @@ export const checkRequiredExtensionsUpdate = async ({
}
);
const incompatibleWithIdeExtensionShortHeaders = requiredExtensionShortHeaders.filter(
requiredExtensionShortHeader =>
!isCompatibleWithGDevelopVersion(
const compatibleWithIdeExtensionShortHeaders: Array<ExtensionShortHeader> = [];
const incompatibleWithIdeExtensionShortHeaders: Array<ExtensionShortHeader> = [];
for (const requiredExtensionShortHeader of requiredExtensionShortHeaders) {
if (
isCompatibleWithGDevelopVersion(
getIDEVersion(),
requiredExtensionShortHeader.gdevelopVersion
)
);
) {
compatibleWithIdeExtensionShortHeaders.push(requiredExtensionShortHeader);
} else {
incompatibleWithIdeExtensionShortHeaders.push(
requiredExtensionShortHeader
);
}
}
const outOfDateExtensionShortHeaders = requiredExtensionShortHeaders.filter(
const outOfDateExtensionShortHeaders = compatibleWithIdeExtensionShortHeaders.filter(
requiredExtensionShortHeader =>
project.hasEventsFunctionsExtensionNamed(
requiredExtensionShortHeader.name
@@ -542,43 +561,16 @@ export const checkRequiredExtensionsUpdate = async ({
.getVersion() !== requiredExtensionShortHeader.version
);
const breakingChangesExtensionShortHeaders = outOfDateExtensionShortHeaders.filter(
requiredExtensionShortHeader =>
project.hasEventsFunctionsExtensionNamed(
requiredExtensionShortHeader.name
) &&
getBreakingChanges(
project
.getEventsFunctionsExtension(requiredExtensionShortHeader.name)
.getVersion(),
requiredExtensionShortHeader
).length > 0
);
const missingExtensionShortHeaders = filterMissingExtensions(
gd,
requiredExtensionShortHeaders
);
const safeToUpdateExtensions = outOfDateExtensionShortHeaders.filter(
extension =>
!incompatibleWithIdeExtensionShortHeaders.includes(extension) &&
!breakingChangesExtensionShortHeaders.includes(extension)
);
// Overridden by `checkRequiredExtensionsUpdateForAssets`
const isGDevelopUpdateNeeded = incompatibleWithIdeExtensionShortHeaders.some(
extension => missingExtensionShortHeaders.includes(extension)
compatibleWithIdeExtensionShortHeaders
);
return {
requiredExtensionShortHeaders,
missingExtensionShortHeaders,
outOfDateExtensionShortHeaders,
breakingChangesExtensionShortHeaders,
incompatibleWithIdeExtensionShortHeaders,
safeToUpdateExtensions,
isGDevelopUpdateNeeded,
};
};
@@ -606,17 +598,7 @@ export const checkRequiredExtensionsUpdateForAssets = async ({
});
});
const requiredExtensionsUpdate = await checkRequiredExtensionsUpdate({
requiredExtensions,
project,
});
// Even if the asset may work with already installed extensions,
// we don't risk it since the asset may use the new features of the extension.
requiredExtensionsUpdate.isGDevelopUpdateNeeded =
requiredExtensionsUpdate.isGDevelopUpdateNeeded ||
requiredExtensionsUpdate.incompatibleWithIdeExtensionShortHeaders.length >
0;
return requiredExtensionsUpdate;
return checkRequiredExtensionsUpdate({ requiredExtensions, project });
};
export const complyVariantsToEventsBasedObjectOf = (

View File

@@ -4,8 +4,8 @@ import {
addSerializedExtensionsToProject,
getRequiredExtensionsFromAsset,
installRequiredExtensions,
sanitizeObjectName,
installPublicAsset,
checkRequiredExtensionsUpdate,
checkRequiredExtensionsUpdateForAssets,
} from './InstallAsset';
import { makeTestProject } from '../fixtures/TestProject';
@@ -16,13 +16,10 @@ import {
fakeAssetWithUnknownExtension1,
fakeAssetWithFlashExtensionDependency1,
flashExtensionShortHeader,
incompatibleFlashExtensionShortHeader,
fireBulletExtensionShortHeader,
fakeAssetWithCustomObject,
buttonV1ExtensionShortHeader,
buttonV2ExtensionShortHeader,
breakingButtonV3ExtensionShortHeader,
incompatibleButtonV4ExtensionShortHeader,
} from '../fixtures/GDevelopServicesTestData';
import { makeTestExtensions } from '../fixtures/TestExtensions';
import {
@@ -31,6 +28,7 @@ import {
type ExtensionShortHeader,
} from '../Utils/GDevelopServices/Extension';
import * as Asset from '../Utils/GDevelopServices/Asset';
//import { useFetchAssets } from './NewObjectDialog';
const gd: libGDevelop = global.gd;
@@ -42,6 +40,19 @@ Asset.getPublicAsset = jest.fn();
const mockFn = (fn: Function): JestMockFn<any, any> => fn;
describe('InstallAsset', () => {
test('sanitizeObjectName', () => {
expect(sanitizeObjectName('')).toBe('UnnamedObject');
expect(sanitizeObjectName('HelloWorld')).toBe('HelloWorld');
expect(sanitizeObjectName('Hello World')).toBe('HelloWorld');
expect(sanitizeObjectName('hello world')).toBe('HelloWorld');
expect(sanitizeObjectName('hello world12')).toBe('HelloWorld12');
expect(sanitizeObjectName('12 hello world')).toBe('_12HelloWorld');
expect(sanitizeObjectName('/-=hello/-=world/-=')).toBe('HelloWorld');
expect(sanitizeObjectName(' hello/-=world/-=')).toBe('HelloWorld');
expect(sanitizeObjectName('9hello/-=world/-=')).toBe('_9helloWorld');
expect(sanitizeObjectName(' 9hello/-=world/-=')).toBe('_9helloWorld');
});
describe('addAssetToProject', () => {
it('installs an object asset in the project, without renaming it if not needed', async () => {
const { project } = makeTestProject(gd);
@@ -383,258 +394,6 @@ describe('InstallAsset', () => {
// });
// });
describe('checkRequiredExtensionsUpdate', () => {
it('can find an extension to install', async () => {
makeTestExtensions(gd);
const { project } = makeTestProject(gd);
expect(project.hasEventsFunctionsExtensionNamed('Flash')).toBe(false);
// The extension is in the registry.
mockFn(getExtensionsRegistry).mockImplementationOnce(() => ({
version: '1.0.0',
headers: [fireBulletExtensionShortHeader, flashExtensionShortHeader],
}));
await expect(
checkRequiredExtensionsUpdate({
requiredExtensions: [
{
extensionName: flashExtensionShortHeader.name,
extensionVersion: flashExtensionShortHeader.version,
},
],
project,
})
).resolves.toEqual({
requiredExtensionShortHeaders: [flashExtensionShortHeader],
missingExtensionShortHeaders: [flashExtensionShortHeader],
outOfDateExtensionShortHeaders: [],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: false,
});
});
it('can find an up to date extension from the project', async () => {
makeTestExtensions(gd);
const { project } = makeTestProject(gd);
expect(project.hasEventsFunctionsExtensionNamed('Button')).toBe(true);
// The extension is in the registry.
mockFn(getExtensionsRegistry).mockImplementationOnce(() => ({
version: '1.0.0',
headers: [buttonV1ExtensionShortHeader],
}));
await expect(
checkRequiredExtensionsUpdate({
requiredExtensions: [
{
extensionName: buttonV1ExtensionShortHeader.name,
extensionVersion: buttonV1ExtensionShortHeader.version,
},
],
project,
})
).resolves.toEqual({
requiredExtensionShortHeaders: [buttonV1ExtensionShortHeader],
missingExtensionShortHeaders: [],
outOfDateExtensionShortHeaders: [],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: false,
});
});
it('can find an extension to update', async () => {
makeTestExtensions(gd);
const { project } = makeTestProject(gd);
expect(project.hasEventsFunctionsExtensionNamed('Button')).toBe(true);
// The extension is in the registry.
mockFn(getExtensionsRegistry).mockImplementationOnce(() => ({
version: '1.0.0',
headers: [buttonV2ExtensionShortHeader],
}));
await expect(
checkRequiredExtensionsUpdate({
requiredExtensions: [
{
extensionName: buttonV2ExtensionShortHeader.name,
extensionVersion: buttonV2ExtensionShortHeader.version,
},
],
project,
})
).resolves.toEqual({
requiredExtensionShortHeaders: [buttonV2ExtensionShortHeader],
missingExtensionShortHeaders: [],
outOfDateExtensionShortHeaders: [buttonV2ExtensionShortHeader],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [buttonV2ExtensionShortHeader],
isGDevelopUpdateNeeded: false,
});
});
it('can find an extension to update with breaking changes', async () => {
makeTestExtensions(gd);
const { project } = makeTestProject(gd);
expect(project.hasEventsFunctionsExtensionNamed('Button')).toBe(true);
// The extension is in the registry.
mockFn(getExtensionsRegistry).mockImplementationOnce(() => ({
version: '1.0.0',
headers: [breakingButtonV3ExtensionShortHeader],
}));
await expect(
checkRequiredExtensionsUpdate({
requiredExtensions: [
{
extensionName: breakingButtonV3ExtensionShortHeader.name,
extensionVersion: breakingButtonV3ExtensionShortHeader.version,
},
],
project,
})
).resolves.toEqual({
requiredExtensionShortHeaders: [breakingButtonV3ExtensionShortHeader],
missingExtensionShortHeaders: [],
outOfDateExtensionShortHeaders: [breakingButtonV3ExtensionShortHeader],
breakingChangesExtensionShortHeaders: [
breakingButtonV3ExtensionShortHeader,
],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: false,
});
});
it('can find an extension to update incompatible with the editor', async () => {
makeTestExtensions(gd);
const { project } = makeTestProject(gd);
expect(project.hasEventsFunctionsExtensionNamed('Button')).toBe(true);
// The extension is in the registry.
mockFn(getExtensionsRegistry).mockImplementationOnce(() => ({
version: '1.0.0',
headers: [incompatibleButtonV4ExtensionShortHeader],
}));
await expect(
checkRequiredExtensionsUpdate({
requiredExtensions: [
{
extensionName: incompatibleButtonV4ExtensionShortHeader.name,
extensionVersion:
incompatibleButtonV4ExtensionShortHeader.version,
},
],
project,
})
).resolves.toEqual({
requiredExtensionShortHeaders: [
incompatibleButtonV4ExtensionShortHeader,
],
missingExtensionShortHeaders: [],
outOfDateExtensionShortHeaders: [
incompatibleButtonV4ExtensionShortHeader,
],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [
incompatibleButtonV4ExtensionShortHeader,
],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: false,
});
});
it('can find an extension to install incompatible with the editor', async () => {
makeTestExtensions(gd);
const { project } = makeTestProject(gd);
expect(project.hasEventsFunctionsExtensionNamed('Flash')).toBe(false);
// The extension is in the registry.
mockFn(getExtensionsRegistry).mockImplementationOnce(() => ({
version: '1.0.0',
headers: [incompatibleFlashExtensionShortHeader],
}));
await expect(
checkRequiredExtensionsUpdate({
requiredExtensions: [
{
extensionName: incompatibleFlashExtensionShortHeader.name,
extensionVersion: incompatibleFlashExtensionShortHeader.version,
},
],
project,
})
).resolves.toEqual({
requiredExtensionShortHeaders: [incompatibleFlashExtensionShortHeader],
missingExtensionShortHeaders: [incompatibleFlashExtensionShortHeader],
outOfDateExtensionShortHeaders: [],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [
incompatibleFlashExtensionShortHeader,
],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: true,
});
});
it('errors if an extension is not found in the registry', async () => {
makeTestExtensions(gd);
const { project } = makeTestProject(gd);
mockFn(getExtensionsRegistry).mockImplementationOnce(() => ({
version: '1.0.0',
headers: [flashExtensionShortHeader, fireBulletExtensionShortHeader],
}));
await expect(
checkRequiredExtensionsUpdate({
requiredExtensions: [
{
extensionName: 'UnknownExtension',
extensionVersion: '1.0.0',
},
],
project,
})
).rejects.toMatchObject({
message: 'Unable to find extension UnknownExtension in the registry.',
});
});
it("errors if the registry can't be loaded ", async () => {
makeTestExtensions(gd);
const { project } = makeTestProject(gd);
mockFn(getExtensionsRegistry).mockImplementationOnce(() => {
throw new Error('Fake error');
});
await expect(
checkRequiredExtensionsUpdate({
requiredExtensions: [
{
extensionName: flashExtensionShortHeader.name,
extensionVersion: flashExtensionShortHeader.version,
},
],
project,
})
).rejects.toMatchObject({
message: 'Fake error',
});
});
});
describe('checkRequiredExtensionsUpdateForAssets', () => {
it('can find an extension to install', async () => {
makeTestExtensions(gd);
@@ -664,10 +423,7 @@ describe('InstallAsset', () => {
requiredExtensionShortHeaders: [flashExtensionShortHeader],
missingExtensionShortHeaders: [flashExtensionShortHeader],
outOfDateExtensionShortHeaders: [],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: false,
});
});
@@ -701,10 +457,7 @@ describe('InstallAsset', () => {
requiredExtensionShortHeaders: [buttonV1ExtensionShortHeader],
missingExtensionShortHeaders: [],
outOfDateExtensionShortHeaders: [],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: false,
});
});
@@ -738,132 +491,7 @@ describe('InstallAsset', () => {
requiredExtensionShortHeaders: [buttonV2ExtensionShortHeader],
missingExtensionShortHeaders: [],
outOfDateExtensionShortHeaders: [buttonV2ExtensionShortHeader],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [buttonV2ExtensionShortHeader],
isGDevelopUpdateNeeded: false,
});
});
it('can find an extension to update with breaking changes', async () => {
makeTestExtensions(gd);
const { project } = makeTestProject(gd);
expect(project.hasEventsFunctionsExtensionNamed('Button')).toBe(true);
// Get an asset that uses an extension...
mockFn(Asset.getPublicAsset).mockImplementationOnce(
() => fakeAssetWithCustomObject
);
// ...and this extension is in the registry
mockFn(getExtensionsRegistry).mockImplementationOnce(() => ({
version: '1.0.0',
headers: [
flashExtensionShortHeader,
fireBulletExtensionShortHeader,
// The project contains the 1.0.0 of this extension.
breakingButtonV3ExtensionShortHeader,
],
}));
await expect(
checkRequiredExtensionsUpdateForAssets({
assets: [fakeAssetWithCustomObject, fakeAssetWithCustomObject],
project,
})
).resolves.toEqual({
requiredExtensionShortHeaders: [breakingButtonV3ExtensionShortHeader],
missingExtensionShortHeaders: [],
outOfDateExtensionShortHeaders: [breakingButtonV3ExtensionShortHeader],
breakingChangesExtensionShortHeaders: [
breakingButtonV3ExtensionShortHeader,
],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: false,
});
});
it('can find an extension to update incompatible with the editor', async () => {
makeTestExtensions(gd);
const { project } = makeTestProject(gd);
expect(project.hasEventsFunctionsExtensionNamed('Button')).toBe(true);
// Get an asset that uses an extension...
mockFn(Asset.getPublicAsset).mockImplementationOnce(
() => fakeAssetWithCustomObject
);
// ...and this extension is in the registry
mockFn(getExtensionsRegistry).mockImplementationOnce(() => ({
version: '1.0.0',
headers: [
flashExtensionShortHeader,
fireBulletExtensionShortHeader,
// The project contains the 1.0.0 of this extension.
incompatibleButtonV4ExtensionShortHeader,
],
}));
await expect(
checkRequiredExtensionsUpdateForAssets({
assets: [fakeAssetWithCustomObject, fakeAssetWithCustomObject],
project,
})
).resolves.toEqual({
requiredExtensionShortHeaders: [
incompatibleButtonV4ExtensionShortHeader,
],
missingExtensionShortHeaders: [],
outOfDateExtensionShortHeaders: [
incompatibleButtonV4ExtensionShortHeader,
],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [
incompatibleButtonV4ExtensionShortHeader,
],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: true,
});
});
it('can find an extension to install incompatible with the editor', async () => {
makeTestExtensions(gd);
const { project } = makeTestProject(gd);
expect(project.hasEventsFunctionsExtensionNamed('Flash')).toBe(false);
// Get an asset that uses an extension...
mockFn(Asset.getPublicAsset).mockImplementationOnce(
() => fakeAssetWithFlashExtensionDependency1
);
// ...and this extension is in the registry
mockFn(getExtensionsRegistry).mockImplementationOnce(() => ({
version: '1.0.0',
headers: [
incompatibleFlashExtensionShortHeader,
fireBulletExtensionShortHeader,
],
}));
await expect(
checkRequiredExtensionsUpdateForAssets({
assets: [
fakeAssetWithFlashExtensionDependency1,
fakeAssetWithFlashExtensionDependency1,
],
project,
})
).resolves.toEqual({
requiredExtensionShortHeaders: [incompatibleFlashExtensionShortHeader],
missingExtensionShortHeaders: [incompatibleFlashExtensionShortHeader],
outOfDateExtensionShortHeaders: [],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [
incompatibleFlashExtensionShortHeader,
],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: true,
});
});
@@ -1026,15 +654,11 @@ describe('InstallAsset', () => {
},
],
outOfDateExtensionShortHeaders: [],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: false,
},
shouldUpdateExtension: true,
eventsFunctionsExtensionsState: mockEventsFunctionsExtensionsState,
project,
onExtensionInstalled: () => {},
})
).rejects.toMatchObject({
// It's just because the mock doesn't reloadProjectEventsFunctionsExtensions.
@@ -1062,15 +686,11 @@ describe('InstallAsset', () => {
requiredExtensionShortHeaders: [flashExtensionShortHeader],
missingExtensionShortHeaders: [flashExtensionShortHeader],
outOfDateExtensionShortHeaders: [],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: false,
},
shouldUpdateExtension: true,
eventsFunctionsExtensionsState: mockEventsFunctionsExtensionsState,
project,
onExtensionInstalled: () => {},
})
).rejects.toMatchObject({
message: 'These extensions could not be installed: Flash',
@@ -1103,15 +723,11 @@ describe('InstallAsset', () => {
],
missingExtensionShortHeaders: [],
outOfDateExtensionShortHeaders: [],
breakingChangesExtensionShortHeaders: [],
incompatibleWithIdeExtensionShortHeaders: [],
safeToUpdateExtensions: [],
isGDevelopUpdateNeeded: false,
},
shouldUpdateExtension: true,
eventsFunctionsExtensionsState: mockEventsFunctionsExtensionsState,
project,
onExtensionInstalled: () => {},
});
// No extensions fetched because the extension is already installed.

View File

@@ -29,11 +29,6 @@ import {
isPrivateAsset,
} from '../Utils/GDevelopServices/Asset';
import { type ExtensionShortHeader } from '../Utils/GDevelopServices/Extension';
import {
getBreakingChanges,
formatExtensionsBreakingChanges,
type ExtensionChange,
} from '../Utils/Extension/ExtensionCompatibilityChecker.js';
import EventsFunctionsExtensionsContext from '../EventsFunctionsExtensionsLoader/EventsFunctionsExtensionsContext';
import Window from '../Utils/Window';
import PrivateAssetsAuthorizationContext from './PrivateAssets/PrivateAssetsAuthorizationContext';
@@ -53,64 +48,20 @@ import { AssetStoreNavigatorContext } from './AssetStoreNavigator';
const isDev = Window.isDev();
export const useExtensionUpdateAlertDialog = () => {
const { showConfirmation, showDeleteConfirmation } = useAlertDialog();
return async ({
project,
outOfDateExtensionShortHeaders,
}: {|
project: gdProject,
outOfDateExtensionShortHeaders: Array<ExtensionShortHeader>,
|}): Promise<string> => {
const breakingChanges = new Map<
ExtensionShortHeader,
Array<ExtensionChange>
>();
for (const extension of outOfDateExtensionShortHeaders) {
if (!project.hasEventsFunctionsExtensionNamed(extension.name)) {
continue;
}
const installedVersion = project
.getEventsFunctionsExtension(extension.name)
.getVersion();
const extensionBreakingChanges = getBreakingChanges(
installedVersion,
extension
);
if (extensionBreakingChanges.length > 0) {
breakingChanges.set(extension, extensionBreakingChanges);
}
}
const notBreakingExtensions = outOfDateExtensionShortHeaders.filter(
extension => !breakingChanges.has(extension)
);
if (breakingChanges.size > 0) {
// Extensions without breaking changes are not listed since it would make
// the message more confusing.
return (await showDeleteConfirmation({
title: t`Breaking changes`,
message: t`This asset requires updates to extensions that have breaking changes${'\n\n' +
formatExtensionsBreakingChanges(breakingChanges) +
'\n'}Do you want to update them now ?`,
confirmButtonLabel: t`Update the extension`,
dismissButtonLabel: t`Abort`,
}))
? 'update'
: // Avoid to install assets which wouldn't work with the installed version.
'abort';
} else {
return (await showConfirmation({
title: t`Extension update`,
message: t`Before installing this asset, it's strongly recommended to update these extensions${'\n\n - ' +
notBreakingExtensions
.map(extension => extension.fullName)
.join('\n - ') +
'\n\n'}Do you want to update them now ?`,
confirmButtonLabel: t`Update the extension`,
dismissButtonLabel: t`Skip the update`,
}))
? 'update'
: 'skip';
}
const { showConfirmation } = useAlertDialog();
return async (
outOfDateExtensionShortHeaders: Array<ExtensionShortHeader>
): Promise<boolean> => {
return await showConfirmation({
title: t`Extension update`,
message: t`Before installing this asset, it's strongly recommended to update these extensions${'\n\n - ' +
outOfDateExtensionShortHeaders
.map(extension => extension.fullName)
.join('\n\n - ') +
'\n\n'}Do you want to update it now ?`,
confirmButtonLabel: t`Update the extension`,
dismissButtonLabel: t`Skip the update`,
});
};
};
@@ -172,14 +123,14 @@ export const useFetchAssets = () => {
export const useInstallAsset = ({
project,
objectsContainer,
targetObjectFolderOrObjectWithContext,
resourceManagementProps,
onExtensionInstalled,
}: {|
project: gdProject | null,
project: gdProject,
objectsContainer: gdObjectsContainer,
targetObjectFolderOrObjectWithContext?: ?ObjectFolderOrObjectWithContext,
resourceManagementProps: ResourceManagementProps,
onExtensionInstalled: (extensionNames: Array<string>) => void,
|}) => {
const shopNavigationState = React.useContext(AssetStoreNavigatorContext);
const { openedAssetPack } = shopNavigationState.getCurrentPage();
@@ -196,18 +147,9 @@ export const useInstallAsset = ({
resourceManagementProps.canInstallPrivateAsset
);
return async ({
assetShortHeader,
objectsContainer,
requestedObjectName,
}: {|
assetShortHeader: AssetShortHeader,
objectsContainer: gdObjectsContainer,
requestedObjectName?: string,
|}): Promise<InstallAssetOutput | null> => {
if (!project) {
return null;
}
return async (
assetShortHeader: AssetShortHeader
): Promise<InstallAssetOutput | null> => {
try {
if (await showProjectNeedToBeSaved(assetShortHeader)) {
return null;
@@ -220,31 +162,27 @@ export const useInstallAsset = ({
project,
}
);
if (requiredExtensionInstallation.isGDevelopUpdateNeeded) {
if (
requiredExtensionInstallation.incompatibleWithIdeExtensionShortHeaders
.length > 0
) {
showAlert({
title: t`Could not install the asset`,
message: t`Please upgrade the editor to the latest version.`,
});
return null;
}
const extensionUpdateAction =
requiredExtensionInstallation.outOfDateExtensionShortHeaders.length ===
0
? 'skip'
: await showExtensionUpdateConfirmation({
project,
outOfDateExtensionShortHeaders:
requiredExtensionInstallation.outOfDateExtensionShortHeaders,
});
if (extensionUpdateAction === 'abort') {
return null;
}
const shouldUpdateExtension =
requiredExtensionInstallation.outOfDateExtensionShortHeaders.length >
0 &&
(await showExtensionUpdateConfirmation(
requiredExtensionInstallation.outOfDateExtensionShortHeaders
));
await installRequiredExtensions({
requiredExtensionInstallation,
shouldUpdateExtension: extensionUpdateAction === 'update',
shouldUpdateExtension,
eventsFunctionsExtensionsState,
project,
onExtensionInstalled,
});
const isPrivate = isPrivateAsset(assetShortHeader);
const installOutput = isPrivate
@@ -252,7 +190,6 @@ export const useInstallAsset = ({
asset,
project,
objectsContainer,
requestedObjectName,
targetObjectFolderOrObject:
targetObjectFolderOrObjectWithContext &&
!targetObjectFolderOrObjectWithContext.global
@@ -263,7 +200,6 @@ export const useInstallAsset = ({
asset,
project,
objectsContainer,
requestedObjectName,
targetObjectFolderOrObject:
targetObjectFolderOrObjectWithContext &&
!targetObjectFolderOrObjectWithContext.global
@@ -312,7 +248,6 @@ type Props = {|
onCreateNewObject: (type: string) => void,
onObjectsAddedFromAssets: (Array<gdObject>) => void,
targetObjectFolderOrObjectWithContext?: ?ObjectFolderOrObjectWithContext,
onExtensionInstalled: (extensionNames: Array<string>) => void,
|};
function NewObjectDialog({
@@ -325,7 +260,6 @@ function NewObjectDialog({
onCreateNewObject,
onObjectsAddedFromAssets,
targetObjectFolderOrObjectWithContext,
onExtensionInstalled,
}: Props) {
const { isMobile } = useResponsiveWindowSize();
const {
@@ -381,9 +315,9 @@ function NewObjectDialog({
const showExtensionUpdateConfirmation = useExtensionUpdateAlertDialog();
const installAsset = useInstallAsset({
project,
objectsContainer,
resourceManagementProps,
targetObjectFolderOrObjectWithContext,
onExtensionInstalled,
});
const onInstallAsset = React.useCallback(
@@ -391,16 +325,13 @@ function NewObjectDialog({
if (!assetShortHeader) return false;
setIsAssetBeingInstalled(true);
const installAssetOutput = await installAsset({
assetShortHeader,
objectsContainer,
});
const installAssetOutput = await installAsset(assetShortHeader);
setIsAssetBeingInstalled(false);
if (installAssetOutput)
onObjectsAddedFromAssets(installAssetOutput.createdObjects);
return !!installAssetOutput;
},
[installAsset, onObjectsAddedFromAssets, objectsContainer]
[installAsset, onObjectsAddedFromAssets]
);
const onInstallEmptyCustomObject = React.useCallback(
@@ -415,34 +346,27 @@ function NewObjectDialog({
project,
}
);
if (requiredExtensionInstallation.isGDevelopUpdateNeeded) {
if (
requiredExtensionInstallation.incompatibleWithIdeExtensionShortHeaders
.length > 0
) {
showAlert({
title: t`Could not install required extensions`,
title: t`Could not install the asset`,
message: t`Please upgrade the editor to the latest version.`,
});
return;
}
// Users must be able to create an object from scratch without being
// forced to update extensions that may break their projects.
const safeToUpdateExtensions =
requiredExtensionInstallation.safeToUpdateExtensions;
const extensionUpdateAction =
requiredExtensionInstallation.outOfDateExtensionShortHeaders
.length === 0
? 'skip'
: (await showExtensionUpdateConfirmation({
project,
outOfDateExtensionShortHeaders: safeToUpdateExtensions,
})) === 'update';
if (extensionUpdateAction === 'abort') {
return;
}
const shouldUpdateExtension =
requiredExtensionInstallation.outOfDateExtensionShortHeaders.length >
0 &&
(await showExtensionUpdateConfirmation(
requiredExtensionInstallation.outOfDateExtensionShortHeaders
));
await installRequiredExtensions({
requiredExtensionInstallation,
shouldUpdateExtension: extensionUpdateAction === 'update',
shouldUpdateExtension,
eventsFunctionsExtensionsState,
project,
onExtensionInstalled,
});
onCreateNewObject(enumeratedObjectMetadata.name);
@@ -464,7 +388,6 @@ function NewObjectDialog({
showExtensionUpdateConfirmation,
eventsFunctionsExtensionsState,
showAlert,
onExtensionInstalled,
]
);
@@ -679,7 +602,6 @@ function NewObjectDialog({
targetObjectFolderOrObjectWithContext={
targetObjectFolderOrObjectWithContext
}
onExtensionInstalled={onExtensionInstalled}
/>
)}
</>

View File

@@ -656,7 +656,6 @@ const PrivateAssetPackInformationPage = ({
analyticsMetadata: {
reason: 'Claim asset pack',
recommendedPlanId: 'gdevelop_gold',
placementId: 'claim-asset-pack',
},
filter: 'individual',
})

View File

@@ -114,7 +114,6 @@ const PrivateAssetsAuthorizationProvider = ({ children }: Props) => {
asset,
project,
objectsContainer,
requestedObjectName,
targetObjectFolderOrObject,
}: InstallAssetArgs): Promise<?InstallAssetOutput> => {
if (!profile) {
@@ -135,7 +134,6 @@ const PrivateAssetsAuthorizationProvider = ({ children }: Props) => {
asset: assetWithAuthorizedResourceUrls,
project,
objectsContainer,
requestedObjectName,
targetObjectFolderOrObject,
});
};

View File

@@ -74,12 +74,3 @@ export const filterEnumeratedBehaviorMetadata = (
);
});
};
export const isBehaviorDefaultCapability = (
behaviorMetadata: gdBehaviorMetadata
) => {
return (
behaviorMetadata.getName().includes('Capability') ||
behaviorMetadata.getName() === 'Scene3D::Base3DBehavior'
);
};

View File

@@ -11,6 +11,7 @@ import { showMessageBox } from '../UI/Messages/MessageBox';
import { getDeprecatedBehaviorsInformation } from '../Hints';
import { enumerateBehaviorsMetadata } from './EnumerateBehaviorsMetadata';
import { BehaviorStore } from '../AssetStore/BehaviorStore';
import { type SearchableBehaviorMetadata } from '../AssetStore/BehaviorStore/BehaviorStoreContext';
import { type BehaviorShortHeader } from '../Utils/GDevelopServices/Extension';
import EventsFunctionsExtensionsContext from '../EventsFunctionsExtensionsLoader/EventsFunctionsExtensionsContext';
import { installExtension } from '../AssetStore/ExtensionStore/InstallExtension';
@@ -32,7 +33,7 @@ type Props = {|
open: boolean,
onClose: () => void,
onChoose: (type: string, defaultName: string) => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
onExtensionInstalled: (extensionName: string) => void,
|};
export default function NewBehaviorDialog({
@@ -89,7 +90,7 @@ export default function NewBehaviorDialog({
[project]
);
const allInstalledBehaviorMetadataList: Array<BehaviorShortHeader> = React.useMemo(
const allInstalledBehaviorMetadataList: Array<SearchableBehaviorMetadata> = React.useMemo(
() => {
const platform = project.getCurrentPlatform();
const behaviorMetadataList =
@@ -114,29 +115,12 @@ export default function NewBehaviorDialog({
behavior.behaviorMetadata
),
tags: behavior.tags,
name: gd.PlatformExtension.getBehaviorNameFromFullBehaviorType(
behavior.type
),
extensionName: gd.PlatformExtension.getExtensionFromFullBehaviorType(
behavior.type
),
isInstalled: true,
// The tier will be overridden with repository data.
// Only the built-in and user extensions will keep this value.
tier: 'installed',
// Not relevant for `installed` extensions
version: '',
url: '',
headerUrl: '',
extensionNamespace: '',
authorIds: [],
}));
},
[project, eventsFunctionsExtension, getAllRequiredBehaviorTypes]
);
const installedBehaviorMetadataList: Array<BehaviorShortHeader> = React.useMemo(
const installedBehaviorMetadataList: Array<SearchableBehaviorMetadata> = React.useMemo(
() =>
allInstalledBehaviorMetadataList.filter(
behavior => !deprecatedBehaviorsInformation[behavior.type]
@@ -144,7 +128,7 @@ export default function NewBehaviorDialog({
[allInstalledBehaviorMetadataList, deprecatedBehaviorsInformation]
);
const deprecatedBehaviorMetadataList: Array<BehaviorShortHeader> = React.useMemo(
const deprecatedBehaviorMetadataList: Array<SearchableBehaviorMetadata> = React.useMemo(
() => {
const deprecatedBehaviors = allInstalledBehaviorMetadataList.filter(
behavior => deprecatedBehaviorsInformation[behavior.type]
@@ -190,7 +174,7 @@ export default function NewBehaviorDialog({
behaviorShortHeader
);
if (wasExtensionInstalled) {
onExtensionInstalled([behaviorShortHeader.extensionName]);
onExtensionInstalled(behaviorShortHeader.extensionName);
}
return wasExtensionInstalled;
} finally {

View File

@@ -34,8 +34,7 @@ import ThreeDotsMenu from '../UI/CustomSvgIcons/ThreeDotsMenu';
import Trash from '../UI/CustomSvgIcons/Trash';
import Add from '../UI/CustomSvgIcons/Add';
import { mapVector } from '../Utils/MapFor';
import Clipboard from '../Utils/Clipboard';
import { SafeExtractor } from '../Utils/SafeExtractor';
import Clipboard, { SafeExtractor } from '../Utils/Clipboard';
import {
serializeToJSObject,
unserializeFromJSObject,
@@ -325,7 +324,7 @@ export const useManageObjectBehaviors = ({
onSizeUpdated?: ?() => void,
onBehaviorsUpdated?: ?() => void,
onUpdateBehaviorsSharedData: () => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
onExtensionInstalled: (extensionName: string) => void,
}): UseManageBehaviorsState => {
const [
justAddedBehaviorName,
@@ -623,7 +622,7 @@ type Props = {|
extensionName: string,
behaviorName: string
) => Promise<void>,
onExtensionInstalled: (extensionNames: Array<string>) => void,
onExtensionInstalled: (extensionName: string) => void,
isListLocked: boolean,
|};

View File

@@ -174,7 +174,6 @@ const LockedCourseChapterPreview = React.forwardRef<Props, HTMLDivElement>(
analyticsMetadata: {
reason: 'Unlock course chapter',
recommendedPlanId: 'gdevelop_silver',
placementId: 'unlock-course-chapter',
},
})
}

View File

@@ -1,538 +0,0 @@
// @flow
import { unserializeFromJSObject } from '../Utils/Serializer';
import {
type AiGeneratedEventChange,
type AiGeneratedEventUndeclaredVariable,
} from '../Utils/GDevelopServices/Generation';
import { mapFor } from '../Utils/MapFor';
const gd: libGDevelop = global.gd;
/**
* Parses an event path string (e.g., "event-0.1.2") into an array of 0-based indices (e.g., [0, 1, 2]).
* Throws an error for invalid formats or non-positive indices.
*/
const parseEventPath = (pathString: string): Array<number> => {
const originalPathString = pathString;
if (!pathString.startsWith('event-')) {
// Fallback for paths that might not have the "event-" prefix, like "1.2.3"
// This is a lenient parsing, primary expectation is "event-" prefix.
const partsNoPrefix = pathString.split('.');
if (
partsNoPrefix.length > 0 &&
partsNoPrefix.every(s => s !== '' && !isNaN(parseInt(s, 10)))
) {
console.warn(
`Event path string "${originalPathString}" does not start with "event-". Parsed as direct indices.`
);
} else {
throw new Error(
`Invalid event path string format: "${originalPathString}". Expected "event-X.Y.Z" or "X.Y.Z".`
);
}
} else {
pathString = pathString.substring('event-'.length);
}
const parts = pathString.split('.');
if (
parts.length === 0 ||
parts.some(s => s === '' || isNaN(parseInt(s, 10)))
) {
throw new Error(
`Invalid event path string content: "${originalPathString}". Ensure numbers are separated by dots.`
);
}
return parts.map(s => {
const num = parseInt(s, 10);
if (num < 0) {
throw new Error(
`Event path indices must be positive in string "${originalPathString}", but found ${num}.`
);
}
return num;
});
};
/**
* Navigates an event tree to find the parent EventsList and the 0-based index
* for an event targeted by the given path.
*/
const getParentListAndIndex = (
rootEventsList: gdEventsList,
path: Array<number>,
operationTypeForErrorMessage: 'access' | 'insertion'
): { parentList: gdEventsList, eventIndexInParentList: number } => {
if (path.length === 0) {
throw new Error('Path cannot be empty for getParentListAndIndex.');
}
let currentList = rootEventsList;
const pathForErrorMessage = path.join('.');
for (let i = 0; i < path.length - 1; i++) {
const eventIndex = path[i];
if (eventIndex < 0 || eventIndex >= currentList.getEventsCount()) {
throw new Error(
`Invalid event path: index ${eventIndex} out of bounds at depth ${i +
1} (max: ${currentList.getEventsCount() -
1}). Path: ${pathForErrorMessage}`
);
}
const event = currentList.getEventAt(eventIndex);
if (!event.canHaveSubEvents()) {
throw new Error(
`Event at path segment ${i +
1} (index ${eventIndex}) cannot have sub-events. Path: ${pathForErrorMessage}`
);
}
currentList = event.getSubEvents();
}
const finalIndex = path[path.length - 1];
if (finalIndex < 0) {
throw new Error(
`Invalid event path: final index ${finalIndex} is negative. Path: ${pathForErrorMessage}.`
);
}
// For insertion, index can be equal to count (to append). For access, it must be less than count.
if (
operationTypeForErrorMessage === 'insertion' &&
finalIndex > currentList.getEventsCount()
) {
throw new Error(
`Invalid event path for insertion: final index ${finalIndex} is out of bounds. Max allowed for insertion: ${currentList.getEventsCount()}. Path: ${pathForErrorMessage}`
);
} else if (
operationTypeForErrorMessage === 'access' &&
finalIndex >= currentList.getEventsCount()
) {
throw new Error(
`Invalid event path for access: final index ${finalIndex} is out of bounds. Max allowed for access: ${currentList.getEventsCount() -
1}. Path: ${pathForErrorMessage}`
);
}
return { parentList: currentList, eventIndexInParentList: finalIndex };
};
/**
* Retrieves an event at a specific path from a root EventsList.
*/
const getEventByPath = (
rootEventsList: gdEventsList,
path: Array<number>
): gdBaseEvent => {
const { parentList, eventIndexInParentList } = getParentListAndIndex(
rootEventsList,
path,
'access'
);
// Bounds check already done by getParentListAndIndex for 'access'
return parentList.getEventAt(eventIndexInParentList);
};
type EventOperationType = 'delete' | 'insert' | 'insertAsSub';
type EventOperation = {|
type: EventOperationType,
path: Array<number>,
eventsToInsert?: gdEventsList,
|};
const comparePathsReverseLexicographically = (
p1: Array<number>,
p2: Array<number>
): number => {
const maxLength = Math.max(p1.length, p2.length);
for (let i = 0; i < maxLength; i++) {
const val1 = i < p1.length ? p1[i] : -1;
const val2 = i < p2.length ? p2[i] : -1;
if (val1 > val2) return -1;
if (val1 < val2) return 1;
}
return 0;
};
export const applyEventsChanges = (
project: gdProject,
sceneEvents: gdEventsList,
eventOperationsInput: Array<AiGeneratedEventChange>,
aiGeneratedEventId: string
): void => {
const operations: Array<EventOperation> = [];
eventOperationsInput.forEach(change => {
const { operationName, operationTargetEvent, generatedEvents } = change;
let parsedPath: Array<number> | null = null;
let localEventsToInsert: gdEventsList | null = null;
try {
if (operationTargetEvent) {
parsedPath = parseEventPath(operationTargetEvent);
} else if (operationName !== 'insert_at_end') {
// Path is generally required, except for 'insert_at_end'.
console.warn(
`Skipping operation "${operationName}" due to missing operationTargetEvent path.`
);
return;
}
if (generatedEvents && operationName !== 'delete_event') {
const eventsListContent = JSON.parse(generatedEvents);
localEventsToInsert = new gd.EventsList();
unserializeFromJSObject(
localEventsToInsert,
eventsListContent,
'unserializeFrom',
project
);
if (localEventsToInsert.isEmpty()) {
console.warn(
`Generated events for operation "${operationName}" (path: ${operationTargetEvent ||
'N/A'}) are empty. Insertion might not add any events.`
);
}
mapFor(0, localEventsToInsert.getEventsCount(), i => {
if (!localEventsToInsert) return;
const event = localEventsToInsert.getEventAt(i);
event.setAiGeneratedEventId(aiGeneratedEventId);
});
}
switch (operationName) {
case 'insert_and_replace_event':
if (!parsedPath) {
console.warn(
`Skipping "insert_and_replace_event" due to missing or invalid path.`
);
if (localEventsToInsert) localEventsToInsert.delete();
return;
}
operations.push({ type: 'delete', path: parsedPath });
operations.push({
type: 'insert',
path: parsedPath,
eventsToInsert: localEventsToInsert || undefined,
});
// localEventsToInsert is now "owned" by the 'insert' operation,
// it should not be deleted here in the switch case.
break;
case 'insert_before_event':
if (!parsedPath) {
console.warn(
`Skipping "insert_before_event" due to missing or invalid path.`
);
if (localEventsToInsert) localEventsToInsert.delete();
return;
}
operations.push({
type: 'insert',
path: parsedPath,
eventsToInsert: localEventsToInsert || undefined,
});
break;
case 'insert_as_sub_event':
if (!parsedPath) {
console.warn(
`Skipping "insert_as_sub_event" due to missing or invalid path.`
);
if (localEventsToInsert) localEventsToInsert.delete();
return;
}
operations.push({
type: 'insertAsSub',
path: parsedPath, // This path is to the parent event
eventsToInsert: localEventsToInsert || undefined,
});
break;
case 'delete_event':
if (!parsedPath) {
console.warn(
`Skipping "delete_event" due to missing or invalid path.`
);
// No localEventsToInsert expected or created for delete_event.
return;
}
// Ensure no events were accidentally parsed for delete.
if (localEventsToInsert) {
console.warn(
'Internal warning: localEventsToInsert was populated for a "delete_event". Cleaning up.'
);
localEventsToInsert.delete();
}
operations.push({ type: 'delete', path: parsedPath });
break;
case 'insert_at_end':
// Path for insert_at_end is synthetic, representing the end of the root list.
operations.push({
type: 'insert',
path: [sceneEvents.getEventsCount()],
eventsToInsert: localEventsToInsert || undefined,
});
break;
default:
console.warn(
`Unknown operationName: "${operationName}". Skipping operation.`
);
// Clean up localEventsToInsert if it was created for an unknown operation
if (localEventsToInsert) localEventsToInsert.delete();
}
} catch (e) {
console.warn(
`Error processing event change (operation: "${operationName}", path: "${operationTargetEvent ||
'N/A'}"): ${e.message}. Skipping this change.`
);
// Ensure cleanup if parsing/unserialization failed mid-way
if (localEventsToInsert) {
localEventsToInsert.delete();
}
}
});
operations.sort((opA, opB) => {
const pathComparison = comparePathsReverseLexicographically(
opA.path,
opB.path
);
if (pathComparison !== 0) return pathComparison;
if (opA.type === 'delete' && opB.type !== 'delete') return -1;
if (opA.type !== 'delete' && opB.type === 'delete') return 1;
return 0;
});
operations.forEach(op => {
const pathForLog = op.path.join('.');
try {
if (op.type === 'delete') {
const { parentList, eventIndexInParentList } = getParentListAndIndex(
sceneEvents,
op.path,
'access' // Deleting an existing event, so 'access'
);
// Check already done by getParentListAndIndex for 'access'
parentList.removeEventAt(eventIndexInParentList);
} else if (op.type === 'insert') {
const {
parentList,
eventIndexInParentList: insertionIndex,
} = getParentListAndIndex(
sceneEvents,
op.path,
'insertion' // Path is for insertion point
);
// Check already done by getParentListAndIndex for 'insertion'
if (op.eventsToInsert && !op.eventsToInsert.isEmpty()) {
parentList.insertEvents(
op.eventsToInsert,
0,
op.eventsToInsert.getEventsCount(),
insertionIndex
);
} else {
console.warn(
`Insert operation for path [${pathForLog}] skipped: no events to insert or events list is empty.`
);
}
} else if (op.type === 'insertAsSub') {
// op.path is the path to the PARENT event
const parentEvent = getEventByPath(sceneEvents, op.path);
if (!parentEvent.canHaveSubEvents()) {
console.warn(
`Cannot insert sub-events: Event at path [${pathForLog}] does not support sub-events. Skipping.`
);
return;
}
const subEventsList = parentEvent.getSubEvents();
if (op.eventsToInsert && !op.eventsToInsert.isEmpty()) {
subEventsList.insertEvents(
op.eventsToInsert,
0,
op.eventsToInsert.getEventsCount(),
subEventsList.getEventsCount() // Insert at the end of sub-events
);
} else {
console.warn(
`InsertAsSub operation for parent path [${pathForLog}] skipped: no events to insert or events list is empty.`
);
}
}
} catch (error) {
console.error(
`Error applying event operation type ${
op.type
} for path [${pathForLog}]:`,
error
);
} finally {
// Clean up the gd.EventsList associated with this operation, if any.
if (op.eventsToInsert) {
op.eventsToInsert.delete();
}
}
});
};
export const addUndeclaredVariables = ({
project,
scene,
undeclaredVariables,
}: {|
project: gdProject,
scene: gdLayout,
undeclaredVariables: Array<AiGeneratedEventUndeclaredVariable>,
|}) => {
undeclaredVariables.forEach(variable => {
const { name, type, requiredScope } = variable;
let newVariable = null;
if (requiredScope === 'global') {
if (!project.getVariables().has(name)) {
newVariable = project.getVariables().insertNew(name, 0);
}
} else if (requiredScope === 'scene' || requiredScope === 'none') {
if (!scene.getVariables().has(name)) {
newVariable = scene.getVariables().insertNew(name, 0);
}
} else {
console.warn(
`Unknown requiredScope for undeclared variable: ${name}. Skipping.`
);
}
if (newVariable && type) {
const lowerCaseType = type.toLowerCase();
newVariable.castTo(
lowerCaseType === 'string'
? 'String'
: lowerCaseType === 'boolean'
? 'Boolean'
: lowerCaseType === 'array'
? 'Array'
: lowerCaseType === 'structure'
? 'Structure'
: 'Number'
);
}
});
};
export const addObjectUndeclaredVariables = ({
project,
scene,
objectName,
undeclaredVariables,
}: {|
project: gdProject,
scene: gdLayout,
objectName: string,
undeclaredVariables: Array<AiGeneratedEventUndeclaredVariable>,
|}) => {
const projectScopedContainers = gd.ProjectScopedContainers.makeNewProjectScopedContainersForProjectAndLayout(
project,
scene
);
const setupVariable = (variable: gdVariable, type: string | null) => {
if (!type) {
return;
}
const lowerCaseType = type.toLowerCase();
variable.castTo(
lowerCaseType === 'string'
? 'String'
: lowerCaseType === 'boolean'
? 'Boolean'
: lowerCaseType === 'array'
? 'Array'
: lowerCaseType === 'structure'
? 'Structure'
: 'Number'
);
};
const addVariableForObjectsOfGroup = (
group: gdObjectGroup,
undeclaredVariable: AiGeneratedEventUndeclaredVariable
) => {
const groupVariablesContainer = gd.ObjectVariableHelper.mergeVariableContainers(
projectScopedContainers.getObjectsContainersList(),
group
);
const originalSerializedVariables = new gd.SerializerElement();
groupVariablesContainer.serializeTo(originalSerializedVariables);
const variable = groupVariablesContainer.insertNew(
undeclaredVariable.name,
0
);
setupVariable(variable, undeclaredVariable.type);
const changeset = gd.WholeProjectRefactorer.computeChangesetForVariablesContainer(
originalSerializedVariables,
groupVariablesContainer
);
originalSerializedVariables.delete();
gd.WholeProjectRefactorer.applyRefactoringForGroupVariablesContainer(
project,
project.getObjects(),
scene.getObjects(),
scene.getInitialInstances(),
groupVariablesContainer,
group,
changeset,
originalSerializedVariables
);
};
undeclaredVariables.forEach(undeclaredVariable => {
if (
projectScopedContainers
.getObjectsContainersList()
.hasObjectOrGroupWithVariableNamed(objectName, undeclaredVariable.name)
) {
// Variable already exists, no need to add it.
return;
}
if (scene.getObjects().hasObjectNamed(objectName)) {
const object = scene.getObjects().getObject(objectName);
const variable = object
.getVariables()
.insertNew(undeclaredVariable.name, 0);
setupVariable(variable, undeclaredVariable.type);
} else if (
scene
.getObjects()
.getObjectGroups()
.has(objectName)
) {
const group = scene
.getObjects()
.getObjectGroups()
.get(objectName);
addVariableForObjectsOfGroup(group, undeclaredVariable);
} else if (project.getObjects().hasObjectNamed(objectName)) {
const object = project.getObjects().getObject(objectName);
const variable = object
.getVariables()
.insertNew(undeclaredVariable.name, 0);
setupVariable(variable, undeclaredVariable.type);
}
if (
project
.getObjects()
.getObjectGroups()
.has(objectName)
) {
const group = project
.getObjects()
.getObjectGroups()
.get(objectName);
addVariableForObjectsOfGroup(group, undeclaredVariable);
}
});
};

View File

@@ -1,376 +0,0 @@
// @flow
import { applyEventsChanges } from './ApplyEventsChanges';
import { type AiGeneratedEventChange } from '../Utils/GDevelopServices/Generation';
const gd: libGDevelop = global.gd;
describe('applyEventsChanges', () => {
let project: gdProject;
let sceneEventsList: gdEventsList;
let newEventsForInsertionJson = ` [{"type":"BuiltinCommonInstructions::Standard","conditions":[],"actions":[]},{"type":"BuiltinCommonInstructions::Standard","conditions":[],"actions":[]}]`;
const fakeGeneratedEventId = 'fakeGeneratedEventId';
beforeEach(() => {
project = new gd.ProjectHelper.createNewGDJSProject();
sceneEventsList = new gd.EventsList();
});
afterEach(() => {
sceneEventsList.delete();
project.delete();
});
const setupInitialSceneEvents = (eventTypes: Array<string>) => {
sceneEventsList.clear();
eventTypes.forEach((type, index) => {
sceneEventsList.insertNewEvent(project, type, index);
});
};
const getEventTypes = (list: gdEventsList): Array<string> => {
const types = [];
for (let i = 0; i < list.getEventsCount(); i++) {
types.push(list.getEventAt(i).getType());
}
return types;
};
it('should delete an event at the specified path', () => {
setupInitialSceneEvents([
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Comment',
'BuiltinCommonInstructions::Standard',
]);
// Path "event-1" targets index 1 (the second event)
const eventOperations: Array<AiGeneratedEventChange> = [
{
operationName: 'delete_event',
operationTargetEvent: 'event-1',
generatedEvents: null,
isEventsJsonValid: null,
areEventsValid: null,
diagnosticLines: [],
extensionNames: [],
undeclaredVariables: [],
undeclaredObjectVariables: {},
},
];
applyEventsChanges(
project,
sceneEventsList,
eventOperations,
fakeGeneratedEventId
);
expect(sceneEventsList.getEventsCount()).toBe(2);
expect(sceneEventsList.getEventAt(0).getType()).toBe(
'BuiltinCommonInstructions::Standard'
);
expect(sceneEventsList.getEventAt(1).getType()).toBe(
'BuiltinCommonInstructions::Standard'
);
});
it('should delete a sub-event', () => {
sceneEventsList.clear();
const parentEvent = gd.asGroupEvent(
sceneEventsList.insertNewEvent(
project,
'BuiltinCommonInstructions::Group',
0
)
);
const subEvents = parentEvent.getSubEvents();
subEvents.insertNewEvent(project, 'BuiltinCommonInstructions::Comment', 0); // sub-event 0
subEvents.insertNewEvent(project, 'BuiltinCommonInstructions::Standard', 1); // sub-event 1 (to delete)
// Path "event-0.1" targets parent at index 0, sub-event at its index 1
const eventOperations: Array<AiGeneratedEventChange> = [
{
operationName: 'delete_event',
operationTargetEvent: 'event-0.1',
generatedEvents: null,
isEventsJsonValid: null,
areEventsValid: null,
diagnosticLines: [],
extensionNames: [],
undeclaredVariables: [],
undeclaredObjectVariables: {},
},
];
applyEventsChanges(
project,
sceneEventsList,
eventOperations,
fakeGeneratedEventId
);
const finalParentEvent = sceneEventsList.getEventAt(0);
expect(finalParentEvent.getSubEvents().getEventsCount()).toBe(1);
expect(
finalParentEvent
.getSubEvents()
.getEventAt(0)
.getType()
).toBe('BuiltinCommonInstructions::Comment');
});
it('should insert events before a specified path', () => {
setupInitialSceneEvents([
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Repeat',
]);
// Path "event-1" means insert at index 1 (before Repeat)
const eventOperations: Array<AiGeneratedEventChange> = [
{
operationName: 'insert_before_event',
operationTargetEvent: 'event-1',
generatedEvents: newEventsForInsertionJson,
isEventsJsonValid: true,
areEventsValid: true,
diagnosticLines: [],
extensionNames: [],
undeclaredVariables: [],
undeclaredObjectVariables: {},
},
];
applyEventsChanges(
project,
sceneEventsList,
eventOperations,
fakeGeneratedEventId
);
// Expected: S0, NewS, NewS, R1
expect(sceneEventsList.getEventsCount()).toBe(4);
expect(getEventTypes(sceneEventsList)).toEqual([
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Repeat',
]);
});
it('should append events if path targets end of list', () => {
setupInitialSceneEvents([
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Repeat',
]); // S0, R1. Count = 2
const eventOperations: Array<AiGeneratedEventChange> = [
{
operationName: 'insert_at_end',
operationTargetEvent: null,
generatedEvents: newEventsForInsertionJson,
isEventsJsonValid: true,
areEventsValid: true,
diagnosticLines: [],
extensionNames: [],
undeclaredVariables: [],
undeclaredObjectVariables: {},
},
];
applyEventsChanges(
project,
sceneEventsList,
eventOperations,
fakeGeneratedEventId
);
// Expected: S0, R1, NewS, NewS
expect(sceneEventsList.getEventsCount()).toBe(4);
expect(getEventTypes(sceneEventsList)).toEqual([
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Repeat',
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Standard',
]);
});
it('should insert events as sub-events', () => {
setupInitialSceneEvents([
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Group',
]); // S0, G1
// Path "event-1" targets parent at index 1 ('Group')
const eventOperations: Array<AiGeneratedEventChange> = [
{
operationName: 'insert_as_sub_event',
operationTargetEvent: 'event-1',
generatedEvents: newEventsForInsertionJson,
isEventsJsonValid: true,
areEventsValid: true,
diagnosticLines: [],
extensionNames: [],
undeclaredVariables: [],
undeclaredObjectVariables: {},
},
];
applyEventsChanges(
project,
sceneEventsList,
eventOperations,
fakeGeneratedEventId
);
const parentEvent = sceneEventsList.getEventAt(1);
expect(parentEvent.getSubEvents().getEventsCount()).toBe(2);
expect(getEventTypes(parentEvent.getSubEvents())).toEqual([
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Standard',
]);
});
it('should replace an event', () => {
setupInitialSceneEvents([
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Repeat',
'BuiltinCommonInstructions::While',
]);
// Path "event-1" targets index 1 ('Repeat') for replacement
const eventOperations: Array<AiGeneratedEventChange> = [
{
operationName: 'insert_and_replace_event',
operationTargetEvent: 'event-1',
generatedEvents: newEventsForInsertionJson,
isEventsJsonValid: true,
areEventsValid: true,
diagnosticLines: [],
extensionNames: [],
undeclaredVariables: [],
undeclaredObjectVariables: {},
},
];
applyEventsChanges(
project,
sceneEventsList,
eventOperations,
fakeGeneratedEventId
);
// Expected: S0, NewS, NewS, W2 (original R1 is gone, 2 new events inserted)
expect(sceneEventsList.getEventsCount()).toBe(4);
expect(getEventTypes(sceneEventsList)).toEqual([
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::While',
]);
});
it('should process deletions before insertions when paths are sorted', () => {
setupInitialSceneEvents([
'BuiltinCommonInstructions::Standard',
'BuiltinCommonInstructions::Repeat',
'BuiltinCommonInstructions::While',
'BuiltinCommonInstructions::ForEach',
]);
// Delete W2 (idx 2, path "event-2")
// Insert new before R1 (idx 1, path "event-1")
const eventOperations: Array<AiGeneratedEventChange> = [
{
operationName: 'delete_event',
operationTargetEvent: 'event-2',
generatedEvents: null,
isEventsJsonValid: null,
areEventsValid: null,
diagnosticLines: [],
extensionNames: [],
undeclaredVariables: [],
undeclaredObjectVariables: {},
},
{
operationName: 'insert_before_event',
operationTargetEvent: 'event-1',
generatedEvents: newEventsForInsertionJson,
isEventsJsonValid: true,
areEventsValid: true,
diagnosticLines: [],
extensionNames: [],
undeclaredVariables: [],
undeclaredObjectVariables: {},
},
];
applyEventsChanges(
project,
sceneEventsList,
eventOperations,
fakeGeneratedEventId
);
// Initial: S0, R1, W2, F3
// After del W2: S0, R1, F3
// After insert new before R1: S0, NewS, NewS, R1, F3
expect(sceneEventsList.getEventsCount()).toBe(5);
expect(getEventTypes(sceneEventsList)).toEqual([
'BuiltinCommonInstructions::Standard', // S0
'BuiltinCommonInstructions::Standard', // NewS
'BuiltinCommonInstructions::Standard', // NewS
'BuiltinCommonInstructions::Repeat', // R1
'BuiltinCommonInstructions::ForEach', // F3
]);
});
it('should warn and skip insert if no generatedEvents provided for an insert operation', () => {
setupInitialSceneEvents(['BuiltinCommonInstructions::Standard']);
const consoleWarnSpy = jest
.spyOn(console, 'warn')
.mockImplementation(() => {});
const eventOperations: Array<AiGeneratedEventChange> = [
{
operationName: 'insert_before_event',
operationTargetEvent: 'event-1', // Insert at index 1 (append)
generatedEvents: null, // No events provided
isEventsJsonValid: null,
areEventsValid: null,
diagnosticLines: [],
extensionNames: [],
undeclaredVariables: [],
undeclaredObjectVariables: {},
},
];
applyEventsChanges(
project,
sceneEventsList,
eventOperations,
fakeGeneratedEventId
);
expect(sceneEventsList.getEventsCount()).toBe(1); // No events added
expect(consoleWarnSpy).toHaveBeenCalledWith(
expect.stringContaining(
'Insert operation for path [1] skipped: no events to insert or events list is empty'
)
);
consoleWarnSpy.mockRestore();
});
it('should skip invalid delete path (out of bounds) gracefully and log error', () => {
setupInitialSceneEvents(['BuiltinCommonInstructions::Standard']);
const consoleErrorSpy = jest
.spyOn(console, 'error')
.mockImplementation(() => {});
const eventOperations: Array<AiGeneratedEventChange> = [
{
operationName: 'delete_event',
operationTargetEvent: 'event-5', // Path "event-5" targets index 5, out of bounds
generatedEvents: null,
isEventsJsonValid: null,
areEventsValid: null,
diagnosticLines: [],
extensionNames: [],
undeclaredVariables: [],
undeclaredObjectVariables: {},
},
];
applyEventsChanges(
project,
sceneEventsList,
eventOperations,
fakeGeneratedEventId
);
expect(sceneEventsList.getEventsCount()).toBe(1); // No change
expect(consoleErrorSpy).toHaveBeenCalledWith(
expect.stringContaining(
'Error applying event operation type delete for path [5]'
),
expect.any(Error)
);
consoleErrorSpy.mockRestore();
});
});

View File

@@ -1,174 +0,0 @@
// @flow
const gd: libGDevelop = global.gd;
const readOrInferVariableType = (
specifiedType: string | null,
value: string
): string => {
if (specifiedType) {
const lowercaseSpecifiedType = specifiedType.toLowerCase();
if (lowercaseSpecifiedType === 'string') {
return 'String';
} else if (lowercaseSpecifiedType === 'number') {
return 'Number';
} else if (lowercaseSpecifiedType === 'boolean') {
return 'Boolean';
}
}
if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {
return 'Boolean';
}
const numberValue = Number(value);
if (!Number.isNaN(numberValue)) {
return 'Number';
}
return 'String';
};
// Parse variable path to handle both dot notation and array indexing
const parseVariablePath = (
variablePath: string
): Array<{| type: 'property' | 'index', value: string |}> => {
const segments = [];
let currentSegment = '';
let i = 0;
while (i < variablePath.length) {
const char = variablePath[i];
if (char === '.') {
// End of property segment
if (currentSegment.trim()) {
segments.push({ type: 'property', value: currentSegment.trim() });
currentSegment = '';
}
i++;
} else if (char === '[') {
// Start of array index
if (currentSegment.trim()) {
segments.push({ type: 'property', value: currentSegment.trim() });
currentSegment = '';
}
// Find the closing bracket
i++; // Skip opening bracket
let indexContent = '';
let foundClosingBracketWithProperIndex = false;
while (i < variablePath.length && variablePath[i] !== ']') {
indexContent += variablePath[i];
i++;
}
if (i < variablePath.length && variablePath[i] === ']') {
// Valid array index
const indexValue = indexContent.trim();
if (indexValue && !isNaN(parseInt(indexValue, 10))) {
segments.push({ type: 'index', value: indexValue });
foundClosingBracketWithProperIndex = true;
} else {
throw new Error(
`Content of the index is invalid ("${indexValue}") - it should be a number.`
);
}
i++; // Skip closing bracket
}
if (!foundClosingBracketWithProperIndex) {
throw new Error(
'Improperly formatted array index. Please check the variable path - it should be formatted like this: `myVar[1].prop`, `myVar`, `myVar.prop`, etc...'
);
}
} else {
currentSegment += char;
i++;
}
}
// Add remaining segment
if (currentSegment.trim()) {
segments.push({ type: 'property', value: currentSegment.trim() });
}
console.log('segments', segments);
return segments;
};
export const applyVariableChange = ({
variablePath,
forcedVariableType,
variablesContainer,
value,
}: {|
variablePath: string,
forcedVariableType: string | null,
variablesContainer: gd.VariablesContainer,
value: string,
|}) => {
const pathSegments = parseVariablePath(variablePath);
if (pathSegments.length === 0) {
throw new Error('Invalid variable path');
}
let addedNewVariable = false;
const firstSegment = pathSegments[0];
if (firstSegment.type !== 'property') {
throw new Error('Variable path must start with a property name');
}
const firstVariableName = firstSegment.value;
let variable = null;
if (!variablesContainer.has(firstVariableName)) {
variable = variablesContainer.insertNew(firstVariableName, 0);
addedNewVariable = true;
} else {
variable = variablesContainer.get(firstVariableName);
}
for (let i = 1; i < pathSegments.length; i++) {
const segment = pathSegments[i];
if (segment.type === 'property') {
// Navigate to structure property
variable.castTo('Structure');
if (!variable.hasChild(segment.value)) {
addedNewVariable = true;
}
variable = variable.getChild(segment.value);
} else if (segment.type === 'index') {
// Navigate to array element
const index = parseInt(segment.value, 10);
variable.castTo('Array');
// Ensure array has enough elements
while (variable.getChildrenCount() <= index) {
variable.pushNew();
addedNewVariable = true;
}
variable = variable.getAtIndex(index);
}
}
const variableType = readOrInferVariableType(forcedVariableType, value);
if (variableType === 'String') {
variable.setString(value);
} else if (variableType === 'Number') {
variable.setValue(parseFloat(value));
} else if (variableType === 'Boolean') {
variable.setBool(value.toLowerCase() === 'true');
}
return {
variable,
variableType,
addedNewVariable,
};
};

View File

@@ -1,399 +0,0 @@
// @flow
import { applyVariableChange } from './ApplyVariableChange';
const gd: libGDevelop = global.gd;
describe('applyVariableChange', () => {
let variablesContainer: gdVariablesContainer;
beforeEach(() => {
variablesContainer = new gd.VariablesContainer(
gd.VariablesContainer.Unknown
);
});
afterEach(() => {
variablesContainer.delete();
});
describe('Root variable modification', () => {
it('should create and set a new root string variable', () => {
const result = applyVariableChange({
variablePath: 'myVariable',
forcedVariableType: null,
variablesContainer,
value: 'hello world',
});
expect(result.addedNewVariable).toBe(true);
expect(variablesContainer.has('myVariable')).toBe(true);
const variable = variablesContainer.get('myVariable');
expect(variable.getType()).toBe(gd.Variable.String);
expect(variable.getString()).toBe('hello world');
});
it('should create and set a new root number variable', () => {
const result = applyVariableChange({
variablePath: 'myNum',
forcedVariableType: null,
variablesContainer,
value: '42.5',
});
expect(result.addedNewVariable).toBe(true);
expect(variablesContainer.has('myNum')).toBe(true);
const variable = variablesContainer.get('myNum');
expect(variable.getType()).toBe(gd.Variable.Number);
expect(variable.getValue()).toBe(42.5);
});
it('should create and set a new root boolean variable', () => {
const result = applyVariableChange({
variablePath: 'myBool',
forcedVariableType: null,
variablesContainer,
value: 'true',
});
expect(result.addedNewVariable).toBe(true);
expect(variablesContainer.has('myBool')).toBe(true);
const variable = variablesContainer.get('myBool');
expect(variable.getType()).toBe(gd.Variable.Boolean);
expect(variable.getBool()).toBe(true);
});
it('should modify an existing root variable', () => {
// Setup existing variable
const existingVar = variablesContainer.insertNew('existing', 0);
existingVar.setString('old value');
const result = applyVariableChange({
variablePath: 'existing',
forcedVariableType: null,
variablesContainer,
value: 'new value',
});
expect(result.addedNewVariable).toBe(false);
expect(variablesContainer.get('existing').getString()).toBe('new value');
});
it('should respect forced variable type', () => {
const result = applyVariableChange({
variablePath: 'forcedString',
forcedVariableType: 'String',
variablesContainer,
value: '123',
});
expect(result.addedNewVariable).toBe(true);
const variable = variablesContainer.get('forcedString');
expect(variable.getType()).toBe(gd.Variable.String);
expect(variable.getString()).toBe('123');
});
});
describe('Structure child modification', () => {
it('should create a new structure with child property', () => {
const result = applyVariableChange({
variablePath: 'myStruct.childProperty',
forcedVariableType: null,
variablesContainer,
value: 'child value',
});
expect(result.addedNewVariable).toBe(true);
expect(variablesContainer.has('myStruct')).toBe(true);
const structVar = variablesContainer.get('myStruct');
expect(structVar.getType()).toBe(gd.Variable.Structure);
expect(structVar.hasChild('childProperty')).toBe(true);
const childVar = structVar.getChild('childProperty');
expect(childVar.getType()).toBe(gd.Variable.String);
expect(childVar.getString()).toBe('child value');
});
it('should add property to existing structure', () => {
// Setup existing structure
const existingStruct = variablesContainer.insertNew('existingStruct', 0);
existingStruct.castTo('Structure');
existingStruct.getChild('existingProp').setString('existing');
const result = applyVariableChange({
variablePath: 'existingStruct.newProperty',
forcedVariableType: null,
variablesContainer,
value: 'new prop value',
});
expect(result.addedNewVariable).toBe(true);
expect(existingStruct.hasChild('existingProp')).toBe(true);
expect(existingStruct.hasChild('newProperty')).toBe(true);
expect(existingStruct.getChild('newProperty').getString()).toBe(
'new prop value'
);
});
it('should handle nested structure properties', () => {
const result = applyVariableChange({
variablePath: 'level1.level2.level3',
forcedVariableType: null,
variablesContainer,
value: 'deep value',
});
expect(result.addedNewVariable).toBe(true);
const level1 = variablesContainer.get('level1');
expect(level1.getType()).toBe(gd.Variable.Structure);
const level2 = level1.getChild('level2');
expect(level2.getType()).toBe(gd.Variable.Structure);
const level3 = level2.getChild('level3');
expect(level3.getString()).toBe('deep value');
});
});
describe('Array item modification', () => {
it('should create a new array and set item at index', () => {
const result = applyVariableChange({
variablePath: 'myArray[2]',
forcedVariableType: null,
variablesContainer,
value: 'third item',
});
expect(result.addedNewVariable).toBe(true);
expect(variablesContainer.has('myArray')).toBe(true);
const arrayVar = variablesContainer.get('myArray');
expect(arrayVar.getType()).toBe(gd.Variable.Array);
expect(arrayVar.getChildrenCount()).toBe(3); // indices 0, 1, 2
const itemVar = arrayVar.getAtIndex(2);
expect(itemVar.getString()).toBe('third item');
});
it('should expand array when accessing higher index', () => {
// Setup existing array with 2 items
const existingArray = variablesContainer.insertNew('existingArray', 0);
existingArray.castTo('Array');
existingArray.pushNew().setString('item0');
existingArray.pushNew().setString('item1');
const result = applyVariableChange({
variablePath: 'existingArray[4]',
forcedVariableType: null,
variablesContainer,
value: 'item4',
});
expect(result.addedNewVariable).toBe(true);
expect(existingArray.getChildrenCount()).toBe(5); // indices 0-4
expect(existingArray.getAtIndex(0).getString()).toBe('item0');
expect(existingArray.getAtIndex(1).getString()).toBe('item1');
expect(existingArray.getAtIndex(4).getString()).toBe('item4');
});
it('should handle array index with whitespace', () => {
const result = applyVariableChange({
variablePath: 'myArray[ 1 ]',
forcedVariableType: null,
variablesContainer,
value: 'spaced index',
});
expect(result.addedNewVariable).toBe(true);
const arrayVar = variablesContainer.get('myArray');
expect(arrayVar.getAtIndex(1).getString()).toBe('spaced index');
});
it('should modify existing array item', () => {
// Setup existing array
const existingArray = variablesContainer.insertNew('existingArray', 0);
existingArray.castTo('Array');
existingArray.pushNew().setString('original');
applyVariableChange({
variablePath: 'existingArray[0]',
forcedVariableType: null,
variablesContainer,
value: 'modified',
});
expect(existingArray.getAtIndex(0).getString()).toBe('modified');
});
});
describe('Mixed structure and array access', () => {
it('should handle array item with structure property', () => {
const result = applyVariableChange({
variablePath: 'myArray[1].itemProperty',
forcedVariableType: null,
variablesContainer,
value: 'nested value',
});
expect(result.addedNewVariable).toBe(true);
const arrayVar = variablesContainer.get('myArray');
expect(arrayVar.getType()).toBe(gd.Variable.Array);
expect(arrayVar.getChildrenCount()).toBe(2); // indices 0, 1
const itemVar = arrayVar.getAtIndex(1);
expect(itemVar.getType()).toBe(gd.Variable.Structure);
expect(itemVar.hasChild('itemProperty')).toBe(true);
expect(itemVar.getChild('itemProperty').getString()).toBe('nested value');
});
it('should handle structure with array property', () => {
const result = applyVariableChange({
variablePath: 'myStruct.arrayProp[2]',
forcedVariableType: null,
variablesContainer,
value: 'array in struct',
});
expect(result.addedNewVariable).toBe(true);
const structVar = variablesContainer.get('myStruct');
expect(structVar.getType()).toBe(gd.Variable.Structure);
const arrayProp = structVar.getChild('arrayProp');
expect(arrayProp.getType()).toBe(gd.Variable.Array);
expect(arrayProp.getChildrenCount()).toBe(3);
expect(arrayProp.getAtIndex(2).getString()).toBe('array in struct');
});
it('should handle complex nested paths', () => {
const result = applyVariableChange({
variablePath: 'players[0].inventory.items[2].name',
forcedVariableType: null,
variablesContainer,
value: 'Magic Sword',
});
expect(result.addedNewVariable).toBe(true);
const players = variablesContainer.get('players');
const player0 = players.getAtIndex(0);
const inventory = player0.getChild('inventory');
const items = inventory.getChild('items');
const item2 = items.getAtIndex(2);
const name = item2.getChild('name');
expect(name.getString()).toBe('Magic Sword');
});
});
describe('Error cases', () => {
it('should throw error for empty path', () => {
expect(() => {
applyVariableChange({
variablePath: '',
forcedVariableType: null,
variablesContainer,
value: 'test',
});
}).toThrow('Invalid variable path');
});
it('should throw error for path starting with array index', () => {
expect(() => {
applyVariableChange({
variablePath: '[0]',
forcedVariableType: null,
variablesContainer,
value: 'test',
});
}).toThrow('Variable path must start with a property name');
});
it('should handle invalid array index gracefully', () => {
// Note: The current implementation filters out invalid indexes,
// so this test verifies that behavior
expect(() => {
applyVariableChange({
variablePath: 'myVar[wrong wrong].prop',
forcedVariableType: null,
variablesContainer,
value: 'test',
});
}).toThrow(
'Content of the index is invalid ("wrong wrong") - it should be a number.'
);
});
it('should handle malformed brackets', () => {
expect(() => {
applyVariableChange({
variablePath: 'malformedVar[1.prop',
forcedVariableType: null,
variablesContainer,
value: 'test',
});
}).toThrow(
'Improperly formatted array index. Please check the variable path - it should be formatted like this: `myVar[1].prop`, `myVar`, `myVar.prop`, etc...'
);
});
});
describe('Type inference', () => {
it('should infer boolean type from "true"', () => {
applyVariableChange({
variablePath: 'testBool',
forcedVariableType: null,
variablesContainer,
value: 'true',
});
const variable = variablesContainer.get('testBool');
expect(variable.getType()).toBe(gd.Variable.Boolean);
expect(variable.getBool()).toBe(true);
});
it('should infer boolean type from "false"', () => {
applyVariableChange({
variablePath: 'testBool',
forcedVariableType: null,
variablesContainer,
value: 'FALSE',
});
const variable = variablesContainer.get('testBool');
expect(variable.getType()).toBe(gd.Variable.Boolean);
expect(variable.getBool()).toBe(false);
});
it('should infer number type from numeric strings', () => {
applyVariableChange({
variablePath: 'testNum',
forcedVariableType: null,
variablesContainer,
value: '3.14159',
});
const variable = variablesContainer.get('testNum');
expect(variable.getType()).toBe(gd.Variable.Number);
expect(variable.getValue()).toBe(3.14159);
});
it('should default to string type for mixed content', () => {
applyVariableChange({
variablePath: 'testString',
forcedVariableType: null,
variablesContainer,
value: '123abc',
});
const variable = variablesContainer.get('testString');
expect(variable.getType()).toBe(gd.Variable.String);
expect(variable.getString()).toBe('123abc');
});
});
});

View File

@@ -1,166 +0,0 @@
// @flow
import { type EventsGenerationResult } from '.';
import {
editorFunctions,
type EditorFunction,
type EditorCallbacks,
type EditorFunctionCall,
type EditorFunctionGenericOutput,
type EventsGenerationOptions,
type AssetSearchAndInstallOptions,
type AssetSearchAndInstallResult,
} from '.';
export type EditorFunctionCallResult =
| {|
status: 'working',
call_id: string,
|}
| {|
status: 'finished',
call_id: string,
success: boolean,
output: any,
|}
| {|
status: 'ignored',
call_id: string,
|};
export type ProcessEditorFunctionCallsOptions = {|
project: gdProject,
functionCalls: Array<EditorFunctionCall>,
editorCallbacks: EditorCallbacks,
ignore: boolean,
generateEvents: (
options: EventsGenerationOptions
) => Promise<EventsGenerationResult>,
onSceneEventsModifiedOutsideEditor: (scene: gdLayout) => void,
ensureExtensionInstalled: (options: {|
extensionName: string,
|}) => Promise<void>,
searchAndInstallAsset: (
options: AssetSearchAndInstallOptions
) => Promise<AssetSearchAndInstallResult>,
|};
export const processEditorFunctionCalls = async ({
functionCalls,
project,
editorCallbacks,
generateEvents,
onSceneEventsModifiedOutsideEditor,
ignore,
ensureExtensionInstalled,
searchAndInstallAsset,
}: ProcessEditorFunctionCallsOptions): Promise<
Array<EditorFunctionCallResult>
> => {
const results: Array<EditorFunctionCallResult> = [];
for (const functionCall of functionCalls) {
const call_id = functionCall.call_id;
if (ignore) {
results.push({
status: 'ignored',
call_id,
});
continue;
}
const name = functionCall.name;
let args;
try {
try {
args = JSON.parse(functionCall.arguments);
} catch (error) {
console.error('Error parsing arguments: ', error);
results.push({
status: 'finished',
call_id,
success: false,
output: {
message: 'Invalid arguments (not a valid JSON string).',
},
});
}
if (name === null) {
results.push({
status: 'finished',
call_id,
success: false,
output: {
message: 'Missing or invalid function name.',
},
});
continue;
}
if (args === null) {
results.push({
status: 'finished',
call_id,
success: false,
output: {
message: `Invalid arguments for function: ${name}.`,
},
});
continue;
}
// Check if the function exists
const editorFunction: EditorFunction | null =
editorFunctions[name] || null;
if (!editorFunction) {
results.push({
status: 'finished',
call_id,
success: false,
output: {
message: `Unknown function: ${name}.`,
},
});
continue;
}
// Execute the function
const result: EditorFunctionGenericOutput = await editorFunction.launchFunction(
{
project,
args,
generateEvents,
onSceneEventsModifiedOutsideEditor,
ensureExtensionInstalled,
searchAndInstallAsset,
}
);
const { success, ...output } = result;
results.push({
status: 'finished',
call_id,
success,
output,
});
if (success && args) {
if (typeof args.scene_name === 'string') {
editorCallbacks.onOpenLayout(args.scene_name, {
openEventsEditor: true,
openSceneEditor: true,
focusWhenOpened: 'none',
});
}
}
} catch (error) {
results.push({
status: 'finished',
call_id,
success: false,
output: { message: error.message || 'Unknown error' },
});
}
}
return results;
};

View File

@@ -1,279 +0,0 @@
// @flow
import { mapFor } from '../../Utils/MapFor';
export type ParameterSummary = {|
isCodeOnly?: boolean,
name?: string,
type: string,
description?: string,
isOptional?: boolean,
extraInfo?: string,
|};
/**
* A simplified summary of an instruction.
*/
export type InstructionSummary = {|
type: string,
description: string,
parameters: Array<ParameterSummary>,
hidden?: boolean,
relevantForSceneEvents?: boolean,
|};
/**
* A simplified summary of an expression.
*/
export type ExpressionSummary = {|
type: string,
description: string,
parameters: Array<ParameterSummary>,
hidden?: boolean,
relevantForSceneEvents?: boolean,
|};
export type ObjectSummary = {|
name: string,
fullName: string,
description: string,
actions: Array<InstructionSummary>,
conditions: Array<InstructionSummary>,
expressions: Array<ExpressionSummary>,
|};
export type BehaviorSummary = {|
name: string,
fullName: string,
description: string,
objectType?: string,
actions: Array<InstructionSummary>,
conditions: Array<InstructionSummary>,
expressions: Array<ExpressionSummary>,
|};
export type ExtensionSummary = {|
extensionName: string,
extensionFullName: string,
description: string,
freeActions: Array<InstructionSummary>,
freeConditions: Array<InstructionSummary>,
freeExpressions: Array<ExpressionSummary>,
objects: { [string]: ObjectSummary },
behaviors: { [string]: BehaviorSummary },
|};
const normalizeType = (parameterType: string) => {
if (parameterType === 'expression') return 'number';
if (
parameterType === 'object' ||
parameterType === 'objectPtr' ||
parameterType === 'objectList' ||
parameterType === 'objectListOrEmptyIfJustDeclared' ||
parameterType === 'objectListOrEmptyWithoutPicking'
) {
return 'object';
}
return parameterType;
};
const getParameterSummary = (
parameterMetadata: gdParameterMetadata
): ParameterSummary => {
const parameterSummary: ParameterSummary = {
type: normalizeType(parameterMetadata.getType()),
};
if (parameterMetadata.getDescription()) {
parameterSummary.description = parameterMetadata.getDescription();
}
if (parameterMetadata.getName()) {
parameterSummary.name = parameterMetadata.getName();
}
if (parameterMetadata.isCodeOnly()) {
parameterSummary.isCodeOnly = true;
}
if (parameterMetadata.isOptional()) {
parameterSummary.isOptional = true;
}
if (parameterMetadata.getExtraInfo()) {
parameterSummary.extraInfo = parameterMetadata.getExtraInfo();
}
return parameterSummary;
};
export const buildExtensionSummary = ({
gd,
extension,
}: {
gd: libGDevelop,
extension: gdPlatformExtension,
}): ExtensionSummary => {
const objects: { [string]: ObjectSummary } = {};
const behaviors: { [string]: BehaviorSummary } = {};
const generateInstructionsSummaries = ({
instructionsMetadata,
}: {
instructionsMetadata: gdMapStringInstructionMetadata,
}) => {
const instructionTypes = instructionsMetadata.keys().toJSArray();
return instructionTypes
.map(instructionType => {
const instructionMetadata = instructionsMetadata.get(instructionType);
if (instructionMetadata.isPrivate()) return null;
const instructionSummary: InstructionSummary = {
type: instructionType,
description: instructionMetadata.getDescription(),
parameters: mapFor(
0,
instructionMetadata.getParameters().getParametersCount(),
index => {
const parameterMetadata = instructionMetadata.getParameter(index);
return getParameterSummary(parameterMetadata);
}
),
};
if (instructionMetadata.isHidden()) {
instructionSummary.hidden = true;
}
if (!instructionMetadata.isRelevantForLayoutEvents()) {
instructionSummary.relevantForSceneEvents = false;
}
return instructionSummary;
})
.filter(Boolean);
};
const generateExpressionSummaries = ({
expressionsMetadata,
}: {
expressionsMetadata: gdMapStringExpressionMetadata,
}) => {
const expressionTypes = expressionsMetadata.keys().toJSArray();
return expressionTypes
.map(expressionType => {
const expressionMetadata = expressionsMetadata.get(expressionType);
if (expressionMetadata.isPrivate()) return null;
const expressionSummary: ExpressionSummary = {
type: expressionType,
description: expressionMetadata.getDescription(),
parameters: mapFor(
0,
expressionMetadata.getParameters().getParametersCount(),
index => {
const parameterMetadata = expressionMetadata.getParameter(index);
return getParameterSummary(parameterMetadata);
}
),
};
if (!expressionMetadata.isShown()) {
expressionSummary.hidden = true;
}
if (!expressionMetadata.isRelevantForLayoutEvents()) {
expressionSummary.relevantForSceneEvents = false;
}
return expressionSummary;
})
.filter(Boolean);
};
extension
.getExtensionObjectsTypes()
.toJSArray()
.forEach(objectType => {
const objectMetadata = extension.getObjectMetadata(objectType);
if (
gd.MetadataProvider.isBadObjectMetadata(objectMetadata) ||
objectMetadata.isPrivate()
) {
return;
}
objects[objectType] = {
name: objectMetadata.getName(),
fullName: objectMetadata.getFullName(),
description: objectMetadata.getDescription(),
actions: generateInstructionsSummaries({
instructionsMetadata: objectMetadata.getAllActions(),
}),
conditions: generateInstructionsSummaries({
instructionsMetadata: objectMetadata.getAllConditions(),
}),
expressions: [
...generateExpressionSummaries({
expressionsMetadata: objectMetadata.getAllExpressions(),
}),
...generateExpressionSummaries({
expressionsMetadata: objectMetadata.getAllStrExpressions(),
}),
],
};
});
extension
.getBehaviorsTypes()
.toJSArray()
.forEach(behaviorType => {
const behaviorMetadata = extension.getBehaviorMetadata(behaviorType);
if (
gd.MetadataProvider.isBadBehaviorMetadata(behaviorMetadata) ||
behaviorMetadata.isPrivate()
) {
return;
}
const behaviorSummary: BehaviorSummary = {
name: behaviorMetadata.getName(),
fullName: behaviorMetadata.getFullName(),
description: behaviorMetadata.getDescription(),
actions: generateInstructionsSummaries({
instructionsMetadata: behaviorMetadata.getAllActions(),
}),
conditions: generateInstructionsSummaries({
instructionsMetadata: behaviorMetadata.getAllConditions(),
}),
expressions: [
...generateExpressionSummaries({
expressionsMetadata: behaviorMetadata.getAllExpressions(),
}),
...generateExpressionSummaries({
expressionsMetadata: behaviorMetadata.getAllStrExpressions(),
}),
],
};
if (behaviorMetadata.getObjectType()) {
behaviorSummary.objectType = behaviorMetadata.getObjectType();
}
behaviors[behaviorType] = behaviorSummary;
});
return {
extensionName: extension.getName(),
extensionFullName: extension.getFullName(),
description: extension.getDescription(),
freeActions: generateInstructionsSummaries({
instructionsMetadata: extension.getAllActions(),
}),
freeConditions: generateInstructionsSummaries({
instructionsMetadata: extension.getAllConditions(),
}),
freeExpressions: [
...generateExpressionSummaries({
expressionsMetadata: extension.getAllExpressions(),
}),
...generateExpressionSummaries({
expressionsMetadata: extension.getAllStrExpressions(),
}),
],
objects,
behaviors,
};
};

View File

@@ -1,386 +0,0 @@
// @flow
import { mapFor, mapVector } from '../../Utils/MapFor';
import { isCollectionVariable } from '../../Utils/VariablesUtils';
import {
buildExtensionSummary,
type ExtensionSummary,
} from './ExtensionSummary';
export type SimplifiedBehavior = {|
behaviorName: string,
behaviorType: string,
|};
type SimplifiedVariable = {|
variableName: string,
type: string,
value?: string,
variableChildren?: Array<SimplifiedVariable>,
|};
type SimplifiedObject = {|
objectName: string,
objectType: string,
behaviors?: Array<SimplifiedBehavior>,
objectVariables?: Array<SimplifiedVariable>,
animationNames?: string,
|};
type SimplifiedObjectGroup = {|
objectGroupName: string,
objectGroupType: string,
objectNames: Array<string>,
behaviors?: Array<SimplifiedBehavior>,
variables?: Array<SimplifiedVariable>,
|};
type SimplifiedScene = {|
sceneName: string,
objects: Array<SimplifiedObject>,
objectGroups: Array<SimplifiedObjectGroup>,
sceneVariables: Array<SimplifiedVariable>,
instancesOnSceneDescription: string,
|};
type SimplifiedProject = {|
globalObjects: Array<SimplifiedObject>,
globalObjectGroups: Array<SimplifiedObjectGroup>,
scenes: Array<SimplifiedScene>,
globalVariables: Array<SimplifiedVariable>,
|};
type ProjectSpecificExtensionsSummary = {|
extensionSummaries: Array<ExtensionSummary>,
|};
export type SimplifiedProjectOptions = {|
scopeToScene?: string,
|};
export const makeSimplifiedProjectBuilder = (gd: libGDevelop) => {
const getVariableType = (variable: gdVariable) => {
const type = variable.getType();
return type === gd.Variable.String
? 'String'
: type === gd.Variable.Number
? 'Number'
: type === gd.Variable.Boolean
? 'Boolean'
: type === gd.Variable.Structure
? 'Structure'
: type === gd.Variable.Array
? 'Array'
: 'unknown';
};
const getVariableValueAsString = (variable: gdVariable) => {
const type = variable.getType();
return type === gd.Variable.Structure || type === gd.Variable.Array
? variable.getChildrenCount() === 0
? `No children`
: variable.getChildrenCount() === 1
? `1 child`
: `${variable.getChildrenCount()} children`
: type === gd.Variable.String
? variable.getString()
: type === gd.Variable.Number
? variable.getValue().toString()
: type === gd.Variable.Boolean
? variable.getBool()
? `True`
: `False`
: 'unknown';
};
const getSimplifiedVariable = (
name: string,
variable: gdVariable,
depth = 0
): SimplifiedVariable => {
const isCollection = isCollectionVariable(variable);
if (isCollection) {
// Don't diplay children of arrays, and only display the first level of children of structures.
if (variable.getType() === gd.Variable.Structure && depth === 0) {
return {
variableName: name,
type: getVariableType(variable),
variableChildren: variable
.getAllChildrenNames()
.toJSArray()
.map(childName => {
const childVariable = variable.getChild(childName);
return getSimplifiedVariable(childName, childVariable, depth + 1);
}),
};
}
return {
variableName: name,
type: getVariableType(variable),
};
}
return {
variableName: name,
type: getVariableType(variable),
value: getVariableValueAsString(variable),
};
};
const getSimplifiedVariablesContainerJson = (
container: gdVariablesContainer
): Array<SimplifiedVariable> => {
return mapFor(0, Math.min(container.count(), 20), (index: number) => {
const name = container.getNameAt(index);
const variable = container.getAt(index);
return getSimplifiedVariable(name, variable);
}).filter(Boolean);
};
const getSimplifiedObject = (object: gdObject): SimplifiedObject => {
const objectVariables = getSimplifiedVariablesContainerJson(
object.getVariables()
);
const behaviors = object
.getAllBehaviorNames()
.toJSArray()
.map(behaviorName => {
const behavior = object.getBehavior(behaviorName);
return {
behaviorName: behavior.getName(),
behaviorType: behavior.getTypeName(),
};
})
.filter(Boolean);
const simplifiedObject: SimplifiedObject = {
objectName: object.getName(),
objectType: object.getType(),
};
if (behaviors.length > 0) {
simplifiedObject.behaviors = behaviors;
}
if (objectVariables.length > 0) {
simplifiedObject.objectVariables = objectVariables;
}
const objectConfiguration = object.getConfiguration();
const animationNames = mapFor(
0,
objectConfiguration.getAnimationsCount(),
i => {
return (
objectConfiguration.getAnimationName(i) ||
`(animation without name, animation index is: ${i})`
);
}
);
if (animationNames.length > 0) {
simplifiedObject.animationNames = animationNames.join(', ');
}
return simplifiedObject;
};
const getSimplifiedObjectsJson = (
objects: gdObjectsContainer
): Array<SimplifiedObject> => {
return mapFor(0, objects.getObjectsCount(), i => {
const object = objects.getObjectAt(i);
return getSimplifiedObject(object);
});
};
const getSimplifiedObjectGroups = (
objectGroups: gdObjectGroupsContainer,
objectsContainersList: gdObjectsContainersList
): Array<SimplifiedObjectGroup> => {
return mapFor(0, objectGroups.count(), i => {
const objectGroup = objectGroups.getAt(i);
const behaviorNames = objectsContainersList
.getBehaviorsOfObject(objectGroup.getName(), true)
.toJSArray();
const variablesContainer = gd.ObjectVariableHelper.mergeVariableContainers(
objectsContainersList,
objectGroup
);
return {
objectGroupName: objectGroup.getName(),
objectGroupType: objectsContainersList.getTypeOfObject(
objectGroup.getName()
),
objectNames: objectGroup.getAllObjectsNames().toJSArray(),
behaviors:
behaviorNames.length > 0
? behaviorNames.map(behaviorName => ({
behaviorName,
behaviorType: objectsContainersList.getTypeOfBehaviorInObjectOrGroup(
objectGroup.getName(),
behaviorName,
true
),
}))
: undefined,
variables:
variablesContainer.count() > 0
? getSimplifiedVariablesContainerJson(variablesContainer)
: undefined,
};
});
};
const getInstancesDescription = (scene: gdLayout): string => {
let isEmpty = true;
const instancesCountPerLayer: { [string]: { [string]: number } } = {};
const instancesListerFunctor = new gd.InitialInstanceJSFunctor();
// $FlowFixMe - invoke is not writable
instancesListerFunctor.invoke = instancePtr => {
// $FlowFixMe - wrapPointer is not exposed
const instance: gdInitialInstance = gd.wrapPointer(
instancePtr,
gd.InitialInstance
);
const name = instance.getObjectName();
if (!name) return;
const layer = instance.getLayer();
const layerInstancesCount = (instancesCountPerLayer[layer] =
instancesCountPerLayer[layer] || {});
layerInstancesCount[name] = (layerInstancesCount[name] || 0) + 1;
isEmpty = false;
};
// $FlowFixMe - JSFunctor is incompatible with Functor
scene.getInitialInstances().iterateOverInstances(instancesListerFunctor);
instancesListerFunctor.delete();
if (isEmpty) {
return 'There are no instances of objects placed on the scene - the scene is empty.';
}
const layersContainer = scene.getLayers();
return [
`On the scene, there are:`,
...mapFor(0, layersContainer.getLayersCount(), i => {
const layer = layersContainer.getLayerAt(i);
const layerName = layer.getName();
const layerInstancesCount = instancesCountPerLayer[layerName];
return [
layerName ? `- on layer "${layer.getName()}":` : `- on base layer:`,
!layerInstancesCount || Object.keys(layerInstancesCount).length === 0
? ` - Nothing (no instances)`
: Object.keys(layerInstancesCount)
.map(name => ` - ${layerInstancesCount[name]} ${name}`)
.join('\n'),
].join('\n');
}),
'',
`Inspect instances on the scene to get more details if needed.`,
].join('\n');
};
const getSimplifiedScene = (
project: gdProject,
scene: gdLayout
): SimplifiedScene => {
const projectScopedContainers = gd.ProjectScopedContainers.makeNewProjectScopedContainersForProjectAndLayout(
project,
scene
);
return {
sceneName: scene.getName(),
objects: getSimplifiedObjectsJson(scene.getObjects()),
objectGroups: getSimplifiedObjectGroups(
scene.getObjects().getObjectGroups(),
projectScopedContainers.getObjectsContainersList()
),
sceneVariables: getSimplifiedVariablesContainerJson(scene.getVariables()),
instancesOnSceneDescription: getInstancesDescription(scene),
};
};
const getSimplifiedProject = (
project: gdProject,
options: SimplifiedProjectOptions
): SimplifiedProject => {
const globalObjects = getSimplifiedObjectsJson(project.getObjects());
const scenes = mapFor(0, project.getLayoutsCount(), i => {
const scene = project.getLayoutAt(i);
if (options.scopeToScene && scene.getName() !== options.scopeToScene)
return null;
return getSimplifiedScene(project, scene);
}).filter(Boolean);
const projectScopedContainers = gd.ProjectScopedContainers.makeNewProjectScopedContainersForProject(
project
);
// Filter extensions to only include extensions from the project.
const simplifiedProject: SimplifiedProject = {
globalObjects,
globalObjectGroups: getSimplifiedObjectGroups(
project.getObjects().getObjectGroups(),
projectScopedContainers.getObjectsContainersList()
),
scenes,
globalVariables: getSimplifiedVariablesContainerJson(
project.getVariables()
),
};
return simplifiedProject;
};
const getProjectSpecificExtensionsSummary = (
project: gdProject
): ProjectSpecificExtensionsSummary => {
const startTime = Date.now();
const platform = project.getCurrentPlatform();
const allExtensions = platform.getAllPlatformExtensions();
const projectExtensionNames = new Set(
mapFor(0, project.getEventsFunctionsExtensionsCount(), i => {
const extension = project.getEventsFunctionsExtensionAt(i);
return extension.getName();
})
);
const projectSpecificExtensions: Array<gdPlatformExtension> = mapVector(
allExtensions,
extension => {
if (projectExtensionNames.has(extension.getName())) {
return extension;
}
return null;
}
).filter(Boolean);
const extensionsSummary: ProjectSpecificExtensionsSummary = {
extensionSummaries: projectSpecificExtensions.map(extension =>
buildExtensionSummary({ gd, extension })
),
};
const duration = Date.now() - startTime;
console.info(
`Project specific extensions summary generated in ${duration.toFixed(
0
)}ms`
);
return extensionsSummary;
};
return { getSimplifiedProject, getProjectSpecificExtensionsSummary };
};

View File

@@ -1,906 +0,0 @@
// @flow
import { makeSimplifiedProjectBuilder } from './SimplifiedProject';
import { makeTestProject } from '../../fixtures/TestProject';
import { makeTestExtensions } from '../../fixtures/TestExtensions';
const initializeGDevelopJs = require('libGD.js-for-tests-only');
describe('SimplifiedProject', () => {
it('should create a simplified project JSON with global objects and scenes', async () => {
const gd = await initializeGDevelopJs();
const { project } = makeTestProject(gd);
const simplifiedJson = makeSimplifiedProjectBuilder(
gd
).getSimplifiedProject(project, {});
expect(simplifiedJson).toMatchInlineSnapshot(`
Object {
"globalObjectGroups": Array [],
"globalObjects": Array [
Object {
"behaviors": Array [
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
],
"objectName": "GlobalTiledSpriteObject",
"objectType": "TiledSpriteObject::TiledSprite",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
Object {
"behaviorName": "Text",
"behaviorType": "TextContainerCapability::TextContainerBehavior",
},
],
"objectName": "GlobalTextObject",
"objectType": "TextObject::Text",
},
],
"globalVariables": Array [],
"scenes": Array [
Object {
"instancesOnSceneDescription": "On the scene, there are:
- on layer \\"GUI\\":
- Nothing (no instances)
- on layer \\"OtherLayer\\":
- Nothing (no instances)
- on base layer:
- 1 CubeObject
- 1 TextInputObject
- 1 MySpriteObject
Inspect instances on the scene to get more details if needed.",
"objectGroups": Array [
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectGroupName": "GroupOfSprites",
"objectGroupType": "Sprite",
"objectNames": Array [
"MySpriteObject",
],
"variables": Array [
Object {
"type": "String",
"value": "A multiline
str value",
"variableName": "ObjectVariable",
},
Object {
"type": "Structure",
"variableChildren": Array [
Object {
"type": "Number",
"value": "564",
"variableName": "ObjectChild1",
},
Object {
"type": "String",
"value": "Guttentag",
"variableName": "ObjectChild2",
},
Object {
"type": "Boolean",
"value": "True",
"variableName": "ObjectChild3",
},
Object {
"type": "Array",
"variableName": "ObjectChild4",
},
],
"variableName": "OtherObjectVariable",
},
],
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectGroupName": "GroupOfObjects",
"objectGroupType": "",
"objectNames": Array [
"MySpriteObject",
"MyTextObject",
],
"variables": undefined,
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Draggable",
"behaviorType": "DraggableBehavior::Draggable",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "PlatformerObject",
"behaviorType": "PlatformBehavior::PlatformerObjectBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectGroupName": "GroupOfSpriteObjectsWithBehaviors",
"objectGroupType": "Sprite",
"objectNames": Array [
"MySpriteObjectWithBehaviors",
],
"variables": undefined,
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectGroupName": "MyGroupWithObjectsHavingLongName",
"objectGroupType": "Sprite",
"objectNames": Array [
"MySpriteObject",
"MySpriteObject_With_A_Veeeerrryyyyyyyyy_Looooooooooooong_Name",
"MySpriteObjectWithoutBehaviors",
],
"variables": undefined,
},
],
"objects": Array [
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "MySpriteObjectWithEffects",
"objectType": "Sprite",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "MySpriteObjectWithoutEffect",
"objectType": "Sprite",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "MySpriteObjectWithoutBehaviors",
"objectType": "Sprite",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Draggable",
"behaviorType": "DraggableBehavior::Draggable",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "PlatformerObject",
"behaviorType": "PlatformBehavior::PlatformerObjectBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "MySpriteObjectWithBehaviors",
"objectType": "Sprite",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "MyEmptySpriteObject",
"objectType": "Sprite",
},
Object {
"animationNames": "My animation, My other animation, (animation without name, animation index is: 2)",
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "MySpriteObject",
"objectType": "Sprite",
"objectVariables": Array [
Object {
"type": "String",
"value": "A multiline
str value",
"variableName": "ObjectVariable",
},
Object {
"type": "Structure",
"variableChildren": Array [
Object {
"type": "Number",
"value": "564",
"variableName": "ObjectChild1",
},
Object {
"type": "String",
"value": "Guttentag",
"variableName": "ObjectChild2",
},
Object {
"type": "Boolean",
"value": "True",
"variableName": "ObjectChild3",
},
Object {
"type": "Array",
"variableName": "ObjectChild4",
},
],
"variableName": "OtherObjectVariable",
},
],
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
],
"objectName": "MyPanelSpriteObject",
"objectType": "PanelSpriteObject::PanelSprite",
},
Object {
"objectName": "TextInputObject",
"objectType": "FakeTextInput::TextInput",
},
Object {
"objectName": "CubeObject",
"objectType": "FakeScene3D::Cube3DObject",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
],
"objectName": "MyTiledSpriteObject",
"objectType": "TiledSpriteObject::TiledSprite",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
],
"objectName": "MyParticleEmitter",
"objectType": "ParticleSystem::ParticleEmitter",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
Object {
"behaviorName": "Text",
"behaviorType": "TextContainerCapability::TextContainerBehavior",
},
],
"objectName": "MyTextObject",
"objectType": "TextObject::Text",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "MyShapePainterObject",
"objectType": "PrimitiveDrawing::Drawer",
},
Object {
"objectName": "MyButton",
"objectType": "Button::PanelSpriteButton",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "MySpriteObject_With_A_Veeeerrryyyyyyyyy_Looooooooooooong_Name",
"objectType": "Sprite",
},
Object {
"objectName": "MyFakeObjectWithUnsupportedCapability",
"objectType": "FakeObjectWithUnsupportedCapability::FakeObjectWithUnsupportedCapability",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "VirtualControls",
"objectType": "Sprite",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "VirtualControls1",
"objectType": "Sprite",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "VirtualControls2",
"objectType": "Sprite",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "VirtualControls3",
"objectType": "Sprite",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "VirtualControls4",
"objectType": "Sprite",
},
Object {
"behaviors": Array [
Object {
"behaviorName": "Animation",
"behaviorType": "AnimatableCapability::AnimatableBehavior",
},
Object {
"behaviorName": "Effect",
"behaviorType": "EffectCapability::EffectBehavior",
},
Object {
"behaviorName": "Flippable",
"behaviorType": "FlippableCapability::FlippableBehavior",
},
Object {
"behaviorName": "Opacity",
"behaviorType": "OpacityCapability::OpacityBehavior",
},
Object {
"behaviorName": "Resizable",
"behaviorType": "ResizableCapability::ResizableBehavior",
},
Object {
"behaviorName": "Scale",
"behaviorType": "ScalableCapability::ScalableBehavior",
},
],
"objectName": "VirtualControls5",
"objectType": "Sprite",
},
],
"sceneName": "TestLayout",
"sceneVariables": Array [
Object {
"type": "String",
"value": "A multiline
str value",
"variableName": "Variable1",
},
Object {
"type": "String",
"value": "123456",
"variableName": "Variable2",
},
Object {
"type": "Structure",
"variableChildren": Array [
Object {
"type": "String",
"value": "Child1 str value",
"variableName": "Child1",
},
Object {
"type": "String",
"value": "7891011",
"variableName": "Child2",
},
Object {
"type": "Structure",
"variableName": "FoldedChild",
},
],
"variableName": "Variable3",
},
Object {
"type": "Array",
"variableName": "FoldedArray",
},
Object {
"type": "Array",
"variableName": "OtherArray",
},
],
},
Object {
"instancesOnSceneDescription": "There are no instances of objects placed on the scene - the scene is empty.",
"objectGroups": Array [],
"objects": Array [],
"sceneName": "EmptyLayout",
"sceneVariables": Array [],
},
Object {
"instancesOnSceneDescription": "There are no instances of objects placed on the scene - the scene is empty.",
"objectGroups": Array [],
"objects": Array [],
"sceneName": "Layout with a very looooooooong naaaaame to test in the project manager",
"sceneVariables": Array [],
},
],
}
`);
});
it('should include summaries of project specific extensions', async () => {
const gd = await initializeGDevelopJs();
makeTestExtensions(gd);
const project = gd.ProjectHelper.createNewGDJSProject();
// Mimic the test extension "FakeBehavior" was created from a project extension:
project.insertNewEventsFunctionsExtension('FakeBehavior', 0);
const projectSpecificExtensionsSummary = makeSimplifiedProjectBuilder(
gd
).getProjectSpecificExtensionsSummary(project);
expect(projectSpecificExtensionsSummary).toMatchInlineSnapshot(`
Object {
"extensionSummaries": Array [
Object {
"behaviors": Object {
"FakeBehavior::FakeBehavior": Object {
"actions": Array [],
"conditions": Array [],
"description": "A fake behavior with two properties.",
"expressions": Array [
Object {
"description": "Some expression returning a number",
"parameters": Array [
Object {
"description": "First parameter (number)",
"type": "number",
},
],
"type": "SomethingReturningNumberWith1NumberParam",
},
Object {
"description": "Some expression returning a string",
"parameters": Array [
Object {
"description": "First parameter (number)",
"type": "number",
},
],
"type": "SomethingReturningStringWith1NumberParam",
},
],
"fullName": "Fake behavior with two properties",
"name": "FakeBehavior::FakeBehavior",
},
},
"description": "A fake extension with a fake behavior containing 2 properties.",
"extensionFullName": "Fake extension with a fake behavior",
"extensionName": "FakeBehavior",
"freeActions": Array [],
"freeConditions": Array [],
"freeExpressions": Array [],
"objects": Object {},
},
],
}
`);
project.delete();
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -42,8 +42,7 @@ import Text from '../UI/Text';
import GDevelopThemeContext from '../UI/Theme/GDevelopThemeContext';
import ThreeDotsMenu from '../UI/CustomSvgIcons/ThreeDotsMenu';
import Add from '../UI/CustomSvgIcons/Add';
import Clipboard from '../Utils/Clipboard';
import { SafeExtractor } from '../Utils/SafeExtractor';
import Clipboard, { SafeExtractor } from '../Utils/Clipboard';
import {
serializeToJSObject,
unserializeFromJSObject,

View File

@@ -28,8 +28,7 @@ import GDevelopThemeContext from '../UI/Theme/GDevelopThemeContext';
import DropIndicator from '../UI/SortableVirtualizedItemList/DropIndicator';
import { makeDragSourceAndDropTarget } from '../UI/DragAndDrop/DragSourceAndDropTarget';
import useForceUpdate from '../Utils/UseForceUpdate';
import Clipboard from '../Utils/Clipboard';
import { SafeExtractor } from '../Utils/SafeExtractor';
import Clipboard, { SafeExtractor } from '../Utils/Clipboard';
import {
serializeToJSObject,
unserializeFromJSObject,

View File

@@ -27,8 +27,7 @@ import GDevelopThemeContext from '../UI/Theme/GDevelopThemeContext';
import DropIndicator from '../UI/SortableVirtualizedItemList/DropIndicator';
import { makeDragSourceAndDropTarget } from '../UI/DragAndDrop/DragSourceAndDropTarget';
import useForceUpdate from '../Utils/UseForceUpdate';
import Clipboard from '../Utils/Clipboard';
import { SafeExtractor } from '../Utils/SafeExtractor';
import Clipboard, { SafeExtractor } from '../Utils/Clipboard';
import {
serializeToJSObject,
unserializeFromJSObject,

View File

@@ -29,8 +29,7 @@ import { DragHandleIcon } from '../../UI/DragHandle';
import GDevelopThemeContext from '../../UI/Theme/GDevelopThemeContext';
import DropIndicator from '../../UI/SortableVirtualizedItemList/DropIndicator';
import { makeDragSourceAndDropTarget } from '../../UI/DragAndDrop/DragSourceAndDropTarget';
import Clipboard from '../../Utils/Clipboard';
import { SafeExtractor } from '../../Utils/SafeExtractor';
import Clipboard, { SafeExtractor } from '../../Utils/Clipboard';
import {
serializeToJSObject,
unserializeFromJSObject,

View File

@@ -89,7 +89,7 @@ type Props = {|
eventsFunctionsExtension: gdEventsFunctionsExtension,
name: string
) => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
onExtensionInstalled: (extensionName: string) => void,
|};
type State = {|

View File

@@ -5,8 +5,7 @@ import { Trans } from '@lingui/macro';
import * as React from 'react';
import newNameGenerator from '../Utils/NewNameGenerator';
import Clipboard from '../Utils/Clipboard';
import { SafeExtractor } from '../Utils/SafeExtractor';
import Clipboard, { SafeExtractor } from '../Utils/Clipboard';
import {
serializeToJSObject,
unserializeFromJSObject,

View File

@@ -5,8 +5,7 @@ import { Trans } from '@lingui/macro';
import * as React from 'react';
import newNameGenerator from '../Utils/NewNameGenerator';
import Clipboard from '../Utils/Clipboard';
import { SafeExtractor } from '../Utils/SafeExtractor';
import Clipboard, { SafeExtractor } from '../Utils/Clipboard';
import {
serializeToJSObject,
unserializeFromJSObject,

View File

@@ -5,8 +5,7 @@ import { Trans } from '@lingui/macro';
import * as React from 'react';
import newNameGenerator from '../Utils/NewNameGenerator';
import Clipboard from '../Utils/Clipboard';
import { SafeExtractor } from '../Utils/SafeExtractor';
import Clipboard, { SafeExtractor } from '../Utils/Clipboard';
import {
serializeToJSObject,
unserializeFromJSObject,

View File

@@ -1,6 +1,5 @@
// @flow
import Clipboard from '../Utils/Clipboard';
import { SafeExtractor } from '../Utils/SafeExtractor';
import Clipboard, { SafeExtractor } from '../Utils/Clipboard';
import {
type SelectionState,
getSelectedEvents,

View File

@@ -67,15 +67,13 @@ const ConditionsActionsColumns = (props: Props) => {
);
}
const conditionWidth =
getConditionWidthRatio(props.eventsSheetWidth) * props.eventsSheetWidth -
props.leftIndentWidth;
return (
<div style={styles.twoColumnsContainer} className={props.className}>
{props.renderConditionsList({
style: {
width: `${conditionWidth}px`,
width: `${getConditionWidthRatio(props.eventsSheetWidth) *
props.eventsSheetWidth -
props.leftIndentWidth}px`,
},
className: conditionsContainer,
})}

Some files were not shown because too many files have changed in this diff Show More