<commit_before>import './directives/sol-vibrate';
import './directives/sol-slide-rm';
import './directives/sol-scroll2top';
import '../modules/sol-backend/sol-backend';
import 'ui-sortable';
import './Services';
import 'angular';

function mouseCoords(event) {
    var totalOffsetX = 0,
        totalOffsetY = 0,
        canvasX = 0,
        canvasY = 0,
        currentElement = event.target;

    do {
        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
        currentElement = currentElement.offsetParent;
    }
    while (currentElement);

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    return {
        x: canvasX,
        y: canvasY
    };
}

export default angular.module('ui.playlist',
    ['sol-backend', 'services', 'filters', 'ui.sortable', 'solVibrate', 'solSlideRm', 'solScroll2top'])
    .directive('playlistPane', [
            '$rootScope', '$http', '$location', 'youtubeAPI', 'playList', 'solBackend', 'lastfm',
            function($rootScope, $http, $location, youtubeAPI, playList, solBackend, lastfm) {
        var definitions = {
            restrict: 'E',
            templateUrl: '/html/playlist/pane.html',
            replace: true,
            scope: true,
            link: function($scope, $element, $attrs) {
                var media = window.matchMedia('(max-width:1280px),(max-device-width:1280px)');

                $scope.duration = 0;
                $scope.progress = 0;

                if (media.matches) {
                    $scope.ready = true;
                } else {
                    $rootScope.$on('searchPane:loaded', function() {
                        $scope.ready = true;
                        if (!$scope.$$phase) $scope.$digest();
                    });
                }

                solBackend.onAuth((authData) => {
                    $scope.authData = authData;
                });

                $scope.publishPlaylist = () => {
                    playList.publishPlaylist().then((refKey) => {
                        $location.search('playlist', refKey);
                    });
                };

                $scope.clearPlaylist = function() {
                    playList.clearList();
                    $location.search('playlist', null);
                };

                $scope.isItemActive = (idx) => {
                    let state = playList.getState();
                    let playing = state === playList.st.PLAYING;
                    let active = playing && $scope.getItemProgress(idx) > 0;
                    return active || undefined;
                };

                $scope.getItemProgress = (idx) => {
                    let progress = $scope.progress;

                    if ($scope.nowPlayingIdx === idx)
                        return progress;
                };

                $scope.itemMatch = function(item, query) {
                    var matches;
                    if (!query) return true;

                    matches = item.snippet
                        .title.toLowerCase()
                        .indexOf(query.toLowerCase()) >= 0;

                    return matches || undefined;
                };

                $scope.$on('actions-toggled', (e, value) => {
                    if (value === true) {
                        let target = e.targetScope;
                        let idx = target.idx;

                        $scope.items.forEach((item, i) => {
                            if (i === idx) return;
                            item.actionsOpen = false;
                        });
                    }
                });

                Object.assign($scope, {
                    getCurrentlyOpenIdx: () => {
                        let idx = null;

                        $scope.items.some((item, i) => {
                            if (item.actionsOpen) {
                                idx = i;
                                return true;
                            }
                        });

                        return idx;
                    },
                    uploadPlaylist () {
                        solBackend.savePlaylist(
                            this.metadata, this.items);
                    },
                    changeBackground () {
                        let nowPlayingIdx = playList.getNowPlayingIdx();
                        let nowPlaying = playList.getNowPlaying();
                        if (nowPlaying) {
                            console.debug('change bg', nowPlaying);
                            lastfm.getTrackImage(
                                nowPlaying.snippet.title
                            ).then(src => {
                                $scope.backgroundImg = src;
                            });
                        }
                        else $scope.backgroundImg = '';
                    }
                });

                $scope.$watch(playList.getNowPlayingIdx,
                    val => {
                        $scope.nowPlayingIdx = val;
                        $scope.progress = 0;
                        $scope.changeBackground();
                    });

                $scope.$watch(playList.getDuration,
                    val => $scope.duration = val);

                $scope.$watch(playList.getProgress,
                    val => $scope.progress = val);

                $scope.sortableOpts = {
                    axis: 'y',
                    handle: '.mover',
                    start: function(e, ui) {
                        $rootScope.$broadcast('closeTrackActions');
                        $scope.currentlyDragging = true;
                        if (!$scope.$$phase) $scope.$digest();
                    },
                    stop: function(e, ui) {
                        // Fix the playlist's currently playing track
                        var fromIdx = ui.item.sortable.index,
                            toIdx = ui.item.sortable.dropindex,
                            nowPlaying = playList.getNowPlayingIdx();

                        if (typeof nowPlaying === 'number') {
                            if (fromIdx < nowPlaying &&
                                toIdx >= nowPlaying) {
                                playList.setNowPlaying(nowPlaying - 1);
                            } else if (fromIdx > nowPlaying &&
                                toIdx <= nowPlaying) {
                                playList.setNowPlaying(nowPlaying + 1);
                            } else if (fromIdx === nowPlaying) {
                                playList.setNowPlaying(toIdx);
                            }
                        }

                        playList.save();
                        $scope.currentlyDragging = false;
                        if (!$scope.$$phase) $scope.$digest();
                    }
                };
            },
            controller: function($scope, $element, $attrs, $transclude) {
                $scope.items = playList.playlist;
                $scope.$watch(() => playList.metadata, (newVal) => {
                    if (newVal)
                        newVal.$bindTo($scope, "metadata");
                });
                $scope.savePlaylist = function() {
                    playList.save();
                };
            }
        };

        return definitions;
    }]).directive('playlistProgress', ['$rootScope', 'youtubePlayer', function($rootScope, youtubePlayer) {
        var definitions = {
            restrict: 'E',
            templateUrl: '/html/playlist/progress.html',
            replace: true,
            scope: {
                progress: '=',
                duration: '@'
            },
            link: function($scope, $element, $attrs) {
                $element.on('click', function(e) {
                    var coords, time;

                    if (e.target.classList.contains('progress')) {
                        coords = mouseCoords(e);
                        time = $scope.duration * (coords.x / e.target.clientWidth);

                        youtubePlayer.seek(time);
                    }
                });
            }
        };

        return definitions;
    }]);
<commit_msg>Destroy old firebase instance to avoid the multi-$bindTo issue<commit_after>import './directives/sol-vibrate';
import './directives/sol-slide-rm';
import './directives/sol-scroll2top';
import '../modules/sol-backend/sol-backend';
import 'ui-sortable';
import './Services';
import 'angular';

function mouseCoords(event) {
    var totalOffsetX = 0,
        totalOffsetY = 0,
        canvasX = 0,
        canvasY = 0,
        currentElement = event.target;

    do {
        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
        currentElement = currentElement.offsetParent;
    }
    while (currentElement);

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    return {
        x: canvasX,
        y: canvasY
    };
}

export default angular.module('ui.playlist',
    ['sol-backend', 'services', 'filters', 'ui.sortable', 'solVibrate', 'solSlideRm', 'solScroll2top'])
    .directive('playlistPane', [
            '$rootScope', '$http', '$location', 'youtubeAPI', 'playList', 'solBackend', 'lastfm',
            function($rootScope, $http, $location, youtubeAPI, playList, solBackend, lastfm) {
        var definitions = {
            restrict: 'E',
            templateUrl: '/html/playlist/pane.html',
            replace: true,
            scope: true,
            link: function($scope, $element, $attrs) {
                var media = window.matchMedia('(max-width:1280px),(max-device-width:1280px)');

                $scope.duration = 0;
                $scope.progress = 0;

                if (media.matches) {
                    $scope.ready = true;
                } else {
                    $rootScope.$on('searchPane:loaded', function() {
                        $scope.ready = true;
                        if (!$scope.$$phase) $scope.$digest();
                    });
                }

                solBackend.onAuth((authData) => {
                    $scope.authData = authData;
                });

                $scope.publishPlaylist = () => {
                    playList.publishPlaylist().then((refKey) => {
                        $location.search('playlist', refKey);
                    });
                };

                $scope.clearPlaylist = function() {
                    playList.clearList();
                    $location.search('playlist', null);
                };

                $scope.isItemActive = (idx) => {
                    let state = playList.getState();
                    let playing = state === playList.st.PLAYING;
                    let active = playing && $scope.getItemProgress(idx) > 0;
                    return active || undefined;
                };

                $scope.getItemProgress = (idx) => {
                    let progress = $scope.progress;

                    if ($scope.nowPlayingIdx === idx)
                        return progress;
                };

                $scope.itemMatch = function(item, query) {
                    var matches;
                    if (!query) return true;

                    matches = item.snippet
                        .title.toLowerCase()
                        .indexOf(query.toLowerCase()) >= 0;

                    return matches || undefined;
                };

                $scope.$on('actions-toggled', (e, value) => {
                    if (value === true) {
                        let target = e.targetScope;
                        let idx = target.idx;

                        $scope.items.forEach((item, i) => {
                            if (i === idx) return;
                            item.actionsOpen = false;
                        });
                    }
                });

                Object.assign($scope, {
                    getCurrentlyOpenIdx: () => {
                        let idx = null;

                        $scope.items.some((item, i) => {
                            if (item.actionsOpen) {
                                idx = i;
                                return true;
                            }
                        });

                        return idx;
                    },
                    uploadPlaylist () {
                        solBackend.savePlaylist(
                            this.metadata, this.items);
                    },
                    changeBackground () {
                        let nowPlayingIdx = playList.getNowPlayingIdx();
                        let nowPlaying = playList.getNowPlaying();
                        if (nowPlaying) {
                            console.debug('change bg', nowPlaying);
                            lastfm.getTrackImage(
                                nowPlaying.snippet.title
                            ).then(src => {
                                $scope.backgroundImg = src;
                            });
                        }
                        else $scope.backgroundImg = '';
                    }
                });

                $scope.$watch(playList.getNowPlayingIdx,
                    val => {
                        $scope.nowPlayingIdx = val;
                        $scope.progress = 0;
                        $scope.changeBackground();
                    });

                $scope.$watch(playList.getDuration,
                    val => $scope.duration = val);

                $scope.$watch(playList.getProgress,
                    val => $scope.progress = val);

                $scope.sortableOpts = {
                    axis: 'y',
                    handle: '.mover',
                    start: function(e, ui) {
                        $rootScope.$broadcast('closeTrackActions');
                        $scope.currentlyDragging = true;
                        if (!$scope.$$phase) $scope.$digest();
                    },
                    stop: function(e, ui) {
                        // Fix the playlist's currently playing track
                        var fromIdx = ui.item.sortable.index,
                            toIdx = ui.item.sortable.dropindex,
                            nowPlaying = playList.getNowPlayingIdx();

                        if (typeof nowPlaying === 'number') {
                            if (fromIdx < nowPlaying &&
                                toIdx >= nowPlaying) {
                                playList.setNowPlaying(nowPlaying - 1);
                            } else if (fromIdx > nowPlaying &&
                                toIdx <= nowPlaying) {
                                playList.setNowPlaying(nowPlaying + 1);
                            } else if (fromIdx === nowPlaying) {
                                playList.setNowPlaying(toIdx);
                            }
                        }

                        playList.save();
                        $scope.currentlyDragging = false;
                        if (!$scope.$$phase) $scope.$digest();
                    }
                };
            },
            controller: function($scope, $element, $attrs, $transclude) {
                $scope.items = playList.playlist;
                $scope.$watch(() => playList.metadata, (newVal, oldVal) => {
                    if (newVal) {
                        if (oldVal) {
                            oldVal.$destroy();
                        }
                        newVal.$bindTo($scope, "metadata");
                    }
                });
                $scope.savePlaylist = function() {
                    playList.save();
                };
            }
        };

        return definitions;
    }]).directive('playlistProgress', ['$rootScope', 'youtubePlayer', function($rootScope, youtubePlayer) {
        var definitions = {
            restrict: 'E',
            templateUrl: '/html/playlist/progress.html',
            replace: true,
            scope: {
                progress: '=',
                duration: '@'
            },
            link: function($scope, $element, $attrs) {
                $element.on('click', function(e) {
                    var coords, time;

                    if (e.target.classList.contains('progress')) {
                        coords = mouseCoords(e);
                        time = $scope.duration * (coords.x / e.target.clientWidth);

                        youtubePlayer.seek(time);
                    }
                });
            }
        };

        return definitions;
    }]);
