Beispiel #1
0
 .onValue((response) => this.setState({
   results: Bacon.zipAsArray(
     Bacon.fromArray(response[1]),
     Bacon.fromArray(response[2]),
     Bacon.fromArray(response[3])
   )
 }));
Beispiel #2
0
    /**
     * Create a room
     * (This function should be in RoomService?)
     *
     * @return {[EventStream.<ReceivedMessage>, Bus.<Room>]}
     */
    makeRoom() {
        const roomStreamOne = this.webRTCService.peerOpen().map((key) => {
            this.logger.log("receive a owner key", key);
            // a connection to me is null
            const p = this.playerService.createPlayer(key, null);

            const room = this.roomService.createRoomAsOwner(p);
            this.logger.log("create a room", room);

            return room;
        });

        const messageStream = this.messageService.makeMessageStreamFromPeerConnect();

        const roomBus = new Bacon.Bus();
        roomBus.plug(roomStreamOne);

        Bacon.zipAsArray(roomBus, messageStream).onValue(([room, receivedMessage]) => {
            this.logger.log("make a new room from a message and room");

            const [message, conn] = [receivedMessage.message, receivedMessage.conn];

            if (message.type === "firstHello" && room.isPlayerLocked === false) {
                const newRoom = this.roomService.addNewPlayer(room, message.body.key, conn);
                this.logger.log("new room is created", newRoom);

                this.messageService.sendMessage(conn, this.messages.ownerHello(newRoom));
                roomBus.push(newRoom);
            }
        });

        return [messageStream, roomBus]
    };
Beispiel #3
0
  expect: function (streams, ex, assert) {
    var a = streams.ships
      .fold(0, function (acc, v) { return acc + v; });

    var b = streams.threat.changes()
      .fold([], '.concat');

    var c = streams.postArrivalShips
      .fold(0, function (acc, v) { return acc + v; });

    var all = Bacon.zipAsArray(a,b,c)
      .onValues(function (ships, threat, postArrivalShips) {
        return assert(ships === 3 && _.isEqual(threat, threats) && postArrivalShips == 2);
      });

    shipSensorR.push(zrrkShip);
    destroyerDistanceStreamR.push(8);
    destroyerDistanceStreamR.push(7);
    destroyerDistanceStreamR.push(4);
    destroyerDistanceStreamR.push(2);
    destroyerDistanceStreamR.push(0.5);
    destroyerDistanceStreamR.push(0);
    shipSensorR.push(earthianShip);
    shipSensorR.push(zrrkShip);
    shipSensorR.push(zrrkShip);
    destroyerDistanceStreamR.end();
    shipSensorR.end();

  }
Beispiel #4
0
function initMarkerPopupStreams() {
    var popupOpenStream =
            Bacon.fromEventTarget(_markerFeatureGroup, 'popupopen'),
        popupClosedStream =
            Bacon.fromEventTarget(_markerFeatureGroup, 'popupclose');

    var locationForCurrentPopup =
        _state.locationChangesProperty.sampledBy(
            popupOpenStream.map('.layer.uid'),
            findLocationByUid
        );

    var treeForCurrentPopup =
        _state.treeChangesProperty.sampledBy(
            locationForCurrentPopup.map('.treeUid'),
            findTreeByUid
        );

    var renderPopupContent = function(loc, popup, tree) {
        var species = _.find(_species, {otm_code: tree.species()}),
            html = renderTemplate(templates.markerPopup, {
                tree: tree,
                loc: loc,
                speciesName: species && species.common_name
            });
        popup.setContent(html);
    };

    // Return a stream that will emit a signal when the popup is closed
    // or the relevant tree has been deleted.
    var getPopupClosedStream = function(loc) {
        return Bacon.mergeAll(
            popupClosedStream,
            _state.locationRemovedStream.filter(function(uid) {
                return loc.uid() === uid;
            })
        );
    };

    var updatePopupWhenTreeChages = function(loc, popup, tree) {
        _state.treeUpdatedStream
            .takeUntil(getPopupClosedStream(loc))
            .filter(function(other) {
                return tree.uid() === other.uid();
            })
            .onValue(renderPopupContent, loc, popup);
    };

    Bacon.zipAsArray(
        locationForCurrentPopup,
        popupOpenStream.map('.popup'),
        treeForCurrentPopup
    ).onValues(function(loc, popup, tree) {
        renderPopupContent(loc, popup, tree);
        updatePopupWhenTreeChages(loc, popup, tree);
    });
}
Beispiel #5
0
    /**
     * Join the room
     * (This function should be in RoomService?)
     *
     * @param {string} ownerKey
     * @returns {[EventStream.<ReceivedMessage>, Bus.<Room>]}
     */
    joinRoom(ownerKey) {
        const roomBus = new Bacon.Bus();
        const presentPlayersMessageStream = this.webRTCService.peerOpen().flatMap((myKey) => {
            this.logger.log("receive a participant's key", myKey);

            const ownerMessageStream = this.messageService.makeMessageStreamFromKey(ownerKey, myKey);
            const presentOtherPlayersStream = ownerMessageStream.filter((receivedMessage) => {
                this.logger.log("filter the message", receivedMessage);
                return (receivedMessage.message.type === "ownerHello");
            }).flatMap((receivedMessage) => {
                const owner = this.playerService.createPlayer(ownerKey, receivedMessage.conn);
                const myData = receivedMessage.message.body.players.find((p) => {
                    return p.key === myKey;
                });
                const me = this.playerService.createPlayer(myData.key, null);
                const otherPlayers = receivedMessage.message.body.players.filter((p) => {
                    return p.key !== myKey && p.key !== ownerKey;
                }).map((p) => {
                    const conn = this.webRTCService.connect(p.key);
                    return this.playerService.createPlayer(p.key, conn);
                });
                this.logger.log("other players", otherPlayers);

                const players = Array.prototype.concat([owner], otherPlayers, [me]);
                const room = this.roomService.createRoomAsCommon(me, owner, players);

                roomBus.push(room);
                this.logger.log("room is created", room);

                return Bacon.mergeAll(
                    otherPlayers.map((p) => {
                        return this.messageService.makeMessageStreamFromConnection(p.conn, me.key);
                    })
                );
            });

            return ownerMessageStream.merge(presentOtherPlayersStream);
        });

        const connectPlayerMessageStream = this.messageService.makeMessageStreamFromPeerConnect();
        const messageStream = presentPlayersMessageStream.merge(connectPlayerMessageStream);

        Bacon.zipAsArray(roomBus, connectPlayerMessageStream).onValue(([room, m]) => {
            if (m.message.type === "firstHello" && room.isPlayerLocked === false) {
                const newPlayer = this.playerService.createPlayer(m.message.body.key, m.conn);
                const newRoom = this.roomService.addPlayer(room, newPlayer);

                this.logger.log("make a new room", newRoom);

                roomBus.push(newRoom);
            }
        });

        return [messageStream, roomBus];
    }
