<commit_before>/**
 * Stack Exchange Chat Status
 * Copyright 2015 - Nathan Osman
 */

(function() {

    // TODO: get rid of this
    if(!location.pathname.startsWith('/rooms/201/')) {
        return;
    }

    /**
     * Default values for global settings.
     */
    var DEFAULTS = {
        debug: false,
        self: true,
        server: 'sechat.quickmediasolutions.com'
    };

    /**
     * Store a value in localStorage.
     * @param key item to set
     * @param val new value
     */
    function set(key, val) {
        localStorage.setItem(key, JSON.stringify(val));
    }

    /**
     * Retrieve a setting from localStorage.
     * @param key item to retrieve
     *
     * The DEFAULTS variable will be used for setting the default value if the
     * key is not set.
     */
    function get(key) {
        var val = localStorage.getItem(key);
        if(val === null) {
            set(key, DEFAULTS[key]);
            return DEFAULTS[key];
        } else {
            return JSON.parse(val);
        }
    }

    /**
     * Log the specified message to the console for debug purposes.
     */
    function log(msg) {
        get('debug') && console.log('[ChatStatus] ' + msg);
    }

    /**
     * Return the current time as a unix timestamp.
     */
    function now() {
        return parseInt(new Date().getTime() / 1000);
    }

    /**
     * Given a message, obtain its ID.
     */
    function messageId(e) {
        return $(e).attr('id').match(/message-(\d+)/)[1];
    }

    /**
     * Given a message, obtain the user's ID. This is made simpler by the fact
     * that SE stores the ID directly in one of the parent elements.
     */
    function messageUserId(e) {
        return $(e).closest('.user-container').data('user');
    }

    /**
     * Load the specified script into the page.
     * @param name filename of the script
     * @param callback function to execute after loading
     */
    function loadScript(name, callback) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://' + get('server') + '/static/' + name;
        script.onload = callback;
        document.body.appendChild(script);
    }

    var pendingContainers = {};

    /**
     * Obtain the container for a specific message, creating it if necessary.
     * @param msgId the ID of the message
     * @return the container for indicators
     *
     * If the message does not exist, the container will be added to a list of
     * "pending" containers to be created when the message does exist.
     */
    function getContainer(msgId) {
        if(msgId in pendingContainers) {
            return pendingContainers[msgId];
        }
        var $msg = $('#message-' + msgId),
            $container = $msg.next('.secs-container');
        if(!$container.length) {
            $container = $('<div>')
                .addClass('secs-container')
                .css('marginLeft', '18px');
            if($msg.length) {
                $msg.after($container);
            } else {
                pendingContainers[msgId] = $container;
            }
        }
        return $container;
    }

    var users = {};

    /**
     * Obtain the indicator element for a user, creating it if necessary.
     * @param userId the ID of the user
     * @return the indicator for the user
     */
    function getUser(userId) {
        var $user;
        if(userId in users) {
            $user = users[userId];
        } else {

            var $typing = $('<img>')
                    .attr('src', '//cdn-chat.sstatic.net/chat/img/progress-dots.gif')
                    .css('marginRight', '4px')
                    .hide();

            $user = $('<span>')
                .css({
                    backgroundColor: 'rgba(0, 0, 0, 0.1)',
                    borderRadius: '12px',
                    display: 'inline-block',
                    margin: '4px 4px 4px 0',
                    padding: '4px'
                })
                .append($(CHAT.RoomUsers.createAvatarImage(userId, 16))
                    .css({
                        borderRadius: '9px',
                        padding: '1px'
                    }))
                .append(' ')
                .append($typing)
                .data('typing', $typing);
            users[userId] = $user;
        }
        return $user;
    }

    /**
     * Update the message that the user has last read.
     * @param userId the ID of the user to update
     * @param msgId the ID of the message or null for the indicator tray
     */
    function updateUserMessage(userId, msgId) {
        getContainer(msgId).append(getUser(userId).detach());
    }

    /**
     * Indicate that a user has stopped typing.
     * @param userId the ID of the user
     */
    function userStoppedTyping(userId) {
    	var $user = getUser(userId),
    		timeout = $user.data('timeout');
    	if(timeout) {
    		window.clearTimeout(timeout);
    		// Animate the hide
    		$user.data('typing').animate({width: 'hide'});
    		$user.removeData('timeout');
    	}
    }

    /**
     * Indicate that a user has started typing.
     * @param userId the ID of the user to update
     *
     * The typing indicator will be displayed for four seconds or until it is
     * reset by another call to this function for the same user.
     */
    function userStartedTyping(userId) {
    	var $user = getUser(userId),
    		timeout = $user.data('timeout');
    	if(timeout) {
    		window.clearTimeout(timeout);
    	} else {
    		// Animate the element as showing
    		$user.data('typing').animate({width: 'show'});
    		$user.data('typing').css('display', 'inline');
    	}
    	$user.data('timeout', window.setTimeout(userStoppedTyping, 4000, userId));
    }

    var socket,
        lastTypingMsg = 0,
        lastMessageRead = 0,
        windowActive = true;

    /**
     * Determine if the socket is active.
     */
    function isActive() {
        return socket && socket.readyState == WebSocket.OPEN;
    }

    /**
     * Send a ping every 30 seconds to avoid having the socket timeout.
     */
    function ping() {
        if(isActive()) {
            log("ping");
            socket.send('');
        }
    }
    window.setInterval(ping, 30000);

    /**
     * Hook the input box in order to notify other users of typing. Only send
     * the messages once per two seconds to avoid excessive bandwidth.
     */
    $('#input').on('keypress', function() {
        if(isActive()) {
            var t = now();
            if(lastTypingMsg < (t - 2)) {
                log("last_char_entered: " + t);
                socket.send(JSON.stringify({
                    id: CHAT.CURRENT_USER_ID,
                    data: {
                        last_char_entered: t.toString()
                    }
                }));
                lastTypingMsg = t;
            }
        }
    });

    /**
     * Broadcast the last message read to the other users.
     */
    function broadcastLastMessageRead() {
        if(isActive()) {
            var msgId = messageId($('.message').last());
            if(parseInt(msgId) > parseInt(lastMessageRead)) {
                lastMessageRead = msgId;
                log("last_message_read: " + lastMessageRead);
                socket.send(JSON.stringify({
                    id: CHAT.CURRENT_USER_ID,
                    data: {
                        last_message_read: lastMessageRead
                    }
                }));
            }
        }
    }

    /**
     * Load Live Query and watch for new messages coming in. When one comes in,
     * that user has stopped typing. Also, check for pending containers.
     */
    loadScript('jquery.livequery.min.js', function() {
        log("Live Query loaded")
        var firstLoad = true;
        $('#chat').livequery('.message', function(e) {
            if(!firstLoad) {
                var msgId = messageId(e),
                    userId = messageUserId(e);
                if(msgId in pendingContainers) {
                    $(e).after(pendingContainers[msgId]);
                    delete pendingContainers[msgId];
                }
                userStoppedTyping(userId);
                if(windowActive) {
                    broadcastLastMessageRead();
                }
            }
        });
        firstLoad = false;
    });

    /**
     * Keep track of whether the window (or tab) is active.
     */
    $(window).on({
        'blur': function() {
            log("Window has lost focus");
            windowActive = false;
        },
        'focus': function() {
            log("Window has gained focus");
            windowActive = true;
            broadcastLastMessageRead();
        }
    });

    /**
     * Connect to the WebSocket endpoint and set the appropriate callbacks;
     */
    function connect() {
        socket = new WebSocket('wss://' + get('server') + '/api/connect');
        socket.onopen = onopen;
        socket.onmessage = onmessage;
        socket.onerror = onerror;
        socket.onclose = onclose;
    }

    /**
     * Log the successful connection.
     */
    function onopen() {
        log("socket opened");
        broadcastLastMessageRead();
    }

    /**
     * Process a message received from another user.
     */
    function onmessage(e) {
        if(e.data.length) {
            log("msg: " + e.data);
            var s = JSON.parse(e.data);
            if('last_char_entered' in s.data &&
                    parseInt(s.data.last_char_entered) > (now() - 4)) {
                userStartedTyping(s.id);
            }
            if('last_message_read' in s.data) {
                updateUserMessage(s.id, s.data.last_message_read);
            }
        }
    }

    /**
     * Log an error that occurs.
     */
    function onerror(e) {
        log("socket error: " + e);
    }

    /**
     * Attempt to reconnect after one minute.
     */
    function onclose() {
        log("socket closed");
        socket = null;
        window.setTimeout(connect, 60 * 1000);
    }

    connect();

    /**
     * Update the visibility of the current user.
     */
    function updateSelf(val) {
        getUser(CHAT.CURRENT_USER_ID).toggle(val);
    }
    updateSelf();

    /**
     * Preference dialog
     */
    var $prefCover = $('<div>')
            .css({
                backgroundColor: 'rgba(0, 0, 0, 0.4)',
                height: '100%',
                left: '0',
                position: 'fixed',
                top: '0',
                width: '100%',
                zIndex: '6'
            })
            .hide()
            .appendTo(document.body),
        $prefDialog = $('<div>')
            .css({
                backgroundColor: '#fff',
                boxShadow: '0 1px 15px #555555',
                boxSizing: 'border-box',
                height: '200px',
                left: '50%',
                marginLeft: '-150px',
                marginTop: '-100px',
                padding: '8px',
                position: 'fixed',
                top: '50%',
                width: '300px'
            })
            .append($('<a>')
                .attr('href', '#')
                .css('float', 'right')
                .html('×')
                .click(function() {
                    $prefCover.fadeOut();
                    return false;
                }))
            .append($('<h4>').text("Preferences"))
            .append('<br>')
            .appendTo($prefCover),
        $debugOption = $('<div>')
            .append($('<input>')
                .attr('type', 'checkbox')
                .prop('checked', get('debug'))
                .change(function() {
                    set('debug', this.checked);
                }))
            .append(" debug messages")
            .appendTo($prefDialog),
        $selfOption = $('<div>')
            .append($('<input>')
                .attr('type', 'checkbox')
                .prop('checked', get('self'))
                .change(function() {
                    set('self', this.checked);
                    updateSelf(this.checked);
                }))
            .append(" show me")
            .appendTo($prefDialog);
    $('input[type=checkbox]').css('verticalAlign', 'middle');
    updateSelf();

    /**
     * Add a link to the bottom of the page for changing preferences
     */
    $('#footer-legal')
        .prepend(' | ')
        .prepend($('<a>')
            .attr('href', '#')
            .text('prefs')
            .click(function() {
                $prefCover.fadeIn();
                return false;
            }));

})();
<commit_msg>UN-remove fix 11 changes<commit_after>/**
 * Stack Exchange Chat Status
 * Copyright 2015 - Nathan Osman
 */

