createHref method

  1. @override
String createHref(
  1. Uri uri
)
override

Formats a Uri as an href for this history implementation.

This is primarily useful on the web (e.g. when calling window.history.pushState), but can also be used to generate link targets.

Implementation

@override
String createHref(Uri uri) {
  // For HashHistory, the entire path (pathname + search + hash) goes in the fragment
  // Manually construct the URL to avoid encoding issues with nested #
  final buffer = StringBuffer();

  // Add base URL if there's a <base> tag
  final base = window.document.querySelector('base');
  if (base != null && base.getAttribute('href') != null) {
    final baseUri = Uri.parse(window.location.href).removeFragment();
    buffer.write(baseUri.toString());
  }

  // Add fragment with full path
  buffer.write('#${uri.path}');
  if (uri.hasQuery) {
    buffer.write('?${uri.query}');
  }
  if (uri.hasFragment) {
    buffer.write('#${uri.fragment}');
  }

  return buffer.toString();
}