### Manipulate DOM Elements Attributes and Content in Gleam Source: https://context7.com/crowdhailer/plinth/llms.txt Leverage Plinth's element bindings to set, get, and remove attributes, manipulate inner HTML or text, and insert new elements adjacent to existing ones. ```gleam import plinth/browser/element.{BeforeEnd, AfterEnd} import plinth/browser/document // Get and set attributes case document.query_selector("#my-input") { Ok(input) -> { element.set_attribute(input, "placeholder", "Enter text...") case element.get_attribute(input, "value") { Ok(value) -> io.println("Current value: " <> value) Error(Nil) -> Nil } element.remove_attribute(input, "disabled") } Error(Nil) -> Nil } // Element content manipulation case document.query_selector("#content") { Ok(el) -> { element.set_inner_html(el, "Bold text") element.set_inner_text(el, "Plain text only") let text = element.inner_text(el) let full_text = element.text_content(el) } Error(Nil) -> Nil } // Insert elements at specific positions let new_item = document.create_element("li") element.set_inner_text(new_item, "New Item") case document.query_selector("ul") { Ok(list) -> { let _ = element.insert_adjacent_element(list, BeforeEnd, new_item) let _ = element.insert_adjacent_html(list, AfterEnd, "

After list

") } Error(Nil) -> Nil } // Scrolling and dimensions case document.query_selector(".scrollable") { Ok(el) -> { let height = element.scroll_height(el) let top = element.scroll_top(el) element.scroll_to(el, 0.0, 100.0, "smooth") element.scroll_into_view(el) // Client dimensions let width = element.client_width(el) let height = element.client_height(el) } Error(Nil) -> Nil } // DOM tree traversal case document.query_selector(".child") { Ok(child) -> { case element.parent_element(child) { Ok(parent) -> element.remove(child) Error(Nil) -> Nil } case element.closest(child, ".container") { Ok(container) -> io.println("Found container") Error(Nil) -> Nil } } Error(Nil) -> Nil } // Input handling case document.query_selector("#text-input") { Ok(input) -> { element.focus(input) element.set_value(input, "Default text") case element.value(input) { Ok(val) -> io.println("Input value: " <> val) Error(Nil) -> Nil } element.set_selection_range(input, 0, 5) let is_checked = element.get_checked(input) } Error(Nil) -> Nil } ``` -------------------------------- ### Manage Blobs and Files Source: https://context7.com/crowdhailer/plinth/llms.txt Shows how to create, read, and manipulate Blob and File objects, including generating object URLs and slicing file content. ```gleam import plinth/browser/file import plinth/browser/blob import gleam/javascript/promise // Create a blob from binary data let content = <<"Hello, World!":utf8>> let my_blob = blob.new(content, "text/plain") let size = blob.size(my_blob) let mime_type = blob.mime(my_blob) // Read blob content use text <- promise.map(blob.text(my_blob)) io.println("Blob text: " <> text) use bytes <- promise.map(blob.bytes(my_blob)) io.println("Got bytes from blob") // Create a file from binary data let my_file = file.new(<<"File content":utf8>>, "example.txt") let filename = file.name(my_file) let file_size = file.size(my_file) let file_mime = file.mime(my_file) // Read file content use content <- promise.map(file.text(my_file)) io.println("File content: " <> content) // Create object URL for downloads or display let url = file.create_object_url(my_file) // Slice a portion of the file let slice = file.slice(my_file, 0, 5) ``` -------------------------------- ### Access Node.js Process Information Source: https://context7.com/crowdhailer/plinth/llms.txt The process module provides access to command line arguments (argv), current working directory (cwd), environment variables (env), and high-resolution time (hrtime). Use process.exit to terminate the process. ```gleam import plinth/node/process import gleam/javascript/array // Command line arguments let args = process.argv() array.to_list(args) |> list.each(fn(arg) { io.println("Arg: " <> arg) }) // Current working directory let cwd = process.cwd() io.println("Working directory: " <> cwd) // Environment variables let env_vars = process.env() array.to_list(env_vars) |> list.each(fn(pair) { let #(key, value) = pair io.println(key <> "=" <> value) }) // High-resolution time (nanoseconds as BigInt) let start = process.hrtime() // ... do work ... let end = process.hrtime() // Exit the process process.exit(code: 0) ``` -------------------------------- ### Read and Write to System Clipboard Source: https://context7.com/crowdhailer/plinth/llms.txt Perform asynchronous clipboard operations using the clipboard module. These functions return promises that resolve to results. ```gleam import plinth/browser/clipboard import gleam/javascript/promise // Write text to clipboard use result <- promise.map(clipboard.write_text("Copied text!")) case result { Ok(Nil) -> io.println("Text copied to clipboard") Error(reason) -> io.println("Copy failed: " <> reason) } // Read text from clipboard use result <- promise.map(clipboard.read_text()) case result { Ok(text) -> io.println("Clipboard contains: " <> text) Error(reason) -> io.println("Read failed: " <> reason) } ``` -------------------------------- ### Access Local File System Source: https://context7.com/crowdhailer/plinth/llms.txt Interact with the user's local file system using directory and file pickers. Requires handling promises for asynchronous file operations. ```gleam import plinth/browser/file_system import plinth/browser/file import gleam/javascript/promise // Open a directory picker use result <- promise.map(file_system.show_directory_picker()) case result { Ok(dir_handle) -> { let dir_name = file_system.name(dir_handle) io.println("Selected: " <> dir_name) // List all entries use entries_result <- promise.map(file_system.all_entries(dir_handle)) case entries_result { Ok(#(dirs, files)) -> io.println("Found directories and files") Error(reason) -> io.println("Error: " <> reason) } // Get or create subdirectory use subdir <- promise.map_try(file_system.get_directory_handle(dir_handle, "subdir", True)) // Get or create file use file_handle <- promise.map_try(file_system.get_file_handle(dir_handle, "data.txt", True)) // Read file use file_obj <- promise.map_try(file_system.get_file(file_handle)) use content <- promise.map(file.text(file_obj)) io.println("File content: " <> content) Ok(Nil) } Error(reason) -> io.println("Cancelled or error: " <> reason) } // Open file picker for reading use result <- promise.map(file_system.show_open_file_picker()) case result { Ok(file_handles) -> io.println("Files selected") Error(reason) -> io.println("Error: " <> reason) } // Save file picker for writing use result <- promise.map(file_system.show_save_file_picker()) case result { Ok(file_handle) -> { use writable <- promise.map_try(file_system.create_writable(file_handle)) use _ <- promise.map_try(file_system.write(writable, <<"New content":utf8>>)) use _ <- promise.map_try(file_system.close(writable)) Ok(io.println("File saved")) } Error(reason) -> io.println("Error: " <> reason) } ``` -------------------------------- ### Receive Server-Sent Events with EventSource Source: https://context7.com/crowdhailer/plinth/llms.txt Establishes a connection to an EventSource endpoint and registers callbacks for open, message, and close events. ```gleam import plinth/browser/eventsource import plinth/browser/message_event case eventsource.constructor() { Ok(create_event_source) -> { let source = create_event_source("https://example.com/events", True) eventsource.on_open(source, fn(event) { io.println("Connection opened") }) eventsource.on_message(source, fn(message_event) { let data = message_event.data(message_event) io.println("Received: " <> data) }) eventsource.on_close(source, fn(event) { io.println("Connection closed") }) } Error(Nil) -> io.println("EventSource not available") } ``` -------------------------------- ### Access Window Properties and Methods in Gleam Source: https://context7.com/crowdhailer/plinth/llms.txt Use the window module to interact with browser window dimensions, dialogs, animation frames, and wake locks. Requires importing plinth/browser/window. ```gleam import plinth/browser/window import gleam/javascript/promise // Get window reference and properties let win = window.self() let doc = window.document(win) let loc = window.location(win) // Window dimensions let inner_h = window.inner_height(win) let inner_w = window.inner_width(win) let outer_h = window.outer_height(win) let outer_w = window.outer_width(win) // Scroll position let scroll_x = window.scroll_x(win) let scroll_y = window.scroll_y(win) // User dialogs window.alert("Hello!") let confirmed = window.confirm("Are you sure?") case window.prompt("Enter your name:") { Ok(name) -> io.println("Hello, " <> name) Error(Nil) -> io.println("User cancelled") } // Animation frames for smooth rendering let request_id = window.request_animation_frame(fn(timestamp) { // Render frame at timestamp Nil }) window.cancel_animation_frame(request_id) // Microtask scheduling window.queue_microtask(fn() { io.println("Runs after current task") }) // Open popup windows case window.open("https://example.com", "_blank", "width=800,height=600") { Ok(popup) -> io.println("Popup opened") Error(reason) -> io.println("Failed: " <> reason) } // Wake lock to prevent screen sleep use result <- promise.map(window.request_wake_lock()) case result { Ok(sentinel) -> io.println("Screen will stay awake") Error(Nil) -> io.println("Wake lock not supported") } ``` -------------------------------- ### Interact with IndexedDB Source: https://context7.com/crowdhailer/plinth/llms.txt Opens an IndexedDB database, creates object stores during upgrades, and performs read/write transactions. ```gleam import plinth/browser/window import plinth/browser/indexeddb/factory import plinth/browser/indexeddb/database.{ReadWrite, Default} import plinth/browser/indexeddb/object_store import plinth/browser/indexeddb/transaction import gleam/javascript/promise import gleam/option.{Some, None} import gleam/dynamic let win = window.self() case factory.from_window(win) { Ok(idb) -> { // Open database with upgrade handler use result <- promise.map(factory.opendb(idb, "my-database", 1, fn(db) { // Create object store during upgrade let _ = database.create_object_store(db, "users", Some("id"), True) })) case result { Ok(db) -> { let db_name = database.name(db) let store_names = database.object_store_names(db) // Start a transaction case database.transaction(db, ["users"], ReadWrite, Default) { Ok(txn) -> { case transaction.object_store(txn, "users") { Ok(store) -> { // Store data let user = dynamic.from([ #("id", dynamic.from(1)), #("name", dynamic.from("Alice")), ]) use _ <- promise.map_try(object_store.put(store, user, None)) // Retrieve all data use result <- promise.map(object_store.get_all(store)) case result { Ok(users) -> io.println("Got users from IndexedDB") Error(reason) -> io.println("Error: " <> reason) } Ok(Nil) } Error(reason) -> promise.resolve(Error(reason)) } } Error(reason) -> io.println("Transaction error: " <> reason) } } Error(reason) -> io.println("Database error: " <> reason) } } Error(Nil) -> io.println("IndexedDB not available") } ``` -------------------------------- ### Play Audio Source: https://context7.com/crowdhailer/plinth/llms.txt Load and play audio files from a URL. ```gleam import plinth/browser/audio import gleam/javascript/promise // Create and play audio let sound = audio.new("https://example.com/sound.mp3") use result <- promise.map(audio.play(sound)) case result { Ok(Nil) -> io.println("Audio playing") Error(reason) -> io.println("Playback failed: " <> reason) } ``` -------------------------------- ### Perform Cryptographic Operations with Plinth Source: https://context7.com/crowdhailer/plinth/llms.txt Demonstrates random UUID generation, hashing, RSA key pair generation, and ECDSA signing using the browser's SubtleCrypto API. ```gleam import plinth/browser/window import plinth/browser/crypto import plinth/browser/crypto/subtle import gleam/javascript/promise let win = window.self() case window.crypto(win) { Ok(crypto_obj) -> { // Generate random UUID let uuid = crypto.random_uuid(crypto_obj) io.println("UUID: " <> uuid) // Generate random bytes case crypto.get_random_values(crypto_obj, 16) { Ok(bytes) -> io.println("Got random bytes") Error(reason) -> io.println("Failed: " <> reason) } } Error(Nil) -> io.println("Crypto not available") } // Cryptographic hashing with SubtleCrypto let data = <<"Hello, World!":utf8>> use result <- promise.map(subtle.digest(subtle.SHA256, data)) case result { Ok(hash) -> io.println("SHA-256 hash computed") Error(reason) -> io.println("Hash failed: " <> reason) } // Generate key pairs let public_exponent = <<1, 0, 1>> // 65537 let algorithm = subtle.RsaHashedKeyGenParams( name: "RSA-OAEP", modulus_length: 2048, public_exponent: public_exponent, hash: subtle.SHA256, ) use result <- promise.map(subtle.generate_key(algorithm, True, [subtle.Encrypt, subtle.Decrypt])) case result { Ok(#(public_key, private_key)) -> io.println("RSA key pair generated") Error(reason) -> io.println("Key generation failed: " <> reason) } // Sign and verify data let algorithm = subtle.EcKeyGenParams(name: "ECDSA", named_curve: "P-256") use result <- promise.map(subtle.generate_key(algorithm, True, [subtle.Sign, subtle.Verify])) case result { Ok(#(public_key, private_key)) -> { let sign_alg = subtle.EcdsaParams(hash: subtle.SHA256) use signature <- promise.map_try(subtle.sign(sign_alg, private_key, data)) use verified <- promise.map_try(subtle.verify(sign_alg, public_key, signature, data)) io.println("Signature verified: " <> bool.to_string(verified)) Ok(Nil) } Error(reason) -> promise.resolve(Error(reason)) } ``` -------------------------------- ### Manage Node.js Child Processes Source: https://context7.com/crowdhailer/plinth/llms.txt The child_process module allows executing shell commands with exec, spawning new processes with spawn, writing to process stdin, and killing processes. ```gleam import plinth/node/child_process import plinth/node/stream // Execute shell command let child = child_process.exec("ls -la") // Spawn process with arguments let proc = child_process.spawn("node", ["script.js", "--flag"]) // Write to process stdin case child_process.stdin(proc) { Ok(stdin) -> { stream.write(stdin, "input data") stream.end(stdin) } Error(Nil) -> io.println("No stdin available") } // Kill the process child_process.kill(proc) ``` -------------------------------- ### Read and Write Files Synchronously Source: https://context7.com/crowdhailer/plinth/llms.txt Use fs.read_file_sync to read file contents and fs.write_file_sync to write content to a file. Handles success and error cases using Gleam's Result type. ```gleam import plinth/node/fs // Read file contents case fs.read_file_sync("/path/to/file.txt") { Ok(content) -> io.println("File content: " <> content) Error(reason) -> io.println("Read error: " <> reason) } // Write file contents case fs.write_file_sync(path: "/path/to/output.txt", content: "Hello, World!") { Ok(Nil) -> io.println("File written successfully") Error(reason) -> io.println("Write error: " <> reason) } ``` -------------------------------- ### Manage Timers and URI Encoding Source: https://context7.com/crowdhailer/plinth/llms.txt Provides access to global JavaScript functions for scheduling tasks and URI manipulation. ```gleam import plinth/javascript/global // Set a timeout (returns timer ID) let timer_id = global.set_timeout(1000, fn() { io.println("Executed after 1 second") }) // Cancel if needed global.clear_timeout(timer_id) // Set an interval let interval_id = global.set_interval(5000, fn() { io.println("Runs every 5 seconds") }) // Stop the interval global.clear_interval(interval_id) // URI encoding let encoded = global.encode_uri("https://example.com/path?q=hello world") let decoded = global.decode_uri(encoded) let component_decoded = global.decode_uri_component("%2Fpath%2Fto%2Fresource") ``` -------------------------------- ### Log and Debug with Console API Source: https://context7.com/crowdhailer/plinth/llms.txt Provides bindings for standard JavaScript console logging, assertions, and grouping. ```gleam import plinth/javascript/console // Basic logging at different levels console.log("Info message") console.info("Information") console.warn("Warning message") console.error("Error message") console.debug("Debug message") // Assertions console.assert_(some_condition, "Condition was false!") // Grouped output console.group("User Details") console.log("Name: Alice") console.log("Age: 30") console.group_end() // Collapsed group console.group_collapsed("Debug Info") console.log("Detailed debug data") console.group_end() // Clear console console.clear() ``` -------------------------------- ### Manage Browser Location and Navigation Source: https://context7.com/crowdhailer/plinth/llms.txt Access URL components, query strings, and hash fragments using the location module. Reload the page using location.reload. ```gleam import plinth/browser/window import plinth/browser/location let win = window.self() let loc = window.location(win) // URL components let full_url = location.href(loc) let origin = location.origin(loc) let path = location.pathname(loc) // Query string and hash case location.search(loc) { Ok(query) -> io.println("Query: " <> query) // e.g., "?page=1" Error(Nil) -> io.println("No query string") } case location.hash(loc) { Ok(hash) -> io.println("Hash: " <> hash) // e.g., "#section1" Error(Nil) -> io.println("No hash") } // Reload the page location.reload(loc) ``` -------------------------------- ### Manage Web Workers Source: https://context7.com/crowdhailer/plinth/llms.txt Execute JavaScript in background threads and communicate via message passing. ```gleam import plinth/browser/worker import gleam/json // Create a new worker case worker.new("/worker.js") { Ok(w) -> { // Send message to worker worker.post_message(w, json.object([ #("type", json.string("process")), #("data", json.array([1, 2, 3], json.int)), ])) // Receive messages from worker worker.on_message(w, fn(message) { io.println("Received from worker") }) } Error(reason) -> io.println("Worker creation failed: " <> reason) } ``` -------------------------------- ### Compress and Decompress Data Streams Source: https://context7.com/crowdhailer/plinth/llms.txt Uses Compression Streams API to handle gzip or deflate data transformations. ```gleam import plinth/javascript/compression_stream import plinth/javascript/decompression_stream import gleam/javascript/promise let data = <<"Large text content to compress...":utf8>> // Compress data with gzip use compressed <- promise.map(compression_stream.compress(data, "gzip")) io.println("Compressed data") // Decompress data use decompressed <- promise.map(decompression_stream.decompress(compressed, "gzip")) io.println("Decompressed back to original") // Also supports "deflate" encoding use deflated <- promise.map(compression_stream.compress(data, "deflate")) use inflated <- promise.map(decompression_stream.decompress(deflated, "deflate")) ``` -------------------------------- ### Broadcast Channel Communication Source: https://context7.com/crowdhailer/plinth/llms.txt Enable cross-context communication between tabs, windows, or iframes using a named channel. ```gleam import plinth/browser/broadcast_channel import gleam/json // Create a broadcast channel case broadcast_channel.new("my-channel") { Ok(channel) -> { // Send message to all listeners let _ = broadcast_channel.post_message(channel, json.object([ #("event", json.string("user-login")), #("userId", json.int(123)), ])) // Listen for messages broadcast_channel.on_message(channel, fn(message) { io.println("Received broadcast message") }) } Error(reason) -> io.println("Channel error: " <> reason) } ``` -------------------------------- ### Handle Dates with Date API Source: https://context7.com/crowdhailer/plinth/llms.txt Wraps JavaScript Date objects for parsing, formatting, and component extraction. ```gleam import plinth/javascript/date // Current date/time let now = date.now() let iso_string = date.to_iso_string(now) // "2024-01-15T10:30:00.000Z" // Parse date string let parsed = date.new("2024-06-15T12:00:00Z") // Extract components let year = date.year(parsed) // 2024 let month = date.month(parsed) // 5 (0-indexed, so June) let day = date.date(parsed) // 15 let weekday = date.day(parsed) // 6 (Saturday) let hours = date.hours(parsed) // 12 let minutes = date.minutes(parsed) // 0 let seconds = date.seconds(parsed) // 0 // Unix timestamp (milliseconds) let timestamp = date.get_time(parsed) ``` -------------------------------- ### Manipulate Shadow DOM with Gleam Source: https://context7.com/crowdhailer/plinth/llms.txt Attaches a shadow root to a host element and manages its internal content and styling. ```gleam import plinth/browser/shadow import plinth/browser/element import plinth/browser/document // Create a custom element with shadow DOM case document.query_selector("#my-component") { Ok(host) -> { // Attach shadow root let shadow_root = shadow.attach_shadow(host, shadow.Open) // Add content to shadow DOM let style = document.create_element("style") element.set_inner_text(style, ":host { display: block; padding: 16px; }") shadow.append_child(shadow_root, style) let content = document.create_element("div") element.set_inner_text(content, "Shadow DOM content") shadow.append_child(shadow_root, content) // Query within shadow DOM case shadow.query_selector(shadow_root, "div") { Ok(div) -> element.set_inner_text(div, "Updated!") Error(Nil) -> Nil } // Get host element from shadow root let host_element = shadow.host(shadow_root) } Error(Nil) -> Nil } ``` -------------------------------- ### Handle DOM Events in Gleam Source: https://context7.com/crowdhailer/plinth/llms.txt Manage window, document, and element events including keyboard input and modifier keys. Use the returned function from add_event_listener to unsubscribe. ```gleam import plinth/browser/event import plinth/browser/window import plinth/browser/document import plinth/browser/element // Window-level event listeners window.add_event_listener("resize", fn(e) { let win = window.self() io.println("Window resized to: " <> int.to_string(window.inner_width(win))) }) // Document-level event listeners document.add_event_listener("DOMContentLoaded", fn(e) { io.println("Document ready") }) // Element event listeners with cleanup case document.query_selector("#my-button") { Ok(btn) -> { let remove_listener = element.add_event_listener(btn, "click", fn(e) { event.prevent_default(e) event.stop_propagation(e) io.println("Button clicked!") }) // Later: remove_listener() to unsubscribe } Error(Nil) -> Nil } // Keyboard event handling document.add_event_listener("keydown", fn(e) { case event.cast_keyboard_event(event.target(e)) { Ok(keyboard_event) -> { let key = event.key(keyboard_event) let code = event.code(keyboard_event) let with_ctrl = event.ctrl_key(keyboard_event) let with_shift = event.shift_key(keyboard_event) let with_alt = event.alt_key(keyboard_event) let with_meta = event.meta_key(keyboard_event) case key, with_ctrl { "s", True -> { event.prevent_default(e) io.println("Ctrl+S pressed - save!") } _, _ -> Nil } } Error(_) -> Nil } }) ``` -------------------------------- ### Perform Arbitrary Precision Arithmetic with BigInt Source: https://context7.com/crowdhailer/plinth/llms.txt Enables operations on large integers using JavaScript BigInt bindings. ```gleam import plinth/javascript/big_int // Create BigInt from int or string let a = big_int.from_int(9_007_199_254_740_993) let b = big_int.from_string("12345678901234567890") // Arithmetic operations let sum = big_int.add(a, b) let diff = big_int.subtract(b, a) let product = big_int.multiply(a, b) let quotient = big_int.divide(b, a) let remainder = big_int.modulo(b, a) let power = big_int.power(big_int.from_int(2), big_int.from_int(64)) ``` -------------------------------- ### Manage Service Workers Source: https://context7.com/crowdhailer/plinth/llms.txt Registers a service worker and handles communication, or defines listeners when running inside the service worker context. ```gleam import plinth/browser/service_worker import gleam/javascript/promise import gleam/json // Register a service worker use result <- promise.map(service_worker.register("/sw.js")) case result { Ok(registration) -> { io.println("Service worker registered") // Wait for activation use ready_registration <- promise.map(service_worker.ready()) case service_worker.active(ready_registration) { Ok(sw) -> { service_worker.service_worker_post_message(sw, json.object([ #("type", json.string("sync")), ])) } Error(Nil) -> io.println("No active service worker") } } Error(reason) -> io.println("Registration failed: " <> reason) } // Inside a service worker script case service_worker.self() { Ok(global_scope) -> { service_worker.add_fetch_listener(global_scope, fn(fetch_event) { let request = service_worker.request(fetch_event) let client_id = service_worker.client_id(fetch_event) // Handle fetch event... }) service_worker.add_activate_listener(global_scope, fn(activate_event) { let _ = service_worker.do_claim(global_scope) }) } Error(reason) -> io.println("Not in service worker context") } ``` -------------------------------- ### Query and Manipulate DOM Elements in Gleam Source: https://context7.com/crowdhailer/plinth/llms.txt Use Plinth's browser document bindings to query elements by CSS selector or ID, create new nodes, and manage document properties like title and visibility. ```gleam import plinth/browser/document import plinth/browser/element // Query a single element by CSS selector case document.query_selector(".my-class") { Ok(el) -> element.set_inner_text(el, "Found it!") Error(Nil) -> Nil } // Query all matching elements let elements = document.query_selector_all("button") // Get element by ID case document.get_element_by_id("main-content") { Ok(el) -> element.set_inner_html(el, "