<|endoftext|>


<commit_before>// this is a script called from the extension
(function(Factlink, window) {
    var el = window.document.getElementById("factlink-opinion-holder");
    var opinion;

    if (el !== undefined) {
      opinion = el.getAttribute("data-opinion");

      el.parentNode.removeChild(el);
    }

    Factlink.createFactFromSelection(opinion);
})(window.Factlink, Factlink.global);
<commit_msg>removed unused script<commit_after><|endoftext|>


<commit_before>function Logs(main) {                                                                       'use strict';

    var that                  = this;
    this.main                 = main;
    this.logLimit             = 2000; //const

    this.logLinesCount        = 0;
    this.logLinesStart        = 0;

    var $logTable, $logOuter, $logPause;
    var logFilterHost = '', logFilterSeverity = '', logFilterMessage = '';
    var pause = {
        list: [],
        mode: false,
        counter: 0,
        overflow: false,
        $counterSpan: null
    };

    var hdr;

    this.prepare = function () {
        $logOuter = $('#log-outer');
        $logTable = $('#log-table');
        $logPause = $('#log-pause');

        hdr = IobListHeader('log-outer-header', {list: $logOuter, colWidthOffset: 1, prefix: 'log-filter'});
        hdr.doFilter = that.filter;

        hdr.add('combobox', 'from', 'host');
        hdr.add('text', 'Time');
        hdr.add('combobox', '', 'severity', [
            { val: "", name: 'debug' },
            { val: "silly", name: 'silly' },
            { val: "info", name: 'info' },
            { val: "warn", name: 'warn' },
            { val: "error", name: 'error' }
        ]).$filter.attr('title', _('severity'));
        hdr.add('edit', 'Message', 'message');

        $('#log-clear-on-disk').button({icons:{primary: 'ui-icon-trash'}, text: false}).click(function () {
            that.main.confirmMessage(_('Log file will be deleted. Are you sure?'), null, null, function (result) {
                if (result) {
                    that.main.socket.emit('sendToHost', main.currentHost, 'delLogs', null, function (err) {
                        if (err) {
                            that.main.showError(err);
                        } else {
                            that.clear();
                        }
                    });
                }
            });
        })/*.css({width: 20, height: 20})*/.addClass('ui-state-error');

        $('#log-refresh').button({icons:{primary: 'ui-icon-refresh'}, text: false}).click(function () {
            that.clear();
        });

        $logPause
            .button({icons:{primary: 'ui-icon-pause'}, text: false})
            //.css({height: 20})
            .attr('title', _('Pause output'))
            .click(function () {
                that.pause();
            });

        pause.$counterSpan = $logPause.find('ui-button-text');

        $('#log-clear').button({icons:{primary: 'ui-icon-close'}, text: false}).click(function () {
            that.clear(false);
        });

        $('#log-copy-text').click(function () {
            $('#log-copy-text').hide().html('');
            $('#tabs').show();
        });

        $('#log-copy').button({icons:{primary: 'ui-icon-copy'}, text: false}).click(function () {
            var text = '' + _('copy note') + '';
            $('#tabs').hide();
            $('#log-copy-text').show().html(text + '

' + $logTable.html() + '
');
            var lines = $('#log-copy-table').find('.log-column-4');
            for (var t = 0; t < lines.length; t++) {
                var q = $(lines[t]);
                q.html(q.attr('title'));
                q.attr('title', '');
            }
        });
    };

    function installColResize() {
        if (!$.fn.colResizable) return;
        if ($logOuter.is(':visible')) {
            $logOuter.colResizable({
                liveDrag: true,

                partialRefresh: true,
                marginLeft: 5,
                postbackSafe:true,

                onResize: function (event) {
                    return hdr.syncHeader();
                    // // read width of data.$tree and set the same width for header
                    // var thDest = $('#log-outer-header >thead>tr>th');	//if table headers are specified in its semantically correct tag, are obtained
                    // var thSrc = $outer.find('>tbody>tr:first>td');
                    // for (var i = 1; i < thSrc.length; i++) {
                    //     $(thDest[i]).attr('width', $(thSrc[i]).width());
                    // }
                }
            });
            hdr.syncHeader();
        } else {
            setTimeout(function () {
                installColResize();
            }, 200)
        }
    }

    this.resize = function (width, height) {
        //width = width;
    };

    // -------------------------------- Logs ------------------------------------------------------------
    this.init = function () {
        if (!this.main.currentHost) {
            setTimeout(function () {
                that.init();
            }, 100);
            return;
        }

        $logTable.html('');
        this.main.socket.emit('sendToHost', this.main.currentHost, 'getLogs', 200, function (lines) {
            setTimeout(function () {
                var message = {message: '', severity: 'debug', from: '', ts: ''};
                var size = lines ? lines.pop() : -1;
                if (size !== -1) {
                    size = parseInt(size);
                    $('#log-size').html((_('Log size:') + ' ' + ((size / (1024 * 1024)).toFixed(2) + ' MB ')).replace(/ /g, ' '));
                }
                for (var i = 0, len = lines.length; i < len; i++) {
                    if (!lines[i]) continue;
                    var line = lines[i];
                    // 2014-12-05 14:47:10.739 - info: iobroker  ERR! network In most cases you are behind a proxy or have bad network settings.npm ERR! network
                    if (line[4] === '-' && line[7] === '-') {
                        line             = line.replace(/(\[[0-9]+m)/g, '');
                        message.ts       = line.substring(0, 23);
                        line             = line.substring(27);

                        var pos          = line.indexOf(':');
                        message.severity = line.substring(0, pos);
                        if (message.severity.charCodeAt(message.severity.length - 1) === 27) message.severity = message.severity.substring(0, message.severity.length - 1);
                        if (message.severity.charCodeAt(0) === 27) message.severity = message.severity.substring(1);

                        line             = line.substring(pos + 2);
                        pos              = line.indexOf(' ');
                        message.from     = line.substring(0, pos);
                        message.message  = line.substring(pos);
                    } else {
                        message.message = line;
                    }
                    that.add(message);
                }

                installColResize();

                logFilterHost     = hdr.host.val();
                logFilterMessage  = hdr.message.val();
                logFilterSeverity = hdr.severity.val();
            }, 0);
        });
    };

    this.add = function (message) {
        // remove instance name from text
        if (message.message.substring(0, message.from.length) === message.from) {
            message.message = message.message.substring(message.from.length + 1);
        }

        if (pause.mode) {
            pause.list.push(message);
            pause.counter++;

            if (pause.counter > this.logLimit) {
                if (!pause.overflow) {
                    $logPause.addClass('ui-state-error')
                        .attr('title', _('Message buffer overflow. Losing oldest'));
                    pause.overflow = true;
                }
                pause.list.shift();
            }
            pause.$counterSpan.html(tdp(pause.counter));
            return;
        }

        //message = {message: msg, severity: level, from: this.namespace, ts: (new Date()).getTime()}
        if (this.logLinesCount >= this.logLimit) {
            var line = document.getElementById('log-line-' + (this.logLinesStart + 1));
            if (line) line.outerHTML = '';
            this.logLinesStart++;
        } else {
            this.logLinesCount++;
        }

        // if (message.from && this.logHosts.indexOf(message.from) === -1) {
        //     this.logHosts.push(message.from);
        //     this.logHosts.sort();
        //     this.$logFilterHost.html('<option value="">' + _('all') + '</option>');
        //     for (var i = 0; i < this.logHosts.length; i++) {
        //         this.$logFilterHost.append('<option value="' + this.logHosts[i].replace(/\./g, '-') + '" ' + ((this.logHosts[i] === this.logFilterHost) ? 'selected' : '') + '>' + this.logHosts[i] + '</option>');
        //     }
        // }

        if (message.from) {
            hdr.host.checkAddOption(message.from, function (o) {
                return { val: o.replace(/\./g, '-'), name: o };
            })
        }

        var visible = '';
        var from = message.from ? message.from.replace(/\./g, '-') : '';

        if (this.logFilterHost && this.logFilterHost !== from) visible = 'display: none';

        if (!visible && logFilterSeverity) {
            if (this.logFilterSeverity === 'debug' && message.severity === 'silly') {
                visible = 'display: none';
            } else if (this.logFilterSeverity === 'info' && (message.severity === 'debug' || message.severity === 'silly')) {
                visible = 'display: none';
            } else if (logFilterSeverity === 'warn' && message.severity !== 'warn' && message.severity !== 'error') {
                visible = 'display: none';
            } else if (logFilterSeverity === 'error' && message.severity !== 'error') {
                visible = 'display: none';
            }
        }

        if (!visible && logFilterMessage && message.message.indexOf(logFilterMessage) === -1) {
            visible = 'display: none';
        }

        if (message.severity === 'error') $('a[href="#tab-log"]').addClass('errorLog');

        var text = '
';
        text += '' + (message.from || '') + '	';
        text += '' + this.main.formatDate(message.ts) + '	';
        text += '' + message.severity + '	';
        text += '' + message.message.substring(0, 200) + '
';

        $logTable.prepend(text);
    };

    this.filter = function () {
        logFilterHost     = hdr.host.val();
        logFilterMessage  = hdr.message.val();
        logFilterSeverity = hdr.severity.val();

        if (logFilterSeverity === 'error') {
            $logOuter.find('.log-severity-silly').hide();
            $logOuter.find('.log-severity-debug').hide();
            $logOuter.find('.log-severity-info').hide();
            $logOuter.find('.log-severity-warn').hide();
            $logOuter.find('.log-severity-error').show();
        } else
        if (logFilterSeverity === 'warn') {
            $logOuter.find('.log-severity-silly').hide();
            $logOuter.find('.log-severity-debug').hide();
            $logOuter.find('.log-severity-info').hide();
            $logOuter.find('.log-severity-warn').show();
            $logOuter.find('.log-severity-error').show();
        } else
        if (that.logFilterSeverity === 'info') {
            $logOuter.find('.log-severity-silly').hide();
            $logOuter.find('.log-severity-debug').hide();
            $logOuter.find('.log-severity-info').show();
            $logOuter.find('.log-severity-warn').show();
            $logOuter.find('.log-severity-error').show();
        } else
        if (logFilterSeverity === 'silly') {
            $logOuter.find('.log-severity-silly').show();
            $logOuter.find('.log-severity-debug').show();
            $logOuter.find('.log-severity-info').show();
            $logOuter.find('.log-severity-warn').show();
            $logOuter.find('.log-severity-error').show();
        } else {
            $logOuter.find('.log-severity-silly').hide();
            $logOuter.find('.log-severity-debug').show();
            $logOuter.find('.log-severity-info').show();
            $logOuter.find('.log-severity-warn').show();
            $logOuter.find('.log-severity-error').show();
        }

        if (logFilterHost || logFilterMessage) {
            $logOuter.find('.log-line').each(function () {
                if (logFilterHost && !$(this).hasClass('log-from-' + logFilterHost)) {
                    $(this).hide();
                } else if (logFilterMessage && $(this).html().indexOf(logFilterMessage) === -1) {
                    $(this).hide();
                }
            });
        }
    };

    this.clear = function (isReload) {
        if (isReload === undefined) isReload = true;
        $logTable.html('');
        this.logLinesCount = 0;
        this.logLinesStart = 0;
        $('a[href="#tab-log"]').removeClass('errorLog');

        if (isReload) {
            setTimeout(function () {
                that.init();
            }, 0);
        }
    };

    this.pause = function () {
        if (!pause.mode) {
            $logPause
                .addClass('ui-state-focus ui-state-error log-pause-button-active')
                .button('option', 'text', true)
                .button('option', 'icons', {primary: null});

            pause.$counterSpan = $logPause.find('.ui-button-text');
            pause.$counterSpan.addClass().html('0');
            pause.counter  = 0;
            pause.mode     = true;
        } else {
            pause.mode     = false;
            for (var i = 0; i < pause.list.length; i++) {
                this.add(pause.list[i]);
            }
            pause.overflow = false;
            pause.list.length = 0;
            pause.counter  = 0;

            $logPause
                .removeClass('ui-state-error ui-state-focus')
                .removeClass('log-pause-button-active')
                .attr('title', _('Pause output'))
                .button('option', 'text', false).button('option', 'icons', {primary: 'ui-icon-pause'});
        }
    };
}
<commit_msg>(bluefox) delete adminLog.js<commit_after><|endoftext|>


<commit_before>import d3 from 'd3';

const render = (options) => {
  const {width, height, timeDomain, temperatureDomain} = options,
        leftMargin = 50,
        rightMargin = 50,
        topMargin = 50,
        bottomMargin = 50,
        contentsWidth = width - leftMargin - rightMargin,
        contentsHeight = height - topMargin - bottomMargin,
        ratio = 20,
        timeScale = d3.time.scale()
          .domain(timeDomain)
          .range([0, contentsWidth * ratio])
          .nice(),
        temperatureScale = d3.scale.linear()
          .domain(temperatureDomain)
          .range([contentsHeight, 0]),
        temperatureColor = d3.scale.quantize()
          .domain([10, 30])
          .range([
            d3.hsl(240, 0.8, 0.5),
            d3.hsl(200, 0.8, 0.5),
            d3.hsl(160, 0.8, 0.5),
            d3.hsl(120, 0.8, 0.5),
            d3.hsl(80, 0.8, 0.5),
            d3.hsl(40, 0.8, 0.5),
            d3.hsl(0, 0.8, 0.5)
          ]),
        timeAxis = d3.svg.axis()
          .scale(timeScale)
          .ticks(240)
          .orient('bottom'),
        temperatureAxis = d3.svg.axis()
          .scale(temperatureScale)
          .orient('left');

  const initialize = (svg) => {
    svg.append('clipPath')
      .attr('id', 'contents-region')
      .append('rect')
      .attr({
        x: 0,
        y: 0,
        width: contentsWidth,
        height: contentsHeight
      });
    svg.append('clipPath')
      .attr('id', 'time-axis-region')
      .append('rect')
      .attr({
        x: 0,
        y: 0,
        width: contentsWidth + rightMargin,
        height: bottomMargin
      });

    const contentsWrapper = svg.append('g')
            .classed('contents-wrapper', true)
            .attr({
              'clip-path': 'url(#contents-region)',
              transform: `translate(${leftMargin},${topMargin})`
            }),
          contents = contentsWrapper.append('g')
            .classed('contents', true)
            .attr('transform', `translate(${-contentsWidth * (ratio - 1)},0)`),
          timeAxisWrapper = svg.append('g')
            .classed('time-axis-wrapper', true)
            .attr({
              'clip-path': 'url(#time-axis-region)',
              transform: `translate(${leftMargin},${height - bottomMargin})`
            }),
          timeAxisG = timeAxisWrapper.append('g')
            .classed('time-axis', true)
            .attr('transform', `translate(${-contentsWidth * (ratio - 1)},0)`)
            .call(timeAxis);
    svg.append('g')
      .classed('temperature-axis', true)
      .attr('transform', `translate(${leftMargin},${topMargin})`)
      .call(temperatureAxis);
    svg.selectAll('g.tick line')
      .attr('stroke', 'black');
    svg.selectAll('path.domain')
      .attr({
        stroke: 'black',
        fill: 'none'
      });

    const zoom = d3.behavior.zoom()
      .scaleExtent([1, 1])
      .translate([-contentsWidth * (ratio - 1), 0])
      .on('zoom', function () {
        const e = d3.event;
        let x = e.translate[0];
        if (x < -contentsWidth * (ratio - 1)) {
          x = -contentsWidth * (ratio - 1);
          zoom.translate([x, 0]);
        }
        contents
          .attr('transform', `translate(${x},0)`);
        timeAxisG
          .attr('transform', `translate(${x},0)`);
      });
    svg.call(zoom);
  };

  return (selection) => {
    selection.each(function (records) {
      const svg = d3.select(this);
      if (svg.select('g.contents').empty()) {
        initialize(svg);
      }
      svg.select('g.contents')
        .selectAll('g.points')
        .data(records, (d) => d.$id)
        .enter()
        .append('g')
        .classed('points', true)
        .attr('transform', (d) => `translate(${timeScale(d.timestamp)},${height - topMargin - bottomMargin})`)
        .append('circle')
        .attr({
          fill: (d) => temperatureColor(d.temperature),
          r: 5
        });
    });

    selection.selectAll('g.points')
      .attr('transform', (d) => `translate(${timeScale(d.timestamp)},${temperatureScale(d.temperature)})`);
    selection.select('g.time-axis')
      .call(timeAxis);
    selection.select('g.temperature-axis')
      .call(temperatureAxis);
  };
};

export default render;
<commit_msg>Vertical scroll<commit_after>import d3 from 'd3';

const render = (options) => {
  const {width, height, timeDomain, temperatureDomain} = options,
        leftMargin = 50,
        rightMargin = 50,
        topMargin = 50,
        bottomMargin = 50,
        contentsWidth = width - leftMargin - rightMargin,
        contentsHeight = height - topMargin - bottomMargin,
        xRatio = 20,
        yRatio = 4,
        timeScale = d3.time.scale()
          .domain(timeDomain)
          .range([0, contentsWidth * xRatio])
          .nice(),
        temperatureScale = d3.scale.linear()
          .domain(temperatureDomain)
          .range([contentsHeight * yRatio, 0]),
        temperatureColor = d3.scale.quantize()
          .domain([10, 30])
          .range([
            d3.hsl(240, 0.8, 0.5),
            d3.hsl(200, 0.8, 0.5),
            d3.hsl(160, 0.8, 0.5),
            d3.hsl(120, 0.8, 0.5),
            d3.hsl(80, 0.8, 0.5),
            d3.hsl(40, 0.8, 0.5),
            d3.hsl(0, 0.8, 0.5)
          ]),
        timeAxis = d3.svg.axis()
          .scale(timeScale)
          .ticks(12 * xRatio)
          .orient('bottom'),
        temperatureAxis = d3.svg.axis()
          .scale(temperatureScale)
          .ticks(40)
          .orient('left');

  const initialize = (svg) => {
    svg.append('clipPath')
      .attr('id', 'contents-region')
      .append('rect')
      .attr({
        x: 0,
        y: -topMargin,
        width: contentsWidth + rightMargin,
        height: contentsHeight + topMargin
      });
    svg.append('clipPath')
      .attr('id', 'time-axis-region')
      .append('rect')
      .attr({
        x: 0,
        y: 0,
        width: contentsWidth + rightMargin,
        height: bottomMargin
      });
    svg.append('clipPath')
      .attr('id', 'temperature-axis-region')
      .append('rect')
      .attr({
        x: -leftMargin,
        y: -topMargin,
        width: leftMargin,
        height: height
      });

    const contentsWrapper = svg.append('g')
            .classed('contents-wrapper', true)
            .attr({
              'clip-path': 'url(#contents-region)',
              transform: `translate(${leftMargin},${topMargin})`
            }),
          contents = contentsWrapper.append('g')
            .classed('contents', true)
            .attr('transform', `translate(${contentsWidth * (1 - xRatio)},${contentsHeight * (3 - yRatio)})`),
          timeAxisWrapper = svg.append('g')
            .classed('time-axis-wrapper', true)
            .attr({
              'clip-path': 'url(#time-axis-region)',
              transform: `translate(${leftMargin},${height - bottomMargin})`
            }),
          timeAxisG = timeAxisWrapper.append('g')
            .classed('time-axis', true)
            .attr('transform', `translate(${contentsWidth * (1 - xRatio)},0)`)
            .call(timeAxis),
          temperatureAxisWrapper = svg.append('g')
            .classed('temperature-axis-wrapper', true)
            .attr({
              'clip-path': 'url(#temperature-axis-region)',
              transform: `translate(${leftMargin},${topMargin})`
            }),
          temperatureAxiG = temperatureAxisWrapper.append('g')
            .classed('temperature-axis', true)
            .attr('transform', `translate(0,${contentsHeight * (3 - yRatio)})`)
            .call(temperatureAxis);
    svg.selectAll('g.tick line')
      .attr('stroke', 'black');
    svg.selectAll('path.domain')
      .attr({
        stroke: 'black',
        fill: 'none'
      });

    const zoom = d3.behavior.zoom()
      .scaleExtent([1, 1])
      .translate([contentsWidth * (1 - xRatio), contentsHeight * (3 - yRatio)])
      .on('zoom', function () {
        const e = d3.event,
              x = Math.min(Math.max(e.translate[0], contentsWidth * (1 - xRatio)), 0),
              y = Math.min(Math.max(e.translate[1], contentsHeight * (1 - yRatio)), 0);
        zoom.translate([x, y]);
        contents
          .attr('transform', `translate(${x},${y})`);
        timeAxisG
          .attr('transform', `translate(${x},0)`);
        temperatureAxiG
          .attr('transform', `translate(0,${y})`);
      });
    svg.call(zoom);
  };

  return (selection) => {
    selection.each(function (records) {
      const svg = d3.select(this);
      if (svg.select('g.contents').empty()) {
        initialize(svg);
      }
      svg.select('g.contents')
        .selectAll('g.points')
        .data(records, (d) => d.$id)
        .enter()
        .append('g')
        .classed('points', true)
        .attr('transform', (d) => `translate(${timeScale(d.timestamp)},${temperatureScale(20)})`)
        .append('circle')
        .attr({
          fill: (d) => temperatureColor(d.temperature),
          r: 5
        });
    });

    selection.selectAll('g.points')
      .attr('transform', (d) => `translate(${timeScale(d.timestamp)},${temperatureScale(d.temperature)})`);
    selection.select('g.time-axis')
      .call(timeAxis);
    selection.select('g.temperature-axis')
      .call(temperatureAxis);
  };
};

export default render;
<|endoftext|>


<commit_before>var react = require('react')
  , pellet = require('./pellet')
  , utils = require('./utils')
  , isolator = require('./isolator')
  , pipeline = require('./isomorphic/pipeline');

// options.context options.mode=MODE_HTML, options.dom =

var pelletRender = module.exports = {
  MODE_STRING: 'static',
  MODE_HTML: 'markup',
  MODE_DOM: 'dom',

  /**
   * Render the component for both the server and browser
   *
   * @param component
   * @param options (mode: targetEl:, context: or props:)
   * @param next
   */
  renderComponent: function(component, options, next) {
    if(typeof options == 'function') {
      next = options;
      options = {};
    } else if(!options) {
      options = {};
    }

    if(!component || !next) {
      throw new Error('the component and next are required')
    }

    // default the mode using the environment so if in browser use
    // DOM render else render full html with react-ids
    if(!options.mode) {
      if(process.env.BROWSER_ENV) {
        options.mode = pelletRender.MODE_DOM;
      } else {
        options.mode = pelletRender.MODE_HTML;
      }
    }

    var instrument = pellet.instrumentation.namespace('isorender.');
    var mesure = instrument.elapseTimer();
    instrument.increment('isorender.count');

    function renderReactComponent(component, ctx) {
      var result;

      try {
        if(options.mode == pelletRender.MODE_DOM && process.env.BROWSER_ENV) {
          if(!options.targetEl) {
            options.targetEl = document.getElementById('__PELLET__');
            if(!options.targetEl) {
              options.targetEl = document.body;
            }
          }

          react.unmountComponentAtNode(options.targetEl);
          //mesure.mark('react_unmount');

          // only add touch events if the device support it
          if ('ontouchstart' in document.documentElement) {
            react.initializeTouchEvents(true);
          }

          result = react.render(component, options.targetEl);
        } else if(options.mode == pelletRender.MODE_STRING) {
          result = react.renderToStaticMarkup(component);
        } else if(options.mode == pelletRender.MODE_HTML) {
          result = react.renderToString(component);
        }
        mesure.mark('react_render');
      } catch(ex) {
        next(ex);
        pellet.instrumentation.increment('isorender.error');
        return;
      }

      next(null, result, ctx);
    }

    var componentWithContext;

    // get the serialize state if component has a onRoute function
    if (component._$construction) {

      try {
        // create a pipeline to render the component and track its state.
        // options.context is the serialized data from the server
        // options.http is isomorphic req/res to
        var pipe = new pipeline(options.context, options.http, options.isolatedConfig, options.requestContext, options.locales);

        // update the pipe props because we got them in our options
        // the route function sets things like originalUrl, params, etc.
        // so the __$onRoute can know about the route that was triggered
        if(options.props) {
          pipe.setProps(options.props);
        }

        mesure.mark('create_pipeline');

        // now run the pre-flight code before asking react to render
        // this allows for async code to be executed and tracks any
        // data that needs to get serialized to the client.
        component._$construction.call(pipe, {}, function (err) {
          mesure.mark('component_construction');

          if(err) {
            instrument.increment('isorender.err');
            return next(err);
          }

          if(pipe.abortRender) {
            pipe.release();
            mesure.mark('release');
            instrument.increment('isorender.abort');
            renderReactComponent(componentWithContext, pipe);
            return next();
          }

          // make sure the react context has locales to pick the
          // rendered language. Then render the element with the
          // props from the __$onRoute.
          try {
            componentWithContext = react.withContext({
              rootIsolator: new isolator(null, null, null, pipe.rootIsolator.isolatedConfig),
              requestContext: options.requestContext,
              locales: options.locales
            }, function () {
              return React.createElement(component, pipe.props);
            });
          } catch(ex) {
            next(ex);
            return;
          }

          // wait a tick so all kefir emit get processed for the
          // pipe serialization.
          //setTimeout(function() {
            pipe.release();
            mesure.mark('release');
            renderReactComponent(componentWithContext, pipe);
          //}, 0);
        });
      } catch(ex) {
        console.error('Error in trying to render component because:', ex.message);

        pipe.release();
        next(ex);
      }
    } else {

      try {
        componentWithContext = react.withContext({
          rootIsolator: new isolator(null, null, null, options.isolatedConfig),
          requestContext: options.requestContext,
          locales: options.locales
        }, function () {
          var props;

          if(options.context && options.context.props) {
            if(options.props) {
              props = {};
              utils.objectUnion([options.context.props, options.props], props);
            } else {
              props = options.context.props;
            }
          } else if(options.props) {
            props = options.props;
          }

          return React.createElement(component, props);
        });
      } catch(ex) {
        next(ex);
        return;
      }

      renderReactComponent(componentWithContext, {
        toJSON: function() {
          try {
            return JSON.stringify({
              requestContext: options.requestContext,
              props: null,
              coordinatorState: null
            });
          } catch(ex) {
            console.error("Cannot serialize isomorphic context because:", ex.message);
            throw ex;
          }
        }
      });
    }
  }
};
<commit_msg>fix: do not render in pipeline's abortRender flag is set to true<commit_after>var react = require('react')
  , pellet = require('./pellet')
  , utils = require('./utils')
  , isolator = require('./isolator')
  , pipeline = require('./isomorphic/pipeline');

// options.context options.mode=MODE_HTML, options.dom =

var pelletRender = module.exports = {
  MODE_STRING: 'static',
  MODE_HTML: 'markup',
  MODE_DOM: 'dom',

  /**
   * Render the component for both the server and browser
   *
   * @param component
   * @param options (mode: targetEl:, context: or props:)
   * @param next
   */
  renderComponent: function(component, options, next) {
    if(typeof options == 'function') {
      next = options;
      options = {};
    } else if(!options) {
      options = {};
    }

    if(!component || !next) {
      throw new Error('the component and next are required')
    }

    // default the mode using the environment so if in browser use
    // DOM render else render full html with react-ids
    if(!options.mode) {
      if(process.env.BROWSER_ENV) {
        options.mode = pelletRender.MODE_DOM;
      } else {
        options.mode = pelletRender.MODE_HTML;
      }
    }

    var instrument = pellet.instrumentation.namespace('isorender.');
    var mesure = instrument.elapseTimer();
    instrument.increment('isorender.count');

    function renderReactComponent(component, ctx) {
      var result;

      try {
        if(options.mode == pelletRender.MODE_DOM && process.env.BROWSER_ENV) {
          if(!options.targetEl) {
            options.targetEl = document.getElementById('__PELLET__');
            if(!options.targetEl) {
              options.targetEl = document.body;
            }
          }

          react.unmountComponentAtNode(options.targetEl);
          //mesure.mark('react_unmount');

          // only add touch events if the device support it
          if ('ontouchstart' in document.documentElement) {
            react.initializeTouchEvents(true);
          }

          result = react.render(component, options.targetEl);
        } else if(options.mode == pelletRender.MODE_STRING) {
          result = react.renderToStaticMarkup(component);
        } else if(options.mode == pelletRender.MODE_HTML) {
          result = react.renderToString(component);
        }
        mesure.mark('react_render');
      } catch(ex) {
        next(ex);
        pellet.instrumentation.increment('isorender.error');
        return;
      }

      next(null, result, ctx);
    }

    var componentWithContext;

    // get the serialize state if component has a onRoute function
    if (component._$construction) {

      try {
        // create a pipeline to render the component and track its state.
        // options.context is the serialized data from the server
        // options.http is isomorphic req/res to
        var pipe = new pipeline(options.context, options.http, options.isolatedConfig, options.requestContext, options.locales);

        // update the pipe props because we got them in our options
        // the route function sets things like originalUrl, params, etc.
        // so the __$onRoute can know about the route that was triggered
        if(options.props) {
          pipe.setProps(options.props);
        }

        mesure.mark('create_pipeline');

        // now run the pre-flight code before asking react to render
        // this allows for async code to be executed and tracks any
        // data that needs to get serialized to the client.
        component._$construction.call(pipe, {}, function (err) {
          mesure.mark('component_construction');

          if(err) {
            instrument.increment('isorender.err');
            return next(err);
          }

          if(pipe.abortRender) {
            pipe.release();
            mesure.mark('release');
            instrument.increment('isorender.abort');
            return next(null, null, pipe);
          }

          // make sure the react context has locales to pick the
          // rendered language. Then render the element with the
          // props from the __$onRoute.
          try {
            componentWithContext = react.withContext({
              rootIsolator: new isolator(null, null, null, pipe.rootIsolator.isolatedConfig),
              requestContext: options.requestContext,
              locales: options.locales
            }, function () {
              return React.createElement(component, pipe.props);
            });
          } catch(ex) {
            next(ex);
            return;
          }

          // wait a tick so all kefir emit get processed for the
          // pipe serialization.
          //setTimeout(function() {
            pipe.release();
            mesure.mark('release');
            renderReactComponent(componentWithContext, pipe);
          //}, 0);
        });
      } catch(ex) {
        console.error('Error in trying to render component because:', ex.message);

        pipe.release();
        next(ex);
      }
    } else {

      try {
        componentWithContext = react.withContext({
          rootIsolator: new isolator(null, null, null, options.isolatedConfig),
          requestContext: options.requestContext,
          locales: options.locales
        }, function () {
          var props;

          if(options.context && options.context.props) {
            if(options.props) {
              props = {};
              utils.objectUnion([options.context.props, options.props], props);
            } else {
              props = options.context.props;
            }
          } else if(options.props) {
            props = options.props;
          }

          return React.createElement(component, props);
        });
      } catch(ex) {
        next(ex);
        return;
      }

      renderReactComponent(componentWithContext, {
        toJSON: function() {
          try {
            return JSON.stringify({
              requestContext: options.requestContext,
              props: null,
              coordinatorState: null
            });
          } catch(ex) {
            console.error("Cannot serialize isomorphic context because:", ex.message);
            throw ex;
          }
        }
      });
    }
  }
};
<|endoftext|>


<commit_before>var R = _.repeat = {
    id: 'x-repeat-id',
    each: 'x-repeat-each',
    count: 0,
    init: function(el, keep) {
        var selector = el.getAttribute('x-repeat'),
            id = R.count++,
            content = selector && D.query(selector).cloneNode(true) || el,
            anchor = D.createElement('x-repeat');
        content.setAttribute(R.id, id);
        anchor.setAttribute(R.id, id);
        for (var i=0,m=el.attributes.length; i<m; i++) {
            var attr = el.attributes[i];
            if (attr.name === 'x-repeat-none') {
                anchor.value = attr.value || el.innerHTML;
            }
            anchor.setAttribute(attr.name, attr.value);
        }
        R.parent(el).insertBefore(anchor, el.nextSibling);
        _.defprop(anchor, 'content', R[id] = content);
        if (keep !== true) {
            el.remove();
        }
        return id;
    },
    parent: function(el) {
        if (!el.parentNode) {
            D.createDocumentFragment().appendChild(el);
        }
        return el.parentNode;
    },
    repeat: function(parent, anchor, content, val) {
        var repeat = content.cloneNode(true);
        if (val !== undefined && val !== null) {
            repeat.xValue = val;
        }
        if (repeat.hasAttribute(R.each)) {
            repeat.getAttribute(R.each)
                .split(',')
                .forEach(function(call) {
                    _.resolve(call, window, [repeat, val]);
                });
        }
        parent.insertBefore(repeat, anchor);
        return repeat;
    },
    style: D.head.append('style')
};

X.add('repeat', function repeat(val) {
    var parent = R.parent(this),
        id = this.getAttribute(R.id) || R.init(this, true),
        selector = '['+R.id+'="'+id+'"]',
        selectAll = selector+':not(x-repeat)';
    if (val === false) {
        return parent.queryAll(selectAll).remove();
    }
    var anchor = parent.query('x-repeat'+selector),
        content = anchor.content || R[id];
    if (anchor.hasAttribute('x-repeat-first')) {
        anchor = parent.query(selector+'[x-index]') || anchor;
    }
    var ret = Array.isArray(val) ?
        val.map(function(v){ return R.repeat(parent, anchor, content, v); }) :
        R.repeat(parent, anchor, content, val);
    parent.queryAll(selectAll).each('setAttribute', 'x-index', '${i}');
    return ret;
}, [Element]);

R.style.textContent = '[x-repeat] { display: none }';
D.addEventListener('DOMContentLoaded', function() {
    D.queryAll('[x-repeat]').each(R.init);
    R.style.textContent = "\nx-repeat { display: none }"+
                          "\nx-repeat[x-repeat-none] { display: inline-block; }"+
                          "\n["+R.id+"] + x-repeat[x-repeat-none] { display: none; }";
});
<commit_msg>run callback post-insert<commit_after>var R = _.repeat = {
    id: 'x-repeat-id',
    each: 'x-repeat-each',
    count: 0,
    init: function(el, keep) {
        var selector = el.getAttribute('x-repeat'),
            id = R.count++,
            content = selector && D.query(selector).cloneNode(true) || el,
            anchor = D.createElement('x-repeat');
        content.setAttribute(R.id, id);
        anchor.setAttribute(R.id, id);
        for (var i=0,m=el.attributes.length; i<m; i++) {
            var attr = el.attributes[i];
            if (attr.name === 'x-repeat-none') {
                anchor.value = attr.value || el.innerHTML;
            }
            anchor.setAttribute(attr.name, attr.value);
        }
        R.parent(el).insertBefore(anchor, el.nextSibling);
        _.defprop(anchor, 'content', R[id] = content);
        if (keep !== true) {
            el.remove();
        }
        return id;
    },
    parent: function(el) {
        if (!el.parentNode) {
            D.createDocumentFragment().appendChild(el);
        }
        return el.parentNode;
    },
    repeat: function(parent, anchor, content, val) {
        var repeat = content.cloneNode(true);
        if (val !== undefined && val !== null) {
            repeat.xValue = val;
        }
        parent.insertBefore(repeat, anchor);
        if (repeat.hasAttribute(R.each)) {
            repeat.getAttribute(R.each)
                .split(',')
                .forEach(function(call) {
                    _.resolve(call, window, [repeat, val]);
                });
        }
        return repeat;
    },
    style: D.head.append('style')
};

X.add('repeat', function repeat(val) {
    var parent = R.parent(this),
        id = this.getAttribute(R.id) || R.init(this, true),
        selector = '['+R.id+'="'+id+'"]',
        selectAll = selector+':not(x-repeat)';
    if (val === false) {
        return parent.queryAll(selectAll).remove();
    }
    var anchor = parent.query('x-repeat'+selector),
        content = anchor.content || R[id];
    if (anchor.hasAttribute('x-repeat-first')) {
        anchor = parent.query(selector+'[x-index]') || anchor;
    }
    var ret = Array.isArray(val) ?
        val.map(function(v){ return R.repeat(parent, anchor, content, v); }) :
        R.repeat(parent, anchor, content, val);
    parent.queryAll(selectAll).each('setAttribute', 'x-index', '${i}');
    return ret;
}, [Element]);

R.style.textContent = '[x-repeat] { display: none }';
D.addEventListener('DOMContentLoaded', function() {
    D.queryAll('[x-repeat]').each(R.init);
    R.style.textContent = "\nx-repeat { display: none }"+
                          "\nx-repeat[x-repeat-none] { display: inline-block; }"+
                          "\n["+R.id+"] + x-repeat[x-repeat-none] { display: none; }";
});
<|endoftext|>


<commit_before>/*
 * JavaScript tracker for Snowplow: queue.js
 *
 * Significant portions copyright 2010 Anthon Pang. Remainder copyright
 * 2012-2014 Snowplow Analytics Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Anthon Pang nor Snowplow Analytics Ltd nor the
 *   names of their contributors may be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

;(function() {

	var
		lodash = require('./lib_managed/lodash'),
		helpers = require('./lib/helpers'),

		object = typeof exports !== 'undefined' ? exports : this; // For eventual node.js environment support

	/************************************************************
	 * Proxy object
	 * - this allows the caller to continue push()'ing to _snaq
	 *   after the Tracker has been initialized and loaded
	 ************************************************************/

	object.InQueueManager = function(TrackerConstructor, version, mutSnowplowState, asyncQueue, functionName) {

		var trackerDictionary = {},
			usedCookieNames = {};

		/**
		 * Get an array of trackers to which a function should be applied.
		 *
		 * @param array names List of namespaces to use. If empty, use all namespaces.
		 */
		function getNamedTrackers(names) {
			var namedTrackers = [];

			if (!names || names.length === 0) {
				namedTrackers = lodash.map(trackerDictionary);
			} else {
				for (var i = 0; i < names.length; i++) {
					if (trackerDictionary.hasOwnProperty(names[i])) {
						namedTrackers.push(trackerDictionary[names[i]]);
					} else {
						helpers.warn('Warning: Tracker namespace "' + names[i] + '" not configured');
					}
				}
			}

			if (namedTrackers.length === 0) {
				helpers.warn('Warning: No tracker configured');
			}

			return namedTrackers;
		}

		/**
		 * Legacy support for input of the form _snaq.push(['setCollectorCf', 'd34uzc5hjrimh8'])
		 *
		 * @param string f Either 'setCollectorCf' or 'setCollectorUrl'
		 * @param string endpoint
		 * @param string namespace Optional tracker name
		 *
		 * TODO: remove this in 2.1.0
		 */
		function legacyCreateNewNamespace(f, endpoint, namespace) {
			helpers.warn(f + ' is deprecated. Set the collector when a new tracker instance using newTracker.');

			var name;

			if (lodash.isUndefined(namespace)) {
				name = 'sp';
			} else {
				name = namespace;
			}

			createNewNamespace(name);
			trackerDictionary[name][f](endpoint);
		}

		/**
		 * Initiate a new tracker namespace
		 *
		 * @param string namespace
		 * @param string endpoint Of the form d3rkrsqld9gmqf.cloudfront.net
		 */
		function createNewNamespace(namespace, endpoint, argmap) {
			argmap = argmap || {};
			if ((!argmap.writeCookies) && (argmap.cookieName in usedCookieNames)) {
				argmap.writeCookies = false;
			} else {
				usedCookieNames[argmap.cookieName] = true;
			}
			trackerDictionary[namespace] = new TrackerConstructor(functionName, namespace, version, mutSnowplowState, argmap);
			trackerDictionary[namespace].setCollectorUrl(endpoint);
		}

		/**
		 * Output an array of the form ['functionName', [trackerName1, trackerName2, ...]]
		 *
		 * @param string inputString
		 */
		function parseInputString(inputString) {
			var separatedString = inputString.split(':'),
				extractedFunction = separatedString[0],
				extractedNames = (separatedString.length > 1) ? separatedString[1].split(';') : [];

			return [extractedFunction, extractedNames];
		}

		/**
		 * apply wrapper
		 *
		 * @param array parameterArray An array comprising either:
		 *      [ 'methodName', optional_parameters ]
		 * or:
		 *      [ functionObject, optional_parameters ]
		 */
		function applyAsyncFunction() {
			var i, j, f, parameterArray, input, parsedString, names, namedTrackers;

			// Outer loop in case someone push'es in zarg of arrays
			for (i = 0; i < arguments.length; i += 1) {
				parameterArray = arguments[i];

				// Arguments is not an array, so we turn it into one
				input = Array.prototype.shift.call(parameterArray);

				// Custom callback rather than tracker method
				if (lodash.isFunction(input)) {
					input.apply(this, parameterArray);
					continue;
				}

				parsedString = parseInputString(input);
				f = parsedString[0];
				names = parsedString[1];

				if (f === 'newTracker') {
					createNewNamespace(parameterArray[0], parameterArray[1], parameterArray[2]);
					continue;
				}

				if ((f === 'setCollectorCf' || f === 'setCollectorUrl') && (!names || names.length === 0)) {
					legacyCreateNewNamespace(f, parameterArray[0], parameterArray[1]);
					continue;
				}

				namedTrackers = getNamedTrackers(names);

				if (lodash.isString(f)) {
					for (j = 0; j < namedTrackers.length; j++) {
						namedTrackers[j][f].apply(namedTrackers[j], parameterArray);
					}
				} else {
					for (j = 0; j < namedTrackers.length; j++) {
						f.apply(namedTrackers[j], parameterArray);
					}
				}
			}
		}

		// We need to manually apply any events collected before this initialization
		for (var i = 0; i < asyncQueue.length; i++) {
			applyAsyncFunction(asyncQueue[i]);
		}

		return {
			push: applyAsyncFunction
		};
	};

}());
<commit_msg>Use tracker as context for onload callbacks, call once per tracker<commit_after>/*
 * JavaScript tracker for Snowplow: queue.js
 *
 * Significant portions copyright 2010 Anthon Pang. Remainder copyright
 * 2012-2014 Snowplow Analytics Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Anthon Pang nor Snowplow Analytics Ltd nor the
 *   names of their contributors may be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

;(function() {

	var
		lodash = require('./lib_managed/lodash'),
		helpers = require('./lib/helpers'),

		object = typeof exports !== 'undefined' ? exports : this; // For eventual node.js environment support

	/************************************************************
	 * Proxy object
	 * - this allows the caller to continue push()'ing to _snaq
	 *   after the Tracker has been initialized and loaded
	 ************************************************************/

	object.InQueueManager = function(TrackerConstructor, version, mutSnowplowState, asyncQueue, functionName) {

		var trackerDictionary = {},
			usedCookieNames = {};

		/**
		 * Get an array of trackers to which a function should be applied.
		 *
		 * @param array names List of namespaces to use. If empty, use all namespaces.
		 */
		function getNamedTrackers(names) {
			var namedTrackers = [];

			if (!names || names.length === 0) {
				namedTrackers = lodash.map(trackerDictionary);
			} else {
				for (var i = 0; i < names.length; i++) {
					if (trackerDictionary.hasOwnProperty(names[i])) {
						namedTrackers.push(trackerDictionary[names[i]]);
					} else {
						helpers.warn('Warning: Tracker namespace "' + names[i] + '" not configured');
					}
				}
			}

			if (namedTrackers.length === 0) {
				helpers.warn('Warning: No tracker configured');
			}

			return namedTrackers;
		}

		/**
		 * Legacy support for input of the form _snaq.push(['setCollectorCf', 'd34uzc5hjrimh8'])
		 *
		 * @param string f Either 'setCollectorCf' or 'setCollectorUrl'
		 * @param string endpoint
		 * @param string namespace Optional tracker name
		 *
		 * TODO: remove this in 2.1.0
		 */
		function legacyCreateNewNamespace(f, endpoint, namespace) {
			helpers.warn(f + ' is deprecated. Set the collector when a new tracker instance using newTracker.');

			var name;

			if (lodash.isUndefined(namespace)) {
				name = 'sp';
			} else {
				name = namespace;
			}

			createNewNamespace(name);
			trackerDictionary[name][f](endpoint);
		}

		/**
		 * Initiate a new tracker namespace
		 *
		 * @param string namespace
		 * @param string endpoint Of the form d3rkrsqld9gmqf.cloudfront.net
		 */
		function createNewNamespace(namespace, endpoint, argmap) {
			argmap = argmap || {};
			if ((!argmap.writeCookies) && (argmap.cookieName in usedCookieNames)) {
				argmap.writeCookies = false;
			} else {
				usedCookieNames[argmap.cookieName] = true;
			}
			trackerDictionary[namespace] = new TrackerConstructor(functionName, namespace, version, mutSnowplowState, argmap);
			trackerDictionary[namespace].setCollectorUrl(endpoint);
		}

		/**
		 * Output an array of the form ['functionName', [trackerName1, trackerName2, ...]]
		 *
		 * @param string inputString
		 */
		function parseInputString(inputString) {
			var separatedString = inputString.split(':'),
				extractedFunction = separatedString[0],
				extractedNames = (separatedString.length > 1) ? separatedString[1].split(';') : [];

			return [extractedFunction, extractedNames];
		}

		/**
		 * apply wrapper
		 *
		 * @param array parameterArray An array comprising either:
		 *      [ 'methodName', optional_parameters ]
		 * or:
		 *      [ functionObject, optional_parameters ]
		 */
		function applyAsyncFunction() {
			var i, j, f, parameterArray, input, parsedString, names, namedTrackers;

			// Outer loop in case someone push'es in zarg of arrays
			for (i = 0; i < arguments.length; i += 1) {
				parameterArray = arguments[i];

				// Arguments is not an array, so we turn it into one
				input = Array.prototype.shift.call(parameterArray);

				// Custom callback rather than tracker method, called for each named tracker
				if (lodash.isFunction(input)) {
					var allNamedTrackers = getNamedTrackers()
					for (j = 0; j < allNamedTrackers.length; j++) {
						input.apply(allNamedTrackers[j], parameterArray);
					}
					continue;
				}

				parsedString = parseInputString(input);
				f = parsedString[0];
				names = parsedString[1];

				if (f === 'newTracker') {
					createNewNamespace(parameterArray[0], parameterArray[1], parameterArray[2]);
					continue;
				}

				if ((f === 'setCollectorCf' || f === 'setCollectorUrl') && (!names || names.length === 0)) {
					legacyCreateNewNamespace(f, parameterArray[0], parameterArray[1]);
					continue;
				}

				namedTrackers = getNamedTrackers(names);

				if (lodash.isString(f)) {
					for (j = 0; j < namedTrackers.length; j++) {
						namedTrackers[j][f].apply(namedTrackers[j], parameterArray);
					}
				} else {
					for (j = 0; j < namedTrackers.length; j++) {
						f.apply(namedTrackers[j], parameterArray);
					}
				}
			}
		}

		// We need to manually apply any events collected before this initialization
		for (var i = 0; i < asyncQueue.length; i++) {
			applyAsyncFunction(asyncQueue[i]);
		}

		return {
			push: applyAsyncFunction
		};
	};

}());
<|endoftext|>


