repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/info/mod.rs
crates/tauri-cli/src/info/mod.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use crate::{ error::Context, helpers::app_paths::{resolve_frontend_dir, resolve_tauri_dir}, Result, }; use clap::Parser; use colored::{ColoredString, Colorize}; use dialoguer::{theme::ColorfulTheme, Confirm}; use serde::Deserialize; use std::fmt::{self, Display, Formatter}; mod app; mod env_nodejs; mod env_rust; pub mod env_system; #[cfg(target_os = "macos")] mod ios; mod packages_nodejs; mod packages_rust; pub mod plugins; #[derive(Deserialize)] struct JsCliVersionMetadata { version: String, node: String, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct VersionMetadata { #[serde(rename = "cli.js")] js_cli: JsCliVersionMetadata, } fn version_metadata() -> Result<VersionMetadata> { serde_json::from_str::<VersionMetadata>(include_str!("../../metadata-v2.json")) .context("failed to parse version metadata") } #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default)] pub enum Status { Neutral = 0, #[default] Success, Warning, Error, } impl Status { fn color<S: AsRef<str>>(&self, s: S) -> ColoredString { let s = s.as_ref(); match self { Status::Neutral => s.normal(), Status::Success => s.green(), Status::Warning => s.yellow(), Status::Error => s.red(), } } } impl Display for Status { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!( f, "{}", match self { Status::Neutral => "-".cyan(), Status::Success => "✔".green(), Status::Warning => "⚠".yellow(), Status::Error => "✘".red(), } ) } } #[derive(Default)] pub enum ActionResult { Full { description: String, status: Status, }, Description(String), #[default] None, } impl From<String> for ActionResult { fn from(value: String) -> Self { ActionResult::Description(value) } } impl From<(String, Status)> for ActionResult { fn from(value: (String, Status)) -> Self { ActionResult::Full { description: value.0, status: value.1, } } } impl From<Option<String>> for ActionResult { fn from(value: Option<String>) -> Self { value.map(ActionResult::Description).unwrap_or_default() } } impl From<Option<(String, Status)>> for ActionResult { fn from(value: Option<(String, Status)>) -> Self { value .map(|v| ActionResult::Full { description: v.0, status: v.1, }) .unwrap_or_default() } } pub struct SectionItem { /// If description is none, the item is skipped description: Option<String>, status: Status, action: Option<Box<dyn FnMut() -> ActionResult>>, action_if_err: Option<Box<dyn FnMut() -> ActionResult>>, } impl Display for SectionItem { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let desc = self .description .as_ref() .map(|s| s.replace('\n', "\n ")) .unwrap_or_default(); let (first, second) = desc.split_once(':').unwrap(); write!(f, "{} {}:{}", self.status, first.bold(), second) } } impl SectionItem { fn new() -> Self { Self { action: None, action_if_err: None, description: None, status: Status::Neutral, } } fn action<F: FnMut() -> ActionResult + 'static>(mut self, action: F) -> Self { self.action = Some(Box::new(action)); self } // fn action_if_err<F: FnMut() -> ActionResult + 'static>(mut self, action: F) -> Self { // self.action_if_err = Some(Box::new(action)); // self // } fn description<S: AsRef<str>>(mut self, description: S) -> Self { self.description = Some(description.as_ref().to_string()); self } fn run_action(&mut self) { let mut res = ActionResult::None; if let Some(action) = &mut self.action { res = action(); } self.apply_action_result(res); } fn run_action_if_err(&mut self) { let mut res = ActionResult::None; if let Some(action) = &mut self.action_if_err { res = action(); } self.apply_action_result(res); } fn apply_action_result(&mut self, result: ActionResult) { match result { ActionResult::Full { description, status, } => { self.description = Some(description); self.status = status; } ActionResult::Description(description) => { self.description = Some(description); } ActionResult::None => {} } } fn run(&mut self, interactive: bool) -> Status { self.run_action(); if self.status == Status::Error && interactive && self.action_if_err.is_some() { if let Some(description) = &self.description { let confirmed = Confirm::with_theme(&ColorfulTheme::default()) .with_prompt(format!( "{}\n Run the automatic fix?", description.replace('\n', "\n ") )) .interact() .unwrap_or(false); if confirmed { self.run_action_if_err() } } } self.status } } struct Section<'a> { label: &'a str, interactive: bool, items: Vec<SectionItem>, } impl Section<'_> { fn display(&mut self) { let mut status = Status::Neutral; for item in &mut self.items { let s = item.run(self.interactive); if s > status { status = s; } } let status_str = format!("[{status}]"); let status = status.color(status_str); println!(); println!("{} {}", status, self.label.bold().yellow()); for item in &self.items { if item.description.is_some() { println!(" {item}"); } } } } #[derive(Debug, Parser)] #[clap( about = "Show a concise list of information about the environment, Rust, Node.js and their versions as well as a few relevant project configurations" )] pub struct Options { /// Interactive mode to apply automatic fixes. #[clap(long)] pub interactive: bool, } pub fn command(options: Options) -> Result<()> { let Options { interactive } = options; let frontend_dir = resolve_frontend_dir(); let tauri_dir = resolve_tauri_dir(); if tauri_dir.is_some() { // safe to initialize crate::helpers::app_paths::resolve(); } let package_manager = frontend_dir .as_ref() .map(packages_nodejs::package_manager) .unwrap_or(crate::helpers::npm::PackageManager::Npm); let metadata = version_metadata()?; let mut environment = Section { label: "Environment", interactive, items: Vec::new(), }; environment.items.extend(env_system::items()); environment.items.extend(env_rust::items()); let items = env_nodejs::items(&metadata); environment.items.extend(items); let mut packages = Section { label: "Packages", interactive, items: Vec::new(), }; packages.items.extend(packages_rust::items( frontend_dir.as_ref(), tauri_dir.as_deref(), )); packages.items.extend(packages_nodejs::items( frontend_dir.as_ref(), package_manager, &metadata, )); let mut plugins = Section { label: "Plugins", interactive, items: plugins::items(frontend_dir.as_ref(), tauri_dir.as_deref(), package_manager), }; let mut app = Section { label: "App", interactive, items: Vec::new(), }; app .items .extend(app::items(frontend_dir.as_ref(), tauri_dir.as_deref())); environment.display(); packages.display(); plugins.display(); if let (Some(frontend_dir), Some(tauri_dir)) = (&frontend_dir, &tauri_dir) { if let Err(error) = plugins::check_mismatched_packages(frontend_dir, tauri_dir) { println!("\n{}: {error}", "Error".bright_red().bold()); } } app.display(); // iOS #[cfg(target_os = "macos")] { if let Some(p) = &tauri_dir { if p.join("gen/apple").exists() { let mut ios = Section { label: "iOS", interactive, items: Vec::new(), }; ios.items.extend(ios::items()); ios.display(); } } } Ok(()) }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/info/packages_nodejs.rs
crates/tauri-cli/src/info/packages_nodejs.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use super::SectionItem; use super::VersionMetadata; use colored::Colorize; use serde::Deserialize; use std::path::PathBuf; use crate::error::Context; use crate::{ error::Error, helpers::{cross_command, npm::PackageManager}, }; #[derive(Deserialize)] struct YarnVersionInfo { data: Vec<String>, } pub fn npm_latest_version(pm: &PackageManager, name: &str) -> crate::Result<Option<String>> { match pm { PackageManager::Yarn => { let mut cmd = cross_command("yarn"); let output = cmd .arg("info") .arg(name) .args(["version", "--json"]) .output() .map_err(|error| Error::CommandFailed { command: "yarn info --json".to_string(), error, })?; if output.status.success() { let stdout = String::from_utf8_lossy(&output.stdout); let info: YarnVersionInfo = serde_json::from_str(&stdout).context("failed to parse yarn info")?; Ok(Some(info.data.last().unwrap().to_string())) } else { Ok(None) } } PackageManager::YarnBerry => { let mut cmd = cross_command("yarn"); let output = cmd .arg("npm") .arg("info") .arg(name) .args(["--fields", "version", "--json"]) .output() .map_err(|error| Error::CommandFailed { command: "yarn npm info --fields version --json".to_string(), error, })?; if output.status.success() { let info: crate::PackageJson = serde_json::from_reader(std::io::Cursor::new(output.stdout)) .context("failed to parse yarn npm info")?; Ok(info.version) } else { Ok(None) } } // Bun and Deno don't support show command PackageManager::Npm | PackageManager::Deno | PackageManager::Bun => { let mut cmd = cross_command("npm"); let output = cmd .arg("show") .arg(name) .arg("version") .output() .map_err(|error| Error::CommandFailed { command: "npm show --version".to_string(), error, })?; if output.status.success() { let stdout = String::from_utf8_lossy(&output.stdout); Ok(Some(stdout.replace('\n', ""))) } else { Ok(None) } } PackageManager::Pnpm => { let mut cmd = cross_command("pnpm"); let output = cmd .arg("info") .arg(name) .arg("version") .output() .map_err(|error| Error::CommandFailed { command: "pnpm info --version".to_string(), error, })?; if output.status.success() { let stdout = String::from_utf8_lossy(&output.stdout); Ok(Some(stdout.replace('\n', ""))) } else { Ok(None) } } } } pub fn package_manager(frontend_dir: &PathBuf) -> PackageManager { let found = PackageManager::all_from_project(frontend_dir); if found.is_empty() { println!( "{}: no lock files found, defaulting to npm", "WARNING".yellow() ); return PackageManager::Npm; } let pkg_manager = found[0]; if found.len() > 1 { println!( "{}: Only one package manager should be used, but found {}.\n Please remove unused package manager lock files, will use {} for now!", "WARNING".yellow(), found.iter().map(ToString::to_string).collect::<Vec<_>>().join(" and "), pkg_manager ); } pkg_manager } pub fn items( frontend_dir: Option<&PathBuf>, package_manager: PackageManager, metadata: &VersionMetadata, ) -> Vec<SectionItem> { let mut items = Vec::new(); if let Some(frontend_dir) = frontend_dir { for (package, version) in [ ("@tauri-apps/api", None), ("@tauri-apps/cli", Some(metadata.js_cli.version.clone())), ] { let frontend_dir = frontend_dir.clone(); let item = nodejs_section_item(package.into(), version, frontend_dir, package_manager); items.push(item); } } items } pub fn nodejs_section_item( package: String, version: Option<String>, frontend_dir: PathBuf, package_manager: PackageManager, ) -> SectionItem { SectionItem::new().action(move || { let version = version.clone().unwrap_or_else(|| { package_manager .current_package_version(&package, &frontend_dir) .unwrap_or_default() .unwrap_or_default() }); let latest_ver = super::packages_nodejs::npm_latest_version(&package_manager, &package) .unwrap_or_default() .unwrap_or_default(); if version.is_empty() { format!("{} {}: not installed!", package, " ⱼₛ".black().on_yellow()) } else { format!( "{} {}: {}{}", package, " ⱼₛ".black().on_yellow(), version, if !(version.is_empty() || latest_ver.is_empty()) { let version = semver::Version::parse(version.as_str()).unwrap(); let target_version = semver::Version::parse(latest_ver.as_str()).unwrap(); if version < target_version { format!(" ({}, latest: {})", "outdated".yellow(), latest_ver.green()) } else { "".into() } } else { "".into() } ) } .into() }) }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/info/plugins.rs
crates/tauri-cli/src/info/plugins.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use std::{ collections::HashMap, iter, path::{Path, PathBuf}, }; use crate::{ helpers::{ self, cargo_manifest::{cargo_manifest_and_lock, crate_version}, npm::PackageManager, }, Error, }; use super::{packages_nodejs, packages_rust, SectionItem}; #[derive(Debug)] pub struct InstalledPackage { pub crate_name: String, pub npm_name: String, pub crate_version: semver::Version, pub npm_version: semver::Version, } #[derive(Debug)] pub struct InstalledPackages(Vec<InstalledPackage>); impl InstalledPackages { pub fn mismatched(&self) -> Vec<&InstalledPackage> { self .0 .iter() .filter(|p| { p.crate_version.major != p.npm_version.major || p.crate_version.minor != p.npm_version.minor }) .collect() } } pub fn installed_tauri_packages( frontend_dir: &Path, tauri_dir: &Path, package_manager: PackageManager, ) -> InstalledPackages { let know_plugins = helpers::plugins::known_plugins(); let crate_names: Vec<String> = iter::once("tauri".to_owned()) .chain( know_plugins .keys() .map(|plugin_name| format!("tauri-plugin-{plugin_name}")), ) .collect(); let npm_names: Vec<String> = iter::once("@tauri-apps/api".to_owned()) .chain( know_plugins .keys() .map(|plugin_name| format!("@tauri-apps/plugin-{plugin_name}")), ) .collect(); let (manifest, lock) = cargo_manifest_and_lock(tauri_dir); let mut rust_plugins: HashMap<String, semver::Version> = crate_names .iter() .filter_map(|crate_name| { let crate_version = crate_version(tauri_dir, manifest.as_ref(), lock.as_ref(), crate_name).version?; let crate_version = semver::Version::parse(&crate_version) .inspect_err(|_| { // On first run there's no lockfile yet so we get the version requirement from Cargo.toml. // In our templates that's `2` which is not a valid semver version but a version requirement. // log::error confused users so we use log::debug to still be able to see this error if needed. log::debug!("Failed to parse version `{crate_version}` for crate `{crate_name}`"); }) .ok()?; Some((crate_name.clone(), crate_version)) }) .collect(); let mut npm_plugins = package_manager .current_package_versions(&npm_names, frontend_dir) .unwrap_or_default(); let installed_plugins = crate_names .iter() .zip(npm_names.iter()) .filter_map(|(crate_name, npm_name)| { let (crate_name, crate_version) = rust_plugins.remove_entry(crate_name)?; let (npm_name, npm_version) = npm_plugins.remove_entry(npm_name)?; Some(InstalledPackage { npm_name, npm_version, crate_name, crate_version, }) }) .collect(); InstalledPackages(installed_plugins) } pub fn items( frontend_dir: Option<&PathBuf>, tauri_dir: Option<&Path>, package_manager: PackageManager, ) -> Vec<SectionItem> { let mut items = Vec::new(); if tauri_dir.is_some() || frontend_dir.is_some() { if let Some(tauri_dir) = tauri_dir { let (manifest, lock) = cargo_manifest_and_lock(tauri_dir); for p in helpers::plugins::known_plugins().keys() { let dep = format!("tauri-plugin-{p}"); let crate_version = crate_version(tauri_dir, manifest.as_ref(), lock.as_ref(), &dep); if !crate_version.has_version() { continue; } let item = packages_rust::rust_section_item(&dep, crate_version); items.push(item); let Some(frontend_dir) = frontend_dir else { continue; }; let package = format!("@tauri-apps/plugin-{p}"); let item = packages_nodejs::nodejs_section_item( package, None, frontend_dir.clone(), package_manager, ); items.push(item); } } } items } pub fn check_mismatched_packages(frontend_dir: &Path, tauri_path: &Path) -> crate::Result<()> { let installed_packages = installed_tauri_packages( frontend_dir, tauri_path, PackageManager::from_project(frontend_dir), ); let mismatched_packages = installed_packages.mismatched(); if mismatched_packages.is_empty() { return Ok(()); } let mismatched_text = mismatched_packages .iter() .map( |InstalledPackage { crate_name, crate_version, npm_name, npm_version, }| format!("{crate_name} (v{crate_version}) : {npm_name} (v{npm_version})"), ) .collect::<Vec<_>>() .join("\n"); Err(Error::GenericError(format!("Found version mismatched Tauri packages. Make sure the NPM package and Rust crate versions are on the same major/minor releases:\n{mismatched_text}"))) }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/src/info/env_system.rs
crates/tauri-cli/src/info/env_system.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use super::{SectionItem, Status}; #[cfg(windows)] use crate::error::Context; use colored::Colorize; #[cfg(windows)] use serde::Deserialize; use std::process::Command; #[cfg(windows)] #[derive(Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct VsInstanceInfo { display_name: String, } #[cfg(windows)] const VSWHERE: &[u8] = include_bytes!("../../scripts/vswhere.exe"); #[cfg(windows)] fn build_tools_version() -> crate::Result<Vec<String>> { let mut vswhere = std::env::temp_dir(); vswhere.push("vswhere.exe"); if !vswhere.exists() { if let Ok(mut file) = std::fs::File::create(&vswhere) { use std::io::Write; let _ = file.write_all(VSWHERE); } } // Check if there are Visual Studio installations that have the "MSVC - C++ Buildtools" and "Windows SDK" components. // Both the Windows 10 and Windows 11 SDKs work so we need to query it twice. let output_sdk10 = Command::new(&vswhere) .args([ "-prerelease", "-products", "*", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-requires", "Microsoft.VisualStudio.Component.Windows10SDK.*", "-format", "json", "-utf8", ]) .output() .map_err(|error| crate::error::Error::CommandFailed { command: "vswhere -prerelease -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -requires Microsoft.VisualStudio.Component.Windows10SDK.* -format json -utf8".to_string(), error, })?; let output_sdk11 = Command::new(vswhere) .args([ "-prerelease", "-products", "*", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-requires", "Microsoft.VisualStudio.Component.Windows11SDK.*", "-format", "json", "-utf8", ]) .output() .map_err(|error| crate::error::Error::CommandFailed { command: "vswhere -prerelease -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -requires Microsoft.VisualStudio.Component.Windows11SDK.* -format json -utf8".to_string(), error, })?; let mut instances: Vec<VsInstanceInfo> = Vec::new(); if output_sdk10.status.success() { let stdout = String::from_utf8_lossy(&output_sdk10.stdout); let found: Vec<VsInstanceInfo> = serde_json::from_str(&stdout).context("failed to parse vswhere output")?; instances.extend(found); } if output_sdk11.status.success() { let stdout = String::from_utf8_lossy(&output_sdk11.stdout); let found: Vec<VsInstanceInfo> = serde_json::from_str(&stdout).context("failed to parse vswhere output")?; instances.extend(found); } let mut instances: Vec<String> = instances .iter() .map(|i| i.display_name.clone()) .collect::<Vec<String>>(); instances.sort_unstable(); instances.dedup(); Ok(instances) } #[cfg(windows)] fn webview2_version() -> crate::Result<Option<String>> { let powershell_path = std::env::var("SYSTEMROOT").map_or_else( |_| "powershell.exe".to_string(), |p| format!("{p}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"), ); // check 64bit machine-wide installation let output = Command::new(&powershell_path) .args(["-NoProfile", "-Command"]) .arg("Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}") .output() .map_err(|error| crate::error::Error::CommandFailed { command: "Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}".to_string(), error, })?; if output.status.success() { return Ok(Some( String::from_utf8_lossy(&output.stdout).replace('\n', ""), )); } // check 32bit machine-wide installation let output = Command::new(&powershell_path) .args(["-NoProfile", "-Command"]) .arg("Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}") .output() .map_err(|error| crate::error::Error::CommandFailed { command: "Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}".to_string(), error, })?; if output.status.success() { return Ok(Some( String::from_utf8_lossy(&output.stdout).replace('\n', ""), )); } // check user-wide installation let output = Command::new(&powershell_path) .args(["-NoProfile", "-Command"]) .arg("Get-ItemProperty -Path 'HKCU:\\SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}") .output() .map_err(|error| crate::error::Error::CommandFailed { command: "Get-ItemProperty -Path 'HKCU:\\SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}".to_string(), error, })?; if output.status.success() { return Ok(Some( String::from_utf8_lossy(&output.stdout).replace('\n', ""), )); } Ok(None) } #[cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] fn pkg_conf_version(package: &str) -> Option<String> { Command::new("pkg-config") .args([package, "--print-provides"]) .output() .map(|o| { String::from_utf8_lossy(&o.stdout) .split('=') .nth(1) .map(|s| s.trim().to_string()) }) .unwrap_or(None) } #[cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] fn webkit2gtk_ver() -> Option<String> { pkg_conf_version("webkit2gtk-4.1") } #[cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] fn rsvg2_ver() -> Option<String> { pkg_conf_version("librsvg-2.0") } #[cfg(target_os = "macos")] fn is_xcode_command_line_tools_installed() -> bool { Command::new("xcode-select") .arg("-p") .output() .map(|o| o.status.success()) .unwrap_or(false) } #[cfg(target_os = "macos")] pub fn xcode_version() -> Option<String> { Command::new("xcodebuild") .arg("-version") .output() .ok() .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) .and_then(|s| { s.split('\n') .filter_map(|line| line.strip_prefix("Xcode ")) .next() .map(ToString::to_string) }) } fn de_and_session() -> String { #[cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] return { let de = std::env::var("XDG_SESSION_DESKTOP"); let session = std::env::var("XDG_SESSION_TYPE"); format!( " ({} on {})", de.as_deref().unwrap_or("Unknown DE"), session.as_deref().unwrap_or("Unknown Session") ) }; #[cfg(not(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" )))] String::new() } pub fn items() -> Vec<SectionItem> { vec![ SectionItem::new().action(|| { let os_info = os_info::get(); format!( "OS: {} {} {} ({:?}){}", os_info.os_type(), os_info.version(), os_info.architecture().unwrap_or("Unknown Architecture"), os_info.bitness(), de_and_session(), ).into() }), #[cfg(windows)] SectionItem::new().action(|| { let error = format!( "Webview2: {}\nVisit {}", "not installed!".red(), "https://developer.microsoft.com/en-us/microsoft-edge/webview2/".cyan() ); webview2_version() .map(|v| { v.map(|v| (format!("WebView2: {v}"), Status::Success)) .unwrap_or_else(|| (error.clone(), Status::Error)) }) .unwrap_or_else(|_| (error, Status::Error)).into() }), #[cfg(windows)] SectionItem::new().action(|| { let build_tools = build_tools_version().unwrap_or_default(); if build_tools.is_empty() { ( format!( "Couldn't detect any Visual Studio or VS Build Tools instance with MSVC and SDK components. Download from {}", "https://aka.ms/vs/17/release/vs_BuildTools.exe".cyan() ), Status::Error, ).into() } else { ( format!( "MSVC: {}{}", if build_tools.len() > 1 { format!("\n {} ", "-".cyan()) } else { "".into() }, build_tools.join(format!("\n {} ", "-".cyan()).as_str()), ), Status::Success, ).into() } }), #[cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] SectionItem::new().action(|| { webkit2gtk_ver() .map(|v| (format!("webkit2gtk-4.1: {v}"), Status::Success)) .unwrap_or_else(|| { ( format!( "webkit2gtk-4.1: {}\nVisit {} to learn more about tauri prerequisites", "not installed".red(), "https://v2.tauri.app/start/prerequisites/".cyan() ), Status::Error, ) }).into() }, ), #[cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] SectionItem::new().action(|| { rsvg2_ver() .map(|v| (format!("rsvg2: {v}"), Status::Success)) .unwrap_or_else(|| { ( format!( "rsvg2: {}\nVisit {} to learn more about tauri prerequisites", "not installed".red(), "https://v2.tauri.app/start/prerequisites/".cyan() ), Status::Error, ) }).into() }, ), #[cfg(target_os = "macos")] SectionItem::new().action(|| { if is_xcode_command_line_tools_installed() { ( "Xcode Command Line Tools: installed".into(), Status::Success, ) } else { ( format!( "Xcode Command Line Tools: {}\n Run `{}`", "not installed!".red(), "xcode-select --install".cyan() ), Status::Error, ) }.into() }, ), #[cfg(target_os = "macos")] SectionItem::new().action(|| { xcode_version().map(|v| (format!("Xcode: {v}"), Status::Success)).unwrap_or_else(|| { (format!("Xcode: {}", "not installed!".red()), Status::Error) }).into() }), ] }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/build.rs
crates/tauri-cli/templates/plugin/build.rs
const COMMANDS: &[&str] = &["ping"]; fn main() { tauri_plugin::Builder::new(COMMANDS) .android_path("android") .ios_path("ios") .build(); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/__example-basic/vanilla/src-tauri/build.rs
crates/tauri-cli/templates/plugin/__example-basic/vanilla/src-tauri/build.rs
fn main() { tauri_build::build() }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/__example-basic/vanilla/src-tauri/src/lib.rs
crates/tauri-cli/templates/plugin/__example-basic/vanilla/src-tauri/src/lib.rs
#[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_{{ plugin_name_snake_case }}::init()) .run(tauri::generate_context!()) .expect("error while running tauri application"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/__example-basic/vanilla/src-tauri/src/main.rs
crates/tauri-cli/templates/plugin/__example-basic/vanilla/src-tauri/src/main.rs
// Prevents additional console window on Windows in release, DO NOT REMOVE!! #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { tauri_app_lib::run(); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/src/mobile.rs
crates/tauri-cli/templates/plugin/src/mobile.rs
{{#if license_header}} {{ license_header }} {{/if}} use serde::de::DeserializeOwned; use tauri::{ plugin::{PluginApi, PluginHandle}, AppHandle, Runtime, }; use crate::models::*; #[cfg(target_os = "ios")] tauri::ios_plugin_binding!(init_plugin_{{ plugin_name_snake_case }}); // initializes the Kotlin or Swift plugin classes pub fn init<R: Runtime, C: DeserializeOwned>( _app: &AppHandle<R>, api: PluginApi<R, C>, ) -> crate::Result<{{ plugin_name_pascal_case }}<R>> { #[cfg(target_os = "android")] let handle = api.register_android_plugin("{{ android_package_id }}", "ExamplePlugin")?; #[cfg(target_os = "ios")] let handle = api.register_ios_plugin(init_plugin_{{ plugin_name_snake_case }})?; Ok({{ plugin_name_pascal_case }}(handle)) } /// Access to the {{ plugin_name }} APIs. pub struct {{ plugin_name_pascal_case }}<R: Runtime>(PluginHandle<R>); impl<R: Runtime> {{ plugin_name_pascal_case }}<R> { pub fn ping(&self, payload: PingRequest) -> crate::Result<PingResponse> { self .0 .run_mobile_plugin("ping", payload) .map_err(Into::into) } }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/src/lib.rs
crates/tauri-cli/templates/plugin/src/lib.rs
{{#if license_header}} {{ license_header }} {{/if}} use tauri::{ plugin::{Builder, TauriPlugin}, Manager, Runtime, }; pub use models::*; #[cfg(desktop)] mod desktop; #[cfg(mobile)] mod mobile; mod commands; mod error; mod models; pub use error::{Error, Result}; #[cfg(desktop)] use desktop::{{ plugin_name_pascal_case }}; #[cfg(mobile)] use mobile::{{ plugin_name_pascal_case }}; /// Extensions to [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`] to access the {{ plugin_name }} APIs. pub trait {{ plugin_name_pascal_case }}Ext<R: Runtime> { fn {{ plugin_name_snake_case }}(&self) -> &{{ plugin_name_pascal_case }}<R>; } impl<R: Runtime, T: Manager<R>> crate::{{ plugin_name_pascal_case }}Ext<R> for T { fn {{ plugin_name_snake_case }}(&self) -> &{{ plugin_name_pascal_case }}<R> { self.state::<{{ plugin_name_pascal_case }}<R>>().inner() } } /// Initializes the plugin. pub fn init<R: Runtime>() -> TauriPlugin<R> { Builder::new("{{ plugin_name }}") .invoke_handler(tauri::generate_handler![commands::ping]) .setup(|app, api| { #[cfg(mobile)] let {{ plugin_name_snake_case }} = mobile::init(app, api)?; #[cfg(desktop)] let {{ plugin_name_snake_case }} = desktop::init(app, api)?; app.manage({{ plugin_name_snake_case }}); Ok(()) }) .build() }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/src/error.rs
crates/tauri-cli/templates/plugin/src/error.rs
{{#if license_header}} {{ license_header }} {{/if}} use serde::{ser::Serializer, Serialize}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug, thiserror::Error)] pub enum Error { #[error(transparent)] Io(#[from] std::io::Error), #[cfg(mobile)] #[error(transparent)] PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError), } impl Serialize for Error { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(self.to_string().as_ref()) } }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/src/commands.rs
crates/tauri-cli/templates/plugin/src/commands.rs
{{#if license_header}} {{ license_header }} {{/if}} use tauri::{AppHandle, command, Runtime}; use crate::models::*; use crate::Result; use crate::{{ plugin_name_pascal_case }}Ext; #[command] pub(crate) async fn ping<R: Runtime>( app: AppHandle<R>, payload: PingRequest, ) -> Result<PingResponse> { app.{{ plugin_name_snake_case }}().ping(payload) }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/src/desktop.rs
crates/tauri-cli/templates/plugin/src/desktop.rs
{{#if license_header}} {{ license_header }} {{/if}} use serde::de::DeserializeOwned; use tauri::{plugin::PluginApi, AppHandle, Runtime}; use crate::models::*; pub fn init<R: Runtime, C: DeserializeOwned>( app: &AppHandle<R>, _api: PluginApi<R, C>, ) -> crate::Result<{{ plugin_name_pascal_case }}<R>> { Ok({{ plugin_name_pascal_case }}(app.clone())) } /// Access to the {{ plugin_name }} APIs. pub struct {{ plugin_name_pascal_case }}<R: Runtime>(AppHandle<R>); impl<R: Runtime> {{ plugin_name_pascal_case }}<R> { pub fn ping(&self, payload: PingRequest) -> crate::Result<PingResponse> { Ok(PingResponse { value: payload.value, }) } }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/src/models.rs
crates/tauri-cli/templates/plugin/src/models.rs
{{#if license_header}} {{ license_header }} {{/if}} use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PingRequest { pub value: Option<String>, } #[derive(Debug, Clone, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct PingResponse { pub value: Option<String>, }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/__example-api/tauri-app/src-tauri/build.rs
crates/tauri-cli/templates/plugin/__example-api/tauri-app/src-tauri/build.rs
fn main() { tauri_build::build() }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/__example-api/tauri-app/src-tauri/src/lib.rs
crates/tauri-cli/templates/plugin/__example-api/tauri-app/src-tauri/src/lib.rs
// Learn more about Tauri commands at https://v2.tauri.app/develop/calling-rust/#commands #[tauri::command] fn greet(name: &str) -> String { format!("Hello, {}! You've been greeted from Rust!", name) } #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .invoke_handler(tauri::generate_handler![greet]) .plugin(tauri_plugin_{{ plugin_name_snake_case }}::init()) .run(tauri::generate_context!()) .expect("error while running tauri application"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/plugin/__example-api/tauri-app/src-tauri/src/main.rs
crates/tauri-cli/templates/plugin/__example-api/tauri-app/src-tauri/src/main.rs
// Prevents additional console window on Windows in release, DO NOT REMOVE!! #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { tauri_app_lib::run(); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/app/src-tauri/build.rs
crates/tauri-cli/templates/app/src-tauri/build.rs
fn main() { tauri_build::build() }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/app/src-tauri/src/lib.rs
crates/tauri-cli/templates/app/src-tauri/src/lib.rs
#[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .setup(|app| { if cfg!(debug_assertions) { app.handle().plugin( tauri_plugin_log::Builder::default() .level(log::LevelFilter::Info) .build(), )?; } Ok(()) }) .run(tauri::generate_context!()) .expect("error while running tauri application"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/crates/tauri-cli/templates/app/src-tauri/src/main.rs
crates/tauri-cli/templates/app/src-tauri/src/main.rs
// Prevents additional console window on Windows in release, DO NOT REMOVE!! #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { app_lib::run(); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/state/main.rs
examples/state/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use std::sync::Mutex; use tauri::State; struct Counter(Mutex<isize>); #[tauri::command] fn increment(counter: State<'_, Counter>) -> isize { let mut c = counter.0.lock().unwrap(); *c += 1; *c } #[tauri::command] fn decrement(counter: State<'_, Counter>) -> isize { let mut c = counter.0.lock().unwrap(); *c -= 1; *c } #[tauri::command] fn reset(counter: State<'_, Counter>) -> isize { let mut c = counter.0.lock().unwrap(); *c = 0; *c } #[tauri::command] fn get(counter: State<'_, Counter>) -> isize { *counter.0.lock().unwrap() } fn main() { tauri::Builder::default() .manage(Counter(Mutex::new(0))) .invoke_handler(tauri::generate_handler![increment, decrement, reset, get]) .run(tauri::generate_context!( "../../examples/state/tauri.conf.json" )) .expect("error while running tauri application"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/isolation/main.rs
examples/isolation/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #[tauri::command] fn ping() { println!("ping: {:?}", std::time::Instant::now()); } fn main() { tauri::Builder::default() .invoke_handler(tauri::generate_handler![ping]) .run(tauri::generate_context!( "../../examples/isolation/tauri.conf.json" )) .expect("error while running tauri application"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/multiwebview/main.rs
examples/multiwebview/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use tauri::{LogicalPosition, LogicalSize, WebviewUrl}; fn main() { tauri::Builder::default() .setup(|app| { let width = 800.; let height = 600.; let window = tauri::window::WindowBuilder::new(app, "main") .inner_size(width, height) .build()?; let _webview1 = window.add_child( tauri::webview::WebviewBuilder::new("main1", WebviewUrl::App(Default::default())) .auto_resize(), LogicalPosition::new(0., 0.), LogicalSize::new(width / 2., height / 2.), )?; let _webview2 = window.add_child( tauri::webview::WebviewBuilder::new( "main2", WebviewUrl::External("https://github.com/tauri-apps/tauri".parse().unwrap()), ) .auto_resize(), LogicalPosition::new(width / 2., 0.), LogicalSize::new(width / 2., height / 2.), )?; let _webview3 = window.add_child( tauri::webview::WebviewBuilder::new( "main3", WebviewUrl::External("https://tauri.app".parse().unwrap()), ) .auto_resize(), LogicalPosition::new(0., height / 2.), LogicalSize::new(width / 2., height / 2.), )?; let _webview4 = window.add_child( tauri::webview::WebviewBuilder::new( "main4", WebviewUrl::External("https://twitter.com/TauriApps".parse().unwrap()), ) .auto_resize(), LogicalPosition::new(width / 2., height / 2.), LogicalSize::new(width / 2., height / 2.), )?; Ok(()) }) .run(tauri::generate_context!( "../../examples/multiwebview/tauri.conf.json" )) .expect("error while running tauri application"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/streaming/main.rs
examples/streaming/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use http::{header::*, response::Builder as ResponseBuilder, status::StatusCode}; use http_range::HttpRange; use std::{ io::{Read, Seek, SeekFrom, Write}, path::PathBuf, process::{Command, Stdio}, }; fn get_stream_response( request: http::Request<Vec<u8>>, ) -> Result<http::Response<Vec<u8>>, Box<dyn std::error::Error>> { // skip leading `/` let path = percent_encoding::percent_decode(&request.uri().path().as_bytes()[1..]) .decode_utf8_lossy() .to_string(); // return error 404 if it's not our video if path != "streaming_example_test_video.mp4" { return Ok(ResponseBuilder::new().status(404).body(Vec::new())?); } let mut file = std::fs::File::open(&path)?; // get file length let len = { let old_pos = file.stream_position()?; let len = file.seek(SeekFrom::End(0))?; file.seek(SeekFrom::Start(old_pos))?; len }; let mut resp = ResponseBuilder::new().header(CONTENT_TYPE, "video/mp4"); // if the webview sent a range header, we need to send a 206 in return let http_response = if let Some(range_header) = request.headers().get("range") { let not_satisfiable = || { ResponseBuilder::new() .status(StatusCode::RANGE_NOT_SATISFIABLE) .header(CONTENT_RANGE, format!("bytes */{len}")) .body(vec![]) }; // parse range header let ranges = if let Ok(ranges) = HttpRange::parse(range_header.to_str()?, len) { ranges .iter() // map the output back to spec range <start-end>, example: 0-499 .map(|r| (r.start, r.start + r.length - 1)) .collect::<Vec<_>>() } else { return Ok(not_satisfiable()?); }; /// The Maximum bytes we send in one range const MAX_LEN: u64 = 1000 * 1024; if ranges.len() == 1 { let &(start, mut end) = ranges.first().unwrap(); // check if a range is not satisfiable // // this should be already taken care of by HttpRange::parse // but checking here again for extra assurance if start >= len || end >= len || end < start { return Ok(not_satisfiable()?); } // adjust end byte for MAX_LEN end = start + (end - start).min(len - start).min(MAX_LEN - 1); // calculate number of bytes needed to be read let bytes_to_read = end + 1 - start; // allocate a buf with a suitable capacity let mut buf = Vec::with_capacity(bytes_to_read as usize); // seek the file to the starting byte file.seek(SeekFrom::Start(start))?; // read the needed bytes file.take(bytes_to_read).read_to_end(&mut buf)?; resp = resp.header(CONTENT_RANGE, format!("bytes {start}-{end}/{len}")); resp = resp.header(CONTENT_LENGTH, end + 1 - start); resp = resp.status(StatusCode::PARTIAL_CONTENT); resp.body(buf) } else { let mut buf = Vec::new(); let ranges = ranges .iter() .filter_map(|&(start, mut end)| { // filter out unsatisfiable ranges // // this should be already taken care of by HttpRange::parse // but checking here again for extra assurance if start >= len || end >= len || end < start { None } else { // adjust end byte for MAX_LEN end = start + (end - start).min(len - start).min(MAX_LEN - 1); Some((start, end)) } }) .collect::<Vec<_>>(); let boundary = random_boundary(); let boundary_sep = format!("\r\n--{boundary}\r\n"); let boundary_closer = format!("\r\n--{boundary}\r\n"); resp = resp.header( CONTENT_TYPE, format!("multipart/byteranges; boundary={boundary}"), ); for (end, start) in ranges { // a new range is being written, write the range boundary buf.write_all(boundary_sep.as_bytes())?; // write the needed headers `Content-Type` and `Content-Range` buf.write_all(format!("{CONTENT_TYPE}: video/mp4\r\n").as_bytes())?; buf.write_all(format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes())?; // write the separator to indicate the start of the range body buf.write_all("\r\n".as_bytes())?; // calculate number of bytes needed to be read let bytes_to_read = end + 1 - start; let mut local_buf = vec![0_u8; bytes_to_read as usize]; file.seek(SeekFrom::Start(start))?; file.read_exact(&mut local_buf)?; buf.extend_from_slice(&local_buf); } // all ranges have been written, write the closing boundary buf.write_all(boundary_closer.as_bytes())?; resp.body(buf) } } else { resp = resp.header(CONTENT_LENGTH, len); let mut buf = Vec::with_capacity(len as usize); file.read_to_end(&mut buf)?; resp.body(buf) }; http_response.map_err(Into::into) } fn random_boundary() -> String { let mut x = [0_u8; 30]; getrandom::fill(&mut x).expect("failed to get random bytes"); (x[..]) .iter() .map(|&x| format!("{x:x}")) .fold(String::new(), |mut a, x| { a.push_str(x.as_str()); a }) } fn download_video() { let video_file = PathBuf::from("streaming_example_test_video.mp4"); if !video_file.exists() { let video_url = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"; // Downloading with curl this saves us from adding // a Rust HTTP client dependency. println!("Downloading {video_url}"); let status = Command::new("curl") .arg("-L") .arg("-o") .arg(&video_file) .arg(video_url) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .output() .unwrap(); assert!(status.status.success()); assert!(video_file.exists()); } } fn main() { download_video(); tauri::Builder::default() .register_asynchronous_uri_scheme_protocol("stream", move |_ctx, request, responder| { match get_stream_response(request) { Ok(http_response) => responder.respond(http_response), Err(e) => responder.respond( ResponseBuilder::new() .status(StatusCode::INTERNAL_SERVER_ERROR) .header(CONTENT_TYPE, "text/plain") .body(e.to_string().as_bytes().to_vec()) .unwrap(), ), } }) .run(tauri::generate_context!( "../../examples/streaming/tauri.conf.json" )) .expect("error while running tauri application"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/commands/commands.rs
examples/commands/commands.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use tauri::{command, State}; #[command] pub fn cmd(_argument: String) {} #[command] pub fn invoke(_argument: String) {} #[command] pub fn message(_argument: String) {} #[command] pub fn resolver(_argument: String) {} #[command] pub fn simple_command(the_argument: String) { println!("{the_argument}"); } #[command] pub fn stateful_command(the_argument: Option<String>, state: State<'_, super::MyState>) { println!("{:?} {:?}", the_argument, state.inner()); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/commands/main.rs
examples/commands/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // we move some basic commands to a separate module just to show it works mod commands; use commands::{cmd, invoke, message, resolver}; use serde::Deserialize; use tauri::{ command, ipc::{Request, Response}, State, Window, }; #[derive(Debug)] pub struct MyState { #[allow(dead_code)] value: u64, #[allow(dead_code)] label: String, } #[derive(Debug, serde::Serialize)] enum MyError { FooError, } // ------------------------ Commands using Window ------------------------ #[command] fn window_label(window: Window) { println!("window label: {}", window.label()); } // Async commands #[command] async fn async_simple_command(the_argument: String) { println!("{the_argument}"); } #[command(rename_all = "snake_case")] async fn async_simple_command_snake(the_argument: String) { println!("{the_argument}"); } #[command] async fn async_stateful_command( the_argument: Option<String>, state: State<'_, MyState>, ) -> Result<(), ()> { println!("{:?} {:?}", the_argument, state.inner()); Ok(()) } // ------------------------ Raw future commands ------------------------ #[command(async)] fn future_simple_command(the_argument: String) -> impl std::future::Future<Output = ()> { println!("{the_argument}"); std::future::ready(()) } #[command(async)] fn future_simple_command_with_return( the_argument: String, ) -> impl std::future::Future<Output = String> { println!("{the_argument}"); std::future::ready(the_argument) } #[command(async)] fn future_simple_command_with_result( the_argument: String, ) -> impl std::future::Future<Output = Result<String, ()>> { println!("{the_argument}"); std::future::ready(Ok(the_argument)) } #[command(async)] fn force_async(the_argument: String) -> String { the_argument } #[command(async)] fn force_async_with_result(the_argument: &str) -> Result<&str, MyError> { (!the_argument.is_empty()) .then_some(the_argument) .ok_or(MyError::FooError) } // ------------------------ Raw future commands - snake_case ------------------------ #[command(async, rename_all = "snake_case")] fn future_simple_command_snake(the_argument: String) -> impl std::future::Future<Output = ()> { println!("{the_argument}"); std::future::ready(()) } #[command(async, rename_all = "snake_case")] fn future_simple_command_with_return_snake( the_argument: String, ) -> impl std::future::Future<Output = String> { println!("{the_argument}"); std::future::ready(the_argument) } #[command(async, rename_all = "snake_case")] fn future_simple_command_with_result_snake( the_argument: String, ) -> impl std::future::Future<Output = Result<String, ()>> { println!("{the_argument}"); std::future::ready(Ok(the_argument)) } #[command(async, rename_all = "snake_case")] fn force_async_snake(the_argument: String) -> String { the_argument } #[command(rename_all = "snake_case", async)] fn force_async_with_result_snake(the_argument: &str) -> Result<&str, MyError> { (!the_argument.is_empty()) .then_some(the_argument) .ok_or(MyError::FooError) } // ------------------------ Commands returning Result ------------------------ #[command] fn simple_command_with_result(the_argument: String) -> Result<String, MyError> { println!("{the_argument}"); (!the_argument.is_empty()) .then_some(the_argument) .ok_or(MyError::FooError) } #[command] fn stateful_command_with_result( the_argument: Option<String>, state: State<'_, MyState>, ) -> Result<String, MyError> { println!("{:?} {:?}", the_argument, state.inner()); dbg!(the_argument.ok_or(MyError::FooError)) } // ------------------------ Commands returning Result - snake_case ------------------------ #[command(rename_all = "snake_case")] fn simple_command_with_result_snake(the_argument: String) -> Result<String, MyError> { println!("{the_argument}"); (!the_argument.is_empty()) .then_some(the_argument) .ok_or(MyError::FooError) } #[command(rename_all = "snake_case")] fn stateful_command_with_result_snake( the_argument: Option<String>, state: State<'_, MyState>, ) -> Result<String, MyError> { println!("{:?} {:?}", the_argument, state.inner()); dbg!(the_argument.ok_or(MyError::FooError)) } // Async commands #[command] async fn async_simple_command_with_result(the_argument: String) -> Result<String, MyError> { println!("{the_argument}"); Ok(the_argument) } #[command] async fn async_stateful_command_with_result( the_argument: Option<String>, state: State<'_, MyState>, ) -> Result<String, MyError> { println!("{:?} {:?}", the_argument, state.inner()); Ok(the_argument.unwrap_or_default()) } // Non-Ident command function arguments #[command] fn command_arguments_wild(_: Window) { println!("we saw the wildcard!") } #[derive(Deserialize)] struct Person<'a> { name: &'a str, age: u8, } #[command] fn command_arguments_struct(Person { name, age }: Person<'_>) { println!("received person struct with name: {name} | age: {age}") } #[derive(Deserialize)] struct InlinePerson<'a>(&'a str, u8); #[command] fn command_arguments_tuple_struct(InlinePerson(name, age): InlinePerson<'_>) { println!("received person tuple with name: {name} | age: {age}") } #[command] fn borrow_cmd(the_argument: &str) -> &str { the_argument } #[command] fn borrow_cmd_async(the_argument: &str) -> &str { the_argument } #[command] fn raw_request(request: Request<'_>) -> Response { println!("{request:?}"); Response::new(include_bytes!("./README.md").to_vec()) } fn main() { tauri::Builder::default() .manage(MyState { value: 0, label: "Tauri!".into(), }) .invoke_handler(tauri::generate_handler![ borrow_cmd, borrow_cmd_async, raw_request, window_label, force_async, force_async_with_result, commands::simple_command, commands::stateful_command, cmd, invoke, message, resolver, async_simple_command, future_simple_command, async_stateful_command, command_arguments_wild, command_arguments_struct, simple_command_with_result, async_simple_command_snake, future_simple_command_snake, future_simple_command_with_return_snake, future_simple_command_with_result_snake, force_async_snake, force_async_with_result_snake, simple_command_with_result_snake, stateful_command_with_result_snake, stateful_command_with_result, command_arguments_tuple_struct, async_simple_command_with_result, future_simple_command_with_return, future_simple_command_with_result, async_stateful_command_with_result, ]) .run(tauri::generate_context!( "../../examples/commands/tauri.conf.json" )) .expect("error while running tauri application"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/helloworld/main.rs
examples/helloworld/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #[tauri::command] fn greet(name: &str) -> String { format!("Hello {name}, You have been greeted from Rust!") } fn main() { tauri::Builder::default() .invoke_handler(tauri::generate_handler![greet]) .run(tauri::generate_context!( "../../examples/helloworld/tauri.conf.json" )) .expect("error while running tauri application"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/build.rs
examples/api/src-tauri/build.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use tauri_build::WindowsAttributes; fn main() { tauri_build::try_build( tauri_build::Attributes::new() .codegen(tauri_build::CodegenContext::new()) .windows_attributes(WindowsAttributes::new_without_app_manifest()) .plugin( "app-menu", tauri_build::InlinedPlugin::new().commands(&["toggle", "popup"]), ) .app_manifest(tauri_build::AppManifest::new().commands(&[ "log_operation", "perform_request", "echo", "spam", ])), ) .expect("failed to run tauri-build"); #[cfg(windows)] { // workaround needed to prevent `STATUS_ENTRYPOINT_NOT_FOUND` error in tests // see https://github.com/tauri-apps/tauri/pull/4383#issuecomment-1212221864 let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap(); let target_env = std::env::var("CARGO_CFG_TARGET_ENV"); let is_tauri_workspace = std::env::var("__TAURI_WORKSPACE__").is_ok_and(|v| v == "true"); if is_tauri_workspace && target_os == "windows" && Ok("msvc") == target_env.as_deref() { embed_manifest_for_tests(); } } } #[cfg(windows)] fn embed_manifest_for_tests() { static WINDOWS_MANIFEST_FILE: &str = "windows-app-manifest.xml"; let manifest = std::env::current_dir() .unwrap() .join("../../../crates/tauri-build/src") .join(WINDOWS_MANIFEST_FILE); println!("cargo:rerun-if-changed={}", manifest.display()); // Embed the Windows application manifest file. println!("cargo:rustc-link-arg=/MANIFEST:EMBED"); println!( "cargo:rustc-link-arg=/MANIFESTINPUT:{}", manifest.to_str().unwrap() ); // Turn linker warnings into errors. println!("cargo:rustc-link-arg=/WX"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/tauri-plugin-sample/build.rs
examples/api/src-tauri/tauri-plugin-sample/build.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT const COMMANDS: &[&str] = &["ping"]; fn main() { tauri_plugin::Builder::new(COMMANDS) .android_path("android") .ios_path("ios") .global_api_script_path("./api-iife.js") .build(); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/tauri-plugin-sample/src/mobile.rs
examples/api/src-tauri/tauri-plugin-sample/src/mobile.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use serde::de::DeserializeOwned; use tauri::{ plugin::{PluginApi, PluginHandle}, AppHandle, Runtime, }; use crate::models::*; #[cfg(target_os = "android")] const PLUGIN_IDENTIFIER: &str = "com.plugin.sample"; #[cfg(target_os = "ios")] tauri::ios_plugin_binding!(init_plugin_sample); // initializes the Kotlin or Swift plugin classes pub fn init<R: Runtime, C: DeserializeOwned>( _app: &AppHandle<R>, api: PluginApi<R, C>, ) -> crate::Result<Sample<R>> { #[cfg(target_os = "android")] let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "ExamplePlugin")?; #[cfg(target_os = "ios")] let handle = api.register_ios_plugin(init_plugin_sample)?; Ok(Sample(handle)) } /// A helper class to access the sample APIs. pub struct Sample<R: Runtime>(PluginHandle<R>); impl<R: Runtime> Sample<R> { pub fn ping(&self, payload: PingRequest) -> crate::Result<PingResponse> { self .0 .run_mobile_plugin("ping", payload) .map_err(Into::into) } }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/tauri-plugin-sample/src/lib.rs
examples/api/src-tauri/tauri-plugin-sample/src/lib.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use serde::Deserialize; use std::path::PathBuf; use tauri::{ plugin::{Builder, TauriPlugin}, Manager, Runtime, }; pub use models::*; #[cfg(desktop)] mod desktop; #[cfg(mobile)] mod mobile; mod error; mod models; #[cfg(desktop)] use desktop::Sample; #[cfg(mobile)] use mobile::Sample; pub use error::*; /// Extensions to [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`] to access the sample APIs. pub trait SampleExt<R: Runtime> { fn sample(&self) -> &Sample<R>; } impl<R: Runtime, T: Manager<R>> crate::SampleExt<R> for T { fn sample(&self) -> &Sample<R> { self.state::<Sample<R>>().inner() } } #[allow(dead_code)] #[derive(Debug, Deserialize)] struct PingScope { path: PathBuf, } #[allow(dead_code)] #[derive(Debug, Deserialize)] struct SampleScope { path: PathBuf, } #[tauri::command] fn ping<R: tauri::Runtime>( app: tauri::AppHandle<R>, value: Option<String>, scope: tauri::ipc::CommandScope<PingScope>, global_scope: tauri::ipc::GlobalScope<SampleScope>, ) -> std::result::Result<PingResponse, String> { println!("local scope {scope:?}"); println!("global scope {global_scope:?}"); app .sample() .ping(PingRequest { value, on_event: tauri::ipc::Channel::new(|_| Ok(())), }) .map_err(|e| e.to_string()) } pub fn init<R: Runtime>() -> TauriPlugin<R> { Builder::new("sample") .setup(|app, api| { #[cfg(mobile)] let sample = mobile::init(app, api)?; #[cfg(desktop)] let sample = desktop::init(app, api)?; app.manage(sample); Ok(()) }) .invoke_handler(tauri::generate_handler![ping]) .on_navigation(|window, url| { println!("navigation {} {url}", window.label()); true }) .build() }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/tauri-plugin-sample/src/error.rs
examples/api/src-tauri/tauri-plugin-sample/src/error.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #[derive(Debug, thiserror::Error)] pub enum Error { #[cfg(mobile)] #[error(transparent)] PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError), #[error(transparent)] Tauri(#[from] tauri::Error), } pub type Result<T> = std::result::Result<T, Error>;
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/tauri-plugin-sample/src/desktop.rs
examples/api/src-tauri/tauri-plugin-sample/src/desktop.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use serde::de::DeserializeOwned; use tauri::{plugin::PluginApi, AppHandle, Runtime}; use crate::models::*; pub fn init<R: Runtime, C: DeserializeOwned>( app: &AppHandle<R>, _api: PluginApi<R, C>, ) -> crate::Result<Sample<R>> { Ok(Sample(app.clone())) } /// A helper class to access the sample APIs. pub struct Sample<R: Runtime>(AppHandle<R>); impl<R: Runtime> Sample<R> { pub fn ping(&self, payload: PingRequest) -> crate::Result<PingResponse> { payload.on_event.send(Event { kind: "ping".to_string(), value: payload.value.clone(), })?; Ok(PingResponse { value: payload.value, }) } }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/tauri-plugin-sample/src/models.rs
examples/api/src-tauri/tauri-plugin-sample/src/models.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use serde::{Deserialize, Serialize}; use tauri::ipc::Channel; #[derive(Serialize)] pub struct Event { pub kind: String, pub value: Option<String>, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct PingRequest { pub value: Option<String>, pub on_event: Channel<Event>, } #[derive(Debug, Clone, Default, Deserialize, Serialize)] pub struct PingResponse { pub value: Option<String>, }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/src/lib.rs
examples/api/src-tauri/src/lib.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT mod cmd; #[cfg(desktop)] mod menu_plugin; #[cfg(desktop)] mod tray; use serde::Serialize; use tauri::{ ipc::Channel, webview::{PageLoadEvent, WebviewWindowBuilder}, App, Emitter, Listener, Runtime, WebviewUrl, }; #[allow(unused)] use tauri::{Manager, RunEvent}; use tauri_plugin_sample::{PingRequest, SampleExt}; #[derive(Clone, Serialize)] struct Reply { data: String, } #[cfg(target_os = "macos")] pub struct AppMenu<R: Runtime>(pub std::sync::Mutex<Option<tauri::menu::Menu<R>>>); #[cfg(all(desktop, not(test)))] pub struct PopupMenu<R: Runtime>(tauri::menu::Menu<R>); #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { run_app(tauri::Builder::default(), |_app| {}) } pub fn run_app<R: Runtime, F: FnOnce(&App<R>) + Send + 'static>( builder: tauri::Builder<R>, setup: F, ) { #[allow(unused_mut)] let mut builder = builder .plugin( tauri_plugin_log::Builder::default() .level(log::LevelFilter::Info) .build(), ) .plugin(tauri_plugin_sample::init()) .setup(move |app| { #[cfg(all(desktop, not(test)))] { let handle = app.handle(); tray::create_tray(handle)?; handle.plugin(menu_plugin::init())?; } #[cfg(target_os = "macos")] app.manage(AppMenu::<R>(Default::default())); #[cfg(all(desktop, not(test)))] app.manage(PopupMenu( tauri::menu::MenuBuilder::new(app) .check("check", "Tauri is awesome!") .text("text", "Do something") .copy() .build()?, )); let mut window_builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::default()) .on_document_title_changed(|_window, title| { println!("document title changed: {title}"); }); #[cfg(all(desktop, not(test)))] { let app_ = app.handle().clone(); let mut created_window_count = std::sync::atomic::AtomicUsize::new(0); window_builder = window_builder .title("Tauri API Validation") .inner_size(1000., 800.) .min_inner_size(600., 400.) .menu(tauri::menu::Menu::default(app.handle())?) .on_new_window(move |url, features| { println!("new window requested: {url:?} {features:?}"); let number = created_window_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let builder = tauri::WebviewWindowBuilder::new( &app_, format!("new-{number}"), tauri::WebviewUrl::External("about:blank".parse().unwrap()), ) .window_features(features) .on_document_title_changed(|window, title| { window.set_title(&title).unwrap(); }) .title(url.as_str()); let window = builder.build().unwrap(); tauri::webview::NewWindowResponse::Create { window } }); } let webview = window_builder.build()?; #[cfg(debug_assertions)] webview.open_devtools(); let value = Some("test".to_string()); let response = app.sample().ping(PingRequest { value: value.clone(), on_event: Channel::new(|event| { println!("got channel event: {event:?}"); Ok(()) }), }); log::info!("got response: {:?}", response); // when #[cfg(desktop)], Rust will detect pattern as irrefutable #[allow(irrefutable_let_patterns)] if let Ok(res) = response { assert_eq!(res.value, value); } #[cfg(desktop)] std::thread::spawn(|| { let server = match tiny_http::Server::http("localhost:3003") { Ok(s) => s, Err(e) => { eprintln!("{e}"); std::process::exit(1); } }; loop { if let Ok(mut request) = server.recv() { let mut body = Vec::new(); let _ = request.as_reader().read_to_end(&mut body); let response = tiny_http::Response::new( tiny_http::StatusCode(200), request.headers().to_vec(), std::io::Cursor::new(body), request.body_length(), None, ); let _ = request.respond(response); } } }); setup(app); Ok(()) }) .on_page_load(|webview, payload| { if payload.event() == PageLoadEvent::Finished { let webview_ = webview.clone(); webview.listen("js-event", move |event| { println!("got js-event with message '{:?}'", event.payload()); let reply = Reply { data: "something else".to_string(), }; webview_ .emit("rust-event", Some(reply)) .expect("failed to emit"); }); } }); #[allow(unused_mut)] let mut app = builder .invoke_handler(tauri::generate_handler![ cmd::log_operation, cmd::perform_request, cmd::echo, cmd::spam, ]) .build(tauri::tauri_build_context!()) .expect("error while building tauri application"); #[cfg(target_os = "macos")] app.set_activation_policy(tauri::ActivationPolicy::Regular); app.run(move |_app_handle, _event| { #[cfg(all(desktop, not(test)))] match &_event { RunEvent::ExitRequested { api, code, .. } => { // Keep the event loop running even if all windows are closed // This allow us to catch tray icon events when there is no window // if we manually requested an exit (code is Some(_)) we will let it go through if code.is_none() { api.prevent_exit(); } } RunEvent::WindowEvent { event: tauri::WindowEvent::CloseRequested { api, .. }, label, .. } => { println!("closing window..."); // run the window destroy manually just for fun :) // usually you'd show a dialog here to ask for confirmation or whatever api.prevent_close(); _app_handle .get_webview_window(label) .unwrap() .destroy() .unwrap(); } _ => (), } }) } #[cfg(test)] mod tests { use tauri::Manager; #[test] fn run_app() { super::run_app(tauri::test::mock_builder(), |app| { let window = app.get_webview_window("main").unwrap(); std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_secs(1)); window.close().unwrap(); }); }) } }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/src/tray.rs
examples/api/src-tauri/src/tray.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg(all(desktop, not(test)))] use std::sync::atomic::{AtomicBool, Ordering}; use tauri::{ include_image, menu::{Menu, MenuItem}, tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}, Manager, Runtime, WebviewUrl, }; pub fn create_tray<R: Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<()> { let toggle_i = MenuItem::with_id(app, "toggle", "Toggle", true, None::<&str>)?; let new_window_i = MenuItem::with_id(app, "new-window", "New window", true, None::<&str>)?; let icon_i_1 = MenuItem::with_id(app, "icon-1", "Icon 1", true, None::<&str>)?; let icon_i_2 = MenuItem::with_id(app, "icon-2", "Icon 2", true, None::<&str>)?; #[cfg(target_os = "macos")] let set_title_i = MenuItem::with_id(app, "set-title", "Set Title", true, None::<&str>)?; let switch_i = MenuItem::with_id(app, "switch-menu", "Switch Menu", true, None::<&str>)?; let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; let remove_tray_i = MenuItem::with_id(app, "remove-tray", "Remove Tray icon", true, None::<&str>)?; let menu1 = Menu::with_items( app, &[ &toggle_i, &new_window_i, &icon_i_1, &icon_i_2, #[cfg(target_os = "macos")] &set_title_i, &switch_i, &quit_i, &remove_tray_i, ], )?; let menu2 = Menu::with_items( app, &[&toggle_i, &new_window_i, &switch_i, &quit_i, &remove_tray_i], )?; let is_menu1 = AtomicBool::new(true); let _ = TrayIconBuilder::with_id("tray-1") .tooltip("Tauri") .icon(app.default_window_icon().unwrap().clone()) .menu(&menu1) .show_menu_on_left_click(false) .on_menu_event(move |app, event| match event.id.as_ref() { "quit" => { app.exit(0); } "remove-tray" => { app.remove_tray_by_id("tray-1"); } "toggle" => { if let Some(window) = app.get_webview_window("main") { let new_title = if window.is_visible().unwrap_or_default() { let _ = window.hide(); "Show" } else { let _ = window.show(); let _ = window.set_focus(); "Hide" }; toggle_i.set_text(new_title).unwrap(); } } "new-window" => { let _webview = tauri::WebviewWindowBuilder::new(app, "new", WebviewUrl::App("index.html".into())) .title("Tauri") .build() .unwrap(); } #[cfg(target_os = "macos")] "set-title" => { if let Some(tray) = app.tray_by_id("tray-1") { let _ = tray.set_title(Some("Tauri")); } } i @ "icon-1" | i @ "icon-2" => { if let Some(tray) = app.tray_by_id("tray-1") { let icon = if i == "icon-1" { include_image!("../../.icons/icon.ico") } else { include_image!("../../.icons/tray_icon_with_transparency.png") }; let _ = tray.set_icon(Some(icon)); } } "switch-menu" => { let flag = is_menu1.load(Ordering::Relaxed); let (menu, tooltip) = if flag { (menu2.clone(), "Menu 2") } else { (menu1.clone(), "Tauri") }; if let Some(tray) = app.tray_by_id("tray-1") { let _ = tray.set_menu(Some(menu)); let _ = tray.set_tooltip(Some(tooltip)); } is_menu1.store(!flag, Ordering::Relaxed); } _ => {} }) .on_tray_icon_event(|tray, event| { if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event { let app = tray.app_handle(); if let Some(window) = app.get_webview_window("main") { let _ = window.unminimize(); let _ = window.show(); let _ = window.set_focus(); } } }) .build(app); Ok(()) }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/src/main.rs
examples/api/src-tauri/src/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT // Prevents additional console window on Windows in release, DO NOT REMOVE!! #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { api_lib::run(); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/src/menu_plugin.rs
examples/api/src-tauri/src/menu_plugin.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg(all(desktop, not(test)))] use tauri::{ command, plugin::{Builder, TauriPlugin}, Runtime, }; #[cfg(not(target_os = "macos"))] #[command] pub fn toggle<R: tauri::Runtime>(window: tauri::Window<R>) { if window.is_menu_visible().unwrap_or_default() { let _ = window.hide_menu(); } else { let _ = window.show_menu(); } } #[cfg(target_os = "macos")] #[command] pub fn toggle<R: tauri::Runtime>( app: tauri::AppHandle<R>, app_menu: tauri::State<'_, crate::AppMenu<R>>, ) { if let Some(menu) = app.remove_menu().unwrap() { app_menu.0.lock().unwrap().replace(menu); } else { app .set_menu(app_menu.0.lock().unwrap().clone().expect("no app menu")) .unwrap(); } } #[command] pub fn popup<R: tauri::Runtime>( window: tauri::Window<R>, popup_menu: tauri::State<'_, crate::PopupMenu<R>>, ) { window.popup_menu(&popup_menu.0).unwrap(); } pub fn init<R: Runtime>() -> TauriPlugin<R> { Builder::new("app-menu") .invoke_handler(tauri::generate_handler![ #![plugin(app_menu)] popup, toggle ]) .build() }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/api/src-tauri/src/cmd.rs
examples/api/src-tauri/src/cmd.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use serde::{Deserialize, Serialize}; use tauri::{ command, ipc::{Channel, CommandScope}, }; #[derive(Debug, Deserialize)] #[allow(unused)] pub struct RequestBody { id: i32, name: String, } #[derive(Debug, Deserialize)] pub struct LogScope { event: String, } #[command] pub fn log_operation( event: String, payload: Option<String>, command_scope: CommandScope<LogScope>, ) -> Result<(), &'static str> { if command_scope.denies().iter().any(|s| s.event == event) { Err("denied") } else if !command_scope.allows().iter().any(|s| s.event == event) { Err("not allowed") } else { log::info!("{event} {payload:?}"); Ok(()) } } #[derive(Serialize)] pub struct ApiResponse { message: String, } #[command] pub fn perform_request(endpoint: String, body: RequestBody) -> ApiResponse { println!("{endpoint} {body:?}"); ApiResponse { message: "message response".into(), } } #[command] pub fn echo(request: tauri::ipc::Request<'_>) -> tauri::ipc::Response { tauri::ipc::Response::new(request.body().clone()) } #[command] pub fn spam(channel: Channel<i32>) -> tauri::Result<()> { for i in 1..=1_000 { channel.send(i)?; } Ok(()) }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/file-associations/src-tauri/build.rs
examples/file-associations/src-tauri/build.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT fn main() { tauri_build::build() }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/file-associations/src-tauri/src/main.rs
examples/file-associations/src-tauri/src/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr( all(not(debug_assertions), target_os = "windows"), windows_subsystem = "windows" )] use std::path::PathBuf; use tauri::{AppHandle, Manager}; fn handle_file_associations(app: AppHandle, files: Vec<PathBuf>) { // -- Scope handling start -- // You can remove this block if you only want to know about the paths, but not actually "use" them in the frontend. // This requires the `fs` tauri plugin and is required to make the plugin's frontend work: // use tauri_plugin_fs::FsExt; // let fs_scope = app.fs_scope(); // This is for the `asset:` protocol to work: let asset_protocol_scope = app.asset_protocol_scope(); for file in &files { // This requires the `fs` plugin: // let _ = fs_scope.allow_file(file); // This is for the `asset:` protocol: let _ = asset_protocol_scope.allow_file(file); } // -- Scope handling end -- let files = files .into_iter() .map(|f| { let file = f.to_string_lossy().replace('\\', "\\\\"); // escape backslash format!("\"{file}\"",) // wrap in quotes for JS array }) .collect::<Vec<_>>() .join(","); tauri::WebviewWindowBuilder::new(&app, "main", Default::default()) .initialization_script(format!("window.openedFiles = [{files}]")) .build() .unwrap(); } fn main() { tauri::Builder::default() .setup(|#[allow(unused_variables)] app| { #[cfg(any(windows, target_os = "linux"))] { let mut files = Vec::new(); // NOTICE: `args` may include URL protocol (`your-app-protocol://`) // or arguments (`--`) if your app supports them. // files may also be passed as `file://path/to/file` for maybe_file in std::env::args().skip(1) { // skip flags like -f or --flag if maybe_file.starts_with('-') { continue; } // handle `file://` path urls and skip other urls if let Ok(url) = url::Url::parse(&maybe_file) { if let Ok(path) = url.to_file_path() { files.push(path); } } else { files.push(PathBuf::from(maybe_file)) } } handle_file_associations(app.handle().clone(), files); } Ok(()) }) .build(tauri::generate_context!()) .expect("error while running tauri application") .run( #[allow(unused_variables)] |app, event| { #[cfg(any(target_os = "macos", target_os = "ios"))] if let tauri::RunEvent::Opened { urls } = event { let files = urls .into_iter() .filter_map(|url| url.to_file_path().ok()) .collect::<Vec<_>>(); handle_file_associations(app.clone(), files); } }, ); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/splashscreen/main.rs
examples/splashscreen/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use tauri::{AppHandle, Manager}; #[tauri::command] fn close_splashscreen(app: AppHandle) { // Close splashscreen app .get_webview_window("splashscreen") .unwrap() .close() .unwrap(); // Show main window app.get_webview_window("main").unwrap().show().unwrap(); } fn main() { tauri::Builder::default() .menu(tauri::menu::Menu::default) .invoke_handler(tauri::generate_handler![close_splashscreen]) .run(tauri::generate_context!( "../../examples/splashscreen/tauri.conf.json" )) .expect("error while running tauri application"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/resources/src-tauri/build.rs
examples/resources/src-tauri/build.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT fn main() { tauri_build::build() }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/resources/src-tauri/src/main.rs
examples/resources/src-tauri/src/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use tauri::Manager; #[tauri::command] fn read_to_string(path: &str) -> String { std::fs::read_to_string(path).unwrap_or_default() } fn main() { tauri::Builder::default() .setup(move |app| { let path = app .path() .resolve("assets/index.js", tauri::path::BaseDirectory::Resource) .unwrap(); let content = std::fs::read_to_string(&path).unwrap(); println!("Resource `assets/index.js` path: {}", path.display()); println!("Resource `assets/index.js` content:\n{content}\n"); Ok(()) }) .invoke_handler(tauri::generate_handler![read_to_string]) .run(tauri::generate_context!()) .expect("error while running tauri application"); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/multiwindow/main.rs
examples/multiwindow/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use tauri::WebviewWindowBuilder; fn main() { tauri::Builder::default() .setup(|app| { WebviewWindowBuilder::new(app, "Third", tauri::WebviewUrl::default()) .title("Tauri - Third") .build()?; Ok(()) }) .run(generate_context()) .expect("failed to run tauri application"); } fn generate_context() -> tauri::Context { let mut context = tauri::generate_context!("../../examples/multiwindow/tauri.conf.json"); for cmd in [ "plugin:event|listen", "plugin:event|emit", "plugin:event|emit_to", "plugin:webview|create_webview_window", ] { context .runtime_authority_mut() .__allow_command(cmd.to_string(), tauri_utils::acl::ExecutionContext::Local); } context }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/examples/run-return/main.rs
examples/run-return/main.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { let app = tauri::Builder::default() .build(tauri::generate_context!( "../../examples/run-return/tauri.conf.json" )) .expect("error while building tauri application"); let exit_code = app.run_return(|_app, _event| { //println!("{:?}", _event); }); println!("I run after exit"); std::process::exit(exit_code); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/packages/cli/build.rs
packages/cli/build.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT fn main() { ::napi_build::setup(); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
tauri-apps/tauri
https://github.com/tauri-apps/tauri/blob/a03219ca196372fca542633900a5ad26d805fcf7/packages/cli/src/lib.rs
packages/cli/src/lib.rs
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT #![cfg(any(target_os = "macos", target_os = "linux", windows))] use std::sync::Arc; use napi::{ threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}, Error, Result, Status, }; #[napi_derive::napi] pub fn run( args: Vec<String>, bin_name: Option<String>, callback: Arc<ThreadsafeFunction<bool>>, ) -> Result<()> { // we need to run in a separate thread so Node.js consumers // can do work while `tauri dev` is running. std::thread::spawn(move || { let res = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { tauri_cli::try_run(args, bin_name).inspect_err(|e| eprintln!("{e:#}")) })) { Ok(t) => t, Err(_) => { return callback.call( Err(Error::new( Status::GenericFailure, "Tauri CLI unexpected panic", )), ThreadsafeFunctionCallMode::Blocking, ); } }; match res { Ok(_) => callback.call(Ok(true), ThreadsafeFunctionCallMode::Blocking), Err(e) => callback.call( Err(Error::new(Status::GenericFailure, format!("{e:#}"))), ThreadsafeFunctionCallMode::Blocking, ), } }); Ok(()) } #[napi_derive::napi] pub fn log_error(error: String) { log::error!("{}", error); }
rust
Apache-2.0
a03219ca196372fca542633900a5ad26d805fcf7
2026-01-04T15:31:58.627796Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/benchmark-core/benches/vnode.rs
tools/benchmark-core/benches/vnode.rs
use yew::prelude::*; fn main() { divan::main(); } #[function_component] fn Stuff(_: &()) -> Html { html! { <p>{"A custom component"}</p> } } #[divan::bench(sample_size = 10000000)] fn vnode_clone(bencher: divan::Bencher) { let html = html! { <div class={classes!("hello-world")}> <span>{"Hello"}</span> <strong style="color:red">{"World"}</strong> <Stuff /> <Suspense fallback={html!("Loading...")}> <Stuff /> </Suspense> </div> }; bencher.bench_local(move || { let _ = divan::black_box(html.clone()); }); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/benchmark-ssr/src/main.rs
tools/benchmark-ssr/src/main.rs
use std::collections::HashMap; use std::fs::File; use std::path::PathBuf; use std::time::{Duration, Instant}; use average::Variance; use clap::Parser; use function_router::{ServerApp, ServerAppProps}; use indicatif::{ProgressBar, ProgressStyle}; use serde::{Deserialize, Serialize}; use tabled::settings::Style; use tabled::{Table, Tabled}; use tokio::task::{spawn_local, LocalSet}; use yew::platform::time::sleep; use yew::prelude::*; #[cfg(unix)] #[global_allocator] static GLOBAL: jemallocator::Jemalloc = jemallocator::Jemalloc; #[derive(Parser)] struct Args { /// Disable terminal support. #[clap(long)] no_term: bool, /// Write the report to an output path in json format. #[clap(long)] output_path: Option<PathBuf>, /// The number of rounds to run. #[clap(long, default_value_t = 10)] rounds: usize, } fn dur_as_millis_f64(dur: Duration) -> f64 { i32::try_from(dur.as_micros()).map(f64::from).unwrap() / 1000.0 } fn bench_baseline() -> Duration { fn fib(n: u32) -> u32 { if n <= 1 { 1 } else { fib(n - 1) + fib(n - 2) } } let start_time = Instant::now(); fib(40); start_time.elapsed() } async fn bench_hello_world() -> Duration { static TOTAL: usize = 1_000_000; #[function_component] fn App() -> Html { html! {<div>{"Hello, World!"}</div>} } let start_time = Instant::now(); for _ in 0..TOTAL { yew::LocalServerRenderer::<App>::new().render().await; } start_time.elapsed() } async fn bench_router_app() -> Duration { static TOTAL: usize = 100_000; let start_time = Instant::now(); for _ in 0..TOTAL { yew::LocalServerRenderer::<ServerApp>::with_props(ServerAppProps { url: "/".into(), queries: HashMap::new(), }) .render() .await; } start_time.elapsed() } async fn bench_many_providers() -> Duration { static TOTAL: usize = 250_000; #[derive(Properties, PartialEq, Clone)] struct ProviderProps { children: Html, } #[function_component] fn Provider(props: &ProviderProps) -> Html { let ProviderProps { children } = props.clone(); children } #[function_component] fn App() -> Html { // Let's make 10 providers. html! { <Provider> <Provider> <Provider> <Provider> <Provider> <Provider> <Provider> <Provider> <Provider> <Provider>{"Hello, World!"}</Provider> </Provider> </Provider> </Provider> </Provider> </Provider> </Provider> </Provider> </Provider> </Provider> } } let start_time = Instant::now(); for _ in 0..TOTAL { yew::LocalServerRenderer::<App>::new().render().await; } start_time.elapsed() } async fn bench_concurrent_task() -> Duration { static TOTAL: usize = 100; let start_time = Instant::now(); #[function_component] fn Comp() -> HtmlResult { let _state = use_prepared_state!((), async move |_| -> usize { sleep(Duration::from_secs(1)).await; 42 })?; Ok(Html::default()) } #[function_component] fn Parent() -> Html { html! { <> <Comp /> <Comp /> <Comp /> <Comp /> </> } } #[function_component] fn App() -> Html { html! { <Suspense fallback={Html::default()}> <Parent /> <Comp /> <Comp /> <Comp /> <Comp /> </Suspense> } } let mut tasks = Vec::new(); for _ in 0..TOTAL { tasks.push(spawn_local(async { yew::LocalServerRenderer::<App>::new().render().await; })); } for task in tasks { task.await.expect("failed to finish task"); } start_time.elapsed() } #[derive(Debug, Tabled, Serialize, Deserialize)] struct Statistics { #[tabled(rename = "Benchmark")] name: String, #[tabled(rename = "Round")] round: String, #[tabled(rename = "Min (ms)")] min: String, #[tabled(rename = "Max (ms)")] max: String, #[tabled(rename = "Mean (ms)")] mean: String, #[tabled(rename = "Standard Deviation")] std_dev: String, } impl Statistics { fn from_results<S>(name: S, round: usize, mut results: Vec<Duration>) -> Self where S: Into<String>, { let name = name.into(); results.sort(); let var: Variance = results.iter().cloned().map(dur_as_millis_f64).collect(); Self { name, round: round.to_string(), min: format!("{:.3}", dur_as_millis_f64(results[0])), max: format!( "{:.3}", dur_as_millis_f64(*results.last().expect("array is empty?")) ), std_dev: format!("{:.3}", var.sample_variance().sqrt()), mean: format!("{:.3}", var.mean()), } } } fn create_progress(tests: usize, rounds: usize) -> ProgressBar { let bar = ProgressBar::new((tests * rounds) as u64); // Progress Bar needs to be updated in a different thread. { let bar = bar.downgrade(); std::thread::spawn(move || { while let Some(bar) = bar.upgrade() { bar.tick(); std::thread::sleep(Duration::from_millis(100)); } }); } bar.set_style( ProgressStyle::default_bar() .template(&format!( "{{spinner:.green}} {{prefix}} [{{elapsed_precise}}] [{{bar:40.cyan/blue}}] round \ {{msg}}/{rounds}", )) .expect("failed to parse template") // .tick_chars("-\\|/") .progress_chars("=>-"), ); bar } #[tokio::main] async fn main() { let local_set = LocalSet::new(); let args = Args::parse(); // Tests in each round. static TESTS: usize = 5; let mut baseline_results = Vec::with_capacity(args.rounds); let mut hello_world_results = Vec::with_capacity(args.rounds); let mut function_router_results = Vec::with_capacity(args.rounds); let mut concurrent_tasks_results = Vec::with_capacity(args.rounds); let mut many_provider_results = Vec::with_capacity(args.rounds); let bar = (!args.no_term).then(|| create_progress(TESTS, args.rounds)); local_set .run_until(async { for i in 0..=args.rounds { if let Some(ref bar) = bar { bar.set_message(i.to_string()); if i == 0 { bar.set_prefix("Warming up"); } else { bar.set_prefix("Running "); } } let dur = bench_baseline(); if i > 0 { baseline_results.push(dur); if let Some(ref bar) = bar { bar.inc(1); } } let dur = bench_hello_world().await; if i > 0 { hello_world_results.push(dur); if let Some(ref bar) = bar { bar.inc(1); } } let dur = bench_router_app().await; if i > 0 { function_router_results.push(dur); if let Some(ref bar) = bar { bar.inc(1); } } let dur = bench_concurrent_task().await; if i > 0 { concurrent_tasks_results.push(dur); if let Some(ref bar) = bar { bar.inc(1); } } let dur = bench_many_providers().await; if i > 0 { many_provider_results.push(dur); if let Some(ref bar) = bar { bar.inc(1); } } } }) .await; if let Some(ref bar) = bar { bar.finish_and_clear(); } drop(bar); let output = [ Statistics::from_results("Baseline", args.rounds, baseline_results), Statistics::from_results("Hello World", args.rounds, hello_world_results), Statistics::from_results("Function Router", args.rounds, function_router_results), Statistics::from_results("Concurrent Task", args.rounds, concurrent_tasks_results), Statistics::from_results("Many Providers", args.rounds, many_provider_results), ]; println!("{}", Table::new(&output).with(Style::rounded())); if let Some(ref p) = args.output_path { let mut f = File::create(p).expect("failed to write output."); serde_json::to_writer_pretty(&mut f, &output).expect("failed to write output."); println!(); println!("Result has been written to: {}", p.display()); } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/process-benchmark-results/src/main.rs
tools/process-benchmark-results/src/main.rs
use std::collections::HashMap; use std::io; use std::io::{Read, Write}; use anyhow::Result; use serde::{Deserialize, Serialize}; use serde_json::Value; #[derive(Serialize)] struct GhActionBenchmark { name: String, unit: String, value: Value, } // from https://github.com/krausest/js-framework-benchmark/blob/master/webdriver-ts/src/writeResults.ts#L67 function createResultFile #[derive(Deserialize)] struct ResultData { median: Value, // some keys missing } #[derive(Deserialize)] struct JsKrauseBenchmarkResult<'r> { framework: &'r str, benchmark: &'r str, r#type: &'r str, values: HashMap<&'r str, ResultData>, } fn transform_results(mut result: JsKrauseBenchmarkResult<'_>) -> GhActionBenchmark { let key = if result.r#type == "cpu" { "total" } else { "DEFAULT" }; let values = result.values.remove(key).unwrap_or_else(|| { panic!( "Expect benchmark data to be present for type {}. Found keys: {:?}, expected {key:?}", result.r#type, result.values.keys().cloned().collect::<Vec<_>>(), ) }); assert!( values.median.is_number(), "expected a numerical benchmark value" ); GhActionBenchmark { name: format!("{} {}", result.framework, result.benchmark).replace('"', ""), unit: String::default(), value: values.median, } } fn main() -> Result<()> { let mut buffer = "".to_string(); io::stdin().read_to_string(&mut buffer)?; let input_json: Vec<_> = serde_json::from_str(buffer.as_str())?; let transformed_benchmarks: Vec<GhActionBenchmark> = input_json.into_iter().map(transform_results).collect(); let output = serde_json::to_string(&transformed_benchmarks)?; io::stdout().write_all(output.as_bytes())?; Ok(()) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/benchmark-hooks/src/lib.rs
tools/benchmark-hooks/src/lib.rs
use std::cmp::min; use std::ops::Deref; use std::rc::Rc; use rand::prelude::*; use wasm_bindgen::prelude::*; use web_sys::window; use yew::prelude::*; static ADJECTIVES: &[&str] = &[ "pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy", ]; static COLOURS: &[&str] = &[ "red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange", ]; static NOUNS: &[&str] = &[ "table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard", ]; #[derive(Clone, PartialEq)] struct RowData { id: usize, label: String, } impl RowData { fn new(id: usize, rng: &mut SmallRng) -> Self { let adjective = *ADJECTIVES.choose(rng).unwrap(); let colour = *COLOURS.choose(rng).unwrap(); let noun = *NOUNS.choose(rng).unwrap(); let label = [adjective, colour, noun].join(" "); Self { id, label } } } enum AppStateAction { Run(usize), Add(usize), Update(usize), Clear, Swap, Remove(usize), Select(usize), } #[derive(Clone)] struct AppState { next_id: usize, selected_id: Option<usize>, rows: Vec<RowData>, rng: SmallRng, } impl Default for AppState { fn default() -> Self { Self { rows: Vec::new(), next_id: 1, selected_id: None, rng: SmallRng::from_os_rng(), } } } impl Reducible for AppState { type Action = AppStateAction; fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> { let mut new_state = self.deref().clone(); match action { AppStateAction::Run(amount) => { let rng = &mut new_state.rng; let next_id = new_state.next_id; let update_amount = min(amount, new_state.rows.len()); for index in 0..update_amount { new_state.rows[index] = RowData::new(next_id + index, rng); } new_state.rows.extend( (update_amount..amount).map(|index| RowData::new(next_id + index, rng)), ); new_state.next_id += amount; } AppStateAction::Add(amount) => { let rng = &mut new_state.rng; let next_id = new_state.next_id; new_state .rows .extend((0..amount).map(|index| RowData::new(next_id + index, rng))); new_state.next_id += amount; } AppStateAction::Update(step) => { for index in (0..new_state.rows.len()).step_by(step) { new_state.rows[index].label += " !!!"; } } AppStateAction::Clear => { new_state.rows.clear(); } AppStateAction::Swap => { if new_state.rows.len() > 998 { new_state.rows.swap(1, 998); } } AppStateAction::Remove(id) => { if let Some(index) = new_state.rows.iter().position(|row| row.id == id) { new_state.rows.remove(index); } } AppStateAction::Select(id) => { new_state.selected_id = Some(id); } }; new_state.into() } } #[function_component(App)] fn app() -> Html { let state = use_reducer(AppState::default); let selected_id = state.deref().selected_id; let rows = state.deref().rows.clone(); let on_run = { let state = state.clone(); Callback::from(move |amount| state.dispatch(AppStateAction::Run(amount))) }; let on_add = { let state = state.clone(); Callback::from(move |amount| state.dispatch(AppStateAction::Add(amount))) }; let on_update = { let state = state.clone(); Callback::from(move |amount| state.dispatch(AppStateAction::Update(amount))) }; let on_clear = { let state = state.clone(); Callback::from(move |_| state.dispatch(AppStateAction::Clear)) }; let on_swap = { let state = state.clone(); Callback::from(move |_| state.dispatch(AppStateAction::Swap)) }; let on_select = { let state = state.clone(); Callback::from(move |id| state.dispatch(AppStateAction::Select(id))) }; let on_remove = Callback::from(move |id| state.dispatch(AppStateAction::Remove(id))); let rows: Html = rows .into_iter() .map(move |row| { let id = row.id; html! { <Row key={id} data={row} selected={selected_id == Some(id)} on_select={on_select.reform(move |_| id)} on_remove={on_remove.reform(move |_| id)} /> } }) .collect(); html! { <div class="container"> <Jumbotron {on_run} {on_add} {on_update} {on_clear} {on_swap} /> <table class="table table-hover table-striped test-data"> <tbody id="tbody"> { rows } </tbody> </table> <span class="preloadicon glyphicon glyphicon-remove" aria-hidden="true"></span> </div> } } #[derive(Properties, Clone, PartialEq)] pub struct JumbotronProps { pub on_run: Callback<usize>, pub on_add: Callback<usize>, pub on_update: Callback<usize>, pub on_clear: Callback<()>, pub on_swap: Callback<()>, } #[function_component(Jumbotron)] fn jumbotron(props: &JumbotronProps) -> Html { html! { <div class="jumbotron"> <div class="row"> <div class="col-md-6"> <h1>{ "Yew-Hooks" }</h1> </div> <div class="col-md-6"> <div class="row"> <div class="col-sm-6 smallpad"> <button type="button" id="run" class="btn btn-primary btn-block" onclick={props.on_run.reform(|_| 1_000)}>{ "Create 1,000 rows" }</button> </div> <div class="col-sm-6 smallpad"> <button type="button" class="btn btn-primary btn-block" onclick={props.on_run.reform(|_| 10_000)} id="runlots">{ "Create 10,000 rows" }</button> </div> <div class="col-sm-6 smallpad"> <button type="button" class="btn btn-primary btn-block" onclick={props.on_add.reform(|_| 1_000)} id="add">{ "Append 1,000 rows" }</button> </div> <div class="col-sm-6 smallpad"> <button type="button" class="btn btn-primary btn-block" onclick={props.on_update.reform(|_| 10)} id="update">{ "Update every 10th row" }</button> </div> <div class="col-sm-6 smallpad"> <button type="button" class="btn btn-primary btn-block" onclick={props.on_clear.reform(|_| ())} id="clear">{ "Clear" }</button> </div> <div class="col-sm-6 smallpad"> <button type="button" class="btn btn-primary btn-block" onclick={props.on_swap.reform(|_| ())} id="swaprows">{ "Swap Rows" }</button> </div> </div> </div> </div> </div> } } #[derive(Properties, Clone, PartialEq)] struct RowProps { on_select: Callback<MouseEvent>, on_remove: Callback<MouseEvent>, selected: bool, data: RowData, } #[function_component(Row)] fn row(props: &RowProps) -> Html { html! { <tr class={if props.selected { "danger" } else { "" }}> <td class="col-md-1">{ props.data.id }</td> <td class="col-md-4" onclick={props.on_select.clone()}> <a class="lbl">{ props.data.label.clone() }</a> </td> <td class="col-md-1"> <a class="remove" onclick={props.on_remove.clone()}> <span class="glyphicon glyphicon-remove remove" aria-hidden="true"></span> </a> </td> <td class="col-md-6"></td> </tr> } } #[wasm_bindgen(start)] pub fn start() { let document = window().unwrap().document().unwrap(); let mount_el = document.query_selector("#main").unwrap().unwrap(); yew::Renderer::<App>::with_root(mount_el).render(); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/benchmark-struct/src/lib.rs
tools/benchmark-struct/src/lib.rs
use std::cmp::min; use rand::prelude::*; use wasm_bindgen::prelude::*; use web_sys::window; use yew::prelude::*; static ADJECTIVES: &[&str] = &[ "pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy", ]; static COLOURS: &[&str] = &[ "red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange", ]; static NOUNS: &[&str] = &[ "table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard", ]; #[derive(Clone, PartialEq)] struct RowData { id: usize, label: String, } impl RowData { fn new(id: usize, rng: &mut SmallRng) -> Self { let adjective = *ADJECTIVES.choose(rng).unwrap(); let colour = *COLOURS.choose(rng).unwrap(); let noun = *NOUNS.choose(rng).unwrap(); let label = [adjective, colour, noun].join(" "); Self { id, label } } } struct App { rows: Vec<RowData>, next_id: usize, selected_id: Option<usize>, rng: SmallRng, on_select: Callback<usize>, on_remove: Callback<usize>, } enum Msg { Run(usize), Add(usize), Update(usize), Clear, Swap, Remove(usize), Select(usize), } impl Component for App { type Message = Msg; type Properties = (); fn create(ctx: &Context<Self>) -> Self { App { rows: Vec::new(), next_id: 1, selected_id: None, rng: SmallRng::from_os_rng(), on_select: ctx.link().callback(Msg::Select), on_remove: ctx.link().callback(Msg::Remove), } } fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool { match msg { Msg::Run(amount) => { let rng = &mut self.rng; let next_id = self.next_id; let update_amount = min(amount, self.rows.len()); for index in 0..update_amount { self.rows[index] = RowData::new(next_id + index, rng); } self.rows.extend( (update_amount..amount).map(|index| RowData::new(next_id + index, rng)), ); self.next_id += amount; } Msg::Add(amount) => { let rng = &mut self.rng; let next_id = self.next_id; self.rows .extend((0..amount).map(|index| RowData::new(next_id + index, rng))); self.next_id += amount; } Msg::Update(step) => { for index in (0..self.rows.len()).step_by(step) { self.rows[index].label += " !!!"; } } Msg::Clear => { self.rows.clear(); } Msg::Swap => { if self.rows.len() > 998 { self.rows.swap(1, 998); } } Msg::Remove(id) => { if let Some(index) = self.rows.iter().position(|row| row.id == id) { self.rows.remove(index); } } Msg::Select(id) => { self.selected_id = Some(id); } } true } fn view(&self, ctx: &Context<Self>) -> Html { let rows: Html = self .rows .iter() .map(|row| { html! { <Row key={row.id} data={row.clone()} selected={self.selected_id == Some(row.id)} on_select={self.on_select.clone()} on_remove={self.on_remove.clone()} /> } }) .collect(); html! { <div class="container"> <Jumbotron on_run={ctx.link().callback(Msg::Run)} on_add={ctx.link().callback(Msg::Add)} on_update={ctx.link().callback(Msg::Update)} on_clear={ctx.link().callback(|_| Msg::Clear)} on_swap={ctx.link().callback(|_| Msg::Swap)} /> <table class="table table-hover table-striped test-data"> <tbody id="tbody"> { rows } </tbody> </table> <span class="preloadicon glyphicon glyphicon-remove" aria-hidden="true"></span> </div> } } } #[derive(Properties, Clone, PartialEq)] pub struct JumbotronProps { pub on_run: Callback<usize>, pub on_add: Callback<usize>, pub on_update: Callback<usize>, pub on_clear: Callback<()>, pub on_swap: Callback<()>, } pub struct Jumbotron {} impl Component for Jumbotron { type Message = (); type Properties = JumbotronProps; fn create(_ctx: &Context<Self>) -> Self { Self {} } fn view(&self, ctx: &Context<Self>) -> Html { html! { <div class="jumbotron"> <div class="row"> <div class="col-md-6"> <h1>{ "Yew" }</h1> </div> <div class="col-md-6"> <div class="row"> <div class="col-sm-6 smallpad"> <button type="button" id="run" class="btn btn-primary btn-block" onclick={ctx.props().on_run.reform(|_| 1_000)}>{ "Create 1,000 rows" }</button> </div> <div class="col-sm-6 smallpad"> <button type="button" class="btn btn-primary btn-block" onclick={ctx.props().on_run.reform(|_| 10_000)} id="runlots">{ "Create 10,000 rows" }</button> </div> <div class="col-sm-6 smallpad"> <button type="button" class="btn btn-primary btn-block" onclick={ctx.props().on_add.reform(|_| 1_000)} id="add">{ "Append 1,000 rows" }</button> </div> <div class="col-sm-6 smallpad"> <button type="button" class="btn btn-primary btn-block" onclick={ctx.props().on_update.reform(|_| 10)} id="update">{ "Update every 10th row" }</button> </div> <div class="col-sm-6 smallpad"> <button type="button" class="btn btn-primary btn-block" onclick={ctx.props().on_clear.reform(|_| ())} id="clear">{ "Clear" }</button> </div> <div class="col-sm-6 smallpad"> <button type="button" class="btn btn-primary btn-block" onclick={ctx.props().on_swap.reform(|_| ())} id="swaprows">{ "Swap Rows" }</button> </div> </div> </div> </div> </div> } } } #[derive(Properties, Clone, PartialEq)] struct RowProps { on_select: Callback<usize>, on_remove: Callback<usize>, selected: bool, data: RowData, } struct Row { on_select: Callback<MouseEvent>, on_remove: Callback<MouseEvent>, } impl Component for Row { type Message = (); type Properties = RowProps; fn create(ctx: &Context<Self>) -> Self { let id = ctx.props().data.id; Self { on_select: ctx.props().on_select.reform(move |_| id), on_remove: ctx.props().on_remove.reform(move |_| id), } } fn changed(&mut self, ctx: &Context<Self>, _: &Self::Properties) -> bool { let id = ctx.props().data.id; self.on_select = ctx.props().on_select.reform(move |_| id); self.on_remove = ctx.props().on_remove.reform(move |_| id); true } fn view(&self, ctx: &Context<Self>) -> Html { html! { <tr class={if ctx.props().selected { "danger" } else { "" }}> <td class="col-md-1">{ ctx.props().data.id }</td> <td class="col-md-4" onclick={self.on_select.clone()}> <a class="lbl">{ ctx.props().data.label.clone() }</a> </td> <td class="col-md-1"> <a class="remove" onclick={self.on_remove.clone()}> <span class="glyphicon glyphicon-remove remove" aria-hidden="true"></span> </a> </td> <td class="col-md-6"></td> </tr> } } } #[wasm_bindgen(start)] pub fn start() { let document = window().unwrap().document().unwrap(); let mount_el = document.query_selector("#main").unwrap().unwrap(); yew::Renderer::<App>::with_root(mount_el).render(); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/website-test/build.rs
tools/website-test/build.rs
use std::collections::HashMap; use std::error::Error; use std::fmt::Write; use std::fs::File; use std::io::{self, BufRead, BufReader, ErrorKind, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use std::process::ExitCode; use std::{env, fs}; use glob::glob; type Result<T = ()> = core::result::Result<T, Box<dyn Error + 'static>>; macro_rules! e { ($($fmt:tt),* $(,)?) => { return Err(format!($($fmt),*).into()) }; } macro_rules! assert { ($condition:expr, $($fmt:tt),* $(,)?) => { if !$condition { e!($($fmt),*) } }; } #[derive(Debug, Default)] struct Level { nested: HashMap<String, Level>, files: Vec<PathBuf>, } fn should_combine_code_blocks(path: &Path) -> io::Result<bool> { const FLAG: &[u8] = b"<!-- COMBINE CODE BLOCKS -->"; let mut file = File::open(path)?; match file.seek(SeekFrom::End(-32)) { Ok(_) => (), Err(e) if e.kind() == ErrorKind::InvalidInput => return Ok(false), Err(e) => return Err(e), } let mut buf = [0u8; 32]; file.read_exact(&mut buf)?; Ok(buf.trim_ascii_end().ends_with(FLAG)) } fn apply_diff(src: &mut String, preamble: &str, added: &str, removed: &str) -> Result { assert!( !preamble.is_empty() || !removed.is_empty(), "Failure on applying a diff: \nNo preamble or text to remove provided, unable to find \ location to insert:\n{added}\nIn the following text:\n{src}", ); let mut matches = src .match_indices(preamble) .filter_map(|(chunk_start, chunk)| { let removed_start = chunk_start + chunk.len(); let removed_end = removed_start + removed.len(); src.get(removed_start..removed_end) .eq(&Some(removed)) .then_some((removed_start, removed_end)) }); let Some((removed_start, removed_end)) = matches.next() else { e!( "Failure on applying a diff: \nCouldn't find the following preamble:\n{preamble}\nIn \ the following text:\n{src}\nWhile trying to remove the following \ text:\n{removed}\nAnd add the following:\n{added}" ) }; assert!( matches.next().is_none(), "Failure on applying a diff: \nAmbiguous preamble:\n{preamble}\nIn the following \ text:\n{src}\nWhile trying to remove the following text:\n{removed}\nAnd add the \ following:\n{added}" ); src.replace_range(removed_start..removed_end, added); Ok(()) } fn combined_code_blocks(path: &Path) -> Result<String> { let file = BufReader::new(File::open(path)?); let mut res = String::new(); let mut err = Ok(()); let mut lines = file .lines() .filter_map(|i| i.map_err(|e| err = Err(e)).ok()); while let Some(line) = lines.next() { if !line.starts_with("```rust") { continue; } let mut preamble = String::new(); let mut added = String::new(); let mut removed = String::new(); let mut diff_applied = false; for line in &mut lines { if line.starts_with("```") { if !added.is_empty() || !removed.is_empty() { apply_diff(&mut res, &preamble, &added, &removed)?; } else if !diff_applied { // if no diff markers were found, just add the contents res += &preamble; } break; } else if let Some(line) = line.strip_prefix('+') { if line.starts_with(char::is_whitespace) { added += " "; } added += line; added += "\n"; } else if let Some(line) = line.strip_prefix('-') { if line.starts_with(char::is_whitespace) { removed += " "; } removed += line; removed += "\n"; } else if line.trim_ascii() == "// ..." { // disregard the preamble preamble.clear(); } else { if !added.is_empty() || !removed.is_empty() { diff_applied = true; apply_diff(&mut res, &preamble, &added, &removed)?; preamble += &added; added.clear(); removed.clear(); } preamble += &line; preamble += "\n"; } } } Ok(res) } impl Level { fn insert(&mut self, path: PathBuf, rel: &[&str]) { if rel.len() == 1 { self.files.push(path); } else { let nested = self.nested.entry(rel[0].to_string()).or_default(); nested.insert(path, &rel[1..]); } } fn to_contents(&self) -> Result<String> { let mut dst = String::new(); self.write_inner(&mut dst, 0)?; Ok(dst) } fn write_into(&self, dst: &mut String, name: &str, level: usize) -> Result { self.write_space(dst, level); let name = name.replace(['-', '.'], "_"); writeln!(dst, "pub mod {name} {{")?; self.write_inner(dst, level + 1)?; self.write_space(dst, level); writeln!(dst, "}}")?; Ok(()) } fn write_inner(&self, dst: &mut String, level: usize) -> Result { for (name, nested) in &self.nested { nested.write_into(dst, name, level)?; } for file in &self.files { let stem = file .file_stem() .ok_or_else(|| format!("no filename in path {file:?}"))? .to_str() .ok_or_else(|| format!("non-UTF8 path: {file:?}"))? .replace('-', "_"); if should_combine_code_blocks(file)? { let res = combined_code_blocks(file)?; self.write_space(dst, level); writeln!(dst, "/// ```rust, no_run")?; for line in res.lines() { self.write_space(dst, level); writeln!(dst, "/// {line}")?; } self.write_space(dst, level); writeln!(dst, "/// ```")?; } else { self.write_space(dst, level); writeln!(dst, "#[doc = include_str!(r\"{}\")]", file.display())?; } self.write_space(dst, level); writeln!(dst, "pub fn {stem}_md() {{}}")?; } Ok(()) } fn write_space(&self, dst: &mut String, level: usize) { for _ in 0..level { dst.push_str(" "); } } } fn inner_main() -> Result { let home = env::var("CARGO_MANIFEST_DIR")?; let pattern = format!("{home}/../../website/docs/**/*.md*"); let base = format!("{home}/../../website"); let base = Path::new(&base).canonicalize()?; let dir_pattern = format!("{home}/../../website/docs/**"); for dir in glob(&dir_pattern)? { println!("cargo:rerun-if-changed={}", dir?.display()); } let mut level = Level::default(); for entry in glob(&pattern)? { let path = entry?.canonicalize()?; println!("cargo:rerun-if-changed={}", path.display()); let rel = path.strip_prefix(&base)?; let mut parts = vec![]; for part in rel { parts.push( part.to_str() .ok_or_else(|| format!("Non-UTF8 path: {rel:?}"))?, ); } level.insert(path.clone(), &parts[..]); } let out = format!("{}/website_tests.rs", env::var("OUT_DIR")?); fs::write(out, level.to_contents()?)?; Ok(()) } fn main() -> ExitCode { match inner_main() { Ok(_) => ExitCode::SUCCESS, Err(e) => { eprintln!("{e}"); ExitCode::FAILURE } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/website-test/src/lib.rs
tools/website-test/src/lib.rs
include!(concat!(env!("OUT_DIR"), "/website_tests.rs"));
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/lib.rs
tools/changelog/src/lib.rs
mod cli; pub mod create_log_line; pub mod create_log_lines; pub mod get_latest_version; pub mod github_fetch; pub mod github_issue_labels_fetcher; pub mod github_user_fetcher; pub mod log_line; pub mod new_version_level; pub mod stdout_tag_description_changelog; pub mod write_changelog_file; pub mod write_log_lines; pub mod write_version_changelog; pub mod yew_package; pub use cli::Cli;
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/create_log_line.rs
tools/changelog/src/create_log_line.rs
use std::sync::Mutex; use anyhow::{anyhow, Context, Result}; use git2::{Error, Oid, Repository}; use once_cell::sync::Lazy; use regex::Regex; use crate::github_issue_labels_fetcher::GitHubIssueLabelsFetcher; use crate::github_user_fetcher::GitHubUsersFetcher; use crate::log_line::LogLine; static REGEX_FOR_ISSUE_ID_CAPTURE: Lazy<Regex> = Lazy::new(|| Regex::new(r"\s*\(#(\d+)\)").unwrap()); static GITHUB_ISSUE_LABELS_FETCHER: Lazy<Mutex<GitHubIssueLabelsFetcher>> = Lazy::new(Default::default); pub fn create_log_line( repo: &Repository, package_labels: &'static [&'static str], oid: Result<Oid, Error>, token: Option<String>, user_fetcher: &mut GitHubUsersFetcher, ) -> Result<Option<LogLine>> { println!("Commit oid: {oid:?}"); let oid = oid?; let commit = repo.find_commit(oid)?; let commit_first_line = commit .message() .context("Invalid UTF-8 in commit message")? .lines() .next() .context("Missing commit message")? .to_string(); let author = commit.author(); let author_name = author.name().unwrap_or("Unknown"); let author_id = user_fetcher .fetch_user_by_commit_author(author_name, commit.id().to_string(), token.clone()) .context("Missing author's GitHub ID")?; let email = author.email().context("Missing author's email")?; if email.contains("dependabot") { println!("email contains dependabot"); return Ok(None); } if email.contains("github-action") { println!("email contains github-action"); return Ok(None); } let mb_captures = REGEX_FOR_ISSUE_ID_CAPTURE .captures_iter(&commit_first_line) .last(); let captures = match mb_captures { Some(some) => some, None => { eprintln!("Missing issue for commit: {oid}"); return Ok(None); } }; let match_to_be_stripped = captures.get(0).ok_or_else(|| { anyhow!("Failed to capture first group - issue part of the message like \" (#2263)\"") })?; let mut message = commit_first_line.clone(); message.replace_range(match_to_be_stripped.range(), ""); let issue_id = captures .get(1) .ok_or_else(|| anyhow!("Failed to capture second group - issue id like \"2263\""))? .as_str() .to_string(); let issue_labels = GITHUB_ISSUE_LABELS_FETCHER .lock() .map_err(|err| anyhow!("Failed to lock GITHUB_ISSUE_LABELS_FETCHER: {err}"))? .fetch_issue_labels(issue_id.clone(), token) .with_context(|| format!("Could not find GitHub labels for issue: {issue_id}"))?; let is_issue_for_this_package = issue_labels .iter() .any(|label| package_labels.contains(&label.as_str())); if !is_issue_for_this_package { println!("Issue {issue_id} is not for {package_labels:?} packages"); let leftovers = issue_labels.iter().filter(|label| { !(label.starts_with("A-") || *label == "documentation" || *label == "meta") }); let count = leftovers.count(); if count > 0 { println!("Potentially invalidly labeled issue: {issue_id}. Neither A-* (area), documentation nor meta labels found. \ inspect/re-tag at https://github.com/yewstack/yew/issues/{issue_id}"); } return Ok(None); } let is_breaking_change = issue_labels .iter() .any(|label| label.to_lowercase().contains("breaking change")); let log_line = LogLine { message, user: author_name.to_string(), user_id: author_id.to_string(), issue_id, is_breaking_change, }; println!("{log_line:?}"); Ok(Some(log_line)) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/write_version_changelog.rs
tools/changelog/src/write_version_changelog.rs
use std::io::Write; use anyhow::Result; use semver::Version; use crate::yew_package::YewPackage; pub fn write_changelog_file( fixes_logs: &[u8], features_logs: &[u8], breaking_changes_logs: &[u8], package: YewPackage, next_version: Version, ) -> Result<Vec<u8>> { let mut version_only_changelog = Vec::default(); writeln!(version_only_changelog, "# Changelog")?; writeln!(version_only_changelog)?; writeln!( version_only_changelog, "## ✨ {package} **{next_version}** *({release_date})* Changelog", next_version = next_version, package = package, release_date = chrono::Utc::now().format("%Y-%m-%d") )?; writeln!(version_only_changelog)?; if fixes_logs.is_empty() && features_logs.is_empty() && breaking_changes_logs.is_empty() { writeln!(version_only_changelog, "No changes")?; writeln!(version_only_changelog)?; } if !fixes_logs.is_empty() { writeln!(version_only_changelog, "### 🛠 Fixes")?; writeln!(version_only_changelog)?; version_only_changelog.extend(fixes_logs); writeln!(version_only_changelog)?; } if !features_logs.is_empty() { writeln!(version_only_changelog, "### ⚡️ Features")?; writeln!(version_only_changelog)?; version_only_changelog.extend(features_logs); writeln!(version_only_changelog)?; } if !breaking_changes_logs.is_empty() { writeln!(version_only_changelog, "### 🚨 Breaking changes")?; writeln!(version_only_changelog)?; version_only_changelog.extend(breaking_changes_logs); writeln!(version_only_changelog)?; } Ok(version_only_changelog) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/cli.rs
tools/changelog/src/cli.rs
use anyhow::{bail, Result}; use clap::Parser; use semver::Version; use crate::create_log_lines::create_log_lines; use crate::get_latest_version::get_latest_version; use crate::new_version_level::NewVersionLevel; use crate::stdout_tag_description_changelog::stdout_tag_description_changelog; use crate::write_changelog_file::write_changelog; use crate::write_log_lines::write_log_lines; use crate::write_version_changelog::write_changelog_file; use crate::yew_package::YewPackage; #[derive(Parser)] pub struct Cli { /// package to generate changelog for pub package: YewPackage, /// package to generate changelog for pub new_version_level: NewVersionLevel, /// From ref. (ex. commit hash or for tags "refs/tags/yew-v0.19.3") overrides version level arg pub from: Option<String>, /// To commit. (ex. commit hash or for tags "refs/tags/yew-v0.19.3") #[clap(short = 'r', long, default_value = "HEAD")] pub to: String, /// Path to changelog file #[clap(short = 'f', long, default_value = "../CHANGELOG.md")] pub changelog_path: String, /// Skip writing changelog file #[clap(short, long)] pub skip_file_write: bool, /// Skip getting the next version #[clap(short = 'b', long)] pub skip_get_bump_version: bool, /// Github token #[clap(short = 't', long)] pub token: Option<String>, } impl Cli { pub fn run(self) -> Result<()> { let Cli { package, from, to, changelog_path, skip_file_write, new_version_level, skip_get_bump_version, token, } = self; let package_labels = package.as_labels(); // set up versions and from ref let (from_ref, next_version) = if skip_get_bump_version { let from_ref = match from { Some(some) => some, None => bail!("from required when skip_get_bump_version is true"), }; let version = Version::parse("0.0.0")?; (from_ref, version) } else { let latest_version = get_latest_version(&package)?; let next_version = new_version_level.bump(latest_version.clone()); let from_ref = match from { Some(some) => some, None => format!("refs/tags/{package}-v{latest_version}"), }; (from_ref, next_version) }; // walk over each commit find text, user, issue let log_lines = create_log_lines(from_ref, to, package_labels, token)?; // categorize logs let (breaking_changes, filtered_log_lines): (Vec<_>, Vec<_>) = log_lines .into_iter() .partition(|log_line| log_line.is_breaking_change); let (fixes, features): (Vec<_>, Vec<_>) = filtered_log_lines .into_iter() .partition(|filtered_log_line| { filtered_log_line.message.to_lowercase().contains("fix") }); // create displayable log lines let fixes_logs = write_log_lines(fixes)?; let features_logs = write_log_lines(features)?; let breaking_changes_logs = write_log_lines(breaking_changes)?; if !skip_file_write { // create version changelog let version_changelog = write_changelog_file( &fixes_logs, &features_logs, &breaking_changes_logs, package, next_version, )?; // write changelog write_changelog(&changelog_path, &version_changelog)?; } // stdout changelog meant for tag description stdout_tag_description_changelog(&fixes_logs, &features_logs, &breaking_changes_logs)?; Ok(()) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/github_issue_labels_fetcher.rs
tools/changelog/src/github_issue_labels_fetcher.rs
use std::collections::HashMap; use anyhow::Result; use serde::Deserialize; use super::github_fetch::github_fetch; #[derive(Deserialize, Debug)] pub struct BodyListItem { name: String, } #[derive(Debug, Default)] pub struct GitHubIssueLabelsFetcher { cache: HashMap<String, Option<Vec<String>>>, } impl GitHubIssueLabelsFetcher { pub fn fetch_issue_labels( &mut self, issue: String, token: Option<String>, ) -> Option<Vec<String>> { self.cache .entry(issue.clone()) .or_insert_with(|| match Self::inner_fetch(&issue, token) { Ok(labels) => labels, Err(err) => { eprintln!("fetch_issue_labels Error: {err}"); None } }) .clone() } fn inner_fetch(q: &str, token: Option<String>) -> Result<Option<Vec<String>>> { let url = format!("https://api.github.com/repos/yewstack/yew/issues/{q}/labels"); let body: Vec<BodyListItem> = github_fetch(&url, token)?; let label_names: Vec<String> = body.into_iter().map(|label| label.name).collect(); Ok(Some(label_names)) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/stdout_tag_description_changelog.rs
tools/changelog/src/stdout_tag_description_changelog.rs
use std::io::{stdout, Write}; use anyhow::Result; pub fn stdout_tag_description_changelog( fixes_logs: &[u8], features_logs: &[u8], breaking_changes_logs: &[u8], ) -> Result<()> { let mut tag_changelog = Vec::new(); writeln!(tag_changelog, "# Changelog")?; writeln!(tag_changelog)?; if fixes_logs.is_empty() && features_logs.is_empty() && breaking_changes_logs.is_empty() { writeln!(tag_changelog, "No changes")?; writeln!(tag_changelog)?; } if !fixes_logs.is_empty() { writeln!(tag_changelog, "## 🛠 Fixes")?; writeln!(tag_changelog)?; tag_changelog.extend(fixes_logs); writeln!(tag_changelog)?; } if !features_logs.is_empty() { writeln!(tag_changelog, "## ⚡️ Features")?; writeln!(tag_changelog)?; tag_changelog.extend(features_logs); } if !breaking_changes_logs.is_empty() { writeln!(tag_changelog, "## 🚨 Breaking changes")?; writeln!(tag_changelog)?; tag_changelog.extend(breaking_changes_logs); } stdout().write_all(&tag_changelog)?; Ok(()) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/write_log_lines.rs
tools/changelog/src/write_log_lines.rs
use std::io::Write; use anyhow::Result; use crate::log_line::LogLine; pub fn write_log_lines(log_lines: Vec<LogLine>) -> Result<Vec<u8>> { let mut logs_list = Vec::default(); for LogLine { message, user, issue_id, user_id, .. } in log_lines { writeln!( logs_list, "- {message}. [[@{user}](https://github.com/{user_id}), [#{issue_id}](https://github.com/yewstack/yew/pull/{issue_id})]", )?; } Ok(logs_list) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/log_line.rs
tools/changelog/src/log_line.rs
#[derive(Debug)] pub struct LogLine { pub message: String, pub user: String, pub user_id: String, pub issue_id: String, pub is_breaking_change: bool, }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/github_fetch.rs
tools/changelog/src/github_fetch.rs
use std::thread; use std::time::Duration; use anyhow::{bail, Result}; use reqwest::blocking::Client; use reqwest::header::{HeaderMap, ACCEPT, AUTHORIZATION, USER_AGENT}; use serde::de::DeserializeOwned; pub fn github_fetch<T: DeserializeOwned>(url: &str, token: Option<String>) -> Result<T> { thread::sleep(Duration::from_secs(1)); let mut optional_headers = HeaderMap::new(); if let Some(token) = token { optional_headers.insert(AUTHORIZATION, format!("Bearer {token}").parse().unwrap()); } let request_client = Client::new(); let resp = request_client .get(url) .header(USER_AGENT, "reqwest") .header(ACCEPT, "application/vnd.github.v3+json") .headers(optional_headers) .send()?; let status = resp.status(); if !status.is_success() { if let Some(remaining) = resp.headers().get("x-ratelimit-remaining") { if remaining == "0" { bail!("GitHub API limit reached."); } } bail!("GitHub API request error: {status}"); } Ok(resp.json()?) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/mod.rs
tools/changelog/src/mod.rs
pub mod github_fetch; pub mod github_issue_labels_fetcher; pub mod github_user_fetcher; pub mod log_line; pub mod yew_package;
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/create_log_lines.rs
tools/changelog/src/create_log_lines.rs
use anyhow::{Context, Result}; use git2::{Repository, Sort}; use crate::create_log_line::create_log_line; use crate::github_user_fetcher::GitHubUsersFetcher; use crate::log_line::LogLine; pub fn create_log_lines( from: String, to: String, package_labels: &'static [&'static str], token: Option<String>, ) -> Result<Vec<LogLine>> { let repo = Repository::open_from_env()?; let mut user_fetcher = GitHubUsersFetcher::default(); let from_oid = repo .revparse_single(&from) .context("Could not find `from` revision")? .id(); let to_oid = repo .revparse_single(&to) .context("Could not find `to` revision")? .id(); let mut revwalk = repo.revwalk()?; revwalk.set_sorting(Sort::TOPOLOGICAL)?; revwalk.hide(from_oid)?; revwalk.push(to_oid)?; revwalk .filter_map(|oid| { create_log_line(&repo, package_labels, oid, token.clone(), &mut user_fetcher) .transpose() }) .collect() }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/github_user_fetcher.rs
tools/changelog/src/github_user_fetcher.rs
use std::collections::HashMap; use anyhow::Result; use serde::Deserialize; use super::github_fetch::github_fetch; #[derive(Deserialize, Debug)] struct ResponseBody { author: ResponseBodyAuthor, } #[derive(Deserialize, Debug)] struct ResponseBodyAuthor { login: String, } #[derive(Debug, Default)] pub struct GitHubUsersFetcher { cache: HashMap<String, Option<String>>, } impl GitHubUsersFetcher { pub fn fetch_user_by_commit_author( &mut self, key: impl Into<String>, commit: impl AsRef<str>, token: Option<String>, ) -> Option<&str> { self.cache .entry(key.into()) .or_insert_with(|| match Self::inner_fetch(commit, token) { Ok(value) => value, Err(err) => { eprintln!("fetch_user_by_commit_author Error: {err}"); None } }) .as_deref() } fn inner_fetch(commit: impl AsRef<str>, token: Option<String>) -> Result<Option<String>> { let url = format!( "https://api.github.com/repos/yewstack/yew/commits/{}", commit.as_ref(), ); let body: ResponseBody = github_fetch(&url, token)?; Ok(Some(body.author.login)) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/main.rs
tools/changelog/src/main.rs
use anyhow::Result; use changelog::Cli; use clap::Parser; fn main() -> Result<()> { Cli::parse().run() }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/get_latest_version.rs
tools/changelog/src/get_latest_version.rs
use anyhow::{Context, Result}; use git2::Repository; use semver::{Error, Version}; use crate::yew_package::YewPackage; pub fn get_latest_version(package: &YewPackage) -> Result<Version> { let common_tag_pattern = format!("{package}-v"); let search_pattern = format!("{common_tag_pattern}*"); let tags: Vec<Version> = Repository::open_from_env()? .tag_names(Some(&search_pattern))? .iter() .filter_map(|mb_tag| { mb_tag.map(|tag| { let version = tag.replace(&common_tag_pattern, ""); Version::parse(&version) }) }) .collect::<Result<Vec<Version>, Error>>()?; tags.into_iter().max().context("no version found") }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/yew_package.rs
tools/changelog/src/yew_package.rs
use strum::{Display, EnumString}; #[derive(Debug, Clone, EnumString, Display)] #[strum(serialize_all = "kebab-case")] pub enum YewPackage { Yew, YewAgent, YewRouter, } impl YewPackage { pub fn as_labels(&self) -> &'static [&'static str] { match self { YewPackage::Yew => &["A-yew", "A-yew-macro", "macro"], YewPackage::YewAgent => &["A-yew-agent"], YewPackage::YewRouter => &["A-yew-router", "A-yew-router-macro"], } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/new_version_level.rs
tools/changelog/src/new_version_level.rs
use semver::Version; use strum::{Display, EnumString}; #[derive(Debug, Clone, EnumString, Display)] #[strum(serialize_all = "lowercase")] pub enum NewVersionLevel { Patch, Minor, Major, } impl NewVersionLevel { pub fn bump(&self, current_version: Version) -> Version { match self { NewVersionLevel::Patch => Version { patch: current_version.patch + 1, ..current_version }, NewVersionLevel::Minor => Version { minor: current_version.minor + 1, patch: 0, ..current_version }, NewVersionLevel::Major => Version { major: current_version.major + 1, minor: 0, patch: 0, ..current_version }, } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/src/write_changelog_file.rs
tools/changelog/src/write_changelog_file.rs
use std::fs; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use anyhow::{Context, Result}; pub fn write_changelog(changelog_path: &str, version_changelog: &[u8]) -> Result<()> { let old_changelog = File::open(changelog_path) .context(format!("could not open {changelog_path} for reading"))?; let old_changelog_reader = BufReader::new(old_changelog); let changelog_path_new = &format!("{changelog_path}.new"); let mut new_changelog = fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .open(changelog_path_new) .context(format!("could not open {changelog_path_new} for writing"))?; new_changelog.write_all(version_changelog)?; for old_line in old_changelog_reader.lines().skip(2) { writeln!(new_changelog, "{}", old_line?)?; } drop(new_changelog); fs::remove_file(changelog_path).context(format!("Could not delete {changelog_path}"))?; fs::rename(changelog_path_new, changelog_path).context(format!( "Could not replace {changelog_path} with {changelog_path_new}" ))?; Ok(()) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/changelog/tests/generate_yew_changelog_file.rs
tools/changelog/tests/generate_yew_changelog_file.rs
use std::fs; use std::fs::File; use std::io::{BufRead, BufReader}; use std::str::FromStr; use anyhow::Result; use changelog::new_version_level::NewVersionLevel; use changelog::yew_package::YewPackage; use changelog::Cli; use chrono::Utc; struct FileDeleteOnDrop; impl Drop for FileDeleteOnDrop { fn drop(&mut self) { fs::remove_file("tests/test_changelog.md").unwrap(); } } fn _generate_yew_changelog_file(from: &str, to: &str) -> Result<()> { let cli_args = Cli { package: YewPackage::from_str("yew").unwrap(), new_version_level: NewVersionLevel::Minor, from: Some(from.to_string()), to: to.to_string(), changelog_path: "tests/test_changelog.md".to_string(), skip_file_write: false, skip_get_bump_version: true, token: None, }; cli_args.run().unwrap(); Ok(()) } #[test] fn generate_yew_changelog_file() -> Result<()> { // Setup let file_delete_on_drop = FileDeleteOnDrop; fs::copy("tests/test_base.md", "tests/test_changelog.md")?; // Run _generate_yew_changelog_file( "abeb8bc3f1ffabc8a58bd9ba4430cd091a06335a", "d8ec50150ed27e2835bb1def26d2371a8c2ab750", )?; _generate_yew_changelog_file( "8086a73a217a099a46138f4363411827b18d1cb0", "934aedbc8815fd77fc6630b644cfea4f9a071236", )?; // Check let expected = File::open("tests/test_expected.md")?; let expected_reader_lines = BufReader::new(expected).lines(); let after = File::open("tests/test_changelog.md")?; let after_reader_lines = BufReader::new(after).lines(); let lines = expected_reader_lines.zip(after_reader_lines); for (i, (expected_line, after_line)) in lines.enumerate() { if i == 2 || i == 13 { // these lines have dynamic things that may break the tests let expected_line_updated = expected_line?.replace( "date_goes_here", Utc::now().format("%Y-%m-%d").to_string().as_str(), ); assert_eq!(expected_line_updated, after_line?); } else { assert_eq!(expected_line?, after_line?); } } drop(file_delete_on_drop); Ok(()) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/build-examples/src/lib.rs
tools/build-examples/src/lib.rs
use std::path::Path; use std::{env, fs}; use serde::Deserialize; use toml::Table; /// Examples that don't use Trunk for building pub const NO_TRUNK_EXAMPLES: [&str; 3] = ["simple_ssr", "ssr_router", "wasi_ssr_module"]; #[derive(Deserialize)] struct GitHubRelease { tag_name: String, } pub fn get_latest_wasm_opt_version() -> String { if let Ok(version) = env::var("LATEST_WASM_OPT_VERSION") { if !version.is_empty() { return version; } } get_latest_wasm_opt_version_from_api() } fn get_latest_wasm_opt_version_from_api() -> String { let url = "https://api.github.com/repos/WebAssembly/binaryen/releases/latest"; let client = reqwest::blocking::Client::new(); // github api requires a user agent // https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api?apiVersion=2022-11-28#user-agent-required let req_builder = client.get(url).header("User-Agent", "yew-wasm-opt-checker"); // Send the request let res = req_builder .send() .expect("Failed to send request to GitHub API"); if !res.status().is_success() { // Get more details about the error let status = res.status(); let error_text = res .text() .unwrap_or_else(|_| "Could not read error response".to_string()); panic!("GitHub API request failed with status: {status}. Details: {error_text}"); } let release: GitHubRelease = res.json().expect("Failed to parse GitHub API response"); release.tag_name } pub fn is_wasm_opt_outdated(path: &Path, latest_version: &str) -> bool { let trunk_toml_path = path.join("Trunk.toml"); if !trunk_toml_path.exists() { return true; } let content = match fs::read_to_string(&trunk_toml_path) { Ok(content) => content, Err(_) => return true, }; // Check if wasm_opt is configured and up-to-date let table: Table = toml::from_str(&content).unwrap(); let tools = table.get("tools").unwrap().as_table().unwrap(); let wasm_opt = tools.get("wasm_opt").unwrap().as_str().unwrap(); wasm_opt != latest_version }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/build-examples/src/main.rs
tools/build-examples/src/main.rs
use std::path::Path; use std::process::{Command, ExitCode}; use std::{env, fs}; use build_examples::{get_latest_wasm_opt_version, is_wasm_opt_outdated, NO_TRUNK_EXAMPLES}; fn main() -> ExitCode { // Must be run from root of the repo: // yew $ cargo r -p build-examples -b build-examples let output_dir = env::current_dir().expect("Failed to get current directory"); let output_dir = output_dir.join("dist"); fs::create_dir_all(&output_dir).expect("Failed to create output directory"); let examples_dir = Path::new("examples"); if !examples_dir.exists() { eprintln!( "examples directory not found. Make sure you're running from the root of the repo." ); return ExitCode::from(1); } let mut failure = false; let latest_wasm_opt = get_latest_wasm_opt_version(); let mut outdated_examples = Vec::new(); let mut outdated_example_paths = Vec::new(); // Get all entries in the examples directory let entries = fs::read_dir(examples_dir).expect("Failed to read examples directory"); for entry in entries { let entry = entry.expect("Failed to read directory entry"); let path = entry.path(); // Skip if not a directory if should_skip_path(&path) { continue; } let example = path .file_name() .expect("Failed to get directory name") .to_string_lossy() .to_string(); // Skip ssr examples as they don't need trunk if NO_TRUNK_EXAMPLES.contains(&example.as_str()) { continue; } // Check Trunk.toml for wasm_opt version and collect outdated examples if is_wasm_opt_outdated(&path, &latest_wasm_opt) { outdated_examples.push(example.clone()); outdated_example_paths.push(path.clone()); } println!("::group::Building {example}"); let sample_success = build_example(&path, &output_dir, &example); println!("::endgroup::"); if !sample_success { eprintln!("::error ::{example} failed to build"); failure = true; } } // Emit warning if any examples have outdated wasm_opt if !outdated_examples.is_empty() { println!( "::warning ::{} example crates do not have up-to-date wasm_opt: {}", outdated_examples.len(), outdated_examples.join(", ") ); } if failure { ExitCode::from(1) } else { ExitCode::from(0) } } fn should_skip_path(path: &Path) -> bool { !path.is_dir() || !path.join("Cargo.toml").exists() } fn build_example(path: &Path, output_dir: &Path, example: &str) -> bool { let public_url_prefix = env::var("PUBLIC_URL_PREFIX").unwrap_or_default(); let dist_dir = output_dir.join(example); // Run trunk build command let status = Command::new("trunk") .current_dir(path) .arg("build") .arg("--release") .arg("--dist") .arg(&dist_dir) .arg("--public-url") .arg(format!("{public_url_prefix}/{example}")) .arg("--no-sri") .status(); match status { Ok(status) if status.success() => { // Check for undefined symbols (imports from 'env') let js_files = match fs::read_dir(&dist_dir) { Ok(entries) => entries .filter_map(Result::ok) .filter(|e| e.path().extension().is_some_and(|ext| ext == "js")) .collect::<Vec<_>>(), Err(_) => return false, }; for js_file in js_files { let content = match fs::read_to_string(js_file.path()) { Ok(content) => content, Err(_) => return false, }; if content.contains("from 'env'") { return false; } } true } _ => false, } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/tools/build-examples/src/bin/update-wasm-opt.rs
tools/build-examples/src/bin/update-wasm-opt.rs
use std::fs; use std::path::{Path, PathBuf}; use std::process::ExitCode; use build_examples::{get_latest_wasm_opt_version, is_wasm_opt_outdated, NO_TRUNK_EXAMPLES}; use regex::Regex; fn main() -> ExitCode { // Must be run from root of the repo let examples_dir = Path::new("examples"); if !examples_dir.exists() { eprintln!( "examples directory not found. Make sure you're running from the root of the repo." ); return ExitCode::from(1); } let latest_wasm_opt = get_latest_wasm_opt_version(); let mut outdated_example_paths = Vec::new(); let mut outdated_examples = Vec::new(); // Get all entries in the examples directory let entries = fs::read_dir(examples_dir).expect("Failed to read examples directory"); for entry in entries { let entry = entry.expect("Failed to read directory entry"); let path = entry.path(); // Skip if not a directory if !path.is_dir() { continue; } // Skip hidden directories (e.g., .cargo) let file_name = entry.file_name(); if file_name.to_string_lossy().starts_with('.') { continue; } let example = path .file_name() .expect("Failed to get directory name") .to_string_lossy() .to_string(); // Skip ssr examples as they don't need trunk if NO_TRUNK_EXAMPLES.contains(&example.as_str()) { continue; } // Check Trunk.toml for wasm_opt version and collect outdated examples if is_wasm_opt_outdated(&path, &latest_wasm_opt) { outdated_examples.push(example); outdated_example_paths.push(path); } } if outdated_examples.is_empty() { println!("All examples are up-to-date with the latest wasm_opt version: {latest_wasm_opt}"); return ExitCode::from(0); } println!( "Found {} examples with outdated or missing wasm_opt configuration:", outdated_examples.len() ); for example in &outdated_examples { println!(" - {example}"); } println!("Latest wasm_opt version is: {latest_wasm_opt}"); println!("Updating all examples..."); let updated_count = update_all_examples(&outdated_example_paths, &latest_wasm_opt); println!("Updated {updated_count} example configurations to use {latest_wasm_opt}"); ExitCode::from(0) } pub fn update_all_examples(outdated_paths: &[PathBuf], latest_version: &str) -> usize { let mut updated_count = 0; let re = Regex::new(r#"(?m)^\[tools\]\s*\nwasm_opt\s*=\s*"(version_\d+)""#).unwrap(); for path in outdated_paths { let trunk_toml_path = path.join("Trunk.toml"); let content = fs::read_to_string(&trunk_toml_path).unwrap_or_default(); let updated_content = if re.is_match(&content) { // Replace existing wasm_opt version re.replace(&content, |_: &regex::Captures| { format!( r#"[tools] wasm_opt = "{latest_version}""# ) }) .to_string() } else { // Add wasm_opt configuration if content.is_empty() { format!( r#"[tools] wasm_opt = "{latest_version}""# ) } else { format!( "{}\n\n[tools]\nwasm_opt = \"{}\"", content.trim(), latest_version ) } }; if let Err(e) = fs::write(&trunk_toml_path, updated_content) { println!("Failed to update {}: {}", trunk_toml_path.display(), e); } else { updated_count += 1; } } updated_count }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_grandchild_with_grandparent/src/grandparent.rs
examples/communication_grandchild_with_grandparent/src/grandparent.rs
use super::*; pub enum Msg { ButtonClick(AttrValue), } /// Our top-level (grandparent) component that holds a reference to the shared state. pub struct GrandParent { state: Rc<AppState>, } impl Component for GrandParent { type Message = Msg; type Properties = (); fn create(ctx: &Context<Self>) -> Self { let child_clicked = ctx.link().callback(Msg::ButtonClick); let state = Rc::new(AppState { total_clicks: 0, child_clicked, last_clicked: None, }); Self { state } } fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool { match msg { Msg::ButtonClick(childs_name) => { // Update the shared state let shared_state = Rc::make_mut(&mut self.state); shared_state.total_clicks += 1; shared_state.last_clicked = Some(childs_name); true } } } fn view(&self, _ctx: &Context<Self>) -> Html { let app_state = self.state.clone(); let detail_msg = if let Some(last_clicked) = &self.state.last_clicked { format!("The last child you clicked was {last_clicked}.") } else { "Waiting for you to click a grandchild...".to_string() }; html! { <ContextProvider<Rc<AppState>> context={app_state}> <div class="grandparent"> <div> <h2 class="title">{ "Grandchild-with-Grandparent Communication Example" }</h2> <div class="grandparent-body"> <div class="grandparent-tag"> <span>{ "Grandparent" }</span> </div> <div class="grandparent-content"> <span>{ "My grandchildren have been clicked " }<span>{ self.state.total_clicks }</span>{ " times." }</span> <span>{detail_msg}</span> <Parent /> </div> </div> </div> </div> </ContextProvider<Rc<AppState>>> } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_grandchild_with_grandparent/src/child.rs
examples/communication_grandchild_with_grandparent/src/child.rs
use super::*; /// The `Child` component is the child of the `Parent` component, and will send and receive updates /// to/from the grandparent using the context. pub struct Child { state: Rc<AppState>, _listener: ContextHandle<Rc<AppState>>, } pub enum ChildMsg { ContextChanged(Rc<AppState>), } #[derive(Clone, Eq, PartialEq, Properties)] pub struct ChildProps { pub name: AttrValue, } impl Component for Child { type Message = ChildMsg; type Properties = ChildProps; fn create(ctx: &Context<Self>) -> Self { // Here we fetch the shared state from the context. For a demonstration on the use of // context in a functional component, have a look at the `examples/contexts` code. let (state, _listener) = ctx .link() .context::<Rc<AppState>>(ctx.link().callback(ChildMsg::ContextChanged)) .expect("context to be set"); Self { state, _listener } } fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool { match msg { ChildMsg::ContextChanged(state) => { self.state = state; true } } } fn view(&self, ctx: &Context<Self>) -> Html { let my_name = ctx.props().name.clone(); let name = format!("I'm {my_name}."); // Here we emit the callback to the grandparent component, whenever the button is clicked. let onclick = self.state.child_clicked.reform(move |_| my_name.clone()); html! { <div class="child-body"> <div class="child-tag"> <span>{ "Child" }</span> </div> <div> <span>{ "We've been clicked " }<span>{ self.state.total_clicks }</span>{ " times." }</span> </div> <div class="child-content"> <span>{ name }</span> <button {onclick}>{"Click"}</button> </div> </div> } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_grandchild_with_grandparent/src/main.rs
examples/communication_grandchild_with_grandparent/src/main.rs
use std::rc::Rc; use child::Child; use grandparent::GrandParent; use parent::Parent; mod child; mod grandparent; mod parent; use yew::{ function_component, html, AttrValue, Callback, Component, Context, ContextHandle, ContextProvider, Html, Properties, }; /// This is the shared state between the parent and child components. #[derive(Clone, PartialEq)] pub struct AppState { /// Total number of clicks received. total_clicks: u32, /// Callback used when a child is clicked. The AttrValue is the name of the child that was /// clicked. child_clicked: Callback<AttrValue>, /// The name of the child that was last clicked. last_clicked: Option<AttrValue>, } fn main() { yew::Renderer::<GrandParent>::new().render(); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_grandchild_with_grandparent/src/parent.rs
examples/communication_grandchild_with_grandparent/src/parent.rs
use super::*; /// The `Parent` component is the parent of the `Child` component. It has no logic, and is here to /// show there is no direct relation between grandchild and grandparent. #[function_component] pub fn Parent() -> Html { html! { <div class="parent-body"> <div class="parent-tag"> <span>{ "Parent" }</span> </div> <div class="parent-content"> <Child name="Alice" /> <Child name="Bob" /> </div> </div> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/inner_html/src/main.rs
examples/inner_html/src/main.rs
use yew::{Component, Context, Html}; const HTML: &str = include_str!("document.html"); pub struct App; impl Component for App { type Message = (); type Properties = (); fn create(_ctx: &Context<Self>) -> Self { Self } fn view(&self, _ctx: &Context<Self>) -> Html { Html::from_html_unchecked(HTML.into()) } } fn main() { yew::Renderer::<App>::new().render(); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_child_to_parent/src/child.rs
examples/communication_child_to_parent/src/child.rs
use super::*; /// The `Child` component is the child of the `Parent` component, and will send updates to the /// parent using a Callback. pub struct Child; #[derive(Clone, PartialEq, Properties)] pub struct ChildProps { pub name: AttrValue, pub on_clicked: Callback<AttrValue>, } impl Component for Child { type Message = (); type Properties = ChildProps; fn create(_ctx: &Context<Self>) -> Self { Self {} } fn view(&self, ctx: &Context<Self>) -> Html { let name = format!("I'm {}.", ctx.props().name); let my_name = ctx.props().name.clone(); // Here we emit the callback to the parent component, whenever the button is clicked. let onclick = ctx.props().on_clicked.reform(move |_| my_name.clone()); html! { <div class="child-body"> <div class="child-tag"> <span>{ "Child" }</span> </div> <div class="child-content"> <span>{ name }</span> <button {onclick}>{"Click"}</button> </div> </div> } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_child_to_parent/src/main.rs
examples/communication_child_to_parent/src/main.rs
use child::Child; use parent::Parent; use yew::{html, AttrValue, Callback, Component, Context, Html, Properties}; mod child; mod parent; fn main() { yew::Renderer::<Parent>::new().render(); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_child_to_parent/src/parent.rs
examples/communication_child_to_parent/src/parent.rs
use super::*; pub enum Msg { ButtonClick(AttrValue), } /// The `Parent` component holds some state that is updated when its children are clicked pub struct Parent { /// The total number of clicks received total_clicks: u32, /// The name of the child that was last clicked last_updated: Option<AttrValue>, } impl Component for Parent { type Message = Msg; type Properties = (); fn create(_ctx: &Context<Self>) -> Self { Self { total_clicks: 0, last_updated: None, } } fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool { match msg { Msg::ButtonClick(childs_name) => { // Keep track of the name of the child that was clicked self.last_updated = Some(childs_name); // Increment the total number of clicks self.total_clicks += 1; true } } } fn view(&self, ctx: &Context<Self>) -> Html { let last_updated_msg = if let Some(last_updated) = self.last_updated.as_ref() { format!("The last child you clicked was {last_updated}.") } else { "Waiting for you to click a child...".to_string() }; let on_clicked = ctx.link().callback(Msg::ButtonClick); html! { <div class="parent"> <div> <h2 class="title">{ "Child-to-Parent Communication Example" }</h2> <div class="parent-body"> <div class="parent-tag"> <span>{ "Parent" }</span> </div> <div class="parent-content"> <span>{ "My children have been clicked " }<span>{ self.total_clicks }</span>{ " times." }</span> <span>{ last_updated_msg }</span> <div> <Child name="Alice" on_clicked={on_clicked.clone()} /> <Child name="Bob" {on_clicked} /> </div> </div> </div> </div> </div> } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/state.rs
examples/function_memory_game/src/state.rs
use std::rc::Rc; use gloo::storage::{LocalStorage, Storage}; use serde::{Deserialize, Serialize}; use yew::prelude::*; use crate::constant::{CardName, Status, KEY_BEST_SCORE}; use crate::helper::shuffle_cards; #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] pub struct RawCard { pub id: String, pub name: CardName, } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] pub struct Card { pub id: String, pub flipped: bool, pub name: CardName, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct State { pub unresolved_card_pairs: u8, pub best_score: u32, pub status: Status, pub cards: Vec<Card>, pub last_card: Option<RawCard>, pub rollback_cards: Option<[RawCard; 2]>, } impl PartialEq<RawCard> for &mut Card { fn eq(&self, other: &RawCard) -> bool { self.id == other.id && self.name == other.name } } pub enum Action { FlipCard(RawCard), RollbackCards([RawCard; 2]), TrySaveBestScore(u32), GameReset, } impl Reducible for State { type Action = Action; fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> { match action { Action::FlipCard(card) => { let status = if self.status == Status::Ready { Status::Playing } else { self.status }; let mut cards = self.cards.clone(); cards.iter_mut().filter(|c| c.eq(&card)).for_each(|c| { c.flipped = !c.flipped; }); let last_card = self.last_card.clone(); match last_card { None => State { unresolved_card_pairs: self.unresolved_card_pairs, best_score: self.best_score, status, cards: cards.clone(), last_card: Some(card), rollback_cards: None, }, Some(last_card) => { let mut unresolved_card_pairs = self.unresolved_card_pairs; let mut status = self.status; let mut rollback_cards = self.rollback_cards.clone(); if card.id.ne(&last_card.id) && card.name.eq(&last_card.name) { unresolved_card_pairs = self.unresolved_card_pairs - 1; status = if unresolved_card_pairs == 0 { Status::Passed } else { self.status }; } else { rollback_cards = Some([last_card, card]); } State { unresolved_card_pairs, best_score: self.best_score, status, cards: cards.clone(), last_card: None, rollback_cards, } } } .into() } Action::RollbackCards(rollback_cards) => { let mut cards = self.cards.clone(); cards .iter_mut() .filter(|c| { rollback_cards.contains( &(RawCard { id: c.id.clone(), name: c.name, }), ) }) .for_each(|c| { c.flipped = !c.flipped; }); State { unresolved_card_pairs: self.unresolved_card_pairs, best_score: self.best_score, status: self.status, cards, last_card: self.last_card.clone(), rollback_cards: None, } .into() } Action::TrySaveBestScore(sec_past) => { (self.best_score > sec_past).then(|| LocalStorage::set(KEY_BEST_SCORE, sec_past)); self } Action::GameReset => State::reset().into(), } } } impl State { pub fn reset() -> State { State { unresolved_card_pairs: 8, best_score: LocalStorage::get(KEY_BEST_SCORE).unwrap_or(9999), status: Status::Ready, cards: shuffle_cards(), last_card: None, rollback_cards: None, } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/helper.rs
examples/function_memory_game/src/helper.rs
use nanoid::nanoid; use rand::rng; use rand::seq::SliceRandom; use crate::constant::RAW_CARDS; use crate::state::Card; pub fn shuffle_cards() -> Vec<Card> { let mut raw_cards = RAW_CARDS; raw_cards.shuffle(&mut rng()); raw_cards .iter() .map(|&p| Card { id: nanoid!(), flipped: false, name: p, }) .collect() }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/constant.rs
examples/function_memory_game/src/constant.rs
use serde::{Deserialize, Serialize}; use strum_macros::{Display, EnumIter}; pub const KEY_BEST_SCORE: &str = "memory.game.best.score"; #[derive(Clone, Copy, Debug, EnumIter, Display, PartialEq, Eq, Serialize, Deserialize)] pub enum CardName { EightBall, Kronos, BakedPotato, Dinosaur, Rocket, SkinnyUnicorn, ThatGuy, Zeppelin, } #[derive(Clone, Copy, Debug, EnumIter, Display, PartialEq, Eq, Serialize, Deserialize)] pub enum Status { Ready, Playing, Passed, } pub const RAW_CARDS: [CardName; 16] = [ CardName::EightBall, CardName::Kronos, CardName::BakedPotato, CardName::Dinosaur, CardName::Rocket, CardName::SkinnyUnicorn, CardName::ThatGuy, CardName::Zeppelin, CardName::EightBall, CardName::Kronos, CardName::BakedPotato, CardName::Dinosaur, CardName::Rocket, CardName::SkinnyUnicorn, CardName::ThatGuy, CardName::Zeppelin, ];
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/main.rs
examples/function_memory_game/src/main.rs
mod components; mod constant; mod helper; mod state; use crate::components::app::App; fn main() { yew::Renderer::<App>::new().render(); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/components.rs
examples/function_memory_game/src/components.rs
pub mod app; pub mod chessboard; pub mod chessboard_card; pub mod game_status_board; pub mod score_board; pub mod score_board_best_score; pub mod score_board_logo; pub mod score_board_progress;
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/components/app.rs
examples/function_memory_game/src/components/app.rs
use std::cell::RefCell; use std::rc::Rc; use gloo::timers::callback::{Interval, Timeout}; use yew::prelude::*; use yew::{function_component, html}; use crate::components::chessboard::Chessboard; use crate::components::game_status_board::GameStatusBoard; use crate::components::score_board::ScoreBoard; use crate::constant::Status; use crate::state::{Action, State}; #[function_component] pub fn App() -> Html { let state = use_reducer(State::reset); let sec_past = use_state(|| 0_u32); let sec_past_timer: Rc<RefCell<Option<Interval>>> = use_mut_ref(|| None); let limit_flips_timer: Rc<RefCell<Option<Timeout>>> = use_mut_ref(|| None); let sec_past_time = *sec_past; use_effect_with(state.clone(), { let limit_flips_timer = limit_flips_timer.clone(); move |state| { // game reset if state.status == Status::Ready { sec_past.set(0); } // game start else if *sec_past == 0 && state.last_card.is_some() { let sec_past = sec_past.clone(); let mut sec = *sec_past; *sec_past_timer.borrow_mut() = Some(Interval::new(1000, move || { sec += 1; sec_past.set(sec); })); } // game over else if state.status == Status::Passed { *sec_past_timer.borrow_mut() = None; *limit_flips_timer.borrow_mut() = None; state.dispatch(Action::TrySaveBestScore(*sec_past)); } // match failed else if state.rollback_cards.is_some() { let cloned_state = state.clone(); let cloned_rollback_cards = state.rollback_cards.clone().unwrap(); *limit_flips_timer.borrow_mut() = Some(Timeout::new(1000, { let limit_flips_timer = limit_flips_timer.clone(); move || { limit_flips_timer.borrow_mut().take(); cloned_state.dispatch(Action::RollbackCards(cloned_rollback_cards)); } })); } || () } }); let on_reset = { let state = state.clone(); Callback::from(move |_| state.dispatch(Action::GameReset)) }; let on_flip = { let state = state.clone(); Callback::from(move |card| { if limit_flips_timer.borrow().is_some() { return; } *limit_flips_timer.borrow_mut() = Some(Timeout::new(1000, { let limit_flips_timer = limit_flips_timer.clone(); move || { limit_flips_timer.borrow_mut().take(); } })); state.dispatch(Action::FlipCard(card)); }) }; html! { <div class="game-panel"> <ScoreBoard unresolved_card_pairs={state.unresolved_card_pairs} best_score={state.best_score} /> <Chessboard cards={state.cards.clone()} {on_flip} /> <GameStatusBoard sec_past={sec_past_time} status={state.status} {on_reset}/> </div> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/components/score_board_progress.rs
examples/function_memory_game/src/components/score_board_progress.rs
use yew::{function_component, html, Html, Properties}; #[derive(PartialEq, Eq, Properties, Clone)] pub struct Props { pub unresolved_card_pairs: u8, } #[function_component] pub fn GameProgress(props: &Props) -> Html { html! { <div class="game-progress"> <span>{"Cards not Matched"}</span> <h2>{ props.unresolved_card_pairs }</h2> </div> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/components/score_board_best_score.rs
examples/function_memory_game/src/components/score_board_best_score.rs
use yew::{function_component, html, Html, Properties}; #[derive(PartialEq, Eq, Properties, Clone)] pub struct Props { pub best_score: u32, } #[function_component] pub fn BestScore(props: &Props) -> Html { html! { <div class="best-score"> <span>{"Highest Record"}</span> <h2>{ props.best_score }</h2> </div> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/components/score_board.rs
examples/function_memory_game/src/components/score_board.rs
use yew::{function_component, html, Html, Properties}; use crate::components::score_board_best_score::BestScore; use crate::components::score_board_logo::Logo; use crate::components::score_board_progress::GameProgress; #[derive(PartialEq, Properties, Clone, Eq)] pub struct Props { pub unresolved_card_pairs: u8, pub best_score: u32, } #[function_component] pub fn ScoreBoard(props: &Props) -> Html { let Props { best_score, unresolved_card_pairs, } = props.clone(); html! { <div class="score-board"> <Logo /> <GameProgress {unresolved_card_pairs} /> <BestScore {best_score} /> </div> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/components/chessboard.rs
examples/function_memory_game/src/components/chessboard.rs
use yew::prelude::*; use yew::{function_component, html, Properties}; use crate::components::chessboard_card::ChessboardCard; use crate::state::{Card, RawCard}; #[derive(Properties, Clone, PartialEq)] pub struct Props { pub cards: Vec<Card>, pub on_flip: Callback<RawCard>, } #[function_component] pub fn Chessboard(props: &Props) -> Html { html! { <div class="chess-board"> { for props.cards.iter().map(|card| html! { <ChessboardCard card={card.clone()} on_flip={&props.on_flip} /> } ) } </div> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/components/score_board_logo.rs
examples/function_memory_game/src/components/score_board_logo.rs
use yew::{function_component, html, Html}; #[function_component] pub fn Logo() -> Html { html! { <h1 class="logo"> <a href="https://examples.yew.rs/function_memory_game" target="_blank">{"Memory"}</a> </h1> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/components/chessboard_card.rs
examples/function_memory_game/src/components/chessboard_card.rs
use web_sys::MouseEvent; use yew::prelude::*; use yew::{function_component, html, Html, Properties}; use crate::constant::CardName; use crate::state::{Card, RawCard}; #[derive(Properties, Clone, PartialEq)] pub struct Props { pub card: Card, pub on_flip: Callback<RawCard>, } #[function_component] pub fn ChessboardCard(props: &Props) -> Html { let Props { card, on_flip } = props.clone(); let Card { flipped, name, id } = card; let get_link_by_cardname = { match name { CardName::EightBall => "public/8-ball.png", CardName::Kronos => "public/kronos.png", CardName::BakedPotato => "public/baked-potato.png", CardName::Dinosaur => "public/dinosaur.png", CardName::Rocket => "public/rocket.png", CardName::SkinnyUnicorn => "public/skinny-unicorn.png", CardName::ThatGuy => "public/that-guy.png", CardName::Zeppelin => "public/zeppelin.png", } .to_string() }; let onclick = move |e: MouseEvent| { e.stop_propagation(); (!flipped).then(|| { on_flip.emit(RawCard { id: id.clone(), name, }) }); }; html! { <div class="chess-board-card-container"> <div class={classes!("card", flipped.then_some("flipped"))} {onclick}> <img class="front" src={get_link_by_cardname} alt="card" /> <img class="back" src="public/back.png" alt="card" /> </div> </div> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_memory_game/src/components/game_status_board.rs
examples/function_memory_game/src/components/game_status_board.rs
use yew::prelude::*; use yew::{function_component, html, Properties}; use crate::constant::Status; #[derive(Properties, Clone, PartialEq)] pub struct Props { pub status: Status, pub sec_past: u32, pub on_reset: Callback<()>, } #[function_component] pub fn GameStatusBoard(props: &Props) -> Html { let get_content = { let onclick = props.on_reset.reform(move |e: MouseEvent| { e.stop_propagation(); e.prevent_default(); }); match props.status { Status::Ready => html! { <span>{"Ready"}</span> }, Status::Playing => html! { <span>{"Playing"}</span> }, Status::Passed => html! { <button class="play-again-btn" {onclick}>{"Play again"}</button> }, } }; html! { <div class="game-status-container"> {get_content} <span class="sec-past">{ props.sec_past}{" s"}</span> </div> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/web_worker_fib/src/lib.rs
examples/web_worker_fib/src/lib.rs
#![recursion_limit = "1024"] #![allow(clippy::large_enum_variant)] pub mod agent; use web_sys::HtmlInputElement; use yew::platform::spawn_local; use yew::prelude::*; use yew_agent::oneshot::{use_oneshot_runner, OneshotProvider}; use crate::agent::{FibonacciTask, Postcard}; #[function_component] fn Main() -> Html { let input_value = use_state_eq(|| 44); let output = use_state(|| "Try out some fibonacci calculations!".to_string()); let fib_task = use_oneshot_runner::<FibonacciTask>(); let clicker_value = use_state_eq(|| 0); let calculate = { let input_value = *input_value; let output = output.clone(); move |_e: MouseEvent| { let fib_agent = fib_task.clone(); let output = output.clone(); spawn_local(async move { // start the worker let output_value = fib_agent.run(input_value).await; output.set(format!("Fibonacci value: {output_value}")); }); } }; let on_input_change = { let input_value = input_value.clone(); move |e: InputEvent| { input_value.set( e.target_unchecked_into::<HtmlInputElement>() .value() .parse() .expect("failed to parse"), ); } }; let inc_clicker = { let clicker_value = clicker_value.clone(); move |_e: MouseEvent| { clicker_value.set(*clicker_value + 1); } }; html! { <> <h1>{ "Web worker demo" }</h1> <p>{ "Submit a value to calculate, then increase the counter on the main thread!"} </p> <p>{ "Large numbers will take some time!" }</p> <h3>{ "Output: " } { &*output }</h3> <br /> <input type="number" value={input_value.to_string()} max="50" oninput={on_input_change} /> <button onclick={calculate}>{ "submit" }</button> <br /> <br /> <h3>{ "Main thread value: " } { *clicker_value }</h3> <button onclick={inc_clicker}>{ "click!" }</button> </> } } #[function_component] pub fn App() -> Html { html! { <OneshotProvider<FibonacciTask, Postcard> path="/worker.js"> <Main /> </OneshotProvider<FibonacciTask, Postcard>> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/web_worker_fib/src/agent.rs
examples/web_worker_fib/src/agent.rs
use js_sys::Uint8Array; use serde::{Deserialize, Serialize}; use wasm_bindgen::JsValue; use yew_agent::prelude::*; use yew_agent::Codec; /// Example to use a custom codec. pub struct Postcard; impl Codec for Postcard { fn encode<I>(input: I) -> JsValue where I: Serialize, { let buf = postcard::to_vec::<_, 32>(&input).expect("can't serialize a worker message"); Uint8Array::from(buf.as_slice()).into() } fn decode<O>(input: JsValue) -> O where O: for<'de> Deserialize<'de>, { let data = Uint8Array::from(input).to_vec(); postcard::from_bytes(&data).expect("can't deserialize a worker message") } } #[oneshot] pub async fn FibonacciTask(n: u32) -> u32 { fn fib(n: u32) -> u32 { if n <= 1 { 1 } else { fib(n - 1) + fib(n - 2) } } fib(n) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/web_worker_fib/src/bin/app.rs
examples/web_worker_fib/src/bin/app.rs
fn main() { yew::Renderer::<yew_worker_fib::App>::new().render(); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false