(function() {

    // TODO: get rid of this
    if(!location.pathname.startsWith('/rooms/201/')) {
        return;
    }

    /**
     * Default values for global settings.
     */
    var DEFAULTS = {
        debug: false,
        self: true,
        server: 'sechat.quickmediasolutions.com'
    };

    /**
     * Store a value in localStorage.
     * @param key item to set
     * @param val new value
     */
    function set(key, val) {
        localStorage.setItem(key, JSON.stringify(val));
    }

    /**
     * Retrieve a setting from localStorage.
     * @param key item to retrieve
     *
     * The DEFAULTS variable will be used for setting the default value if the
     * key is not set.
     */
    function get(key) {
        var val = localStorage.getItem(key);
        if(val === null) {
            set(key, DEFAULTS[key]);
            return DEFAULTS[key];
        } else {
            return JSON.parse(val);
        }
    }

    /**
     * Log the specified message to the console for debug purposes.
     */
    function log(msg) {
        get('debug') && console.log('[ChatStatus] ' + msg);
    }

    /**
     * Return the current time as a unix timestamp.
     */
    function now() {
        return parseInt(new Date().getTime() / 1000);
    }

    /**
     * Given a message, obtain its ID.
     */
    function messageId(e) {
        return $(e).attr('id').match(/message-(\d+)/)[1];
    }

    /**
     * Given a message, obtain the user's ID. This is made simpler by the fact
     * that SE stores the ID directly in one of the parent elements.
     */
    function messageUserId(e) {
        return $(e).closest('.user-container').data('user');
    }

    /**
     * Load the specified script into the page.
     * @param name filename of the script
     * @param callback function to execute after loading
     */
    function loadScript(name, callback) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://' + get('server') + '/static/' + name;
        script.onload = callback;
        document.body.appendChild(script);
    }

    var pendingContainers = {};

    /**
     * Obtain the container for a specific message, creating it if necessary.
     * @param msgId the ID of the message
     * @return the container for indicators
     *
     * If the message does not exist, the container will be added to a list of
     * "pending" containers to be created when the message does exist.
     */
    function getContainer(msgId) {
        if(msgId in pendingContainers) {
            return pendingContainers[msgId];
        }
        var $msg = $('#message-' + msgId),
            $container = $msg.next('.secs-container');
        if(!$container.length) {
            $container = $('<div>')
                .addClass('secs-container')
                .css('marginLeft', '18px');
            if($msg.length) {
                $msg.after($container);
            } else {
                pendingContainers[msgId] = $container;
            }
        }
        return $container;
    }

    var users = {};

    /**
     * Obtain the indicator element for a user, creating it if necessary.
     * @param userId the ID of the user
     * @return the indicator for the user
     */
    function getUser(userId) {
        var $user;
        if(userId in users) {
            $user = users[userId];
        } else {

            var $typing = $('<img>')
                    .attr('src', '//cdn-chat.sstatic.net/chat/img/progress-dots.gif')
                    .css('marginRight', '4px')
                    .hide();

            $user = $('<span>')
                .css({
                    backgroundColor: 'rgba(0, 0, 0, 0.1)',
                    borderRadius: '12px',
                    display: 'inline-block',
                    margin: '4px 4px 4px 0',
                    padding: '4px'
                })
                .append($(CHAT.RoomUsers.createAvatarImage(userId, 16))
                    .css({
                        borderRadius: '9px',
                        padding: '1px'
                    }))
                .append(' ')
                .append($typing)
                .data('typing', $typing);
            users[userId] = $user;

            // Create the allUsers variable as an array of all present users
            var allUsers = CHAT.RoomUsers.allPresent().toArray();

            for (i = 0; i < allUsers.length; i++) {
                // Iterate through the list of present users and if it's equal
                // to the user's ID we are updating then ...
                if (allUsers[i].id == userId) {
                    // ... set the user's element's title attribute equal to
                    // the user's username
                    $user.attr('title', allUsers[i].name);
                }
            }

        }
        return $user;
    }

    /**
     * Update the message that the user has last read.
     * @param userId the ID of the user to update
     * @param msgId the ID of the message or null for the indicator tray
     */
    function updateUserMessage(userId, msgId) {
        getContainer(msgId).append(getUser(userId).detach());
    }

    /**
     * Indicate that a user has stopped typing.
     * @param userId the ID of the user
     */
    function userStoppedTyping(userId) {
    	var $user = getUser(userId),
    		timeout = $user.data('timeout');
    	if(timeout) {
    		window.clearTimeout(timeout);
    		// Animate the hide
    		$user.data('typing').animate({width: 'hide'});
    		$user.removeData('timeout');
    	}
    }

    /**
     * Indicate that a user has started typing.
     * @param userId the ID of the user to update
     *
     * The typing indicator will be displayed for four seconds or until it is
     * reset by another call to this function for the same user.
     */
    function userStartedTyping(userId) {
    	var $user = getUser(userId),
    		timeout = $user.data('timeout');
    	if(timeout) {
    		window.clearTimeout(timeout);
    	} else {
    		// Animate the element as showing
    		$user.data('typing').animate({width: 'show'});
    		$user.data('typing').css('display', 'inline');
    	}
    	$user.data('timeout', window.setTimeout(userStoppedTyping, 4000, userId));
    }

    var socket,
        lastTypingMsg = 0,
        lastMessageRead = 0,
        windowActive = true;

    /**
     * Determine if the socket is active.
     */
    function isActive() {
        return socket && socket.readyState == WebSocket.OPEN;
    }

    /**
     * Send a ping every 30 seconds to avoid having the socket timeout.
     */
    function ping() {
        if(isActive()) {
            log("ping");
            socket.send('');
        }
    }
    window.setInterval(ping, 30000);

    /**
     * Hook the input box in order to notify other users of typing. Only send
     * the messages once per two seconds to avoid excessive bandwidth.
     */
    $('#input').on('keypress', function() {
        if(isActive()) {
            var t = now();
            if(lastTypingMsg < (t - 2)) {
                log("last_char_entered: " + t);
                socket.send(JSON.stringify({
                    id: CHAT.CURRENT_USER_ID,
                    data: {
                        last_char_entered: t.toString()
                    }
                }));
                lastTypingMsg = t;
            }
        }
    });

    /**
     * Broadcast the last message read to the other users.
     */
    function broadcastLastMessageRead() {
        if(isActive()) {
            var msgId = messageId($('.message').last());
            if(parseInt(msgId) > parseInt(lastMessageRead)) {
                lastMessageRead = msgId;
                log("last_message_read: " + lastMessageRead);
                socket.send(JSON.stringify({
                    id: CHAT.CURRENT_USER_ID,
                    data: {
                        last_message_read: lastMessageRead
                    }
                }));
            }
        }
    }

    /**
     * Load Live Query and watch for new messages coming in. When one comes in,
     * that user has stopped typing. Also, check for pending containers.
     */
    loadScript('jquery.livequery.min.js', function() {
        log("Live Query loaded")
        var firstLoad = true;
        $('#chat').livequery('.message', function(e) {
            if(!firstLoad) {
                var msgId = messageId(e),
                    userId = messageUserId(e);
                if(msgId in pendingContainers) {
                    $(e).after(pendingContainers[msgId]);
                    delete pendingContainers[msgId];
                }
                userStoppedTyping(userId);
                if(windowActive) {
                    broadcastLastMessageRead();
                }
            }
        });
        firstLoad = false;
    });

    /**
     * Keep track of whether the window (or tab) is active.
     */
    $(window).on({
        'blur': function() {
            log("Window has lost focus");
            windowActive = false;
        },
        'focus': function() {
            log("Window has gained focus");
            windowActive = true;
            broadcastLastMessageRead();
        }
    });

    /**
     * Connect to the WebSocket endpoint and set the appropriate callbacks;
     */
    function connect() {
        socket = new WebSocket('wss://' + get('server') + '/api/connect');
        socket.onopen = onopen;
        socket.onmessage = onmessage;
        socket.onerror = onerror;
        socket.onclose = onclose;
    }

    /**
     * Log the successful connection.
     */
    function onopen() {
        log("socket opened");
        broadcastLastMessageRead();
    }

    /**
     * Process a message received from another user.
     */
    function onmessage(e) {
        if(e.data.length) {
            log("msg: " + e.data);
            var s = JSON.parse(e.data);
            if('last_char_entered' in s.data &&
                    parseInt(s.data.last_char_entered) > (now() - 4)) {
                userStartedTyping(s.id);
            }
            if('last_message_read' in s.data) {
                updateUserMessage(s.id, s.data.last_message_read);
            }
        }
    }

    /**
     * Log an error that occurs.
     */
    function onerror(e) {
        log("socket error: " + e);
    }

    /**
     * Attempt to reconnect after one minute.
     */
    function onclose() {
        log("socket closed");
        socket = null;
        window.setTimeout(connect, 60 * 1000);
    }

    connect();

    /**
     * Update the visibility of the current user.
     */
    function updateSelf(val) {
        getUser(CHAT.CURRENT_USER_ID).toggle(val);
    }
    updateSelf();

    /**
     * Preference dialog
     */
    var $prefCover = $('<div>')
            .css({
                backgroundColor: 'rgba(0, 0, 0, 0.4)',
                height: '100%',
                left: '0',
                position: 'fixed',
                top: '0',
                width: '100%',
                zIndex: '6'
            })
            .hide()
            .appendTo(document.body),
        $prefDialog = $('<div>')
            .css({
                backgroundColor: '#fff',
                boxShadow: '0 1px 15px #555555',
                boxSizing: 'border-box',
                height: '200px',
                left: '50%',
                marginLeft: '-150px',
                marginTop: '-100px',
                padding: '8px',
                position: 'fixed',
                top: '50%',
                width: '300px'
            })
            .append($('<a>')
                .attr('href', '#')
                .css('float', 'right')
                .html('×')
                .click(function() {
                    $prefCover.fadeOut();
                    return false;
                }))
            .append($('<h4>').text("Preferences"))
            .append('<br>')
            .appendTo($prefCover),
        $debugOption = $('<div>')
            .append($('<input>')
                .attr('type', 'checkbox')
                .prop('checked', get('debug'))
                .change(function() {
                    set('debug', this.checked);
                }))
            .append(" debug messages")
            .appendTo($prefDialog),
        $selfOption = $('<div>')
            .append($('<input>')
                .attr('type', 'checkbox')
                .prop('checked', get('self'))
                .change(function() {
                    set('self', this.checked);
                    updateSelf(this.checked);
                }))
            .append(" show me")
            .appendTo($prefDialog);
    $('input[type=checkbox]').css('verticalAlign', 'middle');
    updateSelf();

    /**
     * Add a link to the bottom of the page for changing preferences
     */
    $('#footer-legal')
        .prepend(' | ')
        .prepend($('<a>')
            .attr('href', '#')
            .text('prefs')
            .click(function() {
                $prefCover.fadeIn();
                return false;
            }));

})();
<|endoftext|>