<commit_before>(function(React){

        "use strict";

/*
$status[0] = 'none';
$status[2] = 'reserved';
$status[10] = 'purchased';
$status[50] = 'cancelled';

remove is set to 1 if a user removes the item from their own list
remove is set to 2 if an item is added to another users list (if I add an item to patricks) and status is set to purchased.  This is done so that we can NOT show items added to another persons list (like if patrick is looking at his own list).

I'm lazy.  Archive is set to 1 for old items.

*/

        const thisUserID = window.gmUtilities.getUriParamsAsObject()["userid"]; //set this after authentication.
        let itemListContainer = document.getElementById('itemListContainer');
        let _this;

        var ItemList = React.createClass({

            loadItemListFromServer: function() {
                $.ajax({
                    url: this.props.ItemListUrl,
                    data : {
                      "cmd" : "giftList",
                      "viewid" : this.state.subjectUID
                    },
                    type: 'GET',
                    dataType: 'json',
                    cache: false,
                    success: function(data) {
                        this.setState({data: data.gifts});
                    }.bind(this),
                    error: function(xhr, status, err) {
                        console.error(this.props.ItemListUrl, status, err.toString());
                    }.bind(this)
                });
            },

            getInitialState: function() {
                return {
                    data: [],
                    subjectUID : thisUserID,
                };
            },

            componentDidMount: function() {
                _this = this;
                this.loadItemListFromServer();
                addEventListener("UserList.userSelected",function(e){
                  _this.setState({"subjectUID": Number(e.detail.userid)},function(){
                    _this.loadItemListFromServer();
                  });
                },false, true);
                if(this.props.pollInterval) {
                    setInterval(this.loadItemListFromServer, this.props.pollInterval);
                }
            },

            render: function() {
                return (

                            <ItemListTable data={this.state.data} subjectUID={this.state.subjectUID} itemListUrl={this.props.ItemListUrl} />

                );
            }
        });

        var ItemListTable = React.createClass({
            render: function() {
              // console.log("this: " , this);
                let subjectUID = this.props.subjectUID;
                let itemListUrl = this.props.itemListUrl;
                let optionOnChange = this.props.optionOnChange;
                var items = this.props.data.map(function(item) {
                    return (
                            <Item item={item} key={item.itemid} subjectUID={subjectUID} itemListUrl={itemListUrl} >
                            </Item>
                    );
                });
                return (

                            {items}

                );
            }
        });

        var Item = React.createClass({

            render: function() {
              // console.log("this: " , this);
                return (

                                {this.props.item.item_name}

                                L

                                {this.props.subjectUID === thisUserID ? <ItemSelectListSelf status={this.props.item.status} remove={this.props.item.remove} itemid={this.props.item.itemid} /> : <ItemSelectListOther status={this.props.item.status} remove={this.props.item.remove} itemid={this.props.item.itemid} />}

                              {this.props.item.item_desc}

                );
            }
        });

        // var ItemMessage = React.createClass({
        //
        //
        //     render: function() {
        //       // console.log("this: " , this);
        //         return (
        //

        //
        //

        //         );
        //     }
        // });

        var ItemSelectListSelf = React.createClass({

          //todo -> clean this up. get url generation into a function so that updates are less likely to break something.
          //tood -> log the cancel date.  later, when items are requested, we'll make sure nothing cancelled more than a day ago is loaded.
            handleItemStatusChange : function(event) {
              let props = this.props;
              let newState = event.target.value;
              // console.log("handleItemStatusChange props.itemid: " + props.itemid);
                this.setState({status: event.target.value},function() {
                  $.ajax({
                    url: _this.props.ItemListUrl,
                    data : {
                        "cmd" : "giftList",
                        "viewid" : _this.state.subjectUID,
                        "itemid" : props.itemid,
                        "userid" : thisUserID,
                        "remove": newState
                      },
                    dataType: 'json',
                    type: 'POST',
                    success: function(data) {
                        this.setState({data: data});
                    }.bind(this),
                    error: function(xhr, status, err) {
                        console.error(props.url, status, err.toString());
                    }.bind(this)
                });
              });
          },

          getInitialState: function() {
             return {
                 status: this.props.status,
                 remove: this.props.remove,
                 itemid: this.props.itemid
             }
         },
          render : function(){
            // console.log("this.props.remove: " + this.props.remove);
            return (
              <select className='item-list-item-select' onChange={this.handleItemStatusChange} data={this.props.itemid}>
                {this.props.remove === 1 ? <option value='2'>Removed</option> : <option></option>}
                {this.props.remove === 1 ? <option value='0'>Add back to list</option> : <option value='1'>Remove</option>}
              </select>
            );
          }
        });

        var ItemSelectListOther = React.createClass({
          getInitialState: function() {
             return {
                 status: '',
                 itemid: ''
             }
         },

         handleItemStatusChange : function(event) {
           let props = this.props;
           let newState = event.target.value;
          //  console.log("handleItemStatusChange props.itemid: " + props.itemid + " and new state: " + newState);
             this.setState({status: event.target.value},function() {
               $.ajax({
                 url: _this.props.ItemListUrl,
                 data : {
                     "cmd" : "giftListUpdate",
                     "viewid" : _this.state.subjectUID,
                     "itemid" : props.itemid,
                     "userid" : thisUserID,
                     "status": newState
                   },
                 dataType: 'json',
                 type: 'POST',
                 success: function(data) {
                     this.setState({data: data});
                 }.bind(this),
                 error: function(xhr, status, err) {
                     console.error(props.url, status, err.toString());
                 }.bind(this)
             });
           });
       },

          render : function(){

            return (

              <select className='item-list-item-select' defaultValue={this.props.status} onChange={this.handleItemStatusChange} data={this.props.itemid}>
                <option></option>
                <option value='2'>Reserved</option>
                <option value='10'>Purchased</option>
                {(() => {
                  switch (this.props.status) {
                    case 2:   return <option value='XX'>Unreserve</option>;
                    case 10: return <option value='XX'>Unpurchase</option>;
                    default:      return "";
                  }
                })()}
              </select>
            );
          }
        });

        ReactDOM.render(
//itemListUrl loads from the html file instead of here, allowing for users to customize it easily without changing any JS.
                <ItemList ItemListUrl={itemListContainer.getAttribute("data-url")} pollInterval={itemListContainer.getAttribute("data-poll-interval") || 0} />,
                itemListContainer
        );

         })(React);
