<commit_before>'use strict';

var images;
var percentLoadedRemaining;
var zip;

var selectedImages = [];

var TARGET_IMAGE_WIDTH = 400;

function loadedAllImages() {
    $('.progress').hide();
    $('#select-images-to-download').show();
    selectedImages = [];
    $('#download-btn').hide();

    var $container = $('#select-images').show().html('');
    var imgCol = 0;
    var $row;

    images.forEach(function(image) {
        if (imgCol % 3 === 0) {
            $row = $('
').appendTo($container);
        }

        var displayImage = image.images[0];
        for (var i = 1; i < image.images.length; i++) {
            if (Math.abs(displayImage.width - TARGET_IMAGE_WIDTH) < Math.abs(image.images[i] - TARGET_IMAGE_WIDTH)) {
                displayImage = image.images[i];
            }
        }

        var $col = $('
').appendTo($row);
        $('')
        .css('background-image', 'url('+displayImage.source+')')
        .appendTo($col)
        .click(function() {
            if (selectedImages.indexOf(image) === -1) {
                $col.addClass('selected');
                selectedImages.push(image);
            } else {
                $col.removeClass('selected');
                selectedImages.splice(selectedImages.indexOf(image), 1);
            }
            if (selectedImages.length > 0) {
                $('#download-btn').show()
                .text('Download ' + selectedImages.length + ' images');
            } else {
                $('#download-btn').hide();
            }
        });

        imgCol++;

        return false;
    });
    $row.appendTo($container);
}

function loadNextImages(url, paging) {
    var params = { limit: 5 };
    if (paging) {
        params.after = paging.cursors.after;
    } else {
        images = [];
        percentLoadedRemaining = 1;
        $('.progress').show();
        $('#progressbar').css({ width: '0%' }).show();
    }
    FB.api('/'+url+'/photos?fields=created_time,source,place{location{latitude,longitude}},name,id,images', 'GET', params, function(response) {
        console.log(response);
        images = images.concat(response.data);

        if (response.paging) {
            setTimeout(function() {
                loadNextImages(url, response.paging);
            },1);

            percentLoadedRemaining *= 0.8;
        } else {
            percentLoadedRemaining = 0;
            loadedAllImages();
        }

        $('#progressbar').css({ width: (1-percentLoadedRemaining)*100 + '%' });

    });
}

function downloadImages() {
    selectedImages.forEach(function(image) {

        var exifData = {};
        if(image.created_time) {
            exifData.DateTime = exifData.DateTimeOriginal = image.created_time;
        }

        var largestImage = image.images[0];
        for (var i = 1; i < image.images.length; i++) {
            if (image.images[i].width > largestImage.width) {
                largestImage = image.images[i];
            }
        }

        zip = new JSZip();

        var request = new XMLHttpRequest();
        request.open('GET', image.source, true);
        request.responseType = 'arraybuffer';
        request.onload = function () {
            if ( this.readyState === 4 && this.status === 200 ) {
                var arrayBuffer = request.response; // Note: not request.responseText

                var binary = '';
                var bytes = new Uint8Array( arrayBuffer );
                var len = bytes.byteLength;
                for (var i = 0; i < len; i++) {
                    binary += String.fromCharCode( bytes[ i ] );
                }
                var base64 = window.btoa( binary );

                var zeroth = {};
                var exif = {};
                var gps = {};
                if (image.created_time) {
                    exif[piexif.ExifIFD.DateTimeOriginal] = image.created_time;
                    gps[piexif.GPSIFD.GPSDateStamp] = image.created_time;
                }
                if (image.place && image.place.location && image.place.location.latitude && image.place.location.longitude) {
                    console.log('Got lat&lng');
                    gps[piexif.GPSIFD.GPSDestLatitude] = image.place.location.latitude;
                    gps[piexif.GPSIFD.GPSDestLongitude] = image.place.location.longitude;
                }

                var exifObj = {'0th':zeroth, 'Exif':exif, 'GPS':gps};
                var exifStr = piexif.dump(exifObj);

                var exifModified = piexif.insert(exifStr, 'data:image/jpeg;base64,' + base64);

                var fileName = (image.name ? image.name.substr(0,100).replace(/[\/\\]/g, '') : image.id);
                var suffix = '';
                var suffixNum = 0;
                var ext = '.jpg';

                while (zip.files[fileName + suffix + ext]) {
                    suffix = '_' + (++suffixNum);
                }

                zip.file(
                    fileName + suffix + ext,
                    exifModified.slice(23),
                    {
                        base64: true,
                        date: image.created_time ? new Date(image.created_time) : new Date()
                    }
                );

                if (Object.keys(zip.files).length === selectedImages.length) {
                    // All loaded, let's fire download
                    var content = zip.generate({type:"blob"});
                    // see FileSaver.js
                    saveAs(content, "download.zip");
                }
            }
        };
        request.send(null);
    });
}

$(function() {
    $('#download-btn').click(function() {
        downloadImages();
    });
});

function loadAlbums() {
    FB.api('/me/albums', 'GET', null, function(response) {
        console.log(response);
        var $albums = $('#albums');
        response.data.forEach(function(album) {
            $('<option />')
            .text(album.name)
            .attr('value', album.id)
            .appendTo($albums);
        });
        $albums.change(function() {
            var albumID = $(this).val();
            loadNextImages(albumID);
        });
    });
}

function checkLoginState() {
    FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            $('.login').hide();
            $('#app').show();
            loadAlbums();
        }
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '483759105134186',
        xfbml      : true,
        version    : 'v2.5'
    });

    checkLoginState();
};
<commit_msg>Fixed: Code styling<commit_after>'use strict';

var images;
var percentLoadedRemaining;
var zip;

var selectedImages = [];

var TARGET_IMAGE_WIDTH = 400;

function loadedAllImages() {
    $('.progress').hide();
    $('#select-images-to-download').show();
    selectedImages = [];
    $('#download-btn').hide();

    var $container = $('#select-images').show().html('');
    var imgCol = 0;
    var $row;

    images.forEach(function(image) {
        if (imgCol % 3 === 0) {
            $row = $('
').appendTo($container);
        }

        var displayImage = image.images[0];
        for (var i = 1; i < image.images.length; i++) {
            if (Math.abs(displayImage.width - TARGET_IMAGE_WIDTH) < Math.abs(image.images[i] - TARGET_IMAGE_WIDTH)) {
                displayImage = image.images[i];
            }
        }

        var $col = $('
').appendTo($row);
        $('')
        .css('background-image', 'url('+displayImage.source+')')
        .appendTo($col)
        .click(function() {
            if (selectedImages.indexOf(image) === -1) {
                $col.addClass('selected');
                selectedImages.push(image);
            } else {
                $col.removeClass('selected');
                selectedImages.splice(selectedImages.indexOf(image), 1);
            }
            if (selectedImages.length > 0) {
                $('#download-btn').show()
                .text('Download ' + selectedImages.length + ' images');
            } else {
                $('#download-btn').hide();
            }
        });

        imgCol++;

        return false;
    });
    $row.appendTo($container);
}

function loadNextImages(url, paging) {
    var params = { limit: 5 };
    if (paging) {
        params.after = paging.cursors.after;
    } else {
        images = [];
        percentLoadedRemaining = 1;
        $('.progress').show();
        $('#progressbar').css({ width: '0%' }).show();
    }
    FB.api('/'+url+'/photos?fields=created_time,source,place{location{latitude,longitude}},name,id,images', 'GET', params, function(response) {
        console.log(response);
        images = images.concat(response.data);

        if (response.paging) {
            setTimeout(function() {
                loadNextImages(url, response.paging);
            },1);

            percentLoadedRemaining *= 0.8;
        } else {
            percentLoadedRemaining = 0;
            loadedAllImages();
        }

        $('#progressbar').css({ width: (1-percentLoadedRemaining)*100 + '%' });

    });
}

function downloadImages() {
    selectedImages.forEach(function(image) {

        var exifData = {};
        if(image.created_time) {
            exifData.DateTime = exifData.DateTimeOriginal = image.created_time;
        }

        var largestImage = image.images[0];
        for (var i = 1; i < image.images.length; i++) {
            if (image.images[i].width > largestImage.width) {
                largestImage = image.images[i];
            }
        }

        zip = new JSZip();

        var request = new XMLHttpRequest();
        request.open('GET', image.source, true);
        request.responseType = 'arraybuffer';
        request.onload = function () {
            if ( this.readyState === 4 && this.status === 200 ) {
                var arrayBuffer = request.response; // Note: not request.responseText

                var binary = '';
                var bytes = new Uint8Array( arrayBuffer );
                var len = bytes.byteLength;
                for (var i = 0; i < len; i++) {
                    binary += String.fromCharCode( bytes[ i ] );
                }
                var base64 = window.btoa( binary );

                var zeroth = {};
                var exif = {};
                var gps = {};
                if (image.created_time) {
                    exif[piexif.ExifIFD.DateTimeOriginal] = image.created_time;
                    gps[piexif.GPSIFD.GPSDateStamp] = image.created_time;
                }
                if (image.place && image.place.location && image.place.location.latitude && image.place.location.longitude) {
                    console.log('Got lat&lng');
                    gps[piexif.GPSIFD.GPSDestLatitude] = image.place.location.latitude;
                    gps[piexif.GPSIFD.GPSDestLongitude] = image.place.location.longitude;
                }

                var exifObj = {'0th':zeroth, 'Exif':exif, 'GPS':gps};
                var exifStr = piexif.dump(exifObj);

                var exifModified = piexif.insert(exifStr, 'data:image/jpeg;base64,' + base64);

                var fileName = (image.name ? image.name.substr(0,100).replace(/[\/\\]/g, '') : image.id);
                var suffix = '';
                var suffixNum = 0;
                var ext = '.jpg';

                while (zip.files[fileName + suffix + ext]) {
                    suffix = '_' + (++suffixNum);
                }

                zip.file(
                    fileName + suffix + ext,
                    exifModified.slice(23),
                    {
                        base64: true,
                        date: image.created_time ? new Date(image.created_time) : new Date()
                    }
                );

                if (Object.keys(zip.files).length === selectedImages.length) {
                    // All loaded, let's fire download
                    var content = zip.generate({type:'blob'});
                    // see FileSaver.js
                    saveAs(content, 'download.zip');
                }
            }
        };
        request.send(null);
    });
}

$(function() {
    $('#download-btn').click(function() {
        downloadImages();
    });
});

function loadAlbums() {
    FB.api('/me/albums', 'GET', null, function(response) {
        console.log(response);
        var $albums = $('#albums');
        response.data.forEach(function(album) {
            $('<option />')
            .text(album.name)
            .attr('value', album.id)
            .appendTo($albums);
        });
        $albums.change(function() {
            var albumID = $(this).val();
            loadNextImages(albumID);
        });
    });
}

function checkLoginState() {
    FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            $('.login').hide();
            $('#app').show();
            loadAlbums();
        }
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '483759105134186',
        xfbml      : true,
        version    : 'v2.5'
    });

    checkLoginState();
};
<|endoftext|>


