create-basicjs 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +12 -0
  2. package/bin/create-basicjs.js +49 -4
  3. package/package.json +1 -1
  4. package/payload/projects/tauri/.github/workflows/build.yml +86 -0
  5. package/payload/projects/tauri/.github/workflows/tests.yml +87 -0
  6. package/payload/projects/tauri/AGENTS.md +128 -0
  7. package/payload/projects/tauri/CLAUDE.md +1 -0
  8. package/payload/projects/tauri/LICENSE +201 -0
  9. package/payload/projects/tauri/NOTICE +8 -0
  10. package/payload/projects/tauri/README.md +269 -0
  11. package/payload/projects/tauri/checks/window-check.js +189 -0
  12. package/payload/projects/tauri/gitignore +8 -0
  13. package/payload/projects/tauri/handbook/01-getting-started.md +188 -0
  14. package/payload/projects/tauri/handbook/02-the-project.md +264 -0
  15. package/payload/projects/tauri/handbook/03-the-page.md +260 -0
  16. package/payload/projects/tauri/handbook/04-commands.md +265 -0
  17. package/payload/projects/tauri/handbook/05-events-and-state.md +275 -0
  18. package/payload/projects/tauri/handbook/06-plugins.md +282 -0
  19. package/payload/projects/tauri/handbook/07-the-window-and-the-app.md +431 -0
  20. package/payload/projects/tauri/handbook/08-security.md +374 -0
  21. package/payload/projects/tauri/handbook/09-tests-and-checks.md +266 -0
  22. package/payload/projects/tauri/handbook/10-building-and-releasing.md +238 -0
  23. package/payload/projects/tauri/handbook/11-troubleshooting.md +259 -0
  24. package/payload/projects/tauri/handbook/README.md +125 -0
  25. package/payload/projects/tauri/handbook/turkce/01-getting-started.md +193 -0
  26. package/payload/projects/tauri/handbook/turkce/02-the-project.md +272 -0
  27. package/payload/projects/tauri/handbook/turkce/03-the-page.md +272 -0
  28. package/payload/projects/tauri/handbook/turkce/04-commands.md +271 -0
  29. package/payload/projects/tauri/handbook/turkce/05-events-and-state.md +284 -0
  30. package/payload/projects/tauri/handbook/turkce/06-plugins.md +286 -0
  31. package/payload/projects/tauri/handbook/turkce/07-the-window-and-the-app.md +433 -0
  32. package/payload/projects/tauri/handbook/turkce/08-security.md +384 -0
  33. package/payload/projects/tauri/handbook/turkce/09-tests-and-checks.md +275 -0
  34. package/payload/projects/tauri/handbook/turkce/10-building-and-releasing.md +241 -0
  35. package/payload/projects/tauri/handbook/turkce/11-troubleshooting.md +264 -0
  36. package/payload/projects/tauri/handbook/turkce/README.md +128 -0
  37. package/payload/projects/tauri/images/app.png +0 -0
  38. package/payload/projects/tauri/src-tauri/Cargo.lock +4389 -0
  39. package/payload/projects/tauri/src-tauri/Cargo.toml +31 -0
  40. package/payload/projects/tauri/src-tauri/app-icon.svg +16 -0
  41. package/payload/projects/tauri/src-tauri/build.rs +15 -0
  42. package/payload/projects/tauri/src-tauri/capabilities/default.json +7 -0
  43. package/payload/projects/tauri/src-tauri/gitignore +5 -0
  44. package/payload/projects/tauri/src-tauri/icons/128x128.png +0 -0
  45. package/payload/projects/tauri/src-tauri/icons/128x128@2x.png +0 -0
  46. package/payload/projects/tauri/src-tauri/icons/32x32.png +0 -0
  47. package/payload/projects/tauri/src-tauri/icons/icon.icns +0 -0
  48. package/payload/projects/tauri/src-tauri/icons/icon.ico +0 -0
  49. package/payload/projects/tauri/src-tauri/src/check.rs +144 -0
  50. package/payload/projects/tauri/src-tauri/src/files.rs +255 -0
  51. package/payload/projects/tauri/src-tauri/src/main.rs +45 -0
  52. package/payload/projects/tauri/src-tauri/src/sizes.rs +214 -0
  53. package/payload/projects/tauri/src-tauri/tauri.conf.json +44 -0
  54. package/payload/projects/tauri/src-tauri/tests/project.rs +243 -0
  55. package/payload/projects/tauri/ui/app.js +459 -0
  56. package/payload/projects/tauri/ui/backend.js +196 -0
  57. package/payload/projects/tauri/ui/basic/LICENSE +14 -0
  58. package/payload/projects/tauri/ui/basic/basic.min.css +1 -0
  59. package/payload/projects/tauri/ui/basic/basic.min.js +78 -0
  60. package/payload/projects/tauri/ui/basic/font/open-sans/LICENSE.txt +206 -0
  61. package/payload/projects/tauri/ui/basic/font/open-sans/OpenSans-Bold.ttf +0 -0
  62. package/payload/projects/tauri/ui/basic/font/open-sans/OpenSans-Regular.ttf +0 -0
  63. package/payload/projects/tauri/ui/basic/scroll-bar.min.js +3 -0
  64. package/payload/projects/tauri/ui/comp/_sources.txt +9 -0
  65. package/payload/projects/tauri/ui/comp/components.min.js +21 -0
  66. package/payload/projects/tauri/ui/index.html +28 -0
  67. package/payload/projects/tauri/ui/sizes.js +104 -0
  68. package/payload/starter/_basic/VERSION +1 -1
  69. package/payload/starter/_basic/comp/bottom-bar.js +31 -3
  70. package/payload/starter/_basic/comp/code-editor.js +219 -1
  71. package/payload/starter/_basic/comp/context-menu.js +6 -1
  72. package/payload/starter/_basic/comp/markdown-view.js +4 -2
  73. package/payload/starter/_basic/comp/phone-field.js +13 -5
  74. package/payload/starter/_basic/comp/property-panel.js +1 -1
  75. package/payload/starter/_basic/comp/slider.js +27 -12
  76. package/payload/starter/_basic/comp/smart-button.js +5 -1
  77. package/payload/starter/_basic/comp/smart-table.js +8 -1
  78. package/payload/starter/_basic/comp/stepper.js +29 -3
  79. package/payload/starter/_basic/comp/toggle.js +2 -1
  80. package/payload/starter/_basic/docs/component-index.md +53 -53
  81. package/payload/starter/_basic/examples/code-editor.htm +48 -1
  82. package/payload/starter/_basic/examples/gallery-styled.htm +896 -0
  83. package/payload/starter/_basic/examples/search-input.htm +1 -1
  84. package/payload/starter/_basic/examples/select-box-2-item-view.htm +304 -0
  85. package/payload/starter/_basic/examples/{slider-2-classic.htm → slider-2-split.htm} +36 -2
  86. package/payload/starter/_basic/examples/stepper-2.htm +22 -6
  87. package/payload/starter/_basic/min/bottom-bar.min.js +1 -1
  88. package/payload/starter/_basic/min/code-editor.min.js +1 -1
  89. package/payload/starter/_basic/min/context-menu.min.js +1 -1
  90. package/payload/starter/_basic/min/markdown-view.min.js +1 -1
  91. package/payload/starter/_basic/min/phone-field.min.js +1 -1
  92. package/payload/starter/_basic/min/slider.min.js +1 -1
  93. package/payload/starter/_basic/min/smart-button.min.js +1 -1
  94. package/payload/starter/_basic/min/smart-table.min.js +1 -1
  95. package/payload/starter/_basic/min/stepper.min.js +1 -1
  96. package/payload/starter/_basic/min/toggle.min.js +1 -1
  97. package/payload/starter/_basic/tools/check.js +13 -2