<commit_msg>fix bug in select list (issue #6)<commit_after>(function(React){

        "use strict";

/*
$status[0] = 'none';
$status[2] = 'reserved';
$status[10] = 'purchased';
$status[50] = 'cancelled';

remove is set to 1 if a user removes the item from their own list
remove is set to 2 if an item is added to another users list (if I add an item to patricks) and status is set to purchased.  This is done so that we can NOT show items added to another persons list (like if patrick is looking at his own list).

I'm lazy.  Archive is set to 1 for old items.

*/

        const thisUserID = window.gmUtilities.getUriParamsAsObject()["userid"]; //set this after authentication.
        let itemListContainer = document.getElementById('itemListContainer');
        let _this;

        var ItemList = React.createClass({

            loadItemListFromServer: function() {
                $.ajax({
                    url: this.props.ItemListUrl,
                    data : {
                      "cmd" : "giftList",
                      "viewid" : this.state.subjectUID
                    },
                    type: 'GET',
                    dataType: 'json',
                    cache: false,
                    success: function(data) {
                        this.setState({data: data.gifts});
                    }.bind(this),
                    error: function(xhr, status, err) {
                        console.error(this.props.ItemListUrl, status, err.toString());
                    }.bind(this)
                });
            },

            getInitialState: function() {
                return {
                    data: [],
                    subjectUID : thisUserID,
                };
            },

            componentDidMount: function() {
                _this = this;
                this.loadItemListFromServer();
                addEventListener("UserList.userSelected",function(e){
                  _this.setState({"subjectUID": Number(e.detail.userid)},function(){
                    console.log("state changed in itemlist. new subjectUID: " + this.state.subjectUID)
                    _this.loadItemListFromServer();
                  });
                },false, true);
                if(this.props.pollInterval) {
                    setInterval(this.loadItemListFromServer, this.props.pollInterval);
                }
            },

            render: function() {
                return (

                            <ItemListTable data={this.state.data} subjectUID={this.state.subjectUID} itemListUrl={this.props.ItemListUrl} />

                );
            }
        });

        var ItemListTable = React.createClass({
            render: function() {
              // console.log("this: " , this);
                let subjectUID = this.props.subjectUID;
                let itemListUrl = this.props.itemListUrl;
                let optionOnChange = this.props.optionOnChange;
                var items = this.props.data.map(function(item) {
                    return (
                            <Item item={item} key={item.itemid} subjectUID={subjectUID} itemListUrl={itemListUrl} >
                            </Item>
                    );
                });
                return (

                            {items}

                );
            }
        });

        var Item = React.createClass({

            render: function() {
              // console.log("this: " , this);
                return (

                                {this.props.item.item_name}

                                L

                            //don't type check this, it won't always match and is overly specific anyway.
                                {this.props.subjectUID == thisUserID ? <ItemSelectListSelf status={this.props.item.status} remove={this.props.item.remove} itemid={this.props.item.itemid} /> : <ItemSelectListOther status={this.props.item.status} remove={this.props.item.remove} itemid={this.props.item.itemid} />}

                              {this.props.item.item_desc}

                );
            }
        });

        // var ItemMessage = React.createClass({
        //
        //
        //     render: function() {
        //       // console.log("this: " , this);
        //         return (
        //

        //
        //

        //         );
        //     }
        // });

        var ItemSelectListSelf = React.createClass({

          //todo -> clean this up. get url generation into a function so that updates are less likely to break something.
          //tood -> log the cancel date.  later, when items are requested, we'll make sure nothing cancelled more than a day ago is loaded.
            handleItemStatusChange : function(event) {
              let props = this.props;
              let newState = event.target.value;
              // console.log("handleItemStatusChange props.itemid: " + props.itemid);
                this.setState({status: event.target.value},function() {
                  $.ajax({
                    url: _this.props.ItemListUrl,
                    data : {
                        "cmd" : "giftList",
                        "viewid" : _this.state.subjectUID,
                        "itemid" : props.itemid,
                        "userid" : thisUserID,
                        "remove": newState
                      },
                    dataType: 'json',
                    type: 'POST',
                    success: function(data) {
                        this.setState({data: data});
                    }.bind(this),
                    error: function(xhr, status, err) {
                        console.error(props.url, status, err.toString());
                    }.bind(this)
                });
              });
          },

          getInitialState: function() {
             return {
                 status: this.props.status,
                 remove: this.props.remove,
                 itemid: this.props.itemid
             }
         },
          render : function(){
            // console.log("this.props.remove: " + this.props.remove);
            return (
              <select className='item-list-item-select' onChange={this.handleItemStatusChange} data={this.props.itemid}>
                {this.props.remove === 1 ? <option value='2'>Removed</option> : <option></option>}
                {this.props.remove === 1 ? <option value='0'>Add back to list</option> : <option value='1'>Remove</option>}
              </select>
            );
          }
        });

        var ItemSelectListOther = React.createClass({
          getInitialState: function() {
             return {
                 status: '',
                 itemid: ''
             }
         },

         handleItemStatusChange : function(event) {
           let props = this.props;
           let newState = event.target.value;
          //  console.log("handleItemStatusChange props.itemid: " + props.itemid + " and new state: " + newState);
             this.setState({status: event.target.value},function() {
               $.ajax({
                 url: _this.props.ItemListUrl,
                 data : {
                     "cmd" : "giftListUpdate",
                     "viewid" : _this.state.subjectUID,
                     "itemid" : props.itemid,
                     "userid" : thisUserID,
                     "status": newState
                   },
                 dataType: 'json',
                 type: 'POST',
                 success: function(data) {
                     this.setState({data: data});
                 }.bind(this),
                 error: function(xhr, status, err) {
                     console.error(props.url, status, err.toString());
                 }.bind(this)
             });
           });
       },

          render : function(){

            return (

              <select className='item-list-item-select' defaultValue={this.props.status} onChange={this.handleItemStatusChange} data={this.props.itemid}>
                <option></option>
                <option value='2'>Reserved</option>
                <option value='10'>Purchased</option>
                {(() => {
                  switch (this.props.status) {
                    case 2:   return <option value='XX'>Unreserve</option>;
                    case 10: return <option value='XX'>Unpurchase</option>;
                    default:      return "";
                  }
                })()}
              </select>
            );
          }
        });

        ReactDOM.render(
//itemListUrl loads from the html file instead of here, allowing for users to customize it easily without changing any JS.
                <ItemList ItemListUrl={itemListContainer.getAttribute("data-url")} pollInterval={itemListContainer.getAttribute("data-poll-interval") || 0} />,
                itemListContainer
        );

         })(React);