Updated content

") Error(Nil) -> Nil } // Create new elements let div = document.create_element("div") let text = document.create_text_node("Hello, World!") element.append_child(div, text) element.append_child(document.body(), div) // Document title and visibility let title = document.title() document.set_title("New Page Title") let is_hidden = document.hidden() let state = document.visibility_state() // "visible" or "hidden" ``` -------------------------------- ### Access Device Geolocation Source: https://context7.com/crowdhailer/plinth/llms.txt Retrieve the device's current geographical position using either promise-based or callback-based APIs. ```gleam import plinth/browser/geolocation import gleam/javascript/promise import gleam/option.{Some, None} // Get current position (Promise-based) use result <- promise.map(geolocation.current_position()) case result { Ok(position) -> { io.println("Latitude: " <> float.to_string(position.latitude)) io.println("Longitude: " <> float.to_string(position.longitude)) io.println("Accuracy: " <> float.to_string(position.accuracy) <> " meters") case position.altitude { Some(alt) -> io.println("Altitude: " <> float.to_string(alt)) None -> Nil } case position.speed { Some(speed) -> io.println("Speed: " <> float.to_string(speed)) None -> Nil } } Error(reason) -> io.println("Location error: " <> reason) } // Callback-based API geolocation.get_current_position( fn(position_dynamic) { io.println("Got position") }, fn(error_dynamic) { io.println("Location error") }, ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.