Refactor JavaScript example to use template project (#4758)

* Refactor JavaScript example to use template project

* Feedback

* Update docs/tutorial/node/src/getting_started.md

Co-authored-by: Simon Hausmann <simon.hausmann@slint.dev>
This commit is contained in:
Chris Chinchilla 2024-03-08 13:20:37 +01:00 committed by GitHub
parent 2355234553
commit 203259f024
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 154 additions and 124 deletions

View file

@ -1,12 +1,14 @@
<!-- Copyright © SixtyFPS GmbH <info@slint.dev> ; SPDX-License-Identifier: MIT -->
# Conclusion
In this tutorial, we have demonstrated how to combine some built-in Slint elements with JavaScript code to build a little
game. There are many more features that we haven't talked about, such as layouts, widgets, or styling.
This tutorial showed you how to combine built-in Slint elements with Rust code to build a
game. There is much more to Slint, such as layouts, widgets, or styling.
We recommend the following links to continue:
* [Examples](https://github.com/slint-ui/slint/tree/master/examples): In the Slint repository we have collected a few demos and examples. These are a great starting point to learn how to use many Slint features.
* [Todo Example](https://github.com/slint-ui/slint/tree/master/examples/todo): This is one of the examples that implements a classic use-case.
* [Memory Puzzle](https://github.com/slint-ui/slint/tree/master/examples/memory): This is a slightly more polished version of the code in this example. And you can <a href="https://slint.dev/demos/memory/" target="_blank">play the wasm version</a> in your browser.
* [Slint API Docs](https://slint.dev/docs/node/): The reference documentation for the NodeJS library.
- [Examples](https://github.com/slint-ui/slint/tree/master/examples): In the Slint repository we have collected several demos and examples. These are a great starting point to learn how to use many Slint features.
- [Todo Example](https://github.com/slint-ui/slint/tree/master/examples/todo): This is one of the examples that implements a classic use-case.
- [Memory Puzzle](https://github.com/slint-ui/slint/tree/master/examples/memory): This is a slightly more polished version of the code in this example and you can <a href="https://slint.dev/demos/memory/" target="_blank">play the wasm version</a> in your browser.
- [Slint API Docs](https://slint.dev/docs/rust/slint/): The reference documentation for the main Rust crate.
- [Slint Interpreter API Docs](https://slint.dev/docs/rust/slint_interpreter/): The reference documentation for Rust crate that allows you to dynamically load Slint files.

View file

@ -1,20 +1,25 @@
<!-- Copyright © SixtyFPS GmbH <info@slint.dev> ; SPDX-License-Identifier: MIT -->
# Creating The Tiles From JavaScript
What we'll do is take the list of tiles declared in the .slint language, duplicate it, and shuffle it.
We'll do so by accessing the `memory_tiles` property through the JavaScript code - in our case `memory_tiles`.
Since `memory_tiles` is an array in the `.slint` language, it's represented as a JavaScript [`Array`](https://slint.dev/docs/node/).
We can't modify the model generated by the .slint, but we can extract the tiles from it, and put it
in a [`slint.ArrayModel`](https://slint.dev/docs/node/classes/arraymodel.html) which implements the [`Model`](https://slint.dev/docs/node/interfaces/model.html) interface.
`ArrayModel` allows us to make modifications and we can use it to replace the static generated model.
This step places the game tiles randomly.
We modify `main.js` like so:
The code takes the list of tiles, duplicates it, and shuffles it, accessing the `memory_tiles` property through the JavaScript code.
As `memory_tiles` is an array, it's represented as a JavaScript [`Array`](https://slint.dev/docs/node/).
You can't change the model generated by Slint, but you can extract the tiles from it, and put them
in a [`slint.ArrayModel`](https://slint.dev/docs/node/classes/arraymodel.html) which implements the [`Model`](https://slint.dev/docs/node/interfaces/model.html) interface.
`ArrayModel` allows you to make changes and you can use it to replace the static generated model.
Change `main.js` to the following:
```js
{{#include main_tiles_from_js.js:main}}
```
Running this gives us a window on the screen that now shows a 4 by 4 grid of rectangles, which can show or obscure
the icons when clicking. There's only one last aspect missing now, the rules for the game.
Running this code opens a window that now shows a 4 by 4 grid of rectangles, which show or hide
the icons when a player clicks on them.
There's one last aspect missing now, the rules for the game.
<video autoplay loop muted playsinline src="https://slint.dev/blog/memory-game-tutorial/creating-the-tiles-from-rust.mp4"></video>

View file

@ -1,34 +1,40 @@
<!-- Copyright © SixtyFPS GmbH <info@slint.dev> ; SPDX-License-Identifier: MIT -->
# From One To Multiple Tiles
After modeling a single tile, let's create a grid of them. For the grid to be our game board, we need two features:
After modeling a single tile, this step creates a grid of them. For the grid to be a game board, you need two features:
1. A data model: This shall be an array where each element describes the tile data structure, such as the
url of the image, whether the image shall be visible and if this tile has been solved. We modify the model
from JS code.
2. A way of creating many instances of the tiles, with the above `.slint` markup code.
1. **A data model**: An array created as a Rust model, where each element describes the tile data structure, such as:
In Slint we can declare an array of structures using brackets, to create a model. We can use the <span class="hljs-keyword">for</span> loop
to create many instances of the same element. In `.slint` the for loop is declarative and automatically updates when
the model changes. We instantiate all the different <span class="hljs-title">MemoryTile</span> elements and place them on a grid based on their
index with a little bit of spacing between the tiles.
- URL of the image
- Whether the image is visible
- If the player has solved this tile.
First, we copy the tile data structure definition and paste it at top inside the `memory.slint` file:
2. A way of creating multiple instances of the tiles.
With Slint you declare an array of structures based on a model using square brackets. Use a <span class="hljs-keyword">for</span> loop
to create multiple instances of the same element.
With Slint the for loop is declarative and automatically updates when
the model changes. The loop instantiates all the <span class="hljs-title">MemoryTile</span> elements and places them on a grid based on their
index with spacing between the tiles.
First, add the tile data structure definition at the top of the `memory.slint` file:
```slint
{{#include ../../rust/src/main_multiple_tiles.rs:tile_data}}
```
Next, we replace the _export component <span class="hljs-title">MainWindow</span> inherits Window { ... }_ section at the bottom of the `memory.slint` file with the following snippet:
Next, replace the _export component <span class="hljs-title">MainWindow</span> inherits Window { ... }_ section at the bottom of the `memory.slint` file with the following:
```slint
{{#include ../../rust/src/main_multiple_tiles.rs:main_window}}
```
The <code><span class="hljs-keyword">for</span> tile\[i\] <span class="hljs-keyword">in</span> memory_tiles:</code> syntax declares a variable `tile` which contains the data of one element from the `memory_tiles` array,
and a variable `i` which is the index of the tile. We use the `i` index to calculate the position of tile based on its row and column,
using the modulo and integer division to create a 4 by 4 grid.
and a variable `i` which is the index of the tile. The code uses the `i` index to calculate the position of a tile, based on its row and column,
using modulo and integer division to create a 4 by 4 grid.
Running this gives us a window that shows 8 tiles, which can be opened individually.
Running the code opens a window that shows 8 tiles, which a player can open individually.
<video autoplay loop muted playsinline src="https://slint.dev/blog/memory-game-tutorial/from-one-to-multiple-tiles.mp4"></video>

View file

@ -1,33 +1,37 @@
<!-- Copyright © SixtyFPS GmbH <info@slint.dev> ; SPDX-License-Identifier: MIT -->
# Game Logic In JavaScript
We'll implement the rules of the game in JavaScript as well. The general philosophy of Slint is that merely the user
interface is implemented in the `.slint` language and the business logic in your favorite programming
language. The game rules shall enforce that at most two tiles have their curtain open. If the tiles match, then we
consider them solved and they remain open. Otherwise we wait for a little while, so the player can memorize
the location of the icons, and then close them again.
This step implements the rules of the game in Rust as well.
We'll modify the `.slint` markup in the `memory.slint` file to signal to the JavaScript code when the user clicks on a tile.
Two changes to <span class="hljs-title">MainWindow</span> are needed: We need to add a way for the MainWindow to call to the JavaScript code that it should
check if a pair of tiles has been solved. And we need to add a property that JavaScript code can toggle to disable further
tile interaction, to prevent the player from opening more tiles than allowed. No cheating allowed! First, we paste
the callback and property declarations into <span class="hljs-title">MainWindow</span>:
Slint's general philosophy is that you implement the user interface in Slint and the business logic in your favorite programming
language.
The game rules enforce that at most two tiles have their curtain open. If the tiles match, then the game
considers them solved and they remain open. Otherwise, the game waits briefly so the player can memorize
the location of the icons, and then closes the curtains again.
Change the contents of `memory.slint` to signal to the JavaScript code when the user clicks on a tile.
```slint
{{#include ../../rust/src/main_game_logic_in_rust.rs:mainwindow_interface}}
```
The last change to the `.slint` markup is to act when the <span class="hljs-title">MemoryTile</span> signals that it was clicked on.
We add the following handler in <span class="hljs-title">MainWindow</span>:
This change adds a way for the <span class="hljs-title">MainWindow</span> to call to the JavaScript code that it should
check if a player has solved a pair of tiles. The Rust code needs an additional property to toggle to disable further
tile interaction, to prevent the player from opening more tiles than allowed. No cheating allowed!
The last change to the code is to act when the <span class="hljs-title">MemoryTile</span> signals that a player clicked it.
Add the following handler in <span class="hljs-title">MainWindow</span>:
```slint
{{#include ../../rust/src/main_game_logic_in_rust.rs:tile_click_logic}}
```
On the JavaScript side, we can now add an handler to the `check_if_pair_solved` callback, that will check if
two tiles are opened. If they match, the `solved` property is set to true in the model. If they don't
match, start a timer that will close them after one second. While the timer is running, we disable every tile so
one can't click anything during this time.
On the JavaScript side, now add a handler to the `check_if_pair_solved` callback, that checks if a player opened two tiles. If they match, the code sets the `solved` property to true in the model. If they don't
match, start a timer that closes the tiles after one second. While the timer is running, disable every tile so
a player can't click anything during this time.
Insert this code before the `mainWindow.run()` call:
@ -35,5 +39,4 @@ Insert this code before the `mainWindow.run()` call:
{{#include main_game_logic.js:game_logic}}
```
These were the last changes and running the result gives us a window on the screen that allows us
to play the game by the rules.
These were the last changes and running the code opens a window that allows a player to play the game by the rules.

View file

@ -1,48 +1,42 @@
<!-- Copyright © SixtyFPS GmbH <info@slint.dev> ; SPDX-License-Identifier: MIT -->
# Getting Started
In this tutorial, we use JavaScript as the host programming language. We also support other programming languages like
This tutorial uses JavaScript as the host programming language. Slint also supports other programming languages like
[Rust](https://slint.dev/docs/rust/slint/) or [C++](https://slint.dev/docs/cpp/).
You'll need a development environment with [Node.js 16](https://nodejs.org/download/release/v16.19.1/) and [npm](https://www.npmjs.com/) installed. More recent
versions of NodeJS are currently not supported, for details check [Issue #961](https://github.com/slint-ui/slint/issues/961).
Since Slint is implemented in the Rust programming language, you also need to install a Rust compiler (1.70 or newer). You can easily install a Rust compiler
following the instruction from [the Rust website](https://www.rust-lang.org/learn/get-started).
You will also need some additional platform-specific dependencies, see <https://github.com/slint-ui/slint/blob/master/docs/building.md#prerequisites>
Slint has an application template you can use to create a project with dependencies already set up that follows recommended best practices.
We're going to use `slint-ui` as `npm` dependency.
In a new directory, we create a new `package.json` file.
Clone the template with the following command:
```json
{{#include package.json}}
```sh
git clone https://github.com/slint-ui/slint-nodejs-template memory
cd memory
```
This should look familiar to people familiar with NodeJS. We see that this package.json
references a `main.js`, which we will add later. We must then create, in the same directory,
the `memory.slint` file. Let's just fill it with a hello world for now:
Install dependencies with npm:
```slint
{{#include memory.slint:main_window}}
```sh
npm install
```
What's still missing is the `main.js`:
The `package.json` file references `src/main.js` as the entry point for the application and `src/main.js` references `memory.slint` as the UI file.
Replace the contents of `src/main.js` with the following:
```js
{{#include main_initial.js:main}}
```
To recap, we now have a directory with a `package.json`, `memory.slint`, and `main.js`.
Note that `slint.loadFile` resolves files from the process's current working directory, so from the `package.json` file's location.
We can now compile and run the program:
Replace the contents of `ui/appwindow.slint` with the following:
```sh
npm install
npm start
```slint
{{#include memory.slint:main_window}}
```
and a window will appear with the green "Hello World" greeting.
Run the example with `npm start` and a window appears with the green "Hello World" greeting.
![Screenshot of initial tutorial app showing Hello World](https://slint.dev/blog/memory-game-tutorial/getting-started.png "Hello World")
Feel free to use your favorite IDE for this purpose.
![Screenshot of an initial tutorial app showing Hello World](https://slint.dev/blog/memory-game-tutorial/getting-started.png "Hello World")

View file

@ -1,12 +1,13 @@
<!-- Copyright © SixtyFPS GmbH <info@slint.dev> ; SPDX-License-Identifier: MIT -->
# Ideas For The Reader
The game is visually a little bare. Here are some ideas how you could make further changes to enhance it:
The game is visually bare. Here are some ideas on how you could make further changes to enhance it:
- The tiles could have rounded corners, to look a little less sharp. The [border-radius](https://slint.dev/docs/slint/src/language/builtins/elements#rectangle)
property of _Rectangle_ can be used to achieve that.
- The tiles could have rounded corners, to look less sharp. Use the [border-radius](https://slint.dev/docs/slint/src/language/builtins/elements#rectangle)
property of _[Rectangle](https://slint.dev/docs/slint/src/language/builtins/elements#rectangle)_ to achieve that.
- In real world memory games, the back of the tiles often have some common graphic. You could add an image with
- In real-world memory games, the back of the tiles often have some common graphic. You could add an image with
the help of another _[Image](https://slint.dev/docs/slint/src/language/builtins/elements#image)_
element. Note that you may have to use _Rectangle_'s _clip property_
element around it to ensure that the image is clipped away when the curtain effect opens.

View file

@ -1,15 +1,16 @@
<!-- Copyright © SixtyFPS GmbH <info@slint.dev> ; SPDX-License-Identifier: MIT -->
# Introduction
This tutorial will introduce you to the Slint UI framework in a playful way by implementing a little memory game. We're going to combine the `.slint` language for the graphics with the game rules implemented in JavaScript.
This tutorial introduces you to the Slint UI framework in a playful way by implementing a memory game. It combines the `.slint` language for the graphics with the game rules implemented in Rust.
The game consists of a grid of 16 rectangular tiles. Clicking on a tile uncovers an icon underneath.
We know that there are 8 different icons in total, so each tile has a sibling somewhere in the grid with the
same icon. The objective is to locate all icon pairs. You can uncover two tiles at the same time. If they
aren't the same, the icons will be obscured again.
If you uncover two tiles with the same icon, then they remain visible - they're solved.
There are 8 different icons in total, so each tile has a sibling somewhere in the grid with the
same icon. The objective is to locate all icon pairs. The player can uncover two tiles at the same time. If they
aren't the same, the game obscures the icons again.
If the player uncovers two tiles with the same icon, then they remain visible - they're solved.
This is how the game looks like in action:
This is how the game looks in action:
<video autoplay loop muted playsinline src="https://slint.dev/blog/memory-game-tutorial/memory_clip.mp4"
class="img-fluid img-thumbnail rounded"></video>

View file

@ -16,10 +16,10 @@ for (let i = tiles.length - 1; i > 0; i--) {
[tiles[i], tiles[j]] = [tiles[j], tiles[i]];
}
// ANCHOR: game_logic
let model = new slint.ArrayModel(tiles);
mainWindow.memory_tiles = model;
// ANCHOR: game_logic
mainWindow.check_if_pair_solved = function () {
let flipped_tiles = [];
tiles.forEach((tile, index) => {
@ -61,7 +61,5 @@ mainWindow.check_if_pair_solved = function () {
}
}
};
await mainWindow.run();
// ANCHOR_END: game_logic
await mainWindow.run();

View file

@ -5,7 +5,7 @@
// main.js
import * as slint from "slint-ui";
let ui = slint.loadFile("./memory.slint");
let ui = slint.loadFile("./ui/appwindow.slint");
let mainWindow = new ui.MainWindow();
await mainWindow.run();

View file

@ -4,7 +4,7 @@
// ANCHOR: main
// main.js
import * as slint from "slint-ui";
let ui = slint.loadFile("./memory.slint");
let ui = slint.loadFile("./ui/appwindow.slint");
let mainWindow = new ui.MainWindow();
let initial_tiles = mainWindow.memory_tiles;

View file

@ -2,7 +2,7 @@
// SPDX-License-Identifier: MIT
// ANCHOR: main_window
// memory.slint
// appwindow.slint
export component MainWindow inherits Window {
Text {
text: "hello world";

View file

@ -1,43 +1,54 @@
<!-- Copyright © SixtyFPS GmbH <info@slint.dev> ; SPDX-License-Identifier: MIT -->
# Memory Tile
With the skeleton in place, let's look at the first element of the game, the memory tile. It will be the
visual building block that consists of an underlying filled rectangle background, the icon image. Later we'll add a
covering rectangle that acts as a curtain. The background rectangle is declared to be 64 logical pixels wide and tall,
and it's filled with a soothing tone of blue. Note how lengths in the `.slint` language have a unit, here
the `px` suffix. That makes the code easier to read and the compiler can detect when your are accidentally
mixing values with different units attached to them.
With the skeleton in place, this step looks at the first element of the game, the memory tile. It's the
visual building block that consists of an underlying filled rectangle background, the icon image. Later you'll add a
covering rectangle that acts as a curtain.
We copy the following code into the `memory.slint` file:
You declare the background rectangle as 64 logical pixels wide and tall
and it's filled with a soothing tone of blue.
Note how lengths in the `.slint` language have a unit, here
the `px` suffix. That makes the code easier to read and the compiler can detect when you accidentally
mix values with different units attached to them.
Copy the following into the `ui/appwindow.slint` file:
```slint
{{#include memory_tile.slint:main_window}}
```
Note that we export the <span class="hljs-title">MainWindow</span> component. This is necessary so that we can later access it
from our business logic.
The code exports the <span class="hljs-title">MainWindow</span> component so that the business logic can access it later.
Inside the <span class="hljs-built_in">Rectangle</span> we place an <span class="hljs-built_in">Image</span> element that
loads an icon with the <span class="hljs-built_in">@image-url()</span> macro. The path is relative to the folder in which
the `memory.slint` is located. This icon and others we're going to use later need to be installed first. You can download a
[Zip archive](https://slint.dev/blog/memory-game-tutorial/icons.zip) that we have prepared.
Inside the <span class="hljs-built_in">Rectangle</span> place an <span class="hljs-built_in">Image</span> element that
loads an icon with the <span class="hljs-built_in">@image-url()</span> macro.
The path is relative to the folder that contains `ui/appwindow.slint`. You need to install this icon and others you use later first. You can download a pre-prepared
[Zip archive](https://slint.dev/blog/memory-game-tutorial/icons.zip) and extract it with the
following two commands:
If you are on Linux or macOS, download and extract it with the following two commands:
```sh
cd ui
curl -O https://slint.dev/blog/memory-game-tutorial/icons.zip
unzip icons.zip
cd ..
```
If you are on Windows, use the following commands:
```
```sh
cd ui
powershell curl -Uri https://slint.dev/blog/memory-game-tutorial/icons.zip -Outfile icons.zip
powershell Expand-Archive -Path icons.zip -DestinationPath .
cd ..
```
This should unpack an `icons` directory containing a bunch of icons.
This unpacks an `icons` directory containing several icons.
We running the program with `npm start` and it gives us a window on the screen that shows the icon of a bus on a blue background.
Running the program with `npm start` now opens a window that shows the icon of a bus on a
blue background.
![Screenshot of the first tile](https://slint.dev/blog/memory-game-tutorial/memory-tile.png "Memory Tile Screenshot")

View file

@ -1,33 +1,42 @@
<!-- Copyright © SixtyFPS GmbH <info@slint.dev> ; SPDX-License-Identifier: MIT -->
# Polishing the Tile
Next, let's add a curtain like cover that opens up when clicking. We achieve this by declaring two rectangles
below the <span class="hljs-built_in">Image</span>, so that they are drawn afterwards and thus on top of the image.
In this step, you add a curtain-like cover that opens when clicked. You do this by declaring two rectangles
below the <span class="hljs-built_in">Image</span>, so that Slint draws them after the Image and thus on top of the image.
The <span class="hljs-built_in">TouchArea</span> element declares a transparent rectangular region that allows
reacting to user input such as a mouse click or tap. We use that to forward a callback to the <em>MainWindow</em>
that the tile was clicked on. In the <em>MainWindow</em> we react by flipping a custom <em>open_curtain</em> property.
That in turn is used in property bindings for the animated width and x properties. Let's look at the two states a bit
more in detail:
reacting to user input such as a mouse click or tap. The element forwards a callback to the <em>MainWindow</em> indicating that a user clicked the tile.
| *open_curtain* value: | false | true |
| --- | --- | --- |
| Left curtain rectangle | Fill the left half by setting the width *width* to half the parent's width | Width of zero makes the rectangle invisible |
| Right curtain rectangle | Fill the right half by setting *x* and *width* to half of the parent's width | *width* of zero makes the rectangle invisible. *x* is moved to the right, to slide the curtain open when animated |
The <em>MainWindow</em> reacts by flipping a custom <em>open_curtain</em> property.
Property bindings for the animated width and x properties also use the custom <em>open_curtain</em> property.
In order to make our tile extensible, the hard-coded icon name is replaced with an *icon*
property that can be set from the outside when instantiating the element. For the final polish, we add a
*solved* property that we use to animate the color to a shade of green when we've found a pair, later. We
replace the code inside the `memory.slint` file with the following:
The following table shows more detail on the two states:
| _open_curtain_ value: | false | true |
| ----------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| Left curtain rectangle | Fill the left half by setting the width _width_ to half the parent's width | Width of zero makes the rectangle invisible |
| Right curtain rectangle | Fill the right half by setting _x_ and _width_ to half of the parent's width | _width_ of zero makes the rectangle invisible. _x_ moves to the right, sliding the curtain open when animated |
To make the tile extensible, replace the hard-coded icon name with an _icon_
property that can be set when instantiating the element.
For the final polish, add a
_solved_ property used to animate the color to a shade of green when a player finds a pair.
Replace the code in `ui/appwindow.slint` with the following:
```slint
{{#include ../../rust/src/main_polishing_the_tile.rs:tile}}
```
Note the use of `root` and `self` in the code. `root` refers to the outermost
element in the component, that's the <span class="hljs-title">MemoryTile</span> in this case. `self` refers
The code uses `root` and `self`. `root` refers to the outermost
element in the component, the <span class="hljs-title">MemoryTile</span> in this case. `self` refers
to the current element.
Running this gives us a window on the screen with a rectangle that opens up to show us the bus icon, when clicking on
it. Subsequent clicks will close and open the curtain again.
The code exports the <span class="hljs-title">MainWindow</span> component. This is necessary so that you can later access it
from application business logic.
Running the code opens a window with a rectangle that opens up to show the bus icon when clicked. Subsequent clicks close and open the curtain again.
<video autoplay loop muted playsinline src="https://slint.dev/blog/memory-game-tutorial/polishing-the-tile.mp4"></video>