<|endoftext|>


<commit_before>import babelPolyfill from 'babel-polyfill';
import LayerModal from 'components/Modals/LayerModal';
import ShareModal from 'components/Modals/ShareModal';
import AlertsModal from 'components/Modals/AlertsModal';
import CanopyModal from 'components/Modals/CanopyModal';
import {assetUrls} from 'js/config';
import Map from 'components/Map';
import ReactDOM from 'react-dom';
import React from 'react';

import GeoProcessor from 'esri/tasks/Geoprocessor';
import SR from 'esri/SpatialReference';

if (!babelPolyfill) { console.log('Missing Babel Polyfill.  May experience some weirdness in IE < 9.'); }

// Set up globals
window.app = {
  debugEnabled: true,
  debug: function (message) {
    if (this.debugEnabled) {
      var print = typeof message === 'string' ? console.log : console.dir;
      print.apply(console, [message]);
    }
  }
};

// Shim for rAF with timeout for callback
window.requestAnimationFrame = (function () {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function (callback) { window.setTimeout(callback, 1000 / 60); };
})();

let loadCSS = (url) => {
  var sheet = document.createElement('link');
  sheet.rel = 'stylesheet';
  sheet.type = 'text/css';
  sheet.href = url;
  requestAnimationFrame(function () { document.getElementsByTagName('head')[0].appendChild(sheet); });
};

