Skip to content

Commit f1becf0

Browse files
authored
Add conversions between Dart's Uri and the JS URL (#365)
1 parent 553c14d commit f1becf0

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

web/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
don't exist.
66
- Fixed generation of variadic arguments to generate 4 optional parameters.
77
- Removed all `@Deprecated` members.
8+
- Added `URL.toDart` and `Uri.toJS` extension methods.
89

910
## 1.1.1
1011

web/lib/src/helpers/extensions.dart

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,22 @@ extension XMLHttpRequestGlue on XMLHttpRequest {
8484
return headers;
8585
}
8686
}
87+
88+
extension URLToUri on URL {
89+
/// Converts this to a Dart [Uri] object.
90+
Uri get toDart => Uri.parse(toString());
91+
}
92+
93+
extension UriToURL on Uri {
94+
/// Converts this to a JavaScript [URL] object.
95+
///
96+
/// Throws an [ArgumentError] if this isn't an absolute URL, since [URL] can
97+
/// only represent absolute URLs.
98+
URL get toJS {
99+
try {
100+
return URL(toString());
101+
} catch (_) {
102+
throw ArgumentError.value(this, 'this', '"$this" isn\'t a valid JS URL.');
103+
}
104+
}
105+
}

web/test/helpers_test.dart

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,4 +134,33 @@ void main() {
134134
// `close` on a `contentWindow` does nothing.
135135
expect(contentWindow.closed, false);
136136
});
137+
138+
test('converts from a JS to a Dart URL', () {
139+
final url =
140+
URL('https://foo:[email protected]:1234/path?query#fragment').toDart;
141+
expect(url.scheme, equals('https'));
142+
expect(url.userInfo, equals('foo:bar'));
143+
expect(url.host, equals('example.org'));
144+
expect(url.port, equals(1234));
145+
expect(url.path, equals('/path'));
146+
expect(url.query, equals('query'));
147+
expect(url.fragment, equals('fragment'));
148+
});
149+
150+
test('converts from a Dart to a JS URL', () {
151+
final url =
152+
Uri.parse('https://foo:[email protected]:1234/path?query#fragment').toJS;
153+
expect(url.protocol, equals('https:'));
154+
expect(url.username, equals('foo'));
155+
expect(url.password, equals('bar'));
156+
expect(url.hostname, equals('example.org'));
157+
expect(url.port, equals('1234'));
158+
expect(url.pathname, equals('/path'));
159+
expect(url.search, equals('?query'));
160+
expect(url.hash, equals('#fragment'));
161+
});
162+
163+
test('Uri.toJS throws an ArgumentError for a relative URL', () {
164+
expect(() => Uri.parse('/path').toJS, throwsArgumentError);
165+
});
137166
}

0 commit comments

Comments
 (0)