<commit_before>/*!
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  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';

  var querySelector = document.querySelector.bind(document);

  var navdrawerContainer = querySelector('.navdrawer-container');
  var body = querySelector('body');
  var appbarElement = querySelector('.app-bar');
  var menuBtn = querySelector('.menu');
  var main = querySelector('main');

  function closeMenu() {
    body.classList.remove('open');
    appbarElement.classList.remove('open');
    navdrawerContainer.classList.remove('open');
  }

  function toggleMenu() {
    body.classList.toggle('open');
    appbarElement.classList.toggle('open');
    navdrawerContainer.classList.toggle('open');
  }

  main.addEventListener('click', closeMenu);
  menuBtn.addEventListener('click', toggleMenu);
  navdrawerContainer.addEventListener('click', function (event) {
    if (event.target.nodeName === 'A' || event.target.nodeName === 'LI') {
      closeMenu();
    }
  });
})();
<commit_msg>Address feedback on #238<commit_after>/*!
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  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';

  var querySelector = document.querySelector.bind(document);

  var navdrawerContainer = querySelector('.navdrawer-container');
  var body = querySelector('document.body');
  var appbarElement = querySelector('.app-bar');
  var menuBtn = querySelector('.menu');
  var main = querySelector('main');

  function closeMenu() {
    body.classList.remove('open');
    appbarElement.classList.remove('open');
    navdrawerContainer.classList.remove('open');
  }

  function toggleMenu() {
    body.classList.toggle('open');
    appbarElement.classList.toggle('open');
    navdrawerContainer.classList.toggle('open');
  }

  main.addEventListener('click', closeMenu);
  menuBtn.addEventListener('click', toggleMenu);
  navdrawerContainer.addEventListener('click', function (event) {
    if (event.target.nodeName === 'A' || event.target.nodeName === 'LI') {
      closeMenu();
    }
  });
})();
<|endoftext|>


<commit_before>// #####################################################################################################################
// #BASE#
// Basic logic django filer
'use strict';

var Cl = window.Cl || {};

/* globals Mediator, django */

// mediator init
Cl.mediator = new Mediator();

(function ($) {
    $(function () {
        var showErrorTimeout;

        window.showError = function (message) {
            var messages = $('.messagelist');
            var header = $('#header');
            var filerErrorClass = 'js-filer-error';
            var tpl = '

{msg}

';
            var msg = tpl.replace('{msg}', message);

            messages.length ? messages.replaceWith(msg) : header.after(msg);

            if (showErrorTimeout) {
                clearTimeout(showErrorTimeout);
            }

            showErrorTimeout = setTimeout(function () {
                $('.' + filerErrorClass).remove();
            }, 3000);
        };

        // Focal point logic init
        if (Cl.FocalPoint) {
            new Cl.FocalPoint();
        }

        // Toggler init
        if (Cl.Toggler) {
            new Cl.Toggler();
        }

        $('.js-filter-files').on('focus blur', function (event) {
            var container = $(this).closest('.js-filter-files-container');
            var dropdownTrigger = container.find('.dropdown-container a');

            if (event.type === 'focus') {
                container.addClass('is-focused');
            } else {
                if (!dropdownTrigger.is(event.relatedTarget)) {
                    container.removeClass('is-focused');
                }
            }
        });

        // Focus on the search field on page load
        (function () {
            var filter = $('.js-filter-files');
            var containerSelector = '.js-filter-files-container';

            if (filter.length) {
                filter.focus().closest(containerSelector)
                    .removeClass('is-focused');
                filter.on('keydown', function () {
                    $(this).closest(containerSelector).addClass('is-focused');
                });

                $(containerSelector).find('.dropdown-container').on('show.bs.dropdown', function () {
                    $(containerSelector).addClass('is-focused');
                }).on('hide.bs.dropdown', function () {
                    $(containerSelector).removeClass('is-focused');
                });
            }
        }());

        // show counter if file is selected
        (function () {
            var table = $('.navigator-table').find('tr');
            var actionList = $('.actions-wrapper');
            var actionSelect = $('.action-select, #action-toggle, .actions .clear a');

            actionSelect.on('change click', function () {
                actionList.toggleClass('action-selected', table.hasClass('selected'));
            });
        }());

        (function () {
            var actionsMenu = $('.js-actions-menu');
            var dropdown = actionsMenu.find('.dropdown-menu');
            var actionsSelect = $('.actions select[name="action"]');
            var actionsSelectOptions = actionsSelect.find('option');
            var actionsGo = $('.actions button[type="submit"]');
            var html = '';
            var actionDelete = $('.js-action-delete');
            var actionCopy = $('.js-action-copy');
            var actionMove = $('.js-action-move');
            var valueDelete = 'delete_files_or_folders';
            var valueCopy = 'copy_files_and_folders';
            var valueMove = 'move_files_and_folders';
            var navigatorTableSelected = $('.navigator-table').find('tr').hasClass('selected');

            // triggers delete copy and move actions on separate buttons
            function actionsButton(optionValue, actionButton) {
                actionsSelectOptions.each(function () {
                    if (this.value === optionValue) {
                        actionButton.show();

                        actionButton.on('click', function (e) {
                            e.preventDefault();
                            if (navigatorTableSelected) {
                                actionsSelect.val(optionValue).prop('selected', true);
                                actionsGo.trigger('click');
                            }
                        });
                    }
                });
            }
            actionsButton(valueDelete, actionDelete);
            actionsButton(valueCopy, actionCopy);
            actionsButton(valueMove, actionMove);

            // mocking the action buttons to work in frontend UI
            actionsSelectOptions.each(function (index) {
                var className = '';
                if (index !== 0) {
                    if (this.value === valueDelete || this.value === valueCopy || this.value === valueMove) {
                        className = 'class="hidden"';
                    }
                    html += '
' + $(this).text() + '
';

                }
            });
            dropdown.append(html);

            dropdown.on('click', 'a', function (clickEvent) {
                var targetIndex = $(this).closest('li').index() + 1;

                clickEvent.preventDefault();

                actionsSelect.find('option').eq(targetIndex).prop('selected', true);
                actionsGo.trigger('click');
            });

            actionsMenu.on('click', function (e) {
                if (!navigatorTableSelected) {
                    e.preventDefault();
                    e.stopPropagation();
                }
            });
        }());
    });
})(django.jQuery);
<commit_msg>caches navigator table row<commit_after>// #####################################################################################################################
// #BASE#
// Basic logic django filer
'use strict';

var Cl = window.Cl || {};

/* globals Mediator, django */

// mediator init
Cl.mediator = new Mediator();