let loadJS = (url, async) => {
  var script = document.createElement('script');
  script.src = url;
  script.async = async || false;
  requestAnimationFrame(function () { document.getElementsByTagName('head')[0].appendChild(script); });
};

let lazyloadAssets = () => {
  app.debug('main >>> lazyloadAssets');
  // This was causing issues so leave this out unless we get bad pagespeed scores
  loadCSS(assetUrls.ionCSS);
  loadCSS(assetUrls.ionSkinCSS);
  loadJS(assetUrls.highcharts);
  loadJS(assetUrls.highchartsMore);
};

let configureApp = () => {
  app.debug('main >>> configureApp');
};

let initializeApp = () => {
  app.debug('main >>> initializeApp');
  ReactDOM.render(<Map />, document.getElementById('root'));
  ReactDOM.render(<LayerModal />, document.getElementById('layer-modal'));
  ReactDOM.render(<ShareModal />, document.getElementById('share-modal'));
  ReactDOM.render(<AlertsModal />, document.getElementById('alerts-modal'));
  ReactDOM.render(<CanopyModal />, document.getElementById('canopy-modal'));
};

lazyloadAssets();
configureApp();
initializeApp();

// let test = () => {
//   let params = {
//     'SnapDistance': '5000',
//     'SnapDistanceUnits': 'Meters',
//     'DataSourceResolution': '90m',
//     'Generalize': 'True',
//     'f': 'json',
//     'InputPoints': '{"geometryType":"esriGeometryPoint","features":[{"geometry":{"x":11058950.018714607,"y":192244.0469047035,"spatialReference":{"wkid":102100,"latestWkid":3857}}}],"sr":{"wkid":102100,"latestWkid":3857}}'
//   };
//
//   let geoprocessor = new GeoProcessor('http://utility.arcgis.com/usrsvcs/appservices/epPvpBkwsBSgIYCd/rest/services/Tools/Hydrology/GPServer/Watershed');
//   geoprocessor.setOutputSpatialReference(new SR(102100));
//   geoprocessor.submitJob(params, results => {
//     console.log(results);
//     geoprocessor.getResultData(results.jobId, 'WatershedArea', data => {
//       console.log('getResultData');
//       console.log(data);
//     });
//   }, status => {
//     console.log(status);
//   });
//
// };

