Эх сурвалжийг харах

docs(api): add example to all functions, closes #4322 (#4325)

Lucas Fernandes Nogueira 3 жил өмнө
parent
commit
a136d0ed5c

+ 16 - 0
tooling/api/src/app.ts

@@ -13,6 +13,11 @@ import { invokeTauriCommand } from './helpers/tauri'
 
 /**
  * Gets the application version.
+ * @example
+ * ```typescript
+ * import { getVersion } from '@tauri-apps/api/app';
+ * const appVersion = await getVersion();
+ * ```
  *
  * @returns A promise resolving to the application version.
  */
@@ -27,6 +32,11 @@ async function getVersion(): Promise<string> {
 
 /**
  * Gets the application name.
+ * @example
+ * ```typescript
+ * import { getName } from '@tauri-apps/api/app';
+ * const appName = await getName();
+ * ```
  *
  * @returns A promise resolving to application name.
  */
@@ -42,6 +52,12 @@ async function getName(): Promise<string> {
 /**
  * Gets the tauri version.
  *
+ * @example
+ * ```typescript
+ * import { getTauriVersion } from '@tauri-apps/api/app';
+ * const tauriVersion = await getTauriVersion();
+ * ```
+ *
  * @returns A promise resolving to tauri version.
  */
 async function getTauriVersion(): Promise<string> {

+ 15 - 0
tooling/api/src/cli.ts

@@ -36,6 +36,21 @@ interface CliMatches {
 
 /**
  * Parse the arguments provided to the current process and get the matches using the configuration defined `tauri.conf.json > tauri > cli`.
+ * @example
+ * ```typescript
+ * import { getMatches } from '@tauri-apps/api/cli';
+ * const matches = await getMatches();
+ * if (matches.subcommand?.name === 'run') {
+ *   // `./your-app run $ARGS` was executed
+ *   const args = matches.subcommand?.matches.args
+ *   if ('debug' in args) {
+ *     // `./your-app run --debug` was executed
+ *   }
+ * } else {
+ *   const args = matches.args
+ *   // `./your-app $ARGS` was executed
+ * }
+ * ```
  *
  * @returns A promise resolving to the parsed arguments.
  */

+ 11 - 0
tooling/api/src/clipboard.ts

@@ -13,6 +13,12 @@ import { invokeTauriCommand } from './helpers/tauri'
 
 /**
  * Writes a plain text to the clipboard.
+ * @example
+ * ```typescript
+ * import { writeText, readText } from '@tauri-apps/api/clipboard';
+ * await writeText('Tauri is awesome!');
+ * assert(await readText(), 'Tauri is awesome!');
+ * ```
  *
  * @returns A promise indicating the success or failure of the operation.
  */
@@ -28,6 +34,11 @@ async function writeText(text: string): Promise<void> {
 
 /**
  * Gets the clipboard content as plain text.
+ * @example
+ * ```typescript
+ * import { readText } from '@tauri-apps/api/clipboard';
+ * const clipboardText = await readText();
+ * ```
  *
  * @returns A promise resolving to the clipboard content as plain text.
  */

+ 64 - 0
tooling/api/src/dialog.ts

@@ -90,6 +90,41 @@ interface MessageDialogOptions {
  *
  * Note that the allowlist scope change is not persisted, so the values are cleared when the application is restarted.
  * You can save it to the filesystem using [tauri-plugin-persisted-scope](https://github.com/tauri-apps/tauri-plugin-persisted-scope).
+ * @example Open a selection dialog for image files
+ * ```typescript
+ * import { open } from '@tauri-apps/api/dialog';
+ * const selected = await open({
+ *   multiple: true,
+ *   filters: {
+ *     name: 'Image',
+ *     extensions: ['png', 'jpeg']
+ *   }
+ * });
+ * if (Array.isArray(selected)) {
+ *   // user selected multiple files
+ * } else if (selected === null) {
+ *   // user cancelled the selection
+ * } else {
+ *   // user selected a single file
+ * }
+ *
+ * @example Open a selection dialog for directories
+ * ```typescript
+ * import { open } from '@tauri-apps/api/dialog';
+ * import { appDir } from '@tauri-apps/api/path';
+ * const selected = await open({
+ *   directory: true,
+ *   multiple: true,
+ *   defaultPath: await appDir(),
+ * });
+ * if (Array.isArray(selected)) {
+ *   // user selected multiple directories
+ * } else if (selected === null) {
+ *   // user cancelled the selection
+ * } else {
+ *   // user selected a single directory
+ * }
+ * ```
  *
  * @returns A promise resolving to the selected path(s)
  */
@@ -118,6 +153,17 @@ async function open(
  *
  * Note that the allowlist scope change is not persisted, so the values are cleared when the application is restarted.
  * You can save it to the filesystem using [tauri-plugin-persisted-scope](https://github.com/tauri-apps/tauri-plugin-persisted-scope).
+ * @example Open a save dialog with a defined file extension
+ * ```typescript
+ * import { save } from '@tauri-apps/api/dialog';
+ * const filePath = await save({
+ *   multiple: true,
+ *   filters: {
+ *     name: 'Image',
+ *     extensions: ['stronghold']
+ *   }
+ * });
+ * ```
  *
  * @returns A promise resolving to the selected path.
  */
@@ -137,6 +183,12 @@ async function save(options: SaveDialogOptions = {}): Promise<string> {
 
 /**
  * Shows a message dialog with an `Ok` button.
+ * @example
+ * ```typescript
+ * import { message } from '@tauri-apps/api/dialog';
+ * await message('Tauri is awesome', 'Tauri');
+ * await message('File not found', { title: 'Tauri', type: 'error' });
+ * ```
  *
  * @param {string} message The message to show.
  * @param {string|MessageDialogOptions|undefined} options The dialog's options. If a string, it represents the dialog title.
@@ -161,6 +213,12 @@ async function message(
 
 /**
  * Shows a question dialog with `Yes` and `No` buttons.
+ * @example
+ * ```typescript
+ * import { ask } from '@tauri-apps/api/dialog';
+ * const yes = await ask('Are you sure?', 'Tauri');
+ * const yes2 = await ask('This action cannot be reverted. Are you sure?', { title: 'Tauri', type: 'warning' });
+ * ```
  *
  * @param {string} message The message to show.
  * @param {string|MessageDialogOptions|undefined} options The dialog's options. If a string, it represents the dialog title.
@@ -185,6 +243,12 @@ async function ask(
 
 /**
  * Shows a question dialog with `Ok` and `Cancel` buttons.
+ * @example
+ * ```typescript
+ * import { confirm } from '@tauri-apps/api/dialog';
+ * const confirm = await confirm('Are you sure?', 'Tauri');
+ * const confirm2 = await confirm('This action cannot be reverted. Are you sure?', { title: 'Tauri', type: 'warning' });
+ * ```
  *
  * @param {string} message The message to show.
  * @param {string|MessageDialogOptions|undefined} options The dialog's options. If a string, it represents the dialog title.

+ 26 - 0
tooling/api/src/event.ts

@@ -19,6 +19,16 @@ import type {
 
 /**
  * Listen to an event from the backend.
+ * @example Listen to the `error` event expecting a string payload
+ * ```typescript
+ * import { listen } from '@tauri-apps/api/event';
+ * const unlisten = await listen<string>('error', (event) => {
+ *   console.log(`Got error in window ${event.windowLabel}, payload: ${payload}`);
+ * });
+ *
+ * // removes the listener later
+ * await unlisten();
+ * ```
  *
  * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
  * @param handler Event handler callback.
@@ -33,6 +43,17 @@ async function listen<T>(
 
 /**
  * Listen to an one-off event from the backend.
+ * @example Listen to the `loaded` event that is only triggered once
+ * ```typescript
+ * import { once } from '@tauri-apps/api/event';
+ * interface LoadedPayload {
+ *   loggedIn: boolean,
+ *   token: string
+ * }
+ * const unlisten = await once<LoadedPayload>('loaded', (event) => {
+ *   console.log(`App is loaded, logggedIn: ${event.payload.loggedIn}, token: ${event.payload.token}`);
+ * });
+ * ```
  *
  * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
  * @param handler Event handler callback.
@@ -47,6 +68,11 @@ async function once<T>(
 
 /**
  * Emits an event to the backend.
+ * @example Emits the `frontend-loaded` event with the given payload
+ * ```typescript
+ * import { emit } from '@tauri-apps/api/event';
+ * await emit('frontend-loaded', { loggedIn: true, token: 'authToken' });
+ * ```
  *
  * @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
  * @param [payload] Event payload

+ 75 - 4
tooling/api/src/fs.ts

@@ -135,6 +135,11 @@ interface FileEntry {
 
 /**
  * Reads a file as an UTF-8 encoded string.
+ * @example Read the text file in the `$APPDIR/app.conf` path
+ * ```typescript
+ * import { readTextFile, BaseDirectory } from '@tauri-apps/api/fs';
+ * const contents = await readTextFile('app.conf', { dir: BaseDirectory.App });
+ * ```
  *
  * @param filePath Path to the file.
  * @param options Configuration object.
@@ -156,6 +161,11 @@ async function readTextFile(
 
 /**
  * Reads a file as byte array.
+ * @example Read the image file in the `$RESOURCEDIR/avatar.png` path
+ * ```typescript
+ * import { readBinaryFile, BaseDirectory } from '@tauri-apps/api/fs';
+ * const contents = await readBinaryFile('avatar.png', { dir: BaseDirectory.Resource });
+ * ```
  *
  * @param filePath Path to the file.
  * @param options Configuration object.
@@ -179,6 +189,11 @@ async function readBinaryFile(
 
 /**
  * Writes a UTF-8 text file.
+ * @example Write a text file to the `$APPDIR/app.conf` path
+ * ```typescript
+ * import { writeTextFile, BaseDirectory } from '@tauri-apps/api/fs';
+ * await writeTextFile('app.conf', 'file contents', { dir: BaseDirectory.App });
+ * ```
  *
  * @param path The file path.
  * @param contents The file contents.
@@ -193,6 +208,11 @@ async function writeTextFile(
 
 /**
  * Writes a UTF-8 text file.
+ * @example Write a text file to the `$APPDIR/app.conf` path
+ * ```typescript
+ * import { writeTextFile, BaseDirectory } from '@tauri-apps/api/fs';
+ * await writeTextFile({ path: 'app.conf', contents: 'file contents' }, { dir: BaseDirectory.App });
+ * ```
  *
  * @param file The object containing the file path and contents.
  * @param options Configuration object.
@@ -206,8 +226,9 @@ async function writeTextFile(
 /**
  * Writes a UTF-8 text file.
  *
- * @param file File configuration object.
- * @param options Configuration object.
+ * @param path File path or configuration object.
+ * @param contents File contents or options.
+ * @param options File options.
  * @returns A promise indicating the success or failure of the operation.
  */
 async function writeTextFile(
@@ -250,6 +271,11 @@ async function writeTextFile(
 
 /**
  * Writes a byte array content to a file.
+ * @example Write a binary file to the `$RESOURCEDIR/avatar.png` path
+ * ```typescript
+ * import { writeBinaryFile, BaseDirectory } from '@tauri-apps/api/fs';
+ * await writeBinaryFile('avatar.png', new Uint8Array([]), { dir: BaseDirectory.Resource });
+ * ```
  *
  * @param path The file path.
  * @param contents The file contents.
@@ -264,6 +290,11 @@ async function writeBinaryFile(
 
 /**
  * Writes a byte array content to a file.
+ * @example Write a binary file to the `$RESOURCEDIR/avatar.png` path
+ * ```typescript
+ * import { writeBinaryFile, BaseDirectory } from '@tauri-apps/api/fs';
+ * await writeBinaryFile({ path: 'avatar.png', contents: new Uint8Array([]) }, { dir: BaseDirectory.Resource });
+ * ```
  *
  * @param file The object containing the file path and contents.
  * @param options Configuration object.
@@ -277,8 +308,9 @@ async function writeBinaryFile(
 /**
  * Writes a byte array content to a file.
  *
- * @param file Write configuration object.
- * @param options Configuration object.
+ * @param path File path or configuration object.
+ * @param contents File contents or options.
+ * @param options File options.
  * @returns A promise indicating the success or failure of the operation.
  */
 async function writeBinaryFile(
@@ -322,6 +354,20 @@ async function writeBinaryFile(
 
 /**
  * List directory files.
+ * @example Reads the `$APPDIR/users` directory recursively
+ * ```typescript
+ * import { readDir, BaseDirectory } from '@tauri-apps/api/fs';
+ * const entries = await readDir('users', new Uint8Array([]), { dir: BaseDirectory.App, recursive: true });
+ *
+ * function processEntries(entries) {
+ *   for (const entry of entries) {
+ *     console.log(`Entry: ${entry.path}`);
+ *     if (entry.children !== null) {
+ *       processEntries(entry.children)
+ *     }
+ *   }
+ * }
+ * ```
  *
  * @param dir Path to the directory to read.
  * @param options Configuration object.
@@ -345,6 +391,11 @@ async function readDir(
  * Creates a directory.
  * If one of the path's parent components doesn't exist
  * and the `recursive` option isn't set to true, the promise will be rejected.
+ * @example Create the `$APPDIR/users` directory
+ * ```typescript
+ * import { createDir, BaseDirectory } from '@tauri-apps/api/fs';
+ * await createDir('users', { dir: BaseDirectory.App, recursive: true });
+ * ```
  *
  * @param dir Path to the directory to create.
  * @param options Configuration object.
@@ -367,6 +418,11 @@ async function createDir(
 /**
  * Removes a directory.
  * If the directory is not empty and the `recursive` option isn't set to true, the promise will be rejected.
+ * @example Remove the directory `$APPDIR/users`
+ * ```typescript
+ * import { removeDir, BaseDirectory } from '@tauri-apps/api/fs';
+ * await removeDir('users', { dir: BaseDirectory.App });
+ * ```
  *
  * @param dir Path to the directory to remove.
  * @param options Configuration object.
@@ -388,6 +444,11 @@ async function removeDir(
 
 /**
  * Copys a file to a destination.
+ * @example Copy the `$APPDIR/app.conf` file to `$APPDIR/app.conf.bk`
+ * ```typescript
+ * import { copyFile, BaseDirectory } from '@tauri-apps/api/fs';
+ * await copyFile('app.conf', 'app.conf.bk', { dir: BaseDirectory.App });
+ * ```
  *
  * @param source A path of the file to copy.
  * @param destination A path for the destination file.
@@ -412,6 +473,11 @@ async function copyFile(
 
 /**
  * Removes a file.
+ * @example Remove the `$APPDIR/app.conf` file
+ * ```typescript
+ * import { removeFile, BaseDirectory } from '@tauri-apps/api/fs';
+ * await removeFile('app.conf', { dir: BaseDirectory.App });
+ * ```
  *
  * @param file Path to the file to remove.
  * @param options Configuration object.
@@ -433,6 +499,11 @@ async function removeFile(
 
 /**
  * Renames a file.
+ * @example Rename the `$APPDIR/avatar.png` file
+ * ```typescript
+ * import { renameFile, BaseDirectory } from '@tauri-apps/api/fs';
+ * await renameFile('avatar.png', 'deleted.png', { dir: BaseDirectory.App });
+ * ```
  *
  * @param oldPath A path of the file to rename.
  * @param newPath A path of the new file name.

+ 29 - 0
tooling/api/src/globalShortcut.ts

@@ -30,6 +30,13 @@ export type ShortcutHandler = (shortcut: string) => void
 
 /**
  * Register a global shortcut.
+ * @example
+ * ```typescript
+ * import { register } from '@tauri-apps/api/globalShortcut';
+ * await register('CommandOrControl+Shift+C', () => {
+ *   console.log('Shortcut triggered');
+ * });
+ * ```
  *
  * @param shortcut Shortcut definition, modifiers and key separated by "+" e.g. CmdOrControl+Q
  * @param handler Shortcut handler callback - takes the triggered shortcut as argument
@@ -51,6 +58,13 @@ async function register(
 
 /**
  * Register a collection of global shortcuts.
+ * @example
+ * ```typescript
+ * import { registerAll } from '@tauri-apps/api/globalShortcut';
+ * await registerAll(['CommandOrControl+Shift+C', 'Ctrl+Alt+F12'], (shortcut) => {
+ *   console.log(`Shortcut ${shortcut} triggered`);
+ * });
+ * ```
  *
  * @param shortcuts Array of shortcut definitions, modifiers and key separated by "+" e.g. CmdOrControl+Q
  * @param handler Shortcut handler callback - takes the triggered shortcut as argument
@@ -72,6 +86,11 @@ async function registerAll(
 
 /**
  * Determines whether the given shortcut is registered by this application or not.
+ * @example
+ * ```typescript
+ * import { isRegistered } from '@tauri-apps/api/globalShortcut';
+ * const isRegistered = await isRegistered('CommandOrControl+P');
+ * ```
  *
  * @param shortcut Array of shortcut definitions, modifiers and key separated by "+" e.g. CmdOrControl+Q
  * @returns A promise resolving to the state.
@@ -88,6 +107,11 @@ async function isRegistered(shortcut: string): Promise<boolean> {
 
 /**
  * Unregister a global shortcut.
+ * @example
+ * ```typescript
+ * import { unregister } from '@tauri-apps/api/globalShortcut';
+ * await unregister('CmdOrControl+Space');
+ * ```
  *
  * @param shortcut shortcut definition, modifiers and key separated by "+" e.g. CmdOrControl+Q
  * @returns
@@ -104,6 +128,11 @@ async function unregister(shortcut: string): Promise<void> {
 
 /**
  * Unregisters all shortcuts registered by the application.
+ * @example
+ * ```typescript
+ * import { unregisterAll } from '@tauri-apps/api/globalShortcut';
+ * await unregisterAll();
+ * ```
  *
  * @returns
  */

+ 101 - 6
tooling/api/src/http.ts

@@ -88,10 +88,8 @@ class Body {
    * but you can set it to `multipart/form-data` if the Cargo feature `http-multipart` is enabled.
    *
    * Note that a file path must be allowed in the `fs` allowlist scope.
-   *
-   * # Examples
-   *
-   * ```js
+   * @example
+   * ```typescript
    * import { Body } from "@tauri-apps/api/http"
    * Body.form({
    *   key: 'value',
@@ -100,7 +98,7 @@ class Body {
    *     mime: 'image/jpeg', // optional
    *     fileName: 'image.jpg' // optional
    *   }
-   * })
+   * });
    * ```
    *
    * @param data The body data.
@@ -130,6 +128,14 @@ class Body {
 
   /**
    * Creates a new JSON body.
+   * @example
+   * ```typescript
+   * import { Body } from "@tauri-apps/api/http"
+   * Body.json({
+   *   registered: true,
+   *   name: 'tauri'
+   * });
+   * ```
    *
    * @param data The body JSON object.
    *
@@ -141,6 +147,11 @@ class Body {
 
   /**
    * Creates a new UTF-8 string body.
+   * @example
+   * ```typescript
+   * import { Body } from "@tauri-apps/api/http"
+   * Body.text('The body content as a string');
+   * ```
    *
    * @param data The body string.
    *
@@ -152,12 +163,17 @@ class Body {
 
   /**
    * Creates a new byte array body.
+   * @example
+   * ```typescript
+   * import { Body } from "@tauri-apps/api/http"
+   * Body.bytes(new Uint8Array([1, 2, 3]));
+   * ```
    *
    * @param data The body byte array.
    *
    * @return The body object ready to be used on the POST and PUT requests.
    */
-  static bytes(bytes: Uint8Array): Body {
+  static bytes(bytes: Iterable<number> | ArrayLike<number>): Body {
     // stringifying Uint8Array doesn't return an array of numbers, so we create one here
     return new Body('Bytes', Array.from(bytes))
   }
@@ -235,6 +251,12 @@ class Client {
 
   /**
    * Drops the client instance.
+   * @example
+   * ```typescript
+   * import { getClient } from '@tauri-apps/api/http';
+   * const client = await getClient();
+   * await client.drop();
+   * ```
    *
    * @returns
    */
@@ -250,6 +272,15 @@ class Client {
 
   /**
    * Makes an HTTP request.
+   * @example
+   * ```typescript
+   * import { getClient } from '@tauri-apps/api/http';
+   * const client = await getClient();
+   * const response = await client.request({
+   *   method: 'GET',
+   *   url: 'http://localhost:3003/users',
+   * });
+   * ```
    *
    * @param options The request options.
    * @returns A promise resolving to the response.
@@ -294,6 +325,16 @@ class Client {
 
   /**
    * Makes a GET request.
+   * @example
+   * ```typescript
+   * import { getClient, ResponseType } from '@tauri-apps/api/http';
+   * const client = await getClient();
+   * const response = await client.get('http://localhost:3003/users', {
+   *   timeout: 30,
+   *   // the expected response type
+   *   responseType: ResponseType.JSON
+   * });
+   * ```
    *
    * @param url The request URL.
    * @param options The request options.
@@ -309,6 +350,19 @@ class Client {
 
   /**
    * Makes a POST request.
+   * @example
+   * ```typescript
+   * import { getClient, Body, ResponseType } from '@tauri-apps/api/http';
+   * const client = await getClient();
+   * const response = await client.post('http://localhost:3003/users', {
+   *   body: Body.json({
+   *     name: 'tauri',
+   *     password: 'awesome'
+   *   }),
+   *   // in this case the server returns a simple string
+   *   responseType: ResponseType.Text,
+   * });
+   * ```
    *
    * @param url The request URL.
    * @param body The body of the request.
@@ -330,6 +384,20 @@ class Client {
 
   /**
    * Makes a PUT request.
+   * @example
+   * ```typescript
+   * import { getClient, Body } from '@tauri-apps/api/http';
+   * const client = await getClient();
+   * const response = await client.put('http://localhost:3003/users/1', {
+   *   body: Body.form({
+   *     file: {
+   *       file: '/home/tauri/avatar.png',
+   *       mime: 'image/png',
+   *       fileName: 'avatar.png'
+   *     }
+   *   })
+   * });
+   * ```
    *
    * @param url The request URL.
    * @param body The body of the request.
@@ -351,6 +419,14 @@ class Client {
 
   /**
    * Makes a PATCH request.
+   * @example
+   * ```typescript
+   * import { getClient, Body } from '@tauri-apps/api/http';
+   * const client = await getClient();
+   * const response = await client.patch('http://localhost:3003/users/1', {
+   *   body: Body.json({ email: 'contact@tauri.studio' })
+   * });
+   * ```
    *
    * @param url The request URL.
    * @param options The request options.
@@ -366,6 +442,12 @@ class Client {
 
   /**
    * Makes a DELETE request.
+   * @example
+   * ```typescript
+   * import { getClient } from '@tauri-apps/api/http';
+   * const client = await getClient();
+   * const response = await client.delete('http://localhost:3003/users/1');
+   * ```
    *
    * @param url The request URL.
    * @param options The request options.
@@ -382,6 +464,11 @@ class Client {
 
 /**
  * Creates a new client using the specified options.
+ * @example
+ * ```typescript
+ * import { getClient } from '@tauri-apps/api/http';
+ * const client = await getClient();
+ * ```
  *
  * @param options Client configuration.
  *
@@ -402,6 +489,14 @@ let defaultClient: Client | null = null
 
 /**
  * Perform an HTTP request using the default client.
+ * @example
+ * ```typescript
+ * import { fetch } from '@tauri-apps/api/http';
+ * const response = await fetch('http://localhost:3003/users/2', {
+ *   method: 'GET',
+ *   timeout: 30,
+ * });
+ * ```
  *
  * @param url The request URL.
  * @param options The fetch options.

+ 27 - 0
tooling/api/src/notification.ts

@@ -43,6 +43,11 @@ type Permission = 'granted' | 'denied' | 'default'
 
 /**
  * Checks if the permission to send notifications is granted.
+ * @example
+ * ```typescript
+ * import { isPermissionGranted } from '@tauri-apps/api/notification';
+ * const permissionGranted = await isPermissionGranted();
+ * ```
  *
  * @returns
  */
@@ -60,6 +65,15 @@ async function isPermissionGranted(): Promise<boolean> {
 
 /**
  * Requests the permission to send notifications.
+ * @example
+ * ```typescript
+ * import { isPermissionGranted, requestPermission } from '@tauri-apps/api/notification';
+ * let permissionGranted = await isPermissionGranted();
+ * if (!permissionGranted) {
+ *   const permission = await requestPermission();
+ *   permissionGranted = permission === 'granted';
+ * }
+ * ```
  *
  * @returns A promise resolving to whether the user granted the permission or not.
  */
@@ -69,6 +83,19 @@ async function requestPermission(): Promise<Permission> {
 
 /**
  * Sends a notification to the user.
+ * @example
+ * ```typescript
+ * import { isPermissionGranted, requestPermission, sendNotification } from '@tauri-apps/api/notification';
+ * let permissionGranted = await isPermissionGranted();
+ * if (!permissionGranted) {
+ *   const permission = await requestPermission();
+ *   permissionGranted = permission === 'granted';
+ * }
+ * if (permissionGranted) {
+ *   sendNotification('Tauri is awesome!');
+ *   sendNotification({ title: 'TAURI', body: 'Tauri is awesome!' });
+ * }
+ * ```
  *
  * @param options Notification options.
  */

+ 27 - 1
tooling/api/src/os.ts

@@ -37,6 +37,11 @@ const EOL = isWindows() ? '\r\n' : '\n'
 /**
  * Returns a string identifying the operating system platform.
  * The value is set at compile time. Possible values are `'linux'`, `'darwin'`, `'ios'`, `'freebsd'`, `'dragonfly'`, `'netbsd'`, `'openbsd'`, `'solaris'`, `'android'`, `'win32'`
+ * @example
+ * ```typescript
+ * import { platform } from '@tauri-apps/api/os';
+ * const platformName = await platform();
+ * ```
  */
 async function platform(): Promise<
   LiteralUnion<
@@ -63,6 +68,11 @@ async function platform(): Promise<
 
 /**
  * Returns a string identifying the kernel version.
+ * @example
+ * ```typescript
+ * import { version } from '@tauri-apps/api/os';
+ * const osVersion = await version();
+ * ```
  */
 async function version(): Promise<string> {
   return invokeTauriCommand<string>({
@@ -75,6 +85,11 @@ async function version(): Promise<string> {
 
 /**
  * Returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows.
+ * @example
+ * ```typescript
+ * import { type } from '@tauri-apps/api/os';
+ * const osType = await type();
+ * ```
  */
 async function type(): Promise<
   LiteralUnion<'Linux' | 'Darwin' | 'Windows_NT', string>
@@ -88,7 +103,13 @@ async function type(): Promise<
 }
 
 /**
- * Returns the operating system CPU architecture for which the tauri app was compiled. Possible values are `'x86'`, `'x86_64'`, `'arm'`, `'aarch64'`, `'mips'`, `'mips64'`, `'powerpc'`, `'powerpc64'`, `'riscv64'`, `'s390x'`, `'sparc64'`
+ * Returns the operating system CPU architecture for which the tauri app was compiled.
+ * Possible values are `'x86'`, `'x86_64'`, `'arm'`, `'aarch64'`, `'mips'`, `'mips64'`, `'powerpc'`, `'powerpc64'`, `'riscv64'`, `'s390x'`, `'sparc64'`.
+ * @example
+ * ```typescript
+ * import { arch } from '@tauri-apps/api/os';
+ * const archName = await arch();
+ * ```
  */
 async function arch(): Promise<
   LiteralUnion<
@@ -116,6 +137,11 @@ async function arch(): Promise<
 
 /**
  * Returns the operating system's default directory for temporary files as a string.
+ * @example
+ * ```typescript
+ * import { tempdir } from '@tauri-apps/api/os';
+ * const tempdirPath = await tempdir();
+ * ```
  */
 async function tempdir(): Promise<string> {
   return invokeTauriCommand<string>({

+ 147 - 1
tooling/api/src/path.ts

@@ -30,6 +30,11 @@ import { isWindows } from './helpers/os-check'
 /**
  * Returns the path to the suggested directory for your app config files.
  * Resolves to `${configDir}/${bundleIdentifier}`, where `bundleIdentifier` is the value configured on `tauri.conf.json > tauri > bundle > identifier`.
+ * @example
+ * ```typescript
+ * import { appDir } from '@tauri-apps/api/path';
+ * const appDirPath = await appDir();
+ * ```
  *
  * @returns
  */
@@ -52,6 +57,11 @@ async function appDir(): Promise<string> {
  * - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_MUSIC_DIR`.
  * - **macOS:** Resolves to `$HOME/Music`.
  * - **Windows:** Resolves to `{FOLDERID_Music}`.
+ * @example
+ * ```typescript
+ * import { audioDir } from '@tauri-apps/api/path';
+ * const audioDirPath = await audioDir();
+ * ```
  *
  * @returns
  */
@@ -74,6 +84,11 @@ async function audioDir(): Promise<string> {
  * - **Linux:** Resolves to `$XDG_CACHE_HOME` or `$HOME/.cache`.
  * - **macOS:** Resolves to `$HOME/Library/Caches`.
  * - **Windows:** Resolves to `{FOLDERID_LocalAppData}`.
+ * @example
+ * ```typescript
+ * import { cacheDir } from '@tauri-apps/api/path';
+ * const cacheDirPath = await cacheDir();
+ * ```
  *
  * @returns
  */
@@ -96,6 +111,11 @@ async function cacheDir(): Promise<string> {
  * - **Linux:** Resolves to `$XDG_CONFIG_HOME` or `$HOME/.config`.
  * - **macOS:** Resolves to `$HOME/Library/Application Support`.
  * - **Windows:** Resolves to `{FOLDERID_LocalAppData}`.
+ * @example
+ * ```typescript
+ * import { configDir } from '@tauri-apps/api/path';
+ * const configDirPath = await configDir();
+ * ```
  *
  * @returns
  */
@@ -118,6 +138,11 @@ async function configDir(): Promise<string> {
  * - **Linux:** Resolves to `$XDG_DATA_HOME` or `$HOME/.local/share`.
  * - **macOS:** Resolves to `$HOME/Library/Application Support`.
  * - **Windows:** Resolves to `{FOLDERID_RoamingAppData}`.
+ * @example
+ * ```typescript
+ * import { dataDir } from '@tauri-apps/api/path';
+ * const dataDirPath = await dataDir();
+ * ```
  *
  * @returns
  */
@@ -140,6 +165,11 @@ async function dataDir(): Promise<string> {
  * - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_DESKTOP_DIR`.
  * - **macOS:** Resolves to `$HOME/Library/Desktop`.
  * - **Windows:** Resolves to `{FOLDERID_Desktop}`.
+ * @example
+ * ```typescript
+ * import { desktopDir } from '@tauri-apps/api/path';
+ * const desktopPath = await desktopDir();
+ * ```
 
  * @returns
  */
@@ -156,6 +186,11 @@ async function desktopDir(): Promise<string> {
 
 /**
  * Returns the path to the user's document directory.
+ * @example
+ * ```typescript
+ * import { documentDir } from '@tauri-apps/api/path';
+ * const documentDirPath = await documentDir();
+ * ```
  *
  * #### Platform-specific
  *
@@ -184,6 +219,11 @@ async function documentDir(): Promise<string> {
  * - **Linux**: Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_DOWNLOAD_DIR`.
  * - **macOS**: Resolves to `$HOME/Downloads`.
  * - **Windows**: Resolves to `{FOLDERID_Downloads}`.
+ * @example
+ * ```typescript
+ * import { downloadDir } from '@tauri-apps/api/path';
+ * const downloadDirPath = await downloadDir();
+ * ```
  *
  * @returns
  */
@@ -206,6 +246,11 @@ async function downloadDir(): Promise<string> {
  * - **Linux:** Resolves to `$XDG_BIN_HOME/../bin` or `$XDG_DATA_HOME/../bin` or `$HOME/.local/bin`.
  * - **macOS:** Not supported.
  * - **Windows:** Not supported.
+ * @example
+ * ```typescript
+ * import { executableDir } from '@tauri-apps/api/path';
+ * const executableDirPath = await executableDir();
+ * ```
  *
  * @returns
  */
@@ -228,6 +273,11 @@ async function executableDir(): Promise<string> {
  * - **Linux:** Resolves to `$XDG_DATA_HOME/fonts` or `$HOME/.local/share/fonts`.
  * - **macOS:** Resolves to `$HOME/Library/Fonts`.
  * - **Windows:** Not supported.
+ * @example
+ * ```typescript
+ * import { fontDir } from '@tauri-apps/api/path';
+ * const fontDirPath = await fontDir();
+ * ```
  *
  * @returns
  */
@@ -250,6 +300,11 @@ async function fontDir(): Promise<string> {
  * - **Linux:** Resolves to `$HOME`.
  * - **macOS:** Resolves to `$HOME`.
  * - **Windows:** Resolves to `{FOLDERID_Profile}`.
+ * @example
+ * ```typescript
+ * import { homeDir } from '@tauri-apps/api/path';
+ * const homeDirPath = await homeDir();
+ * ```
  *
  * @returns
  */
@@ -272,6 +327,11 @@ async function homeDir(): Promise<string> {
  * - **Linux:** Resolves to `$XDG_DATA_HOME` or `$HOME/.local/share`.
  * - **macOS:** Resolves to `$HOME/Library/Application Support`.
  * - **Windows:** Resolves to `{FOLDERID_LocalAppData}`.
+ * @example
+ * ```typescript
+ * import { localDataDir } from '@tauri-apps/api/path';
+ * const localDataDirPath = await localDataDir();
+ * ```
  *
  * @returns
  */
@@ -294,6 +354,11 @@ async function localDataDir(): Promise<string> {
  * - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_PICTURES_DIR`.
  * - **macOS:** Resolves to `$HOME/Pictures`.
  * - **Windows:** Resolves to `{FOLDERID_Pictures}`.
+ * @example
+ * ```typescript
+ * import { pictureDir } from '@tauri-apps/api/path';
+ * const pictureDirPath = await pictureDir();
+ * ```
  *
  * @returns
  */
@@ -316,6 +381,11 @@ async function pictureDir(): Promise<string> {
  * - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_PUBLICSHARE_DIR`.
  * - **macOS:** Resolves to `$HOME/Public`.
  * - **Windows:** Resolves to `{FOLDERID_Public}`.
+ * @example
+ * ```typescript
+ * import { publicDir } from '@tauri-apps/api/path';
+ * const publicDirPath = await publicDir();
+ * ```
  *
  * @returns
  */
@@ -333,6 +403,11 @@ async function publicDir(): Promise<string> {
 /**
  * Returns the path to the application's resource directory.
  * To resolve a resource path, see the [[resolveResource | `resolveResource API`]].
+ * @example
+ * ```typescript
+ * import { resourceDir } from '@tauri-apps/api/path';
+ * const resourceDirPath = await resourceDir();
+ * ```
  *
  * @returns
  */
@@ -349,6 +424,11 @@ async function resourceDir(): Promise<string> {
 
 /**
  * Resolve the path to a resource file.
+ * @example
+ * ```typescript
+ * import { resolveResource } from '@tauri-apps/api/path';
+ * const resourcePath = await resolveResource('script.sh');
+ * ```
  *
  * @param resourcePath The path to the resource.
  * Must follow the same syntax as defined in `tauri.conf.json > tauri > bundle > resources`, i.e. keeping subfolders and parent dir components (`../`).
@@ -373,6 +453,11 @@ async function resolveResource(resourcePath: string): Promise<string> {
  * - **Linux:** Resolves to `$XDG_RUNTIME_DIR`.
  * - **macOS:** Not supported.
  * - **Windows:** Not supported.
+ * @example
+ * ```typescript
+ * import { runtimeDir } from '@tauri-apps/api/path';
+ * const runtimeDirPath = await runtimeDir();
+ * ```
  *
  * @returns
  */
@@ -395,6 +480,11 @@ async function runtimeDir(): Promise<string> {
  * - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_TEMPLATES_DIR`.
  * - **macOS:** Not supported.
  * - **Windows:** Resolves to `{FOLDERID_Templates}`.
+ * @example
+ * ```typescript
+ * import { templateDir } from '@tauri-apps/api/path';
+ * const templateDirPath = await templateDir();
+ * ```
  *
  * @returns
  */
@@ -417,6 +507,11 @@ async function templateDir(): Promise<string> {
  * - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_VIDEOS_DIR`.
  * - **macOS:** Resolves to `$HOME/Movies`.
  * - **Windows:** Resolves to `{FOLDERID_Videos}`.
+ * @example
+ * ```typescript
+ * import { videoDir } from '@tauri-apps/api/path';
+ * const videoDirPath = await videoDir();
+ * ```
  *
  * @returns
  */
@@ -439,6 +534,11 @@ async function videoDir(): Promise<string> {
  * - **Linux:** Resolves to `${configDir}/${bundleIdentifier}`.
  * - **macOS:** Resolves to `${homeDir}//Library/Logs/{bundleIdentifier}`
  * - **Windows:** Resolves to `${configDir}/${bundleIdentifier}`.
+ * @example
+ * ```typescript
+ * import { logDir } from '@tauri-apps/api/path';
+ * const logDirPath = await logDir();
+ * ```
  *
  * @returns
  */
@@ -469,6 +569,12 @@ const delimiter = isWindows() ? ';' : ':'
 
 /**
  * Resolves a sequence of `paths` or `path` segments into an absolute path.
+ * @example
+ * ```typescript
+ * import { resolve, appDir } from '@tauri-apps/api/path';
+ * const appDirPath = await appDir();
+ * const path = await resolve(appDirPath, '..', 'users', 'tauri', 'avatar.png');
+ * ```
  *
  * @param paths A sequence of paths or path segments.
  */
@@ -484,6 +590,12 @@ async function resolve(...paths: string[]): Promise<string> {
 
 /**
  * Normalizes the given `path`, resolving `'..'` and `'.'` segments and resolve symolic links.
+ * @example
+ * ```typescript
+ * import { normalize, appDir } from '@tauri-apps/api/path';
+ * const appDirPath = await appDir();
+ * const path = await normalize(appDirPath, '..', 'users', 'tauri', 'avatar.png');
+ * ```
  */
 async function normalize(path: string): Promise<string> {
   return invokeTauriCommand<string>({
@@ -497,6 +609,12 @@ async function normalize(path: string): Promise<string> {
 
 /**
  *  Joins all given `path` segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.
+ * @example
+ * ```typescript
+ * import { join, appDir } from '@tauri-apps/api/path';
+ * const appDirPath = await appDir();
+ * const path = await join(appDirPath, 'users', 'tauri', 'avatar.png');
+ * ```
  *
  * @param paths A sequence of path segments.
  */
@@ -512,6 +630,12 @@ async function join(...paths: string[]): Promise<string> {
 
 /**
  * Returns the directory name of a `path`. Trailing directory separators are ignored.
+ * @example
+ * ```typescript
+ * import { dirname, appDir } from '@tauri-apps/api/path';
+ * const appDirPath = await appDir();
+ * const dir = await dirname(appDirPath);
+ * ```
  */
 async function dirname(path: string): Promise<string> {
   return invokeTauriCommand<string>({
@@ -525,6 +649,13 @@ async function dirname(path: string): Promise<string> {
 
 /**
  * Returns the extension of the `path`.
+ * @example
+ * ```typescript
+ * import { extname, resolveResource } from '@tauri-apps/api/path';
+ * const resourcePath = await resolveResource('app.conf');
+ * const ext = await extname(resourcePath);
+ * assert(ext === 'conf');
+ * ```
  */
 async function extname(path: string): Promise<string> {
   return invokeTauriCommand<string>({
@@ -537,7 +668,14 @@ async function extname(path: string): Promise<string> {
 }
 
 /**
- *  Returns the last portion of a `path`. Trailing directory separators are ignored.
+ * Returns the last portion of a `path`. Trailing directory separators are ignored.
+ * @example
+ * ```typescript
+ * import { basename, resolveResource } from '@tauri-apps/api/path';
+ * const resourcePath = await resolveResource('app.conf');
+ * const base = await basename(resourcePath);
+ * assert(base === 'app');
+ * ```
  *
  * @param ext An optional file extension to be removed from the returned path.
  */
@@ -552,6 +690,14 @@ async function basename(path: string, ext?: string): Promise<string> {
   })
 }
 
+/**
+ * Returns whether the path is absolute or not.
+ * @example
+ * ```typescript
+ * import { isAbsolute } from '@tauri-apps/api/path';
+ * assert(await ibsolute('/home/tauri'));
+ * ```
+ */
 async function isAbsolute(path: string): Promise<boolean> {
   return invokeTauriCommand<boolean>({
     __tauriModule: 'Path',

+ 10 - 0
tooling/api/src/process.ts

@@ -13,6 +13,11 @@ import { invokeTauriCommand } from './helpers/tauri'
 
 /**
  * Exits immediately with the given `exitCode`.
+ * @example
+ * ```typescript
+ * import { exit } from '@tauri-apps/api/process';
+ * await exit(1);
+ * ```
  *
  * @param exitCode The exit code to use.
  * @returns A promise indicating the success or failure of the operation.
@@ -29,6 +34,11 @@ async function exit(exitCode: number = 0): Promise<void> {
 
 /**
  * Exits the current instance of the app then relaunches it.
+ * @example
+ * ```typescript
+ * import { relaunch } from '@tauri-apps/api/process';
+ * await relaunch();
+ * ```
  *
  * @returns A promise indicating the success or failure of the operation.
  */

+ 26 - 21
tooling/api/src/shell.ts

@@ -190,10 +190,11 @@ class Child {
    * @param data The message to write, either a string or a byte array.
    * @example
    * ```typescript
-   * const command = new Command('node')
-   * const child = await command.spawn()
-   * await child.write('message')
-   * await child.write([0, 1, 2, 3, 4, 5])
+   * import { Command } from '@tauri-apps/api/shell';
+   * const command = new Command('node');
+   * const child = await command.spawn();
+   * await child.write('message');
+   * await child.write([0, 1, 2, 3, 4, 5]);
    * ```
    *
    * @return A promise indicating the success or failure of the operation.
@@ -231,16 +232,17 @@ class Child {
  * It emits the `close` and `error` events.
  * @example
  * ```typescript
- * const command = new Command('node')
+ * import { Command } from '@tauri-apps/api/shell';
+ * const command = new Command('node');
  * command.on('close', data => {
  *   console.log(`command finished with code ${data.code} and signal ${data.signal}`)
- * })
- * command.on('error', error => console.error(`command error: "${error}"`))
- * command.stdout.on('data', line => console.log(`command stdout: "${line}"`))
- * command.stderr.on('data', line => console.log(`command stderr: "${line}"`))
+ * });
+ * command.on('error', error => console.error(`command error: "${error}"`));
+ * command.stdout.on('data', line => console.log(`command stdout: "${line}"`));
+ * command.stderr.on('data', line => console.log(`command stderr: "${line}"`));
  *
- * const child = await command.spawn()
- * console.log('pid:', child.pid)
+ * const child = await command.spawn();
+ * console.log('pid:', child.pid);
  * ```
  */
 class Command extends EventEmitter<'close' | 'error'> {
@@ -278,8 +280,9 @@ class Command extends EventEmitter<'close' | 'error'> {
    * Creates a command to execute the given sidecar program.
    * @example
    * ```typescript
-   * const command = Command.sidecar('my-sidecar')
-   * const output = await command.execute()
+   * import { Command } from '@tauri-apps/api/shell';
+   * const command = Command.sidecar('my-sidecar');
+   * const output = await command.execute();
    * ```
    *
    * @param program The program to execute.
@@ -331,11 +334,12 @@ class Command extends EventEmitter<'close' | 'error'> {
    * Executes the command as a child process, waiting for it to finish and collecting all of its output.
    * @example
    * ```typescript
-   * const output = await new Command('echo', 'message').execute()
-   * assert(output.code === 0)
-   * assert(output.signal === null)
-   * assert(output.stdout === 'message')
-   * assert(output.stderr === '')
+   * import { Command } from '@tauri-apps/api/shell';
+   * const output = await new Command('echo', 'message').execute();
+   * assert(output.code === 0);
+   * assert(output.signal === null);
+   * assert(output.stdout === 'message');
+   * assert(output.stderr === '');
    * ```
    *
    * @return A promise resolving to the child process output.
@@ -398,12 +402,13 @@ type CommandEvent =
  *
  * @example
  * ```typescript
+ * import { open } from '@tauri-apps/api/shell';
  * // opens the given URL on the default browser:
- * await open('https://github.com/tauri-apps/tauri')
+ * await open('https://github.com/tauri-apps/tauri');
  * // opens the given URL using `firefox`:
- * await open('https://github.com/tauri-apps/tauri', 'firefox')
+ * await open('https://github.com/tauri-apps/tauri', 'firefox');
  * // opens a file using the default program:
- * await open('/path/to/file')
+ * await open('/path/to/file');
  * ```
  *
  * @param path The path or URL to open.

+ 16 - 11
tooling/api/src/tauri.ts

@@ -60,6 +60,11 @@ interface InvokeArgs {
 
 /**
  * Sends a message to the backend.
+ * @example
+ * ```typescript
+ * import { invoke } from '@tauri-apps/api/tauri';
+ * await invoke('login', { user: 'tauri', password: 'poiwe3h4r5ip3yrhtew9ty' });
+ * ```
  *
  * @param cmd The command name.
  * @param args The optional arguments to pass to the command.
@@ -97,18 +102,18 @@ async function invoke<T>(cmd: string, args: InvokeArgs = {}): Promise<T> {
  * @param  protocol The protocol to use. Defaults to `asset`. You only need to set this when using a custom protocol.
  * @example
  * ```typescript
- * import { appDir, join } from '@tauri-apps/api/path'
- * import { convertFileSrc } from '@tauri-apps/api/tauri'
- * const appDirPath = await appDir()
- * const filePath = await join(appDir, 'assets/video.mp4')
- * const assetUrl = convertFileSrc(filePath)
+ * import { appDir, join } from '@tauri-apps/api/path';
+ * import { convertFileSrc } from '@tauri-apps/api/tauri';
+ * const appDirPath = await appDir();
+ * const filePath = await join(appDir, 'assets/video.mp4');
+ * const assetUrl = convertFileSrc(filePath);
  *
- * const video = document.getElementById('my-video')
- * const source = document.createElement('source')
- * source.type = 'video/mp4'
- * source.src = assetUrl
- * video.appendChild(source)
- * video.load()
+ * const video = document.getElementById('my-video');
+ * const source = document.createElement('source');
+ * source.type = 'video/mp4';
+ * source.src = assetUrl;
+ * video.appendChild(source);
+ * video.load();
  * ```
  *
  * @return the URL that can be used as source on the webview.

+ 15 - 0
tooling/api/src/updater.ts

@@ -31,6 +31,15 @@ interface UpdateResult {
 
 /**
  * Install the update if there's one available.
+ * @example
+ * ```typescript
+ * import { checkUpdate, installUpdate } from '@tauri-apps/api/updater';
+ * const update = await checkUpdate();
+ * if (update.shouldUpdate) {
+ *   console.log(`Installing update ${update.manifest?.version}, ${update.manifest?.date}, ${update.manifest.body}`);
+ *   await installUpdate();
+ * }
+ * ```
  *
  * @return A promise indicating the success or failure of the operation.
  */
@@ -83,6 +92,12 @@ async function installUpdate(): Promise<void> {
 
 /**
  * Checks if an update is available.
+ * @example
+ * ```typescript
+ * import { checkUpdate } from '@tauri-apps/api/updater';
+ * const update = await checkUpdate();
+ * // now run installUpdate() if needed
+ * ```
  *
  * @return Promise resolving to the update status.
  */

+ 291 - 27
tooling/api/src/window.ts

@@ -150,7 +150,16 @@ class PhysicalSize {
     this.height = height
   }
 
-  /** Converts the physical size to a logical one. */
+  /**
+   * Converts the physical size to a logical one.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const factor = await appWindow.scaleFactor();
+   * const size = await appWindow.innerSize();
+   * const logical = size.toLogical(factor);
+   * ```
+   *  */
   toLogical(scaleFactor: number): LogicalSize {
     return new LogicalSize(this.width / scaleFactor, this.height / scaleFactor)
   }
@@ -179,7 +188,16 @@ class PhysicalPosition {
     this.y = y
   }
 
-  /** Converts the physical position to a logical one. */
+  /**
+   * Converts the physical position to a logical one.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const factor = await appWindow.scaleFactor();
+   * const position = await appWindow.innerPosition();
+   * const logical = position.toLogical(factor);
+   * ```
+   * */
   toLogical(scaleFactor: number): LogicalPosition {
     return new LogicalPosition(this.x / scaleFactor, this.y / scaleFactor)
   }
@@ -380,7 +398,16 @@ class WebviewWindowHandle {
  */
 class WindowManager extends WebviewWindowHandle {
   // Getters
-  /** The scale factor that can be used to map physical pixels to logical pixels. */
+  /**
+   * The scale factor that can be used to map physical pixels to logical pixels.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const factor = await appWindow.scaleFactor();
+   * ```
+   *
+   * @returns The window's monitor scale factor.
+   * */
   async scaleFactor(): Promise<number> {
     return invokeTauriCommand({
       __tauriModule: 'Window',
@@ -396,7 +423,16 @@ class WindowManager extends WebviewWindowHandle {
     })
   }
 
-  /** The position of the top-left hand corner of the window's client area relative to the top-left hand corner of the desktop. */
+  /**
+   * The position of the top-left hand corner of the window's client area relative to the top-left hand corner of the desktop.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const position = await appWindow.innerPosition();
+   * ```
+   *
+   * @returns The window's inner position.
+   *  */
   async innerPosition(): Promise<PhysicalPosition> {
     return invokeTauriCommand<{ x: number; y: number }>({
       __tauriModule: 'Window',
@@ -412,7 +448,16 @@ class WindowManager extends WebviewWindowHandle {
     }).then(({ x, y }) => new PhysicalPosition(x, y))
   }
 
-  /** The position of the top-left hand corner of the window relative to the top-left hand corner of the desktop. */
+  /**
+   * The position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const position = await appWindow.outerPosition();
+   * ```
+   *
+   * @returns The window's outer position.
+   *  */
   async outerPosition(): Promise<PhysicalPosition> {
     return invokeTauriCommand<{ x: number; y: number }>({
       __tauriModule: 'Window',
@@ -431,6 +476,13 @@ class WindowManager extends WebviewWindowHandle {
   /**
    * The physical size of the window's client area.
    * The client area is the content of the window, excluding the title bar and borders.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const size = await appWindow.innerSize();
+   * ```
+   *
+   * @returns The window's inner size.
    */
   async innerSize(): Promise<PhysicalSize> {
     return invokeTauriCommand<{ width: number; height: number }>({
@@ -450,6 +502,13 @@ class WindowManager extends WebviewWindowHandle {
   /**
    * The physical size of the entire window.
    * These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const size = await appWindow.outerSize();
+   * ```
+   *
+   * @returns The window's outer size.
    */
   async outerSize(): Promise<PhysicalSize> {
     return invokeTauriCommand<{ width: number; height: number }>({
@@ -466,7 +525,16 @@ class WindowManager extends WebviewWindowHandle {
     }).then(({ width, height }) => new PhysicalSize(width, height))
   }
 
-  /** Gets the window's current fullscreen state. */
+  /**
+   * Gets the window's current fullscreen state.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const fullscreen = await appWindow.isFullscreen();
+   * ```
+   *
+   * @returns Whether the window is in fullscreen mode or not.
+   *  */
   async isFullscreen(): Promise<boolean> {
     return invokeTauriCommand({
       __tauriModule: 'Window',
@@ -482,7 +550,16 @@ class WindowManager extends WebviewWindowHandle {
     })
   }
 
-  /** Gets the window's current maximized state. */
+  /**
+   * Gets the window's current maximized state.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const maximized = await appWindow.isMaximized();
+   * ```
+   *
+   * @returns Whether the window is maximized or not.
+   * */
   async isMaximized(): Promise<boolean> {
     return invokeTauriCommand({
       __tauriModule: 'Window',
@@ -498,7 +575,16 @@ class WindowManager extends WebviewWindowHandle {
     })
   }
 
-  /** Gets the window's current decorated state. */
+  /**
+   * Gets the window's current decorated state.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const decorated = await appWindow.isDecorated();
+   * ```
+   *
+   * @returns Whether the window is decorated or not.
+   *  */
   async isDecorated(): Promise<boolean> {
     return invokeTauriCommand({
       __tauriModule: 'Window',
@@ -514,7 +600,16 @@ class WindowManager extends WebviewWindowHandle {
     })
   }
 
-  /** Gets the window's current resizable state. */
+  /**
+   * Gets the window's current resizable state.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const resizable = await appWindow.isResizable();
+   * ```
+   *
+   * @returns Whether the window is resizable or not.
+   *  */
   async isResizable(): Promise<boolean> {
     return invokeTauriCommand({
       __tauriModule: 'Window',
@@ -530,7 +625,16 @@ class WindowManager extends WebviewWindowHandle {
     })
   }
 
-  /** Gets the window's current visible state. */
+  /**
+   * Gets the window's current visible state.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const visible = await appWindow.isVisible();
+   * ```
+   *
+   * @returns Whether the window is visible or not.
+   *  */
   async isVisible(): Promise<boolean> {
     return invokeTauriCommand({
       __tauriModule: 'Window',
@@ -546,7 +650,16 @@ class WindowManager extends WebviewWindowHandle {
     })
   }
 
-  /** Gets the window's current visible state. */
+  /**
+   * Gets the window's current visible state.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * const theme = await appWindow.theme();
+   * ```
+   *
+   * @returns The system theme.
+   * */
   async theme(): Promise<Theme | null> {
     return invokeTauriCommand({
       __tauriModule: 'Window',
@@ -566,6 +679,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Centers the window.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.center();
+   * ```
    *
    * @param resizable
    * @returns A promise indicating the success or failure of the operation.
@@ -597,6 +715,11 @@ class WindowManager extends WebviewWindowHandle {
    *
    * - **macOS:** `null` has no effect.
    * - **Linux:** Urgency levels have the same effect.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.requestUserAttention();
+   * ```
    *
    * @param resizable
    * @returns A promise indicating the success or failure of the operation.
@@ -629,6 +752,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Updates the window resizable flag.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.setResizable(false);
+   * ```
    *
    * @param resizable
    * @returns A promise indicating the success or failure of the operation.
@@ -651,6 +779,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Sets the window title.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.setTitle('Tauri');
+   * ```
    *
    * @param title The new title
    * @returns A promise indicating the success or failure of the operation.
@@ -673,6 +806,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Maximizes the window.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.maximize();
+   * ```
    *
    * @returns A promise indicating the success or failure of the operation.
    */
@@ -693,6 +831,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Unmaximizes the window.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.unmaximize();
+   * ```
    *
    * @returns A promise indicating the success or failure of the operation.
    */
@@ -713,6 +856,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Toggles the window maximized state.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.toggleMaximize();
+   * ```
    *
    * @returns A promise indicating the success or failure of the operation.
    */
@@ -733,6 +881,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Minimizes the window.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.minimize();
+   * ```
    *
    * @returns A promise indicating the success or failure of the operation.
    */
@@ -753,6 +906,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Unminimizes the window.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.unminimize();
+   * ```
    *
    * @returns A promise indicating the success or failure of the operation.
    */
@@ -773,6 +931,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Sets the window visibility to true.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.show();
+   * ```
    *
    * @returns A promise indicating the success or failure of the operation.
    */
@@ -793,6 +956,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Sets the window visibility to false.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.hide();
+   * ```
    *
    * @returns A promise indicating the success or failure of the operation.
    */
@@ -813,6 +981,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Closes the window.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.close();
+   * ```
    *
    * @returns A promise indicating the success or failure of the operation.
    */
@@ -833,6 +1006,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Whether the window should have borders and bars.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.setDecorations(false);
+   * ```
    *
    * @param decorations Whether the window should have borders and bars.
    * @returns A promise indicating the success or failure of the operation.
@@ -855,6 +1033,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Whether the window should always be on top of other windows.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.setAlwaysOnTop(true);
+   * ```
    *
    * @param alwaysOnTop Whether the window should always be on top of other windows or not.
    * @returns A promise indicating the success or failure of the operation.
@@ -879,8 +1062,8 @@ class WindowManager extends WebviewWindowHandle {
    * Resizes the window with a new inner size.
    * @example
    * ```typescript
-   * import { appWindow, LogicalSize } from '@tauri-apps/api/window'
-   * await appWindow.setSize(new LogicalSize(600, 500))
+   * import { appWindow, LogicalSize } from '@tauri-apps/api/window';
+   * await appWindow.setSize(new LogicalSize(600, 500));
    * ```
    *
    * @param size The logical or physical inner size.
@@ -917,8 +1100,8 @@ class WindowManager extends WebviewWindowHandle {
    * Sets the window minimum inner size. If the `size` argument is not provided, the constraint is unset.
    * @example
    * ```typescript
-   * import { appWindow, PhysicalSize } from '@tauri-apps/api/window'
-   * await appWindow.setMinSize(new PhysicalSize(600, 500))
+   * import { appWindow, PhysicalSize } from '@tauri-apps/api/window';
+   * await appWindow.setMinSize(new PhysicalSize(600, 500));
    * ```
    *
    * @param size The logical or physical inner size, or `null` to unset the constraint.
@@ -959,8 +1142,8 @@ class WindowManager extends WebviewWindowHandle {
    * Sets the window maximum inner size. If the `size` argument is undefined, the constraint is unset.
    * @example
    * ```typescript
-   * import { appWindow, LogicalSize } from '@tauri-apps/api/window'
-   * await appWindow.setMaxSize(new LogicalSize(600, 500))
+   * import { appWindow, LogicalSize } from '@tauri-apps/api/window';
+   * await appWindow.setMaxSize(new LogicalSize(600, 500));
    * ```
    *
    * @param size The logical or physical inner size, or `null` to unset the constraint.
@@ -1001,8 +1184,8 @@ class WindowManager extends WebviewWindowHandle {
    * Sets the window outer position.
    * @example
    * ```typescript
-   * import { appWindow, LogicalPosition } from '@tauri-apps/api/window'
-   * await appWindow.setPosition(new LogicalPosition(600, 500))
+   * import { appWindow, LogicalPosition } from '@tauri-apps/api/window';
+   * await appWindow.setPosition(new LogicalPosition(600, 500));
    * ```
    *
    * @param position The new position, in logical or physical pixels.
@@ -1042,6 +1225,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Sets the window fullscreen state.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.setFullscreen(true);
+   * ```
    *
    * @param fullscreen Whether the window should go to fullscreen or not.
    * @returns A promise indicating the success or failure of the operation.
@@ -1064,6 +1252,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Bring the window to front and focus.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.setFocus();
+   * ```
    *
    * @returns A promise indicating the success or failure of the operation.
    */
@@ -1084,6 +1277,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Sets the window icon.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.setIcon('/tauri/awesome.png');
+   * ```
    *
    * Note that you need the `icon-ico` or `icon-png` Cargo features to use this API.
    * To enable it, change your Cargo.toml file:
@@ -1116,6 +1314,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Whether to show the window icon in the task bar or not.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.setSkipTaskbar(true);
+   * ```
    *
    * @param skip true to hide window icon, false to show it.
    * @returns A promise indicating the success or failure of the operation.
@@ -1146,6 +1349,11 @@ class WindowManager extends WebviewWindowHandle {
    *
    * - **Linux:** Unsupported.
    * - **macOS:** This locks the cursor in a fixed location, which looks visually awkward.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.setCursorGrab(true);
+   * ```
    *
    * @param grab `true` to grab the cursor icon, `false` to release it.
    * @returns A promise indicating the success or failure of the operation.
@@ -1174,6 +1382,11 @@ class WindowManager extends WebviewWindowHandle {
    * - **Windows:** The cursor is only hidden within the confines of the window.
    * - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is
    *   outside of the window.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.setCursorVisible(false);
+   * ```
    *
    * @param visible If `false`, this will hide the cursor. If `true`, this will show the cursor.
    * @returns A promise indicating the success or failure of the operation.
@@ -1196,6 +1409,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Modifies the cursor icon of the window.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.setCursorIcon('help');
+   * ```
    *
    * @param icon The new cursor icon.
    * @returns A promise indicating the success or failure of the operation.
@@ -1218,6 +1436,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Changes the position of the cursor in window coordinates.
+   * @example
+   * ```typescript
+   * import { appWindow, LogicalPosition } from '@tauri-apps/api/window';
+   * await appWindow.setCursorPosition(new LogicalPosition(600, 300));
+   * ```
    *
    * @param position The new cursor position.
    * @returns A promise indicating the success or failure of the operation.
@@ -1256,6 +1479,11 @@ class WindowManager extends WebviewWindowHandle {
 
   /**
    * Starts dragging the window.
+   * @example
+   * ```typescript
+   * import { appWindow } from '@tauri-apps/api/window';
+   * await appWindow.startDragging();
+   * ```
    *
    * @return A promise indicating the success or failure of the operation.
    */
@@ -1286,29 +1514,43 @@ class WindowManager extends WebviewWindowHandle {
  * // loading embedded asset:
  * const webview = new WebviewWindow('theUniqueLabel', {
  *   url: 'path/to/page.html'
- * })
+ * });
  * // alternatively, load a remote URL:
  * const webview = new WebviewWindow('theUniqueLabel', {
  *   url: 'https://github.com/tauri-apps/tauri'
- * })
+ * });
  *
  * webview.once('tauri://created', function () {
  *  // webview window successfully created
- * })
+ * });
  * webview.once('tauri://error', function (e) {
  *  // an error happened creating the webview window
- * })
+ * });
  *
  * // emit an event to the backend
- * await webview.emit("some event", "data")
+ * await webview.emit("some event", "data");
  * // listen to an event from the backend
- * const unlisten = await webview.listen("event name", e => {})
- * unlisten()
+ * const unlisten = await webview.listen("event name", e => {});
+ * unlisten();
  * ```
  */
 class WebviewWindow extends WindowManager {
   /**
    * Creates a new WebviewWindow.
+   * @example
+   * ```typescript
+   * import { WebviewWindow } from '@tauri-apps/api/window';
+   * const webview = new WebviewWindow('my-label', {
+   *   url: 'https://github.com/tauri-apps/tauri'
+   * });
+   * webview.once('tauri://created', function () {
+   *  // webview window successfully created
+   * });
+   * webview.once('tauri://error', function (e) {
+   *  // an error happened creating the webview window
+   * });
+   * ```
+   *
    * * @param label The unique webview window label. Must be alphanumeric: `a-zA-Z-/:_`.
    * @returns The WebviewWindow instance to communicate with the webview.
    */
@@ -1335,6 +1577,11 @@ class WebviewWindow extends WindowManager {
 
   /**
    * Gets the WebviewWindow for the webview associated with the given label.
+   * @example
+   * ```typescript
+   * import { WebviewWindow } from '@tauri-apps/api/window';
+   * const mainWindow = WebviewWindow.getByLabel('main');
+   * ```
    *
    * @param label The webview window label.
    * @returns The WebviewWindow instance to communicate with the webview or null if the webview doesn't exist.
@@ -1437,6 +1684,11 @@ interface WindowOptions {
 /**
  * Returns the monitor on which the window currently resides.
  * Returns `null` if current monitor can't be detected.
+ * @example
+ * ```typescript
+ * import { currentMonitor } from '@tauri-apps/api/window';
+ * const monitor = currentMonitor();
+ * ```
  */
 async function currentMonitor(): Promise<Monitor | null> {
   return invokeTauriCommand({
@@ -1455,6 +1707,11 @@ async function currentMonitor(): Promise<Monitor | null> {
 /**
  * Returns the primary monitor of the system.
  * Returns `null` if it can't identify any monitor as a primary one.
+ * @example
+ * ```typescript
+ * import { primaryMonitor } from '@tauri-apps/api/window';
+ * const monitor = primaryMonitor();
+ * ```
  */
 async function primaryMonitor(): Promise<Monitor | null> {
   return invokeTauriCommand({
@@ -1470,7 +1727,14 @@ async function primaryMonitor(): Promise<Monitor | null> {
   })
 }
 
-/** Returns the list of all the monitors available on the system. */
+/**
+ * Returns the list of all the monitors available on the system.
+ * @example
+ * ```typescript
+ * import { availableMonitors } from '@tauri-apps/api/window';
+ * const monitors = availableMonitors();
+ * ```
+ * */
 async function availableMonitors(): Promise<Monitor[]> {
   return invokeTauriCommand({
     __tauriModule: 'Window',