(function ($) {
    $(function () {
        var showErrorTimeout;

        window.showError = function (message) {
            var messages = $('.messagelist');
            var header = $('#header');
            var filerErrorClass = 'js-filer-error';
            var tpl = '

{msg}

';
            var msg = tpl.replace('{msg}', message);

            messages.length ? messages.replaceWith(msg) : header.after(msg);

            if (showErrorTimeout) {
                clearTimeout(showErrorTimeout);
            }

            showErrorTimeout = setTimeout(function () {
                $('.' + filerErrorClass).remove();
            }, 3000);
        };

        // Focal point logic init
        if (Cl.FocalPoint) {
            new Cl.FocalPoint();
        }

        // Toggler init
        if (Cl.Toggler) {
            new Cl.Toggler();
        }

        $('.js-filter-files').on('focus blur', function (event) {
            var container = $(this).closest('.js-filter-files-container');
            var dropdownTrigger = container.find('.dropdown-container a');

            if (event.type === 'focus') {
                container.addClass('is-focused');
            } else {
                if (!dropdownTrigger.is(event.relatedTarget)) {
                    container.removeClass('is-focused');
                }
            }
        });

        // Focus on the search field on page load
        (function () {
            var filter = $('.js-filter-files');
            var containerSelector = '.js-filter-files-container';

            if (filter.length) {
                filter.focus().closest(containerSelector)
                    .removeClass('is-focused');
                filter.on('keydown', function () {
                    $(this).closest(containerSelector).addClass('is-focused');
                });

                $(containerSelector).find('.dropdown-container').on('show.bs.dropdown', function () {
                    $(containerSelector).addClass('is-focused');
                }).on('hide.bs.dropdown', function () {
                    $(containerSelector).removeClass('is-focused');
                });
            }
        }());

        // show counter if file is selected
        (function () {
            var table = $('.navigator-table').find('tr');
            var actionList = $('.actions-wrapper');
            var actionSelect = $('.action-select, #action-toggle, .actions .clear a');

            actionSelect.on('change click', function () {
                actionList.toggleClass('action-selected', table.hasClass('selected'));
            });
        }());

        (function () {
            var actionsMenu = $('.js-actions-menu');
            var dropdown = actionsMenu.find('.dropdown-menu');
            var actionsSelect = $('.actions select[name="action"]');
            var actionsSelectOptions = actionsSelect.find('option');
            var actionsGo = $('.actions button[type="submit"]');
            var html = '';
            var actionDelete = $('.js-action-delete');
            var actionCopy = $('.js-action-copy');
            var actionMove = $('.js-action-move');
            var valueDelete = 'delete_files_or_folders';
            var valueCopy = 'copy_files_and_folders';
            var valueMove = 'move_files_and_folders';
            var navigatorTableSelected = $('.navigator-table').find('tr');

            // triggers delete copy and move actions on separate buttons
            function actionsButton(optionValue, actionButton) {
                actionsSelectOptions.each(function () {
                    if (this.value === optionValue) {
                        actionButton.show();
                        actionButton.on('click', function (e) {
                            e.preventDefault();
                            if (navigatorTableSelected.hasClass('selected')) {
                                actionsSelect.val(optionValue).prop('selected', true);
                                actionsGo.trigger('click');
                            }
                        });
                    }
                });
            }
            actionsButton(valueDelete, actionDelete);
            actionsButton(valueCopy, actionCopy);
            actionsButton(valueMove, actionMove);

            // mocking the action buttons to work in frontend UI
            actionsSelectOptions.each(function (index) {
                var className = '';
                if (index !== 0) {
                    if (this.value === valueDelete || this.value === valueCopy || this.value === valueMove) {
                        className = 'class="hidden"';
                    }
                    html += '
' + $(this).text() + '
';

                }
            });
            dropdown.append(html);

            dropdown.on('click', 'a', function (clickEvent) {
                var targetIndex = $(this).closest('li').index() + 1;

                clickEvent.preventDefault();

                actionsSelect.find('option').eq(targetIndex).prop('selected', true);
                actionsGo.trigger('click');
            });

            actionsMenu.on('click', function (e) {
                if (!navigatorTableSelected.hasClass('selected')) {
                    e.preventDefault();
                    e.stopPropagation();
                }
            });
        }());
    });
})(django.jQuery);
<|endoftext|>


<commit_before>"use strict";
var EAN13;

EAN13 = (function() {
  EAN13.prototype.defaults = {
    number: true,
    prefix: true,
    color: "#000",
    offsetX: 0,
    offsetY: 0,
    onValid: function() {},
    onInvalid: function() {},
    onSuccess: function() {},
    onError: function() {}
  };

  EAN13.prototype.options = {};

  function EAN13() {}

  EAN13.prototype.draw = function(element, number, _options) {
    var code;
    this.parseOptions(_options);
    code = this.getCode(number);
    return this.print(element, code, number);
  };

  EAN13.prototype.print = function(element, code, number) {
    var border_height, char, chars, context, height, i, item_width, layout, left, lines, offset, offsetX, offsetY, prefix, width, _i, _j, _len, _len1;
    layout = {
      prefix_offset: 0.06,
      font_stretch: 0.073,
      border_line_height_number: 0.9,
      border_line_height: 1,
      line_height: 0.9,
      font_size: 0.15,
      font_y: 1.03,
      text_offset: 4.5
    };
    offsetX = this.options.offsetX;
    offsetY = this.options.offsetY;
    width = this.options.width || element.width;
    width = (this.options.prefix ? width * 0.8 : width);
    height = this.options.height || element.height;
    if (this.options.number) {
      border_height = layout.border_line_height_number * height;
    } else {
      border_height = layout.border_line_height * height;
    }
    height = layout.line_height * border_height;
    item_width = width / 95;
    if (element.getContext) {
      context = element.getContext("2d");
      this.clear(element, context);
      context.fillStyle = this.options.color;
      left = (this.options.prefix ? element.width * layout.prefix_offset : 0);
      lines = code.split("");
      context.fillRect(offsetX + left, offsetY, item_width, border_height);
      left = left + item_width * 2;
      context.fillRect(offsetX + left, offsetY, item_width, border_height);
      left = left + item_width;
      i = 0;
      while (i < 42) {
        if (lines[i] === "1") {
          context.fillRect(offsetX + left, offsetY, item_width, height);
        }
        left = left + item_width;
        i++;
      }
      left = left + item_width;
      context.fillRect(offsetX + left, offsetY, item_width, border_height);
      left = left + item_width * 2;
      context.fillRect(offsetX + left, offsetY, item_width, border_height);
      left = left + item_width * 2;
      i = 42;
      while (i < 84) {
        if (lines[i] === "1") {
          context.fillRect(offsetX + left, offsetY, item_width, height);
        }
        left = left + item_width;
        i++;
      }
      context.fillRect(offsetX + left, offsetY, item_width, border_height);
      left = left + item_width * 2;
      context.fillRect(offsetX + left, offsetY, item_width, border_height);
      if (this.options.number) {
        context.font = layout.font_size * height + "px monospace";
        prefix = number.substr(0, 1);
        if (this.options.prefix) {
          context.fillText(prefix, offsetX + 0, offsetY + (border_height * layout.font_y));
        }
        offset = item_width * layout.text_offset + (this.options.prefix ? layout.prefix_offset * element.width : 0);
        chars = number.substr(1, 6).split("");
        for (_i = 0, _len = chars.length; _i < _len; _i++) {
          char = chars[_i];
          context.fillText(char, offsetX + offset, offsetY + (border_height * layout.font_y));
          offset += layout.font_stretch * width;
        }
        offset = 49 * item_width + (this.options.prefix ? layout.prefix_offset * element.width : 0) + layout.text_offset;
        chars = number.substr(7).split("");
        for (_j = 0, _len1 = chars.length; _j < _len1; _j++) {
          char = chars[_j];
          context.fillText(char, offsetX + offset, offsetY + (border_height * layout.font_y));
          offset += layout.font_stretch * width;
        }
      }
      if (this.options.onSuccess) {
        return this.options.onSuccess.call();
      }
    } else {
      if (this.options.onError) {
        return this.options.onError.call();
      }
    }
  };

  EAN13.prototype.clear = function(element, context) {
    return context.clearRect(this.options.offsetX, this.options.offsetY, this.options.width || element.width, this.options.height || element.height);
  };

  EAN13.prototype.parseOptions = function(_options) {

    this.options=_options;
    for(var option in this.defaults)
      this.options[option] = _options[option] || this.defaults[option];
    ;
    return null;
  };

  EAN13.prototype.getCode = function(number) {
    var c_encoding, code, countries, i, parts, raw_number, x, y, z;
    if (this.validate(number)) {
      if (this.options.onValid) {
        this.options.onValid.call();
      }
    } else {
      if (this.options.onInvalid) {
        this.options.onInvalid.call();
      }
    }
    x = ["0001101", "0011001", "0010011", "0111101", "0100011", "0110001", "0101111", "0111011", "0110111", "0001011"];
    y = ["0100111", "0110011", "0011011", "0100001", "0011101", "0111001", "0000101", "0010001", "0001001", "0010111"];
    z = ["1110010", "1100110", "1101100", "1000010", "1011100", "1001110", "1010000", "1000100", "1001000", "1110100"];
    countries = ["xxxxxx", "xxyxyy", "xxyyxy", "xxyyyx", "xyxxyy", "xyyxxy", "xyyyxx", "xyxyxy", "xyxyyx", "xyyxyx"];
    code = "";
    c_encoding = countries[parseInt(number.substr(0, 1), 10)].split("");
    raw_number = number.substr(1);
    parts = raw_number.split("");
    i = 0;
    while (i < 6) {
      if (c_encoding[i] === "x") {
        code += x[parts[i]];
      } else {
        code += y[parts[i]];
      }
      i++;
    }
    i = 6;
    while (i < 12) {
      code += z[parts[i]];
      i++;
    }
    return code;
  };

  EAN13.prototype.validate = function(number) {
    var chars, counter, result, value, _i, _len;
    result = null;
    chars = number.split("");
    counter = 0;
    for (_i = 0, _len = chars.length; _i < _len; _i++) {
      value = chars[_i];
      if (_i % 2 === 0) {
        counter += parseInt(value, 10);
      } else {
        counter += 3 * parseInt(value, 10);
      }
    }
    if ((counter % 10) === 0) {
      result = true;
    } else {
      result = false;
    }
    return result;
  };

  return EAN13;

})();

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  module.exports = EAN13;
}
<commit_msg>removed unminified<commit_after><|endoftext|>