@@ -0,0 +1,265 @@
1
+ # 4. Commands
2
+
3
+ *Türkçe: [4. Komutlar](turkce/04-commands.md)*
4
+
5
+ A command is a Rust function that the page calls and waits for. This chapter reads the command of the template line
6
+ by line, then adds one of your own: a preview of a text file, with its test and its sample answer.
7
+
8
+ ## The idea
9
+
10
+ ```text
11
+ the page (ui/backend.js) Rust (src-tauri/src/files.rs)
12
+ invoke("list_folder", { path, showHidden }) --> list_folder(app, path, show_hidden)
13
+ .then(folder) or .catch(error) <-- Ok(Folder) or Err(String)
14
+ ```
15
+
16
+ The page gives a name and an object of arguments. Tauri finds the command of that name, turns the arguments into Rust
17
+ values, runs it and sends its answer back as JSON. The page gets a promise. There is no server and no port.
18
+
19
+ ## The command of the template, line by line
20
+
21
+ `src-tauri/src/files.rs`:
22
+
23
+ ```rust
24
+ #[tauri::command(async)]
25
+ pub fn list_folder(
26
+ app: tauri::AppHandle,
27
+ path: String,
28
+ show_hidden: bool,
29
+ ) -> Result<Folder, String> {
30
+ let folder = if path.is_empty() {
31
+ app.path().home_dir().map_err(|error| error.to_string())?
32
+ } else {
33
+ PathBuf::from(path)
34
+ };
35
+ read_folder(&folder, show_hidden)
36
+ }
37
+ ```
38
+
39
+ - `#[tauri::command(async)]` makes the function a command (`(async)`: "Which thread runs a command" below). `pub fn`
40
+ is a function that other files (`main.rs`) may use.
41
+ - Every argument has a type: `path: String` is a text, `show_hidden: bool` is `true` or `false`; the page sends them.
42
+ Tauri gives the others itself, wherever they stand in the list: `app: tauri::AppHandle` (the app: its folders with
43
+ `app.path()`, its events, its state), `state: tauri::State<T>` (a value the app keeps for its commands, chapter 5)
44
+ and `window: tauri::WebviewWindow` (the window that called; tried: its `label()` is `"main"`).
45
+ - `-> Result<Folder, String>`: the answer is `Ok(a Folder)`, or `Err(a text)`. The last line without `;` is the
46
+ answer of a function: here the answer of `read_folder`.
47
+ - A `String` is a text the function owns. `&` lends a value without giving it away (`&folder`): a lent text is a
48
+ `&str`, a lent path a `&Path`.
49
+ - `|error| error.to_string()` is a small function, as `function (error) { return String(error); }`. `map_err` turns
50
+ the error of `home_dir()` into a text with it; `?` gives the value of an `Ok`, or ends the command with the `Err`.
51
+
52
+ ## The three places of a command
53
+
54
+ 1. **The function** with `#[tauri::command]` in a file of `src-tauri/src/`. A file is a *module*: `mod files;` at the
55
+ top of `main.rs` makes `files.rs` a part of the app.
56
+ 2. **Its name** in `tauri::generate_handler![...]` of `src-tauri/src/main.rs`, with its module: `files::list_folder`.
57
+ 3. **A function of `Backend`** in `ui/backend.js`, with its sample answer for a browser:
58
+
59
+ ```js
60
+ Backend.listFolder = function (path, showHidden) {
61
+ if (!Backend.isInApp()) return Backend.listSampleFolder(path, showHidden);
62
+ return window.__TAURI__.core.invoke("list_folder", { path: path, showHidden: showHidden });
63
+ };
64
+ ```
65
+
66
+ **The names.** The page calls a command by the name of its function (`"list_folder"`). The keys of the arguments are
67
+ the names of Rust in camelCase: `show_hidden` is `showHidden`; a key written as in Rust is not read, and the call
68
+ fails as if it was missing. `#[tauri::command(rename_all = "snake_case")]` makes one command take the names of Rust
69
+ as they are (tried); the template does not use it.
70
+
71
+ ## A command of your own: a preview
72
+
73
+ A click on a file shows its first characters in a message. Rust reads only the start of the file, so a file of some
74
+ GB costs nothing.
75
+
76
+ **1. The command:** a new file, `preview.rs` in `src-tauri/src/` (with the header of the other files):
77
+
78
+ ```rust
79
+ use serde::Serialize;
80
+ use std::fs::File;
81
+ use std::io::Read;
82
+ use std::path::Path;
83
+
84
+ // WHY two limits: a file can be some GB, so only its start is read; the page shows fewer characters than that
85
+ const MAX_READ_BYTES: u64 = 4096;
86
+ const PREVIEW_LENGTH: usize = 200; // characters
87
+
88
+ #[derive(Serialize)]
89
+ #[serde(rename_all = "camelCase")]
90
+ pub struct Preview {
91
+ text: String, // the first PREVIEW_LENGTH characters
92
+ is_cut: bool, // the file has more
93
+ }
94
+
95
+ /// The first characters of a text file. An Err reaches JavaScript as a rejected promise with its text.
96
+ #[tauri::command(async)]
97
+ pub fn preview_file(path: String) -> Result<Preview, String> {
98
+ read_preview(Path::new(&path))
99
+ }
100
+
101
+ // WHY without Tauri: the test below calls it
102
+ pub fn read_preview(path: &Path) -> Result<Preview, String> {
103
+ let file = File::open(path).map_err(|error| format!("{}: {}", path.display(), error))?;
104
+ let mut bytes = Vec::new();
105
+ file.take(MAX_READ_BYTES)
106
+ .read_to_end(&mut bytes)
107
+ .map_err(|error| format!("{}: {}", path.display(), error))?;
108
+
109
+ // WHY: a 0 byte is in pictures, archives and programs, not in a text
110
+ if bytes.contains(&0) {
111
+ return Err(format!("{}: not a text file", path.display()));
112
+ }
113
+ let text = String::from_utf8_lossy(&bytes);
114
+ Ok(Preview {
115
+ text: text.chars().take(PREVIEW_LENGTH).collect(),
116
+ is_cut: text.chars().count() > PREVIEW_LENGTH,
117
+ })
118
+ }
119
+ ```
120
+
121
+ - `use` brings names of crates and modules into the file (`std` is the library that comes with Rust).
122
+ - A `struct` is an object whose fields and types are fixed. `#[derive(Serialize)]` lets the crate serde write it as
123
+ JSON; `rename_all = "camelCase"` writes `is_cut` as `isCut`, the name the page reads.
124
+ - `u64` is a whole number from 0, `usize` a count, `f64` a number with a fraction: numbers in JavaScript. `Vec` is a
125
+ list (an array). `Option<String>` (Ex: `parent` in the `Folder` of `list_folder`) is `Some(a text)` or `None`;
126
+ `None` is `null` in the page (tried: the root `/` has `parent: null`).
127
+ - `let mut` may change. `file.take(MAX_READ_BYTES)` reads at most 4096 bytes; `read_to_end` puts them into `bytes`,
128
+ lent with the right to change it (`&mut`). `format!` makes a text, as a template string does.
129
+ - `String::from_utf8_lossy` reads the bytes as UTF-8 (a byte that is not UTF-8 becomes `�`). The command only calls
130
+ `read_preview`, a function of plain values, which can be tested without a window.
131
+
132
+ **2. Its test**, at the end of the same file:
133
+
134
+ ```rust
135
+ #[cfg(test)]
136
+ mod tests {
137
+ use super::*;
138
+ use std::fs;
139
+
140
+ #[test]
141
+ fn a_text_file_gives_its_first_characters() {
142
+ let folder =
143
+ std::env::temp_dir().join(format!("tauri-starter-preview-{}", std::process::id()));
144
+ fs::create_dir_all(&folder).unwrap();
145
+ fs::write(folder.join("short.txt"), "hello").unwrap();
146
+ fs::write(folder.join("long.txt"), "a".repeat(PREVIEW_LENGTH + 1)).unwrap();
147
+ fs::write(folder.join("picture.png"), [137, 80, 78, 71, 0, 0]).unwrap();
148
+ let short = read_preview(&folder.join("short.txt")).unwrap();
149
+ assert_eq!(short.text, "hello");
150
+ assert!(!short.is_cut);
151
+ let long = read_preview(&folder.join("long.txt")).unwrap();
152
+ assert_eq!(long.text.chars().count(), PREVIEW_LENGTH);
153
+ assert!(long.is_cut);
154
+ let picture = read_preview(&folder.join("picture.png")).err().unwrap();
155
+ assert!(picture.ends_with("not a text file"));
156
+ fs::remove_dir_all(&folder).unwrap();
157
+ }
158
+ }
159
+ ```
160
+
161
+ `cargo test` in `src-tauri/` now gives `7 passed` for `src/`. Reading and writing tests:
162
+ [9. Tests and checks](09-tests-and-checks.md).
163
+
164
+ **3. Into the app.** In `src-tauri/src/main.rs`: `mod preview;` under `mod files;`, and `preview::preview_file` at
165
+ the end of the list of `generate_handler!` (with a comma after `sizes::stop_measure`).
166
+
167
+ **4. The call**, in `ui/backend.js` after `Backend.listFolder` (and its sample text next to `SAMPLE_CHOSEN_FOLDER`):
168
+
169
+ ```js
170
+ // The first characters of a text file. The answer: { text, isCut }
171
+ Backend.previewFile = function (path) {
172
+ if (!Backend.isInApp()) return Promise.resolve({ text: Backend.SAMPLE_PREVIEW, isCut: false });
173
+ return window.__TAURI__.core.invoke("preview_file", { path: path });
174
+ };
175
+
176
+ Backend.SAMPLE_PREVIEW = "Buy milk and bread. Call the bank about the letter of Monday."; // every file in a browser
177
+ ```
178
+
179
+ **5. The page.** In `ui/app.js`, a click on a file did nothing (`if (!row.isFolder) return;` in `onRowClick`). Make
180
+ that line `if (!row.isFolder) { showPreview(row); return; }` (on four lines), and add the function:
181
+
182
+ ```js
183
+ // A file: its first characters in a toast. WHY the key: a click on another file uses the same toast.
184
+ const showPreview = function (row) {
185
+ Backend.previewFile(row.path)
186
+ .then(function (preview) {
187
+ const text = preview.isCut ? preview.text + "…" : preview.text;
188
+ Toast.info(text || "An empty file", { key: "preview", titleText: row.name });
189
+ })
190
+ .catch(function (error) {
191
+ Toast.error(String(error), { key: "preview", titleText: "No preview" });
192
+ });
193
+ };
194
+ ```
195
+
196
+ Run `cargo tauri dev` and click a text file; a picture says `...: not a text file`.
197
+
198
+ - `.then` gets the value of the `Ok`; `.catch` gets the text of the `Err`, a string (not an `Error` object), Ex:
199
+ `/Users/me/notes.txt: No such file or directory (os error 2)`. In an `async` function: `await` in a `try`.
200
+ - A command with no `->` (`stop_measure`) answers `null`. `Toast` writes its texts as plain text (no HTML).
201
+
202
+ **6. A step of the window check** (`checks/window-check.js`, after "the table shows the entries"); the check prints
203
+ one line more, `PASS a preview gives the start of a file: hello`:
204
+
205
+ ```js
206
+ // A command of chapter 4 of the handbook
207
+ const preview = await Backend.previewFile(WindowCheck.entryOf("a-file.txt").path);
208
+ const isPreviewRight = preview.text == "hello" && preview.isCut === false;
209
+ WindowCheck.expect(isPreviewRight, "a preview gives the start of a file: " + preview.text);
210
+ ```
211
+
212
+ ## Which thread runs a command
213
+
214
+ - **A plain `#[tauri::command]`** runs on the main thread, the one that draws the window. Measured on an Apple M1 with
215
+ 8 GB (2026-11-27, `cargo run`): a plain command that took 1.5 s let the page draw 1 frame (not about 90), and a
216
+ `list_folder` called in that time was answered after 1.4 s.
217
+ - **`#[tauri::command(async)]`** runs on another thread: with the same command the page drew 91 frames, and the
218
+ `list_folder` was answered in 5 ms. An **`async fn`** runs off the main thread too, and waits with `.await`.
219
+ - A command that reads the disk or the network is `(async)`, as `list_folder` and `preview_file`. `measure_folder` is
220
+ plain on purpose: it starts a thread and answers at once. A job of seconds with steps to tell: chapter 5.
221
+
222
+ ## Big answers
223
+
224
+ An answer is one JSON text: a folder of 100,000 entries is about 15 MB, read by Rust in 226 ms and in the page after
225
+ 302 ms (the release build, Apple M1 with 8 GB, 2026-11-04). `MAX_ENTRIES` in `files.rs` stops the list there (`total`
226
+ tells how many there are). For more, send it in parts: an argument for the first entry, or events (chapter 5).
227
+
228
+ ## What the project tests catch
229
+
230
+ The compiler does not see a name that is only on one side, so `cargo test` reads the files
231
+ (`src-tauri/tests/project.rs`). Without `preview::preview_file` in `generate_handler!`:
232
+
233
+ ```text
234
+ the page calls invoke("preview_file"), but generate_handler! of src/main.rs has no preview_file
235
+ ```
236
+
237
+ The second test names the function too (`preview_file is written with #[tauri::command], but it is not in
238
+ generate_handler!...`), and the compiler warns that `preview_file` is never used. The tests look for `invoke("...")`
239
+ with the name written in it: keep the name in the call, not in a variable. All four project tests: chapter 9.
240
+
241
+ ## The usual mistakes
242
+
243
+ What the page sent, and the error of its promise (tried in the window):
244
+
245
+ ```text
246
+ invoke("list_foldr", ...)
247
+ Command list_foldr not found
248
+ { path: "" } or { path: "", show_hidden: false }
249
+ invalid args `showHidden` for command `list_folder`: command list_folder missing required key showHidden
250
+ { path: 5, showHidden: false }
251
+ invalid args `path` for command `list_folder`: invalid type: integer `5`, expected a string
252
+ { path: "", showHidden: "yes" }
253
+ invalid args `showHidden` for command `list_folder`: invalid type: string "yes", expected a boolean
254
+ invoke("measure_folder", { path: "/x", job: -1 })
255
+ invalid args `job` for command `measure_folder`: invalid value: integer `-1`, expected u32
256
+ ```
257
+
258
+ - A key that Rust does not have is no error: it is left out. An `Option<String>` argument may be left out or `null`:
259
+ Rust gets `None` (tried).
260
+ - A command whose `State` the app does not keep: chapter 5. More: [11. Troubleshooting](11-troubleshooting.md).
261
+
262
+ ## Next
263
+
264
+ [5. Events and state](05-events-and-state.md): when one answer is not enough. Rust tells the page how a long job goes,
265
+ and the app keeps a value for its commands.
@@ -0,0 +1,275 @@
1
+ # 5. Events and state
2
+
3
+ *Türkçe: [5. Olaylar ve durum](turkce/05-events-and-state.md)*
4
+
5
+ A command answers once. An event is for what comes later: the steps of a long job, or a thing that happens by itself.
6
+ This chapter reads "Sizes", the events of the template, and the state its commands share; then it adds a watch of the
7
+ open folder: a file added in Finder or Explorer appears in the list by itself.
8
+
9
+ ## When an answer is not enough
10
+
11
+ A long job: "Sizes" on `/usr` (68,000 files) took 1.7 s, and the page showed its progress 17 times meanwhile (the
12
+ release build, Apple M1 with 8 GB, 2026-11-04). A thing that happens by itself: a file appears in the open folder, and
13
+ nobody asked. Rust sends an event any number of times; the page listens to it:
14
+
15
+ ```text
16
+ the page (ui/sizes.js) Rust (src-tauri/src/sizes.rs)
17
+ invoke("measure_folder", { path, job }) --> starts a thread, answers at once (null)
18
+ listen("measure-progress", ...) <-- app.emit("measure-progress", { job, files, bytes }) many times
19
+ listen("measure-folder", ...) <-- app.emit("measure-folder", { job, path, files, bytes })
20
+ listen("measure-done", ...) <-- app.emit("measure-done", { job, files, bytes, millis, stopped })
21
+ ```
22
+
23
+ ## Rust sends: app.emit
24
+
25
+ ```rust
26
+ use tauri::{AppHandle, Emitter, State};
27
+
28
+ let _ = app.emit("measure-folder", folder_size); // folder_size: a FolderSize, a struct of sizes.rs
29
+ ```
30
+
31
+ - `emit` is a function of the trait `Emitter`: a trait gives a type more functions, and they are there only where the
32
+ trait is in `use`. Without it the compiler says ``no method named `emit` found for reference `&AppHandle` `` and,
33
+ under it, ``trait `Emitter` which provides `emit` is implemented but not in scope``.
34
+ - The payload is a struct with `#[derive(Clone, Serialize)]`: `Serialize` sends it as JSON, `Clone` is asked by
35
+ `emit` (without it: ``the trait bound `FolderSize: Clone` is not satisfied``). Two words in a name need
36
+ `#[serde(rename_all = "camelCase")]` ([4. Commands](04-commands.md)). `let _ =` drops the answer of `emit`.
37
+ - A name has only letters, digits, `-`, `/`, `:` and `_`. Another letter is an error of the page: ``invalid args
38
+ `event` for command `listen`: Event name must include only alphanumeric characters, `-`, `/`, `:` and `_`.``
39
+
40
+ ## The page listens
41
+
42
+ `Backend.listen(eventName, handler)` of `ui/backend.js` calls `window.__TAURI__.event.listen(eventName, ...)` in the
43
+ app, and keeps the handler for `Backend.emitSample(eventName, payload)` in a browser.
44
+
45
+ - The event that `listen` gets has `event` (its name), `id` and `payload`; the handler of `Backend.listen` gets the
46
+ payload. Listen once, when the page starts (`Sizes.listen()`): every `listen` adds one more handler.
47
+ - **An event sent before the page listens is lost** (tried: 0 of 1 arrived). That is why the template listens first.
48
+ - `Backend.listen` listens for the whole life of the page. `listen` itself gives a promise of a function that stops
49
+ it (tried: a stopped handler got nothing): `const stopListening = await window.__TAURI__.event.listen(name, fn);`,
50
+ then `stopListening();`. `once` takes only the first event (tried: 1 of 2).
51
+
52
+ ## "Sizes", step by step
53
+
54
+ **1. The page gives the job a number** and starts it (`Sizes.start()` in `ui/sizes.js`): `Sizes.lastJob++`,
55
+ `Sizes.job = Sizes.lastJob`, then `Backend.measureFolder(currentFolder.path, Sizes.job)`.
56
+
57
+ **2. The command starts a thread and answers** (`src-tauri/src/sizes.rs`):
58
+
59
+ ```rust
60
+ #[tauri::command]
61
+ pub fn measure_folder(app: AppHandle, measure: State<Measure>, path: String, job: u32) {
62
+ let stop = Arc::new(AtomicBool::new(false));
63
+ let old_stop = measure.stop_flag.lock().unwrap().replace(stop.clone());
64
+ if let Some(old_stop) = old_stop {
65
+ old_stop.store(true, Ordering::SeqCst);
66
+ }
67
+ std::thread::spawn(move || run_job(&app, job, &PathBuf::from(path), &stop));
68
+ }
69
+ ```
70
+
71
+ - `AtomicBool` is a `true` / `false` that two threads may read and write at once. `Arc` shares one value between
72
+ threads: `stop.clone()` is one more handle to the same flag. The flag of the job before is set: one job at a time.
73
+ - `std::thread::spawn(move || ...)` runs the function in a thread of its own; `move` gives it `app`, `path` and
74
+ `stop`. The command ends at once, so it is a plain command ([4. Commands](04-commands.md)).
75
+
76
+ **3. The thread sends events.** `run_job` measures each folder inside, sends `measure-folder` after each one and
77
+ `measure-done` at the end. `measure-progress` comes at most every `PROGRESS_INTERVAL` (100 ms): a folder of a million
78
+ files would send a million events otherwise.
79
+
80
+ **4. The page drops what is not its job:** every handler of `ui/sizes.js` starts with
81
+ `if (folderSize.job != Sizes.job) return;`. WHY the page gives the number, not Rust: an event of a small folder can
82
+ come before the answer of `measure_folder`, so the page must know the number before it asks.
83
+
84
+ **5. Stop.** `stop_measure` sets the flag; the thread sees it at its next folder and sends `measure-done` with
85
+ `stopped: true`.
86
+
87
+ ## State: .manage() and State<T>
88
+
89
+ ```rust
90
+ #[derive(Default)]
91
+ pub struct Measure {
92
+ stop_flag: Mutex<Option<Arc<AtomicBool>>>, // the stop flag of the running job
93
+ }
94
+ ```
95
+
96
+ - `.manage(sizes::Measure::default())` in `main.rs` gives Tauri one value of this type for the life of the app
97
+ (`#[derive(Default)]` makes `default()`: every field empty). A command takes it as `measure: State<Measure>`; a
98
+ place that has only the `AppHandle` (a thread) takes it with `app.state::<Measure>()` (and `use tauri::Manager`).
99
+ - Two commands can run at the same time on two threads. A `Mutex` lets one of them hold the value at a time:
100
+ `lock()` waits for its turn and gives the value; it is let go at the end of the line (or of the block).
101
+ `.unwrap()` stops the app only when a thread stopped while it held the lock.
102
+ - WHY state and not a global value: Rust allows a changing global only with care. A state is made once in `main.rs`,
103
+ has a type, and reaches only the commands that name it.
104
+ - A command whose state is not given to `.manage()` compiles, and fails when the page calls it (tried):
105
+ ``state not managed for field `watch` on command `watch_folder`. You must call `.manage()` before using this command``
106
+
107
+ ## A watch of the open folder
108
+
109
+ Rust looks at the open folder once a second. When its list changed (an entry added, deleted or renamed: then the
110
+ time of the folder changes), it sends `folder-changed`, and the page reads the folder again.
111
+
112
+ **1. The command and its thread:** a new file, `watch.rs` in `src-tauri/src/` (with the header of the other files):
113
+
114
+ ```rust
115
+ use serde::Serialize;
116
+ use std::fs;
117
+ use std::path::{Path, PathBuf};
118
+ use std::sync::Mutex;
119
+ use std::time::{Duration, SystemTime};
120
+ use tauri::{AppHandle, Emitter, Manager, State};
121
+
122
+ // WHY: one look at the folder in a second costs nothing, and a person does not wait longer for the new list
123
+ const WATCH_INTERVAL: Duration = Duration::from_secs(1);
124
+
125
+ /// The number of the watch that runs (0: none): kept by Tauri (.manage() in main.rs)
126
+ #[derive(Default)]
127
+ pub struct Watch {
128
+ job: Mutex<u32>,
129
+ }
130
+
131
+ #[derive(Clone, Serialize)]
132
+ struct FolderChanged {
133
+ job: u32,
134
+ path: String,
135
+ }
136
+
137
+ /// Watches a folder until the page watches another one. It answers at once: a thread looks at the folder.
138
+ #[tauri::command]
139
+ pub fn watch_folder(app: AppHandle, watch: State<Watch>, path: String, job: u32) {
140
+ *watch.job.lock().unwrap() = job;
141
+ std::thread::spawn(move || watch_until_replaced(&app, &PathBuf::from(path), job));
142
+ }
143
+
144
+ fn watch_until_replaced(app: &AppHandle, folder: &Path, job: u32) {
145
+ let mut last_change = changed_at(folder);
146
+ loop {
147
+ std::thread::sleep(WATCH_INTERVAL);
148
+ if !is_current(app, job) {
149
+ return;
150
+ }
151
+ let change = changed_at(folder);
152
+ if change == last_change {
153
+ continue;
154
+ }
155
+ last_change = change;
156
+ let changed = FolderChanged {
157
+ job,
158
+ path: folder.display().to_string(),
159
+ };
160
+ let _ = app.emit("folder-changed", changed);
161
+ }
162
+ }
163
+
164
+ // WHY app.state(): the thread has no State argument; the AppHandle gives the same state
165
+ fn is_current(app: &AppHandle, job: u32) -> bool {
166
+ let watch = app.state::<Watch>();
167
+ let current_job = *watch.job.lock().unwrap();
168
+ current_job == job
169
+ }
170
+
171
+ /// The time of the last change of the list of a folder (an entry added, deleted or renamed). None: not readable.
172
+ pub fn changed_at(folder: &Path) -> Option<SystemTime> {
173
+ fs::metadata(folder)
174
+ .and_then(|metadata| metadata.modified())
175
+ .ok()
176
+ }
177
+ ```
178
+
179
+ - `*watch.job.lock().unwrap() = job;` writes into the value that the lock gives (`*` is "the value itself").
180
+ - `loop` runs until `return`; `continue` goes to its next turn. The thread of an old watch ends at its next look.
181
+ - A test of `changed_at`, as the one of chapter 4: a folder in the temporary folder, `changed_at` before and after a
182
+ new file in it (wait 50 ms between them), `assert_ne!` of the two.
183
+ - Tried on macOS: a new file, a rename, a deletion and a new folder change the time of the folder; a file written
184
+ again, or a file in a folder inside, does not. A deleted folder gives `None`: one event, and the page shows its
185
+ error. The system can also report changes itself (the crate `notify` does it); one look a second needs no crate.
186
+
187
+ **2. Into the app.** In `src-tauri/src/main.rs`: `mod watch;`, `.manage(watch::Watch::default())` under the
188
+ `.manage(...)` of `sizes.rs`, and `watch::watch_folder` at the end of the list of `generate_handler!`.
189
+
190
+ **3. The call**, in `ui/backend.js` (to try the handler in a browser, type in the console:
191
+ `Backend.emitSample("folder-changed", { job: watchJob, path: currentFolder.path })`):
192
+
193
+ ```js
194
+ // Rust watches the folder and sends "folder-changed" { job, path } when an entry is added, deleted or renamed in
195
+ // it. Only the last folder is watched. In a browser the sample folders do not change: no event comes.
196
+ Backend.watchFolder = function (path, job) {
197
+ if (!Backend.isInApp()) return Promise.resolve(null);
198
+ return window.__TAURI__.core.invoke("watch_folder", { path: path, job: job });
199
+ };
200
+ ```
201
+
202
+ **4. The page** (`ui/app.js`): a number next to `let showHidden = false;`, the listener in `start()` next to
203
+ `Sizes.listen();`, two lines in the `if (isNewFolder)` block of `showFolder()`, and the handler:
204
+
205
+ ```js
206
+ let watchJob = 0; // the number of the last folder Rust watches
207
+
208
+ Backend.listen("folder-changed", onFolderChanged);
209
+
210
+ watchJob++;
211
+ Backend.watchFolder(folder.path, watchJob);
212
+
213
+ // Rust: an entry of the open folder was added, deleted or renamed. The folder is read again.
214
+ const onFolderChanged = function (changed) {
215
+ if (changed.job != watchJob) return;
216
+ openFolder(currentFolder.path);
217
+ };
218
+ ```
219
+
220
+ Run `cargo tauri dev`, open a folder, and add a file to it in Finder (or Explorer): the row is there about a second
221
+ later (tried on macOS: 0.7 to 1.6 s). The window check can not add a file (the page has no command for it): the test
222
+ of `changed_at` and this try are the proof.
223
+
224
+ ## An event from the page to Rust
225
+
226
+ The page can send an event too (`ui/backend.js`), and Rust listens to it in `.setup()` of the builder
227
+ (`src-tauri/src/main.rs`, after the `.manage(...)` lines, with `use tauri::Listener;` at the top of the file):
228
+
229
+ ```js
230
+ // An event of the page to Rust (app.listen() in main.rs). In a browser nobody listens.
231
+ Backend.emit = function (eventName, payload) {
232
+ if (!Backend.isInApp()) return Promise.resolve();
233
+ return window.__TAURI__.event.emit(eventName, payload);
234
+ };
235
+ ```
236
+
237
+ ```rust
238
+ // An event of the page (Backend.emit in ui/backend.js). Its payload is a JSON text, with its quotes.
239
+ .setup(|app| {
240
+ app.listen("folder-opened", |event| {
241
+ println!("the page opened {}", event.payload());
242
+ });
243
+ Ok(())
244
+ })
245
+ ```
246
+
247
+ - With `Backend.emit("folder-opened", folder.path)` in the `if (isNewFolder)` block, the terminal prints
248
+ `the page opened "/Users/me"` for every folder (tried); an object comes as `{"count":2,"path":"/x"}`. The window
249
+ check talks this way too: the page sends `check-done`, `src/check.rs` listens.
250
+ - Rust values from the payload: `serde_json::from_str`. `serde_json` is only for the window check in the template;
251
+ for the app, write `serde_json = "1"` and `window-check = []` in `Cargo.toml` (cargo refuses `dep:serde_json` for
252
+ a crate that is not optional).
253
+ - `.setup()` runs once, when the app starts: the place for what the whole app needs (a listener, a menu). `Ok(())`
254
+ is its answer: all went well. It runs under the window check too (tried), which is a plugin of its own.
255
+ - A command is better when the page wants an answer or a typed argument; an event, when it only tells.
256
+
257
+ ## Events and more windows
258
+
259
+ `app.emit` goes to every window; `app.emit_to("main", "name", payload)` to the window with that label. In the page,
260
+ `window.__TAURI__.event.listen` hears the events of every window (tried: it got an `emit_to("main", ...)` and one to
261
+ a label no window has); `window.__TAURI__.webviewWindow.getCurrentWebviewWindow().listen` hears only the events of
262
+ its own window (tried: only the one to `"main"`). More windows:
263
+ [7. The window and the app](07-the-window-and-the-app.md).
264
+
265
+ ## The usual mistakes
266
+
267
+ - **A name with a typo:** no error on either side; the page waits for an event that never comes. Copy the name.
268
+ - **Listening after Rust sent:** the event is lost. Listen in `start()`, before the first command.
269
+ - **An event of an old job:** it lands in the rows of another folder. Give every job a number and check it.
270
+ - **`listen` twice:** the handler runs twice ([11. Troubleshooting](11-troubleshooting.md)).
271
+
272
+ ## Next
273
+
274
+ [6. Plugins](06-plugins.md): a feature of Tauri with no Rust to write, its permission, and a second plugin that keeps
275
+ the settings of the app.