<commit_before>/**
   Copyright 2011 Couchbase, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 **/

function alertDialog(alertMsg) {
  var dialog = genericDialog({
    buttons: {ok: true},
    header: "Alert",
    textHTML: alertMsg,
    callback: function (e, btn, dialog) {
      dialog.close();
    }
  });
}

var DocumentsSection = {

  init: function () {

    var self = this;

    // Prepare an empty document then send the user to edit
    function createDoc(bucket, id, callback) {

      // Do not do extra id validation here, leave that to the server
      if (id === '') {
        alertDialog('Document ID cannot be empty');
        return;
      }

      couchReq('PUT', buildURL('/couchBase/', bucket, id), {_id: id}, function() {
        document.location.href = '#sec=edit_doc&bucketName=' +
          encodeURIComponent(bucket) + '&docId=' + encodeURIComponent(id);
        callback();
      }, function(err) {
        if (err.error === 'conflict') {
          document.location.href = '#sec=edit_doc&bucketName=' +
            encodeURIComponent(bucket) + '&docId=' + encodeURIComponent(id);
          callback();
        } else {
          alertDialog('Unknown error saving document');
        }
      });
    }

    function lookupDocument(id) {

      if (id === '') {
        alertDialog('Document ID cannot be empty');
        return;
      }

      couchReq('GET', buildDocURL(buildURL('/couchBase/', self.bucketName), id), null, function() {
        lookupInp.val('');
        document.location.href = '#sec=edit_doc&bucketName=' +
          encodeURIComponent(self.bucketName) + '&docId=' + encodeURIComponent(id);
      }, function() {
        alertDialog('Document was not found');
      });

    }

    $('#documents .header_2 a.btn_create').click(function(){
      showDialog('create_document_dialog', {
        eventBindings: [['.save_button', 'click', function (e) {
          e.preventDefault();
          createDoc(self.bucketName, $('#new_doc_id').val(), function() {
            $('#new_doc_id').val('');
          });
        }]]
      });
    });

    self.rawDocumentsBucketCell = new StringHashFragmentCell("documentsBucket");

    self.selectedBucketCell = Cell.compute(function (v) {
      if (v.need(DAL.cells.mode) != 'documents')
        return;
      return v.need(self.documentsBucketCell);
    }).name("selectedBucket");

    // This shouldnt exist, just passing from allDocs cell into subscribe
    self.bucketName;

    self.dbUrlCell = Cell
      .needing(DAL.cells.capiBase, self.selectedBucketCell)
      .compute(function (v, baseUri, bucketName) {
        self.bucketName = bucketName;
        return buildURL(baseUri, bucketName) + "/";
      });

    var currentPage = 0;
    var limit = 5;
    var total = 0;

    var prevBtn = $('#documents .arr_prev');
    var nextBtn = $('#documents .arr_next');
    var lookupBtn = $('#docs_lookup_doc_by_id_btn');
    var lookupInp = $('#docs_lookup_doc_by_id');

    self.allDocs = Cell
      .needing(self.dbUrlCell)
      .compute(function (v, dbUrl) {
        var params = '?limit=' + limit + '&skip=' + (currentPage * limit);
        renderTemplate('documents_list', {loading: true});
        return future.get({url: dbUrl + '_all_docs' + params});
      });

    self.allDocs.subscribe(function (cell, x) {

      total = cell.value.total_rows;
      var lastPage = Math.max(0, Math.ceil(total / limit) - 1);
      if (currentPage > lastPage) {
        currentPage = lastPage;
      }

      if (total > 0) {
        lookupInp.removeAttr('disabled');
      } else {
        lookupInp.attr('disabled', 'disabled');
      }

      lookupBtn.toggleClass('disabled', !(total > 0));
      prevBtn.toggleClass('disabled', currentPage === 0);
      nextBtn.toggleClass('disabled', currentPage > lastPage - 1);

      renderTemplate('documents_list', {
        loading: false,
        rows: cell.value.rows,
        bucketName: self.bucketName
      });
    });

    (function () {

      function pageBtnClicker(btn, increment) {
        btn.click(function (ev) {
          if (btn.hasClass('disabled')) {
            return;
          }
          ev.preventDefault();
          currentPage = currentPage + increment;
          self.allDocs.invalidate();
        });
      }

      pageBtnClicker(prevBtn, -1);
      pageBtnClicker(nextBtn, 1);

      lookupBtn.live('mousedown', function(e) {
        if (lookupBtn.hasClass('disabled')) {
          return;
        }
        e.preventDefault();
        lookupDocument(lookupInp.val());
      });

    })();

    self.documentsBucketCell = Cell.compute(function (v) {
      var selected = v(self.rawDocumentsBucketCell);
      if (selected) {
        return selected;
      }
      var buckets = v.need(DAL.cells.bucketsListCell).byType.membase;
      var bucketInfo = _.detect(buckets, function (info) {
        return info.name === "default"
      }) || buckets[0];

      if (!bucketInfo) {
        return null;
      }
      return bucketInfo.name;
    });

    (function () {

      var cell = Cell.compute(function (v) {

        var mode = v.need(DAL.cells.mode);
        if (mode != 'documents') {
          return;
        }

        var buckets = v.need(DAL.cells.bucketsListCell).byType.membase;
        var selectedBucketName = v.need(self.documentsBucketCell);
        return {
          list: _.map(buckets, function (info) { return [info.name, info.name] }),
          selected: selectedBucketName
        };
      });

      $('#docs_buckets_select').bindListCell(cell, {
        onChange: function (e, newValue) {
          self.rawDocumentsBucketCell.setValue(newValue);
        }
      });

    })();

  },
  onEnter: function () {
    this.allDocs.invalidate();
  },
  navClick: function () {
  }
};

var EditDocumentSection = {

  init: function() {

    var self = this;

    self.bucketNameVal;
    self.docIdVal;
    self.docRevVal;

    var bucketName = self.bucketName = new StringHashFragmentCell("bucketName");
    var docId = self.docId = new StringHashFragmentCell("docId");

    function saveDoc(id, rev, callback) {

      try {
        var json = JSON.parse(self.jsonCodeEditor.getValue());
      } catch(err) {
        alertDialog('Document is invalid JSON');
        return;
      }

      for (var key in json) {
        if (/^(\$|_)/.test(key)) {
          delete json[key];
        }
      }

      json._id = id;
      if (rev) {
        json._rev = rev;
      }

      $('#doc_save').addClass('disabled').find('span').text("Saving");

      couchReq('PUT', buildURL('/', 'couchBase', self.bucketNameVal, id), json,
               function(data) {
        $('#doc_save').removeClass('disabled').find('span').text("Save");
        self.docIdVal = data.id;
        self.docRevVal = data.rev;
        callback();
      }, function() {
        $('#doc_save').removeClass('disabled').find('span').text("Save");
        alertDialog('Unknown error saving document');
      });
    }

    function deleteDoc() {
      var obj = {_id: self.docIdVal, _rev: self.docRevVal};
      var url = buildURL('/', 'couchBase', self.bucketNameVal, self.docIdVal,
                         {rev: self.docRevVal});
      couchReq('DELETE', url, null, function(data) {
        document.location.hash = 'sec=documents&documentsBucket='
          + encodeURIComponent(self.bucketNameVal);
      }, function() {
        alertDialog('Unknown error saving document');
      });
    }

    var dbUrl = self.dbUrl = Cell
    .needing(DAL.cells.capiBase, bucketName)
    .compute(function (v, baseUri, bucketName) {
      self.bucketNameVal = bucketName;
      return baseUri + bucketName;
    });

    var currentDoc = self.currentDoc = Cell
      .needing(dbUrl, docId)
      .compute(function (v, dbUrl, docId) {
        self.docIdVal = docId;
        return future.get({url: buildDocURL(dbUrl, docId)});
      });

    self.jsonCodeEditor = CodeMirror.fromTextArea($("#json_doc")[0], {
      lineNumbers: true,
      matchBrackets: true,
      mode: {name: "javascript", json: true},
      theme: 'default'
    });

    // subscriptions
    bucketName.subscribeValue(function (bucket) {
      $('#doc_buckets_select + a').attr('href', '#sec=documents&bucketName='
        + encodeURIComponent(bucket));
    });

    currentDoc.subscribeValue(function (doc) {
      if (doc === undefined) {
        return;
      } else {
        self.docRevVal = doc._rev;
        self.jsonCodeEditor.setValue(JSON.stringify(doc, null, "  "));
        $('#json_doc_id').text(doc._id);
        // We no longer have metadata to test for non json documents, for
        // now just test attachments
        if(typeof doc._attachments === 'undefined') {
          self.jsonCodeEditor.setOption('readOnly', false);
          $('#doc_saveas').removeClass('disabled');
          $('#doc_save').removeClass('disabled');
          $('#editing-notice').text('');
        } else {
          $('#editing-notice').text('(Editing disabled for non JSON documents)');
          self.jsonCodeEditor.setOption('readOnly', 'nocursor');
          $('#doc_saveas').addClass('disabled');
          $('#doc_save').addClass('disabled');
        }
      }
    });

    $('#doc_delete:not(.disabled)').live('click', deleteDoc);
    $('#doc_save:not(.disabled)').live('click', function() {
      saveDoc(self.docIdVal, self.docRevVal, function() {});
    });

    $('#doc_saveas:not(.disabled)').live('click', function(ev) {
      showDialog('save_documentas_dialog', {
        eventBindings: [['.save_button', 'click', function (e) {
          e.preventDefault();
          var id = $('#saveas_id').val();
          saveDoc(id, null, function() {
            $('#saveas_id').val('');
            document.location.hash = 'sec=edit_doc&bucketName=' +
              encodeURIComponent(self.bucketNameVal) +
              '&docId=' + encodeURIComponent(id);
          });
        }]]
      });
    });

    self.documentsBucketCell = Cell.compute(function (v) {
      var selected = v(self.bucketName);
      if (selected) {
        return selected;
      }
      var buckets = v.need(DAL.cells.bucketsListCell).byType.membase;
      var bucketInfo = _.detect(buckets, function (info) {
        return info.name === "default"
      }) || buckets[0];

      if (!bucketInfo) {
        return null;
      }
      return bucketInfo.name;
    });

    (function () {

      var cell = Cell.compute(function (v) {

        var mode = v.need(DAL.cells.mode);
        if (mode != 'edit_doc') {
          return;
        }

        var buckets = v.need(DAL.cells.bucketsListCell).byType.membase;
        var selectedBucketName = v.need(self.documentsBucketCell);
        return {
          list: _.map(buckets, function (info) { return [info.name, info.name] }),
          selected: selectedBucketName
        };
      });

      $('#doc_buckets_select').bindListCell(cell, {
        onChange: function (e, newValue) {
          self.rawDocumentsBucketCell.setValue(newValue);
        }
      });

    })();

  },
  onEnter: function () {
  },
  navClick: function () {
  }
};
<commit_msg>made bucket select changing switch to docs list<commit_after>/**
   Copyright 2011 Couchbase, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 **/