<commit_before>(function(){

})();<commit_msg>default state works<commit_after>(function () {
  var SocialMedia   = SocialMedia || {};
  SocialMedia.icons = {
    list: function () {
      var ic = {
        facebook: {
          name: 'facebook',
          url: 'http://www.facebook.com/sharer.php?u=',
          fawesome: {
            official: 'fa fa-facebook-official',
            standard: 'fa fa-facebook',
            square: 'fa fa-facebook-square'
          }
        },
        twitter: {
          name: 'twitter',
          url: 'http://twitter.com/share?url=',
          fawesome: {
            standard: 'fa fa-twitter',
            square: 'fa fa-twitter-square'
          }
        },
        linkedin: {
          name: 'linkedin',
          url: 'http://www.linkedin.com/shareArticle?mini=true&url=',
          fawesome: {
            standard: 'fa fa-linkedin',
            square: 'fa fa-linkedin-square'
          }
        },
        pinterest: {
          name: 'pinterest',
          url: 'http://pinterest.com/pin/create/button/?url=',
          fawesome: {
            official: 'fa fa-pinterest-p',
            standard: 'fa fa-pinterest',
            square: 'fa fa-pinterest-square'
          }
        }
      };
      return ic;
    },
    build: function (cls) {
      return '';
      /*var iconList = SocialMedia.icons.list();
       return '';*/
    }
  };

  SocialMedia.config = {
    setupData: function () {
      var dt = {
        pageURL: window.location.href,
        defaultElement: 'socialMedia'
      };
      return dt;
    },
    init: function () {
      if (arguments.length && typeof arguments === "object") {
        console.log(arguments);
      }
    },
    makeAnchor: function (cls, txt, hrf) {
      var selector = SocialMedia.config.setupData();
      for (var i = 0; i < document.getElementsByClassName(selector.defaultElement).length; i++) {
        var anchorLink = document.createElement('a');
        var anchorText = document.getElementsByClassName(selector.defaultElement)[i];
        var icon       = document.createTextNode(txt);
        anchorLink.setAttribute('class', cls);
        anchorLink.setAttribute('href', hrf);
        anchorText.appendChild(anchorLink);
        anchorLink.appendChild(icon);
      }

    },
    getAllElemets: function () {
      var iconList = SocialMedia.icons.list();
      for (var key in iconList) {
        var iconTag = SocialMedia.icons.build(iconList[key].fawesome.standard);
        var path    = SocialMedia.config.setupData();
        var url     = iconList[key].url + path.pageURL;
        SocialMedia.config.makeAnchor(iconList[key].fawesome.standard, iconTag, url);
      }
    }
  };
  SocialMedia.config.getAllElemets();
})();<|endoftext|>


<commit_before>var register = {};

register.model = {
    teamOne: {
      player: [m.prop(''), m.prop('')]
    },
    teamTwo: {
      player: [m.prop(''), m.prop('')]
    },
    teamOneScore: m.prop(''),
    teamTwoScore: m.prop('')
}

register.controller = () => {
  var mapper = (team) => {
    return team.player.map((player) => {
        return player();
      })
  }
  var update = (e) => {
    e.preventDefault();
    var data = {
      teams: [mapper(register.model.teamOne), mapper(register.model.teamTwo)],
      score: [register.model.teamOneScore(), register.model.teamTwoScore()]
    }
    console.log(data)
    m.request({ method: 'POST', url: '/api/register', data: data})
      .then(() =>{
        console.log('got a response')
      });
  };

  return {
    update: update
  }
};

register.view = (ctrl) => {
  return [
    m('h1', { class: 'heading1' }, 'Register result'),
    m('form', [
      m('input', {
        value: register.model.teamOne.player[0](),
        onchange: m.withAttr('value', register.model.teamOne.player[0]),
        class: 'inputPlayer',
        placeholder: 'Player 3'
      }),
      m('span', { class: 'playerSeperator' }, ' and '),
      m('input', {
        value: register.model.teamOne.player[1](),
        onchange: m.withAttr('value', register.model.teamOne.player[1]),
        class: 'inputPlayer',
        placeholder: 'Player 4'
      }),
      m('h2', { class: ['heading2__lessVSpace'] }, 'vs.'),
      m('input', {
        value: register.model.teamTwo.player[0](),
        onchange: m.withAttr('value', register.model.teamTwo.player[0]),
        class: 'inputPlayer',
        placeholder: 'Player 3'
      }),
      m('span', { class: 'playerSeperator' }, ' and '),
      m('input', {
        value: register.model.teamTwo.player[1](),
        onchange: m.withAttr('value', register.model.teamTwo.player[1]),
        class: 'inputPlayer',
        placeholder: 'Player 4'
      }),
      m('div', { class: 'teamScore-container' }, [
        m('h2', { class: 'heading2__lessVSpace' },  'Result'),
        m('input', {
          value: register.model.teamOneScore(),
          onchange: m.withAttr('value', register.model.teamOneScore),
          class: 'teamScore',
          placeholder: 'Team One'
        }),
        m('div', { class: 'teamScore-divider' }),
        m('input', {
          value: register.model.teamTwoScore(),
          onchange: m.withAttr('value', register.model.teamTwoScore),
          class: 'teamScore',
          placeholder: 'Team Two'
        }),
        m('button', { class: 'submitButton-register', onclick: ctrl.update} ,'Register')])])
  ]
};

m.module(document.getElementById('app'), register);
<commit_msg>(chore) Wops forgot to rename the placeholder value<commit_after>var register = {};

register.model = {
    teamOne: {
      player: [m.prop(''), m.prop('')]
    },
    teamTwo: {
      player: [m.prop(''), m.prop('')]
    },
    teamOneScore: m.prop(''),
    teamTwoScore: m.prop('')
}

register.controller = () => {
  var mapper = (team) => {
    return team.player.map((player) => {
        return player();
      })
  }
  var update = (e) => {
    e.preventDefault();
    var data = {
      teams: [mapper(register.model.teamOne), mapper(register.model.teamTwo)],
      score: [register.model.teamOneScore(), register.model.teamTwoScore()]
    }
    console.log(data)
    m.request({ method: 'POST', url: '/api/register', data: data})
      .then(() =>{
        console.log('got a response')
      });
  };

  return {
    update: update
  }
};

register.view = (ctrl) => {
  return [
    m('h1', { class: 'heading1' }, 'Register result'),
    m('form', [
      m('input', {
        value: register.model.teamOne.player[0](),
        onchange: m.withAttr('value', register.model.teamOne.player[0]),
        class: 'inputPlayer',
        placeholder: 'Player 1'
      }),
      m('span', { class: 'playerSeperator' }, ' and '),
      m('input', {
        value: register.model.teamOne.player[1](),
        onchange: m.withAttr('value', register.model.teamOne.player[1]),
        class: 'inputPlayer',
        placeholder: 'Player 2'
      }),
      m('h2', { class: ['heading2__lessVSpace'] }, 'vs.'),
      m('input', {
        value: register.model.teamTwo.player[0](),
        onchange: m.withAttr('value', register.model.teamTwo.player[0]),
        class: 'inputPlayer',
        placeholder: 'Player 3'
      }),
      m('span', { class: 'playerSeperator' }, ' and '),
      m('input', {
        value: register.model.teamTwo.player[1](),
        onchange: m.withAttr('value', register.model.teamTwo.player[1]),
        class: 'inputPlayer',
        placeholder: 'Player 4'
      }),
      m('div', { class: 'teamScore-container' }, [
        m('h2', { class: 'heading2__lessVSpace' },  'Result'),
        m('input', {
          value: register.model.teamOneScore(),
          onchange: m.withAttr('value', register.model.teamOneScore),
          class: 'teamScore',
          placeholder: 'Team One'
        }),
        m('div', { class: 'teamScore-divider' }),
        m('input', {
          value: register.model.teamTwoScore(),
          onchange: m.withAttr('value', register.model.teamTwoScore),
          class: 'teamScore',
          placeholder: 'Team Two'
        }),
        m('button', { class: 'submitButton-register', onclick: ctrl.update} ,'Register')])])
  ]
};

m.module(document.getElementById('app'), register);
<|endoftext|>


<commit_before>
"use strict";

