Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use fragment / hash for source. #15

Merged
merged 3 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## unreleased

* Playground: Use URL fragment/hash instead of query params to store source.


## 0.6.0 (2024-06-09)

* SVGs copied now use ` ` for spaces for valid SVG XML.
Expand Down
3 changes: 2 additions & 1 deletion playground/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ lz-str = "0.2.1"

[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = { workspace = true }
web-sys = { workspace = true, features = ["Document", "Element", "HtmlElement", "Url", "UrlSearchParams", "Window"] }
web-sys = { workspace = true, features = ["console", "Document", "Element", "HtmlElement", "Url", "UrlSearchParams", "Window"] }
js-sys = { workspace = true }

[features]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
Expand Down
28 changes: 22 additions & 6 deletions playground/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,30 @@ const QUERY_PARAM_DIAGRAM_ONLY: &str = "diagram_only";
/// `create_effect` is safe.
#[cfg(target_arch = "wasm32")]
fn diagram_only_init(set_diagram_only: WriteSignal<bool>) {
use web_sys::Url;
use js_sys::Array;
use web_sys::{console, Url, UrlSearchParams};

create_effect(move |_| {
if let Some(url_search_params) = web_sys::window().map(|window| {
Url::new(&String::from(window.location().to_string()))
.expect("Expected URL to be valid.")
.search_params()
}) {
let url_search_params = web_sys::window().and_then(|window| {
let url = Url::new(&String::from(window.location().to_string()))
.expect("Expected URL to be valid.");

let hash = url.hash();
if hash.is_empty() {
Some(url.search_params())
} else {
match UrlSearchParams::new_with_str(hash.as_str()) {
Ok(search_params) => Some(search_params),
Err(error) => {
let message = Array::new_with_length(1);
message.set(0, error);
console::log(&message);
None
}
}
}
});
if let Some(url_search_params) = url_search_params {
let diagram_only = url_search_params
.get(QUERY_PARAM_DIAGRAM_ONLY)
.and_then(|diagram_only_str| serde_yaml::from_str::<bool>(&diagram_only_str).ok())
Expand Down
122 changes: 82 additions & 40 deletions playground/src/app/info_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ use dot_ix::{
};
use leptos::*;

#[cfg(target_arch = "wasm32")]
use super::QUERY_PARAM_DIAGRAM_ONLY;

const INFO_GRAPH_DEMO: &str = include_str!("info_graph_example.yaml");

/// User provided info graph source.
Expand All @@ -23,47 +26,67 @@ const QUERY_PARAM_SRC: &str = "src";
#[cfg(target_arch = "wasm32")]
fn info_graph_src_init(set_info_graph_src: WriteSignal<String>) {
use lz_str::decompress_from_encoded_uri_component;
use web_sys::{Document, Url};
use web_sys::{console, Document, Url, UrlSearchParams};
use js_sys::Array;

create_effect(move |_| {
if let Some(window) = web_sys::window() {
let url_search_params = Url::new(&String::from(window.location().to_string()))
.expect("Expected URL to be valid.")
.search_params();
let info_graph_src_initial = url_search_params
.get(QUERY_PARAM_SRC)
.map(|src| {
if src.contains("\n") {
// Treat src as plain yaml
src
} else {
// Try deserialize/serialize src as lz_str
decompress_from_encoded_uri_component(&src).map_or_else(
|| format!("# deserialize src error: invalid data"),
|s| {
String::from_utf16(&s).unwrap_or_else(|_| {
format!("# deserialize src error: invalid data")
})
},
)
let url_search_params = {
let url = Url::new(&String::from(window.location().to_string()))
.expect("Expected URL to be valid.");

let hash = url.hash();
if hash.is_empty() {
Some(url.search_params())
} else {
match UrlSearchParams::new_with_str(hash.as_str()) {
Ok(search_params) => Some(search_params),
Err(error) => {
let message = Array::new_with_length(1);
message.set(0, error);
console::log(&message);
None
}
}
})
.unwrap_or_else(|| String::from(INFO_GRAPH_DEMO));

set_info_graph_src.set(info_graph_src_initial);

// Hack: Get Tailwind CSS from CDN to reevaluate document.
set_timeout(
move || {
let _ = window
.document()
.as_ref()
.and_then(Document::body)
.as_deref()
.map(|element| element.append_with_str_1(""));
},
Duration::from_millis(200),
);
}
};

if let Some(url_search_params) = url_search_params {
let info_graph_src_initial = url_search_params
.get(QUERY_PARAM_SRC)
.map(|src| {
if src.contains("\n") {
// Treat src as plain yaml
src
} else {
// Try deserialize/serialize src as lz_str
decompress_from_encoded_uri_component(&src).map_or_else(
|| format!("# deserialize src error: invalid data"),
|s| {
String::from_utf16(&s).unwrap_or_else(|_| {
format!("# deserialize src error: invalid data")
})
},
)
}
})
.unwrap_or_else(|| String::from(INFO_GRAPH_DEMO));

set_info_graph_src.set(info_graph_src_initial);

// Hack: Get Tailwind CSS from CDN to reevaluate document.
set_timeout(
move || {
let _ = window
.document()
.as_ref()
.and_then(Document::body)
.as_deref()
.map(|element| element.append_with_str_1(""));
},
Duration::from_millis(200),
);
}
} else {
set_info_graph_src.set(String::from("# Could not extract search params."));
}
Expand Down Expand Up @@ -171,10 +194,29 @@ pub fn InfoGraph(diagram_only: ReadSignal<bool>) -> impl IntoView {
let src_compressed = compress_to_encoded_uri_component(&info_graph_src);
if let Some(window) = web_sys::window() {
let url = {
let u = web_sys::Url::new(&String::from(window.location().to_string()))
let url = web_sys::Url::new(&String::from(window.location().to_string()))
.expect("Expected URL to be valid.");
u.search_params().set(QUERY_PARAM_SRC, &src_compressed);
u.to_string()

// Remove this in a few versions.
url.search_params().delete(QUERY_PARAM_SRC);
url.search_params().delete(QUERY_PARAM_DIAGRAM_ONLY);

let fragment = {
let mut fragment = String::with_capacity(QUERY_PARAM_SRC.len() + src_compressed.len() + 64);
fragment.push_str(QUERY_PARAM_SRC);
fragment.push_str("=");
fragment.push_str(&src_compressed);

if diagram_only.get() {
fragment.push_str("&");
fragment.push_str(QUERY_PARAM_DIAGRAM_ONLY);
fragment.push_str("=true");
}

fragment
};
url.set_hash(&fragment);
url.to_string()
.as_string()
.expect("# Failed to decode src parameter")
};
Expand Down
Loading