function alertDialog(alertMsg) {
  var dialog = genericDialog({
    buttons: {ok: true},
    header: "Alert",
    textHTML: alertMsg,
    callback: function (e, btn, dialog) {
      dialog.close();
    }
  });
}

var DocumentsSection = {

  init: function () {

    var self = this;

    // Prepare an empty document then send the user to edit
    function createDoc(bucket, id, callback) {

      // Do not do extra id validation here, leave that to the server
      if (id === '') {
        alertDialog('Document ID cannot be empty');
        return;
      }

      couchReq('PUT', buildURL('/couchBase/', bucket, id), {_id: id}, function() {
        document.location.href = '#sec=edit_doc&bucketName=' +
          encodeURIComponent(bucket) + '&docId=' + encodeURIComponent(id);
        callback();
      }, function(err) {
        if (err.error === 'conflict') {
          document.location.href = '#sec=edit_doc&bucketName=' +
            encodeURIComponent(bucket) + '&docId=' + encodeURIComponent(id);
          callback();
        } else {
          alertDialog('Unknown error saving document');
        }
      });
    }

    function lookupDocument(id) {

      if (id === '') {
        alertDialog('Document ID cannot be empty');
        return;
      }

      couchReq('GET', buildDocURL(buildURL('/couchBase/', self.bucketName), id), null, function() {
        lookupInp.val('');
        document.location.href = '#sec=edit_doc&bucketName=' +
          encodeURIComponent(self.bucketName) + '&docId=' + encodeURIComponent(id);
      }, function() {
        alertDialog('Document was not found');
      });

    }

    $('#documents .header_2 a.btn_create').click(function(){
      showDialog('create_document_dialog', {
        eventBindings: [['.save_button', 'click', function (e) {
          e.preventDefault();
          createDoc(self.bucketName, $('#new_doc_id').val(), function() {
            $('#new_doc_id').val('');
          });
        }]]
      });
    });

    self.rawDocumentsBucketCell = new StringHashFragmentCell("documentsBucket");

    self.selectedBucketCell = Cell.compute(function (v) {
      if (v.need(DAL.cells.mode) != 'documents')
        return;
      return v.need(self.documentsBucketCell);
    }).name("selectedBucket");

    // This shouldnt exist, just passing from allDocs cell into subscribe
    self.bucketName;

    self.dbUrlCell = Cell
      .needing(DAL.cells.capiBase, self.selectedBucketCell)
      .compute(function (v, baseUri, bucketName) {
        self.bucketName = bucketName;
        return buildURL(baseUri, bucketName) + "/";
      });

    var currentPage = 0;
    var limit = 5;
    var total = 0;

    var prevBtn = $('#documents .arr_prev');
    var nextBtn = $('#documents .arr_next');
    var lookupBtn = $('#docs_lookup_doc_by_id_btn');
    var lookupInp = $('#docs_lookup_doc_by_id');

    self.allDocs = Cell
      .needing(self.dbUrlCell)
      .compute(function (v, dbUrl) {
        var params = '?limit=' + limit + '&skip=' + (currentPage * limit);
        renderTemplate('documents_list', {loading: true});
        return future.get({url: dbUrl + '_all_docs' + params});
      });

    self.allDocs.subscribe(function (cell, x) {

      total = cell.value.total_rows;
      var lastPage = Math.max(0, Math.ceil(total / limit) - 1);
      if (currentPage > lastPage) {
        currentPage = lastPage;
      }

      if (total > 0) {
        lookupInp.removeAttr('disabled');
      } else {
        lookupInp.attr('disabled', 'disabled');
      }

      lookupBtn.toggleClass('disabled', !(total > 0));
      prevBtn.toggleClass('disabled', currentPage === 0);
      nextBtn.toggleClass('disabled', currentPage > lastPage - 1);

      renderTemplate('documents_list', {
        loading: false,
        rows: cell.value.rows,
        bucketName: self.bucketName
      });
    });

    (function () {

      function pageBtnClicker(btn, increment) {
        btn.click(function (ev) {
          if (btn.hasClass('disabled')) {
            return;
          }
          ev.preventDefault();
          currentPage = currentPage + increment;
          self.allDocs.invalidate();
        });
      }

      pageBtnClicker(prevBtn, -1);
      pageBtnClicker(nextBtn, 1);

      lookupBtn.live('mousedown', function(e) {
        if (lookupBtn.hasClass('disabled')) {
          return;
        }
        e.preventDefault();
        lookupDocument(lookupInp.val());
      });

    })();

    self.documentsBucketCell = Cell.compute(function (v) {
      var selected = v(self.rawDocumentsBucketCell);
      if (selected) {
        return selected;
      }
      var buckets = v.need(DAL.cells.bucketsListCell).byType.membase;
      var bucketInfo = _.detect(buckets, function (info) {
        return info.name === "default"
      }) || buckets[0];

      if (!bucketInfo) {
        return null;
      }
      return bucketInfo.name;
    });

    (function () {

      var cell = Cell.compute(function (v) {

        var mode = v.need(DAL.cells.mode);
        if (mode != 'documents') {
          return;
        }

        var buckets = v.need(DAL.cells.bucketsListCell).byType.membase;
        var selectedBucketName = v.need(self.documentsBucketCell);
        return {
          list: _.map(buckets, function (info) { return [info.name, info.name] }),
          selected: selectedBucketName
        };
      });

      $('#docs_buckets_select').bindListCell(cell, {
        onChange: function (e, newValue) {
          self.rawDocumentsBucketCell.setValue(newValue);
        }
      });

    })();

  },
  onEnter: function () {
    this.allDocs.invalidate();
  },
  navClick: function () {
  }
};

var EditDocumentSection = {

  init: function() {

    var self = this;

    self.bucketNameVal;
    self.docIdVal;
    self.docRevVal;

    var bucketName = self.bucketName = new StringHashFragmentCell("bucketName");
    var docId = self.docId = new StringHashFragmentCell("docId");

    function saveDoc(id, rev, callback) {

      try {
        var json = JSON.parse(self.jsonCodeEditor.getValue());
      } catch(err) {
        alertDialog('Document is invalid JSON');
        return;
      }

      for (var key in json) {
        if (/^(\$|_)/.test(key)) {
          delete json[key];
        }
      }

      json._id = id;
      if (rev) {
        json._rev = rev;
      }

      $('#doc_save').addClass('disabled').find('span').text("Saving");

      couchReq('PUT', buildURL('/', 'couchBase', self.bucketNameVal, id), json,
               function(data) {
        $('#doc_save').removeClass('disabled').find('span').text("Save");
        self.docIdVal = data.id;
        self.docRevVal = data.rev;
        callback();
      }, function() {
        $('#doc_save').removeClass('disabled').find('span').text("Save");
        alertDialog('Unknown error saving document');
      });
    }

    function deleteDoc() {
      var obj = {_id: self.docIdVal, _rev: self.docRevVal};
      var url = buildURL('/', 'couchBase', self.bucketNameVal, self.docIdVal,
                         {rev: self.docRevVal});
      couchReq('DELETE', url, null, function(data) {
        document.location.hash = 'sec=documents&documentsBucket='
          + encodeURIComponent(self.bucketNameVal);
      }, function() {
        alertDialog('Unknown error saving document');
      });
    }

    var dbUrl = self.dbUrl = Cell
    .needing(DAL.cells.capiBase, bucketName)
    .compute(function (v, baseUri, bucketName) {
      self.bucketNameVal = bucketName;
      return baseUri + bucketName;
    });

    var currentDoc = self.currentDoc = Cell
      .needing(dbUrl, docId)
      .compute(function (v, dbUrl, docId) {
        self.docIdVal = docId;
        return future.get({url: buildDocURL(dbUrl, docId)});
      });

    self.jsonCodeEditor = CodeMirror.fromTextArea($("#json_doc")[0], {
      lineNumbers: true,
      matchBrackets: true,
      mode: {name: "javascript", json: true},
      theme: 'default'
    });

    // subscriptions
    bucketName.subscribeValue(function (bucket) {
      $('#doc_buckets_select + a').attr('href', '#sec=documents&bucketName='
        + encodeURIComponent(bucket));
    });

    currentDoc.subscribeValue(function (doc) {
      if (doc === undefined) {
        return;
      } else {
        self.docRevVal = doc._rev;
        self.jsonCodeEditor.setValue(JSON.stringify(doc, null, "  "));
        $('#json_doc_id').text(doc._id);
        // We no longer have metadata to test for non json documents, for
        // now just test attachments
        if(typeof doc._attachments === 'undefined') {
          self.jsonCodeEditor.setOption('readOnly', false);
          $('#doc_saveas').removeClass('disabled');
          $('#doc_save').removeClass('disabled');
          $('#editing-notice').text('');
        } else {
          $('#editing-notice').text('(Editing disabled for non JSON documents)');
          self.jsonCodeEditor.setOption('readOnly', 'nocursor');
          $('#doc_saveas').addClass('disabled');
          $('#doc_save').addClass('disabled');
        }
      }
    });

    $('#doc_delete:not(.disabled)').live('click', deleteDoc);
    $('#doc_save:not(.disabled)').live('click', function() {
      saveDoc(self.docIdVal, self.docRevVal, function() {});
    });

    $('#doc_saveas:not(.disabled)').live('click', function(ev) {
      showDialog('save_documentas_dialog', {
        eventBindings: [['.save_button', 'click', function (e) {
          e.preventDefault();
          var id = $('#saveas_id').val();
          saveDoc(id, null, function() {
            $('#saveas_id').val('');
            document.location.hash = 'sec=edit_doc&bucketName=' +
              encodeURIComponent(self.bucketNameVal) +
              '&docId=' + encodeURIComponent(id);
          });
        }]]
      });
    });

    self.documentsBucketCell = Cell.compute(function (v) {
      var selected = v(self.bucketName);
      if (selected) {
        return selected;
      }
      var buckets = v.need(DAL.cells.bucketsListCell).byType.membase;
      var bucketInfo = _.detect(buckets, function (info) {
        return info.name === "default"
      }) || buckets[0];

      if (!bucketInfo) {
        return null;
      }
      return bucketInfo.name;
    });

    (function () {

      var cell = Cell.compute(function (v) {

        var mode = v.need(DAL.cells.mode);
        if (mode != 'edit_doc') {
          return;
        }

        var buckets = v.need(DAL.cells.bucketsListCell).byType.membase;
        var selectedBucketName = v.need(self.documentsBucketCell);
        return {
          list: _.map(buckets, function (info) { return [info.name, info.name] }),
          selected: selectedBucketName
        };
      });

      $('#doc_buckets_select').bindListCell(cell, {
        onChange: function (e, newValue) {
          self.rawDocumentsBucketCell.setValue(newValue);
          docId.setValue("");
          ThePage.gotoSection('documents');
        }
      });

    })();

  },
  onEnter: function () {
  },
  navClick: function () {
  }
};
<|endoftext|>