// test();
<commit_msg>commented out modules for test function<commit_after>import babelPolyfill from 'babel-polyfill';
import LayerModal from 'components/Modals/LayerModal';
import ShareModal from 'components/Modals/ShareModal';
import AlertsModal from 'components/Modals/AlertsModal';
import CanopyModal from 'components/Modals/CanopyModal';
import {assetUrls} from 'js/config';
import Map from 'components/Map';
import ReactDOM from 'react-dom';
import React from 'react';

// import GeoProcessor from 'esri/tasks/Geoprocessor';
// import SR from 'esri/SpatialReference';

if (!babelPolyfill) { console.log('Missing Babel Polyfill.  May experience some weirdness in IE < 9.'); }

// Set up globals
window.app = {
  debugEnabled: true,
  debug: function (message) {
    if (this.debugEnabled) {
      var print = typeof message === 'string' ? console.log : console.dir;
      print.apply(console, [message]);
    }
  }
};

// Shim for rAF with timeout for callback
window.requestAnimationFrame = (function () {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function (callback) { window.setTimeout(callback, 1000 / 60); };
})();

let loadCSS = (url) => {
  var sheet = document.createElement('link');
  sheet.rel = 'stylesheet';
  sheet.type = 'text/css';
  sheet.href = url;
  requestAnimationFrame(function () { document.getElementsByTagName('head')[0].appendChild(sheet); });
};

