utils.dart 1.73 KB
Newer Older
1 2 3 4 5 6
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:html';

7
final AnchorElement _urlParsingNode = AnchorElement();
8 9 10 11 12 13

/// Extracts the pathname part of a full [url].
///
/// Example: for the url `http://example.com/foo`, the extracted pathname will
/// be `/foo`.
String extractPathname(String url) {
14
  _urlParsingNode.href = url; // ignore: unsafe_html, node is never exposed to the user
15
  final String pathname = _urlParsingNode.pathname ?? '';
16 17 18
  return (pathname.isEmpty || pathname[0] == '/') ? pathname : '/$pathname';
}

19 20
// The <base> element in the document.
final Element? _baseElement = document.querySelector('base');
21

22
/// Returns the `href` attribute of the <base> element in the document.
23 24
///
/// Returns null if the element isn't found.
25
String? getBaseElementHrefFromDom() => _baseElement?.getAttribute('href');
26 27 28 29

/// Checks that [baseHref] is set.
///
/// Throws an exception otherwise.
30
String checkBaseHref(String? baseHref) {
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
  if (baseHref == null) {
    throw Exception('Please add a <base> element to your index.html');
  }
  if (!baseHref.endsWith('/')) {
    throw Exception('The base href has to end with a "/" to work correctly');
  }
  return baseHref;
}

/// Prepends a forward slash to [path] if it doesn't start with one already.
///
/// Returns [path] unchanged if it already starts with a forward slash.
String ensureLeadingSlash(String path) {
  if (!path.startsWith('/')) {
    return '/$path';
  }
  return path;
}

/// Removes the trailing forward slash from [path] if any.
String stripTrailingSlash(String path) {
  if (path.endsWith('/')) {
    return path.substring(0, path.length - 1);
  }
  return path;
}