<commit_before>// include gulp
var gulp = require('gulp');
// include plug-ins
var istanbul = require('gulp-istanbul');
var mocha = require('gulp-mocha');
var eslint = require('gulp-eslint');

// ESLint task
gulp.task('lint', function () {
    return gulp.src(['./test/*.js'])
        // eslint() attaches the lint output to the eslint property
        // of the file object so it can be used by other modules.
        .pipe(eslint())
        // eslint.format() outputs the lint results to the console.
        // Alternatively use eslint.formatEach() (see Docs).
        .pipe(eslint.format())
        // To have the process exit with an error code (1) on
        // lint error, return the stream and pipe to failOnError last.
        .pipe(eslint.failOnError());
});

//Istanbul task
gulp.task('istanbul', ['lint'], function () {
  return gulp.src(['*.js'])
  // Covering files
  .pipe(istanbul())
  // Force `require` to return covered files
  .pipe(istanbul.hookRequire());
});

//Mocha task
gulp.task('mocha',['istanbul'], function () {
    return gulp.src('./test/*.js', {read: false})
    // gulp-mocha needs filepaths so you can't have any plugins before it
    .pipe(mocha())
    // Creating the reports after tests ran
    .pipe(istanbul.writeReports())
    // Enforce a coverage of at least 70%
    .pipe(istanbul.enforceThresholds({ thresholds: { global: 70 }}));

});

//test someone testcase file.
function testcase(file){
	if(file!="*" && file.indexOf("_tests")<0){
		file=file+"_tests";
	}
	return gulp.src('./test/'+file+'.js', {read: false})
    .pipe(mocha())
    // Creating the reports after tests ran
    .pipe(istanbul.writeReports())
    // Enforce a coverage of at least 70%
    .pipe(istanbul.enforceThresholds({ thresholds: { global: 70 }}));
}

//test api test cases
gulp.task('page',['istanbul'], function () {
	return testcase('page');
});

// Default task
gulp.task('default',['mocha'], function () {
	//do nothing
});

gulp.doneCallback = function (err) {
	process.exit(err ? 1 : 0);
};<commit_msg>down the coverage rate<commit_after>// include gulp
var gulp = require('gulp');
// include plug-ins
var istanbul = require('gulp-istanbul');
var mocha = require('gulp-mocha');
var eslint = require('gulp-eslint');

// ESLint task
gulp.task('lint', function () {
    return gulp.src(['./test/*.js'])
        // eslint() attaches the lint output to the eslint property
        // of the file object so it can be used by other modules.
        .pipe(eslint())
        // eslint.format() outputs the lint results to the console.
        // Alternatively use eslint.formatEach() (see Docs).
        .pipe(eslint.format())
        // To have the process exit with an error code (1) on
        // lint error, return the stream and pipe to failOnError last.
        .pipe(eslint.failOnError());
});

//Istanbul task
gulp.task('istanbul', ['lint'], function () {
  return gulp.src(['*.js'])
  // Covering files
  .pipe(istanbul())
  // Force `require` to return covered files
  .pipe(istanbul.hookRequire());
});

//Mocha task
gulp.task('mocha',['istanbul'], function () {
    return gulp.src('./test/*.js', {read: false})
    // gulp-mocha needs filepaths so you can't have any plugins before it
    .pipe(mocha())
    // Creating the reports after tests ran
    .pipe(istanbul.writeReports())
    // Enforce a coverage of at least 70%
    .pipe(istanbul.enforceThresholds({ thresholds: { global: 30 }}));

});

//test someone testcase file.
function testcase(file){
	if(file!="*" && file.indexOf("_tests")<0){
		file=file+"_tests";
	}
	return gulp.src('./test/'+file+'.js', {read: false})
    .pipe(mocha())
    // Creating the reports after tests ran
    .pipe(istanbul.writeReports())
    // Enforce a coverage of at least 70%
    .pipe(istanbul.enforceThresholds({ thresholds: { global: 30 }}));
}

//test api test cases
gulp.task('page',['istanbul'], function () {
	return testcase('page');
});

// Default task
gulp.task('default',['mocha'], function () {
	//do nothing
});

gulp.doneCallback = function (err) {
	process.exit(err ? 1 : 0);
};<|endoftext|>


<commit_before>/**
 * External dependencies
 */
import styled, { css } from 'styled-components';
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { useCallback } from '@wordpress/element';

/**
 * Internal dependencies
 */
import { useStory } from '../../../app';

const Wrapper = styled.div`
	display: flex;
	align-items: center;
	justify-content: flex-start;
	height: 100%;
	color:  ${ ( { theme } ) => theme.colors.fg.v1 };
`;

const Space = styled.div`
	flex: 0 1 ${ ( { isNext } ) => isNext ? 60 : 115 }px;
`;

const NavLink = styled.a``;

const IconStyle = css`
	border: solid ${ ( { theme } ) => theme.colors.fg.v1 };
	border-width: 0 1px 1px 0;
	display: inline-block;
	padding: 3px;
	cursor: pointer;
	opacity: .25;
	display: flex;
	align-items: center;
	justify-content: center;
	color: inherit;
	height: 25px;
	width: 25px;
	&:hover {
		color: inherit;
		opacity: 1;
	}
`;

const IconNext = styled.i`
	${ IconStyle }
	transform: rotate(-45deg);
`;

const IconPrev = styled.i`
	${ IconStyle }
	transform: rotate(135deg);
`;

function PageNav( { isNext } ) {
	const { state: { pages, currentPageIndex }, actions: { setCurrentPage } } = useStory();
	const handleClick = useCallback( () => {
		const newPage = isNext ? pages[ currentPageIndex + 1 ] : pages[ currentPageIndex - 1 ];
		if ( newPage ) {
			setCurrentPage( { pageId: newPage.id } );
		}
	}, [ setCurrentPage, currentPageIndex, isNext, pages ] );
	return (
		<Wrapper>
			<Space isNext={ isNext } />
			<NavLink aria-label={ isNext ? 'Next Page' : 'Previous Page' } onClick={ handleClick }>
				{ isNext && currentPageIndex < pages.length - 1 && ( <IconNext /> ) }
				{ ! isNext && currentPageIndex > 0 && ( <IconPrev /> ) }
			</NavLink>
		</Wrapper>
	);
}

PageNav.propTypes = {
	isNext: PropTypes.bool,
};

PageNav.defaultProps = {
	isNext: true,
};

export default PageNav;
<commit_msg>Use button instead of link.<commit_after>/**
 * External dependencies
 */
import styled, { css } from 'styled-components';
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { useCallback } from '@wordpress/element';

/**
 * Internal dependencies
 */
import { useStory } from '../../../app';

const Wrapper = styled.div`
	display: flex;
	align-items: center;
	justify-content: flex-start;
	height: 100%;
	color:  ${ ( { theme } ) => theme.colors.fg.v1 };
`;

const Space = styled.div`
	flex: 0 1 ${ ( { isNext } ) => isNext ? 60 : 115 }px;
`;

const NavButton = styled.button`
	display: block;
	background: transparent;
	border: none;
	width: 40px;
	height: 40px;
	&:focus {
		outline: 1px dotted -webkit-focus-ring-color
	}
`;

const IconStyle = css`
	border: solid ${ ( { theme } ) => theme.colors.fg.v1 };
	border-width: 0 1px 1px 0;
	display: inline-block;
	padding: 3px;
	cursor: pointer;
	opacity: .25;
	display: flex;
	align-items: center;
	justify-content: center;
	color: inherit;
	height: 25px;
	width: 25px;
	&:hover {
		color: inherit;
		opacity: 1;
	}
`;

const IconNext = styled.i`
	${ IconStyle }
	transform: rotate(-45deg);
`;

const IconPrev = styled.i`
	${ IconStyle }
	transform: rotate(135deg);
`;

function PageNav( { isNext } ) {
	const { state: { pages, currentPageIndex }, actions: { setCurrentPage } } = useStory();
	const handleClick = useCallback( () => {
		const newPage = isNext ? pages[ currentPageIndex + 1 ] : pages[ currentPageIndex - 1 ];
		if ( newPage ) {
			setCurrentPage( { pageId: newPage.id } );
		}
	}, [ setCurrentPage, currentPageIndex, isNext, pages ] );
	const displayNav = ( isNext && currentPageIndex < pages.length - 1 ) || ( ! isNext && currentPageIndex > 0 );
	return (
		<Wrapper>
			<Space isNext={ isNext } />
			{ displayNav && (
				<NavButton aria-label={ isNext ? 'Next Page' : 'Previous Page' } onClick={ handleClick }>
					{ isNext && ( <IconNext /> ) }
					{ ! isNext && ( <IconPrev /> ) }
				</NavButton>
			) }
		</Wrapper>
	);
}

PageNav.propTypes = {
	isNext: PropTypes.bool,
};

PageNav.defaultProps = {
	isNext: true,
};

export default PageNav;
<|endoftext|>


