Compare commits

...

27 Commits

Author SHA1 Message Date
Cursor Agent
ab36c6eb5a Refactor AI project creation and add initialize_project function
Co-authored-by: florian <florian@gdevelop.io>
2025-09-07 15:48:31 +00:00
Florian Rival
37bed36315 Make comment events editable exactly as they look (#7812) 2025-09-05 14:46:42 +02:00
D8H
5394cc5201 Forbid to add Physics behaviors on objects inside custom objects (#7809) 2025-09-04 19:37:57 +02:00
Florian Rival
5e3dfb0e9c Add condition to check if a key was just pressed (#7808) 2025-09-04 17:32:25 +02:00
Clément Pasteau
f6a6c981f8 Add a small intro explaining how to follow the courses (#7807) 2025-09-04 16:10:37 +02:00
Clément Pasteau
415c1bfd2f Fix bundles showing up in new object search (#7806) 2025-09-03 14:11:16 +02:00
github-actions[bot]
e4a911db25 Update translations [skip ci] (#7804)
Co-authored-by: ClementPasteau <4895034+ClementPasteau@users.noreply.github.com>
2025-09-03 10:42:14 +02:00
Clément Pasteau
5fcd67d77b Additional bundles are added to the Learn & Shop sections (#7805)
* A premium bundle, including multiple courses, asset packs, templates and a gold subscription
* A curated platformer-specific bundle, including everything needed to learn & create a platformer game
2025-09-03 10:30:24 +02:00
Florian Rival
86db08ac3f Fix npm start on Windows
Don't show in changelog
2025-09-01 15:49:21 +02:00
github-actions[bot]
8d735fc726 Update translations [skip ci] (#7800)
Co-authored-by: ClementPasteau <4895034+ClementPasteau@users.noreply.github.com>
2025-09-01 14:32:50 +02:00
Clément Pasteau
1e1f4bb2a3 Merge Bundle page into 1 component + small design fixes (#7803)
Do not show in changelog
2025-09-01 14:17:33 +02:00
Florian Rival
d8000aca10 Simplify editor README [skip ci] [ci skip] 2025-09-01 00:00:14 +02:00
Florian Rival
a2660ff0dc Allow to easily work on the game engine using the web-app development version (#7802) 2025-08-31 23:54:44 +02:00
Florian Rival
000d5785cf Improve AI agent performance by removing old object properties
Don't show in changelog
2025-08-30 17:29:49 +02:00
Florian Rival
9fe04712a9 Improve AI ability to update existing instances 2025-08-30 16:59:09 +02:00
Florian Rival
846afd9e0a Improve documentation with reference of all available effects. 2025-08-30 14:16:00 +02:00
Florian Rival
6125ff0f90 Allow AI to change layers/effects/scene and some game properties (#7799) 2025-08-29 19:15:50 +02:00
github-actions[bot]
a5428a8843 Update translations [skip ci] (#7798)
Co-authored-by: ClementPasteau <4895034+ClementPasteau@users.noreply.github.com>
2025-08-29 15:58:38 +02:00
Ansel Games
19be45cda6 Fix grammar in text font size change warning (#7797) 2025-08-29 14:26:04 +02:00
Clément Pasteau
889c97cb27 Update Bundle Page with more details about content and limited offer (#7795) 2025-08-29 14:24:49 +02:00
Florian Rival
1d83da41a9 Improve physics extensions descriptions to tell about the scale and typical force values 2025-08-27 16:42:41 +02:00
github-actions[bot]
a65f2174eb Update translations [skip ci] (#7781)
Co-authored-by: D8H <2611977+D8H@users.noreply.github.com>
2025-08-27 10:05:59 +02:00
D8H
9db493e87e Refactor tab opening (#7794)
- Don't show in changelogs
2025-08-26 17:29:42 +02:00
Florian Rival
49a3a18b51 Make clear in-app tutorials are free
Don't show in changelog
2025-08-26 15:53:55 +02:00
Florian Rival
0489e7036b Rework stories for TeamSection 2025-08-26 12:07:57 +02:00
Florian Rival
794d5a781c Add support for setting a full name for a student account (#7788) 2025-08-26 11:09:19 +02:00
D8H
c21dfbcc1f Optimize used resources search during export (#7790) 2025-08-25 20:12:17 +02:00
176 changed files with 6479 additions and 3666 deletions

View File

@@ -52,10 +52,25 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsKeyboardExtension(
.SetHidden();
extension
.AddCondition("KeyFromTextPressed",
_("Key pressed"),
_("Check if a key is pressed"),
_("_PARAM1_ key is pressed"),
.AddCondition(
"KeyFromTextPressed",
_("Key pressed"),
_("Check if a key is pressed. This stays true as long as "
"the key is held down. To check if a key was pressed during "
"the frame, use \"Key just pressed\" instead."),
_("_PARAM1_ key is pressed"),
"",
"res/conditions/keyboard24.png",
"res/conditions/keyboard.png")
.AddCodeOnlyParameter("currentScene", "")
.AddParameter("keyboardKey", _("Key to check"))
.MarkAsSimple();
extension
.AddCondition("KeyFromTextJustPressed",
_("Key just pressed"),
_("Check if a key was just pressed."),
_("_PARAM1_ key was just pressed"),
"",
"res/conditions/keyboard24.png",
"res/conditions/keyboard.png")
@@ -66,7 +81,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsKeyboardExtension(
extension
.AddCondition("KeyFromTextReleased",
_("Key released"),
_("Check if a key was just released"),
_("Check if a key was just released."),
_("_PARAM1_ key is released"),
"",
"res/conditions/keyboard24.png",

View File

@@ -298,6 +298,19 @@ class GD_CORE_API BehaviorMetadata : public InstructionOrExpressionContainerMeta
return *this;
}
/**
* Check if the behavior can be used on objects from event-based objects.
*/
bool IsRelevantForChildObjects() const { return isRelevantForChildObjects; }
/**
* Set that behavior can't be used on objects from event-based objects.
*/
BehaviorMetadata &MarkAsIrrelevantForChildObjects() {
isRelevantForChildObjects = false;
return *this;
}
QuickCustomization::Visibility GetQuickCustomizationVisibility() const {
return quickCustomizationVisibility;
}
@@ -393,6 +406,7 @@ class GD_CORE_API BehaviorMetadata : public InstructionOrExpressionContainerMeta
mutable std::vector<gd::String> requiredBehaviors;
bool isPrivate = false;
bool isHidden = false;
bool isRelevantForChildObjects = true;
gd::String openFullEditorLabel;
QuickCustomization::Visibility quickCustomizationVisibility = QuickCustomization::Visibility::Default;

View File

@@ -277,6 +277,10 @@ class GD_CORE_API MetadataProvider {
return &metadata == &badObjectInfo;
}
static bool IsBadEffectMetadata(const gd::EffectMetadata& metadata) {
return &metadata == &badEffectMetadata;
}
virtual ~MetadataProvider();
private:

View File

@@ -75,6 +75,17 @@ void ResourceExposer::ExposeProjectResources(
// Expose global objects configuration resources
auto objectWorker = gd::GetResourceWorkerOnObjects(project, worker);
objectWorker.Launch(project.GetObjects());
// Exposed extension event resources
// Note that using resources in extensions is very unlikely and probably not
// worth the effort of something smart.
auto eventWorker = gd::GetResourceWorkerOnEvents(project, worker);
for (std::size_t e = 0; e < project.GetEventsFunctionsExtensionsCount();
e++) {
auto &eventsFunctionsExtension = project.GetEventsFunctionsExtension(e);
gd::ProjectBrowserHelper::ExposeEventsFunctionsExtensionEvents(
project, eventsFunctionsExtension, eventWorker);
}
}
void ResourceExposer::ExposeLayoutResources(
@@ -103,16 +114,6 @@ void ResourceExposer::ExposeLayoutResources(
auto eventWorker = gd::GetResourceWorkerOnEvents(project, worker);
gd::ProjectBrowserHelper::ExposeLayoutEventsAndDependencies(
project, layout, eventWorker);
// Exposed extension event resources
// Note that using resources in extensions is very unlikely and probably not
// worth the effort of something smart.
for (std::size_t e = 0; e < project.GetEventsFunctionsExtensionsCount();
e++) {
auto &eventsFunctionsExtension = project.GetEventsFunctionsExtension(e);
gd::ProjectBrowserHelper::ExposeEventsFunctionsExtensionEvents(
project, eventsFunctionsExtension, eventWorker);
}
}
void ResourceExposer::ExposeEffectResources(

View File

@@ -764,129 +764,6 @@ TEST_CASE("ArbitraryResourceWorker", "[common][resources]") {
REQUIRE(worker.audios[0] == "res4");
}
SECTION("Can find resource usages in event-based functions") {
gd::Project project;
gd::Platform platform;
SetupProjectWithDummyPlatform(project, platform);
project.GetResourcesManager().AddResource(
"res1", "path/to/file1.png", "image");
project.GetResourcesManager().AddResource(
"res2", "path/to/file2.png", "image");
project.GetResourcesManager().AddResource(
"res3", "path/to/file3.png", "image");
ArbitraryResourceWorkerTest worker(project.GetResourcesManager());
auto& extension = project.InsertNewEventsFunctionsExtension("MyEventExtension", 0);
auto &function = extension.GetEventsFunctions().InsertNewEventsFunction(
"MyFreeFunction", 0);
gd::StandardEvent standardEvent;
gd::Instruction instruction;
instruction.SetType("MyExtension::DoSomethingWithResources");
instruction.SetParametersCount(3);
instruction.SetParameter(0, "res3");
instruction.SetParameter(1, "res1");
instruction.SetParameter(2, "res4");
standardEvent.GetActions().Insert(instruction);
function.GetEvents().InsertEvent(standardEvent);
auto& layout = project.InsertNewLayout("MyScene", 0);
// MyEventExtension::MyFreeFunction doesn't need to be actually used in
// events because the implementation is naive.
gd::ResourceExposer::ExposeLayoutResources(project, layout, worker);
REQUIRE(worker.bitmapFonts.size() == 1);
REQUIRE(worker.bitmapFonts[0] == "res3");
REQUIRE(worker.images.size() == 1);
REQUIRE(worker.images[0] == "res1");
REQUIRE(worker.audios.size() == 1);
REQUIRE(worker.audios[0] == "res4");
}
SECTION("Can find resource usages in event-based behavior functions") {
gd::Project project;
gd::Platform platform;
SetupProjectWithDummyPlatform(project, platform);
project.GetResourcesManager().AddResource(
"res1", "path/to/file1.png", "image");
project.GetResourcesManager().AddResource(
"res2", "path/to/file2.png", "image");
project.GetResourcesManager().AddResource(
"res3", "path/to/file3.png", "image");
ArbitraryResourceWorkerTest worker(project.GetResourcesManager());
auto& extension = project.InsertNewEventsFunctionsExtension("MyEventExtension", 0);
auto& behavior = extension.GetEventsBasedBehaviors().InsertNew("MyBehavior", 0);
auto& function = behavior.GetEventsFunctions().InsertNewEventsFunction("MyFunction", 0);
gd::StandardEvent standardEvent;
gd::Instruction instruction;
instruction.SetType("MyExtension::DoSomethingWithResources");
instruction.SetParametersCount(3);
instruction.SetParameter(0, "res3");
instruction.SetParameter(1, "res1");
instruction.SetParameter(2, "res4");
standardEvent.GetActions().Insert(instruction);
function.GetEvents().InsertEvent(standardEvent);
auto& layout = project.InsertNewLayout("MyScene", 0);
// MyEventExtension::MyBehavior::MyFunction doesn't need to be actually used in
// events because the implementation is naive.
gd::ResourceExposer::ExposeLayoutResources(project, layout, worker);
REQUIRE(worker.bitmapFonts.size() == 1);
REQUIRE(worker.bitmapFonts[0] == "res3");
REQUIRE(worker.images.size() == 1);
REQUIRE(worker.images[0] == "res1");
REQUIRE(worker.audios.size() == 1);
REQUIRE(worker.audios[0] == "res4");
}
SECTION("Can find resource usages in event-based object functions") {
gd::Project project;
gd::Platform platform;
SetupProjectWithDummyPlatform(project, platform);
project.GetResourcesManager().AddResource(
"res1", "path/to/file1.png", "image");
project.GetResourcesManager().AddResource(
"res2", "path/to/file2.png", "image");
project.GetResourcesManager().AddResource(
"res3", "path/to/file3.png", "image");
ArbitraryResourceWorkerTest worker(project.GetResourcesManager());
auto& extension = project.InsertNewEventsFunctionsExtension("MyEventExtension", 0);
auto& object = extension.GetEventsBasedObjects().InsertNew("MyObject", 0);
auto& function = object.GetEventsFunctions().InsertNewEventsFunction("MyFunction", 0);
gd::StandardEvent standardEvent;
gd::Instruction instruction;
instruction.SetType("MyExtension::DoSomethingWithResources");
instruction.SetParametersCount(3);
instruction.SetParameter(0, "res3");
instruction.SetParameter(1, "res1");
instruction.SetParameter(2, "res4");
standardEvent.GetActions().Insert(instruction);
function.GetEvents().InsertEvent(standardEvent);
auto& layout = project.InsertNewLayout("MyScene", 0);
// MyEventExtension::MyObject::MyFunction doesn't need to be actually used in
// events because the implementation is naive.
gd::ResourceExposer::ExposeLayoutResources(project, layout, worker);
REQUIRE(worker.bitmapFonts.size() == 1);
REQUIRE(worker.bitmapFonts[0] == "res3");
REQUIRE(worker.images.size() == 1);
REQUIRE(worker.images[0] == "res1");
REQUIRE(worker.audios.size() == 1);
REQUIRE(worker.audios[0] == "res4");
}
SECTION("Can find resource usages in layer effects") {
gd::Project project;
gd::Platform platform;

View File

@@ -1908,7 +1908,9 @@ module.exports = {
.addEffect('AmbientLight')
.setFullName(_('Ambient light'))
.setDescription(
_('A light that illuminates all objects from every direction.')
_(
'A light that illuminates all objects from every direction. Often used along with a Directional light (though a Hemisphere light can be used instead of an Ambient light).'
)
)
.markAsNotWorkingForObjects()
.markAsOnlyWorkingFor3D()
@@ -1929,7 +1931,11 @@ module.exports = {
const effect = extension
.addEffect('DirectionalLight')
.setFullName(_('Directional light'))
.setDescription(_('A very far light source like the sun.'))
.setDescription(
_(
"A very far light source like the sun. This is the light to use for casting shadows for 3D objects (other lights won't emit shadows). Often used along with a Hemisphere light."
)
)
.markAsNotWorkingForObjects()
.markAsOnlyWorkingFor3D()
.addIncludeFile('Extensions/3D/DirectionalLight.js');
@@ -2013,7 +2019,7 @@ module.exports = {
.setFullName(_('Hemisphere light'))
.setDescription(
_(
'A light that illuminates objects from every direction with a gradient.'
'A light that illuminates objects from every direction with a gradient. Often used along with a Directional light.'
)
)
.markAsNotWorkingForObjects()

View File

@@ -21,7 +21,11 @@ module.exports = {
.setExtensionInformation(
'Physics2',
_('2D Physics Engine'),
"The 2D physics engine simulates realistic object physics, with gravity, forces, collisions, joints, etc. It's perfect for 2D games that need to have realistic behaving objects and a gameplay centered around it.",
"The 2D physics engine simulates realistic object physics, with gravity, forces, collisions, joints, etc. It's perfect for 2D games that need to have realistic behaving objects and a gameplay centered around it.\n" +
'\n' +
'Objects like floors or wall objects should usually be set to "Static" as type. Objects that should be moveable are usually "Dynamic" (default). "Kinematic" objects (typically, players or controlled characters) are only moved by their "linear velocity" and "angular velocity" - they can interact with other objects but only these other objects will move.\n' +
'\n' +
'Forces (and impulses) are expressed in all conditions/expressions/actions of the 2D physics engine in Newtons (N). Typical values for a force are 10-200 N. One meter is 100 pixels by default in the game (check the world scale). Mass is expressed in kilograms (kg).',
'Florian Rival, Franco Maciel',
'MIT'
)
@@ -527,6 +531,7 @@ module.exports = {
physics2Behavior,
sharedData
)
.markAsIrrelevantForChildObjects()
.setIncludeFile('Extensions/Physics2Behavior/physics2runtimebehavior.js')
.addIncludeFile('Extensions/Physics2Behavior/Box2D_v2.3.1_min.wasm.js')
.addRequiredFile('Extensions/Physics2Behavior/Box2D_v2.3.1_min.wasm.wasm')

View File

@@ -21,7 +21,11 @@ module.exports = {
.setExtensionInformation(
'Physics3D',
_('3D physics engine'),
"The 3D physics engine simulates realistic object physics, with gravity, forces, collisions, joints, etc. It's perfect for almost all 3D games.",
"The 3D physics engine simulates realistic object physics, with gravity, forces, collisions, joints, etc. It's perfect for almost all 3D games.\n" +
'\n' +
'Objects like floors or wall objects should usually be set to "Static" as type. Objects that should be moveable are usually "Dynamic" (default). "Kinematic" objects (typically, players or controlled characters) are only moved by their "linear velocity" and "angular velocity" - they can interact with other objects but only these other objects will move.\n' +
'\n' +
'Forces (and impulses) are expressed in all conditions/expressions/actions of the 3D physics engine in Newtons (N). Typical values for a force are 10-200 N. One meter is 100 pixels by default in the game (check the world scale). Mass is expressed in kilograms (kg).',
'Florian Rival',
'MIT'
)
@@ -675,6 +679,7 @@ module.exports = {
behavior,
sharedData
)
.markAsIrrelevantForChildObjects()
.addIncludeFile(
'Extensions/Physics3DBehavior/Physics3DRuntimeBehavior.js'
)
@@ -2043,7 +2048,12 @@ module.exports = {
'PhysicsCharacter3D',
_('3D physics character'),
'PhysicsCharacter3D',
_('Jump and run on platforms.'),
_(
'Allow an object to jump and run on platforms that have the 3D physics behavior' +
'(and which are generally set to "Static" as type, unless the platform is animated/moved in events).\n' +
'\n' +
'This behavior is usually used with one or more "mapper" behavior to let the player move it.'
),
'',
'JsPlatform/Extensions/physics_character3d.svg',
'PhysicsCharacter3D',
@@ -2612,7 +2622,7 @@ module.exports = {
'JumpSustainTime',
_('Jump sustain time'),
_(
'the jump sustain time of an object. This is the time during which keeping the jump button held allow the initial jump speed to be maintained.'
'the jump sustain time of an object. This is the time during which keeping the jump button held allow the initial jump speed to be maintained'
),
_('the jump sustain time'),
_('Character configuration'),
@@ -3300,7 +3310,11 @@ module.exports = {
'PhysicsCar3D',
_('3D physics car'),
'PhysicsCar3D',
_('Simulate a realistic car using the 3D physics engine.'),
_(
"Simulate a realistic car using the 3D physics engine. This is mostly useful for the car controlled by the player (it's usually too complex for other cars in a game).\n" +
'\n' +
'This behavior is usually used with one or more "mapper" behavior to let the player move it.'
),
'',
'JsPlatform/Extensions/physics_car3d.svg',
'PhysicsCar3D',

View File

@@ -37,7 +37,8 @@ void DeclarePhysicsBehaviorExtension(gd::PlatformExtension& extension) {
"res/physics-deprecated32.png",
"PhysicsBehavior",
std::make_shared<PhysicsBehavior>(),
std::make_shared<ScenePhysicsDatas>());
std::make_shared<ScenePhysicsDatas>())
.MarkAsIrrelevantForChildObjects();
aut.AddAction("SetStatic",
("Make the object static"),

View File

@@ -18,6 +18,8 @@ KeyboardExtension::KeyboardExtension() {
"gdjs.evtTools.input.wasKeyReleased");
GetAllConditions()["KeyFromTextPressed"].SetFunctionName(
"gdjs.evtTools.input.isKeyPressed");
GetAllConditions()["KeyFromTextJustPressed"].SetFunctionName(
"gdjs.evtTools.input.wasKeyJustPressed");
GetAllConditions()["KeyFromTextReleased"].SetFunctionName(
"gdjs.evtTools.input.wasKeyReleased");
GetAllConditions()["AnyKeyPressed"].SetFunctionName(

View File

@@ -153,7 +153,7 @@ namespace gdjs {
};
/**
* Return true if the specified key is pressed
* Return true if the specified key is pressed (i.e: just pressed or held down).
*
*/
export const isKeyPressed = function (
@@ -170,8 +170,22 @@ namespace gdjs {
};
/**
* Return true if the specified key was just released
*
* Return true if the specified key was just pressed (i.e: it started being pressed
* during this frame).
*/
export const wasKeyJustPressed = function (
instanceContainer: gdjs.RuntimeInstanceContainer,
key: string
) {
return instanceContainer
.getGame()
.getInputManager()
.wasKeyJustPressed(gdjs.evtTools.input.keysNameToCode[key]);
};
/**
* Return true if the specified key was just released (i.e: it stopped being pressed
* during this frame).
*/
export const wasKeyReleased = function (
instanceContainer: gdjs.RuntimeInstanceContainer,
@@ -187,7 +201,7 @@ namespace gdjs {
};
/**
* Return the name of the last key pressed in the game
* Return the name of the last key pressed in the game.
*/
export const lastPressedKey = function (
instanceContainer: gdjs.RuntimeInstanceContainer

View File

@@ -23,12 +23,13 @@ namespace gdjs {
* variants and should default to their left variant values
* if location is not specified.
*/
static _DEFAULT_LEFT_VARIANT_KEYS: integer[] = [16, 17, 18, 91];
_pressedKeys: Hashtable<boolean>;
_releasedKeys: Hashtable<boolean>;
_lastPressedKey: float = 0;
_pressedMouseButtons: Array<boolean>;
_releasedMouseButtons: Array<boolean>;
private static _DEFAULT_LEFT_VARIANT_KEYS: integer[] = [16, 17, 18, 91];
private _pressedKeys: Hashtable<boolean>;
private _justPressedKeys: Hashtable<boolean>;
private _releasedKeys: Hashtable<boolean>;
private _lastPressedKey: float = 0;
private _pressedMouseButtons: Array<boolean>;
private _releasedMouseButtons: Array<boolean>;
/**
* The cursor X position (moved by mouse and touch events).
*/
@@ -79,6 +80,7 @@ namespace gdjs {
constructor() {
this._pressedKeys = new Hashtable();
this._justPressedKeys = new Hashtable();
this._releasedKeys = new Hashtable();
this._pressedMouseButtons = new Array(5);
this._releasedMouseButtons = new Array(5);
@@ -124,6 +126,7 @@ namespace gdjs {
location
);
this._pressedKeys.put(locationAwareKeyCode, true);
this._justPressedKeys.put(locationAwareKeyCode, true);
this._lastPressedKey = locationAwareKeyCode;
}
@@ -140,9 +143,34 @@ namespace gdjs {
location
);
this._pressedKeys.put(locationAwareKeyCode, false);
this._justPressedKeys.put(locationAwareKeyCode, false);
this._releasedKeys.put(locationAwareKeyCode, true);
}
/**
* Release all keys that are currently pressed.
* Note: if you want to discard pressed keys without considering them as
* released, check `clearAllPressedKeys` instead.
*/
releaseAllPressedKeys(): void {
for (const locationAwareKeyCode in this._pressedKeys.items) {
this._pressedKeys.put(locationAwareKeyCode, false);
this._justPressedKeys.put(locationAwareKeyCode, false);
this._releasedKeys.put(locationAwareKeyCode, true);
}
}
/**
* Clears all stored pressed keys without making the keys go through
* the release state.
* Note: prefer to use `releaseAllPressedKeys` instead, as it corresponds
* to a normal key release.
*/
clearAllPressedKeys(): void {
this._pressedKeys.clear();
this._justPressedKeys.clear();
}
/**
* Return the location-aware code of the last key that was pressed.
* @return The location-aware code of the last key pressed.
@@ -152,14 +180,21 @@ namespace gdjs {
}
/**
* Return true if the key corresponding to the location-aware keyCode is pressed.
* Return true if the key corresponding to the location-aware keyCode is pressed
* (either it was just pressed or is still held down).
* @param locationAwareKeyCode The location-aware key code to be tested.
*/
isKeyPressed(locationAwareKeyCode: number): boolean {
return (
this._pressedKeys.containsKey(locationAwareKeyCode) &&
this._pressedKeys.get(locationAwareKeyCode)
);
return !!this._pressedKeys.get(locationAwareKeyCode);
}
/**
* Return true if the key corresponding to the location-aware keyCode
* was just pressed during the last frame.
* @param locationAwareKeyCode The location-aware key code to be tested.
*/
wasKeyJustPressed(locationAwareKeyCode: number): boolean {
return !!this._justPressedKeys.get(locationAwareKeyCode);
}
/**
@@ -167,10 +202,7 @@ namespace gdjs {
* @param locationAwareKeyCode The location-aware key code to be tested.
*/
wasKeyReleased(locationAwareKeyCode: number) {
return (
this._releasedKeys.containsKey(locationAwareKeyCode) &&
this._releasedKeys.get(locationAwareKeyCode)
);
return !!this._releasedKeys.get(locationAwareKeyCode);
}
/**
@@ -544,6 +576,7 @@ namespace gdjs {
this._startedTouches.length = 0;
this._endedTouches.length = 0;
this._releasedKeys.clear();
this._justPressedKeys.clear();
this._releasedMouseButtons.length = 0;
this._mouseWheelDelta = 0;
this._lastStartedTouchIndex = 0;
@@ -564,14 +597,6 @@ namespace gdjs {
return this.getMouseWheelDelta() < 0;
}
/**
* Clears all stored pressed keys without making the keys go through
* the release state.
*/
clearAllPressedKeys(): void {
this._pressedKeys.clear();
}
static _allTouchIds: Array<integer> = [];
}
}

View File

@@ -657,6 +657,14 @@ namespace gdjs {
e.preventDefault();
}
if (e.repeat) {
// If `repeat` is true, this is not the first press of the key.
// We only communicate the changes of states ("first" key down, key up)
// to the manager, which then tracks the state of the key:
// pressed, just pressed or released.
return;
}
manager.onKeyPressed(e.keyCode, e.location);
};
document.onkeyup = function (e) {

View File

@@ -34,9 +34,14 @@ describe('gdjs.InputManager', () => {
inputManager.onKeyPressed(33);
expect(inputManager.getLastPressedKey()).to.be(33);
expect(inputManager.isKeyPressed(32)).to.be(true);
expect(inputManager.wasKeyJustPressed(32)).to.be(true);
expect(inputManager.isKeyPressed(30)).to.be(false);
expect(inputManager.wasKeyJustPressed(30)).to.be(false);
expect(inputManager.isKeyPressed(33)).to.be(true);
expect(inputManager.wasKeyJustPressed(33)).to.be(true);
inputManager.onKeyReleased(32);
expect(inputManager.isKeyPressed(32)).to.be(false);
expect(inputManager.wasKeyJustPressed(32)).to.be(false);
expect(inputManager.wasKeyReleased(32)).to.be(true);
expect(inputManager.anyKeyReleased()).to.be(true);
expect(inputManager.anyKeyPressed()).to.be(true);
@@ -46,10 +51,14 @@ describe('gdjs.InputManager', () => {
expect(inputManager.anyKeyPressed()).to.be(true);
expect(inputManager.anyKeyReleased()).to.be(false);
expect(inputManager.isKeyPressed(33)).to.be(true);
expect(inputManager.wasKeyJustPressed(33)).to.be(false);
expect(inputManager.wasKeyJustPressed(32)).to.be(false);
inputManager.onFrameEnded();
inputManager.onKeyReleased(33);
expect(inputManager.wasKeyReleased(33)).to.be(true);
expect(inputManager.wasKeyJustPressed(33)).to.be(false);
expect(inputManager.wasKeyJustPressed(32)).to.be(false);
expect(inputManager.anyKeyPressed()).to.be(false);
expect(inputManager.anyKeyReleased()).to.be(true);
inputManager.onFrameEnded();
@@ -61,12 +70,16 @@ describe('gdjs.InputManager', () => {
expect(inputManager.getLastPressedKey()).to.be(2016);
expect(inputManager.isKeyPressed(2016)).to.be(true);
expect(inputManager.isKeyPressed(1016)).to.be(false);
expect(inputManager.wasKeyJustPressed(2016)).to.be(true);
expect(inputManager.wasKeyJustPressed(1016)).to.be(false);
// Pressed Control with no location - expect to default to left.
inputManager.onKeyPressed(17);
expect(inputManager.getLastPressedKey()).to.be(1017);
expect(inputManager.isKeyPressed(1017)).to.be(true);
expect(inputManager.isKeyPressed(2017)).to.be(false);
expect(inputManager.wasKeyJustPressed(1017)).to.be(true);
expect(inputManager.wasKeyJustPressed(2017)).to.be(false);
inputManager.onKeyReleased(16, 2);
expect(inputManager.wasKeyReleased(2016)).to.be(true);

View File

@@ -1143,6 +1143,7 @@ interface LayersContainer {
boolean HasLayerNamed([Const] DOMString name);
void RemoveLayer([Const] DOMString name);
unsigned long GetLayersCount();
unsigned long GetLayerPosition([Const] DOMString name);
void SwapLayers(unsigned long firstLayerIndex, unsigned long secondLayerIndex);
void MoveLayer(unsigned long oldIndex, unsigned long newIndex);
void SerializeLayersTo([Ref] SerializerElement element);
@@ -2144,6 +2145,9 @@ interface BehaviorMetadata {
boolean IsHidden();
[Ref] BehaviorMetadata SetHidden();
boolean IsRelevantForChildObjects();
[Ref] BehaviorMetadata MarkAsIrrelevantForChildObjects();
QuickCustomization_Visibility GetQuickCustomizationVisibility();
[Ref] BehaviorMetadata SetQuickCustomizationVisibility(QuickCustomization_Visibility visibility);
@@ -2932,6 +2936,7 @@ interface MetadataProvider {
boolean STATIC_IsBadInstructionMetadata([Const, Ref] InstructionMetadata metadata);
boolean STATIC_IsBadBehaviorMetadata([Const, Ref] BehaviorMetadata metadata);
boolean STATIC_IsBadObjectMetadata([Const, Ref] ObjectMetadata metadata);
boolean STATIC_IsBadEffectMetadata([Const, Ref] EffectMetadata metadata);
};
enum ProjectDiagnostic_ErrorType {

View File

@@ -606,6 +606,7 @@ typedef std::vector<gd::PropertyDescriptorChoice> VectorPropertyDescriptorChoice
#define STATIC_IsBadInstructionMetadata IsBadInstructionMetadata
#define STATIC_IsBadBehaviorMetadata IsBadBehaviorMetadata
#define STATIC_IsBadObjectMetadata IsBadObjectMetadata
#define STATIC_IsBadEffectMetadata IsBadEffectMetadata
#define STATIC_RenameObjectInEvents RenameObjectInEvents
#define STATIC_RemoveObjectInEvents RemoveObjectInEvents

View File

@@ -941,6 +941,7 @@ export class LayersContainer extends EmscriptenObject {
hasLayerNamed(name: string): boolean;
removeLayer(name: string): void;
getLayersCount(): number;
getLayerPosition(name: string): number;
swapLayers(firstLayerIndex: number, secondLayerIndex: number): void;
moveLayer(oldIndex: number, newIndex: number): void;
serializeLayersTo(element: SerializerElement): void;
@@ -1670,6 +1671,8 @@ export class BehaviorMetadata extends EmscriptenObject {
setPrivate(): BehaviorMetadata;
isHidden(): boolean;
setHidden(): BehaviorMetadata;
isRelevantForChildObjects(): boolean;
markAsIrrelevantForChildObjects(): BehaviorMetadata;
getQuickCustomizationVisibility(): QuickCustomization_Visibility;
setQuickCustomizationVisibility(visibility: QuickCustomization_Visibility): BehaviorMetadata;
setOpenFullEditorLabel(label: string): BehaviorMetadata;
@@ -2109,6 +2112,7 @@ export class MetadataProvider extends EmscriptenObject {
static isBadInstructionMetadata(metadata: InstructionMetadata): boolean;
static isBadBehaviorMetadata(metadata: BehaviorMetadata): boolean;
static isBadObjectMetadata(metadata: ObjectMetadata): boolean;
static isBadEffectMetadata(metadata: EffectMetadata): boolean;
}
export class ProjectDiagnostic extends EmscriptenObject {

View File

@@ -33,6 +33,8 @@ declare class gdBehaviorMetadata {
setPrivate(): gdBehaviorMetadata;
isHidden(): boolean;
setHidden(): gdBehaviorMetadata;
isRelevantForChildObjects(): boolean;
markAsIrrelevantForChildObjects(): gdBehaviorMetadata;
getQuickCustomizationVisibility(): QuickCustomization_Visibility;
setQuickCustomizationVisibility(visibility: QuickCustomization_Visibility): gdBehaviorMetadata;
setOpenFullEditorLabel(label: string): gdBehaviorMetadata;

View File

@@ -7,6 +7,7 @@ declare class gdLayersContainer {
hasLayerNamed(name: string): boolean;
removeLayer(name: string): void;
getLayersCount(): number;
getLayerPosition(name: string): number;
swapLayers(firstLayerIndex: number, secondLayerIndex: number): void;
moveLayer(oldIndex: number, newIndex: number): void;
serializeLayersTo(element: gdSerializerElement): void;

View File

@@ -26,6 +26,7 @@ declare class gdMetadataProvider {
static isBadInstructionMetadata(metadata: gdInstructionMetadata): boolean;
static isBadBehaviorMetadata(metadata: gdBehaviorMetadata): boolean;
static isBadObjectMetadata(metadata: gdObjectMetadata): boolean;
static isBadEffectMetadata(metadata: gdEffectMetadata): boolean;
delete(): void;
ptr: number;
};

View File

@@ -33,9 +33,6 @@ Images resources, GDJS Runtime, extensions will be copied in resources, and [lib
You can run the standalone app with Electron. **Make sure that you've launched `npm start` (or `yarn start`) in the `app` folder before** (see above) and **keep it running** (in development, the app is served from a local server, even for the standalone app).
> Note for Windows: With **Node.js 14 or older**, there is an error related to `git-sh-setup` when running npm install.
> To solve this problem: add [this folder to your path environment variable](https://stackoverflow.com/questions/49256190/how-to-fix-git-sh-setup-file-not-found-in-windows) **OR** run `npm install` in newIDE/electron-app/app **before** npm install in newIDE/electron-app.
```bash
cd newIDE/app && npm start # Be sure to have this running in another terminal, before the rest!
@@ -81,17 +78,11 @@ It's pretty easy to create new themes. Check the [README about themes](./README-
### Development of the game engine or extensions
Make sure to have the standalone app running with Electron.
- If you want to create/modify _extensions_, check the [README about extensions](./README-extensions.md) for step-by-step explanations to get started in 5 minutes.
- The _game engine core_ ([GDJS](https://github.com/4ian/GDevelop/tree/master/GDJS)) is in [GDJS/Runtime folder](https://github.com/4ian/GDevelop/tree/master/GDJS/Runtime).
- If you want to create/modify _extensions_, check the [README about extensions](./README-extensions.md) for step-by-step explanations to get started in 5 minutes.
- The _game engine core_ ([GDJS](https://github.com/4ian/GDevelop/tree/master/GDJS)) is in [GDJS/Runtime folder](https://github.com/4ian/GDevelop/tree/master/GDJS/Runtime).
If you modify any file while the IDE is running with Electron, a watcher will _automatically import_ your changes (look at the console to be sure).
You can then _launch a preview_ in GDevelop (again, be sure to be using [the standalone app running with Electron](https://github.com/4ian/GDevelop/blob/master/newIDE/README.md#development-of-the-standalone-app) to be sure to have your changes reflected immediately).
> If you deactivated the watcher in preferences, run the `import-GDJS-Runtime.js` script manually (`cd newIDE/app/scripts` then `node import-GDJS-Runtime.js`) after every change, before launching a preview.
If you modify any file while the editor is running, a watcher will _automatically rebuild_ the engine (look at the console to be sure).
You can then _launch a preview_ in GDevelop.
### Recommended tools for development

View File

@@ -33,11 +33,14 @@ export const parameters = {
// that we don't use.
controls: { hideNoControlsWarning: true },
docs: { disable: true },
mockAddonConfigs: {
globalMockData: [],
},
};
export const decorators = [
themeDecorator,
GDevelopJsInitializerDecorator,
i18nProviderDecorator,
BrowserDropDownMenuDisablerDecorator
]
BrowserDropDownMenuDisablerDecorator,
];

View File

@@ -81,10 +81,13 @@
"@storybook/react": "7.4.6",
"@storybook/react-webpack5": "7.4.6",
"@storybook/theming": "7.4.6",
"@types/node": "22.18.0",
"adm-zip": "^0.5.10",
"axios-mock-adapter": "^1.22.0",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "8.1.0",
"chokidar": "4.0.3",
"concurrently": "9.2.1",
"flow-bin": "0.131.0",
"flow-coverage-report": "^0.4.0",
"folder-hash": "^3.0.0",
@@ -96,6 +99,7 @@
"react-scripts": "5.0.1",
"recursive-copy": "^2.0.14",
"recursive-readdir": "^2.2.2",
"serve-handler": "6.1.6",
"shelljs": "0.8.4",
"storybook": "7.4.6",
"storybook-addon-mock": "4.3.0",
@@ -7065,6 +7069,12 @@
}
}
},
"node_modules/@storybook/builder-webpack5/node_modules/@types/node": {
"version": "16.18.126",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.126.tgz",
"integrity": "sha512-OTcgaiwfGFBKacvfwuHzzn1KLxH/er8mluiy8/uM3sGXHaRe73RrSIj01jow9t4kJEW633Ov+cOexXeiApTyAw==",
"dev": true
},
"node_modules/@storybook/builder-webpack5/node_modules/ajv": {
"version": "8.12.0",
"dev": true,
@@ -8053,6 +8063,12 @@
"url": "https://opencollective.com/storybook"
}
},
"node_modules/@storybook/core-common/node_modules/@types/node": {
"version": "16.18.126",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.126.tgz",
"integrity": "sha512-OTcgaiwfGFBKacvfwuHzzn1KLxH/er8mluiy8/uM3sGXHaRe73RrSIj01jow9t4kJEW633Ov+cOexXeiApTyAw==",
"dev": true
},
"node_modules/@storybook/core-common/node_modules/brace-expansion": {
"version": "2.0.1",
"dev": true,
@@ -8375,6 +8391,12 @@
"url": "https://opencollective.com/storybook"
}
},
"node_modules/@storybook/core-server/node_modules/@types/node": {
"version": "16.18.126",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.126.tgz",
"integrity": "sha512-OTcgaiwfGFBKacvfwuHzzn1KLxH/er8mluiy8/uM3sGXHaRe73RrSIj01jow9t4kJEW633Ov+cOexXeiApTyAw==",
"dev": true
},
"node_modules/@storybook/core-server/node_modules/fs-extra": {
"version": "11.1.1",
"dev": true,
@@ -8546,6 +8568,12 @@
"url": "https://opencollective.com/storybook"
}
},
"node_modules/@storybook/core-webpack/node_modules/@types/node": {
"version": "16.18.126",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.126.tgz",
"integrity": "sha512-OTcgaiwfGFBKacvfwuHzzn1KLxH/er8mluiy8/uM3sGXHaRe73RrSIj01jow9t4kJEW633Ov+cOexXeiApTyAw==",
"dev": true
},
"node_modules/@storybook/csf": {
"version": "0.1.1",
"dev": true,
@@ -8843,6 +8871,12 @@
}
}
},
"node_modules/@storybook/preset-react-webpack/node_modules/@types/node": {
"version": "16.18.126",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.126.tgz",
"integrity": "sha512-OTcgaiwfGFBKacvfwuHzzn1KLxH/er8mluiy8/uM3sGXHaRe73RrSIj01jow9t4kJEW633Ov+cOexXeiApTyAw==",
"dev": true
},
"node_modules/@storybook/preset-react-webpack/node_modules/fs-extra": {
"version": "11.1.1",
"dev": true,
@@ -9067,6 +9101,18 @@
}
}
},
"node_modules/@storybook/react-webpack5/node_modules/@types/node": {
"version": "16.18.126",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.126.tgz",
"integrity": "sha512-OTcgaiwfGFBKacvfwuHzzn1KLxH/er8mluiy8/uM3sGXHaRe73RrSIj01jow9t4kJEW633Ov+cOexXeiApTyAw==",
"dev": true
},
"node_modules/@storybook/react/node_modules/@types/node": {
"version": "16.18.126",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.126.tgz",
"integrity": "sha512-OTcgaiwfGFBKacvfwuHzzn1KLxH/er8mluiy8/uM3sGXHaRe73RrSIj01jow9t4kJEW633Ov+cOexXeiApTyAw==",
"dev": true
},
"node_modules/@storybook/react/node_modules/acorn": {
"version": "7.4.1",
"dev": true,
@@ -10055,8 +10101,12 @@
"license": "MIT"
},
"node_modules/@types/node": {
"version": "16.18.12",
"license": "MIT"
"version": "22.18.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.18.0.tgz",
"integrity": "sha512-m5ObIqwsUp6BZzyiy4RdZpzWGub9bqLJMvZDD0QMXhxjqMHMENlj+SqF5QxoUwaQNFe+8kz8XM8ZQhqkQPTgMQ==",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/node-fetch": {
"version": "2.6.6",
@@ -12199,11 +12249,15 @@
}
},
"node_modules/binary-extensions": {
"version": "2.1.0",
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
"integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/bl": {
@@ -12712,29 +12766,18 @@
"license": "MIT"
},
"node_modules/chokidar": {
"version": "3.5.3",
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
"integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
"dev": true,
"funding": [
{
"type": "individual",
"url": "https://paulmillr.com/funding/"
}
],
"license": "MIT",
"dependencies": {
"anymatch": "~3.1.2",
"braces": "~3.0.2",
"glob-parent": "~5.1.2",
"is-binary-path": "~2.1.0",
"is-glob": "~4.0.1",
"normalize-path": "~3.0.0",
"readdirp": "~3.6.0"
"readdirp": "^4.0.1"
},
"engines": {
"node": ">= 8.10.0"
"node": ">= 14.16.0"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/chownr": {
@@ -13153,6 +13196,171 @@
"typedarray": "^0.0.6"
}
},
"node_modules/concurrently": {
"version": "9.2.1",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz",
"integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==",
"dev": true,
"dependencies": {
"chalk": "4.1.2",
"rxjs": "7.8.2",
"shell-quote": "1.8.3",
"supports-color": "8.1.1",
"tree-kill": "1.2.2",
"yargs": "17.7.2"
},
"bin": {
"conc": "dist/bin/concurrently.js",
"concurrently": "dist/bin/concurrently.js"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/open-cli-tools/concurrently?sponsor=1"
}
},
"node_modules/concurrently/node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"engines": {
"node": ">=8"
}
},
"node_modules/concurrently/node_modules/cliui": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
"integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
"dev": true,
"dependencies": {
"string-width": "^4.2.0",
"strip-ansi": "^6.0.1",
"wrap-ansi": "^7.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/concurrently/node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"dev": true,
"engines": {
"node": ">=8"
}
},
"node_modules/concurrently/node_modules/rxjs": {
"version": "7.8.2",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz",
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
"dev": true,
"dependencies": {
"tslib": "^2.1.0"
}
},
"node_modules/concurrently/node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/concurrently/node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/concurrently/node_modules/supports-color": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
"integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
"dev": true,
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/supports-color?sponsor=1"
}
},
"node_modules/concurrently/node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true
},
"node_modules/concurrently/node_modules/wrap-ansi": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
"dev": true,
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/concurrently/node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
"dev": true,
"engines": {
"node": ">=10"
}
},
"node_modules/concurrently/node_modules/yargs": {
"version": "17.7.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
"integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",
"dev": true,
"dependencies": {
"cliui": "^8.0.1",
"escalade": "^3.1.1",
"get-caller-file": "^2.0.5",
"require-directory": "^2.1.1",
"string-width": "^4.2.3",
"y18n": "^5.0.5",
"yargs-parser": "^21.1.1"
},
"engines": {
"node": ">=12"
}
},
"node_modules/concurrently/node_modules/yargs-parser": {
"version": "21.1.1",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
"integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
"dev": true,
"engines": {
"node": ">=12"
}
},
"node_modules/confusing-browser-globals": {
"version": "1.0.11",
"dev": true,
@@ -16779,6 +16987,30 @@
"webpack": "^5.11.0"
}
},
"node_modules/fork-ts-checker-webpack-plugin/node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
"dev": true,
"dependencies": {
"anymatch": "~3.1.2",
"braces": "~3.0.2",
"glob-parent": "~5.1.2",
"is-binary-path": "~2.1.0",
"is-glob": "~4.0.1",
"normalize-path": "~3.0.0",
"readdirp": "~3.6.0"
},
"engines": {
"node": ">= 8.10.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
}
},
"node_modules/fork-ts-checker-webpack-plugin/node_modules/cosmiconfig": {
"version": "7.1.0",
"dev": true,
@@ -16850,6 +17082,18 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/fork-ts-checker-webpack-plugin/node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
"integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
"dev": true,
"dependencies": {
"picomatch": "^2.2.1"
},
"engines": {
"node": ">=8.10.0"
}
},
"node_modules/fork-ts-checker-webpack-plugin/node_modules/resolve-from": {
"version": "4.0.0",
"dev": true,
@@ -18364,8 +18608,9 @@
},
"node_modules/is-binary-path": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
"integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
"dev": true,
"license": "MIT",
"dependencies": {
"binary-extensions": "^2.0.0"
},
@@ -22613,14 +22858,6 @@
"shell-quote": "^1.7.3"
}
},
"node_modules/launch-editor/node_modules/shell-quote": {
"version": "1.8.1",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/lazy-universal-dotenv": {
"version": "4.0.0",
"dev": true,
@@ -24920,6 +25157,12 @@
"node": ">=0.10.0"
}
},
"node_modules/path-is-inside": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz",
"integrity": "sha512-DUWJr3+ULp4zXmol/SZkFf3JGsS9/SIv+Y3Rt93/UjPpDpklB5f1er4O3POIbUuUJ3FXgqte2Q7SrU6zAqwk8w==",
"dev": true
},
"node_modules/path-key": {
"version": "2.0.1",
"dev": true,
@@ -26800,6 +27043,30 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/react-scripts/node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
"dev": true,
"dependencies": {
"anymatch": "~3.1.2",
"braces": "~3.0.2",
"glob-parent": "~5.1.2",
"is-binary-path": "~2.1.0",
"is-glob": "~4.0.1",
"normalize-path": "~3.0.0",
"readdirp": "~3.6.0"
},
"engines": {
"node": ">= 8.10.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
}
},
"node_modules/react-scripts/node_modules/cosmiconfig": {
"version": "7.1.0",
"dev": true,
@@ -28518,6 +28785,18 @@
"node": ">= 12.13.0"
}
},
"node_modules/react-scripts/node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
"integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
"dev": true,
"dependencies": {
"picomatch": "^2.2.1"
},
"engines": {
"node": ">=8.10.0"
}
},
"node_modules/react-scripts/node_modules/resolve-from": {
"version": "4.0.0",
"dev": true,
@@ -28621,14 +28900,6 @@
"node": ">=8"
}
},
"node_modules/react-scripts/node_modules/shell-quote": {
"version": "1.8.1",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/react-scripts/node_modules/source-map": {
"version": "0.6.1",
"dev": true,
@@ -29111,14 +29382,16 @@
"license": "MIT"
},
"node_modules/readdirp": {
"version": "3.6.0",
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
"integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",
"dev": true,
"license": "MIT",
"dependencies": {
"picomatch": "^2.2.1"
},
"engines": {
"node": ">=8.10.0"
"node": ">= 14.18.0"
},
"funding": {
"type": "individual",
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/recast": {
@@ -30089,6 +30362,87 @@
"randombytes": "^2.1.0"
}
},
"node_modules/serve-handler": {
"version": "6.1.6",
"resolved": "https://registry.npmjs.org/serve-handler/-/serve-handler-6.1.6.tgz",
"integrity": "sha512-x5RL9Y2p5+Sh3D38Fh9i/iQ5ZK+e4xuXRd/pGbM4D13tgo/MGwbttUk8emytcr1YYzBYs+apnUngBDFYfpjPuQ==",
"dev": true,
"dependencies": {
"bytes": "3.0.0",
"content-disposition": "0.5.2",
"mime-types": "2.1.18",
"minimatch": "3.1.2",
"path-is-inside": "1.0.2",
"path-to-regexp": "3.3.0",
"range-parser": "1.2.0"
}
},
"node_modules/serve-handler/node_modules/bytes": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz",
"integrity": "sha512-pMhOfFDPiv9t5jjIXkHosWmkSyQbvsgEVNkz0ERHbuLh2T/7j4Mqqpz523Fe8MVY89KC6Sh/QfS2sM+SjgFDcw==",
"dev": true,
"engines": {
"node": ">= 0.8"
}
},
"node_modules/serve-handler/node_modules/content-disposition": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz",
"integrity": "sha512-kRGRZw3bLlFISDBgwTSA1TMBFN6J6GWDeubmDE3AF+3+yXL8hTWv8r5rkLbqYXY4RjPk/EzHnClI3zQf1cFmHA==",
"dev": true,
"engines": {
"node": ">= 0.6"
}
},
"node_modules/serve-handler/node_modules/mime-db": {
"version": "1.33.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.33.0.tgz",
"integrity": "sha512-BHJ/EKruNIqJf/QahvxwQZXKygOQ256myeN/Ew+THcAa5q+PjyTTMMeNQC4DZw5AwfvelsUrA6B67NKMqXDbzQ==",
"dev": true,
"engines": {
"node": ">= 0.6"
}
},
"node_modules/serve-handler/node_modules/mime-types": {
"version": "2.1.18",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.18.tgz",
"integrity": "sha512-lc/aahn+t4/SWV/qcmumYjymLsWfN3ELhpmVuUFjgsORruuZPVSwAQryq+HHGvO/SI2KVX26bx+En+zhM8g8hQ==",
"dev": true,
"dependencies": {
"mime-db": "~1.33.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/serve-handler/node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"dev": true,
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/serve-handler/node_modules/path-to-regexp": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-3.3.0.tgz",
"integrity": "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==",
"dev": true
},
"node_modules/serve-handler/node_modules/range-parser": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.0.tgz",
"integrity": "sha512-kA5WQoNVo4t9lNx2kQNFCxKeBl5IbbSNBl1M/tLkw9WCn+hxNBAW5Qh8gdhs63CJnhjJ2zQWFoqPJP2sK1AV5A==",
"dev": true,
"engines": {
"node": ">= 0.6"
}
},
"node_modules/serve-index": {
"version": "1.9.1",
"dev": true,
@@ -30198,6 +30552,18 @@
"node": ">=0.10.0"
}
},
"node_modules/shell-quote": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
"dev": true,
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/shelljs": {
"version": "0.8.4",
"dev": true,
@@ -31330,6 +31696,42 @@
"node": ">= 8"
}
},
"node_modules/tailwindcss/node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
"dev": true,
"dependencies": {
"anymatch": "~3.1.2",
"braces": "~3.0.2",
"glob-parent": "~5.1.2",
"is-binary-path": "~2.1.0",
"is-glob": "~4.0.1",
"normalize-path": "~3.0.0",
"readdirp": "~3.6.0"
},
"engines": {
"node": ">= 8.10.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
}
},
"node_modules/tailwindcss/node_modules/chokidar/node_modules/glob-parent": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
"dev": true,
"dependencies": {
"is-glob": "^4.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/tailwindcss/node_modules/fast-glob": {
"version": "3.2.12",
"dev": true,
@@ -31474,6 +31876,18 @@
"postcss": "^8.2.14"
}
},
"node_modules/tailwindcss/node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
"integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
"dev": true,
"dependencies": {
"picomatch": "^2.2.1"
},
"engines": {
"node": ">=8.10.0"
}
},
"node_modules/tailwindcss/node_modules/yaml": {
"version": "2.3.1",
"dev": true,
@@ -31911,6 +32325,15 @@
"node": ">=6"
}
},
"node_modules/tree-kill": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
"integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",
"dev": true,
"bin": {
"tree-kill": "cli.js"
}
},
"node_modules/trim-lines": {
"version": "3.0.1",
"license": "MIT",
@@ -32119,6 +32542,11 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="
},
"node_modules/unicode-canonical-property-names-ecmascript": {
"version": "2.0.0",
"dev": true,
@@ -32299,6 +32727,42 @@
"webpack-virtual-modules": "^0.5.0"
}
},
"node_modules/unplugin/node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
"dev": true,
"dependencies": {
"anymatch": "~3.1.2",
"braces": "~3.0.2",
"glob-parent": "~5.1.2",
"is-binary-path": "~2.1.0",
"is-glob": "~4.0.1",
"normalize-path": "~3.0.0",
"readdirp": "~3.6.0"
},
"engines": {
"node": ">= 8.10.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
}
},
"node_modules/unplugin/node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
"integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
"dev": true,
"dependencies": {
"picomatch": "^2.2.1"
},
"engines": {
"node": ">=8.10.0"
}
},
"node_modules/unplugin/node_modules/webpack-sources": {
"version": "3.2.3",
"dev": true,
@@ -32856,6 +33320,30 @@
"ajv": "^8.8.2"
}
},
"node_modules/webpack-dev-server/node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
"dev": true,
"dependencies": {
"anymatch": "~3.1.2",
"braces": "~3.0.2",
"glob-parent": "~5.1.2",
"is-binary-path": "~2.1.0",
"is-glob": "~4.0.1",
"normalize-path": "~3.0.0",
"readdirp": "~3.6.0"
},
"engines": {
"node": ">= 8.10.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
}
},
"node_modules/webpack-dev-server/node_modules/ipaddr.js": {
"version": "2.1.0",
"dev": true,
@@ -32885,6 +33373,18 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/webpack-dev-server/node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
"integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==",
"dev": true,
"dependencies": {
"picomatch": "^2.2.1"
},
"engines": {
"node": ">=8.10.0"
}
},
"node_modules/webpack-dev-server/node_modules/rimraf": {
"version": "3.0.2",
"dev": true,

View File

@@ -17,10 +17,13 @@
"@storybook/react": "7.4.6",
"@storybook/react-webpack5": "7.4.6",
"@storybook/theming": "7.4.6",
"@types/node": "22.18.0",
"adm-zip": "^0.5.10",
"axios-mock-adapter": "^1.22.0",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "8.1.0",
"chokidar": "4.0.3",
"concurrently": "9.2.1",
"flow-bin": "0.131.0",
"flow-coverage-report": "^0.4.0",
"folder-hash": "^3.0.0",
@@ -32,6 +35,7 @@
"react-scripts": "5.0.1",
"recursive-copy": "^2.0.14",
"recursive-readdir": "^2.2.2",
"serve-handler": "6.1.6",
"shelljs": "0.8.4",
"storybook": "7.4.6",
"storybook-addon-mock": "4.3.0",
@@ -116,7 +120,7 @@
"import-resources": "npm run import-zipped-external-editors && npm run build-theme-resources && cd scripts && node import-libGD.js && node import-GDJS-Runtime.js && node import-monaco-editor.js && node import-zipped-external-libs.js",
"make-version-metadata": "cd scripts && node make-version-metadata.js",
"make-service-worker": "cd scripts && node make-service-worker.js",
"start": "npm run import-resources && npm run make-version-metadata && react-app-rewired start",
"start": "npm run import-resources && npm run make-version-metadata && concurrently \"react-app-rewired start\" \"node scripts/watch-serve-GDJS-runtime.js\" -n \"editor,game engine\"",
"electron-app": "cd ../electron-app && npm run start",
"build": "npm run import-resources && npm run make-version-metadata && react-app-rewired build && npm run make-service-worker",
"format": "prettier --write \"src/!(locales)/**/*.js\"",

View File

@@ -632,6 +632,56 @@ const generateExtensionRawText = (
...expressionsReferenceTexts,
];
}),
{ text: '' },
...extension
.getExtensionEffectTypes()
.toJSArray()
.map(
/**
* @param {string} effectType
* @returns {RawText}
*/
effectType => {
const effectMetadata = extension.getEffectMetadata(effectType);
const properties = effectMetadata.getProperties();
const propertyNames = properties.keys().toJSArray();
return {
text: [
`### Effect "${effectMetadata.getFullName()}"`,
'',
`${effectMetadata.getDescription().replace(/\n/g, ' ')}`,
'',
...[
effectMetadata.isMarkedAsUnique()
? 'This effect can be added only once on a layer.'
: null,
effectMetadata.isMarkedAsOnlyWorkingFor2D()
? effectMetadata.isMarkedAsNotWorkingForObjects()
? 'This effect is for 2D layers only.'
: 'This effect is for 2D layers or objects only.'
: null,
effectMetadata.isMarkedAsOnlyWorkingFor3D()
? 'This effect is for 3D layers only.'
: null,
].filter(Boolean),
'',
`Properties of this effect are:`,
'',
...propertyNames.map(propertyName => {
const propertyMetadata = properties.get(propertyName);
return [
propertyMetadata.getDescription()
? `- **${propertyMetadata.getLabel()}**: ${propertyMetadata.getDescription()}.`
: `- **${propertyMetadata.getLabel()}**.`,
`Default value is \`${propertyMetadata.getValue()}\`. For events, write: \`"${propertyName}"\`.`,
].join(' ');
}),
'',
].join(`\n`),
};
}
),
generateExtensionFooterText({ extension }),
].filter(Boolean);
};

View File

@@ -0,0 +1,239 @@
#!/usr/bin/env node
// @ts-check
/*
* This script watches GDJS Runtime and Extensions files for changes
* and automatically runs import-GDJS-Runtime.js when changes are detected.
*
* Usage: node watch-GDJS-runtime.js
* Stop with Ctrl+C
*/
const chokidar = require('chokidar');
const debounce = require('lodash.debounce');
const child_process = require('child_process');
const path = require('path');
const handler = require('serve-handler');
const http = require('http');
const PORT = 5002;
const gdevelopRootPath = path.join(__dirname, '..', '..', '..');
const gdjsRootPath = path.join(__dirname, '..', 'resources', 'GDJS');
// Serve the built files for GDJS.
const server = http.createServer((request, response) => {
return handler(request, response, {
public: gdjsRootPath,
cleanUrls: false,
headers: [
{
source: '**/*',
headers: [
// Tell the browser not to cache the files:
{
key: 'Cache-Control',
value: 'no-cache',
},
// Allow CORS because the web-app is served from a different origin:
{
key: 'Access-Control-Allow-Origin',
value: '*',
},
{
key: 'Access-Control-Allow-Headers',
value: '*',
},
{
key: 'Access-Control-Allow-Credentials',
value: 'true',
},
{
key: 'Access-Control-Allow-Private-Network',
value: 'true',
},
],
},
],
});
});
/**
* Launch the import-GDJS-Runtime script.
* Cleaning the GDJS output folder and copying sources are both
* skipped to speed up the build.
* @returns {Promise<void>}
*/
const importGDJSRuntime = () => {
return new Promise((resolve, reject) => {
const startTime = performance.now();
const scriptPath = path.join(__dirname, 'import-GDJS-Runtime.js');
console.log('🔄 Running import-GDJS-Runtime.js...');
child_process.exec(
`node "${scriptPath}" --skip-clean --skip-sources`,
(error, stdout, stderr) => {
if (error) {
console.error(`❌ GDJS Runtime update error: ${error.message}`);
reject(error);
return;
}
if (stdout) {
console.log(stdout);
}
if (stderr) {
console.error(`⚠️ GDJS Runtime update warnings: ${stderr}`);
}
const duration = (performance.now() - startTime).toFixed(0);
console.log(`✅ GDJS Runtime updated in ${duration}ms.`);
resolve();
}
);
});
};
/**
* Callback for file changes, debounced to avoid running too frequently
*/
const onWatchEvent = debounce(
(event, filePath) => {
const eventName = event || 'unknown-event';
const resolvedFilename =
path.relative(gdevelopRootPath, filePath) || 'unknown-file';
console.log(
`📁 Detected "${eventName}" in ${resolvedFilename}, updating GDJS Runtime...`
);
importGDJSRuntime().catch(error => {
console.error('❌ Failed to update GDJS Runtime:', error.message);
});
},
100 // Avoid running the script too much in case multiple changes are fired at the same time
);
/**
* Set up file watchers for GDJS and Extensions sources
*/
const setupWatcher = () => {
const watchPaths = [
path.join(gdevelopRootPath, 'GDJS', 'Runtime'),
path.join(gdevelopRootPath, 'Extensions'),
];
const watcher = chokidar.watch(watchPaths, {
ignored: (filePath, stats) => {
if (!stats) return false;
if (!stats.isFile()) return false;
const ignoredExtensions = [
'.d.ts',
'.map',
'.md',
'.png',
'.svg',
'.svgz',
'.txt',
'.DS_Store',
'.prettierrc',
];
const ignoredFolderNames = ['tests', 'example', 'diagrams'];
if (ignoredExtensions.some(ext => filePath.endsWith(ext))) return true;
if (
ignoredFolderNames.some(
folder =>
filePath.includes(folder + '/') || filePath.includes(folder + '\\')
)
)
return true;
// Uncomment to log all watched files:
// console.log('Watched file path: ' + filePath);
return false;
},
persistent: true,
awaitWriteFinish: {
stabilityThreshold: 100,
pollInterval: 50,
},
ignoreInitial: true,
});
// Set up event handlers:
const startTime = performance.now();
watcher
.on('all', onWatchEvent)
.on('error', error => {
console.error(
'❌ GDJS watcher error. Please try to relaunch it. Full error is:',
error
);
})
.on('ready', () => {
const duration = (performance.now() - startTime).toFixed(2);
console.log(`✅ GDJS watcher ready in ${duration}ms.`);
console.log(
` Watching GDJS engine files for changes in:\n${watchPaths
.map(path => `- ${path}`)
.join('\n')}.`
);
});
return watcher;
};
const watcher = setupWatcher();
// Handle graceful shutdown:
const shutdown = () => {
console.log('\n Shutting GDJS Runtime file watcher and server...');
server.close(() => {
console.log('✅ GDJS Runtime server closed.');
});
watcher
.close()
.then(() => {
console.log('✅ GDJS Runtime watcher closed.');
process.exit(0);
})
.catch(error => {
console.error('❌ Error closing GDJS Runtime watcher:', error);
process.exit(1);
});
};
// Handle Ctrl+C and other termination signals.
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
process.on('SIGHUP', shutdown);
// Start the server (used to serve the game engine to the web-app).
server.on('error', error => {
// @ts-ignore
if (error.code === 'EADDRINUSE') {
console.error(
`❌ Error: Port ${PORT} is already in use and can't be used to serve the game engine to the web-app.`
);
}
// @ts-ignore
else if (error.code === 'EACCES') {
console.error(
`❌ Error: Permission denied to bind to port ${PORT} and can't be used to serve the game engine to the web-app.`
);
} else {
console.error('❌ Game engine server error:', error);
}
process.exit(1);
});
server.listen(PORT, () => {
console.log(
` GDJS Runtime served for the web-app at http://localhost:${PORT}.`
);
});

View File

@@ -5,6 +5,7 @@ import { I18n } from '@lingui/react';
import {
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from '../MainFrame/EditorContainers/BaseEditor';
import { type ObjectWithContext } from '../ObjectsList/EnumerateObjects';
import Paper from '../UI/Paper';
@@ -49,8 +50,9 @@ import {
sendAiRequestMessageSent,
sendAiRequestStarted,
} from '../Utils/Analytics/EventSender';
import { useCreateAiProjectDialog } from './UseCreateAiProjectDialog';
import { type ExampleShortHeader } from '../Utils/GDevelopServices/Example';
import { listAllExamples } from '../Utils/GDevelopServices/Example';
import UrlStorageProvider from '../ProjectsStorage/UrlStorageProvider';
import { prepareAiUserContent } from './PrepareAiUserContent';
import { AiRequestContext } from './AiRequestContext';
import { getAiConfigurationPresetsWithAvailability } from './AiConfiguration';
@@ -67,6 +69,7 @@ const useProcessFunctionCalls = ({
getEditorFunctionCallResults,
addEditorFunctionCallResults,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
onExtensionInstalled,
}: {|
i18n: I18nType,
@@ -85,6 +88,9 @@ const useProcessFunctionCalls = ({
onSceneEventsModifiedOutsideEditor: (
changes: SceneEventsOutsideEditorChanges
) => void,
onInstancesModifiedOutsideEditor: (
changes: InstancesOutsideEditorChanges
) => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
|}) => {
const { ensureExtensionInstalled } = useEnsureExtensionInstalled({
@@ -159,6 +165,7 @@ const useProcessFunctionCalls = ({
});
},
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
ensureExtensionInstalled,
searchAndInstallAsset,
});
@@ -179,6 +186,7 @@ const useProcessFunctionCalls = ({
searchAndInstallAsset,
generateEvents,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
triggerSendEditorFunctionCallResults,
editorCallbacks,
]
@@ -192,7 +200,7 @@ const useProcessFunctionCalls = ({
editorFunctionCallResults: getEditorFunctionCallResults(
selectedAiRequest.id
),
})
}).filter(functionCall => functionCall.name !== 'initialize_project')
: [],
[selectedAiRequest, getEditorFunctionCallResults]
);
@@ -327,7 +335,6 @@ type Props = {|
storageProvider: ?StorageProvider,
setToolbar: (?React.Node) => void,
i18n: I18nType,
onCreateEmptyProject: (newProjectSetup: NewProjectSetup) => Promise<void>,
onCreateProjectFromExample: (
exampleShortHeader: ExampleShortHeader,
newProjectSetup: NewProjectSetup,
@@ -349,6 +356,9 @@ type Props = {|
onSceneEventsModifiedOutsideEditor: (
changes: SceneEventsOutsideEditorChanges
) => void,
onInstancesModifiedOutsideEditor: (
changes: InstancesOutsideEditorChanges
) => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
initialMode: 'chat' | 'agent' | null,
initialAiRequestId: string | null,
@@ -372,6 +382,9 @@ export type AskAiEditorInterface = {|
onSceneEventsModifiedOutsideEditor: (
changes: SceneEventsOutsideEditorChanges
) => void,
onInstancesModifiedOutsideEditor: (
changes: InstancesOutsideEditorChanges
) => void,
startOrOpenChat: ({|
mode: 'chat' | 'agent',
aiRequestId: string | null,
@@ -397,10 +410,10 @@ export const AskAiEditor = React.memo<Props>(
fileMetadata,
storageProvider,
i18n,
onCreateEmptyProject,
onCreateProjectFromExample,
onOpenLayout,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
onExtensionInstalled,
initialMode,
initialAiRequestId,
@@ -488,10 +501,7 @@ export const AskAiEditor = React.memo<Props>(
setLastSendError,
} = aiRequestStorage;
const {
createAiProject,
renderCreateAiProjectDialog,
} = useCreateAiProjectDialog();
const updateToolbar = React.useCallback(
() => {
@@ -518,6 +528,7 @@ export const AskAiEditor = React.memo<Props>(
onSceneObjectEdited: noop,
onSceneObjectsDeleted: noop,
onSceneEventsModifiedOutsideEditor: noop,
onInstancesModifiedOutsideEditor: noop,
startOrOpenChat: onStartOrOpenChat,
}));
@@ -582,28 +593,7 @@ export const AskAiEditor = React.memo<Props>(
} = newAiRequestOptions;
startNewAiRequest(null);
// If no project is opened, create a new empty one if the request is for
// the AI agent.
if (mode === 'agent' && !project) {
try {
console.info(
'No project opened, opening the dialog to create a new project.'
);
const result = await createAiProject();
if (result === 'canceled') {
return;
}
console.info('New project created - starting AI request.');
startNewAiRequest({
mode,
userRequest,
aiConfigurationPresetId,
});
} catch (error) {
console.error('Error creating a new empty project:', error);
}
return;
}
// Do not create a project automatically anymore.
// Ensure the user has enough credits to pay for the request, or ask them
// to buy some more.
@@ -655,6 +645,7 @@ export const AskAiEditor = React.memo<Props>(
fileMetadata,
storageProviderName,
mode,
toolsVersion: 'v2',
aiConfiguration: {
presetId: aiConfigurationPresetId,
},
@@ -904,6 +895,107 @@ export const AskAiEditor = React.memo<Props>(
[onSendMessage]
);
const processInitializeProjectFunctionCalls = React.useCallback(
async (
functionCalls: Array<AiRequestMessageAssistantFunctionCall>
) => {
if (!selectedAiRequest) return;
// Mark all provided calls as working.
addEditorFunctionCallResults(
selectedAiRequest.id,
functionCalls.map(functionCall => ({
status: 'working',
call_id: functionCall.call_id,
}))
);
const results: Array<EditorFunctionCallResult> = [];
for (const functionCall of functionCalls) {
let args: any = null;
try {
args = JSON.parse(functionCall.arguments);
} catch (error) {
results.push({
status: 'finished',
call_id: functionCall.call_id,
success: false,
output: { message: 'Invalid arguments (not a valid JSON string).' },
});
continue;
}
const name: ?string = args && args.name;
const slug: ?string = args && args.slug;
if (!name || !slug) {
results.push({
status: 'finished',
call_id: functionCall.call_id,
success: false,
output: { message: 'Missing required arguments: name and slug.' },
});
continue;
}
try {
const fetchedAllExamples = await listAllExamples();
const exampleShortHeader: ?ExampleShortHeader = fetchedAllExamples.exampleShortHeaders.find(
exampleShortHeader => exampleShortHeader.slug === slug
);
if (!exampleShortHeader) {
results.push({
status: 'finished',
call_id: functionCall.call_id,
success: false,
output: { message: `Unable to find the example with slug "${slug}".` },
});
continue;
}
const newProjectSetup: NewProjectSetup = {
storageProvider: UrlStorageProvider,
saveAsLocation: null,
projectName: name,
dontOpenAnySceneOrProjectManager: true,
};
await onCreateProjectFromExample(
exampleShortHeader,
newProjectSetup,
i18n,
false
);
results.push({
status: 'finished',
call_id: functionCall.call_id,
success: true,
output: { message: `Initialized project "${name}" from example "${slug}".` },
});
} catch (error) {
console.error('Error initializing project from example:', error);
results.push({
status: 'finished',
call_id: functionCall.call_id,
success: false,
output: { message: error && error.message ? error.message : 'Unknown error while initializing project.' },
});
}
}
addEditorFunctionCallResults(selectedAiRequest.id, results);
await onSendEditorFunctionCallResults(null);
},
[
selectedAiRequest,
addEditorFunctionCallResults,
onCreateProjectFromExample,
i18n,
onSendEditorFunctionCallResults,
]
);
const onSendFeedback = React.useCallback(
async (
aiRequestId,
@@ -944,10 +1036,60 @@ export const AskAiEditor = React.memo<Props>(
getEditorFunctionCallResults,
addEditorFunctionCallResults,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
i18n,
onExtensionInstalled,
});
const onProcessFunctionCallsWithInit = React.useCallback(
async (
functionCalls: Array<AiRequestMessageAssistantFunctionCall>,
options: ?{| ignore?: boolean |}
) => {
const initializeCalls = functionCalls.filter(
functionCall => functionCall.name === 'initialize_project'
);
const otherCalls = functionCalls.filter(
functionCall => functionCall.name !== 'initialize_project'
);
if (initializeCalls.length > 0) {
await processInitializeProjectFunctionCalls(initializeCalls);
}
if (otherCalls.length > 0) {
await onProcessFunctionCalls(otherCalls, options);
}
},
[processInitializeProjectFunctionCalls, onProcessFunctionCalls]
);
// Auto-process initialize_project calls even without an opened project.
React.useEffect(
() => {
(async () => {
if (!selectedAiRequest) return;
const functionCallsToProcess = getFunctionCallsToProcess({
aiRequest: selectedAiRequest,
editorFunctionCallResults: getEditorFunctionCallResults(
selectedAiRequest.id
),
});
const initializeCalls = functionCallsToProcess.filter(
functionCall => functionCall.name === 'initialize_project'
);
if (initializeCalls.length === 0) return;
console.info('Processing initialize_project AI function calls...');
await processInitializeProjectFunctionCalls(initializeCalls);
})();
},
[
selectedAiRequest,
getEditorFunctionCallResults,
processInitializeProjectFunctionCalls,
]
);
return (
<>
<Paper square background="dark" style={styles.paper}>
@@ -971,7 +1113,7 @@ export const AskAiEditor = React.memo<Props>(
? 'upgrade'
: 'none'
}
onProcessFunctionCalls={onProcessFunctionCalls}
onProcessFunctionCalls={onProcessFunctionCallsWithInit}
editorFunctionCallResults={
(selectedAiRequest &&
getEditorFunctionCallResults(selectedAiRequest.id)) ||
@@ -1000,10 +1142,6 @@ export const AskAiEditor = React.memo<Props>(
/>
</div>
</Paper>
{renderCreateAiProjectDialog({
onCreateEmptyProject,
onCreateProjectFromExample,
})}
<AskAiHistory
open={isHistoryOpen}
onClose={onCloseHistory}
@@ -1038,12 +1176,14 @@ export const renderAskAiEditorContainer = (
storageProvider={props.storageProvider}
setToolbar={props.setToolbar}
isActive={props.isActive}
onCreateEmptyProject={props.onCreateEmptyProject}
onCreateProjectFromExample={props.onCreateProjectFromExample}
onOpenLayout={props.onOpenLayout}
onSceneEventsModifiedOutsideEditor={
props.onSceneEventsModifiedOutsideEditor
}
onInstancesModifiedOutsideEditor={
props.onInstancesModifiedOutsideEditor
}
onExtensionInstalled={props.onExtensionInstalled}
initialMode={
(props.extraEditorProps && props.extraEditorProps.mode) || null

View File

@@ -65,7 +65,7 @@ export const AnnouncementsFeed = ({
const classesForClickableContainer = useStylesForClickableContainer();
if (error) {
if (error && !hideLoader) {
return (
<PlaceholderError onRetry={fetchAnnouncementsAndPromotions}>
<Trans>

View File

@@ -155,6 +155,7 @@ export const getBundleTiles = ({
receivedBundles,
openedShopCategory,
hasAssetFiltersApplied,
onlyShowAssets,
}: {|
allBundleListingDatas: ?Array<BundleListingData>,
displayedBundleListingDatas: ?Array<BundleListingData>,
@@ -162,12 +163,14 @@ export const getBundleTiles = ({
receivedBundles: ?Array<any>,
openedShopCategory?: ?string,
hasAssetFiltersApplied?: boolean,
onlyShowAssets?: boolean,
|}): Array<React.Node> => {
if (
!allBundleListingDatas ||
!displayedBundleListingDatas ||
!onBundleSelection ||
hasAssetFiltersApplied
hasAssetFiltersApplied ||
onlyShowAssets
)
return [];

View File

@@ -580,6 +580,7 @@ const AssetsList = React.forwardRef<Props, AssetsListInterface>(
onBundleSelection,
receivedBundles,
hasAssetFiltersApplied,
onlyShowAssets,
}),
[
allBundleListingDatas,
@@ -587,6 +588,7 @@ const AssetsList = React.forwardRef<Props, AssetsListInterface>(
onBundleSelection,
receivedBundles,
hasAssetFiltersApplied,
onlyShowAssets,
]
);

View File

@@ -33,6 +33,7 @@ type Props = {|
id?: string,
objectType: string,
objectBehaviorsTypes: Array<string>,
isChildObject: boolean,
behaviorShortHeader: BehaviorShortHeader,
matches: ?Array<SearchMatch>,
onChoose: () => void,
@@ -45,6 +46,7 @@ export const BehaviorListItem = ({
id,
objectType,
objectBehaviorsTypes,
isChildObject,
behaviorShortHeader,
matches,
onChoose,
@@ -53,20 +55,28 @@ export const BehaviorListItem = ({
platform,
}: Props) => {
const alreadyAdded = objectBehaviorsTypes.includes(behaviorShortHeader.type);
// An empty object type means the base object, i.e: any object.
const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
platform,
behaviorShortHeader.type
);
const isObjectCompatible =
// An empty object type means the base object, i.e: any object.
(!behaviorShortHeader.objectType ||
objectType === behaviorShortHeader.objectType) &&
(!isChildObject || behaviorMetadata.isRelevantForChildObjects()) &&
behaviorShortHeader.allRequiredBehaviorTypes.every(requiredBehaviorType => {
const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
platform,
requiredBehaviorType
);
return (
!behaviorMetadata.isHidden() ||
objectBehaviorsTypes.includes(requiredBehaviorType)
(!isChildObject || behaviorMetadata.isRelevantForChildObjects()) &&
(!behaviorMetadata.isHidden() ||
objectBehaviorsTypes.includes(requiredBehaviorType))
);
});
const isEngineCompatible = isCompatibleWithGDevelopVersion(
getIDEVersion(),
behaviorShortHeader.gdevelopVersion

View File

@@ -62,6 +62,7 @@ type Props = {|
project: gdProject,
objectType: string,
objectBehaviorsTypes: Array<string>,
isChildObject: boolean,
installedBehaviorMetadataList: Array<BehaviorShortHeader>,
deprecatedBehaviorMetadataList: Array<BehaviorShortHeader>,
onInstall: (behaviorShortHeader: BehaviorShortHeader) => Promise<boolean>,
@@ -76,6 +77,7 @@ export const BehaviorStore = ({
project,
objectType,
objectBehaviorsTypes,
isChildObject,
installedBehaviorMetadataList,
deprecatedBehaviorMetadataList,
onInstall,
@@ -316,6 +318,7 @@ export const BehaviorStore = ({
key={behaviorShortHeader.type}
objectType={objectType}
objectBehaviorsTypes={objectBehaviorsTypes}
isChildObject={isChildObject}
onHeightComputed={onHeightComputed}
behaviorShortHeader={behaviorShortHeader}
matches={getExtensionsMatches(behaviorShortHeader)}

View File

@@ -1,80 +1,53 @@
// @flow
import * as React from 'react';
import { I18n } from '@lingui/react';
import {
type BundleListingData,
type PrivateAssetPackListingData,
type PrivateGameTemplateListingData,
type CourseListingData,
} from '../../Utils/GDevelopServices/Shop';
import { Column, Line, Spacer } from '../../UI/Grid';
import BundlePageHeader from './BundlePageHeader';
import { BundleStoreContext } from './BundleStoreContext';
import PlaceholderLoader from '../../UI/PlaceholderLoader';
import {
getBundle,
type Bundle,
type Course,
} from '../../Utils/GDevelopServices/Asset';
import Text from '../../UI/Text';
import {
type PrivateAssetPackListingData,
type BundleListingData,
type PrivateGameTemplateListingData,
type CourseListingData,
} from '../../Utils/GDevelopServices/Shop';
import { type SubscriptionPlanWithPricingSystems } from '../../Utils/GDevelopServices/Usage';
import { extractGDevelopApiErrorStatusAndCode } from '../../Utils/GDevelopServices/Errors';
import { Trans } from '@lingui/macro';
import AlertMessage from '../../UI/AlertMessage';
import PlaceholderLoader from '../../UI/PlaceholderLoader';
import FlatButton from '../../UI/FlatButton';
import {
ResponsiveLineStackLayout,
LineStackLayout,
ColumnStackLayout,
} from '../../UI/Layout';
import { Column, LargeSpacer, Line, Spacer } from '../../UI/Grid';
import {
getUserPublicProfile,
type UserPublicProfile,
} from '../../Utils/GDevelopServices/User';
import Link from '../../UI/Link';
import ResponsiveMediaGallery from '../../UI/ResponsiveMediaGallery';
getProductsIncludedInBundle,
getProductsIncludedInBundleTiles,
} from '../ProductPageHelper';
import { PrivateGameTemplateStoreContext } from '../PrivateGameTemplates/PrivateGameTemplateStoreContext';
import { AssetStoreContext } from '../AssetStoreContext';
import AuthenticatedUserContext from '../../Profile/AuthenticatedUserContext';
import { GridList, GridListTile } from '@material-ui/core';
import {
useResponsiveWindowSize,
type WindowSizeType,
} from '../../UI/Responsive/ResponsiveWindowMeasurer';
import { sendBundleBuyClicked } from '../../Utils/Analytics/EventSender';
import { MarkdownText } from '../../UI/MarkdownText';
import ScrollView from '../../UI/ScrollView';
import { shouldUseAppStoreProduct } from '../../Utils/AppStorePurchases';
import AuthenticatedUserContext from '../../Profile/AuthenticatedUserContext';
import { extractGDevelopApiErrorStatusAndCode } from '../../Utils/GDevelopServices/Errors';
import Avatar from '@material-ui/core/Avatar';
import GridList from '@material-ui/core/GridList';
import { BundleStoreContext } from './BundleStoreContext';
import {
getBundlesContainingProductTiles,
getOtherProductsFromSameAuthorTiles,
getProductMediaItems,
getProductsIncludedInBundle,
getProductsIncludedInBundleTiles,
getUserProductPurchaseUsageType,
PurchaseProductButtons,
} from '../ProductPageHelper';
import SecureCheckout from '../SecureCheckout/SecureCheckout';
import GDevelopThemeContext from '../../UI/Theme/GDevelopThemeContext';
import BundlePurchaseDialog from './BundlePurchaseDialog';
import PublicProfileContext from '../../Profile/PublicProfileContext';
import { LARGE_WIDGET_SIZE } from '../../MainFrame/EditorContainers/HomePage/CardWidget';
import { PrivateGameTemplateStoreContext } from '../PrivateGameTemplates/PrivateGameTemplateStoreContext';
import { AssetStoreContext } from '../AssetStoreContext';
import Text from '../../UI/Text';
import CourseStoreContext from '../../Course/CourseStoreContext';
import { getCreditsAmountFromId } from '../CreditsPackages/CreditsPackageStoreContext';
import Coin from '../../Credits/Icons/Coin';
import {
getPlanIcon,
getPlanInferredNameFromId,
} from '../../Profile/Subscription/PlanCard';
import RedemptionCodesDialog from '../../RedemptionCode/RedemptionCodesDialog';
import { selectMessageByLocale } from '../../Utils/i18n/MessageByLocale';
import { formatDurationOfRedemptionCode } from '../../RedemptionCode/Utils';
import { planIdSortingFunction } from '../../Profile/Subscription/PlanCard';
import SubscriptionPlanPricingSummary from '../../Profile/Subscription/PromotionSubscriptionDialog/SubscriptionPlanPricingSummary';
import { ResponsiveLineStackLayout } from '../../UI/Layout';
import SubscriptionPlanTableSummary from '../../Profile/Subscription/PromotionSubscriptionDialog/SubscriptionPlanTableSummary';
import GDevelopThemeContext from '../../UI/Theme/GDevelopThemeContext';
import { LARGE_WIDGET_SIZE } from '../../MainFrame/EditorContainers/HomePage/CardWidget';
import SectionContainer, {
SectionRow,
} from '../../MainFrame/EditorContainers/HomePage/SectionContainer';
import { type CourseCompletion } from '../../MainFrame/EditorContainers/HomePage/UseCourses';
import CourseCard from '../../MainFrame/EditorContainers/HomePage/LearnSection/CourseCard';
const cellSpacing = 10;
const getTemplateColumns = (
windowSize: WindowSizeType,
isLandscape: boolean
) => {
const getColumns = (windowSize: WindowSizeType, isLandscape: boolean) => {
switch (windowSize) {
case 'small':
return isLandscape ? 4 : 2;
@@ -88,80 +61,50 @@ const getTemplateColumns = (
return 3;
}
};
const MAX_COLUMNS = getTemplateColumns('xlarge', true);
const cellSpacing = 10;
const MAX_COLUMNS = getColumns('xlarge', true);
const MAX_SECTION_WIDTH = (LARGE_WIDGET_SIZE + 2 * 5) * MAX_COLUMNS; // widget size + 5 padding per side
const styles = {
disabledText: { opacity: 0.6 },
scrollview: { overflowX: 'hidden' },
grid: {
// Avoid tiles taking too much space on large screens.
maxWidth: MAX_SECTION_WIDTH,
overflow: 'hidden',
width: `calc(100% + ${cellSpacing}px)`, // This is needed to compensate for the `margin: -5px` added by MUI related to spacing.
},
leftColumnContainer: {
flex: 1,
minWidth: 0, // This is needed for the container to take the right size.
},
rightColumnContainer: {
flex: 2,
},
leftColumnContainerMobile: {
flex: 1,
minWidth: 0, // This is needed for the container to take the right size.
},
rightColumnContainerMobile: {
flex: 1,
},
avatar: {
width: 20,
height: 20,
},
ownedTag: {
padding: '4px 8px',
borderRadius: 4,
color: 'black',
},
playIcon: {
width: 20,
height: 20,
},
coinIcon: {
width: 13,
height: 13,
position: 'relative',
top: -1,
},
};
type Props = {|
bundleListingData: BundleListingData,
bundleListingDatasFromSameCreator?: ?Array<BundleListingData>,
receivedCourses: ?Array<Course>,
onBack?: () => void | Promise<void>,
getSubscriptionPlansWithPricingSystems: () => Array<SubscriptionPlanWithPricingSystems> | null,
onBundleOpen: BundleListingData => void,
onGameTemplateOpen: PrivateGameTemplateListingData => void,
onAssetPackOpen: (
privateAssetPackListingData: PrivateAssetPackListingData,
options?: {|
forceProductPage?: boolean,
|}
privateAssetPackListingData: PrivateAssetPackListingData
) => void,
onCourseOpen: CourseListingData => void,
simulateAppStoreProduct?: boolean,
courses: ?Array<Course>,
receivedCourses: ?Array<Course>,
getCourseCompletion: (courseId: string) => CourseCompletion | null,
noPadding?: boolean,
|};
const BundleInformationPage = ({
bundleListingData,
bundleListingDatasFromSameCreator,
receivedCourses,
onBundleOpen,
onGameTemplateOpen,
onBack,
getSubscriptionPlansWithPricingSystems,
onAssetPackOpen,
onGameTemplateOpen,
onBundleOpen,
onCourseOpen,
simulateAppStoreProduct,
courses,
receivedCourses,
getCourseCompletion,
noPadding,
}: Props) => {
const { id, name, sellerId } = bundleListingData;
const { bundleListingDatas } = React.useContext(BundleStoreContext);
const { windowSize, isLandscape, isMobile } = useResponsiveWindowSize();
const { bundleListingDatas } = React.useContext(BundleStoreContext); // If archived, should use the one passed.
const { privateGameTemplateListingDatas } = React.useContext(
PrivateGameTemplateStoreContext
);
@@ -169,181 +112,125 @@ const BundleInformationPage = ({
const { listedCourses } = React.useContext(CourseStoreContext);
const {
receivedBundles,
bundlePurchases,
receivedGameTemplates,
receivedAssetPacks,
} = React.useContext(AuthenticatedUserContext);
const [bundle, setBundle] = React.useState<?Bundle>(null);
const [
purchasingBundleListingData,
setPurchasingBundleListingData,
] = React.useState<?BundleListingData>(null);
const [isFetching, setIsFetching] = React.useState<boolean>(false);
const { openUserPublicProfile } = React.useContext(PublicProfileContext);
const [
sellerPublicProfile,
setSellerPublicProfile,
] = React.useState<?UserPublicProfile>(null);
const [errorText, setErrorText] = React.useState<?React.Node>(null);
const {
windowSize,
isLandscape,
isMediumScreen,
isMobile,
} = useResponsiveWindowSize();
const gdevelopTheme = React.useContext(GDevelopThemeContext);
const [
isRedemptionCodesDialogOpen,
setIsRedemptionCodesDialogOpen,
] = React.useState<boolean>(false);
palette: { type: paletteType },
} = React.useContext(GDevelopThemeContext);
const shouldUseOrSimulateAppStoreProduct =
shouldUseAppStoreProduct() || simulateAppStoreProduct;
const userBundlePurchaseUsageType = React.useMemo(
() =>
getUserProductPurchaseUsageType({
productId: bundleListingData ? bundleListingData.id : null,
receivedProducts: receivedBundles,
productPurchases: bundlePurchases,
allProductListingDatas: bundleListingDatas,
}),
[bundlePurchases, bundleListingData, bundleListingDatas, receivedBundles]
);
const isAlreadyReceived = !!userBundlePurchaseUsageType;
const isOwningAnotherVariant = React.useMemo(
() => {
if (!bundle || isAlreadyReceived || !receivedBundles) return false;
// Another bundle older version of that bundle can be owned.
// We look at the tag to determine if the bundle is the same.
return !!receivedBundles.find(
receivedBundle => receivedBundle.tag === bundle.tag
);
},
[bundle, isAlreadyReceived, receivedBundles]
);
const additionalProductThumbnailsIncludedInBundle: string[] = React.useMemo(
() => {
const productsIncludedInBundle = getProductsIncludedInBundle({
productListingDatas: [
...(bundleListingDatas || []),
...(privateGameTemplateListingDatas || []),
...(privateAssetPackListingDatas || []),
...(listedCourses || []),
],
const courseAndTheirListingDataIncludedInBundle = React.useMemo(
(): Array<{|
course: Course,
courseListingData: CourseListingData,
|}> | null => {
if (!bundle || !bundleListingData || !courses) return null;
const productListingDatasInBundle = getProductsIncludedInBundle({
productListingData: bundleListingData,
productListingDatas: [...(listedCourses || [])],
});
if (!productsIncludedInBundle) return [];
if (!productListingDatasInBundle) return null;
// $FlowIgnore - Flow doesn't understand that we have filtered the products to only include courses.
const courseListingDatasInBundle: CourseListingData[] = productListingDatasInBundle.filter(
productListingData => productListingData.productType === 'COURSE'
);
const additionalThumbnails = productsIncludedInBundle
.map(product => (product.thumbnailUrls || []).slice(0, 2))
.reduce((acc, thumbnails) => acc.concat(thumbnails), []);
return additionalThumbnails;
return (courseListingDatasInBundle || [])
.map(courseListingData => {
const course = courses.find(
course => course.id === courseListingData.id
);
if (!course) return null;
return {
course,
courseListingData,
};
})
.filter(Boolean);
},
[
bundleListingDatas,
privateGameTemplateListingDatas,
privateAssetPackListingDatas,
listedCourses,
bundleListingData,
]
[bundle, bundleListingData, listedCourses, courses]
);
const productsIncludedInBundleTiles = React.useMemo(
const productsExceptCoursesIncludedInBundleTiles = React.useMemo(
() =>
getProductsIncludedInBundleTiles({
product: bundle,
productListingDatas: [
...(bundleListingDatas || []),
...(privateGameTemplateListingDatas || []),
...(privateAssetPackListingDatas || []),
...(listedCourses || []),
],
productListingData: bundleListingData,
receivedProducts: [
...(receivedBundles || []),
...(receivedGameTemplates || []),
...(receivedAssetPacks || []),
...(receivedCourses || []),
],
onPrivateAssetPackOpen: product =>
onAssetPackOpen(product, { forceProductPage: true }),
onPrivateGameTemplateOpen: onGameTemplateOpen,
onBundleOpen,
onCourseOpen,
}),
bundle && bundleListingData
? getProductsIncludedInBundleTiles({
product: bundle,
productListingDatas: [
...(bundleListingDatas || []),
...(privateGameTemplateListingDatas || []),
...(privateAssetPackListingDatas || []),
],
productListingData: bundleListingData,
receivedProducts: [
...(receivedBundles || []),
...(receivedGameTemplates || []),
...(receivedAssetPacks || []),
],
onPrivateAssetPackOpen: onAssetPackOpen,
onPrivateGameTemplateOpen: onGameTemplateOpen,
onBundleOpen,
onCourseOpen,
discountedPrice: true,
})
: null,
[
bundle,
bundleListingDatas,
privateGameTemplateListingDatas,
privateAssetPackListingDatas,
listedCourses,
receivedBundles,
receivedGameTemplates,
receivedAssetPacks,
receivedCourses,
bundleListingData,
onAssetPackOpen,
onGameTemplateOpen,
onBundleOpen,
onCourseOpen,
bundleListingData,
]
);
const bundlesContainingBundleTiles = React.useMemo(
() =>
getBundlesContainingProductTiles({
product: bundle,
productListingData: bundleListingData,
productListingDatas: bundleListingDatas,
receivedProducts: receivedBundles,
onPrivateAssetPackOpen: product =>
onAssetPackOpen(product, { forceProductPage: true }),
onPrivateGameTemplateOpen: onGameTemplateOpen,
onBundleOpen,
}),
[
bundle,
bundleListingData,
bundleListingDatas,
receivedBundles,
onAssetPackOpen,
onGameTemplateOpen,
onBundleOpen,
]
);
const subscriptionPlansWithPricingSystems = getSubscriptionPlansWithPricingSystems();
const otherBundlesFromTheSameAuthorTiles = React.useMemo(
() =>
getOtherProductsFromSameAuthorTiles({
otherProductListingDatasFromSameCreator: bundleListingDatasFromSameCreator,
currentProductListingData: bundleListingData,
receivedProducts: receivedBundles,
onProductOpen: onBundleOpen,
}),
[
bundleListingDatasFromSameCreator,
bundleListingData,
receivedBundles,
onBundleOpen,
]
const highestSubscriptionPlanIncludedInBundle = React.useMemo(
() => {
if (!bundleListingData) return null;
const sortedIncludedRedemptionCodes = (
bundleListingData.includedRedemptionCodes || []
).sort((a, b) =>
planIdSortingFunction(
a.givenSubscriptionPlanId,
b.givenSubscriptionPlanId
)
);
if (!sortedIncludedRedemptionCodes.length) return null;
const planId =
sortedIncludedRedemptionCodes[sortedIncludedRedemptionCodes.length - 1]
.givenSubscriptionPlanId;
return subscriptionPlansWithPricingSystems
? subscriptionPlansWithPricingSystems.find(
subscriptionPlanWithPricingSystems =>
subscriptionPlanWithPricingSystems.id === planId
)
: null;
},
[bundleListingData, subscriptionPlansWithPricingSystems]
);
React.useEffect(
() => {
(async () => {
setIsFetching(true);
try {
const [bundle, profile] = await Promise.all([
getBundle(id),
getUserPublicProfile(sellerId),
]);
const bundle = await getBundle(bundleListingData.id);
setBundle(bundle);
setSellerPublicProfile(profile);
} catch (error) {
const extractedStatusAndCode = extractGDevelopApiErrorStatusAndCode(
error
@@ -359,328 +246,149 @@ const BundleInformationPage = ({
<Trans>An error occurred, please try again later.</Trans>
);
}
} finally {
setIsFetching(false);
}
})();
},
[id, sellerId]
[bundleListingData.id]
);
const onClickBuy = React.useCallback(
async () => {
if (!bundle || isOwningAnotherVariant) return;
if (isAlreadyReceived) {
onBundleOpen(bundleListingData);
return;
}
const customSectionPaperStyle = {
// $FlowIgnore
...(noPadding
? {
padding: 0,
}
: {}),
...(bundleListingData.visibleUntil && !noPadding
? {
backgroundAttachment: 'local',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'top',
backgroundSize: isMobile && !isLandscape ? 'contain' : 'auto',
backgroundImage: `${
paletteType === 'dark'
? 'linear-gradient(180deg, #6B1A18 0px, #2D2331 5%, #1d1d2600 10%)'
: 'linear-gradient(180deg, #F03F18 0px, #f5f5f700 10%)'
}`,
}
: {}),
};
try {
const price = bundleListingData.prices.find(
price => price.usageType === 'default'
);
if (errorText) {
return (
<SectionContainer
flexBody
backAction={onBack}
customPaperStyle={customSectionPaperStyle}
>
<SectionRow expand>
<Line alignItems="center" justifyContent="center" expand>
<AlertMessage kind="error">{errorText}</AlertMessage>
</Line>
</SectionRow>
</SectionContainer>
);
}
sendBundleBuyClicked({
bundleId: bundle.id,
bundleName: bundle.name,
bundleTag: bundle.tag,
currency: price ? price.currency : undefined,
usageType: 'default',
});
setPurchasingBundleListingData(bundleListingData);
} catch (e) {
console.warn('Unable to send event', e);
}
},
[
bundle,
bundleListingData,
isAlreadyReceived,
isOwningAnotherVariant,
onBundleOpen,
]
);
const mediaItems = React.useMemo(
() =>
getProductMediaItems({
product: bundle,
productListingData: bundleListingData,
shouldSimulateAppStoreProduct: simulateAppStoreProduct,
additionalThumbnails: additionalProductThumbnailsIncludedInBundle,
}),
[
bundle,
bundleListingData,
simulateAppStoreProduct,
additionalProductThumbnailsIncludedInBundle,
]
);
const includedCreditsAmount = React.useMemo(
() =>
(bundleListingData.includedListableProducts || [])
.filter(product => product.productType === 'CREDIT_PACKAGE')
.reduce(
(total, product) => total + getCreditsAmountFromId(product.productId),
0
),
[bundleListingData]
);
const includedRedemptionCodes = React.useMemo(
() => bundleListingData.includedRedemptionCodes || [],
[bundleListingData]
);
if (!bundleListingData || !bundle) {
return (
<SectionContainer flexBody customPaperStyle={customSectionPaperStyle}>
<SectionRow expand>
<PlaceholderLoader />
</SectionRow>
</SectionContainer>
);
}
return (
<I18n>
{({ i18n }) => (
<>
{errorText ? (
<Line alignItems="center" justifyContent="center" expand>
<AlertMessage kind="error">{errorText}</AlertMessage>
</Line>
) : isFetching ? (
<Column expand alignItems="center" justifyContent="center">
<PlaceholderLoader />
</Column>
) : bundle && sellerPublicProfile ? (
<Column noOverflowParent expand noMargin>
<ScrollView autoHideScrollbar style={styles.scrollview}>
<ResponsiveLineStackLayout
noColumnMargin
noMargin
// Force the columns to wrap on tablets and small screens.
forceMobileLayout={isMediumScreen}
// Prevent it to wrap when in landscape mode on small screens.
noResponsiveLandscape
useLargeSpacer
<SectionContainer
backAction={onBack}
customPaperStyle={customSectionPaperStyle}
>
<BundlePageHeader
bundleListingData={bundleListingData}
bundle={bundle}
i18n={i18n}
/>
<Line noMargin>
<Text size="section-title">
<Trans>What's included:</Trans>
</Text>
</Line>
{courseAndTheirListingDataIncludedInBundle &&
courseAndTheirListingDataIncludedInBundle.length > 0 && (
<Line>
<GridList
cols={getColumns(windowSize, isLandscape)}
style={styles.grid}
cellHeight="auto"
spacing={cellSpacing}
>
<div
style={
isMobile
? styles.leftColumnContainerMobile
: styles.leftColumnContainer
}
>
<ResponsiveMediaGallery
mediaItems={mediaItems}
altTextTemplate={`Bundle ${name} preview image {mediaIndex}`}
horizontalOuterMarginToEatOnMobile={8}
/>
</div>
<div
style={
isMobile
? styles.rightColumnContainerMobile
: styles.rightColumnContainer
}
>
<ColumnStackLayout noMargin>
<LineStackLayout
noMargin
alignItems="center"
justifyContent="space-between"
>
<Text noMargin size="title">
{selectMessageByLocale(i18n, bundle.nameByLocale)}
</Text>
{isAlreadyReceived && (
<div
style={{
...styles.ownedTag,
backgroundColor:
gdevelopTheme.statusIndicator.success,
{courseAndTheirListingDataIncludedInBundle.map(
({ course, courseListingData }) => {
const completion = getCourseCompletion(course.id);
return (
<GridListTile key={course.id}>
<CourseCard
course={course}
courseListingData={courseListingData}
completion={completion}
onClick={() => {
onCourseOpen(courseListingData);
}}
>
<Text color="inherit" noMargin>
<Trans>OWNED</Trans>
</Text>
</div>
)}
</LineStackLayout>
<LineStackLayout noMargin alignItems="center">
<Avatar
src={sellerPublicProfile.iconUrl}
style={styles.avatar}
/>
<Text displayInlineAsSpan size="sub-title">
<Link
onClick={() =>
openUserPublicProfile({
userId: sellerPublicProfile.id,
callbacks: {
onAssetPackOpen,
onGameTemplateOpen,
},
})
}
href="#"
>
{sellerPublicProfile.username || ''}
</Link>
</Text>
</LineStackLayout>
<Spacer />
{isOwningAnotherVariant ? (
<AlertMessage kind="warning">
<Trans>
You own an older version of this bundle. Browse the
store to access it!
</Trans>
</AlertMessage>
) : !isAlreadyReceived ? (
<>
{!shouldUseOrSimulateAppStoreProduct && (
<SecureCheckout />
)}
{!errorText && (
<PurchaseProductButtons
i18n={i18n}
productListingData={bundleListingData}
selectedUsageType="default"
onUsageTypeChange={() => {}}
simulateAppStoreProduct={simulateAppStoreProduct}
isAlreadyReceived={isAlreadyReceived}
onClickBuy={onClickBuy}
onClickBuyWithCredits={() => {}}
/>
)}
</>
) : null}
<Text size="body2" displayInlineAsSpan>
<MarkdownText
source={selectMessageByLocale(
i18n,
bundle.longDescriptionByLocale
)}
allowParagraphs
/>
</Text>
{includedRedemptionCodes.length > 0 && (
<ColumnStackLayout noMargin>
{includedRedemptionCodes.map(
(includedRedemptionCode, index) => (
<LineStackLayout
noMargin
alignItems="center"
key={`${
includedRedemptionCode.givenSubscriptionPlanId
}-${index}`}
>
{getPlanIcon({
planId:
includedRedemptionCode.givenSubscriptionPlanId,
logoSize: 20,
})}
<Text>
<Trans>
{formatDurationOfRedemptionCode(
includedRedemptionCode.durationInDays
)}{' '}
of
{getPlanInferredNameFromId(
includedRedemptionCode.givenSubscriptionPlanId
)}
subscription included
</Trans>
</Text>
</LineStackLayout>
)
)}
{isAlreadyReceived && (
<Line noMargin>
<FlatButton
primary
label={<Trans>See my codes</Trans>}
onClick={() =>
setIsRedemptionCodesDialogOpen(true)
}
/>
</Line>
)}
</ColumnStackLayout>
)}
{includedCreditsAmount > 0 && (
<LineStackLayout noMargin alignItems="center">
<Coin style={styles.coinIcon} />
<Text>
<Trans>
{includedCreditsAmount} credits included
</Trans>
</Text>
</LineStackLayout>
)}
</ColumnStackLayout>
</div>
</ResponsiveLineStackLayout>
{bundlesContainingBundleTiles &&
bundlesContainingBundleTiles.length ? (
<>
<ColumnStackLayout noMargin>
<LargeSpacer />
{bundlesContainingBundleTiles}
<LargeSpacer />
</ColumnStackLayout>
</>
) : null}
{productsIncludedInBundleTiles && (
<>
<Line>
<Text size="block-title">
<Trans>Included in this bundle</Trans>
</Text>
</Line>
<Line>
<GridList
cols={getTemplateColumns(windowSize, isLandscape)}
cellHeight="auto"
spacing={cellSpacing}
style={styles.grid}
>
{productsIncludedInBundleTiles}
</GridList>
</Line>
</>
)}
{otherBundlesFromTheSameAuthorTiles &&
otherBundlesFromTheSameAuthorTiles.length > 0 && (
<>
<Line>
<Text size="block-title">
<Trans>Similar bundles</Trans>
</Text>
</Line>
<Line>
<GridList
cols={getTemplateColumns(windowSize, isLandscape)}
cellHeight="auto"
spacing={cellSpacing}
style={styles.grid}
>
{otherBundlesFromTheSameAuthorTiles}
</GridList>
</Line>
</>
discountedPrice
/>
</GridListTile>
);
}
)}
</ScrollView>
</Column>
) : null}
{!!purchasingBundleListingData && (
<BundlePurchaseDialog
bundleListingData={purchasingBundleListingData}
usageType="default"
onClose={() => setPurchasingBundleListingData(null)}
/>
</GridList>
</Line>
)}
{productsExceptCoursesIncludedInBundleTiles && (
<Line>
<GridList
cols={getColumns(windowSize, isLandscape)}
cellHeight="auto"
spacing={cellSpacing}
style={styles.grid}
>
{productsExceptCoursesIncludedInBundleTiles}
</GridList>
</Line>
)}
{isRedemptionCodesDialogOpen && (
<RedemptionCodesDialog
onClose={() => setIsRedemptionCodesDialogOpen(false)}
/>
{highestSubscriptionPlanIncludedInBundle && (
<ResponsiveLineStackLayout expand noColumnMargin>
<Column noMargin justifyContent="center">
<Line expand>
<SubscriptionPlanPricingSummary
subscriptionPlanWithPricingSystems={
highestSubscriptionPlanIncludedInBundle
}
disabled={false}
onClickChoosePlan={async () => {}}
seatsCount={0}
setSeatsCount={() => {}}
period={'month'}
setPeriod={() => {}}
onlyShowDiscountedPrice
/>
</Line>
</Column>
<Spacer />
<Column noMargin>
<SubscriptionPlanTableSummary
subscriptionPlanWithPricingSystems={
highestSubscriptionPlanIncludedInBundle
}
hideActions
/>
</Column>
</ResponsiveLineStackLayout>
)}
</>
</SectionContainer>
)}
</I18n>
);

View File

@@ -0,0 +1,517 @@
// @flow
import * as React from 'react';
import { Trans } from '@lingui/macro';
import { I18n } from '@lingui/react';
import { type I18n as I18nType } from '@lingui/core';
import { type Bundle } from '../../Utils/GDevelopServices/Asset';
import { type BundleListingData } from '../../Utils/GDevelopServices/Shop';
import Paper from '../../UI/Paper';
import Text from '../../UI/Text';
import { Column, Line } from '../../UI/Grid';
import {
ColumnStackLayout,
LineStackLayout,
ResponsiveLineStackLayout,
} from '../../UI/Layout';
import { useResponsiveWindowSize } from '../../UI/Responsive/ResponsiveWindowMeasurer';
import { selectMessageByLocale } from '../../Utils/i18n/MessageByLocale';
import { renderProductPrice } from '../../AssetStore/ProductPriceTag';
import {
getProductsIncludedInBundle,
getUserProductPurchaseUsageType,
PurchaseProductButtons,
} from '../../AssetStore/ProductPageHelper';
import { shouldUseAppStoreProduct } from '../../Utils/AppStorePurchases';
import AuthenticatedUserContext from '../../Profile/AuthenticatedUserContext';
import { BundleStoreContext } from '../../AssetStore/Bundles/BundleStoreContext';
import { sendBundleBuyClicked } from '../../Utils/Analytics/EventSender';
import BundlePurchaseDialog from '../../AssetStore/Bundles/BundlePurchaseDialog';
import RedemptionCodesDialog from '../../RedemptionCode/RedemptionCodesDialog';
import {
getEstimatedSavingsFormatted,
renderEstimatedTotalPriceFormatted,
} from '../../AssetStore/Bundles/Utils';
import { PrivateGameTemplateStoreContext } from '../../AssetStore/PrivateGameTemplates/PrivateGameTemplateStoreContext';
import { CreditsPackageStoreContext } from '../../AssetStore/CreditsPackages/CreditsPackageStoreContext';
import { AssetStoreContext } from '../../AssetStore/AssetStoreContext';
import CourseStoreContext from '../../Course/CourseStoreContext';
import SecureCheckout from '../../AssetStore/SecureCheckout/SecureCheckout';
import FlatButton from '../../UI/FlatButton';
import Chip from '../../UI/Chip';
import ProductLimitedTimeOffer from '../../AssetStore/ProductLimitedTimeOffer';
import Skeleton from '@material-ui/lab/Skeleton';
import { getSummaryLines } from './Utils';
import { SectionRow } from '../../MainFrame/EditorContainers/HomePage/SectionContainer';
const styles = {
title: { overflowWrap: 'anywhere', textWrap: 'wrap' },
image: { width: 300, aspectRatio: '16 / 9' },
imageContainer: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
position: 'relative',
borderRadius: 8,
overflow: 'hidden',
},
discountedPrice: { textDecoration: 'line-through', opacity: 0.7 },
discountChip: {
height: 24,
backgroundColor: '#F03F18',
color: 'white',
},
};
type Props = {|
bundleListingData: BundleListingData,
bundle: Bundle,
simulateAppStoreProduct?: boolean,
i18n: I18nType,
|};
const BundlePageHeader = ({
bundle,
bundleListingData,
simulateAppStoreProduct,
i18n,
}: Props) => {
const { privateGameTemplateListingDatas } = React.useContext(
PrivateGameTemplateStoreContext
);
const { creditsPackageListingDatas } = React.useContext(
CreditsPackageStoreContext
);
const { bundleListingDatas } = React.useContext(BundleStoreContext);
const { privateAssetPackListingDatas } = React.useContext(AssetStoreContext);
const { listedCourses } = React.useContext(CourseStoreContext);
const authenticatedUser = React.useContext(AuthenticatedUserContext);
const { receivedBundles, bundlePurchases } = authenticatedUser;
const [
purchasingBundleListingData,
setPurchasingBundleListingData,
] = React.useState<?BundleListingData>(null);
const { isMobile, isMediumScreen } = useResponsiveWindowSize();
const isMobileOrMediumScreen = isMobile || isMediumScreen;
const [
isRedemptionCodesDialogOpen,
setIsRedemptionCodesDialogOpen,
] = React.useState<boolean>(false);
const shouldUseOrSimulateAppStoreProduct =
shouldUseAppStoreProduct() || simulateAppStoreProduct;
const userBundlePurchaseUsageType = React.useMemo(
() =>
getUserProductPurchaseUsageType({
productId: bundleListingData ? bundleListingData.id : null,
receivedProducts: receivedBundles,
productPurchases: bundlePurchases,
allProductListingDatas: bundleListingDatas,
}),
[bundlePurchases, bundleListingData, bundleListingDatas, receivedBundles]
);
const isAlreadyReceived = !!userBundlePurchaseUsageType;
const productListingDatasIncludedInBundle = React.useMemo(
() =>
bundleListingData &&
bundleListingDatas &&
privateGameTemplateListingDatas &&
privateAssetPackListingDatas &&
listedCourses &&
creditsPackageListingDatas
? getProductsIncludedInBundle({
productListingDatas: [
...bundleListingDatas,
...privateGameTemplateListingDatas,
...privateAssetPackListingDatas,
...listedCourses,
...creditsPackageListingDatas,
],
productListingData: bundleListingData,
})
: null,
[
bundleListingData,
bundleListingDatas,
privateGameTemplateListingDatas,
privateAssetPackListingDatas,
listedCourses,
creditsPackageListingDatas,
]
);
const redemptionCodesIncludedInBundle = React.useMemo(
() =>
bundleListingData
? bundleListingData.includedRedemptionCodes || []
: null,
[bundleListingData]
);
const summaryLines = React.useMemo(
() => {
if (
!productListingDatasIncludedInBundle ||
!redemptionCodesIncludedInBundle ||
!bundleListingData
)
return isMobile ? (
<ColumnStackLayout noMargin>
<Column expand noMargin>
<Skeleton height={25} />
<Skeleton height={20} />
<Skeleton height={20} />
</Column>
<Column expand noMargin>
<Skeleton height={25} />
<Skeleton height={20} />
<Skeleton height={20} />
</Column>
</ColumnStackLayout>
) : (
<Column expand noMargin>
<Skeleton height={25} />
<Skeleton height={20} />
<Skeleton height={20} />
</Column>
);
if (isAlreadyReceived) {
return (
<Line noMargin>
<FlatButton
primary
label={<Trans>See my subscription codes</Trans>}
onClick={() => setIsRedemptionCodesDialogOpen(true)}
/>
</Line>
);
}
const summaryLines = getSummaryLines({
redemptionCodesIncludedInBundle,
bundleListingData,
productListingDatasIncludedInBundle,
});
if (isMobile) {
return summaryLines.mobileLines;
}
return summaryLines.desktopLines;
},
[
isAlreadyReceived,
redemptionCodesIncludedInBundle,
bundleListingData,
productListingDatasIncludedInBundle,
isMobile,
]
);
const estimatedTotalPriceFormatted = React.useMemo(
() =>
renderEstimatedTotalPriceFormatted({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
}),
[
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
]
);
const estimatedSavingsFormatted = React.useMemo(
() =>
getEstimatedSavingsFormatted({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
}),
[
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
]
);
const productPrice = React.useMemo(
() =>
renderProductPrice({
i18n,
productListingData: bundleListingData,
usageType: 'default',
plainText: true,
}),
[i18n, bundleListingData]
);
const onClickBuy = React.useCallback(
async () => {
if (!bundle) return;
if (isAlreadyReceived) {
return;
}
try {
const price = bundleListingData.prices.find(
price => price.usageType === 'default'
);
sendBundleBuyClicked({
bundleId: bundle.id,
bundleName: bundle.name,
bundleTag: bundle.tag,
currency: price ? price.currency : undefined,
usageType: 'default',
});
setPurchasingBundleListingData(bundleListingData);
} catch (e) {
console.warn('Unable to send event', e);
}
},
[bundle, bundleListingData, isAlreadyReceived]
);
return (
<I18n>
{({ i18n }) => (
<Column noOverflowParent noMargin>
{!isAlreadyReceived && !isMobileOrMediumScreen && (
<SectionRow>
<Paper background="medium" style={{ padding: 16 }}>
{!!bundleListingData && (
<LineStackLayout noMargin justifyContent="space-between">
{bundleListingData.visibleUntil ? (
<ProductLimitedTimeOffer
visibleUntil={bundleListingData.visibleUntil}
/>
) : estimatedSavingsFormatted ? (
<Column
noMargin
alignItems="flex-start"
justifyContent="center"
>
<Chip
label={<Trans>Bundle</Trans>}
style={styles.discountChip}
/>
<Text color="secondary">
<Trans>
Get{' '}
{estimatedSavingsFormatted.savingsPriceFormatted}{' '}
worth of value for less!
</Trans>
</Text>
</Column>
) : (
<Skeleton height={24} width={100} />
)}
{estimatedTotalPriceFormatted &&
estimatedSavingsFormatted &&
productPrice ? (
<LineStackLayout justifyContent="flex-end" noMargin>
<Column noMargin alignItems="flex-end">
<LineStackLayout>
<Text noMargin color="secondary" size="block-title">
<span style={styles.discountedPrice}>
{estimatedTotalPriceFormatted}
</span>
</Text>
{bundleListingData.visibleUntil && (
<Chip
label={
<Trans>
{
estimatedSavingsFormatted.savingsPercentageFormatted
}{' '}
OFF
</Trans>
}
style={styles.discountChip}
/>
)}
</LineStackLayout>
<Text noMargin size="block-title">
{productPrice}
</Text>
</Column>
<ColumnStackLayout noMargin alignItems="center">
<PurchaseProductButtons
i18n={i18n}
productListingData={bundleListingData}
selectedUsageType="default"
onUsageTypeChange={() => {}}
simulateAppStoreProduct={simulateAppStoreProduct}
isAlreadyReceived={isAlreadyReceived}
onClickBuy={onClickBuy}
onClickBuyWithCredits={() => {}}
customLabel={
<Trans>
Buy now and save{' '}
{
estimatedSavingsFormatted.savingsPriceFormatted
}
</Trans>
}
/>
{!shouldUseOrSimulateAppStoreProduct && (
<SecureCheckout />
)}
</ColumnStackLayout>
</LineStackLayout>
) : (
<Column noMargin justifyContent="flex-end">
<Skeleton height={24} width={100} />
<Skeleton height={24} width={100} />
</Column>
)}
</LineStackLayout>
)}
</Paper>
</SectionRow>
)}
{!isAlreadyReceived &&
isMobileOrMediumScreen &&
bundleListingData &&
bundleListingData.visibleUntil && (
<SectionRow>
<ProductLimitedTimeOffer
visibleUntil={bundleListingData.visibleUntil}
/>
</SectionRow>
)}
<SectionRow>
<ResponsiveLineStackLayout
noMargin
alignItems="center"
justifyContent="flex-start"
forceMobileLayout={isMediumScreen}
expand
>
<div style={styles.imageContainer}>
<img
src={bundle.previewImageUrls[0]}
style={styles.image}
alt=""
/>
</div>
<ColumnStackLayout
expand
justifyContent="flex-start"
noMargin={isMobile}
>
<Text size="title" noMargin style={styles.title}>
{selectMessageByLocale(i18n, bundle.nameByLocale)}
</Text>
<Line noMargin>
<Text noMargin>
{selectMessageByLocale(
i18n,
bundle.longDescriptionByLocale
)}
</Text>
</Line>
{summaryLines}
</ColumnStackLayout>
</ResponsiveLineStackLayout>
</SectionRow>
{!isAlreadyReceived && isMobileOrMediumScreen && bundleListingData && (
<SectionRow>
<Paper background="medium" style={{ padding: 16 }}>
{estimatedTotalPriceFormatted &&
estimatedSavingsFormatted &&
productPrice ? (
<ResponsiveLineStackLayout justifyContent="flex-end" noMargin>
<LineStackLayout
alignItems="center"
justifyContent="center"
>
{bundleListingData.visibleUntil && (
<Chip
label={
<Trans>
{
estimatedSavingsFormatted.savingsPercentageFormatted
}{' '}
OFF
</Trans>
}
style={styles.discountChip}
/>
)}
<Text noMargin color="secondary" size="block-title">
<span style={styles.discountedPrice}>
{estimatedTotalPriceFormatted}
</span>
</Text>
<Text noMargin size="block-title">
{productPrice}
</Text>
</LineStackLayout>
<ColumnStackLayout noMargin alignItems="center">
<PurchaseProductButtons
i18n={i18n}
productListingData={bundleListingData}
selectedUsageType="default"
onUsageTypeChange={() => {}}
simulateAppStoreProduct={simulateAppStoreProduct}
isAlreadyReceived={isAlreadyReceived}
onClickBuy={onClickBuy}
onClickBuyWithCredits={() => {}}
customLabel={
<Trans>
Buy now and save{' '}
{
(
getEstimatedSavingsFormatted({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
}) || {}
).savingsPriceFormatted
}
</Trans>
}
/>
{!shouldUseOrSimulateAppStoreProduct && (
<SecureCheckout />
)}
</ColumnStackLayout>
</ResponsiveLineStackLayout>
) : (
<Column noMargin expand justifyContent="flex-end">
<Skeleton height={isMobile ? 60 : 40} />
<Skeleton height={isMobile ? 60 : 40} />
</Column>
)}
</Paper>
</SectionRow>
)}
{!!purchasingBundleListingData && (
<BundlePurchaseDialog
bundleListingData={purchasingBundleListingData}
usageType="default"
onClose={() => setPurchasingBundleListingData(null)}
/>
)}
{isRedemptionCodesDialogOpen && (
<RedemptionCodesDialog
onClose={() => setIsRedemptionCodesDialogOpen(false)}
/>
)}
</Column>
)}
</I18n>
);
};
export default BundlePageHeader;

View File

@@ -2,6 +2,7 @@
import * as React from 'react';
import { I18n } from '@lingui/react';
import { type I18n as I18nType } from '@lingui/core';
import { Trans } from '@lingui/macro';
import Divider from '@material-ui/core/Divider';
import {
@@ -48,8 +49,12 @@ import Hammer from '../../UI/CustomSvgIcons/Hammer';
import School from '../../UI/CustomSvgIcons/School';
import Coin from '../../Credits/Icons/Coin';
import Sparkle from '../../UI/CustomSvgIcons/Sparkle';
import { renderEstimatedTotalPriceFormatted } from './Utils';
import {
getEstimatedSavingsFormatted,
renderEstimatedTotalPriceFormatted,
} from './Utils';
import { formatDurationOfRedemptionCode } from '../../RedemptionCode/Utils';
import ProductLimitedTimeOffer from '../ProductLimitedTimeOffer';
const highlightColor = '#6CF9F7';
@@ -62,7 +67,7 @@ const styles = {
display: 'flex',
flex: 1,
flexDirection: 'column',
gap: 8,
gap: 16,
justifyContent: 'space-between',
},
bundlePreviewContainer: {
@@ -254,9 +259,11 @@ const getColumnsFromWindowSize = (windowSize: WindowSizeType) => {
type Props = {|
onDisplayBundle: (bundleListingData: BundleListingData) => void,
i18n: I18nType,
category: string,
|};
const BundlePreviewBanner = ({ onDisplayBundle }: Props) => {
const BundlePreviewBanner = ({ onDisplayBundle, i18n, category }: Props) => {
const { isMobile, isLandscape, windowSize } = useResponsiveWindowSize();
const numberOfTilesToDisplay = getColumnsFromWindowSize(windowSize) - 1; // Reserve one tile for the bundle preview.
const { privateGameTemplateListingDatas } = React.useContext(
@@ -272,28 +279,34 @@ const BundlePreviewBanner = ({ onDisplayBundle }: Props) => {
const { bundlePurchases, receivedBundles } = authenticatedUser;
// For the moment, we either display:
// - the first bundle in the list if none are owned.
// - the first owned bundle (as a listing data if still listed, or as an archived listing data otherwise)
// TODO: improve that logic when we'll have more bundles.
// - the first bundle of that category if none are owned.
// - the first owned bundle of that category (as a listing data if still listed, or as an archived listing data otherwise)
const bundleListingData: BundleListingData | null = React.useMemo(
() => {
if (!bundleListingDatas || !receivedBundles) return null;
if (receivedBundles.length === 0) {
return bundleListingDatas[0]; // Display the first bundle if none are owned.
const bundleListingDataOfCategory = bundleListingDatas.filter(bundle =>
bundle.categories.includes(category)
)[0];
const receivedBundleOfCategory = receivedBundles.filter(bundle =>
bundle.categories.includes(category)
)[0];
if (!receivedBundleOfCategory) {
// Display the first bundle if none are found with that category.
return bundleListingDataOfCategory || bundleListingDatas[0];
}
const receivedBundle = receivedBundles[0];
const bundleListingData = bundleListingDatas.find(
bundleListingData => bundleListingData.id === receivedBundle.id
const bundleListingDataMatchingOwnedBundle = bundleListingDatas.find(
bundleListingData =>
bundleListingData.id === receivedBundleOfCategory.id
);
if (bundleListingData) {
return bundleListingData; // Display the first owned bundle that is still listed.
}
// If this bundle is not listed anymore, get an archived listing data for that bundle.
return getArchivedBundleListingData({
bundle: receivedBundle,
});
return (
bundleListingDataMatchingOwnedBundle ||
getArchivedBundleListingData({
bundle: receivedBundleOfCategory,
})
);
},
[bundleListingDatas, receivedBundles]
[bundleListingDatas, receivedBundles, category]
);
const userBundlePurchaseUsageType = React.useMemo(
@@ -342,6 +355,51 @@ const BundlePreviewBanner = ({ onDisplayBundle }: Props) => {
[bundleListingData]
);
const estimatedTotalPriceFormatted = React.useMemo(
() =>
renderEstimatedTotalPriceFormatted({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
}),
[
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
]
);
const estimatedSavingsFormatted = React.useMemo(
() =>
getEstimatedSavingsFormatted({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
}),
[
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
]
);
const productPrice = React.useMemo(
() =>
bundleListingData
? renderProductPrice({
i18n,
productListingData: bundleListingData,
usageType: 'default',
plainText: true,
})
: null,
[i18n, bundleListingData]
);
const courseTiles = React.useMemo(
() => {
if (isMobile && !isLandscape) {
@@ -433,27 +491,6 @@ const BundlePreviewBanner = ({ onDisplayBundle }: Props) => {
}}
>
<ColumnStackLayout noMargin>
<Line noMargin>
{bundleListingData ? (
<Chip
label={
isAlreadyReceived ? (
<Trans>Owned</Trans>
) : (
<Trans>Discount</Trans>
)
}
style={
isAlreadyReceived
? styles.ownedChip
: styles.discountChip
}
/>
) : (
<Skeleton variant="rect" height={20} />
)}
</Line>
<Spacer />
{bundleListingData ? (
<Text noMargin size="block-title">
{bundleListingData.nameByLocale
@@ -478,20 +515,74 @@ const BundlePreviewBanner = ({ onDisplayBundle }: Props) => {
) : (
<Skeleton height={30} />
)}
{isMobile && (
<BundlePreviewTile bundleListingData={bundleListingData} />
)}
</ColumnStackLayout>
{bundleListingData ? (
<ColumnStackLayout noMargin>
{!isAlreadyReceived && (
<Text noMargin color="secondary">
<span style={styles.discountedPrice}>
{renderEstimatedTotalPriceFormatted({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
})}
</span>
</Text>
{estimatedSavingsFormatted &&
estimatedTotalPriceFormatted &&
productPrice !== null ? (
<LineStackLayout
alignItems="center"
justifyContent={
bundleListingData.visibleUntil && !isMobile
? 'flex-start'
: 'space-between'
}
noMargin
>
<LineStackLayout noMargin alignItems="center">
{!isAlreadyReceived && estimatedTotalPriceFormatted && (
<Text noMargin color="secondary" size="sub-title">
<span style={styles.discountedPrice}>
{estimatedTotalPriceFormatted}
</span>
</Text>
)}
{(isAlreadyReceived ||
!bundleListingData.visibleUntil) && (
<Chip
label={
isAlreadyReceived ? (
<Trans>Owned</Trans>
) : (
<Trans>
{
estimatedSavingsFormatted.savingsPercentageFormatted
}{' '}
OFF
</Trans>
)
}
style={
isAlreadyReceived
? styles.ownedChip
: styles.discountChip
}
/>
)}
</LineStackLayout>
{!isAlreadyReceived && (
<Text noMargin size="block-title">
{productPrice}
</Text>
)}
</LineStackLayout>
) : (
<Skeleton variant="rect" height={20} />
)}
{!isAlreadyReceived && bundleListingData.visibleUntil && (
<Line noMargin expand>
<Column noMargin expand>
<ProductLimitedTimeOffer
visibleUntil={bundleListingData.visibleUntil}
hideMinutesAndSeconds
alignCenter
/>
</Column>
</Line>
)}
<RaisedButton
primary
@@ -499,15 +590,7 @@ const BundlePreviewBanner = ({ onDisplayBundle }: Props) => {
isAlreadyReceived ? (
<Trans>Browse bundle</Trans>
) : (
<Trans>
Buy for{' '}
{renderProductPrice({
i18n,
productListingData: bundleListingData,
usageType: 'default',
plainText: true,
})}
</Trans>
<Trans>Discover this bundle</Trans>
)
}
onClick={() => onDisplayBundle(bundleListingData)}
@@ -520,7 +603,9 @@ const BundlePreviewBanner = ({ onDisplayBundle }: Props) => {
)}
</div>
{courseTiles}
<BundlePreviewTile bundleListingData={bundleListingData} />
{!isMobile && (
<BundlePreviewTile bundleListingData={bundleListingData} />
)}
</ResponsiveLineStackLayout>
</Column>
</Paper>

View File

@@ -8,12 +8,263 @@ import {
type CreditsPackageListingData,
type IncludedRedemptionCode,
} from '../../Utils/GDevelopServices/Shop';
import { renderPriceFormatted } from '../ProductPriceTag';
import * as React from 'react';
import { Trans } from '@lingui/macro';
import { I18n } from '@lingui/react';
import Text from '../../UI/Text';
import { Column, Line, Spacer } from '../../UI/Grid';
import { LineStackLayout, ResponsiveLineStackLayout } from '../../UI/Layout';
import {
getPlanIcon,
getPlanInferredNameFromId,
} from '../../Profile/Subscription/PlanCard';
import Coin from '../../Credits/Icons/Coin';
import { formatDurationOfRedemptionCode } from '../../RedemptionCode/Utils';
import School from '../../UI/CustomSvgIcons/School';
import Hammer from '../../UI/CustomSvgIcons/Hammer';
import Store from '../../UI/CustomSvgIcons/Store';
import { Divider } from '@material-ui/core';
import { getCreditsAmountFromId } from '../../AssetStore/CreditsPackages/CreditsPackageStoreContext';
const styles = {
discountedPrice: { textDecoration: 'line-through', opacity: 0.7 },
coinIcon: {
width: 13,
height: 13,
position: 'relative',
top: -1,
},
};
const getEstimatedRedemptionCodePrice = (
redemptionCode: IncludedRedemptionCode,
currencyCode: 'USD' | 'EUR'
): number => {
const planId = redemptionCode.givenSubscriptionPlanId;
if (!planId) {
return 0;
}
let estimatedAmountInCents = null;
if (redemptionCode.estimatedPrices) {
const estimatedPrice = redemptionCode.estimatedPrices.find(
price => price.currency === currencyCode
);
if (estimatedPrice) {
estimatedAmountInCents = estimatedPrice.value;
}
}
// If no estimated price is provided, guess a mostly correct value
// for backward compatibility.
if (estimatedAmountInCents === null) {
const monthlyEstimatedAmountInCents =
planId === 'gdevelop_silver'
? 599
: planId === 'gdevelop_gold'
? 1099
: planId === 'gdevelop_startup'
? 3499
: 0;
estimatedAmountInCents =
monthlyEstimatedAmountInCents *
Math.max(1, Math.round(redemptionCode.durationInDays / 30));
}
return estimatedAmountInCents;
};
export const renderEstimatedRedemptionCodePriceFormatted = (
bundleListingData: BundleListingData,
redemptionCode: IncludedRedemptionCode,
i18n: I18nType
): string => {
const bundlePrice = bundleListingData.prices.find(
price => price.usageType === 'default'
);
const currencyCode = bundlePrice ? bundlePrice.currency : 'USD';
const estimatedPrice = getEstimatedRedemptionCodePrice(
redemptionCode,
currencyCode
);
return renderPriceFormatted(estimatedPrice, currencyCode, i18n);
};
const getEstimatedTotalPriceAndCurrencyCode = ({
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
filter,
}: {
bundleListingData: ?BundleListingData,
productListingDatasIncludedInBundle: ?Array<
| PrivateAssetPackListingData
| PrivateGameTemplateListingData
| BundleListingData
| CourseListingData
| CreditsPackageListingData
>,
redemptionCodesIncludedInBundle: ?Array<IncludedRedemptionCode>,
filter?:
| 'ASSET_PACK'
| 'GAME_TEMPLATE'
| 'COURSE'
| 'BUNDLE'
| 'CREDITS_PACKAGE'
| 'REDEMPTION_CODE',
}): ?{
totalPrice: number,
bundlePrice: number,
currencyCode: 'USD' | 'EUR',
} => {
let totalPrice = 0;
if (
!bundleListingData ||
!productListingDatasIncludedInBundle ||
!redemptionCodesIncludedInBundle
)
return null;
const productPrices = bundleListingData.prices;
const bundlePrice = productPrices.find(
price => price.usageType === 'default'
);
const currencyCode = bundlePrice ? bundlePrice.currency : 'USD';
const bundlePriceValue = bundlePrice ? bundlePrice.value : 0;
for (const product of bundleListingData.includedListableProducts || []) {
if (
product.productType === 'ASSET_PACK' &&
(!filter || filter === 'ASSET_PACK')
) {
const listedAssetPack =
productListingDatasIncludedInBundle.find(
assetPack => assetPack.id === product.productId
) || null;
if (listedAssetPack) {
const price = listedAssetPack.prices.find(
price => price.usageType === product.usageType
);
totalPrice += price ? price.value : 0;
}
} else if (
product.productType === 'GAME_TEMPLATE' &&
(!filter || filter === 'GAME_TEMPLATE')
) {
const listedGameTemplate =
productListingDatasIncludedInBundle.find(
gameTemplate => gameTemplate.id === product.productId
) || null;
if (listedGameTemplate) {
const price = listedGameTemplate.prices.find(
price => price.usageType === product.usageType
);
totalPrice += price ? price.value : 0;
}
} else if (
product.productType === 'COURSE' &&
(!filter || filter === 'COURSE')
) {
const listedCourse = productListingDatasIncludedInBundle.find(
course => course.id === product.productId
);
if (listedCourse) {
const price = listedCourse.prices.find(
price => price.usageType === product.usageType
);
totalPrice += price ? price.value : 0;
}
} else if (
product.productType === 'BUNDLE' &&
(!filter || filter === 'BUNDLE')
) {
const listedBundle = productListingDatasIncludedInBundle.find(
bundle => bundle.id === product.productId
);
if (listedBundle) {
const price = listedBundle.prices.find(
price => price.usageType === product.usageType
);
totalPrice += price ? price.value : 0;
}
} else if (
product.productType === 'CREDITS_PACKAGE' &&
(!filter || filter === 'CREDITS_PACKAGE')
) {
const listedCreditsPackage =
productListingDatasIncludedInBundle.find(
creditsPackage => creditsPackage.id === product.productId
) || null;
if (listedCreditsPackage) {
const price = listedCreditsPackage.prices.find(
price => price.usageType === product.usageType
);
totalPrice += price ? price.value : 0;
}
}
}
if (
redemptionCodesIncludedInBundle.length > 0 &&
(!filter || filter === 'REDEMPTION_CODE')
) {
for (const redemptionCode of redemptionCodesIncludedInBundle) {
const estimatedAmountInCents = getEstimatedRedemptionCodePrice(
redemptionCode,
currencyCode
);
totalPrice += estimatedAmountInCents || 0;
}
}
return { totalPrice, bundlePrice: bundlePriceValue, currencyCode };
};
export const renderEstimatedTotalPriceFormatted = ({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
filter,
}: {|
i18n: I18nType,
bundleListingData: ?BundleListingData,
productListingDatasIncludedInBundle: ?Array<
| PrivateAssetPackListingData
| PrivateGameTemplateListingData
| BundleListingData
| CourseListingData
| CreditsPackageListingData
>,
redemptionCodesIncludedInBundle: ?Array<IncludedRedemptionCode>,
filter?:
| 'ASSET_PACK'
| 'GAME_TEMPLATE'
| 'COURSE'
| 'BUNDLE'
| 'CREDITS_PACKAGE'
| 'REDEMPTION_CODE',
|}): ?string => {
const estimatedPriceAndCode = getEstimatedTotalPriceAndCurrencyCode({
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
filter,
});
if (!estimatedPriceAndCode || !bundleListingData) return null;
return renderPriceFormatted(
estimatedPriceAndCode.totalPrice,
estimatedPriceAndCode.currencyCode,
i18n
);
};
export const getEstimatedSavingsFormatted = ({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
}: {
i18n: I18nType,
bundleListingData: ?BundleListingData,
@@ -25,118 +276,450 @@ export const renderEstimatedTotalPriceFormatted = ({
| CreditsPackageListingData
>,
redemptionCodesIncludedInBundle: ?Array<IncludedRedemptionCode>,
}): ?string => {
let totalPrice = 0;
if (
!bundleListingData ||
!productListingDatasIncludedInBundle ||
!redemptionCodesIncludedInBundle
)
return null;
}): ?{ savingsPriceFormatted: string, savingsPercentageFormatted: string } => {
const estimatedTotalPriceAndCode = getEstimatedTotalPriceAndCurrencyCode({
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
});
if (!estimatedTotalPriceAndCode || !bundleListingData) return null;
const productPrices = bundleListingData.prices;
const bundlePrice = productPrices.find(
price => price.usageType === 'default'
);
const currencyCode = bundlePrice ? bundlePrice.currency : 'USD';
const currencySymbol = currencyCode === 'USD' ? '$' : '€';
const savings =
estimatedTotalPriceAndCode.totalPrice -
estimatedTotalPriceAndCode.bundlePrice;
for (const product of bundleListingData.includedListableProducts || []) {
if (product.productType === 'ASSET_PACK') {
const listedAssetPack =
productListingDatasIncludedInBundle.find(
assetPack => assetPack.id === product.productId
) || null;
if (listedAssetPack) {
const price = listedAssetPack.prices.find(
price => price.usageType === product.usageType
);
totalPrice += price ? price.value : 0;
}
} else if (product.productType === 'GAME_TEMPLATE') {
const listedGameTemplate =
productListingDatasIncludedInBundle.find(
gameTemplate => gameTemplate.id === product.productId
) || null;
if (listedGameTemplate) {
const price = listedGameTemplate.prices.find(
price => price.usageType === product.usageType
);
totalPrice += price ? price.value : 0;
}
} else if (product.productType === 'COURSE') {
const listedCourse = productListingDatasIncludedInBundle.find(
course => course.id === product.productId
);
if (listedCourse) {
const price = listedCourse.prices.find(
price => price.usageType === product.usageType
);
totalPrice += price ? price.value : 0;
}
} else if (product.productType === 'BUNDLE') {
const listedBundle = productListingDatasIncludedInBundle.find(
bundle => bundle.id === product.productId
);
if (listedBundle) {
const price = listedBundle.prices.find(
price => price.usageType === product.usageType
);
totalPrice += price ? price.value : 0;
}
} else if (product.productType === 'CREDITS_PACKAGE') {
const listedCreditsPackage =
productListingDatasIncludedInBundle.find(
creditsPackage => creditsPackage.id === product.productId
) || null;
if (listedCreditsPackage) {
const price = listedCreditsPackage.prices.find(
price => price.usageType === product.usageType
);
totalPrice += price ? price.value : 0;
}
}
}
if (redemptionCodesIncludedInBundle.length > 0) {
for (const redemptionCode of redemptionCodesIncludedInBundle) {
const planId = redemptionCode.givenSubscriptionPlanId;
if (planId) {
let estimatedAmountInCents = null;
if (redemptionCode.estimatedPrices) {
const estimatedPrice = redemptionCode.estimatedPrices.find(
price => price.currency === currencyCode
);
if (estimatedPrice) {
estimatedAmountInCents = estimatedPrice.value;
}
}
// If no estimated price is provided, guess a mostly correct value
// for backward compatibility.
if (estimatedAmountInCents === null) {
const monthlyEstimatedAmountInCents =
planId === 'gdevelop_silver'
? 599
: planId === 'gdevelop_gold'
? 1099
: planId === 'gdevelop_startup'
? 3499
: 0;
estimatedAmountInCents =
monthlyEstimatedAmountInCents *
Math.max(1, Math.round(redemptionCode.durationInDays / 30));
}
totalPrice += estimatedAmountInCents || 0;
}
}
}
return `${currencySymbol} ${i18n
.number(totalPrice / 100, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
.replace(/\D00$/, '')}`;
return {
savingsPriceFormatted: renderPriceFormatted(
savings,
estimatedTotalPriceAndCode.currencyCode,
i18n
),
savingsPercentageFormatted: `${Math.round(
(savings / estimatedTotalPriceAndCode.totalPrice) * 100
)}%`,
};
};
const getCoursesEstimatedHoursToComplete = (
courseListingDatas: CourseListingData[]
) => {
// Ideally we'd look at the Course durationInWeeks, but to avoid too
// many API calls, we just estimate.
const totalHours = courseListingDatas.reduce((acc, course) => {
const estimatedHours = 4 * 5; // Estimate 4h per day, 5 days a week.
return acc + Math.round(estimatedHours);
}, 0);
return Math.round(totalHours);
};
const CoursesLineSummary = ({
courseListingDatasIncludedInBundle,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
}: {|
courseListingDatasIncludedInBundle: CourseListingData[],
bundleListingData: BundleListingData,
productListingDatasIncludedInBundle: (
| PrivateAssetPackListingData
| PrivateGameTemplateListingData
| BundleListingData
| CreditsPackageListingData
| CourseListingData
)[],
redemptionCodesIncludedInBundle: IncludedRedemptionCode[],
|}) => (
<I18n>
{({ i18n }) => (
<LineStackLayout noMargin alignItems="flex-start">
<School />
<Column noMargin>
<Text noMargin size="sub-title">
<Trans>
{courseListingDatasIncludedInBundle.length === 1 ? (
<Trans>
{courseListingDatasIncludedInBundle.length} Course
</Trans>
) : (
<Trans>
{courseListingDatasIncludedInBundle.length} Courses
</Trans>
)}
</Trans>
</Text>
<Text color="secondary" noMargin>
<Trans>
{getCoursesEstimatedHoursToComplete(
courseListingDatasIncludedInBundle
)}{' '}
hours of material
</Trans>
</Text>
<Text color="secondary" noMargin>
<span style={styles.discountedPrice}>
{renderEstimatedTotalPriceFormatted({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
filter: 'COURSE',
})}
</span>
</Text>
</Column>
</LineStackLayout>
)}
</I18n>
);
const AssetPacksLineSummary = ({
assetPackListingDatasIncludedInBundle,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
}: {|
assetPackListingDatasIncludedInBundle: PrivateAssetPackListingData[],
bundleListingData: BundleListingData,
productListingDatasIncludedInBundle: (
| PrivateAssetPackListingData
| PrivateGameTemplateListingData
| BundleListingData
| CreditsPackageListingData
| CourseListingData
)[],
redemptionCodesIncludedInBundle: IncludedRedemptionCode[],
|}) => (
<I18n>
{({ i18n }) => (
<LineStackLayout noMargin alignItems="flex-start">
<Store />
<Column noMargin>
<Text noMargin size="sub-title">
<Trans>
{assetPackListingDatasIncludedInBundle.length === 1 ? (
<Trans>
{assetPackListingDatasIncludedInBundle.length} Asset pack
</Trans>
) : (
<Trans>
{assetPackListingDatasIncludedInBundle.length} Asset packs
</Trans>
)}
</Trans>
</Text>
<Text color="secondary" noMargin>
<Trans>Commercial License</Trans>
</Text>
<Text color="secondary" noMargin>
<span style={styles.discountedPrice}>
{renderEstimatedTotalPriceFormatted({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
filter: 'ASSET_PACK',
})}
</span>
</Text>
</Column>
</LineStackLayout>
)}
</I18n>
);
const GameTemplatesLineSummary = ({
gameTemplateListingDatasIncludedInBundle,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
}: {|
gameTemplateListingDatasIncludedInBundle: PrivateGameTemplateListingData[],
bundleListingData: BundleListingData,
productListingDatasIncludedInBundle: (
| PrivateAssetPackListingData
| PrivateGameTemplateListingData
| BundleListingData
| CreditsPackageListingData
| CourseListingData
)[],
redemptionCodesIncludedInBundle: IncludedRedemptionCode[],
|}) => (
<I18n>
{({ i18n }) => (
<LineStackLayout noMargin alignItems="flex-start">
<Hammer />
<Column noMargin>
<Text noMargin size="sub-title">
<Trans>
{gameTemplateListingDatasIncludedInBundle.length === 1 ? (
<Trans>
{gameTemplateListingDatasIncludedInBundle.length} Game
template
</Trans>
) : (
<Trans>
{gameTemplateListingDatasIncludedInBundle.length} Game
templates
</Trans>
)}
</Trans>
</Text>
<Text color="secondary" noMargin>
<Trans>Lifetime access</Trans>
</Text>
<Text color="secondary" noMargin>
<span style={styles.discountedPrice}>
{renderEstimatedTotalPriceFormatted({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
filter: 'GAME_TEMPLATE',
})}
</span>
</Text>
</Column>
</LineStackLayout>
)}
</I18n>
);
const RedemptionCodeLineSummary = ({
includedRedemptionCode,
bundleListingData,
}: {|
includedRedemptionCode: IncludedRedemptionCode,
bundleListingData: BundleListingData,
|}) => (
<I18n>
{({ i18n }) => (
<LineStackLayout noMargin alignItems="flex-start">
{getPlanIcon({
planId: includedRedemptionCode.givenSubscriptionPlanId,
logoSize: 20,
})}
<Column noMargin>
<Text noMargin size="sub-title">
<Trans>
{getPlanInferredNameFromId(
includedRedemptionCode.givenSubscriptionPlanId
)}
subscription
</Trans>
</Text>
<Text color="secondary" noMargin>
{formatDurationOfRedemptionCode(
includedRedemptionCode.durationInDays
)}
</Text>
<Text color="secondary" noMargin>
<span style={styles.discountedPrice}>
{renderEstimatedRedemptionCodePriceFormatted(
bundleListingData,
includedRedemptionCode,
i18n
)}
</span>
</Text>
</Column>
</LineStackLayout>
)}
</I18n>
);
const CreditsLineSummary = ({
includedCreditsAmount,
}: {
includedCreditsAmount: number,
}) => (
<LineStackLayout noMargin alignItems="center">
<Coin style={styles.coinIcon} />
<Text noMargin size="sub-title">
<Trans>{includedCreditsAmount} credits</Trans>
</Text>
</LineStackLayout>
);
export const getSummaryLines = ({
redemptionCodesIncludedInBundle,
bundleListingData,
productListingDatasIncludedInBundle,
}: {|
redemptionCodesIncludedInBundle: IncludedRedemptionCode[],
bundleListingData: BundleListingData,
productListingDatasIncludedInBundle: (
| PrivateAssetPackListingData
| PrivateGameTemplateListingData
| BundleListingData
| CreditsPackageListingData
| CourseListingData
)[],
|}) => {
const includedListableProducts =
bundleListingData.includedListableProducts || [];
const summaryLineItems = [];
const includedCourseListableProducts = includedListableProducts.filter(
product => product.productType === 'COURSE'
);
const courseListingDatasIncludedInBundle = includedCourseListableProducts
.map(product => {
// $FlowFixMe - We know it's a course because of the filter.
const courseListingData: ?CourseListingData = productListingDatasIncludedInBundle.find(
listingData =>
listingData.id === product.productId &&
listingData.productType === 'COURSE'
);
return courseListingData;
})
.filter(Boolean);
if (courseListingDatasIncludedInBundle.length) {
summaryLineItems.push(
<CoursesLineSummary
courseListingDatasIncludedInBundle={courseListingDatasIncludedInBundle}
bundleListingData={bundleListingData}
productListingDatasIncludedInBundle={
productListingDatasIncludedInBundle
}
redemptionCodesIncludedInBundle={redemptionCodesIncludedInBundle}
/>
);
}
const includedAssetPackListableProducts = includedListableProducts.filter(
product => product.productType === 'ASSET_PACK'
);
const assetPackListingDatasIncludedInBundle = includedAssetPackListableProducts
.map(product => {
// $FlowFixMe - We know it's an asset pack because of the filter.
const assetPackListingData: ?PrivateAssetPackListingData = productListingDatasIncludedInBundle.find(
listingData =>
listingData.id === product.productId &&
listingData.productType === 'ASSET_PACK'
);
return assetPackListingData;
})
.filter(Boolean);
if (assetPackListingDatasIncludedInBundle.length) {
summaryLineItems.push(
<AssetPacksLineSummary
assetPackListingDatasIncludedInBundle={
assetPackListingDatasIncludedInBundle
}
bundleListingData={bundleListingData}
productListingDatasIncludedInBundle={
productListingDatasIncludedInBundle
}
redemptionCodesIncludedInBundle={redemptionCodesIncludedInBundle}
/>
);
}
const includedGameTemplateListableProducts = includedListableProducts.filter(
product => product.productType === 'GAME_TEMPLATE'
);
const gameTemplateListingDatasIncludedInBundle = includedGameTemplateListableProducts
.map(product => {
// $FlowFixMe - We know it's a game template because of the filter.
const gameTemplateListingData: ?PrivateGameTemplateListingData = productListingDatasIncludedInBundle.find(
listingData =>
listingData.id === product.productId &&
listingData.productType === 'GAME_TEMPLATE'
);
return gameTemplateListingData;
})
.filter(Boolean);
if (gameTemplateListingDatasIncludedInBundle.length) {
summaryLineItems.push(
<GameTemplatesLineSummary
gameTemplateListingDatasIncludedInBundle={
gameTemplateListingDatasIncludedInBundle
}
bundleListingData={bundleListingData}
productListingDatasIncludedInBundle={
productListingDatasIncludedInBundle
}
redemptionCodesIncludedInBundle={redemptionCodesIncludedInBundle}
/>
);
}
if (redemptionCodesIncludedInBundle.length) {
redemptionCodesIncludedInBundle.forEach(code => {
summaryLineItems.push(
<RedemptionCodeLineSummary
includedRedemptionCode={code}
bundleListingData={bundleListingData}
/>
);
});
}
const includedCreditsAmount = includedListableProducts
.filter(product => product.productType === 'CREDIT_PACKAGE')
.reduce(
(total, product) => total + getCreditsAmountFromId(product.productId),
0
);
if (includedCreditsAmount) {
summaryLineItems.push(
<CreditsLineSummary includedCreditsAmount={includedCreditsAmount} />
);
}
const mobileLineItems = [];
const desktopLineItems = [];
summaryLineItems.forEach((item, index) => {
if (index !== 0) {
desktopLineItems.push(
<Line noMargin key={`divider-${index}`}>
<Spacer />
<Column>
<Divider orientation="vertical" />
</Column>
<Spacer />
</Line>
);
if (index % 2 === 1) {
mobileLineItems.push(
<Column key={`divider-${index}`}>
<Divider orientation="vertical" />
</Column>
);
}
}
desktopLineItems.push(item);
mobileLineItems.push(
<Column expand noMargin key={`item-${index}`}>
{item}
</Column>
);
});
// Desktop, everything on one line.
const desktopLines = [];
desktopLines.push(
<ResponsiveLineStackLayout expand key="desktop-line">
{desktopLineItems}
</ResponsiveLineStackLayout>
);
// Mobile, 3 items by line (2 + 1 divider)
const mobileLines = [];
for (let i = 0; i < mobileLineItems.length; i += 3) {
mobileLines.push(
<LineStackLayout key={`mobile-line-${i}`} expand>
{mobileLineItems.slice(i, i + 3)}
</LineStackLayout>
);
}
return {
mobileLines,
desktopLines,
};
};

View File

@@ -736,10 +736,7 @@ const PrivateAssetPackInformationPage = ({
label={<Trans>Browse assets</Trans>}
/>
) : (
<>
{!shouldUseOrSimulateAppStoreProduct && (
<SecureCheckout />
)}
<ColumnStackLayout noMargin>
{!errorText && (
<PurchaseProductButtons
i18n={i18n}
@@ -752,7 +749,10 @@ const PrivateAssetPackInformationPage = ({
onClickBuyWithCredits={onWillBuyWithCredits}
/>
)}
</>
{!shouldUseOrSimulateAppStoreProduct && (
<SecureCheckout />
)}
</ColumnStackLayout>
)}
</ColumnStackLayout>
</div>

View File

@@ -596,10 +596,7 @@ const PrivateGameTemplateInformationPage = ({
/>
<Spacer />
{!isAlreadyReceived ? (
<>
{!shouldUseOrSimulateAppStoreProduct && (
<SecureCheckout />
)}
<ColumnStackLayout noMargin>
{!errorText && (
<PurchaseProductButtons
i18n={i18n}
@@ -614,7 +611,10 @@ const PrivateGameTemplateInformationPage = ({
onClickBuyWithCredits={onWillBuyWithCredits}
/>
)}
</>
{!shouldUseOrSimulateAppStoreProduct && (
<SecureCheckout />
)}
</ColumnStackLayout>
) : onCreateWithGameTemplate ? (
<OpenProductButton
productListingData={privateGameTemplateListingData}

View File

@@ -0,0 +1,133 @@
// @flow
import * as React from 'react';
import { Trans } from '@lingui/macro';
import Text from '../UI/Text';
import { Column, Spacer } from '../UI/Grid';
import { LineStackLayout } from '../UI/Layout';
const styles = {
limitedTimeContainer: {
display: 'flex',
backgroundColor: '#F03F18',
color: 'white',
borderRadius: 4,
padding: '8px 0',
},
};
type Props = {|
visibleUntil: string,
hideMinutesAndSeconds?: boolean,
alignCenter?: boolean,
|};
const ProductLimitedTimeOffer = ({
visibleUntil,
hideMinutesAndSeconds,
alignCenter,
}: Props) => {
const [timeLeft, setTimeLeft] = React.useState<{|
days: number,
hours: number,
minutes: number,
seconds: number,
|}>({ days: 0, hours: 0, minutes: 0, seconds: 0 });
React.useEffect(
() => {
const updateCountdown = () => {
const now = new Date().getTime();
const targetTime = new Date(visibleUntil).getTime();
const difference = targetTime - now;
if (difference > 0) {
setTimeLeft({
days: Math.floor(difference / (1000 * 60 * 60 * 24)),
hours: Math.floor(
(difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
),
minutes: Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)),
seconds: Math.floor((difference % (1000 * 60)) / 1000),
});
} else {
setTimeLeft({ days: 0, hours: 0, minutes: 0, seconds: 0 });
}
};
updateCountdown();
const interval = setInterval(updateCountdown, 1000);
return () => clearInterval(interval);
},
[visibleUntil]
);
if (!timeLeft) return null;
return (
<div style={styles.limitedTimeContainer}>
<Column
justifyContent="center"
expand
alignItems={alignCenter ? 'center' : undefined}
>
<Text>
<Trans>Limited time offer:</Trans>
</Text>
<LineStackLayout alignItems="center" noMargin>
<Text noMargin size="block-title">
{String(timeLeft.days).padStart(2, '0')}
</Text>
<Text noMargin>
<Trans>Days</Trans>
</Text>
<Spacer />
<Text
noMargin
size="block-title"
style={{
fontVariantNumeric: 'tabular-nums',
}}
>
{String(timeLeft.hours).padStart(2, '0')}
</Text>
<Text noMargin>
<Trans>Hours</Trans>
</Text>
{!hideMinutesAndSeconds && (
<LineStackLayout alignItems="center" noMargin>
<Spacer />
<Text
noMargin
size="block-title"
style={{
fontVariantNumeric: 'tabular-nums',
}}
>
{String(timeLeft.minutes).padStart(2, '0')}
</Text>
<Text noMargin>
<Trans>Minutes</Trans>
</Text>
<Spacer />
<Text
noMargin
size="block-title"
style={{
fontVariantNumeric: 'tabular-nums',
}}
>
{String(timeLeft.seconds).padStart(2, '0')}
</Text>
<Text noMargin>
<Trans>Seconds</Trans>
</Text>
</LineStackLayout>
)}
</LineStackLayout>
</Column>
</div>
);
};
export default ProductLimitedTimeOffer;

View File

@@ -319,6 +319,7 @@ export const getProductsIncludedInBundleTiles = ({
onPrivateGameTemplateOpen,
onBundleOpen,
onCourseOpen,
discountedPrice,
}: {|
product: ?PrivateAssetPack | PrivateGameTemplate | Bundle | Course,
productListingDatas: ?Array<
@@ -343,6 +344,7 @@ export const getProductsIncludedInBundleTiles = ({
) => void,
onBundleOpen?: (bundleListingData: BundleListingData) => void,
onCourseOpen?: (courseListingData: CourseListingData) => void,
discountedPrice?: boolean,
|}): ?Array<React.Node> => {
if (!product || !productListingDatas) return null;
@@ -378,6 +380,7 @@ export const getProductsIncludedInBundleTiles = ({
onPrivateGameTemplateOpen(includedProductListingData)
}
owned={isProductOwned}
discountedPrice={discountedPrice}
/>
);
}
@@ -395,6 +398,7 @@ export const getProductsIncludedInBundleTiles = ({
key={includedProductListingData.id}
onSelect={() => onPrivateAssetPackOpen(includedProductListingData)}
owned={isProductOwned}
discountedPrice={discountedPrice}
/>
);
}
@@ -412,6 +416,7 @@ export const getProductsIncludedInBundleTiles = ({
key={includedProductListingData.id}
onSelect={() => onBundleOpen(includedProductListingData)}
owned={isProductOwned}
discountedPrice={discountedPrice}
/>
);
}
@@ -429,6 +434,7 @@ export const getProductsIncludedInBundleTiles = ({
key={includedProductListingData.id}
onSelect={() => onCourseOpen(includedProductListingData)}
owned={isProductOwned}
discountedPrice={discountedPrice}
/>
);
}
@@ -529,6 +535,7 @@ export const PurchaseProductButtons = <
isAlreadyReceived,
onClickBuy,
onClickBuyWithCredits,
customLabel,
}: {|
productListingData: T,
selectedUsageType: string,
@@ -538,6 +545,7 @@ export const PurchaseProductButtons = <
isAlreadyReceived: boolean,
onClickBuy: () => void | Promise<void>,
onClickBuyWithCredits?: () => void | Promise<void>,
customLabel?: React.Node,
|}) => {
const { authenticated } = React.useContext(AuthenticatedUserContext);
const shouldUseOrSimulateAppStoreProduct =
@@ -578,10 +586,13 @@ export const PurchaseProductButtons = <
<LineStackLayout>
<RaisedButton
primary
label={<Trans>Buy for {formattedProductPriceText}</Trans>}
label={
customLabel || <Trans>Buy for {formattedProductPriceText}</Trans>
}
onClick={onClickBuyWithCredits}
id={`buy-${productType}-with-credits`}
icon={<Coin fontSize="small" />}
size="medium"
/>
{!isAlreadyReceived && !authenticated && (
<Text size="body-small">
@@ -592,21 +603,27 @@ export const PurchaseProductButtons = <
)}
</LineStackLayout>
) : (
<LineStackLayout>
<LineStackLayout noMargin>
{creditPrice && (
<FlatButton
primary
label={<Trans>Buy for {creditPrice.amount} credits</Trans>}
label={
customLabel || <Trans>Buy for {creditPrice.amount} credits</Trans>
}
onClick={onClickBuyWithCredits}
id={`buy-${productType}-with-credits`}
leftIcon={<Coin fontSize="small" />}
size="medium"
/>
)}
<RaisedButton
primary
label={<Trans>Buy for {formattedProductPriceText}</Trans>}
label={
customLabel || <Trans>Buy for {formattedProductPriceText}</Trans>
}
onClick={onClickBuy}
id={`buy-${productType}`}
size="medium"
/>
</LineStackLayout>
);

View File

@@ -38,6 +38,22 @@ const styles = {
marginTop: -3,
marginBottom: -1,
},
discountedPrice: { textDecoration: 'line-through', opacity: 0.7 },
};
export const renderPriceFormatted = (
priceInCents: number,
currencyCode: 'USD' | 'EUR',
i18n: I18nType
): string => {
const currencySymbol = currencyCode === 'USD' ? '$' : '€';
// Use a non-breaking space to ensure the currency stays next to the price.
return `${currencySymbol}\u00A0${i18n
.number(priceInCents / 100, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
.replace(/\D00$/, '')}`;
};
type FormatProps = {|
@@ -51,6 +67,7 @@ type FormatProps = {|
usageType?: string,
plainText?: boolean,
showBothPrices?: 'column' | 'line', // If defined, will show both the credits price and the product price.
discountedPrice?: boolean,
|};
export const renderProductPrice = ({
@@ -59,6 +76,7 @@ export const renderProductPrice = ({
usageType,
plainText,
showBothPrices,
discountedPrice,
}: FormatProps): React.Node => {
// For Credits packages & Bundles, on mobile, only show the app store product price.
if (
@@ -79,8 +97,9 @@ export const renderProductPrice = ({
? creditPrices[0]
: null;
// If we're on mobile, only show credits prices for other packages.
if (shouldUseAppStoreProduct()) {
// If we're on mobile, only show credits prices for other products,
// except if we're showing the discounted price.
if (shouldUseAppStoreProduct() && !discountedPrice) {
if (!creditPrice) return '';
return plainText ? (
i18n._(t`${creditPrice.amount} credits`)
@@ -103,17 +122,15 @@ export const renderProductPrice = ({
: null;
if (!price) return '';
const currencyCode = price.currency === 'USD' ? '$' : '€';
const formattedPrice = `${currencyCode} ${i18n
.number(price.value / 100, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
.replace(/\D00$/, '')}`;
const formattedPrice = renderPriceFormatted(
price.value,
price.currency,
i18n
);
return plainText ? (
formattedPrice
) : showBothPrices && creditPrice ? (
) : showBothPrices && creditPrice && !discountedPrice ? (
showBothPrices === 'column' ? (
<Column alignItems="flex-end">
<div style={styles.creditPriceContainer}>
@@ -149,7 +166,11 @@ export const renderProductPrice = ({
)
) : (
<Text noMargin size="sub-title" color="inherit">
{formattedPrice}
{discountedPrice ? (
<span style={styles.discountedPrice}>{formattedPrice}</span>
) : (
formattedPrice
)}
</Text>
);
};
@@ -165,6 +186,7 @@ type ProductPriceOrOwnedProps = {|
usageType?: string,
owned?: boolean,
showBothPrices?: 'column' | 'line',
discountedPrice?: boolean,
|};
export const OwnedLabel = () => {
@@ -189,11 +211,18 @@ export const getProductPriceOrOwnedLabel = ({
usageType,
owned,
showBothPrices,
discountedPrice,
}: ProductPriceOrOwnedProps): React.Node => {
return owned ? (
<OwnedLabel />
) : (
renderProductPrice({ i18n, productListingData, usageType, showBothPrices })
renderProductPrice({
i18n,
productListingData,
usageType,
showBothPrices,
discountedPrice,
})
);
};
@@ -211,6 +240,7 @@ type ProductPriceTagProps = {|
*/
withOverlay?: boolean,
owned?: boolean,
discountedPrice?: boolean,
|};
const ProductPriceTag = ({
@@ -218,6 +248,7 @@ const ProductPriceTag = ({
usageType,
withOverlay,
owned,
discountedPrice,
}: ProductPriceTagProps) => {
return (
<I18n>
@@ -227,6 +258,7 @@ const ProductPriceTag = ({
productListingData,
usageType,
owned,
discountedPrice,
});
return <PriceTag withOverlay={withOverlay} label={label} />;

View File

@@ -1,52 +1,23 @@
// @flow
import React from 'react';
import { LineStackLayout } from '../../UI/Layout';
import Visa from '../../UI/CustomSvgIcons/Visa';
import MasterCard from '../../UI/CustomSvgIcons/MasterCard';
import Paypal from '../../UI/CustomSvgIcons/Paypal';
import Text from '../../UI/Text';
import { Trans } from '@lingui/macro';
import GDevelopThemeContext from '../../UI/Theme/GDevelopThemeContext';
const styles = {
logoContainer: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
padding: '4px 8px',
borderRadius: 8,
},
};
const LogoContainer = ({ children }) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
return (
<div
style={{
...styles.logoContainer,
background: gdevelopTheme.palette.secondary,
}}
>
{children}
</div>
);
};
import ShieldChecked from '../../UI/CustomSvgIcons/ShieldChecked';
const SecureCheckout = () => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
return (
<LineStackLayout>
<Text>
<Trans>Secure Checkout:</Trans>
<LineStackLayout noMargin alignItems="center">
<ShieldChecked style={{ color: gdevelopTheme.message.valid }} />
<Text color="secondary">
<Trans>Paypal secure</Trans>
</Text>
<ShieldChecked style={{ color: gdevelopTheme.message.valid }} />
<Text color="secondary">
<Trans>Stripe secure</Trans>
</Text>
<LogoContainer>
<Paypal />
</LogoContainer>
<LogoContainer>
<Visa />
</LogoContainer>
<LogoContainer>
<MasterCard />
</LogoContainer>
</LineStackLayout>
);
};

View File

@@ -244,6 +244,7 @@ export const PrivateAssetPackTile = ({
style,
owned,
disabled,
discountedPrice,
}: {|
assetPackListingData: PrivateAssetPackListingData,
onSelect: () => void,
@@ -251,6 +252,7 @@ export const PrivateAssetPackTile = ({
style?: any,
owned: boolean,
disabled?: boolean,
discountedPrice?: boolean,
|}) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
return (
@@ -291,6 +293,7 @@ export const PrivateAssetPackTile = ({
productListingData={assetPackListingData}
withOverlay
owned={owned}
discountedPrice={discountedPrice}
/>
</div>
<Column>
@@ -464,6 +467,7 @@ export const PrivateGameTemplateTile = ({
style,
owned,
disabled,
discountedPrice,
}: {|
privateGameTemplateListingData: PrivateGameTemplateListingData,
onSelect: () => void,
@@ -471,6 +475,7 @@ export const PrivateGameTemplateTile = ({
style?: any,
owned: boolean,
disabled?: boolean,
discountedPrice?: boolean,
|}) => {
const { isMobile } = useResponsiveWindowSize();
const gdevelopTheme = React.useContext(GDevelopThemeContext);
@@ -500,6 +505,7 @@ export const PrivateGameTemplateTile = ({
productListingData={privateGameTemplateListingData}
withOverlay
owned={owned}
discountedPrice={discountedPrice}
/>
</div>
<Column>
@@ -522,6 +528,7 @@ export const CourseTile = ({
style,
owned,
disabled,
discountedPrice,
}: {|
courseListingData: CourseListingData,
onSelect: () => void,
@@ -529,6 +536,7 @@ export const CourseTile = ({
style?: any,
owned: boolean,
disabled?: boolean,
discountedPrice?: boolean,
|}) => {
const { isMobile } = useResponsiveWindowSize();
const gdevelopTheme = React.useContext(GDevelopThemeContext);
@@ -556,6 +564,7 @@ export const CourseTile = ({
productListingData={courseListingData}
withOverlay
owned={owned}
discountedPrice={discountedPrice}
/>
</div>
<Column>
@@ -578,6 +587,7 @@ export const BundleTile = ({
style,
owned,
disabled,
discountedPrice,
}: {|
bundleListingData: BundleListingData,
onSelect: () => void,
@@ -585,6 +595,7 @@ export const BundleTile = ({
style?: any,
owned: boolean,
disabled?: boolean,
discountedPrice?: boolean,
|}) => {
const { isMobile } = useResponsiveWindowSize();
const gdevelopTheme = React.useContext(GDevelopThemeContext);
@@ -616,6 +627,7 @@ export const BundleTile = ({
productListingData={bundleListingData}
withOverlay
owned={owned}
discountedPrice={discountedPrice}
/>
) : (
<OwnedLabel />

View File

@@ -1,5 +1,6 @@
// @flow
import * as React from 'react';
import { I18n } from '@lingui/react';
import { t, Trans } from '@lingui/macro';
import ChevronArrowLeft from '../UI/CustomSvgIcons/ChevronArrowLeft';
import Tune from '../UI/CustomSvgIcons/Tune';
@@ -68,6 +69,8 @@ import { AssetSwappingAssetStoreSearchFilter } from './AssetStoreSearchFilter';
import { delay } from '../Utils/Delay';
import { BundleStoreContext } from './Bundles/BundleStoreContext';
import BundleInformationPage from './Bundles/BundleInformationPage';
import { type CourseCompletion } from '../MainFrame/EditorContainers/HomePage/UseCourses';
import { type SubscriptionPlanWithPricingSystems } from '../Utils/GDevelopServices/Usage';
type Props = {|
onlyShowAssets?: boolean, // TODO: if we add more options, use an array instead.
@@ -76,8 +79,11 @@ type Props = {|
privateGameTemplateListingData: PrivateGameTemplateListingData
) => void,
onOpenProfile?: () => void,
courses?: ?Array<Course>,
receivedCourses?: ?Array<Course>,
onCourseOpen?: (courseId: string) => void,
getSubscriptionPlansWithPricingSystems?: () => Array<SubscriptionPlanWithPricingSystems> | null,
getCourseCompletion?: (courseId: string) => CourseCompletion | null,
assetSwappedObject?: ?gdObject,
minimalUI?: boolean,
|};
@@ -118,8 +124,11 @@ export const AssetStore = React.forwardRef<Props, AssetStoreInterface>(
displayPromotions,
onOpenPrivateGameTemplateListingData,
onOpenProfile,
courses,
receivedCourses,
onCourseOpen,
getSubscriptionPlansWithPricingSystems,
getCourseCompletion,
assetSwappedObject,
minimalUI,
}: Props,
@@ -660,291 +669,323 @@ export const AssetStore = React.forwardRef<Props, AssetStoreInterface>(
]
);
const onBack = React.useCallback(
async () => {
const page = shopNavigationState.backToPreviousPage();
const isUpdatingSearchtext = reApplySearchTextIfNeeded(page);
if (isUpdatingSearchtext) {
// Updating the search is not instant, so we cannot apply the scroll position
// right away. We force a wait as there's no easy way to know when results are completely updated.
await delay(500);
setScrollUpdateIsNeeded(page);
applyBackScrollPosition(page); // We apply it manually, because the layout effect won't be called again.
} else {
setScrollUpdateIsNeeded(page);
}
},
[
shopNavigationState,
reApplySearchTextIfNeeded,
setScrollUpdateIsNeeded,
applyBackScrollPosition,
]
);
return (
<Column expand noMargin useFullHeight noOverflowParent id="asset-store">
<>
<LineStackLayout>
{!(assetSwappedObject && minimalUI) && (
<IconButton
id="home-button"
key="back-discover"
tooltip={t`Back to discover`}
onClick={() => {
setSearchText('');
const page = assetSwappedObject
? shopNavigationState.openAssetSwapping()
: shopNavigationState.openHome();
setScrollUpdateIsNeeded(page);
clearAllAssetStoreFilters();
setIsFiltersPanelOpen(false);
}}
size="small"
>
<Home />
</IconButton>
)}
<Column expand useFullHeight noMargin>
<SearchBar
placeholder={
onlyShowAssets ? t`Search assets` : t`Search the shop`
}
value={searchText}
onChange={(newValue: string) => {
if (searchText === newValue || newValue.length === 1) {
return;
}
setSearchText(newValue);
if (isOnSearchResultPage) {
// An existing search is already being done: just move to the
// top search results.
shopNavigationState.openSearchResultPage();
const assetsListInterface = assetsList.current;
if (assetsListInterface) {
assetsListInterface.scrollToPosition(0);
assetsListInterface.setPageBreakIndex(0);
<I18n>
{({ i18n }) => (
<Column
expand
noMargin
useFullHeight
noOverflowParent
id="asset-store"
>
<>
<LineStackLayout>
{!(assetSwappedObject && minimalUI) && (
<IconButton
id="home-button"
key="back-discover"
tooltip={t`Back to discover`}
onClick={() => {
setSearchText('');
const page = assetSwappedObject
? shopNavigationState.openAssetSwapping()
: shopNavigationState.openHome();
setScrollUpdateIsNeeded(page);
clearAllAssetStoreFilters();
setIsFiltersPanelOpen(false);
}}
size="small"
>
<Home />
</IconButton>
)}
<Column expand useFullHeight noMargin>
<SearchBar
placeholder={
onlyShowAssets ? t`Search assets` : t`Search the shop`
}
} else {
// A new search is being initiated: navigate to the search page,
// and clear the history as a new search was launched.
if (!!newValue) {
shopNavigationState.clearHistory();
shopNavigationState.openSearchResultPage();
openFiltersPanelIfAppropriate();
}
}
}}
onRequestSearch={() => {}}
ref={searchBar}
id="asset-store-search-bar"
/>
</Column>
{!(assetSwappedObject && minimalUI) && (
<IconButton
onClick={() => setIsFiltersPanelOpen(!isFiltersPanelOpen)}
disabled={!canShowFiltersPanel}
selected={canShowFiltersPanel && isFiltersPanelOpen}
size="small"
>
<Tune />
</IconButton>
)}
</LineStackLayout>
<Spacer />
</>
<Column noMargin>
<Line justifyContent="space-between" noMargin alignItems="center">
{(!isOnHomePage || !!openedShopCategory) &&
!(assetSwappedObject && minimalUI) && (
<>
{shopNavigationState.isRootPage ? null : (
<Column expand alignItems="flex-start" noMargin>
<TextButton
icon={<ChevronArrowLeft />}
label={<Trans>Back</Trans>}
onClick={async () => {
const page = shopNavigationState.backToPreviousPage();
const isUpdatingSearchtext = reApplySearchTextIfNeeded(
page
);
if (isUpdatingSearchtext) {
// Updating the search is not instant, so we cannot apply the scroll position
// right away. We force a wait as there's no easy way to know when results are completely updated.
await delay(500);
setScrollUpdateIsNeeded(page);
applyBackScrollPosition(page); // We apply it manually, because the layout effect won't be called again.
} else {
setScrollUpdateIsNeeded(page);
}
}}
/>
</Column>
)}
{(openedAssetPack ||
openedPrivateAssetPackListingData ||
filtersState.chosenCategory) && (
value={searchText}
onChange={(newValue: string) => {
if (searchText === newValue || newValue.length === 1) {
return;
}
setSearchText(newValue);
if (isOnSearchResultPage) {
// An existing search is already being done: just move to the
// top search results.
shopNavigationState.openSearchResultPage();
const assetsListInterface = assetsList.current;
if (assetsListInterface) {
assetsListInterface.scrollToPosition(0);
assetsListInterface.setPageBreakIndex(0);
}
} else {
// A new search is being initiated: navigate to the search page,
// and clear the history as a new search was launched.
if (!!newValue) {
shopNavigationState.clearHistory();
shopNavigationState.openSearchResultPage();
openFiltersPanelIfAppropriate();
}
}
}}
onRequestSearch={() => {}}
ref={searchBar}
id="asset-store-search-bar"
/>
</Column>
{!(assetSwappedObject && minimalUI) && (
<IconButton
onClick={() => setIsFiltersPanelOpen(!isFiltersPanelOpen)}
disabled={!canShowFiltersPanel}
selected={canShowFiltersPanel && isFiltersPanelOpen}
size="small"
>
<Tune />
</IconButton>
)}
</LineStackLayout>
<Spacer />
</>
<Column noMargin>
<Line justifyContent="space-between" noMargin alignItems="center">
{(!isOnHomePage || !!openedShopCategory) &&
!(assetSwappedObject && minimalUI) && (
<>
{!openedAssetPack && !openedPrivateAssetPackListingData && (
// Only show the category name if we're not on an asset pack page.
<Column expand alignItems="center">
<Text size="block-title" noMargin>
{filtersState.chosenCategory
? capitalize(
filtersState.chosenCategory.node.name
)
: ''}
</Text>
{shopNavigationState.isRootPage ||
// Don't show back action on bundle pages, as it's handled by the page itself.
openedBundleListingData ? null : (
<Column expand alignItems="flex-start" noMargin>
<TextButton
icon={<ChevronArrowLeft />}
label={<Trans>Back</Trans>}
onClick={onBack}
/>
</Column>
)}
<Column
expand
alignItems="flex-end"
noMargin
justifyContent="center"
>
{openedAssetPack &&
openedAssetPack.content &&
doesAssetPackContainAudio(openedAssetPack) &&
!isAssetPackAudioOnly(openedAssetPack) ? (
<PrivateAssetPackAudioFilesDownloadButton
assetPack={openedAssetPack}
/>
) : null}
</Column>
{(openedAssetPack ||
openedPrivateAssetPackListingData ||
filtersState.chosenCategory) && (
<>
{!openedAssetPack &&
!openedPrivateAssetPackListingData && (
// Only show the category name if we're not on an asset pack page.
<Column expand alignItems="center">
<Text size="block-title" noMargin>
{filtersState.chosenCategory
? capitalize(
filtersState.chosenCategory.node.name
)
: ''}
</Text>
</Column>
)}
<Column
expand
alignItems="flex-end"
noMargin
justifyContent="center"
>
{openedAssetPack &&
openedAssetPack.content &&
doesAssetPackContainAudio(openedAssetPack) &&
!isAssetPackAudioOnly(openedAssetPack) ? (
<PrivateAssetPackAudioFilesDownloadButton
assetPack={openedAssetPack}
/>
) : null}
</Column>
</>
)}
</>
)}
</>
)}
</Line>
</Column>
<Line
expand
noMargin
overflow={
'hidden' /* Somehow required on Chrome/Firefox to avoid children growing (but not on Safari) */
}
>
{isOnHomePage ? (
storeError ? (
<PlaceholderError onRetry={fetchAssetsAndGameTemplates}>
<AlertMessage kind="error">
<Trans>
An error occurred when fetching the store content. Please
try again later.
</Trans>
</AlertMessage>
</PlaceholderError>
) : publicAssetPacks &&
privateAssetPackListingDatas &&
privateGameTemplateListingDatas &&
bundleListingDatas ? (
<AssetsHome
ref={assetsHome}
publicAssetPacks={publicAssetPacks}
privateAssetPackListingDatas={privateAssetPackListingDatas}
privateGameTemplateListingDatas={
privateGameTemplateListingDatas
}
bundleListingDatas={bundleListingDatas}
onPublicAssetPackSelection={selectPublicAssetPack}
onPrivateAssetPackSelection={selectPrivateAssetPack}
onPrivateGameTemplateSelection={selectPrivateGameTemplate}
onBundleSelection={selectBundle}
onCategorySelection={selectShopCategory}
openedShopCategory={openedShopCategory}
onlyShowAssets={onlyShowAssets}
displayPromotions={displayPromotions}
onOpenProfile={onOpenProfile}
/>
) : (
<PlaceholderLoader />
)
) : isOnSearchResultPage ? (
<AssetsList
publicAssetPacks={
assetSwappedObject ? [] : publicAssetPacksSearchResults
</Line>
</Column>
<Line
expand
noMargin
overflow={
'hidden' /* Somehow required on Chrome/Firefox to avoid children growing (but not on Safari) */
}
privateAssetPackListingDatas={
assetSwappedObject
? []
: privateAssetPackListingDatasSearchResults
}
privateGameTemplateListingDatas={
assetSwappedObject
? []
: privateGameTemplateListingDatasSearchResults
}
bundleListingDatas={
assetSwappedObject ? [] : bundleListingDatasSearchResults
}
assetShortHeaders={assetShortHeadersSearchResults}
ref={assetsList}
error={storeError}
onOpenDetails={onOpenDetails}
onPrivateAssetPackSelection={selectPrivateAssetPack}
onPublicAssetPackSelection={selectPublicAssetPack}
onPrivateGameTemplateSelection={selectPrivateGameTemplate}
onBundleSelection={selectBundle}
onFolderSelection={selectFolder}
onGoBackToFolderIndex={goBackToFolderIndex}
currentPage={shopNavigationState.getCurrentPage()}
onlyShowAssets={onlyShowAssets}
hideDetails={!!assetSwappedObject && !!minimalUI}
/>
) : // Do not show the asset details if we're swapping an asset.
openedAssetShortHeader && !(assetSwappedObject && minimalUI) ? (
<AssetDetails
ref={assetDetails}
onTagSelection={selectTag}
assetShortHeader={openedAssetShortHeader}
onOpenDetails={onOpenDetails}
onAssetLoaded={() => applyBackScrollPosition(currentPage)}
onPrivateAssetPackSelection={selectPrivateAssetPack}
onPrivateGameTemplateSelection={selectPrivateGameTemplate}
/>
) : !!openedPrivateAssetPackListingData ? (
<PrivateAssetPackInformationPage
privateAssetPackListingData={openedPrivateAssetPackListingData}
onAssetPackOpen={selectPrivateAssetPack}
onGameTemplateOpen={selectPrivateGameTemplate}
onBundleOpen={selectBundle}
privateAssetPackListingDatasFromSameCreator={
privateAssetPackListingDatasFromSameCreator
}
/>
) : !!openedPrivateGameTemplateListingData ? (
<PrivateGameTemplateInformationPage
privateGameTemplateListingData={
openedPrivateGameTemplateListingData
}
onCreateWithGameTemplate={() => {
onOpenPrivateGameTemplateListingData &&
onOpenPrivateGameTemplateListingData(
openedPrivateGameTemplateListingData
);
}}
onAssetPackOpen={selectPrivateAssetPack}
onGameTemplateOpen={selectPrivateGameTemplate}
onBundleOpen={selectBundle}
privateGameTemplateListingDatasFromSameCreator={
privateGameTemplateListingDatasFromSameCreator
}
/>
) : !!openedBundleListingData ? (
<BundleInformationPage
bundleListingData={openedBundleListingData}
receivedCourses={receivedCourses}
onBundleOpen={selectBundle}
onGameTemplateOpen={selectPrivateGameTemplate}
onAssetPackOpen={selectPrivateAssetPack}
onCourseOpen={selectCourse}
/>
) : null}
{canShowFiltersPanel && (
<ResponsivePaperOrDrawer
onClose={() => setIsFiltersPanelOpen(false)}
open={isFiltersPanelOpen}
>
<ScrollView>
<Column>
<Column noMargin>
<Line alignItems="center">
<Tune />
<Subheader>
<Trans>Object filters</Trans>
</Subheader>
</Line>
</Column>
<Line justifyContent="space-between" alignItems="center">
<AssetStoreFilterPanel
assetSwappedObject={assetSwappedObject}
/>
</Line>
</Column>
</ScrollView>
</ResponsivePaperOrDrawer>
)}
</Line>
</Column>
{isOnHomePage ? (
storeError ? (
<PlaceholderError onRetry={fetchAssetsAndGameTemplates}>
<AlertMessage kind="error">
<Trans>
An error occurred when fetching the store content.
Please try again later.
</Trans>
</AlertMessage>
</PlaceholderError>
) : publicAssetPacks &&
privateAssetPackListingDatas &&
privateGameTemplateListingDatas &&
bundleListingDatas ? (
<AssetsHome
ref={assetsHome}
publicAssetPacks={publicAssetPacks}
privateAssetPackListingDatas={privateAssetPackListingDatas}
privateGameTemplateListingDatas={
privateGameTemplateListingDatas
}
bundleListingDatas={bundleListingDatas}
onPublicAssetPackSelection={selectPublicAssetPack}
onPrivateAssetPackSelection={selectPrivateAssetPack}
onPrivateGameTemplateSelection={selectPrivateGameTemplate}
onBundleSelection={selectBundle}
onCategorySelection={selectShopCategory}
openedShopCategory={openedShopCategory}
onlyShowAssets={onlyShowAssets}
displayPromotions={displayPromotions}
onOpenProfile={onOpenProfile}
/>
) : (
<PlaceholderLoader />
)
) : isOnSearchResultPage ? (
<AssetsList
publicAssetPacks={
assetSwappedObject ? [] : publicAssetPacksSearchResults
}
privateAssetPackListingDatas={
assetSwappedObject
? []
: privateAssetPackListingDatasSearchResults
}
privateGameTemplateListingDatas={
assetSwappedObject
? []
: privateGameTemplateListingDatasSearchResults
}
bundleListingDatas={
assetSwappedObject ? [] : bundleListingDatasSearchResults
}
assetShortHeaders={assetShortHeadersSearchResults}
ref={assetsList}
error={storeError}
onOpenDetails={onOpenDetails}
onPrivateAssetPackSelection={selectPrivateAssetPack}
onPublicAssetPackSelection={selectPublicAssetPack}
onPrivateGameTemplateSelection={selectPrivateGameTemplate}
onBundleSelection={selectBundle}
onFolderSelection={selectFolder}
onGoBackToFolderIndex={goBackToFolderIndex}
currentPage={shopNavigationState.getCurrentPage()}
onlyShowAssets={onlyShowAssets}
hideDetails={!!assetSwappedObject && !!minimalUI}
/>
) : // Do not show the asset details if we're swapping an asset.
openedAssetShortHeader && !(assetSwappedObject && minimalUI) ? (
<AssetDetails
ref={assetDetails}
onTagSelection={selectTag}
assetShortHeader={openedAssetShortHeader}
onOpenDetails={onOpenDetails}
onAssetLoaded={() => applyBackScrollPosition(currentPage)}
onPrivateAssetPackSelection={selectPrivateAssetPack}
onPrivateGameTemplateSelection={selectPrivateGameTemplate}
/>
) : !!openedPrivateAssetPackListingData ? (
<PrivateAssetPackInformationPage
privateAssetPackListingData={
openedPrivateAssetPackListingData
}
onAssetPackOpen={selectPrivateAssetPack}
onGameTemplateOpen={selectPrivateGameTemplate}
onBundleOpen={selectBundle}
privateAssetPackListingDatasFromSameCreator={
privateAssetPackListingDatasFromSameCreator
}
/>
) : !!openedPrivateGameTemplateListingData ? (
<PrivateGameTemplateInformationPage
privateGameTemplateListingData={
openedPrivateGameTemplateListingData
}
onCreateWithGameTemplate={() => {
onOpenPrivateGameTemplateListingData &&
onOpenPrivateGameTemplateListingData(
openedPrivateGameTemplateListingData
);
}}
onAssetPackOpen={selectPrivateAssetPack}
onGameTemplateOpen={selectPrivateGameTemplate}
onBundleOpen={selectBundle}
privateGameTemplateListingDatasFromSameCreator={
privateGameTemplateListingDatasFromSameCreator
}
/>
) : !!openedBundleListingData &&
getSubscriptionPlansWithPricingSystems &&
getCourseCompletion ? (
<BundleInformationPage
bundleListingData={openedBundleListingData}
noPadding
onBack={onBack}
onBundleOpen={selectBundle}
onGameTemplateOpen={selectPrivateGameTemplate}
onAssetPackOpen={selectPrivateAssetPack}
onCourseOpen={selectCourse}
getSubscriptionPlansWithPricingSystems={
getSubscriptionPlansWithPricingSystems
}
courses={courses}
receivedCourses={receivedCourses}
getCourseCompletion={getCourseCompletion}
/>
) : null}
{canShowFiltersPanel && (
<ResponsivePaperOrDrawer
onClose={() => setIsFiltersPanelOpen(false)}
open={isFiltersPanelOpen}
>
<ScrollView>
<Column>
<Column noMargin>
<Line alignItems="center">
<Tune />
<Subheader>
<Trans>Object filters</Trans>
</Subheader>
</Line>
</Column>
<Line justifyContent="space-between" alignItems="center">
<AssetStoreFilterPanel
assetSwappedObject={assetSwappedObject}
/>
</Line>
</Column>
</ScrollView>
</ResponsivePaperOrDrawer>
)}
</Line>
</Column>
)}
</I18n>
);
}
);

View File

@@ -29,6 +29,7 @@ type Props = {|
eventsFunctionsExtension: gdEventsFunctionsExtension | null,
objectType: string,
objectBehaviorsTypes: Array<string>,
isChildObject: boolean,
open: boolean,
onClose: () => void,
onChoose: (type: string, defaultName: string) => void,
@@ -43,6 +44,7 @@ export default function NewBehaviorDialog({
onChoose,
objectType,
objectBehaviorsTypes,
isChildObject,
onExtensionInstalled,
}: Props) {
const [isInstalling, setIsInstalling] = React.useState(false);
@@ -224,6 +226,7 @@ export default function NewBehaviorDialog({
project={project}
objectType={objectType}
objectBehaviorsTypes={objectBehaviorsTypes}
isChildObject={isChildObject}
isInstalling={isInstalling}
onInstall={async shortHeader =>
onInstallExtension(i18n, shortHeader)

View File

@@ -71,6 +71,7 @@ type BehaviorConfigurationEditorProps = {|
project: gdProject,
object: gdObject,
behavior: gdBehavior,
isChildObject: boolean,
resourceManagementProps: ResourceManagementProps,
onBehaviorsUpdated: () => void,
onChangeBehaviorName: (behavior: gdBehavior, newName: string) => void,
@@ -94,6 +95,7 @@ const BehaviorConfigurationEditor = React.forwardRef<
project,
object,
behavior,
isChildObject,
resourceManagementProps,
onBehaviorsUpdated,
onChangeBehaviorName,
@@ -311,6 +313,7 @@ type UseManageBehaviorsState = {|
export const useManageObjectBehaviors = ({
project,
object,
isChildObject,
eventsFunctionsExtension,
onUpdate,
onSizeUpdated,
@@ -320,6 +323,7 @@ export const useManageObjectBehaviors = ({
}: {
project: gdProject,
object: gdObject,
isChildObject: boolean,
eventsFunctionsExtension: gdEventsFunctionsExtension | null,
onUpdate: () => void,
onSizeUpdated?: ?() => void,
@@ -586,6 +590,7 @@ export const useManageObjectBehaviors = ({
open
objectType={object.getType()}
objectBehaviorsTypes={listObjectBehaviorsTypes(object)}
isChildObject={isChildObject}
onClose={() => setNewBehaviorDialogOpen(false)}
onChoose={addBehavior}
project={project}
@@ -615,6 +620,7 @@ type Props = {|
project: gdProject,
eventsFunctionsExtension: gdEventsFunctionsExtension | null,
object: gdObject,
isChildObject: boolean,
onUpdateBehaviorsSharedData: () => void,
onSizeUpdated?: ?() => void,
resourceManagementProps: ResourceManagementProps,
@@ -636,6 +642,7 @@ const BehaviorsEditor = (props: Props) => {
const {
object,
isChildObject,
project,
eventsFunctionsExtension,
onSizeUpdated,
@@ -665,6 +672,7 @@ const BehaviorsEditor = (props: Props) => {
} = useManageObjectBehaviors({
project,
object,
isChildObject,
eventsFunctionsExtension,
onUpdate: forceUpdate,
onSizeUpdated,
@@ -785,6 +793,7 @@ const BehaviorsEditor = (props: Props) => {
key={behaviorName}
project={project}
object={object}
isChildObject={isChildObject}
behavior={behavior}
copyBehavior={copyBehavior}
onRemoveBehavior={removeBehavior}

View File

@@ -10,6 +10,7 @@ import {
type AssetSearchAndInstallOptions,
type AssetSearchAndInstallResult,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from '.';
export type EditorFunctionCallResult =
@@ -39,6 +40,9 @@ export type ProcessEditorFunctionCallsOptions = {|
onSceneEventsModifiedOutsideEditor: (
changes: SceneEventsOutsideEditorChanges
) => void,
onInstancesModifiedOutsideEditor: (
changes: InstancesOutsideEditorChanges
) => void,
ensureExtensionInstalled: (options: {|
extensionName: string,
|}) => Promise<void>,
@@ -53,6 +57,7 @@ export const processEditorFunctionCalls = async ({
editorCallbacks,
generateEvents,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
ignore,
ensureExtensionInstalled,
searchAndInstallAsset,
@@ -136,6 +141,7 @@ export const processEditorFunctionCalls = async ({
args,
generateEvents,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
ensureExtensionInstalled,
searchAndInstallAsset,
}

View File

@@ -32,6 +32,12 @@ export type ExpressionSummary = {|
relevantForSceneEvents?: boolean,
|};
export type PropertySummary = {|
name: string,
description: string,
type: string,
|};
export type ObjectSummary = {|
name: string,
fullName: string,
@@ -51,6 +57,17 @@ export type BehaviorSummary = {|
expressions: Array<ExpressionSummary>,
|};
export type EffectSummary = {|
name: string,
fullName: string,
description: string,
notWorkingForObjects: boolean,
onlyWorkingFor2D: boolean,
onlyWorkingFor3D: boolean,
unique: boolean,
properties: Array<PropertySummary>,
|};
export type ExtensionSummary = {|
extensionName: string,
extensionFullName: string,
@@ -60,6 +77,7 @@ export type ExtensionSummary = {|
freeExpressions: Array<ExpressionSummary>,
objects: { [string]: ObjectSummary },
behaviors: { [string]: BehaviorSummary },
effects: { [string]: EffectSummary },
|};
const normalizeType = (parameterType: string) => {
@@ -102,6 +120,29 @@ const getParameterSummary = (
return parameterSummary;
};
const getPropertySummary = (
propertyName: string,
property: gdPropertyDescriptor
) => {
return {
name: propertyName,
description: property.getDescription(),
type: property.getType(),
};
};
const getPropertiesSummary = (
propertiesMetadata: gdMapStringPropertyDescriptor
) => {
return propertiesMetadata
.keys()
.toJSArray()
.map(propertyName => {
const property = propertiesMetadata.get(propertyName);
return getPropertySummary(propertyName, property);
});
};
export const buildExtensionSummary = ({
gd,
extension,
@@ -111,6 +152,7 @@ export const buildExtensionSummary = ({
}): ExtensionSummary => {
const objects: { [string]: ObjectSummary } = {};
const behaviors: { [string]: BehaviorSummary } = {};
const effects: { [string]: EffectSummary } = {};
const generateInstructionsSummaries = ({
instructionsMetadata,
@@ -254,6 +296,27 @@ export const buildExtensionSummary = ({
behaviors[behaviorType] = behaviorSummary;
});
extension
.getExtensionEffectTypes()
.toJSArray()
.forEach(effectType => {
const effectMetadata = extension.getEffectMetadata(effectType);
if (gd.MetadataProvider.isBadEffectMetadata(effectMetadata)) {
return;
}
const effectSummary: EffectSummary = {
name: effectMetadata.getType(),
fullName: effectMetadata.getFullName(),
description: effectMetadata.getDescription(),
notWorkingForObjects: effectMetadata.isMarkedAsNotWorkingForObjects(),
onlyWorkingFor2D: effectMetadata.isMarkedAsOnlyWorkingFor2D(),
onlyWorkingFor3D: effectMetadata.isMarkedAsOnlyWorkingFor3D(),
unique: effectMetadata.isMarkedAsUnique(),
properties: getPropertiesSummary(effectMetadata.getProperties()),
};
effects[effectType] = effectSummary;
});
return {
extensionName: extension.getName(),
@@ -275,5 +338,6 @@ export const buildExtensionSummary = ({
],
objects,
behaviors,
effects,
};
};

View File

@@ -894,6 +894,7 @@ describe('SimplifiedProject', () => {
},
},
"description": "A fake extension with a fake behavior containing 2 properties.",
"effects": Object {},
"extensionFullName": "Fake extension with a fake behavior",
"extensionName": "FakeBehavior",
"freeActions": Array [],

File diff suppressed because it is too large Load Diff

View File

@@ -113,11 +113,12 @@ export default function EventsBasedObjectEditor({
}}
/>
<Checkbox
label={<Trans>Has animations</Trans>}
checked={eventsBasedObject.isAnimatable()}
label={<Trans>Expand inner area with parent</Trans>}
checked={eventsBasedObject.isInnerAreaFollowingParentSize()}
onCheck={(e, checked) => {
eventsBasedObject.markAsAnimatable(checked);
eventsBasedObject.markAsInnerAreaFollowingParentSize(checked);
onChange();
onEventsBasedObjectChildrenEdited(eventsBasedObject);
}}
/>
<Checkbox
@@ -129,12 +130,11 @@ export default function EventsBasedObjectEditor({
}}
/>
<Checkbox
label={<Trans>Expand inner area with parent</Trans>}
checked={eventsBasedObject.isInnerAreaFollowingParentSize()}
label={<Trans>Has animations (JavaScript only)</Trans>}
checked={eventsBasedObject.isAnimatable()}
onCheck={(e, checked) => {
eventsBasedObject.markAsInnerAreaFollowingParentSize(checked);
eventsBasedObject.markAsAnimatable(checked);
onChange();
onEventsBasedObjectChildrenEdited(eventsBasedObject);
}}
/>
{isDev && (

View File

@@ -1,9 +1,6 @@
// @flow
import { t } from '@lingui/macro';
import * as React from 'react';
import classNames from 'classnames';
import TextField, { type TextFieldInterface } from '../../../UI/TextField';
import { rgbToHex } from '../../../Utils/ColorTransformer';
import {
largeSelectedArea,
@@ -22,6 +19,15 @@ const gd: libGDevelop = global.gd;
const commentTextStyle = {
width: '100%',
fontSize: 'inherit',
fontFamily: '-apple-system, BlinkMacSystemFont, sans-serif',
padding: 0,
backgroundColor: 'transparent',
outline: 0,
border: 0,
// Big enough to have an empty text be the same size as an empty textarea.
lineHeight: '1.5em',
};
const styles = {
@@ -30,9 +36,9 @@ const styles = {
flexWrap: 'wrap',
padding: 5,
overflow: 'hidden',
minHeight: '2.1em',
minHeight: '2.4em',
},
commentTextField: { ...commentTextStyle, fontSize: 'inherit' },
commentTextField: { ...commentTextStyle, minHeight: '0', resize: 'none' },
commentSpan: {
...commentTextStyle,
alignItems: 'center',
@@ -55,8 +61,7 @@ export default class CommentEvent extends React.Component<
editingPreviousValue: null,
};
_selectable: ?HTMLSpanElement;
_textField: ?TextFieldInterface;
_textField: ?HTMLTextAreaElement;
edit = () => {
if (this.state.editing) return;
@@ -67,8 +72,11 @@ export default class CommentEvent extends React.Component<
editingPreviousValue: commentEvent.getComment(),
},
() => {
if (this._textField) {
this._textField.focus({ caretPosition: 'end' });
const textField = this._textField;
if (textField) {
textField.focus();
textField.selectionStart = textField.value.length;
textField.selectionEnd = textField.value.length;
}
// Wait for the change to be applied on the DOM before calling onUpdate,
// so that the height of the event is updated.
@@ -77,15 +85,12 @@ export default class CommentEvent extends React.Component<
);
};
onChange = (e: any, text: string) => {
onChange = (e: any) => {
const commentEvent = gd.asCommentEvent(this.props.event);
commentEvent.setComment(text);
commentEvent.setComment(e.target.value);
this.forceUpdate(() => {
// Wait for the change to be applied on the DOM before calling onUpdate,
// so that the height of the event is updated.
this.props.onUpdate();
});
this._autoResizeTextArea();
this.forceUpdate();
};
endEditing = () => {
@@ -114,6 +119,22 @@ export default class CommentEvent extends React.Component<
.replace(/\n/g, '<br>');
};
_autoResizeTextArea = () => {
if (this._textField) {
const previousHeight = this._textField.style.height;
this._textField.style.height = 'auto';
this._textField.style.height = this._textField.scrollHeight + 'px';
if (previousHeight !== this._textField.style.height) {
this.props.onUpdate(); // Notify the parent that the height has changed.
}
}
};
componentDidUpdate() {
this._autoResizeTextArea();
}
render() {
const commentEvent = gd.asCommentEvent(this.props.event);
@@ -149,31 +170,26 @@ export default class CommentEvent extends React.Component<
id={`${this.props.idPrefix}-comment`}
>
{this.state.editing ? (
<TextField
multiline
margin="none"
<textarea
ref={textField => (this._textField = textField)}
value={commentEvent.getComment()}
translatableHintText={t`<Enter comment>`}
placeholder="..."
onBlur={this.endEditing}
onChange={this.onChange}
style={styles.commentTextField}
inputStyle={{
color: textColor,
padding: 0,
}}
fullWidth
style={{ ...styles.commentTextField, color: textColor }}
id="comment-title"
onKeyDown={event => {
if (shouldCloseOrCancel(event) || shouldSubmit(event)) {
this.endEditing();
}
}}
underlineShow={false}
rows={
/* Ensure the textarea resize down to 1 line when no text or just a single line is entered. */
1
}
/>
) : (
<span
ref={selectable => (this._selectable = selectable)}
className={classNames({
[selectableArea]: true,
[disabledText]: this.props.disabled,

View File

@@ -428,6 +428,7 @@ const InstructionEditorDialog = ({
open={newBehaviorDialogOpen}
objectType={chosenObject.getType()}
objectBehaviorsTypes={listObjectBehaviorsTypes(chosenObject)}
isChildObject={!scope.layout}
onClose={() => setNewBehaviorDialogOpen(false)}
onChoose={addBehavior}
onExtensionInstalled={extensionName => {

View File

@@ -19,7 +19,10 @@ import {
} from '../../Utils/GDevelopServices/Project';
import PlaceholderLoader from '../../UI/PlaceholderLoader';
import PlaceholderError from '../../UI/PlaceholderError';
import { getUserPublicProfilesByIds } from '../../Utils/GDevelopServices/User';
import {
getUserPublicProfilesByIds,
type UserPublicProfileByIds,
} from '../../Utils/GDevelopServices/User';
import Dialog, { DialogPrimaryButton } from '../../UI/Dialog';
import FlatButton from '../../UI/FlatButton';
import LeftLoader from '../../UI/LeftLoader';
@@ -84,9 +87,10 @@ const InviteHome = ({ cloudProjectId }: Props) => {
| 'unexpected'
| null
>(null);
const [userPublicProfileByIds, setUserPublicProfileByIds] = React.useState(
{}
);
const [
userPublicProfileByIds,
setUserPublicProfileByIds,
] = React.useState<UserPublicProfileByIds>({});
const [
showCollaboratorAddDialog,
setShowCollaboratorAddDialog,
@@ -312,6 +316,7 @@ const InviteHome = ({ cloudProjectId }: Props) => {
<ColumnStackLayout expand noMargin>
<UserLine
username={profile.username}
fullName={profile.fullName}
email={profile.email}
level={currentUserLevel}
/>
@@ -365,6 +370,7 @@ const InviteHome = ({ cloudProjectId }: Props) => {
projectUserAcls.map(projectUserAcl => (
<UserLine
username={getCollaboratorUsername(projectUserAcl.userId)}
fullName={null}
email={projectUserAcl.email}
level={projectUserAcl.level}
onDelete={() => {

View File

@@ -1,4 +1,5 @@
// @flow
import Window from '../Utils/Window';
import { getIDEVersion } from '../Version';
type FileSet =
@@ -48,10 +49,9 @@ export const findGDJS = (
// run `newIDE/web-app/scripts/deploy-GDJS-Runtime` script.
let gdjsRoot = `https://resources.gdevelop-app.com/GDJS-${getIDEVersion()}`;
// If you want to test your local changes to the game engine on the local web-app,
// run `npx serve --cors -p 5001` (or another CORS enabled http server on port 5001)
// in `newIDE/app/resources/GDJS` and uncomment this line:
// gdjsRoot = `http://localhost:5001`;
if (Window.isDev()) {
gdjsRoot = `http://localhost:5002`;
}
return Promise.all(
filesToDownload[fileSet].map(relativeFilePath => {

View File

@@ -113,7 +113,7 @@ export const getExtraInstructionInformation = (type: string): ?Hint => {
if (type === 'TextObject::Text::SetFontSize') {
return {
kind: 'warning',
message: t`This action will create a new texture and re-render the text each time it is called, which is expensive and can reduce performances. Prefer to avoid changing a lot the character size of a text.`,
message: t`This action will create a new texture and re-render the text each time it is called, which is expensive and can reduce performance. Avoid changing the character size of text frequently.`,
};
}
if (type === 'PlayMusicCanal' || type === 'PlayMusic') {

View File

@@ -37,6 +37,10 @@ export type SceneEventsOutsideEditorChanges = {|
newOrChangedAiGeneratedEventIds: Set<string>,
|};
export type InstancesOutsideEditorChanges = {|
scene: gdLayout,
|};
export type RenderEditorContainerProps = {|
isActive: boolean,
projectItemName: ?string,
@@ -179,11 +183,14 @@ export type RenderEditorContainerProps = {|
) => void,
onSceneObjectsDeleted: (scene: gdLayout) => void,
onInstancesModifiedOutsideEditor: (
changes: InstancesOutsideEditorChanges
) => void,
// Events editing
onSceneEventsModifiedOutsideEditor: (
changes: SceneEventsOutsideEditorChanges
) => void,
onExtractAsExternalLayout: (name: string) => void,
onExtractAsEventBasedObject: (
extensionName: string,

View File

@@ -4,6 +4,7 @@ import {
type RenderEditorContainerProps,
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from './BaseEditor';
import { prepareInstancesEditorSettings } from '../../InstancesEditor/InstancesEditorSettings';
import {
@@ -115,6 +116,10 @@ export class CustomObjectEditorContainer extends React.Component<RenderEditorCon
// No thing to be done.
}
onInstancesModifiedOutsideEditor(changes: InstancesOutsideEditorChanges) {
// No thing to be done.
}
saveUiSettings = () => {
// const layout = this.getCustomObject();
// const editor = this.editor;

View File

@@ -7,6 +7,7 @@ import {
type RenderEditorContainerProps,
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from './BaseEditor';
import SubscriptionChecker, {
type SubscriptionCheckerInterface,
@@ -66,6 +67,10 @@ export class DebuggerEditorContainer extends React.Component<
// No thing to be done.
}
onInstancesModifiedOutsideEditor(changes: InstancesOutsideEditorChanges) {
// No thing to be done.
}
// To be updated, see https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops.
UNSAFE_componentWillReceiveProps() {
this._checkUserHasSubscription();

View File

@@ -6,6 +6,7 @@ import {
type RenderEditorContainerProps,
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from './BaseEditor';
import { ProjectScopedContainersAccessor } from '../../InstructionOrExpression/EventsScope';
import { type ObjectWithContext } from '../../ObjectsList/EnumerateObjects';
@@ -68,6 +69,10 @@ export class EventsEditorContainer extends React.Component<RenderEditorContainer
}
}
onInstancesModifiedOutsideEditor(changes: InstancesOutsideEditorChanges) {
// No thing to be done.
}
getLayout(): ?gdLayout {
const { project, projectItemName } = this.props;
if (

View File

@@ -5,6 +5,7 @@ import {
type RenderEditorContainerProps,
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from './BaseEditor';
import { type ObjectWithContext } from '../../ObjectsList/EnumerateObjects';
@@ -55,6 +56,10 @@ export class EventsFunctionsExtensionEditorContainer extends React.Component<Ren
// No thing to be done.
}
onInstancesModifiedOutsideEditor(changes: InstancesOutsideEditorChanges) {
// No thing to be done.
}
shouldComponentUpdate(nextProps: RenderEditorContainerProps) {
// We stop updates when the component is inactive.
// If it's active, was active or becoming active again we let update propagate.

View File

@@ -8,6 +8,7 @@ import {
type RenderEditorContainerProps,
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from './BaseEditor';
import ExternalPropertiesDialog, {
type ExternalProperties,
@@ -99,6 +100,10 @@ export class ExternalEventsEditorContainer extends React.Component<
// No thing to be done.
}
onInstancesModifiedOutsideEditor(changes: InstancesOutsideEditorChanges) {
// No thing to be done.
}
getExternalEvents(): ?gdExternalEvents {
const { project, projectItemName } = this.props;
if (!project || !projectItemName) return null;

View File

@@ -13,6 +13,7 @@ import {
type RenderEditorContainerProps,
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from './BaseEditor';
import ExternalPropertiesDialog, {
type ExternalProperties,
@@ -157,6 +158,16 @@ export class ExternalLayoutEditorContainer extends React.Component<
// No thing to be done.
}
onInstancesModifiedOutsideEditor(changes: InstancesOutsideEditorChanges) {
if (changes.scene !== this.getLayout()) {
return;
}
if (this.editor) {
this.editor.onInstancesModifiedOutsideEditor();
}
}
getExternalLayout(): ?gdExternalLayout {
const { project, projectItemName } = this.props;
if (!project || !projectItemName) return null;

View File

@@ -1,303 +0,0 @@
// @flow
import * as React from 'react';
import { I18n } from '@lingui/react';
import SectionContainer, { SectionRow } from '../SectionContainer';
import { Column, Line } from '../../../../UI/Grid';
import BundlePageHeader from './BundlePageHeader';
import { BundleStoreContext } from '../../../../AssetStore/Bundles/BundleStoreContext';
import PlaceholderLoader from '../../../../UI/PlaceholderLoader';
import type { CourseCompletion } from '../UseCourses';
import {
getBundle,
type Bundle,
type Course,
} from '../../../../Utils/GDevelopServices/Asset';
import {
type PrivateAssetPackListingData,
type BundleListingData,
type PrivateGameTemplateListingData,
type CourseListingData,
} from '../../../../Utils/GDevelopServices/Shop';
import { type SubscriptionPlanWithPricingSystems } from '../../../../Utils/GDevelopServices/Usage';
import { extractGDevelopApiErrorStatusAndCode } from '../../../../Utils/GDevelopServices/Errors';
import { Trans } from '@lingui/macro';
import AlertMessage from '../../../../UI/AlertMessage';
import {
getProductsIncludedInBundle,
getProductsIncludedInBundleTiles,
} from '../../../../AssetStore/ProductPageHelper';
import { PrivateGameTemplateStoreContext } from '../../../../AssetStore/PrivateGameTemplates/PrivateGameTemplateStoreContext';
import { AssetStoreContext } from '../../../../AssetStore/AssetStoreContext';
import AuthenticatedUserContext from '../../../../Profile/AuthenticatedUserContext';
import { GridList, GridListTile } from '@material-ui/core';
import { LARGE_WIDGET_SIZE } from '../CardWidget';
import {
useResponsiveWindowSize,
type WindowSizeType,
} from '../../../../UI/Responsive/ResponsiveWindowMeasurer';
import Text from '../../../../UI/Text';
import CourseStoreContext from '../../../../Course/CourseStoreContext';
import CourseCard from './CourseCard';
const getColumns = (windowSize: WindowSizeType, isLandscape: boolean) => {
switch (windowSize) {
case 'small':
return isLandscape ? 4 : 2;
case 'medium':
return 3;
case 'large':
return 4;
case 'xlarge':
return 6;
default:
return 3;
}
};
const cellSpacing = 10;
const MAX_COLUMNS = getColumns('xlarge', true);
const MAX_SECTION_WIDTH = (LARGE_WIDGET_SIZE + 2 * 5) * MAX_COLUMNS; // widget size + 5 padding per side
const styles = {
grid: {
// Avoid tiles taking too much space on large screens.
maxWidth: MAX_SECTION_WIDTH,
overflow: 'hidden',
width: `calc(100% + ${cellSpacing}px)`, // This is needed to compensate for the `margin: -5px` added by MUI related to spacing.
},
};
type Props = {|
bundleListingData: BundleListingData,
onBack: () => void,
getSubscriptionPlansWithPricingSystems: () => Array<SubscriptionPlanWithPricingSystems> | null,
onBundleOpen: BundleListingData => void,
onGameTemplateOpen: PrivateGameTemplateListingData => void,
onAssetPackOpen: (
privateAssetPackListingData: PrivateAssetPackListingData
) => void,
onCourseOpen: CourseListingData => void,
courses: ?Array<Course>,
receivedCourses: ?Array<Course>,
getCourseCompletion: (courseId: string) => CourseCompletion | null,
|};
const BundlePage = ({
bundleListingData,
onBack,
getSubscriptionPlansWithPricingSystems,
onAssetPackOpen,
onGameTemplateOpen,
onBundleOpen,
onCourseOpen,
courses,
receivedCourses,
getCourseCompletion,
}: Props) => {
const { windowSize, isLandscape } = useResponsiveWindowSize();
const { bundleListingDatas } = React.useContext(BundleStoreContext); // If archived, should use the one passed.
const { privateGameTemplateListingDatas } = React.useContext(
PrivateGameTemplateStoreContext
);
const { privateAssetPackListingDatas } = React.useContext(AssetStoreContext);
const { listedCourses } = React.useContext(CourseStoreContext);
const {
receivedBundles,
receivedGameTemplates,
receivedAssetPacks,
} = React.useContext(AuthenticatedUserContext);
const [bundle, setBundle] = React.useState<?Bundle>(null);
const [errorText, setErrorText] = React.useState<?React.Node>(null);
const courseAndTheirListingDataIncludedInBundle = React.useMemo(
(): Array<{|
course: Course,
courseListingData: CourseListingData,
|}> | null => {
if (!bundle || !bundleListingData || !courses) return null;
const productListingDatasInBundle = getProductsIncludedInBundle({
productListingData: bundleListingData,
productListingDatas: [...(listedCourses || [])],
});
if (!productListingDatasInBundle) return null;
// $FlowIgnore - Flow doesn't understand that we have filtered the products to only include courses.
const courseListingDatasInBundle: CourseListingData[] = productListingDatasInBundle.filter(
productListingData => productListingData.productType === 'COURSE'
);
return (courseListingDatasInBundle || [])
.map(courseListingData => {
const course = courses.find(
course => course.id === courseListingData.id
);
if (!course) return null;
return {
course,
courseListingData,
};
})
.filter(Boolean);
},
[bundle, bundleListingData, listedCourses, courses]
);
const productsExceptCoursesIncludedInBundleTiles = React.useMemo(
() =>
bundle && bundleListingData
? getProductsIncludedInBundleTiles({
product: bundle,
productListingDatas: [
...(bundleListingDatas || []),
...(privateGameTemplateListingDatas || []),
...(privateAssetPackListingDatas || []),
],
productListingData: bundleListingData,
receivedProducts: [
...(receivedBundles || []),
...(receivedGameTemplates || []),
...(receivedAssetPacks || []),
],
onPrivateAssetPackOpen: onAssetPackOpen,
onPrivateGameTemplateOpen: onGameTemplateOpen,
onBundleOpen,
onCourseOpen,
})
: null,
[
bundle,
bundleListingDatas,
privateGameTemplateListingDatas,
privateAssetPackListingDatas,
receivedBundles,
receivedGameTemplates,
receivedAssetPacks,
bundleListingData,
onAssetPackOpen,
onGameTemplateOpen,
onBundleOpen,
onCourseOpen,
]
);
React.useEffect(
() => {
(async () => {
try {
const bundle = await getBundle(bundleListingData.id);
setBundle(bundle);
} catch (error) {
const extractedStatusAndCode = extractGDevelopApiErrorStatusAndCode(
error
);
if (extractedStatusAndCode && extractedStatusAndCode.status === 404) {
setErrorText(
<Trans>
Bundle not found - An error occurred, please try again later.
</Trans>
);
} else {
setErrorText(
<Trans>An error occurred, please try again later.</Trans>
);
}
}
})();
},
[bundleListingData.id]
);
if (errorText) {
return (
<SectionContainer flexBody backAction={onBack}>
<SectionRow expand>
<Line alignItems="center" justifyContent="center" expand>
<AlertMessage kind="error">{errorText}</AlertMessage>
</Line>
</SectionRow>
</SectionContainer>
);
}
if (!bundleListingData || !bundle) {
return (
<SectionContainer flexBody>
<SectionRow expand>
<PlaceholderLoader />
</SectionRow>
</SectionContainer>
);
}
return (
<I18n>
{({ i18n }) => (
<SectionContainer
applyTopSpacingAsMarginOnChildrenContainer
backAction={onBack}
>
<Column noOverflowParent noMargin>
<BundlePageHeader
bundleListingData={bundleListingData}
bundle={bundle}
getSubscriptionPlansWithPricingSystems={
getSubscriptionPlansWithPricingSystems
}
/>
</Column>
{courseAndTheirListingDataIncludedInBundle &&
courseAndTheirListingDataIncludedInBundle.length > 0 && (
<Line>
<GridList
cols={getColumns(windowSize, isLandscape)}
style={styles.grid}
cellHeight="auto"
spacing={cellSpacing}
>
{courseAndTheirListingDataIncludedInBundle.map(
({ course, courseListingData }) => {
const completion = getCourseCompletion(course.id);
return (
<GridListTile key={course.id}>
<CourseCard
course={course}
courseListingData={courseListingData}
completion={completion}
onClick={() => {
onCourseOpen(courseListingData);
}}
/>
</GridListTile>
);
}
)}
</GridList>
</Line>
)}
{productsExceptCoursesIncludedInBundleTiles && (
<>
<Line>
<Text size="block-title">
<Trans>Also included in this bundle</Trans>
</Text>
</Line>
<Line>
<GridList
cols={getColumns(windowSize, isLandscape)}
cellHeight="auto"
spacing={cellSpacing}
style={styles.grid}
>
{productsExceptCoursesIncludedInBundleTiles}
</GridList>
</Line>
</>
)}
</SectionContainer>
)}
</I18n>
);
};
export default BundlePage;

View File

@@ -1,388 +0,0 @@
// @flow
import * as React from 'react';
import { Trans } from '@lingui/macro';
import { I18n } from '@lingui/react';
import { type Bundle } from '../../../../Utils/GDevelopServices/Asset';
import { type BundleListingData } from '../../../../Utils/GDevelopServices/Shop';
import { SectionRow } from '../SectionContainer';
import Paper from '../../../../UI/Paper';
import Text from '../../../../UI/Text';
import { Column, Line } from '../../../../UI/Grid';
import {
ColumnStackLayout,
LineStackLayout,
ResponsiveLineStackLayout,
} from '../../../../UI/Layout';
import GDevelopThemeContext from '../../../../UI/Theme/GDevelopThemeContext';
import { useResponsiveWindowSize } from '../../../../UI/Responsive/ResponsiveWindowMeasurer';
import { selectMessageByLocale } from '../../../../Utils/i18n/MessageByLocale';
import { renderProductPrice } from '../../../../AssetStore/ProductPriceTag';
import {
getProductsIncludedInBundle,
getUserProductPurchaseUsageType,
PurchaseProductButtons,
} from '../../../../AssetStore/ProductPageHelper';
import { shouldUseAppStoreProduct } from '../../../../Utils/AppStorePurchases';
import { Divider } from '@material-ui/core';
import AuthenticatedUserContext from '../../../../Profile/AuthenticatedUserContext';
import { BundleStoreContext } from '../../../../AssetStore/Bundles/BundleStoreContext';
import { sendBundleBuyClicked } from '../../../../Utils/Analytics/EventSender';
import BundlePurchaseDialog from '../../../../AssetStore/Bundles/BundlePurchaseDialog';
import RedemptionCodesDialog from '../../../../RedemptionCode/RedemptionCodesDialog';
import { renderEstimatedTotalPriceFormatted } from '../../../../AssetStore/Bundles/Utils';
import { PrivateGameTemplateStoreContext } from '../../../../AssetStore/PrivateGameTemplates/PrivateGameTemplateStoreContext';
import {
CreditsPackageStoreContext,
getCreditsAmountFromId,
} from '../../../../AssetStore/CreditsPackages/CreditsPackageStoreContext';
import { AssetStoreContext } from '../../../../AssetStore/AssetStoreContext';
import CourseStoreContext from '../../../../Course/CourseStoreContext';
import SecureCheckout from '../../../../AssetStore/SecureCheckout/SecureCheckout';
import {
getPlanIcon,
getPlanInferredNameFromId,
} from '../../../../Profile/Subscription/PlanCard';
import FlatButton from '../../../../UI/FlatButton';
import Coin from '../../../../Credits/Icons/Coin';
import { type SubscriptionPlanWithPricingSystems } from '../../../../Utils/GDevelopServices/Usage';
import { formatDurationOfRedemptionCode } from '../../../../RedemptionCode/Utils';
const styles = {
title: { overflowWrap: 'anywhere', textWrap: 'wrap' },
image: { width: 300, aspectRatio: '16 / 9' },
imageContainer: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
position: 'relative',
borderRadius: 8,
overflow: 'hidden',
},
discountedPrice: { textDecoration: 'line-through', opacity: 0.7 },
coinIcon: {
width: 13,
height: 13,
position: 'relative',
top: -1,
},
};
const ResponsiveDivider = () => {
const { isMobile, isMediumScreen } = useResponsiveWindowSize();
return isMobile || isMediumScreen ? (
<Column noMargin>
<Divider orientation="horizontal" />
</Column>
) : (
<Line noMargin>
<Divider orientation="vertical" />
</Line>
);
};
type Props = {|
bundleListingData: BundleListingData,
bundle: Bundle,
getSubscriptionPlansWithPricingSystems: () => Array<SubscriptionPlanWithPricingSystems> | null,
simulateAppStoreProduct?: boolean,
|};
const BundlePageHeader = ({
bundle,
bundleListingData,
getSubscriptionPlansWithPricingSystems,
simulateAppStoreProduct,
}: Props) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
const { privateGameTemplateListingDatas } = React.useContext(
PrivateGameTemplateStoreContext
);
const { creditsPackageListingDatas } = React.useContext(
CreditsPackageStoreContext
);
const { bundleListingDatas } = React.useContext(BundleStoreContext);
const { privateAssetPackListingDatas } = React.useContext(AssetStoreContext);
const { listedCourses } = React.useContext(CourseStoreContext);
const authenticatedUser = React.useContext(AuthenticatedUserContext);
const { receivedBundles, bundlePurchases } = authenticatedUser;
const [
purchasingBundleListingData,
setPurchasingBundleListingData,
] = React.useState<?BundleListingData>(null);
const { isMobile, isMediumScreen } = useResponsiveWindowSize();
const [
isRedemptionCodesDialogOpen,
setIsRedemptionCodesDialogOpen,
] = React.useState<boolean>(false);
const shouldUseOrSimulateAppStoreProduct =
shouldUseAppStoreProduct() || simulateAppStoreProduct;
const userBundlePurchaseUsageType = React.useMemo(
() =>
getUserProductPurchaseUsageType({
productId: bundleListingData ? bundleListingData.id : null,
receivedProducts: receivedBundles,
productPurchases: bundlePurchases,
allProductListingDatas: bundleListingDatas,
}),
[bundlePurchases, bundleListingData, bundleListingDatas, receivedBundles]
);
const isAlreadyReceived = !!userBundlePurchaseUsageType;
const productListingDatasIncludedInBundle = React.useMemo(
() =>
bundleListingData &&
bundleListingDatas &&
privateGameTemplateListingDatas &&
privateAssetPackListingDatas &&
listedCourses &&
creditsPackageListingDatas
? getProductsIncludedInBundle({
productListingDatas: [
...bundleListingDatas,
...privateGameTemplateListingDatas,
...privateAssetPackListingDatas,
...listedCourses,
...creditsPackageListingDatas,
],
productListingData: bundleListingData,
})
: null,
[
bundleListingData,
bundleListingDatas,
privateGameTemplateListingDatas,
privateAssetPackListingDatas,
listedCourses,
creditsPackageListingDatas,
]
);
const subscriptionPlansWithPricingSystems = getSubscriptionPlansWithPricingSystems();
const redemptionCodesIncludedInBundle = React.useMemo(
() =>
bundleListingData
? bundleListingData.includedRedemptionCodes || []
: null,
[bundleListingData]
);
const includedCreditsAmount = React.useMemo(
() =>
(bundleListingData.includedListableProducts || [])
.filter(product => product.productType === 'CREDIT_PACKAGE')
.reduce(
(total, product) => total + getCreditsAmountFromId(product.productId),
0
),
[bundleListingData]
);
const onClickBuy = React.useCallback(
async () => {
if (!bundle) return;
if (isAlreadyReceived) {
return;
}
try {
const price = bundleListingData.prices.find(
price => price.usageType === 'default'
);
sendBundleBuyClicked({
bundleId: bundle.id,
bundleName: bundle.name,
bundleTag: bundle.tag,
currency: price ? price.currency : undefined,
usageType: 'default',
});
setPurchasingBundleListingData(bundleListingData);
} catch (e) {
console.warn('Unable to send event', e);
}
},
[bundle, bundleListingData, isAlreadyReceived]
);
return (
<I18n>
{({ i18n }) => (
<>
<SectionRow>
<Paper background="dark" variant="outlined" style={{ padding: 16 }}>
<ColumnStackLayout noMargin>
<ResponsiveLineStackLayout
noMargin
alignItems="center"
justifyContent="flex-start"
forceMobileLayout={isMediumScreen}
expand
>
<div style={styles.imageContainer}>
<img
src={bundle.previewImageUrls[0]}
style={styles.image}
alt=""
/>
</div>
<ColumnStackLayout expand justifyContent="flex-start">
<Text size="title" noMargin style={styles.title}>
{selectMessageByLocale(i18n, bundle.nameByLocale)}
</Text>
<Line noMargin>
<Text noMargin>
{selectMessageByLocale(
i18n,
bundle.longDescriptionByLocale
)}
</Text>
</Line>
</ColumnStackLayout>
</ResponsiveLineStackLayout>
<ResponsiveLineStackLayout
expand
justifyContent="space-between"
forceMobileLayout={isMediumScreen}
>
{redemptionCodesIncludedInBundle &&
redemptionCodesIncludedInBundle.length > 0 && (
<ColumnStackLayout noMargin expand>
{redemptionCodesIncludedInBundle.map(
(includedRedemptionCode, index) => (
<LineStackLayout
noMargin
alignItems="center"
key={`${
includedRedemptionCode.givenSubscriptionPlanId
}-${index}`}
>
{getPlanIcon({
planId:
includedRedemptionCode.givenSubscriptionPlanId,
logoSize: 20,
})}
<Text>
<Trans>
{formatDurationOfRedemptionCode(
includedRedemptionCode.durationInDays
)}{' '}
of
{getPlanInferredNameFromId(
includedRedemptionCode.givenSubscriptionPlanId
)}
subscription included
</Trans>
</Text>
</LineStackLayout>
)
)}
{isAlreadyReceived && (
<Line noMargin>
<FlatButton
primary
label={<Trans>See my codes</Trans>}
onClick={() =>
setIsRedemptionCodesDialogOpen(true)
}
/>
</Line>
)}
</ColumnStackLayout>
)}
{includedCreditsAmount > 0 && (
<Column justifyContent="center" expand noMargin>
<LineStackLayout noMargin alignItems="center">
<Coin style={styles.coinIcon} />
<Text>
<Trans>
{includedCreditsAmount} credits included
</Trans>
</Text>
</LineStackLayout>
</Column>
)}
<ResponsiveDivider />
</ResponsiveLineStackLayout>
{!isAlreadyReceived && (
<Paper background="medium" style={{ padding: 16 }}>
{!!bundleListingData && (
<ResponsiveLineStackLayout
justifyContent="space-between"
noMargin
>
{!isMobile && !isMediumScreen && (
<Column noMargin justifyContent="center">
<LineStackLayout noMargin>
<Text noMargin color="secondary">
<span style={styles.discountedPrice}>
{renderEstimatedTotalPriceFormatted({
i18n,
bundleListingData,
productListingDatasIncludedInBundle,
redemptionCodesIncludedInBundle,
subscriptionPlansWithPricingSystems,
})}
</span>
</Text>
<div
style={{
color: gdevelopTheme.text.color.secondary,
}}
>
{renderProductPrice({
i18n,
productListingData: bundleListingData,
usageType: 'default',
})}
</div>
</LineStackLayout>
</Column>
)}
<ResponsiveLineStackLayout
noMargin
forceMobileLayout={isMediumScreen}
>
{!shouldUseOrSimulateAppStoreProduct && (
<SecureCheckout />
)}
<PurchaseProductButtons
i18n={i18n}
productListingData={bundleListingData}
selectedUsageType="default"
onUsageTypeChange={() => {}}
simulateAppStoreProduct={simulateAppStoreProduct}
isAlreadyReceived={isAlreadyReceived}
onClickBuy={onClickBuy}
onClickBuyWithCredits={() => {}}
/>
</ResponsiveLineStackLayout>
</ResponsiveLineStackLayout>
)}
</Paper>
)}
</ColumnStackLayout>
</Paper>
</SectionRow>
{!!purchasingBundleListingData && (
<BundlePurchaseDialog
bundleListingData={purchasingBundleListingData}
usageType="default"
onClose={() => setPurchasingBundleListingData(null)}
/>
)}
{isRedemptionCodesDialogOpen && (
<RedemptionCodesDialog
onClose={() => setIsRedemptionCodesDialogOpen(false)}
/>
)}
</>
)}
</I18n>
);
};
export default BundlePageHeader;

View File

@@ -131,6 +131,7 @@ type Props = {|
course: ?Course,
courseListingData: ?CourseListingData,
onClick?: () => void,
discountedPrice?: boolean,
|};
const CourseCard = ({
@@ -138,6 +139,7 @@ const CourseCard = ({
course,
courseListingData,
onClick,
discountedPrice,
}: Props) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
const specializationConfig = getSpecializationConfig(
@@ -255,6 +257,7 @@ const CourseCard = ({
usageType: 'default',
showBothPrices: 'column',
owned: !course.isLocked,
discountedPrice,
})}
</Line>
</div>

View File

@@ -39,6 +39,7 @@ import CoursePageHeader from './CoursePageHeader';
import Window from '../../../../Utils/Window';
import AuthenticatedUserContext from '../../../../Profile/AuthenticatedUserContext';
import { RatingBanner } from './RatingBanner';
import { selectMessageByLocale } from '../../../../Utils/i18n/MessageByLocale';
const styles = {
desktopContainer: { display: 'flex', gap: 16 },
@@ -353,8 +354,20 @@ const CoursePage = ({
</AlertMessage>
</Line>
)}
{course.introByLocale && (
<Line>
<AlertMessage kind="info" background="light">
{selectMessageByLocale(i18n, course.introByLocale)}
</AlertMessage>
</Line>
)}
{courseChapters.map((chapter: CourseChapter, index) => (
<ColumnStackLayout expand noOverflowParent noMargin>
<ColumnStackLayout
expand
noOverflowParent
noMargin
key={chapter.id}
>
{chapter.videoUrl ? (
<VideoBasedCourseChapterView
chapterIndex={index}

View File

@@ -276,9 +276,6 @@ const CoursePageHeader = ({
noMargin
forceMobileLayout={isMediumScreen}
>
{!shouldUseOrSimulateAppStoreProduct && (
<SecureCheckout />
)}
<PurchaseProductButtons
i18n={i18n}
productListingData={courseListingData}
@@ -295,6 +292,9 @@ const CoursePageHeader = ({
onWillBuyWithCredits(i18n)
}
/>
{!shouldUseOrSimulateAppStoreProduct && (
<SecureCheckout />
)}
</ResponsiveLineStackLayout>
</ResponsiveLineStackLayout>
)}

View File

@@ -129,7 +129,11 @@ const CoursesPage = ({
</SectionRow>
{!hidePremiumProducts && (
<SectionRow>
<BundlePreviewBanner onDisplayBundle={onSelectBundle} />
<BundlePreviewBanner
onDisplayBundle={onSelectBundle}
category="starter"
i18n={i18n}
/>
</SectionRow>
)}
{courses && listedCourses && courses.length > numberOfItemsOnOneRow && (
@@ -141,28 +145,72 @@ const CoursesPage = ({
cellHeight="auto"
spacing={ITEMS_SPACING * 2}
>
{courses.slice(numberOfItemsOnOneRow).map(course => {
const completion = getCourseCompletion(course.id);
const courseListingData = listedCourses.find(
listedCourse => listedCourse.id === course.id
);
return (
<GridListTile key={course.id}>
<CourseCard
course={course}
courseListingData={courseListingData}
completion={completion}
onClick={() => {
onSelectCourse(course.id);
}}
/>
</GridListTile>
);
})}
{courses
.slice(numberOfItemsOnOneRow, 2 * numberOfItemsOnOneRow)
.map(course => {
const completion = getCourseCompletion(course.id);
const courseListingData = listedCourses.find(
listedCourse => listedCourse.id === course.id
);
return (
<GridListTile key={course.id}>
<CourseCard
course={course}
courseListingData={courseListingData}
completion={completion}
onClick={() => {
onSelectCourse(course.id);
}}
/>
</GridListTile>
);
})}
</GridList>
</Line>
</SectionRow>
)}
{!hidePremiumProducts && (
<SectionRow>
<BundlePreviewBanner
onDisplayBundle={onSelectBundle}
category="premium"
i18n={i18n}
/>
</SectionRow>
)}
{courses &&
listedCourses &&
courses.length > 2 * numberOfItemsOnOneRow && (
<SectionRow>
<Line>
<GridList
cols={numberOfItemsOnOneRow}
style={styles.grid}
cellHeight="auto"
spacing={ITEMS_SPACING * 2}
>
{courses.slice(2 * numberOfItemsOnOneRow).map(course => {
const completion = getCourseCompletion(course.id);
const courseListingData = listedCourses.find(
listedCourse => listedCourse.id === course.id
);
return (
<GridListTile key={course.id}>
<CourseCard
course={course}
courseListingData={courseListingData}
completion={completion}
onClick={() => {
onSelectCourse(course.id);
}}
/>
</GridListTile>
);
})}
</GridList>
</Line>
</SectionRow>
)}
</SectionContainer>
)}
</I18n>

View File

@@ -240,7 +240,11 @@ const MainPage = ({
</SectionRow>
{!hidePremiumProducts && (
<SectionRow>
<BundlePreviewBanner onDisplayBundle={onSelectBundle} />
<BundlePreviewBanner
onDisplayBundle={onSelectBundle}
category="starter"
i18n={i18n}
/>
</SectionRow>
)}
<SectionRow>
@@ -252,7 +256,7 @@ const MainPage = ({
>
<Column noMargin>
<Text size="section-title">
<Trans>In-app tutorials</Trans>
<Trans>Free in-app tutorials</Trans>
</Text>
</Column>
<Column noMargin>

View File

@@ -26,13 +26,13 @@ import CoursesPage from './CoursesPage';
import { type LearnCategory } from './Utils';
import { type ExampleShortHeader } from '../../../../Utils/GDevelopServices/Example';
import { type SubscriptionPlanWithPricingSystems } from '../../../../Utils/GDevelopServices/Usage';
import BundlePage from './BundlePage';
import RouterContext from '../../../RouterContext';
import {
sendBundleInformationOpened,
sendCourseInformationOpened,
} from '../../../../Utils/Analytics/EventSender';
import { BundleStoreContext } from '../../../../AssetStore/Bundles/BundleStoreContext';
import BundleInformationPage from '../../../../AssetStore/Bundles/BundleInformationPage';
type Props = {|
selectInAppTutorial: (tutorialId: string) => void,
@@ -195,7 +195,7 @@ const LearnSection = ({
if (selectedBundleListingData) {
return (
<BundlePage
<BundleInformationPage
bundleListingData={selectedBundleListingData}
onBack={() => setSelectedBundleListingData(null)}
getSubscriptionPlansWithPricingSystems={

View File

@@ -65,7 +65,7 @@ type Props = {|
subtitleText?: React.Node,
customPaperStyle?: Object,
renderSubtitle?: () => React.Node,
backAction?: () => void,
backAction?: () => void | Promise<void>,
flexBody?: boolean,
renderFooter?: () => React.Node,
noScroll?: boolean,

View File

@@ -11,9 +11,11 @@ import AssetPackInstallDialog from '../../../../AssetStore/AssetPackInstallDialo
import { enumerateAssetStoreIds } from '../../../../AssetStore/EnumerateAssetStoreIds';
import { type PrivateGameTemplateListingData } from '../../../../Utils/GDevelopServices/Shop';
import { type Course } from '../../../../Utils/GDevelopServices/Asset';
import { type SubscriptionPlanWithPricingSystems } from '../../../../Utils/GDevelopServices/Usage';
import ErrorBoundary from '../../../../UI/ErrorBoundary';
import { getAssetShortHeadersToDisplay } from '../../../../AssetStore/AssetsList';
import { AssetStoreNavigatorContext } from '../../../../AssetStore/AssetStoreNavigator';
import { type CourseCompletion } from '../UseCourses';
type Props = {|
project: ?gdProject,
@@ -23,8 +25,11 @@ type Props = {|
) => void,
onOpenProfile: () => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
getSubscriptionPlansWithPricingSystems: () => Array<SubscriptionPlanWithPricingSystems> | null,
onCourseOpen: (courseId: string) => void,
receivedCourses?: ?Array<Course>,
courses?: ?Array<Course>,
getCourseCompletion: (courseId: string) => CourseCompletion | null,
|};
const StoreSection = ({
@@ -34,7 +39,10 @@ const StoreSection = ({
onOpenProfile,
onExtensionInstalled,
onCourseOpen,
courses,
receivedCourses,
getSubscriptionPlansWithPricingSystems,
getCourseCompletion,
}: Props) => {
const [
isAssetPackDialogInstallOpen,
@@ -89,8 +97,13 @@ const StoreSection = ({
}
displayPromotions
onOpenProfile={onOpenProfile}
courses={courses}
receivedCourses={receivedCourses}
onCourseOpen={onCourseOpen}
getSubscriptionPlansWithPricingSystems={
getSubscriptionPlansWithPricingSystems
}
getCourseCompletion={getCourseCompletion}
/>
{(openedAssetPack || openedAssetShortHeader) && (
<Line justifyContent="flex-end">

View File

@@ -0,0 +1,119 @@
// @flow
import * as React from 'react';
import { Trans } from '@lingui/macro';
import FlatButton from '../../../../../UI/FlatButton';
import Dialog, { DialogPrimaryButton } from '../../../../../UI/Dialog';
import { ColumnStackLayout } from '../../../../../UI/Layout';
import {
type User,
type EditUserChanges,
type UsernameAvailability,
} from '../../../../../Utils/GDevelopServices/User';
import LeftLoader from '../../../../../UI/LeftLoader';
import SemiControlledTextField from '../../../../../UI/SemiControlledTextField';
import { UsernameField } from '../../../../../Profile/UsernameField';
import AlertMessage from '../../../../../UI/AlertMessage';
type Props = {|
member: User,
onApply: (changes: EditUserChanges) => Promise<void>,
onClose: () => void,
isSaving: boolean,
error: ?Error,
|};
export const EditStudentDialog = ({
member,
onApply,
onClose,
isSaving,
error,
}: Props) => {
const [changes, setChanges] = React.useState<EditUserChanges | null>(null);
const [
usernameAvailability,
setUsernameAvailability,
] = React.useState<?UsernameAvailability>(null);
const [
isValidatingUsername,
setIsValidatingUsername,
] = React.useState<boolean>(false);
const canSave =
!usernameAvailability || (usernameAvailability.isAvailable && !!changes);
const triggerApply = React.useCallback(
async () => {
if (!canSave || !changes) return;
await onApply(changes);
},
[changes, canSave, onApply]
);
return (
<Dialog
open
title={<Trans>Edit student</Trans>}
actions={[
<FlatButton
key="close"
label={<Trans>Close</Trans>}
primary={false}
onClick={onClose}
disabled={isSaving}
id="close-button"
/>,
<LeftLoader isLoading={isSaving}>
<DialogPrimaryButton
key="apply"
primary
label={<Trans>Apply</Trans>}
onClick={triggerApply}
disabled={isSaving || !canSave}
id="apply-button"
/>
</LeftLoader>,
]}
onRequestClose={onClose}
onApply={triggerApply}
maxWidth="sm"
>
<ColumnStackLayout expand noMargin>
{error && (
<AlertMessage kind="error">
<Trans>
An error occurred while editing the student. Please try again.
</Trans>
</AlertMessage>
)}
<SemiControlledTextField
onChange={fullName => setChanges({ ...changes, fullName })}
value={
changes && typeof changes.fullName !== 'undefined'
? changes.fullName
: member.fullName || ''
}
disabled={isSaving}
fullWidth
commitOnBlur
floatingLabelText={<Trans>Full name</Trans>}
/>
<UsernameField
initialUsername={member.username}
value={
changes && typeof changes.username !== 'undefined'
? changes.username
: member.username || ''
}
onChange={(_, username) => setChanges({ ...changes, username })}
disabled={isSaving}
allowEmpty
onAvailabilityChecked={setUsernameAvailability}
onAvailabilityCheckLoading={setIsValidatingUsername}
isValidatingUsername={isValidatingUsername}
/>
</ColumnStackLayout>
</Dialog>
);
};

View File

@@ -3,7 +3,10 @@
import * as React from 'react';
import { t, Trans } from '@lingui/macro';
import Grid from '@material-ui/core/Grid';
import { type User } from '../../../../../Utils/GDevelopServices/User';
import {
type User,
type EditUserChanges,
} from '../../../../../Utils/GDevelopServices/User';
import Text from '../../../../../UI/Text';
import { LineStackLayout } from '../../../../../UI/Layout';
import Checkbox from '../../../../../UI/Checkbox';
@@ -12,9 +15,11 @@ import CheckboxChecked from '../../../../../UI/CustomSvgIcons/CheckboxChecked';
import AsyncSemiControlledTextField from '../../../../../UI/AsyncSemiControlledTextField';
import IconButton from '../../../../../UI/IconButton';
import Key from '../../../../../UI/CustomSvgIcons/Key';
import Edit from '../../../../../UI/CustomSvgIcons/Edit';
import { Line } from '../../../../../UI/Grid';
import { useResponsiveWindowSize } from '../../../../../UI/Responsive/ResponsiveWindowMeasurer';
import { textEllipsisStyle } from '../../../../../UI/TextEllipsis';
import { EditStudentDialog } from './EditStudentDialog';
const primaryTextArchivedOpacity = 0.6;
const primaryTextPlaceholderOpacity = 0.7;
@@ -47,6 +52,10 @@ type Props = {|
userId: string,
newPassword: string,
|}) => Promise<void>,
onEdit: ({|
editedUserId: string,
changes: EditUserChanges,
|}) => Promise<void>,
|};
const ManageStudentRow = ({
@@ -55,11 +64,18 @@ const ManageStudentRow = ({
isArchived,
onSelect,
onChangePassword,
onEdit,
}: Props) => {
const { isMobile } = useResponsiveWindowSize();
const [isEditingPassword, setIsEditingPassword] = React.useState<boolean>(
false
);
const [isSavingUser, setIsSavingUser] = React.useState<boolean>(false);
const [isEditingUser, setIsEditingUser] = React.useState<boolean>(false);
const [editedUserError, setEditedUserError] = React.useState<Error | null>(
null
);
const [
passwordEditionError,
setPasswordEditionError,
@@ -110,15 +126,30 @@ const ManageStudentRow = ({
uncheckedIcon={<CheckboxUnchecked />}
checkedIcon={<CheckboxChecked />}
/>
{member.username ? (
{member.username || member.fullName ? (
<Text
allowSelection
style={{
...textEllipsisStyle,
opacity: isArchived ? primaryTextArchivedOpacity : undefined,
}}
tooltip={[member.fullName, member.username]
.filter(Boolean)
.join(' - ')}
>
<b>{member.username}</b>
<b>
{member.fullName ? (
member.username ? (
<Trans>
{member.fullName} ({member.username})
</Trans>
) : (
member.fullName
)
) : (
member.username
)}
</b>
</Text>
) : (
<Text
@@ -136,6 +167,15 @@ const ManageStudentRow = ({
</i>
</Text>
)}
{!isArchived && (
<IconButton
size="small"
onClick={() => setIsEditingUser(true)}
tooltip={t`Change username or full name`}
>
<Edit fontSize="small" />
</IconButton>
)}
</LineStackLayout>
);
@@ -205,6 +245,31 @@ const ManageStudentRow = ({
</LineStackLayout>
);
const editDialog = isEditingUser && (
<EditStudentDialog
member={member}
isSaving={isSavingUser}
error={editedUserError}
onApply={async (changes: EditUserChanges) => {
try {
setEditedUserError(null);
setIsSavingUser(true);
await onEdit({ editedUserId: member.id, changes });
setIsEditingUser(false);
} catch (error) {
console.error('An error occurred while editing user:', error);
setEditedUserError(error);
} finally {
setIsSavingUser(false);
}
}}
onClose={() => {
setIsEditingUser(false);
setEditedUserError(null);
}}
/>
);
if (isMobile) {
return (
<>
@@ -217,21 +282,23 @@ const ManageStudentRow = ({
<Grid item xs={4} style={isMobile ? styles.mobileCell : styles.cell}>
{passwordCell}
</Grid>
{editDialog}
</>
);
}
return (
<>
<Grid item xs={5} style={isMobile ? styles.mobileCell : styles.cell}>
<Grid item xs={9} style={isMobile ? styles.mobileCell : styles.cell}>
<LineStackLayout noMargin alignItems="center">
{usernameCell}
{emailCell}
</LineStackLayout>
</Grid>
<Grid item xs={7} style={isMobile ? styles.mobileCell : styles.cell}>
<Grid item xs={3} style={isMobile ? styles.mobileCell : styles.cell}>
{passwordCell}
</Grid>
{editDialog}
</>
);
};

View File

@@ -56,6 +56,7 @@ import { selectMessageByLocale } from '../../../../../Utils/i18n/MessageByLocale
import TextButton from '../../../../../UI/TextButton';
import Chip from '../../../../../UI/Chip';
import { SubscriptionSuggestionContext } from '../../../../../Profile/Subscription/SubscriptionSuggestionContext';
import { type EditUserChanges } from '../../../../../Utils/GDevelopServices/User';
const styles = {
selectedMembersControlsContainer: {
@@ -324,6 +325,7 @@ const ManageEducationAccountDialog = ({ onClose }: Props) => {
onActivateMembers,
onSetAdmin,
onRefreshAdmins,
onEditUser,
} = React.useContext(TeamContext);
React.useEffect(
@@ -337,6 +339,20 @@ const ManageEducationAccountDialog = ({ onClose }: Props) => {
[credentialsCopySuccess]
);
const onEditTeamMember = React.useCallback(
async ({
editedUserId,
changes,
}: {|
editedUserId: string,
changes: EditUserChanges,
|}) => {
await onEditUser(editedUserId, changes);
await onRefreshMembers();
},
[onEditUser, onRefreshMembers]
);
const onChangeTeamMemberPassword = React.useCallback(
async ({
userId,
@@ -354,7 +370,7 @@ const ManageEducationAccountDialog = ({ onClose }: Props) => {
const onCopyActiveCredentials = React.useCallback(
() => {
if (!members) return;
let content = 'Username,Email,Password';
let content = 'Username,Full Name,Email,Password';
let membersToConsider = [];
if (selectedUserIds.length === 0) {
membersToConsider = members.filter(member => !member.deactivatedAt);
@@ -364,7 +380,7 @@ const ManageEducationAccountDialog = ({ onClose }: Props) => {
);
}
membersToConsider.forEach(member => {
content += `\n${member.username || ''},${
content += `\n${member.username || ''},${member.fullName || ''},${
member.email
},${member.password || ''}`;
});
@@ -673,12 +689,13 @@ const ManageEducationAccountDialog = ({ onClose }: Props) => {
<UserLine
key={adminUser.id}
username={adminUser.username}
fullName={adminUser.fullName}
email={adminUser.email}
level={null}
onDelete={() => onRemoveAdmin(adminUser.email)}
disabled={
(profile && adminUser.id === profile.id) ||
(adminEmailBeingRemoved &&
(!!adminEmailBeingRemoved &&
adminEmailBeingRemoved === adminUser.email)
}
/>
@@ -822,10 +839,10 @@ const ManageEducationAccountDialog = ({ onClose }: Props) => {
size="small"
tooltip={
selectedUserIds.length === 0
? t`Copy active credentials`
? t`Copy active credentials to CSV`
: t`Copy ${
selectedUserIds.length
} credentials`
} credentials to CSV`
}
disabled={
hasNoActiveTeamMembers &&
@@ -847,12 +864,12 @@ const ManageEducationAccountDialog = ({ onClose }: Props) => {
<Column>
{!isMobile && (
<GridList cols={2} cellHeight={'auto'}>
<Grid item xs={5}>
<Grid item xs={9}>
<Text style={{ opacity: 0.7 }}>
<Trans>Student</Trans>
</Text>
</Grid>
<Grid item xs={7}>
<Grid item xs={3}>
<Text style={{ opacity: 0.7 }}>
<Trans>Password</Trans>
</Text>
@@ -885,6 +902,7 @@ const ManageEducationAccountDialog = ({ onClose }: Props) => {
onChangePassword={
onChangeTeamMemberPassword
}
onEdit={onEditTeamMember}
isSelected={selectedUserIds.includes(
member.id
)}
@@ -966,6 +984,7 @@ const ManageEducationAccountDialog = ({ onClose }: Props) => {
onChangePassword={
onChangeTeamMemberPassword
}
onEdit={onEditTeamMember}
isSelected={selectedUserIds.includes(
member.id
)}

View File

@@ -117,9 +117,19 @@ const TeamMemberRow = ({
/>
) : (
<LineStackLayout noMargin alignItems="center">
{member.username && (
{(member.username || member.fullName) && (
<Text allowSelection noMargin>
{member.username}
{member.fullName ? (
member.username ? (
<Trans>
{member.fullName} ({member.username})
</Trans>
) : (
member.fullName
)
) : (
member.username
)}
</Text>
)}
<Text allowSelection noMargin color="secondary">

View File

@@ -5,6 +5,7 @@ import { type I18n as I18nType } from '@lingui/core';
import {
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from '../BaseEditor';
import {
type FileMetadataAndStorageProviderName,
@@ -178,6 +179,9 @@ export type HomePageEditorInterface = {|
onSceneEventsModifiedOutsideEditor: (
scene: SceneEventsOutsideEditorChanges
) => void,
onInstancesModifiedOutsideEditor: (
changes: InstancesOutsideEditorChanges
) => void,
|};
export const HomePage = React.memo<Props>(
@@ -486,6 +490,13 @@ export const HomePage = React.memo<Props>(
[]
);
const onInstancesModifiedOutsideEditor = React.useCallback(
(changes: InstancesOutsideEditorChanges) => {
// No thing to be done.
},
[]
);
React.useImperativeHandle(ref, () => ({
getProject,
updateToolbar,
@@ -494,6 +505,7 @@ export const HomePage = React.memo<Props>(
onSceneObjectEdited,
onSceneObjectsDeleted,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
}));
// As the homepage is never unmounted, we need to ensure the games platform
@@ -628,6 +640,11 @@ export const HomePage = React.memo<Props>(
? courses.filter(course => !course.isLocked)
: undefined
}
courses={courses}
getCourseCompletion={getCourseCompletion}
getSubscriptionPlansWithPricingSystems={
getSubscriptionPlansWithPricingSystems
}
/>
)}
{activeTab === 'team-view' &&

View File

@@ -4,6 +4,7 @@ import {
type RenderEditorContainerProps,
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from './BaseEditor';
import ResourcesEditor from '../../ResourcesEditor';
import { type ObjectWithContext } from '../../ObjectsList/EnumerateObjects';
@@ -50,6 +51,10 @@ export class ResourcesEditorContainer extends React.Component<RenderEditorContai
// No thing to be done.
}
onInstancesModifiedOutsideEditor(changes: InstancesOutsideEditorChanges) {
// No thing to be done.
}
componentDidUpdate(prevProps: RenderEditorContainerProps) {
if (
this.editor &&

View File

@@ -10,6 +10,7 @@ import {
type RenderEditorContainerProps,
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from './BaseEditor';
import { ProjectScopedContainersAccessor } from '../../InstructionOrExpression/EventsScope';
import { type ObjectWithContext } from '../../ObjectsList/EnumerateObjects';
@@ -98,6 +99,16 @@ export class SceneEditorContainer extends React.Component<RenderEditorContainerP
// No thing to be done.
}
onInstancesModifiedOutsideEditor(changes: InstancesOutsideEditorChanges) {
if (changes.scene !== this.getLayout()) {
return;
}
if (this.editor) {
this.editor.onInstancesModifiedOutsideEditor();
}
}
getLayout(): ?gdLayout {
const { project, projectItemName } = this.props;
if (

View File

@@ -172,16 +172,9 @@ export const openEditorTab = (
editor => editor.key === key
);
if (existingEditorId !== -1) {
return {
...state,
panes: {
...state.panes,
[paneIdentifier]: {
...pane,
currentTab: dontFocusTab ? pane.currentTab : existingEditorId,
},
},
};
return dontFocusTab
? { ...state }
: changeCurrentTab(state, paneIdentifier, existingEditorId);
}
}
@@ -203,7 +196,7 @@ export const openEditorTab = (
throw new Error(`Pane with identifier "${paneIdentifier}" is not valid.`);
}
return {
let newState = {
...state,
panes: {
...state.panes,
@@ -214,10 +207,14 @@ export const openEditorTab = (
key === 'start page'
? [editorTab, ...pane.editors]
: [...pane.editors, editorTab],
currentTab: dontFocusTab ? pane.currentTab : pane.editors.length,
currentTab: pane.currentTab,
},
},
};
if (!dontFocusTab) {
newState = changeCurrentTab(newState, paneIdentifier, pane.editors.length);
}
return newState;
};
export const changeCurrentTab = (
@@ -591,6 +588,7 @@ export const moveTabToPosition = (
else if (tabIsMovedFromLeftToRightOfCurrentTab) paneNewCurrentTab -= 1;
else if (tabIsMovedFromRightToLeftOfCurrentTab) paneNewCurrentTab += 1;
// The index changes but the tab is the same so there is no need to call changeCurrentTab.
return {
...editorTabsState,
panes: {

View File

@@ -24,7 +24,10 @@ import {
saveUiSettings,
} from './EditorTabs/EditorTabsHandler';
import { type PreviewState } from './PreviewState';
import { type SceneEventsOutsideEditorChanges } from './EditorContainers/BaseEditor';
import {
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from './EditorContainers/BaseEditor';
import { type ResourceManagementProps } from '../ResourcesList/ResourceSource';
import { type HotReloadPreviewButtonProps } from '../HotReload/HotReloadPreviewButton';
import { type GamesList } from '../GameDashboard/UseGamesList';
@@ -206,6 +209,9 @@ export type EditorTabsPaneCommonProps = {|
onSceneEventsModifiedOutsideEditor: (
changes: SceneEventsOutsideEditorChanges
) => void,
onInstancesModifiedOutsideEditor: (
changes: InstancesOutsideEditorChanges
) => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
gamesList: GamesList,
@@ -294,6 +300,7 @@ const EditorTabsPane = React.forwardRef<Props, {||}>((props, ref) => {
onSceneObjectEdited,
onSceneObjectsDeleted,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
onExtensionInstalled,
gamesList,
setEditorTabs,
@@ -681,6 +688,7 @@ const EditorTabsPane = React.forwardRef<Props, {||}>((props, ref) => {
onSceneObjectEdited: onSceneObjectEdited,
onSceneObjectsDeleted: onSceneObjectsDeleted,
onSceneEventsModifiedOutsideEditor: onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor: onInstancesModifiedOutsideEditor,
onExtensionInstalled: onExtensionInstalled,
gamesList,
gamesPlatformFrameTools,

View File

@@ -58,6 +58,7 @@ import { renderResourcesEditorContainer } from './EditorContainers/ResourcesEdit
import {
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
} from './EditorContainers/BaseEditor';
import { type Exporter } from '../ExportAndShare/ShareDialog';
import ResourcesLoader from '../ResourcesLoader/index';
@@ -2431,6 +2432,18 @@ const MainFrame = (props: Props) => {
[state.editorTabs]
);
const onInstancesModifiedOutsideEditor = React.useCallback(
(changes: InstancesOutsideEditorChanges) => {
for (const editor of getAllEditorTabs(state.editorTabs)) {
const { editorRef } = editor;
if (editorRef) {
editorRef.onInstancesModifiedOutsideEditor(changes);
}
}
},
[state.editorTabs]
);
const _onProjectItemModified = () => {
triggerUnsavedChanges();
forceUpdate();
@@ -3872,6 +3885,7 @@ const MainFrame = (props: Props) => {
onSceneObjectEdited: onSceneObjectEdited,
onSceneObjectsDeleted: onSceneObjectsDeleted,
onSceneEventsModifiedOutsideEditor: onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor: onInstancesModifiedOutsideEditor,
onExtensionInstalled: onExtensionInstalled,
gamesList: gamesList,
};

View File

@@ -366,6 +366,7 @@ export const CompactObjectPropertiesEditor = ({
} = useManageObjectBehaviors({
project,
object,
isChildObject: !layout,
eventsFunctionsExtension,
onUpdate: forceUpdate,
onBehaviorsUpdated: forceUpdate,

View File

@@ -326,6 +326,7 @@ const InnerDialog = (props: InnerDialogProps) => {
{currentTab === 'behaviors' && (
<BehaviorsEditor
object={object}
isChildObject={!!eventsBasedObject}
project={project}
eventsFunctionsExtension={eventsFunctionsExtension}
resourceManagementProps={resourceManagementProps}

View File

@@ -4,7 +4,6 @@ import {
type Profile,
type LoginForm,
type RegisterForm,
type PatchUserPayload,
type ForgotPasswordForm,
type AuthError,
type IdentityProvider,
@@ -13,7 +12,10 @@ import { type PreferencesValues } from '../MainFrame/Preferences/PreferencesCont
import { type CloudProjectWithUserAccessInfo } from '../Utils/GDevelopServices/Project';
import { User as FirebaseUser } from 'firebase/auth';
import { type Badge, type Achievement } from '../Utils/GDevelopServices/Badge';
import { type Recommendation } from '../Utils/GDevelopServices/User';
import {
type Recommendation,
type EditUserChanges,
} from '../Utils/GDevelopServices/User';
import { type Notification } from '../Utils/GDevelopServices/Notification';
import {
type Limits,
@@ -62,7 +64,7 @@ export type AuthenticatedUser = {|
preferences: PreferencesValues
) => Promise<void>,
onEditProfile: (
payload: PatchUserPayload,
changes: EditUserChanges,
preferences: PreferencesValues
) => Promise<void>,
onResetPassword: ForgotPasswordForm => Promise<void>,

View File

@@ -8,6 +8,8 @@ import {
getUserEarningsBalance,
} from '../Utils/GDevelopServices/Usage';
import {
editUser,
type EditUserChanges,
getUserBadges,
listDefaultRecommendations,
listRecommendations,
@@ -17,7 +19,6 @@ import { getAchievements } from '../Utils/GDevelopServices/Badge';
import Authentication, {
type LoginForm,
type RegisterForm,
type PatchUserPayload,
type ChangeEmailForm,
type AuthError,
type ForgotPasswordForm,
@@ -622,10 +623,11 @@ export default class AuthenticatedUserProvider extends React.Component<
if (!userProfile.isCreator) {
// If the user is not a creator, then update the profile to say they now are.
try {
await authentication.editUserProfile(
authentication.getAuthorizationHeader,
{ isCreator: true }
);
await editUser(authentication.getAuthorizationHeader, {
editedUserId: userProfile.id,
userId: userProfile.id,
changes: { isCreator: true },
});
} catch (error) {
// Catch the error so that the user profile is still fetched.
console.error('Error while updating the user profile:', error);
@@ -1206,11 +1208,13 @@ export default class AuthenticatedUserProvider extends React.Component<
};
_doEdit = async (
payload: PatchUserPayload,
payload: EditUserChanges,
preferences: PreferencesValues
) => {
const { authentication } = this.props;
if (!authentication) return;
const { profile } = this.state.authenticatedUser;
if (!profile) return;
this.setState({
editInProgress: true,
@@ -1218,9 +1222,10 @@ export default class AuthenticatedUserProvider extends React.Component<
});
this._automaticallyUpdateUserProfile = false;
try {
await authentication.editUserProfile(
authentication.getAuthorizationHeader,
{
await editUser(authentication.getAuthorizationHeader, {
editedUserId: profile.id,
userId: profile.id,
changes: {
username: payload.username,
description: payload.description,
getGameStatsEmail: payload.getGameStatsEmail,
@@ -1231,8 +1236,8 @@ export default class AuthenticatedUserProvider extends React.Component<
githubUsername: payload.githubUsername,
communityLinks: payload.communityLinks,
survey: payload.survey,
}
);
},
});
await this._fetchUserProfileWithoutThrowingErrors();
} catch (apiCallError) {
this.setState({ apiCallError });
@@ -1625,9 +1630,9 @@ export default class AuthenticatedUserProvider extends React.Component<
badges={this.state.authenticatedUser.badges}
subscription={this.state.authenticatedUser.subscription}
onClose={() => this.openEditProfileDialog(false)}
onEdit={async form => {
onEdit={async changes => {
try {
await this._doEdit(form, this.props.preferencesValues);
await this._doEdit(changes, this.props.preferencesValues);
this.openEditProfileDialog(false);
} catch (error) {
// Ignore errors, we will let the user retry in their profile.

View File

@@ -207,7 +207,6 @@ const CreateAccountDialog = ({
onChangeOptInNewsletterEmail={setGetNewsletterEmail}
createAccountInProgress={createAccountInProgress}
error={error}
usernameAvailability={usernameAvailability}
onChangeUsernameAvailability={setUsernameAvailability}
isValidatingUsername={isValidatingUsername}
onChangeIsValidatingUsername={setIsValidatingUsername}

View File

@@ -60,7 +60,6 @@ type Props = {|
onChangeUsername: string => void,
optInNewsletterEmail: boolean,
onChangeOptInNewsletterEmail: boolean => void,
usernameAvailability: ?UsernameAvailability,
onChangeUsernameAvailability: (?UsernameAvailability) => void,
isValidatingUsername: boolean,
onChangeIsValidatingUsername: boolean => void,
@@ -80,7 +79,6 @@ const CreateAccountForm = ({
onChangeUsername,
optInNewsletterEmail,
onChangeOptInNewsletterEmail,
usernameAvailability,
onChangeUsernameAvailability,
isValidatingUsername,
onChangeIsValidatingUsername,

View File

@@ -7,7 +7,6 @@ import { type MessageDescriptor } from '../Utils/i18n/MessageDescriptor.flow';
import FlatButton from '../UI/FlatButton';
import Dialog, { DialogPrimaryButton } from '../UI/Dialog';
import {
type EditForm,
type AuthError,
type Profile,
type UpdateGitHubStarResponse,
@@ -16,6 +15,7 @@ import {
type UpdateYoutubeSubscriptionResponse,
} from '../Utils/GDevelopServices/Authentication';
import {
type EditUserChanges,
communityLinksConfig,
donateLinkConfig,
discordUsernameConfig,
@@ -59,7 +59,7 @@ export type EditProfileDialogProps = {|
badges: ?Array<Badge>,
subscription: ?Subscription,
onClose: () => void,
onEdit: (form: EditForm) => Promise<void>,
onEdit: (form: EditUserChanges) => Promise<void>,
onUpdateGitHubStar: (
githubUsername: string
) => Promise<UpdateGitHubStarResponse>,

View File

@@ -226,6 +226,25 @@ export const getPlanInferredNameFromId = (planId: string): string => {
}
};
export const planIdSortingFunction = (
planIdA: string,
planIdB: string
): number => {
const planOrder = [
'gdevelop_free',
'gdevelop_indie',
'gdevelop_silver',
'gdevelop_gold',
'gdevelop_pro',
'gdevelop_education',
'gdevelop_startup',
'gdevelop_enterprise',
];
const indexA = planOrder.indexOf(planIdA);
const indexB = planOrder.indexOf(planIdB);
return indexA - indexB;
};
export const getPlanIcon = ({
planId,
logoSize,

View File

@@ -2,39 +2,24 @@
import * as React from 'react';
import { I18n } from '@lingui/react';
import Text from '../../../UI/Text';
import { Column, LargeSpacer, Line, Spacer } from '../../../UI/Grid';
import {
type SubscriptionPlanWithPricingSystems,
type SubscriptionPlanPricingSystem,
EDUCATION_PLAN_MAX_SEATS,
EDUCATION_PLAN_MIN_SEATS,
getSummarizedSubscriptionPlanFeatures,
} from '../../../Utils/GDevelopServices/Usage';
import { selectMessageByLocale } from '../../../Utils/i18n/MessageByLocale';
import { getPlanIcon } from '../PlanCard';
import RedemptionCodeIcon from '../../../UI/CustomSvgIcons/RedemptionCode';
import {
ColumnStackLayout,
LineStackLayout,
ResponsiveLineStackLayout,
} from '../../../UI/Layout';
import { t, Trans } from '@lingui/macro';
import Link from '../../../UI/Link';
import Window from '../../../Utils/Window';
import { Trans } from '@lingui/macro';
import FlatButton from '../../../UI/FlatButton';
import GDevelopThemeContext from '../../../UI/Theme/GDevelopThemeContext';
import CheckCircleFilled from '../../../UI/CustomSvgIcons/CheckCircleFilled';
import ShieldChecked from '../../../UI/CustomSvgIcons/ShieldChecked';
import classes from './PromotionSubscriptionPlan.module.css';
import Paper from '../../../UI/Paper';
import RaisedButton from '../../../UI/RaisedButton';
import LeftLoader from '../../../UI/LeftLoader';
import { FormControlLabel, Radio, RadioGroup } from '@material-ui/core';
import DiscountFlame from '../../../UI/HotMessage/DiscountFlame';
import ThumbsUp from '../../../UI/CustomSvgIcons/ThumbsUp';
import { useResponsiveWindowSize } from '../../../UI/Responsive/ResponsiveWindowMeasurer';
import SemiControlledTextField from '../../../UI/SemiControlledTextField';
import CircledClose from '../../../UI/CustomSvgIcons/CircledClose';
import SubscriptionPlanTableSummary from './SubscriptionPlanTableSummary';
import SubscriptionPlanPricingSummary from './SubscriptionPlanPricingSummary';
const styles = {
simpleSizeContainer: {
@@ -49,65 +34,6 @@ const styles = {
justifyContent: 'center',
alignItems: 'center',
},
summarizeFeatureRow: {
paddingTop: 4,
paddingBottom: 4,
},
tableRightItemContainer: {
width: 120,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
bulletText: { flex: 1 },
bulletIcon: { width: 20, height: 20 },
paper: { flex: 1, zIndex: 2, padding: 16 },
descriptionContainer: { minHeight: 70 }, // Keep height the same for 1 or 2 lines.
discountContainer: {
padding: '4px 8px',
borderRadius: 4,
display: 'flex',
alignItems: 'center',
},
radioGroup: { flex: 1 },
formControlLabel: {
borderRadius: 4,
// Override MUI margins
marginLeft: 0,
marginRight: 0,
cursor: 'default',
},
discountedPrice: { textDecoration: 'line-through' },
unlimitedContainer: {
padding: '4px 8px',
borderRadius: 4,
display: 'flex',
alignItems: 'center',
color: 'black',
},
};
const formatPriceWithCurrency = (amountInCents: number, currency: string) => {
if (currency === 'USD') {
return `$${amountInCents / 100}`;
}
return `${amountInCents / 100}${currency === 'EUR' ? '€' : currency}`;
};
const getYearlyDiscountDisplayText = (
monthlyPricingSystem: SubscriptionPlanPricingSystem,
yearlyPricingSystem: SubscriptionPlanPricingSystem
): string | null => {
return (
'-' +
((
100 -
(yearlyPricingSystem.amountInCents /
(monthlyPricingSystem.amountInCents * 12)) *
100
).toFixed(0) +
'%')
);
};
const PromotionSubscriptionPlan = ({
@@ -132,39 +58,6 @@ const PromotionSubscriptionPlan = ({
const gdevelopTheme = React.useContext(GDevelopThemeContext);
const [period, setPeriod] = React.useState<'year' | 'month'>('year');
const planIcon = getPlanIcon({
planId: subscriptionPlanWithPricingSystems.id,
logoSize: 12,
});
const selectedPricingSystem = subscriptionPlanWithPricingSystems.pricingSystems.find(
pricingSystem => pricingSystem.period === period
);
const yearlyPlanPrice = subscriptionPlanWithPricingSystems.pricingSystems.find(
price => price.period === 'year'
);
const monthlyPlanPrice = subscriptionPlanWithPricingSystems.pricingSystems.find(
price => price.period === 'month'
);
if (!selectedPricingSystem || !yearlyPlanPrice || !monthlyPlanPrice) {
console.error(
'No pricing system found for period',
period,
'in',
subscriptionPlanWithPricingSystems
);
return null;
}
const yearlyPriceInCentsWithMonthlyPlan = Math.floor(
monthlyPlanPrice.amountInCents * 12
);
const yearlyDiscountDisplayText = getYearlyDiscountDisplayText(
monthlyPlanPrice,
yearlyPlanPrice
);
return (
<I18n>
{({ i18n }) => (
@@ -176,292 +69,25 @@ const PromotionSubscriptionPlan = ({
: styles.simpleSizeContainer
}
>
<Column justifyContent="center" noMargin>
<div
style={{
backgroundColor: gdevelopTheme.paper.backgroundColor.light,
}}
>
<Line alignItems="center" justifyContent="flex-end" noMargin>
<div style={styles.tableRightItemContainer}>
<Text size="sub-title">
{selectMessageByLocale(
i18n,
subscriptionPlanWithPricingSystems.nameByLocale
)}{' '}
</Text>
</div>
</Line>
</div>
{getSummarizedSubscriptionPlanFeatures(
i18n,
<SubscriptionPlanTableSummary
subscriptionPlanWithPricingSystems={
subscriptionPlanWithPricingSystems
).map((summarizedFeature, index) => (
<Column key={index} noMargin>
<div
style={{
...styles.summarizeFeatureRow,
borderTop:
index !== 0 &&
`1px solid ${gdevelopTheme.listItem.separatorColor}`,
}}
>
<Line
noMargin
alignItems="center"
justifyContent="space-between"
>
<Text style={styles.bulletText}>
{summarizedFeature.displayedFeatureName}
</Text>
<div style={styles.tableRightItemContainer}>
{summarizedFeature.enabled === 'yes' ? (
<CheckCircleFilled
style={{
...styles.bulletIcon,
color: gdevelopTheme.message.valid,
}}
/>
) : summarizedFeature.enabled === 'no' ? (
<CircledClose style={styles.bulletIcon} />
) : summarizedFeature.unlimited ? (
<div
style={{
...styles.unlimitedContainer,
backgroundColor: gdevelopTheme.message.valid,
}}
>
<Text noMargin color="inherit">
<Trans>Unlimited</Trans>
</Text>
</div>
) : (
<Text>{summarizedFeature.description}</Text>
)}
</div>
</Line>
</div>
</Column>
))}
<LargeSpacer />
<Line noMargin justifyContent="center">
<Text size="body" color="secondary">
<Trans>
Compare all the advantages of the different plans in this{' '}
<Link
href="https://gdevelop.io/pricing#feature-comparison"
onClick={() =>
Window.openExternalURL(
'https://gdevelop.io/pricing#feature-comparison'
)
}
>
big feature comparison table
</Link>
.
</Trans>
</Text>
</Line>
</Column>
}
/>
</div>
<div style={styles.simpleSizeContainer}>
<ColumnStackLayout expand noMargin>
<div className={classes.choosePlanContainer}>
<Paper background="dark" style={styles.paper}>
<ColumnStackLayout>
<Line alignItems="center" justifyContent="center">
{planIcon}
<Text size="block-title">
<span style={{ textTransform: 'uppercase' }}>
<b>
{selectMessageByLocale(
i18n,
subscriptionPlanWithPricingSystems.nameByLocale
)}
</b>
</span>
</Text>
</Line>
<Text size="section-title" noMargin align="center">
<div style={styles.descriptionContainer}>
{selectMessageByLocale(
i18n,
subscriptionPlanWithPricingSystems.descriptionByLocale
)}
</div>
</Text>
{subscriptionPlanWithPricingSystems.id ===
'gdevelop_education' && (
<ColumnStackLayout key="options" expand noMargin>
<SemiControlledTextField
value={seatsCount.toString()}
floatingLabelFixed
fullWidth
floatingLabelText={<Trans>Number of seats</Trans>}
commitOnBlur
type="number"
onChange={value => {
const newValue = parseInt(value);
setSeatsCount(
Math.min(
EDUCATION_PLAN_MAX_SEATS,
Math.max(
Number.isNaN(newValue)
? EDUCATION_PLAN_MIN_SEATS
: newValue,
EDUCATION_PLAN_MIN_SEATS
)
)
);
}}
min={EDUCATION_PLAN_MIN_SEATS}
max={EDUCATION_PLAN_MAX_SEATS}
step={1}
helperMarkdownText={i18n._(
t`As a teacher, you will use one seat in the plan so make sure to include yourself!`
)}
/>
</ColumnStackLayout>
)}
<Line noMargin expand>
<RadioGroup
value={period}
onChange={event => {
setPeriod(event.target.value);
}}
style={styles.radioGroup}
>
<FormControlLabel
style={{
...styles.formControlLabel,
backgroundColor:
period === 'year'
? gdevelopTheme.paper.backgroundColor.light
: gdevelopTheme.paper.backgroundColor.medium,
}}
value="year"
control={
<Radio color="secondary" disabled={disabled} />
}
label={
<Line>
<Column>
<Text noMargin color="inherit" size="sub-title">
{!yearlyPlanPrice.isPerUser ? (
<Trans>
Yearly,
{formatPriceWithCurrency(
yearlyPlanPrice.amountInCents,
yearlyPlanPrice.currency
)}
</Trans>
) : (
<Trans>
Yearly,
{formatPriceWithCurrency(
yearlyPlanPrice.amountInCents,
yearlyPlanPrice.currency
)}{' '}
per seat
</Trans>
)}
</Text>
<Text color="secondary" noMargin>
<Trans>
Instead of{' '}
<span style={styles.discountedPrice}>
{formatPriceWithCurrency(
yearlyPriceInCentsWithMonthlyPlan,
yearlyPlanPrice.currency
)}
</span>
</Trans>
</Text>
</Column>
<Column
alignItems="center"
justifyContent="center"
>
<span
style={{
...styles.discountContainer,
backgroundColor:
gdevelopTheme.message.hot.backgroundColor,
color: gdevelopTheme.message.hot.color,
}}
>
<DiscountFlame fontSize="small" />
<Spacer />
<Text color="inherit" noMargin>
{yearlyDiscountDisplayText}
</Text>
</span>
</Column>
</Line>
}
/>
<Spacer />
<FormControlLabel
style={{
...styles.formControlLabel,
backgroundColor:
period === 'month'
? gdevelopTheme.paper.backgroundColor.light
: gdevelopTheme.paper.backgroundColor.medium,
}}
value="month"
control={
<Radio color="secondary" disabled={disabled} />
}
label={
<Line>
<Column>
<Text noMargin size="sub-title" color="inherit">
{!monthlyPlanPrice.isPerUser ? (
<Trans>
Monthly,
{formatPriceWithCurrency(
monthlyPlanPrice.amountInCents,
monthlyPlanPrice.currency
)}
</Trans>
) : (
<Trans>
Monthly,
{formatPriceWithCurrency(
monthlyPlanPrice.amountInCents,
monthlyPlanPrice.currency
)}{' '}
per seat
</Trans>
)}
</Text>
</Column>
</Line>
}
/>
</RadioGroup>
</Line>
<Line alignItems="center" justifyContent="center">
<RaisedButton
color="premium"
key="upgrade"
disabled={disabled}
label={
<LeftLoader isLoading={disabled}>
<Text size="block-title" color="inherit">
<Trans>Choose this plan</Trans>
</Text>
</LeftLoader>
}
onClick={() => onClickChoosePlan(selectedPricingSystem)}
size="large"
fullWidth
/>
</Line>
</ColumnStackLayout>
</Paper>
</div>
<SubscriptionPlanPricingSummary
subscriptionPlanWithPricingSystems={
subscriptionPlanWithPricingSystems
}
disabled={disabled}
onClickChoosePlan={onClickChoosePlan}
seatsCount={seatsCount}
setSeatsCount={setSeatsCount}
period={period}
setPeriod={setPeriod}
/>
<LineStackLayout justifyContent="center" alignItems="center">
<ShieldChecked style={{ color: gdevelopTheme.message.valid }} />
<Text color="secondary">

View File

@@ -0,0 +1,367 @@
// @flow
import * as React from 'react';
import { I18n } from '@lingui/react';
import Text from '../../../UI/Text';
import { Column, Line, Spacer } from '../../../UI/Grid';
import {
type SubscriptionPlanWithPricingSystems,
type SubscriptionPlanPricingSystem,
EDUCATION_PLAN_MAX_SEATS,
EDUCATION_PLAN_MIN_SEATS,
} from '../../../Utils/GDevelopServices/Usage';
import { selectMessageByLocale } from '../../../Utils/i18n/MessageByLocale';
import { getPlanIcon } from '../PlanCard';
import { ColumnStackLayout } from '../../../UI/Layout';
import { t, Trans } from '@lingui/macro';
import GDevelopThemeContext from '../../../UI/Theme/GDevelopThemeContext';
import classes from './SubscriptionPlanPricingSummary.module.css';
import Paper from '../../../UI/Paper';
import RaisedButton from '../../../UI/RaisedButton';
import LeftLoader from '../../../UI/LeftLoader';
import { FormControlLabel, Radio, RadioGroup } from '@material-ui/core';
import DiscountFlame from '../../../UI/HotMessage/DiscountFlame';
import SemiControlledTextField from '../../../UI/SemiControlledTextField';
import Chip from '../../../UI/Chip';
const styles = {
paper: {
display: 'flex',
alignItems: 'center',
flex: 1,
zIndex: 2,
padding: 16,
},
descriptionContainer: { minHeight: 70 }, // Keep height the same for 1 or 2 lines.
discountContainer: {
padding: '4px 8px',
borderRadius: 4,
display: 'flex',
alignItems: 'center',
},
radioGroup: { flex: 1 },
formControlLabel: {
borderRadius: 4,
// Override MUI margins
marginLeft: 0,
marginRight: 0,
cursor: 'default',
},
discountedPrice: { textDecoration: 'line-through' },
discountChip: { height: 24, backgroundColor: '#F03F18', color: 'white' },
};
const formatPriceWithCurrency = (amountInCents: number, currency: string) => {
if (currency === 'USD') {
return `$${amountInCents / 100}`;
}
return `${amountInCents / 100}${currency === 'EUR' ? '€' : currency}`;
};
const getYearlyDiscountDisplayText = (
monthlyPricingSystem: SubscriptionPlanPricingSystem,
yearlyPricingSystem: SubscriptionPlanPricingSystem
): string | null => {
return (
'-' +
((
100 -
(yearlyPricingSystem.amountInCents /
(monthlyPricingSystem.amountInCents * 12)) *
100
).toFixed(0) +
'%')
);
};
const SubscriptionPlanPricingSummary = ({
subscriptionPlanWithPricingSystems,
disabled,
onClickChoosePlan,
seatsCount,
setSeatsCount,
period,
setPeriod,
onlyShowDiscountedPrice,
}: {|
subscriptionPlanWithPricingSystems: SubscriptionPlanWithPricingSystems,
disabled?: boolean,
onClickChoosePlan: (
pricingSystem: SubscriptionPlanPricingSystem
) => Promise<void>,
seatsCount: number,
setSeatsCount: (seatsCount: number) => void,
period: 'year' | 'month',
setPeriod: ('year' | 'month') => void,
onlyShowDiscountedPrice?: boolean,
|}) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
const planIcon = getPlanIcon({
planId: subscriptionPlanWithPricingSystems.id,
logoSize: 12,
});
const selectedPricingSystem = subscriptionPlanWithPricingSystems.pricingSystems.find(
pricingSystem => pricingSystem.period === period
);
const yearlyPlanPrice = subscriptionPlanWithPricingSystems.pricingSystems.find(
price => price.period === 'year'
);
const monthlyPlanPrice = subscriptionPlanWithPricingSystems.pricingSystems.find(
price => price.period === 'month'
);
if (!selectedPricingSystem || !yearlyPlanPrice || !monthlyPlanPrice) {
console.error(
'No pricing system found for period',
period,
'in',
subscriptionPlanWithPricingSystems
);
return null;
}
const yearlyPriceInCentsWithMonthlyPlan = Math.floor(
monthlyPlanPrice.amountInCents * 12
);
const yearlyDiscountDisplayText = getYearlyDiscountDisplayText(
monthlyPlanPrice,
yearlyPlanPrice
);
return (
<I18n>
{({ i18n }) => (
<div className={classes.choosePlanContainer}>
<Paper background="dark" style={styles.paper}>
<ColumnStackLayout>
<Line alignItems="center" justifyContent="center">
{planIcon}
<Text size="block-title">
<span style={{ textTransform: 'uppercase' }}>
<b>
{selectMessageByLocale(
i18n,
subscriptionPlanWithPricingSystems.nameByLocale
)}
</b>
</span>
</Text>
</Line>
<Text size="section-title" noMargin align="center">
<div style={styles.descriptionContainer}>
{selectMessageByLocale(
i18n,
subscriptionPlanWithPricingSystems.descriptionByLocale
)}
</div>
</Text>
{subscriptionPlanWithPricingSystems.id === 'gdevelop_education' &&
!onlyShowDiscountedPrice && (
<ColumnStackLayout key="options" expand noMargin>
<SemiControlledTextField
value={seatsCount.toString()}
floatingLabelFixed
fullWidth
floatingLabelText={<Trans>Number of seats</Trans>}
commitOnBlur
type="number"
onChange={value => {
const newValue = parseInt(value);
setSeatsCount(
Math.min(
EDUCATION_PLAN_MAX_SEATS,
Math.max(
Number.isNaN(newValue)
? EDUCATION_PLAN_MIN_SEATS
: newValue,
EDUCATION_PLAN_MIN_SEATS
)
)
);
}}
min={EDUCATION_PLAN_MIN_SEATS}
max={EDUCATION_PLAN_MAX_SEATS}
step={1}
helperMarkdownText={i18n._(
t`As a teacher, you will use one seat in the plan so make sure to include yourself!`
)}
/>
</ColumnStackLayout>
)}
{!onlyShowDiscountedPrice && (
<Line noMargin expand>
<RadioGroup
value={period}
onChange={event => {
setPeriod(event.target.value);
}}
style={styles.radioGroup}
>
<FormControlLabel
style={{
...styles.formControlLabel,
backgroundColor:
period === 'year'
? gdevelopTheme.paper.backgroundColor.light
: gdevelopTheme.paper.backgroundColor.medium,
}}
value="year"
control={<Radio color="secondary" disabled={disabled} />}
label={
<Line>
<Column>
<Text noMargin color="inherit" size="sub-title">
{!yearlyPlanPrice.isPerUser ? (
<Trans>
Yearly,
{formatPriceWithCurrency(
yearlyPlanPrice.amountInCents,
yearlyPlanPrice.currency
)}
</Trans>
) : (
<Trans>
Yearly,
{formatPriceWithCurrency(
yearlyPlanPrice.amountInCents,
yearlyPlanPrice.currency
)}{' '}
per seat
</Trans>
)}
</Text>
<Text color="secondary" noMargin>
<Trans>
Instead of{' '}
<span style={styles.discountedPrice}>
{formatPriceWithCurrency(
yearlyPriceInCentsWithMonthlyPlan,
yearlyPlanPrice.currency
)}
</span>
</Trans>
</Text>
</Column>
<Column alignItems="center" justifyContent="center">
<span
style={{
...styles.discountContainer,
backgroundColor:
gdevelopTheme.message.hot.backgroundColor,
color: gdevelopTheme.message.hot.color,
}}
>
<DiscountFlame fontSize="small" />
<Spacer />
<Text color="inherit" noMargin>
{yearlyDiscountDisplayText}
</Text>
</span>
</Column>
</Line>
}
/>
<Spacer />
<FormControlLabel
style={{
...styles.formControlLabel,
backgroundColor:
period === 'month'
? gdevelopTheme.paper.backgroundColor.light
: gdevelopTheme.paper.backgroundColor.medium,
}}
value="month"
control={<Radio color="secondary" disabled={disabled} />}
label={
<Line>
<Column>
<Text noMargin size="sub-title" color="inherit">
{!monthlyPlanPrice.isPerUser ? (
<Trans>
Monthly,
{formatPriceWithCurrency(
monthlyPlanPrice.amountInCents,
monthlyPlanPrice.currency
)}
</Trans>
) : (
<Trans>
Monthly,
{formatPriceWithCurrency(
monthlyPlanPrice.amountInCents,
monthlyPlanPrice.currency
)}{' '}
per seat
</Trans>
)}
</Text>
</Column>
</Line>
}
/>
</RadioGroup>
</Line>
)}
{!onlyShowDiscountedPrice && (
<Line alignItems="center" justifyContent="center">
<RaisedButton
color="premium"
key="upgrade"
disabled={disabled}
label={
<LeftLoader isLoading={disabled}>
<Text size="block-title" color="inherit">
<Trans>Choose this plan</Trans>
</Text>
</LeftLoader>
}
onClick={() => onClickChoosePlan(selectedPricingSystem)}
size="large"
fullWidth
/>
</Line>
)}
{onlyShowDiscountedPrice && (
<Column>
<Line alignItems="center" justifyContent="center">
<span style={styles.discountedPrice}>
<Text noMargin color="secondary">
{!monthlyPlanPrice.isPerUser ? (
<Trans>
Monthly,
{formatPriceWithCurrency(
monthlyPlanPrice.amountInCents,
monthlyPlanPrice.currency
)}
</Trans>
) : (
<Trans>
Monthly,
{formatPriceWithCurrency(
monthlyPlanPrice.amountInCents,
monthlyPlanPrice.currency
)}{' '}
per seat
</Trans>
)}
</Text>
</span>
</Line>
<Line noMargin alignItems="center" justifyContent="center">
<Chip
label={<Trans>Included</Trans>}
style={styles.discountChip}
/>
</Line>
</Column>
)}
</ColumnStackLayout>
</Paper>
</div>
)}
</I18n>
);
};
export default SubscriptionPlanPricingSummary;

View File

@@ -0,0 +1,148 @@
// @flow
import * as React from 'react';
import { I18n } from '@lingui/react';
import Text from '../../../UI/Text';
import { Column, LargeSpacer, Line } from '../../../UI/Grid';
import {
type SubscriptionPlanWithPricingSystems,
getSummarizedSubscriptionPlanFeatures,
} from '../../../Utils/GDevelopServices/Usage';
import { selectMessageByLocale } from '../../../Utils/i18n/MessageByLocale';
import { Trans } from '@lingui/macro';
import Link from '../../../UI/Link';
import Window from '../../../Utils/Window';
import GDevelopThemeContext from '../../../UI/Theme/GDevelopThemeContext';
import CheckCircleFilled from '../../../UI/CustomSvgIcons/CheckCircleFilled';
import CircledClose from '../../../UI/CustomSvgIcons/CircledClose';
const styles = {
summarizeFeatureRow: {
paddingTop: 4,
paddingBottom: 4,
},
tableRightItemContainer: {
width: 120,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
bulletText: { flex: 1 },
bulletIcon: { width: 20, height: 20 },
unlimitedContainer: {
padding: '4px 8px',
borderRadius: 4,
display: 'flex',
alignItems: 'center',
color: 'black',
},
};
const SubscriptionPlanTableSummary = ({
subscriptionPlanWithPricingSystems,
hideActions,
}: {|
subscriptionPlanWithPricingSystems: SubscriptionPlanWithPricingSystems,
hideActions?: boolean,
|}) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
return (
<I18n>
{({ i18n }) => (
<Column justifyContent="center" noMargin>
<div
style={{
backgroundColor: gdevelopTheme.paper.backgroundColor.light,
}}
>
<Line alignItems="center" justifyContent="flex-end" noMargin>
<div style={styles.tableRightItemContainer}>
<Text size="sub-title">
{selectMessageByLocale(
i18n,
subscriptionPlanWithPricingSystems.nameByLocale
)}{' '}
</Text>
</div>
</Line>
</div>
{getSummarizedSubscriptionPlanFeatures(
i18n,
subscriptionPlanWithPricingSystems
).map((summarizedFeature, index) => (
<Column key={index} noMargin>
<div
style={{
...styles.summarizeFeatureRow,
borderTop:
index !== 0 &&
`1px solid ${gdevelopTheme.listItem.separatorColor}`,
}}
>
<Line
noMargin
alignItems="center"
justifyContent="space-between"
>
<Text style={styles.bulletText}>
{summarizedFeature.displayedFeatureName}
</Text>
<div style={styles.tableRightItemContainer}>
{summarizedFeature.enabled === 'yes' ? (
<CheckCircleFilled
style={{
...styles.bulletIcon,
color: gdevelopTheme.message.valid,
}}
/>
) : summarizedFeature.enabled === 'no' ? (
<CircledClose style={styles.bulletIcon} />
) : summarizedFeature.unlimited ? (
<div
style={{
...styles.unlimitedContainer,
backgroundColor: gdevelopTheme.message.valid,
}}
>
<Text noMargin color="inherit">
<Trans>Unlimited</Trans>
</Text>
</div>
) : (
<Text>{summarizedFeature.description}</Text>
)}
</div>
</Line>
</div>
</Column>
))}
{!hideActions && (
<>
<LargeSpacer />
<Line noMargin justifyContent="center">
<Text size="body" color="secondary">
<Trans>
Compare all the advantages of the different plans in this{' '}
<Link
href="https://gdevelop.io/pricing#feature-comparison"
onClick={() =>
Window.openExternalURL(
'https://gdevelop.io/pricing#feature-comparison'
)
}
>
big feature comparison table
</Link>
.
</Trans>
</Text>
</Line>
</>
)}
</Column>
)}
</I18n>
);
};
export default SubscriptionPlanTableSummary;

View File

@@ -125,10 +125,6 @@ export default function PromotionSubscriptionDialog({
[purchasablePlansWithPricingSystems, selectedPlanId]
);
if (!displayedPlan) {
return null;
}
const isLoading = isRefreshing;
return (
@@ -149,11 +145,12 @@ export default function PromotionSubscriptionDialog({
flexColumnBody
topBackgroundSrc={'res/premium/premium_dialog_background.png'}
>
<ColumnStackLayout noMargin justifyContent="space-between" expand>
{!purchasablePlansWithPricingSystems ||
authenticatedUser.loginState === 'loggingIn' ? (
<PlaceholderLoader />
) : (
{!purchasablePlansWithPricingSystems ||
!displayedPlan ||
authenticatedUser.loginState === 'loggingIn' ? (
<PlaceholderLoader />
) : (
<ColumnStackLayout noMargin justifyContent="space-between" expand>
<ColumnStackLayout expand noMargin>
<PromotionSubscriptionPlan
onClickRedeemCode={
@@ -183,41 +180,41 @@ export default function PromotionSubscriptionDialog({
disabled={isLoading}
/>
</ColumnStackLayout>
)}
<Line>
<ColumnStackLayout noMargin>
<Column noMargin>
<LineStackLayout noMargin>
<Text size="sub-title"></Text>
<Text size="sub-title">
<Trans>Support What You Love</Trans>
<Line>
<ColumnStackLayout noMargin>
<Column noMargin>
<LineStackLayout noMargin>
<Text size="sub-title"></Text>
<Text size="sub-title">
<Trans>Support What You Love</Trans>
</Text>
</LineStackLayout>
<Text size="body" color="secondary">
<Trans>
The GDevelop project is open-source, powered by
passion and community. Your membership helps the
GDevelop company maintain servers, build new features,
develop commercial offerings and keep the open-source
project thriving. Our goal: make game development
fast, fun and accessible to all.
</Trans>
</Text>
</LineStackLayout>
<Text size="body" color="secondary">
<Trans>
The GDevelop project is open-source, powered by passion
and community. Your membership helps the GDevelop
company maintain servers, build new features, develop
commercial offerings and keep the open-source project
thriving. Our goal: make game development fast, fun and
accessible to all.
</Trans>
</Text>
</Column>
{getPlanSpecificRequirements(
i18n,
subscriptionPlansWithPricingSystems
).map(planSpecificRequirements => (
<AlertMessage
kind="info"
key={planSpecificRequirements.substring(0, 25)}
>
{planSpecificRequirements}
</AlertMessage>
))}
</ColumnStackLayout>
</Line>
</ColumnStackLayout>
</Column>
{getPlanSpecificRequirements(
i18n,
subscriptionPlansWithPricingSystems
).map(planSpecificRequirements => (
<AlertMessage
kind="info"
key={planSpecificRequirements.substring(0, 25)}
>
{planSpecificRequirements}
</AlertMessage>
))}
</ColumnStackLayout>
</Line>
</ColumnStackLayout>
)}
</Dialog>
{redeemCodeDialogOpen && (
<RedeemCodeDialog

View File

@@ -5,6 +5,7 @@ import {
type TeamGroup,
type User,
type TeamMembership,
type EditUserChanges,
} from '../../Utils/GDevelopServices/User';
import { type CloudProjectWithUserAccessInfo } from '../../Utils/GDevelopServices/Project';
@@ -31,6 +32,7 @@ export type TeamState = {|
userId: string,
newPassword: string
) => Promise<void>,
onEditUser: (editedUserId: string, changes: EditUserChanges) => Promise<void>,
|};
export const initialTeamState = {
@@ -51,6 +53,7 @@ export const initialTeamState = {
onRefreshAdmins: async () => {},
onSetAdmin: async () => {},
onChangeMemberPassword: async () => {},
onEditUser: async () => {},
};
const TeamContext = React.createContext<TeamState>(initialTeamState);

View File

@@ -20,6 +20,8 @@ import {
changeTeamMemberPassword,
activateTeamMembers,
setUserAsAdmin,
editUser,
type EditUserChanges,
} from '../../Utils/GDevelopServices/User';
import AuthenticatedUserContext from '../../Profile/AuthenticatedUserContext';
import { listOtherUserCloudProjects } from '../../Utils/GDevelopServices/Project';
@@ -150,6 +152,18 @@ const TeamProvider = ({ children }: Props) => {
[team, getAuthorizationHeader, adminUserId]
);
const onEditUser = React.useCallback(
async (editedUserId: string, changes: EditUserChanges) => {
if (!adminUserId) return;
await editUser(getAuthorizationHeader, {
userId: adminUserId,
editedUserId,
changes,
});
},
[getAuthorizationHeader, adminUserId]
);
const onChangeMemberPassword = React.useCallback(
async (userId: string, newPassword: string) => {
if (!adminUserId) return;
@@ -357,6 +371,7 @@ const TeamProvider = ({ children }: Props) => {
admins,
members,
memberships,
onEditUser,
onChangeGroupName,
onChangeUserGroup,
onListUserProjects,

View File

@@ -15,6 +15,7 @@ import SelectOption from '../../UI/SelectOption';
import { enumerateEventsFunctionsExtensions } from '../../ProjectManager/EnumerateProjectItems';
import getObjectByName from '../../Utils/GetObjectByName';
import AlertMessage from '../../UI/AlertMessage';
import { mapVector } from '../../Utils/MapFor';
const gd: libGDevelop = global.gd;
@@ -116,9 +117,55 @@ export default function ExtractAsCustomObjectDialog({
[globalObjectsContainer, objectsContainer, project, selectedInstances]
);
const irrelevantBehaviorMetadatas = React.useMemo<Array<gdBehaviorMetadata>>(
() => {
const objects = new Set<gdObject>();
for (const selectedInstance of selectedInstances) {
const objectName = selectedInstance.getObjectName();
const object = getObjectByName(
globalObjectsContainer,
objectsContainer,
objectName
);
if (object) {
objects.add(object);
}
}
const behaviorMetadatas = new Set<gdBehaviorMetadata>();
for (const object of objects) {
mapVector(object.getAllBehaviorNames(), behaviorName => {
const behavior = object.getBehavior(behaviorName);
const platform = project.getCurrentPlatform();
const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
platform,
behavior.getTypeName()
);
const isRelevantForChildObjects =
behaviorMetadata.isRelevantForChildObjects() &&
behaviorMetadata
.getRequiredBehaviorTypes()
.toJSArray()
.every(requiredBehaviorType => {
const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
platform,
requiredBehaviorType
);
return behaviorMetadata.isRelevantForChildObjects();
});
if (!isRelevantForChildObjects) {
behaviorMetadatas.add(behaviorMetadata);
}
});
}
return [...behaviorMetadatas];
},
[globalObjectsContainer, objectsContainer, project, selectedInstances]
);
const apply = React.useCallback(
(i18n: I18nType) => {
if (has2DAnd3D) {
if (has2DAnd3D || irrelevantBehaviorMetadatas) {
onCancel();
} else {
onApply(
@@ -131,6 +178,7 @@ export default function ExtractAsCustomObjectDialog({
},
[
has2DAnd3D,
irrelevantBehaviorMetadatas,
onCancel,
onApply,
extensionName,
@@ -158,7 +206,7 @@ export default function ExtractAsCustomObjectDialog({
label={<Trans>Move instances</Trans>}
primary={true}
onClick={() => apply(i18n)}
disabled={has2DAnd3D}
disabled={has2DAnd3D || irrelevantBehaviorMetadatas.length > 0}
/>,
]}
secondaryActions={[
@@ -187,6 +235,19 @@ export default function ExtractAsCustomObjectDialog({
</Trans>
</AlertMessage>
) : null}
{irrelevantBehaviorMetadatas ? (
<AlertMessage kind="error">
<Trans>
Objects inside custom objects can't contain the following
behaviors:
</Trans>
<ul>
{irrelevantBehaviorMetadatas.map(BehaviorMetadata => (
<li>{BehaviorMetadata.getFullName()}</li>
))}
</ul>
</AlertMessage>
) : null}
<ResponsiveLineStackLayout noMargin expand noResponsiveLandscape>
<SelectField
floatingLabelText={

View File

@@ -311,6 +311,18 @@ export default class SceneEditor extends React.Component<Props, State> {
}
};
onInstancesModifiedOutsideEditor = () => {
// /!\ Drop the selection to avoid keeping any references to deleted instances.
// This could be avoided if the selection used something like UUID to address instances.
this.instancesSelection.clearSelection();
// /!\ Force the instances editor to destroy and mount again the
// renderers to avoid keeping any references to existing instances
if (this.editorDisplay)
this.editorDisplay.instancesHandlers.forceRemountInstancesRenderers();
this.updateToolbar();
};
updateToolbar = () => {
const { editorDisplay } = this;
if (!editorDisplay) return;
@@ -590,10 +602,8 @@ export default class SceneEditor extends React.Component<Props, State> {
);
undo = () => {
// TODO: Do not clear selection so that the user can actually see
// the changes it is undoing (variable change, instance moved, etc.)
// or find a way to display a sumup of the change such as "Variable XXX
// in instance of Enemy changed to YYY"
// /!\ Drop the selection to avoid keeping any references to deleted instances.
// This could be avoided if the selection used something like UUID to address instances.
this.instancesSelection.clearSelection();
this.setState(
{
@@ -610,6 +620,8 @@ export default class SceneEditor extends React.Component<Props, State> {
};
redo = () => {
// /!\ Drop the selection to avoid keeping any references to deleted instances.
// This could be avoided if the selection used something like UUID to address instances.
this.instancesSelection.clearSelection();
this.setState(
{

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