Skip to content

Commit

Permalink
Merge pull request #1 from sdeleuze/master
Browse files Browse the repository at this point in the history
Dart 1.0 fixes
  • Loading branch information
nelsonsilva committed Dec 11, 2013
2 parents 813de27 + 9082016 commit 5aa5b92
Show file tree
Hide file tree
Showing 12 changed files with 86 additions and 78 deletions.
20 changes: 10 additions & 10 deletions example/echo.dart
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
library echo;

import "dart:html";
import "dart:json";
import "dart:convert";
import "package:sockjs_client/sockjs.dart" as SockJS;

DivElement div = query('#first div');
InputElement inp = query('#first input');
FormElement form = query('#first form');
DivElement div = querySelector('#first div');
InputElement inp = querySelector('#first input');
FormElement form = querySelector('#first form');

print(m, [p = '']) {
if(!p.isEmpty) {
p = JSON.stringify(p);
p = JSON.encode(p);
}
div.elements
..add(new Element.html("<code/>")..text=("$m$p"))
..add(new Element.html("<br>"));
div
..append(new Element.html("<code/>")..text=("$m$p"))
..append(new Element.html("<br>"));

div.scrollTop += 10000;
}
Expand All @@ -23,13 +23,13 @@ main() {
print("Starting");
var sockjs_url = 'http://127.0.0.1:8081/echo';
var sockjs = new SockJS.Client(sockjs_url, protocolsWhitelist:['websocket', 'xhr-streaming'], debug: true);
query('#first input').focus();
querySelector('#first input').focus();

sockjs.on.open.add( (_) => print('[*] open ${sockjs.protocol}') );
sockjs.on.message.add( (e) => print('[.] message ${e.data}') );
sockjs.on.close.add( (_) => print('[*] close') );

inp.on.keyUp.add( (KeyboardEvent e) {
inp.onKeyUp.listen( (KeyboardEvent e) {
if (e.keyCode == 13) {
print('[ ] sending ${inp.value}');
sockjs.send(inp.value);
Expand Down
4 changes: 2 additions & 2 deletions example/echo.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ <h1>SockJS Echo example</h1>

<div id="first" class="box">
<div></div>
<input autocomplete="off" value="Type here..."></input>
<input autocomplete="off" placeholder="Type here..."></input>
</div>

<script type="application/dart" src="echo.dart"></script>
<script src="http://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
<script type="text/javascript" src="packages/browser/dart.js"></script>
</body>
</html>
4 changes: 2 additions & 2 deletions lib/sockjs.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
library sockjs_client;

import "dart:html";
import "dart:json";
import "dart:isolate";
import "dart:convert";
import "dart:async";

import "src/events.dart" as event;
import "src/utils.dart" as utils;
Expand Down
19 changes: 10 additions & 9 deletions lib/src/ajax.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
part of sockjs_client;

class XHREvents extends event.Events {
get chunk => this["chunk"];
get finish => this["finish"];
get timeout => this["timeout"];
event.ListenerList get chunk => this["chunk"];
event.ListenerList get finish => this["finish"];
event.ListenerList get timeout => this["timeout"];
}

class StatusEvent {
Expand All @@ -18,6 +18,7 @@ class AbstractXHRObject implements event.Emitter<XHREvents> {
XHREvents on = new XHREvents();

HttpRequest xhr;
StreamSubscription changeSubscription;

_start(method, url, payload, {noCredentials: false, headers}) {

Expand All @@ -41,7 +42,7 @@ class AbstractXHRObject implements event.Emitter<XHREvents> {
//that.unload_ref = utils.unload_add(function(){that._cleanup(true);});

try {
xhr.open(method, url, true);
xhr.open(method, url);
} catch(e) {
// IE raises an exception on wrong port.
on.finish.dispatch(new StatusEvent());
Expand All @@ -54,11 +55,11 @@ class AbstractXHRObject implements event.Emitter<XHREvents> {
// "This never affects same-site requests."
xhr.withCredentials = true;
}
if (?headers) {
if (headers != null) {
headers.forEach((k, v) => xhr.setRequestHeader(k, v));
}

xhr.on.readyStateChange.add(_readyStateHandler);
changeSubscription = xhr.onReadyStateChange.listen(_readyStateHandler);

xhr.send(payload);
}
Expand Down Expand Up @@ -91,7 +92,7 @@ class AbstractXHRObject implements event.Emitter<XHREvents> {
// utils.unload_del(that.unload_ref);

// IE needs this field to be a function
xhr.on.readyStateChange.remove(_readyStateHandler);
changeSubscription.cancel();

if (abort) {
try {
Expand All @@ -109,15 +110,15 @@ class AbstractXHRObject implements event.Emitter<XHREvents> {

class XHRCorsObject extends AbstractXHRObject {
XHRCorsObject(method, url, payload, {noCredentials, headers} ) {
utils.delay(()=>_start(method, url, payload, noCredentials: false));
Timer.run(() =>_start(method, url, payload, noCredentials: false));
}
}



class XHRLocalObject extends AbstractXHRObject {
XHRLocalObject (method, url, payload, {noCredentials, headers}) {
utils.delay(() => _start(method, url, payload, noCredentials: true));
Timer.run(() =>_start(method, url, payload, noCredentials: true));
}
}

Expand Down
18 changes: 9 additions & 9 deletions lib/src/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class Client implements event.Emitter<SockJSEvents> {
}
readyState = CLOSED;

utils.delay(() => on.close.dispatch(close_event));
Timer.run(() => on.close.dispatch(close_event));
}

_dispatchOpen() {
Expand All @@ -136,7 +136,7 @@ class Client implements event.Emitter<SockJSEvents> {
}

_dispatchHeartbeat() {
if (readyState !== OPEN) {
if (readyState != OPEN) {
return;
}
on.heartbeat.dispatch();
Expand All @@ -151,21 +151,21 @@ class Client implements event.Emitter<SockJSEvents> {
case 'a':
var s = data.substring(1);
if (s == null) s = '[]';
var payload = JSON.parse(s);
var payload = JSON.decode(s);
for(var i=0; i < payload.length; i++){
_dispatchMessage(payload[i]);
}
break;
case 'm':
var s = data.substring(1);
if (s == null) s = 'null';
var payload = JSON.parse(s);
var payload = JSON.decode(s);
_dispatchMessage(payload);
break;
case 'c':
var s = data.substring(1);
if (s == null) s = '[]';
var payload = JSON.parse(s);
var payload = JSON.decode(s);
_didClose(payload[0], payload[1]);
break;
case 'h':
Expand Down Expand Up @@ -198,9 +198,9 @@ class Client implements event.Emitter<SockJSEvents> {
PROTOCOLS[protocol].needBody &&
( (document.body == null) || (document.readyState != null && document.readyState != 'complete'))
) {
_protocols.insertRange(0, 1, protocol);
_protocols.insert(0, protocol);
this.protocol = 'waiting-for-load';
document.on.load.add( (_) => _tryNextProtocol());
document.onLoad.listen( (_) => _tryNextProtocol());
return true;
}

Expand All @@ -211,14 +211,14 @@ class Client implements event.Emitter<SockJSEvents> {
var roundTrips = PROTOCOLS[protocol].roundTrips;
var to = rto * roundTrips;
if (to == 0) to = 5000;
_transportTref = utils.delay(() {
_transportTref = new Timer(new Duration(milliseconds:to), () {
if (readyState == CONNECTING) {
// I can't understand how it is possible to run
// this timer, when the state is CLOSED, but
// apparently in IE everythin is possible.
_didClose(2007, "Transport timeouted");
}
}, to);
});

var connid = utils.random_string(8);
var trans_url = "$_baseUrl/$server/$connid";
Expand Down
6 changes: 4 additions & 2 deletions lib/src/events.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ class Events {

Map<String, ListenerList> _listeners;

Events() : _listeners = <ListenerList>{};
Events() : _listeners = <String, ListenerList>{};

ListenerList operator [](String type) => _listeners.putIfAbsent(type, () => new ListenerList(type));
ListenerList operator [](String type) => _listeners.putIfAbsent(type, () {
return new ListenerList(type);
});

removeAllListeners() => _listeners = {};
}
Expand Down
16 changes: 8 additions & 8 deletions lib/src/info.dart
Original file line number Diff line number Diff line change
Expand Up @@ -56,21 +56,21 @@ abstract class InfoReceiver implements event.Emitter<InfoReceiverEvents> {
class AjaxInfoReceiver extends InfoReceiver {

AjaxInfoReceiver(String baseUrl, AjaxObjectFactory xhrFactory) {
utils.delay(() => doXhr(baseUrl, xhrFactory));
Timer.run(() => doXhr(baseUrl, xhrFactory));
}

doXhr(String baseUrl, AjaxObjectFactory xhrFactory) {
var t0 = new Date.now().millisecondsSinceEpoch;
var t0 = new DateTime.now().millisecondsSinceEpoch;
var xo = xhrFactory('GET', "$baseUrl/info");

var tref = utils.delay(() => xo.on.timeout.dispatch(), 8000);
var tref = new Timer(new Duration(milliseconds:8000), xo.on.timeout.dispatch);

xo.on.finish.add( (StatusEvent evt) {
tref.cancel();
tref = null;
if (evt.status == 200) {
var rtt = new Date.now().millisecondsSinceEpoch - t0;
var info = new Info.fromJSON(JSON.parse(evt.text));
var rtt = new DateTime.now().millisecondsSinceEpoch - t0;
var info = new Info.fromJSON(JSON.decode(evt.text));
on.finish.dispatch(new InfoReceiverEvent(info, rtt));
} else {
on.finish.dispatch(new InfoReceiverEvent());
Expand All @@ -88,7 +88,7 @@ class InfoReceiverIframe extends InfoReceiver {

InfoReceiverIframe (base_url) {
if(document.body == null) {
document.on.load.add((_) => go());
document.onLoad.listen((_) => go());
} else {
go();
}
Expand Down Expand Up @@ -127,7 +127,7 @@ class InfoReceiverFake extends InfoReceiver {
// It may not be possible to do cross domain AJAX to get the info
// data, for example for IE7. But we want to run JSONP, so let's
// fake the response, with rtt=2s (rto=6s).
utils.delay(() => on.finish.dispatch(), 2000);
new Timer(new Duration(milliseconds:2000), on.finish.dispatch);
}
}

Expand All @@ -137,7 +137,7 @@ class WInfoReceiverIframe {
WInfoReceiverIframe(ri, _trans_url, baseUrl) {
var ir = new AjaxInfoReceiver(baseUrl, XHRLocalObjectFactory);
ir.on.finish.add( (evt) {
ri._didMessage('m${JSON.stringify([evt.info, evt.rtt])}');
ri._didMessage('m${JSON.encode([evt.info, evt.rtt])}');
ri._didClose();
});
}
Expand Down
4 changes: 2 additions & 2 deletions lib/src/transport/receiver.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
part of sockjs_client;

class ReceiverEvents extends event.Events {
get message => this["message"];
get close => this["close"];
event.ListenerList get message => this["message"];
event.ListenerList get close => this["close"];
}

class Receiver implements event.Emitter<ReceiverEvents> {
Expand Down
21 changes: 11 additions & 10 deletions lib/src/transport/sender.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ class BufferedSender {
sendStop = null;
tref.cancel();
};
tref = utils.delay(() {
tref = new Timer(new Duration(milliseconds:25), () {
sendStop = null;
sendSchedule();
}, 25);
});
}

sendSchedule() {
if (!sendBuffer.isEmpty) {
var payload = '[${Strings.join(sendBuffer, ',')}]';
var payload = '[${sendBuffer.join(',')}]';
sendStop = sender(transUrl,
payload,
([status, reason]) {
Expand All @@ -62,6 +62,8 @@ class BufferedSender {
}
}

/** TODO To be fixed since Dart 1.0 does not give access anymore to IFrame ReadyState and only authorize
// postMessage communication */
class JsonPGenericSender {

FormElement _sendForm = null;
Expand All @@ -82,8 +84,8 @@ class JsonPGenericSender {
form.method = 'POST';
form.enctype = 'application/x-www-form-urlencoded';
form.acceptCharset = "UTF-8";
form.elements.add(area);
document.body.elements.add(form);
form.children.add(area);
document.body.children.add(form);
}
form = _sendForm;
area = _sendArea;
Expand All @@ -100,7 +102,7 @@ class JsonPGenericSender {
iframe.name = id;
}
iframe.id = id;
form.elements.add(iframe);
form.children.add(iframe);
iframe.style.display = 'none';

try {
Expand All @@ -122,10 +124,10 @@ class JsonPGenericSender {

// Opera mini doesn't like if we GC iframe
// immediately, thus this timeout.
utils.delay(() {
iframe.parentNode.removeChild(iframe);
new Timer(new Duration(milliseconds: 500),() {
iframe.remove();
iframe = null;
}, 500);
});
area.value = '';
callback();
};
Expand All @@ -137,7 +139,6 @@ class JsonPGenericSender {
}
}


createAjaxSender(AjaxObjectFactory xhrFactory)
=> (url, payload, callback([status, reason])) {
AbstractXHRObject xo = xhrFactory('POST', '$url/xhr_send', payload);
Expand Down
Loading

0 comments on commit 5aa5b92

Please sign in to comment.