<commit_before>
$( document ).ready(function() {

            /*GLOBAL STATE VARS */
            mode = "none";
            pauseButtonState = "pause";
            hasCalib = false;
            log = [];
            inBetweenSpeech = 5; //seconds
            timeOut = 5; //seconds
            successCount = 0; //count of # of times in bounds
            loopRun = 0;
            wasInBounds = false;
            /*END GLOBAL STATE */

            $("#calibMode").click(function(){
                hasCalib = true;
                mode = "calibration";
                webgazer.showPredictionPoints(true);
                $('#gazedot').css('opacity',0.7);
            });
            $("#useMode").click(function(){
                if(!hasCalib){
                    alert("Please calibrate first");
                    return false;
                }
                else{
                    mode = "use";
                    webgazer.showPredictionPoints(true);
                    $('#gazedot').css('opacity',0);
                }
            });
            $("#pause").click(function(){
                if(pauseButtonState === "pause"){
                    mode = "pause";
                    pauseButtonState = "resume";
                    webgazer.pause();
                    $("#pause").html('RESUME');
                }
                else if(pauseButtonState === "resume"){
                    mode = "resume";
                    pauseButtonState = "pause";
                    webgazer.resume();
                    $("#pause").html('PAUSE');
                }
            });

            function getTransform(el) {
                var results = $(el).css('-webkit-transform').match(/matrix(?:(3d)\(\d+(?:, \d+)*(?:, (\d+))(?:, (\d+))(?:, (\d+)), \d+\)|\(\d+(?:, \d+)*(?:, (\d+))(?:, (\d+))\))/)

                if(!results) return /*[0, 0, 0]*/undefined;
                if(results[1] == '3d') return results.slice(2,5);

                results.push(0);
                return results.slice(5, 8);
            }
            setInterval(updatePosDisplay, 100);
            function updatePosDisplay(){
                var transform = getTransform('#gazedot');
                ++loopRun;
                $('#pos').text(transform);
                console.log(transform);
                console.log(isInBounds(transform));
                //$('#isinbounds').text(isInBounds(transform)) removed
                if(isInBounds(transform)){
                    $('#pos').css('background-color','blue');
                    log.push(true);
                    if(loopRun % (10*inBetweenSpeech) === 0|| loopRun === 0||!wasInBounds){
                        var msg = new SpeechSynthesisUtterance('Good');
                        window.speechSynthesis.speak(msg);
                        loopRun = 0;
                    }
                    wasInBounds = true;
                }
                else{
                    $('#pos').css('background-color','red');
                    log.push(false);
                    if(loopRun % (10*inBetweenSpeech) === 0|| loopRun === 0||wasInBounds){
                        var msg = new SpeechSynthesisUtterance('Make eye contact');
                        window.speechSynthesis.speak(msg);
                        loopRun = 0;
                    }
                    wasInBounds = false;
                }
            }

            function isInBounds(coords){
                var w = window.innerWidth;
                var h = window.innerHeight;
                var topBound = .66115702478*h;
                var bottomBound = .38567493112*h;
                var leftBound = .30769230769*w;
                var rightBound = .69336723881*w;
                var left = coords[0];
                var top = coords[1];
                var x = left;
                var y = h- top;
                console.log('x: '+x);
                console.log('y: '+y);
                console.log('bottom: '+bottomBound);
                console.log('top: '+topBound);
                return x >= leftBound && x <= rightBound && y >= bottomBound && y <= topBound;
            }
});<commit_msg>Probably won't work<commit_after>
$( document ).ready(function() {

            /*GLOBAL STATE VARS */
            mode = "none";
            pauseButtonState = "pause";
            hasCalib = false;
            log = [];
            inBetweenSpeech = 5; //seconds
            timeOut = 5; //seconds
            successCount = 0; //count of # of times in bounds
            loopRun = 0;
            wasInBounds = false;
            /*END GLOBAL STATE */

            $("#calibMode").click(function(){
                hasCalib = true;
                mode = "calibration";
                webgazer.showPredictionPoints(true);
                $('#gazedot').css('opacity',0.7);
            });
            $("#useMode").click(function(){
                if(!hasCalib){
                    alert("Please calibrate first");
                    return false;
                }
                else{
                    mode = "use";
                    webgazer.showPredictionPoints(true);
                    $('#gazedot').css('opacity',0);
                }
            });
            $("#pause").click(function(){
                if(pauseButtonState === "pause"){
                    mode = "pause";
                    pauseButtonState = "resume";
                    webgazer.pause();
                    $("#pause").html('RESUME');
                }
                else if(pauseButtonState === "resume"){
                    mode = "resume";
                    pauseButtonState = "pause";
                    webgazer.resume();
                    $("#pause").html('PAUSE');
                }
            });

            function getTransform(el) {
                var results = $(el).css('-webkit-transform').match(/matrix(?:(3d)\(\d+(?:, \d+)*(?:, (\d+))(?:, (\d+))(?:, (\d+)), \d+\)|\(\d+(?:, \d+)*(?:, (\d+))(?:, (\d+))\))/)

                if(!results) return /*[0, 0, 0]*/undefined;
                if(results[1] == '3d') return results.slice(2,5);

                results.push(0);
                return results.slice(5, 8);
            }
            setInterval(updatePosDisplay, 100);
            function updatePosDisplay(){
                var transform = getTransform('#gazedot');
                ++loopRun;
                $('#pos').text(transform);
                console.log(transform);
                console.log(isInBounds(transform));
                //$('#isinbounds').text(isInBounds(transform)) removed
                if(isInBounds(transform)){
                    $('#pos').css('background-color','blue');
                    log.push(true);
                    if(loopRun % (10*inBetweenSpeech) === 0|| loopRun === 0||!wasInBounds){
                        var msg = new SpeechSynthesisUtterance('Good');
                        window.speechSynthesis.speak(msg);
                    }
                    wasInBounds = true;
                }
                else{
                    $('#pos').css('background-color','red');
                    log.push(false);
                    if(loopRun % (10*inBetweenSpeech) === 0|| loopRun === 0||wasInBounds){
                        var msg = new SpeechSynthesisUtterance('Make eye contact');
                        window.speechSynthesis.speak(msg);
                    }
                    wasInBounds = false;
                }
            }

            function isInBounds(coords){
                var w = window.innerWidth;
                var h = window.innerHeight;
                var topBound = .66115702478*h;
                var bottomBound = .38567493112*h;
                var leftBound = .30769230769*w;
                var rightBound = .69336723881*w;
                var left = coords[0];
                var top = coords[1];
                var x = left;
                var y = h- top;
                console.log('x: '+x);
                console.log('y: '+y);
                console.log('bottom: '+bottomBound);
                console.log('top: '+topBound);
                return x >= leftBound && x <= rightBound && y >= bottomBound && y <= topBound;
            }
});<|endoftext|>


<commit_before>'use strict';
angular
  .module('core')
  .directive('a', preventClickDirective)
  .directive('a', cardExpandDirective)
  .directive('a', asideMenuToggleDirective)
  .directive('body', asideMenuHideDirective)
  .directive('backToTop', backToTopDirective)
  .directive('button', asidePanelToggleDirective)
  .directive('a', asidePanelToggleDirective)
  .directive('imagePreview', imagePreviewDirective)
  .directive('img', imageFullScreenDirective);

//Prevent click if href="#"
function preventClickDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    if (attrs.href === '#') {
      element.on('click', function (event) {
        event.preventDefault();
      });
    }
  }
}

//Card Collapse
function cardExpandDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function () {
      if (element.hasClass('card-expand-toggle')) {
        element.find('i').toggleClass('r180');
        element.parent().parent().toggleClass('open');
      }
      //
    });
  }
}

//LayoutToggle
asideMenuToggleDirective.$inject = ['$interval'];
function asideMenuToggleDirective($interval) {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function (e) {
      if (element.hasClass('aside-menu-toggler')) {
        angular.element('body').toggleClass('aside-menu-show');
      }
    });
  }
}
function asideMenuHideDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    angular.element(document).bind("mouseup touchend", function (e) {
      var container = angular.element("#aside-menu");
      var btn = angular.element("#aside-menu-toggler");
      if (!container.is(e.target) && container.has(e.target).length === 0 && !btn.is(e.target) && btn.has(e.target).length === 0) {
        if (element.hasClass('aside-menu-show')) {
          element.removeClass('aside-menu-show');
        }
      }
    });
  }
}
function backToTopDirective() {
  var directive = {
    restrict: 'E',
    replace: true,
    template: '<button class="md-fab md-button md-ink-ripple back-to-top"></button>',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    angular.element(window).on('scroll', function () {
      if (angular.element(window).scrollTop() <= 0) {
        angular.element(element).fadeOut();
      }
      else {
        angular.element(element).fadeIn();
      }
    });
    angular.element(element).on('click', function () {
      angular.element('html, body').animate({ scrollTop: 0 }, 'fast');
    });
  }
}
function asidePanelToggleDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function (e) {
      if (element.hasClass('aside-panel-toggle')) {
        angular.element('body').toggleClass('aside-panel-open');
      }
    });
  }
}
imagePreviewDirective.$inject = ['$window'];
function imagePreviewDirective($window) {
  var helper = {
    support: !!($window.FileReader && $window.CanvasRenderingContext2D),
    isFile: function (item) {
      return angular.isObject(item) && item instanceof $window.File;
    },
    isImage: function (file) {
      var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
      return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
    }
  };
  var directive = {
    restrict: 'A',
    template: '<canvas/>',
    link: link
  };
  return directive;

  function link(scope, element, attributes) {
    if (!helper.support) return;

    var params = scope.$eval(attributes.imagePreview);

    if (!helper.isFile(params.file)) return;
    if (!helper.isImage(params.file)) return;

    var canvas = element.find('canvas');
    var reader = new FileReader();

    reader.onload = onLoadFile;
    reader.readAsDataURL(params.file);

    function onLoadFile(event) {
      var img = new Image();
      img.onload = function () {
        var width = params.width || this.width / this.height * params.height;
        var height = params.height || this.height / this.width * params.width;
        canvas.attr({ width: width, height: height });
        canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
      };
      img.src = event.target.result;
    }
  }
}

