# platform/web (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/platform/web/

Web platform. (wasm32)
- As in the original, fills the window's inside with the canvas and gets a WebGL2 context with the same options as the original.
- One engine frame per request_animation_frame callback. (the browser calls it in step with vertical sync, and the screen is presented when the callback finishes)
- Receives keyboard, mouse and fingers. Text input for input fields (a hidden DOM <input>, IME composition, context menu) and the clipboard are handled by web/textinput.rs.
- When a key is pressed, if it is one of the input manager's keys to prevent (set_prevented_keys), the default action is prevented unless typing in a text input. The last used device is recorded on every key, mouse and finger event.
- Audio: as in the original engine.js, click / touchstart / keydown (and touchend / pointerup if set) count as a user gesture
  and call engine.resume_on_user_gesture(), and on focus and when the page becomes visible again engine.resume() is called.
- Page: passes visibilitychange, blur, focus, pointerdown as engine page events, calls on_page_visibility_restored when visible again,
  and on_page_process_restored on document resume and pageshow (persisted). (the original setupAllDocumentEvents)
- Max FPS decides turns by the number of frames processed since counting started, as in the original. (platform/framelimiter.rs, at 90 Hz 60 FPS also averages 60)
- On the canvas's webglcontextlost, webglcontextrestored, forgets the GL state cache like the original WebGLStateCache.
- Key, mouse, finger and page events do not borrow twice even when they re-enter inside the frame callback (like dispatchEvent or focus() in game code).
  If they can borrow right away they are handled on the spot, otherwise they are queued and handled in arrival order at the end of the frame callback. (platform/eventqueue.rs)
- exit_application: as in the original, tries Capacitor's App.exitApp, or window.close if missing.

Example: Read page query values, safe area and primary input (called by the same names as desktop)

```rust
use vanilla::platform;

let quality = platform::read_page_query_value("quality").unwrap_or_else(|| String::from("high"));
let safe_area_insets = platform::read_safe_area_insets();
let is_touch_first = platform::is_coarse_pointer();
println!("{} {:?} {}", quality, safe_area_insets, is_touch_first);
```

## PlatformWindow (type)

Window handle held by the engine. (for changing the cursor)

```rust
pub type PlatformWindow = web_sys::HtmlCanvasElement
```

## Functions and constants

- `pub fn set_cursor_visible(platform_window: Option<&PlatformWindow>, is_visible: bool)` (method, since 0.3.2): Sets cursor visibility.
  - Writes none to the canvas's cursor style when hiding, and an empty value (browser default) when showing.
  - `platform_window` Option<&PlatformWindow>: Engine canvas. (does nothing if None)
  - `is_visible` bool: true to show it.
