1- use default_env:: default_env;
2- use yew:: virtual_dom:: { Transformer , VComp } ;
1+ use yew:: {
2+ virtual_dom:: { Transformer , VComp } ,
3+ web_sys:: Url ,
4+ } ;
35use yew_router:: { components:: RouterAnchor , prelude:: * , switch:: Permissive } ;
46
57#[ derive( Clone , Debug , Switch ) ]
@@ -35,16 +37,24 @@ impl AppRoute {
3537#[ derive( Clone , Debug ) ]
3638pub struct PublicUrlSwitch ( AppRoute ) ;
3739impl PublicUrlSwitch {
38- // this variable is set by the build script
39- const PUBLIC_URL : & ' static str = default_env ! ( "PUBLIC_URL" , "/" ) ;
40+ fn base_url ( ) -> Url {
41+ if let Ok ( Some ( href) ) = yew:: utils:: document ( ) . base_uri ( ) {
42+ // since this always returns an absolute URL we turn it into `Url`
43+ // so we can more easily get the path.
44+ Url :: new ( & href) . unwrap ( )
45+ } else {
46+ Url :: new ( "/" ) . unwrap ( )
47+ }
48+ }
49+
50+ fn base_path ( ) -> String {
51+ let mut path = Self :: base_url ( ) . pathname ( ) ;
52+ if path. ends_with ( '/' ) {
53+ // pop the trailing slash because AppRoute already accounts for it
54+ path. pop ( ) ;
55+ }
4056
41- /// Return `PUBLIC_URL` without a trailing slash.
42- /// This is required because `AppRoute` still expects paths to
43- /// start with a slash so we only want to strip away the parts before that.
44- fn public_url_no_trailing_slash ( ) -> & ' static str {
45- Self :: PUBLIC_URL
46- . strip_suffix ( '/' )
47- . unwrap_or ( Self :: PUBLIC_URL )
57+ path
4858 }
4959
5060 pub fn route ( self ) -> AppRoute {
@@ -53,7 +63,7 @@ impl PublicUrlSwitch {
5363}
5464impl Switch for PublicUrlSwitch {
5565 fn from_route_part < STATE > ( part : String , state : Option < STATE > ) -> ( Option < Self > , Option < STATE > ) {
56- if let Some ( part) = part. strip_prefix ( Self :: public_url_no_trailing_slash ( ) ) {
66+ if let Some ( part) = part. strip_prefix ( & Self :: base_path ( ) ) {
5767 let ( route, state) = AppRoute :: from_route_part ( part. to_owned ( ) , state) ;
5868 ( route. map ( Self ) , state)
5969 } else {
@@ -62,7 +72,7 @@ impl Switch for PublicUrlSwitch {
6272 }
6373
6474 fn build_route_section < STATE > ( self , route : & mut String ) -> Option < STATE > {
65- route. push_str ( Self :: public_url_no_trailing_slash ( ) ) ;
75+ route. push_str ( & Self :: base_path ( ) ) ;
6676 self . 0 . build_route_section ( route)
6777 }
6878}
0 commit comments