-
Notifications
You must be signed in to change notification settings - Fork 0
/
RouteData.hx
90 lines (73 loc) · 2.47 KB
/
RouteData.hx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package coconut.router;
import coconut.data.Model;
import coconut.ui.View;
import coconut.ui.RenderResult;
import tink.state.*;
import tink.Url;
class RouteData implements Model {
@:external var url:Url;
#if (js && !nodejs)
public static inline function create(noMonkeyPatch = false)
return new RouteData({url: new BrowserPath(noMonkeyPatch)});
public static function link(attr:vdom.VDom.AnchorAttr, ?children) {
untyped {
var original = attr.onclick;
attr.onclick = function(e) {
onclick(e);
if(original != null) original(e);
}
}
return vdom.VDom.a(attr, children);
}
static function onclick(e:js.html.MouseEvent) {
var elem:js.html.AnchorElement = cast e.currentTarget;
switch elem.getAttribute('href') {
case null: // do nothing
case href if(href.indexOf('//') >= 0): // do nothing, let browser handle
case href:
e.preventDefault();
js.Browser.window.history.pushState(null, null, href);
}
}
public inline function goto(href:String)
js.Browser.window.history.pushState(null, null, href);
#end
}
#if (js && !nodejs)
abstract BrowserPath(Observable<Url>) to Observable<Url> {
public function new(noMonkeyPatch = false) {
if(!noMonkeyPatch) {
var window = js.Browser.window;
// polyfill Event on IE
untyped __js__('(function () {
if ( typeof window.CustomEvent === "function" ) return false;
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( "CustomEvent" );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();');
var oldPushState = window.history.pushState;
untyped window.history.pushState = function(data, title, ?url) {
oldPushState(data, title, url);
window.dispatchEvent(new js.html.CustomEvent('popstate'));
}
var window = js.Browser.window;
var oldReplaceState = window.history.replaceState;
untyped window.history.replaceState = function(data, title, ?url) {
oldReplaceState(data, title, url);
window.dispatchEvent(new js.html.CustomEvent('popstate'));
}
}
var state = new State(getCurrent());
js.Browser.window.addEventListener('popstate', function() state.set(getCurrent()));
this = state.observe();
}
static function getCurrent():Url {
return js.Browser.window.location.href;
}
}
#end