- `pub fn set_cursor(platform_window: Option<&PlatformWindow>, cursor_value: &CursorValue)` (method, since 0.4.0): Sets the cursor shape. (writes the CSS value to the canvas's cursor style, an empty value is the browser default, for an image cursor the CSS value contains the image)
  - `platform_window` Option<&PlatformWindow>: Engine canvas. (does nothing if None)
  - `cursor_value` &CursorValue: Cursor value. (css_value is written as is)
- `pub fn is_coarse_pointer() -> bool` (method, since 0.4.0): Whether the primary pointer is a finger. (CSS pointer: coarse)
  - returns bool: true if matchMedia("(pointer: coarse)") matches. false if there is no window or it cannot be read.
- `pub fn is_text_field_focused() -> bool` (method, since 0.4.0): Whether the document's focus is on a text input. (text-type input, textarea, contenteditable, select)
  - returns bool: true if document.activeElement is a text input. (inputs like button, checkbox are false, false if nothing is focused)
- `pub fn read_page_query_value(name: &str) -> Option<String>` (method, since 0.4.0): Query value of the page address. (as in the original, reads location.search with URLSearchParams and takes the first value, None if missing)
  - `name` &str: Query name. (such as safeArea)
  - returns Option<String>: First value with that name. None if not in the query or window, location, URLSearchParams cannot be read.
- `pub fn read_canvas_client_position() -> Vector2` (method, since 0.4.0): Top-left of the canvas in screen (client) coordinates. (left, top of the original canvas.getBoundingClientRect(), 0 if there is no canvas)
  - returns Vector2: Top-left position of the canvas. (CSS pixels, 0, 0 if the engine canvas does not exist yet)
- `pub fn save_capture_file(file_name: &str, png_bytes: &[u8]) -> Result<(), String>` (method, since 0.4.0): Saves the screen for verification. (downloads it as in the original, makes the PNG a Blob URL and clicks it with the download of an a element)
  - `file_name` &str: File name to download. (the download value of the a element)
  - `png_bytes` &[u8]: PNG file bytes.
  - returns Result<(), String>: Ok if the download was clicked. Err(reason text) if window, document, body, Blob, URL.createObjectURL are missing or a DOM call fails.
- `pub fn read_client_native_size() -> Option<Vector2>` (method, since 0.4.0): Full page size. (the original window.innerWidth, innerHeight)
  - returns Option<Vector2>: Inner size of the window. (CSS pixels) None if there is no window or the values cannot be read.
- `pub fn read_safe_area_insets() -> [f64; 4]` (method, since 0.4.0): CSS env(safe-area-inset-*) safe area insets. (the original viewManager.readSafeAreaFromEnvironment, CSS pixels [top, right, bottom, left])
  - Sets env() on the padding of a hidden element and reads the computed values with parseFloat. 0 if there is no document or body.
  - returns [f64; 4]: [top, right, bottom, left] insets. (CSS pixels, entries that could not be read are 0)
- `pub fn set_title(_platform_window: Option<&PlatformWindow>, title: &str)` (method, since 0.3.2): Sets the window title. (the document title)
  - `_platform_window` Option<&PlatformWindow>: Engine canvas. (not used, kept to match the desktop form)
  - `title` &str: Title text. (document.title)
- `pub fn request_asset_bytes(asset_location: String, load_handle: AssetLoadHandle, is_no_cache: bool)` (method, since 0.3.2): Reads asset bytes. (receives with fetch and finishes once received. Frames keep running in the meantime)
  - Records the response's content-type on the handle. (response.headers.get("content-type") of the original Material.loadImageDescription)
  - If the response is an image type (image/...) or the URL has an image extension (png, jpg, gif, webp, bmp, ico, svg, avif, etc.), lets the browser decode it as in the original before finishing and keeps it on the handle.
    (ImageAsset, AssetLoader use it as is) Like the original HTMLImageElement, passes the response's content-type as the type as is, so the browser treats SVG by that type (image/svg+xml)
    and other images by their content. Only responses without the header use the extension's type. For data: URLs, fetch gives the URL's type as content-type.
  - Handles that must be decoded as images (images of ImageAsset and AssetLoader) are decoded by the browser by content without a type, even if the type and extension are not images. (same as the original img.src; the web has no engine decoder)
  - `asset_location` String: URL to receive. (made from the asset path by the engine, data: URLs work too)
  - `load_handle` AssetLoadHandle: Handle to finish with the bytes or error text once received.
  - `is_no_cache` bool: If true, adds cache: "no-cache" to fetch. (the original TextAsset)
- `pub fn run(engine_runner: EngineRunner) -> Result<(), String>` (method, since 0.3.2): Starts. (grabs the canvas and WebGL2, sets up request_animation_frame and returns right away)
  - `engine_runner` EngineRunner: Engine runner. (Engine::run makes it with the engine and the first scene and passes it)
  - returns Result<(), String>: Ok if the frame callback was set. Err(reason text) if the canvas or WebGL2 context could not be obtained or event listeners could not be attached.
- `pub fn exit_application()` (method, since 0.4.0): Exits the application. (the original exitApplication: exits with the App plugin if Capacitor native, otherwise tries to close the window)
  - Either can be refused depending on the environment, and no error is raised on failure. The engine records the exit request and stops running from the next frame.
- `pub fn open_url(url: &str) -> bool` (method, since 0.4.0): Opens an outside URL. (original Engine.openUrl, opens a new tab with window.open(url, "_blank", "noopener"))
  - It opens only when called inside user input (click, tap, key) handling. This is the browser's popup-blocking rule.
  - Only http, https, mailto and tel can be opened. (is_openable_url) Other forms are not opened and return false.
  - `url` &str: URL to open. (http, https, mailto or tel)
  - returns bool: True if the open was handed to the browser.
- `pub fn read_local_time(minute_offset: f64) -> crate::platform::LocalTime` (method, since 0.4.0): Read the local time. (same as the original Engine.readLocalTime, the local calendar time of new Date(Date.now() + offset minutes))
  - `minute_offset` f64: Minutes to add to now. (negative is the past, 0 is now)
  - returns crate::platform::LocalTime: The calendar time of the shifted moment in the browser's time zone.