let loadJS = (url, async) => {
  var script = document.createElement('script');
  script.src = url;
  script.async = async || false;
  requestAnimationFrame(function () { document.getElementsByTagName('head')[0].appendChild(script); });
};

let lazyloadAssets = () => {
  app.debug('main >>> lazyloadAssets');
  // This was causing issues so leave this out unless we get bad pagespeed scores
  loadCSS(assetUrls.ionCSS);
  loadCSS(assetUrls.ionSkinCSS);
  loadJS(assetUrls.highcharts);
  loadJS(assetUrls.highchartsMore);
};

let configureApp = () => {
  app.debug('main >>> configureApp');
};

let initializeApp = () => {
  app.debug('main >>> initializeApp');
  ReactDOM.render(<Map />, document.getElementById('root'));
  ReactDOM.render(<LayerModal />, document.getElementById('layer-modal'));
  ReactDOM.render(<ShareModal />, document.getElementById('share-modal'));
  ReactDOM.render(<AlertsModal />, document.getElementById('alerts-modal'));
  ReactDOM.render(<CanopyModal />, document.getElementById('canopy-modal'));
};

lazyloadAssets();
configureApp();
initializeApp();

// let test = () => {
//   let params = {
//     'SnapDistance': '5000',
//     'SnapDistanceUnits': 'Meters',
//     'DataSourceResolution': '90m',
//     'Generalize': 'True',
//     'f': 'json',
//     'InputPoints': '{"geometryType":"esriGeometryPoint","features":[{"geometry":{"x":11058950.018714607,"y":192244.0469047035,"spatialReference":{"wkid":102100,"latestWkid":3857}}}],"sr":{"wkid":102100,"latestWkid":3857}}'
//   };
//
//   let geoprocessor = new GeoProcessor('http://utility.arcgis.com/usrsvcs/appservices/epPvpBkwsBSgIYCd/rest/services/Tools/Hydrology/GPServer/Watershed');
//   geoprocessor.setOutputSpatialReference(new SR(102100));
//   geoprocessor.submitJob(params, results => {
//     console.log(results);
//     geoprocessor.getResultData(results.jobId, 'WatershedArea', data => {
//       console.log('getResultData');
//       console.log(data);
//     });
//   }, status => {
//     console.log(status);
//   });
//
// };

// test();
<|endoftext|>