let isDate = new RegExp(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
let mapper = {
    Jan: '01',
    Feb: '02',
    Mar: '03',
    Apr: '04',
    May: '05',
    Jun: '06',
    Jul: '07',
    Aug: '08',
    Sep: '09',
    Oct: '10',
    Nov: '11',
    Dec: '12'
};

function map(month) {
    return mapper[month];
};

class Model {

    constructor() {
        this.$initial = undefined;
        this.$data = {};
        this.$deleted = false;
    }

    static $create(data = {}, derivedClass = undefined) {
        derivedClass = derivedClass || Model;
        let instance = new derivedClass();
        instance.$load(data);
        instance.$initial = undefined;
        return instance;
    }

    $load(data = {}) {
        this.$initial = data;
        for (let key in data) {
            let checkDate = isDate.exec(data[key]);
            if (checkDate) {
                checkDate.shift();
                data[key] = new Date(...checkDate);
            }
            var props = {enumerable: true, configurable: true};
            if (!this.hasOwnProperty(key)) {
                props.get = () => {
                    return this.$data[key];
                };
                props.set = value => {
                    this.$data[key] = value;
                };
            }
            Object.defineProperty(this, key, props);
            this.$data[key] = data[key];
        }
        return this;
    }

    $update() {
        for (let field in this) {
            if (field.substring(0, 1) == '$') {
                continue;
            }
            if (typeof this[field] == 'object' && this[field] != null) {
                if ('$delete' in this[field] && this[field].$deleted) {
                    this[field].$delete();
                } else if ('$update' in this[field] && this[field].$dirty) {
                    this[field].$update();
                } else if ('map' in this[field]) {
                    this[field].map(item => {
                        if (typeof item == 'object') {
                            if ('$delete' in item && item.$deleted) {
                                item.$delete();
                            } else if ('$update' in item && item.$dirty) {
                                item.$update();
                            }
                        }
                    });
                }
            }
            if (this.$initial[field]) {
                this.$initial[field] = this.$data[field];
            }
        }
    }

    get $new() {
        return this.$initial === undefined;
    }

    get $dirty() {
        if (this.$deleted) {
            return true;
        }
        if (this.$new) {
            return false;
        }
        for (let key in this) {
            if (key.substring(0, 1) == '$') {
                continue;
            }
            if (key in this.$data && this.$data[key] != this.$initial[key]) {
                return true;
            } else if (typeof this[key] == 'object' && this[key] != null) {
                if ('map' in this[key]) {
                    let dirty = false;
                    this[key].map(elem => {
                        if (typeof elem == 'object' && elem.$dirty || elem.$deleted) {
                            dirty = true;
                        }
                    });
                    if (dirty) {
                        return true;
                    }
                } else if (this[key].$dirty || this[key].$deleted) {
                    return true;
                }
            }
        }
        return false;
    }

    $export() {
        let data = {};
        for (let prop in this) {
            if (prop.substring(0, 1) == '$') {
                continue;
            }
            if (this[prop] && typeof this[prop] == 'object' && 'getFullYear' in this[prop]) {
                let d = (this[prop] + '').split(' ');
                data[prop] = [d[3], map(d[1]), d[2]].join('-') + ' '+ d[4];
            } else {
                data[prop] = this[prop];
            }
        }
        return data;
    }

};

export {Model};

<commit_msg>moved to post modifier<commit_after>
"use strict";

let isDate = new RegExp(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
let mapper = {
    Jan: '01',
    Feb: '02',
    Mar: '03',
    Apr: '04',
    May: '05',
    Jun: '06',
    Jul: '07',
    Aug: '08',
    Sep: '09',
    Oct: '10',
    Nov: '11',
    Dec: '12'
};

function map(month) {
    return mapper[month];
};

class Model {

    constructor() {
        this.$initial = undefined;
        this.$data = {};
        this.$deleted = false;
    }

    static $create(data = {}, derivedClass = undefined) {
        derivedClass = derivedClass || Model;
        let instance = new derivedClass();
        instance.$load(data);
        instance.$initial = undefined;
        return instance;
    }

    $load(data = {}) {
        this.$initial = data;
        for (let key in data) {
            let checkDate = isDate.exec(data[key]);
            if (checkDate) {
                checkDate.shift();
                data[key] = new Date(...checkDate);
            }
            var props = {enumerable: true, configurable: true};
            if (!this.hasOwnProperty(key)) {
                props.get = () => {
                    return this.$data[key];
                };
                props.set = value => {
                    this.$data[key] = value;
                };
            }
            Object.defineProperty(this, key, props);
            this.$data[key] = data[key];
        }
        return this;
    }

    $update() {
        for (let field in this) {
            if (field.substring(0, 1) == '$') {
                continue;
            }
            if (typeof this[field] == 'object' && this[field] != null) {
                if ('$delete' in this[field] && this[field].$deleted) {
                    this[field].$delete();
                } else if ('$update' in this[field] && this[field].$dirty) {
                    this[field].$update();
                } else if ('map' in this[field]) {
                    this[field].map(item => {
                        if (typeof item == 'object') {
                            if ('$delete' in item && item.$deleted) {
                                item.$delete();
                            } else if ('$update' in item && item.$dirty) {
                                item.$update();
                            }
                        }
                    });
                }
            }
            if (this.$initial[field]) {
                this.$initial[field] = this.$data[field];
            }
        }
    }

    get $new() {
        return this.$initial === undefined;
    }

    get $dirty() {
        if (this.$deleted) {
            return true;
        }
        if (this.$new) {
            return false;
        }
        for (let key in this) {
            if (key.substring(0, 1) == '$') {
                continue;
            }
            if (key in this.$data && this.$data[key] != this.$initial[key]) {
                return true;
            } else if (typeof this[key] == 'object' && this[key] != null) {
                if ('map' in this[key]) {
                    let dirty = false;
                    this[key].map(elem => {
                        if (typeof elem == 'object' && elem.$dirty || elem.$deleted) {
                            dirty = true;
                        }
                    });
                    if (dirty) {
                        return true;
                    }
                } else if (this[key].$dirty || this[key].$deleted) {
                    return true;
                }
            }
        }
        return false;
    }

    $export() {
        let data = {};
        for (let prop in this) {
            if (prop.substring(0, 1) == '$') {
                continue;
            }
            data[prop] = this[prop];
        }
        return data;
    }

};

export {Model};

<|endoftext|>


<commit_before>
"use strict";

let isDate = new RegExp(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
let mapper = {
    Jan: '01',
    Feb: '02',
    Mar: '03',
    Apr: '04',
    May: '05',
    Jun: '06',
    Jul: '07',
    Aug: '08',
    Sep: '09',
    Oct: '10',
    Nov: '11',
    Dec: '12'
};

function map(month) {
    return mapper[month];
};

class Model {

    constructor() {
        this.$data = {};
        this.$fields = [];
        this.$deleted = false;
        this.$new = true;
    }

    $create(data = {}, recursive = true) {
        let result = (new this.constructor()).$load(data, recursive);
        result.$new = true;
        return result;
    }

    $load(data = {}, recursive = true) {
        this.$initial = data;
        this.$new = false;
        for (let key in data) {
            let checkDate = isDate.exec(data[key]);
            if (checkDate) {
                checkDate.shift();
                data[key] = new Date(...checkDate);
            }
            var props = {enumerable: true, configurable: true};
            if (!this.hasOwnProperty(key)) {
                props.get = () => {
                    return this.$data[key];
                };
                props.set = value => {
                    this.$data[key] = value;
                };
            }
            Object.defineProperty(this, key, props);
            this.$data[key] = data[key];
            this.$fields.push(key);
        }
        return this;
    }

    $update() {
        for (let field in this) {
            if (field.substring(0, 1) == '$') {
                continue;
            }
            if (typeof this[field] == 'object' && this[field] != null) {
                if ('$delete' in this[field] && this[field].$deleted) {
                    this[field].$delete();
                } else if ('$update' in this[field] && this[field].$dirty) {
                    this[field].$update();
                } else if ('map' in this[field]) {
                    this[field].map(item => {
                        if (typeof item == 'object') {
                            if ('$delete' in item && item.$deleted) {
                                item.$delete();
                            } else if ('$update' in item && item.$dirty) {
                                item.$update();
                            }
                        }
                    });
                }
            }
            if (this.$initial[field]) {
                this.$initial[field] = this.$data[field];
            }
        }
    }

    get $dirty() {
        if (this.$deleted) {
            return true;
        }
        for (let key in this) {
            if (key.substring(0, 1) == '$') {
                continue;
            }
            if (key in this.$data && this.$data[key] != this.$initial[key]) {
                return true;
            } else if (typeof this[key] == 'object' && this[key] != null) {
                if ('map' in this[key]) {
                    let dirty = false;
                    this[key].map(elem => {
                        if (typeof elem == 'object' && elem.$dirty || elem.$deleted) {
                            dirty = true;
                        }
                    });
                    if (dirty) {
                        return true;
                    }
                } else if (this[key].$dirty || this[key].$deleted) {
                    return true;
                }
            }
        }
        return false;
    }

    $pluralize(field) {
        field = field.replace(/y$/, 'ie');
        return this[field + 's'];
    }

    $export() {
        let data = {};
        for (let prop in this) {
            if (prop.substring(0, 1) == '$') {
                continue;
            }
            if (typeof this[prop] == 'object' && 'getFullYear' in this[prop]) {
                let d = (this[prop] + '').split(' ');
                data[prop] = [d[3], map(d[1]), d[2]].join('-') + ' '+ d[4];
            } else {
                data[prop] = this[prop];
            }
        }
        return data;
    }

};

export {Model};

<commit_msg>new can never be dirty<commit_after>
"use strict";

let isDate = new RegExp(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
let mapper = {
    Jan: '01',
    Feb: '02',
    Mar: '03',
    Apr: '04',
    May: '05',
    Jun: '06',
    Jul: '07',
    Aug: '08',
    Sep: '09',
    Oct: '10',
    Nov: '11',
    Dec: '12'
};

function map(month) {
    return mapper[month];
};

class Model {

    constructor() {
        this.$data = {};
        this.$fields = [];
        this.$deleted = false;
        this.$new = true;
    }

    $create(data = {}, recursive = true) {
        let result = (new this.constructor()).$load(data, recursive);
        result.$new = true;
        return result;
    }

    $load(data = {}, recursive = true) {
        this.$initial = data;
        this.$new = false;
        for (let key in data) {
            let checkDate = isDate.exec(data[key]);
            if (checkDate) {
                checkDate.shift();
                data[key] = new Date(...checkDate);
            }
            var props = {enumerable: true, configurable: true};
            if (!this.hasOwnProperty(key)) {
                props.get = () => {
                    return this.$data[key];
                };
                props.set = value => {
                    this.$data[key] = value;
                };
            }
            Object.defineProperty(this, key, props);
            this.$data[key] = data[key];
            this.$fields.push(key);
        }
        return this;
    }

    $update() {
        for (let field in this) {
            if (field.substring(0, 1) == '$') {
                continue;
            }
            if (typeof this[field] == 'object' && this[field] != null) {
                if ('$delete' in this[field] && this[field].$deleted) {
                    this[field].$delete();
                } else if ('$update' in this[field] && this[field].$dirty) {
                    this[field].$update();
                } else if ('map' in this[field]) {
                    this[field].map(item => {
                        if (typeof item == 'object') {
                            if ('$delete' in item && item.$deleted) {
                                item.$delete();
                            } else if ('$update' in item && item.$dirty) {
                                item.$update();
                            }
                        }
                    });
                }
            }
            if (this.$initial[field]) {
                this.$initial[field] = this.$data[field];
            }
        }
    }

    get $dirty() {
        if (this.$deleted) {
            return true;
        }
        if (this.$new) {
            return false;
        }
        for (let key in this) {
            if (key.substring(0, 1) == '$') {
                continue;
            }
            if (key in this.$data && this.$data[key] != this.$initial[key]) {
                return true;
            } else if (typeof this[key] == 'object' && this[key] != null) {
                if ('map' in this[key]) {
                    let dirty = false;
                    this[key].map(elem => {
                        if (typeof elem == 'object' && elem.$dirty || elem.$deleted) {
                            dirty = true;
                        }
                    });
                    if (dirty) {
                        return true;
                    }
                } else if (this[key].$dirty || this[key].$deleted) {
                    return true;
                }
            }
        }
        return false;
    }

    $pluralize(field) {
        field = field.replace(/y$/, 'ie');
        return this[field + 's'];
    }

    $export() {
        let data = {};
        for (let prop in this) {
            if (prop.substring(0, 1) == '$') {
                continue;
            }
            if (typeof this[prop] == 'object' && 'getFullYear' in this[prop]) {
                let d = (this[prop] + '').split(' ');
                data[prop] = [d[3], map(d[1]), d[2]].join('-') + ' '+ d[4];
            } else {
                data[prop] = this[prop];
            }
        }
        return data;
    }

};

export {Model};

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-2015 Memba Sarl. All rights reserved.
 * Sources at https://github.com/Memba
 */

/* jslint node: true */
/* jshint node: true */

'use strict';

var uuid = require('node-uuid'),
    deepExtend = require('deep-extend');

module.exports = {

    /**
     * Checks if `obj` is an object.
     * @param obj
     * @returns {boolean}
     */
    isObject: function (obj) {
        return '[object Object]' === Object.prototype.toString.call(obj); //((obj instanceof Object) && (typeof obj === 'object'));
    },

    /**
     * Checks if `obj` is an empty object
     * @param obj
     * @returns {boolean}
     */
    isEmptyObject: function(obj) {
        return '[object Object]' === Object.prototype.toString.call(obj) && 0 === Object.keys(obj).length;
    },

    /**
     * Similar to $.extend
     * @see https://github.com/unclechu/node-deep-extend
     * @param obj
     * @param obj1, obj2, ...
     */
    deepExtend: deepExtend,

    /**
     * uuid generator
     * @see https://github.com/broofa/node-uuid
     * @see http://jsperf.com/node-uuid-performance/24
     * @returns {string}
     */
    uuid: uuid.v1

};
<commit_msg>Minor changes<commit_after>/**
 * Copyright (c) 2013-2015 Memba Sarl. All rights reserved.
 * Sources at https://github.com/Memba
 */

/* jshint node: true */

'use strict';

var uuid = require('node-uuid'),
    deepExtend = require('deep-extend');

module.exports = {

    /**
     * Checks if `obj` is an object.
     * @param obj
     * @returns {boolean}
     */
    isObject: function (obj) {
        return '[object Object]' === Object.prototype.toString.call(obj); //((obj instanceof Object) && (typeof obj === 'object'));
    },

    /**
     * Checks if `obj` is an empty object
     * @param obj
     * @returns {boolean}
     */
    isEmptyObject: function(obj) {
        return '[object Object]' === Object.prototype.toString.call(obj) && 0 === Object.keys(obj).length;
    },

    /**
     * Similar to $.extend
     * @see https://github.com/unclechu/node-deep-extend
     * @param obj
     * @param obj1, obj2, ...
     */
    deepExtend: deepExtend,

    /**
     * uuid generator
     * @see https://github.com/broofa/node-uuid
     * @see http://jsperf.com/node-uuid-performance/24
     * @returns {string}
     */
    uuid: uuid.v1

};
<|endoftext|>


<commit_before>define([
    'jquery',
    'underscore',
    'backbone',
    'knockout',
    'bootstrap-nifty'
], function($, _, Backbone, ko) {
    var PageView = Backbone.View.extend({
        el: $('body'),

        constructor: function (options) {
            var self = this;
            this.viewModel = (options && options.viewModel) ? options.viewModel : {};

            _.defaults(this.viewModel, {
                loading: ko.observable(false),
                showTabs: ko.observable(false),
                tabsActive: ko.observable(false),
                menuActive: ko.observable(false),
                dirty: ko.observable(false),
                showConfirmNav: ko.observable(false),
                navDestination: ko.observable(''),
                navigate: function(url, bypass) {
                    if (!bypass && self.viewModel.dirty()) {
                        self.viewModel.navDestination(url);
                        self.viewModel.showConfirmNav(true);
                        return;
                    }
                    self.viewModel.showConfirmNav(false);
                    self.viewModel.loading(true);
                    window.location = url;
                }
            });

            this.viewModel.showConfirmNav.subscribe(function(val) {
                $('#confirm-nav-modal').modal(val?'show':'hide')
            });

            Backbone.View.apply(this, arguments);
            return this;
        },

        initialize: function(options) {
            ko.applyBindings(this.viewModel);
            $('[data-toggle="tooltip"]').tooltip();
        }
    });
    return PageView;
});
<commit_msg>re: #457<commit_after>define([
    'jquery',
    'underscore',
    'backbone',
    'knockout',
    'bootstrap-nifty'
], function($, _, Backbone, ko) {
    /**
    * A backbone view representing a basic page in arches.  It sets up the
    * viewModel defaults, optionally accepts additional view model data and
    * binds the view model to the entire page.  When using, no other views
    * should bind data to the DOM.
    *
    * @augments Backbone.View
    * @constructor
    * @name PageView
    */
    var PageView = Backbone.View.extend({
        el: $('body'),

        /**
        * Creates an instance of PageView, optionally using a passed in view
        * model
        *
        * @memberof PageView.prototype
        * @param {object} options
        * @param {object} options.viewModel - an optional view model to be
        *                 bound to the page
        * @return {object} an instance of PageView
        */
        constructor: function (options) {
            var self = this;
            this.viewModel = (options && options.viewModel) ? options.viewModel : {};

            _.defaults(this.viewModel, {
                loading: ko.observable(false),
                showTabs: ko.observable(false),
                tabsActive: ko.observable(false),
                menuActive: ko.observable(false),
                dirty: ko.observable(false),
                showConfirmNav: ko.observable(false),
                navDestination: ko.observable(''),
                navigate: function(url, bypass) {
                    if (!bypass && self.viewModel.dirty()) {
                        self.viewModel.navDestination(url);
                        self.viewModel.showConfirmNav(true);
                        return;
                    }
                    self.viewModel.showConfirmNav(false);
                    self.viewModel.loading(true);
                    window.location = url;
                }
            });

            this.viewModel.showConfirmNav.subscribe(function(val) {
                $('#confirm-nav-modal').modal(val?'show':'hide')
            });

            Backbone.View.apply(this, arguments);
            return this;
        },

        initialize: function(options) {
            ko.applyBindings(this.viewModel);
            $('[data-toggle="tooltip"]').tooltip();
        }
    });
    return PageView;
});
<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2017, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/* global postMessage */

import _ from 'lodash';
import bows from 'bows';

import PDFWorker from './PDFWorker';
import DataWorker from './DataWorker';
import queue from 'async/queue';

const dataWorker = new DataWorker();
const pdfWorker = new PDFWorker(dataWorker.dataUtil);
const log = bows('Worker');

let q;

onmessage = (msg) => {
  const { patientId } = _.get(msg, 'data.meta', {});

  if (patientId) {
    // Instantiate a new queue if not set or patientId changes
    if (!q || q.id !== patientId) q = newQueue(patientId);

    // Add message to queue
    q.push(msg);
    log('Pushed msg to queue:', msg);
  }
};

function newQueue(patientId) {
  const _queue = queue(processMessage, 1);
  _queue.id = patientId;

  log('New queue with patientId:', patientId, _queue);
  return _queue;
}

function processMessage(msg, cb) {
  switch(_.get(msg, 'data.meta.worker')) {
    case 'pdf':
      pdfWorker.handleMessage(msg, postMessage);
      break;

    case 'data':
      dataWorker.handleMessage(msg, postMessage);
      break;
    }

  cb();
}
<commit_msg>[RELEASE-1.31.1] Fix for loading async.queue in production build<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2017, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

/* global postMessage */

import _ from 'lodash';
import bows from 'bows';

import PDFWorker from './PDFWorker';
import DataWorker from './DataWorker';
import { queue } from 'async';

const dataWorker = new DataWorker();
const pdfWorker = new PDFWorker(dataWorker.dataUtil);
const log = bows('Worker');

let q;

onmessage = (msg) => {
  const { patientId } = _.get(msg, 'data.meta', {});

  if (patientId) {
    // Instantiate a new queue if not set or patientId changes
    if (!q || q.id !== patientId) q = newQueue(patientId);

    // Add message to queue
    q.push(msg);
    log('Pushed msg to queue:', msg);
  }
};

function newQueue(patientId) {
  const _queue = queue(processMessage, 1);
  _queue.id = patientId;

  log('New queue with patientId:', patientId, _queue);
  return _queue;
}

function processMessage(msg, cb) {
  switch(_.get(msg, 'data.meta.worker')) {
    case 'pdf':
      pdfWorker.handleMessage(msg, postMessage);
      break;

    case 'data':
      dataWorker.handleMessage(msg, postMessage);
      break;
    }

  cb();
}
<|endoftext|>


<commit_before>/*
 * Copyright 2019 Google Inc. All Rights Reserved.
 *
 *  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.
 */

'use strict';

const TwaGenerator = require('../../lib/TwaGenerator');
const {TwaManifest} = require('../../lib/TwaManifest');
const KeyTool = require('../../lib/jdk/KeyTool');
const {JdkHelper} = require('../../lib/jdk/JdkHelper');
const {promisify} = require('util');
const colors = require('colors/safe');
const prompt = require('prompt');
const validUrl = require('valid-url');
const fs = require('fs');
const Color = require('color');
prompt.get = promisify(prompt.get);

async function confirmTwaConfig(twaManifest) {
  const validateColor = (color) => {
    try {
      new Color(color);
      return true;
    } catch (_) {
      return false;
    }
  };

  prompt.message = colors.green('[llama-pack-init]');
  prompt.delimiter = ' ';
  prompt.start();
  const schema = {
    properties: {
      host: {
        name: 'host',
        description: 'Domain being opened in the TWA:',
        required: true,
        default: twaManifest.host,
      },
      name: {
        name: 'name',
        description: 'Name to be shown on the Android Launcher:',
        required: true,
        default: twaManifest.name,
      },
      themeColor: {
        name: 'themeColor',
        description: 'Color to be used for the status bar:',
        message: 'Must use a color in hex format',
        required: true,
        conform: validateColor,
        default: twaManifest.themeColor.hex(),
      },
      backgroundColor: {
        name: 'backgroundColor',
        description: 'Color to be used for the splash screen background:',
        message: 'Must use a color in hex format',
        required: true,
        conform: validateColor,
        default: twaManifest.backgroundColor.hex(),
      },
      startUrl: {
        name: 'startUrl',
        message: 'Must be relative to the root domain.',
        description: 'Relative path to open the TWA:',
        required: true,
        default: twaManifest.startUrl,
      },
      iconUrl: {
        name: 'iconUrl',
        description: 'URL to an image that is at least 512x512px',
        message: 'Must be a well-formed http or https URL.',
        required: true,
        default: twaManifest.iconUrl,
        conform: validUrl.isWebUri,
      },
      maskableIconUrl: {
        name: 'maskableIconUrl',
        description: 'URL to an image that is at least 512x512px to be used when generating ' +
            'maskable icons',
        message: 'Must be a well-formed http or https URL.',
        default: twaManifest.maskableIconUrl || undefined,
        conform: validUrl.isWebUri,
      },
      shortcuts: {
        name: 'shortcuts',
        validator: /y[es]*|n[o]?/,
        message: 'Include app shortcuts?\n' + twaManifest.shortcuts,
        description: 'App shortcuts to display for users TO quickly start common or recommended ' +
            'tasks within the app',
        warning: 'Must respond yes or no',
        default: 'yes',
        ask: () => twaManifest.shortcuts !== '[]',
      },
      packageId: {
        name: 'packageId',
        description: 'Android Package Name (or Application ID):',
        required: true,
        default: twaManifest.packageId,
      },
      signingKey: {
        properties: {
          path: {
            name: 'path',
            description: 'Location of the Signing Key:',
            required: true,
            default: twaManifest.signingKey.path,
          },
          alias: {
            name: 'alias',
            description: 'Key name:',
            required: true,
            default: twaManifest.signingKey.alias,
          },
        },
      },
    },
  };
  const result = await prompt.get(schema);
  Object.assign(twaManifest, result, {
    themeColor: new Color(result.themeColor),
    backgroundColor: new Color(result.themeColor),
    shortcuts: result.shortcuts === 'no' ? '[]' : twaManifest.shortcuts,
  });
  return twaManifest;
}

async function init(args, config) {
  console.log('Fetching Manifest: ', args.manifest);
  try {
    let twaManifest = await TwaManifest.fromWebManifest(args.manifest);
    twaManifest = await confirmTwaConfig(twaManifest);
    const twaGenerator = new TwaGenerator();
    const targetDirectory = args.directory || process.cwd();
    await twaManifest.saveToFile('./twa-manifest.json');
    await twaGenerator.createTwaProject(targetDirectory, twaManifest);
    await createSigningKey(twaManifest, config);
    return true;
  } catch (e) {
    console.error('Error Genearating TWA', e);
    return false;
  }
}

async function createSigningKey(twaManifest, config) {
  // Signing Key already exists. Skip creation.
  if (fs.existsSync(twaManifest.signingKey.path)) {
    return;
  }

  const jdkHelper = new JdkHelper(process, config);
  const keytool = new KeyTool(jdkHelper);

  prompt.start();

  // Ask user if they want to create a signing key now.
  const property = {
    name: 'yesno',
    message: `Signing Key could not be found at "${twaManifest.signingKey.path}". Do you want to` +
        ' create one now?',
    validator: /y[es]*|n[o]?/,
    warning: 'Must respond yes or no',
    default: 'yes',
  };

  const result = await prompt.get(property);
  if (result.yesno === 'no') {
    return;
  }

  await keytool.createSigningKeyIfNeeded(
      twaManifest.signingKey.path,
      twaManifest.signingKey.alias,
  );
}

module.exports = init;
<commit_msg>Fixes themeColor being used in pace of backgroundColor<commit_after>/*
 * Copyright 2019 Google Inc. All Rights Reserved.
 *
 *  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.
 */

'use strict';

const TwaGenerator = require('../../lib/TwaGenerator');
const {TwaManifest} = require('../../lib/TwaManifest');
const KeyTool = require('../../lib/jdk/KeyTool');
const {JdkHelper} = require('../../lib/jdk/JdkHelper');
const {promisify} = require('util');
const colors = require('colors/safe');
const prompt = require('prompt');
const validUrl = require('valid-url');
const fs = require('fs');
const Color = require('color');
prompt.get = promisify(prompt.get);

async function confirmTwaConfig(twaManifest) {
  const validateColor = (color) => {
    try {
      new Color(color);
      return true;
    } catch (_) {
      return false;
    }
  };

  prompt.message = colors.green('[llama-pack-init]');
  prompt.delimiter = ' ';
  prompt.start();
  const schema = {
    properties: {
      host: {
        name: 'host',
        description: 'Domain being opened in the TWA:',
        required: true,
        default: twaManifest.host,
      },
      name: {
        name: 'name',
        description: 'Name to be shown on the Android Launcher:',
        required: true,
        default: twaManifest.name,
      },
      themeColor: {
        name: 'themeColor',
        description: 'Color to be used for the status bar:',
        message: 'Must use a color in hex format',
        required: true,
        conform: validateColor,
        default: twaManifest.themeColor.hex(),
      },
      backgroundColor: {
        name: 'backgroundColor',
        description: 'Color to be used for the splash screen background:',
        message: 'Must use a color in hex format',
        required: true,
        conform: validateColor,
        default: twaManifest.backgroundColor.hex(),
      },
      startUrl: {
        name: 'startUrl',
        message: 'Must be relative to the root domain.',
        description: 'Relative path to open the TWA:',
        required: true,
        default: twaManifest.startUrl,
      },
      iconUrl: {
        name: 'iconUrl',
        description: 'URL to an image that is at least 512x512px',
        message: 'Must be a well-formed http or https URL.',
        required: true,
        default: twaManifest.iconUrl,
        conform: validUrl.isWebUri,
      },
      maskableIconUrl: {
        name: 'maskableIconUrl',
        description: 'URL to an image that is at least 512x512px to be used when generating ' +
            'maskable icons',
        message: 'Must be a well-formed http or https URL.',
        default: twaManifest.maskableIconUrl || undefined,
        conform: validUrl.isWebUri,
      },
      shortcuts: {
        name: 'shortcuts',
        validator: /y[es]*|n[o]?/,
        message: 'Include app shortcuts?\n' + twaManifest.shortcuts,
        description: 'App shortcuts to display for users TO quickly start common or recommended ' +
            'tasks within the app',
        warning: 'Must respond yes or no',
        default: 'yes',
        ask: () => twaManifest.shortcuts !== '[]',
      },
      packageId: {
        name: 'packageId',
        description: 'Android Package Name (or Application ID):',
        required: true,
        default: twaManifest.packageId,
      },
      signingKey: {
        properties: {
          path: {
            name: 'path',
            description: 'Location of the Signing Key:',
            required: true,
            default: twaManifest.signingKey.path,
          },
          alias: {
            name: 'alias',
            description: 'Key name:',
            required: true,
            default: twaManifest.signingKey.alias,
          },
        },
      },
    },
  };
  const result = await prompt.get(schema);
  Object.assign(twaManifest, result, {
    themeColor: new Color(result.themeColor),
    backgroundColor: new Color(result.backgroundColor),
    shortcuts: result.shortcuts === 'no' ? '[]' : twaManifest.shortcuts,
  });
  return twaManifest;
}

async function init(args, config) {
  console.log('Fetching Manifest: ', args.manifest);
  try {
    let twaManifest = await TwaManifest.fromWebManifest(args.manifest);
    twaManifest = await confirmTwaConfig(twaManifest);
    const twaGenerator = new TwaGenerator();
    const targetDirectory = args.directory || process.cwd();
    await twaManifest.saveToFile('./twa-manifest.json');
    await twaGenerator.createTwaProject(targetDirectory, twaManifest);
    await createSigningKey(twaManifest, config);
    return true;
  } catch (e) {
    console.error('Error Genearating TWA', e);
    return false;
  }
}

async function createSigningKey(twaManifest, config) {
  // Signing Key already exists. Skip creation.
  if (fs.existsSync(twaManifest.signingKey.path)) {
    return;
  }

  const jdkHelper = new JdkHelper(process, config);
  const keytool = new KeyTool(jdkHelper);

  prompt.start();

  // Ask user if they want to create a signing key now.
  const property = {
    name: 'yesno',
    message: `Signing Key could not be found at "${twaManifest.signingKey.path}". Do you want to` +
        ' create one now?',
    validator: /y[es]*|n[o]?/,
    warning: 'Must respond yes or no',
    default: 'yes',
  };

  const result = await prompt.get(property);
  if (result.yesno === 'no') {
    return;
  }

  await keytool.createSigningKeyIfNeeded(
      twaManifest.signingKey.path,
      twaManifest.signingKey.alias,
  );
}

module.exports = init;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
/* global __fbBatchedBridge, self, importScripts, postMessage, addEventListener: true */

// Edit from https://github.com/facebook/react-native/blob/master/local-cli/server/util/debuggerWorker.js

import './setup';
import { checkAvailableDevMenuMethods, invokeDevMenuMethodIfAvailable } from './devMenu';
import { reportDefaultReactDevToolsPort } from './reactDevTools';
import devToolsEnhancer, { composeWithDevTools } from './reduxAPI';
import * as RemoteDev from './remotedev';
import { getRequiredModules, ignoreRNDIntervalSpy } from './utils';
import { toggleNetworkInspect } from './networkInspect';
import { getSafeAsyncStorage } from './asyncStorage';
import Bridge from 'apollo-client-devtools/bridge';
import { initBackend, sendBridgeReady } from 'apollo-client-devtools/backend';
import { version as devToolsVersion } from 'apollo-client-devtools/package.json';
/* eslint-disable no-underscore-dangle */
self.__REMOTEDEV__ = RemoteDev;

devToolsEnhancer.send = RemoteDev.send;
devToolsEnhancer.connect = RemoteDev.connect;

// Deprecated API, these may removed when redux-devtools-extension 3.0 release
self.devToolsExtension = devToolsEnhancer;
self.reduxNativeDevTools = devToolsEnhancer;
self.reduxNativeDevToolsCompose = composeWithDevTools;

self.__REDUX_DEVTOOLS_EXTENSION__ = devToolsEnhancer;
self.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ = composeWithDevTools;

const setupRNDebuggerBeforeImportScript = message => {
  self.__REACT_DEVTOOLS_PORT__ = message.reactDevToolsPort;
  if (message.networkInspect) {
    self.__NETWORK_INSPECT__ = toggleNetworkInspect;
  }
};

const setupRNDebugger = async message => {
  // We need to regularly update JS runtime
  // because the changes of worker message (Redux DevTools, DevMenu)
  // doesn't notify to the remote JS runtime
  self.__RND_INTERVAL__ = setInterval(function() {}, 100); // eslint-disable-line

  const modules = await getRequiredModules(message.moduleSize);
  if (modules) {
    ignoreRNDIntervalSpy(modules);
    checkAvailableDevMenuMethods(modules, message.networkInspect);
    reportDefaultReactDevToolsPort(modules);
  }

  const interval = setInterval(() => {
    if (!self.__APOLLO_CLIENT__) {
      return;
    }

    clearInterval(interval);

    const hook = {
      ApolloClient: self.__APOLLO_CLIENT__,
      devToolsVersion
    };

    let listener;

    const bridge = new Bridge({
      listen(fn) {
        listener = self.addEventListener('message', evt => {
          if (evt.data.source === 'apollo-devtools-proxy') {
            return fn(evt.data);
          }
        });
      },
      send(data) {
        console.log(data);

        postMessage({
          ...data,
          source: 'apollo-devtools-backend',
        });
      },
    });

    bridge.on('init', () => {
      sendBridgeReady();
    });

    bridge.on("shutdown", () => {
      self.removeEventListener('message', listener);
    });

    initBackend(bridge, hook, getSafeAsyncStorage(modules.AsyncStorage));

  }, 1000);
};

const messageHandlers = {
  executeApplicationScript(message, sendReply) {
    setupRNDebuggerBeforeImportScript(message);

    Object.keys(message.inject).forEach(key => {
      self[key] = JSON.parse(message.inject[key]);
    });
    let error;
    try {
      importScripts(message.url);
    } catch (err) {
      error = err.message;
    }

    sendReply(null /* result */, error);

    if (!error) {
      setupRNDebugger(message);
    }
    return false;
  },
  emitReduxMessage() {
    // pass to other listeners
    return true;
  },
  invokeDevMenuMethod({ name, args }) {
    invokeDevMenuMethodIfAvailable(name, args);
    return false;
  },
  beforeTerminate() {
    // Clean for notify native bridge
    if (window.__RND_INTERVAL__) {
      clearInterval(window.__RND_INTERVAL__);
      window.__RND_INTERVAL__ = null;
    }
    return false;
  },
};

addEventListener('message', message => {
  const object = message.data;

  const sendReply = (result, error) => {
    postMessage({ replyID: object.id, result, error });
  };

  const handler = messageHandlers[object.method];
  if (handler) {
    // Special cased handlers
    return handler(object, sendReply);
  }
  // Other methods get called on the bridge
  let returnValue = [[], [], [], 0];
  let error;
  try {
    if (typeof __fbBatchedBridge === 'object') {
      returnValue = __fbBatchedBridge[object.method].apply(null, object.arguments);
    } else {
      error = 'Failed to call function, __fbBatchedBridge is undefined';
    }
  } catch (err) {
    error = err.message;
  } finally {
    sendReply(JSON.stringify(returnValue), error);
  }
  return false;
});
<commit_msg>Removed console.log.<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
/* global __fbBatchedBridge, self, importScripts, postMessage, addEventListener: true */

// Edit from https://github.com/facebook/react-native/blob/master/local-cli/server/util/debuggerWorker.js

import './setup';
import { checkAvailableDevMenuMethods, invokeDevMenuMethodIfAvailable } from './devMenu';
import { reportDefaultReactDevToolsPort } from './reactDevTools';
import devToolsEnhancer, { composeWithDevTools } from './reduxAPI';
import * as RemoteDev from './remotedev';
import { getRequiredModules, ignoreRNDIntervalSpy } from './utils';
import { toggleNetworkInspect } from './networkInspect';
import { getSafeAsyncStorage } from './asyncStorage';
import Bridge from 'apollo-client-devtools/bridge';
import { initBackend, sendBridgeReady } from 'apollo-client-devtools/backend';
import { version as devToolsVersion } from 'apollo-client-devtools/package.json';
/* eslint-disable no-underscore-dangle */
self.__REMOTEDEV__ = RemoteDev;

devToolsEnhancer.send = RemoteDev.send;
devToolsEnhancer.connect = RemoteDev.connect;

// Deprecated API, these may removed when redux-devtools-extension 3.0 release
self.devToolsExtension = devToolsEnhancer;
self.reduxNativeDevTools = devToolsEnhancer;
self.reduxNativeDevToolsCompose = composeWithDevTools;

self.__REDUX_DEVTOOLS_EXTENSION__ = devToolsEnhancer;
self.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ = composeWithDevTools;

const setupRNDebuggerBeforeImportScript = message => {
  self.__REACT_DEVTOOLS_PORT__ = message.reactDevToolsPort;
  if (message.networkInspect) {
    self.__NETWORK_INSPECT__ = toggleNetworkInspect;
  }
};

const setupRNDebugger = async message => {
  // We need to regularly update JS runtime
  // because the changes of worker message (Redux DevTools, DevMenu)
  // doesn't notify to the remote JS runtime
  self.__RND_INTERVAL__ = setInterval(function() {}, 100); // eslint-disable-line

  const modules = await getRequiredModules(message.moduleSize);
  if (modules) {
    ignoreRNDIntervalSpy(modules);
    checkAvailableDevMenuMethods(modules, message.networkInspect);
    reportDefaultReactDevToolsPort(modules);
  }

  const interval = setInterval(() => {
    if (!self.__APOLLO_CLIENT__) {
      return;
    }

    clearInterval(interval);

    const hook = {
      ApolloClient: self.__APOLLO_CLIENT__,
      devToolsVersion
    };

    let listener;

    const bridge = new Bridge({
      listen(fn) {
        listener = self.addEventListener('message', evt => {
          if (evt.data.source === 'apollo-devtools-proxy') {
            return fn(evt.data);
          }
        });
      },
      send(data) {
        postMessage({
          ...data,
          source: 'apollo-devtools-backend',
        });
      },
    });

    bridge.on('init', () => {
      sendBridgeReady();
    });

    bridge.on("shutdown", () => {
      self.removeEventListener('message', listener);
    });

    initBackend(bridge, hook, getSafeAsyncStorage(modules.AsyncStorage));

  }, 1000);
};

const messageHandlers = {
  executeApplicationScript(message, sendReply) {
    setupRNDebuggerBeforeImportScript(message);

    Object.keys(message.inject).forEach(key => {
      self[key] = JSON.parse(message.inject[key]);
    });
    let error;
    try {
      importScripts(message.url);
    } catch (err) {
      error = err.message;
    }

    sendReply(null /* result */, error);

    if (!error) {
      setupRNDebugger(message);
    }
    return false;
  },
  emitReduxMessage() {
    // pass to other listeners
    return true;
  },
  invokeDevMenuMethod({ name, args }) {
    invokeDevMenuMethodIfAvailable(name, args);
    return false;
  },
  beforeTerminate() {
    // Clean for notify native bridge
    if (window.__RND_INTERVAL__) {
      clearInterval(window.__RND_INTERVAL__);
      window.__RND_INTERVAL__ = null;
    }
    return false;
  },
};

addEventListener('message', message => {
  const object = message.data;

  const sendReply = (result, error) => {
    postMessage({ replyID: object.id, result, error });
  };

  const handler = messageHandlers[object.method];
  if (handler) {
    // Special cased handlers
    return handler(object, sendReply);
  }
  // Other methods get called on the bridge
  let returnValue = [[], [], [], 0];
  let error;
  try {
    if (typeof __fbBatchedBridge === 'object') {
      returnValue = __fbBatchedBridge[object.method].apply(null, object.arguments);
    } else {
      error = 'Failed to call function, __fbBatchedBridge is undefined';
    }
  } catch (err) {
    error = err.message;
  } finally {
    sendReply(JSON.stringify(returnValue), error);
  }
  return false;
});
<|endoftext|>