imageFullScreenDirective.$inject = ['ngDialog'];
function imageFullScreenDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function (e) {
      if (element.hasClass('full-screen')) {
        console.log(element.src);
        var template = '';
        ngDialog.open({
          template: template,
          plain: true
        });
      }
    });
  }
}<commit_msg>Commited from HaNhatLenh at Sun, Aug 27, 2017  1:11:41 PM<commit_after>'use strict';
angular
  .module('core')
  .directive('a', preventClickDirective)
  .directive('a', cardExpandDirective)
  .directive('a', asideMenuToggleDirective)
  .directive('body', asideMenuHideDirective)
  .directive('backToTop', backToTopDirective)
  .directive('button', asidePanelToggleDirective)
  .directive('a', asidePanelToggleDirective)
  .directive('imagePreview', imagePreviewDirective)
  .directive('img', imageFullScreenDirective);

//Prevent click if href="#"
function preventClickDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    if (attrs.href === '#') {
      element.on('click', function (event) {
        event.preventDefault();
      });
    }
  }
}

//Card Collapse
function cardExpandDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function () {
      if (element.hasClass('card-expand-toggle')) {
        element.find('i').toggleClass('r180');
        element.parent().parent().toggleClass('open');
      }
      //
    });
  }
}

//LayoutToggle
asideMenuToggleDirective.$inject = ['$interval'];
function asideMenuToggleDirective($interval) {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function (e) {
      if (element.hasClass('aside-menu-toggler')) {
        angular.element('body').toggleClass('aside-menu-show');
      }
    });
  }
}
function asideMenuHideDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    angular.element(document).bind("mouseup touchend", function (e) {
      var container = angular.element("#aside-menu");
      var btn = angular.element("#aside-menu-toggler");
      if (!container.is(e.target) && container.has(e.target).length === 0 && !btn.is(e.target) && btn.has(e.target).length === 0) {
        if (element.hasClass('aside-menu-show')) {
          element.removeClass('aside-menu-show');
        }
      }
    });
  }
}
function backToTopDirective() {
  var directive = {
    restrict: 'E',
    replace: true,
    template: '<button class="md-fab md-button md-ink-ripple back-to-top"></button>',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    angular.element(window).on('scroll', function () {
      if (angular.element(window).scrollTop() <= 0) {
        angular.element(element).fadeOut();
      }
      else {
        angular.element(element).fadeIn();
      }
    });
    angular.element(element).on('click', function () {
      angular.element('html, body').animate({ scrollTop: 0 }, 'fast');
    });
  }
}
function asidePanelToggleDirective() {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function (e) {
      if (element.hasClass('aside-panel-toggle')) {
        angular.element('body').toggleClass('aside-panel-open');
      }
    });
  }
}
imagePreviewDirective.$inject = ['$window'];
function imagePreviewDirective($window) {
  var helper = {
    support: !!($window.FileReader && $window.CanvasRenderingContext2D),
    isFile: function (item) {
      return angular.isObject(item) && item instanceof $window.File;
    },
    isImage: function (file) {
      var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
      return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
    }
  };
  var directive = {
    restrict: 'A',
    template: '<canvas/>',
    link: link
  };
  return directive;

  function link(scope, element, attributes) {
    if (!helper.support) return;

    var params = scope.$eval(attributes.imagePreview);

    if (!helper.isFile(params.file)) return;
    if (!helper.isImage(params.file)) return;

    var canvas = element.find('canvas');
    var reader = new FileReader();

    reader.onload = onLoadFile;
    reader.readAsDataURL(params.file);

    function onLoadFile(event) {
      var img = new Image();
      img.onload = function () {
        var width = params.width || this.width / this.height * params.height;
        var height = params.height || this.height / this.width * params.width;
        canvas.attr({ width: width, height: height });
        canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
      };
      img.src = event.target.result;
    }
  }
}

imageFullScreenDirective.$inject = ['ngDialog'];
function imageFullScreenDirective(ngDialog) {
  var directive = {
    restrict: 'E',
    link: link
  };
  return directive;

  function link(scope, element, attrs) {
    element.on('click', function (e) {
      if (element.hasClass('full-screen')) {
        console.log(element.src);
        var template = '';
        ngDialog.open({
          template: template,
          plain: true
        });
      }
    });
  }
}<|endoftext|>


<commit_before>exports.config = {
    exclude: [
    ],
    maxInstances: 10,
    sync: true,
    logLevel: 'verbose',
    coloredLogs: true,
    screenshotPath: './errorShots/',
    baseUrl: 'http://localhost:8080',
    waitforTimeout: 10000,
    connectionRetryTimeout: 90000,
    connectionRetryCount: 3,
    services: ['sauce'],
    user: process.env.SAUCE_USERNAME,
    key: process.env.SAUCE_ACCESS_KEY,
    sauceConnect: true,
    framework: 'mocha',
    reporters: ['dot'],
    mochaOpts: {
        ui: 'bdd'
    }
}
<commit_msg>METL-154: Merged changes.<commit_after>exports.config = {
    exclude: [],
    maxInstances: 10,
    sync: true,
    logLevel: 'verbose',
    coloredLogs: true,
    screenshotPath: './errorShots/',
    baseUrl: 'http://localhost:8080',
    waitforTimeout: 10000,
    connectionRetryTimeout: 90000,
    connectionRetryCount: 3,
    services: ['sauce'],
    user: process.env.SAUCE_USERNAME,
    key: process.env.SAUCE_ACCESS_KEY,
    sauceConnect: true,
    framework: 'mocha',
    reporters: ['dot'],
    mochaOpts: {
        ui: 'bdd',
        timeout:999999
    }
}
<|endoftext|>


<commit_before>'use strict';

// Products controller
angular.module('core').controller('ProductsController', ['$window','$http','$scope','$rootScope', '$stateParams', '$location', 'Authentication', 'Products',
  function ($window, $http, $scope, $rootScope, $stateParams, $location, Authentication, Products) {
    $scope.authentication = Authentication;
    $scope.displayType = false; //initialized cultural

    $scope.displayCultural = function () {
      $scope.displayType = true;
    }

    $scope.displayGeological = function () {
      $scope.displayType = false;
    }

    // Create new Product
    $scope.create = function (isValid) {

      var prodType = null;
      var teachType = null;
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'productForm');
        return false;
      }

      if(document.getElementById("proType-cb").checked) {
        prodType = true;
      }
      else {
        prodType = false;
      }

      if(document.getElementById("teacher-cb").checked) {
        teachType = true;
      }
      else {
        teachType = false;
      }

      // Create new Product object
      var product = new Products({
        proType: prodType,
        proTitle: this.proTitle,
        longDes: this.longDes,
        shortDes: this.shortDes,
        imageUrl: this.imageUrl,
        imageOne: this.imageOne,
        imageTwo: this.imageTwo,
        imageThree: this.imageThree,
        imageFour: this.imageFour,
        indvPrice: this.indvPrice,
        eduPrice: this.eduPrice,
        wholePrice: this.wholePrice,
        teacher: teachType
      });

      // Redirect after save
      product.$save(function (response) {
      $location.path('products');

      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });

      console.log('Product has been created');
    };

    //editting shows
    $scope.isEditing = false;

    // Find a list of Products
    $scope.find = function () {
      $scope.products = Products.query();
    };

    // Find existing Products
    $scope.findOne = function () {
      $scope.product = Products.get({
        productId: $stateParams.productId
      });
    };

    //Add one product to Cart
    $scope.addOnetoCart = function(productID){
      $http.post('/api/cart/product/' + productID , {quantity:1}).success(function (res) {
          $rootScope.$broadcast('cartChange');
          $location.path('cart');
      });
    };

  }
]);
<commit_msg>initial commit<commit_after>'use strict';

// Products controller
angular.module('core').controller('ProductsController', ['$window','$http','$scope','$rootScope', '$stateParams', '$location', 'Authentication', 'Products',
  function ($window, $http, $scope, $rootScope, $stateParams, $location, Authentication, Products) {
    $scope.authentication = Authentication;
    $scope.displayType = false; //initialized cultural

    $scope.displayCultural = function () {
      $scope.displayType = true;
    };

    $scope.displayGeological = function () {
      $scope.displayType = false;
    };

    // Create new Product
    $scope.create = function (isValid) {

      var prodType = null;
      var teachType = null;
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'productForm');
        return false;
      }

      if(document.getElementById("proType-cb").checked) {
        prodType = true;
      }
      else {
        prodType = false;
      }

      if(document.getElementById("teacher-cb").checked) {
        teachType = true;
      }
      else {
        teachType = false;
      }

      // Create new Product object
      var product = new Products({
        proType: prodType,
        proTitle: this.proTitle,
        longDes: this.longDes,
        shortDes: this.shortDes,
        imageUrl: this.imageUrl,
        imageOne: this.imageOne,
        imageTwo: this.imageTwo,
        imageThree: this.imageThree,
        imageFour: this.imageFour,
        indvPrice: this.indvPrice,
        eduPrice: this.eduPrice,
        wholePrice: this.wholePrice,
        teacher: teachType
      });

      // Redirect after save
      product.$save(function (response) {
      $location.path('products');

      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });

      console.log('Product has been created');
    };

    //editting shows
    $scope.isEditing = false;

    // Find a list of Products
    $scope.find = function () {
      $scope.products = Products.query();
    };

    // Find existing Products
    $scope.findOne = function () {
      $scope.product = Products.get({
        productId: $stateParams.productId
      });
    };

    //Add one product to Cart
    $scope.addOnetoCart = function(productID){
      $http.post('/api/cart/product/' + productID , {quantity:1}).success(function (res) {
          $rootScope.$broadcast('cartChange');
          $location.path('cart');
      });
    };

  }
]);
<|endoftext|>


