//! Media in the note: attached files, pasted and dropped files, and microphone recordings. //! A file is POSTed raw to `/media?name=` and comes back as `/media/.`. That URL //! becomes an image inline; its extension picks img, audio or video when it is rendered. //! A recording is a take on the server, streamed over a socket part by part. Its URL //! (`/media/rec/`) is placed at the cursor of the press once the first chunk is stored. A //! continuation adds a part to a take and places nothing. use std::cell::{Cell, RefCell}; use std::collections::VecDeque; use std::rc::{Rc, Weak}; use loro::cursor::Cursor; use wasm_bindgen::closure::Closure; use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen_futures::{JsFuture, spawn_local}; use web_sys::{ BeforeUnloadEvent, BinaryType, Blob, BlobEvent, BlobPropertyBag, Element, Event, EventTarget, File, FileList, HtmlButtonElement, HtmlElement, HtmlInputElement, MediaRecorder, MediaRecorderOptions, MediaStream, MediaStreamConstraints, MediaStreamTrack, MessageEvent, MouseEvent, RequestInit, Response, WebSocket, }; use super::{Ctx, Ed, h}; use crate::core::commands; use crate::core::pos::{self, Pos, Selection}; use crate::editor::Editor; use crate::strings::Strings; use note_model::marks::Marks; use note_model::render::embed_of; use note_model::write::Inline; /// The toolbar's status line, where a failed upload says so. pub const STATUS_ID: &str = "editor-media-status"; /// How long a notice stays in the status line (ms). const NOTICE_MS: i32 = 4000; /// The recorder's format. The server joins only WebM with Opus. const MIME: &str = "audio/webm;codecs=opus"; /// A socket that goes this long without an answer, while a chunk waits for its ack or before /// it is ready, is dead (ms). const STALL_MS: f64 = 5000.0; /// The wait before a lost socket is reconnected (ms). const RETRY_MS: i32 = 1000; /// The microphone recording in progress, and everything wired to it. Dropped in a later task /// after the stop, with every handler cleared first. struct Recording { recorder: MediaRecorder, stream: MediaStream, take: Rc, tick: Option, _on_data: Closure, _on_stop: Closure, _ticker: Closure, } /// One part of a take on its way to the server: the chunks the server does not have yet, and /// every chunk for the local fallback. Shared by the recording and its socket task, so it /// outlives the recording itself. struct Take { /// The take's id: asked for by the first connection of a new take, then known for good. session: RefCell>, /// The part this take's socket is attached to, from the server's `ready`. part: Cell>, /// A new take: its URL is placed in the note once its first chunk is stored. fresh: bool, /// Set once the URL is placed. placed: Cell, /// Where the URL goes: the cursor as it was when the button was pressed. at: Option, /// The alt text of the embed. name: String, mime: String, chunks: js_sys::Array, /// Chunks the server does not have yet, the first one at byte `sent`. queue: RefCell>, /// Bytes of this part the server has stored: the offset of the first queued chunk. sent: Cell, /// Set on stop: no more chunks come. ended: Cell, /// Set when the server rejected the take: nothing more is sent. failed: Cell, /// The beforeunload guard, kept until the take is concluded. unload: Closure, } /// What a recording starts: a new take placed at a cursor, or a new part of an earlier take. enum Start { New(Option), Continue(String), } struct Inner { /// Weak, so a closed editor is not kept alive by an upload or a recording. ed: Weak>, note_id: String, rec: Rc>>, /// Set while the microphone is being opened, so a second click does not start another. starting: Cell, /// Set on `note:detach`: the editor is leaving, so a finished recording is kept for later. detached: Cell, /// The record button and its m:ss readout, bound by the toolbar. ui: RefCell>, input: HtmlInputElement, } /// Handle to the media buttons' behaviour. Clones share the same state. #[derive(Clone)] pub struct Media(Rc); impl Media { /// Opens the file picker; the picked files are uploaded and inserted. pub fn attach(&self) { self.0.input.click(); } /// Starts a recording, or stops the one running. pub fn toggle_record(&self) { let inner = self.0.clone(); let recording = inner.rec.borrow().is_some(); if recording { stop_current(&inner); } else if !inner.starting.replace(true) { let at = press_cursor(&inner); spawn_local(start(inner, Start::New(at))); } } pub fn recording(&self) -> bool { self.0.rec.borrow().is_some() } /// Gives the toolbar's record button and its readout to the recording. pub fn bind_record(&self, btn: HtmlButtonElement, time: HtmlElement) { *self.0.ui.borrow_mut() = Some((btn, time)); } } /// Adds the file input and the detach and continue handlers. Call before the toolbar, /// which binds the record button to the returned handle. pub fn install(ed: &Ed, cx: &Ctx) -> Media { let document = &cx.document; let input: HtmlInputElement = h(document, "input", &[("type", "file"), ("multiple", ""), ("hidden", "")], None).unchecked_into(); let _ = cx.mount.append_child(&input); let inner = Rc::new(Inner { ed: Rc::downgrade(ed), note_id: cx.note_id.clone(), rec: Rc::default(), starting: Cell::new(false), detached: Cell::new(false), ui: RefCell::new(None), input: input.clone(), }); // Picked files are uploaded; the input is reset so the same file can be picked again. { let (host, picker) = (Rc::downgrade(ed), input.clone()); let cb = Closure::::new(move |_: Event| { let files = files_of(picker.files()); picker.set_value(""); if let Some(host) = host.upgrade() && !files.is_empty() { insert_files(&host, files); } }); let _ = input.add_event_listener_with_callback_and_add_event_listener_options("change", cb.as_ref().unchecked_ref(), &cx.opts); cb.forget(); } // Leaving the note: a recording in progress is stopped, and its take is finished by the socket task. { let weak = Rc::downgrade(&inner); let cb = Closure::::new(move |_: Event| { let Some(inner) = weak.upgrade() else { return }; inner.detached.set(true); stop_current(&inner); }); if let Some(win) = web_sys::window() { let _ = win.add_event_listener_with_callback_and_add_event_listener_options("note:detach", cb.as_ref().unchecked_ref(), &cx.opts); } cb.forget(); } // The continue button of a take: a press keeps the caret where it is, and a click continues the take. { let root = ed.borrow().view.root.clone(); let target: &EventTarget = root.as_ref(); let press = Closure::::new(|ev: MouseEvent| { if continue_target(&ev).is_some() { ev.prevent_default(); } }); let _ = target.add_event_listener_with_callback_and_add_event_listener_options("mousedown", press.as_ref().unchecked_ref(), &cx.opts); press.forget(); let weak = Rc::downgrade(&inner); let click = Closure::::new(move |ev: MouseEvent| { if let (Some(session), Some(inner)) = (continue_target(&ev), weak.upgrade()) { continue_take(inner, session); } }); let _ = target.add_event_listener_with_callback_and_add_event_listener_options("click", click.as_ref().unchecked_ref(), &cx.opts); click.forget(); } Media(inner) } /// The files of a file list (picker or clipboard), in order. pub fn files_of(list: Option) -> Vec { let Some(list) = list else { return Vec::new() }; (0..list.length()).filter_map(|i| list.item(i)).collect() } /// Uploads each file in turn and inserts it at the selection once it is stored. A failed /// upload shows a notice and the rest still go on. pub fn insert_files(ed: &Ed, files: Vec) { let weak = Rc::downgrade(ed); spawn_local(async move { for file in files { let name = file.name(); let blob: &Blob = file.as_ref(); match upload(blob, &name).await { Ok(url) => { if let Some(ed) = weak.upgrade() { insert(&ed, embed(&url, &name)); } } Err(_) => notice("mediaFailed"), } } }); } /// POSTs one file as its raw bytes. The answer is the URL of the stored copy. async fn upload(blob: &Blob, name: &str) -> Result { let win = web_sys::window().ok_or("no window")?; let url = format!("/media?name={}", String::from(js_sys::encode_uri_component(name))); let body: &JsValue = blob.as_ref(); let init = RequestInit::new(); init.set_method("POST"); init.set_body(body); let resp: Response = JsFuture::from(win.fetch_with_str_and_init(&url, &init)).await?.dyn_into()?; if !resp.ok() { return Err(format!("upload {}", resp.status()).into()); } let text = JsFuture::from(resp.text()?).await?.as_string().unwrap_or_default(); Ok(text.trim().to_owned()) } /// The inline for a stored file: an embed when its extension can show, else a link to it. fn embed(url: &str, name: &str) -> Inline { if embed_of(url).is_some() { Inline::Image { src: url.to_owned(), alt: name.to_owned(), title: None } } else { let mut marks = Marks::default(); marks.link = Some((url.to_owned(), None)); Inline::Text(name.to_owned(), marks) } } /// Puts an inline at the selection, the way typing does. False when the editor is busy. fn insert(ed: &Ed, inl: Inline) -> bool { let Ok(mut e) = ed.try_borrow_mut() else { return false }; e.run(|cx| commands::insert_inline(cx, &[inl])) } /// Puts an inline at the cursor `at`, or at the end of the doc when it no longer resolves, and /// leaves the selection where it was (moved past the inline when it was after it). False when /// the editor is busy. fn insert_at(ed: &Ed, at: Option<&Cursor>, inl: Inline) -> bool { let Ok(mut e) = ed.try_borrow_mut() else { return false }; e.run(|cx| { let m = cx.m; let p = at.and_then(|c| m.cursor_pos(c)).unwrap_or_else(|| m.total()); let p = pos::snap(m, p); let saved = std::mem::replace(&mut cx.sel, Selection::caret(p)); let ok = commands::insert_inline(cx, &[inl]); let shift = |q: Pos| if q >= p { q + 1 } else { q }; cx.sel = match saved { Selection::Text { anchor, head } => Selection::Text { anchor: shift(anchor), head: shift(head) }, Selection::Node(q) => Selection::Node(shift(q)), Selection::Gap(q) => Selection::Gap(shift(q)), Selection::All => Selection::All, }; ok }) } /// Shows a message in the status line, then clears it when it is still the one shown. fn notice(key: &str) { let Some(win) = web_sys::window() else { return }; let Some(doc) = win.document() else { return }; let Some(el) = doc.get_element_by_id(STATUS_ID) else { return }; let text = Strings::load(&doc).get(key); el.set_text_content(Some(&text)); let shown = text; let clear = Closure::once_into_js(move || { if el.text_content().is_some_and(|t| t == shown) { el.set_text_content(None); } }); let _ = win.set_timeout_with_callback_and_timeout_and_arguments_0(clear.unchecked_ref(), NOTICE_MS); } // --------------------------------------------------------------------------- // Recording // --------------------------------------------------------------------------- /// The cursor at the selection's head, as a Loro cursor so the embed lands there even when the /// text before it changes while the take runs. fn press_cursor(inner: &Inner) -> Option { let ed = inner.ed.upgrade()?; let e = ed.try_borrow().ok()?; let pos = e.sel.head()?; e.m.cursor(pos) } /// Continues the take `session` with a new part, from its continue button. Refused while a /// recording runs. fn continue_take(inner: Rc, session: String) { if inner.rec.borrow().is_none() && !inner.starting.replace(true) { spawn_local(start(inner, Start::Continue(session))); } } /// The take of the continue button under a mouse event, if the event is on one. fn continue_target(ev: &MouseEvent) -> Option { let el: Element = ev.target()?.dyn_into().ok()?; let button = el.closest(".note-take-continue").ok()??; let span = button.closest("[data-take]").ok()??; span.get_attribute("data-take") } /// Opens the microphone and the recorder, then starts the socket task that sends the take. /// A failure shows a notice and leaves nothing running. async fn start(inner: Rc, how: Start) { let rec = open_take(&inner, how).await; inner.starting.set(false); match rec { Ok(rec) => { let take = rec.take.clone(); *inner.rec.borrow_mut() = Some(rec); set_ui(&inner, true); spawn_local(link(inner.clone(), take)); // The page may have started leaving while the microphone was being opened. if inner.detached.get() { stop_current(&inner); } } Err(key) => notice(key), } } /// Opens the microphone and the recorder for `how`. A failure stops the microphone. async fn open_take(inner: &Rc, how: Start) -> Result { let stream = request_mic().await.map_err(|_| "micDenied")?; if !MediaRecorder::is_type_supported(MIME) { stop_tracks(&stream); return Err("mediaFailed"); } let name = format!("recording-{}.weba", stamp()); begin(inner, stream.clone(), how, name).map_err(|_| { stop_tracks(&stream); "mediaFailed" }) } async fn request_mic() -> Result { let devices = web_sys::window().ok_or("no window")?.navigator().media_devices()?; let constraints = MediaStreamConstraints::new(); constraints.set_audio(&JsValue::TRUE); let promise = devices.get_user_media_with_constraints(&constraints)?; JsFuture::from(promise).await?.dyn_into() } /// Builds the recorder with its handlers and starts it with one chunk a second. Each chunk is /// kept in the take and queued for the socket task. fn begin(inner: &Rc, stream: MediaStream, how: Start, name: String) -> Result { let opts = MediaRecorderOptions::new(); opts.set_mime_type(MIME); let recorder = MediaRecorder::new_with_media_stream_and_media_recorder_options(&stream, &opts)?; let (session, at, fresh) = match how { Start::New(at) => (None, at, true), Start::Continue(session) => (Some(session), None, false), }; // A tab close while the take is open asks first; the guard goes when the take is concluded. let unload = Closure::::new(|ev: Event| { ev.prevent_default(); if let Some(e) = ev.dyn_ref::() { e.set_return_value(""); } }); let take = Rc::new(Take { session: RefCell::new(session), part: Cell::new(None), fresh, placed: Cell::new(false), at, name, mime: recorder.mime_type(), chunks: js_sys::Array::new(), queue: RefCell::default(), sent: Cell::new(0), ended: Cell::new(false), failed: Cell::new(false), unload, }); let sink = take.clone(); let on_data = Closure::::new(move |ev: BlobEvent| { if let Some(blob) = ev.data().filter(|b| b.size() > 0.0) { let raw: &JsValue = blob.as_ref(); sink.chunks.push(raw); sink.queue.borrow_mut().push_back(blob); } }); recorder.set_ondataavailable(Some(on_data.as_ref().unchecked_ref())); // Strong, so the take is still finished when the page leaves. `on_stopped` moves the // recording, and this closure with it, out of `inner`, which breaks the cycle. let held = inner.clone(); let on_stop = Closure::::new(move || on_stopped(&held)); recorder.set_onstop(Some(on_stop.as_ref().unchecked_ref())); recorder.start_with_time_slice(1000)?; let win = web_sys::window().ok_or("no window")?; win.add_event_listener_with_callback("beforeunload", take.unload.as_ref().unchecked_ref())?; let started = js_sys::Date::now(); let time = inner.ui.borrow().as_ref().map(|(_, t)| t.clone()); let ticker = Closure::::new(move || { if let Some(t) = &time { t.set_text_content(Some(&clock(js_sys::Date::now() - started))); } }); let tick = win.set_interval_with_callback_and_timeout_and_arguments_0(ticker.as_ref().unchecked_ref(), 1000)?; Ok(Recording { recorder, stream, take, tick: Some(tick), _on_data: on_data, _on_stop: on_stop, _ticker: ticker }) } /// Asks the recorder to stop. The rest happens in `on_stopped`, once its data is in. fn stop_current(inner: &Inner) { let recorder = inner.rec.borrow().as_ref().map(|r| r.recorder.clone()); if let Some(recorder) = recorder { let _ = recorder.stop(); } } /// The recorder stopped: releases the microphone and the timers, and marks the take ended so /// the socket task can send `end` once every chunk is acked. Runs inside the recorder's stop /// event, so the recording is dropped in a later task, not here. fn on_stopped(inner: &Rc) { let taken = inner.rec.borrow_mut().take(); let Some(rec) = taken else { return }; release(&rec); rec.take.ended.set(true); set_ui(inner, false); spawn_local(async move { drop(rec) }); } /// Stops the timers and the handlers of a finished recording, and its tracks. The beforeunload /// guard stays until the take is concluded. fn release(rec: &Recording) { if let Some(win) = web_sys::window() && let Some(id) = rec.tick { win.clear_interval_with_handle(id); } rec.recorder.set_ondataavailable(None); rec.recorder.set_onstop(None); stop_tracks(&rec.stream); } fn stop_tracks(stream: &MediaStream) { for track in stream.get_tracks().iter() { if let Ok(track) = track.dyn_into::() { track.stop(); } } } /// How one socket of a take ended. enum Link { /// The server answered `done`: the part is stored. Done, /// The socket closed, or went quiet. Lost, /// The server answered `reject`. Rejected, } /// The socket task of a take. Connects, sends each chunk once the last one is acked, and /// reconnects for as long as the tab lives. A reject gives up. Once every chunk is acked after /// the stop, the take is concluded. async fn link(inner: Rc, take: Rc) { loop { match connection(&inner, &take).await { Link::Done => break, Link::Lost => sleep(RETRY_MS).await, Link::Rejected => { take.failed.set(true); // Nothing more is sent, so the recording is stopped and its chunks gathered. stop_current(&inner); while !take.ended.get() { sleep(200).await; } break; } } } conclude(inner, take).await; } /// The URL of the take's next socket. A new take asks for its note until the server names it, /// then reconnects to its part. A continuation asks for its take until the server gives a part. fn url(inner: &Inner, take: &Take) -> Option { let session = take.session.borrow().clone(); let query = match (session, take.part.get()) { (Some(s), Some(part)) => format!("session={}&part={part}", enc(&s)), (Some(s), None) => format!("session={}", enc(&s)), (None, _) => format!("note={}", enc(&inner.note_id)), }; let loc = web_sys::window()?.location(); let proto = if loc.protocol().unwrap_or_default() == "https:" { "wss" } else { "ws" }; Some(format!("{proto}://{}/media/live?{query}", loc.host().unwrap_or_default())) } /// One socket of a take: it attaches to the part, then sends the queued chunks one at a time, /// each once the one before is acked. A stop sends `end` once the queue is empty. async fn connection(inner: &Inner, take: &Take) -> Link { let Some(socket) = url(inner, take).and_then(|u| Socket::open(&u)) else { return Link::Lost }; let mut ready = false; let mut waiting = false; let mut end_sent = false; let mut last = js_sys::Date::now(); loop { if ready && !waiting { let next = take.queue.borrow().front().cloned(); match next { Some(blob) => { if socket.ws.send_with_blob(&blob).is_err() { return Link::Lost; } waiting = true; } None if take.ended.get() && !end_sent => { let _ = socket.ws.send_with_str("end"); end_sent = true; } None => {} } } let frame = socket.inbox.borrow_mut().pop_front(); let text = match frame { Some(Frame::Text(text)) => text, Some(Frame::Closed) => return Link::Lost, None => { if (!ready || waiting) && js_sys::Date::now() - last > STALL_MS { return Link::Lost; } sleep(100).await; continue; } }; last = js_sys::Date::now(); let fields: Vec<&str> = text.split(' ').collect(); match fields.as_slice() { ["ready", session, part, bytes] => { let (Ok(part), Ok(bytes)) = (part.parse::(), bytes.parse::()) else { return Link::Lost }; take.attach(session, part, bytes); ready = true; } ["ack", bytes] if waiting => { let Ok(bytes) = bytes.parse::() else { return Link::Lost }; take.acked(bytes); waiting = false; if take.fresh && !take.placed.get() { place(inner, take); } } ["done"] => return Link::Done, ["reject"] => return Link::Rejected, _ => {} } } } impl Take { /// The server's `ready`: the take's id and the part, and what the part already holds. Those /// bytes are not sent again. fn attach(&self, session: &str, part: u32, bytes: u64) { *self.session.borrow_mut() = Some(session.to_owned()); self.part.set(Some(part)); let mut queue = self.queue.borrow_mut(); let mut skip = bytes.saturating_sub(self.sent.get()); while skip > 0 { let Some(front) = queue.front() else { break }; let size = front.size() as u64; if size <= skip { skip -= size; queue.pop_front(); } else { if let Ok(rest) = front.slice_with_f64_and_f64(skip as f64, size as f64) { queue[0] = rest; } break; } } self.sent.set(bytes); } /// A chunk is stored: it leaves the queue, and `bytes` is the new offset. fn acked(&self, bytes: u64) { self.queue.borrow_mut().pop_front(); self.sent.set(bytes); } } /// Places a new take's URL at its cursor. False while the editor is busy or gone or leaving, or /// before the server has named the take. fn place(inner: &Inner, take: &Take) -> bool { if inner.detached.get() { return false; } let (Some(ed), Some(session)) = (inner.ed.upgrade(), take.session.borrow().clone()) else { return false }; let url = format!("/media/rec/{session}"); let done = insert_at(&ed, take.at.as_ref(), embed(&url, &take.name)); take.placed.set(done); done } /// Runs once the socket task is done with the take. A rejected take is saved locally, and so is /// a new take whose URL could not be placed (the editor went, or the server never named the /// take), so its recording is not lost. Then the beforeunload guard goes. async fn conclude(inner: Rc, take: Rc) { if !take.failed.get() && take.fresh && !take.placed.get() { // The first chunk may have come while the editor was busy. for _ in 0..5 { if place(&inner, &take) { break; } sleep(200).await; } } if take.failed.get() { notice("mediaFailed"); } if take.failed.get() || (take.fresh && !take.placed.get()) { if let Some(blob) = take_blob(&take) { save_locally(&blob, &take.name); } } if let Some(win) = web_sys::window() { let _ = win.remove_event_listener_with_callback("beforeunload", take.unload.as_ref().unchecked_ref()); } } /// The whole part as one blob. None when there is nothing to save. fn take_blob(take: &Take) -> Option { if take.chunks.length() == 0 { return None; } let bag = BlobPropertyBag::new(); bag.set_type(&take.mime); let parts: &JsValue = take.chunks.as_ref(); Blob::new_with_blob_sequence_and_options(parts, &bag).ok() } /// A take that could not be uploaded goes to the browser's downloads rather than being lost. fn save_locally(blob: &Blob, name: &str) { let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return }; let Ok(url) = web_sys::Url::create_object_url_with_blob(blob) else { return }; let link: HtmlElement = h(&doc, "a", &[("href", &url), ("download", name)], None).unchecked_into(); link.click(); } /// What a socket hears from the server or the browser. enum Frame { Text(String), Closed, } /// A WebSocket with its handlers, which push what arrives into `inbox`. Dropping it clears the /// handlers and closes the socket, so an abandoned socket says nothing more. struct Socket { ws: WebSocket, inbox: Rc>>, _on_message: Closure, _on_close: Closure, } impl Socket { fn open(url: &str) -> Option { let ws = WebSocket::new(url).ok()?; ws.set_binary_type(BinaryType::Arraybuffer); let inbox: Rc>> = Rc::default(); let sink = inbox.clone(); let on_message = Closure::::new(move |ev: MessageEvent| { if let Some(text) = ev.data().as_string() { sink.borrow_mut().push_back(Frame::Text(text)); } }); let sink = inbox.clone(); let on_close = Closure::::new(move || sink.borrow_mut().push_back(Frame::Closed)); ws.set_onmessage(Some(on_message.as_ref().unchecked_ref())); ws.set_onerror(Some(on_close.as_ref().unchecked_ref())); ws.set_onclose(Some(on_close.as_ref().unchecked_ref())); Some(Socket { ws, inbox, _on_message: on_message, _on_close: on_close }) } } impl Drop for Socket { fn drop(&mut self) { self.ws.set_onmessage(None); self.ws.set_onerror(None); self.ws.set_onclose(None); let _ = self.ws.close(); } } /// Waits `ms` milliseconds. async fn sleep(ms: i32) { let Some(win) = web_sys::window() else { return }; let wait = js_sys::Promise::new(&mut |resolve, _reject| { let _ = win.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); }); let _ = JsFuture::from(wait).await; } /// Percent-encodes a query value. fn enc(s: &str) -> String { String::from(js_sys::encode_uri_component(s)) } /// Pressed state, label and the m:ss readout of the record button. fn set_ui(inner: &Inner, on: bool) { let bound = inner.ui.borrow().clone(); let Some((btn, time)) = bound else { return }; let value = if on { "true" } else { "false" }; let _ = btn.set_attribute("aria-pressed", value); let _ = btn.set_attribute("data-recording", value); let label = btn.owner_document().map(|d| Strings::load(&d).get(if on { "stopRecording" } else { "recordAudio" })).unwrap_or_default(); let _ = btn.set_attribute("aria-label", &label); if let Ok(Some(tip)) = btn.query_selector(".tip-label") { tip.set_text_content(Some(&label)); } if on { let _ = time.remove_attribute("hidden"); time.set_text_content(Some("0:00")); } else { let _ = time.set_attribute("hidden", ""); time.set_text_content(None); } } /// `m:ss` for a span in milliseconds. fn clock(ms: f64) -> String { let s = (ms / 1000.0).max(0.0) as u64; format!("{}:{:02}", s / 60, s % 60) } /// Local time as `YYYYMMDD-HHMMSS`, for recording names. fn stamp() -> String { let d = js_sys::Date::new_0(); format!( "{:04}{:02}{:02}-{:02}{:02}{:02}", d.get_full_year(), d.get_month() + 1, d.get_date(), d.get_hours(), d.get_minutes(), d.get_seconds() ) }