Skip to content

Commit

Permalink
docs: add examples and gotchas for docs (#200)
Browse files Browse the repository at this point in the history
* docs: add examples and gotchas for docs

* chore: update static_checks.yml

* chore: update static_checks.yml

* chore: update static_checks.yml

* chore: update static_checks.yml

* chore: update static_checks.yml

* chore: update static_checks.yml

* chore: update CONTRIBUTING.md

* test: clang-format

* test: clang-format
  • Loading branch information
nmerget authored Sep 15, 2024
1 parent 8f06259 commit fd0759e
Show file tree
Hide file tree
Showing 13 changed files with 313 additions and 38 deletions.
12 changes: 6 additions & 6 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<!--
Please target the `master` branch in priority.
PRs can target `3.x` if the same change was done in `master`, or is not relevant there.
## Description

Relevant fixes are cherry-picked for stable branches as needed by maintainers.
You can mention in the description if the change is compatible with `3.x`.
-->
<!-- Describe the changes you've done -->

Make sure to follow the PR preparation steps in [CONTRIBUTING.md](../CONTRIBUTING.md#preparing-your-pr) before submitting your PR:

- [ ] format the codebase: from the root, run `bash ./clang_format.sh`.
5 changes: 3 additions & 2 deletions .github/workflows/static_checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ on:
required: true
type: string


concurrency:
group: ci-${{github.actor}}-${{github.head_ref || github.run_number}}-${{github.ref}}-static
cancel-in-progress: true
Expand All @@ -30,7 +29,9 @@ jobs:
path: tmp

- name: Checkout workaround
run: mv tmp/misc/scripts misc/scripts
run: |
mv tmp/misc/scripts misc/scripts
cp clang_format.sh misc/scripts/clang_format.sh
- name: Install APT dependencies
uses: awalsh128/cache-apt-pkgs-action@latest
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@
*.gen.json
.vscode
.idea
/site
16 changes: 16 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Local Development

## Project Structure

TODO

## Documentation

This project uses [MKDocs](https://www.mkdocs.org/) to serve all docs. You can change the documentation inside the `docs` folder.
To add new pages you need to update `mkdocs.yml`.

## Preparing your PR

The project is using [`clang-format`](https://clang.llvm.org/docs/ClangFormat.html) to format most files. You need to run `bash ./clang_format.sh` before your PR for a successful pipeline.

Furthermore, there is an `utf-8` and `LF` checker to fix file formats. Additionally, some spellchecks run inside the [pipeline](.github/workflows/static_checks.yml).
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,7 @@ Read this [documentation](https://geequlim.github.io/ECMAScript/getting-started)
- [godot-ECMAScript-cookbook](https://github.com/why-try313/godot-ECMAScript-cookbook/wiki) - Tutorial
- [godot-typescript-starter](https://github.com/citizenll/godot-typescript-starter) - Template
- [godot-js-template](https://github.com/fukaraadam-workspace/godot-js-template) - Template

## Contributing

If you like to contribute to this project check the [CONTRIBUTING.md](https://github.com/Geequlim/ECMAScript/blob/master/CONTRIBUTING.md) file.
36 changes: 36 additions & 0 deletions clang_format.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env bash

# This script runs clang-format and fixes copyright headers on all relevant files in the repo.
# This is the primary script responsible for fixing style violations.

set -uo pipefail

if [ $# -eq 0 ]; then
# Loop through all code files tracked by Git.
files=$(git ls-files -- '*.c' '*.h' '*.cpp' '*.hpp' '*.cc' '*.hh' '*.cxx' '*.m' '*.mm' '*.inc' '*.java' '*.glsl' \
':!:.git/*' ':!:thirdparty/*' ':!:*/thirdparty/*' ':!:platform/android/java/lib/src/com/google/*' \
':!:*-so_wrap.*' ':!:tests/python_build/*')
else
# $1 should be a file listing file paths to process. Used in CI.
files=$(cat "$1" | grep -v "thirdparty/" | grep -E "\.(c|h|cpp|hpp|cc|hh|cxx|m|mm|inc|java|glsl)$" | grep -v "platform/android/java/lib/src/com/google/" | grep -v "\-so_wrap\." | grep -v "tests/python_build/")
fi

if [ ! -z "$files" ]; then
clang-format --Wno-error=unknown -i $files
fi

diff=$(git diff --color)

# If no diff has been generated all is OK, clean up, and exit.
if [ -z "$diff" ] ; then
printf "\e[1;32m*** Files in this commit comply with the clang-format style rules.\e[0m\n"
exit 0
fi

# A diff has been created, notify the user, clean up, and exit.
printf "\n\e[1;33m*** The following changes must be made to comply with the formatting rules:\e[0m\n\n"
# Perl commands replace trailing spaces with `·` and tabs with `<TAB>`.
printf "%s\n" "$diff" | perl -pe 's/(.*[^ ])( +)(\e\[m)$/my $spaces="·" x length($2); sprintf("$1$spaces$3")/ge' | perl -pe 's/(.*[^\t])(\t+)(\e\[m)$/my $tabs="<TAB>" x length($2); sprintf("$1$tabs$3")/ge'

printf "\n\e[1;91m*** Please fix your commit(s) with 'git commit --amend' or 'git rebase -i <hash>'\e[0m\n"
exit 1
77 changes: 77 additions & 0 deletions docs/examples/load-json-in-singleton.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Load json in singleton

This example shows how to load a file like a ``config`` inside a singleton to access it everywhere.
We use ``TypeScript`` for this example all `.ts` files will be compiled as `.mjs` to the folder `scripts/generated/**`. If you use `TypeScript` you need to set `"resolveJsonModule": true` inside your `tsconfig.json`.

## 1. Create file

We create a new folder named ``config`` and a new file `test.json`.

Next we write this to the ``test.json``:

````json title="test.json"
{
"test": true
}
````

## 2. Create the singleton

We create a new file inside our `src` folder like ``read-config.ts`` and add this code to it:

````ts title="read-config.ts"
// @ts-ignore
import TestJson from "res://config/test.json";

type TestType = {
test: boolean;
};

export default class ReadConfig extends godot.Node {
static _singleton: ReadConfig;

static get singleton() {
return ReadConfig._singleton;
}

constructor() {
super();
if (!ReadConfig._singleton) {
ReadConfig._singleton = this;
}
}

// This property is available for other classes
config: TestType = TestJson as TestType;
}
````

## 3. Autoload singleton in project

We need to update the ``[autoload]`` inside `project.godot`:

````text title="project.godot"
...
[autoload]
; Use the generated `.mjs` file instead of `.ts`
ReadConfig="*res://scripts/generated/read-config.mjs"
...
````

## 4. Use the singleton in other class

In another class e.g. ``main.ts`` you need to import the `ReadConfig` then you can access every public property and method from `ReadConfig` via `ReadConfig.singleton`:

````ts title="main.ts"
import ReadConfig from "./read-config";

export default class Main extends godot.Node {
_ready(): void {
console.log(ReadConfig.singleton.config.test); // prints "true"
}
}

````


37 changes: 37 additions & 0 deletions docs/examples/read-file-local.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Read file local

This example shows how to load any file as string from a local folder.

We use ``TypeScript`` for this example all `.ts` files will be compiled as `.mjs`.

## 1. Create the file you want to read

In this example we try to read a ``.csv`` file, but it should work with any other file as well.

We create a folder ``resources`` and add a new file `test.csv`:

````csv title="test.csv"
keys,en,de
HELLO,hello,hallo
````

## 2. Read the file in class

We use [FileAccess](https://docs.godotengine.org/en/stable/classes/class_fileaccess.html) to read the file.

We create a new file ``read-local-file.ts``:

````ts title="read-local-file.ts"
export default class ReadLocalFile extends godot.Node {
_ready(): void {
const file = new godot.FileAccess();
file.open("res://resources/test.csv", godot.FileAccess.ModeFlags.READ);
let fileContent: string = "";
while (!file.eof_reached()) {
fileContent += `${file.get_line()}\n`;
}
console.log(fileContent);
}
}
````

55 changes: 55 additions & 0 deletions docs/examples/use-gdscript-in-ts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Use GDScript in TypeScript

This example shows how to use a class written in GDScript in another TS class.

We use ``TypeScript`` for this example all `.ts` files will be compiled as `.mjs` to the folder `scripts/generated/**`.

## 1. Create the GDScript file

First we create a simple class with GDScript inside a new file `scripts/gd/GDTest.gd`:

````gdscript title="GDTest.gd"
extends Node
func _ready():
pass
func print_in_gd_test():
print("bla")
````

## 2. Create a declaration (*.d.ts) for GDScript

For proper TypeScript support we need to add a ``gdtest.d.ts`` file:

````ts title="gdtest.d.ts"
declare module "res://scripts/gd/GDTest.gd" {
class GDTest {
call(func: "print_in_gd_test"): void;

static new() {
return this;
}
}
export = GDTest;
}
````

## 3. Use the class inside your TS file

In the end we need to call the ``GDTest.gd`` from another `.ts` file, like `main.ts`:

````ts title="main.ts"
import GDTest from "res://scripts/gd/GDTest.gd";

export default class Main extends godot.Node {
_ready(): void {
const bla: Bla = Bla.new();
bla.call("run_in_bla");
}
}

````

> **Note:** The important thing here is that you use `new()` to instantiate and `call` to execute the function
8 changes: 4 additions & 4 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

1. Define your JavaScript class and inherit from a Godot class, then export it as the **default** entry:

```js
```
// The default export entry is treated as an exported class to Godot
export default class MySprite extends godot.Sprite {
// this is _init() in GDScript
constructor() {
super();
}
_ready() {}
_reajavascript title="my-sprite.mjs"dy() {}
_process(delta) {}
}
Expand All @@ -21,15 +21,15 @@ export default class MySprite extends godot.Sprite {

### How to export signals

```js
```javascript title="my-sprite.mjs"
export default class MySprite extends godot.Sprite {}
// register game_over signal to MySprite class
godot.register_signal(MySprite, "game_over");
```

### How to export properties

```js
```javascript title="my-sprite.mjs"
export default class MySprite extends godot.Sprite {
_process(delta) {
// Yes! We can use operators in JavaScript like GDScript
Expand Down
60 changes: 60 additions & 0 deletions docs/gotchas.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Gotchas and limitations

Some common mistakes and limitations.

## Import dependency from `node_modules`

If you use `TypeScript` you may encounter the problem where dependencies from `node_modules` are not bundled correctly.

As a workaround you can create a new file `npm-modules.bundle.ts`:

```ts title="npm-modules.bundle.ts"
import { default as dayjs } from "dayjs";
export default { dayjs };
```

In your class you can use the dependency like this:

```ts title="main.ts"
import npm from "./npm-modules.bundle";

export default class Main extends godot.Node {
_ready(): void {
console.log(npm.dayjs().toString());
}
}
```

With a bundler like `esbuild` you should build the `npm-modules.bundle.ts` with the `--bundle` option, but all the other classes like `main.ts` without it.

## Position.x is immutable

You cannot change `this.position.x` try to change `this.position`:

```javascript title="player.mjs"
export default class Player extends godot.KinematicBody2D {
constructor() {
super();
this.direction = new godot.Vector2(1, 0);
}
_ready() {}
_process(delta) {
this.position.x += this.direction.x; // <- breaks
this.position += this.direction; // <- works
}
}
godot.register_property(Player, "direction", new godot.Vector2(1, 0));
```

## ``register_property`` has to be a target

You cannot change `this.position.x` try to change `this.position`:

```javascript title="player.mjs"
export default class Player extends godot.KinematicBody2D {
}
// This works
godot.register_property(Player, "directionWorks", new godot.Vector2(1, 0));
// This breaks because `player` isn't a correct target
godot.register_property(player, "directionBreaks", new godot.Vector2(1, 0));
```
Loading

0 comments on commit fd0759e

Please sign in to comment.