Beispiel #6
0
 componentDidMount: function() {
   this.unsubscribe =
     Bacon.zipAsArray(StationDataStore.stationArrivalView, StationMetadataStore.stationsByCode)
     .onValues((stationView, stationCodes) => {
       this.stationCodes = stationCodes
       this.setState({
         dataSource: this.state.dataSource.cloneWithRows(stationView),
       })
     })
   LiveDataActions.trainListDidMount.push(true)
 },
Beispiel #7
0
  all: function() {
    var streams = this.sourceStreams = toArray(arguments);

    if(streams.length === 1) {
      this.any.apply(this, streams);
      return this;
    }

    this.resultStream = Bacon.zipAsArray(streams);

    this.streamsHash = this._computeStreamsHash('all', streams);

    // invalidate 'any'
    return this;
  },
Beispiel #8
0
module.exports = function(options) {
    var $container = $(options.container),

        lessOrMoreElementStream = $container.asEventStream('click', '[data-less-more]')
            .doAction('.preventDefault')
            .map('.target')
            .map($),

        // We use event delegation on the outer container, because we replace
        // the entire table including the pagination and filter section.
        //
        // We prevent default events for everything, but only get new pages
        // for anchor tags which have href values
        pageEventStream = $container.asEventStream('click', '.pagination li a'),
        filterEventStream = $container.asEventStream('click', '[data-comments-filter] li a'),
        sortingEventStream = $container.asEventStream('click', '[data-comments-sort] th a'),

        urlStream = Bacon.mergeAll(pageEventStream, filterEventStream, sortingEventStream)
            .doAction('.preventDefault')
            .map('.target.href')
            .filter(BU.isDefinedNonEmpty),

        singleActionStream = $container.asEventStream('click', '[data-comment-single-action] a'),
        batchActionStream = $container.asEventStream('click', '[data-comment-batch] a'),
        toggleAllEventStream = $container.asEventStream('click', '[data-comment-toggle-all]'),

        actionUrlStream = Bacon.mergeAll(singleActionStream, batchActionStream)
            .doAction('.preventDefault')
            .map('.target.href')
            .filter(BU.isDefinedNonEmpty)
            .map(function(url) {
                // We have to look this up every time because it changes based
                // on the current filter/sort/page
                var params = $container.find('[data-comments-params]').attr('data-comments-params');
                return url + '?' + params;
            }),

        singleActionIdStream = singleActionStream
            .map('.target')
            .map($)
            .map(function($elem) {
                return [$elem.parents('[data-comment-id]').attr('data-comment-id')];
            }),

        getSelectedCommentIds = function() {
            var $selectedCheckboxes = $container
                .find('[data-comment-id]')
                .has('[data-batch-action-checkbox]:checked');

            return _.map($selectedCheckboxes, function(elem) {
                return $(elem).attr('data-comment-id');
            });
        },

        batchActionIdStream = batchActionStream
            .map(getSelectedCommentIds),

        actionIdStream = Bacon.mergeAll(singleActionIdStream, batchActionIdStream)
            .map(function(array) {
                return {'comment-ids': array.join(',')};
            }),

        actionResultStream = Bacon.zipAsArray(actionUrlStream, actionIdStream);

    lessOrMoreElementStream.onValue(function($elem) {
        $elem.text($elem.text() == 'less' ? 'more' : 'less');
        var $text = $elem.prev();
        $text.toggleClass('less');
    });

    urlStream.onValue($container, 'load');

    actionResultStream.onValues(_.bind($container.load, $container));

    toggleAllEventStream
        .map($container, 'find', '[data-batch-action-checkbox]')
        .onValue(function($elems) {
            var checked = $container.find('[data-comment-toggle-all]').is(':checked');
            $elems.prop('checked', checked);
        });
};
require('isomorphic-fetch')

var LiveDataActions = require('../actions/LiveDataActions.js')

var METADATA_URL = 'http://rata.digitraffic.fi/api/v1/metadata/station'

var stations = Bacon.fromPromise(fetch(METADATA_URL))
  .flatMap(response => Bacon.fromPromise(response.json()))
  .toProperty()

var stationsByCode = stations.map(stations =>
  _(stations)
    .map(station => {
      station.stationName = station.stationName.replace(' asema', '')
      return station
    })
    .indexBy('stationShortCode')
    .value()
)

var metadataForStation =
  Bacon.zipAsArray(stationsByCode, LiveDataActions.station)
  .map(params => {
    [stations, station] = params
  })

module.exports = {
  stations: stations,
  stationsByCode: stationsByCode
}