<commit_before>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function () {
  'use strict';

  angular.module('pnc.common.select-modals').component('buildConfigMultiSelect', {
    bindings: {
      modalCtrl: '<'
    },
    templateUrl: 'common/select-modals/build-config-multi-select/build-config-multi-select.html',
    controller: Controller
  });

  function Controller() {
    var $ctrl = this;

    // -- Controller API --

    $ctrl.save = save;
    $ctrl.cancel = cancel;
    $ctrl.onRemove = onRemove;
    $ctrl.onAdd = onAdd;

    $ctrl.title = $ctrl.modalCtrl.config.title;
    $ctrl.buildConfigs = angular.copy($ctrl.modalCtrl.config.buildConfigs);

    // --------------------

    function save() {
      $ctrl.modalCtrl.$close($ctrl.buildConfigs);
    }

    function cancel() {
      $ctrl.modalCtrl.$dismiss();
    }

    function getBcIndex(buildConfig) {
      return $ctrl.buildConfigs.findIndex(function (x) { return buildConfig.id === x.id; });
    }

    function onAdd(buildConfig) {
      if (getBcIndex(buildConfig) < 0) {
        $ctrl.buildConfigs.push(buildConfig);
      }
    }

    function onRemove(buildConfig) {
      var index = getBcIndex(buildConfig);

      if (index > -1) {
        $ctrl.buildConfigs.splice(index, 1);
      }
    }
  }

})();
<commit_msg>NCL-3875 Force pf-list-view to be updated<commit_after>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function () {
  'use strict';

  angular.module('pnc.common.select-modals').component('buildConfigMultiSelect', {
    bindings: {
      modalCtrl: '<'
    },
    templateUrl: 'common/select-modals/build-config-multi-select/build-config-multi-select.html',
    controller: Controller
  });

  function Controller() {
    var $ctrl = this;

    // -- Controller API --

    $ctrl.save = save;
    $ctrl.cancel = cancel;
    $ctrl.onRemove = onRemove;
    $ctrl.onAdd = onAdd;

    $ctrl.title = $ctrl.modalCtrl.config.title;
    $ctrl.buildConfigs = angular.copy($ctrl.modalCtrl.config.buildConfigs);

    // --------------------

    function save() {
      $ctrl.modalCtrl.$close($ctrl.buildConfigs);
    }

    function cancel() {
      $ctrl.modalCtrl.$dismiss();
    }

    function getBcIndex(buildConfig) {
      return $ctrl.buildConfigs.findIndex(function (x) { return buildConfig.id === x.id; });
    }

    function onAdd(buildConfig) {
      if (getBcIndex(buildConfig) < 0) {
        // force pf-list-view to be updated
        $ctrl.buildConfigs = angular.copy($ctrl.buildConfigs.concat(buildConfig));
      }
    }

    function onRemove(buildConfig) {
      var index = getBcIndex(buildConfig);

      if (index > -1) {
        $ctrl.buildConfigs.splice(index, 1);
      }
    }
  }

})();
<|endoftext|>


<commit_before>import { toByteArray } from 'base64-js';
import pako from 'pako';

import macro from 'vtk.js/Sources/macro';
import Endian from 'vtk.js/Sources/Common/Core/Endian';
import { DataTypeByteSize } from 'vtk.js/Sources/Common/Core/DataArray/Constants';

const { vtkErrorMacro, vtkDebugMacro } = macro;

let requestCount = 0;

function getContent(url) {
  const el = document.querySelector(`.webResource[data-url="${url}"]`);
  return el ? el.innerHTML : null;
}

function removeLeadingSlash(str) {
  return str[0] === '/' ? str.substr(1) : str;
}

function fetchText(instance = {}, url, options = {}) {
  return new Promise((resolve, reject) => {
    const txt = getContent(url);
    if (txt === null) {
      reject(`No such text ${url}`);
    } else {
      resolve(txt);
    }
  });
}

function fetchJSON(instance = {}, url, options = {}) {
  return new Promise((resolve, reject) => {
    const txt = getContent(removeLeadingSlash(url));
    if (txt === null) {
      reject(`No such JSON ${url}`);
    } else {
      resolve(JSON.parse(txt));
    }
  });
}

function fetchArray(instance = {}, baseURL, array, options = {}) {
  return new Promise((resolve, reject) => {
    const url = removeLeadingSlash(
      [
        baseURL,
        array.ref.basepath,
        options.compression ? `${array.ref.id}.gz` : array.ref.id,
      ].join('/')
    );

    const txt = getContent(url);
    if (txt === null) {
      reject(`No such array ${url}`);
    } else {
      if (array.dataType === 'string') {
        let bText = atob(txt);
        if (options.compression) {
          bText = pako.inflate(bText, { to: 'string' });
        }
        array.values = JSON.parse(bText);
      } else {
        const uint8array = toByteArray(txt);

        array.buffer = new ArrayBuffer(uint8array.length);

        // copy uint8array to buffer
        const view = new Uint8Array(array.buffer);
        view.set(uint8array);

        if (options.compression) {
          if (array.dataType === 'string' || array.dataType === 'JSON') {
            array.buffer = pako.inflate(new Uint8Array(array.buffer), {
              to: 'string',
            });
          } else {
            array.buffer = pako.inflate(new Uint8Array(array.buffer)).buffer;
          }
        }

        if (array.ref.encode === 'JSON') {
          array.values = JSON.parse(array.buffer);
        } else {
          if (Endian.ENDIANNESS !== array.ref.encode && Endian.ENDIANNESS) {
            // Need to swap bytes
            vtkDebugMacro(`Swap bytes of ${array.name}`);
            Endian.swapBytes(array.buffer, DataTypeByteSize[array.dataType]);
          }

          array.values = new window[array.dataType](array.buffer);
        }

        if (array.values.length !== array.size) {
          vtkErrorMacro(
            `Error in FetchArray: ${
              array.name
            } does not have the proper array size. Got ${
              array.values.length
            }, instead of ${array.size}`
          );
        }
      }

      // Done with the ref and work
      delete array.ref;
      if (--requestCount === 0 && instance.invokeBusy) {
        instance.invokeBusy(false);
      }
      if (instance.modified) {
        instance.modified();
      }

      resolve(array);
    }
  });
}

// Export fetch methods
export default {
  fetchJSON,
  fetchText,
  fetchArray,
};
<commit_msg>fix(HtmlDataAccessHelper): ESLint reject(new Error(...))<commit_after>import { toByteArray } from 'base64-js';
import pako from 'pako';

import macro from 'vtk.js/Sources/macro';
import Endian from 'vtk.js/Sources/Common/Core/Endian';
import { DataTypeByteSize } from 'vtk.js/Sources/Common/Core/DataArray/Constants';

const { vtkErrorMacro, vtkDebugMacro } = macro;

let requestCount = 0;

function getContent(url) {
  const el = document.querySelector(`.webResource[data-url="${url}"]`);
  return el ? el.innerHTML : null;
}

function removeLeadingSlash(str) {
  return str[0] === '/' ? str.substr(1) : str;
}

function fetchText(instance = {}, url, options = {}) {
  return new Promise((resolve, reject) => {
    const txt = getContent(url);
    if (txt === null) {
      reject(new Error(`No such text ${url}`));
    } else {
      resolve(txt);
    }
  });
}

function fetchJSON(instance = {}, url, options = {}) {
  return new Promise((resolve, reject) => {
    const txt = getContent(removeLeadingSlash(url));
    if (txt === null) {
      reject(new Error(`No such JSON ${url}`));
    } else {
      resolve(JSON.parse(txt));
    }
  });
}

function fetchArray(instance = {}, baseURL, array, options = {}) {
  return new Promise((resolve, reject) => {
    const url = removeLeadingSlash(
      [
        baseURL,
        array.ref.basepath,
        options.compression ? `${array.ref.id}.gz` : array.ref.id,
      ].join('/')
    );

    const txt = getContent(url);
    if (txt === null) {
      reject(new Error(`No such array ${url}`));
    } else {
      if (array.dataType === 'string') {
        let bText = atob(txt);
        if (options.compression) {
          bText = pako.inflate(bText, { to: 'string' });
        }
        array.values = JSON.parse(bText);
      } else {
        const uint8array = toByteArray(txt);

        array.buffer = new ArrayBuffer(uint8array.length);

        // copy uint8array to buffer
        const view = new Uint8Array(array.buffer);
        view.set(uint8array);

        if (options.compression) {
          if (array.dataType === 'string' || array.dataType === 'JSON') {
            array.buffer = pako.inflate(new Uint8Array(array.buffer), {
              to: 'string',
            });
          } else {
            array.buffer = pako.inflate(new Uint8Array(array.buffer)).buffer;
          }
        }

        if (array.ref.encode === 'JSON') {
          array.values = JSON.parse(array.buffer);
        } else {
          if (Endian.ENDIANNESS !== array.ref.encode && Endian.ENDIANNESS) {
            // Need to swap bytes
            vtkDebugMacro(`Swap bytes of ${array.name}`);
            Endian.swapBytes(array.buffer, DataTypeByteSize[array.dataType]);
          }

          array.values = new window[array.dataType](array.buffer);
        }

        if (array.values.length !== array.size) {
          vtkErrorMacro(
            `Error in FetchArray: ${
              array.name
            } does not have the proper array size. Got ${
              array.values.length
            }, instead of ${array.size}`
          );
        }
      }

      // Done with the ref and work
      delete array.ref;
      if (--requestCount === 0 && instance.invokeBusy) {
        instance.invokeBusy(false);
      }
      if (instance.modified) {
        instance.modified();
      }

      resolve(array);
    }
  });
}

// Export fetch methods
export default {
  fetchJSON,
  fetchText,
  fetchArray,
};
<|endoftext|>


<commit_before>'use strict';

(function() {

    angular.module('app').controller('AlunoDetalheController', ['$scope', '$routeParams', '$log', 'alunoService', 'notificador', '_', function ($scope, $routeParams, $log, alunoService, notificador, _) {

        alunoService.obter($routeParams.matricula)
            .success(function (aluno) {
                $scope.aluno = aluno;
            });

        $scope.concluirCadeira = function (cadeira) {
            var cadeiras = $scope.aluno.grade.cadeiras;
            var index = cadeiras.indexOf(cadeira);
            cadeiras[index].status = 'concluida';

            if (!_.any(cadeiras, { status: 'cursando' })) {
                $scope.aluno.estahMatriculado = false;
            }

            alunoService.alterar($scope.aluno)
                .success(function (alunoAlterado) {
                    $log.log(alunoAlterado);
                })
                .error(function (response) {
                    notificador.erro('Ocorreu um erro. Alteração não realizada.', response);
                });
        };

    }]);

})();
<commit_msg>change error message<commit_after>'use strict';

(function() {

    angular.module('app').controller('AlunoDetalheController', ['$scope', '$routeParams', '$log', 'alunoService', 'notificador', '_', function ($scope, $routeParams, $log, alunoService, notificador, _) {

        alunoService.obter($routeParams.matricula)
            .success(function (aluno) {
                $scope.aluno = aluno;
            });

        $scope.concluirCadeira = function (cadeira) {
            var cadeiras = $scope.aluno.grade.cadeiras;
            var index = cadeiras.indexOf(cadeira);
            cadeiras[index].status = 'concluida';

            if (!_.any(cadeiras, { status: 'cursando' })) {
                $scope.aluno.estahMatriculado = false;
            }

            alunoService.alterar($scope.aluno)
                .success(function (alunoAlterado) {
                    $log.log(alunoAlterado);
                })
                .error(function (response) {
                    notificador.erro('Não foi possível realizar alteração', response);
                });
        };

    }]);

})();
<|endoftext|>