platform/lib/browser.dart
2018-08-20 14:59:51 -04:00

204 lines
5.6 KiB
Dart

import 'dart:async' show Stream, StreamController;
import 'dart:html';
import 'angel_route.dart';
import 'package:path/path.dart' as p;
final RegExp _hash = new RegExp(r'^#/');
final RegExp _straySlashes = new RegExp(r'(^/+)|(/+$)');
/// A variation of the [Router] support both hash routing and push state.
abstract class BrowserRouter extends Router {
/// Fires whenever the active route changes. Fires `null` if none is selected (404).
Stream<RoutingResult> get onResolve;
/// Fires whenever the active route changes. Fires `null` if none is selected (404).
Stream<Route> get onRoute;
/// Set `hash` to true to use hash routing instead of push state.
/// `listen` as `true` will call `listen` after initialization.
factory BrowserRouter({bool hash: false, bool listen: false}) {
return hash
? new _HashRouter(listen: listen)
: new _PushStateRouter(listen: listen);
}
BrowserRouter._() : super();
void _goTo(String path);
/// Navigates to the path generated by calling
/// [navigate] with the given [linkParams].
///
/// This always navigates to an absolute path.
void go(List linkParams);
// Handles a route path, manually.
// void handle(String path);
/// Begins listen for location changes.
void listen();
/// Identical to [all].
Route on(String path, handler, {List middleware});
}
abstract class _BrowserRouterImpl extends Router implements BrowserRouter {
bool _listening = false;
Route _current;
StreamController<RoutingResult> _onResolve =
new StreamController<RoutingResult>();
StreamController<Route> _onRoute = new StreamController<Route>();
Route get currentRoute => _current;
@override
Stream<RoutingResult> get onResolve => _onResolve.stream;
@override
Stream<Route> get onRoute => _onRoute.stream;
_BrowserRouterImpl({bool listen}) : super() {
if (listen != false) this.listen();
prepareAnchors();
}
@override
void go(Iterable linkParams) => _goTo(navigate(linkParams));
Route on(String path, handler, {List middleware}) =>
all(path, handler, middleware: middleware);
void prepareAnchors() {
final anchors = window.document.querySelectorAll('a:not([dynamic])');
for (final AnchorElement $a in anchors) {
if ($a.attributes.containsKey('href') &&
!$a.attributes.containsKey('download') &&
!$a.attributes.containsKey('target') &&
$a.attributes['rel'] != 'external') {
$a.onClick.listen((e) {
e.preventDefault();
go($a.attributes['href'].split('/').where((str) => str.isNotEmpty));
});
}
$a.attributes['dynamic'] = 'true';
}
}
void _listen();
@override
void listen() {
if (_listening)
throw new StateError('The router is already listening for page changes.');
_listening = true;
_listen();
}
}
class _HashRouter extends _BrowserRouterImpl {
_HashRouter({bool listen}) : super(listen: listen) {
if (listen) this.listen();
}
@override
void _goTo(String uri) {
window.location.hash = '#$uri';
}
void handleHash([_]) {
final path = window.location.hash.replaceAll(_hash, '');
final resolved = resolveAbsolute(path).first;
if (resolved == null) {
_onResolve.add(null);
_onRoute.add(_current = null);
} else if (resolved != null && resolved.route != _current) {
_onResolve.add(resolved);
_onRoute.add(_current = resolved.route);
}
}
void handlePath(String path) {
final resolved = resolveAbsolute(path).first;
if (resolved == null) {
_onResolve.add(null);
_onRoute.add(_current = null);
} else if (resolved != null && resolved.route != _current) {
_onResolve.add(resolved);
_onRoute.add(_current = resolved.route);
}
}
@override
void _listen() {
window.onHashChange.listen(handleHash);
handleHash();
}
}
class _PushStateRouter extends _BrowserRouterImpl {
String _basePath;
_PushStateRouter({bool listen, Route root}) : super(listen: listen) {
var $base = window.document.querySelector('base[href]') as BaseElement;
if ($base?.href?.isNotEmpty != true)
throw new StateError(
'You must have a <base href="<base-url-here>"> element present in your document to run the push state router.');
_basePath = $base.href.replaceAll(_straySlashes, '');
if (listen) this.listen();
}
@override
void _goTo(String uri) {
final resolved = resolveAbsolute(uri).first;
var relativeUri = uri;
if (_basePath?.isNotEmpty == true) {
relativeUri = p.join(_basePath, uri.replaceAll(_straySlashes, ''));
}
if (resolved == null) {
_onResolve.add(null);
_onRoute.add(_current = null);
} else {
final route = resolved.route;
window.history.pushState(
{'path': route.path, 'params': {}},
route.name ?? route.path,
relativeUri);
_onResolve.add(resolved);
_onRoute.add(_current = route);
}
}
void handleState(state) {
if (state is Map && state.containsKey('path')) {
var path = state['path'].toString();
final resolved = resolveAbsolute(path).first;
if (resolved != null && resolved.route != _current) {
//properties.addAll(state['properties'] ?? {});
_onResolve.add(resolved);
_onRoute.add(_current = resolved.route);
} else {
_onResolve.add(null);
_onRoute.add(_current = null);
}
} else {
_onResolve.add(null);
_onRoute.add(_current = null);
}
}
@override
void _listen() {
window.onPopState.listen((e) {
handleState(e.state);
});
handleState(window.history.state);
}
}